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
diff options
context:
space:
mode:
Diffstat (limited to 'source/blender')
-rw-r--r--source/blender/CMakeLists.txt9
-rw-r--r--source/blender/alembic/ABC_alembic.h55
-rw-r--r--source/blender/alembic/CMakeLists.txt3
-rw-r--r--source/blender/alembic/intern/abc_archive.cc41
-rw-r--r--source/blender/alembic/intern/abc_archive.h9
-rw-r--r--source/blender/alembic/intern/abc_camera.cc20
-rw-r--r--source/blender/alembic/intern/abc_camera.h7
-rw-r--r--source/blender/alembic/intern/abc_curves.cc78
-rw-r--r--source/blender/alembic/intern/abc_curves.h14
-rw-r--r--source/blender/alembic/intern/abc_customdata.cc233
-rw-r--r--source/blender/alembic/intern/abc_customdata.h3
-rw-r--r--source/blender/alembic/intern/abc_exporter.cc342
-rw-r--r--source/blender/alembic/intern/abc_exporter.h31
-rw-r--r--source/blender/alembic/intern/abc_hair.cc46
-rw-r--r--source/blender/alembic/intern/abc_hair.h2
-rw-r--r--source/blender/alembic/intern/abc_mball.cc122
-rw-r--r--source/blender/alembic/intern/abc_mball.h61
-rw-r--r--source/blender/alembic/intern/abc_mesh.cc183
-rw-r--r--source/blender/alembic/intern/abc_mesh.h28
-rw-r--r--source/blender/alembic/intern/abc_nurbs.cc3
-rw-r--r--source/blender/alembic/intern/abc_nurbs.h2
-rw-r--r--source/blender/alembic/intern/abc_object.cc122
-rw-r--r--source/blender/alembic/intern/abc_object.h57
-rw-r--r--source/blender/alembic/intern/abc_points.cc34
-rw-r--r--source/blender/alembic/intern/abc_points.h13
-rw-r--r--source/blender/alembic/intern/abc_transform.cc53
-rw-r--r--source/blender/alembic/intern/abc_transform.h11
-rw-r--r--source/blender/alembic/intern/abc_util.cc366
-rw-r--r--source/blender/alembic/intern/abc_util.h114
-rw-r--r--source/blender/alembic/intern/alembic_capi.cc654
-rw-r--r--source/blender/avi/CMakeLists.txt1
-rw-r--r--source/blender/avi/intern/avi.c36
-rw-r--r--source/blender/avi/intern/avi_codecs.c2
-rw-r--r--source/blender/avi/intern/avi_intern.h2
-rw-r--r--source/blender/avi/intern/avi_mjpeg.c92
-rw-r--r--source/blender/avi/intern/avi_mjpeg.h4
-rw-r--r--source/blender/avi/intern/avi_rgb.c90
-rw-r--r--source/blender/avi/intern/avi_rgb.h4
-rw-r--r--source/blender/avi/intern/avi_rgb32.c32
-rw-r--r--source/blender/avi/intern/avi_rgb32.h4
-rw-r--r--source/blender/blenfont/BLF_api.h6
-rw-r--r--source/blender/blenfont/intern/blf.c22
-rw-r--r--source/blender/blenfont/intern/blf_font.c4
-rw-r--r--source/blender/blenfont/intern/blf_glyph.c119
-rw-r--r--source/blender/blenfont/intern/blf_internal_types.h28
-rw-r--r--source/blender/blenkernel/BKE_DerivedMesh.h21
-rw-r--r--source/blender/blenkernel/BKE_action.h10
-rw-r--r--source/blender/blenkernel/BKE_addon.h13
-rw-r--r--source/blender/blenkernel/BKE_animsys.h21
-rw-r--r--source/blender/blenkernel/BKE_appdir.h4
-rw-r--r--source/blender/blenkernel/BKE_armature.h25
-rw-r--r--source/blender/blenkernel/BKE_blender.h20
-rw-r--r--source/blender/blenkernel/BKE_blender_undo.h17
-rw-r--r--source/blender/blenkernel/BKE_blender_version.h2
-rw-r--r--source/blender/blenkernel/BKE_blendfile.h22
-rw-r--r--source/blender/blenkernel/BKE_boids.h2
-rw-r--r--source/blender/blenkernel/BKE_brush.h25
-rw-r--r--source/blender/blenkernel/BKE_bvhutils.h4
-rw-r--r--source/blender/blenkernel/BKE_cachefile.h6
-rw-r--r--source/blender/blenkernel/BKE_camera.h3
-rw-r--r--source/blender/blenkernel/BKE_cloth.h6
-rw-r--r--source/blender/blenkernel/BKE_colorband.h52
-rw-r--r--source/blender/blenkernel/BKE_colortools.h4
-rw-r--r--source/blender/blenkernel/BKE_constraint.h1
-rw-r--r--source/blender/blenkernel/BKE_context.h4
-rw-r--r--source/blender/blenkernel/BKE_curve.h27
-rw-r--r--source/blender/blenkernel/BKE_deform.h4
-rw-r--r--source/blender/blenkernel/BKE_editlattice.h (renamed from source/blender/blenkernel/BKE_utildefines.h)27
-rw-r--r--source/blender/blenkernel/BKE_fcurve.h19
-rw-r--r--source/blender/blenkernel/BKE_font.h6
-rw-r--r--source/blender/blenkernel/BKE_freestyle.h2
-rw-r--r--source/blender/blenkernel/BKE_global.h34
-rw-r--r--source/blender/blenkernel/BKE_gpencil.h3
-rw-r--r--source/blender/blenkernel/BKE_group.h4
-rw-r--r--source/blender/blenkernel/BKE_icons.h20
-rw-r--r--source/blender/blenkernel/BKE_idprop.h16
-rw-r--r--source/blender/blenkernel/BKE_image.h11
-rw-r--r--source/blender/blenkernel/BKE_key.h3
-rw-r--r--source/blender/blenkernel/BKE_lamp.h5
-rw-r--r--source/blender/blenkernel/BKE_lattice.h3
-rw-r--r--source/blender/blenkernel/BKE_library.h85
-rw-r--r--source/blender/blenkernel/BKE_library_query.h9
-rw-r--r--source/blender/blenkernel/BKE_library_remap.h5
-rw-r--r--source/blender/blenkernel/BKE_linestyle.h17
-rw-r--r--source/blender/blenkernel/BKE_main.h9
-rw-r--r--source/blender/blenkernel/BKE_mask.h16
-rw-r--r--source/blender/blenkernel/BKE_material.h5
-rw-r--r--source/blender/blenkernel/BKE_mball.h5
-rw-r--r--source/blender/blenkernel/BKE_mesh.h50
-rw-r--r--source/blender/blenkernel/BKE_modifier.h24
-rw-r--r--source/blender/blenkernel/BKE_movieclip.h12
-rw-r--r--source/blender/blenkernel/BKE_nla.h25
-rw-r--r--source/blender/blenkernel/BKE_node.h27
-rw-r--r--source/blender/blenkernel/BKE_object.h148
-rw-r--r--source/blender/blenkernel/BKE_object_deform.h3
-rw-r--r--source/blender/blenkernel/BKE_paint.h76
-rw-r--r--source/blender/blenkernel/BKE_particle.h23
-rw-r--r--source/blender/blenkernel/BKE_pbvh.h24
-rw-r--r--source/blender/blenkernel/BKE_pointcache.h12
-rw-r--r--source/blender/blenkernel/BKE_property.h4
-rw-r--r--source/blender/blenkernel/BKE_rigidbody.h6
-rw-r--r--source/blender/blenkernel/BKE_sca.h14
-rw-r--r--source/blender/blenkernel/BKE_scene.h9
-rw-r--r--source/blender/blenkernel/BKE_sequencer.h27
-rw-r--r--source/blender/blenkernel/BKE_sound.h2
-rw-r--r--source/blender/blenkernel/BKE_speaker.h3
-rw-r--r--source/blender/blenkernel/BKE_subsurf.h8
-rw-r--r--source/blender/blenkernel/BKE_text.h92
-rw-r--r--source/blender/blenkernel/BKE_texture.h19
-rw-r--r--source/blender/blenkernel/BKE_tracking.h42
-rw-r--r--source/blender/blenkernel/BKE_undo_system.h197
-rw-r--r--source/blender/blenkernel/BKE_world.h10
-rw-r--r--source/blender/blenkernel/CMakeLists.txt21
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf.h3
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf_legacy.c817
-rw-r--r--source/blender/blenkernel/intern/CCGSubSurf_opensubdiv.c2
-rw-r--r--source/blender/blenkernel/intern/DerivedMesh.c241
-rw-r--r--source/blender/blenkernel/intern/action.c109
-rw-r--r--source/blender/blenkernel/intern/addon.c47
-rw-r--r--source/blender/blenkernel/intern/anim_sys.c218
-rw-r--r--source/blender/blenkernel/intern/appdir.c202
-rw-r--r--source/blender/blenkernel/intern/armature.c92
-rw-r--r--source/blender/blenkernel/intern/armature_update.c127
-rw-r--r--source/blender/blenkernel/intern/blender.c177
-rw-r--r--source/blender/blenkernel/intern/blender_undo.c315
-rw-r--r--source/blender/blenkernel/intern/blendfile.c142
-rw-r--r--source/blender/blenkernel/intern/bmfont.c5
-rw-r--r--source/blender/blenkernel/intern/boids.c12
-rw-r--r--source/blender/blenkernel/intern/bpath.c8
-rw-r--r--source/blender/blenkernel/intern/brush.c87
-rw-r--r--source/blender/blenkernel/intern/bullet.c2
-rw-r--r--source/blender/blenkernel/intern/bvhutils.c31
-rw-r--r--source/blender/blenkernel/intern/cachefile.c36
-rw-r--r--source/blender/blenkernel/intern/camera.c26
-rw-r--r--source/blender/blenkernel/intern/cdderivedmesh.c333
-rw-r--r--source/blender/blenkernel/intern/cloth.c43
-rw-r--r--source/blender/blenkernel/intern/collision.c22
-rw-r--r--source/blender/blenkernel/intern/colorband.c629
-rw-r--r--source/blender/blenkernel/intern/colortools.c31
-rw-r--r--source/blender/blenkernel/intern/constraint.c50
-rw-r--r--source/blender/blenkernel/intern/curve.c870
-rw-r--r--source/blender/blenkernel/intern/curve_decimate.c339
-rw-r--r--source/blender/blenkernel/intern/customdata.c102
-rw-r--r--source/blender/blenkernel/intern/customdata_file.c8
-rw-r--r--source/blender/blenkernel/intern/data_transfer.c6
-rw-r--r--source/blender/blenkernel/intern/deform.c15
-rw-r--r--source/blender/blenkernel/intern/depsgraph.c155
-rw-r--r--source/blender/blenkernel/intern/displist.c16
-rw-r--r--source/blender/blenkernel/intern/dynamicpaint.c486
-rw-r--r--source/blender/blenkernel/intern/editderivedmesh.c149
-rw-r--r--source/blender/blenkernel/intern/editlattice.c147
-rw-r--r--source/blender/blenkernel/intern/effect.c70
-rw-r--r--source/blender/blenkernel/intern/fcurve.c257
-rw-r--r--source/blender/blenkernel/intern/fluidsim.c7
-rw-r--r--source/blender/blenkernel/intern/fmodifier.c31
-rw-r--r--source/blender/blenkernel/intern/font.c75
-rw-r--r--source/blender/blenkernel/intern/freestyle.c26
-rw-r--r--source/blender/blenkernel/intern/gpencil.c81
-rw-r--r--source/blender/blenkernel/intern/group.c47
-rw-r--r--source/blender/blenkernel/intern/icons.c105
-rw-r--r--source/blender/blenkernel/intern/idprop.c228
-rw-r--r--source/blender/blenkernel/intern/image.c528
-rw-r--r--source/blender/blenkernel/intern/image_gen.c2
-rw-r--r--source/blender/blenkernel/intern/ipo.c8
-rw-r--r--source/blender/blenkernel/intern/key.c56
-rw-r--r--source/blender/blenkernel/intern/lamp.c63
-rw-r--r--source/blender/blenkernel/intern/lattice.c48
-rw-r--r--source/blender/blenkernel/intern/library.c766
-rw-r--r--source/blender/blenkernel/intern/library_query.c166
-rw-r--r--source/blender/blenkernel/intern/library_remap.c225
-rw-r--r--source/blender/blenkernel/intern/linestyle.c153
-rw-r--r--source/blender/blenkernel/intern/mask.c141
-rw-r--r--source/blender/blenkernel/intern/mask_evaluate.c108
-rw-r--r--source/blender/blenkernel/intern/mask_rasterize.c88
-rw-r--r--source/blender/blenkernel/intern/material.c108
-rw-r--r--source/blender/blenkernel/intern/mball.c58
-rw-r--r--source/blender/blenkernel/intern/mball_tessellate.c60
-rw-r--r--source/blender/blenkernel/intern/mesh.c376
-rw-r--r--source/blender/blenkernel/intern/mesh_evaluate.c928
-rw-r--r--source/blender/blenkernel/intern/mesh_mapping.c4
-rw-r--r--source/blender/blenkernel/intern/mesh_remap.c29
-rw-r--r--source/blender/blenkernel/intern/mesh_validate.c24
-rw-r--r--source/blender/blenkernel/intern/modifier.c62
-rw-r--r--source/blender/blenkernel/intern/modifiers_bmesh.c20
-rw-r--r--source/blender/blenkernel/intern/movieclip.c87
-rw-r--r--source/blender/blenkernel/intern/multires.c394
-rw-r--r--source/blender/blenkernel/intern/nla.c121
-rw-r--r--source/blender/blenkernel/intern/node.c358
-rw-r--r--source/blender/blenkernel/intern/object.c336
-rw-r--r--source/blender/blenkernel/intern/object_deform.c72
-rw-r--r--source/blender/blenkernel/intern/object_dupli.c52
-rw-r--r--source/blender/blenkernel/intern/object_update.c93
-rw-r--r--source/blender/blenkernel/intern/ocean.c20
-rw-r--r--source/blender/blenkernel/intern/outliner_treehash.c8
-rw-r--r--source/blender/blenkernel/intern/packedFile.c27
-rw-r--r--source/blender/blenkernel/intern/paint.c194
-rw-r--r--source/blender/blenkernel/intern/particle.c267
-rw-r--r--source/blender/blenkernel/intern/particle_child.c338
-rw-r--r--source/blender/blenkernel/intern/particle_distribute.c83
-rw-r--r--source/blender/blenkernel/intern/particle_system.c304
-rw-r--r--source/blender/blenkernel/intern/pbvh.c430
-rw-r--r--source/blender/blenkernel/intern/pbvh_bmesh.c165
-rw-r--r--source/blender/blenkernel/intern/pbvh_intern.h21
-rw-r--r--source/blender/blenkernel/intern/pointcache.c90
-rw-r--r--source/blender/blenkernel/intern/property.c4
-rw-r--r--source/blender/blenkernel/intern/rigidbody.c183
-rw-r--r--source/blender/blenkernel/intern/sca.c32
-rw-r--r--source/blender/blenkernel/intern/scene.c561
-rw-r--r--source/blender/blenkernel/intern/screen.c6
-rw-r--r--source/blender/blenkernel/intern/seqeffects.c984
-rw-r--r--source/blender/blenkernel/intern/seqmodifier.c15
-rw-r--r--source/blender/blenkernel/intern/sequencer.c157
-rw-r--r--source/blender/blenkernel/intern/shrinkwrap.c65
-rw-r--r--source/blender/blenkernel/intern/smoke.c90
-rw-r--r--source/blender/blenkernel/intern/softbody.c95
-rw-r--r--source/blender/blenkernel/intern/sound.c30
-rw-r--r--source/blender/blenkernel/intern/speaker.c29
-rw-r--r--source/blender/blenkernel/intern/subsurf_ccg.c339
-rw-r--r--source/blender/blenkernel/intern/text.c807
-rw-r--r--source/blender/blenkernel/intern/texture.c506
-rw-r--r--source/blender/blenkernel/intern/tracking.c247
-rw-r--r--source/blender/blenkernel/intern/tracking_auto.c363
-rw-r--r--source/blender/blenkernel/intern/tracking_region_tracker.c2
-rw-r--r--source/blender/blenkernel/intern/tracking_stabilize.c84
-rw-r--r--source/blender/blenkernel/intern/tracking_util.c212
-rw-r--r--source/blender/blenkernel/intern/undo_system.c841
-rw-r--r--source/blender/blenkernel/intern/unit.c11
-rw-r--r--source/blender/blenkernel/intern/world.c63
-rw-r--r--source/blender/blenkernel/intern/writeavi.c14
-rw-r--r--source/blender/blenkernel/intern/writeffmpeg.c69
-rw-r--r--source/blender/blenkernel/intern/writeframeserver.c4
-rw-r--r--source/blender/blenkernel/particle_private.h54
-rw-r--r--source/blender/blenkernel/tracking_private.h12
-rw-r--r--source/blender/blenlib/BLI_alloca.h4
-rw-r--r--source/blender/blenlib/BLI_array.h60
-rw-r--r--source/blender/blenlib/BLI_array_utils.h12
-rw-r--r--source/blender/blenlib/BLI_assert.h106
-rw-r--r--source/blender/blenlib/BLI_bitmap_draw_2d.h10
-rw-r--r--source/blender/blenlib/BLI_boxpack_2d.h (renamed from source/blender/blenlib/BLI_boxpack2d.h)10
-rw-r--r--source/blender/blenlib/BLI_buffer.h2
-rw-r--r--source/blender/blenlib/BLI_compiler_attrs.h14
-rw-r--r--source/blender/blenlib/BLI_compiler_compat.h12
-rw-r--r--source/blender/blenlib/BLI_console.h42
-rw-r--r--source/blender/blenlib/BLI_convexhull_2d.h (renamed from source/blender/blenlib/BLI_convexhull2d.h)8
-rw-r--r--source/blender/blenlib/BLI_dial_2d.h (renamed from source/blender/blenlib/BLI_dial.h)12
-rw-r--r--source/blender/blenlib/BLI_dynstr.h6
-rw-r--r--source/blender/blenlib/BLI_edgehash.h4
-rw-r--r--source/blender/blenlib/BLI_fileops.h5
-rw-r--r--source/blender/blenlib/BLI_fileops_types.h6
-rw-r--r--source/blender/blenlib/BLI_fnmatch.h6
-rw-r--r--source/blender/blenlib/BLI_ghash.h302
-rw-r--r--source/blender/blenlib/BLI_gsqueue.h4
-rw-r--r--source/blender/blenlib/BLI_hash.h83
-rw-r--r--source/blender/blenlib/BLI_heap.h34
-rw-r--r--source/blender/blenlib/BLI_jitter_2d.h (renamed from source/blender/blenlib/BLI_jitter.h)8
-rw-r--r--source/blender/blenlib/BLI_kdopbvh.h6
-rw-r--r--source/blender/blenlib/BLI_kdtree.h4
-rw-r--r--source/blender/blenlib/BLI_lasso_2d.h (renamed from source/blender/blenlib/BLI_lasso.h)8
-rw-r--r--source/blender/blenlib/BLI_linklist.h3
-rw-r--r--source/blender/blenlib/BLI_linklist_lockfree.h88
-rw-r--r--source/blender/blenlib/BLI_linklist_stack.h2
-rw-r--r--source/blender/blenlib/BLI_listbase.h24
-rw-r--r--source/blender/blenlib/BLI_math_base.h41
-rw-r--r--source/blender/blenlib/BLI_math_bits.h19
-rw-r--r--source/blender/blenlib/BLI_math_color.h13
-rw-r--r--source/blender/blenlib/BLI_math_geom.h65
-rw-r--r--source/blender/blenlib/BLI_math_inline.h7
-rw-r--r--source/blender/blenlib/BLI_math_matrix.h1
-rw-r--r--source/blender/blenlib/BLI_math_rotation.h13
-rw-r--r--source/blender/blenlib/BLI_math_solvers.h5
-rw-r--r--source/blender/blenlib/BLI_math_vector.h9
-rw-r--r--source/blender/blenlib/BLI_mempool.h7
-rw-r--r--source/blender/blenlib/BLI_path_util.h29
-rw-r--r--source/blender/blenlib/BLI_polyfill_2d.h (renamed from source/blender/blenlib/BLI_polyfill2d.h)6
-rw-r--r--source/blender/blenlib/BLI_polyfill_2d_beautify.h (renamed from source/blender/blenlib/BLI_polyfill2d_beautify.h)17
-rw-r--r--source/blender/blenlib/BLI_rand.h12
-rw-r--r--source/blender/blenlib/BLI_rect.h5
-rw-r--r--source/blender/blenlib/BLI_smallhash.h2
-rw-r--r--source/blender/blenlib/BLI_sort_utils.h7
-rw-r--r--source/blender/blenlib/BLI_stack.h8
-rw-r--r--source/blender/blenlib/BLI_strict_flags.h2
-rw-r--r--source/blender/blenlib/BLI_string.h14
-rw-r--r--source/blender/blenlib/BLI_string_cursor_utf8.h22
-rw-r--r--source/blender/blenlib/BLI_string_utf8.h10
-rw-r--r--source/blender/blenlib/BLI_string_utils.h19
-rw-r--r--source/blender/blenlib/BLI_sys_types.h8
-rw-r--r--source/blender/blenlib/BLI_task.h137
-rw-r--r--source/blender/blenlib/BLI_threads.h28
-rw-r--r--source/blender/blenlib/BLI_utildefines.h88
-rw-r--r--source/blender/blenlib/BLI_utildefines_iter.h52
-rw-r--r--source/blender/blenlib/BLI_utildefines_stack.h (renamed from source/blender/blenlib/BLI_stackdefines.h)12
-rw-r--r--source/blender/blenlib/BLI_utildefines_variadic.h50
-rw-r--r--source/blender/blenlib/BLI_vfontdata.h2
-rw-r--r--source/blender/blenlib/BLI_voronoi_2d.h (renamed from source/blender/blenlib/BLI_voronoi.h)8
-rw-r--r--source/blender/blenlib/BLI_winstuff.h29
-rw-r--r--source/blender/blenlib/CMakeLists.txt42
-rw-r--r--source/blender/blenlib/intern/BLI_args.c6
-rw-r--r--source/blender/blenlib/intern/BLI_array.c20
-rw-r--r--source/blender/blenlib/intern/BLI_dial_2d.c (renamed from source/blender/blenlib/intern/BLI_dial.c)10
-rw-r--r--source/blender/blenlib/intern/BLI_dynstr.c70
-rw-r--r--source/blender/blenlib/intern/BLI_ghash.c508
-rw-r--r--source/blender/blenlib/intern/BLI_ghash_utils.c288
-rw-r--r--source/blender/blenlib/intern/BLI_heap.c164
-rw-r--r--source/blender/blenlib/intern/BLI_kdopbvh.c266
-rw-r--r--source/blender/blenlib/intern/BLI_kdtree.c180
-rw-r--r--source/blender/blenlib/intern/BLI_linklist.c4
-rw-r--r--source/blender/blenlib/intern/BLI_linklist_lockfree.c91
-rw-r--r--source/blender/blenlib/intern/BLI_mempool.c130
-rw-r--r--source/blender/blenlib/intern/array_store.c46
-rw-r--r--source/blender/blenlib/intern/array_utils.c17
-rw-r--r--source/blender/blenlib/intern/astar.c2
-rw-r--r--source/blender/blenlib/intern/bitmap_draw_2d.c206
-rw-r--r--source/blender/blenlib/intern/boxpack_2d.c (renamed from source/blender/blenlib/intern/boxpack2d.c)24
-rw-r--r--source/blender/blenlib/intern/convexhull_2d.c (renamed from source/blender/blenlib/intern/convexhull2d.c)10
-rw-r--r--source/blender/blenlib/intern/edgehash.c124
-rw-r--r--source/blender/blenlib/intern/fileops.c23
-rw-r--r--source/blender/blenlib/intern/freetypefont.c30
-rw-r--r--source/blender/blenlib/intern/gsqueue.c4
-rw-r--r--source/blender/blenlib/intern/hash_mm2a.c6
-rw-r--r--source/blender/blenlib/intern/jitter_2d.c (renamed from source/blender/blenlib/intern/jitter.c)4
-rw-r--r--source/blender/blenlib/intern/lasso_2d.c (renamed from source/blender/blenlib/intern/lasso.c)4
-rw-r--r--source/blender/blenlib/intern/listbase.c110
-rw-r--r--source/blender/blenlib/intern/math_base_inline.c119
-rw-r--r--source/blender/blenlib/intern/math_bits_inline.c75
-rw-r--r--source/blender/blenlib/intern/math_color.c37
-rw-r--r--source/blender/blenlib/intern/math_color_blend_inline.c42
-rw-r--r--source/blender/blenlib/intern/math_color_inline.c8
-rw-r--r--source/blender/blenlib/intern/math_geom.c299
-rw-r--r--source/blender/blenlib/intern/math_matrix.c35
-rw-r--r--source/blender/blenlib/intern/math_rotation.c121
-rw-r--r--source/blender/blenlib/intern/math_solvers.c108
-rw-r--r--source/blender/blenlib/intern/math_statistics.c13
-rw-r--r--source/blender/blenlib/intern/math_vector.c126
-rw-r--r--source/blender/blenlib/intern/math_vector_inline.c14
-rw-r--r--source/blender/blenlib/intern/noise.c10
-rw-r--r--source/blender/blenlib/intern/path_util.c203
-rw-r--r--source/blender/blenlib/intern/polyfill2d_beautify.c496
-rw-r--r--source/blender/blenlib/intern/polyfill_2d.c (renamed from source/blender/blenlib/intern/polyfill2d.c)110
-rw-r--r--source/blender/blenlib/intern/polyfill_2d_beautify.c440
-rw-r--r--source/blender/blenlib/intern/rand.c101
-rw-r--r--source/blender/blenlib/intern/rct.c64
-rw-r--r--source/blender/blenlib/intern/smallhash.c44
-rw-r--r--source/blender/blenlib/intern/sort_utils.c22
-rw-r--r--source/blender/blenlib/intern/storage.c44
-rw-r--r--source/blender/blenlib/intern/string.c12
-rw-r--r--source/blender/blenlib/intern/string_cursor_utf8.c53
-rw-r--r--source/blender/blenlib/intern/string_utf8.c66
-rw-r--r--source/blender/blenlib/intern/string_utils.c88
-rw-r--r--source/blender/blenlib/intern/system.c4
-rw-r--r--source/blender/blenlib/intern/task.c784
-rw-r--r--source/blender/blenlib/intern/threads.c103
-rw-r--r--source/blender/blenlib/intern/timecode.c10
-rw-r--r--source/blender/blenlib/intern/voronoi_2d.c (renamed from source/blender/blenlib/intern/voronoi.c)10
-rw-r--r--source/blender/blenlib/intern/winstuff.c2
-rw-r--r--source/blender/blenloader/BLO_blend_defs.h2
-rw-r--r--source/blender/blenloader/BLO_readfile.h43
-rw-r--r--source/blender/blenloader/BLO_runtime.h3
-rw-r--r--source/blender/blenloader/BLO_undofile.h29
-rw-r--r--source/blender/blenloader/CMakeLists.txt7
-rw-r--r--source/blender/blenloader/intern/blend_validate.c151
-rw-r--r--source/blender/blenloader/intern/readblenentry.c15
-rw-r--r--source/blender/blenloader/intern/readfile.c1433
-rw-r--r--source/blender/blenloader/intern/readfile.h2
-rw-r--r--source/blender/blenloader/intern/undofile.c132
-rw-r--r--source/blender/blenloader/intern/versioning_250.c6
-rw-r--r--source/blender/blenloader/intern/versioning_260.c7
-rw-r--r--source/blender/blenloader/intern/versioning_270.c261
-rw-r--r--source/blender/blenloader/intern/versioning_defaults.c50
-rw-r--r--source/blender/blenloader/intern/versioning_legacy.c21
-rw-r--r--source/blender/blenloader/intern/writefile.c2305
-rw-r--r--source/blender/blentranslation/CMakeLists.txt4
-rw-r--r--source/blender/blentranslation/msgfmt/CMakeLists.txt (renamed from source/blender/quicktime/CMakeLists.txt)46
-rw-r--r--source/blender/blentranslation/msgfmt/msgfmt.c468
-rw-r--r--source/blender/bmesh/CMakeLists.txt5
-rw-r--r--source/blender/bmesh/bmesh.h5
-rw-r--r--source/blender/bmesh/bmesh_class.h10
-rw-r--r--source/blender/bmesh/bmesh_tools.h1
-rw-r--r--source/blender/bmesh/intern/bmesh_callback_generic.c2
-rw-r--r--source/blender/bmesh/intern/bmesh_construct.c4
-rw-r--r--source/blender/bmesh/intern/bmesh_core.c207
-rw-r--r--source/blender/bmesh/intern/bmesh_core.h52
-rw-r--r--source/blender/bmesh/intern/bmesh_edgeloop.c99
-rw-r--r--source/blender/bmesh/intern/bmesh_interp.c132
-rw-r--r--source/blender/bmesh/intern/bmesh_iterators.c4
-rw-r--r--source/blender/bmesh/intern/bmesh_iterators.h4
-rw-r--r--source/blender/bmesh/intern/bmesh_iterators_inline.h34
-rw-r--r--source/blender/bmesh/intern/bmesh_log.c72
-rw-r--r--source/blender/bmesh/intern/bmesh_marking.c108
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh.c684
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh.h17
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh_conv.c208
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh_conv.h9
-rw-r--r--source/blender/bmesh/intern/bmesh_mesh_validate.c2
-rw-r--r--source/blender/bmesh/intern/bmesh_mods.c57
-rw-r--r--source/blender/bmesh/intern/bmesh_mods.h7
-rw-r--r--source/blender/bmesh/intern/bmesh_opdefines.c22
-rw-r--r--source/blender/bmesh/intern/bmesh_operators.c327
-rw-r--r--source/blender/bmesh/intern/bmesh_operators.h15
-rw-r--r--source/blender/bmesh/intern/bmesh_polygon.c202
-rw-r--r--source/blender/bmesh/intern/bmesh_polygon.h8
-rw-r--r--source/blender/bmesh/intern/bmesh_polygon_edgenet.c182
-rw-r--r--source/blender/bmesh/intern/bmesh_polygon_edgenet.h4
-rw-r--r--source/blender/bmesh/intern/bmesh_private.h9
-rw-r--r--source/blender/bmesh/intern/bmesh_queries.c120
-rw-r--r--source/blender/bmesh/intern/bmesh_queries.h25
-rw-r--r--source/blender/bmesh/intern/bmesh_structure.c10
-rw-r--r--source/blender/bmesh/intern/bmesh_structure.h4
-rw-r--r--source/blender/bmesh/operators/bmo_bevel.c2
-rw-r--r--source/blender/bmesh/operators/bmo_bisect_plane.c9
-rw-r--r--source/blender/bmesh/operators/bmo_connect.c4
-rw-r--r--source/blender/bmesh/operators/bmo_connect_concave.c15
-rw-r--r--source/blender/bmesh/operators/bmo_connect_nonplanar.c4
-rw-r--r--source/blender/bmesh/operators/bmo_connect_pair.c27
-rw-r--r--source/blender/bmesh/operators/bmo_create.c18
-rw-r--r--source/blender/bmesh/operators/bmo_dissolve.c10
-rw-r--r--source/blender/bmesh/operators/bmo_dupe.c21
-rw-r--r--source/blender/bmesh/operators/bmo_edgenet.c30
-rw-r--r--source/blender/bmesh/operators/bmo_fill_attribute.c4
-rw-r--r--source/blender/bmesh/operators/bmo_fill_grid.c20
-rw-r--r--source/blender/bmesh/operators/bmo_fill_holes.c2
-rw-r--r--source/blender/bmesh/operators/bmo_hull.c2
-rw-r--r--source/blender/bmesh/operators/bmo_inset.c6
-rw-r--r--source/blender/bmesh/operators/bmo_join_triangles.c14
-rw-r--r--source/blender/bmesh/operators/bmo_mesh_conv.c11
-rw-r--r--source/blender/bmesh/operators/bmo_offset_edgeloops.c7
-rw-r--r--source/blender/bmesh/operators/bmo_primitive.c98
-rw-r--r--source/blender/bmesh/operators/bmo_removedoubles.c122
-rw-r--r--source/blender/bmesh/operators/bmo_rotate_edges.c272
-rw-r--r--source/blender/bmesh/operators/bmo_smooth_laplacian.c6
-rw-r--r--source/blender/bmesh/operators/bmo_split_edges.c2
-rw-r--r--source/blender/bmesh/operators/bmo_subdivide.c16
-rw-r--r--source/blender/bmesh/operators/bmo_subdivide_edgering.c32
-rw-r--r--source/blender/bmesh/operators/bmo_triangulate.c12
-rw-r--r--source/blender/bmesh/operators/bmo_utils.c54
-rw-r--r--source/blender/bmesh/tools/bmesh_beautify.c17
-rw-r--r--source/blender/bmesh/tools/bmesh_bevel.c1816
-rw-r--r--source/blender/bmesh/tools/bmesh_bisect_plane.c57
-rw-r--r--source/blender/bmesh/tools/bmesh_bisect_plane.h2
-rw-r--r--source/blender/bmesh/tools/bmesh_decimate_collapse.c39
-rw-r--r--source/blender/bmesh/tools/bmesh_decimate_dissolve.c15
-rw-r--r--source/blender/bmesh/tools/bmesh_decimate_unsubdivide.c28
-rw-r--r--source/blender/bmesh/tools/bmesh_edgenet.c44
-rw-r--r--source/blender/bmesh/tools/bmesh_edgesplit.c2
-rw-r--r--source/blender/bmesh/tools/bmesh_intersect.c72
-rw-r--r--source/blender/bmesh/tools/bmesh_intersect.h2
-rw-r--r--source/blender/bmesh/tools/bmesh_path.c53
-rw-r--r--source/blender/bmesh/tools/bmesh_path.h4
-rw-r--r--source/blender/bmesh/tools/bmesh_path_region.c30
-rw-r--r--source/blender/bmesh/tools/bmesh_region_match.c108
-rw-r--r--source/blender/bmesh/tools/bmesh_region_match.h2
-rw-r--r--source/blender/bmesh/tools/bmesh_separate.c133
-rw-r--r--source/blender/bmesh/tools/bmesh_separate.h32
-rw-r--r--source/blender/bmesh/tools/bmesh_triangulate.c19
-rw-r--r--source/blender/collada/AnimationExporter.cpp670
-rw-r--r--source/blender/collada/AnimationExporter.h29
-rw-r--r--source/blender/collada/AnimationImporter.cpp160
-rw-r--r--source/blender/collada/AnimationImporter.h9
-rw-r--r--source/blender/collada/ArmatureExporter.cpp86
-rw-r--r--source/blender/collada/ArmatureExporter.h2
-rw-r--r--source/blender/collada/ArmatureImporter.cpp82
-rw-r--r--source/blender/collada/ControllerExporter.cpp131
-rw-r--r--source/blender/collada/ControllerExporter.h2
-rw-r--r--source/blender/collada/DocumentExporter.cpp29
-rw-r--r--source/blender/collada/DocumentExporter.h5
-rw-r--r--source/blender/collada/DocumentImporter.cpp43
-rw-r--r--source/blender/collada/EffectExporter.cpp146
-rw-r--r--source/blender/collada/EffectExporter.h1
-rw-r--r--source/blender/collada/ErrorHandler.cpp18
-rw-r--r--source/blender/collada/ExportSettings.h39
-rw-r--r--source/blender/collada/GeometryExporter.cpp312
-rw-r--r--source/blender/collada/GeometryExporter.h34
-rw-r--r--source/blender/collada/ImageExporter.cpp32
-rw-r--r--source/blender/collada/ImportSettings.h8
-rw-r--r--source/blender/collada/InstanceWriter.cpp64
-rw-r--r--source/blender/collada/InstanceWriter.h3
-rw-r--r--source/blender/collada/MaterialExporter.cpp36
-rw-r--r--source/blender/collada/MeshImporter.cpp25
-rw-r--r--source/blender/collada/SceneExporter.cpp12
-rw-r--r--source/blender/collada/SceneExporter.h3
-rw-r--r--source/blender/collada/SkinInfo.cpp2
-rw-r--r--source/blender/collada/TransformReader.cpp23
-rw-r--r--source/blender/collada/TransformReader.h5
-rw-r--r--source/blender/collada/TransformWriter.cpp7
-rw-r--r--source/blender/collada/TransformWriter.h3
-rw-r--r--source/blender/collada/collada.cpp95
-rw-r--r--source/blender/collada/collada.h49
-rw-r--r--source/blender/collada/collada_internal.cpp29
-rw-r--r--source/blender/collada/collada_internal.h10
-rw-r--r--source/blender/collada/collada_utils.cpp457
-rw-r--r--source/blender/collada/collada_utils.h37
-rw-r--r--source/blender/compositor/CMakeLists.txt4
-rw-r--r--source/blender/compositor/COM_compositor.h13
-rw-r--r--source/blender/compositor/intern/COM_Debug.cpp4
-rw-r--r--source/blender/compositor/intern/COM_ExecutionGroup.h2
-rw-r--r--source/blender/compositor/intern/COM_WorkScheduler.cpp117
-rw-r--r--source/blender/compositor/intern/COM_compositor.cpp16
-rw-r--r--source/blender/compositor/nodes/COM_BrightnessNode.cpp2
-rw-r--r--source/blender/compositor/nodes/COM_CompositorNode.cpp1
-rw-r--r--source/blender/compositor/nodes/COM_ImageNode.cpp47
-rw-r--r--source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp5
-rw-r--r--source/blender/compositor/nodes/COM_RenderLayersNode.cpp198
-rw-r--r--source/blender/compositor/nodes/COM_RenderLayersNode.h20
-rw-r--r--source/blender/compositor/nodes/COM_ScaleNode.cpp19
-rw-r--r--source/blender/compositor/operations/COM_BrightnessOperation.cpp14
-rw-r--r--source/blender/compositor/operations/COM_BrightnessOperation.h3
-rw-r--r--source/blender/compositor/operations/COM_CalculateMeanOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_ColorRampOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_CompositorOperation.cpp59
-rw-r--r--source/blender/compositor/operations/COM_CompositorOperation.h4
-rw-r--r--source/blender/compositor/operations/COM_ConvertOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp6
-rw-r--r--source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp6
-rw-r--r--source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_GlareSimpleStarOperation.cpp4
-rw-r--r--source/blender/compositor/operations/COM_KeyingOperation.cpp17
-rw-r--r--source/blender/compositor/operations/COM_KeyingScreenOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp25
-rw-r--r--source/blender/compositor/operations/COM_MapRangeOperation.cpp5
-rw-r--r--source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp80
-rw-r--r--source/blender/compositor/operations/COM_MovieClipAttributeOperation.h6
-rw-r--r--source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_PlaneDistortCommonOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_PlaneTrackOperation.cpp2
-rw-r--r--source/blender/compositor/operations/COM_RenderLayersProg.cpp188
-rw-r--r--source/blender/compositor/operations/COM_RenderLayersProg.h132
-rw-r--r--source/blender/compositor/operations/COM_ScaleOperation.cpp78
-rw-r--r--source/blender/compositor/operations/COM_ScaleOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_TextureOperation.cpp29
-rw-r--r--source/blender/compositor/operations/COM_TextureOperation.h2
-rw-r--r--source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp6
-rw-r--r--source/blender/compositor/operations/COM_VectorBlurOperation.cpp718
-rw-r--r--source/blender/compositor/operations/COM_ViewerOperation.cpp6
-rw-r--r--source/blender/datatoc/datatoc.c5
-rw-r--r--source/blender/depsgraph/CMakeLists.txt17
-rw-r--r--source/blender/depsgraph/DEG_depsgraph.h38
-rw-r--r--source/blender/depsgraph/DEG_depsgraph_build.h15
-rw-r--r--source/blender/depsgraph/DEG_depsgraph_debug.h45
-rw-r--r--source/blender/depsgraph/DEG_depsgraph_query.h12
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder.cc86
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder.h4
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_cycle.cc160
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_map.cc (renamed from source/blender/modifiers/intern/MOD_boolean_util.h)50
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_map.h69
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_nodes.cc1093
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_nodes.h86
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_nodes_rig.cc241
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_nodes_scene.cc84
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_pchanmap.cc2
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations.cc1943
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations.h284
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations_impl.h230
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations_keys.cc25
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations_rig.cc246
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_relations_scene.cc79
-rw-r--r--source/blender/depsgraph/intern/builder/deg_builder_transitive.cc20
-rw-r--r--source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc (renamed from source/blender/depsgraph/intern/debug/deg_debug_graphviz.cc)190
-rw-r--r--source/blender/depsgraph/intern/debug/deg_debug_stats_gnuplot.cc157
-rw-r--r--source/blender/depsgraph/intern/depsgraph.cc490
-rw-r--r--source/blender/depsgraph/intern/depsgraph.h59
-rw-r--r--source/blender/depsgraph/intern/depsgraph_build.cc188
-rw-r--r--source/blender/depsgraph/intern/depsgraph_debug.cc36
-rw-r--r--source/blender/depsgraph/intern/depsgraph_eval.cc14
-rw-r--r--source/blender/depsgraph/intern/depsgraph_intern.h18
-rw-r--r--source/blender/depsgraph/intern/depsgraph_query.cc3
-rw-r--r--source/blender/depsgraph/intern/depsgraph_query_foreach.cc148
-rw-r--r--source/blender/depsgraph/intern/depsgraph_tag.cc112
-rw-r--r--source/blender/depsgraph/intern/depsgraph_type_defines.cc70
-rw-r--r--source/blender/depsgraph/intern/depsgraph_types.h228
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval.cc257
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval_debug.cc250
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval_debug.h79
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval_flush.cc345
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval_stats.cc70
-rw-r--r--source/blender/depsgraph/intern/eval/deg_eval_stats.h (renamed from source/blender/depsgraph/util/deg_util_hash.h)21
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node.cc290
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node.h160
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_component.cc170
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_component.h114
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_id.cc179
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_id.h79
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_operation.cc22
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_operation.h21
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_time.cc46
-rw-r--r--source/blender/depsgraph/intern/nodes/deg_node_time.h52
-rw-r--r--source/blender/depsgraph/util/deg_util_foreach.h25
-rw-r--r--source/blender/depsgraph/util/deg_util_function.h2
-rw-r--r--source/blender/editors/CMakeLists.txt2
-rw-r--r--source/blender/editors/animation/anim_channels_defines.c9
-rw-r--r--source/blender/editors/animation/anim_channels_edit.c165
-rw-r--r--source/blender/editors/animation/anim_draw.c1
-rw-r--r--source/blender/editors/animation/anim_filter.c78
-rw-r--r--source/blender/editors/animation/anim_markers.c47
-rw-r--r--source/blender/editors/animation/anim_ops.c20
-rw-r--r--source/blender/editors/animation/drivers.c11
-rw-r--r--source/blender/editors/animation/fmodifier_ui.c12
-rw-r--r--source/blender/editors/animation/keyframes_draw.c6
-rw-r--r--source/blender/editors/animation/keyframes_edit.c4
-rw-r--r--source/blender/editors/animation/keyframes_general.c21
-rw-r--r--source/blender/editors/animation/keyframing.c85
-rw-r--r--source/blender/editors/animation/keyingsets.c4
-rw-r--r--source/blender/editors/armature/CMakeLists.txt1
-rw-r--r--source/blender/editors/armature/armature_add.c101
-rw-r--r--source/blender/editors/armature/armature_edit.c92
-rw-r--r--source/blender/editors/armature/armature_intern.h7
-rw-r--r--source/blender/editors/armature/armature_naming.c33
-rw-r--r--source/blender/editors/armature/armature_relations.c62
-rw-r--r--source/blender/editors/armature/armature_select.c215
-rw-r--r--source/blender/editors/armature/armature_skinning.c2
-rw-r--r--source/blender/editors/armature/armature_utils.c128
-rw-r--r--source/blender/editors/armature/editarmature_generate.c6
-rw-r--r--source/blender/editors/armature/editarmature_retarget.c22
-rw-r--r--source/blender/editors/armature/editarmature_sketch.c13
-rw-r--r--source/blender/editors/armature/editarmature_undo.c191
-rw-r--r--source/blender/editors/armature/meshlaplacian.c2
-rw-r--r--source/blender/editors/armature/meshlaplacian.h2
-rw-r--r--source/blender/editors/armature/pose_edit.c86
-rw-r--r--source/blender/editors/armature/pose_group.c2
-rw-r--r--source/blender/editors/armature/pose_lib.c55
-rw-r--r--source/blender/editors/armature/pose_select.c26
-rw-r--r--source/blender/editors/armature/pose_slide.c339
-rw-r--r--source/blender/editors/armature/pose_transform.c45
-rw-r--r--source/blender/editors/armature/pose_utils.c4
-rw-r--r--source/blender/editors/armature/reeb.c12
-rw-r--r--source/blender/editors/curve/CMakeLists.txt1
-rw-r--r--source/blender/editors/curve/curve_intern.h8
-rw-r--r--source/blender/editors/curve/curve_ops.c7
-rw-r--r--source/blender/editors/curve/editcurve.c271
-rw-r--r--source/blender/editors/curve/editcurve_add.c2
-rw-r--r--source/blender/editors/curve/editcurve_paint.c120
-rw-r--r--source/blender/editors/curve/editcurve_select.c10
-rw-r--r--source/blender/editors/curve/editcurve_undo.c256
-rw-r--r--source/blender/editors/curve/editfont.c84
-rw-r--r--source/blender/editors/curve/editfont_undo.c122
-rw-r--r--source/blender/editors/datafiles/CMakeLists.txt495
-rw-r--r--source/blender/editors/gpencil/drawgpencil.c99
-rw-r--r--source/blender/editors/gpencil/editaction_gpencil.c8
-rw-r--r--source/blender/editors/gpencil/gpencil_brush.c36
-rw-r--r--source/blender/editors/gpencil/gpencil_convert.c8
-rw-r--r--source/blender/editors/gpencil/gpencil_data.c65
-rw-r--r--source/blender/editors/gpencil/gpencil_edit.c132
-rw-r--r--source/blender/editors/gpencil/gpencil_intern.h112
-rw-r--r--source/blender/editors/gpencil/gpencil_interpolate.c43
-rw-r--r--source/blender/editors/gpencil/gpencil_ops.c6
-rw-r--r--source/blender/editors/gpencil/gpencil_paint.c49
-rw-r--r--source/blender/editors/gpencil/gpencil_select.c30
-rw-r--r--source/blender/editors/gpencil/gpencil_undo.c1
-rw-r--r--source/blender/editors/gpencil/gpencil_utils.c76
-rw-r--r--source/blender/editors/include/ED_anim_api.h13
-rw-r--r--source/blender/editors/include/ED_armature.h75
-rw-r--r--source/blender/editors/include/ED_clip.h2
-rw-r--r--source/blender/editors/include/ED_curve.h10
-rw-r--r--source/blender/editors/include/ED_image.h2
-rw-r--r--source/blender/editors/include/ED_keyframing.h13
-rw-r--r--source/blender/editors/include/ED_lattice.h18
-rw-r--r--source/blender/editors/include/ED_mball.h4
-rw-r--r--source/blender/editors/include/ED_mesh.h34
-rw-r--r--source/blender/editors/include/ED_node.h2
-rw-r--r--source/blender/editors/include/ED_object.h74
-rw-r--r--source/blender/editors/include/ED_paint.h39
-rw-r--r--source/blender/editors/include/ED_particle.h11
-rw-r--r--source/blender/editors/include/ED_screen.h7
-rw-r--r--source/blender/editors/include/ED_sculpt.h6
-rw-r--r--source/blender/editors/include/ED_text.h10
-rw-r--r--source/blender/editors/include/ED_transform.h15
-rw-r--r--source/blender/editors/include/ED_transform_snap_object_context.h8
-rw-r--r--source/blender/editors/include/ED_undo.h64
-rw-r--r--source/blender/editors/include/ED_util.h39
-rw-r--r--source/blender/editors/include/ED_uvedit.h89
-rw-r--r--source/blender/editors/include/ED_view3d.h82
-rw-r--r--source/blender/editors/include/UI_icons.h4
-rw-r--r--source/blender/editors/include/UI_interface.h93
-rw-r--r--source/blender/editors/include/UI_resources.h1
-rw-r--r--source/blender/editors/include/UI_view2d.h3
-rw-r--r--source/blender/editors/interface/CMakeLists.txt17
-rw-r--r--source/blender/editors/interface/interface.c165
-rw-r--r--source/blender/editors/interface/interface_anim.c2
-rw-r--r--source/blender/editors/interface/interface_draw.c8
-rw-r--r--source/blender/editors/interface/interface_eyedropper.c1198
-rw-r--r--source/blender/editors/interface/interface_eyedropper_color.c356
-rw-r--r--source/blender/editors/interface/interface_eyedropper_colorband.c337
-rw-r--r--source/blender/editors/interface/interface_eyedropper_datablock.c351
-rw-r--r--source/blender/editors/interface/interface_eyedropper_depth.c384
-rw-r--r--source/blender/editors/interface/interface_eyedropper_driver.c232
-rw-r--r--source/blender/editors/interface/interface_eyedropper_intern.h54
-rw-r--r--source/blender/editors/interface/interface_handlers.c471
-rw-r--r--source/blender/editors/interface/interface_icons.c14
-rw-r--r--source/blender/editors/interface/interface_intern.h61
-rw-r--r--source/blender/editors/interface/interface_layout.c500
-rw-r--r--source/blender/editors/interface/interface_ops.c84
-rw-r--r--source/blender/editors/interface/interface_panel.c22
-rw-r--r--source/blender/editors/interface/interface_region_color_picker.c650
-rw-r--r--source/blender/editors/interface/interface_region_menu_pie.c380
-rw-r--r--source/blender/editors/interface/interface_region_menu_popup.c626
-rw-r--r--source/blender/editors/interface/interface_region_popup.c683
-rw-r--r--source/blender/editors/interface/interface_region_search.c800
-rw-r--r--source/blender/editors/interface/interface_region_tooltip.c764
-rw-r--r--source/blender/editors/interface/interface_regions.c3344
-rw-r--r--source/blender/editors/interface/interface_regions_intern.h39
-rw-r--r--source/blender/editors/interface/interface_templates.c451
-rw-r--r--source/blender/editors/interface/interface_utils.c23
-rw-r--r--source/blender/editors/interface/interface_widgets.c237
-rw-r--r--source/blender/editors/interface/resources.c44
-rw-r--r--source/blender/editors/interface/view2d.c27
-rw-r--r--source/blender/editors/interface/view2d_ops.c21
-rw-r--r--source/blender/editors/io/io_alembic.c108
-rw-r--r--source/blender/editors/io/io_cache.c35
-rw-r--r--source/blender/editors/io/io_collada.c236
-rw-r--r--source/blender/editors/lattice/CMakeLists.txt45
-rw-r--r--source/blender/editors/lattice/editlattice_select.c (renamed from source/blender/editors/object/object_lattice.c)516
-rw-r--r--source/blender/editors/lattice/editlattice_tools.c340
-rw-r--r--source/blender/editors/lattice/editlattice_undo.c195
-rw-r--r--source/blender/editors/lattice/lattice_intern.h (renamed from source/blender/editors/util/util_intern.h)34
-rw-r--r--source/blender/editors/lattice/lattice_ops.c80
-rw-r--r--source/blender/editors/mask/mask_add.c13
-rw-r--r--source/blender/editors/mask/mask_draw.c84
-rw-r--r--source/blender/editors/mask/mask_ops.c17
-rw-r--r--source/blender/editors/mask/mask_select.c43
-rw-r--r--source/blender/editors/mesh/CMakeLists.txt1
-rw-r--r--source/blender/editors/mesh/editface.c263
-rw-r--r--source/blender/editors/mesh/editmesh_add.c11
-rw-r--r--source/blender/editors/mesh/editmesh_bevel.c17
-rw-r--r--source/blender/editors/mesh/editmesh_extrude.c180
-rw-r--r--source/blender/editors/mesh/editmesh_inset.c41
-rw-r--r--source/blender/editors/mesh/editmesh_intersect.c56
-rw-r--r--source/blender/editors/mesh/editmesh_knife.c44
-rw-r--r--source/blender/editors/mesh/editmesh_loopcut.c13
-rw-r--r--source/blender/editors/mesh/editmesh_path.c33
-rw-r--r--source/blender/editors/mesh/editmesh_rip.c6
-rw-r--r--source/blender/editors/mesh/editmesh_select.c521
-rw-r--r--source/blender/editors/mesh/editmesh_tools.c810
-rw-r--r--source/blender/editors/mesh/editmesh_undo.c200
-rw-r--r--source/blender/editors/mesh/editmesh_utils.c429
-rw-r--r--source/blender/editors/mesh/mesh_data.c53
-rw-r--r--source/blender/editors/mesh/mesh_mirror.c374
-rw-r--r--source/blender/editors/mesh/mesh_navmesh.c5
-rw-r--r--source/blender/editors/mesh/meshtools.c166
-rw-r--r--source/blender/editors/metaball/CMakeLists.txt1
-rw-r--r--source/blender/editors/metaball/editmball_undo.c199
-rw-r--r--source/blender/editors/metaball/mball_edit.c123
-rw-r--r--source/blender/editors/object/CMakeLists.txt2
-rw-r--r--source/blender/editors/object/object_add.c253
-rw-r--r--source/blender/editors/object/object_bake.c6
-rw-r--r--source/blender/editors/object/object_bake_api.c71
-rw-r--r--source/blender/editors/object/object_constraint.c6
-rw-r--r--source/blender/editors/object/object_data_transfer.c16
-rw-r--r--source/blender/editors/object/object_edit.c278
-rw-r--r--source/blender/editors/object/object_group.c5
-rw-r--r--source/blender/editors/object/object_hook.c4
-rw-r--r--source/blender/editors/object/object_intern.h11
-rw-r--r--source/blender/editors/object/object_modes.c178
-rw-r--r--source/blender/editors/object/object_modifier.c80
-rw-r--r--source/blender/editors/object/object_ops.c41
-rw-r--r--source/blender/editors/object/object_relations.c287
-rw-r--r--source/blender/editors/object/object_select.c6
-rw-r--r--source/blender/editors/object/object_shapekey.c10
-rw-r--r--source/blender/editors/object/object_transform.c96
-rw-r--r--source/blender/editors/object/object_vgroup.c330
-rw-r--r--source/blender/editors/physics/CMakeLists.txt2
-rw-r--r--source/blender/editors/physics/dynamicpaint_ops.c42
-rw-r--r--source/blender/editors/physics/particle_edit.c387
-rw-r--r--source/blender/editors/physics/particle_edit_undo.c297
-rw-r--r--source/blender/editors/physics/particle_edit_utildefines.h50
-rw-r--r--source/blender/editors/physics/particle_object.c61
-rw-r--r--source/blender/editors/physics/physics_fluid.c118
-rw-r--r--source/blender/editors/physics/physics_intern.h10
-rw-r--r--source/blender/editors/physics/physics_ops.c10
-rw-r--r--source/blender/editors/physics/physics_pointcache.c42
-rw-r--r--source/blender/editors/physics/rigidbody_constraint.c1
-rw-r--r--source/blender/editors/physics/rigidbody_object.c3
-rw-r--r--source/blender/editors/render/CMakeLists.txt10
-rw-r--r--source/blender/editors/render/render_internal.c60
-rw-r--r--source/blender/editors/render/render_opengl.c78
-rw-r--r--source/blender/editors/render/render_preview.c38
-rw-r--r--source/blender/editors/render/render_shading.c29
-rw-r--r--source/blender/editors/render/render_update.c6
-rw-r--r--source/blender/editors/render/render_view.c19
-rw-r--r--source/blender/editors/screen/CMakeLists.txt1
-rw-r--r--source/blender/editors/screen/area.c33
-rw-r--r--source/blender/editors/screen/glutil.c8
-rw-r--r--source/blender/editors/screen/screen_context.c30
-rw-r--r--source/blender/editors/screen/screen_draw.c355
-rw-r--r--source/blender/editors/screen/screen_edit.c362
-rw-r--r--source/blender/editors/screen/screen_intern.h10
-rw-r--r--source/blender/editors/screen/screen_ops.c907
-rw-r--r--source/blender/editors/sculpt_paint/CMakeLists.txt7
-rw-r--r--source/blender/editors/sculpt_paint/paint_cursor.c54
-rw-r--r--source/blender/editors/sculpt_paint/paint_curve.c118
-rw-r--r--source/blender/editors/sculpt_paint/paint_curve_undo.c168
-rw-r--r--source/blender/editors/sculpt_paint/paint_hide.c12
-rw-r--r--source/blender/editors/sculpt_paint/paint_image.c412
-rw-r--r--source/blender/editors/sculpt_paint/paint_image_2d.c28
-rw-r--r--source/blender/editors/sculpt_paint/paint_image_proj.c63
-rw-r--r--source/blender/editors/sculpt_paint/paint_image_undo.c533
-rw-r--r--source/blender/editors/sculpt_paint/paint_intern.h127
-rw-r--r--source/blender/editors/sculpt_paint/paint_mask.c48
-rw-r--r--source/blender/editors/sculpt_paint/paint_ops.c333
-rw-r--r--source/blender/editors/sculpt_paint/paint_stroke.c46
-rw-r--r--source/blender/editors/sculpt_paint/paint_undo.c410
-rw-r--r--source/blender/editors/sculpt_paint/paint_utils.c26
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex.c3868
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex_color_ops.c574
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex_color_utils.c648
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex_proj.c37
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c859
-rw-r--r--source/blender/editors/sculpt_paint/paint_vertex_weight_utils.c311
-rw-r--r--source/blender/editors/sculpt_paint/sculpt.c1668
-rw-r--r--source/blender/editors/sculpt_paint/sculpt_intern.h246
-rw-r--r--source/blender/editors/sculpt_paint/sculpt_undo.c194
-rw-r--r--source/blender/editors/sculpt_paint/sculpt_uv.c12
-rw-r--r--source/blender/editors/sound/sound_ops.c20
-rw-r--r--source/blender/editors/space_action/action_buttons.c2
-rw-r--r--source/blender/editors/space_action/action_data.c8
-rw-r--r--source/blender/editors/space_action/action_edit.c13
-rw-r--r--source/blender/editors/space_action/action_select.c63
-rw-r--r--source/blender/editors/space_action/space_action.c8
-rw-r--r--source/blender/editors/space_api/spacetypes.c5
-rw-r--r--source/blender/editors/space_buttons/buttons_ops.c2
-rw-r--r--source/blender/editors/space_buttons/buttons_texture.c6
-rw-r--r--source/blender/editors/space_clip/clip_buttons.c2
-rw-r--r--source/blender/editors/space_clip/clip_draw.c16
-rw-r--r--source/blender/editors/space_clip/clip_editor.c12
-rw-r--r--source/blender/editors/space_clip/clip_graph_ops.c20
-rw-r--r--source/blender/editors/space_clip/clip_intern.h2
-rw-r--r--source/blender/editors/space_clip/clip_ops.c4
-rw-r--r--source/blender/editors/space_clip/clip_toolbar.c4
-rw-r--r--source/blender/editors/space_clip/clip_utils.c63
-rw-r--r--source/blender/editors/space_clip/space_clip.c3
-rw-r--r--source/blender/editors/space_clip/tracking_ops.c34
-rw-r--r--source/blender/editors/space_clip/tracking_ops_detect.c2
-rw-r--r--source/blender/editors/space_clip/tracking_ops_orient.c5
-rw-r--r--source/blender/editors/space_clip/tracking_ops_plane.c3
-rw-r--r--source/blender/editors/space_clip/tracking_ops_track.c8
-rw-r--r--source/blender/editors/space_clip/tracking_select.c55
-rw-r--r--source/blender/editors/space_console/console_intern.h2
-rw-r--r--source/blender/editors/space_console/console_ops.c6
-rw-r--r--source/blender/editors/space_file/file_draw.c2
-rw-r--r--source/blender/editors/space_file/file_ops.c37
-rw-r--r--source/blender/editors/space_file/file_panels.c2
-rw-r--r--source/blender/editors/space_file/filelist.c87
-rw-r--r--source/blender/editors/space_file/filelist.h3
-rw-r--r--source/blender/editors/space_file/fsmenu.c46
-rw-r--r--source/blender/editors/space_file/space_file.c10
-rw-r--r--source/blender/editors/space_graph/graph_buttons.c47
-rw-r--r--source/blender/editors/space_graph/graph_edit.c108
-rw-r--r--source/blender/editors/space_graph/graph_intern.h1
-rw-r--r--source/blender/editors/space_graph/graph_ops.c15
-rw-r--r--source/blender/editors/space_graph/graph_select.c57
-rw-r--r--source/blender/editors/space_graph/graph_utils.c4
-rw-r--r--source/blender/editors/space_graph/space_graph.c15
-rw-r--r--source/blender/editors/space_image/image_buttons.c87
-rw-r--r--source/blender/editors/space_image/image_draw.c12
-rw-r--r--source/blender/editors/space_image/image_edit.c2
-rw-r--r--source/blender/editors/space_image/image_ops.c119
-rw-r--r--source/blender/editors/space_image/space_image.c42
-rw-r--r--source/blender/editors/space_info/info_ops.c1
-rw-r--r--source/blender/editors/space_info/info_report.c10
-rw-r--r--source/blender/editors/space_logic/logic_buttons.c8
-rw-r--r--source/blender/editors/space_logic/logic_ops.c8
-rw-r--r--source/blender/editors/space_logic/logic_window.c4
-rw-r--r--source/blender/editors/space_nla/nla_buttons.c8
-rw-r--r--source/blender/editors/space_nla/nla_channels.c10
-rw-r--r--source/blender/editors/space_nla/nla_draw.c23
-rw-r--r--source/blender/editors/space_nla/nla_edit.c36
-rw-r--r--source/blender/editors/space_nla/nla_select.c30
-rw-r--r--source/blender/editors/space_nla/space_nla.c15
-rw-r--r--source/blender/editors/space_node/drawnode.c166
-rw-r--r--source/blender/editors/space_node/node_add.c32
-rw-r--r--source/blender/editors/space_node/node_buttons.c11
-rw-r--r--source/blender/editors/space_node/node_draw.c145
-rw-r--r--source/blender/editors/space_node/node_edit.c39
-rw-r--r--source/blender/editors/space_node/node_group.c25
-rw-r--r--source/blender/editors/space_node/node_intern.h5
-rw-r--r--source/blender/editors/space_node/node_relationships.c57
-rw-r--r--source/blender/editors/space_node/node_select.c41
-rw-r--r--source/blender/editors/space_node/node_templates.c11
-rw-r--r--source/blender/editors/space_node/node_view.c14
-rw-r--r--source/blender/editors/space_node/space_node.c4
-rw-r--r--source/blender/editors/space_outliner/outliner_draw.c58
-rw-r--r--source/blender/editors/space_outliner/outliner_edit.c82
-rw-r--r--source/blender/editors/space_outliner/outliner_intern.h8
-rw-r--r--source/blender/editors/space_outliner/outliner_select.c239
-rw-r--r--source/blender/editors/space_outliner/outliner_tools.c61
-rw-r--r--source/blender/editors/space_outliner/outliner_tree.c23
-rw-r--r--source/blender/editors/space_sequencer/sequencer_add.c5
-rw-r--r--source/blender/editors/space_sequencer/sequencer_draw.c34
-rw-r--r--source/blender/editors/space_sequencer/sequencer_edit.c124
-rw-r--r--source/blender/editors/space_sequencer/sequencer_modifier.c4
-rw-r--r--source/blender/editors/space_sequencer/sequencer_scopes.c43
-rw-r--r--source/blender/editors/space_sequencer/sequencer_select.c16
-rw-r--r--source/blender/editors/space_sequencer/space_sequencer.c8
-rw-r--r--source/blender/editors/space_text/CMakeLists.txt3
-rw-r--r--source/blender/editors/space_text/space_text.c4
-rw-r--r--source/blender/editors/space_text/text_autocomplete.c19
-rw-r--r--source/blender/editors/space_text/text_draw.c8
-rw-r--r--source/blender/editors/space_text/text_format.h2
-rw-r--r--source/blender/editors/space_text/text_format_pov.c903
-rw-r--r--source/blender/editors/space_text/text_format_pov_ini.c491
-rw-r--r--source/blender/editors/space_text/text_ops.c164
-rw-r--r--source/blender/editors/space_text/text_undo.c185
-rw-r--r--source/blender/editors/space_time/space_time.c2
-rw-r--r--source/blender/editors/space_view3d/CMakeLists.txt1
-rw-r--r--source/blender/editors/space_view3d/drawanimviz.c18
-rw-r--r--source/blender/editors/space_view3d/drawarmature.c15
-rw-r--r--source/blender/editors/space_view3d/drawmesh.c14
-rw-r--r--source/blender/editors/space_view3d/drawobject.c185
-rw-r--r--source/blender/editors/space_view3d/drawsimdebug.c2
-rw-r--r--source/blender/editors/space_view3d/drawvolume.c10
-rw-r--r--source/blender/editors/space_view3d/space_view3d.c53
-rw-r--r--source/blender/editors/space_view3d/view3d_buttons.c21
-rw-r--r--source/blender/editors/space_view3d/view3d_camera_control.c6
-rw-r--r--source/blender/editors/space_view3d/view3d_draw.c366
-rw-r--r--source/blender/editors/space_view3d/view3d_edit.c1982
-rw-r--r--source/blender/editors/space_view3d/view3d_fly.c4
-rw-r--r--source/blender/editors/space_view3d/view3d_header.c6
-rw-r--r--source/blender/editors/space_view3d/view3d_intern.h36
-rw-r--r--source/blender/editors/space_view3d/view3d_iterators.c2
-rw-r--r--source/blender/editors/space_view3d/view3d_ops.c10
-rw-r--r--source/blender/editors/space_view3d/view3d_project.c5
-rw-r--r--source/blender/editors/space_view3d/view3d_ruler.c10
-rw-r--r--source/blender/editors/space_view3d/view3d_select.c353
-rw-r--r--source/blender/editors/space_view3d/view3d_toolbar.c6
-rw-r--r--source/blender/editors/space_view3d/view3d_utils.c1506
-rw-r--r--source/blender/editors/space_view3d/view3d_view.c815
-rw-r--r--source/blender/editors/space_view3d/view3d_walk.c19
-rw-r--r--source/blender/editors/transform/transform.c165
-rw-r--r--source/blender/editors/transform/transform.h3
-rw-r--r--source/blender/editors/transform/transform_constraints.c9
-rw-r--r--source/blender/editors/transform/transform_conversions.c499
-rw-r--r--source/blender/editors/transform/transform_generics.c60
-rw-r--r--source/blender/editors/transform/transform_input.c13
-rw-r--r--source/blender/editors/transform/transform_manipulator.c332
-rw-r--r--source/blender/editors/transform/transform_ops.c37
-rw-r--r--source/blender/editors/transform/transform_orientations.c67
-rw-r--r--source/blender/editors/transform/transform_snap.c32
-rw-r--r--source/blender/editors/transform/transform_snap_object.c1445
-rw-r--r--source/blender/editors/undo/CMakeLists.txt45
-rw-r--r--source/blender/editors/undo/ed_undo.c (renamed from source/blender/editors/util/undo.c)428
-rw-r--r--source/blender/editors/undo/memfile_undo.c150
-rw-r--r--source/blender/editors/undo/undo_intern.h35
-rw-r--r--source/blender/editors/undo/undo_system_types.c74
-rw-r--r--source/blender/editors/util/CMakeLists.txt4
-rw-r--r--source/blender/editors/util/ed_transverts.c2
-rw-r--r--source/blender/editors/util/ed_util.c70
-rw-r--r--source/blender/editors/util/editmode_undo.c360
-rw-r--r--source/blender/editors/util/numinput.c27
-rw-r--r--source/blender/editors/uvedit/uvedit_draw.c10
-rw-r--r--source/blender/editors/uvedit/uvedit_intern.h27
-rw-r--r--source/blender/editors/uvedit/uvedit_ops.c845
-rw-r--r--source/blender/editors/uvedit/uvedit_parametrizer.c14
-rw-r--r--source/blender/editors/uvedit/uvedit_smart_stitch.c19
-rw-r--r--source/blender/editors/uvedit/uvedit_unwrap_ops.c167
-rw-r--r--source/blender/freestyle/intern/application/AppView.cpp6
-rw-r--r--source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp4
-rw-r--r--source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp12
-rw-r--r--source/blender/freestyle/intern/geometry/matrix_util.h6
-rw-r--r--source/blender/freestyle/intern/python/BPy_Freestyle.cpp4
-rw-r--r--source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h2
-rw-r--r--source/blender/freestyle/intern/system/PythonInterpreter.h2
-rw-r--r--source/blender/freestyle/intern/system/StringUtils.h1
-rw-r--r--source/blender/freestyle/intern/view_map/ViewMapAdvancedIterators.h6
-rw-r--r--source/blender/freestyle/intern/winged_edge/WingedEdgeBuilder.h2
-rw-r--r--source/blender/gpu/CMakeLists.txt3
-rw-r--r--source/blender/gpu/GPU_buffers.h58
-rw-r--r--source/blender/gpu/GPU_material.h8
-rw-r--r--source/blender/gpu/GPU_select.h16
-rw-r--r--source/blender/gpu/intern/gpu_basic_shader.c4
-rw-r--r--source/blender/gpu/intern/gpu_buffers.c194
-rw-r--r--source/blender/gpu/intern/gpu_codegen.c4
-rw-r--r--source/blender/gpu/intern/gpu_compositing.c4
-rw-r--r--source/blender/gpu/intern/gpu_debug.c20
-rw-r--r--source/blender/gpu/intern/gpu_draw.c52
-rw-r--r--source/blender/gpu/intern/gpu_framebuffer.c6
-rw-r--r--source/blender/gpu/intern/gpu_material.c55
-rw-r--r--source/blender/gpu/intern/gpu_select.c286
-rw-r--r--source/blender/gpu/intern/gpu_select_pick.c746
-rw-r--r--source/blender/gpu/intern/gpu_select_private.h53
-rw-r--r--source/blender/gpu/intern/gpu_select_sample_query.c213
-rw-r--r--source/blender/gpu/intern/gpu_shader.c1
-rw-r--r--source/blender/gpu/intern/gpu_texture.c14
-rw-r--r--source/blender/gpu/shaders/gpu_shader_fx_ssao_frag.glsl2
-rw-r--r--source/blender/gpu/shaders/gpu_shader_material.glsl355
-rw-r--r--source/blender/ikplugin/intern/iksolver_plugin.c50
-rw-r--r--source/blender/imbuf/CMakeLists.txt12
-rw-r--r--source/blender/imbuf/IMB_colormanagement.h2
-rw-r--r--source/blender/imbuf/IMB_imbuf.h31
-rw-r--r--source/blender/imbuf/IMB_imbuf_types.h23
-rw-r--r--source/blender/imbuf/IMB_metadata.h (renamed from source/blender/imbuf/intern/IMB_metadata.h)42
-rw-r--r--source/blender/imbuf/intern/IMB_anim.h25
-rw-r--r--source/blender/imbuf/intern/IMB_colormanagement_intern.h2
-rw-r--r--source/blender/imbuf/intern/allocimbuf.c44
-rw-r--r--source/blender/imbuf/intern/anim_movie.c104
-rw-r--r--source/blender/imbuf/intern/bmp.c30
-rw-r--r--source/blender/imbuf/intern/cineon/cineon_dpx.c4
-rw-r--r--source/blender/imbuf/intern/cineon/cineonlib.c1
-rw-r--r--source/blender/imbuf/intern/cineon/dpxlib.c6
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.c120
-rw-r--r--source/blender/imbuf/intern/cineon/logImageCore.h2
-rw-r--r--source/blender/imbuf/intern/colormanagement.c110
-rw-r--r--source/blender/imbuf/intern/dds/DirectDrawSurface.cpp13
-rw-r--r--source/blender/imbuf/intern/dds/dds_api.cpp4
-rw-r--r--source/blender/imbuf/intern/filetype.c12
-rw-r--r--source/blender/imbuf/intern/filter.c6
-rw-r--r--source/blender/imbuf/intern/indexer.c8
-rw-r--r--source/blender/imbuf/intern/iris.c409
-rw-r--r--source/blender/imbuf/intern/jp2.c4
-rw-r--r--source/blender/imbuf/intern/jpeg.c6
-rw-r--r--source/blender/imbuf/intern/metadata.c90
-rw-r--r--source/blender/imbuf/intern/moviecache.c4
-rw-r--r--source/blender/imbuf/intern/oiio/openimageio_api.cpp4
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_api.cpp581
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_multi.h15
-rw-r--r--source/blender/imbuf/intern/openexr/openexr_stub.cpp20
-rw-r--r--source/blender/imbuf/intern/png.c62
-rw-r--r--source/blender/imbuf/intern/radiance_hdr.c42
-rw-r--r--source/blender/imbuf/intern/rectop.c49
-rw-r--r--source/blender/imbuf/intern/scaling.c40
-rw-r--r--source/blender/imbuf/intern/thumbs.c35
-rw-r--r--source/blender/imbuf/intern/thumbs_blend.c1
-rw-r--r--source/blender/imbuf/intern/tiff.c69
-rw-r--r--source/blender/imbuf/intern/util.c42
-rw-r--r--source/blender/imbuf/intern/writeimage.c19
-rw-r--r--source/blender/makesdna/DNA_ID.h33
-rw-r--r--source/blender/makesdna/DNA_action_types.h16
-rw-r--r--source/blender/makesdna/DNA_anim_types.h17
-rw-r--r--source/blender/makesdna/DNA_armature_types.h2
-rw-r--r--source/blender/makesdna/DNA_boid_types.h12
-rw-r--r--source/blender/makesdna/DNA_brush_types.h73
-rw-r--r--source/blender/makesdna/DNA_cachefile_types.h7
-rw-r--r--source/blender/makesdna/DNA_color_types.h4
-rw-r--r--source/blender/makesdna/DNA_constraint_types.h19
-rw-r--r--source/blender/makesdna/DNA_curve_types.h23
-rw-r--r--source/blender/makesdna/DNA_gpencil_types.h8
-rw-r--r--source/blender/makesdna/DNA_meshdata_types.h10
-rw-r--r--source/blender/makesdna/DNA_meta_types.h1
-rw-r--r--source/blender/makesdna/DNA_modifier_types.h92
-rw-r--r--source/blender/makesdna/DNA_node_types.h28
-rw-r--r--source/blender/makesdna/DNA_object_enums.h49
-rw-r--r--source/blender/makesdna/DNA_object_fluidsim_types.h (renamed from source/blender/makesdna/DNA_object_fluidsim.h)10
-rw-r--r--source/blender/makesdna/DNA_object_force_types.h (renamed from source/blender/makesdna/DNA_object_force.h)15
-rw-r--r--source/blender/makesdna/DNA_object_types.h37
-rw-r--r--source/blender/makesdna/DNA_packedFile_types.h2
-rw-r--r--source/blender/makesdna/DNA_particle_types.h16
-rw-r--r--source/blender/makesdna/DNA_scene_types.h387
-rw-r--r--source/blender/makesdna/DNA_screen_types.h13
-rw-r--r--source/blender/makesdna/DNA_sequence_types.h32
-rw-r--r--source/blender/makesdna/DNA_smoke_types.h5
-rw-r--r--source/blender/makesdna/DNA_space_types.h13
-rw-r--r--source/blender/makesdna/DNA_text_types.h5
-rw-r--r--source/blender/makesdna/DNA_texture_types.h2
-rw-r--r--source/blender/makesdna/DNA_userdef_types.h168
-rw-r--r--source/blender/makesdna/DNA_view2d_types.h91
-rw-r--r--source/blender/makesdna/DNA_view3d_types.h3
-rw-r--r--source/blender/makesdna/DNA_windowmanager_types.h18
-rw-r--r--source/blender/makesdna/intern/CMakeLists.txt1
-rw-r--r--source/blender/makesdna/intern/dna_genfile.c6
-rw-r--r--source/blender/makesdna/intern/makesdna.c27
-rw-r--r--source/blender/makesrna/RNA_access.h65
-rw-r--r--source/blender/makesrna/RNA_define.h14
-rw-r--r--source/blender/makesrna/RNA_enum_types.h261
-rw-r--r--source/blender/makesrna/RNA_types.h44
-rw-r--r--source/blender/makesrna/intern/CMakeLists.txt13
-rw-r--r--source/blender/makesrna/intern/makesrna.c46
-rw-r--r--source/blender/makesrna/intern/rna_ID.c141
-rw-r--r--source/blender/makesrna/intern/rna_access.c441
-rw-r--r--source/blender/makesrna/intern/rna_action.c3
-rw-r--r--source/blender/makesrna/intern/rna_actuator.c56
-rw-r--r--source/blender/makesrna/intern/rna_animation.c23
-rw-r--r--source/blender/makesrna/intern/rna_animviz.c9
-rw-r--r--source/blender/makesrna/intern/rna_armature.c44
-rw-r--r--source/blender/makesrna/intern/rna_armature_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_boid.c4
-rw-r--r--source/blender/makesrna/intern/rna_brush.c100
-rw-r--r--source/blender/makesrna/intern/rna_cachefile.c13
-rw-r--r--source/blender/makesrna/intern/rna_camera.c27
-rw-r--r--source/blender/makesrna/intern/rna_cloth.c2
-rw-r--r--source/blender/makesrna/intern/rna_color.c43
-rw-r--r--source/blender/makesrna/intern/rna_constraint.c54
-rw-r--r--source/blender/makesrna/intern/rna_context.c2
-rw-r--r--source/blender/makesrna/intern/rna_controller.c4
-rw-r--r--source/blender/makesrna/intern/rna_curve.c20
-rw-r--r--source/blender/makesrna/intern/rna_curve_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_define.c216
-rw-r--r--source/blender/makesrna/intern/rna_depsgraph.c67
-rw-r--r--source/blender/makesrna/intern/rna_dynamicpaint.c30
-rw-r--r--source/blender/makesrna/intern/rna_fcurve.c83
-rw-r--r--source/blender/makesrna/intern/rna_fluidsim.c20
-rw-r--r--source/blender/makesrna/intern/rna_gpencil.c14
-rw-r--r--source/blender/makesrna/intern/rna_image.c15
-rw-r--r--source/blender/makesrna/intern/rna_image_api.c4
-rw-r--r--source/blender/makesrna/intern/rna_internal.h4
-rw-r--r--source/blender/makesrna/intern/rna_internal_types.h18
-rw-r--r--source/blender/makesrna/intern/rna_key.c4
-rw-r--r--source/blender/makesrna/intern/rna_lamp.c26
-rw-r--r--source/blender/makesrna/intern/rna_linestyle.c45
-rw-r--r--source/blender/makesrna/intern/rna_main_api.c129
-rw-r--r--source/blender/makesrna/intern/rna_mask.c16
-rw-r--r--source/blender/makesrna/intern/rna_material.c51
-rw-r--r--source/blender/makesrna/intern/rna_mesh.c95
-rw-r--r--source/blender/makesrna/intern/rna_mesh_utils.h2
-rw-r--r--source/blender/makesrna/intern/rna_meta.c2
-rw-r--r--source/blender/makesrna/intern/rna_meta_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_modifier.c357
-rw-r--r--source/blender/makesrna/intern/rna_movieclip.c32
-rw-r--r--source/blender/makesrna/intern/rna_nla.c17
-rw-r--r--source/blender/makesrna/intern/rna_nodetree.c454
-rw-r--r--source/blender/makesrna/intern/rna_object.c78
-rw-r--r--source/blender/makesrna/intern/rna_object_api.c79
-rw-r--r--source/blender/makesrna/intern/rna_object_force.c128
-rw-r--r--source/blender/makesrna/intern/rna_packedfile.c2
-rw-r--r--source/blender/makesrna/intern/rna_particle.c183
-rw-r--r--source/blender/makesrna/intern/rna_pose.c22
-rw-r--r--source/blender/makesrna/intern/rna_property.c2
-rw-r--r--source/blender/makesrna/intern/rna_render.c154
-rw-r--r--source/blender/makesrna/intern/rna_rigidbody.c33
-rw-r--r--source/blender/makesrna/intern/rna_rna.c124
-rw-r--r--source/blender/makesrna/intern/rna_scene.c596
-rw-r--r--source/blender/makesrna/intern/rna_scene_api.c106
-rw-r--r--source/blender/makesrna/intern/rna_screen.c4
-rw-r--r--source/blender/makesrna/intern/rna_sculpt_paint.c77
-rw-r--r--source/blender/makesrna/intern/rna_sensor.c20
-rw-r--r--source/blender/makesrna/intern/rna_sequencer.c211
-rw-r--r--source/blender/makesrna/intern/rna_sequencer_api.c3
-rw-r--r--source/blender/makesrna/intern/rna_smoke.c100
-rw-r--r--source/blender/makesrna/intern/rna_space.c509
-rw-r--r--source/blender/makesrna/intern/rna_space_api.c2
-rw-r--r--source/blender/makesrna/intern/rna_text_api.c4
-rw-r--r--source/blender/makesrna/intern/rna_texture.c80
-rw-r--r--source/blender/makesrna/intern/rna_tracking.c165
-rw-r--r--source/blender/makesrna/intern/rna_ui.c72
-rw-r--r--source/blender/makesrna/intern/rna_ui_api.c105
-rw-r--r--source/blender/makesrna/intern/rna_userdef.c240
-rw-r--r--source/blender/makesrna/intern/rna_wm.c399
-rw-r--r--source/blender/makesrna/intern/rna_wm_api.c28
-rw-r--r--source/blender/makesrna/intern/rna_world.c12
-rw-r--r--source/blender/modifiers/CMakeLists.txt12
-rw-r--r--source/blender/modifiers/MOD_modifiertypes.h1
-rw-r--r--source/blender/modifiers/intern/MOD_armature.c28
-rw-r--r--source/blender/modifiers/intern/MOD_array.c140
-rw-r--r--source/blender/modifiers/intern/MOD_bevel.c14
-rw-r--r--source/blender/modifiers/intern/MOD_boolean.c164
-rw-r--r--source/blender/modifiers/intern/MOD_boolean_util.c787
-rw-r--r--source/blender/modifiers/intern/MOD_build.c22
-rw-r--r--source/blender/modifiers/intern/MOD_cast.c20
-rw-r--r--source/blender/modifiers/intern/MOD_cloth.c23
-rw-r--r--source/blender/modifiers/intern/MOD_collision.c7
-rw-r--r--source/blender/modifiers/intern/MOD_correctivesmooth.c20
-rw-r--r--source/blender/modifiers/intern/MOD_curve.c25
-rw-r--r--source/blender/modifiers/intern/MOD_datatransfer.c17
-rw-r--r--source/blender/modifiers/intern/MOD_decimate.c2
-rw-r--r--source/blender/modifiers/intern/MOD_displace.c56
-rw-r--r--source/blender/modifiers/intern/MOD_dynamicpaint.c40
-rw-r--r--source/blender/modifiers/intern/MOD_edgesplit.c1
-rw-r--r--source/blender/modifiers/intern/MOD_explode.c12
-rw-r--r--source/blender/modifiers/intern/MOD_fluidsim.c42
-rw-r--r--source/blender/modifiers/intern/MOD_fluidsim_util.c41
-rw-r--r--source/blender/modifiers/intern/MOD_hook.c24
-rw-r--r--source/blender/modifiers/intern/MOD_laplaciandeform.c32
-rw-r--r--source/blender/modifiers/intern/MOD_laplaciansmooth.c16
-rw-r--r--source/blender/modifiers/intern/MOD_lattice.c22
-rw-r--r--source/blender/modifiers/intern/MOD_mask.c24
-rw-r--r--source/blender/modifiers/intern/MOD_meshcache.c6
-rw-r--r--source/blender/modifiers/intern/MOD_meshcache_mdd.c5
-rw-r--r--source/blender/modifiers/intern/MOD_meshcache_pc2.c6
-rw-r--r--source/blender/modifiers/intern/MOD_meshcache_util.c2
-rw-r--r--source/blender/modifiers/intern/MOD_meshdeform.c45
-rw-r--r--source/blender/modifiers/intern/MOD_meshsequencecache.c56
-rw-r--r--source/blender/modifiers/intern/MOD_mirror.c36
-rw-r--r--source/blender/modifiers/intern/MOD_multires.c2
-rw-r--r--source/blender/modifiers/intern/MOD_normal_edit.c29
-rw-r--r--source/blender/modifiers/intern/MOD_ocean.c56
-rw-r--r--source/blender/modifiers/intern/MOD_particleinstance.c239
-rw-r--r--source/blender/modifiers/intern/MOD_screw.c85
-rw-r--r--source/blender/modifiers/intern/MOD_shrinkwrap.c24
-rw-r--r--source/blender/modifiers/intern/MOD_simpledeform.c185
-rw-r--r--source/blender/modifiers/intern/MOD_skin.c20
-rw-r--r--source/blender/modifiers/intern/MOD_smoke.c33
-rw-r--r--source/blender/modifiers/intern/MOD_smooth.c4
-rw-r--r--source/blender/modifiers/intern/MOD_softbody.c29
-rw-r--r--source/blender/modifiers/intern/MOD_solidify.c28
-rw-r--r--source/blender/modifiers/intern/MOD_surface.c5
-rw-r--r--source/blender/modifiers/intern/MOD_surfacedeform.c1241
-rw-r--r--source/blender/modifiers/intern/MOD_triangulate.c2
-rw-r--r--source/blender/modifiers/intern/MOD_util.c3
-rw-r--r--source/blender/modifiers/intern/MOD_uvproject.c26
-rw-r--r--source/blender/modifiers/intern/MOD_uvwarp.c35
-rw-r--r--source/blender/modifiers/intern/MOD_warp.c35
-rw-r--r--source/blender/modifiers/intern/MOD_wave.c42
-rw-r--r--source/blender/modifiers/intern/MOD_weightvg_util.c4
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgedit.c40
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgmix.c62
-rw-r--r--source/blender/modifiers/intern/MOD_weightvgproximity.c95
-rw-r--r--source/blender/modifiers/intern/MOD_wireframe.c7
-rw-r--r--source/blender/nodes/CMakeLists.txt9
-rw-r--r--source/blender/nodes/NOD_composite.h4
-rw-r--r--source/blender/nodes/NOD_shader.h5
-rw-r--r--source/blender/nodes/NOD_static_types.h7
-rw-r--r--source/blender/nodes/composite/node_composite_tree.c35
-rw-r--r--source/blender/nodes/composite/node_composite_util.h1
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_bilateralblur.c1
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_brightness.c5
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_directionalblur.c1
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_hueSatVal.c4
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_image.c545
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_switchview.c1
-rw-r--r--source/blender/nodes/composite/nodes/node_composite_valToRgb.c2
-rw-r--r--source/blender/nodes/intern/node_exec.c3
-rw-r--r--source/blender/nodes/intern/node_socket.c24
-rw-r--r--source/blender/nodes/intern/node_util.c11
-rw-r--r--source/blender/nodes/intern/node_util.h1
-rw-r--r--source/blender/nodes/shader/node_shader_tree.c23
-rw-r--r--source/blender/nodes/shader/node_shader_util.c52
-rw-r--r--source/blender/nodes/shader/node_shader_util.h1
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bevel.c70
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bsdf_principled.c115
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_bump.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_displacement.c84
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_fresnel.c22
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_hair_info.c1
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_layer_weight.c19
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_normal_map.c40
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_object_info.c12
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_output_material.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_particle_info.c3
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_brick.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_environment.c1
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_image.c1
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_tex_pointdensity.c3
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_valToRgb.c6
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_vectTransform.c2
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_vector_displacement.c82
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_volume_principled.c85
-rw-r--r--source/blender/nodes/shader/nodes/node_shader_volume_scatter.c2
-rw-r--r--source/blender/nodes/texture/node_texture_tree.c4
-rw-r--r--source/blender/nodes/texture/node_texture_util.h1
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_image.c7
-rw-r--r--source/blender/nodes/texture/nodes/node_texture_valToRgb.c4
-rw-r--r--source/blender/physics/intern/BPH_mass_spring.cpp53
-rw-r--r--source/blender/physics/intern/eigen_utils.h2
-rw-r--r--source/blender/physics/intern/implicit.h10
-rw-r--r--source/blender/physics/intern/implicit_blender.c37
-rw-r--r--source/blender/physics/intern/implicit_eigen.cpp4
-rw-r--r--source/blender/python/BPY_extern.h3
-rw-r--r--source/blender/python/BPY_extern_clog.h35
-rw-r--r--source/blender/python/bmesh/bmesh_py_ops_call.c51
-rw-r--r--source/blender/python/bmesh/bmesh_py_types.c96
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_customdata.c5
-rw-r--r--source/blender/python/bmesh/bmesh_py_types_meshdata.c21
-rw-r--r--source/blender/python/bmesh/bmesh_py_utils.c6
-rw-r--r--source/blender/python/generic/bgl.c130
-rw-r--r--source/blender/python/generic/bpy_internal_import.c25
-rw-r--r--source/blender/python/generic/idprop_py_api.c442
-rw-r--r--source/blender/python/generic/py_capi_utils.c313
-rw-r--r--source/blender/python/generic/py_capi_utils.h56
-rw-r--r--source/blender/python/generic/python_utildefines.h6
-rw-r--r--source/blender/python/intern/CMakeLists.txt35
-rw-r--r--source/blender/python/intern/bpy.c29
-rw-r--r--source/blender/python/intern/bpy_app.c29
-rw-r--r--source/blender/python/intern/bpy_app_alembic.c6
-rw-r--r--source/blender/python/intern/bpy_app_build_options.c14
-rw-r--r--source/blender/python/intern/bpy_app_ffmpeg.c5
-rw-r--r--source/blender/python/intern/bpy_app_handlers.c12
-rw-r--r--source/blender/python/intern/bpy_app_ocio.c7
-rw-r--r--source/blender/python/intern/bpy_app_oiio.c7
-rw-r--r--source/blender/python/intern/bpy_app_opensubdiv.c110
-rw-r--r--source/blender/python/intern/bpy_app_opensubdiv.h32
-rw-r--r--source/blender/python/intern/bpy_app_openvdb.c7
-rw-r--r--source/blender/python/intern/bpy_app_sdl.c8
-rw-r--r--source/blender/python/intern/bpy_capi_utils.c (renamed from source/blender/python/intern/bpy_util.c)12
-rw-r--r--source/blender/python/intern/bpy_capi_utils.h (renamed from source/blender/python/intern/bpy_util.h)14
-rw-r--r--source/blender/python/intern/bpy_interface.c82
-rw-r--r--source/blender/python/intern/bpy_interface_atexit.c2
-rw-r--r--source/blender/python/intern/bpy_library_load.c16
-rw-r--r--source/blender/python/intern/bpy_library_write.c23
-rw-r--r--source/blender/python/intern/bpy_operator.c6
-rw-r--r--source/blender/python/intern/bpy_operator_wrap.c14
-rw-r--r--source/blender/python/intern/bpy_operator_wrap.h4
-rw-r--r--source/blender/python/intern/bpy_props.c660
-rw-r--r--source/blender/python/intern/bpy_props.h4
-rw-r--r--source/blender/python/intern/bpy_rna.c341
-rw-r--r--source/blender/python/intern/bpy_rna.h12
-rw-r--r--source/blender/python/intern/bpy_rna_anim.c2
-rw-r--r--source/blender/python/intern/bpy_rna_array.c16
-rw-r--r--source/blender/python/intern/bpy_rna_callback.c10
-rw-r--r--source/blender/python/intern/bpy_rna_driver.c10
-rw-r--r--source/blender/python/intern/bpy_rna_id_collection.c10
-rw-r--r--source/blender/python/intern/bpy_utils_units.c26
-rw-r--r--source/blender/python/intern/gpu.c13
-rw-r--r--source/blender/python/intern/gpu_offscreen.c36
-rw-r--r--source/blender/python/mathutils/mathutils.c39
-rw-r--r--source/blender/python/mathutils/mathutils.h15
-rw-r--r--source/blender/python/mathutils/mathutils_Color.c2
-rw-r--r--source/blender/python/mathutils/mathutils_Color.h3
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.c6
-rw-r--r--source/blender/python/mathutils/mathutils_Euler.h3
-rw-r--r--source/blender/python/mathutils/mathutils_Matrix.c104
-rw-r--r--source/blender/python/mathutils/mathutils_Matrix.h10
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.c2
-rw-r--r--source/blender/python/mathutils/mathutils_Quaternion.h4
-rw-r--r--source/blender/python/mathutils/mathutils_Vector.c890
-rw-r--r--source/blender/python/mathutils/mathutils_Vector.h4
-rw-r--r--source/blender/python/mathutils/mathutils_bvhtree.c13
-rw-r--r--source/blender/python/mathutils/mathutils_bvhtree.h2
-rw-r--r--source/blender/python/mathutils/mathutils_geometry.c28
-rw-r--r--source/blender/quicktime/apple/qtkit_export.m884
-rw-r--r--source/blender/quicktime/apple/qtkit_import.m400
-rw-r--r--source/blender/quicktime/quicktime_export.h162
-rw-r--r--source/blender/quicktime/quicktime_import.h63
-rw-r--r--source/blender/render/CMakeLists.txt16
-rw-r--r--source/blender/render/extern/include/RE_bake.h12
-rw-r--r--source/blender/render/extern/include/RE_engine.h8
-rw-r--r--source/blender/render/extern/include/RE_pipeline.h41
-rw-r--r--source/blender/render/extern/include/RE_render_ext.h6
-rw-r--r--source/blender/render/extern/include/RE_shader_ext.h6
-rw-r--r--source/blender/render/intern/include/render_result.h8
-rw-r--r--source/blender/render/intern/include/render_types.h7
-rw-r--r--source/blender/render/intern/include/rendercore.h8
-rw-r--r--source/blender/render/intern/include/shading.h2
-rw-r--r--source/blender/render/intern/raytrace/rayobject_rtbuild.cpp12
-rw-r--r--source/blender/render/intern/raytrace/rayobject_rtbuild.h7
-rw-r--r--source/blender/render/intern/source/bake.c16
-rw-r--r--source/blender/render/intern/source/bake_api.c16
-rw-r--r--source/blender/render/intern/source/convertblender.c41
-rw-r--r--source/blender/render/intern/source/envmap.c20
-rw-r--r--source/blender/render/intern/source/external_engine.c59
-rw-r--r--source/blender/render/intern/source/imagetexture.c12
-rw-r--r--source/blender/render/intern/source/initrender.c6
-rw-r--r--source/blender/render/intern/source/multires_bake.c6
-rw-r--r--source/blender/render/intern/source/occlusion.c16
-rw-r--r--source/blender/render/intern/source/pipeline.c246
-rw-r--r--source/blender/render/intern/source/pixelshading.c2
-rw-r--r--source/blender/render/intern/source/pointdensity.c27
-rw-r--r--source/blender/render/intern/source/render_result.c892
-rw-r--r--source/blender/render/intern/source/render_texture.c88
-rw-r--r--source/blender/render/intern/source/rendercore.c410
-rw-r--r--source/blender/render/intern/source/renderdatabase.c12
-rw-r--r--source/blender/render/intern/source/shadbuf.c24
-rw-r--r--source/blender/render/intern/source/shadeinput.c6
-rw-r--r--source/blender/render/intern/source/shadeoutput.c50
-rw-r--r--source/blender/render/intern/source/sss.c4
-rw-r--r--source/blender/render/intern/source/sunsky.c2
-rw-r--r--source/blender/render/intern/source/volume_precache.c10
-rw-r--r--source/blender/render/intern/source/volumetric.c6
-rw-r--r--source/blender/render/intern/source/voxeldata.c2
-rw-r--r--source/blender/render/intern/source/zbuf.c807
-rw-r--r--source/blender/windowmanager/CMakeLists.txt17
-rw-r--r--source/blender/windowmanager/WM_api.h57
-rw-r--r--source/blender/windowmanager/WM_keymap.h23
-rw-r--r--source/blender/windowmanager/WM_types.h56
-rw-r--r--source/blender/windowmanager/intern/wm.c61
-rw-r--r--source/blender/windowmanager/intern/wm_cursors.c7
-rw-r--r--source/blender/windowmanager/intern/wm_dragdrop.c8
-rw-r--r--source/blender/windowmanager/intern/wm_draw.c152
-rw-r--r--source/blender/windowmanager/intern/wm_event_system.c353
-rw-r--r--source/blender/windowmanager/intern/wm_files.c465
-rw-r--r--source/blender/windowmanager/intern/wm_files_link.c44
-rw-r--r--source/blender/windowmanager/intern/wm_gesture.c24
-rw-r--r--source/blender/windowmanager/intern/wm_gesture_ops.c883
-rw-r--r--source/blender/windowmanager/intern/wm_init_exit.c71
-rw-r--r--source/blender/windowmanager/intern/wm_jobs.c10
-rw-r--r--source/blender/windowmanager/intern/wm_keymap.c93
-rw-r--r--source/blender/windowmanager/intern/wm_operator_props.c109
-rw-r--r--source/blender/windowmanager/intern/wm_operators.c1048
-rw-r--r--source/blender/windowmanager/intern/wm_playanim.c5
-rw-r--r--source/blender/windowmanager/intern/wm_stereo.c26
-rw-r--r--source/blender/windowmanager/intern/wm_tooltip.c106
-rw-r--r--source/blender/windowmanager/intern/wm_window.c282
-rw-r--r--source/blender/windowmanager/wm.h18
-rw-r--r--source/blender/windowmanager/wm_event_system.h8
-rw-r--r--source/blender/windowmanager/wm_event_types.h2
-rw-r--r--source/blender/windowmanager/wm_files.h5
-rw-r--r--source/blender/windowmanager/wm_window.h3
1377 files changed, 85893 insertions, 53417 deletions
diff --git a/source/blender/CMakeLists.txt b/source/blender/CMakeLists.txt
index 6f2b78e0845..690e1bcf318 100644
--- a/source/blender/CMakeLists.txt
+++ b/source/blender/CMakeLists.txt
@@ -63,8 +63,9 @@ set(SRC_DNA_INC
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_modifier_types.h
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_nla_types.h
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_node_types.h
- ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_fluidsim.h
- ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_force.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_fluidsim_types.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_force_types.h
+ ${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_enums.h
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_object_types.h
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_outliner_types.h
${CMAKE_CURRENT_SOURCE_DIR}/makesdna/DNA_packedFile_types.h
@@ -138,10 +139,6 @@ if(WITH_CODEC_AVI)
add_subdirectory(avi)
endif()
-if(WITH_CODEC_QUICKTIME)
- add_subdirectory(quicktime)
-endif()
-
if(WITH_PYTHON)
add_subdirectory(python)
endif()
diff --git a/source/blender/alembic/ABC_alembic.h b/source/blender/alembic/ABC_alembic.h
index e92d5f2d9f7..70250310213 100644
--- a/source/blender/alembic/ABC_alembic.h
+++ b/source/blender/alembic/ABC_alembic.h
@@ -47,47 +47,63 @@ struct AlembicExportParams {
double frame_start;
double frame_end;
- double frame_step_xform;
- double frame_step_shape;
+ unsigned int frame_samples_xform;
+ unsigned int frame_samples_shape;
double shutter_open;
double shutter_close;
- /* bools */
- unsigned int selected_only : 1;
- unsigned int uvs : 1;
- unsigned int normals : 1;
- unsigned int vcolors : 1;
- unsigned int apply_subdiv : 1;
- unsigned int flatten_hierarchy : 1;
- unsigned int visible_layers_only : 1;
- unsigned int renderable_only : 1;
- unsigned int face_sets : 1;
- unsigned int use_subdiv_schema : 1;
- unsigned int packuv : 1;
- unsigned int triangulate : 1;
+ bool selected_only;
+ bool uvs;
+ bool normals;
+ bool vcolors;
+ bool apply_subdiv;
+ bool flatten_hierarchy;
+ bool visible_layers_only;
+ bool renderable_only;
+ bool face_sets;
+ bool use_subdiv_schema;
+ bool packuv;
+ bool triangulate;
+ bool export_hair;
+ bool export_particles;
unsigned int compression_type : 1;
+ /* See MOD_TRIANGULATE_NGON_xxx and MOD_TRIANGULATE_QUAD_xxx
+ * in DNA_modifier_types.h */
int quad_method;
int ngon_method;
+
float global_scale;
};
-void ABC_export(
+/* The ABC_export and ABC_import functions both take a as_background_job
+ * parameter, and return a boolean.
+ *
+ * When as_background_job=true, returns false immediately after scheduling
+ * a background job.
+ *
+ * When as_background_job=false, performs the export synchronously, and returns
+ * true when the export was ok, and false if there were any errors.
+ */
+
+bool ABC_export(
struct Scene *scene,
struct bContext *C,
const char *filepath,
- const struct AlembicExportParams *params);
+ const struct AlembicExportParams *params,
+ bool as_background_job);
-void ABC_import(struct bContext *C,
+bool ABC_import(struct bContext *C,
const char *filepath,
float scale,
bool is_sequence,
bool set_frame_range,
int sequence_len,
int offset,
- bool validate_meshes);
+ bool validate_meshes,
+ bool as_background_job);
AbcArchiveHandle *ABC_create_handle(const char *filename, struct ListBase *object_paths);
@@ -105,6 +121,7 @@ struct DerivedMesh *ABC_read_mesh(struct CacheReader *reader,
const char **err_str,
int flags);
+void CacheReader_incref(struct CacheReader *reader);
void CacheReader_free(struct CacheReader *reader);
struct CacheReader *CacheReader_open_alembic_object(struct AbcArchiveHandle *handle,
diff --git a/source/blender/alembic/CMakeLists.txt b/source/blender/alembic/CMakeLists.txt
index a6e0be6a7f3..fb08887c076 100644
--- a/source/blender/alembic/CMakeLists.txt
+++ b/source/blender/alembic/CMakeLists.txt
@@ -33,6 +33,7 @@ set(INC
../makesdna
../makesrna
../windowmanager
+ ../depsgraph
../../../intern/guardedalloc
../../../intern/utfconv
)
@@ -51,6 +52,7 @@ set(SRC
intern/abc_curves.cc
intern/abc_exporter.cc
intern/abc_hair.cc
+ intern/abc_mball.cc
intern/abc_mesh.cc
intern/abc_nurbs.cc
intern/abc_object.cc
@@ -66,6 +68,7 @@ set(SRC
intern/abc_curves.h
intern/abc_exporter.h
intern/abc_hair.h
+ intern/abc_mball.h
intern/abc_mesh.h
intern/abc_nurbs.h
intern/abc_object.h
diff --git a/source/blender/alembic/intern/abc_archive.cc b/source/blender/alembic/intern/abc_archive.cc
index 5f8fc1a3739..bd16196cb78 100644
--- a/source/blender/alembic/intern/abc_archive.cc
+++ b/source/blender/alembic/intern/abc_archive.cc
@@ -23,11 +23,17 @@
*/
#include "abc_archive.h"
+extern "C"
+{
+ #include "BKE_blender_version.h"
+}
#ifdef WIN32
# include "utfconv.h"
#endif
+#include <fstream>
+
using Alembic::Abc::Exception;
using Alembic::Abc::ErrorHandler;
using Alembic::Abc::IArchive;
@@ -38,8 +44,9 @@ static IArchive open_archive(const std::string &filename,
const std::vector<std::istream *> &input_streams,
bool &is_hdf5)
{
+ is_hdf5 = false;
+
try {
- is_hdf5 = false;
Alembic::AbcCoreOgawa::ReadArchive archive_reader(input_streams);
return IArchive(archive_reader(filename),
@@ -63,6 +70,27 @@ static IArchive open_archive(const std::string &filename,
return IArchive();
}
#else
+ /* Inspect the file to see whether it's really a HDF5 file. */
+ char header[4]; /* char(0x89) + "HDF" */
+ std::ifstream the_file(filename.c_str(), std::ios::in | std::ios::binary);
+ if (!the_file) {
+ std::cerr << "Unable to open " << filename << std::endl;
+ }
+ else if (!the_file.read(header, sizeof(header))) {
+ std::cerr << "Unable to read from " << filename << std::endl;
+ }
+ else if (strncmp(header + 1, "HDF", 3)) {
+ std::cerr << filename << " has an unknown file format, unable to read." << std::endl;
+ }
+ else {
+ is_hdf5 = true;
+ std::cerr << filename << " is in the obsolete HDF5 format, unable to read." << std::endl;
+ }
+
+ if (the_file.is_open()) {
+ the_file.close();
+ }
+
return IArchive();
#endif
}
@@ -83,16 +111,20 @@ ArchiveReader::ArchiveReader(const char *filename)
m_streams.push_back(&m_infile);
- bool is_hdf5;
- m_archive = open_archive(filename, m_streams, is_hdf5);
+ m_archive = open_archive(filename, m_streams, m_is_hdf5);
/* We can't open an HDF5 file from a stream, so close it. */
- if (is_hdf5) {
+ if (m_is_hdf5) {
m_infile.close();
m_streams.clear();
}
}
+bool ArchiveReader::is_hdf5() const
+{
+ return m_is_hdf5;
+}
+
bool ArchiveReader::valid() const
{
return m_archive.valid();
@@ -115,6 +147,7 @@ static OArchive create_archive(std::ostream *ostream,
{
md.set(Alembic::Abc::kApplicationNameKey, "Blender");
md.set(Alembic::Abc::kUserDescriptionKey, scene_name);
+ md.set("blender_version", versionstr);
time_t raw_time;
time(&raw_time);
diff --git a/source/blender/alembic/intern/abc_archive.h b/source/blender/alembic/intern/abc_archive.h
index d412574b736..84309fbc9df 100644
--- a/source/blender/alembic/intern/abc_archive.h
+++ b/source/blender/alembic/intern/abc_archive.h
@@ -44,12 +44,21 @@ class ArchiveReader {
Alembic::Abc::IArchive m_archive;
std::ifstream m_infile;
std::vector<std::istream *> m_streams;
+ bool m_is_hdf5;
public:
explicit ArchiveReader(const char *filename);
bool valid() const;
+ /**
+ * Returns true when either Blender is compiled with HDF5 support and
+ * the archive was succesfully opened (valid() will also return true),
+ * or when Blender was built without HDF5 support but a HDF5 file was
+ * detected (valid() will return false).
+ */
+ bool is_hdf5() const;
+
Alembic::Abc::IObject getTop();
};
diff --git a/source/blender/alembic/intern/abc_camera.cc b/source/blender/alembic/intern/abc_camera.cc
index 4f70b2a972c..16416205983 100644
--- a/source/blender/alembic/intern/abc_camera.cc
+++ b/source/blender/alembic/intern/abc_camera.cc
@@ -117,11 +117,27 @@ bool AbcCameraReader::valid() const
return m_schema.valid();
}
-void AbcCameraReader::readObjectData(Main *bmain, float time)
+bool AbcCameraReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::ICamera::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to Camera when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_CAMERA) {
+ *err_str = "Object type mismatch, Alembic object path points to Camera.";
+ return false;
+ }
+
+ return true;
+}
+
+void AbcCameraReader::readObjectData(Main *bmain, const ISampleSelector &sample_sel)
{
Camera *bcam = static_cast<Camera *>(BKE_camera_add(bmain, m_data_name.c_str()));
- ISampleSelector sample_sel(time);
CameraSample cam_sample;
m_schema.get(cam_sample, sample_sel);
diff --git a/source/blender/alembic/intern/abc_camera.h b/source/blender/alembic/intern/abc_camera.h
index fafb4d3eb39..16c5cccd5ea 100644
--- a/source/blender/alembic/intern/abc_camera.h
+++ b/source/blender/alembic/intern/abc_camera.h
@@ -54,8 +54,11 @@ public:
AbcCameraReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
- void readObjectData(Main *bmain, float time);
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
};
-#endif /* __ABC_CAMERA_H__ */ \ No newline at end of file
+#endif /* __ABC_CAMERA_H__ */
diff --git a/source/blender/alembic/intern/abc_curves.cc b/source/blender/alembic/intern/abc_curves.cc
index 0542255d84b..f73fe957fea 100644
--- a/source/blender/alembic/intern/abc_curves.cc
+++ b/source/blender/alembic/intern/abc_curves.cc
@@ -49,19 +49,26 @@ using Alembic::Abc::Int32ArraySamplePtr;
using Alembic::Abc::FloatArraySamplePtr;
using Alembic::Abc::P3fArraySamplePtr;
using Alembic::Abc::UcharArraySamplePtr;
+using Alembic::Abc::PropertyHeader;
+using Alembic::AbcGeom::ICompoundProperty;
using Alembic::AbcGeom::ICurves;
using Alembic::AbcGeom::ICurvesSchema;
using Alembic::AbcGeom::IFloatGeomParam;
+using Alembic::AbcGeom::IInt16Property;
using Alembic::AbcGeom::ISampleSelector;
using Alembic::AbcGeom::kWrapExisting;
using Alembic::AbcGeom::CurvePeriodicity;
+using Alembic::AbcGeom::OCompoundProperty;
using Alembic::AbcGeom::OCurves;
using Alembic::AbcGeom::OCurvesSchema;
+using Alembic::AbcGeom::OInt16Property;
using Alembic::AbcGeom::ON3fGeomParam;
using Alembic::AbcGeom::OV2fGeomParam;
+#define ABC_CURVE_RESOLUTION_U_PROPNAME "blender:resolution"
+
/* ************************************************************************** */
AbcCurveWriter::AbcCurveWriter(Scene *scene,
@@ -73,6 +80,11 @@ AbcCurveWriter::AbcCurveWriter(Scene *scene,
{
OCurves curves(parent->alembicXform(), m_name, m_time_sampling);
m_schema = curves.getSchema();
+
+ Curve *cu = static_cast<Curve *>(m_object->data);
+ OCompoundProperty user_props = m_schema.getUserProperties();
+ OInt16Property user_prop_resolu(user_props, ABC_CURVE_RESOLUTION_U_PROPNAME);
+ user_prop_resolu.set(cu->resolu);
}
void AbcCurveWriter::do_write()
@@ -95,7 +107,7 @@ void AbcCurveWriter::do_write()
for (; nurbs; nurbs = nurbs->next) {
if (nurbs->bp) {
curve_basis = Alembic::AbcGeom::kNoBasis;
- curve_type = Alembic::AbcGeom::kLinear;
+ curve_type = Alembic::AbcGeom::kVariableOrder;
const int totpoint = nurbs->pntsu * nurbs->pntsv;
@@ -160,7 +172,7 @@ void AbcCurveWriter::do_write()
}
}
- orders.push_back(nurbs->orderu + 1);
+ orders.push_back(nurbs->orderu);
vert_counts.push_back(verts.size());
}
@@ -199,17 +211,44 @@ bool AbcCurveReader::valid() const
return m_curves_schema.valid();
}
-void AbcCurveReader::readObjectData(Main *bmain, float time)
+bool AbcCurveReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::ICurves::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to Curves when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_CURVE) {
+ *err_str = "Object type mismatch, Alembic object path points to Curves.";
+ return false;
+ }
+
+ return true;
+}
+
+void AbcCurveReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
{
Curve *cu = BKE_curve_add(bmain, m_data_name.c_str(), OB_CURVE);
cu->flag |= CU_DEFORM_FILL | CU_3D;
cu->actvert = CU_ACT_NONE;
+ cu->resolu = 1;
+
+ ICompoundProperty user_props = m_curves_schema.getUserProperties();
+ if (user_props) {
+ const PropertyHeader *header = user_props.getPropertyHeader(ABC_CURVE_RESOLUTION_U_PROPNAME);
+ if (header != NULL && header->isScalar() && IInt16Property::matches(*header)) {
+ IInt16Property resolu(user_props, header->getName());
+ cu->resolu = resolu.getValue(sample_sel);
+ }
+ }
m_object = BKE_object_add_only_object(bmain, OB_CURVE, m_object_name.c_str());
m_object->data = cu;
- read_curve_sample(cu, m_curves_schema, time);
+ read_curve_sample(cu, m_curves_schema, sample_sel);
if (has_animations(m_curves_schema, m_settings)) {
addCacheModifier();
@@ -218,9 +257,8 @@ void AbcCurveReader::readObjectData(Main *bmain, float time)
/* ************************************************************************** */
-void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const float time)
+void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const ISampleSelector &sample_sel)
{
- const ISampleSelector sample_sel(time);
ICurvesSchema::Sample smp = schema.getValue(sample_sel);
const Int32ArraySamplePtr num_vertices = smp.getCurvesNumVertices();
const P3fArraySamplePtr positions = smp.getPositions();
@@ -250,13 +288,19 @@ void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const float time)
nu->pntsv = 1;
nu->flag |= CU_SMOOTH;
- nu->orderu = num_verts;
-
- if (smp.getType() == Alembic::AbcGeom::kCubic) {
- nu->orderu = 3;
- }
- else if (orders && orders->size() > i) {
- nu->orderu = static_cast<short>((*orders)[i] - 1);
+ switch (smp.getType()) {
+ case Alembic::AbcGeom::kCubic:
+ nu->orderu = 4;
+ break;
+ case Alembic::AbcGeom::kVariableOrder:
+ if (orders && orders->size() > i) {
+ nu->orderu = static_cast<short>((*orders)[i]);
+ break;
+ }
+ ATTR_FALLTHROUGH;
+ case Alembic::AbcGeom::kLinear:
+ default:
+ nu->orderu = 2;
}
if (periodicity == Alembic::AbcGeom::kNonPeriodic) {
@@ -361,9 +405,11 @@ void read_curve_sample(Curve *cu, const ICurvesSchema &schema, const float time)
* object directly and create a new DerivedMesh from that. Also we might need to
* create new or delete existing NURBS in the curve.
*/
-DerivedMesh *AbcCurveReader::read_derivedmesh(DerivedMesh * /*dm*/, const float time, int /*read_flag*/, const char ** /*err_str*/)
+DerivedMesh *AbcCurveReader::read_derivedmesh(DerivedMesh * /*dm*/,
+ const ISampleSelector &sample_sel,
+ int /*read_flag*/,
+ const char ** /*err_str*/)
{
- ISampleSelector sample_sel(time);
const ICurvesSchema::Sample sample = m_curves_schema.getValue(sample_sel);
const P3fArraySamplePtr &positions = sample.getPositions();
@@ -377,7 +423,7 @@ DerivedMesh *AbcCurveReader::read_derivedmesh(DerivedMesh * /*dm*/, const float
if (curve_count != num_vertices->size()) {
BKE_nurbList_free(&curve->nurb);
- read_curve_sample(curve, m_curves_schema, time);
+ read_curve_sample(curve, m_curves_schema, sample_sel);
}
else {
Nurb *nurbs = static_cast<Nurb *>(curve->nurb.first);
diff --git a/source/blender/alembic/intern/abc_curves.h b/source/blender/alembic/intern/abc_curves.h
index 2757d179a47..a9231f947b2 100644
--- a/source/blender/alembic/intern/abc_curves.h
+++ b/source/blender/alembic/intern/abc_curves.h
@@ -54,13 +54,21 @@ public:
AbcCurveReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
- void readObjectData(Main *bmain, float time);
- DerivedMesh *read_derivedmesh(DerivedMesh *, const float time, int read_flag, const char **err_str);
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
+ DerivedMesh *read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str);
};
/* ************************************************************************** */
-void read_curve_sample(Curve *cu, const Alembic::AbcGeom::ICurvesSchema &schema, const float time);
+void read_curve_sample(Curve *cu,
+ const Alembic::AbcGeom::ICurvesSchema &schema,
+ const Alembic::Abc::ISampleSelector &sample_selector);
#endif /* __ABC_CURVES_H__ */
diff --git a/source/blender/alembic/intern/abc_customdata.cc b/source/blender/alembic/intern/abc_customdata.cc
index ebf1b2ba96e..b3b015c7abf 100644
--- a/source/blender/alembic/intern/abc_customdata.cc
+++ b/source/blender/alembic/intern/abc_customdata.cc
@@ -227,48 +227,6 @@ using Alembic::AbcGeom::IC3fGeomParam;
using Alembic::AbcGeom::IC4fGeomParam;
using Alembic::AbcGeom::IV2fGeomParam;
-static void read_mcols(const CDStreamConfig &config, void *data,
- const C3fArraySamplePtr &c3f_ptr, const C4fArraySamplePtr &c4f_ptr)
-{
- MCol *cfaces = static_cast<MCol *>(data);
- MPoly *polys = config.mpoly;
- MLoop *mloops = config.mloop;
-
- if (c3f_ptr) {
- for (int i = 0; i < config.totpoly; ++i) {
- MPoly *p = &polys[i];
- MCol *cface = &cfaces[p->loopstart + p->totloop];
- MLoop *mloop = &mloops[p->loopstart + p->totloop];
-
- for (int j = 0; j < p->totloop; ++j) {
- cface--;
- mloop--;
- const Imath::C3f &color = (*c3f_ptr)[mloop->v];
- cface->a = FTOCHAR(color[0]);
- cface->r = FTOCHAR(color[1]);
- cface->g = FTOCHAR(color[2]);
- cface->b = 255;
- }
- }
- }
- else if (c4f_ptr) {
- for (int i = 0; i < config.totpoly; ++i) {
- MPoly *p = &polys[i];
- MCol *cface = &cfaces[p->loopstart + p->totloop];
- MLoop *mloop = &mloops[p->loopstart + p->totloop];
-
- for (int j = 0; j < p->totloop; ++j) {
- cface--;
- mloop--;
- const Imath::C4f &color = (*c4f_ptr)[mloop->v];
- cface->a = FTOCHAR(color[0]);
- cface->r = FTOCHAR(color[1]);
- cface->g = FTOCHAR(color[2]);
- cface->b = FTOCHAR(color[3]);
- }
- }
- }
-}
static void read_uvs(const CDStreamConfig &config, void *data,
const Alembic::AbcGeom::V2fArraySamplePtr &uvs,
@@ -277,72 +235,183 @@ static void read_uvs(const CDStreamConfig &config, void *data,
MPoly *mpolys = config.mpoly;
MLoopUV *mloopuvs = static_cast<MLoopUV *>(data);
- unsigned int uv_index, loop_index;
+ unsigned int uv_index, loop_index, rev_loop_index;
for (int i = 0; i < config.totpoly; ++i) {
MPoly &poly = mpolys[i];
+ unsigned int rev_loop_offset = poly.loopstart + poly.totloop - 1;
for (int f = 0; f < poly.totloop; ++f) {
loop_index = poly.loopstart + f;
+ rev_loop_index = rev_loop_offset - f;
uv_index = (*indices)[loop_index];
const Imath::V2f &uv = (*uvs)[uv_index];
- MLoopUV &loopuv = mloopuvs[loop_index];
+ MLoopUV &loopuv = mloopuvs[rev_loop_index];
loopuv.uv[0] = uv[0];
loopuv.uv[1] = uv[1];
}
}
}
-static void read_custom_data_ex(const ICompoundProperty &prop,
- const PropertyHeader &prop_header,
- const CDStreamConfig &config,
- const Alembic::Abc::ISampleSelector &iss,
- int data_type)
+static size_t mcols_out_of_bounds_check(
+ const size_t color_index,
+ const size_t array_size,
+ const std::string & iobject_full_name,
+ const PropertyHeader &prop_header,
+ bool &r_bounds_warning_given)
{
- if (data_type == CD_MLOOPCOL) {
- C3fArraySamplePtr c3f_ptr = C3fArraySamplePtr();
- C4fArraySamplePtr c4f_ptr = C4fArraySamplePtr();
+ if (color_index < array_size) {
+ return color_index;
+ }
- if (IC3fGeomParam::matches(prop_header)) {
- IC3fGeomParam color_param(prop, prop_header.getName());
- IC3fGeomParam::Sample sample;
- color_param.getIndexed(sample, iss);
+ if (!r_bounds_warning_given) {
+ std::cerr << "Alembic: color index out of bounds "
+ "reading face colors for object "
+ << iobject_full_name
+ << ", property "
+ << prop_header.getName() << std::endl;
+ r_bounds_warning_given = true;
+ }
- c3f_ptr = sample.getVals();
- }
- else if (IC4fGeomParam::matches(prop_header)) {
- IC4fGeomParam color_param(prop, prop_header.getName());
- IC4fGeomParam::Sample sample;
- color_param.getIndexed(sample, iss);
+ return 0;
+}
- c4f_ptr = sample.getVals();
- }
+static void read_custom_data_mcols(const std::string & iobject_full_name,
+ const ICompoundProperty &arbGeomParams,
+ const PropertyHeader &prop_header,
+ const CDStreamConfig &config,
+ const Alembic::Abc::ISampleSelector &iss)
+{
+ C3fArraySamplePtr c3f_ptr = C3fArraySamplePtr();
+ C4fArraySamplePtr c4f_ptr = C4fArraySamplePtr();
+ Alembic::Abc::UInt32ArraySamplePtr indices;
+ bool use_c3f_ptr;
+ bool is_facevarying;
+
+ /* Find the correct interpretation of the data */
+ if (IC3fGeomParam::matches(prop_header)) {
+ IC3fGeomParam color_param(arbGeomParams, prop_header.getName());
+ IC3fGeomParam::Sample sample;
+ BLI_assert(!strcmp("rgb", color_param.getInterpretation()));
+
+ color_param.getIndexed(sample, iss);
+ is_facevarying = sample.getScope() == kFacevaryingScope &&
+ config.totloop == sample.getIndices()->size();
+
+ c3f_ptr = sample.getVals();
+ indices = sample.getIndices();
+ use_c3f_ptr = true;
+ }
+ else if (IC4fGeomParam::matches(prop_header)) {
+ IC4fGeomParam color_param(arbGeomParams, prop_header.getName());
+ IC4fGeomParam::Sample sample;
+ BLI_assert(!strcmp("rgba", color_param.getInterpretation()));
+
+ color_param.getIndexed(sample, iss);
+ is_facevarying = sample.getScope() == kFacevaryingScope &&
+ config.totloop == sample.getIndices()->size();
+
+ c4f_ptr = sample.getVals();
+ indices = sample.getIndices();
+ use_c3f_ptr = false;
+ }
+ else {
+ /* this won't happen due to the checks in read_custom_data() */
+ return;
+ }
+ BLI_assert(c3f_ptr || c4f_ptr);
+
+ /* Read the vertex colors */
+ void *cd_data = config.add_customdata_cb(config.user_data,
+ prop_header.getName().c_str(),
+ CD_MLOOPCOL);
+ MCol *cfaces = static_cast<MCol *>(cd_data);
+ MPoly *mpolys = config.mpoly;
+ MLoop *mloops = config.mloop;
- void *cd_data = config.add_customdata_cb(config.user_data,
- prop_header.getName().c_str(),
- data_type);
+ size_t face_index = 0;
+ size_t color_index;
+ bool bounds_warning_given = false;
- read_mcols(config, cd_data, c3f_ptr, c4f_ptr);
- }
- else if (data_type == CD_MLOOPUV) {
- IV2fGeomParam uv_param(prop, prop_header.getName());
- IV2fGeomParam::Sample sample;
- uv_param.getIndexed(sample, iss);
+ /* The colors can go through two layers of indexing. Often the 'indices'
+ * array doesn't do anything (i.e. indices[n] = n), but when it does, it's
+ * important. Blender 2.79 writes indices incorrectly (see T53745), which
+ * is why we have to check for indices->size() > 0 */
+ bool use_dual_indexing = is_facevarying && indices->size() > 0;
+
+ for (int i = 0; i < config.totpoly; ++i) {
+ MPoly *poly = &mpolys[i];
+ MCol *cface = &cfaces[poly->loopstart + poly->totloop];
+ MLoop *mloop = &mloops[poly->loopstart + poly->totloop];
- if (uv_param.getScope() != kFacevaryingScope) {
- return;
+ for (int j = 0; j < poly->totloop; ++j, ++face_index) {
+ --cface;
+ --mloop;
+
+ color_index = is_facevarying ? face_index : mloop->v;
+ if (use_dual_indexing) {
+ color_index = (*indices)[color_index];
+ }
+ if (use_c3f_ptr) {
+ color_index = mcols_out_of_bounds_check(
+ color_index,
+ c3f_ptr->size(),
+ iobject_full_name, prop_header,
+ bounds_warning_given);
+
+ const Imath::C3f &color = (*c3f_ptr)[color_index];
+ cface->a = FTOCHAR(color[0]);
+ cface->r = FTOCHAR(color[1]);
+ cface->g = FTOCHAR(color[2]);
+ cface->b = 255;
+ }
+ else {
+ color_index = mcols_out_of_bounds_check(
+ color_index,
+ c4f_ptr->size(),
+ iobject_full_name, prop_header,
+ bounds_warning_given);
+
+ const Imath::C4f &color = (*c4f_ptr)[color_index];
+ cface->a = FTOCHAR(color[0]);
+ cface->r = FTOCHAR(color[1]);
+ cface->g = FTOCHAR(color[2]);
+ cface->b = FTOCHAR(color[3]);
+ }
}
+ }
+}
- void *cd_data = config.add_customdata_cb(config.user_data,
- prop_header.getName().c_str(),
- data_type);
+static void read_custom_data_uvs(const ICompoundProperty &prop,
+ const PropertyHeader &prop_header,
+ const CDStreamConfig &config,
+ const Alembic::Abc::ISampleSelector &iss)
+{
+ IV2fGeomParam uv_param(prop, prop_header.getName());
- read_uvs(config, cd_data, sample.getVals(), sample.getIndices());
+ if (!uv_param.isIndexed()) {
+ return;
}
+
+ IV2fGeomParam::Sample sample;
+ uv_param.getIndexed(sample, iss);
+
+ if (uv_param.getScope() != kFacevaryingScope) {
+ return;
+ }
+
+ void *cd_data = config.add_customdata_cb(config.user_data,
+ prop_header.getName().c_str(),
+ CD_MLOOPUV);
+
+ read_uvs(config, cd_data, sample.getVals(), sample.getIndices());
}
-void read_custom_data(const ICompoundProperty &prop, const CDStreamConfig &config, const Alembic::Abc::ISampleSelector &iss)
+void read_custom_data(const std::string & iobject_full_name,
+ const ICompoundProperty &prop,
+ const CDStreamConfig &config,
+ const Alembic::Abc::ISampleSelector &iss)
{
if (!prop.valid()) {
return;
@@ -362,7 +431,7 @@ void read_custom_data(const ICompoundProperty &prop, const CDStreamConfig &confi
continue;
}
- read_custom_data_ex(prop, prop_header, config, iss, CD_MLOOPUV);
+ read_custom_data_uvs(prop, prop_header, config, iss);
continue;
}
@@ -372,7 +441,7 @@ void read_custom_data(const ICompoundProperty &prop, const CDStreamConfig &confi
continue;
}
- read_custom_data_ex(prop, prop_header, config, iss, CD_MLOOPCOL);
+ read_custom_data_mcols(iobject_full_name, prop, prop_header, config, iss);
continue;
}
}
diff --git a/source/blender/alembic/intern/abc_customdata.h b/source/blender/alembic/intern/abc_customdata.h
index 9e671fde386..b3072a2c9f7 100644
--- a/source/blender/alembic/intern/abc_customdata.h
+++ b/source/blender/alembic/intern/abc_customdata.h
@@ -96,7 +96,8 @@ void write_custom_data(const OCompoundProperty &prop,
CustomData *data,
int data_type);
-void read_custom_data(const ICompoundProperty &prop,
+void read_custom_data(const std::string & iobject_full_name,
+ const ICompoundProperty &prop,
const CDStreamConfig &config,
const Alembic::Abc::ISampleSelector &iss);
diff --git a/source/blender/alembic/intern/abc_exporter.cc b/source/blender/alembic/intern/abc_exporter.cc
index 90a99469389..946b89213e6 100644
--- a/source/blender/alembic/intern/abc_exporter.cc
+++ b/source/blender/alembic/intern/abc_exporter.cc
@@ -28,6 +28,7 @@
#include "abc_camera.h"
#include "abc_curves.h"
#include "abc_hair.h"
+#include "abc_mball.h"
#include "abc_mesh.h"
#include "abc_nurbs.h"
#include "abc_points.h"
@@ -37,6 +38,7 @@
extern "C" {
#include "DNA_camera_types.h"
#include "DNA_curve_types.h"
+#include "DNA_meta_types.h"
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
@@ -54,6 +56,7 @@ extern "C" {
#include "BKE_global.h"
#include "BKE_idprop.h"
#include "BKE_main.h"
+#include "BKE_mball.h"
#include "BKE_modifier.h"
#include "BKE_particle.h"
#include "BKE_scene.h"
@@ -66,13 +69,14 @@ using Alembic::Abc::OBox3dProperty;
ExportSettings::ExportSettings()
: scene(NULL)
+ , logger()
, selected_only(false)
, visible_layers_only(false)
, renderable_only(false)
, frame_start(1)
, frame_end(1)
- , frame_step_xform(1)
- , frame_step_shape(1)
+ , frame_samples_xform(1)
+ , frame_samples_shape(1)
, shutter_open(0.0)
, shutter_close(1.0)
, global_scale(1.0f)
@@ -82,6 +86,8 @@ ExportSettings::ExportSettings()
, export_vcols(false)
, export_face_sets(false)
, export_vweigths(false)
+ , export_hair(true)
+ , export_particles(true)
, apply_subdiv(false)
, use_subdiv_schema(false)
, export_child_hairs(true)
@@ -105,7 +111,7 @@ static bool object_is_smoke_sim(Object *ob)
return false;
}
-static bool object_is_shape(Object *ob)
+static bool object_type_is_exportable(Scene *scene, Object *ob)
{
switch (ob->type) {
case OB_MESH:
@@ -114,23 +120,43 @@ static bool object_is_shape(Object *ob)
}
return true;
+ case OB_EMPTY:
case OB_CURVE:
case OB_SURF:
case OB_CAMERA:
return true;
+ case OB_MBALL:
+ return AbcMBallWriter::isBasisBall(scene, ob);
default:
return false;
}
}
-static bool export_object(const ExportSettings * const settings, Object *ob)
+
+/**
+ * Returns whether this object should be exported into the Alembic file.
+ *
+ * \param settings: export settings, used for options like 'selected only'.
+ * \param ob: the object in question.
+ * \param is_duplicated: Normally false; true when the object is instanced
+ * into the scene by a dupli-object (e.g. part of a dupligroup).
+ * This ignores selection and layer visibility,
+ * and assumes that the dupli-object itself (e.g. the group-instantiating empty) is exported.
+ */
+static bool export_object(const ExportSettings * const settings, Object *ob,
+ bool is_duplicated)
{
- if (settings->selected_only && !parent_selected(ob)) {
- return false;
- }
+ if (!is_duplicated) {
+ /* These two tests only make sense when the object isn't being instanced
+ * into the scene. When it is, its exportability is determined by
+ * its dupli-object and the DupliObject::no_draw property. */
+ if (settings->selected_only && !parent_selected(ob)) {
+ return false;
+ }
- if (settings->visible_layers_only && !(settings->scene->lay & ob->lay)) {
- return false;
+ if (settings->visible_layers_only && !(settings->scene->lay & ob->lay)) {
+ return false;
+ }
}
if (settings->renderable_only && (ob->restrictflag & OB_RESTRICT_RENDER)) {
@@ -142,8 +168,9 @@ static bool export_object(const ExportSettings * const settings, Object *ob)
/* ************************************************************************** */
-AbcExporter::AbcExporter(Scene *scene, const char *filename, ExportSettings &settings)
- : m_settings(settings)
+AbcExporter::AbcExporter(Main *bmain, Scene *scene, const char *filename, ExportSettings &settings)
+ : m_bmain(bmain)
+ , m_settings(settings)
, m_filename(filename)
, m_trans_sampling_index(0)
, m_shape_sampling_index(0)
@@ -153,11 +180,13 @@ AbcExporter::AbcExporter(Scene *scene, const char *filename, ExportSettings &set
AbcExporter::~AbcExporter()
{
- std::map<std::string, AbcTransformWriter*>::iterator it, e;
- for (it = m_xforms.begin(), e = m_xforms.end(); it != e; ++it) {
- delete it->second;
+ /* Free xforms map */
+ m_xforms_type::iterator it_x, e_x;
+ for (it_x = m_xforms.begin(), e_x = m_xforms.end(); it_x != e_x; ++it_x) {
+ delete it_x->second;
}
+ /* Free shapes vector */
for (int i = 0, e = m_shapes.size(); i != e; ++i) {
delete m_shapes[i];
}
@@ -165,60 +194,56 @@ AbcExporter::~AbcExporter()
delete m_writer;
}
-void AbcExporter::getShutterSamples(double step, bool time_relative,
+void AbcExporter::getShutterSamples(unsigned int nr_of_samples,
+ bool time_relative,
std::vector<double> &samples)
{
+ Scene *scene = m_scene; /* for use in the FPS macro */
samples.clear();
- const double time_factor = time_relative ? m_scene->r.frs_sec : 1.0;
- const double shutter_open = m_settings.shutter_open;
- const double shutter_close = m_settings.shutter_close;
+ unsigned int frame_offset = time_relative ? m_settings.frame_start : 0;
+ double time_factor = time_relative ? FPS : 1.0;
+ double shutter_open = m_settings.shutter_open;
+ double shutter_close = m_settings.shutter_close;
+ double time_inc = (shutter_close - shutter_open) / nr_of_samples;
- /* sample all frame */
- if (shutter_open == 0.0 && shutter_close == 1.0) {
- for (double t = 0.0; t < 1.0; t += step) {
- samples.push_back((t + m_settings.frame_start) / time_factor);
- }
- }
- else {
- /* sample between shutter open & close */
- const int nsamples = static_cast<int>(std::max((1.0 / step) - 1.0, 1.0));
- const double time_inc = (shutter_close - shutter_open) / nsamples;
+ /* sample between shutter open & close */
+ for (int sample=0; sample < nr_of_samples; ++sample) {
+ double sample_time = shutter_open + time_inc * sample;
+ double time = (frame_offset + sample_time) / time_factor;
- for (double t = shutter_open; t <= shutter_close; t += time_inc) {
- samples.push_back((t + m_settings.frame_start) / time_factor);
- }
+ samples.push_back(time);
}
}
Alembic::Abc::TimeSamplingPtr AbcExporter::createTimeSampling(double step)
{
- TimeSamplingPtr time_sampling;
std::vector<double> samples;
if (m_settings.frame_start == m_settings.frame_end) {
- time_sampling.reset(new Alembic::Abc::TimeSampling());
- return time_sampling;
+ return TimeSamplingPtr(new Alembic::Abc::TimeSampling());
}
getShutterSamples(step, true, samples);
- Alembic::Abc::TimeSamplingType ts(static_cast<uint32_t>(samples.size()), 1.0 / m_scene->r.frs_sec);
- time_sampling.reset(new Alembic::Abc::TimeSampling(ts, samples));
+ Alembic::Abc::TimeSamplingType ts(
+ static_cast<uint32_t>(samples.size()),
+ 1.0 / m_scene->r.frs_sec);
- return time_sampling;
+ return TimeSamplingPtr(new Alembic::Abc::TimeSampling(ts, samples));
}
-void AbcExporter::getFrameSet(double step, std::set<double> &frames)
+void AbcExporter::getFrameSet(unsigned int nr_of_samples,
+ std::set<double> &frames)
{
frames.clear();
std::vector<double> shutter_samples;
- getShutterSamples(step, false, shutter_samples);
+ getShutterSamples(nr_of_samples, false, shutter_samples);
for (double frame = m_settings.frame_start; frame <= m_settings.frame_end; frame += 1.0) {
- for (int j = 0, e = shutter_samples.size(); j < e; ++j) {
+ for (size_t j = 0; j < nr_of_samples; ++j) {
frames.insert(frame + shutter_samples[j]);
}
}
@@ -250,44 +275,37 @@ void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
/* Create time samplings for transforms and shapes. */
- TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_step_xform);
+ TimeSamplingPtr trans_time = createTimeSampling(m_settings.frame_samples_xform);
m_trans_sampling_index = m_writer->archive().addTimeSampling(*trans_time);
TimeSamplingPtr shape_time;
- if ((m_settings.frame_step_shape == m_settings.frame_step_xform) ||
+ if ((m_settings.frame_samples_shape == m_settings.frame_samples_xform) ||
(m_settings.frame_start == m_settings.frame_end))
{
shape_time = trans_time;
m_shape_sampling_index = m_trans_sampling_index;
}
else {
- shape_time = createTimeSampling(m_settings.frame_step_shape);
+ shape_time = createTimeSampling(m_settings.frame_samples_shape);
m_shape_sampling_index = m_writer->archive().addTimeSampling(*shape_time);
}
OBox3dProperty archive_bounds_prop = Alembic::AbcGeom::CreateOArchiveBounds(m_writer->archive(), m_trans_sampling_index);
- if (m_settings.flatten_hierarchy) {
- createTransformWritersFlat();
- }
- else {
- createTransformWritersHierarchy(bmain->eval_ctx);
- }
-
+ createTransformWritersHierarchy(bmain->eval_ctx);
createShapeWriters(bmain->eval_ctx);
/* Make a list of frames to export. */
std::set<double> xform_frames;
- getFrameSet(m_settings.frame_step_xform, xform_frames);
+ getFrameSet(m_settings.frame_samples_xform, xform_frames);
std::set<double> shape_frames;
- getFrameSet(m_settings.frame_step_shape, shape_frames);
+ getFrameSet(m_settings.frame_samples_shape, shape_frames);
/* Merge all frames needed. */
-
std::set<double> frames(xform_frames);
frames.insert(shape_frames.begin(), shape_frames.end());
@@ -310,7 +328,7 @@ void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
const double frame = *begin;
/* 'frame' is offset by start frame, so need to cancel the offset. */
- setCurrentFrame(bmain, frame - m_settings.frame_start);
+ setCurrentFrame(bmain, frame);
if (shape_frames.count(frame) != 0) {
for (int i = 0, e = m_shapes.size(); i != e; ++i) {
@@ -322,7 +340,7 @@ void AbcExporter::operator()(Main *bmain, float &progress, bool &was_canceled)
continue;
}
- std::map<std::string, AbcTransformWriter *>::iterator xit, xe;
+ m_xforms_type::iterator xit, xe;
for (xit = m_xforms.begin(), xe = m_xforms.end(); xit != xe; ++xit) {
xit->second->write();
}
@@ -346,34 +364,14 @@ void AbcExporter::createTransformWritersHierarchy(EvaluationContext *eval_ctx)
while (base) {
Object *ob = base->object;
- if (export_object(&m_settings, ob)) {
- switch(ob->type) {
- case OB_LAMP:
- case OB_LATTICE:
- case OB_MBALL:
- case OB_SPEAKER:
- /* We do not export transforms for objects of these classes. */
- break;
-
- default:
- exploreTransform(eval_ctx, ob, ob->parent, NULL);
- }
- }
-
- base = base->next;
- }
-}
-
-void AbcExporter::createTransformWritersFlat()
-{
- Base *base = static_cast<Base *>(m_scene->base.first);
-
- while (base) {
- Object *ob = base->object;
-
- if (export_object(&m_settings, ob) && object_is_shape(ob)) {
- std::string name = get_id_name(ob);
- m_xforms[name] = new AbcTransformWriter(ob, m_writer->archive().getTop(), 0, m_trans_sampling_index, m_settings);
+ switch (ob->type) {
+ case OB_LAMP:
+ case OB_LATTICE:
+ case OB_SPEAKER:
+ /* We do not export transforms for objects of these classes. */
+ break;
+ default:
+ exploreTransform(eval_ctx, ob, ob->parent);
}
base = base->next;
@@ -382,8 +380,13 @@ void AbcExporter::createTransformWritersFlat()
void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Object *ob, Object *parent, Object *dupliObParent)
{
+ /* If an object isn't exported itself, its duplilist shouldn't be
+ * exported either. */
+ if (!export_object(&m_settings, ob, dupliObParent != NULL)) {
+ return;
+ }
- if (export_object(&m_settings, ob) && object_is_shape(ob)) {
+ if (object_type_is_exportable(m_scene, ob)) {
createTransformWriter(ob, parent, dupliObParent);
}
@@ -394,68 +397,91 @@ void AbcExporter::exploreTransform(EvaluationContext *eval_ctx, Object *ob, Obje
Object *dupli_ob = NULL;
Object *dupli_parent = NULL;
- while (link) {
+ for (; link; link = link->next) {
+ /* This skips things like custom bone shapes. */
+ if (m_settings.renderable_only && link->no_draw) {
+ continue;
+ }
+
if (link->type == OB_DUPLIGROUP) {
dupli_ob = link->ob;
dupli_parent = (dupli_ob->parent) ? dupli_ob->parent : ob;
exploreTransform(eval_ctx, dupli_ob, dupli_parent, ob);
}
-
- link = link->next;
}
}
free_object_duplilist(lb);
}
-void AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
+AbcTransformWriter * AbcExporter::createTransformWriter(Object *ob, Object *parent, Object *dupliObParent)
{
- const std::string name = get_object_dag_path_name(ob, dupliObParent);
-
/* An object should not be its own parent, or we'll get infinite loops. */
BLI_assert(ob != parent);
BLI_assert(ob != dupliObParent);
- /* check if we have already created a transform writer for this object */
- if (getXForm(name) != NULL){
- std::cerr << "xform " << name << " already exists\n";
- return;
+ std::string name;
+ if (m_settings.flatten_hierarchy) {
+ name = get_id_name(ob);
+ }
+ else {
+ name = get_object_dag_path_name(ob, dupliObParent);
}
- AbcTransformWriter *parent_xform = NULL;
+ /* check if we have already created a transform writer for this object */
+ AbcTransformWriter *my_writer = getXForm(name);
+ if (my_writer != NULL) {
+ return my_writer;
+ }
- if (parent) {
- const std::string parentname = get_object_dag_path_name(parent, dupliObParent);
- parent_xform = getXForm(parentname);
+ AbcTransformWriter *parent_writer = NULL;
+ Alembic::Abc::OObject alembic_parent;
- if (!parent_xform) {
- if (parent->parent) {
- createTransformWriter(parent, parent->parent, dupliObParent);
+ if (m_settings.flatten_hierarchy || parent == NULL) {
+ /* Parentless objects still have the "top object" as parent
+ * in Alembic. */
+ alembic_parent = m_writer->archive().getTop();
+ }
+ else {
+ /* Since there are so many different ways to find parents (as evident
+ * in the number of conditions below), we can't really look up the
+ * parent by name. We'll just call createTransformWriter(), which will
+ * return the parent's AbcTransformWriter pointer. */
+ if (parent->parent) {
+ if (parent == dupliObParent) {
+ parent_writer = createTransformWriter(parent, parent->parent, NULL);
+ }
+ else {
+ parent_writer = createTransformWriter(parent, parent->parent, dupliObParent);
}
- else if (parent == dupliObParent) {
- if (dupliObParent->parent == NULL) {
- createTransformWriter(parent, NULL, NULL);
- }
- else {
- createTransformWriter(parent, dupliObParent->parent, dupliObParent->parent);
- }
+ }
+ else if (parent == dupliObParent) {
+ if (dupliObParent->parent == NULL) {
+ parent_writer = createTransformWriter(parent, NULL, NULL);
}
else {
- createTransformWriter(parent, dupliObParent, dupliObParent);
+ parent_writer = createTransformWriter(parent, dupliObParent->parent, dupliObParent->parent);
}
-
- parent_xform = getXForm(parentname);
}
- }
+ else {
+ parent_writer = createTransformWriter(parent, dupliObParent, dupliObParent);
+ }
- if (parent_xform) {
- m_xforms[name] = new AbcTransformWriter(ob, parent_xform->alembicXform(), parent_xform, m_trans_sampling_index, m_settings);
- m_xforms[name]->setParent(parent);
+ BLI_assert(parent_writer);
+ alembic_parent = parent_writer->alembicXform();
}
- else {
- m_xforms[name] = new AbcTransformWriter(ob, m_writer->archive().getTop(), NULL, m_trans_sampling_index, m_settings);
+
+ my_writer = new AbcTransformWriter(ob, alembic_parent, parent_writer,
+ m_trans_sampling_index, m_settings);
+
+ /* When flattening, the matrix of the dupliobject has to be added. */
+ if (m_settings.flatten_hierarchy && dupliObParent) {
+ my_writer->m_proxy_from = dupliObParent;
}
+
+ m_xforms[name] = my_writer;
+ return my_writer;
}
void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
@@ -472,32 +498,60 @@ void AbcExporter::createShapeWriters(EvaluationContext *eval_ctx)
void AbcExporter::exploreObject(EvaluationContext *eval_ctx, Object *ob, Object *dupliObParent)
{
- ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
-
+ /* If an object isn't exported itself, its duplilist shouldn't be
+ * exported either. */
+ if (!export_object(&m_settings, ob, dupliObParent != NULL)) {
+ return;
+ }
+
createShapeWriter(ob, dupliObParent);
+ ListBase *lb = object_duplilist(eval_ctx, m_scene, ob);
+
if (lb) {
- DupliObject *dupliob = static_cast<DupliObject *>(lb->first);
+ DupliObject *link = static_cast<DupliObject *>(lb->first);
- while (dupliob) {
- if (dupliob->type == OB_DUPLIGROUP) {
- exploreObject(eval_ctx, dupliob->ob, ob);
+ for (; link; link = link->next) {
+ /* This skips things like custom bone shapes. */
+ if (m_settings.renderable_only && link->no_draw) {
+ continue;
}
- dupliob = dupliob->next;
+ if (link->type == OB_DUPLIGROUP) {
+ exploreObject(eval_ctx, link->ob, ob);
+ }
}
}
free_object_duplilist(lb);
}
-void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
+void AbcExporter::createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform)
{
- if (!object_is_shape(ob)) {
+ if (!m_settings.export_hair && !m_settings.export_particles) {
return;
}
- if (!export_object(&m_settings, ob)) {
+ ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
+
+ for (; psys; psys = psys->next) {
+ if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
+ continue;
+ }
+
+ if (m_settings.export_hair && psys->part->type == PART_HAIR) {
+ m_settings.export_child_hairs = true;
+ m_shapes.push_back(new AbcHairWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
+ }
+ else if (m_settings.export_particles && psys->part->type == PART_EMITTER) {
+ m_shapes.push_back(new AbcPointsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
+ }
+ }
+}
+
+void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
+{
+ if (!object_type_is_exportable(m_scene, ob)) {
return;
}
@@ -513,32 +567,18 @@ void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
AbcTransformWriter *xform = getXForm(name);
if (!xform) {
- std::cerr << __func__ << ": xform " << name << " is NULL\n";
+ ABC_LOG(m_settings.logger) << __func__ << ": xform " << name << " is NULL\n";
return;
}
- ParticleSystem *psys = static_cast<ParticleSystem *>(ob->particlesystem.first);
+ createParticleSystemsWriters(ob, xform);
- for (; psys; psys = psys->next) {
- if (!psys_check_enabled(ob, psys, G.is_rendering) || !psys->part) {
- continue;
- }
-
- if (psys->part->type == PART_HAIR) {
- m_settings.export_child_hairs = true;
- m_shapes.push_back(new AbcHairWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
- }
- else if (psys->part->type == PART_EMITTER) {
- m_shapes.push_back(new AbcPointsWriter(m_scene, ob, xform, m_shape_sampling_index, m_settings, psys));
- }
- }
-
- switch(ob->type) {
+ switch (ob->type) {
case OB_MESH:
{
Mesh *me = static_cast<Mesh *>(ob->data);
- if (!me || me->totvert == 0) {
+ if (!me) {
return;
}
@@ -577,6 +617,18 @@ void AbcExporter::createShapeWriter(Object *ob, Object *dupliObParent)
break;
}
+ case OB_MBALL:
+ {
+ MetaBall *mball = static_cast<MetaBall *>(ob->data);
+ if (!mball) {
+ return;
+ }
+
+ m_shapes.push_back(new AbcMBallWriter(
+ m_bmain, m_scene, ob, xform,
+ m_shape_sampling_index, m_settings));
+ break;
+ }
}
}
diff --git a/source/blender/alembic/intern/abc_exporter.h b/source/blender/alembic/intern/abc_exporter.h
index b0eb8e185d6..280682b2896 100644
--- a/source/blender/alembic/intern/abc_exporter.h
+++ b/source/blender/alembic/intern/abc_exporter.h
@@ -28,6 +28,8 @@
#include <set>
#include <vector>
+#include "abc_util.h"
+
class AbcObjectWriter;
class AbcTransformWriter;
class ArchiveWriter;
@@ -41,14 +43,15 @@ struct ExportSettings {
ExportSettings();
Scene *scene;
+ SimpleLogger logger;
bool selected_only;
bool visible_layers_only;
bool renderable_only;
double frame_start, frame_end;
- double frame_step_xform;
- double frame_step_shape;
+ double frame_samples_xform;
+ double frame_samples_shape;
double shutter_open;
double shutter_close;
float global_scale;
@@ -60,6 +63,8 @@ struct ExportSettings {
bool export_vcols;
bool export_face_sets;
bool export_vweigths;
+ bool export_hair;
+ bool export_particles;
bool apply_subdiv;
bool use_subdiv_schema;
@@ -76,6 +81,7 @@ struct ExportSettings {
};
class AbcExporter {
+ Main *m_bmain;
ExportSettings &m_settings;
const char *m_filename;
@@ -86,29 +92,34 @@ class AbcExporter {
ArchiveWriter *m_writer;
- std::map<std::string, AbcTransformWriter *> m_xforms;
+ /* mapping from name to transform writer */
+ typedef std::map<std::string, AbcTransformWriter *> m_xforms_type;
+ m_xforms_type m_xforms;
+
std::vector<AbcObjectWriter *> m_shapes;
public:
- AbcExporter(Scene *scene, const char *filename, ExportSettings &settings);
+ AbcExporter(Main *bmain, Scene *scene, const char *filename, ExportSettings &settings);
~AbcExporter();
void operator()(Main *bmain, float &progress, bool &was_canceled);
-private:
- void getShutterSamples(double step, bool time_relative, std::vector<double> &samples);
+protected:
+ void getShutterSamples(unsigned int nr_of_samples,
+ bool time_relative,
+ std::vector<double> &samples);
+ void getFrameSet(unsigned int nr_of_samples, std::set<double> &frames);
+private:
Alembic::Abc::TimeSamplingPtr createTimeSampling(double step);
- void getFrameSet(double step, std::set<double> &frames);
-
void createTransformWritersHierarchy(EvaluationContext *eval_ctx);
- void createTransformWritersFlat();
- void createTransformWriter(Object *ob, Object *parent, Object *dupliObParent);
+ AbcTransformWriter * createTransformWriter(Object *ob, Object *parent, Object *dupliObParent);
void exploreTransform(EvaluationContext *eval_ctx, Object *ob, Object *parent, Object *dupliObParent = NULL);
void exploreObject(EvaluationContext *eval_ctx, Object *ob, Object *dupliObParent);
void createShapeWriters(EvaluationContext *eval_ctx);
void createShapeWriter(Object *ob, Object *dupliObParent);
+ void createParticleSystemsWriters(Object *ob, AbcTransformWriter *xform);
AbcTransformWriter *getXForm(const std::string &name);
diff --git a/source/blender/alembic/intern/abc_hair.cc b/source/blender/alembic/intern/abc_hair.cc
index e328df24e53..0208da8a6d7 100644
--- a/source/blender/alembic/intern/abc_hair.cc
+++ b/source/blender/alembic/intern/abc_hair.cc
@@ -56,6 +56,7 @@ AbcHairWriter::AbcHairWriter(Scene *scene,
ExportSettings &settings,
ParticleSystem *psys)
: AbcObjectWriter(scene, ob, time_sampling, settings, parent)
+ , m_uv_warning_shown(false)
{
m_psys = psys;
@@ -75,7 +76,7 @@ void AbcHairWriter::do_write()
return;
}
- DerivedMesh *dm = mesh_create_derived_view(m_scene, m_object, CD_MASK_MESH);
+ DerivedMesh *dm = mesh_create_derived_render(m_scene, m_object, CD_MASK_MESH);
DM_ensure_tessface(dm);
std::vector<Imath::V3f> verts;
@@ -132,8 +133,10 @@ void AbcHairWriter::write_hair_sample(DerivedMesh *dm,
MFace *mface = dm->getTessFaceArray(dm);
MVert *mverts = dm->getVertArray(dm);
- if (!mtface || !mface) {
- std::fprintf(stderr, "Warning, no UV set found for underlying geometry.\n");
+ if ((!mtface || !mface) && !m_uv_warning_shown) {
+ std::fprintf(stderr, "Warning, no UV set found for underlying geometry of %s.\n",
+ m_object->id.name + 2);
+ m_uv_warning_shown = true;
}
ParticleData * pa = m_psys->particles;
@@ -238,13 +241,8 @@ void AbcHairWriter::write_hair_child_sample(DerivedMesh *dm,
invert_m4_m4_safe(inv_mat, m_object->obmat);
MTFace *mtface = static_cast<MTFace *>(CustomData_get_layer(&dm->faceData, CD_MTFACE));
- MFace *mface = dm->getTessFaceArray(dm);
MVert *mverts = dm->getVertArray(dm);
- if (!mtface || !mface) {
- std::fprintf(stderr, "Warning, no UV set found for underlying geometry.\n");
- }
-
ParticleCacheKey **cache = m_psys->childcache;
ParticleCacheKey *path;
@@ -253,22 +251,38 @@ void AbcHairWriter::write_hair_child_sample(DerivedMesh *dm,
for (int p = 0; p < m_psys->totchild; ++p, ++pc) {
path = cache[p];
- if (part->from == PART_FROM_FACE) {
+ if (part->from == PART_FROM_FACE &&
+ part->childtype != PART_CHILD_PARTICLES &&
+ mtface)
+ {
const int num = pc->num;
+ if (num < 0) {
+ ABC_LOG(m_settings.logger)
+ << "Warning, child particle of hair system " << m_psys->name
+ << " has unknown face index of geometry of "<< (m_object->id.name + 2)
+ << ", skipping child hair." << std::endl;
+ continue;
+ }
MFace *face = static_cast<MFace *>(dm->getTessFaceData(dm, num, CD_MFACE));
MTFace *tface = mtface + num;
- if (mface && mtface) {
- float r_uv[2], tmpnor[3], mapfw[4], vec[3];
+ float r_uv[2], tmpnor[3], mapfw[4], vec[3];
- psys_interpolate_uvs(tface, face->v4, pc->fuv, r_uv);
- uv_values.push_back(Imath::V2f(r_uv[0], r_uv[1]));
+ psys_interpolate_uvs(tface, face->v4, pc->fuv, r_uv);
+ uv_values.push_back(Imath::V2f(r_uv[0], r_uv[1]));
- psys_interpolate_face(mverts, face, tface, NULL, mapfw, vec, tmpnor, NULL, NULL, NULL, NULL);
+ psys_interpolate_face(mverts, face, tface, NULL, mapfw, vec, tmpnor, NULL, NULL, NULL, NULL);
- /* Convert Z-up to Y-up. */
- norm_values.push_back(Imath::V3f(tmpnor[0], tmpnor[2], -tmpnor[1]));
+ /* Convert Z-up to Y-up. */
+ norm_values.push_back(Imath::V3f(tmpnor[0], tmpnor[2], -tmpnor[1]));
+ }
+ else {
+ if (uv_values.size()) {
+ uv_values.push_back(uv_values[pc->parent]);
+ }
+ if (norm_values.size()) {
+ norm_values.push_back(norm_values[pc->parent]);
}
}
diff --git a/source/blender/alembic/intern/abc_hair.h b/source/blender/alembic/intern/abc_hair.h
index d132b60be12..61f5fe361f8 100644
--- a/source/blender/alembic/intern/abc_hair.h
+++ b/source/blender/alembic/intern/abc_hair.h
@@ -37,6 +37,8 @@ class AbcHairWriter : public AbcObjectWriter {
Alembic::AbcGeom::OCurvesSchema m_schema;
Alembic::AbcGeom::OCurvesSchema::Sample m_sample;
+ bool m_uv_warning_shown;
+
public:
AbcHairWriter(Scene *scene,
Object *ob,
diff --git a/source/blender/alembic/intern/abc_mball.cc b/source/blender/alembic/intern/abc_mball.cc
new file mode 100644
index 00000000000..1ef7b757577
--- /dev/null
+++ b/source/blender/alembic/intern/abc_mball.cc
@@ -0,0 +1,122 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Sybren A. Stüvel
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "abc_mball.h"
+#include "abc_mesh.h"
+#include "abc_transform.h"
+
+extern "C" {
+#include "DNA_meta_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_curve.h"
+#include "BKE_depsgraph.h"
+#include "BKE_displist.h"
+#include "BKE_main.h"
+#include "BKE_mball.h"
+#include "BKE_mesh.h"
+#include "BKE_object.h"
+
+#include "DEG_depsgraph.h"
+#include "MEM_guardedalloc.h"
+}
+
+AbcMBallWriter::AbcMBallWriter(
+ Main *bmain,
+ Scene *scene,
+ Object *ob,
+ AbcTransformWriter *parent,
+ uint32_t time_sampling,
+ ExportSettings &settings)
+ : AbcObjectWriter(scene, ob, time_sampling, settings, parent)
+ , m_bmain(bmain)
+{
+ m_is_animated = isAnimated();
+
+ m_mesh_ob = BKE_object_copy(bmain, ob);
+ m_mesh_ob->curve_cache = (CurveCache *)MEM_callocN(
+ sizeof(CurveCache),
+ "CurveCache for AbcMBallWriter");
+
+ m_mesh_writer = new AbcMeshWriter(scene, m_mesh_ob, parent,
+ time_sampling, settings);
+ m_mesh_writer->setIsAnimated(m_is_animated);
+}
+
+
+AbcMBallWriter::~AbcMBallWriter()
+{
+ delete m_mesh_writer;
+ BKE_object_free(m_mesh_ob);
+}
+
+bool AbcMBallWriter::isAnimated() const
+{
+ MetaBall *mb = static_cast<MetaBall *>(m_object->data);
+ if (mb->adt != NULL) return true;
+
+ /* Any movement of any object in the parent chain
+ * could cause the mball to deform. */
+ for (Object *ob = m_object; ob != NULL; ob = ob->parent) {
+ if (ob->adt != NULL) return true;
+ }
+ return false;
+}
+
+void AbcMBallWriter::do_write()
+{
+ /* We have already stored a sample for this object. */
+ if (!m_first_frame && !m_is_animated)
+ return;
+
+ Mesh *tmpmesh = BKE_mesh_add(m_bmain, ((ID *)m_object->data)->name + 2);
+ BLI_assert(tmpmesh != NULL);
+ m_mesh_ob->data = tmpmesh;
+
+ /* BKE_mesh_add gives us a user count we don't need */
+ id_us_min(&tmpmesh->id);
+
+ ListBase disp = {NULL, NULL};
+ /* TODO(sergey): This is gonna to work for until EvaluationContext
+ * only contains for_render flag. As soon as CoW is
+ * implemented, this is to be rethinked.
+ */
+ EvaluationContext eval_ctx;
+ DEG_evaluation_context_init(&eval_ctx, DAG_EVAL_RENDER);
+ BKE_displist_make_mball_forRender(&eval_ctx, m_scene, m_object, &disp);
+ BKE_mesh_from_metaball(&disp, tmpmesh);
+ BKE_displist_free(&disp);
+
+ BKE_mesh_texspace_copy_from_object(tmpmesh, m_mesh_ob);
+
+ m_mesh_writer->write();
+
+ BKE_id_free(m_bmain, tmpmesh);
+ m_mesh_ob->data = NULL;
+}
+
+bool AbcMBallWriter::isBasisBall(Scene *scene, Object *ob)
+{
+ Object *basis_ob = BKE_mball_basis_find(scene, ob);
+ return ob == basis_ob;
+}
diff --git a/source/blender/alembic/intern/abc_mball.h b/source/blender/alembic/intern/abc_mball.h
new file mode 100644
index 00000000000..9b943698416
--- /dev/null
+++ b/source/blender/alembic/intern/abc_mball.h
@@ -0,0 +1,61 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Sybren A. Stüvel
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __ABC_MBALL_H__
+#define __ABC_MBALL_H__
+
+#include "abc_object.h"
+
+class AbcMeshWriter;
+struct Main;
+struct MetaBall;
+struct Object;
+
+/* AbcMBallWriter converts the metaballs to meshes at every frame,
+ * and defers to a wrapped AbcMeshWriter to perform the writing
+ * to the Alembic file. Only the basis balls are exported, as this
+ * results in the entire shape as one mesh. */
+class AbcMBallWriter : public AbcObjectWriter {
+ AbcMeshWriter *m_mesh_writer;
+ Object *m_mesh_ob;
+ bool m_is_animated;
+ Main *m_bmain;
+public:
+ AbcMBallWriter(
+ Main *bmain,
+ Scene *scene,
+ Object *ob,
+ AbcTransformWriter *parent,
+ uint32_t time_sampling,
+ ExportSettings &settings);
+
+ ~AbcMBallWriter();
+
+ static bool isBasisBall(Scene *scene, Object *ob);
+
+private:
+ virtual void do_write();
+ bool isAnimated() const;
+};
+
+
+#endif /* __ABC_MBALL_H__ */
diff --git a/source/blender/alembic/intern/abc_mesh.cc b/source/blender/alembic/intern/abc_mesh.cc
index 8bc9c335054..90e95542a9a 100644
--- a/source/blender/alembic/intern/abc_mesh.cc
+++ b/source/blender/alembic/intern/abc_mesh.cc
@@ -31,7 +31,7 @@ extern "C" {
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "BLI_math_geom.h"
@@ -355,7 +355,12 @@ bool AbcMeshWriter::isAnimated() const
md = md->next;
}
- return false;
+ return me->adt != NULL;
+}
+
+void AbcMeshWriter::setIsAnimated(bool is_animated)
+{
+ m_is_animated = is_animated;
}
void AbcMeshWriter::do_write()
@@ -681,17 +686,17 @@ static void assign_materials(Main *bmain, Object *ob, const std::map<std::string
std::string mat_name = it->first;
mat_iter = mat_map.find(mat_name.c_str());
- Material *assigned_name;
+ Material *assigned_mat;
if (mat_iter == mat_map.end()) {
- assigned_name = BKE_material_add(bmain, mat_name.c_str());
- mat_map[mat_name] = assigned_name;
+ assigned_mat = BKE_material_add(bmain, mat_name.c_str());
+ mat_map[mat_name] = assigned_mat;
}
else {
- assigned_name = mat_iter->second;
+ assigned_mat = mat_iter->second;
}
- assign_material(ob, assigned_name, it->second, BKE_MAT_ASSIGN_OBJECT);
+ assign_material(ob, assigned_mat, it->second, BKE_MAT_ASSIGN_OBDATA);
}
}
}
@@ -897,19 +902,31 @@ static void *add_customdata_cb(void *user_data, const char *name, int data_type)
{
DerivedMesh *dm = static_cast<DerivedMesh *>(user_data);
CustomDataType cd_data_type = static_cast<CustomDataType>(data_type);
- void *cd_ptr = NULL;
-
- if (ELEM(cd_data_type, CD_MLOOPUV, CD_MLOOPCOL)) {
- cd_ptr = CustomData_get_layer_named(dm->getLoopDataLayout(dm), cd_data_type, name);
-
- if (cd_ptr == NULL) {
- cd_ptr = CustomData_add_layer_named(dm->getLoopDataLayout(dm),
- cd_data_type,
- CD_DEFAULT,
- NULL,
- dm->getNumLoops(dm),
- name);
- }
+ void *cd_ptr;
+ CustomData *loopdata;
+ int numloops;
+
+ /* unsupported custom data type -- don't do anything. */
+ if (!ELEM(cd_data_type, CD_MLOOPUV, CD_MLOOPCOL)) {
+ return NULL;
+ }
+
+ loopdata = dm->getLoopDataLayout(dm);
+ cd_ptr = CustomData_get_layer_named(loopdata, cd_data_type, name);
+ if (cd_ptr != NULL) {
+ /* layer already exists, so just return it. */
+ return cd_ptr;
+ }
+
+ /* create a new layer, taking care to construct the hopefully-soon-to-be-removed
+ * CD_MTEXPOLY layer too, with the same name. */
+ numloops = dm->getNumLoops(dm);
+ cd_ptr = CustomData_add_layer_named(loopdata, cd_data_type, CD_DEFAULT,
+ NULL, numloops, name);
+ if (cd_data_type == CD_MLOOPUV) {
+ CustomData_add_layer_named(dm->getPolyDataLayout(dm),
+ CD_MTEXPOLY, CD_DEFAULT,
+ NULL, numloops, name);
}
return cd_ptr;
@@ -931,7 +948,8 @@ static void get_weight_and_index(CDStreamConfig &config,
config.ceil_index = i1;
}
-static void read_mesh_sample(ImportSettings *settings,
+static void read_mesh_sample(const std::string & iobject_full_name,
+ ImportSettings *settings,
const IPolyMeshSchema &schema,
const ISampleSelector &selector,
CDStreamConfig &config,
@@ -969,10 +987,9 @@ static void read_mesh_sample(ImportSettings *settings,
}
if ((settings->read_flag & (MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)) != 0) {
- read_custom_data(schema.getArbGeomParams(), config, selector);
+ read_custom_data(iobject_full_name,
+ schema.getArbGeomParams(), config, selector);
}
-
- /* TODO: face sets */
}
CDStreamConfig get_config(DerivedMesh *dm)
@@ -1009,17 +1026,15 @@ bool AbcMeshReader::valid() const
return m_schema.valid();
}
-void AbcMeshReader::readObjectData(Main *bmain, float time)
+void AbcMeshReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
{
Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
m_object = BKE_object_add_only_object(bmain, OB_MESH, m_object_name.c_str());
m_object->data = mesh;
- const ISampleSelector sample_sel(time);
-
DerivedMesh *dm = CDDM_from_mesh(mesh);
- DerivedMesh *ndm = this->read_derivedmesh(dm, time, MOD_MESHSEQ_READ_ALL, NULL);
+ DerivedMesh *ndm = this->read_derivedmesh(dm, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
if (ndm != dm) {
dm->release(dm);
@@ -1038,9 +1053,28 @@ void AbcMeshReader::readObjectData(Main *bmain, float time)
}
}
-DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str)
+bool AbcMeshReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::IPolyMesh::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to PolyMesh when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_MESH) {
+ *err_str = "Object type mismatch, Alembic object path points to PolyMesh.";
+ return false;
+ }
+
+ return true;
+}
+
+DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm,
+ const ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str)
{
- ISampleSelector sample_sel(time);
const IPolyMeshSchema::Sample sample = m_schema.getValue(sample_sel);
const P3fArraySamplePtr &positions = sample.getPositions();
@@ -1053,7 +1087,10 @@ DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm, const float time,
ImportSettings settings;
settings.read_flag |= read_flag;
- if (dm->getNumVerts(dm) != positions->size()) {
+ bool topology_changed = positions->size() != dm->getNumVerts(dm) ||
+ face_counts->size() != dm->getNumPolys(dm) ||
+ face_indices->size() != dm->getNumLoops(dm);
+ if (topology_changed) {
new_dm = CDDM_from_template(dm,
positions->size(),
0,
@@ -1080,10 +1117,11 @@ DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm, const float time,
}
CDStreamConfig config = get_config(new_dm ? new_dm : dm);
- config.time = time;
+ config.time = sample_sel.getRequestedTime();
bool do_normals = false;
- read_mesh_sample(&settings, m_schema, sample_sel, config, do_normals);
+ read_mesh_sample(m_iobject.getFullName(),
+ &settings, m_schema, sample_sel, config, do_normals);
if (new_dm) {
/* Check if we had ME_SMOOTH flag set to restore it. */
@@ -1094,6 +1132,16 @@ DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm, const float time,
CDDM_calc_normals(new_dm);
CDDM_calc_edges(new_dm);
+ /* Here we assume that the number of materials doesn't change, i.e. that
+ * the material slots that were created when the object was loaded from
+ * Alembic are still valid now. */
+ size_t num_polys = new_dm->getNumPolys(new_dm);
+ if (num_polys > 0) {
+ MPoly *dmpolies = new_dm->getPolyArray(new_dm);
+ std::map<std::string, int> mat_map;
+ assign_facesets_to_mpoly(sample_sel, 0, dmpolies, num_polys, mat_map);
+ }
+
return new_dm;
}
@@ -1104,8 +1152,11 @@ DerivedMesh *AbcMeshReader::read_derivedmesh(DerivedMesh *dm, const float time,
return dm;
}
-void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_start,
- const ISampleSelector &sample_sel)
+void AbcMeshReader::assign_facesets_to_mpoly(
+ const ISampleSelector &sample_sel,
+ size_t poly_start,
+ MPoly *mpoly, int totpoly,
+ std::map<std::string, int> & r_mat_map)
{
std::vector<std::string> face_sets;
m_schema.getFaceSetNames(face_sets);
@@ -1114,21 +1165,21 @@ void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_star
return;
}
- std::map<std::string, int> mat_map;
int current_mat = 0;
for (int i = 0; i < face_sets.size(); ++i) {
const std::string &grp_name = face_sets[i];
- if (mat_map.find(grp_name) == mat_map.end()) {
- mat_map[grp_name] = 1 + current_mat++;
+ if (r_mat_map.find(grp_name) == r_mat_map.end()) {
+ r_mat_map[grp_name] = 1 + current_mat++;
}
- const int assigned_mat = mat_map[grp_name];
+ const int assigned_mat = r_mat_map[grp_name];
const IFaceSet faceset = m_schema.getFaceSet(grp_name);
if (!faceset.valid()) {
+ std::cerr << " Face set " << grp_name << " invalid for " << m_object_name << "\n";
continue;
}
@@ -1140,16 +1191,25 @@ void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_star
for (size_t l = 0; l < num_group_faces; l++) {
size_t pos = (*group_faces)[l] + poly_start;
- if (pos >= mesh->totpoly) {
+ if (pos >= totpoly) {
std::cerr << "Faceset overflow on " << faceset.getName() << '\n';
break;
}
- MPoly &poly = mesh->mpoly[pos];
+ MPoly &poly = mpoly[pos];
poly.mat_nr = assigned_mat - 1;
}
}
+}
+
+void AbcMeshReader::readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_start,
+ const ISampleSelector &sample_sel)
+{
+ std::map<std::string, int> mat_map;
+ assign_facesets_to_mpoly(sample_sel,
+ poly_start, mesh->mpoly, mesh->totpoly,
+ mat_map);
utils::assign_materials(bmain, m_object, mat_map);
}
@@ -1168,7 +1228,8 @@ ABC_INLINE MEdge *find_edge(MEdge *edges, int totedge, int v1, int v2)
return NULL;
}
-static void read_subd_sample(ImportSettings *settings,
+static void read_subd_sample(const std::string & iobject_full_name,
+ ImportSettings *settings,
const ISubDSchema &schema,
const ISampleSelector &selector,
CDStreamConfig &config)
@@ -1203,10 +1264,9 @@ static void read_subd_sample(ImportSettings *settings,
}
if ((settings->read_flag & (MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)) != 0) {
- read_custom_data(schema.getArbGeomParams(), config, selector);
+ read_custom_data(iobject_full_name,
+ schema.getArbGeomParams(), config, selector);
}
-
- /* TODO: face sets */
}
/* ************************************************************************** */
@@ -1227,7 +1287,24 @@ bool AbcSubDReader::valid() const
return m_schema.valid();
}
-void AbcSubDReader::readObjectData(Main *bmain, float time)
+bool AbcSubDReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::ISubD::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to SubD when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_MESH) {
+ *err_str = "Object type mismatch, Alembic object path points to SubD.";
+ return false;
+ }
+
+ return true;
+}
+
+void AbcSubDReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
{
Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
@@ -1235,7 +1312,7 @@ void AbcSubDReader::readObjectData(Main *bmain, float time)
m_object->data = mesh;
DerivedMesh *dm = CDDM_from_mesh(mesh);
- DerivedMesh *ndm = this->read_derivedmesh(dm, time, MOD_MESHSEQ_READ_ALL, NULL);
+ DerivedMesh *ndm = this->read_derivedmesh(dm, sample_sel, MOD_MESHSEQ_READ_ALL, NULL);
if (ndm != dm) {
dm->release(dm);
@@ -1243,7 +1320,6 @@ void AbcSubDReader::readObjectData(Main *bmain, float time)
DM_to_mesh(ndm, mesh, m_object, CD_MASK_MESH, true);
- const ISampleSelector sample_sel(time);
const ISubDSchema::Sample sample = m_schema.getValue(sample_sel);
Int32ArraySamplePtr indices = sample.getCreaseIndices();
Alembic::Abc::FloatArraySamplePtr sharpnesses = sample.getCreaseSharpnesses();
@@ -1274,9 +1350,11 @@ void AbcSubDReader::readObjectData(Main *bmain, float time)
}
}
-DerivedMesh *AbcSubDReader::read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str)
+DerivedMesh *AbcSubDReader::read_derivedmesh(DerivedMesh *dm,
+ const ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str)
{
- ISampleSelector sample_sel(time);
const ISubDSchema::Sample sample = m_schema.getValue(sample_sel);
const P3fArraySamplePtr &positions = sample.getPositions();
@@ -1316,8 +1394,9 @@ DerivedMesh *AbcSubDReader::read_derivedmesh(DerivedMesh *dm, const float time,
/* Only read point data when streaming meshes, unless we need to create new ones. */
CDStreamConfig config = get_config(new_dm ? new_dm : dm);
- config.time = time;
- read_subd_sample(&settings, m_schema, sample_sel, config);
+ config.time = sample_sel.getRequestedTime();
+ read_subd_sample(m_iobject.getFullName(),
+ &settings, m_schema, sample_sel, config);
if (new_dm) {
/* Check if we had ME_SMOOTH flag set to restore it. */
diff --git a/source/blender/alembic/intern/abc_mesh.h b/source/blender/alembic/intern/abc_mesh.h
index 64a3109232c..77c352d7cd3 100644
--- a/source/blender/alembic/intern/abc_mesh.h
+++ b/source/blender/alembic/intern/abc_mesh.h
@@ -57,6 +57,7 @@ public:
ExportSettings &settings);
~AbcMeshWriter();
+ void setIsAnimated(bool is_animated);
private:
virtual void do_write();
@@ -99,14 +100,24 @@ public:
AbcMeshReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
- void readObjectData(Main *bmain, float time);
-
- DerivedMesh *read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str);
+ DerivedMesh *read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str);
private:
void readFaceSetsSample(Main *bmain, Mesh *mesh, size_t poly_start,
const Alembic::AbcGeom::ISampleSelector &sample_sel);
+
+ void assign_facesets_to_mpoly(const Alembic::Abc::ISampleSelector &sample_sel,
+ size_t poly_start,
+ MPoly *mpoly, int totpoly,
+ std::map<std::string, int> & r_mat_map);
};
/* ************************************************************************** */
@@ -120,9 +131,14 @@ public:
AbcSubDReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
-
- void readObjectData(Main *bmain, float time);
- DerivedMesh *read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str);
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
+ DerivedMesh *read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str);
};
/* ************************************************************************** */
diff --git a/source/blender/alembic/intern/abc_nurbs.cc b/source/blender/alembic/intern/abc_nurbs.cc
index d0b9561f679..eaef06fd6d1 100644
--- a/source/blender/alembic/intern/abc_nurbs.cc
+++ b/source/blender/alembic/intern/abc_nurbs.cc
@@ -239,7 +239,7 @@ static bool set_knots(const FloatArraySamplePtr &knots, float *&nu_knots)
return true;
}
-void AbcNurbsReader::readObjectData(Main *bmain, float time)
+void AbcNurbsReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
{
Curve *cu = static_cast<Curve *>(BKE_curve_add(bmain, "abc_curve", OB_SURF));
cu->actvert = CU_ACT_NONE;
@@ -253,7 +253,6 @@ void AbcNurbsReader::readObjectData(Main *bmain, float time)
nu->resolu = cu->resolu;
nu->resolv = cu->resolv;
- const ISampleSelector sample_sel(time);
const INuPatchSchema &schema = it->first;
const INuPatchSchema::Sample smp = schema.getValue(sample_sel);
diff --git a/source/blender/alembic/intern/abc_nurbs.h b/source/blender/alembic/intern/abc_nurbs.h
index 1b2e7a8391f..abe460a8988 100644
--- a/source/blender/alembic/intern/abc_nurbs.h
+++ b/source/blender/alembic/intern/abc_nurbs.h
@@ -54,7 +54,7 @@ public:
bool valid() const;
- void readObjectData(Main *bmain, float time);
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
private:
void getNurbsPatches(const Alembic::Abc::IObject &obj);
diff --git a/source/blender/alembic/intern/abc_object.cc b/source/blender/alembic/intern/abc_object.cc
index a5b8af542fc..ddedcf6dcbc 100644
--- a/source/blender/alembic/intern/abc_object.cc
+++ b/source/blender/alembic/intern/abc_object.cc
@@ -91,7 +91,7 @@ Imath::Box3d AbcObjectWriter::bounds()
if (!bb) {
if (this->m_object->type != OB_CAMERA) {
- std::cerr << "Boundbox is null!\n";
+ ABC_LOG(m_settings.logger) << "Bounding box is null!\n";
}
return Imath::Box3d();
@@ -127,6 +127,7 @@ AbcObjectReader::AbcObjectReader(const IObject &object, ImportSettings &settings
, m_min_time(std::numeric_limits<chrono_t>::max())
, m_max_time(std::numeric_limits<chrono_t>::min())
, m_refcount(0)
+ , parent_reader(NULL)
{
m_name = object.getFullName();
std::vector<std::string> parts;
@@ -139,6 +140,38 @@ AbcObjectReader::AbcObjectReader(const IObject &object, ImportSettings &settings
else {
m_object_name = m_data_name = parts[parts.size() - 1];
}
+
+ determine_inherits_xform();
+}
+
+/* Determine whether we can inherit our parent's XForm */
+void AbcObjectReader::determine_inherits_xform()
+{
+ m_inherits_xform = false;
+
+ IXform ixform = xform();
+ if (!ixform) {
+ return;
+ }
+
+ const IXformSchema & schema(ixform.getSchema());
+ if (!schema.valid()) {
+ std::cerr << "Alembic object " << ixform.getFullName()
+ << " has an invalid schema." << std::endl;
+ return;
+ }
+
+ m_inherits_xform = schema.getInheritsXforms();
+
+ IObject ixform_parent = ixform.getParent();
+ if (!ixform_parent.getParent()) {
+ /* The archive top object certainly is not a transform itself, so handle
+ * it as "no parent". */
+ m_inherits_xform = false;
+ }
+ else {
+ m_inherits_xform = ixform_parent && m_inherits_xform;
+ }
}
AbcObjectReader::~AbcObjectReader()
@@ -214,7 +247,15 @@ Imath::M44d get_matrix(const IXformSchema &schema, const float time)
return s0.getMatrix();
}
-void AbcObjectReader::readObjectMatrix(const float time)
+DerivedMesh *AbcObjectReader::read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &UNUSED(sample_sel),
+ int UNUSED(read_flag),
+ const char **UNUSED(err_str))
+{
+ return dm;
+}
+
+void AbcObjectReader::setupObjectTransform(const float time)
{
bool is_constant = false;
@@ -236,49 +277,67 @@ void AbcObjectReader::readObjectMatrix(const float time)
}
}
-void AbcObjectReader::read_matrix(float mat[4][4], const float time, const float scale, bool &is_constant)
+Alembic::AbcGeom::IXform AbcObjectReader::xform()
{
- IXform ixform;
- bool has_alembic_parent = false;
-
/* Check that we have an empty object (locator, bone head/tail...). */
if (IXform::matches(m_iobject.getMetaData())) {
- ixform = IXform(m_iobject, Alembic::AbcGeom::kWrapExisting);
-
- /* See comment below. */
- has_alembic_parent = m_iobject.getParent().getParent().valid();
+ return IXform(m_iobject, Alembic::AbcGeom::kWrapExisting);
}
- /* Check that we have an object with actual data. */
- else if (IXform::matches(m_iobject.getParent().getMetaData())) {
- ixform = IXform(m_iobject.getParent(), Alembic::AbcGeom::kWrapExisting);
-
- /* This is a bit hackish, but we need to make sure that extra
- * transformations added to the matrix (rotation/scale) are only applied
- * to root objects. The way objects and their hierarchy are created will
- * need to be revisited at some point but for now this seems to do the
- * trick.
- *
- * Explanation of the trick:
- * The first getParent() will return this object's transformation matrix.
- * The second getParent() will get the parent of the transform, but this
- * might be the archive root ('/') which is valid, so we go passed it to
- * make sure that there is no parent.
- */
- has_alembic_parent = m_iobject.getParent().getParent().getParent().valid();
+
+ /* Check that we have an object with actual data, in which case the
+ * parent Alembic object should contain the transform. */
+ IObject abc_parent = m_iobject.getParent();
+
+ /* The archive's top object can be recognised by not having a parent. */
+ if (abc_parent.getParent()
+ && IXform::matches(abc_parent.getMetaData()))
+ {
+ return IXform(abc_parent, Alembic::AbcGeom::kWrapExisting);
}
+
/* Should not happen. */
- else {
+ std::cerr << "AbcObjectReader::xform(): "
+ << "unable to find IXform for Alembic object '"
+ << m_iobject.getFullName() << "'\n";
+ BLI_assert(false);
+
+ return IXform();
+}
+
+void AbcObjectReader::read_matrix(float r_mat[4][4], const float time,
+ const float scale, bool &is_constant)
+{
+ IXform ixform = xform();
+ if (!ixform) {
return;
}
- const IXformSchema &schema(ixform.getSchema());
-
+ const IXformSchema & schema(ixform.getSchema());
if (!schema.valid()) {
+ std::cerr << "Alembic object " << ixform.getFullName()
+ << " has an invalid schema." << std::endl;
return;
}
const Imath::M44d matrix = get_matrix(schema, time);
- convert_matrix(matrix, m_object, mat, scale, has_alembic_parent);
+ convert_matrix(matrix, m_object, r_mat);
+
+ if (m_inherits_xform) {
+ /* In this case, the matrix in Alembic is in local coordinates, so
+ * convert to world matrix. To prevent us from reading and accumulating
+ * all parent matrices in the Alembic file, we assume that the Blender
+ * parent object is already updated for the current timekey, and use its
+ * world matrix. */
+ BLI_assert(m_object->parent);
+ mul_m4_m4m4(r_mat, m_object->parent->obmat, r_mat);
+ }
+ else {
+ /* Only apply scaling to root objects, parenting will propagate it. */
+ float scale_mat[4][4];
+ scale_m4_fl(scale_mat, scale);
+ scale_mat[3][3] = scale; /* scale translations too */
+ mul_m4_m4m4(r_mat, r_mat, scale_mat);
+ }
is_constant = schema.isConstant();
}
@@ -322,4 +381,5 @@ void AbcObjectReader::incref()
void AbcObjectReader::decref()
{
--m_refcount;
+ BLI_assert(m_refcount >= 0);
}
diff --git a/source/blender/alembic/intern/abc_object.h b/source/blender/alembic/intern/abc_object.h
index 0f733e67d3f..852ef451f23 100644
--- a/source/blender/alembic/intern/abc_object.h
+++ b/source/blender/alembic/intern/abc_object.h
@@ -90,7 +90,7 @@ struct ImportSettings {
/* Length and frame offset of file sequences. */
int sequence_len;
- int offset;
+ int sequence_offset;
/* From MeshSeqCacheModifierData.read_flag */
int read_flag;
@@ -107,7 +107,7 @@ struct ImportSettings {
, is_sequence(false)
, set_frame_range(false)
, sequence_len(1)
- , offset(0)
+ , sequence_offset(0)
, read_flag(0)
, validate_meshes(false)
, cache_file(NULL)
@@ -117,15 +117,7 @@ struct ImportSettings {
template <typename Schema>
static bool has_animations(Schema &schema, ImportSettings *settings)
{
- if (settings->is_sequence) {
- return true;
- }
-
- if (!schema.isConstant()) {
- return true;
- }
-
- return false;
+ return settings->is_sequence || !schema.isConstant();
}
/* ************************************************************************** */
@@ -151,6 +143,11 @@ protected:
* modifiers and/or constraints. */
int m_refcount;
+ bool m_inherits_xform;
+
+public:
+ AbcObjectReader *parent_reader;
+
public:
explicit AbcObjectReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
@@ -158,22 +155,36 @@ public:
const Alembic::Abc::IObject &iobject() const;
+ typedef std::vector<AbcObjectReader *> ptr_vector;
+
+ /**
+ * Returns the transform of this object. This can be the Alembic object
+ * itself (in case of an Empty) or it can be the parent Alembic object.
+ */
+ virtual Alembic::AbcGeom::IXform xform();
+
Object *object() const;
void object(Object *ob);
+ const std::string & name() const { return m_name; }
+ const std::string & object_name() const { return m_object_name; }
+ const std::string & data_name() const { return m_data_name; }
+ bool inherits_xform() const { return m_inherits_xform; }
+
virtual bool valid() const = 0;
+ virtual bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const = 0;
- virtual void readObjectData(Main *bmain, float time) = 0;
+ virtual void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel) = 0;
- virtual DerivedMesh *read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str)
- {
- (void)time;
- (void)read_flag;
- (void)err_str;
- return dm;
- }
+ virtual DerivedMesh *read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str);
- void readObjectMatrix(const float time);
+ /** Reads the object matrix and sets up an object transform if animated. */
+ void setupObjectTransform(const float time);
void addCacheModifier();
@@ -184,7 +195,11 @@ public:
void incref();
void decref();
- void read_matrix(float mat[4][4], const float time, const float scale, bool &is_constant);
+ void read_matrix(float r_mat[4][4], const float time,
+ const float scale, bool &is_constant);
+
+protected:
+ void determine_inherits_xform();
};
Imath::M44d get_matrix(const Alembic::AbcGeom::IXformSchema &schema, const float time);
diff --git a/source/blender/alembic/intern/abc_points.cc b/source/blender/alembic/intern/abc_points.cc
index fc84759b1d9..80567cd6bf0 100644
--- a/source/blender/alembic/intern/abc_points.cc
+++ b/source/blender/alembic/intern/abc_points.cc
@@ -151,12 +151,29 @@ bool AbcPointsReader::valid() const
return m_schema.valid();
}
-void AbcPointsReader::readObjectData(Main *bmain, float time)
+bool AbcPointsReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::IPoints::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to Points when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_MESH) {
+ *err_str = "Object type mismatch, Alembic object path points to Points.";
+ return false;
+ }
+
+ return true;
+}
+
+void AbcPointsReader::readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel)
{
Mesh *mesh = BKE_mesh_add(bmain, m_data_name.c_str());
DerivedMesh *dm = CDDM_from_mesh(mesh);
- DerivedMesh *ndm = this->read_derivedmesh(dm, time, 0, NULL);
+ DerivedMesh *ndm = this->read_derivedmesh(dm, sample_sel, 0, NULL);
if (ndm != dm) {
dm->release(dm);
@@ -178,8 +195,7 @@ void AbcPointsReader::readObjectData(Main *bmain, float time)
void read_points_sample(const IPointsSchema &schema,
const ISampleSelector &selector,
- CDStreamConfig &config,
- float time)
+ CDStreamConfig &config)
{
Alembic::AbcGeom::IPointsSchema::Sample sample = schema.getValue(selector);
@@ -189,7 +205,7 @@ void read_points_sample(const IPointsSchema &schema,
N3fArraySamplePtr vnormals;
if (has_property(prop, "N")) {
- const Alembic::Util::uint32_t itime = static_cast<Alembic::Util::uint32_t>(time);
+ const Alembic::Util::uint32_t itime = static_cast<Alembic::Util::uint32_t>(selector.getRequestedTime());
const IN3fArrayProperty &normals_prop = IN3fArrayProperty(prop, "N", itime);
if (normals_prop) {
@@ -200,9 +216,11 @@ void read_points_sample(const IPointsSchema &schema,
read_mverts(config.mvert, positions, vnormals);
}
-DerivedMesh *AbcPointsReader::read_derivedmesh(DerivedMesh *dm, const float time, int /*read_flag*/, const char ** /*err_str*/)
+DerivedMesh *AbcPointsReader::read_derivedmesh(DerivedMesh *dm,
+ const ISampleSelector &sample_sel,
+ int /*read_flag*/,
+ const char ** /*err_str*/)
{
- ISampleSelector sample_sel(time);
const IPointsSchema::Sample sample = m_schema.getValue(sample_sel);
const P3fArraySamplePtr &positions = sample.getPositions();
@@ -214,7 +232,7 @@ DerivedMesh *AbcPointsReader::read_derivedmesh(DerivedMesh *dm, const float time
}
CDStreamConfig config = get_config(new_dm ? new_dm : dm);
- read_points_sample(m_schema, sample_sel, config, time);
+ read_points_sample(m_schema, sample_sel, config);
return new_dm ? new_dm : dm;
}
diff --git a/source/blender/alembic/intern/abc_points.h b/source/blender/alembic/intern/abc_points.h
index cb68dbca4d5..369a802d763 100644
--- a/source/blender/alembic/intern/abc_points.h
+++ b/source/blender/alembic/intern/abc_points.h
@@ -58,15 +58,20 @@ public:
AbcPointsReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
- void readObjectData(Main *bmain, float time);
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
- DerivedMesh *read_derivedmesh(DerivedMesh *dm, const float time, int read_flag, const char **err_str);
+ DerivedMesh *read_derivedmesh(DerivedMesh *dm,
+ const Alembic::Abc::ISampleSelector &sample_sel,
+ int read_flag,
+ const char **err_str);
};
void read_points_sample(const Alembic::AbcGeom::IPointsSchema &schema,
const Alembic::AbcGeom::ISampleSelector &selector,
- CDStreamConfig &config,
- float time);
+ CDStreamConfig &config);
#endif /* __ABC_POINTS_H__ */
diff --git a/source/blender/alembic/intern/abc_transform.cc b/source/blender/alembic/intern/abc_transform.cc
index 2c6ef09326c..5392387663f 100644
--- a/source/blender/alembic/intern/abc_transform.cc
+++ b/source/blender/alembic/intern/abc_transform.cc
@@ -36,6 +36,7 @@ extern "C" {
using Alembic::AbcGeom::OObject;
using Alembic::AbcGeom::OXform;
+using Alembic::Abc::ISampleSelector;
/* ************************************************************************** */
@@ -62,9 +63,9 @@ AbcTransformWriter::AbcTransformWriter(Object *ob,
unsigned int time_sampling,
ExportSettings &settings)
: AbcObjectWriter(NULL, ob, time_sampling, settings, parent)
+ , m_proxy_from(NULL)
{
m_is_animated = hasAnimation(m_object);
- m_parent = NULL;
if (!m_is_animated) {
time_sampling = 0;
@@ -72,6 +73,9 @@ AbcTransformWriter::AbcTransformWriter(Object *ob,
m_xform = OXform(abc_parent, get_id_name(m_object), time_sampling);
m_schema = m_xform.getSchema();
+
+ /* Blender objects can't have a parent without inheriting the transform. */
+ m_inherits_xform = parent != NULL;
}
void AbcTransformWriter::do_write()
@@ -86,27 +90,30 @@ void AbcTransformWriter::do_write()
return;
}
- float mat[4][4];
- create_transform_matrix(m_object, mat);
+ float yup_mat[4][4];
+ create_transform_matrix(m_object, yup_mat,
+ m_inherits_xform ? ABC_MATRIX_LOCAL : ABC_MATRIX_WORLD,
+ m_proxy_from);
/* Only apply rotation to root camera, parenting will propagate it. */
- if (m_object->type == OB_CAMERA && !has_parent_camera(m_object)) {
+ if (m_object->type == OB_CAMERA && (!m_inherits_xform || !has_parent_camera(m_object))) {
float rot_mat[4][4];
axis_angle_to_mat4_single(rot_mat, 'X', -M_PI_2);
- mul_m4_m4m4(mat, mat, rot_mat);
+ mul_m4_m4m4(yup_mat, yup_mat, rot_mat);
}
- if (!m_object->parent) {
+ if (!m_object->parent || !m_inherits_xform) {
/* Only apply scaling to root objects, parenting will propagate it. */
float scale_mat[4][4];
scale_m4_fl(scale_mat, m_settings.global_scale);
- mul_m4_m4m4(mat, mat, scale_mat);
- mul_v3_fl(mat[3], m_settings.global_scale);
+ scale_mat[3][3] = m_settings.global_scale; /* also scale translation */
+ mul_m4_m4m4(yup_mat, yup_mat, scale_mat);
+ yup_mat[3][3] /= m_settings.global_scale; /* normalise the homogeneous component */
}
- m_matrix = convert_matrix(mat);
-
+ m_matrix = convert_matrix(yup_mat);
m_sample.setMatrix(m_matrix);
+ m_sample.setInheritsXforms(m_inherits_xform);
m_schema.set(m_sample);
}
@@ -133,6 +140,10 @@ bool AbcTransformWriter::hasAnimation(Object * /*ob*/) const
AbcEmptyReader::AbcEmptyReader(const Alembic::Abc::IObject &object, ImportSettings &settings)
: AbcObjectReader(object, settings)
{
+ /* Empties have no data. It makes the import of Alembic files easier to
+ * understand when we name the empty after its name in Alembic. */
+ m_object_name = object.getName();
+
Alembic::AbcGeom::IXform xform(object, Alembic::AbcGeom::kWrapExisting);
m_schema = xform.getSchema();
@@ -144,8 +155,26 @@ bool AbcEmptyReader::valid() const
return m_schema.valid();
}
-void AbcEmptyReader::readObjectData(Main *bmain, float /*time*/)
+bool AbcEmptyReader::accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const
+{
+ if (!Alembic::AbcGeom::IXform::matches(alembic_header)) {
+ *err_str = "Object type mismatch, Alembic object path pointed to XForm when importing, but not any more.";
+ return false;
+ }
+
+ if (ob->type != OB_EMPTY) {
+ *err_str = "Object type mismatch, Alembic object path points to XForm.";
+ return false;
+ }
+
+ return true;
+}
+
+void AbcEmptyReader::readObjectData(Main *bmain, const ISampleSelector &UNUSED(sample_sel))
{
- m_object = BKE_object_add_only_object(bmain, OB_EMPTY, m_data_name.c_str());
+ m_object = BKE_object_add_only_object(bmain, OB_EMPTY,
+ m_object_name.c_str());
m_object->data = NULL;
}
diff --git a/source/blender/alembic/intern/abc_transform.h b/source/blender/alembic/intern/abc_transform.h
index 6a3aae216f2..753a4247e9f 100644
--- a/source/blender/alembic/intern/abc_transform.h
+++ b/source/blender/alembic/intern/abc_transform.h
@@ -37,8 +37,11 @@ class AbcTransformWriter : public AbcObjectWriter {
Alembic::Abc::M44d m_matrix;
bool m_is_animated;
- Object *m_parent;
bool m_visible;
+ bool m_inherits_xform;
+
+public:
+ Object *m_proxy_from;
public:
AbcTransformWriter(Object *ob,
@@ -49,7 +52,6 @@ public:
Alembic::AbcGeom::OXform &alembicXform() { return m_xform;}
virtual Imath::Box3d bounds();
- void setParent(Object *p) { m_parent = p; }
private:
virtual void do_write();
@@ -66,8 +68,11 @@ public:
AbcEmptyReader(const Alembic::Abc::IObject &object, ImportSettings &settings);
bool valid() const;
+ bool accepts_object_type(const Alembic::AbcCoreAbstract::ObjectHeader &alembic_header,
+ const Object *const ob,
+ const char **err_str) const;
- void readObjectData(Main *bmain, float time);
+ void readObjectData(Main *bmain, const Alembic::Abc::ISampleSelector &sample_sel);
};
#endif /* __ABC_TRANSFORM_H__ */
diff --git a/source/blender/alembic/intern/abc_util.cc b/source/blender/alembic/intern/abc_util.cc
index 08c94f437e6..24a508e8292 100644
--- a/source/blender/alembic/intern/abc_util.cc
+++ b/source/blender/alembic/intern/abc_util.cc
@@ -37,9 +37,11 @@ extern "C" {
#include "DNA_object_types.h"
#include "BLI_math.h"
+
+#include "PIL_time.h"
}
-std::string get_id_name(Object *ob)
+std::string get_id_name(const Object * const ob)
{
if (!ob) {
return "";
@@ -48,7 +50,7 @@ std::string get_id_name(Object *ob)
return get_id_name(&ob->id);
}
-std::string get_id_name(ID *id)
+std::string get_id_name(const ID * const id)
{
std::string name(id->name + 2);
std::replace(name.begin(), name.end(), ' ', '_');
@@ -58,7 +60,7 @@ std::string get_id_name(ID *id)
return name;
}
-std::string get_object_dag_path_name(Object *ob, Object *dupli_parent)
+std::string get_object_dag_path_name(const Object * const ob, Object *dupli_parent)
{
std::string name = get_id_name(ob);
@@ -130,15 +132,28 @@ void split(const std::string &s, const char delim, std::vector<std::string> &tok
}
}
-/* Create a rotation matrix for each axis from euler angles.
- * Euler angles are swaped to change coordinate system. */
-static void create_rotation_matrix(
+void create_swapped_rotation_matrix(
float rot_x_mat[3][3], float rot_y_mat[3][3],
- float rot_z_mat[3][3], const float euler[3], const bool to_yup)
+ float rot_z_mat[3][3], const float euler[3],
+ AbcAxisSwapMode mode)
{
const float rx = euler[0];
- const float ry = (to_yup) ? euler[2] : -euler[2];
- const float rz = (to_yup) ? -euler[1] : euler[1];
+ float ry;
+ float rz;
+
+ /* Apply transformation */
+ switch (mode) {
+ case ABC_ZUP_FROM_YUP:
+ ry = -euler[2];
+ rz = euler[1];
+ break;
+ case ABC_YUP_FROM_ZUP:
+ ry = euler[2];
+ rz = -euler[1];
+ break;
+ default:
+ BLI_assert(false);
+ }
unit_m3(rot_x_mat);
unit_m3(rot_y_mat);
@@ -160,58 +175,70 @@ static void create_rotation_matrix(
rot_z_mat[1][1] = cos(rz);
}
-/* Recompute transform matrix of object in new coordinate system
- * (from Y-Up to Z-Up). */
-void create_transform_matrix(float r_mat[4][4])
+/* Convert matrix from Z=up to Y=up or vice versa. Use yup_mat = zup_mat for in-place conversion. */
+void copy_m44_axis_swap(float dst_mat[4][4], float src_mat[4][4], AbcAxisSwapMode mode)
{
- float rot_mat[3][3], rot[3][3], scale_mat[4][4], invmat[4][4], transform_mat[4][4];
+ float dst_rot[3][3], src_rot[3][3], dst_scale_mat[4][4];
float rot_x_mat[3][3], rot_y_mat[3][3], rot_z_mat[3][3];
- float loc[3], scale[3], euler[3];
+ float src_trans[3], dst_scale[3], src_scale[3], euler[3];
- zero_v3(loc);
- zero_v3(scale);
+ zero_v3(src_trans);
+ zero_v3(dst_scale);
+ zero_v3(src_scale);
zero_v3(euler);
- unit_m3(rot);
- unit_m3(rot_mat);
- unit_m4(scale_mat);
- unit_m4(transform_mat);
- unit_m4(invmat);
+ unit_m3(src_rot);
+ unit_m3(dst_rot);
+ unit_m4(dst_scale_mat);
- /* Compute rotation matrix. */
+ /* We assume there is no sheer component and no homogeneous scaling component. */
+ BLI_assert(fabs(src_mat[0][3]) < 2 * FLT_EPSILON);
+ BLI_assert(fabs(src_mat[1][3]) < 2 * FLT_EPSILON);
+ BLI_assert(fabs(src_mat[2][3]) < 2 * FLT_EPSILON);
+ BLI_assert(fabs(src_mat[3][3] - 1.0f) < 2 * FLT_EPSILON);
- /* Extract location, rotation, and scale from matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, r_mat);
+ /* Extract translation, rotation, and scale form matrix. */
+ mat4_to_loc_rot_size(src_trans, src_rot, src_scale, src_mat);
/* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_XYZ, rot);
+ mat3_to_eulO(euler, ROT_MODE_XZY, src_rot);
/* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, false);
+ create_swapped_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, mode);
/* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
+ mul_m3_m3m3(dst_rot, dst_rot, rot_z_mat);
+ mul_m3_m3m3(dst_rot, dst_rot, rot_y_mat);
+ mul_m3_m3m3(dst_rot, dst_rot, rot_x_mat);
- /* Add rotation matrix to transformation matrix. */
- copy_m4_m3(transform_mat, rot_mat);
+ mat3_to_eulO(euler, ROT_MODE_XZY, dst_rot);
- /* Add translation to transformation matrix. */
- copy_zup_from_yup(transform_mat[3], loc);
+ /* Start construction of dst_mat from rotation matrix */
+ unit_m4(dst_mat);
+ copy_m4_m3(dst_mat, dst_rot);
- /* Create scale matrix. */
- scale_mat[0][0] = scale[0];
- scale_mat[1][1] = scale[2];
- scale_mat[2][2] = scale[1];
+ /* Apply translation */
+ switch (mode) {
+ case ABC_ZUP_FROM_YUP:
+ copy_zup_from_yup(dst_mat[3], src_trans);
+ break;
+ case ABC_YUP_FROM_ZUP:
+ copy_yup_from_zup(dst_mat[3], src_trans);
+ break;
+ default:
+ BLI_assert(false);
+ }
- /* Add scale to transformation matrix. */
- mul_m4_m4m4(transform_mat, transform_mat, scale_mat);
+ /* Apply scale matrix. Swaps y and z, but does not
+ * negate like translation does. */
+ dst_scale[0] = src_scale[0];
+ dst_scale[1] = src_scale[2];
+ dst_scale[2] = src_scale[1];
- copy_m4_m4(r_mat, transform_mat);
+ size_to_mat4(dst_scale_mat, dst_scale);
+ mul_m4_m4m4(dst_mat, dst_mat, dst_scale_mat);
}
-void convert_matrix(const Imath::M44d &xform, Object *ob,
- float r_mat[4][4], float scale, bool has_alembic_parent)
+void convert_matrix(const Imath::M44d &xform, Object *ob, float r_mat[4][4])
{
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
@@ -225,207 +252,32 @@ void convert_matrix(const Imath::M44d &xform, Object *ob,
mul_m4_m4m4(r_mat, r_mat, cam_to_yup);
}
- create_transform_matrix(r_mat);
-
- if (ob->parent) {
- mul_m4_m4m4(r_mat, ob->parent->obmat, r_mat);
- }
- /* TODO(kevin) */
- else if (!has_alembic_parent) {
- /* Only apply scaling to root objects, parenting will propagate it. */
- float scale_mat[4][4];
- scale_m4_fl(scale_mat, scale);
- mul_m4_m4m4(r_mat, r_mat, scale_mat);
- mul_v3_fl(r_mat[3], scale);
- }
+ copy_m44_axis_swap(r_mat, r_mat, ABC_ZUP_FROM_YUP);
}
-/* Recompute transform matrix of object in new coordinate system (from Z-Up to Y-Up). */
-void create_transform_matrix(Object *obj, float transform_mat[4][4])
+/* Recompute transform matrix of object in new coordinate system
+ * (from Z-Up to Y-Up). */
+void create_transform_matrix(Object *obj, float r_yup_mat[4][4], AbcMatrixMode mode,
+ Object *proxy_from)
{
- float rot_mat[3][3], rot[3][3], scale_mat[4][4], invmat[4][4], mat[4][4];
- float rot_x_mat[3][3], rot_y_mat[3][3], rot_z_mat[3][3];
- float loc[3], scale[3], euler[3];
-
- zero_v3(loc);
- zero_v3(scale);
- zero_v3(euler);
- unit_m3(rot);
- unit_m3(rot_mat);
- unit_m4(scale_mat);
- unit_m4(transform_mat);
- unit_m4(invmat);
- unit_m4(mat);
-
- /* get local matrix. */
- if (obj->parent) {
- invert_m4_m4(invmat, obj->parent->obmat);
- mul_m4_m4m4(mat, invmat, obj->obmat);
+ float zup_mat[4][4];
+
+ /* get local or world matrix. */
+ if (mode == ABC_MATRIX_LOCAL && obj->parent) {
+ /* Note that this produces another matrix than the local matrix, due to
+ * constraints and modifiers as well as the obj->parentinv matrix. */
+ invert_m4_m4(obj->parent->imat, obj->parent->obmat);
+ mul_m4_m4m4(zup_mat, obj->parent->imat, obj->obmat);
}
else {
- copy_m4_m4(mat, obj->obmat);
+ copy_m4_m4(zup_mat, obj->obmat);
}
- /* Compute rotation matrix. */
- switch (obj->rotmode) {
- case ROT_MODE_AXISANGLE:
- {
- /* Get euler angles from axis angle rotation. */
- axis_angle_to_eulO(euler, ROT_MODE_XYZ, obj->rotAxis, obj->rotAngle);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
-
- /* Extract location and scale from matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- break;
- }
- case ROT_MODE_QUAT:
- {
- float q[4];
- copy_v4_v4(q, obj->quat);
-
- /* Swap axis. */
- q[2] = obj->quat[3];
- q[3] = -obj->quat[2];
-
- /* Compute rotation matrix from quaternion. */
- quat_to_mat3(rot_mat, q);
-
- /* Extract location and scale from matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- break;
- }
- case ROT_MODE_XYZ:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_XYZ, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
-
- break;
- }
- case ROT_MODE_XZY:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_XZY, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
-
- break;
- }
- case ROT_MODE_YXZ:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_YXZ, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
-
- break;
- }
- case ROT_MODE_YZX:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_YZX, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
-
- break;
- }
- case ROT_MODE_ZXY:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_ZXY, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
-
- break;
- }
- case ROT_MODE_ZYX:
- {
- /* Extract location, rotation, and scale form matrix. */
- mat4_to_loc_rot_size(loc, rot, scale, mat);
-
- /* Get euler angles from rotation matrix. */
- mat3_to_eulO(euler, ROT_MODE_ZYX, rot);
-
- /* Create X, Y, Z rotation matrices from euler angles. */
- create_rotation_matrix(rot_x_mat, rot_y_mat, rot_z_mat, euler, true);
-
- /* Concatenate rotation matrices. */
- mul_m3_m3m3(rot_mat, rot_mat, rot_x_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_z_mat);
- mul_m3_m3m3(rot_mat, rot_mat, rot_y_mat);
-
- break;
- }
+ if (proxy_from) {
+ mul_m4_m4m4(zup_mat, proxy_from->obmat, zup_mat);
}
- /* Add rotation matrix to transformation matrix. */
- copy_m4_m3(transform_mat, rot_mat);
-
- /* Add translation to transformation matrix. */
- copy_yup_from_zup(transform_mat[3], loc);
-
- /* Create scale matrix. */
- scale_mat[0][0] = scale[0];
- scale_mat[1][1] = scale[2];
- scale_mat[2][2] = scale[1];
-
- /* Add scale to transformation matrix. */
- mul_m4_m4m4(transform_mat, transform_mat, scale_mat);
+ copy_m44_axis_swap(r_yup_mat, zup_mat, ABC_YUP_FROM_ZUP);
}
bool has_property(const Alembic::Abc::ICompoundProperty &prop, const std::string &name)
@@ -518,8 +370,52 @@ AbcObjectReader *create_reader(const Alembic::AbcGeom::IObject &object, ImportSe
reader = new AbcCurveReader(object, settings);
}
else {
- assert(false);
+ std::cerr << "Alembic: unknown how to handle objects of schema '"
+ << md.get("schemaObjTitle")
+ << "', skipping object '"
+ << object.getFullName() << "'" << std::endl;
}
return reader;
}
+
+/* ********************** */
+
+ScopeTimer::ScopeTimer(const char *message)
+ : m_message(message)
+ , m_start(PIL_check_seconds_timer())
+{}
+
+ScopeTimer::~ScopeTimer()
+{
+ fprintf(stderr, "%s: %fs\n", m_message, PIL_check_seconds_timer() - m_start);
+}
+
+/* ********************** */
+
+bool SimpleLogger::empty()
+{
+ return ((size_t)m_stream.tellp()) == 0ul;
+}
+
+std::string SimpleLogger::str() const
+{
+ return m_stream.str();
+}
+
+void SimpleLogger::clear()
+{
+ m_stream.clear();
+ m_stream.str("");
+}
+
+std::ostringstream &SimpleLogger::stream()
+{
+ return m_stream;
+}
+
+std::ostream &operator<<(std::ostream &os, const SimpleLogger &logger)
+{
+ os << logger.str();
+ return os;
+}
diff --git a/source/blender/alembic/intern/abc_util.h b/source/blender/alembic/intern/abc_util.h
index a7ac9df91c7..2526958111a 100644
--- a/source/blender/alembic/intern/abc_util.h
+++ b/source/blender/alembic/intern/abc_util.h
@@ -32,6 +32,11 @@
# define ABC_INLINE static inline
#endif
+/**
+ * \brief The CacheReader struct is only used for anonymous pointers,
+ * to interface between C and C++ code. This library only creates
+ * pointers to AbcObjectReader (or subclasses thereof).
+ */
struct CacheReader {
int unused;
};
@@ -44,16 +49,21 @@ struct ImportSettings;
struct ID;
struct Object;
-std::string get_id_name(ID *id);
-std::string get_id_name(Object *ob);
-std::string get_object_dag_path_name(Object *ob, Object *dupli_parent);
+std::string get_id_name(const ID * const id);
+std::string get_id_name(const Object * const ob);
+std::string get_object_dag_path_name(const Object * const ob, Object *dupli_parent);
bool object_selected(Object *ob);
bool parent_selected(Object *ob);
Imath::M44d convert_matrix(float mat[4][4]);
-void create_transform_matrix(float r_mat[4][4]);
-void create_transform_matrix(Object *obj, float transform_mat[4][4]);
+
+typedef enum {
+ ABC_MATRIX_WORLD = 1,
+ ABC_MATRIX_LOCAL = 2,
+} AbcMatrixMode;
+void create_transform_matrix(Object *obj, float r_transform_mat[4][4],
+ AbcMatrixMode mode, Object *proxy_from);
void split(const std::string &s, const char delim, std::vector<std::string> &tokens);
@@ -64,8 +74,7 @@ bool begins_with(const TContainer &input, const TContainer &match)
&& std::equal(match.begin(), match.end(), input.begin());
}
-void convert_matrix(const Imath::M44d &xform, Object *ob,
- float r_mat[4][4], float scale, bool has_alembic_parent = false);
+void convert_matrix(const Imath::M44d &xform, Object *ob, float r_mat[4][4]);
template <typename Schema>
void get_min_max_time_ex(const Schema &schema, chrono_t &min, chrono_t &max)
@@ -118,32 +127,115 @@ AbcObjectReader *create_reader(const Alembic::AbcGeom::IObject &object, ImportSe
ABC_INLINE void copy_zup_from_yup(float zup[3], const float yup[3])
{
+ const float old_yup1 = yup[1]; /* in case zup == yup */
zup[0] = yup[0];
zup[1] = -yup[2];
- zup[2] = yup[1];
+ zup[2] = old_yup1;
}
ABC_INLINE void copy_zup_from_yup(short zup[3], const short yup[3])
{
+ const short old_yup1 = yup[1]; /* in case zup == yup */
zup[0] = yup[0];
zup[1] = -yup[2];
- zup[2] = yup[1];
+ zup[2] = old_yup1;
}
/* Copy from Z-up to Y-up. */
ABC_INLINE void copy_yup_from_zup(float yup[3], const float zup[3])
{
+ const float old_zup1 = zup[1]; /* in case yup == zup */
yup[0] = zup[0];
yup[1] = zup[2];
- yup[2] = -zup[1];
+ yup[2] = -old_zup1;
}
ABC_INLINE void copy_yup_from_zup(short yup[3], const short zup[3])
{
+ const short old_zup1 = zup[1]; /* in case yup == zup */
yup[0] = zup[0];
yup[1] = zup[2];
- yup[2] = -zup[1];
+ yup[2] = -old_zup1;
}
+/* Names are given in (dst, src) order, just like
+ * the parameters of copy_m44_axis_swap() */
+typedef enum {
+ ABC_ZUP_FROM_YUP = 1,
+ ABC_YUP_FROM_ZUP = 2,
+} AbcAxisSwapMode;
+
+/* Create a rotation matrix for each axis from euler angles.
+ * Euler angles are swaped to change coordinate system. */
+void create_swapped_rotation_matrix(
+ float rot_x_mat[3][3], float rot_y_mat[3][3],
+ float rot_z_mat[3][3], const float euler[3],
+ AbcAxisSwapMode mode);
+
+void copy_m44_axis_swap(float dst_mat[4][4], float src_mat[4][4], AbcAxisSwapMode mode);
+
+/* *************************** */
+
+#undef ABC_DEBUG_TIME
+
+class ScopeTimer {
+ const char *m_message;
+ double m_start;
+
+public:
+ ScopeTimer(const char *message);
+ ~ScopeTimer();
+};
+
+#ifdef ABC_DEBUG_TIME
+# define SCOPE_TIMER(message) ScopeTimer prof(message)
+#else
+# define SCOPE_TIMER(message)
+#endif
+
+/* *************************** */
+
+/**
+ * Utility class whose purpose is to more easily log related informations. An
+ * instance of the SimpleLogger can be created in any context, and will hold a
+ * copy of all the strings passed to its output stream.
+ *
+ * Different instances of the class may be accessed from different threads,
+ * although accessing the same instance from different threads will lead to race
+ * conditions.
+ */
+class SimpleLogger {
+ std::ostringstream m_stream;
+
+public:
+ /**
+ * Check whether or not the SimpleLogger's stream is empty.
+ */
+ bool empty();
+
+ /**
+ * Return a copy of the string contained in the SimpleLogger's stream.
+ */
+ std::string str() const;
+
+ /**
+ * Remove the bits set on the SimpleLogger's stream and clear its string.
+ */
+ void clear();
+
+ /**
+ * Return a reference to the SimpleLogger's stream, in order to e.g. push
+ * content into it.
+ */
+ std::ostringstream &stream();
+};
+
+#define ABC_LOG(logger) logger.stream()
+
+/**
+ * Pass the content of the logger's stream to the specified std::ostream.
+ */
+std::ostream &operator<<(std::ostream &os, const SimpleLogger &logger);
+
#endif /* __ABC_UTIL_H__ */
diff --git a/source/blender/alembic/intern/alembic_capi.cc b/source/blender/alembic/intern/alembic_capi.cc
index d8d017119b1..0d2316ce7d9 100644
--- a/source/blender/alembic/intern/alembic_capi.cc
+++ b/source/blender/alembic/intern/alembic_capi.cc
@@ -21,6 +21,7 @@
*/
#include "../ABC_alembic.h"
+#include <boost/foreach.hpp>
#include <Alembic/AbcMaterial/IMaterial.h>
@@ -120,91 +121,62 @@ ABC_INLINE AbcArchiveHandle *handle_from_archive(ArchiveReader *archive)
/* NOTE: this function is similar to visit_objects below, need to keep them in
* sync. */
-static void gather_objects_paths(const IObject &object, ListBase *object_paths)
+static bool gather_objects_paths(const IObject &object, ListBase *object_paths)
{
if (!object.valid()) {
- return;
+ return false;
}
- for (int i = 0; i < object.getNumChildren(); ++i) {
- IObject child = object.getChild(i);
- if (!child.valid()) {
- continue;
- }
+ size_t children_claiming_this_object = 0;
+ size_t num_children = object.getNumChildren();
- bool get_path = false;
+ for (size_t i = 0; i < num_children; ++i) {
+ bool child_claims_this_object = gather_objects_paths(object.getChild(i), object_paths);
+ children_claiming_this_object += child_claims_this_object ? 1 : 0;
+ }
- const MetaData &md = child.getMetaData();
+ const MetaData &md = object.getMetaData();
+ bool get_path = false;
+ bool parent_is_part_of_this_object = false;
- if (IXform::matches(md)) {
- /* Check whether or not this object is a Maya locator, which is
- * similar to empties used as parent object in Blender. */
- if (has_property(child.getProperties(), "locator")) {
- get_path = true;
- }
- else {
- /* Avoid creating an empty object if the child of this transform
- * is not a transform (that is an empty). */
- if (child.getNumChildren() == 1) {
- if (IXform::matches(child.getChild(0).getMetaData())) {
- get_path = true;
- }
-#if 0
- else {
- std::cerr << "Skipping " << child.getFullName() << '\n';
- }
-#endif
- }
- else {
- get_path = true;
- }
- }
- }
- else if (IPolyMesh::matches(md)) {
- get_path = true;
- }
- else if (ISubD::matches(md)) {
- get_path = true;
- }
- else if (INuPatch::matches(md)) {
-#ifdef USE_NURBS
- get_path = true;
-#endif
- }
- else if (ICamera::matches(md)) {
- get_path = true;
- }
- else if (IPoints::matches(md)) {
- get_path = true;
- }
- else if (IMaterial::matches(md)) {
- /* Pass for now. */
- }
- else if (ILight::matches(md)) {
- /* Pass for now. */
- }
- else if (IFaceSet::matches(md)) {
- /* Pass, those are handled in the mesh reader. */
- }
- else if (ICurves::matches(md)) {
+ if (!object.getParent()) {
+ /* The root itself is not an object we should import. */
+ }
+ else if (IXform::matches(md)) {
+ if (has_property(object.getProperties(), "locator")) {
get_path = true;
}
else {
- assert(false);
+ get_path = children_claiming_this_object == 0;
}
- if (get_path) {
- AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
- MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
-
- BLI_strncpy(abc_path->path, child.getFullName().c_str(), PATH_MAX);
+ /* Transforms are never "data" for their parent. */
+ parent_is_part_of_this_object = false;
+ }
+ else {
+ /* These types are "data" for their parent. */
+ get_path =
+ IPolyMesh::matches(md) ||
+ ISubD::matches(md) ||
+#ifdef USE_NURBS
+ INuPatch::matches(md) ||
+#endif
+ ICamera::matches(md) ||
+ IPoints::matches(md) ||
+ ICurves::matches(md);
+ parent_is_part_of_this_object = get_path;
+ }
- BLI_addtail(object_paths, abc_path);
- }
+ if (get_path) {
+ void *abc_path_void = MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath");
+ AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(abc_path_void);
- gather_objects_paths(child, object_paths);
+ BLI_strncpy(abc_path->path, object.getFullName().c_str(), sizeof(abc_path->path));
+ BLI_addtail(object_paths, abc_path);
}
+
+ return parent_is_part_of_this_object;
}
AbcArchiveHandle *ABC_create_handle(const char *filename, ListBase *object_paths)
@@ -266,6 +238,7 @@ struct ExportJobData {
float *progress;
bool was_canceled;
+ bool export_ok;
};
static void export_startjob(void *customdata, short *stop, short *do_update, float *progress)
@@ -286,7 +259,7 @@ static void export_startjob(void *customdata, short *stop, short *do_update, flo
try {
Scene *scene = data->scene;
- AbcExporter exporter(scene, data->filename, data->settings);
+ AbcExporter exporter(data->bmain, scene, data->filename, data->settings);
const int orig_frame = CFRA;
@@ -299,12 +272,14 @@ static void export_startjob(void *customdata, short *stop, short *do_update, flo
BKE_scene_update_for_newframe(data->bmain->eval_ctx, data->bmain,
scene, scene->lay);
}
+
+ data->export_ok = !data->was_canceled;
}
catch (const std::exception &e) {
- std::cerr << "Abc Export error: " << e.what() << '\n';
+ ABC_LOG(data->settings.logger) << "Abc Export error: " << e.what() << '\n';
}
catch (...) {
- std::cerr << "Abc Export error\n";
+ ABC_LOG(data->settings.logger) << "Abc Export: unknown error...\n";
}
}
@@ -316,26 +291,49 @@ static void export_endjob(void *customdata)
BLI_delete(data->filename, false, false);
}
+ if (!data->settings.logger.empty()) {
+ std::cerr << data->settings.logger;
+ WM_report(RPT_ERROR, "Errors occured during the export, look in the console to know more...");
+ }
+
G.is_rendering = false;
BKE_spacedata_draw_locks(false);
}
-void ABC_export(
+bool ABC_export(
Scene *scene,
bContext *C,
const char *filepath,
- const struct AlembicExportParams *params)
+ const struct AlembicExportParams *params,
+ bool as_background_job)
{
ExportJobData *job = static_cast<ExportJobData *>(MEM_mallocN(sizeof(ExportJobData), "ExportJobData"));
job->scene = scene;
job->bmain = CTX_data_main(C);
+ job->export_ok = false;
BLI_strncpy(job->filename, filepath, 1024);
+ /* Alright, alright, alright....
+ *
+ * ExportJobData contains an ExportSettings containing a SimpleLogger.
+ *
+ * Since ExportJobData is a C-style struct dynamically allocated with
+ * MEM_mallocN (see above), its construtor is never called, therefore the
+ * ExportSettings constructor is not called which implies that the
+ * SimpleLogger one is not called either. SimpleLogger in turn does not call
+ * the constructor of its data members which ultimately means that its
+ * std::ostringstream member has a NULL pointer. To be able to properly use
+ * the stream's operator<<, the pointer needs to be set, therefore we have
+ * to properly construct everything. And this is done using the placement
+ * new operator as here below. It seems hackish, but I'm too lazy to
+ * do bigger refactor and maybe there is a better way which does not involve
+ * hardcore refactoring. */
+ new (&job->settings) ExportSettings();
job->settings.scene = job->scene;
job->settings.frame_start = params->frame_start;
job->settings.frame_end = params->frame_end;
- job->settings.frame_step_xform = params->frame_step_xform;
- job->settings.frame_step_shape = params->frame_step_shape;
+ job->settings.frame_samples_xform = params->frame_samples_xform;
+ job->settings.frame_samples_shape = params->frame_samples_shape;
job->settings.shutter_open = params->shutter_open;
job->settings.shutter_close = params->shutter_close;
job->settings.selected_only = params->selected_only;
@@ -343,6 +341,8 @@ void ABC_export(
job->settings.export_normals = params->normals;
job->settings.export_uvs = params->uvs;
job->settings.export_vcols = params->vcolors;
+ job->settings.export_hair = params->export_hair;
+ job->settings.export_particles = params->export_particles;
job->settings.apply_subdiv = params->apply_subdiv;
job->settings.flatten_hierarchy = params->flatten_hierarchy;
job->settings.visible_layers_only = params->visible_layers_only;
@@ -359,136 +359,248 @@ void ABC_export(
std::swap(job->settings.frame_start, job->settings.frame_end);
}
- wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
- CTX_wm_window(C),
- job->scene,
- "Alembic Export",
- WM_JOB_PROGRESS,
- WM_JOB_TYPE_ALEMBIC);
+ bool export_ok = false;
+ if (as_background_job) {
+ wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
+ CTX_wm_window(C),
+ job->scene,
+ "Alembic Export",
+ WM_JOB_PROGRESS,
+ WM_JOB_TYPE_ALEMBIC);
- /* setup job */
- WM_jobs_customdata_set(wm_job, job, MEM_freeN);
- WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
- WM_jobs_callbacks(wm_job, export_startjob, NULL, NULL, export_endjob);
+ /* setup job */
+ WM_jobs_customdata_set(wm_job, job, MEM_freeN);
+ WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
+ WM_jobs_callbacks(wm_job, export_startjob, NULL, NULL, export_endjob);
- WM_jobs_start(CTX_wm_manager(C), wm_job);
+ WM_jobs_start(CTX_wm_manager(C), wm_job);
+ }
+ else {
+ /* Fake a job context, so that we don't need NULL pointer checks while exporting. */
+ short stop = 0, do_update = 0;
+ float progress = 0.f;
+
+ export_startjob(job, &stop, &do_update, &progress);
+ export_endjob(job);
+ export_ok = job->export_ok;
+
+ MEM_freeN(job);
+ }
+
+ return export_ok;
}
/* ********************** Import file ********************** */
-static void visit_object(const IObject &object,
- std::vector<AbcObjectReader *> &readers,
- GHash *parent_map,
- ImportSettings &settings)
+/**
+ * Generates an AbcObjectReader for this Alembic object and its children.
+ *
+ * \param object The Alembic IObject to visit.
+ * \param readers The created AbcObjectReader * will be appended to this vector.
+ * \param settings Import settings, not used directly but passed to the
+ * AbcObjectReader subclass constructors.
+ * \param r_assign_as_parent Return parameter, contains a list of reader
+ * pointers, whose parent pointer should still be set.
+ * This is filled when this call to visit_object() didn't create
+ * a reader that should be the parent.
+ * \return A pair of boolean and reader pointer. The boolean indicates whether
+ * this IObject claims its parent as part of the same object
+ * (for example an IPolyMesh object would claim its parent, as the mesh
+ * is interpreted as the object's data, and the parent IXform as its
+ * Blender object). The pointer is the AbcObjectReader that represents
+ * the IObject parameter.
+ *
+ * NOTE: this function is similar to gather_object_paths above, need to keep
+ * them in sync. */
+static std::pair<bool, AbcObjectReader *> visit_object(
+ const IObject &object,
+ AbcObjectReader::ptr_vector &readers,
+ ImportSettings &settings,
+ AbcObjectReader::ptr_vector &r_assign_as_parent)
{
+ const std::string & full_name = object.getFullName();
+
if (!object.valid()) {
- return;
+ std::cerr << " - "
+ << full_name
+ << ": object is invalid, skipping it and all its children.\n";
+ return std::make_pair(false, static_cast<AbcObjectReader *>(NULL));
}
- for (int i = 0; i < object.getNumChildren(); ++i) {
- IObject child = object.getChild(i);
-
- if (!child.valid()) {
- continue;
- }
-
- AbcObjectReader *reader = NULL;
+ /* The interpretation of data by the children determine the role of this
+ * object. This is especially important for Xform objects, as they can be
+ * either part of a Blender object or a Blender object (Empty) themselves.
+ */
+ size_t children_claiming_this_object = 0;
+ size_t num_children = object.getNumChildren();
+ AbcObjectReader::ptr_vector claiming_child_readers;
+ AbcObjectReader::ptr_vector nonclaiming_child_readers;
+ AbcObjectReader::ptr_vector assign_as_parent;
+ for (size_t i = 0; i < num_children; ++i) {
+ const IObject ichild = object.getChild(i);
- const MetaData &md = child.getMetaData();
+ /* TODO: When we only support C++11, use std::tie() instead. */
+ std::pair<bool, AbcObjectReader *> child_result;
+ child_result = visit_object(ichild, readers, settings, assign_as_parent);
- if (IXform::matches(md)) {
- bool create_xform = false;
+ bool child_claims_this_object = child_result.first;
+ AbcObjectReader *child_reader = child_result.second;
- /* Check whether or not this object is a Maya locator, which is
- * similar to empties used as parent object in Blender. */
- if (has_property(child.getProperties(), "locator")) {
- create_xform = true;
+ if (child_reader == NULL) {
+ BLI_assert(!child_claims_this_object);
+ }
+ else {
+ if (child_claims_this_object) {
+ claiming_child_readers.push_back(child_reader);
}
else {
- /* Avoid creating an empty object if the child of this transform
- * is not a transform (that is an empty). */
- if (child.getNumChildren() == 1) {
- if (IXform::matches(child.getChild(0).getMetaData())) {
- create_xform = true;
- }
-#if 0
- else {
- std::cerr << "Skipping " << child.getFullName() << '\n';
- }
-#endif
- }
- else {
- create_xform = true;
- }
+ nonclaiming_child_readers.push_back(child_reader);
}
+ }
- if (create_xform) {
- reader = new AbcEmptyReader(child, settings);
- }
+ children_claiming_this_object += child_claims_this_object ? 1 : 0;
+ }
+ BLI_assert(children_claiming_this_object == claiming_child_readers.size());
+
+ AbcObjectReader *reader = NULL;
+ const MetaData &md = object.getMetaData();
+ bool parent_is_part_of_this_object = false;
+
+ if (!object.getParent()) {
+ /* The root itself is not an object we should import. */
+ }
+ else if (IXform::matches(md)) {
+ bool create_empty;
+
+ /* An xform can either be a Blender Object (if it contains a mesh, for
+ * example), but it can also be an Empty. Its correct translation to
+ * Blender's data model depends on its children. */
+
+ /* Check whether or not this object is a Maya locator, which is
+ * similar to empties used as parent object in Blender. */
+ if (has_property(object.getProperties(), "locator")) {
+ create_empty = true;
}
- else if (IPolyMesh::matches(md)) {
- reader = new AbcMeshReader(child, settings);
+ else {
+ create_empty = claiming_child_readers.empty();
}
- else if (ISubD::matches(md)) {
- reader = new AbcSubDReader(child, settings);
+
+ if (create_empty) {
+ reader = new AbcEmptyReader(object, settings);
}
- else if (INuPatch::matches(md)) {
+ }
+ else if (IPolyMesh::matches(md)) {
+ reader = new AbcMeshReader(object, settings);
+ parent_is_part_of_this_object = true;
+ }
+ else if (ISubD::matches(md)) {
+ reader = new AbcSubDReader(object, settings);
+ parent_is_part_of_this_object = true;
+ }
+ else if (INuPatch::matches(md)) {
#ifdef USE_NURBS
- /* TODO(kevin): importing cyclic NURBS from other software crashes
- * at the moment. This is due to the fact that NURBS in other
- * software have duplicated points which causes buffer overflows in
- * Blender. Need to figure out exactly how these points are
- * duplicated, in all cases (cyclic U, cyclic V, and cyclic UV).
- * Until this is fixed, disabling NURBS reading. */
- reader = new AbcNurbsReader(child, settings);
+ /* TODO(kevin): importing cyclic NURBS from other software crashes
+ * at the moment. This is due to the fact that NURBS in other
+ * software have duplicated points which causes buffer overflows in
+ * Blender. Need to figure out exactly how these points are
+ * duplicated, in all cases (cyclic U, cyclic V, and cyclic UV).
+ * Until this is fixed, disabling NURBS reading. */
+ reader = new AbcNurbsReader(object, settings);
+ parent_is_part_of_this_object = true;
#endif
+ }
+ else if (ICamera::matches(md)) {
+ reader = new AbcCameraReader(object, settings);
+ parent_is_part_of_this_object = true;
+ }
+ else if (IPoints::matches(md)) {
+ reader = new AbcPointsReader(object, settings);
+ parent_is_part_of_this_object = true;
+ }
+ else if (IMaterial::matches(md)) {
+ /* Pass for now. */
+ }
+ else if (ILight::matches(md)) {
+ /* Pass for now. */
+ }
+ else if (IFaceSet::matches(md)) {
+ /* Pass, those are handled in the mesh reader. */
+ }
+ else if (ICurves::matches(md)) {
+ reader = new AbcCurveReader(object, settings);
+ parent_is_part_of_this_object = true;
+ }
+ else {
+ std::cerr << "Alembic object " << full_name
+ << " is of unsupported schema type '"
+ << object.getMetaData().get("schemaObjTitle") << "'"
+ << std::endl;
+ }
+
+ if (reader) {
+ /* We have created a reader, which should imply that this object is
+ * not claimed as part of any child Alembic object. */
+ BLI_assert(claiming_child_readers.empty());
+
+ readers.push_back(reader);
+ reader->incref();
+
+ AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
+ MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
+ BLI_strncpy(abc_path->path, full_name.c_str(), sizeof(abc_path->path));
+ BLI_addtail(&settings.cache_file->object_paths, abc_path);
+
+ /* We can now assign this reader as parent for our children. */
+ if (nonclaiming_child_readers.size() + assign_as_parent.size() > 0) {
+ /* TODO: When we only support C++11, use for (a: b) instead. */
+ BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
+ child_reader->parent_reader = reader;
+ }
+ BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
+ child_reader->parent_reader = reader;
+ }
}
- else if (ICamera::matches(md)) {
- reader = new AbcCameraReader(child, settings);
- }
- else if (IPoints::matches(md)) {
- reader = new AbcPointsReader(child, settings);
- }
- else if (IMaterial::matches(md)) {
- /* Pass for now. */
- }
- else if (ILight::matches(md)) {
- /* Pass for now. */
- }
- else if (IFaceSet::matches(md)) {
- /* Pass, those are handled in the mesh reader. */
- }
- else if (ICurves::matches(md)) {
- reader = new AbcCurveReader(child, settings);
+ }
+ else if (object.getParent()) {
+ if (claiming_child_readers.size() > 0) {
+ /* The first claiming child will serve just fine as parent to
+ * our non-claiming children. Since all claiming children share
+ * the same XForm, it doesn't really matter which one we pick. */
+ AbcObjectReader *claiming_child = claiming_child_readers[0];
+ BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
+ child_reader->parent_reader = claiming_child;
+ }
+ BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
+ child_reader->parent_reader = claiming_child;
+ }
+ /* Claiming children should have our parent set as their parent. */
+ BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
+ r_assign_as_parent.push_back(child_reader);
+ }
}
else {
- assert(false);
- }
-
- if (reader) {
- readers.push_back(reader);
- reader->incref();
-
- AlembicObjectPath *abc_path = static_cast<AlembicObjectPath *>(
- MEM_callocN(sizeof(AlembicObjectPath), "AlembicObjectPath"));
-
- BLI_strncpy(abc_path->path, child.getFullName().c_str(), PATH_MAX);
-
- BLI_addtail(&settings.cache_file->object_paths, abc_path);
-
- /* Cast to `void *` explicitly to avoid compiler errors because it
- * is a `const char *` which the compiler cast to `const void *`
- * instead of the expected `void *`. */
- BLI_ghash_insert(parent_map, (void *)child.getFullName().c_str(), reader);
+ /* This object isn't claimed by any child, and didn't produce
+ * a reader. Odd situation, could be the top Alembic object, or
+ * an unsupported Alembic schema. Delegate to our parent. */
+ BOOST_FOREACH(AbcObjectReader *child_reader, claiming_child_readers) {
+ r_assign_as_parent.push_back(child_reader);
+ }
+ BOOST_FOREACH(AbcObjectReader *child_reader, nonclaiming_child_readers) {
+ r_assign_as_parent.push_back(child_reader);
+ }
+ BOOST_FOREACH(AbcObjectReader *child_reader, assign_as_parent) {
+ r_assign_as_parent.push_back(child_reader);
+ }
}
-
- visit_object(child, readers, parent_map, settings);
}
+
+ return std::make_pair(parent_is_part_of_this_object, reader);
}
enum {
ABC_NO_ERROR = 0,
ABC_ARCHIVE_FAIL,
+ ABC_UNSUPPORTED_HDF5,
};
struct ImportJobData {
@@ -498,7 +610,6 @@ struct ImportJobData {
char filename[1024];
ImportSettings settings;
- GHash *parent_map;
std::vector<AbcObjectReader *> readers;
short *stop;
@@ -507,6 +618,7 @@ struct ImportJobData {
char error_code;
bool was_cancelled;
+ bool import_ok;
};
ABC_INLINE bool is_mesh_and_strands(const IObject &object)
@@ -542,6 +654,8 @@ ABC_INLINE bool is_mesh_and_strands(const IObject &object)
static void import_startjob(void *user_data, short *stop, short *do_update, float *progress)
{
+ SCOPE_TIMER("Alembic import, objects reading and creation");
+
ImportJobData *data = static_cast<ImportJobData *>(user_data);
data->stop = stop;
@@ -551,8 +665,12 @@ static void import_startjob(void *user_data, short *stop, short *do_update, floa
ArchiveReader *archive = new ArchiveReader(data->filename);
if (!archive->valid()) {
- delete archive;
+#ifndef WITH_ALEMBIC_HDF5
+ data->error_code = archive->is_hdf5() ? ABC_UNSUPPORTED_HDF5 : ABC_ARCHIVE_FAIL;
+#else
data->error_code = ABC_ARCHIVE_FAIL;
+#endif
+ delete archive;
return;
}
@@ -573,11 +691,12 @@ static void import_startjob(void *user_data, short *stop, short *do_update, floa
*data->do_update = true;
*data->progress = 0.05f;
- data->parent_map = BLI_ghash_str_new("alembic parent ghash");
-
/* Parse Alembic Archive. */
+ AbcObjectReader::ptr_vector assign_as_parent;
+ visit_object(archive->getTop(), data->readers, data->settings, assign_as_parent);
- visit_object(archive->getTop(), data->readers, data->parent_map, data->settings);
+ /* There shouldn't be any orphans. */
+ BLI_assert(assign_as_parent.size() == 0);
if (G.is_break) {
data->was_cancelled = true;
@@ -595,19 +714,23 @@ static void import_startjob(void *user_data, short *stop, short *do_update, floa
chrono_t min_time = std::numeric_limits<chrono_t>::max();
chrono_t max_time = std::numeric_limits<chrono_t>::min();
+ ISampleSelector sample_sel(0.0f);
std::vector<AbcObjectReader *>::iterator iter;
for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
AbcObjectReader *reader = *iter;
if (reader->valid()) {
- reader->readObjectData(data->bmain, 0.0f);
- reader->readObjectMatrix(0.0f);
+ reader->readObjectData(data->bmain, sample_sel);
min_time = std::min(min_time, reader->minTime());
max_time = std::max(max_time, reader->maxTime());
}
+ else {
+ std::cerr << "Object " << reader->name() << " in Alembic file "
+ << data->filename << " is invalid.\n";
+ }
- *data->progress = 0.1f + 0.6f * (++i / size);
+ *data->progress = 0.1f + 0.3f * (++i / size);
*data->do_update = true;
if (G.is_break) {
@@ -620,50 +743,36 @@ static void import_startjob(void *user_data, short *stop, short *do_update, floa
Scene *scene = data->scene;
if (data->settings.is_sequence) {
- SFRA = data->settings.offset;
+ SFRA = data->settings.sequence_offset;
EFRA = SFRA + (data->settings.sequence_len - 1);
CFRA = SFRA;
}
else if (min_time < max_time) {
- SFRA = static_cast<int>(min_time * FPS);
- EFRA = static_cast<int>(max_time * FPS);
+ SFRA = static_cast<int>(round(min_time * FPS));
+ EFRA = static_cast<int>(round(max_time * FPS));
CFRA = SFRA;
}
}
- /* Setup parentship. */
-
- i = 0;
+ /* Setup parenthood. */
for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
const AbcObjectReader *reader = *iter;
- const AbcObjectReader *parent_reader = NULL;
- const IObject &iobject = reader->iobject();
-
- IObject parent = iobject.getParent();
-
- if (!IXform::matches(iobject.getHeader())) {
- /* In the case of an non XForm node, the parent is the transform
- * matrix of the data itself, so we get the its grand parent.
- */
+ const AbcObjectReader *parent_reader = reader->parent_reader;
+ Object *ob = reader->object();
- /* Special case with object only containing a mesh and some strands,
- * we want both objects to be parented to the same object. */
- if (!is_mesh_and_strands(parent)) {
- parent = parent.getParent();
- }
+ if (parent_reader == NULL || !reader->inherits_xform()) {
+ ob->parent = NULL;
}
-
- parent_reader = reinterpret_cast<AbcObjectReader *>(
- BLI_ghash_lookup(data->parent_map, parent.getFullName().c_str()));
-
- if (parent_reader) {
- Object *parent = parent_reader->object();
-
- if (parent != NULL && reader->object() != parent) {
- Object *ob = reader->object();
- ob->parent = parent;
- }
+ else {
+ ob->parent = parent_reader->object();
}
+ }
+
+ /* Setup transformations and constraints. */
+ i = 0;
+ for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
+ AbcObjectReader *reader = *iter;
+ reader->setupObjectTransform(0.0f);
*data->progress = 0.7f + 0.3f * (++i / size);
*data->do_update = true;
@@ -677,6 +786,8 @@ static void import_startjob(void *user_data, short *stop, short *do_update, floa
static void import_endjob(void *user_data)
{
+ SCOPE_TIMER("Alembic import, cleanup");
+
ImportJobData *data = static_cast<ImportJobData *>(user_data);
std::vector<AbcObjectReader *>::iterator iter;
@@ -686,23 +797,25 @@ static void import_endjob(void *user_data)
for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
Object *ob = (*iter)->object();
- if (ob->data) {
- BKE_libblock_free_us(data->bmain, ob->data);
- ob->data = NULL;
- }
+ /* It's possible that cancellation occured between the creation of
+ * the reader and the creation of the Blender object. */
+ if (ob == NULL) continue;
BKE_libblock_free_us(data->bmain, ob);
}
}
else {
/* Add object to scene. */
+ Base *base;
+
BKE_scene_base_deselect_all(data->scene);
for (iter = data->readers.begin(); iter != data->readers.end(); ++iter) {
Object *ob = (*iter)->object();
ob->lay = data->scene->lay;
- BKE_scene_base_add(data->scene, ob);
+ base = BKE_scene_base_add(data->scene, ob);
+ BKE_scene_base_select(data->scene, base);
DAG_id_tag_update_ex(data->bmain, &ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
}
@@ -719,17 +832,17 @@ static void import_endjob(void *user_data)
}
}
- if (data->parent_map) {
- BLI_ghash_free(data->parent_map, NULL, NULL);
- }
-
switch (data->error_code) {
default:
case ABC_NO_ERROR:
+ data->import_ok = !data->was_cancelled;
break;
case ABC_ARCHIVE_FAIL:
WM_report(RPT_ERROR, "Could not open Alembic archive for reading! See console for detail.");
break;
+ case ABC_UNSUPPORTED_HDF5:
+ WM_report(RPT_ERROR, "Alembic archive in obsolete HDF5 format is not supported.");
+ break;
}
WM_main_add_notifier(NC_SCENE | ND_FRAME, data->scene);
@@ -741,40 +854,58 @@ static void import_freejob(void *user_data)
delete data;
}
-void ABC_import(bContext *C, const char *filepath, float scale, bool is_sequence, bool set_frame_range, int sequence_len, int offset, bool validate_meshes)
+bool ABC_import(bContext *C, const char *filepath, float scale, bool is_sequence,
+ bool set_frame_range, int sequence_len, int offset,
+ bool validate_meshes, bool as_background_job)
{
/* Using new here since MEM_* funcs do not call ctor to properly initialize
* data. */
ImportJobData *job = new ImportJobData();
job->bmain = CTX_data_main(C);
job->scene = CTX_data_scene(C);
+ job->import_ok = false;
BLI_strncpy(job->filename, filepath, 1024);
job->settings.scale = scale;
job->settings.is_sequence = is_sequence;
job->settings.set_frame_range = set_frame_range;
job->settings.sequence_len = sequence_len;
- job->settings.offset = offset;
+ job->settings.sequence_offset = offset;
job->settings.validate_meshes = validate_meshes;
- job->parent_map = NULL;
job->error_code = ABC_NO_ERROR;
job->was_cancelled = false;
G.is_break = false;
- wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
- CTX_wm_window(C),
- job->scene,
- "Alembic Import",
- WM_JOB_PROGRESS,
- WM_JOB_TYPE_ALEMBIC);
+ bool import_ok = false;
+ if (as_background_job) {
+ wmJob *wm_job = WM_jobs_get(CTX_wm_manager(C),
+ CTX_wm_window(C),
+ job->scene,
+ "Alembic Import",
+ WM_JOB_PROGRESS,
+ WM_JOB_TYPE_ALEMBIC);
+
+ /* setup job */
+ WM_jobs_customdata_set(wm_job, job, import_freejob);
+ WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
+ WM_jobs_callbacks(wm_job, import_startjob, NULL, NULL, import_endjob);
- /* setup job */
- WM_jobs_customdata_set(wm_job, job, import_freejob);
- WM_jobs_timer(wm_job, 0.1, NC_SCENE | ND_FRAME, NC_SCENE | ND_FRAME);
- WM_jobs_callbacks(wm_job, import_startjob, NULL, NULL, import_endjob);
+ WM_jobs_start(CTX_wm_manager(C), wm_job);
+ }
+ else {
+ /* Fake a job context, so that we don't need NULL pointer checks while importing. */
+ short stop = 0, do_update = 0;
+ float progress = 0.f;
+
+ import_startjob(job, &stop, &do_update, &progress);
+ import_endjob(job);
+ import_ok = job->import_ok;
+
+ import_freejob(job);
+ }
- WM_jobs_start(CTX_wm_manager(C), wm_job);
+ return import_ok;
}
/* ************************************************************************** */
@@ -809,42 +940,15 @@ DerivedMesh *ABC_read_mesh(CacheReader *reader,
}
const ObjectHeader &header = iobject.getHeader();
-
- if (IPolyMesh::matches(header)) {
- if (ob->type != OB_MESH) {
- *err_str = "Object type mismatch: object path points to a mesh!";
- return NULL;
- }
-
- return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
- }
- else if (ISubD::matches(header)) {
- if (ob->type != OB_MESH) {
- *err_str = "Object type mismatch: object path points to a subdivision mesh!";
- return NULL;
- }
-
- return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
- }
- else if (IPoints::matches(header)) {
- if (ob->type != OB_MESH) {
- *err_str = "Object type mismatch: object path points to a point cloud (requires a mesh object)!";
- return NULL;
- }
-
- return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
- }
- else if (ICurves::matches(header)) {
- if (ob->type != OB_CURVE) {
- *err_str = "Object type mismatch: object path points to a curve!";
- return NULL;
- }
-
- return abc_reader->read_derivedmesh(dm, time, read_flag, err_str);
+ if (!abc_reader->accepts_object_type(header, ob, err_str)) {
+ /* err_str is set by acceptsObjectType() */
+ return NULL;
}
- *err_str = "Unsupported object type: verify object path"; // or poke developer
- return NULL;
+ /* kFloorIndex is used to be compatible with non-interpolating
+ * properties; they use the floor. */
+ ISampleSelector sample_sel(time, ISampleSelector::kFloorIndex);
+ return abc_reader->read_derivedmesh(dm, sample_sel, read_flag, err_str);
}
/* ************************************************************************** */
@@ -859,6 +963,12 @@ void CacheReader_free(CacheReader *reader)
}
}
+void CacheReader_incref(CacheReader *reader)
+{
+ AbcObjectReader *abc_reader = reinterpret_cast<AbcObjectReader *>(reader);
+ abc_reader->incref();
+}
+
CacheReader *CacheReader_open_alembic_object(AbcArchiveHandle *handle, CacheReader *reader, Object *object, const char *object_path)
{
if (object_path[0] == '\0') {
@@ -880,6 +990,10 @@ CacheReader *CacheReader_open_alembic_object(AbcArchiveHandle *handle, CacheRead
ImportSettings settings;
AbcObjectReader *abc_reader = create_reader(iobject, settings);
+ if (abc_reader == NULL) {
+ /* This object is not supported */
+ return NULL;
+ }
abc_reader->object(object);
abc_reader->incref();
diff --git a/source/blender/avi/CMakeLists.txt b/source/blender/avi/CMakeLists.txt
index 292206d8cb9..5009bd2a30b 100644
--- a/source/blender/avi/CMakeLists.txt
+++ b/source/blender/avi/CMakeLists.txt
@@ -26,6 +26,7 @@
set(INC
.
../blenlib
+ ../imbuf
../../../intern/guardedalloc
)
diff --git a/source/blender/avi/intern/avi.c b/source/blender/avi/intern/avi.c
index 9601d6e5002..6695998fd35 100644
--- a/source/blender/avi/intern/avi.c
+++ b/source/blender/avi/intern/avi.c
@@ -285,13 +285,15 @@ bool AVI_is_avi(const char *name)
fseek(movie.fp, movie.header->size - 14 * 4, SEEK_CUR);
- if (movie.header->Streams < 1) {
- DEBUG_PRINT("streams less than 1\n");
+ /* Limit number of streams to some reasonable amount to prevent
+ * buffer oveflow vulnerabilities. */
+ if (movie.header->Streams < 1 || movie.header->Streams > 65536) {
+ DEBUG_PRINT("Number of streams should be in range 1-65536\n");
fclose(movie.fp);
return 0;
}
- movie.streams = (AviStreamRec *) MEM_callocN(sizeof(AviStreamRec) * movie.header->Streams, "moviestreams");
+ movie.streams = (AviStreamRec *) MEM_calloc_arrayN(movie.header->Streams, sizeof(AviStreamRec), "moviestreams");
for (temp = 0; temp < movie.header->Streams; temp++) {
@@ -486,12 +488,14 @@ AviError AVI_open_movie(const char *name, AviMovie *movie)
fseek(movie->fp, movie->header->size - 14 * 4, SEEK_CUR);
- if (movie->header->Streams < 1) {
- DEBUG_PRINT("streams less than 1\n");
+ /* Limit number of streams to some reasonable amount to prevent
+ * buffer oveflow vulnerabilities. */
+ if (movie->header->Streams < 1 || movie->header->Streams > 65536) {
+ DEBUG_PRINT("Number of streams should be in range 1-65536\n");
return AVI_ERROR_FORMAT;
}
- movie->streams = (AviStreamRec *) MEM_callocN(sizeof(AviStreamRec) * movie->header->Streams, "moviestreams");
+ movie->streams = (AviStreamRec *) MEM_calloc_arrayN(movie->header->Streams, sizeof(AviStreamRec), "moviestreams");
for (temp = 0; temp < movie->header->Streams; temp++) {
@@ -689,7 +693,7 @@ AviError AVI_open_movie(const char *name, AviMovie *movie)
void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream)
{
- int cur_frame = -1, temp, i = 0, rewind = 1;
+ int cur_frame = -1, i = 0, rewind = 1;
void *buffer;
/* Retrieve the record number of the desired frame in the index
@@ -720,16 +724,16 @@ void *AVI_read_frame(AviMovie *movie, AviFormat format, int frame, int stream)
fseek(movie->fp, movie->read_offset + movie->entries[i - 1].Offset, SEEK_SET);
- temp = GET_FCC(movie->fp);
- buffer = MEM_mallocN(temp, "readbuffer");
+ size_t size = GET_FCC(movie->fp);
+ buffer = MEM_mallocN(size, "readbuffer");
- if (fread(buffer, 1, temp, movie->fp) != temp) {
+ if (fread(buffer, 1, size, movie->fp) != size) {
MEM_freeN(buffer);
return NULL;
}
- buffer = avi_format_convert(movie, stream, buffer, movie->streams[stream].format, format, &temp);
+ buffer = avi_format_convert(movie, stream, buffer, movie->streams[stream].format, format, &size);
return buffer;
}
@@ -801,6 +805,13 @@ AviError AVI_open_compress(char *name, AviMovie *movie, int streams, ...)
movie->header->Reserved[2] = 0;
movie->header->Reserved[3] = 0;
+ /* Limit number of streams to some reasonable amount to prevent
+ * buffer oveflow vulnerabilities. */
+ if (movie->header->Streams < 0 || movie->header->Streams > 65536) {
+ DEBUG_PRINT("Number of streams should be in range 0-65536\n");
+ return AVI_ERROR_FORMAT;
+ }
+
movie->streams = (AviStreamRec *) MEM_mallocN(sizeof(AviStreamRec) * movie->header->Streams, "moviestreams");
va_start(ap, streams);
@@ -968,7 +979,6 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...)
int64_t rec_off;
AviFormat format;
void *buffer;
- int size;
if (frame_num < 0)
return AVI_ERROR_OPTION;
@@ -1002,7 +1012,7 @@ AviError AVI_write_frame(AviMovie *movie, int frame_num, ...)
format = va_arg(ap, AviFormat);
buffer = va_arg(ap, void *);
- size = va_arg(ap, int);
+ size_t size = va_arg(ap, int);
/* Convert the buffer into the output format */
buffer = avi_format_convert(movie, stream, buffer, format, movie->streams[stream].format, &size);
diff --git a/source/blender/avi/intern/avi_codecs.c b/source/blender/avi/intern/avi_codecs.c
index c14d088c8ea..f52ec44faab 100644
--- a/source/blender/avi/intern/avi_codecs.c
+++ b/source/blender/avi/intern/avi_codecs.c
@@ -39,7 +39,7 @@
#include "avi_mjpeg.h"
#include "avi_rgb32.h"
-void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, int *size)
+void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, size_t *size)
{
if (from == to)
return buffer;
diff --git a/source/blender/avi/intern/avi_intern.h b/source/blender/avi/intern/avi_intern.h
index 0b494047612..b2fec1edfc1 100644
--- a/source/blender/avi/intern/avi_intern.h
+++ b/source/blender/avi/intern/avi_intern.h
@@ -59,7 +59,7 @@ unsigned int GET_TCC(FILE *fp);
putc(ch2[1], fp); \
} (void)0
-void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, int *size);
+void *avi_format_convert(AviMovie *movie, int stream, void *buffer, AviFormat from, AviFormat to, size_t *size);
int avi_get_data_id(AviFormat format, int stream);
int avi_get_format_type(AviFormat format);
diff --git a/source/blender/avi/intern/avi_mjpeg.c b/source/blender/avi/intern/avi_mjpeg.c
index 1fa9da6b3a2..258426809fb 100644
--- a/source/blender/avi/intern/avi_mjpeg.c
+++ b/source/blender/avi/intern/avi_mjpeg.c
@@ -39,15 +39,17 @@
#include "MEM_guardedalloc.h"
+#include "IMB_imbuf.h"
+
#include "jpeglib.h"
#include "jerror.h"
#include "avi_mjpeg.h"
-static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, int bufsize);
-static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, int bufsize);
+static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, size_t bufsize);
+static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, size_t bufsize);
-static int numbytes;
+static size_t numbytes;
static void add_huff_table(j_decompress_ptr dinfo, JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
{
@@ -151,10 +153,8 @@ static void std_huff_tables(j_decompress_ptr dinfo)
bits_ac_chrominance, val_ac_chrominance);
}
-static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsigned int width, unsigned int height, int bufsize)
+static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsigned int width, unsigned int height, size_t bufsize)
{
- int rowstride;
- unsigned int y;
struct jpeg_decompress_struct dinfo;
struct jpeg_error_mgr jerr;
@@ -174,8 +174,8 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
jpeg_start_decompress(&dinfo);
- rowstride = dinfo.output_width * dinfo.output_components;
- for (y = 0; y < dinfo.output_height; y++) {
+ size_t rowstride = dinfo.output_width * dinfo.output_components;
+ for (size_t y = 0; y < dinfo.output_height; y++) {
jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1);
outBuffer += rowstride;
}
@@ -194,7 +194,7 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
jpeg_start_decompress(&dinfo);
rowstride = dinfo.output_width * dinfo.output_components;
- for (y = 0; y < dinfo.output_height; y++) {
+ for (size_t y = 0; y < dinfo.output_height; y++) {
jpeg_read_scanlines(&dinfo, (JSAMPARRAY) &outBuffer, 1);
outBuffer += rowstride;
}
@@ -204,10 +204,8 @@ static int Decode_JPEG(unsigned char *inBuffer, unsigned char *outBuffer, unsign
return 1;
}
-static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned char *inBuffer, int width, int height, int bufsize)
+static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned char *inBuffer, int width, int height, size_t bufsize)
{
- int i, rowstride;
- unsigned int y;
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
unsigned char marker[60];
@@ -240,7 +238,7 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
jpeg_start_compress(&cinfo, false);
- i = 0;
+ int i = 0;
marker[i++] = 'A';
marker[i++] = 'V';
marker[i++] = 'I';
@@ -257,8 +255,8 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
jpeg_write_marker(&cinfo, JPEG_COM, marker, 60);
- rowstride = cinfo.image_width * cinfo.input_components;
- for (y = 0; y < cinfo.image_height; y++) {
+ size_t rowstride = cinfo.image_width * cinfo.input_components;
+ for (size_t y = 0; y < cinfo.image_height; y++) {
jpeg_write_scanlines(&cinfo, (JSAMPARRAY) &inBuffer, 1);
inBuffer += rowstride;
}
@@ -268,7 +266,7 @@ static void Compress_JPEG(int quality, unsigned char *outbuffer, const unsigned
static void interlace(unsigned char *to, unsigned char *from, int width, int height)
{
- int i, rowstride = width * 3;
+ size_t i, rowstride = width * 3;
for (i = 0; i < height; i++) {
if (i & 1)
@@ -280,7 +278,7 @@ static void interlace(unsigned char *to, unsigned char *from, int width, int hei
static void deinterlace(int odd, unsigned char *to, unsigned char *from, int width, int height)
{
- int i, rowstride = width * 3;
+ size_t i, rowstride = width * 3;
for (i = 0; i < height; i++) {
if ((i & 1) == odd)
@@ -290,22 +288,27 @@ static void deinterlace(int odd, unsigned char *to, unsigned char *from, int wid
}
}
-void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
int deint;
unsigned char *buf;
(void)stream; /* unused */
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_from_mjpeg 1");
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_from_mjpeg 1");
+ if (!buf) {
+ return NULL;
+ }
deint = Decode_JPEG(buffer, buf, movie->header->Width, movie->header->Height, *size);
MEM_freeN(buffer);
if (deint) {
- buffer = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_from_mjpeg 2");
- interlace(buffer, buf, movie->header->Width, movie->header->Height);
+ buffer = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_from_mjpeg 2");
+ if (buffer) {
+ interlace(buffer, buf, movie->header->Width, movie->header->Height);
+ }
MEM_freeN(buf);
buf = buffer;
@@ -314,43 +317,50 @@ void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffe
return buf;
}
-void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
unsigned char *buf;
- int bufsize = *size;
+ size_t bufsize = *size;
numbytes = 0;
*size = 0;
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_to_mjpeg 1");
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_to_mjpeg 1");
+ if (!buf) {
+ return NULL;
+ }
+
if (!movie->interlace) {
Compress_JPEG(movie->streams[stream].sh.Quality / 100,
buf, buffer,
movie->header->Width,
movie->header->Height,
bufsize);
+ *size += numbytes;
}
else {
deinterlace(movie->odd_fields, buf, buffer, movie->header->Width, movie->header->Height);
MEM_freeN(buffer);
buffer = buf;
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "avi.avi_converter_to_mjpeg 2");
-
- Compress_JPEG(movie->streams[stream].sh.Quality / 100,
- buf, buffer,
- movie->header->Width,
- movie->header->Height / 2,
- bufsize / 2);
- *size += numbytes;
- numbytes = 0;
- Compress_JPEG(movie->streams[stream].sh.Quality / 100,
- buf + *size, buffer + (movie->header->Height / 2) * movie->header->Width * 3,
- movie->header->Width,
- movie->header->Height / 2,
- bufsize / 2);
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "avi.avi_converter_to_mjpeg 1");
+
+ if (buf) {
+ Compress_JPEG(movie->streams[stream].sh.Quality / 100,
+ buf, buffer,
+ movie->header->Width,
+ movie->header->Height / 2,
+ bufsize / 2);
+ *size += numbytes;
+ numbytes = 0;
+ Compress_JPEG(movie->streams[stream].sh.Quality / 100,
+ buf + *size, buffer + (size_t)(movie->header->Height / 2) * (size_t)movie->header->Width * 3,
+ movie->header->Width,
+ movie->header->Height / 2,
+ bufsize / 2);
+ *size += numbytes;
+ }
}
- *size += numbytes;
MEM_freeN(buffer);
return buf;
@@ -377,7 +387,7 @@ static void jpegmemdestmgr_term_destination(j_compress_ptr cinfo)
MEM_freeN(cinfo->dest);
}
-static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, int bufsize)
+static void jpegmemdestmgr_build(j_compress_ptr cinfo, unsigned char *buffer, size_t bufsize)
{
cinfo->dest = MEM_mallocN(sizeof(*(cinfo->dest)), "avi.jpegmemdestmgr_build");
@@ -430,7 +440,7 @@ static void jpegmemsrcmgr_term_source(j_decompress_ptr dinfo)
MEM_freeN(dinfo->src);
}
-static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, int bufsize)
+static void jpegmemsrcmgr_build(j_decompress_ptr dinfo, unsigned char *buffer, size_t bufsize)
{
dinfo->src = MEM_mallocN(sizeof(*(dinfo->src)), "avi.jpegmemsrcmgr_build");
diff --git a/source/blender/avi/intern/avi_mjpeg.h b/source/blender/avi/intern/avi_mjpeg.h
index e8cba1849e7..e1e3cdf1fd8 100644
--- a/source/blender/avi/intern/avi_mjpeg.h
+++ b/source/blender/avi/intern/avi_mjpeg.h
@@ -32,7 +32,7 @@
#ifndef __AVI_MJPEG_H__
#define __AVI_MJPEG_H__
-void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size);
-void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_from_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
+void *avi_converter_to_mjpeg(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_MJPEG_H__ */
diff --git a/source/blender/avi/intern/avi_rgb.c b/source/blender/avi/intern/avi_rgb.c
index 632ecad61a6..f0baf7c6c14 100644
--- a/source/blender/avi/intern/avi_rgb.c
+++ b/source/blender/avi/intern/avi_rgb.c
@@ -40,11 +40,12 @@
#include "AVI_avi.h"
#include "avi_rgb.h"
+#include "IMB_imbuf.h"
+
/* implementation */
-void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
- int x, y, i, rowstride;
unsigned char *buf;
AviBitmapInfoHeader *bi;
short bits = 32;
@@ -60,33 +61,35 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
#ifdef __BIG_ENDIAN__
unsigned char *pxla;
#endif
-
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromavirgbbuf");
- y = movie->header->Height;
- to = buf;
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromavirgbbuf");
+
+ if (buf) {
+ size_t y = movie->header->Height;
+ to = buf;
+
+ while (y--) {
+ pxl = (unsigned short *) (buffer + y * movie->header->Width * 2);
- while (y--) {
- pxl = (unsigned short *) (buffer + y * movie->header->Width * 2);
-
#ifdef __BIG_ENDIAN__
- pxla = (unsigned char *)pxl;
+ pxla = (unsigned char *)pxl;
#endif
- x = movie->header->Width;
- while (x--) {
+ size_t x = movie->header->Width;
+ while (x--) {
#ifdef __BIG_ENDIAN__
- i = pxla[0];
- pxla[0] = pxla[1];
- pxla[1] = i;
-
- pxla += 2;
+ int i = pxla[0];
+ pxla[0] = pxla[1];
+ pxla[1] = i;
+
+ pxla += 2;
#endif
-
- *(to++) = ((*pxl >> 10) & 0x1f) * 8;
- *(to++) = ((*pxl >> 5) & 0x1f) * 8;
- *(to++) = (*pxl & 0x1f) * 8;
- pxl++;
+
+ *(to++) = ((*pxl >> 10) & 0x1f) * 8;
+ *(to++) = ((*pxl >> 5) & 0x1f) * 8;
+ *(to++) = (*pxl & 0x1f) * 8;
+ pxl++;
+ }
}
}
@@ -95,48 +98,49 @@ void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buf
return buf;
}
else {
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromavirgbbuf");
-
- rowstride = movie->header->Width * 3;
- if ((bits != 16) && (movie->header->Width % 2)) rowstride++;
-
- for (y = 0; y < movie->header->Height; y++) {
- memcpy(&buf[y * movie->header->Width * 3], &buffer[((movie->header->Height - 1) - y) * rowstride], movie->header->Width * 3);
- }
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromavirgbbuf");
- for (y = 0; y < movie->header->Height * movie->header->Width * 3; y += 3) {
- i = buf[y];
- buf[y] = buf[y + 2];
- buf[y + 2] = i;
+ if (buf) {
+ size_t rowstride = movie->header->Width * 3;
+ if ((bits != 16) && (movie->header->Width % 2)) rowstride++;
+
+ for (size_t y = 0; y < movie->header->Height; y++) {
+ memcpy(&buf[y * movie->header->Width * 3], &buffer[((movie->header->Height - 1) - y) * rowstride], movie->header->Width * 3);
+ }
+
+ for (size_t y = 0; y < (size_t)movie->header->Height * (size_t)movie->header->Width * 3; y += 3) {
+ int i = buf[y];
+ buf[y] = buf[y + 2];
+ buf[y + 2] = i;
+ }
}
-
+
MEM_freeN(buffer);
-
+
return buf;
}
}
-void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
- int y, x, i, rowstride;
unsigned char *buf;
(void)stream; /* unused */
- rowstride = movie->header->Width * 3;
+ size_t rowstride = movie->header->Width * 3;
/* AVI files has uncompressed lines 4-byte aligned */
rowstride = (rowstride + 3) & ~3;
*size = movie->header->Height * rowstride;
buf = MEM_mallocN(*size, "toavirgbbuf");
- for (y = 0; y < movie->header->Height; y++) {
+ for (size_t y = 0; y < movie->header->Height; y++) {
memcpy(&buf[y * rowstride], &buffer[((movie->header->Height - 1) - y) * movie->header->Width * 3], movie->header->Width * 3);
}
- for (y = 0; y < movie->header->Height; y++) {
- for (x = 0; x < movie->header->Width * 3; x += 3) {
- i = buf[y * rowstride + x];
+ for (size_t y = 0; y < movie->header->Height; y++) {
+ for (size_t x = 0; x < movie->header->Width * 3; x += 3) {
+ int i = buf[y * rowstride + x];
buf[y * rowstride + x] = buf[y * rowstride + x + 2];
buf[y * rowstride + x + 2] = i;
}
diff --git a/source/blender/avi/intern/avi_rgb.h b/source/blender/avi/intern/avi_rgb.h
index 773166e9fab..67bb4172769 100644
--- a/source/blender/avi/intern/avi_rgb.h
+++ b/source/blender/avi/intern/avi_rgb.h
@@ -32,7 +32,7 @@
#ifndef __AVI_RGB_H__
#define __AVI_RGB_H__
-void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size);
-void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_from_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
+void *avi_converter_to_avi_rgb(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_RGB_H__ */
diff --git a/source/blender/avi/intern/avi_rgb32.c b/source/blender/avi/intern/avi_rgb32.c
index c9cbcb05bb8..051fdba1cd2 100644
--- a/source/blender/avi/intern/avi_rgb32.c
+++ b/source/blender/avi/intern/avi_rgb32.c
@@ -37,24 +37,28 @@
#include "MEM_guardedalloc.h"
+#include "IMB_imbuf.h"
+
#include "AVI_avi.h"
#include "avi_rgb32.h"
-void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
- int y, x, rowstridea, rowstrideb;
unsigned char *buf;
(void)stream; /* unused */
- buf = MEM_mallocN(movie->header->Height * movie->header->Width * 3, "fromrgb32buf");
- *size = movie->header->Height * movie->header->Width * 3;
+ *size = (size_t)movie->header->Height * (size_t)movie->header->Width * 3;
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "fromrgb32buf");
+ if (!buf) {
+ return NULL;
+ }
- rowstridea = movie->header->Width * 3;
- rowstrideb = movie->header->Width * 4;
+ size_t rowstridea = movie->header->Width * 3;
+ size_t rowstrideb = movie->header->Width * 4;
- for (y = 0; y < movie->header->Height; y++) {
- for (x = 0; x < movie->header->Width; x++) {
+ for (size_t y = 0; y < movie->header->Height; y++) {
+ for (size_t x = 0; x < movie->header->Width; x++) {
buf[y * rowstridea + x * 3 + 0] = buffer[y * rowstrideb + x * 4 + 3];
buf[y * rowstridea + x * 3 + 1] = buffer[y * rowstrideb + x * 4 + 2];
buf[y * rowstridea + x * 3 + 2] = buffer[y * rowstrideb + x * 4 + 1];
@@ -66,21 +70,23 @@ void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffe
return buf;
}
-void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size)
+void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size)
{
- int i;
unsigned char *buf;
unsigned char *to, *from;
(void)stream; /* unused */
- *size = movie->header->Height * movie->header->Width * 4;
- buf = MEM_mallocN(*size, "torgb32buf");
+ *size = (size_t)movie->header->Height * (size_t)movie->header->Width * 4;
+ buf = imb_alloc_pixels(movie->header->Height, movie->header->Width, 3, sizeof(unsigned char), "torgb32buf");
+ if (!buf) {
+ return NULL;
+ }
memset(buf, 255, *size);
to = buf; from = buffer;
- i = movie->header->Height * movie->header->Width;
+ size_t i = (size_t)movie->header->Height * (size_t)movie->header->Width;
while (i--) {
memcpy(to, from, 3);
diff --git a/source/blender/avi/intern/avi_rgb32.h b/source/blender/avi/intern/avi_rgb32.h
index 523f9e795fd..a9373a69821 100644
--- a/source/blender/avi/intern/avi_rgb32.h
+++ b/source/blender/avi/intern/avi_rgb32.h
@@ -32,7 +32,7 @@
#ifndef __AVI_RGB32_H__
#define __AVI_RGB32_H__
-void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size);
-void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, int *size);
+void *avi_converter_from_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
+void *avi_converter_to_rgb32(AviMovie *movie, int stream, unsigned char *buffer, size_t *size);
#endif /* __AVI_RGB32_H__ */
diff --git a/source/blender/blenfont/BLF_api.h b/source/blender/blenfont/BLF_api.h
index 1f38d64924c..f31c132c973 100644
--- a/source/blender/blenfont/BLF_api.h
+++ b/source/blender/blenfont/BLF_api.h
@@ -33,16 +33,20 @@
#define __BLF_API_H__
#include "BLI_compiler_attrs.h"
+#include "BLI_sys_types.h"
struct rctf;
struct ColorManagedDisplay;
struct ResultBLF;
-int BLF_init(int points, int dpi);
+int BLF_init(void);
void BLF_exit(void);
void BLF_default_dpi(int dpi);
void BLF_default_set(int fontid);
+void BLF_antialias_set(bool enabled);
+bool BLF_antialias_get(void);
+
void BLF_cache_clear(void);
int BLF_load(const char *name) ATTR_NONNULL();
diff --git a/source/blender/blenfont/intern/blf.c b/source/blender/blenfont/intern/blf.c
index 132a0ec3808..38c1498d76b 100644
--- a/source/blender/blenfont/intern/blf.c
+++ b/source/blender/blenfont/intern/blf.c
@@ -84,6 +84,7 @@ static FontBLF *global_font[BLF_MAX_FONT] = {NULL};
static int global_font_default = -1;
static int global_font_points = 11;
static int global_font_dpi = 72;
+static bool global_use_antialias = true;
/* XXX, should these be made into global_font_'s too? */
int blf_mono_font = -1;
@@ -96,15 +97,16 @@ static FontBLF *blf_get(int fontid)
return NULL;
}
-int BLF_init(int points, int dpi)
+int BLF_init(void)
{
int i;
for (i = 0; i < BLF_MAX_FONT; i++)
global_font[i] = NULL;
- global_font_points = points;
- global_font_dpi = dpi;
+ global_font_points = 11;
+ global_font_dpi = 72;
+
return blf_font_init();
}
@@ -174,6 +176,16 @@ void BLF_default_set(int fontid)
}
}
+void BLF_antialias_set(bool enabled)
+{
+ global_use_antialias = enabled;
+}
+
+bool BLF_antialias_get(void)
+{
+ return global_use_antialias;
+}
+
int BLF_load(const char *name)
{
FontBLF *font;
@@ -759,7 +771,7 @@ int BLF_height_max(int fontid)
FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
- return font->glyph_cache->max_glyph_height;
+ return font->glyph_cache->glyph_height_max;
}
return 0;
@@ -770,7 +782,7 @@ float BLF_width_max(int fontid)
FontBLF *font = blf_get(fontid);
if (font && font->glyph_cache) {
- return font->glyph_cache->max_glyph_width;
+ return font->glyph_cache->glyph_width_max;
}
return 0.0f;
diff --git a/source/blender/blenfont/intern/blf_font.c b/source/blender/blenfont/intern/blf_font.c
index 44a1d08f1fd..af0c2fab7dd 100644
--- a/source/blender/blenfont/intern/blf_font.c
+++ b/source/blender/blenfont/intern/blf_font.c
@@ -719,7 +719,7 @@ static void blf_font_wrap_apply(
wrap.start = wrap.last[0];
i = wrap.last[1];
pen_x = 0;
- pen_y -= font->glyph_cache->max_glyph_height;
+ pen_y -= font->glyph_cache->glyph_height_max;
g_prev = NULL;
lines += 1;
continue;
@@ -923,7 +923,7 @@ static void blf_font_fill(FontBLF *font)
BLI_listbase_clear(&font->cache);
font->glyph_cache = NULL;
font->blur = 0;
- font->max_tex_size = -1;
+ font->tex_size_max = -1;
font->buf_info.fbuf = NULL;
font->buf_info.cbuf = NULL;
diff --git a/source/blender/blenfont/intern/blf_glyph.c b/source/blender/blenfont/intern/blf_glyph.c
index aa7d539538b..60dfdae519b 100644
--- a/source/blender/blenfont/intern/blf_glyph.c
+++ b/source/blender/blenfont/intern/blf_glyph.c
@@ -56,7 +56,7 @@
#include "BLF_api.h"
#ifndef BLF_STANDALONE
-#include "GPU_basic_shader.h"
+# include "GPU_basic_shader.h"
#endif
#include "blf_internal_types.h"
@@ -92,34 +92,34 @@ GlyphCacheBLF *blf_glyph_cache_new(FontBLF *font)
memset(gc->bucket, 0, sizeof(gc->bucket));
gc->textures = (GLuint *)MEM_mallocN(sizeof(GLuint) * 256, __func__);
- gc->ntex = 256;
- gc->cur_tex = BLF_CURTEX_UNSET;
- gc->x_offs = 0;
- gc->y_offs = 0;
+ gc->textures_len = 256;
+ gc->texture_current = BLF_TEXTURE_UNSET;
+ gc->offset_x = 0;
+ gc->offset_y = 0;
gc->pad = 3;
- gc->num_glyphs = (int)font->face->num_glyphs;
- gc->rem_glyphs = (int)font->face->num_glyphs;
+ gc->glyphs_len_max = (int)font->face->num_glyphs;
+ gc->glyphs_len_free = (int)font->face->num_glyphs;
gc->ascender = ((float)font->face->size->metrics.ascender) / 64.0f;
gc->descender = ((float)font->face->size->metrics.descender) / 64.0f;
if (FT_IS_SCALABLE(font->face)) {
- gc->max_glyph_width = (int)((float)(font->face->bbox.xMax - font->face->bbox.xMin) *
+ gc->glyph_width_max = (int)((float)(font->face->bbox.xMax - font->face->bbox.xMin) *
(((float)font->face->size->metrics.x_ppem) /
((float)font->face->units_per_EM)));
- gc->max_glyph_height = (int)((float)(font->face->bbox.yMax - font->face->bbox.yMin) *
+ gc->glyph_height_max = (int)((float)(font->face->bbox.yMax - font->face->bbox.yMin) *
(((float)font->face->size->metrics.y_ppem) /
((float)font->face->units_per_EM)));
}
else {
- gc->max_glyph_width = (int)(((float)font->face->size->metrics.max_advance) / 64.0f);
- gc->max_glyph_height = (int)(((float)font->face->size->metrics.height) / 64.0f);
+ gc->glyph_width_max = (int)(((float)font->face->size->metrics.max_advance) / 64.0f);
+ gc->glyph_height_max = (int)(((float)font->face->size->metrics.height) / 64.0f);
}
/* can happen with size 1 fonts */
- CLAMP_MIN(gc->max_glyph_width, 1);
- CLAMP_MIN(gc->max_glyph_height, 1);
+ CLAMP_MIN(gc->glyph_width_max, 1);
+ CLAMP_MIN(gc->glyph_height_max, 1);
gc->p2_width = 0;
gc->p2_height = 0;
@@ -135,6 +135,7 @@ void blf_glyph_cache_clear(FontBLF *font)
while ((gc = BLI_pophead(&font->cache))) {
blf_glyph_cache_free(gc);
}
+ font->glyph_cache = NULL;
}
void blf_glyph_cache_free(GlyphCacheBLF *gc)
@@ -148,9 +149,10 @@ void blf_glyph_cache_free(GlyphCacheBLF *gc)
}
}
- if (gc->cur_tex != BLF_CURTEX_UNSET)
- glDeleteTextures((int)gc->cur_tex + 1, gc->textures);
- MEM_freeN((void *)gc->textures);
+ if (gc->texture_current != BLF_TEXTURE_UNSET) {
+ glDeleteTextures((int)gc->texture_current + 1, gc->textures);
+ }
+ MEM_freeN(gc->textures);
MEM_freeN(gc);
}
@@ -159,25 +161,27 @@ static void blf_glyph_cache_texture(FontBLF *font, GlyphCacheBLF *gc)
int i;
/* move the index. */
- gc->cur_tex++;
+ gc->texture_current++;
- if (UNLIKELY(gc->cur_tex >= gc->ntex)) {
- gc->ntex *= 2;
- gc->textures = (GLuint *)MEM_reallocN((void *)gc->textures, sizeof(GLuint) * gc->ntex);
+ if (UNLIKELY(gc->texture_current >= gc->textures_len)) {
+ gc->textures_len *= 2;
+ gc->textures = MEM_reallocN((void *)gc->textures, sizeof(GLuint) * gc->textures_len);
}
- gc->p2_width = (int)blf_next_p2((unsigned int)((gc->rem_glyphs * gc->max_glyph_width) + (gc->pad * 2)));
- if (gc->p2_width > font->max_tex_size)
- gc->p2_width = font->max_tex_size;
+ gc->p2_width = (int)blf_next_p2((unsigned int)((gc->glyphs_len_free * gc->glyph_width_max) + (gc->pad * 2)));
+ if (gc->p2_width > font->tex_size_max) {
+ gc->p2_width = font->tex_size_max;
+ }
- i = (int)((gc->p2_width - (gc->pad * 2)) / gc->max_glyph_width);
- gc->p2_height = (int)blf_next_p2((unsigned int)(((gc->num_glyphs / i) + 1) * gc->max_glyph_height));
+ i = (int)((gc->p2_width - (gc->pad * 2)) / gc->glyph_width_max);
+ gc->p2_height = (int)blf_next_p2((unsigned int)(((gc->glyphs_len_max / i) + 1) * gc->glyph_height_max));
- if (gc->p2_height > font->max_tex_size)
- gc->p2_height = font->max_tex_size;
+ if (gc->p2_height > font->tex_size_max) {
+ gc->p2_height = font->tex_size_max;
+ }
- glGenTextures(1, &gc->textures[gc->cur_tex]);
- glBindTexture(GL_TEXTURE_2D, (font->tex_bind_state = gc->textures[gc->cur_tex]));
+ glGenTextures(1, &gc->textures[gc->texture_current]);
+ glBindTexture(GL_TEXTURE_2D, (font->tex_bind_state = gc->textures[gc->texture_current]));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
@@ -217,7 +221,7 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c)
GlyphBLF *g;
FT_Error err;
FT_Bitmap bitmap, tempbitmap;
- const bool is_sharp = (U.text_render & USER_TEXT_DISABLE_AA) != 0;
+ const bool is_sharp = !BLF_antialias_get();
int flags = FT_LOAD_TARGET_NORMAL | FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;
FT_BBox bbox;
unsigned int key;
@@ -277,8 +281,8 @@ GlyphBLF *blf_glyph_add(FontBLF *font, unsigned int index, unsigned int c)
g = (GlyphBLF *)MEM_callocN(sizeof(GlyphBLF), "blf_glyph_add");
g->c = c;
g->idx = (FT_UInt)index;
- g->xoff = -1;
- g->yoff = -1;
+ g->offset_x = -1;
+ g->offset_y = -1;
bitmap = slot->bitmap;
g->width = (int)bitmap.width;
g->height = (int)bitmap.rows;
@@ -321,8 +325,9 @@ void blf_glyph_free(GlyphBLF *g)
/* don't need free the texture, the GlyphCache already
* have a list of all the texture and free it.
*/
- if (g->bitmap)
+ if (g->bitmap) {
MEM_freeN(g->bitmap);
+ }
MEM_freeN(g);
}
@@ -413,38 +418,38 @@ void blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
if (g->build_tex == 0) {
GlyphCacheBLF *gc = font->glyph_cache;
- if (font->max_tex_size == -1)
- glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint *)&font->max_tex_size);
+ if (font->tex_size_max == -1)
+ glGetIntegerv(GL_MAX_TEXTURE_SIZE, (GLint *)&font->tex_size_max);
- if (gc->cur_tex == BLF_CURTEX_UNSET) {
+ if (gc->texture_current == BLF_TEXTURE_UNSET) {
blf_glyph_cache_texture(font, gc);
- gc->x_offs = gc->pad;
- gc->y_offs = 0;
+ gc->offset_x = gc->pad;
+ gc->offset_y = 0;
}
- if (gc->x_offs > (gc->p2_width - gc->max_glyph_width)) {
- gc->x_offs = gc->pad;
- gc->y_offs += gc->max_glyph_height;
+ if (gc->offset_x > (gc->p2_width - gc->glyph_width_max)) {
+ gc->offset_x = gc->pad;
+ gc->offset_y += gc->glyph_height_max;
- if (gc->y_offs > (gc->p2_height - gc->max_glyph_height)) {
- gc->y_offs = 0;
+ if (gc->offset_y > (gc->p2_height - gc->glyph_height_max)) {
+ gc->offset_y = 0;
blf_glyph_cache_texture(font, gc);
}
}
- g->tex = gc->textures[gc->cur_tex];
- g->xoff = gc->x_offs;
- g->yoff = gc->y_offs;
+ g->tex = gc->textures[gc->texture_current];
+ g->offset_x = gc->offset_x;
+ g->offset_y = gc->offset_y;
/* prevent glTexSubImage2D from failing if the character
* asks for pixels out of bounds, this tends only to happen
* with very small sizes (5px high or less) */
- if (UNLIKELY((g->xoff + g->width) > gc->p2_width)) {
- g->width -= (g->xoff + g->width) - gc->p2_width;
+ if (UNLIKELY((g->offset_x + g->width) > gc->p2_width)) {
+ g->width -= (g->offset_x + g->width) - gc->p2_width;
BLI_assert(g->width > 0);
}
- if (UNLIKELY((g->yoff + g->height) > gc->p2_height)) {
- g->height -= (g->yoff + g->height) - gc->p2_height;
+ if (UNLIKELY((g->offset_y + g->height) > gc->p2_height)) {
+ g->height -= (g->offset_y + g->height) - gc->p2_height;
BLI_assert(g->height > 0);
}
@@ -455,18 +460,18 @@ void blf_glyph_render(FontBLF *font, GlyphBLF *g, float x, float y)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glBindTexture(GL_TEXTURE_2D, g->tex);
- glTexSubImage2D(GL_TEXTURE_2D, 0, g->xoff, g->yoff, g->width, g->height, GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap);
+ glTexSubImage2D(GL_TEXTURE_2D, 0, g->offset_x, g->offset_y, g->width, g->height, GL_ALPHA, GL_UNSIGNED_BYTE, g->bitmap);
glPopClientAttrib();
- g->uv[0][0] = ((float)g->xoff) / ((float)gc->p2_width);
- g->uv[0][1] = ((float)g->yoff) / ((float)gc->p2_height);
- g->uv[1][0] = ((float)(g->xoff + g->width)) / ((float)gc->p2_width);
- g->uv[1][1] = ((float)(g->yoff + g->height)) / ((float)gc->p2_height);
+ g->uv[0][0] = ((float)g->offset_x) / ((float)gc->p2_width);
+ g->uv[0][1] = ((float)g->offset_y) / ((float)gc->p2_height);
+ g->uv[1][0] = ((float)(g->offset_x + g->width)) / ((float)gc->p2_width);
+ g->uv[1][1] = ((float)(g->offset_y + g->height)) / ((float)gc->p2_height);
/* update the x offset for the next glyph. */
- gc->x_offs += (int)BLI_rctf_size_x(&g->box) + gc->pad;
+ gc->offset_x += (int)BLI_rctf_size_x(&g->box) + gc->pad;
- gc->rem_glyphs--;
+ gc->glyphs_len_free--;
g->build_tex = 1;
}
diff --git a/source/blender/blenfont/intern/blf_internal_types.h b/source/blender/blenfont/intern/blf_internal_types.h
index 0fac576a8cc..ced8064302b 100644
--- a/source/blender/blenfont/intern/blf_internal_types.h
+++ b/source/blender/blenfont/intern/blf_internal_types.h
@@ -51,33 +51,33 @@ typedef struct GlyphCacheBLF {
unsigned int *textures;
/* size of the array. */
- unsigned int ntex;
+ unsigned int textures_len;
/* and the last texture, aka. the current texture. */
- unsigned int cur_tex;
+ unsigned int texture_current;
/* like bftgl, we draw every glyph in a big texture, so this is the
* current position inside the texture.
*/
- int x_offs;
- int y_offs;
+ int offset_x;
+ int offset_y;
/* and the space from one to other. */
int pad;
/* and the bigger glyph in the font. */
- int max_glyph_width;
- int max_glyph_height;
+ int glyph_width_max;
+ int glyph_height_max;
/* next two integer power of two, to build the texture. */
int p2_width;
int p2_height;
/* number of glyphs in the font. */
- int num_glyphs;
+ int glyphs_len_max;
- /* number of glyphs that we load here. */
- int rem_glyphs;
+ /* number of glyphs not yet loaded (decreases every glyph loaded). */
+ int glyphs_len_free;
/* ascender and descender value. */
float ascender;
@@ -106,8 +106,8 @@ typedef struct GlyphBLF {
unsigned int tex;
/* position inside the texture where this glyph is store. */
- int xoff;
- int yoff;
+ int offset_x;
+ int offset_y;
/* Bitmap data, from freetype. Take care that this
* can be NULL.
@@ -130,7 +130,7 @@ typedef struct GlyphBLF {
float pos_y;
/* with value of zero mean that we need build the texture. */
- short build_tex;
+ char build_tex;
} GlyphBLF;
typedef struct FontBufInfoBLF {
@@ -209,7 +209,7 @@ typedef struct FontBLF {
unsigned int size;
/* max texture size. */
- int max_tex_size;
+ int tex_size_max;
/* cache current OpenGL texture to save calls into the API */
unsigned int tex_bind_state;
@@ -244,6 +244,6 @@ typedef struct DirBLF {
char *path;
} DirBLF;
-#define BLF_CURTEX_UNSET ((unsigned int)-1)
+#define BLF_TEXTURE_UNSET ((unsigned int)-1)
#endif /* __BLF_INTERNAL_TYPES_H__ */
diff --git a/source/blender/blenkernel/BKE_DerivedMesh.h b/source/blender/blenkernel/BKE_DerivedMesh.h
index 789bc8df7e5..4d2e9ef8b3c 100644
--- a/source/blender/blenkernel/BKE_DerivedMesh.h
+++ b/source/blender/blenkernel/BKE_DerivedMesh.h
@@ -166,7 +166,7 @@ typedef enum DMDirtyFlag {
DM_DIRTY_TESS_CDLAYERS = 1 << 0,
/* One of the MCOL layers have been updated, force updating of GPUDrawObject's colors buffer.
* This is necessary with modern, VBO draw code, as e.g. in vpaint mode me->mcol may be updated
- * without actually rebuilding dm (hence by defautl keeping same GPUDrawObject, and same colors
+ * without actually rebuilding dm (hence by default keeping same GPUDrawObject, and same colors
* buffer, which prevents update during a stroke!). */
DM_DIRTY_MCOL_UPDATE_DRAW = 1 << 1,
@@ -193,7 +193,9 @@ struct DerivedMesh {
* \warning Typical access is done via #getLoopTriArray, #getNumLoopTri.
*/
struct {
- struct MLoopTri *array;
+ /* WARNING! swapping between array (ready-to-be-used data) and array_wip (where data is actually computed)
+ * shall always be protected by same lock as one used for looptris computing. */
+ struct MLoopTri *array, *array_wip;
int num;
int num_alloc;
} looptris;
@@ -201,7 +203,7 @@ struct DerivedMesh {
/* use for converting to BMesh which doesn't store bevel weight and edge crease by default */
char cd_flag;
- char tangent_mask; /* which tangent layers are calculated */
+ short tangent_mask; /* which tangent layers are calculated */
/** Calculate vert and face normals */
void (*calcNormals)(DerivedMesh *dm);
@@ -220,7 +222,7 @@ struct DerivedMesh {
/** Recalculates mesh tessellation */
void (*recalcTessellation)(DerivedMesh *dm);
- /** Loop tessellation cache */
+ /** Loop tessellation cache (WARNING! Only call inside threading-protected code!) */
void (*recalcLoopTri)(DerivedMesh *dm);
/** accessor functions */
const struct MLoopTri *(*getLoopTriArray)(DerivedMesh * dm);
@@ -625,7 +627,6 @@ void DM_ensure_normals(DerivedMesh *dm);
void DM_ensure_tessface(DerivedMesh *dm);
void DM_ensure_looptri_data(DerivedMesh *dm);
-void DM_ensure_looptri(DerivedMesh *dm);
void DM_verttri_from_looptri(MVertTri *verttri, const MLoop *mloop, const MLoopTri *looptri, int looptri_num);
void DM_update_tessface_data(DerivedMesh *dm);
@@ -791,11 +792,13 @@ void DM_calc_tangents_names_from_gpu(
void DM_add_named_tangent_layer_for_uv(
CustomData *uv_data, CustomData *tan_data, int numLoopData,
const char *layer_name);
+
+#define DM_TANGENT_MASK_ORCO (1 << 9)
void DM_calc_loop_tangents_step_0(
const CustomData *loopData, bool calc_active_tangent,
const char (*tangent_names)[MAX_NAME], int tangent_names_count,
bool *rcalc_act, bool *rcalc_ren, int *ract_uv_n, int *rren_uv_n,
- char *ract_uv_name, char *rren_uv_name, char *rtangent_mask);
+ char *ract_uv_name, char *rren_uv_name, short *rtangent_mask);
void DM_calc_loop_tangents(
DerivedMesh *dm, bool calc_active_tangent, const char (*tangent_names)[MAX_NAME],
int tangent_names_count);
@@ -830,11 +833,5 @@ struct MEdge *DM_get_edge_array(struct DerivedMesh *dm, bool *r_allocated);
struct MLoop *DM_get_loop_array(struct DerivedMesh *dm, bool *r_allocated);
struct MPoly *DM_get_poly_array(struct DerivedMesh *dm, bool *r_allocated);
struct MFace *DM_get_tessface_array(struct DerivedMesh *dm, bool *r_allocated);
-const MLoopTri *DM_get_looptri_array(
- DerivedMesh *dm,
- const MVert *mvert,
- const MPoly *mpoly, int mpoly_len,
- const MLoop *mloop, int mloop_len,
- bool *r_allocated);
#endif /* __BKE_DERIVEDMESH_H__ */
diff --git a/source/blender/blenkernel/BKE_action.h b/source/blender/blenkernel/BKE_action.h
index 6527ba7f94f..f7ebe85bcef 100644
--- a/source/blender/blenkernel/BKE_action.h
+++ b/source/blender/blenkernel/BKE_action.h
@@ -55,10 +55,11 @@ extern "C" {
/* Action Lib Stuff ----------------- */
/* Allocate a new bAction with the given name */
-struct bAction *add_empty_action(struct Main *bmain, const char name[]);
+struct bAction *BKE_action_add(struct Main *bmain, const char name[]);
-/* Allocate a copy of the given Action and all its data */
-struct bAction *BKE_action_copy(struct Main *bmain, struct bAction *src);
+void BKE_action_copy_data(struct Main *bmain, struct bAction *act_dst, const struct bAction *act_src, const int flag);
+/* Allocate a copy of the given Action and all its data */
+struct bAction *BKE_action_copy(struct Main *bmain, const struct bAction *act_src);
/* Deallocate all of the Action's data, but not the Action itself */
void BKE_action_free(struct bAction *act);
@@ -150,7 +151,8 @@ void BKE_pose_free_data_ex(struct bPose *pose, bool do_id_user);
void BKE_pose_free_data(struct bPose *pose);
void BKE_pose_free(struct bPose *pose);
void BKE_pose_free_ex(struct bPose *pose, bool do_id_user);
-void BKE_pose_copy_data(struct bPose **dst, struct bPose *src, const bool copy_constraints);
+void BKE_pose_copy_data_ex(struct bPose **dst, const struct bPose *src, const int flag, const bool copy_constraints);
+void BKE_pose_copy_data(struct bPose **dst, const struct bPose *src, const bool copy_constraints);
void BKE_pose_channel_copy_data(struct bPoseChannel *pchan, const struct bPoseChannel *pchan_from);
struct bPoseChannel *BKE_pose_channel_find_name(const struct bPose *pose, const char *name);
struct bPoseChannel *BKE_pose_channel_active(struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_addon.h b/source/blender/blenkernel/BKE_addon.h
index 74c1edd1c1b..e631d1d6537 100644
--- a/source/blender/blenkernel/BKE_addon.h
+++ b/source/blender/blenkernel/BKE_addon.h
@@ -26,8 +26,11 @@
* \ingroup bke
*/
-#include "RNA_types.h"
+struct ListBase;
+struct bAddon;
+
+#ifdef __RNA_TYPES_H__
typedef struct bAddonPrefType {
/* type info */
char idname[64]; // best keep the same size as BKE_ST_MAXNAME
@@ -36,6 +39,10 @@ typedef struct bAddonPrefType {
ExtensionRNA ext;
} bAddonPrefType;
+#else
+typedef struct bAddonPrefType bAddonPrefType;
+#endif
+
bAddonPrefType *BKE_addon_pref_type_find(const char *idname, bool quiet);
void BKE_addon_pref_type_add(bAddonPrefType *apt);
void BKE_addon_pref_type_remove(const bAddonPrefType *apt);
@@ -43,4 +50,8 @@ void BKE_addon_pref_type_remove(const bAddonPrefType *apt);
void BKE_addon_pref_type_init(void);
void BKE_addon_pref_type_free(void);
+struct bAddon *BKE_addon_new(void);
+struct bAddon *BKE_addon_ensure(struct ListBase *addons, const char *module);
+void BKE_addon_free(struct bAddon *addon);
+
#endif /* __BKE_ADDON_H__ */
diff --git a/source/blender/blenkernel/BKE_animsys.h b/source/blender/blenkernel/BKE_animsys.h
index a67e903877a..a70690d4029 100644
--- a/source/blender/blenkernel/BKE_animsys.h
+++ b/source/blender/blenkernel/BKE_animsys.h
@@ -35,6 +35,7 @@ struct ID;
struct ListBase;
struct Main;
struct AnimData;
+struct FCurve;
struct KeyingSet;
struct KS_Path;
struct PathResolvedRNA;
@@ -67,10 +68,10 @@ bool BKE_animdata_set_action(struct ReportList *reports, struct ID *id, struct b
void BKE_animdata_free(struct ID *id, const bool do_id_user);
/* Copy AnimData */
-struct AnimData *BKE_animdata_copy(struct AnimData *adt, const bool do_action);
+struct AnimData *BKE_animdata_copy(struct Main *bmain, struct AnimData *adt, const bool do_action);
/* Copy AnimData */
-bool BKE_animdata_copy_id(struct ID *id_to, struct ID *id_from, const bool do_action);
+bool BKE_animdata_copy_id(struct Main *bmain, struct ID *id_to, struct ID *id_from, const bool do_action);
/* Copy AnimData Actions */
void BKE_animdata_copy_id_action(struct ID *id, const bool set_newid);
@@ -89,12 +90,6 @@ typedef enum eAnimData_MergeCopy_Modes {
void BKE_animdata_merge_copy(struct ID *dst_id, struct ID *src_id, eAnimData_MergeCopy_Modes action_mode, bool fix_drivers);
-/* Make Local */
-void BKE_animdata_make_local(struct AnimData *adt);
-
-/* Re-Assign ID's */
-void BKE_animdata_relink(struct AnimData *adt);
-
/* ************************************* */
/* KeyingSets API */
@@ -108,7 +103,7 @@ struct KS_Path *BKE_keyingset_add_path(struct KeyingSet *ks, struct ID *id, cons
struct KS_Path *BKE_keyingset_find_path(struct KeyingSet *ks, struct ID *id, const char group_name[], const char rna_path[], int array_index, int group_mode);
/* Copy all KeyingSets in the given list */
-void BKE_keyingsets_copy(struct ListBase *newlist, struct ListBase *list);
+void BKE_keyingsets_copy(struct ListBase *newlist, const struct ListBase *list);
/* Free the given Keying Set path */
void BKE_keyingset_free_path(struct KeyingSet *ks, struct KS_Path *ksp);
@@ -158,9 +153,15 @@ char *BKE_animdata_driver_path_hack(struct bContext *C, struct PointerRNA *ptr,
/* Define for callback looper used in BKE_animdata_main_cb */
typedef void (*ID_AnimData_Edit_Callback)(struct ID *id, struct AnimData *adt, void *user_data);
+/* Define for callback looper used in BKE_fcurves_main_cb */
+typedef void (*ID_FCurve_Edit_Callback)(struct ID *id, struct FCurve *fcu, void *user_data);
+
/* Loop over all datablocks applying callback */
-void BKE_animdata_main_cb(struct Main *main, ID_AnimData_Edit_Callback func, void *user_data);
+void BKE_animdata_main_cb(struct Main *bmain, ID_AnimData_Edit_Callback func, void *user_data);
+
+/* Loop over all datablocks applying callback to all its F-Curves */
+void BKE_fcurves_main_cb(struct Main *bmain, ID_FCurve_Edit_Callback func, void *user_data);
/* ************************************* */
// TODO: overrides, remapping, and path-finding api's
diff --git a/source/blender/blenkernel/BKE_appdir.h b/source/blender/blenkernel/BKE_appdir.h
index 077fe2a629c..ac8f861fa56 100644
--- a/source/blender/blenkernel/BKE_appdir.h
+++ b/source/blender/blenkernel/BKE_appdir.h
@@ -27,11 +27,15 @@
/* note on naming: typical _get() suffix is omitted here,
* since its the main purpose of the API. */
const char *BKE_appdir_folder_default(void);
+const char *BKE_appdir_folder_id_ex(const int folder_id, const char *subfolder, char *path, size_t path_len);
const char *BKE_appdir_folder_id(const int folder_id, const char *subfolder);
const char *BKE_appdir_folder_id_create(const int folder_id, const char *subfolder);
const char *BKE_appdir_folder_id_user_notest(const int folder_id, const char *subfolder);
const char *BKE_appdir_folder_id_version(const int folder_id, const int ver, const bool do_check);
+bool BKE_appdir_app_template_any(void);
+bool BKE_appdir_app_template_id_search(const char *app_template, char *path, size_t path_len);
+
/* Initialize path to program executable */
void BKE_appdir_program_path_init(const char *argv0);
diff --git a/source/blender/blenkernel/BKE_armature.h b/source/blender/blenkernel/BKE_armature.h
index 78d6f6c7cb9..f6de39c897e 100644
--- a/source/blender/blenkernel/BKE_armature.h
+++ b/source/blender/blenkernel/BKE_armature.h
@@ -77,7 +77,8 @@ int BKE_armature_bonelist_count(struct ListBase *lb);
void BKE_armature_bonelist_free(struct ListBase *lb);
void BKE_armature_free(struct bArmature *arm);
void BKE_armature_make_local(struct Main *bmain, struct bArmature *arm, const bool lib_local);
-struct bArmature *BKE_armature_copy(struct Main *bmain, struct bArmature *arm);
+void BKE_armature_copy_data(struct Main *bmain, struct bArmature *arm_dst, const struct bArmature *arm_src, const int flag);
+struct bArmature *BKE_armature_copy(struct Main *bmain, const struct bArmature *arm);
/* Bounding box. */
struct BoundBox *BKE_armature_boundbox_get(struct Object *ob);
@@ -168,35 +169,39 @@ void BKE_splineik_execute_tree(struct Scene *scene, struct Object *ob, struct bP
void BKE_pose_eval_init(struct EvaluationContext *eval_ctx,
struct Scene *scene,
- struct Object *ob,
- struct bPose *pose);
+ struct Object *ob);
+
+void BKE_pose_eval_init_ik(struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
void BKE_pose_eval_bone(struct EvaluationContext *eval_ctx,
struct Scene *scene,
struct Object *ob,
- struct bPoseChannel *pchan);
+ int pchan_index);
void BKE_pose_constraints_evaluate(struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
struct Object *ob,
- struct bPoseChannel *pchan);
+ int pchan_index);
void BKE_pose_bone_done(struct EvaluationContext *eval_ctx,
- struct bPoseChannel *pchan);
+ struct Object *ob,
+ int pchan_index);
void BKE_pose_iktree_evaluate(struct EvaluationContext *eval_ctx,
struct Scene *scene,
struct Object *ob,
- struct bPoseChannel *rootchan);
+ int rootchan_index);
void BKE_pose_splineik_evaluate(struct EvaluationContext *eval_ctx,
struct Scene *scene,
struct Object *ob,
- struct bPoseChannel *rootchan);
+ int rootchan_index);
void BKE_pose_eval_flush(struct EvaluationContext *eval_ctx,
struct Scene *scene,
- struct Object *ob,
- struct bPose *pose);
+ struct Object *ob);
void BKE_pose_eval_proxy_copy(struct EvaluationContext *eval_ctx,
struct Object *ob);
diff --git a/source/blender/blenkernel/BKE_blender.h b/source/blender/blenkernel/BKE_blender.h
index d2d9c763031..647291382ef 100644
--- a/source/blender/blenkernel/BKE_blender.h
+++ b/source/blender/blenkernel/BKE_blender.h
@@ -38,14 +38,28 @@
extern "C" {
#endif
+struct UserDef;
+
void BKE_blender_free(void);
void BKE_blender_globals_init(void);
void BKE_blender_globals_clear(void);
+void BKE_blender_version_string(
+ char *version_str, size_t maxncpy,
+ short version, short subversion, bool v_prefix, bool include_subversion);
+
+void BKE_blender_userdef_data_swap(struct UserDef *userdef_dst, struct UserDef *userdef_src);
+void BKE_blender_userdef_data_set(struct UserDef *userdef);
+void BKE_blender_userdef_data_set_and_free(struct UserDef *userdef);
+
+void BKE_blender_userdef_app_template_data_swap(struct UserDef *userdef_dst, struct UserDef *userdef_src);
+void BKE_blender_userdef_app_template_data_set(struct UserDef *userdef);
+void BKE_blender_userdef_app_template_data_set_and_free(struct UserDef *userdef);
+
+void BKE_blender_userdef_data_duplicate(struct UserDef *userdef_dst, struct UserDef *userdef_src);
+
+void BKE_blender_userdef_data_free(struct UserDef *userdef, bool clear_fonts);
-void BKE_blender_userdef_free(void);
-void BKE_blender_userdef_refresh(void);
-
/* set this callback when a UI is running */
void BKE_blender_callback_test_break_set(void (*func)(void));
int BKE_blender_test_break(void);
diff --git a/source/blender/blenkernel/BKE_blender_undo.h b/source/blender/blenkernel/BKE_blender_undo.h
index 84a6d07be7d..a96f8af1fdb 100644
--- a/source/blender/blenkernel/BKE_blender_undo.h
+++ b/source/blender/blenkernel/BKE_blender_undo.h
@@ -31,22 +31,13 @@ extern "C" {
struct bContext;
struct Scene;
struct Main;
+struct MemFileUndoData;
#define BKE_UNDO_STR_MAX 64
-/* global undo */
-extern void BKE_undo_write(struct bContext *C, const char *name);
-extern void BKE_undo_step(struct bContext *C, int step);
-extern void BKE_undo_name(struct bContext *C, const char *name);
-extern bool BKE_undo_is_valid(const char *name);
-extern void BKE_undo_reset(void);
-extern void BKE_undo_number(struct bContext *C, int nr);
-extern const char *BKE_undo_get_name(int nr, bool *r_active);
-extern const char *BKE_undo_get_name_last(void);
-extern bool BKE_undo_save_file(const char *filename);
-extern struct Main *BKE_undo_get_main(struct Scene **r_scene);
-
-extern void BKE_undo_callback_wm_kill_jobs_set(void (*callback)(struct bContext *C));
+struct MemFileUndoData *BKE_memfile_undo_encode(struct Main *bmain, struct MemFileUndoData *mfu_prev);
+bool BKE_memfile_undo_decode(struct MemFileUndoData *mfu, struct bContext *C);
+void BKE_memfile_undo_free(struct MemFileUndoData *mfu);
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_blender_version.h b/source/blender/blenkernel/BKE_blender_version.h
index 4f4787f9da5..b5d906b2968 100644
--- a/source/blender/blenkernel/BKE_blender_version.h
+++ b/source/blender/blenkernel/BKE_blender_version.h
@@ -27,7 +27,7 @@
/* these lines are grep'd, watch out for our not-so-awesome regex
* and keep comment above the defines.
* Use STRINGIFY() rather than defining with quotes */
-#define BLENDER_VERSION 278
+#define BLENDER_VERSION 279
#define BLENDER_SUBVERSION 4
/* Several breakages with 270, e.g. constraint deg vs rad */
#define BLENDER_MINVERSION 270
diff --git a/source/blender/blenkernel/BKE_blendfile.h b/source/blender/blenkernel/BKE_blendfile.h
index 6767fce3abd..9ff164f60be 100644
--- a/source/blender/blenkernel/BKE_blendfile.h
+++ b/source/blender/blenkernel/BKE_blendfile.h
@@ -33,8 +33,7 @@ struct ID;
struct Main;
struct MemFile;
struct ReportList;
-
-int BKE_blendfile_read(struct bContext *C, const char *filepath, struct ReportList *reports);
+struct UserDef;
enum {
BKE_BLENDFILE_READ_FAIL = 0, /* no load */
@@ -42,16 +41,25 @@ enum {
BKE_BLENDFILE_READ_OK_USERPREFS = 2, /* OK, and with new user settings */
};
+int BKE_blendfile_read(
+ struct bContext *C, const char *filepath,
+ struct ReportList *reports, int skip_flag);
bool BKE_blendfile_read_from_memory(
- struct bContext *C, const void *filebuf,
- int filelength, struct ReportList *reports, bool update_defaults);
+ struct bContext *C, const void *filebuf, int filelength,
+ struct ReportList *reports, int skip_flag, bool update_defaults);
bool BKE_blendfile_read_from_memfile(
struct bContext *C, struct MemFile *memfile,
- struct ReportList *reports);
+ struct ReportList *reports, int skip_flag);
+void BKE_blendfile_read_make_empty(struct bContext *C);
-int BKE_blendfile_read_userdef(const char *filepath, struct ReportList *reports);
-int BKE_blendfile_write_userdef(const char *filepath, struct ReportList *reports);
+struct UserDef *BKE_blendfile_userdef_read(
+ const char *filepath, struct ReportList *reports);
+struct UserDef *BKE_blendfile_userdef_read_from_memory(
+ const void *filebuf, int filelength,
+ struct ReportList *reports);
+bool BKE_blendfile_userdef_write(const char *filepath, struct ReportList *reports);
+bool BKE_blendfile_userdef_write_app_template(const char *filepath, struct ReportList *reports);
/* partial blend file writing */
void BKE_blendfile_write_partial_tag_ID(struct ID *id, bool set);
diff --git a/source/blender/blenkernel/BKE_boids.h b/source/blender/blenkernel/BKE_boids.h
index 582cd0cef8d..24f19951efe 100644
--- a/source/blender/blenkernel/BKE_boids.h
+++ b/source/blender/blenkernel/BKE_boids.h
@@ -61,6 +61,6 @@ BoidRule *boid_new_rule(int type);
BoidState *boid_new_state(BoidSettings *boids);
BoidState *boid_duplicate_state(BoidSettings *boids, BoidState *state);
void boid_free_settings(BoidSettings *boids);
-BoidSettings *boid_copy_settings(BoidSettings *boids);
+BoidSettings *boid_copy_settings(const BoidSettings *boids);
BoidState *boid_get_current_state(BoidSettings *boids);
#endif
diff --git a/source/blender/blenkernel/BKE_brush.h b/source/blender/blenkernel/BKE_brush.h
index 8bd4bdf89e1..f2601f2ca32 100644
--- a/source/blender/blenkernel/BKE_brush.h
+++ b/source/blender/blenkernel/BKE_brush.h
@@ -27,14 +27,16 @@
* General operations for brushes.
*/
+enum eCurveMappingPreset;
struct Brush;
struct ImBuf;
struct ImagePool;
struct Main;
struct Scene;
struct UnifiedPaintSettings;
-// enum CurveMappingPreset;
+// enum eCurveMappingPreset;
+#include "DNA_object_enums.h"
/* globals for brush execution */
void BKE_brush_system_init(void);
@@ -42,9 +44,10 @@ void BKE_brush_system_exit(void);
/* datablock functions */
void BKE_brush_init(struct Brush *brush);
-struct Brush *BKE_brush_add(struct Main *bmain, const char *name, short ob_mode);
-struct Brush *BKE_brush_first_search(struct Main *bmain, short ob_mode);
-struct Brush *BKE_brush_copy(struct Main *bmain, struct Brush *brush);
+struct Brush *BKE_brush_add(struct Main *bmain, const char *name, const eObjectMode ob_mode);
+struct Brush *BKE_brush_first_search(struct Main *bmain, const eObjectMode ob_mode);
+void BKE_brush_copy_data(struct Main *bmain, struct Brush *brush_dst, const struct Brush *brush_src, const int flag);
+struct Brush *BKE_brush_copy(struct Main *bmain, const struct Brush *brush);
void BKE_brush_make_local(struct Main *bmain, struct Brush *brush, const bool lib_local);
void BKE_brush_unlink(struct Main *bmain, struct Brush *brush);
void BKE_brush_free(struct Brush *brush);
@@ -67,13 +70,13 @@ void BKE_brush_jitter_pos(
void BKE_brush_randomize_texture_coords(struct UnifiedPaintSettings *ups, bool mask);
/* brush curve */
-void BKE_brush_curve_preset(struct Brush *b, int preset);
+void BKE_brush_curve_preset(struct Brush *b, enum eCurveMappingPreset preset);
float BKE_brush_curve_strength_clamped(struct Brush *br, float p, const float len);
-float BKE_brush_curve_strength(struct Brush *br, float p, const float len);
+float BKE_brush_curve_strength(const struct Brush *br, float p, const float len);
/* sampling */
float BKE_brush_sample_tex_3D(
- const struct Scene *scene, struct Brush *br, const float point[3],
+ const struct Scene *scene, const struct Brush *br, const float point[3],
float rgba[4], const int thread, struct ImagePool *pool);
float BKE_brush_sample_masktex(
const struct Scene *scene, struct Brush *br, const float point[2],
@@ -102,9 +105,11 @@ void BKE_brush_alpha_set(struct Scene *scene, struct Brush *brush, float alpha);
float BKE_brush_weight_get(const struct Scene *scene, const struct Brush *brush);
void BKE_brush_weight_set(const struct Scene *scene, struct Brush *brush, float value);
-int BKE_brush_use_locked_size(const struct Scene *scene, const struct Brush *brush);
-int BKE_brush_use_alpha_pressure(const struct Scene *scene, const struct Brush *brush);
-int BKE_brush_use_size_pressure(const struct Scene *scene, const struct Brush *brush);
+bool BKE_brush_use_locked_size(const struct Scene *scene, const struct Brush *brush);
+bool BKE_brush_use_alpha_pressure(const struct Scene *scene, const struct Brush *brush);
+bool BKE_brush_use_size_pressure(const struct Scene *scene, const struct Brush *brush);
+
+bool BKE_brush_sculpt_has_secondary_color(const struct Brush *brush);
/* scale unprojected radius to reflect a change in the brush's 2D size */
void BKE_brush_scale_unprojected_radius(
diff --git a/source/blender/blenkernel/BKE_bvhutils.h b/source/blender/blenkernel/BKE_bvhutils.h
index cb72f0859d5..b3122f8adb9 100644
--- a/source/blender/blenkernel/BKE_bvhutils.h
+++ b/source/blender/blenkernel/BKE_bvhutils.h
@@ -46,7 +46,7 @@ struct MFace;
typedef struct LinkNode BVHCache;
/**
- * struct that kepts basic information about a BVHTree build from a editmesh
+ * Struct that stores basic information about a BVHTree built from a edit-mesh.
*/
typedef struct BVHTreeFromEditMesh {
struct BVHTree *tree;
@@ -66,7 +66,7 @@ typedef struct BVHTreeFromEditMesh {
} BVHTreeFromEditMesh;
/**
- * struct that kepts basic information about a BVHTree build from a mesh
+ * Struct that stores basic information about a BVHTree built from a mesh.
*/
typedef struct BVHTreeFromMesh {
struct BVHTree *tree;
diff --git a/source/blender/blenkernel/BKE_cachefile.h b/source/blender/blenkernel/BKE_cachefile.h
index 7e1c069df9a..e9712681090 100644
--- a/source/blender/blenkernel/BKE_cachefile.h
+++ b/source/blender/blenkernel/BKE_cachefile.h
@@ -47,7 +47,9 @@ void BKE_cachefile_init(struct CacheFile *cache_file);
void BKE_cachefile_free(struct CacheFile *cache_file);
-struct CacheFile *BKE_cachefile_copy(struct Main *bmain, struct CacheFile *cache_file);
+void BKE_cachefile_copy_data(
+ struct Main *bmain, struct CacheFile *cache_file_dst, const struct CacheFile *cache_file_src, const int flag);
+struct CacheFile *BKE_cachefile_copy(struct Main *bmain, const struct CacheFile *cache_file);
void BKE_cachefile_make_local(struct Main *bmain, struct CacheFile *cache_file, const bool lib_local);
@@ -55,7 +57,7 @@ void BKE_cachefile_reload(const struct Main *bmain, struct CacheFile *cache_file
void BKE_cachefile_ensure_handle(const struct Main *bmain, struct CacheFile *cache_file);
-void BKE_cachefile_update_frame(struct Main *bmain, struct Scene *scene,const float ctime, const float fps);
+void BKE_cachefile_update_frame(struct Main *bmain, struct Scene *scene, const float ctime, const float fps);
bool BKE_cachefile_filepath_get(
const struct Main *bmain, const struct CacheFile *cache_file, float frame,
diff --git a/source/blender/blenkernel/BKE_camera.h b/source/blender/blenkernel/BKE_camera.h
index 31a732cf7e5..04dee70faa6 100644
--- a/source/blender/blenkernel/BKE_camera.h
+++ b/source/blender/blenkernel/BKE_camera.h
@@ -52,7 +52,8 @@ struct GPUFXSettings;
void BKE_camera_init(struct Camera *cam);
void *BKE_camera_add(struct Main *bmain, const char *name);
-struct Camera *BKE_camera_copy(struct Main *bmain, struct Camera *cam);
+void BKE_camera_copy_data(struct Main *bmain, struct Camera *cam_dst, const struct Camera *cam_src, const int flag);
+struct Camera *BKE_camera_copy(struct Main *bmain, const struct Camera *cam);
void BKE_camera_make_local(struct Main *bmain, struct Camera *cam, const bool lib_local);
void BKE_camera_free(struct Camera *ca);
diff --git a/source/blender/blenkernel/BKE_cloth.h b/source/blender/blenkernel/BKE_cloth.h
index 36330242f18..6c517bd02df 100644
--- a/source/blender/blenkernel/BKE_cloth.h
+++ b/source/blender/blenkernel/BKE_cloth.h
@@ -136,9 +136,6 @@ typedef struct ClothSpring {
float restlen; /* The original length of the spring. */
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;
@@ -240,9 +237,6 @@ void bvhselftree_update_from_cloth(struct ClothModifierData *clmd, bool moving);
// needed for button_object.c
void cloth_clear_cache (struct Object *ob, struct ClothModifierData *clmd, float framenr );
-// needed for cloth.c
-int cloth_add_spring (struct ClothModifierData *clmd, unsigned int indexA, unsigned int indexB, float restlength, int spring_type);
-
void cloth_parallel_transport_hair_frame(float mat[3][3], const float dir_old[3], const float dir_new[3]);
////////////////////////////////////////////////
diff --git a/source/blender/blenkernel/BKE_colorband.h b/source/blender/blenkernel/BKE_colorband.h
new file mode 100644
index 00000000000..edb724d2aec
--- /dev/null
+++ b/source/blender/blenkernel/BKE_colorband.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef __BKE_COLORBAND_H__
+#define __BKE_COLORBAND_H__
+
+/** \file BKE_colorband.h
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct ColorBand;
+
+/* in ColorBand struct */
+#define MAXCOLORBAND 32
+
+void BKE_colorband_init(struct ColorBand *coba, bool rangetype);
+void BKE_colorband_init_from_table_rgba(
+ struct ColorBand *coba, const float (*array)[4], const int array_len, bool filter_sample);
+struct ColorBand *BKE_colorband_add(bool rangetype);
+bool BKE_colorband_evaluate(const struct ColorBand *coba, float in, float out[4]);
+void BKE_colorband_evaluate_table_rgba(const struct ColorBand *coba, float **array, int *size);
+struct CBData *BKE_colorband_element_add(struct ColorBand *coba, float position);
+int BKE_colorband_element_remove(struct ColorBand *coba, int index);
+void BKE_colorband_update_sort(struct ColorBand *coba);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BKE_COLORBAND_H__ */
diff --git a/source/blender/blenkernel/BKE_colortools.h b/source/blender/blenkernel/BKE_colortools.h
index 5b4f5910821..f68c4a2757b 100644
--- a/source/blender/blenkernel/BKE_colortools.h
+++ b/source/blender/blenkernel/BKE_colortools.h
@@ -46,8 +46,8 @@ void curvemapping_set_defaults(struct CurveMapping *cumap, int to
struct CurveMapping *curvemapping_add(int tot, float minx, float miny, float maxx, float maxy);
void curvemapping_free_data(struct CurveMapping *cumap);
void curvemapping_free(struct CurveMapping *cumap);
-void curvemapping_copy_data(struct CurveMapping *target, struct CurveMapping *cumap);
-struct CurveMapping *curvemapping_copy(struct CurveMapping *cumap);
+void curvemapping_copy_data(struct CurveMapping *target, const struct CurveMapping *cumap);
+struct CurveMapping *curvemapping_copy(const struct CurveMapping *cumap);
void curvemapping_set_black_white_ex(const float black[3], const float white[3], float r_bwmul[3]);
void curvemapping_set_black_white(struct CurveMapping *cumap, const float black[3], const float white[3]);
diff --git a/source/blender/blenkernel/BKE_constraint.h b/source/blender/blenkernel/BKE_constraint.h
index 047d1787f76..4e0eb5c65ac 100644
--- a/source/blender/blenkernel/BKE_constraint.h
+++ b/source/blender/blenkernel/BKE_constraint.h
@@ -120,6 +120,7 @@ void BKE_constraint_unique_name(struct bConstraint *con, struct ListBase *list);
void BKE_constraints_free(struct ListBase *list);
void BKE_constraints_free_ex(struct ListBase *list, bool do_id_user);
void BKE_constraints_copy(struct ListBase *dst, const struct ListBase *src, bool do_extern);
+void BKE_constraints_copy_ex(struct ListBase *dst, const struct ListBase *src, const int flag, bool do_extern);
void BKE_constraints_id_loop(struct ListBase *list, ConstraintIDFunc func, void *userdata);
void BKE_constraint_free_data(struct bConstraint *con);
void BKE_constraint_free_data_ex(struct bConstraint *con, bool do_id_user);
diff --git a/source/blender/blenkernel/BKE_context.h b/source/blender/blenkernel/BKE_context.h
index 4da6a61cbfa..6de323258bd 100644
--- a/source/blender/blenkernel/BKE_context.h
+++ b/source/blender/blenkernel/BKE_context.h
@@ -230,6 +230,10 @@ void CTX_data_list_add(bContextDataResult *result, void *data);
BLI_freelistN(&ctx_data_list); \
} (void)0
+#define CTX_DATA_BEGIN_WITH_ID(C, Type, instance, member, Type_id, instance_id) \
+ CTX_DATA_BEGIN(C, Type, instance, member) \
+ Type_id instance_id = ctx_link->ptr.id.data; \
+
int ctx_data_list_count(const bContext *C, int (*func)(const bContext *, ListBase *));
#define CTX_DATA_COUNT(C, member) \
diff --git a/source/blender/blenkernel/BKE_curve.h b/source/blender/blenkernel/BKE_curve.h
index e111bd0e16b..175fa1dad79 100644
--- a/source/blender/blenkernel/BKE_curve.h
+++ b/source/blender/blenkernel/BKE_curve.h
@@ -78,7 +78,8 @@ void BKE_curve_free(struct Curve *cu);
void BKE_curve_editfont_free(struct Curve *cu);
void BKE_curve_init(struct Curve *cu);
struct Curve *BKE_curve_add(struct Main *bmain, const char *name, int type);
-struct Curve *BKE_curve_copy(struct Main *bmain, struct Curve *cu);
+void BKE_curve_copy_data(struct Main *bmain, struct Curve *cu_dst, const struct Curve *cu_src, const int flag);
+struct Curve *BKE_curve_copy(struct Main *bmain, const struct Curve *cu);
void BKE_curve_make_local(struct Main *bmain, struct Curve *cu, const bool lib_local);
short BKE_curve_type_get(struct Curve *cu);
void BKE_curve_type_test(struct Object *ob);
@@ -92,8 +93,8 @@ void BKE_curve_texspace_get(struct Curve *cu, float r_loc[3], float r_rot[3], fl
bool BKE_curve_minmax(struct Curve *cu, bool use_radius, float min[3], float max[3]);
bool BKE_curve_center_median(struct Curve *cu, float cent[3]);
bool BKE_curve_center_bounds(struct Curve *cu, float cent[3]);
-void BKE_curve_transform_ex(struct Curve *cu, float mat[4][4], const bool do_keys, const float unit_scale);
-void BKE_curve_transform(struct Curve *cu, float mat[4][4], const bool do_keys);
+void BKE_curve_transform_ex(struct Curve *cu, float mat[4][4], const bool do_keys, const bool do_props, const float unit_scale);
+void BKE_curve_transform(struct Curve *cu, float mat[4][4], const bool do_keys, const bool do_props);
void BKE_curve_translate(struct Curve *cu, float offset[3], const bool do_keys);
void BKE_curve_material_index_remove(struct Curve *cu, int index);
void BKE_curve_material_index_clear(struct Curve *cu);
@@ -142,7 +143,7 @@ int BKE_nurbList_verts_count(struct ListBase *nurb);
int BKE_nurbList_verts_count_without_handles(struct ListBase *nurb);
void BKE_nurbList_free(struct ListBase *lb);
-void BKE_nurbList_duplicate(struct ListBase *lb1, struct ListBase *lb2);
+void BKE_nurbList_duplicate(struct ListBase *lb1, const struct ListBase *lb2);
void BKE_nurbList_handles_set(struct ListBase *editnurb, const char code);
void BKE_nurbList_handles_recalculate(struct ListBase *editnurb, const bool calc_length, const char flag);
@@ -150,7 +151,7 @@ void BKE_nurbList_handles_autocalc(ListBase *editnurb, int flag);
void BKE_nurbList_flag_set(ListBase *editnurb, short flag);
void BKE_nurb_free(struct Nurb *nu);
-struct Nurb *BKE_nurb_duplicate(struct Nurb *nu);
+struct Nurb *BKE_nurb_duplicate(const struct Nurb *nu);
struct Nurb *BKE_nurb_copy(struct Nurb *src, int pntsu, int pntsv);
void BKE_nurb_test2D(struct Nurb *nu);
@@ -198,12 +199,15 @@ void BKE_nurb_bezt_calc_normal(struct Nurb *nu, struct BezTriple *bezt, float r_
void BKE_nurb_bezt_calc_plane(struct Nurb *nu, struct BezTriple *bezt, float r_plane[3]);
void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, struct BPoint *bp, float r_normal[3]);
+void BKE_nurb_bpoint_calc_plane(struct Nurb *nu, struct BPoint *bp, float r_plane[3]);
void BKE_nurb_handle_calc(struct BezTriple *bezt, struct BezTriple *prev, struct BezTriple *next,
- const bool is_fcurve);
+ const bool is_fcurve, const char smoothing);
void BKE_nurb_handle_calc_simple(struct Nurb *nu, struct BezTriple *bezt);
void BKE_nurb_handle_calc_simple_auto(struct Nurb *nu, struct BezTriple *bezt);
+void BKE_nurb_handle_smooth_fcurve(struct BezTriple *bezt, int total, bool cyclic);
+
void BKE_nurb_handles_calc(struct Nurb *nu);
void BKE_nurb_handles_autocalc(struct Nurb *nu, int flag);
void BKE_nurb_bezt_handle_test(struct BezTriple *bezt, const bool use_handle);
@@ -216,7 +220,14 @@ struct EvaluationContext;
void BKE_curve_eval_geometry(struct EvaluationContext *eval_ctx,
struct Curve *curve);
-void BKE_curve_eval_path(struct EvaluationContext *eval_ctx,
- struct Curve *curve);
+/* curve_decimate.c */
+unsigned int BKE_curve_decimate_bezt_array(
+ struct BezTriple *bezt_array, const unsigned int bezt_array_len, const unsigned int resolu, const bool is_cyclic,
+ const char flag_test, const char flag_set,
+ const float error_sq_max, const unsigned int error_target_len);
+
+void BKE_curve_decimate_nurb(
+ struct Nurb *nu, const unsigned int resolu,
+ const float error_sq_max, const unsigned int error_target_len);
#endif /* __BKE_CURVE_H__ */
diff --git a/source/blender/blenkernel/BKE_deform.h b/source/blender/blenkernel/BKE_deform.h
index 3ce08a14177..a20c5a4240c 100644
--- a/source/blender/blenkernel/BKE_deform.h
+++ b/source/blender/blenkernel/BKE_deform.h
@@ -44,8 +44,8 @@ struct MLoop;
struct MPoly;
struct bDeformGroup *BKE_defgroup_new(struct Object *ob, const char *name);
-void defgroup_copy_list(struct ListBase *lb1, struct ListBase *lb2);
-struct bDeformGroup *defgroup_duplicate(struct bDeformGroup *ingroup);
+void defgroup_copy_list(struct ListBase *lb1, const struct ListBase *lb2);
+struct bDeformGroup *defgroup_duplicate(const struct bDeformGroup *ingroup);
struct bDeformGroup *defgroup_find_name(struct Object *ob, const char *name);
int *defgroup_flip_map(struct Object *ob, int *flip_map_len, const bool use_default);
int *defgroup_flip_map_single(struct Object *ob, int *flip_map_len, const bool use_default, int defgroup);
diff --git a/source/blender/blenkernel/BKE_utildefines.h b/source/blender/blenkernel/BKE_editlattice.h
index 7c1e0e97565..476cf535e97 100644
--- a/source/blender/blenkernel/BKE_utildefines.h
+++ b/source/blender/blenkernel/BKE_editlattice.h
@@ -18,28 +18,17 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file BKE_utildefines.h
+/** \file BKE_editlattice.h
* \ingroup bke
- * \brief blender format specific macros
- * \note generic defines should go in BLI_utildefines.h
*/
+#ifndef __BKE_EDITLATTICE_H__
+#define __BKE_EDITLATTICE_H__
-#ifndef __BKE_UTILDEFINES_H__
-#define __BKE_UTILDEFINES_H__
+struct Object;
-#ifdef __cplusplus
-extern "C" {
-#endif
+void BKE_editlattice_free(struct Object *ob);
+void BKE_editlattice_make(struct Object *obedit);
+void BKE_editlattice_load(struct Object *obedit);
-#define BKE_BIT_TEST_SET(value, test, flag) \
-{ \
- if (test) (value) |= flag; \
- else (value) &= ~flag; \
-} (void)0
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* __BKE_UTILDEFINES_H__ */
+#endif /* __BKE_EDITLATTICE_H__ */
diff --git a/source/blender/blenkernel/BKE_fcurve.h b/source/blender/blenkernel/BKE_fcurve.h
index 3a45097efc5..09f5ecce050 100644
--- a/source/blender/blenkernel/BKE_fcurve.h
+++ b/source/blender/blenkernel/BKE_fcurve.h
@@ -92,7 +92,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, struct BezTriple *bezt);
/* ---------------------- */
void fcurve_free_driver(struct FCurve *fcu);
-struct ChannelDriver *fcurve_copy_driver(struct ChannelDriver *driver);
+struct ChannelDriver *fcurve_copy_driver(const struct ChannelDriver *driver);
void driver_variables_copy(struct ListBase *dst_list, const struct ListBase *src_list);
@@ -138,7 +138,7 @@ typedef struct FModifierTypeInfo {
/* free any data that is allocated separately (optional) */
void (*free_data)(struct FModifier *fcm);
/* copy any special data that is allocated separately (optional) */
- void (*copy_data)(struct FModifier *fcm, struct FModifier *src);
+ void (*copy_data)(struct FModifier *fcm, const struct FModifier *src);
/* set settings for data that will be used for FCuModifier.data (memory already allocated using MEM_callocN) */
void (*new_data)(void *mdata);
/* verifies that the modifier settings are valid */
@@ -183,14 +183,14 @@ typedef enum eFMI_Requirement_Flags {
} eFMI_Requirement_Flags;
/* Function Prototypes for FModifierTypeInfo's */
-const FModifierTypeInfo *fmodifier_get_typeinfo(struct FModifier *fcm);
-const FModifierTypeInfo *get_fmodifier_typeinfo(int type);
+const FModifierTypeInfo *fmodifier_get_typeinfo(const struct FModifier *fcm);
+const FModifierTypeInfo *get_fmodifier_typeinfo(const int type);
/* ---------------------- */
-struct FModifier *add_fmodifier(ListBase *modifiers, int type);
-struct FModifier *copy_fmodifier(struct FModifier *src);
-void copy_fmodifiers(ListBase *dst, ListBase *src);
+struct FModifier *add_fmodifier(ListBase *modifiers, int type, struct FCurve *owner_fcu);
+struct FModifier *copy_fmodifier(const struct FModifier *src);
+void copy_fmodifiers(ListBase *dst, const ListBase *src);
bool remove_fmodifier(ListBase *modifiers, struct FModifier *fcm);
void free_fmodifiers(ListBase *modifiers);
@@ -216,7 +216,7 @@ int BKE_fcm_envelope_find_index(struct FCM_EnvelopeData *array, float frame, int
/* -------- Data Management -------- */
void free_fcurve(struct FCurve *fcu);
-struct FCurve *copy_fcurve(struct FCurve *fcu);
+struct FCurve *copy_fcurve(const struct FCurve *fcu);
void free_fcurves(ListBase *list);
void copy_fcurves(ListBase *dst, ListBase *src);
@@ -266,6 +266,9 @@ bool fcurve_are_keyframes_usable(struct FCurve *fcu);
bool fcurve_is_keyframable(struct FCurve *fcu);
bool BKE_fcurve_is_protected(struct FCurve *fcu);
+/* The curve is an infinite cycle via Cycles modifier */
+bool BKE_fcurve_is_cyclic(struct FCurve *fcu);
+
/* -------- Curve Sanity -------- */
void calchandles_fcurve(struct FCurve *fcu);
diff --git a/source/blender/blenkernel/BKE_font.h b/source/blender/blenkernel/BKE_font.h
index 6775639125f..e5eea4423c9 100644
--- a/source/blender/blenkernel/BKE_font.h
+++ b/source/blender/blenkernel/BKE_font.h
@@ -60,8 +60,9 @@ typedef struct EditFont {
struct CharInfo *textbufinfo;
/* array of rectangles & rotation */
- EditFontSelBox *selboxes;
float textcurs[4][2];
+ EditFontSelBox *selboxes;
+ int selboxes_len;
/* positional vars relative to the textbuf, textbufinfo (not utf8 bytes)
* a copy of these is kept in Curve, but use these in editmode */
@@ -77,6 +78,7 @@ void BKE_vfont_builtin_register(void *mem, int size);
void BKE_vfont_free_data(struct VFont *vfont);
void BKE_vfont_free(struct VFont *sc);
void BKE_vfont_init(struct VFont *vfont);
+void BKE_vfont_copy_data(struct Main *bmain, struct VFont *vfont_dst, const struct VFont *vfont_src, const int flag);
struct VFont *BKE_vfont_builtin_get(void);
struct VFont *BKE_vfont_load(struct Main *bmain, const char *filepath);
struct VFont *BKE_vfont_load_exists_ex(struct Main *bmain, const char *filepath, bool *r_exists);
@@ -84,7 +86,7 @@ struct VFont *BKE_vfont_load_exists(struct Main *bmain, const char *filepath);
void BKE_vfont_make_local(struct Main *bmain, struct VFont *vfont, const bool lib_local);
-bool BKE_vfont_to_curve_ex(struct Main *bmain, struct Object *ob, int mode,
+bool BKE_vfont_to_curve_ex(struct Main *bmain, struct Object *ob, struct Curve *cu, int mode,
struct ListBase *r_nubase,
const wchar_t **r_text, int *r_text_len, bool *r_text_free,
struct CharTrans **r_chartransdata);
diff --git a/source/blender/blenkernel/BKE_freestyle.h b/source/blender/blenkernel/BKE_freestyle.h
index 50407f3bdfc..1045fde0039 100644
--- a/source/blender/blenkernel/BKE_freestyle.h
+++ b/source/blender/blenkernel/BKE_freestyle.h
@@ -50,7 +50,7 @@ typedef struct FreestyleModuleSettings FreestyleModuleSettings;
/* FreestyleConfig */
void BKE_freestyle_config_init(FreestyleConfig *config);
void BKE_freestyle_config_free(FreestyleConfig *config);
-void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config);
+void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config, const int flag);
/* FreestyleConfig.modules */
FreestyleModuleConfig *BKE_freestyle_module_add(FreestyleConfig *config);
diff --git a/source/blender/blenkernel/BKE_global.h b/source/blender/blenkernel/BKE_global.h
index 4bb2b950901..ce8de456697 100644
--- a/source/blender/blenkernel/BKE_global.h
+++ b/source/blender/blenkernel/BKE_global.h
@@ -80,11 +80,16 @@ typedef struct Global {
* however this is now only used for runtime options */
int f;
+ struct {
+ /* Logging vars (different loggers may use). */
+ int level;
+ /* FILE handle or use stderr (we own this so close when done). */
+ void *file;
+ } log;
+
/* debug flag, G_DEBUG, G_DEBUG_PYTHON & friends, set python or command line args */
int debug;
- bool have_quicktime;
-
/* this variable is written to / read from FileGlobal->fileflags */
int fileflags;
@@ -124,12 +129,20 @@ enum {
G_DEBUG_WM = (1 << 5), /* operator, undo */
G_DEBUG_JOBS = (1 << 6), /* jobs time profiling */
G_DEBUG_FREESTYLE = (1 << 7), /* freestyle messages */
- G_DEBUG_DEPSGRAPH = (1 << 8), /* depsgraph messages */
- G_DEBUG_SIMDATA = (1 << 9), /* sim debug data display */
- G_DEBUG_GPU_MEM = (1 << 10), /* gpu memory in status bar */
- G_DEBUG_DEPSGRAPH_NO_THREADS = (1 << 11), /* single threaded depsgraph */
- G_DEBUG_GPU = (1 << 12), /* gpu debug */
- G_DEBUG_IO = (1 << 13), /* IO Debugging (for Collada, ...)*/
+ G_DEBUG_DEPSGRAPH_BUILD = (1 << 8), /* depsgraph construction messages */
+ G_DEBUG_DEPSGRAPH_EVAL = (1 << 9), /* depsgraph evaluation messages */
+ G_DEBUG_DEPSGRAPH_TAG = (1 << 10), /* depsgraph tagging messages */
+ G_DEBUG_DEPSGRAPH_TIME = (1 << 11), /* depsgraph timing statistics and messages */
+ G_DEBUG_DEPSGRAPH_NO_THREADS = (1 << 12), /* single threaded depsgraph */
+ G_DEBUG_DEPSGRAPH_PRETTY = (1 << 13), /* use pretty colors in depsgraph messages */
+ G_DEBUG_DEPSGRAPH = (G_DEBUG_DEPSGRAPH_BUILD |
+ G_DEBUG_DEPSGRAPH_EVAL |
+ G_DEBUG_DEPSGRAPH_TAG |
+ G_DEBUG_DEPSGRAPH_TIME),
+ G_DEBUG_SIMDATA = (1 << 14), /* sim debug data display */
+ G_DEBUG_GPU_MEM = (1 << 15), /* gpu memory in status bar */
+ G_DEBUG_GPU = (1 << 16), /* gpu debug */
+ G_DEBUG_IO = (1 << 17), /* IO Debugging (for Collada, ...)*/
};
#define G_DEBUG_ALL (G_DEBUG | G_DEBUG_FFMPEG | G_DEBUG_PYTHON | G_DEBUG_EVENTS | G_DEBUG_WM | G_DEBUG_JOBS | \
@@ -189,11 +202,6 @@ enum {
# error Either __BIG_ENDIAN__ or __LITTLE_ENDIAN__ must be defined.
#endif
-/* there is really no good place for this */
-#if defined(FREE_WINDOWS) && ((__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ < 6)))
-# error "Mingw requires GCC 4.6 minimum"
-#endif
-
#define L_ENDIAN 1
#define B_ENDIAN 0
diff --git a/source/blender/blenkernel/BKE_gpencil.h b/source/blender/blenkernel/BKE_gpencil.h
index 3378f4acc60..b6de922c245 100644
--- a/source/blender/blenkernel/BKE_gpencil.h
+++ b/source/blender/blenkernel/BKE_gpencil.h
@@ -60,7 +60,8 @@ struct bGPdata *BKE_gpencil_data_addnew(const char name[]);
struct bGPDframe *BKE_gpencil_frame_duplicate(const struct bGPDframe *gpf_src);
struct bGPDlayer *BKE_gpencil_layer_duplicate(const struct bGPDlayer *gpl_src);
-struct bGPdata *BKE_gpencil_data_duplicate(struct Main *bmain, struct bGPdata *gpd, bool internal_copy);
+void BKE_gpencil_copy_data(struct Main *bmain, struct bGPdata *gpd_dst, const struct bGPdata *gpd_src, const int flag);
+struct bGPdata *BKE_gpencil_data_duplicate(struct Main *bmain, const struct bGPdata *gpd, bool internal_copy);
void BKE_gpencil_make_local(struct Main *bmain, struct bGPdata *gpd, const bool lib_local);
diff --git a/source/blender/blenkernel/BKE_group.h b/source/blender/blenkernel/BKE_group.h
index 09a069ee36f..e07dd259970 100644
--- a/source/blender/blenkernel/BKE_group.h
+++ b/source/blender/blenkernel/BKE_group.h
@@ -42,7 +42,8 @@ struct Scene;
void BKE_group_free(struct Group *group);
struct Group *BKE_group_add(struct Main *bmain, const char *name);
-struct Group *BKE_group_copy(struct Main *bmain, struct Group *group);
+void BKE_group_copy_data(struct Main *bmain, struct Group *group_dst, const struct Group *group_src, const int flag);
+struct Group *BKE_group_copy(struct Main *bmain, const struct Group *group);
void BKE_group_make_local(struct Main *bmain, struct Group *group, const bool lib_local);
bool BKE_group_object_add(struct Group *group, struct Object *ob, struct Scene *scene, struct Base *base);
bool BKE_group_object_unlink(struct Group *group, struct Object *ob, struct Scene *scene, struct Base *base);
@@ -51,7 +52,6 @@ bool BKE_group_object_exists(struct Group *group, struct Object *ob);
bool BKE_group_object_cyclic_check(struct Main *bmain, struct Object *object, struct Group *group);
bool BKE_group_is_animated(struct Group *group, struct Object *parent);
-void BKE_group_tag_recalc(struct Group *group);
void BKE_group_handle_recalc_and_update(struct EvaluationContext *eval_ctx, struct Scene *scene, struct Object *parent, struct Group *group);
#endif /* __BKE_GROUP_H__ */
diff --git a/source/blender/blenkernel/BKE_icons.h b/source/blender/blenkernel/BKE_icons.h
index 6944c5ccd28..686dba21283 100644
--- a/source/blender/blenkernel/BKE_icons.h
+++ b/source/blender/blenkernel/BKE_icons.h
@@ -39,7 +39,8 @@ typedef void (*DrawInfoFreeFP)(void *drawinfo);
struct Icon {
void *drawinfo;
void *obj;
- short type;
+ /** #ID_Type or 0 when not used for ID preview. */
+ short id_type;
DrawInfoFreeFP drawinfo_free;
};
@@ -58,23 +59,26 @@ int BKE_icon_id_ensure(struct ID *id);
int BKE_icon_preview_ensure(struct ID *id, struct PreviewImage *preview);
/* retrieve icon for id */
-struct Icon *BKE_icon_get(int icon_id);
+struct Icon *BKE_icon_get(const int icon_id);
/* set icon for id if not already defined */
/* used for inserting the internal icons */
-void BKE_icon_set(int icon_id, struct Icon *icon);
+void BKE_icon_set(const int icon_id, struct Icon *icon);
/* remove icon and free data if library object becomes invalid */
void BKE_icon_id_delete(struct ID *id);
-void BKE_icon_delete(int icon_id);
+void BKE_icon_delete(const int icon_id);
/* report changes - icon needs to be recalculated */
-void BKE_icon_changed(int icon_id);
+void BKE_icon_changed(const int icon_id);
/* free all icons */
void BKE_icons_free(void);
+/* free all icons marked for deferred deletion */
+void BKE_icons_deferred_free(void);
+
/* free the preview image for use in list */
void BKE_previewimg_freefunc(void *link);
@@ -88,7 +92,7 @@ void BKE_previewimg_clear(struct PreviewImage *prv);
void BKE_previewimg_clear_single(struct PreviewImage *prv, enum eIconSizes size);
/* get the preview from any pointer */
-struct PreviewImage **BKE_previewimg_id_get_p(struct ID *id);
+struct PreviewImage **BKE_previewimg_id_get_p(const struct ID *id);
/* free the preview image belonging to the id */
void BKE_previewimg_id_free(struct ID *id);
@@ -97,9 +101,9 @@ void BKE_previewimg_id_free(struct ID *id);
struct PreviewImage *BKE_previewimg_create(void);
/* create a copy of the preview image */
-struct PreviewImage *BKE_previewimg_copy(struct PreviewImage *prv);
+struct PreviewImage *BKE_previewimg_copy(const struct PreviewImage *prv);
-void BKE_previewimg_id_copy(struct ID *new_id, struct ID *old_id);
+void BKE_previewimg_id_copy(struct ID *new_id, const struct ID *old_id);
/* retrieve existing or create new preview image */
struct PreviewImage *BKE_previewimg_id_ensure(struct ID *id);
diff --git a/source/blender/blenkernel/BKE_idprop.h b/source/blender/blenkernel/BKE_idprop.h
index 5b10d7ebc06..5d8cd02756d 100644
--- a/source/blender/blenkernel/BKE_idprop.h
+++ b/source/blender/blenkernel/BKE_idprop.h
@@ -58,9 +58,7 @@ typedef union IDPropertyTemplate {
/* ----------- Property Array Type ---------- */
IDProperty *IDP_NewIDPArray(const char *name) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-IDProperty *IDP_CopyIDPArray(const IDProperty *array) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-
-void IDP_FreeIDPArray(IDProperty *prop);
+IDProperty *IDP_CopyIDPArray(const IDProperty *array, const int flag) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
/* shallow copies item */
void IDP_SetIndexArray(struct IDProperty *prop, int index, struct IDProperty *item) ATTR_NONNULL();
@@ -81,8 +79,8 @@ void IDP_ConcatString(struct IDProperty *str1, struct IDProperty *append) ATTR_N
void IDP_FreeString(struct IDProperty *prop) ATTR_NONNULL();
/*-------- ID Type -------*/
-void IDP_LinkID(struct IDProperty *prop, ID *id);
-void IDP_UnlinkID(struct IDProperty *prop);
+
+typedef void(*IDPWalkFunc)(void *userData, IDProperty *idp);
/*-------- Group Functions -------*/
@@ -105,6 +103,7 @@ IDProperty *IDP_GetPropertyTypeFromGroup(struct IDProperty *prop, const char *na
/*-------- Main Functions --------*/
struct IDProperty *IDP_GetProperties(struct ID *id, const bool create_if_needed) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
struct IDProperty *IDP_CopyProperty(const struct IDProperty *prop) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+struct IDProperty *IDP_CopyProperty_ex(const struct IDProperty *prop, const int flag) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is_strict) ATTR_WARN_UNUSED_RESULT;
@@ -112,11 +111,12 @@ bool IDP_EqualsProperties(struct IDProperty *prop1, struct IDProperty *prop2) AT
struct IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char *name) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+void IDP_FreeProperty_ex(struct IDProperty *prop, const bool do_id_user);
void IDP_FreeProperty(struct IDProperty *prop);
void IDP_ClearProperty(IDProperty *prop);
-void IDP_UnlinkProperty(struct IDProperty *prop);
+void IDP_RelinkProperty(struct IDProperty *prop);
#define IDP_Int(prop) ((prop)->data.val)
#define IDP_Array(prop) ((prop)->data.pointer)
@@ -134,11 +134,15 @@ void IDP_UnlinkProperty(struct IDProperty *prop);
# define IDP_IDPArray(prop) _Generic((prop), \
IDProperty *: ((IDProperty *) (prop)->data.pointer), \
const IDProperty *: ((const IDProperty *) (prop)->data.pointer))
+# define IDP_Id(prop) _Generic((prop), \
+ IDProperty *: ((ID *) (prop)->data.pointer), \
+ const IDProperty *: ((const ID *) (prop)->data.pointer))
#else
# define IDP_Float(prop) (*(float *)&(prop)->data.val)
# define IDP_Double(prop) (*(double *)&(prop)->data.val)
# define IDP_String(prop) ((char *) (prop)->data.pointer)
# define IDP_IDPArray(prop) ((IDProperty *) (prop)->data.pointer)
+# define IDP_Id(prop) ((ID *) (prop)->data.pointer)
#endif
#ifndef NDEBUG
diff --git a/source/blender/blenkernel/BKE_image.h b/source/blender/blenkernel/BKE_image.h
index 132c73209d1..1af123759e6 100644
--- a/source/blender/blenkernel/BKE_image.h
+++ b/source/blender/blenkernel/BKE_image.h
@@ -58,6 +58,7 @@ void BKE_images_exit(void);
void BKE_image_free_packedfiles(struct Image *image);
void BKE_image_free_views(struct Image *image);
void BKE_image_free_buffers(struct Image *image);
+void BKE_image_free_buffers_ex(struct Image *image, bool do_lock);
/* call from library */
void BKE_image_free(struct Image *image);
@@ -66,9 +67,16 @@ void BKE_image_init(struct Image *image);
typedef void (StampCallback)(void *data, const char *propname, char *propvalue, int len);
void BKE_render_result_stamp_info(struct Scene *scene, struct Object *camera, struct RenderResult *rr, bool allocate_only);
+/**
+ * Fills in the static stamp data (i.e. everything except things that can change per frame).
+ * The caller is responsible for freeing the allocated memory.
+ */
+struct StampData *BKE_stamp_info_from_scene_static(struct Scene *scene);
void BKE_imbuf_stamp_info(struct RenderResult *rr, struct ImBuf *ibuf);
void BKE_stamp_info_from_imbuf(struct RenderResult *rr, struct ImBuf *ibuf);
void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip);
+void BKE_render_result_stamp_data(struct RenderResult *rr, const char *key, const char *value);
+void BKE_stamp_data_free(struct StampData *stamp_data);
void BKE_image_stamp_buf(
struct Scene *scene, struct Object *camera, const struct StampData *stamp_data_template,
unsigned char *rect, float *rectf, int width, int height, int channels);
@@ -250,7 +258,8 @@ void BKE_image_packfiles_from_mem(struct ReportList *reports, struct Image *ima,
void BKE_image_print_memlist(void);
/* empty image block, of similar type and filename */
-struct Image *BKE_image_copy(struct Main *bmain, struct Image *ima);
+void BKE_image_copy_data(struct Main *bmain, struct Image *ima_dst, const struct Image *ima_src, const int flag);
+struct Image *BKE_image_copy(struct Main *bmain, const struct Image *ima);
/* merge source into dest, and free source */
void BKE_image_merge(struct Image *dest, struct Image *source);
diff --git a/source/blender/blenkernel/BKE_key.h b/source/blender/blenkernel/BKE_key.h
index e590ff148d7..5eef44ef896 100644
--- a/source/blender/blenkernel/BKE_key.h
+++ b/source/blender/blenkernel/BKE_key.h
@@ -51,7 +51,8 @@ extern "C" {
void BKE_key_free(struct Key *sc);
void BKE_key_free_nolib(struct Key *key);
struct Key *BKE_key_add(struct ID *id);
-struct Key *BKE_key_copy(struct Main *bmain, struct Key *key);
+void BKE_key_copy_data(struct Main *bmain, struct Key *key_dst, const struct Key *key_src, const int flag);
+struct Key *BKE_key_copy(struct Main *bmain, const struct Key *key);
struct Key *BKE_key_copy_nolib(struct Key *key);
void BKE_key_sort(struct Key *key);
diff --git a/source/blender/blenkernel/BKE_lamp.h b/source/blender/blenkernel/BKE_lamp.h
index 4d53850c572..3673e657b33 100644
--- a/source/blender/blenkernel/BKE_lamp.h
+++ b/source/blender/blenkernel/BKE_lamp.h
@@ -44,8 +44,9 @@ struct Scene;
void BKE_lamp_init(struct Lamp *la);
struct Lamp *BKE_lamp_add(struct Main *bmain, const char *name) ATTR_WARN_UNUSED_RESULT;
-struct Lamp *BKE_lamp_copy(struct Main *bmain, struct Lamp *la) ATTR_WARN_UNUSED_RESULT;
-struct Lamp *localize_lamp(struct Lamp *la) ATTR_WARN_UNUSED_RESULT;
+void BKE_lamp_copy_data(struct Main *bmain, struct Lamp *la_dst, const struct Lamp *la_src, const int flag);
+struct Lamp *BKE_lamp_copy(struct Main *bmain, const struct Lamp *la) ATTR_WARN_UNUSED_RESULT;
+struct Lamp *BKE_lamp_localize(struct Lamp *la) ATTR_WARN_UNUSED_RESULT;
void BKE_lamp_make_local(struct Main *bmain, struct Lamp *la, const bool lib_local);
void BKE_lamp_free(struct Lamp *la);
diff --git a/source/blender/blenkernel/BKE_lattice.h b/source/blender/blenkernel/BKE_lattice.h
index 226c82da295..f7d006785d2 100644
--- a/source/blender/blenkernel/BKE_lattice.h
+++ b/source/blender/blenkernel/BKE_lattice.h
@@ -47,7 +47,8 @@ struct MDeformVert;
void BKE_lattice_resize(struct Lattice *lt, int u, int v, int w, struct Object *ltOb);
void BKE_lattice_init(struct Lattice *lt);
struct Lattice *BKE_lattice_add(struct Main *bmain, const char *name);
-struct Lattice *BKE_lattice_copy(struct Main *bmain, struct Lattice *lt);
+void BKE_lattice_copy_data(struct Main *bmain, struct Lattice *lt_dst, const struct Lattice *lt_src, const int flag);
+struct Lattice *BKE_lattice_copy(struct Main *bmain, const struct Lattice *lt);
void BKE_lattice_free(struct Lattice *lt);
void BKE_lattice_make_local(struct Main *bmain, struct Lattice *lt, const bool lib_local);
void calc_lat_fudu(int flag, int res, float *r_fu, float *r_du);
diff --git a/source/blender/blenkernel/BKE_library.h b/source/blender/blenkernel/BKE_library.h
index 72ae2cf4efa..9e1bc2611fb 100644
--- a/source/blender/blenkernel/BKE_library.h
+++ b/source/blender/blenkernel/BKE_library.h
@@ -50,12 +50,41 @@ struct bContext;
struct PointerRNA;
struct PropertyRNA;
-void *BKE_libblock_alloc_notest(short type);
-void *BKE_libblock_alloc(struct Main *bmain, short type, const char *name) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-void BKE_libblock_init_empty(struct ID *id);
-void *BKE_libblock_copy(struct Main *bmain, struct ID *id) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-void *BKE_libblock_copy_nolib(struct ID *id, const bool do_action) ATTR_NONNULL();
-void BKE_libblock_copy_data(struct ID *id, const struct ID *id_from, const bool do_action);
+size_t BKE_libblock_get_alloc_info(short type, const char **name);
+void *BKE_libblock_alloc_notest(short type) ATTR_WARN_UNUSED_RESULT;
+void *BKE_libblock_alloc(struct Main *bmain, short type, const char *name, const int flag) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void BKE_libblock_init_empty(struct ID *id) ATTR_NONNULL(1);
+
+/**
+ * New ID creation/copying options.
+ */
+enum {
+ /* *** Generic options (should be handled by all ID types copying, ID creation, etc.). *** */
+ /* Create datablock outside of any main database - similar to 'localize' functions of materials etc. */
+ LIB_ID_CREATE_NO_MAIN = 1 << 0,
+ /* Do not affect user refcount of datablocks used by new one (which also gets zero usercount then).
+ * Implies LIB_ID_CREATE_NO_MAIN. */
+ LIB_ID_CREATE_NO_USER_REFCOUNT = 1 << 1,
+ /* Assume given 'newid' already points to allocated memory for whole datablock (ID + data) - USE WITH CAUTION!
+ * Implies LIB_ID_CREATE_NO_MAIN. */
+ LIB_ID_CREATE_NO_ALLOCATE = 1 << 2,
+
+ LIB_ID_CREATE_NO_DEG_TAG = 1 << 8, /* Do not tag new ID for update in depsgraph. */
+
+ /* Specific options to some ID types or usages, may be ignored by unrelated ID copying functions. */
+ LIB_ID_COPY_NO_PROXY_CLEAR = 1 << 16, /* Object only, needed by make_local code. */
+ LIB_ID_COPY_NO_PREVIEW = 1 << 17, /* Do not copy preview data, when supported. */
+ LIB_ID_COPY_CACHES = 1 << 18, /* Copy runtime data caches. */
+ /* XXX TODO Do we want to keep that? would rather try to get rid of it... */
+ LIB_ID_COPY_ACTIONS = 1 << 19, /* EXCEPTION! Deep-copy actions used by animdata of copied ID. */
+ LIB_ID_COPY_KEEP_LIB = 1 << 20, /* Keep the library pointer when copying datablock outside of bmain. */
+};
+
+void BKE_libblock_copy_ex(struct Main *bmain, const struct ID *id, struct ID **r_newid, const int flag);
+void *BKE_libblock_copy(struct Main *bmain, const struct ID *id) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/* "Deprecated" old API. */
+void *BKE_libblock_copy_nolib(const struct ID *id, const bool do_action) ATTR_NONNULL();
+
void BKE_libblock_rename(struct Main *bmain, struct ID *id, const char *name) ATTR_NONNULL();
void BLI_libblock_ensure_unique_name(struct Main *bmain, const char *name) ATTR_NONNULL();
@@ -63,12 +92,45 @@ struct ID *BKE_libblock_find_name_ex(struct Main *bmain, const short type, const
struct ID *BKE_libblock_find_name(const short type, const char *name) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
/* library_remap.c (keep here since they're general functions) */
-void BKE_libblock_free(struct Main *bmain, void *idv) ATTR_NONNULL();
+/**
+ * New freeing logic options.
+ */
+enum {
+ /* *** Generic options (should be handled by all ID types freeing). *** */
+ /* Do not try to remove freed ID from given Main (passed Main may be NULL). */
+ LIB_ID_FREE_NO_MAIN = 1 << 0,
+ /* Do not affect user refcount of datablocks used by freed one.
+ * Implies LIB_ID_FREE_NO_MAIN. */
+ LIB_ID_FREE_NO_USER_REFCOUNT = 1 << 1,
+ /* Assume freed ID datablock memory is managed elsewhere, do not free it
+ * (still calls relevant ID type's freeing function though) - USE WITH CAUTION!
+ * Implies LIB_ID_FREE_NO_MAIN. */
+ LIB_ID_FREE_NOT_ALLOCATED = 1 << 2,
+
+ LIB_ID_FREE_NO_DEG_TAG = 1 << 8, /* Do not tag freed ID for update in depsgraph. */
+ LIB_ID_FREE_NO_UI_USER = 1 << 9, /* Do not attempt to remove freed ID from UI data/notifiers/... */
+};
+
+void BKE_id_free_ex(struct Main *bmain, void *idv, int flag, const bool use_flag_from_idtag);
+void BKE_id_free(struct Main *bmain, void *idv);
+/* Those three naming are bad actually, should be BKE_id_free... (since it goes beyond mere datablock). */
+/* "Deprecated" old API */
void BKE_libblock_free_ex(struct Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user) ATTR_NONNULL();
+void BKE_libblock_free(struct Main *bmain, void *idv) ATTR_NONNULL();
void BKE_libblock_free_us(struct Main *bmain, void *idv) ATTR_NONNULL();
-void BKE_libblock_free_data(struct Main *bmain, struct ID *id) ATTR_NONNULL();
+
+void BKE_libblock_management_main_add(struct Main *bmain, void *idv);
+void BKE_libblock_management_main_remove(struct Main *bmain, void *idv);
+
+void BKE_libblock_management_usercounts_set(struct Main *bmain, void *idv);
+void BKE_libblock_management_usercounts_clear(struct Main *bmain, void *idv);
+
+/* TODO should be named "BKE_id_delete()". */
void BKE_libblock_delete(struct Main *bmain, void *idv) ATTR_NONNULL();
+void BKE_libblock_free_datablock(struct ID *id, const int flag) ATTR_NONNULL();
+void BKE_libblock_free_data(struct ID *id, const bool do_id_user) ATTR_NONNULL();
+
void BKE_id_lib_local_paths(struct Main *bmain, struct Library *lib, struct ID *id);
void id_lib_extern(struct ID *id);
void BKE_library_filepath_set(struct Library *lib, const char *filepath);
@@ -84,12 +146,13 @@ void BKE_id_clear_newpoin(struct ID *id);
void BKE_id_make_local_generic(struct Main *bmain, struct ID *id, const bool id_in_mainlist, const bool lib_local);
bool id_make_local(struct Main *bmain, struct ID *id, const bool test, const bool force_local);
bool id_single_user(struct bContext *C, struct ID *id, struct PointerRNA *ptr, struct PropertyRNA *prop);
-bool id_copy(struct Main *bmain, struct ID *id, struct ID **newid, bool test);
+bool id_copy(struct Main *bmain, const struct ID *id, struct ID **newid, bool test);
+bool BKE_id_copy_ex(struct Main *bmain, const struct ID *id, struct ID **r_newid, const int flag, const bool test);
void id_sort_by_name(struct ListBase *lb, struct ID *id);
void BKE_id_expand_local(struct Main *bmain, struct ID *id);
-void BKE_id_copy_ensure_local(struct Main *bmain, struct ID *old_id, struct ID *new_id);
+void BKE_id_copy_ensure_local(struct Main *bmain, const struct ID *old_id, struct ID *new_id);
-bool new_id(struct ListBase *lb, struct ID *id, const char *name);
+bool new_id(struct ListBase *lb, struct ID *id, const char *name) ATTR_NONNULL(1, 2);
void id_clear_lib_data(struct Main *bmain, struct ID *id);
void id_clear_lib_data_ex(struct Main *bmain, struct ID *id, const bool id_in_mainlist);
diff --git a/source/blender/blenkernel/BKE_library_query.h b/source/blender/blenkernel/BKE_library_query.h
index 1258e2fa72e..d6e7d98f371 100644
--- a/source/blender/blenkernel/BKE_library_query.h
+++ b/source/blender/blenkernel/BKE_library_query.h
@@ -51,6 +51,11 @@ enum {
* This means callback shall not *do* anything, only use this as informative data if it needs it. */
IDWALK_CB_PRIVATE = (1 << 3),
+ /** That ID is not really used by its owner, it's just an internal hint/helper.
+ * This addresses Their Highest Ugliness the 'from' pointers: Object->from_proxy and Key->from.
+ * How to handle that kind of cases totally depends on what caller code is doing... */
+ IDWALK_CB_LOOPBACK = (1 << 4),
+
/**
* Adjusts #ID.us reference-count.
* \note keep in sync with 'newlibadr_us' use in readfile.c
@@ -78,6 +83,8 @@ enum {
IDWALK_NOP = 0,
IDWALK_READONLY = (1 << 0),
IDWALK_RECURSE = (1 << 1), /* Also implies IDWALK_READONLY. */
+
+ IDWALK_NO_INDIRECT_PROXY_DATA_USAGE = (1 << 8), /* Ugly special case :(((( */
};
/* Loop over all of the ID's this datablock links to. */
@@ -87,7 +94,7 @@ void BKE_library_update_ID_link_user(struct ID *id_dst, struct ID *id_src, const
int BKE_library_ID_use_ID(struct ID *id_user, struct ID *id_used);
-bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id_type_used);
+bool BKE_library_id_can_use_idtype(struct ID *id_owner, const short id_type_used);
bool BKE_library_ID_is_locally_used(struct Main *bmain, void *idv);
bool BKE_library_ID_is_indirectly_used(struct Main *bmain, void *idv);
diff --git a/source/blender/blenkernel/BKE_library_remap.h b/source/blender/blenkernel/BKE_library_remap.h
index 53d438a0fdd..fd37fd762f4 100644
--- a/source/blender/blenkernel/BKE_library_remap.h
+++ b/source/blender/blenkernel/BKE_library_remap.h
@@ -46,6 +46,11 @@ enum {
/* This tells the callback func to force setting IDs using target one with a 'never NULL' pointer to NULL.
* WARNING! Use with extreme care, this will leave database in broken state and can cause crashes very easily! */
ID_REMAP_FORCE_NEVER_NULL_USAGE = 1 << 3,
+ /* Do not consider proxy/_group pointers of local objects as indirect usages...
+ * Our oh-so-beloved proxies again... Do not consider data used by local proxy object as indirect usage.
+ * This is needed e.g. in reload scenario, since we have to ensure remapping of Armature data of local proxy
+ * is also performed. Usual nightmare... */
+ ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE = 1 << 4,
};
/* Note: Requiring new_id to be non-null, this *may* not be the case ultimately, but makes things simpler for now. */
diff --git a/source/blender/blenkernel/BKE_linestyle.h b/source/blender/blenkernel/BKE_linestyle.h
index af9bf58ce77..3ba4fbe0338 100644
--- a/source/blender/blenkernel/BKE_linestyle.h
+++ b/source/blender/blenkernel/BKE_linestyle.h
@@ -52,7 +52,10 @@ struct bContext;
void BKE_linestyle_init(struct FreestyleLineStyle *linestyle);
FreestyleLineStyle *BKE_linestyle_new(struct Main *bmain, const char *name);
void BKE_linestyle_free(FreestyleLineStyle *linestyle);
-FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, FreestyleLineStyle *linestyle);
+void BKE_linestyle_copy_data(
+ struct Main *bmain, struct FreestyleLineStyle *linestyle_dst, const struct FreestyleLineStyle *linestyle_src,
+ const int flag);
+FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, const FreestyleLineStyle *linestyle);
void BKE_linestyle_make_local(struct Main *bmain, struct FreestyleLineStyle *linestyle, const bool lib_local);
@@ -63,10 +66,14 @@ LineStyleModifier *BKE_linestyle_alpha_modifier_add(FreestyleLineStyle *linestyl
LineStyleModifier *BKE_linestyle_thickness_modifier_add(FreestyleLineStyle *linestyle, const char *name, int type);
LineStyleModifier *BKE_linestyle_geometry_modifier_add(FreestyleLineStyle *linestyle, const char *name, int type);
-LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m);
-LineStyleModifier *BKE_linestyle_alpha_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m);
-LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m);
-LineStyleModifier *BKE_linestyle_geometry_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m);
+LineStyleModifier *BKE_linestyle_color_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag);
+LineStyleModifier *BKE_linestyle_alpha_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag);
+LineStyleModifier *BKE_linestyle_thickness_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag);
+LineStyleModifier *BKE_linestyle_geometry_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag);
int BKE_linestyle_color_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *modifier);
int BKE_linestyle_alpha_modifier_remove(FreestyleLineStyle *linestyle, LineStyleModifier *modifier);
diff --git a/source/blender/blenkernel/BKE_main.h b/source/blender/blenkernel/BKE_main.h
index 387045878f3..e224155726f 100644
--- a/source/blender/blenkernel/BKE_main.h
+++ b/source/blender/blenkernel/BKE_main.h
@@ -84,10 +84,12 @@ typedef struct Main {
short minversionfile, minsubversionfile;
uint64_t build_commit_timestamp; /* commit's timestamp from buildinfo */
char build_hash[16]; /* hash from buildinfo */
- short recovered; /* indicate the main->name (file) is the recovered one */
+ char recovered; /* indicate the main->name (file) is the recovered one */
+ /** All current ID's exist in the last memfile undo step. */
+ char is_memfile_undo_written;
BlendThumbnail *blen_thumb;
-
+
struct Library *curlib;
ListBase scene;
ListBase library;
@@ -145,7 +147,8 @@ typedef struct Main {
#define BLEN_THUMB_SIZE 128
-#define BLEN_THUMB_MEMSIZE(_x, _y) (sizeof(BlendThumbnail) + (size_t)((_x) * (_y)) * sizeof(int))
+#define BLEN_THUMB_MEMSIZE(_x, _y) (sizeof(BlendThumbnail) + ((size_t)(_x) * (size_t)(_y)) * sizeof(int))
+#define BLEN_THUMB_SAFE_MEMSIZE(_x, _y) ((uint64_t)_x * (uint64_t)_y < (SIZE_MAX / (sizeof(int) * 4)))
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_mask.h b/source/blender/blenkernel/BKE_mask.h
index 3349bffac85..5598f0dc473 100644
--- a/source/blender/blenkernel/BKE_mask.h
+++ b/source/blender/blenkernel/BKE_mask.h
@@ -32,6 +32,7 @@
* \ingroup bke
*/
+struct EvaluationContext;
struct ImageUser;
struct Image;
struct ListBase;
@@ -77,14 +78,14 @@ void BKE_mask_layer_free(struct MaskLayer *masklay);
void BKE_mask_layer_free_list(struct ListBase *masklayers);
void BKE_mask_spline_free(struct MaskSpline *spline);
void BKE_mask_spline_free_list(struct ListBase *splines);
-struct MaskSpline *BKE_mask_spline_copy(struct MaskSpline *spline);
+struct MaskSpline *BKE_mask_spline_copy(const struct MaskSpline *spline);
void BKE_mask_point_free(struct MaskSplinePoint *point);
void BKE_mask_layer_unique_name(struct Mask *mask, struct MaskLayer *masklay);
void BKE_mask_layer_rename(struct Mask *mask, struct MaskLayer *masklay, char *oldname, char *newname);
-struct MaskLayer *BKE_mask_layer_copy(struct MaskLayer *layer);
-void BKE_mask_layer_copy_list(struct ListBase *masklayers_new, struct ListBase *masklayers);
+struct MaskLayer *BKE_mask_layer_copy(const struct MaskLayer *layer);
+void BKE_mask_layer_copy_list(struct ListBase *masklayers_new, const struct ListBase *masklayers);
/* splines */
struct MaskSpline *BKE_mask_spline_add(struct MaskLayer *masklay);
@@ -122,8 +123,9 @@ void BKE_mask_point_select_set_handle(struct MaskSplinePoint *point, const eMask
/* general */
struct Mask *BKE_mask_new(struct Main *bmain, const char *name);
+void BKE_mask_copy_data(struct Main *bmain, struct Mask *mask_dst, const struct Mask *mask_src, const int flag);
struct Mask *BKE_mask_copy_nolib(struct Mask *mask);
-struct Mask *BKE_mask_copy(struct Main *bmain, struct Mask *mask);
+struct Mask *BKE_mask_copy(struct Main *bmain, const struct Mask *mask);
void BKE_mask_make_local(struct Main *bmain, struct Mask *mask, const bool lib_local);
@@ -232,6 +234,12 @@ float *BKE_mask_point_segment_feather_diff(struct MaskSpline *spline, struct Mas
int width, int height,
unsigned int *tot_feather_point);
+void BKE_mask_layer_evaluate_animation(struct MaskLayer *masklay, const float ctime);
+void BKE_mask_layer_evaluate_deform(struct MaskLayer *masklay, const float ctime);
+
+void BKE_mask_eval_animation(struct EvaluationContext *eval_ctx, struct Mask *mask);
+void BKE_mask_eval_update(struct EvaluationContext *eval_ctx, struct Mask *mask);
+
/* mask_rasterize.c */
struct MaskRasterHandle;
typedef struct MaskRasterHandle MaskRasterHandle;
diff --git a/source/blender/blenkernel/BKE_material.h b/source/blender/blenkernel/BKE_material.h
index 8ae5c2b3c45..f7850913014 100644
--- a/source/blender/blenkernel/BKE_material.h
+++ b/source/blender/blenkernel/BKE_material.h
@@ -54,8 +54,9 @@ void BKE_material_init(struct Material *ma);
void BKE_material_remap_object(struct Object *ob, const unsigned int *remap);
void BKE_material_remap_object_calc(struct Object *ob_dst, struct Object *ob_src, short *remap_src_to_dst);
struct Material *BKE_material_add(struct Main *bmain, const char *name);
-struct Material *BKE_material_copy(struct Main *bmain, struct Material *ma);
-struct Material *localize_material(struct Material *ma);
+void BKE_material_copy_data(struct Main *bmain, struct Material *ma_dst, const struct Material *ma_src, const int flag);
+struct Material *BKE_material_copy(struct Main *bmain, const struct Material *ma);
+struct Material *BKE_material_localize(struct Material *ma);
struct Material *give_node_material(struct Material *ma); /* returns node material or self */
void BKE_material_make_local(struct Main *bmain, struct Material *ma, const bool lib_local);
diff --git a/source/blender/blenkernel/BKE_mball.h b/source/blender/blenkernel/BKE_mball.h
index 64320a20281..f02704ba903 100644
--- a/source/blender/blenkernel/BKE_mball.h
+++ b/source/blender/blenkernel/BKE_mball.h
@@ -41,7 +41,8 @@ struct MetaElem;
void BKE_mball_free(struct MetaBall *mb);
void BKE_mball_init(struct MetaBall *mb);
struct MetaBall *BKE_mball_add(struct Main *bmain, const char *name);
-struct MetaBall *BKE_mball_copy(struct Main *bmain, struct MetaBall *mb);
+void BKE_mball_copy_data(struct Main *bmain, struct MetaBall *mb_dst, const struct MetaBall *mb_src, const int flag);
+struct MetaBall *BKE_mball_copy(struct Main *bmain, const struct MetaBall *mb);
void BKE_mball_make_local(struct Main *bmain, struct MetaBall *mb, const bool lib_local);
@@ -59,7 +60,7 @@ bool BKE_mball_minmax_ex(struct MetaBall *mb, float min[3], float max[3],
float obmat[4][4], const short flag);
bool BKE_mball_center_median(struct MetaBall *mb, float r_cent[3]);
bool BKE_mball_center_bounds(struct MetaBall *mb, float r_cent[3]);
-void BKE_mball_transform(struct MetaBall *mb, float mat[4][4]);
+void BKE_mball_transform(struct MetaBall *mb, float mat[4][4], const bool do_props);
void BKE_mball_translate(struct MetaBall *mb, const float offset[3]);
struct MetaElem *BKE_mball_element_add(struct MetaBall *mb, const int type);
diff --git a/source/blender/blenkernel/BKE_mesh.h b/source/blender/blenkernel/BKE_mesh.h
index b83bec5a302..bf135254941 100644
--- a/source/blender/blenkernel/BKE_mesh.h
+++ b/source/blender/blenkernel/BKE_mesh.h
@@ -87,7 +87,8 @@ int BKE_mesh_edge_other_vert(const struct MEdge *e, int v);
void BKE_mesh_free(struct Mesh *me);
void BKE_mesh_init(struct Mesh *me);
struct Mesh *BKE_mesh_add(struct Main *bmain, const char *name);
-struct Mesh *BKE_mesh_copy(struct Main *bmain, struct Mesh *me);
+void BKE_mesh_copy_data(struct Main *bmain, struct Mesh *me_dst, const struct Mesh *me_src, const int flag);
+struct Mesh *BKE_mesh_copy(struct Main *bmain, const struct Mesh *me);
void BKE_mesh_update_customdata_pointers(struct Mesh *me, const bool do_ensure_tess_cd);
void BKE_mesh_ensure_skin_customdata(struct Mesh *me);
@@ -110,7 +111,8 @@ int BKE_mesh_nurbs_displist_to_mdata(
struct MEdge **r_alledge, int *r_totedge,
struct MLoop **r_allloop, struct MPoly **r_allpoly,
struct MLoopUV **r_alluv, int *r_totloop, int *r_totpoly);
-void BKE_mesh_from_nurbs_displist(struct Object *ob, struct ListBase *dispbase, const bool use_orco_uv);
+void BKE_mesh_from_nurbs_displist(
+ struct Object *ob, struct ListBase *dispbase, const bool use_orco_uv, const char *obdata_name);
void BKE_mesh_from_nurbs(struct Object *ob);
void BKE_mesh_to_curve_nurblist(struct DerivedMesh *dm, struct ListBase *nurblist, const int edge_users_test);
void BKE_mesh_to_curve(struct Scene *scene, struct Object *ob);
@@ -193,6 +195,17 @@ void BKE_mesh_loop_tangents_ex(
struct ReportList *reports);
void BKE_mesh_loop_tangents(
struct Mesh *mesh, const char *uvmap, float (*r_looptangents)[4], struct ReportList *reports);
+void BKE_mesh_loop_manifold_fan_around_vert_next(
+ const struct MLoop *mloops, const struct MPoly *mpolys,
+ const int *loop_to_poly, const int *e2lfan_curr, const uint mv_pivot_index,
+ const struct MLoop **r_mlfan_curr, int *r_mlfan_curr_index, int *r_mlfan_vert_index, int *r_mpfan_curr_index);
+
+void BKE_edges_sharp_from_angle_set(
+ const struct MVert *mverts, const int numVerts,
+ struct MEdge *medges, const int numEdges,
+ struct MLoop *mloops, const int numLoops,
+ struct MPoly *mpolys, const float (*polynors)[3], const int numPolys,
+ const float split_angle);
/**
* References a contiguous loop-fan with normal offset vars.
@@ -203,17 +216,38 @@ typedef struct MLoopNorSpace {
float vec_ortho[3]; /* Third vector, orthogonal to vec_lnor and vec_ref. */
float ref_alpha; /* Reference angle, around vec_ortho, in ]0, pi] range (0.0 marks that space as invalid). */
float ref_beta; /* Reference angle, around vec_lnor, in ]0, 2pi] range (0.0 marks that space as invalid). */
- struct LinkNode *loops; /* All indices (uint_in_ptr) of loops using this lnor space (i.e. smooth fan of loops). */
+ /* All loops using this lnor space (i.e. smooth fan of loops),
+ * as (depending on owning MLoopNorSpaceArrary.data_type):
+ * - Indices (uint_in_ptr), or
+ * - BMLoop pointers. */
+ struct LinkNode *loops;
+ char flags;
} MLoopNorSpace;
/**
+ * MLoopNorSpace.flags
+ */
+enum {
+ MLNOR_SPACE_IS_SINGLE = 1 << 0,
+};
+
+/**
* Collection of #MLoopNorSpace basic storage & pre-allocation.
*/
typedef struct MLoopNorSpaceArray {
MLoopNorSpace **lspacearr; /* MLoop aligned array */
struct LinkNode *loops_pool; /* Allocated once, avoids to call BLI_linklist_prepend_arena() for each loop! */
+ char data_type; /* Whether we store loop indices, or pointers to BMLoop. */
struct MemArena *mem;
} MLoopNorSpaceArray;
-void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoops);
+/**
+ * MLoopNorSpaceArray.data_type
+ */
+enum {
+ MLNOR_SPACEARR_LOOP_INDEX = 0,
+ MLNOR_SPACEARR_BMLOOP_PTR = 1,
+};
+
+void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoops, const char data_type);
void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr);
void BKE_lnor_spacearr_free(MLoopNorSpaceArray *lnors_spacearr);
MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr);
@@ -221,7 +255,8 @@ void BKE_lnor_space_define(
MLoopNorSpace *lnor_space, const float lnor[3], float vec_ref[3], float vec_other[3],
struct BLI_Stack *edge_vectors);
void BKE_lnor_space_add_loop(
- MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space, const int ml_index, const bool add_to_list);
+ MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space,
+ const int ml_index, void *bm_loop, const bool is_single);
void BKE_lnor_space_custom_data_to_normal(MLoopNorSpace *lnor_space, const short clnor_data[2], float r_custom_lnor[3]);
void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space, const float custom_lnor[3], short r_clnor_data[2]);
@@ -234,7 +269,7 @@ void BKE_mesh_normals_loop_split(
const struct MVert *mverts, const int numVerts, struct MEdge *medges, const int numEdges,
struct MLoop *mloops, float (*r_loopnors)[3], const int numLoops,
struct MPoly *mpolys, const float (*polynors)[3], const int numPolys,
- const bool use_split_normals, float split_angle,
+ const bool use_split_normals, const float split_angle,
MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], int *r_loop_to_poly);
void BKE_mesh_normals_loop_custom_set(
@@ -278,7 +313,8 @@ void BKE_mesh_poly_edgebitmap_insert(
bool BKE_mesh_center_median(const struct Mesh *me, float r_cent[3]);
bool BKE_mesh_center_bounds(const struct Mesh *me, float r_cent[3]);
-bool BKE_mesh_center_centroid(const struct Mesh *me, float r_cent[3]);
+bool BKE_mesh_center_of_surface(const struct Mesh *me, float r_cent[3]);
+bool BKE_mesh_center_of_volume(const struct Mesh *me, float r_cent[3]);
void BKE_mesh_calc_volume(
const struct MVert *mverts, const int mverts_num,
diff --git a/source/blender/blenkernel/BKE_modifier.h b/source/blender/blenkernel/BKE_modifier.h
index b241b5ca5b7..18cde156f5e 100644
--- a/source/blender/blenkernel/BKE_modifier.h
+++ b/source/blender/blenkernel/BKE_modifier.h
@@ -127,6 +127,18 @@ typedef enum ModifierApplyFlag {
} ModifierApplyFlag;
+typedef struct ModifierUpdateDepsgraphContext {
+ struct Scene *scene;
+ struct Object *object;
+
+ /* Old depsgraph node handle. */
+ struct DagForest *forest;
+ struct DagNode *obNode;
+
+ /* new depsgraph node handle. */
+ struct DepsNodeHandle *node;
+} ModifierUpdateDepsgraphContext;
+
typedef struct ModifierTypeInfo {
/* The user visible name for this modifier */
char name[32];
@@ -265,9 +277,8 @@ typedef struct ModifierTypeInfo {
*
* This function is optional.
*/
- void (*updateDepgraph)(struct ModifierData *md, struct DagForest *forest,
- struct Main *bmain, struct Scene *scene,
- struct Object *ob, struct DagNode *obNode);
+ void (*updateDepgraph)(struct ModifierData *md,
+ const ModifierUpdateDepsgraphContext *ctx);
/* Add the appropriate relations to the dependency graph.
*
@@ -275,10 +286,7 @@ typedef struct ModifierTypeInfo {
*/
/* TODO(sergey): Remove once we finally switched to the new depsgraph. */
void (*updateDepsgraph)(struct ModifierData *md,
- struct Main *bmain,
- struct Scene *scene,
- struct Object *ob,
- struct DepsNodeHandle *node);
+ const ModifierUpdateDepsgraphContext *ctx);
/* Should return true if the modifier needs to be recalculated on time
* changes.
@@ -338,12 +346,14 @@ const ModifierTypeInfo *modifierType_getInfo(ModifierType type);
* default values if pointer is optional.
*/
struct ModifierData *modifier_new(int type);
+void modifier_free_ex(struct ModifierData *md, const int flag);
void modifier_free(struct ModifierData *md);
bool modifier_unique_name(struct ListBase *modifiers, struct ModifierData *md);
void modifier_copyData_generic(const struct ModifierData *md, struct ModifierData *target);
void modifier_copyData(struct ModifierData *md, struct ModifierData *target);
+void modifier_copyData_ex(struct ModifierData *md, struct ModifierData *target, const int flag);
bool modifier_dependsOnTime(struct ModifierData *md);
bool modifier_supportsMapping(struct ModifierData *md);
bool modifier_supportsCage(struct Scene *scene, struct ModifierData *md);
diff --git a/source/blender/blenkernel/BKE_movieclip.h b/source/blender/blenkernel/BKE_movieclip.h
index 3237c146bc5..818f79ad8ac 100644
--- a/source/blender/blenkernel/BKE_movieclip.h
+++ b/source/blender/blenkernel/BKE_movieclip.h
@@ -32,6 +32,7 @@
* \author Sergey Sharybin
*/
+struct EvaluationContext;
struct ImBuf;
struct Main;
struct MovieClip;
@@ -41,7 +42,8 @@ struct MovieDistortion;
void BKE_movieclip_free(struct MovieClip *clip);
-struct MovieClip *BKE_movieclip_copy(struct Main *bmain, struct MovieClip *clip);
+void BKE_movieclip_copy_data(struct Main *bmain, struct MovieClip *clip_dst, const struct MovieClip *clip_src, const int flag);
+struct MovieClip *BKE_movieclip_copy(struct Main *bmain, const struct MovieClip *clip);
void BKE_movieclip_make_local(struct Main *bmain, struct MovieClip *clip, const bool lib_local);
struct MovieClip *BKE_movieclip_file_add(struct Main *bmain, const char *name);
@@ -58,6 +60,7 @@ struct ImBuf *BKE_movieclip_get_ibuf_flag(struct MovieClip *clip, struct MovieCl
void BKE_movieclip_get_size(struct MovieClip *clip, struct MovieClipUser *user, int *width, int *height);
void BKE_movieclip_get_size_fl(struct MovieClip *clip, struct MovieClipUser *user, float size[2]);
int BKE_movieclip_get_duration(struct MovieClip *clip);
+float BKE_movieclip_get_fps(struct MovieClip *clip);
void BKE_movieclip_get_aspect(struct MovieClip *clip, float *aspx, float *aspy);
bool BKE_movieclip_has_frame(struct MovieClip *clip, struct MovieClipUser *user);
void BKE_movieclip_user_set_frame(struct MovieClipUser *user, int framenr);
@@ -72,8 +75,8 @@ void BKE_movieclip_build_proxy_frame(struct MovieClip *clip, int clip_flag, stru
void BKE_movieclip_build_proxy_frame_for_ibuf(struct MovieClip *clip, struct ImBuf *ibuf, struct MovieDistortion *distortion,
int cfra, int *build_sizes, int build_count, bool undistorted);
-float BKE_movieclip_remap_scene_to_clip_frame(struct MovieClip *clip, float framenr);
-float BKE_movieclip_remap_clip_to_scene_frame(struct MovieClip *clip, float framenr);
+float BKE_movieclip_remap_scene_to_clip_frame(const struct MovieClip *clip, float framenr);
+float BKE_movieclip_remap_clip_to_scene_frame(const struct MovieClip *clip, float framenr);
void BKE_movieclip_filename_for_frame(struct MovieClip *clip, struct MovieClipUser *user, char *name);
struct ImBuf *BKE_movieclip_anim_ibuf_for_frame(struct MovieClip *clip, struct MovieClipUser *user);
@@ -81,6 +84,9 @@ struct ImBuf *BKE_movieclip_anim_ibuf_for_frame(struct MovieClip *clip, struct M
bool BKE_movieclip_has_cached_frame(struct MovieClip *clip, struct MovieClipUser *user);
bool BKE_movieclip_put_frame_if_possible(struct MovieClip *clip, struct MovieClipUser *user, struct ImBuf *ibuf);
+/* Evaluaiton. */
+void BKE_movieclip_eval_update(struct EvaluationContext *eval_ctx, struct MovieClip *clip);
+
/* cacheing flags */
#define MOVIECLIP_CACHE_SKIP (1 << 0)
diff --git a/source/blender/blenkernel/BKE_nla.h b/source/blender/blenkernel/BKE_nla.h
index 3bf8bba47f5..4509d374b02 100644
--- a/source/blender/blenkernel/BKE_nla.h
+++ b/source/blender/blenkernel/BKE_nla.h
@@ -40,21 +40,24 @@ struct bAction;
struct Scene;
struct Speaker;
+struct PointerRNA;
+struct PropertyRNA;
+
/* ----------------------------- */
/* Data Management */
-void free_nlastrip(ListBase *strips, struct NlaStrip *strip);
-void free_nlatrack(ListBase *tracks, struct NlaTrack *nlt);
-void free_nladata(ListBase *tracks);
+void BKE_nlastrip_free(ListBase *strips, struct NlaStrip *strip);
+void BKE_nlatrack_free(ListBase *tracks, struct NlaTrack *nlt);
+void BKE_nla_tracks_free(ListBase *tracks);
-struct NlaStrip *copy_nlastrip(struct NlaStrip *strip, const bool use_same_action);
-struct NlaTrack *copy_nlatrack(struct NlaTrack *nlt, const bool use_same_actions);
-void copy_nladata(ListBase *dst, ListBase *src);
+struct NlaStrip *BKE_nlastrip_copy(struct NlaStrip *strip, const bool use_same_action);
+struct NlaTrack *BKE_nlatrack_copy(struct NlaTrack *nlt, const bool use_same_actions);
+void BKE_nla_tracks_copy(ListBase *dst, ListBase *src);
-struct NlaTrack *add_nlatrack(struct AnimData *adt, struct NlaTrack *prev);
-struct NlaStrip *add_nlastrip(struct bAction *act);
-struct NlaStrip *add_nlastrip_to_stack(struct AnimData *adt, struct bAction *act);
-struct NlaStrip *add_nla_soundstrip(struct Scene *scene, struct Speaker *spk);
+struct NlaTrack *BKE_nlatrack_add(struct AnimData *adt, struct NlaTrack *prev);
+struct NlaStrip *BKE_nlastrip_new(struct bAction *act);
+struct NlaStrip *BKE_nlastack_add_strip(struct AnimData *adt, struct bAction *act);
+struct NlaStrip *BKE_nla_add_soundstrip(struct Scene *scene, struct Speaker *spk);
/* ----------------------------- */
/* API */
@@ -103,6 +106,8 @@ bool BKE_nlatrack_has_animated_strips(struct NlaTrack *nlt);
bool BKE_nlatracks_have_animated_strips(ListBase *tracks);
void BKE_nlastrip_validate_fcurves(struct NlaStrip *strip);
+bool BKE_nlastrip_has_curves_for_property(const struct PointerRNA *ptr, const struct PropertyRNA *prop);
+
void BKE_nla_validate_state(struct AnimData *adt);
/* ............ */
diff --git a/source/blender/blenkernel/BKE_node.h b/source/blender/blenkernel/BKE_node.h
index 546f0d97c2b..efad8e48e3d 100644
--- a/source/blender/blenkernel/BKE_node.h
+++ b/source/blender/blenkernel/BKE_node.h
@@ -49,7 +49,7 @@
#include "RNA_types.h"
/* not very important, but the stack solver likes to know a maximum */
-#define MAX_SOCKET 64
+#define MAX_SOCKET 512
struct bContext;
struct bNode;
@@ -335,8 +335,9 @@ struct bNodeTree *ntreeAddTree(struct Main *bmain, const char *name, const char
/* copy/free funcs, need to manage ID users */
void ntreeFreeTree(struct bNodeTree *ntree);
-struct bNodeTree *ntreeCopyTree_ex(struct bNodeTree *ntree, struct Main *bmain, const bool do_id_user);
-struct bNodeTree *ntreeCopyTree(struct Main *bmain, struct bNodeTree *ntree);
+void BKE_node_tree_copy_data(struct Main *bmain, struct bNodeTree *ntree_dst, const struct bNodeTree *ntree_src, const int flag);
+struct bNodeTree *ntreeCopyTree_ex(const struct bNodeTree *ntree, struct Main *bmain, const bool do_id_user);
+struct bNodeTree *ntreeCopyTree(struct Main *bmain, const struct bNodeTree *ntree);
/* node->id user count */
void ntreeUserIncrefID(struct bNodeTree *ntree);
void ntreeUserDecrefID(struct bNodeTree *ntree);
@@ -445,6 +446,7 @@ struct bNodeSocket *nodeInsertStaticSocket(struct bNodeTree *ntree, struct bNode
struct bNodeSocket *next_sock, const char *identifier, const char *name);
void nodeRemoveSocket(struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *sock);
void nodeRemoveAllSockets(struct bNodeTree *ntree, struct bNode *node);
+void nodeModifySocketType(struct bNodeTree *ntree, struct bNode *node, struct bNodeSocket *sock, int type, int subtype);
struct bNode *nodeAddNode(const struct bContext *C, struct bNodeTree *ntree, const char *idname);
struct bNode *nodeAddStaticNode(const struct bContext *C, struct bNodeTree *ntree, int type);
@@ -452,6 +454,7 @@ void nodeUnlinkNode(struct bNodeTree *ntree, struct bNode *node);
void nodeUniqueName(struct bNodeTree *ntree, struct bNode *node);
void nodeFreeNode(struct bNodeTree *ntree, struct bNode *node);
+struct bNode *BKE_node_copy_ex(struct bNodeTree *ntree, struct bNode *node_src, const int flag);
struct bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node);
struct bNodeLink *nodeAddLink(struct bNodeTree *ntree, struct bNode *fromnode, struct bNodeSocket *fromsock, struct bNode *tonode, struct bNodeSocket *tosock);
@@ -510,7 +513,7 @@ int BKE_node_clipboard_get_type(void);
/* Node Instance Hash */
typedef struct bNodeInstanceHash {
- GHash *ghash; /* XXX should be made a direct member, GHash allocation needs to support it */
+ GHash *ghash; /* XXX should be made a direct member, GHash allocation needs to support it */
} bNodeInstanceHash;
typedef void (*bNodeInstanceValueFP)(void *value);
@@ -570,7 +573,6 @@ void BKE_node_preview_set_pixel(struct bNodePreview *preview, const f
/** \} */
-
/* -------------------------------------------------------------------- */
/** \name Node Type Access
* \{ */
@@ -600,6 +602,7 @@ void node_type_gpu(struct bNodeType *ntype, NodeGPUExecFunction gpufu
void node_type_internal_links(struct bNodeType *ntype, void (*update_internal_links)(struct bNodeTree *, struct bNode *));
void node_type_compatibility(struct bNodeType *ntype, short compatibility);
+/** \} */
/* -------------------------------------------------------------------- */
/** \name Node Generic Functions
@@ -689,7 +692,7 @@ bool BKE_node_tree_iter_step(struct NodeTreeIterStore *ntreeiter,
/* -------------------------------------------------------------------- */
/** \name Shader Nodes
- */
+ * \{ */
struct ShadeInput;
struct ShadeResult;
@@ -785,6 +788,11 @@ struct ShadeResult;
#define SH_NODE_OUTPUT_LINESTYLE 190
#define SH_NODE_UVALONGSTROKE 191
#define SH_NODE_TEX_POINTDENSITY 192
+#define SH_NODE_BSDF_PRINCIPLED 193
+#define SH_NODE_BEVEL 197
+#define SH_NODE_DISPLACEMENT 198
+#define SH_NODE_VECTOR_DISPLACEMENT 199
+#define SH_NODE_VOLUME_PRINCIPLED 200
/* custom defines options for Material node */
#define SH_NODE_MAT_DIFF 1
@@ -808,7 +816,7 @@ void ntreeGPUMaterialNodes(struct bNodeTree *ntree, struct GPUMateria
/* -------------------------------------------------------------------- */
/** \name Composite Nodes
- */
+ * \{ */
/* output socket defines */
#define RRES_OUT_IMAGE 0
@@ -972,7 +980,8 @@ void ntreeCompositExecTree(struct Scene *scene, struct bNodeTree *ntree, struct
void ntreeCompositTagRender(struct Scene *sce);
int ntreeCompositTagAnimated(struct bNodeTree *ntree);
void ntreeCompositTagGenerators(struct bNodeTree *ntree);
-void ntreeCompositForceHidden(struct bNodeTree *ntree);
+void ntreeCompositUpdateRLayers(struct bNodeTree *ntree);
+void ntreeCompositRegisterPass(struct bNodeTree *ntree, struct Scene *scene, struct SceneRenderLayer *srl, const char *name, int type);
void ntreeCompositClearTags(struct bNodeTree *ntree);
struct bNodeSocket *ntreeCompositOutputFileAddSocket(struct bNodeTree *ntree, struct bNode *node,
@@ -991,7 +1000,7 @@ void ntreeCompositColorBalanceSyncFromCDL(bNodeTree *ntree, bNode *node);
/* -------------------------------------------------------------------- */
/** \name Texture Nodes
- */
+ * \{ */
struct TexResult;
diff --git a/source/blender/blenkernel/BKE_object.h b/source/blender/blenkernel/BKE_object.h
index 89adbc4338f..7cc43f33e3a 100644
--- a/source/blender/blenkernel/BKE_object.h
+++ b/source/blender/blenkernel/BKE_object.h
@@ -53,10 +53,10 @@ void BKE_object_workob_clear(struct Object *workob);
void BKE_object_workob_calc_parent(struct Scene *scene, struct Object *ob, struct Object *workob);
void BKE_object_transform_copy(struct Object *ob_tar, const struct Object *ob_src);
-struct SoftBody *copy_softbody(const struct SoftBody *sb, bool copy_caches);
-struct BulletSoftBody *copy_bulletsoftbody(struct BulletSoftBody *sb);
-struct ParticleSystem *BKE_object_copy_particlesystem(struct ParticleSystem *psys);
-void BKE_object_copy_particlesystems(struct Object *ob_dst, const struct Object *ob_src);
+struct SoftBody *copy_softbody(const struct SoftBody *sb, const int flag);
+struct BulletSoftBody *copy_bulletsoftbody(const struct BulletSoftBody *sb, const int flag);
+struct ParticleSystem *BKE_object_copy_particlesystem(struct ParticleSystem *psys, const int flag);
+void BKE_object_copy_particlesystems(struct Object *ob_dst, const struct Object *ob_src, const int flag);
void BKE_object_copy_softbody(struct Object *ob_dst, const struct Object *ob_src);
void BKE_object_free_particlesystems(struct Object *ob);
void BKE_object_free_softbody(struct Object *ob);
@@ -70,18 +70,18 @@ void BKE_object_free_caches(struct Object *object);
void BKE_object_modifier_hook_reset(struct Object *ob, struct HookModifierData *hmd);
-bool BKE_object_support_modifier_type_check(struct Object *ob, int modifier_type);
+bool BKE_object_support_modifier_type_check(const struct Object *ob, int modifier_type);
void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_src);
-void BKE_object_free_modifiers(struct Object *ob);
+void BKE_object_free_modifiers(struct Object *ob, const int flag);
void BKE_object_make_proxy(struct Object *ob, struct Object *target, struct Object *gob);
void BKE_object_copy_proxy_drivers(struct Object *ob, struct Object *target);
-bool BKE_object_exists_check(struct Object *obtest);
-bool BKE_object_is_in_editmode(struct Object *ob);
-bool BKE_object_is_in_editmode_vgroup(struct Object *ob);
-bool BKE_object_is_in_wpaint_select_vert(struct Object *ob);
+bool BKE_object_exists_check(const struct Object *obtest);
+bool BKE_object_is_in_editmode(const struct Object *ob);
+bool BKE_object_is_in_editmode_vgroup(const struct Object *ob);
+bool BKE_object_is_in_wpaint_select_vert(const struct Object *ob);
void BKE_object_init(struct Object *ob);
struct Object *BKE_object_add_only_object(
@@ -105,12 +105,12 @@ bool BKE_object_lod_is_usable(struct Object *ob, struct Scene *scene);
struct Object *BKE_object_lod_meshob_get(struct Object *ob, struct Scene *scene);
struct Object *BKE_object_lod_matob_get(struct Object *ob, struct Scene *scene);
-struct Object *BKE_object_copy_ex(struct Main *bmain, struct Object *ob, bool copy_caches);
-struct Object *BKE_object_copy(struct Main *bmain, struct Object *ob);
+void BKE_object_copy_data(struct Main *bmain, struct Object *ob_dst, const struct Object *ob_src, const int flag);
+struct Object *BKE_object_copy(struct Main *bmain, const struct Object *ob);
void BKE_object_make_local(struct Main *bmain, struct Object *ob, const bool lib_local);
void BKE_object_make_local_ex(struct Main *bmain, struct Object *ob, const bool lib_local, const bool clear_proxy);
-bool BKE_object_is_libdata(struct Object *ob);
-bool BKE_object_obdata_is_libdata(struct Object *ob);
+bool BKE_object_is_libdata(const struct Object *ob);
+bool BKE_object_obdata_is_libdata(const struct Object *ob);
void BKE_object_obdata_size_init(struct Object *ob, const float scale);
@@ -122,15 +122,17 @@ void BKE_object_to_mat4(struct Object *ob, float mat[4][4]);
void BKE_object_apply_mat4(struct Object *ob, float mat[4][4], const bool use_compat, const bool use_parent);
void BKE_object_matrix_local_get(struct Object *ob, float mat[4][4]);
-bool BKE_object_pose_context_check(struct Object *ob);
+bool BKE_object_pose_context_check(const struct Object *ob);
struct Object *BKE_object_pose_armature_get(struct Object *ob);
void BKE_object_get_parent_matrix(struct Scene *scene, struct Object *ob, struct Object *par, float parentmat[4][4]);
void BKE_object_where_is_calc(struct Scene *scene, struct Object *ob);
-void BKE_object_where_is_calc_ex(struct Scene *scene, struct RigidBodyWorld *rbw, struct Object *ob, float r_originmat[3][3]);
+void BKE_object_where_is_calc_ex(
+ struct Scene *scene, struct RigidBodyWorld *rbw, struct Object *ob, float r_originmat[3][3]);
void BKE_object_where_is_calc_time(struct Scene *scene, struct Object *ob, float ctime);
-void BKE_object_where_is_calc_time_ex(struct Scene *scene, struct Object *ob, float ctime,
- struct RigidBodyWorld *rbw, float r_originmat[3][3]);
+void BKE_object_where_is_calc_time_ex(
+ struct Scene *scene, struct Object *ob, float ctime,
+ struct RigidBodyWorld *rbw, float r_originmat[3][3]);
void BKE_object_where_is_calc_mat4(struct Scene *scene, struct Object *ob, float obmat[4][4]);
/* possibly belong in own moduke? */
@@ -146,15 +148,18 @@ void BKE_object_dimensions_set(struct Object *ob, const float value[3]);
void BKE_object_empty_draw_type_set(struct Object *ob, const int value);
void BKE_object_boundbox_flag(struct Object *ob, int flag, const bool set);
void BKE_object_minmax(struct Object *ob, float r_min[3], float r_max[3], const bool use_hidden);
-bool BKE_object_minmax_dupli(struct Scene *scene, struct Object *ob, float r_min[3], float r_max[3], const bool use_hidden);
+bool BKE_object_minmax_dupli(
+ struct Scene *scene, struct Object *ob, float r_min[3], float r_max[3], const bool use_hidden);
/* sometimes min-max isn't enough, we need to loop over each point */
-void BKE_object_foreach_display_point(struct Object *ob, float obmat[4][4],
- void (*func_cb)(const float[3], void *), void *user_data);
-void BKE_scene_foreach_display_point(struct Scene *scene,
- struct View3D *v3d,
- const short flag,
- void (*func_cb)(const float[3], void *), void *user_data);
+void BKE_object_foreach_display_point(
+ struct Object *ob, float obmat[4][4],
+ void (*func_cb)(const float[3], void *), void *user_data);
+void BKE_scene_foreach_display_point(
+ struct Scene *scene,
+ struct View3D *v3d,
+ const short flag,
+ void (*func_cb)(const float[3], void *), void *user_data);
bool BKE_object_parent_loop_check(const struct Object *parent, const struct Object *ob);
@@ -170,44 +175,61 @@ typedef struct ObjectTfmProtectedChannels {
float rotAngle, drotAngle;
} ObjectTfmProtectedChannels;
-void BKE_object_tfm_protected_backup(const struct Object *ob,
- ObjectTfmProtectedChannels *obtfm);
+void BKE_object_tfm_protected_backup(
+ const struct Object *ob,
+ ObjectTfmProtectedChannels *obtfm);
-void BKE_object_tfm_protected_restore(struct Object *ob,
- const ObjectTfmProtectedChannels *obtfm,
- const short protectflag);
+void BKE_object_tfm_protected_restore(
+ struct Object *ob,
+ const ObjectTfmProtectedChannels *obtfm,
+ const short protectflag);
/* Dependency graph evaluation callbacks. */
-void BKE_object_eval_local_transform(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
-void BKE_object_eval_parent(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
-void BKE_object_eval_constraints(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
+void BKE_object_eval_local_transform(
+ struct EvaluationContext *eval_ctx,
+ struct Object *ob);
+void BKE_object_eval_parent(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
+void BKE_object_eval_constraints(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
void BKE_object_eval_done(struct EvaluationContext *eval_ctx, struct Object *ob);
-void BKE_object_eval_modifier(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob,
- struct ModifierData *md);
-void BKE_object_eval_uber_transform(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
-void BKE_object_eval_uber_data(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
-
-void BKE_object_handle_data_update(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob);
+bool BKE_object_eval_proxy_copy(
+ struct EvaluationContext *eval_ctx,
+ struct Object *object);
+void BKE_object_eval_uber_transform(
+ struct EvaluationContext *eval_ctx,
+ struct Object *ob);
+void BKE_object_eval_uber_data(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
+
+void BKE_object_eval_cloth(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *object);
+
+
+void BKE_object_eval_transform_all(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *object);
+
+void BKE_object_handle_data_update(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
void BKE_object_handle_update(struct EvaluationContext *eval_ctx, struct Scene *scene, struct Object *ob);
-void BKE_object_handle_update_ex(struct EvaluationContext *eval_ctx,
- struct Scene *scene, struct Object *ob,
- struct RigidBodyWorld *rbw,
- const bool do_proxy_update);
+void BKE_object_handle_update_ex(
+ struct EvaluationContext *eval_ctx,
+ struct Scene *scene, struct Object *ob,
+ struct RigidBodyWorld *rbw,
+ const bool do_proxy_update);
void BKE_object_sculpt_modifiers_changed(struct Object *ob);
int BKE_object_obdata_texspace_get(struct Object *ob, short **r_texflag, float **r_loc, float **r_size, float **r_rot);
@@ -220,7 +242,7 @@ bool BKE_object_shapekey_free(struct Main *bmain, struct Object *ob);
bool BKE_object_flag_test_recursive(const struct Object *ob, short flag);
-bool BKE_object_is_child_recursive(struct Object *ob_parent, struct Object *ob_child);
+bool BKE_object_is_child_recursive(const struct Object *ob_parent, const struct Object *ob_child);
bool BKE_object_is_animated(struct Scene *scene, struct Object *ob);
/* return ModifierMode flag */
@@ -250,7 +272,8 @@ typedef enum eObjectSet {
OB_SET_ALL /* All Objects */
} eObjectSet;
-struct LinkNode *BKE_object_relational_superset(struct Scene *scene, eObjectSet objectSet, eObRelationTypes includeFilter);
+struct LinkNode *BKE_object_relational_superset(
+ struct Scene *scene, eObjectSet objectSet, eObRelationTypes includeFilter);
struct LinkNode *BKE_object_groups(struct Object *ob);
void BKE_object_groups_clear(struct Scene *scene, struct Base *base, struct Object *object);
@@ -258,9 +281,10 @@ struct KDTree *BKE_object_as_kdtree(struct Object *ob, int *r_tot);
bool BKE_object_modifier_use_time(struct Object *ob, struct ModifierData *md);
-bool BKE_object_modifier_update_subframe(struct Scene *scene, struct Object *ob, bool update_mesh,
- int parent_recursion, float frame,
- int type);
+bool BKE_object_modifier_update_subframe(
+ struct Scene *scene, struct Object *ob, bool update_mesh,
+ int parent_recursion, float frame,
+ int type);
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_object_deform.h b/source/blender/blenkernel/BKE_object_deform.h
index 19a2220006a..ab54330cf53 100644
--- a/source/blender/blenkernel/BKE_object_deform.h
+++ b/source/blender/blenkernel/BKE_object_deform.h
@@ -54,7 +54,8 @@ void BKE_object_defgroup_remove(struct Object *ob, struct bDeformGroup *defgroup
void BKE_object_defgroup_remove_all_ex(struct Object *ob, bool only_unlocked);
void BKE_object_defgroup_remove_all(struct Object *ob);
-
+int *BKE_object_defgroup_index_map_create(struct Object *ob_src, struct Object *ob_dst, int *r_map_len);
+void BKE_object_defgroup_index_map_apply(struct MDeformVert *dvert, int dvert_len, const int *map, int map_len);
/* Select helpers */
enum eVGroupSelect;
diff --git a/source/blender/blenkernel/BKE_paint.h b/source/blender/blenkernel/BKE_paint.h
index 0a3cc950f32..285b9b3f99f 100644
--- a/source/blender/blenkernel/BKE_paint.h
+++ b/source/blender/blenkernel/BKE_paint.h
@@ -58,14 +58,16 @@ struct Tex;
struct ImagePool;
struct UnifiedPaintSettings;
-enum OverlayFlags;
+enum eOverlayFlags;
+
+#include "DNA_object_enums.h"
extern const char PAINT_CURSOR_SCULPT[3];
extern const char PAINT_CURSOR_VERTEX_PAINT[3];
extern const char PAINT_CURSOR_WEIGHT_PAINT[3];
extern const char PAINT_CURSOR_TEXTURE_PAINT[3];
-typedef enum PaintMode {
+typedef enum ePaintMode {
ePaintSculpt = 0,
ePaintVertex = 1,
ePaintWeight = 2,
@@ -73,17 +75,17 @@ typedef enum PaintMode {
ePaintTexture2D = 4,
ePaintSculptUV = 5,
ePaintInvalid = 6
-} PaintMode;
+} ePaintMode;
/* overlay invalidation */
-typedef enum OverlayControlFlags {
+typedef enum eOverlayControlFlags {
PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY = 1,
PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY = (1 << 2),
PAINT_INVALID_OVERLAY_CURVE = (1 << 3),
PAINT_OVERLAY_OVERRIDE_CURSOR = (1 << 4),
PAINT_OVERLAY_OVERRIDE_PRIMARY = (1 << 5),
PAINT_OVERLAY_OVERRIDE_SECONDARY = (1 << 6)
-} OverlayControlFlags;
+} eOverlayControlFlags;
#define PAINT_OVERRIDE_MASK (PAINT_OVERLAY_OVERRIDE_SECONDARY | \
PAINT_OVERLAY_OVERRIDE_PRIMARY | \
@@ -92,14 +94,16 @@ typedef enum OverlayControlFlags {
void BKE_paint_invalidate_overlay_tex(struct Scene *scene, const struct Tex *tex);
void BKE_paint_invalidate_cursor_overlay(struct Scene *scene, struct CurveMapping *curve);
void BKE_paint_invalidate_overlay_all(void);
-OverlayControlFlags BKE_paint_get_overlay_flags(void);
-void BKE_paint_reset_overlay_invalid(OverlayControlFlags flag);
-void BKE_paint_set_overlay_override(enum OverlayFlags flag);
+eOverlayControlFlags BKE_paint_get_overlay_flags(void);
+void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag);
+void BKE_paint_set_overlay_override(enum eOverlayFlags flag);
/* palettes */
void BKE_palette_free(struct Palette *palette);
struct Palette *BKE_palette_add(struct Main *bmain, const char *name);
-struct Palette *BKE_palette_copy(struct Main *bmain, struct Palette *palette);
+void BKE_palette_copy_data(
+ struct Main *bmain, struct Palette *palette_dst, const struct Palette *palette_src, const int flag);
+struct Palette *BKE_palette_copy(struct Main *bmain, const struct Palette *palette);
void BKE_palette_make_local(struct Main *bmain, struct Palette *palette, const bool lib_local);
struct PaletteColor *BKE_palette_color_add(struct Palette *palette);
bool BKE_palette_is_empty(const struct Palette *palette);
@@ -109,20 +113,22 @@ void BKE_palette_clear(struct Palette *palette);
/* paint curves */
struct PaintCurve *BKE_paint_curve_add(struct Main *bmain, const char *name);
void BKE_paint_curve_free(struct PaintCurve *pc);
-struct PaintCurve *BKE_paint_curve_copy(struct Main *bmain, struct PaintCurve *pc);
+void BKE_paint_curve_copy_data(
+ struct Main *bmain, struct PaintCurve *pc_dst, const struct PaintCurve *pc_src, const int flag);
+struct PaintCurve *BKE_paint_curve_copy(struct Main *bmain, const struct PaintCurve *pc);
void BKE_paint_curve_make_local(struct Main *bmain, struct PaintCurve *pc, const bool lib_local);
-void BKE_paint_init(struct Scene *sce, PaintMode mode, const char col[3]);
+void BKE_paint_init(struct Scene *sce, ePaintMode mode, const char col[3]);
void BKE_paint_free(struct Paint *p);
-void BKE_paint_copy(struct Paint *src, struct Paint *tar);
+void BKE_paint_copy(struct Paint *src, struct Paint *tar, const int flag);
void BKE_paint_cavity_curve_preset(struct Paint *p, int preset);
-short BKE_paint_object_mode_from_paint_mode(PaintMode mode);
-struct Paint *BKE_paint_get_active_from_paintmode(struct Scene *sce, PaintMode mode);
+eObjectMode BKE_paint_object_mode_from_paint_mode(ePaintMode mode);
+struct Paint *BKE_paint_get_active_from_paintmode(struct Scene *sce, ePaintMode mode);
struct Paint *BKE_paint_get_active(struct Scene *sce);
struct Paint *BKE_paint_get_active_from_context(const struct bContext *C);
-PaintMode BKE_paintmode_get_active_from_context(const struct bContext *C);
+ePaintMode BKE_paintmode_get_active_from_context(const struct bContext *C);
struct Brush *BKE_paint_brush(struct Paint *paint);
void BKE_paint_brush_set(struct Paint *paint, struct Brush *br);
struct Palette *BKE_paint_palette(struct Paint *paint);
@@ -151,11 +157,19 @@ float paint_grid_paint_mask(const struct GridPaintMask *gpm, unsigned level,
unsigned x, unsigned y);
/* stroke related */
-void paint_calculate_rake_rotation(struct UnifiedPaintSettings *ups, struct Brush *brush, const float mouse_pos[2]);
+bool paint_calculate_rake_rotation(struct UnifiedPaintSettings *ups, struct Brush *brush, const float mouse_pos[2]);
void paint_update_brush_rake_rotation(struct UnifiedPaintSettings *ups, struct Brush *brush, float rotation);
void BKE_paint_stroke_get_average(struct Scene *scene, struct Object *ob, float stroke[3]);
+/* Used for both vertex color and weight paint */
+struct SculptVertexPaintGeomMap {
+ int *vert_map_mem;
+ struct MeshElemMap *vert_to_loop;
+ int *poly_map_mem;
+ struct MeshElemMap *vert_to_poly;
+};
+
/* Session data (mode-specific) */
typedef struct SculptSession {
@@ -182,6 +196,7 @@ typedef struct SculptSession {
/* PBVH acceleration structure */
struct PBVH *pbvh;
bool show_diffuse_color;
+ bool show_mask;
/* Painting on deformed mesh */
bool modifiers_active; /* object is deformed with some modifiers */
@@ -199,12 +214,38 @@ typedef struct SculptSession {
/* Layer brush persistence between strokes */
float (*layer_co)[3]; /* Copy of the mesh vertices' locations */
- struct SculptStroke *stroke;
struct StrokeCache *cache;
+
+ union {
+ struct {
+ struct SculptVertexPaintGeomMap gmap;
+
+ /* For non-airbrush painting to re-apply from the original (MLoop aligned). */
+ unsigned int *previous_color;
+ } vpaint;
+
+ struct {
+ struct SculptVertexPaintGeomMap gmap;
+ /* Keep track of how much each vertex has been painted (non-airbrush only). */
+ float *alpha_weight;
+
+ /* Needed to continuously re-apply over the same weights (BRUSH_ACCUMULATE disabled).
+ * Lazy initialize as needed (flag is set to 1 to tag it as uninitialized). */
+ struct MDeformVert *dvert_prev;
+ } wpaint;
+
+ /* TODO: identify sculpt-only fields */
+ // struct { ... } sculpt;
+ } mode;
+ int mode_type;
+
+ /* This flag prevents PBVH from being freed when creating the vp_handle for texture paint. */
+ bool building_vp_handle;
} SculptSession;
void BKE_sculptsession_free(struct Object *ob);
void BKE_sculptsession_free_deformMats(struct SculptSession *ss);
+void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss);
void BKE_sculptsession_bm_to_me(struct Object *ob, bool reorder);
void BKE_sculptsession_bm_to_me_for_render(struct Object *object);
void BKE_sculpt_update_mesh_elements(struct Scene *scene, struct Sculpt *sd, struct Object *ob,
@@ -212,6 +253,7 @@ void BKE_sculpt_update_mesh_elements(struct Scene *scene, struct Sculpt *sd, str
struct MultiresModifierData *BKE_sculpt_multires_active(struct Scene *scene, struct Object *ob);
int BKE_sculpt_mask_layers_ensure(struct Object *ob,
struct MultiresModifierData *mmd);
+void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene);
enum {
SCULPT_MASK_LAYER_CALC_VERT = (1 << 0),
diff --git a/source/blender/blenkernel/BKE_particle.h b/source/blender/blenkernel/BKE_particle.h
index e5967be0bc7..0cda7dceb33 100644
--- a/source/blender/blenkernel/BKE_particle.h
+++ b/source/blender/blenkernel/BKE_particle.h
@@ -112,6 +112,7 @@ typedef struct ParticleTexture {
float damp, gravity, field; /* used in physics */
float length, clump, kink_freq, kink_amp, effector; /* used in path caching */
float rough1, rough2, roughe; /* used in path caching */
+ float twist; /* used in path caching */
} ParticleTexture;
typedef struct ParticleSeam {
@@ -159,9 +160,11 @@ typedef struct ParticleThreadContext {
float *vg_length, *vg_clump, *vg_kink;
float *vg_rough1, *vg_rough2, *vg_roughe;
float *vg_effector;
+ float *vg_twist;
struct CurveMapping *clumpcurve;
struct CurveMapping *roughcurve;
+ struct CurveMapping *twistcurve;
} ParticleThreadContext;
typedef struct ParticleTask {
@@ -207,7 +210,7 @@ typedef struct ParticleCollisionElement {
typedef struct ParticleCollision {
struct Object *current;
struct Object *hit;
- struct Object *skip[PARTICLE_COLLISION_MAX_COLLISIONS+1];
+ struct Object *skip[PARTICLE_COLLISION_MAX_COLLISIONS + 1];
struct Object *emitter;
struct CollisionModifierData *md; // collision modifier for current object;
@@ -243,7 +246,8 @@ typedef struct ParticleDrawData {
float *cdata, *cd; /* color data */
float *vedata, *ved; /* velocity data */
float *ma_col;
- int tot_vec_size, flag;
+ int totpart, partsize;
+ int flag;
int totpoint, totve;
} ParticleDrawData;
@@ -323,8 +327,11 @@ struct ParticleSystemModifierData *psys_get_modifier(struct Object *ob, struct P
struct ModifierData *object_add_particle_system(struct Scene *scene, struct Object *ob, const char *name);
void object_remove_particle_system(struct Scene *scene, struct Object *ob);
-struct ParticleSettings *psys_new_settings(const char *name, struct Main *main);
-struct ParticleSettings *BKE_particlesettings_copy(struct Main *bmain, struct ParticleSettings *part);
+struct ParticleSettings *BKE_particlesettings_add(struct Main *main, const char *name);
+void BKE_particlesettings_copy_data(
+ struct Main *bmain, struct ParticleSettings *part_dst, const struct ParticleSettings *part_src,
+ const int flag);
+struct ParticleSettings *BKE_particlesettings_copy(struct Main *bmain, const struct ParticleSettings *part);
void BKE_particlesettings_make_local(struct Main *bmain, struct ParticleSettings *part, const bool lib_local);
void psys_reset(struct ParticleSystem *psys, int mode);
@@ -345,6 +352,7 @@ int psys_get_particle_state(struct ParticleSimulationData *sim, int p, struct Pa
/* child paths */
void BKE_particlesettings_clump_curve_init(struct ParticleSettings *part);
void BKE_particlesettings_rough_curve_init(struct ParticleSettings *part);
+void BKE_particlesettings_twist_curve_init(struct ParticleSettings *part);
void psys_apply_child_modifiers(struct ParticleThreadContext *ctx, struct ListBase *modifiers,
struct ChildParticle *cpa, struct ParticleTexture *ptex, const float orco[3], const float ornor[3], float hairmat[4][4],
struct ParticleCacheKey *keys, struct ParticleCacheKey *parent_keys, const float parent_orco[3]);
@@ -473,9 +481,8 @@ typedef struct ParticleRenderData {
struct EvaluationContext;
-void BKE_particle_system_eval(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob,
- struct ParticleSystem *psys);
+void BKE_particle_system_eval_init(struct EvaluationContext *eval_ctx,
+ struct Scene *scene,
+ struct Object *ob);
#endif
diff --git a/source/blender/blenkernel/BKE_pbvh.h b/source/blender/blenkernel/BKE_pbvh.h
index 927303f8b3c..f619133ee4b 100644
--- a/source/blender/blenkernel/BKE_pbvh.h
+++ b/source/blender/blenkernel/BKE_pbvh.h
@@ -32,6 +32,7 @@
struct CCGElem;
struct CCGKey;
+struct CCGDerivedMesh;
struct CustomData;
struct DMFlagMat;
struct MPoly;
@@ -58,6 +59,8 @@ typedef bool (*BKE_pbvh_SearchCallback)(PBVHNode *node, void *data);
typedef void (*BKE_pbvh_HitCallback)(PBVHNode *node, void *data);
typedef void (*BKE_pbvh_HitOccludedCallback)(PBVHNode *node, void *data, float *tmin);
+typedef void (*BKE_pbvh_SearchNearestCallback)(PBVHNode *node, void *data, float *tmin);
+
/* Building */
PBVH *BKE_pbvh_new(void);
@@ -71,7 +74,7 @@ void BKE_pbvh_build_grids(PBVH *bvh, struct CCGElem **grid_elems,
struct CCGKey *key, void **gridfaces, struct DMFlagMat *flagmats,
unsigned int **grid_hidden);
void BKE_pbvh_build_bmesh(PBVH *bvh, struct BMesh *bm, bool smooth_shading, struct BMLog *log, const int cd_vert_node_offset, const int cd_face_node_offset);
-
+void BKE_pbvh_set_ccgdm(PBVH *bvh, struct CCGDerivedMesh *ccgdm);
void BKE_pbvh_free(PBVH *bvh);
void BKE_pbvh_free_layer_disp(PBVH *bvh);
@@ -100,12 +103,12 @@ void BKE_pbvh_raycast(
bool BKE_pbvh_node_raycast(
PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
const float ray_start[3], const float ray_normal[3],
- float *dist);
+ float *depth);
bool BKE_pbvh_bmesh_node_raycast_detail(
PBVHNode *node,
const float ray_start[3], const float ray_normal[3],
- float *dist, float *r_detail);
+ float *depth, float *r_detail);
/* for orthographic cameras, project the far away ray segment points to the root node so
* we can have better precision. */
@@ -113,11 +116,22 @@ void BKE_pbvh_raycast_project_ray_root(
PBVH *bvh, bool original,
float ray_start[3], float ray_end[3], float ray_normal[3]);
+void BKE_pbvh_find_nearest_to_ray(
+ PBVH *bvh, BKE_pbvh_HitOccludedCallback cb, void *data,
+ const float ray_start[3], const float ray_normal[3],
+ bool original);
+
+bool BKE_pbvh_node_find_nearest_to_ray(
+ PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
+ const float ray_start[3], const float ray_normal[3],
+ float *depth, float *dist_sq);
+
/* Drawing */
void BKE_pbvh_node_draw(PBVHNode *node, void *data);
void BKE_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*face_nors)[3],
int (*setMaterial)(int matnr, void *attribs), bool wireframe, bool fast);
+void BKE_pbvh_draw_BB(PBVH *bvh);
/* PBVH Access */
typedef enum {
@@ -141,6 +155,7 @@ int BKE_pbvh_count_grid_quads(BLI_bitmap **grid_hidden,
/* multires level, only valid for type == PBVH_GRIDS */
void BKE_pbvh_get_grid_key(const PBVH *pbvh, struct CCGKey *key);
+struct CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh);
/* Only valid for type == PBVH_BMESH */
struct BMesh *BKE_pbvh_get_bmesh(PBVH *pbvh);
@@ -153,7 +168,7 @@ typedef enum {
bool BKE_pbvh_bmesh_update_topology(
PBVH *bvh, PBVHTopologyUpdateMode mode,
const float center[3], const float view_normal[3],
- float radius);
+ float radius, const bool use_frontface, const bool use_projected);
/* Node Access */
@@ -355,5 +370,6 @@ bool BKE_pbvh_node_vert_update_check_any(PBVH *bvh, PBVHNode *node);
//void BKE_pbvh_node_BB_expand(PBVHNode *node, float co[3]);
void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color);
+void pbvh_show_mask_set(PBVH *bvh, bool show_mask);
#endif /* __BKE_PBVH_H__ */
diff --git a/source/blender/blenkernel/BKE_pointcache.h b/source/blender/blenkernel/BKE_pointcache.h
index 02f6c435ee2..cc60df1b2d6 100644
--- a/source/blender/blenkernel/BKE_pointcache.h
+++ b/source/blender/blenkernel/BKE_pointcache.h
@@ -34,7 +34,7 @@
#include "DNA_ID.h"
#include "DNA_dynamicpaint_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_boid_types.h"
#include <stdio.h> /* for FILE */
@@ -140,7 +140,7 @@ typedef struct PTCacheID {
unsigned int default_step;
unsigned int max_step;
- /* flags defined in DNA_object_force.h */
+ /* flags defined in DNA_object_force_types.h */
unsigned int data_types, info_types;
/* copies point data to cache data */
@@ -227,7 +227,6 @@ typedef struct PTCacheEditPoint {
} PTCacheEditPoint;
typedef struct PTCacheUndo {
- struct PTCacheUndo *next, *prev;
struct PTCacheEditPoint *points;
/* particles stuff */
@@ -240,12 +239,11 @@ typedef struct PTCacheUndo {
struct ListBase mem_cache;
int totpoint;
- char name[64];
+
+ size_t undo_size;
} PTCacheUndo;
typedef struct PTCacheEdit {
- ListBase undo;
- struct PTCacheUndo *curundo;
PTCacheEditPoint *points;
struct PTCacheID pid;
@@ -314,7 +312,7 @@ struct PointCache *BKE_ptcache_add(struct ListBase *ptcaches);
void BKE_ptcache_free_mem(struct ListBase *mem_cache);
void BKE_ptcache_free(struct PointCache *cache);
void BKE_ptcache_free_list(struct ListBase *ptcaches);
-struct PointCache *BKE_ptcache_copy_list(struct ListBase *ptcaches_new, const struct ListBase *ptcaches_old, bool copy_data);
+struct PointCache *BKE_ptcache_copy_list(struct ListBase *ptcaches_new, const struct ListBase *ptcaches_old, const int flag);
/********************** Baking *********************/
diff --git a/source/blender/blenkernel/BKE_property.h b/source/blender/blenkernel/BKE_property.h
index 99e60757f15..c787e8e8ed1 100644
--- a/source/blender/blenkernel/BKE_property.h
+++ b/source/blender/blenkernel/BKE_property.h
@@ -37,8 +37,8 @@ struct Object;
void BKE_bproperty_free(struct bProperty *prop);
void BKE_bproperty_free_list(struct ListBase *lb);
-struct bProperty *BKE_bproperty_copy(struct bProperty *prop);
-void BKE_bproperty_copy_list(struct ListBase *lbn, struct ListBase *lbo);
+struct bProperty *BKE_bproperty_copy(const struct bProperty *prop);
+void BKE_bproperty_copy_list(struct ListBase *lbn, const struct ListBase *lbo);
void BKE_bproperty_init(struct bProperty *prop);
struct bProperty *BKE_bproperty_new(int type);
void BKE_bproperty_unique(struct bProperty *first, struct bProperty *prop, int force);
diff --git a/source/blender/blenkernel/BKE_rigidbody.h b/source/blender/blenkernel/BKE_rigidbody.h
index 443c3b2b5b2..3c7274ca3c5 100644
--- a/source/blender/blenkernel/BKE_rigidbody.h
+++ b/source/blender/blenkernel/BKE_rigidbody.h
@@ -49,8 +49,8 @@ void BKE_rigidbody_free_constraint(struct Object *ob);
/* ...... */
-struct RigidBodyOb *BKE_rigidbody_copy_object(struct Object *ob);
-struct RigidBodyCon *BKE_rigidbody_copy_constraint(struct Object *ob);
+struct RigidBodyOb *BKE_rigidbody_copy_object(const struct Object *ob, const int flag);
+struct RigidBodyCon *BKE_rigidbody_copy_constraint(const struct Object *ob, const int flag);
/* Callback format for performing operations on ID-pointers for rigidbody world. */
typedef void (*RigidbodyWorldIDFunc)(struct RigidBodyWorld *rbw, struct ID **idpoin, void *userdata, int cb_flag);
@@ -66,7 +66,7 @@ struct RigidBodyOb *BKE_rigidbody_create_object(struct Scene *scene, struct Obje
struct RigidBodyCon *BKE_rigidbody_create_constraint(struct Scene *scene, struct Object *ob, short type);
/* copy */
-struct RigidBodyWorld *BKE_rigidbody_world_copy(struct RigidBodyWorld *rbw);
+struct RigidBodyWorld *BKE_rigidbody_world_copy(struct RigidBodyWorld *rbw, const int flag);
void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw);
/* 'validate' (i.e. make new or replace old) Physics-Engine objects */
diff --git a/source/blender/blenkernel/BKE_sca.h b/source/blender/blenkernel/BKE_sca.h
index 1579a0c7bb3..35bcd91a9b1 100644
--- a/source/blender/blenkernel/BKE_sca.h
+++ b/source/blender/blenkernel/BKE_sca.h
@@ -52,16 +52,16 @@ void free_actuators(struct ListBase *lb);
void free_sensor(struct bSensor *sens);
void free_sensors(struct ListBase *lb);
-struct bSensor *copy_sensor(struct bSensor *sens);
-void copy_sensors(struct ListBase *lbn, struct ListBase *lbo);
+struct bSensor *copy_sensor(struct bSensor *sens, const int flag);
+void copy_sensors(struct ListBase *lbn, const struct ListBase *lbo, const int flag);
void init_sensor(struct bSensor *sens);
struct bSensor *new_sensor(int type);
-struct bController *copy_controller(struct bController *cont);
-void copy_controllers(struct ListBase *lbn, struct ListBase *lbo);
+struct bController *copy_controller(struct bController *cont, const int flag);
+void copy_controllers(struct ListBase *lbn, const struct ListBase *lbo, const int flag);
void init_controller(struct bController *cont);
struct bController *new_controller(int type);
-struct bActuator *copy_actuator(struct bActuator *act);
-void copy_actuators(struct ListBase *lbn, struct ListBase *lbo);
+struct bActuator *copy_actuator(struct bActuator *act, const int flag);
+void copy_actuators(struct ListBase *lbn, const struct ListBase *lbo, const int flag);
void init_actuator(struct bActuator *act);
struct bActuator *new_actuator(int type);
void clear_sca_new_poins_ob(struct Object *ob);
@@ -70,7 +70,7 @@ void set_sca_new_poins_ob(struct Object *ob);
void set_sca_new_poins(void);
void BKE_sca_logic_links_remap(struct Main *bmain, struct Object *ob_old, struct Object *ob_new);
-void BKE_sca_logic_copy(struct Object *ob_new, struct Object *ob);
+void BKE_sca_logic_copy(struct Object *ob_new, const struct Object *ob, const int flag);
void sca_move_sensor(struct bSensor *sens_to_move, struct Object *ob, int move_up);
void sca_move_controller(struct bController *cont_to_move, struct Object *ob, int move_up);
diff --git a/source/blender/blenkernel/BKE_scene.h b/source/blender/blenkernel/BKE_scene.h
index d2152950bff..0e1472b7062 100644
--- a/source/blender/blenkernel/BKE_scene.h
+++ b/source/blender/blenkernel/BKE_scene.h
@@ -42,7 +42,6 @@ struct Base;
struct EvaluationContext;
struct Main;
struct Object;
-struct QuicktimeCodecData;
struct RenderData;
struct SceneRenderLayer;
struct Scene;
@@ -64,7 +63,6 @@ struct Main;
struct Base *_setlooper_base_step(struct Scene **sce_iter, struct Base *base);
void free_avicodecdata(struct AviCodecData *acd);
-void free_qtcodecdata(struct QuicktimeCodecData *acd);
void BKE_scene_free(struct Scene *sce);
void BKE_scene_init(struct Scene *sce);
@@ -98,6 +96,10 @@ void BKE_scene_base_flag_from_objects(struct Scene *scene);
void BKE_scene_set_background(struct Main *bmain, struct Scene *sce);
struct Scene *BKE_scene_set_name(struct Main *bmain, const char *name);
+struct ToolSettings *BKE_toolsettings_copy(struct ToolSettings *toolsettings, const int flag);
+void BKE_toolsettings_free(struct ToolSettings *toolsettings);
+
+void BKE_scene_copy_data(struct Main *bmain, struct Scene *sce_dst, const struct Scene *sce_src, const int flag);
struct Scene *BKE_scene_copy(struct Main *bmain, struct Scene *sce, int type);
void BKE_scene_groups_relink(struct Scene *sce);
@@ -151,6 +153,8 @@ bool BKE_scene_check_rigidbody_active(const struct Scene *scene);
int BKE_scene_num_threads(const struct Scene *scene);
int BKE_render_num_threads(const struct RenderData *r);
+int BKE_render_preview_pixel_size(const struct RenderData *r);
+
double BKE_scene_unit_scale(const struct UnitSettings *unit, const int unit_type, double value);
/* multiview */
@@ -175,4 +179,3 @@ int BKE_scene_multiview_num_videos_get(const struct RenderData *rd);
#endif
#endif
-
diff --git a/source/blender/blenkernel/BKE_sequencer.h b/source/blender/blenkernel/BKE_sequencer.h
index 811e9136fc9..3c2cebce3cf 100644
--- a/source/blender/blenkernel/BKE_sequencer.h
+++ b/source/blender/blenkernel/BKE_sequencer.h
@@ -335,7 +335,8 @@ bool BKE_sequence_base_shuffle(
bool BKE_sequence_base_shuffle_time(ListBase *seqbasep, struct Scene *evil_scene);
bool BKE_sequence_base_isolated_sel_check(struct ListBase *seqbase);
void BKE_sequencer_free_imbuf(struct Scene *scene, struct ListBase *seqbasep, bool for_render);
-struct Sequence *BKE_sequence_dupli_recursive(struct Scene *scene, struct Scene *scene_to, struct Sequence *seq, int dupe_flag);
+struct Sequence *BKE_sequence_dupli_recursive(
+ const struct Scene *scene_src, struct Scene *scene_dst, struct Sequence *seq, int dupe_flag);
int BKE_sequence_swap(struct Sequence *seq_a, struct Sequence *seq_b, const char **error_str);
bool BKE_sequence_check_depend(struct Sequence *seq, struct Sequence *cur);
@@ -352,8 +353,8 @@ void BKE_sequencer_refresh_sound_length(struct Scene *scene);
void BKE_sequence_base_unique_name_recursive(ListBase *seqbasep, struct Sequence *seq);
void BKE_sequence_base_dupli_recursive(
- struct Scene *scene, struct Scene *scene_to, ListBase *nseqbase, ListBase *seqbase,
- int dupe_flag);
+ const struct Scene *scene_src, struct Scene *scene_dst, struct ListBase *nseqbase, const struct ListBase *seqbase,
+ int dupe_flag, const int flag);
bool BKE_sequence_is_valid_check(struct Sequence *seq);
void BKE_sequencer_clear_scene_in_allseqs(struct Main *bmain, struct Scene *sce);
@@ -404,6 +405,8 @@ struct Sequence *BKE_sequence_alloc(ListBase *lb, int cfra, int machine);
void BKE_sequence_alpha_mode_from_extension(struct Sequence *seq);
void BKE_sequence_init_colorspace(struct Sequence *seq);
+float BKE_sequence_get_fps(struct Scene *scene, struct Sequence *seq);
+
/* RNA enums, just to be more readable */
enum {
SEQ_SIDE_NONE = 0,
@@ -420,11 +423,21 @@ struct Sequence *BKE_sequencer_add_sound_strip(struct bContext *C, ListBase *seq
struct Sequence *BKE_sequencer_add_movie_strip(struct bContext *C, ListBase *seqbasep, struct SeqLoadInfo *seq_load);
/* view3d draw callback, run when not in background view */
+/* NOTE: Keep in sync with V3D_OFSDRAW_* flags. */
+enum {
+ SEQ_OFSDRAW_NONE = (0),
+ SEQ_OFSDRAW_USE_BACKGROUND = (1 << 0),
+ SEQ_OFSDRAW_USE_FULL_SAMPLE = (1 << 1),
+ SEQ_OFSDRAW_USE_GPENCIL = (1 << 2),
+ SEQ_OFSDRAW_USE_SOLID_TEX = (1 << 2),
+ SEQ_OFSDRAW_USE_CAMERA_DOF = (1 << 3),
+};
+
typedef struct ImBuf *(*SequencerDrawView)(
- struct Scene *, struct Object *, int, int,
- unsigned int, int, bool, bool, bool,
- int, int, bool, const char *,
- struct GPUFX *, struct GPUOffScreen *, char[256]);
+ struct Scene *scene, struct Object *camera, int width, int height,
+ unsigned int flag, unsigned int draw_flags, int drawtype, int alpha_mode,
+ int samples, const char *viewname,
+ struct GPUFX *fx, struct GPUOffScreen *ofs, char err_out[256]);
extern SequencerDrawView sequencer_view3d_cb;
/* copy/paste */
diff --git a/source/blender/blenkernel/BKE_sound.h b/source/blender/blenkernel/BKE_sound.h
index a5c626e74d7..6f8274fabc8 100644
--- a/source/blender/blenkernel/BKE_sound.h
+++ b/source/blender/blenkernel/BKE_sound.h
@@ -80,6 +80,8 @@ void BKE_sound_load(struct Main *main, struct bSound *sound);
void BKE_sound_free(struct bSound *sound);
+void BKE_sound_copy_data(struct Main *bmain, struct bSound *sound_dst, const struct bSound *sound_src, const int flag);
+
void BKE_sound_make_local(struct Main *bmain, struct bSound *sound, const bool lib_local);
#if defined(__AUD_C_API_H__) || defined(WITH_SYSTEM_AUDASPACE)
diff --git a/source/blender/blenkernel/BKE_speaker.h b/source/blender/blenkernel/BKE_speaker.h
index b91b64c4b74..57f4c37f129 100644
--- a/source/blender/blenkernel/BKE_speaker.h
+++ b/source/blender/blenkernel/BKE_speaker.h
@@ -33,7 +33,8 @@ struct Speaker;
void BKE_speaker_init(struct Speaker *spk);
void *BKE_speaker_add(struct Main *bmain, const char *name);
-struct Speaker *BKE_speaker_copy(struct Main *bmain, struct Speaker *spk);
+void BKE_speaker_copy_data(struct Main *bmain, struct Speaker *spk_dst, const struct Speaker *spk_src, const int flag);
+struct Speaker *BKE_speaker_copy(struct Main *bmain, const struct Speaker *spk);
void BKE_speaker_make_local(struct Main *bmain, struct Speaker *spk, const bool lib_local);
void BKE_speaker_free(struct Speaker *spk);
diff --git a/source/blender/blenkernel/BKE_subsurf.h b/source/blender/blenkernel/BKE_subsurf.h
index f52bb2ab9cb..96320415b16 100644
--- a/source/blender/blenkernel/BKE_subsurf.h
+++ b/source/blender/blenkernel/BKE_subsurf.h
@@ -34,6 +34,9 @@
/* struct DerivedMesh is used directly */
#include "BKE_DerivedMesh.h"
+/* Thread sync primitives used directly. */
+#include "BLI_threads.h"
+
struct CCGElem;
struct DMFlagMat;
struct DMGridAdjacency;
@@ -125,6 +128,8 @@ typedef struct CCGDerivedMesh {
struct CCGFace **gridFaces;
struct DMFlagMat *gridFlagMats;
unsigned int **gridHidden;
+ /* Elements in arrays above. */
+ unsigned int numGrid;
struct {
struct MultiresModifierData *mmd;
@@ -138,6 +143,9 @@ typedef struct CCGDerivedMesh {
} multires;
struct EdgeHash *ehash;
+
+ ThreadMutex loops_cache_lock;
+ ThreadRWMutex origindex_cache_rwlock;
} CCGDerivedMesh;
#ifdef WITH_OPENSUBDIV
diff --git a/source/blender/blenkernel/BKE_text.h b/source/blender/blenkernel/BKE_text.h
index 081b7589af6..b53af3cec53 100644
--- a/source/blender/blenkernel/BKE_text.h
+++ b/source/blender/blenkernel/BKE_text.h
@@ -40,11 +40,10 @@ extern "C" {
struct Main;
struct Text;
struct TextLine;
+struct TextUndoBuf;
void BKE_text_free_lines (struct Text *text);
void BKE_text_free (struct Text *text);
-void txt_set_undostate (int u);
-int txt_get_undostate (void);
void BKE_text_init(struct Text *ta);
struct Text *BKE_text_add (struct Main *bmain, const char *name);
int txt_extended_ascii_as_utf8(char **str);
@@ -52,10 +51,11 @@ bool BKE_text_reload(struct Text *text);
struct Text *BKE_text_load_ex(struct Main *bmain, const char *file, const char *relpath,
const bool is_internal);
struct Text *BKE_text_load (struct Main *bmain, const char *file, const char *relpath);
-struct Text *BKE_text_copy (struct Main *bmain, struct Text *ta);
+void BKE_text_copy_data(struct Main *bmain, struct Text *ta_dst, const struct Text *ta_src, const int flag);
+struct Text *BKE_text_copy (struct Main *bmain, const struct Text *ta);
void BKE_text_make_local (struct Main *bmain, struct Text *text, const bool lib_local);
-void BKE_text_clear (struct Text *text);
-void BKE_text_write (struct Text *text, const char *str);
+void BKE_text_clear (struct Text *text, struct TextUndoBuf *utxt);
+void BKE_text_write (struct Text *text, struct TextUndoBuf *utxt, const char *str);
int BKE_text_file_modified_check(struct Text *text);
void BKE_text_file_modified_ignore(struct Text *text);
@@ -82,29 +82,29 @@ void txt_move_eol (struct Text *text, const bool sel);
void txt_move_toline (struct Text *text, unsigned int line, const bool sel);
void txt_move_to (struct Text *text, unsigned int line, unsigned int ch, const bool sel);
void txt_pop_sel (struct Text *text);
-void txt_delete_char (struct Text *text);
-void txt_delete_word (struct Text *text);
-void txt_delete_selected (struct Text *text);
+void txt_delete_char (struct Text *text, struct TextUndoBuf *utxt);
+void txt_delete_word (struct Text *text, struct TextUndoBuf *utxt);
+void txt_delete_selected (struct Text *text, struct TextUndoBuf *utxt);
void txt_sel_all (struct Text *text);
void txt_sel_clear (struct Text *text);
void txt_sel_line (struct Text *text);
char *txt_sel_to_buf (struct Text *text);
-void txt_insert_buf (struct Text *text, const char *in_buffer);
-void txt_undo_add_op (struct Text *text, int op);
-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);
-bool txt_add_char (struct Text *text, unsigned int add);
-bool txt_add_raw_char (struct Text *text, unsigned int add);
-bool txt_replace_char (struct Text *text, unsigned int add);
-void txt_unindent (struct Text *text);
-void txt_comment (struct Text *text);
-void txt_indent (struct Text *text);
-void txt_uncomment (struct Text *text);
-void txt_move_lines (struct Text *text, const int direction);
-void txt_duplicate_line (struct Text *text);
+void txt_insert_buf (struct Text *text, struct TextUndoBuf *utxt, const char *in_buffer);
+void txt_undo_add_op (struct Text *text, struct TextUndoBuf *utxt, int op);
+void txt_do_undo (struct Text *text, struct TextUndoBuf *utxt);
+void txt_do_redo (struct Text *text, struct TextUndoBuf *utxt);
+void txt_split_curline (struct Text *text, struct TextUndoBuf *utxt);
+void txt_backspace_char (struct Text *text, struct TextUndoBuf *utxt);
+void txt_backspace_word (struct Text *text, struct TextUndoBuf *utxt);
+bool txt_add_char (struct Text *text, struct TextUndoBuf *utxt, unsigned int add);
+bool txt_add_raw_char (struct Text *text, struct TextUndoBuf *utxt, unsigned int add);
+bool txt_replace_char (struct Text *text, struct TextUndoBuf *utxt, unsigned int add);
+void txt_unindent (struct Text *text, struct TextUndoBuf *utxt);
+void txt_comment (struct Text *text, struct TextUndoBuf *utxt);
+void txt_indent (struct Text *text, struct TextUndoBuf *utxt);
+void txt_uncomment (struct Text *text, struct TextUndoBuf *utxt);
+void txt_move_lines (struct Text *text, struct TextUndoBuf *utxt, const int direction);
+void txt_duplicate_line (struct Text *text, struct TextUndoBuf *utxt);
int txt_setcurr_tab_spaces(struct Text *text, int space);
bool txt_cursor_is_line_start(struct Text *text);
bool txt_cursor_is_line_end(struct Text *text);
@@ -134,46 +134,10 @@ enum {
TXT_MOVE_LINE_DOWN = 1
};
-
-/* Undo opcodes */
-
-/* Complex editing */
-/* 1 - opcode is followed by 1 byte for ascii character and opcode (repeat)) */
-/* 2 - opcode is followed by 2 bytes for utf-8 character and opcode (repeat)) */
-/* 3 - opcode is followed by 3 bytes for utf-8 character and opcode (repeat)) */
-/* 4 - opcode is followed by 4 bytes for unicode character and opcode (repeat)) */
-#define UNDO_INSERT_1 013
-#define UNDO_INSERT_2 014
-#define UNDO_INSERT_3 015
-#define UNDO_INSERT_4 016
-
-#define UNDO_BS_1 017
-#define UNDO_BS_2 020
-#define UNDO_BS_3 021
-#define UNDO_BS_4 022
-
-#define UNDO_DEL_1 023
-#define UNDO_DEL_2 024
-#define UNDO_DEL_3 025
-#define UNDO_DEL_4 026
-
-/* Text block (opcode is followed
- * by 4 character length ID + the text
- * block itself + the 4 character length
- * ID (repeat) and opcode (repeat)) */
-#define UNDO_DBLOCK 027 /* Delete block */
-#define UNDO_IBLOCK 030 /* Insert block */
-
-/* Misc */
-#define UNDO_INDENT 032
-#define UNDO_UNINDENT 033
-#define UNDO_COMMENT 034
-#define UNDO_UNCOMMENT 035
-
-#define UNDO_MOVE_LINES_UP 036
-#define UNDO_MOVE_LINES_DOWN 037
-
-#define UNDO_DUPLICATE 040
+typedef struct TextUndoBuf {
+ char *buf;
+ int pos, len;
+} TextUndoBuf;
#ifdef __cplusplus
}
diff --git a/source/blender/blenkernel/BKE_texture.h b/source/blender/blenkernel/BKE_texture.h
index 9a60eb29957..4e98852c995 100644
--- a/source/blender/blenkernel/BKE_texture.h
+++ b/source/blender/blenkernel/BKE_texture.h
@@ -60,17 +60,10 @@ struct World;
#define MAXCOLORBAND 32
-void init_colorband(struct ColorBand *coba, bool rangetype);
-struct ColorBand *add_colorband(bool rangetype);
-bool do_colorband(const struct ColorBand *coba, float in, float out[4]);
-void colorband_table_RGBA(struct ColorBand *coba, float **array, int *size);
-struct CBData *colorband_element_add(struct ColorBand *coba, float position);
-int colorband_element_remove(struct ColorBand *coba, int index);
-void colorband_update_sort(struct ColorBand *coba);
-
void BKE_texture_free(struct Tex *tex);
void BKE_texture_default(struct Tex *tex);
-struct Tex *BKE_texture_copy(struct Main *bmain, struct Tex *tex);
+void BKE_texture_copy_data(struct Main *bmain, struct Tex *tex_dst, const struct Tex *tex_src, const int flag);
+struct Tex *BKE_texture_copy(struct Main *bmain, const struct Tex *tex);
struct Tex *BKE_texture_add(struct Main *bmain, const char *name);
struct Tex *BKE_texture_localize(struct Tex *tex);
void BKE_texture_make_local(struct Main *bmain, struct Tex *tex, const bool lib_local);
@@ -114,13 +107,13 @@ void BKE_texture_colormapping_default(struct ColorMapping *color
void BKE_texture_envmap_free_data(struct EnvMap *env);
void BKE_texture_envmap_free(struct EnvMap *env);
struct EnvMap *BKE_texture_envmap_add(void);
-struct EnvMap *BKE_texture_envmap_copy(struct EnvMap *env);
+struct EnvMap *BKE_texture_envmap_copy(const struct EnvMap *env, const int flag);
void BKE_texture_pointdensity_init_data(struct PointDensity *pd);
void BKE_texture_pointdensity_free_data(struct PointDensity *pd);
void BKE_texture_pointdensity_free(struct PointDensity *pd);
struct PointDensity *BKE_texture_pointdensity_add(void);
-struct PointDensity *BKE_texture_pointdensity_copy(struct PointDensity *pd);
+struct PointDensity *BKE_texture_pointdensity_copy(const struct PointDensity *pd, const int flag);
void BKE_texture_voxeldata_free_data(struct VoxelData *vd);
void BKE_texture_voxeldata_free(struct VoxelData *vd);
@@ -129,7 +122,7 @@ struct VoxelData *BKE_texture_voxeldata_copy(struct VoxelData *vd);
void BKE_texture_ocean_free(struct OceanTex *ot);
struct OceanTex *BKE_texture_ocean_add(void);
-struct OceanTex *BKE_texture_ocean_copy(struct OceanTex *ot);
+struct OceanTex *BKE_texture_ocean_copy(const struct OceanTex *ot, const int flag);
bool BKE_texture_dependsOnTime(const struct Tex *texture);
bool BKE_texture_is_image_user(const struct Tex *tex);
@@ -144,6 +137,8 @@ void BKE_texture_get_value(
const struct Scene *scene, struct Tex *texture,
float *tex_co, struct TexResult *texres, bool use_color_management);
+void BKE_texture_fetch_images_for_pool(struct Tex *texture, struct ImagePool *pool);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenkernel/BKE_tracking.h b/source/blender/blenkernel/BKE_tracking.h
index 30873567297..13302caa09d 100644
--- a/source/blender/blenkernel/BKE_tracking.h
+++ b/source/blender/blenkernel/BKE_tracking.h
@@ -52,7 +52,7 @@ struct rcti;
/* **** Common functions **** */
void BKE_tracking_free(struct MovieTracking *tracking);
-void BKE_tracking_copy(struct MovieTracking *tracking_dst, struct MovieTracking *tracking_src);
+void BKE_tracking_copy(struct MovieTracking *tracking_dst, const struct MovieTracking *tracking_src, const int flag);
void BKE_tracking_settings_init(struct MovieTracking *tracking);
@@ -288,6 +288,46 @@ void BKE_tracking_stabilization_data_to_mat4(int width, int height, float aspect
void BKE_tracking_dopesheet_tag_update(struct MovieTracking *tracking);
void BKE_tracking_dopesheet_update(struct MovieTracking *tracking);
+/* **** Query/search **** */
+
+struct MovieTrackingObject *BKE_tracking_find_object_for_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track);
+struct ListBase *BKE_tracking_find_tracks_list_for_track(
+ struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track);
+
+struct MovieTrackingObject *BKE_tracking_find_object_for_plane_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track);
+struct ListBase *BKE_tracking_find_tracks_list_for_plane_track(
+ struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track);
+
+
+void BKE_tracking_get_rna_path_for_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track,
+ char *rna_path,
+ size_t rna_path_len);
+void BKE_tracking_get_rna_path_prefix_for_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track,
+ char *rna_path,
+ size_t rna_path_len);
+void BKE_tracking_get_rna_path_for_plane_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track,
+ char *rna_path,
+ size_t rna_path_len);
+void BKE_tracking_get_rna_path_prefix_for_plane_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track,
+ char *rna_path,
+ size_t rna_path_len);
+
+/* **** Utility macros **** */
+
#define TRACK_SELECTED(track) ((track)->flag & SELECT || (track)->pat_flag & SELECT || (track)->search_flag & SELECT)
#define TRACK_AREA_SELECTED(track, area) ((area) == TRACK_AREA_POINT ? (track)->flag & SELECT : \
diff --git a/source/blender/blenkernel/BKE_undo_system.h b/source/blender/blenkernel/BKE_undo_system.h
new file mode 100644
index 00000000000..53ea8ddefe8
--- /dev/null
+++ b/source/blender/blenkernel/BKE_undo_system.h
@@ -0,0 +1,197 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+#ifndef __BKE_UNDO_SYSTEM_H__
+#define __BKE_UNDO_SYSTEM_H__
+
+/** \file BKE_undo_system.h
+ * \ingroup bke
+ */
+
+struct Main;
+struct UndoStep;
+struct bContext;
+
+/* ID's */
+struct Mesh;
+struct Object;
+struct Scene;
+struct Text;
+
+#include "DNA_ID.h"
+#include "DNA_listBase.h"
+
+typedef struct UndoRefID { struct ID *ptr; char name[MAX_ID_NAME]; } UndoRefID;
+/* UndoRefID_Mesh & friends. */
+#define UNDO_REF_ID_TYPE(ptr_ty) \
+ typedef struct UndoRefID_##ptr_ty { struct ptr_ty *ptr; char name[MAX_ID_NAME]; } UndoRefID_##ptr_ty
+UNDO_REF_ID_TYPE(Mesh);
+UNDO_REF_ID_TYPE(Object);
+UNDO_REF_ID_TYPE(Scene);
+UNDO_REF_ID_TYPE(Text);
+
+typedef struct UndoStack {
+ ListBase steps;
+ struct UndoStep *step_active;
+
+ /**
+ * Some undo systems require begin/end, see: #UndoType.step_encode_init
+ *
+ * \note This is not included in the 'steps' list.
+ * That is done once end is called.
+ */
+ struct UndoStep *step_init;
+} UndoStack;
+
+
+typedef struct UndoStep {
+ struct UndoStep *next, *prev;
+ char name[64];
+ const struct UndoType *type;
+ /** Size in bytes of all data in step (not including the step). */
+ size_t data_size;
+ /** Users should never see this step (only use for internal consistency). */
+ bool skip;
+ /* Over alloc 'type->struct_size'. */
+} UndoStep;
+
+typedef enum eUndoTypeMode {
+ /**
+ * Each undo step stores a version of the state.
+ * This means we can simply load in a previous state at any time.
+ */
+ BKE_UNDOTYPE_MODE_STORE = 1,
+ /**
+ * Each undo step is a series of edits.
+ * This means to change states we need to apply each edit.
+ * It also means the 'step_decode' callback needs to detect the difference between undo and redo.
+ * (Currently used for text edit and image & sculpt painting).
+ */
+ BKE_UNDOTYPE_MODE_ACCUMULATE = 2,
+} eUndoTypeMode;
+
+typedef void (*UndoTypeForEachIDRefFn)(void *user_data, struct UndoRefID *id_ref);
+
+typedef struct UndoType {
+ struct UndoType *next, *prev;
+ /** Only for debugging. */
+ const char *name;
+
+ /**
+ * When NULL, we don't consider this undo type for context checks.
+ * Operators must explicitly set the undo type and handle adding the undo step.
+ * This is needed when tools operate on data which isn't the primary mode (eg, paint-curve in sculpt mode).
+ */
+ bool (*poll)(struct bContext *C);
+
+ /**
+ * None of these callbacks manage list add/removal.
+ *
+ * Note that 'step_encode_init' is optional,
+ * some undo types need to perform operatons before undo push finishes.
+ */
+ void (*step_encode_init)(struct bContext *C, UndoStep *us);
+
+ bool (*step_encode)(struct bContext *C, UndoStep *us);
+ void (*step_decode)(struct bContext *C, UndoStep *us, int dir);
+
+ /**
+ * \note When freeing all steps,
+ * free from the last since #MemFileUndoType will merge with the next undo type in the list. */
+ void (*step_free)(UndoStep *us);
+
+ void (*step_foreach_ID_ref)(UndoStep *us, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data);
+
+ eUndoTypeMode mode;
+ bool use_context;
+
+ int step_size;
+} UndoType;
+
+/* expose since we need to perform operations on spesific undo types (rarely). */
+extern const UndoType *BKE_UNDOSYS_TYPE_IMAGE;
+extern const UndoType *BKE_UNDOSYS_TYPE_MEMFILE;
+extern const UndoType *BKE_UNDOSYS_TYPE_PAINTCURVE;
+extern const UndoType *BKE_UNDOSYS_TYPE_PARTICLE;
+extern const UndoType *BKE_UNDOSYS_TYPE_SCULPT;
+extern const UndoType *BKE_UNDOSYS_TYPE_TEXT;
+
+UndoStack *BKE_undosys_stack_create(void);
+void BKE_undosys_stack_destroy(UndoStack *ustack);
+void BKE_undosys_stack_clear(UndoStack *ustack);
+bool BKE_undosys_stack_has_undo(UndoStack *ustack, const char *name);
+void BKE_undosys_stack_init_from_main(UndoStack *ustack, struct Main *bmain);
+UndoStep *BKE_undosys_stack_active_with_type(UndoStack *ustack, const UndoType *ut);
+UndoStep *BKE_undosys_stack_init_or_active_with_type(UndoStack *ustack, const UndoType *ut);
+void BKE_undosys_stack_limit_steps_and_memory(UndoStack *ustack, int steps, size_t memory_limit);
+
+/* Only some UndoType's require init. */
+UndoStep *BKE_undosys_step_push_init_with_type(UndoStack *ustack, struct bContext *C, const char *name, const UndoType *ut);
+UndoStep *BKE_undosys_step_push_init(UndoStack *ustack, struct bContext *C, const char *name);
+
+bool BKE_undosys_step_push_with_type(UndoStack *ustack, struct bContext *C, const char *name, const UndoType *ut);
+bool BKE_undosys_step_push(UndoStack *ustack, struct bContext *C, const char *name);
+
+UndoStep *BKE_undosys_step_find_by_name_with_type(UndoStack *ustack, const char *name, const UndoType *ut);
+UndoStep *BKE_undosys_step_find_by_type(UndoStack *ustack, const UndoType *ut);
+UndoStep *BKE_undosys_step_find_by_name(UndoStack *ustack, const char *name);
+
+bool BKE_undosys_step_undo_with_data_ex(UndoStack *ustack, struct bContext *C, UndoStep *us, bool use_skip);
+bool BKE_undosys_step_undo_with_data(UndoStack *ustack, struct bContext *C, UndoStep *us);
+bool BKE_undosys_step_undo(UndoStack *ustack, struct bContext *C);
+
+bool BKE_undosys_step_redo_with_data_ex(UndoStack *ustack, struct bContext *C, UndoStep *us, bool use_skip);
+bool BKE_undosys_step_redo_with_data(UndoStack *ustack, struct bContext *C, UndoStep *us);
+bool BKE_undosys_step_redo(UndoStack *ustack, struct bContext *C);
+
+bool BKE_undosys_step_load_data(UndoStack *ustack, struct bContext *C, UndoStep *us);
+
+bool BKE_undosys_step_undo_compat_only(UndoStack *ustack, struct bContext *C, int step);
+void BKE_undosys_step_undo_from_index(UndoStack *ustack, struct bContext *C, int index);
+UndoStep *BKE_undosys_step_same_type_next(UndoStep *us);
+UndoStep *BKE_undosys_step_same_type_prev(UndoStep *us);
+
+/* Type System */
+UndoType *BKE_undosys_type_append(void (*undosys_fn)(UndoType *));
+void BKE_undosys_type_free_all(void);
+
+/* ID Accessor */
+#if 0 /* functionality is only used internally for now. */
+void BKE_undosys_foreach_ID_ref(UndoStack *ustack, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data);
+#endif
+
+/* Use when the undo step stores many arbitrary pointers. */
+struct UndoIDPtrMap;
+struct UndoIDPtrMap *BKE_undosys_ID_map_create(void);
+void BKE_undosys_ID_map_destroy(struct UndoIDPtrMap *map);
+void BKE_undosys_ID_map_add(struct UndoIDPtrMap *map, ID *id);
+struct ID *BKE_undosys_ID_map_lookup(const struct UndoIDPtrMap *map, const struct ID *id_src);
+
+void BKE_undosys_ID_map_add_with_prev(
+ struct UndoIDPtrMap *map, struct ID *id,
+ struct ID **id_prev);
+struct ID *BKE_undosys_ID_map_lookup_with_prev(
+ const struct UndoIDPtrMap *map, struct ID *id_src,
+ struct ID *id_prev_match[2]);
+
+void BKE_undosys_ID_map_foreach_ID_ref(
+ struct UndoIDPtrMap *map,
+ UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data);
+
+#endif /* __BKE_UNDO_SYSTEM_H__ */
diff --git a/source/blender/blenkernel/BKE_world.h b/source/blender/blenkernel/BKE_world.h
index 23bf9ec3d22..b28bac08727 100644
--- a/source/blender/blenkernel/BKE_world.h
+++ b/source/blender/blenkernel/BKE_world.h
@@ -38,10 +38,10 @@ struct World;
void BKE_world_free(struct World *sc);
void BKE_world_init(struct World *wrld);
-struct World *add_world(struct Main *bmian, const char *name);
-struct World *BKE_world_copy(struct Main *bmain, struct World *wrld);
-struct World *localize_world(struct World *wrld);
+struct World *BKE_world_add(struct Main *bmain, const char *name);
+void BKE_world_copy_data(struct Main *bmain, struct World *wrld_dst, const struct World *wrld_src, const int flag);
+struct World *BKE_world_copy(struct Main *bmain, const struct World *wrld);
+struct World *BKE_world_localize(struct World *wrld);
void BKE_world_make_local(struct Main *bmain, struct World *wrld, const bool lib_local);
-#endif
-
+#endif /* __BKE_WORLD_H__ */
diff --git a/source/blender/blenkernel/CMakeLists.txt b/source/blender/blenkernel/CMakeLists.txt
index 157c4408d6a..d789671ab24 100644
--- a/source/blender/blenkernel/CMakeLists.txt
+++ b/source/blender/blenkernel/CMakeLists.txt
@@ -48,7 +48,9 @@ set(INC
../../../intern/mikktspace
../../../intern/smoke/extern
../../../intern/atomic
+ ../../../intern/clog
../../../intern/libmv
+ ../../../extern/curve_fit_nd
)
set(INC_SYS
@@ -86,11 +88,13 @@ set(SRC
intern/cdderivedmesh.c
intern/cloth.c
intern/collision.c
+ intern/colorband.c
intern/colortools.c
intern/constraint.c
intern/context.c
intern/crazyspace.c
intern/curve.c
+ intern/curve_decimate.c
intern/customdata.c
intern/customdata_file.c
intern/data_transfer.c
@@ -99,6 +103,7 @@ set(SRC
intern/displist.c
intern/dynamicpaint.c
intern/editderivedmesh.c
+ intern/editlattice.c
intern/editmesh.c
intern/editmesh_bvh.c
intern/effect.c
@@ -183,6 +188,7 @@ set(SRC
intern/tracking_solver.c
intern/tracking_stabilize.c
intern/tracking_util.c
+ intern/undo_system.c
intern/unit.c
intern/world.c
intern/writeavi.c
@@ -214,6 +220,7 @@ set(SRC
BKE_cdderivedmesh.h
BKE_cloth.h
BKE_collision.h
+ BKE_colorband.h
BKE_colortools.h
BKE_constraint.h
BKE_context.h
@@ -226,6 +233,7 @@ set(SRC
BKE_depsgraph.h
BKE_displist.h
BKE_dynamicpaint.h
+ BKE_editlattice.h
BKE_editmesh.h
BKE_editmesh_bvh.h
BKE_effect.h
@@ -289,8 +297,8 @@ set(SRC
BKE_text.h
BKE_texture.h
BKE_tracking.h
+ BKE_undo_system.h
BKE_unit.h
- BKE_utildefines.h
BKE_world.h
BKE_writeavi.h
BKE_writeframeserver.h
@@ -298,6 +306,7 @@ set(SRC
depsgraph_private.h
nla_private.h
tracking_private.h
+ particle_private.h
intern/CCGSubSurf.h
intern/CCGSubSurf_inline.h
intern/CCGSubSurf_intern.h
@@ -385,16 +394,6 @@ if(WITH_CODEC_AVI)
add_definitions(-DWITH_AVI)
endif()
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../quicktime
- )
- list(APPEND INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_CODEC_FFMPEG)
list(APPEND SRC
intern/writeffmpeg.c
diff --git a/source/blender/blenkernel/intern/CCGSubSurf.h b/source/blender/blenkernel/intern/CCGSubSurf.h
index 4c913e79586..8cdbd2a7a98 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf.h
+++ b/source/blender/blenkernel/intern/CCGSubSurf.h
@@ -73,6 +73,9 @@ typedef enum {
#define CCG_OMP_LIMIT 1000000
+/* TODO(sergey): This actually depends on subsurf level as well. */
+#define CCG_TASK_LIMIT 16
+
/***/
CCGSubSurf* ccgSubSurf_new (CCGMeshIFC *ifc, int subdivisionLevels, CCGAllocatorIFC *allocatorIFC, CCGAllocatorHDL allocator);
diff --git a/source/blender/blenkernel/intern/CCGSubSurf_legacy.c b/source/blender/blenkernel/intern/CCGSubSurf_legacy.c
index e9002af19b1..756935b50ba 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf_legacy.c
+++ b/source/blender/blenkernel/intern/CCGSubSurf_legacy.c
@@ -27,6 +27,7 @@
#include "BLI_utildefines.h" /* for BLI_assert */
#include "BLI_math.h"
+#include "BLI_task.h"
#include "CCGSubSurf.h"
#include "CCGSubSurf_intern.h"
@@ -121,98 +122,231 @@ static float EDGE_getSharpness(CCGEdge *e, int lvl)
return e->crease - lvl;
}
-static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss,
- CCGVert **effectedV, CCGEdge **effectedE, CCGFace **effectedF,
- int numEffectedV, int numEffectedE, int numEffectedF)
+
+
+typedef struct CCGSubSurfCalcSubdivData {
+ CCGSubSurf *ss;
+ CCGVert **effectedV;
+ CCGEdge **effectedE;
+ CCGFace **effectedF;
+ int numEffectedV;
+ int numEffectedE;
+ int numEffectedF;
+
+ int curLvl;
+} CCGSubSurfCalcSubdivData;
+
+static void ccgSubSurf__calcVertNormals_faces_accumulate_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
- int i, ptrIdx;
- int subdivLevels = ss->subdivLevels;
- int lvl = ss->subdivLevels;
- int edgeSize = ccg_edgesize(lvl);
- int gridSize = ccg_gridsize(lvl);
- int normalDataOffset = ss->normalDataOffset;
- int vertDataSize = ss->meshIFC.vertDataSize;
+ CCGSubSurfCalcSubdivData *data = userdata;
-#pragma omp parallel for private(ptrIdx) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
- for (ptrIdx = 0; ptrIdx < numEffectedF; ptrIdx++) {
- CCGFace *f = (CCGFace *) effectedF[ptrIdx];
- int S, x, y;
- float no[3];
+ CCGSubSurf *ss = data->ss;
+ CCGFace *f = data->effectedF[ptrIdx];
- for (S = 0; S < f->numVerts; S++) {
- for (y = 0; y < gridSize - 1; y++) {
- for (x = 0; x < gridSize - 1; x++) {
- NormZero(FACE_getIFNo(f, lvl, S, x, y));
- }
- }
+ const int subdivLevels = ss->subdivLevels;
+ const int lvl = ss->subdivLevels;
+ const int gridSize = ccg_gridsize(lvl);
+ const int normalDataOffset = ss->normalDataOffset;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
- if (FACE_getEdges(f)[(S - 1 + f->numVerts) % f->numVerts]->flags & Edge_eEffected) {
- for (x = 0; x < gridSize - 1; x++) {
- NormZero(FACE_getIFNo(f, lvl, S, x, gridSize - 1));
- }
+ int S, x, y;
+ float no[3];
+
+ for (S = 0; S < f->numVerts; S++) {
+ for (y = 0; y < gridSize - 1; y++) {
+ for (x = 0; x < gridSize - 1; x++) {
+ NormZero(FACE_getIFNo(f, lvl, S, x, y));
}
- if (FACE_getEdges(f)[S]->flags & Edge_eEffected) {
- for (y = 0; y < gridSize - 1; y++) {
- NormZero(FACE_getIFNo(f, lvl, S, gridSize - 1, y));
- }
+ }
+
+ if (FACE_getEdges(f)[(S - 1 + f->numVerts) % f->numVerts]->flags & Edge_eEffected) {
+ for (x = 0; x < gridSize - 1; x++) {
+ NormZero(FACE_getIFNo(f, lvl, S, x, gridSize - 1));
}
- if (FACE_getVerts(f)[S]->flags & Vert_eEffected) {
- NormZero(FACE_getIFNo(f, lvl, S, gridSize - 1, gridSize - 1));
+ }
+ if (FACE_getEdges(f)[S]->flags & Edge_eEffected) {
+ for (y = 0; y < gridSize - 1; y++) {
+ NormZero(FACE_getIFNo(f, lvl, S, gridSize - 1, y));
}
}
+ if (FACE_getVerts(f)[S]->flags & Vert_eEffected) {
+ NormZero(FACE_getIFNo(f, lvl, S, gridSize - 1, gridSize - 1));
+ }
+ }
- for (S = 0; S < f->numVerts; S++) {
- int yLimit = !(FACE_getEdges(f)[(S - 1 + f->numVerts) % f->numVerts]->flags & Edge_eEffected);
- int xLimit = !(FACE_getEdges(f)[S]->flags & Edge_eEffected);
- int yLimitNext = xLimit;
- int xLimitPrev = yLimit;
-
- for (y = 0; y < gridSize - 1; y++) {
- for (x = 0; x < gridSize - 1; x++) {
- int xPlusOk = (!xLimit || x < gridSize - 2);
- int yPlusOk = (!yLimit || y < gridSize - 2);
-
- FACE_calcIFNo(f, lvl, S, x, y, no);
-
- NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 0), no);
- if (xPlusOk)
- NormAdd(FACE_getIFNo(f, lvl, S, x + 1, y + 0), no);
- if (yPlusOk)
- NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 1), no);
- if (xPlusOk && yPlusOk) {
- if (x < gridSize - 2 || y < gridSize - 2 || FACE_getVerts(f)[S]->flags & Vert_eEffected) {
- NormAdd(FACE_getIFNo(f, lvl, S, x + 1, y + 1), no);
- }
+ for (S = 0; S < f->numVerts; S++) {
+ int yLimit = !(FACE_getEdges(f)[(S - 1 + f->numVerts) % f->numVerts]->flags & Edge_eEffected);
+ int xLimit = !(FACE_getEdges(f)[S]->flags & Edge_eEffected);
+ int yLimitNext = xLimit;
+ int xLimitPrev = yLimit;
+
+ for (y = 0; y < gridSize - 1; y++) {
+ for (x = 0; x < gridSize - 1; x++) {
+ int xPlusOk = (!xLimit || x < gridSize - 2);
+ int yPlusOk = (!yLimit || y < gridSize - 2);
+
+ FACE_calcIFNo(f, lvl, S, x, y, no);
+
+ NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 0), no);
+ if (xPlusOk)
+ NormAdd(FACE_getIFNo(f, lvl, S, x + 1, y + 0), no);
+ if (yPlusOk)
+ NormAdd(FACE_getIFNo(f, lvl, S, x + 0, y + 1), no);
+ if (xPlusOk && yPlusOk) {
+ if (x < gridSize - 2 || y < gridSize - 2 || FACE_getVerts(f)[S]->flags & Vert_eEffected) {
+ NormAdd(FACE_getIFNo(f, lvl, S, x + 1, y + 1), no);
}
+ }
- if (x == 0 && y == 0) {
- int K;
+ if (x == 0 && y == 0) {
+ int K;
- if (!yLimitNext || 1 < gridSize - 1)
- NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, 1), no);
- if (!xLimitPrev || 1 < gridSize - 1)
- NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, 1, 0), no);
+ if (!yLimitNext || 1 < gridSize - 1)
+ NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, 1), no);
+ if (!xLimitPrev || 1 < gridSize - 1)
+ NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, 1, 0), no);
- for (K = 0; K < f->numVerts; K++) {
- if (K != S) {
- NormAdd(FACE_getIFNo(f, lvl, K, 0, 0), no);
- }
+ for (K = 0; K < f->numVerts; K++) {
+ if (K != S) {
+ NormAdd(FACE_getIFNo(f, lvl, K, 0, 0), no);
}
}
- else if (y == 0) {
- NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x), no);
- if (!yLimitNext || x < gridSize - 2)
- NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x + 1), no);
- }
- else if (x == 0) {
- NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y, 0), no);
- if (!xLimitPrev || y < gridSize - 2)
- NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y + 1, 0), no);
- }
}
+ else if (y == 0) {
+ NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x), no);
+ if (!yLimitNext || x < gridSize - 2)
+ NormAdd(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, x + 1), no);
+ }
+ else if (x == 0) {
+ NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y, 0), no);
+ if (!xLimitPrev || y < gridSize - 2)
+ NormAdd(FACE_getIFNo(f, lvl, (S - 1 + f->numVerts) % f->numVerts, y + 1, 0), no);
+ }
+ }
+ }
+ }
+}
+
+static void ccgSubSurf__calcVertNormals_faces_finalize_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ CCGSubSurfCalcSubdivData *data = userdata;
+
+ CCGSubSurf *ss = data->ss;
+ CCGFace *f = data->effectedF[ptrIdx];
+
+ const int subdivLevels = ss->subdivLevels;
+ const int lvl = ss->subdivLevels;
+ const int gridSize = ccg_gridsize(lvl);
+ const int normalDataOffset = ss->normalDataOffset;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+
+ int S, x, y;
+
+ for (S = 0; S < f->numVerts; S++) {
+ NormCopy(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, gridSize - 1),
+ FACE_getIFNo(f, lvl, S, gridSize - 1, 0));
+ }
+
+ for (S = 0; S < f->numVerts; S++) {
+ for (y = 0; y < gridSize; y++) {
+ for (x = 0; x < gridSize; x++) {
+ float *no = FACE_getIFNo(f, lvl, S, x, y);
+ Normalize(no);
+ }
+ }
+
+ VertDataCopy((float *)((byte *)FACE_getCenterData(f) + normalDataOffset),
+ FACE_getIFNo(f, lvl, S, 0, 0), ss);
+
+ for (x = 1; x < gridSize - 1; x++) {
+ NormCopy(FACE_getIENo(f, lvl, S, x),
+ FACE_getIFNo(f, lvl, S, x, 0));
+ }
+ }
+}
+
+static void ccgSubSurf__calcVertNormals_edges_accumulate_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ CCGSubSurfCalcSubdivData *data = userdata;
+
+ CCGSubSurf *ss = data->ss;
+ CCGEdge *e = data->effectedE[ptrIdx];
+
+ const int subdivLevels = ss->subdivLevels;
+ const int lvl = ss->subdivLevels;
+ const int edgeSize = ccg_edgesize(lvl);
+ const int normalDataOffset = ss->normalDataOffset;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+
+ if (e->numFaces) {
+ CCGFace *fLast = e->faces[e->numFaces - 1];
+ int x, i;
+
+ for (i = 0; i < e->numFaces - 1; i++) {
+ CCGFace *f = e->faces[i];
+ const int f_ed_idx = ccg_face_getEdgeIndex(f, e);
+ const int f_ed_idx_last = ccg_face_getEdgeIndex(fLast, e);
+
+ for (x = 1; x < edgeSize - 1; x++) {
+ NormAdd(_face_getIFNoEdge(fLast, e, f_ed_idx_last, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset),
+ _face_getIFNoEdge(f, e, f_ed_idx, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset));
+ }
+ }
+
+ for (i = 0; i < e->numFaces - 1; i++) {
+ CCGFace *f = e->faces[i];
+ const int f_ed_idx = ccg_face_getEdgeIndex(f, e);
+ const int f_ed_idx_last = ccg_face_getEdgeIndex(fLast, e);
+
+ for (x = 1; x < edgeSize - 1; x++) {
+ NormCopy(_face_getIFNoEdge(f, e, f_ed_idx, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset),
+ _face_getIFNoEdge(fLast, e, f_ed_idx_last, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset));
}
}
}
+}
+
+static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss,
+ CCGVert **effectedV, CCGEdge **effectedE, CCGFace **effectedF,
+ int numEffectedV, int numEffectedE, int numEffectedF)
+{
+ int i, ptrIdx;
+ const int subdivLevels = ss->subdivLevels;
+ const int lvl = ss->subdivLevels;
+ const int edgeSize = ccg_edgesize(lvl);
+ const int gridSize = ccg_gridsize(lvl);
+ const int normalDataOffset = ss->normalDataOffset;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+
+ CCGSubSurfCalcSubdivData data = {
+ .ss = ss,
+ .effectedV = effectedV,
+ .effectedE = effectedE,
+ .effectedF = effectedF,
+ .numEffectedV = numEffectedV,
+ .numEffectedE = numEffectedE,
+ .numEffectedF = numEffectedF
+ };
+
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedF,
+ &data,
+ ccgSubSurf__calcVertNormals_faces_accumulate_cb,
+ &settings);
+ }
+
/* XXX can I reduce the number of normalisations here? */
for (ptrIdx = 0; ptrIdx < numEffectedV; ptrIdx++) {
CCGVert *v = (CCGVert *) effectedV[ptrIdx];
@@ -236,62 +370,25 @@ static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss,
NormCopy(FACE_getIFNo(f, lvl, ccg_face_getVertIndex(f, v), gridSize - 1, gridSize - 1), no);
}
}
- for (ptrIdx = 0; ptrIdx < numEffectedE; ptrIdx++) {
- CCGEdge *e = (CCGEdge *) effectedE[ptrIdx];
-
- if (e->numFaces) {
- CCGFace *fLast = e->faces[e->numFaces - 1];
- int x;
-
- for (i = 0; i < e->numFaces - 1; i++) {
- CCGFace *f = e->faces[i];
- const int f_ed_idx = ccg_face_getEdgeIndex(f, e);
- const int f_ed_idx_last = ccg_face_getEdgeIndex(fLast, e);
- for (x = 1; x < edgeSize - 1; x++) {
- NormAdd(_face_getIFNoEdge(fLast, e, f_ed_idx_last, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset),
- _face_getIFNoEdge(f, e, f_ed_idx, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset));
- }
- }
-
- for (i = 0; i < e->numFaces - 1; i++) {
- CCGFace *f = e->faces[i];
- const int f_ed_idx = ccg_face_getEdgeIndex(f, e);
- const int f_ed_idx_last = ccg_face_getEdgeIndex(fLast, e);
-
- for (x = 1; x < edgeSize - 1; x++) {
- NormCopy(_face_getIFNoEdge(f, e, f_ed_idx, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset),
- _face_getIFNoEdge(fLast, e, f_ed_idx_last, lvl, x, 0, subdivLevels, vertDataSize, normalDataOffset));
- }
- }
- }
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedE,
+ &data,
+ ccgSubSurf__calcVertNormals_edges_accumulate_cb,
+ &settings);
}
-#pragma omp parallel for private(ptrIdx) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
- for (ptrIdx = 0; ptrIdx < numEffectedF; ptrIdx++) {
- CCGFace *f = (CCGFace *) effectedF[ptrIdx];
- int S, x, y;
-
- for (S = 0; S < f->numVerts; S++) {
- NormCopy(FACE_getIFNo(f, lvl, (S + 1) % f->numVerts, 0, gridSize - 1),
- FACE_getIFNo(f, lvl, S, gridSize - 1, 0));
- }
-
- for (S = 0; S < f->numVerts; S++) {
- for (y = 0; y < gridSize; y++) {
- for (x = 0; x < gridSize; x++) {
- float *no = FACE_getIFNo(f, lvl, S, x, y);
- Normalize(no);
- }
- }
-
- VertDataCopy((float *)((byte *)FACE_getCenterData(f) + normalDataOffset),
- FACE_getIFNo(f, lvl, S, 0, 0), ss);
-
- for (x = 1; x < gridSize - 1; x++)
- NormCopy(FACE_getIENo(f, lvl, S, x),
- FACE_getIFNo(f, lvl, S, x, 0));
- }
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedF,
+ &data,
+ ccgSubSurf__calcVertNormals_faces_finalize_cb,
+ &settings);
}
for (ptrIdx = 0; ptrIdx < numEffectedE; ptrIdx++) {
@@ -322,100 +419,282 @@ static void ccgSubSurf__calcVertNormals(CCGSubSurf *ss,
}
}
-static void ccgSubSurf__calcSubdivLevel(
- CCGSubSurf *ss,
- CCGVert **effectedV, CCGEdge **effectedE, CCGFace **effectedF,
- const int numEffectedV, const int numEffectedE, const int numEffectedF, const int curLvl)
+
+static void ccgSubSurf__calcSubdivLevel_interior_faces_edges_midpoints_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
+ CCGSubSurfCalcSubdivData *data = userdata;
+
+ CCGSubSurf *ss = data->ss;
+ CCGFace *f = data->effectedF[ptrIdx];
+
const int subdivLevels = ss->subdivLevels;
+ const int curLvl = data->curLvl;
const int nextLvl = curLvl + 1;
- int edgeSize = ccg_edgesize(curLvl);
- int gridSize = ccg_gridsize(curLvl);
- int ptrIdx, i;
- int vertDataSize = ss->meshIFC.vertDataSize;
- float *q = ss->q, *r = ss->r;
+ const int gridSize = ccg_gridsize(curLvl);
+ const int vertDataSize = ss->meshIFC.vertDataSize;
-#pragma omp parallel for private(ptrIdx) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
- for (ptrIdx = 0; ptrIdx < numEffectedF; ptrIdx++) {
- CCGFace *f = (CCGFace *) effectedF[ptrIdx];
- int S, x, y;
+ int S, x, y;
+
+ /* interior face midpoints
+ * - old interior face points
+ */
+ for (S = 0; S < f->numVerts; S++) {
+ for (y = 0; y < gridSize - 1; y++) {
+ for (x = 0; x < gridSize - 1; x++) {
+ int fx = 1 + 2 * x;
+ int fy = 1 + 2 * y;
+ const float *co0 = FACE_getIFCo(f, curLvl, S, x + 0, y + 0);
+ const float *co1 = FACE_getIFCo(f, curLvl, S, x + 1, y + 0);
+ const float *co2 = FACE_getIFCo(f, curLvl, S, x + 1, y + 1);
+ const float *co3 = FACE_getIFCo(f, curLvl, S, x + 0, y + 1);
+ float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
+
+ VertDataAvg4(co, co0, co1, co2, co3, ss);
+ }
+ }
+ }
+
+ /* interior edge midpoints
+ * - old interior edge points
+ * - new interior face midpoints
+ */
+ for (S = 0; S < f->numVerts; S++) {
+ for (x = 0; x < gridSize - 1; x++) {
+ int fx = x * 2 + 1;
+ const float *co0 = FACE_getIECo(f, curLvl, S, x + 0);
+ const float *co1 = FACE_getIECo(f, curLvl, S, x + 1);
+ const float *co2 = FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx);
+ const float *co3 = FACE_getIFCo(f, nextLvl, S, fx, 1);
+ float *co = FACE_getIECo(f, nextLvl, S, fx);
+
+ VertDataAvg4(co, co0, co1, co2, co3, ss);
+ }
- /* interior face midpoints
+ /* interior face interior edge midpoints
* - old interior face points
+ * - new interior face midpoints
*/
- for (S = 0; S < f->numVerts; S++) {
+
+ /* vertical */
+ for (x = 1; x < gridSize - 1; x++) {
for (y = 0; y < gridSize - 1; y++) {
- for (x = 0; x < gridSize - 1; x++) {
- int fx = 1 + 2 * x;
- int fy = 1 + 2 * y;
- const float *co0 = FACE_getIFCo(f, curLvl, S, x + 0, y + 0);
- const float *co1 = FACE_getIFCo(f, curLvl, S, x + 1, y + 0);
- const float *co2 = FACE_getIFCo(f, curLvl, S, x + 1, y + 1);
- const float *co3 = FACE_getIFCo(f, curLvl, S, x + 0, y + 1);
- float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
-
- VertDataAvg4(co, co0, co1, co2, co3, ss);
- }
+ int fx = x * 2;
+ int fy = y * 2 + 1;
+ const float *co0 = FACE_getIFCo(f, curLvl, S, x, y + 0);
+ const float *co1 = FACE_getIFCo(f, curLvl, S, x, y + 1);
+ const float *co2 = FACE_getIFCo(f, nextLvl, S, fx - 1, fy);
+ const float *co3 = FACE_getIFCo(f, nextLvl, S, fx + 1, fy);
+ float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
+
+ VertDataAvg4(co, co0, co1, co2, co3, ss);
}
}
- /* interior edge midpoints
- * - old interior edge points
- * - new interior face midpoints
- */
- for (S = 0; S < f->numVerts; S++) {
+ /* horizontal */
+ for (y = 1; y < gridSize - 1; y++) {
for (x = 0; x < gridSize - 1; x++) {
int fx = x * 2 + 1;
- const float *co0 = FACE_getIECo(f, curLvl, S, x + 0);
- const float *co1 = FACE_getIECo(f, curLvl, S, x + 1);
- const float *co2 = FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx);
- const float *co3 = FACE_getIFCo(f, nextLvl, S, fx, 1);
- float *co = FACE_getIECo(f, nextLvl, S, fx);
-
+ int fy = y * 2;
+ const float *co0 = FACE_getIFCo(f, curLvl, S, x + 0, y);
+ const float *co1 = FACE_getIFCo(f, curLvl, S, x + 1, y);
+ const float *co2 = FACE_getIFCo(f, nextLvl, S, fx, fy - 1);
+ const float *co3 = FACE_getIFCo(f, nextLvl, S, fx, fy + 1);
+ float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
+
VertDataAvg4(co, co0, co1, co2, co3, ss);
}
+ }
+ }
+}
- /* interior face interior edge midpoints
- * - old interior face points
- * - new interior face midpoints
- */
-
- /* vertical */
- for (x = 1; x < gridSize - 1; x++) {
- for (y = 0; y < gridSize - 1; y++) {
- int fx = x * 2;
- int fy = y * 2 + 1;
- const float *co0 = FACE_getIFCo(f, curLvl, S, x, y + 0);
- const float *co1 = FACE_getIFCo(f, curLvl, S, x, y + 1);
- const float *co2 = FACE_getIFCo(f, nextLvl, S, fx - 1, fy);
- const float *co3 = FACE_getIFCo(f, nextLvl, S, fx + 1, fy);
- float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
-
- VertDataAvg4(co, co0, co1, co2, co3, ss);
- }
- }
+static void ccgSubSurf__calcSubdivLevel_interior_faces_edges_centerpoints_shift_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ CCGSubSurfCalcSubdivData *data = userdata;
+
+ CCGSubSurf *ss = data->ss;
+ CCGFace *f = data->effectedF[ptrIdx];
+
+ const int subdivLevels = ss->subdivLevels;
+ const int curLvl = data->curLvl;
+ const int nextLvl = curLvl + 1;
+ const int gridSize = ccg_gridsize(curLvl);
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+
+ float *q_thread = alloca(vertDataSize);
+ float *r_thread = alloca(vertDataSize);
- /* horizontal */
+ int S, x, y;
+
+ /* interior center point shift
+ * - old face center point (shifting)
+ * - old interior edge points
+ * - new interior face midpoints
+ */
+ VertDataZero(q_thread, ss);
+ for (S = 0; S < f->numVerts; S++) {
+ VertDataAdd(q_thread, FACE_getIFCo(f, nextLvl, S, 1, 1), ss);
+ }
+ VertDataMulN(q_thread, 1.0f / f->numVerts, ss);
+ VertDataZero(r_thread, ss);
+ for (S = 0; S < f->numVerts; S++) {
+ VertDataAdd(r_thread, FACE_getIECo(f, curLvl, S, 1), ss);
+ }
+ VertDataMulN(r_thread, 1.0f / f->numVerts, ss);
+
+ VertDataMulN((float *)FACE_getCenterData(f), f->numVerts - 2.0f, ss);
+ VertDataAdd((float *)FACE_getCenterData(f), q_thread, ss);
+ VertDataAdd((float *)FACE_getCenterData(f), r_thread, ss);
+ VertDataMulN((float *)FACE_getCenterData(f), 1.0f / f->numVerts, ss);
+
+ for (S = 0; S < f->numVerts; S++) {
+ /* interior face shift
+ * - old interior face point (shifting)
+ * - new interior edge midpoints
+ * - new interior face midpoints
+ */
+ for (x = 1; x < gridSize - 1; x++) {
for (y = 1; y < gridSize - 1; y++) {
- for (x = 0; x < gridSize - 1; x++) {
- int fx = x * 2 + 1;
- int fy = y * 2;
- const float *co0 = FACE_getIFCo(f, curLvl, S, x + 0, y);
- const float *co1 = FACE_getIFCo(f, curLvl, S, x + 1, y);
- const float *co2 = FACE_getIFCo(f, nextLvl, S, fx, fy - 1);
- const float *co3 = FACE_getIFCo(f, nextLvl, S, fx, fy + 1);
- float *co = FACE_getIFCo(f, nextLvl, S, fx, fy);
-
- VertDataAvg4(co, co0, co1, co2, co3, ss);
- }
+ int fx = x * 2;
+ int fy = y * 2;
+ const float *co = FACE_getIFCo(f, curLvl, S, x, y);
+ float *nCo = FACE_getIFCo(f, nextLvl, S, fx, fy);
+
+ VertDataAvg4(q_thread,
+ FACE_getIFCo(f, nextLvl, S, fx - 1, fy - 1),
+ FACE_getIFCo(f, nextLvl, S, fx + 1, fy - 1),
+ FACE_getIFCo(f, nextLvl, S, fx + 1, fy + 1),
+ FACE_getIFCo(f, nextLvl, S, fx - 1, fy + 1),
+ ss);
+
+ VertDataAvg4(r_thread,
+ FACE_getIFCo(f, nextLvl, S, fx - 1, fy + 0),
+ FACE_getIFCo(f, nextLvl, S, fx + 1, fy + 0),
+ FACE_getIFCo(f, nextLvl, S, fx + 0, fy - 1),
+ FACE_getIFCo(f, nextLvl, S, fx + 0, fy + 1),
+ ss);
+
+ VertDataCopy(nCo, co, ss);
+ VertDataSub(nCo, q_thread, ss);
+ VertDataMulN(nCo, 0.25f, ss);
+ VertDataAdd(nCo, r_thread, ss);
}
}
+
+ /* interior edge interior shift
+ * - old interior edge point (shifting)
+ * - new interior edge midpoints
+ * - new interior face midpoints
+ */
+ for (x = 1; x < gridSize - 1; x++) {
+ int fx = x * 2;
+ const float *co = FACE_getIECo(f, curLvl, S, x);
+ float *nCo = FACE_getIECo(f, nextLvl, S, fx);
+
+ VertDataAvg4(q_thread,
+ FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx - 1),
+ FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx + 1),
+ FACE_getIFCo(f, nextLvl, S, fx + 1, +1),
+ FACE_getIFCo(f, nextLvl, S, fx - 1, +1),
+ ss);
+
+ VertDataAvg4(r_thread,
+ FACE_getIECo(f, nextLvl, S, fx - 1),
+ FACE_getIECo(f, nextLvl, S, fx + 1),
+ FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx),
+ FACE_getIFCo(f, nextLvl, S, fx, 1),
+ ss);
+
+ VertDataCopy(nCo, co, ss);
+ VertDataSub(nCo, q_thread, ss);
+ VertDataMulN(nCo, 0.25f, ss);
+ VertDataAdd(nCo, r_thread, ss);
+ }
+ }
+}
+
+static void ccgSubSurf__calcSubdivLevel_verts_copydata_cb(
+ void *__restrict userdata,
+ const int ptrIdx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ CCGSubSurfCalcSubdivData *data = userdata;
+
+ CCGSubSurf *ss = data->ss;
+ CCGFace *f = data->effectedF[ptrIdx];
+
+ const int subdivLevels = ss->subdivLevels;
+ const int nextLvl = data->curLvl + 1;
+ const int gridSize = ccg_gridsize(nextLvl);
+ const int cornerIdx = gridSize - 1;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+
+ int S, x;
+
+ for (S = 0; S < f->numVerts; S++) {
+ CCGEdge *e = FACE_getEdges(f)[S];
+ CCGEdge *prevE = FACE_getEdges(f)[(S + f->numVerts - 1) % f->numVerts];
+
+ VertDataCopy(FACE_getIFCo(f, nextLvl, S, 0, 0), (float *)FACE_getCenterData(f), ss);
+ VertDataCopy(FACE_getIECo(f, nextLvl, S, 0), (float *)FACE_getCenterData(f), ss);
+ VertDataCopy(FACE_getIFCo(f, nextLvl, S, cornerIdx, cornerIdx), VERT_getCo(FACE_getVerts(f)[S], nextLvl), ss);
+ VertDataCopy(FACE_getIECo(f, nextLvl, S, cornerIdx), EDGE_getCo(FACE_getEdges(f)[S], nextLvl, cornerIdx), ss);
+ for (x = 1; x < gridSize - 1; x++) {
+ float *co = FACE_getIECo(f, nextLvl, S, x);
+ VertDataCopy(FACE_getIFCo(f, nextLvl, S, x, 0), co, ss);
+ VertDataCopy(FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 0, x), co, ss);
+ }
+ for (x = 0; x < gridSize - 1; x++) {
+ int eI = gridSize - 1 - x;
+ VertDataCopy(FACE_getIFCo(f, nextLvl, S, cornerIdx, x), _edge_getCoVert(e, FACE_getVerts(f)[S], nextLvl, eI, vertDataSize), ss);
+ VertDataCopy(FACE_getIFCo(f, nextLvl, S, x, cornerIdx), _edge_getCoVert(prevE, FACE_getVerts(f)[S], nextLvl, eI, vertDataSize), ss);
+ }
+ }
+}
+
+static void ccgSubSurf__calcSubdivLevel(
+ CCGSubSurf *ss,
+ CCGVert **effectedV, CCGEdge **effectedE, CCGFace **effectedF,
+ const int numEffectedV, const int numEffectedE, const int numEffectedF, const int curLvl)
+{
+ const int subdivLevels = ss->subdivLevels;
+ const int nextLvl = curLvl + 1;
+ int edgeSize = ccg_edgesize(curLvl);
+ int ptrIdx, i;
+ const int vertDataSize = ss->meshIFC.vertDataSize;
+ float *q = ss->q, *r = ss->r;
+
+ CCGSubSurfCalcSubdivData data = {
+ .ss = ss,
+ .effectedV = effectedV,
+ .effectedE = effectedE,
+ .effectedF = effectedF,
+ .numEffectedV = numEffectedV,
+ .numEffectedE = numEffectedE,
+ .numEffectedF = numEffectedF,
+ .curLvl = curLvl
+ };
+
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedF,
+ &data,
+ ccgSubSurf__calcSubdivLevel_interior_faces_edges_midpoints_cb,
+ &settings);
}
/* exterior edge midpoints
* - old exterior edge points
* - new interior face midpoints
*/
+ /* Not worth parallelizing. */
for (ptrIdx = 0; ptrIdx < numEffectedE; ptrIdx++) {
CCGEdge *e = (CCGEdge *) effectedE[ptrIdx];
float sharpness = EDGE_getSharpness(e, curLvl);
@@ -470,6 +749,7 @@ static void ccgSubSurf__calcSubdivLevel(
* - old exterior edge points
* - new interior face midpoints
*/
+ /* Not worth parallelizing. */
for (ptrIdx = 0; ptrIdx < numEffectedV; ptrIdx++) {
CCGVert *v = (CCGVert *) effectedV[ptrIdx];
const float *co = VERT_getCo(v, curLvl);
@@ -600,6 +880,7 @@ static void ccgSubSurf__calcSubdivLevel(
* - old exterior edge midpoints
* - new interior face midpoints
*/
+ /* Not worth parallelizing. */
for (ptrIdx = 0; ptrIdx < numEffectedE; ptrIdx++) {
CCGEdge *e = (CCGEdge *) effectedE[ptrIdx];
float sharpness = EDGE_getSharpness(e, curLvl);
@@ -682,150 +963,34 @@ static void ccgSubSurf__calcSubdivLevel(
}
}
-#pragma omp parallel private(ptrIdx) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
{
- float *q_thread, *r_thread;
-
-#pragma omp critical
- {
- q_thread = MEM_mallocN(ss->meshIFC.vertDataSize, "CCGSubsurf q");
- r_thread = MEM_mallocN(ss->meshIFC.vertDataSize, "CCGSubsurf r");
- }
-
-#pragma omp for schedule(static)
- for (ptrIdx = 0; ptrIdx < numEffectedF; ptrIdx++) {
- CCGFace *f = (CCGFace *) effectedF[ptrIdx];
- int S, x, y;
-
- /* interior center point shift
- * - old face center point (shifting)
- * - old interior edge points
- * - new interior face midpoints
- */
- VertDataZero(q_thread, ss);
- for (S = 0; S < f->numVerts; S++) {
- VertDataAdd(q_thread, FACE_getIFCo(f, nextLvl, S, 1, 1), ss);
- }
- VertDataMulN(q_thread, 1.0f / f->numVerts, ss);
- VertDataZero(r_thread, ss);
- for (S = 0; S < f->numVerts; S++) {
- VertDataAdd(r_thread, FACE_getIECo(f, curLvl, S, 1), ss);
- }
- VertDataMulN(r_thread, 1.0f / f->numVerts, ss);
-
- VertDataMulN((float *)FACE_getCenterData(f), f->numVerts - 2.0f, ss);
- VertDataAdd((float *)FACE_getCenterData(f), q_thread, ss);
- VertDataAdd((float *)FACE_getCenterData(f), r_thread, ss);
- VertDataMulN((float *)FACE_getCenterData(f), 1.0f / f->numVerts, ss);
-
- for (S = 0; S < f->numVerts; S++) {
- /* interior face shift
- * - old interior face point (shifting)
- * - new interior edge midpoints
- * - new interior face midpoints
- */
- for (x = 1; x < gridSize - 1; x++) {
- for (y = 1; y < gridSize - 1; y++) {
- int fx = x * 2;
- int fy = y * 2;
- const float *co = FACE_getIFCo(f, curLvl, S, x, y);
- float *nCo = FACE_getIFCo(f, nextLvl, S, fx, fy);
-
- VertDataAvg4(q_thread,
- FACE_getIFCo(f, nextLvl, S, fx - 1, fy - 1),
- FACE_getIFCo(f, nextLvl, S, fx + 1, fy - 1),
- FACE_getIFCo(f, nextLvl, S, fx + 1, fy + 1),
- FACE_getIFCo(f, nextLvl, S, fx - 1, fy + 1),
- ss);
-
- VertDataAvg4(r_thread,
- FACE_getIFCo(f, nextLvl, S, fx - 1, fy + 0),
- FACE_getIFCo(f, nextLvl, S, fx + 1, fy + 0),
- FACE_getIFCo(f, nextLvl, S, fx + 0, fy - 1),
- FACE_getIFCo(f, nextLvl, S, fx + 0, fy + 1),
- ss);
-
- VertDataCopy(nCo, co, ss);
- VertDataSub(nCo, q_thread, ss);
- VertDataMulN(nCo, 0.25f, ss);
- VertDataAdd(nCo, r_thread, ss);
- }
- }
-
- /* interior edge interior shift
- * - old interior edge point (shifting)
- * - new interior edge midpoints
- * - new interior face midpoints
- */
- for (x = 1; x < gridSize - 1; x++) {
- int fx = x * 2;
- const float *co = FACE_getIECo(f, curLvl, S, x);
- float *nCo = FACE_getIECo(f, nextLvl, S, fx);
-
- VertDataAvg4(q_thread,
- FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx - 1),
- FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx + 1),
- FACE_getIFCo(f, nextLvl, S, fx + 1, +1),
- FACE_getIFCo(f, nextLvl, S, fx - 1, +1), ss);
-
- VertDataAvg4(r_thread,
- FACE_getIECo(f, nextLvl, S, fx - 1),
- FACE_getIECo(f, nextLvl, S, fx + 1),
- FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 1, fx),
- FACE_getIFCo(f, nextLvl, S, fx, 1),
- ss);
-
- VertDataCopy(nCo, co, ss);
- VertDataSub(nCo, q_thread, ss);
- VertDataMulN(nCo, 0.25f, ss);
- VertDataAdd(nCo, r_thread, ss);
- }
- }
- }
-
-#pragma omp critical
- {
- MEM_freeN(q_thread);
- MEM_freeN(r_thread);
- }
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedF,
+ &data,
+ ccgSubSurf__calcSubdivLevel_interior_faces_edges_centerpoints_shift_cb,
+ &settings);
}
/* copy down */
edgeSize = ccg_edgesize(nextLvl);
- gridSize = ccg_gridsize(nextLvl);
- const int cornerIdx = gridSize - 1;
-#pragma omp parallel for private(i) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
+ /* Not worth parallelizing. */
for (i = 0; i < numEffectedE; i++) {
CCGEdge *e = effectedE[i];
VertDataCopy(EDGE_getCo(e, nextLvl, 0), VERT_getCo(e->v0, nextLvl), ss);
VertDataCopy(EDGE_getCo(e, nextLvl, edgeSize - 1), VERT_getCo(e->v1, nextLvl), ss);
}
-#pragma omp parallel for private(i) if (numEffectedF * edgeSize * edgeSize * 4 >= CCG_OMP_LIMIT)
- for (i = 0; i < numEffectedF; i++) {
- CCGFace *f = effectedF[i];
- int S, x;
-
- for (S = 0; S < f->numVerts; S++) {
- CCGEdge *e = FACE_getEdges(f)[S];
- CCGEdge *prevE = FACE_getEdges(f)[(S + f->numVerts - 1) % f->numVerts];
-
- VertDataCopy(FACE_getIFCo(f, nextLvl, S, 0, 0), (float *)FACE_getCenterData(f), ss);
- VertDataCopy(FACE_getIECo(f, nextLvl, S, 0), (float *)FACE_getCenterData(f), ss);
- VertDataCopy(FACE_getIFCo(f, nextLvl, S, cornerIdx, cornerIdx), VERT_getCo(FACE_getVerts(f)[S], nextLvl), ss);
- VertDataCopy(FACE_getIECo(f, nextLvl, S, cornerIdx), EDGE_getCo(FACE_getEdges(f)[S], nextLvl, cornerIdx), ss);
- for (x = 1; x < gridSize - 1; x++) {
- float *co = FACE_getIECo(f, nextLvl, S, x);
- VertDataCopy(FACE_getIFCo(f, nextLvl, S, x, 0), co, ss);
- VertDataCopy(FACE_getIFCo(f, nextLvl, (S + 1) % f->numVerts, 0, x), co, ss);
- }
- for (x = 0; x < gridSize - 1; x++) {
- int eI = gridSize - 1 - x;
- VertDataCopy(FACE_getIFCo(f, nextLvl, S, cornerIdx, x), _edge_getCoVert(e, FACE_getVerts(f)[S], nextLvl, eI, vertDataSize), ss);
- VertDataCopy(FACE_getIFCo(f, nextLvl, S, x, cornerIdx), _edge_getCoVert(prevE, FACE_getVerts(f)[S], nextLvl, eI, vertDataSize), ss);
- }
- }
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+ BLI_task_parallel_range(0, numEffectedF,
+ &data,
+ ccgSubSurf__calcSubdivLevel_verts_copydata_cb,
+ &settings);
}
}
diff --git a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv.c b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv.c
index 65cf899b42b..f568bb94ac5 100644
--- a/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv.c
+++ b/source/blender/blenkernel/intern/CCGSubSurf_opensubdiv.c
@@ -282,6 +282,7 @@ bool ccgSubSurf_prepareGLMesh(CCGSubSurf *ss,
sizeof(GLfloat) * 6, (float *)12);
glBindBuffer(GL_ARRAY_BUFFER, 0);
+ glBindVertexArray(0);
}
else if (ss->osd_coarse_coords_invalid) {
ccgSubSurf__updateGLMeshCoords(ss);
@@ -299,6 +300,7 @@ void ccgSubSurf_drawGLMesh(CCGSubSurf *ss, bool fill_quads,
int start_partition, int num_partitions)
{
if (LIKELY(ss->osd_mesh != NULL)) {
+ glBindVertexArray(ss->osd_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,
openSubdiv_getOsdGLMeshPatchIndexBuffer(ss->osd_mesh));
diff --git a/source/blender/blenkernel/intern/DerivedMesh.c b/source/blender/blenkernel/intern/DerivedMesh.c
index 160adcc3988..15469e3ae4b 100644
--- a/source/blender/blenkernel/intern/DerivedMesh.c
+++ b/source/blender/blenkernel/intern/DerivedMesh.c
@@ -52,6 +52,7 @@
#include "BLI_task.h"
#include "BKE_cdderivedmesh.h"
+#include "BKE_colorband.h"
#include "BKE_editmesh.h"
#include "BKE_key.h"
#include "BKE_library.h"
@@ -62,7 +63,6 @@
#include "BKE_object.h"
#include "BKE_object_deform.h"
#include "BKE_paint.h"
-#include "BKE_texture.h"
#include "BKE_multires.h"
#include "BKE_bvhutils.h"
#include "BKE_deform.h"
@@ -93,6 +93,10 @@ static DerivedMesh *navmesh_dm_createNavMeshForVisualization(DerivedMesh *dm);
# define ASSERT_IS_VALID_DM(dm)
#endif
+
+static ThreadRWMutex loops_cache_lock = PTHREAD_RWLOCK_INITIALIZER;
+
+
static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *ob);
static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape_uid);
@@ -180,7 +184,7 @@ static MPoly *dm_getPolyArray(DerivedMesh *dm)
static MVert *dm_dupVertArray(DerivedMesh *dm)
{
- MVert *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumVerts(dm),
+ MVert *tmp = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(*tmp),
"dm_dupVertArray tmp");
if (tmp) dm->copyVertArray(dm, tmp);
@@ -190,7 +194,7 @@ static MVert *dm_dupVertArray(DerivedMesh *dm)
static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
{
- MEdge *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumEdges(dm),
+ MEdge *tmp = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(*tmp),
"dm_dupEdgeArray tmp");
if (tmp) dm->copyEdgeArray(dm, tmp);
@@ -200,7 +204,7 @@ static MEdge *dm_dupEdgeArray(DerivedMesh *dm)
static MFace *dm_dupFaceArray(DerivedMesh *dm)
{
- MFace *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumTessFaces(dm),
+ MFace *tmp = MEM_malloc_arrayN(dm->getNumTessFaces(dm), sizeof(*tmp),
"dm_dupFaceArray tmp");
if (tmp) dm->copyTessFaceArray(dm, tmp);
@@ -210,7 +214,7 @@ static MFace *dm_dupFaceArray(DerivedMesh *dm)
static MLoop *dm_dupLoopArray(DerivedMesh *dm)
{
- MLoop *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumLoops(dm),
+ MLoop *tmp = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(*tmp),
"dm_dupLoopArray tmp");
if (tmp) dm->copyLoopArray(dm, tmp);
@@ -220,7 +224,7 @@ static MLoop *dm_dupLoopArray(DerivedMesh *dm)
static MPoly *dm_dupPolyArray(DerivedMesh *dm)
{
- MPoly *tmp = MEM_mallocN(sizeof(*tmp) * dm->getNumPolys(dm),
+ MPoly *tmp = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(*tmp),
"dm_dupPolyArray tmp");
if (tmp) dm->copyPolyArray(dm, tmp);
@@ -235,6 +239,30 @@ static int dm_getNumLoopTri(DerivedMesh *dm)
return numlooptris;
}
+static const MLoopTri *dm_getLoopTriArray(DerivedMesh *dm)
+{
+ MLoopTri *looptri;
+
+ BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_READ);
+ looptri = dm->looptris.array;
+ BLI_rw_mutex_unlock(&loops_cache_lock);
+
+ if (looptri != NULL) {
+ BLI_assert(dm->getNumLoopTri(dm) == dm->looptris.num);
+ }
+ else {
+ BLI_rw_mutex_lock(&loops_cache_lock, THREAD_LOCK_WRITE);
+ /* We need to ensure array is still NULL inside mutex-protected code, some other thread might have already
+ * recomputed those looptris. */
+ if (dm->looptris.array == NULL) {
+ dm->recalcLoopTri(dm);
+ }
+ looptri = dm->looptris.array;
+ BLI_rw_mutex_unlock(&loops_cache_lock);
+ }
+ return looptri;
+}
+
static CustomData *dm_getVertCData(DerivedMesh *dm)
{
return &dm->vertData;
@@ -278,6 +306,8 @@ void DM_init_funcs(DerivedMesh *dm)
dm->dupLoopArray = dm_dupLoopArray;
dm->dupPolyArray = dm_dupPolyArray;
+ dm->getLoopTriArray = dm_getLoopTriArray;
+
/* subtypes handle getting actual data */
dm->getNumLoopTri = dm_getNumLoopTri;
@@ -471,6 +501,8 @@ void DM_ensure_tessface(DerivedMesh *dm)
/**
* Ensure the array is large enough
+ *
+ * /note This function must always be thread-protected by caller. It should only be used by internal code.
*/
void DM_ensure_looptri_data(DerivedMesh *dm)
{
@@ -478,18 +510,22 @@ void DM_ensure_looptri_data(DerivedMesh *dm)
const unsigned int totloop = dm->numLoopData;
const int looptris_num = poly_to_tri_count(totpoly, totloop);
+ BLI_assert(dm->looptris.array_wip == NULL);
+
+ SWAP(MLoopTri *, dm->looptris.array, dm->looptris.array_wip);
+
if ((looptris_num > dm->looptris.num_alloc) ||
(looptris_num < dm->looptris.num_alloc * 2) ||
(totpoly == 0))
{
- MEM_SAFE_FREE(dm->looptris.array);
+ MEM_SAFE_FREE(dm->looptris.array_wip);
dm->looptris.num_alloc = 0;
dm->looptris.num = 0;
}
if (totpoly) {
- if (dm->looptris.array == NULL) {
- dm->looptris.array = MEM_mallocN(sizeof(*dm->looptris.array) * looptris_num, __func__);
+ if (dm->looptris.array_wip == NULL) {
+ dm->looptris.array_wip = MEM_malloc_arrayN(looptris_num, sizeof(*dm->looptris.array_wip), __func__);
dm->looptris.num_alloc = looptris_num;
}
@@ -497,19 +533,6 @@ void DM_ensure_looptri_data(DerivedMesh *dm)
}
}
-/**
- * The purpose of this function is that we can call:
- * `dm->getLoopTriArray(dm)` and get the array returned.
- */
-void DM_ensure_looptri(DerivedMesh *dm)
-{
- const int numPolys = dm->getNumPolys(dm);
-
- if ((dm->looptris.num == 0) && (numPolys != 0)) {
- dm->recalcLoopTri(dm);
- }
-}
-
void DM_verttri_from_looptri(MVertTri *verttri, const MLoop *mloop, const MLoopTri *looptri, int looptri_num)
{
int i;
@@ -551,7 +574,7 @@ void DM_update_tessface_data(DerivedMesh *dm)
CustomData_has_layer(fdata, CD_TESSLOOPNORMAL) ||
CustomData_has_layer(fdata, CD_TANGENT))
{
- loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__);
+ loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
const int mf_len = mf->v4 ? 4 : 3;
@@ -612,7 +635,7 @@ void DM_generate_tangent_tessface_data(DerivedMesh *dm, bool generate)
CustomData_bmesh_update_active_layers(fdata, pdata, ldata);
if (!loopindex) {
- loopindex = MEM_mallocN(sizeof(*loopindex) * totface, __func__);
+ loopindex = MEM_malloc_arrayN(totface, sizeof(*loopindex), __func__);
for (mf_idx = 0, mf = mface; mf_idx < totface; mf_idx++, mf++) {
const int mf_len = mf->v4 ? 4 : 3;
unsigned int *ml_idx = loopindex[mf_idx];
@@ -657,7 +680,7 @@ void DM_update_materials(DerivedMesh *dm, Object *ob)
if (dm->mat)
MEM_freeN(dm->mat);
- dm->mat = MEM_mallocN(totmat * sizeof(*dm->mat), "DerivedMesh.mat");
+ dm->mat = MEM_malloc_arrayN(totmat, sizeof(*dm->mat), "DerivedMesh.mat");
}
/* we leave last material as empty - rationale here is being able to index
@@ -847,7 +870,7 @@ void DM_to_meshkey(DerivedMesh *dm, Mesh *me, KeyBlock *kb)
}
if (kb->data) MEM_freeN(kb->data);
- kb->data = MEM_mallocN(me->key->elemsize * me->totvert, "kb->data");
+ kb->data = MEM_malloc_arrayN(me->key->elemsize, me->totvert, "kb->data");
kb->totelem = totvert;
fp = kb->data;
@@ -1183,7 +1206,7 @@ static float (*get_editbmesh_orco_verts(BMEditMesh *em))[3]
/* these may not really be the orco's, but it's only for preview.
* could be solver better once, but isn't simple */
- orco = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "BMEditMesh Orco");
+ orco = MEM_malloc_arrayN(em->bm->totvert, sizeof(float) * 3, "BMEditMesh Orco");
BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(orco[i], eve->co);
@@ -1257,7 +1280,7 @@ static void add_orco_dm(
totvert = dm->getNumVerts(dm);
if (orcodm) {
- orco = MEM_callocN(sizeof(float[3]) * totvert, "dm orco");
+ orco = MEM_calloc_arrayN(totvert, sizeof(float[3]), "dm orco");
free = 1;
if (orcodm->getNumVerts(orcodm) == totvert)
@@ -1354,7 +1377,7 @@ static void weightpaint_color(unsigned char r_col[4], DMWeightColorInfo *dm_wcin
float colf[4];
if (dm_wcinfo && dm_wcinfo->coba) {
- do_colorband(dm_wcinfo->coba, input, colf);
+ BKE_colorband_evaluate(dm_wcinfo->coba, input, colf);
}
else {
weight_to_rgb(colf, input);
@@ -1539,7 +1562,7 @@ void DM_update_weight_mcol(
wtcol_v = em->derivedVertColor;
}
else {
- wtcol_v = MEM_mallocN(sizeof(*wtcol_v) * numVerts, __func__);
+ wtcol_v = MEM_malloc_arrayN(numVerts, sizeof(*wtcol_v), __func__);
}
/* Weights are given by caller. */
@@ -1548,7 +1571,7 @@ void DM_update_weight_mcol(
/* If indices is not NULL, it means we do not have weights for all vertices,
* so we must create them (and set them to zero)... */
if (indices) {
- w = MEM_callocN(sizeof(float) * numVerts, "Temp weight array DM_update_weight_mcol");
+ w = MEM_calloc_arrayN(numVerts, sizeof(float), "Temp weight array DM_update_weight_mcol");
i = num;
while (i--)
w[indices[i]] = weights[i];
@@ -1580,7 +1603,7 @@ void DM_update_weight_mcol(
/* now add to loops, so the data can be passed through the modifier stack
* If no CD_PREVIEW_MLOOPCOL existed yet, we have to add a new one! */
if (!wtcol_l) {
- wtcol_l = MEM_mallocN(sizeof(*wtcol_l) * dm_totloop, __func__);
+ wtcol_l = MEM_malloc_arrayN(dm_totloop, sizeof(*wtcol_l), __func__);
CustomData_add_layer(&dm->loopData, CD_PREVIEW_MLOOPCOL, CD_ASSIGN, wtcol_l, dm_totloop);
}
@@ -1635,7 +1658,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
cos = CustomData_get_layer_n(&dm->vertData, CD_SHAPEKEY, i);
kb->totelem = dm->numVertData;
- kb->data = kbcos = MEM_mallocN(sizeof(float) * 3 * kb->totelem, "kbcos DerivedMesh.c");
+ kb->data = kbcos = MEM_malloc_arrayN(kb->totelem, 3 * sizeof(float), "kbcos DerivedMesh.c");
if (kb->uid == actshape_uid) {
MVert *mvert = dm->getVertArray(dm);
@@ -1656,7 +1679,7 @@ static void shapekey_layers_to_keyblocks(DerivedMesh *dm, Mesh *me, int actshape
MEM_freeN(kb->data);
kb->totelem = dm->numVertData;
- kb->data = MEM_callocN(sizeof(float) * 3 * kb->totelem, "kb->data derivedmesh.c");
+ kb->data = MEM_calloc_arrayN(kb->totelem, 3 * sizeof(float), "kb->data derivedmesh.c");
fprintf(stderr, "%s: lost a shapekey layer: '%s'! (bmesh internal error)\n", __func__, kb->name);
}
}
@@ -1667,7 +1690,6 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
KeyBlock *kb;
Key *key = me->key;
int i;
- const size_t shape_alloc_len = sizeof(float) * 3 * me->totvert;
if (!me->key)
return;
@@ -1688,11 +1710,11 @@ static void add_shapekey_layers(DerivedMesh *dm, Mesh *me, Object *UNUSED(ob))
fprintf(stderr,
"%s: vertex size mismatch (Mesh '%s':%d != KeyBlock '%s':%d)\n",
__func__, me->id.name + 2, me->totvert, kb->name, kb->totelem);
- array = MEM_callocN(shape_alloc_len, __func__);
+ array = MEM_calloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
}
else {
- array = MEM_mallocN(shape_alloc_len, __func__);
- memcpy(array, kb->data, shape_alloc_len);
+ array = MEM_malloc_arrayN((size_t)me->totvert, 3 * sizeof(float), __func__);
+ memcpy(array, kb->data, (size_t)me->totvert * 3 * sizeof(float));
}
CustomData_add_layer_named(&dm->vertData, CD_SHAPEKEY, CD_ASSIGN, array, dm->numVertData, kb->name);
@@ -1965,7 +1987,7 @@ static void mesh_calc_modifiers(
*/
numVerts = dm->getNumVerts(dm);
deformedVerts =
- MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
+ MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
dm->getVertCos(dm, deformedVerts);
}
else {
@@ -2123,6 +2145,8 @@ static void mesh_calc_modifiers(
DM_update_weight_mcol(ob, dm, draw_flag, NULL, 0, NULL);
append_mask |= CD_MASK_PREVIEW_MLOOPCOL;
}
+
+ dm->deformedOnly = false;
}
isPrevDeform = (mti->type == eModifierTypeType_OnlyDeform);
@@ -2199,7 +2223,6 @@ static void mesh_calc_modifiers(
if (dataMask & CD_MASK_MFACE) {
DM_ensure_tessface(finaldm);
}
- DM_ensure_looptri(finaldm);
/* without this, drawing ngon tri's faces will show ugly tessellated face
* normals and will also have to calculate normals on the fly, try avoid
@@ -2257,7 +2280,7 @@ float (*editbmesh_get_vertex_cos(BMEditMesh *em, int *r_numVerts))[3]
*r_numVerts = em->bm->totvert;
- cos = MEM_mallocN(sizeof(float) * 3 * em->bm->totvert, "vertexcos");
+ cos = MEM_malloc_arrayN(em->bm->totvert, 3 * sizeof(float), "vertexcos");
BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
copy_v3_v3(cos[i], eve->co);
@@ -2363,7 +2386,7 @@ static void editbmesh_calc_modifiers(
*/
numVerts = dm->getNumVerts(dm);
deformedVerts =
- MEM_mallocN(sizeof(*deformedVerts) * numVerts, "dfmv");
+ MEM_malloc_arrayN(numVerts, sizeof(*deformedVerts), "dfmv");
dm->getVertCos(dm, deformedVerts);
}
else {
@@ -2463,6 +2486,8 @@ static void editbmesh_calc_modifiers(
deformedVerts = NULL;
}
}
+
+ dm->deformedOnly = false;
}
/* In case of active preview modifier, make sure preview mask remains for following modifiers. */
@@ -2637,7 +2662,7 @@ static void mesh_build_data(
ob->lastDataMask = dataMask;
ob->lastNeedMapping = need_mapping;
- if ((ob->mode & OB_MODE_SCULPT) && ob->sculpt) {
+ if ((ob->mode & OB_MODE_ALL_SCULPT) && ob->sculpt) {
/* create PBVH immediately (would be created on the fly too,
* but this avoids waiting on first stroke) */
@@ -2912,9 +2937,6 @@ DerivedMesh *editbmesh_get_derived_base(Object *obedit, BMEditMesh *em, CustomDa
/* get derived mesh from an object, using editbmesh if available. */
DerivedMesh *object_get_derived_final(Object *ob, const bool for_render)
{
- Mesh *me = ob->data;
- BMEditMesh *em = me->edit_btmesh;
-
if (for_render) {
/* TODO(sergey): use proper derived render here in the future. */
return ob->derivedFinal;
@@ -2922,9 +2944,13 @@ DerivedMesh *object_get_derived_final(Object *ob, const bool for_render)
/* only return the editmesh if its from this object because
* we don't a mesh from another object's modifier stack: T43122 */
- if (em && (em->ob == ob)) {
- DerivedMesh *dm = em->derivedFinal;
- return dm;
+ if (ob->type == OB_MESH) {
+ Mesh *me = ob->data;
+ BMEditMesh *em = me->edit_btmesh;
+ if (em && (em->ob == ob)) {
+ DerivedMesh *dm = em->derivedFinal;
+ return dm;
+ }
}
return ob->derivedFinal;
@@ -2973,11 +2999,11 @@ DMCoNo *mesh_get_mapped_verts_nors(Scene *scene, Object *ob)
dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH | CD_MASK_ORIGINDEX);
if (dm->foreachMappedVert) {
- vertexcosnos = MEM_callocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
+ vertexcosnos = MEM_calloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
dm->foreachMappedVert(dm, make_vertexcosnos__mapFunc, vertexcosnos);
}
else {
- DMCoNo *v_co_no = vertexcosnos = MEM_mallocN(sizeof(DMCoNo) * me->totvert, "vertexcosnos map");
+ DMCoNo *v_co_no = vertexcosnos = MEM_malloc_arrayN(me->totvert, sizeof(DMCoNo), "vertexcosnos map");
int a;
for (a = 0; a < me->totvert; a++, v_co_no++) {
dm->getVertCo(dm, a, v_co_no->co);
@@ -3317,7 +3343,8 @@ void DM_calc_loop_tangents_step_0(
const CustomData *loopData, bool calc_active_tangent,
const char (*tangent_names)[MAX_NAME], int tangent_names_count,
bool *rcalc_act, bool *rcalc_ren, int *ract_uv_n, int *rren_uv_n,
- char *ract_uv_name, char *rren_uv_name, char *rtangent_mask) {
+ char *ract_uv_name, char *rren_uv_name, short *rtangent_mask)
+{
/* Active uv in viewport */
int layer_index = CustomData_get_layer_index(loopData, CD_MLOOPUV);
*ract_uv_n = CustomData_get_active_layer(loopData, CD_MLOOPUV);
@@ -3371,21 +3398,22 @@ void DM_calc_loop_tangents_step_0(
if (add)
*rtangent_mask |= 1 << n;
}
+
+ if (uv_layer_num == 0)
+ *rtangent_mask |= DM_TANGENT_MASK_ORCO;
}
void DM_calc_loop_tangents(
DerivedMesh *dm, bool calc_active_tangent,
const char (*tangent_names)[MAX_NAME], int tangent_names_count)
{
- if (CustomData_number_of_layers(&dm->loopData, CD_MLOOPUV) == 0)
- return;
int act_uv_n = -1;
int ren_uv_n = -1;
bool calc_act = false;
bool calc_ren = false;
char act_uv_name[MAX_NAME];
char ren_uv_name[MAX_NAME];
- char tangent_mask = 0;
+ short tangent_mask = 0;
DM_calc_loop_tangents_step_0(
&dm->loopData, calc_active_tangent, tangent_names, tangent_names_count,
&calc_act, &calc_ren, &act_uv_n, &ren_uv_n, act_uv_name, ren_uv_name, &tangent_mask);
@@ -3398,6 +3426,8 @@ void DM_calc_loop_tangents(
for (int i = 0; i < tangent_names_count; i++)
if (tangent_names[i][0])
DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, tangent_names[i]);
+ if ((tangent_mask & DM_TANGENT_MASK_ORCO) && CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, "") == -1)
+ CustomData_add_layer_named(&dm->loopData, CD_TANGENT, CD_CALLOC, NULL, dm->numLoopData, "");
if (calc_act && act_uv_name[0])
DM_add_named_tangent_layer_for_uv(&dm->loopData, &dm->loopData, dm->numLoopData, act_uv_name);
if (calc_ren && ren_uv_name[0])
@@ -3412,7 +3442,7 @@ void DM_calc_loop_tangents(
/* over alloc, since we dont know how many ngon or quads we have */
/* map fake face index to looptri */
- face_as_quad_map = MEM_mallocN(sizeof(int) * totface, __func__);
+ face_as_quad_map = MEM_malloc_arrayN(totface, sizeof(int), __func__);
int k, j;
for (k = 0, j = 0; j < totface; k++, j++) {
face_as_quad_map[k] = j;
@@ -3455,23 +3485,28 @@ void DM_calc_loop_tangents(
* have to check this is valid...
*/
mesh2tangent->precomputedLoopNormals = dm->getLoopDataArray(dm, CD_NORMAL);
- mesh2tangent->precomputedFaceNormals = CustomData_get_layer(&dm->faceData, CD_NORMAL);
+ mesh2tangent->precomputedFaceNormals = CustomData_get_layer(&dm->polyData, CD_NORMAL);
mesh2tangent->orco = NULL;
mesh2tangent->mloopuv = CustomData_get_layer_named(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name);
+
+ /* Fill the resulting tangent_mask */
if (!mesh2tangent->mloopuv) {
mesh2tangent->orco = dm->getVertDataArray(dm, CD_ORCO);
if (!mesh2tangent->orco)
continue;
+
+ dm->tangent_mask |= DM_TANGENT_MASK_ORCO;
+ }
+ else {
+ int uv_ind = CustomData_get_named_layer_index(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name);
+ int uv_start = CustomData_get_layer_index(&dm->loopData, CD_MLOOPUV);
+ BLI_assert(uv_ind != -1 && uv_start != -1);
+ BLI_assert(uv_ind - uv_start < MAX_MTFACE);
+ dm->tangent_mask |= 1 << (uv_ind - uv_start);
}
- mesh2tangent->tangent = dm->loopData.layers[index].data;
- /* Fill the resulting tangent_mask */
- int uv_ind = CustomData_get_named_layer_index(&dm->loopData, CD_MLOOPUV, dm->loopData.layers[index].name);
- int uv_start = CustomData_get_layer_index(&dm->loopData, CD_MLOOPUV);
- BLI_assert(uv_ind != -1 && uv_start != -1);
- BLI_assert(uv_ind - uv_start < MAX_MTFACE);
- dm->tangent_mask |= 1 << (uv_ind - uv_start);
+ mesh2tangent->tangent = dm->loopData.layers[index].data;
BLI_task_pool_push(task_pool, DM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW);
}
@@ -3487,21 +3522,19 @@ void DM_calc_loop_tangents(
#endif
- int uv_index, tan_index;
-
/* Update active layer index */
- uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, act_uv_n);
- if (uv_index != -1) {
- tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name);
+ int act_uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, act_uv_n);
+ if (act_uv_index != -1) {
+ int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[act_uv_index].name);
CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index);
- }
+ } /* else tangent has been built from orco */
/* Update render layer index */
- uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, ren_uv_n);
- if (uv_index != -1) {
- tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[uv_index].name);
+ int ren_uv_index = CustomData_get_layer_index_n(&dm->loopData, CD_MLOOPUV, ren_uv_n);
+ if (ren_uv_index != -1) {
+ int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, dm->loopData.layers[ren_uv_index].name);
CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index);
- }
+ } /* else tangent has been built from orco */
}
}
@@ -3877,17 +3910,25 @@ void DM_draw_attrib_vertex_uniforms(const DMVertexAttribs *attribs)
{
int i;
if (attribs->totorco) {
- glUniform1i(attribs->orco.gl_info_index, 0);
+ if (attribs->orco.gl_info_index != -1) {
+ glUniform1i(attribs->orco.gl_info_index, 0);
+ }
}
for (i = 0; i < attribs->tottface; i++) {
- glUniform1i(attribs->tface[i].gl_info_index, 0);
+ if (attribs->tface[i].gl_info_index != -1) {
+ glUniform1i(attribs->tface[i].gl_info_index, 0);
+ }
}
for (i = 0; i < attribs->totmcol; i++) {
- glUniform1i(attribs->mcol[i].gl_info_index, GPU_ATTR_INFO_SRGB);
+ if (attribs->mcol[i].gl_info_index != -1) {
+ glUniform1i(attribs->mcol[i].gl_info_index, GPU_ATTR_INFO_SRGB);
+ }
}
for (i = 0; i < attribs->tottang; i++) {
- glUniform1i(attribs->tang[i].gl_info_index, 0);
+ if (attribs->tang[i].gl_info_index != -1) {
+ glUniform1i(attribs->tang[i].gl_info_index, 0);
+ }
}
}
@@ -4116,7 +4157,7 @@ void DM_init_origspace(DerivedMesh *dm)
BKE_mesh_calc_poly_normal(mp, l, mv, p_nor);
axis_dominant_v3_to_m3(mat, p_nor);
- BLI_array_empty(vcos_2d);
+ BLI_array_clear(vcos_2d);
BLI_array_reserve(vcos_2d, mp->totloop);
for (j = 0; j < mp->totloop; j++, l++) {
mul_v3_m3v3(co, mat, mv[l->v].co);
@@ -4303,7 +4344,7 @@ MVert *DM_get_vert_array(DerivedMesh *dm, bool *allocated)
*allocated = false;
if (mvert == NULL) {
- mvert = MEM_mallocN(sizeof(MVert) * dm->getNumVerts(dm), "dmvh vert data array");
+ mvert = MEM_malloc_arrayN(dm->getNumVerts(dm), sizeof(MVert), "dmvh vert data array");
dm->copyVertArray(dm, mvert);
*allocated = true;
}
@@ -4318,7 +4359,7 @@ MEdge *DM_get_edge_array(DerivedMesh *dm, bool *allocated)
*allocated = false;
if (medge == NULL) {
- medge = MEM_mallocN(sizeof(MEdge) * dm->getNumEdges(dm), "dm medge data array");
+ medge = MEM_malloc_arrayN(dm->getNumEdges(dm), sizeof(MEdge), "dm medge data array");
dm->copyEdgeArray(dm, medge);
*allocated = true;
}
@@ -4333,7 +4374,7 @@ MLoop *DM_get_loop_array(DerivedMesh *dm, bool *r_allocated)
*r_allocated = false;
if (mloop == NULL) {
- mloop = MEM_mallocN(sizeof(MLoop) * dm->getNumLoops(dm), "dm loop data array");
+ mloop = MEM_malloc_arrayN(dm->getNumLoops(dm), sizeof(MLoop), "dm loop data array");
dm->copyLoopArray(dm, mloop);
*r_allocated = true;
}
@@ -4348,7 +4389,7 @@ MPoly *DM_get_poly_array(DerivedMesh *dm, bool *r_allocated)
*r_allocated = false;
if (mpoly == NULL) {
- mpoly = MEM_mallocN(sizeof(MPoly) * dm->getNumPolys(dm), "dm poly data array");
+ mpoly = MEM_malloc_arrayN(dm->getNumPolys(dm), sizeof(MPoly), "dm poly data array");
dm->copyPolyArray(dm, mpoly);
*r_allocated = true;
}
@@ -4366,7 +4407,7 @@ MFace *DM_get_tessface_array(DerivedMesh *dm, bool *r_allocated)
int numTessFaces = dm->getNumTessFaces(dm);
if (numTessFaces > 0) {
- mface = MEM_mallocN(sizeof(MFace) * numTessFaces, "bvh mface data array");
+ mface = MEM_malloc_arrayN(numTessFaces, sizeof(MFace), "bvh mface data array");
dm->copyTessFaceArray(dm, mface);
*r_allocated = true;
}
@@ -4374,35 +4415,3 @@ MFace *DM_get_tessface_array(DerivedMesh *dm, bool *r_allocated)
return mface;
}
-
-const MLoopTri *DM_get_looptri_array(
- DerivedMesh *dm,
- const MVert *mvert,
- const MPoly *mpoly, int mpoly_len,
- const MLoop *mloop, int mloop_len,
- bool *r_allocated)
-{
- const MLoopTri *looptri = dm->getLoopTriArray(dm);
- *r_allocated = false;
-
- if (looptri == NULL) {
- if (mpoly_len > 0) {
- const int looptris_num = poly_to_tri_count(mpoly_len, mloop_len);
- MLoopTri *looptri_data;
-
- looptri_data = MEM_mallocN(sizeof(MLoopTri) * looptris_num, __func__);
-
- BKE_mesh_recalc_looptri(
- mloop, mpoly,
- mvert,
- mloop_len, mpoly_len,
- looptri_data);
-
- looptri = looptri_data;
-
- *r_allocated = true;
- }
- }
-
- return looptri;
-}
diff --git a/source/blender/blenkernel/intern/action.c b/source/blender/blenkernel/intern/action.c
index 1e33fe4ab46..c06a1a8106c 100644
--- a/source/blender/blenkernel/intern/action.c
+++ b/source/blender/blenkernel/intern/action.c
@@ -84,11 +84,11 @@
/* ***************** Library data level operations on action ************** */
-bAction *add_empty_action(Main *bmain, const char name[])
+bAction *BKE_action_add(Main *bmain, const char name[])
{
bAction *act;
- act = BKE_libblock_alloc(bmain, ID_AC, name);
+ act = BKE_libblock_alloc(bmain, ID_AC, name, 0);
return act;
}
@@ -120,46 +120,56 @@ void BKE_action_free(bAction *act)
/* .................................. */
-bAction *BKE_action_copy(Main *bmain, bAction *src)
+/**
+ * Only copy internal data of Action ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_action_copy_data(Main *UNUSED(bmain), bAction *act_dst, const bAction *act_src, const int UNUSED(flag))
{
- bAction *dst = NULL;
- bActionGroup *dgrp, *sgrp;
- FCurve *dfcu, *sfcu;
-
- if (src == NULL)
- return NULL;
- dst = BKE_libblock_copy(bmain, &src->id);
-
+ bActionGroup *grp_dst, *grp_src;
+ FCurve *fcu_dst, *fcu_src;
+
/* duplicate the lists of groups and markers */
- BLI_duplicatelist(&dst->groups, &src->groups);
- BLI_duplicatelist(&dst->markers, &src->markers);
-
+ BLI_duplicatelist(&act_dst->groups, &act_src->groups);
+ BLI_duplicatelist(&act_dst->markers, &act_src->markers);
+
/* copy F-Curves, fixing up the links as we go */
- BLI_listbase_clear(&dst->curves);
-
- for (sfcu = src->curves.first; sfcu; sfcu = sfcu->next) {
+ BLI_listbase_clear(&act_dst->curves);
+
+ for (fcu_src = act_src->curves.first; fcu_src; fcu_src = fcu_src->next) {
/* duplicate F-Curve */
- dfcu = copy_fcurve(sfcu);
- BLI_addtail(&dst->curves, dfcu);
-
+ fcu_dst = copy_fcurve(fcu_src); /* XXX TODO pass subdata flag? But surprisingly does not seem to be doing any ID refcounting... */
+ BLI_addtail(&act_dst->curves, fcu_dst);
+
/* fix group links (kindof bad list-in-list search, but this is the most reliable way) */
- for (dgrp = dst->groups.first, sgrp = src->groups.first; dgrp && sgrp; dgrp = dgrp->next, sgrp = sgrp->next) {
- if (sfcu->grp == sgrp) {
- dfcu->grp = dgrp;
-
- if (dgrp->channels.first == sfcu)
- dgrp->channels.first = dfcu;
- if (dgrp->channels.last == sfcu)
- dgrp->channels.last = dfcu;
-
+ for (grp_dst = act_dst->groups.first, grp_src = act_src->groups.first;
+ grp_dst && grp_src;
+ grp_dst = grp_dst->next, grp_src = grp_src->next)
+ {
+ if (fcu_src->grp == grp_src) {
+ fcu_dst->grp = grp_dst;
+
+ if (grp_dst->channels.first == fcu_src) {
+ grp_dst->channels.first = fcu_dst;
+ }
+ if (grp_dst->channels.last == fcu_src) {
+ grp_dst->channels.last = fcu_dst;
+ }
break;
}
}
}
-
- BKE_id_copy_ensure_local(bmain, &src->id, &dst->id);
+}
- return dst;
+bAction *BKE_action_copy(Main *bmain, const bAction *act_src)
+{
+ bAction *act_copy;
+ BKE_id_copy_ex(bmain, &act_src->id, (ID **)&act_copy, 0, false);
+ return act_copy;
}
/* *************** Action Groups *************** */
@@ -489,7 +499,7 @@ bPoseChannel *BKE_pose_channel_active(Object *ob)
}
/**
- * \see #ED_armature_bone_get_mirrored (edit-mode, matching function)
+ * \see #ED_armature_ebone_get_mirrored (edit-mode, matching function)
*/
bPoseChannel *BKE_pose_channel_get_mirrored(const bPose *pose, const char *name)
{
@@ -523,7 +533,7 @@ const char *BKE_pose_ikparam_get_name(bPose *pose)
*
* \param dst Should be freed already, makes entire duplicate.
*/
-void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints)
+void BKE_pose_copy_data_ex(bPose **dst, const bPose *src, const int flag, const bool copy_constraints)
{
bPose *outPose;
bPoseChannel *pchan;
@@ -553,9 +563,8 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints)
outPose->avs = src->avs;
for (pchan = outPose->chanbase.first; pchan; pchan = pchan->next) {
-
- if (pchan->custom) {
- id_us_plus(&pchan->custom->id);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)pchan->custom);
}
/* warning, O(n2) here, if done without the hash, but these are rarely used features. */
@@ -570,13 +579,13 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints)
}
if (copy_constraints) {
- BKE_constraints_copy(&listb, &pchan->constraints, true); // BKE_constraints_copy NULLs listb
+ BKE_constraints_copy_ex(&listb, &pchan->constraints, flag, true); // BKE_constraints_copy NULLs listb
pchan->constraints = listb;
pchan->mpath = NULL; /* motion paths should not get copied yet... */
}
if (pchan->prop) {
- pchan->prop = IDP_CopyProperty(pchan->prop);
+ pchan->prop = IDP_CopyProperty_ex(pchan->prop, flag);
}
}
@@ -588,6 +597,11 @@ void BKE_pose_copy_data(bPose **dst, bPose *src, const bool copy_constraints)
*dst = outPose;
}
+void BKE_pose_copy_data(bPose **dst, const bPose *src, const bool copy_constraints)
+{
+ BKE_pose_copy_data_ex(dst, src, 0, copy_constraints);
+}
+
void BKE_pose_itasc_init(bItasc *itasc)
{
if (itasc) {
@@ -856,6 +870,8 @@ static void copy_pose_channel_data(bPoseChannel *pchan, const bPoseChannel *chan
pchan->curveInY = chan->curveInY;
pchan->curveOutX = chan->curveOutX;
pchan->curveOutY = chan->curveOutY;
+ pchan->ease1 = chan->ease1;
+ pchan->ease2 = chan->ease2;
pchan->scaleIn = chan->scaleIn;
pchan->scaleOut = chan->scaleOut;
@@ -1115,9 +1131,13 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_
if (fcu->totvert) {
float nmin, nmax;
- /* get extents for this curve */
- /* TODO: allow enabling/disabling this? */
- calc_fcurve_range(fcu, &nmin, &nmax, false, true);
+ /* get extents for this curve
+ * - no "selected only", since this is often used in the backend
+ * - no "minimum length" (we will apply this later), otherwise
+ * single-keyframe curves will increase the overall length by
+ * a phantom frame (T50354)
+ */
+ calc_fcurve_range(fcu, &nmin, &nmax, false, false);
/* compare to the running tally */
min = min_ff(min, nmin);
@@ -1170,7 +1190,9 @@ void calc_action_range(const bAction *act, float *start, float *end, short incl_
}
if (foundvert || foundmod) {
+ /* ensure that action is at least 1 frame long (for NLA strips to have a valid length) */
if (min == max) max += 1.0f;
+
*start = min;
*end = max;
}
@@ -1341,6 +1363,7 @@ void BKE_pose_rest(bPose *pose)
pchan->roll1 = pchan->roll2 = 0.0f;
pchan->curveInX = pchan->curveInY = 0.0f;
pchan->curveOutX = pchan->curveOutY = 0.0f;
+ pchan->ease1 = pchan->ease2 = 0.0f;
pchan->scaleIn = pchan->scaleOut = 1.0f;
pchan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE | POSE_BBONE_SHAPE);
@@ -1384,6 +1407,8 @@ bool BKE_pose_copy_result(bPose *to, bPose *from)
pchanto->curveInY = pchanfrom->curveInY;
pchanto->curveOutX = pchanfrom->curveOutX;
pchanto->curveOutY = pchanfrom->curveOutY;
+ pchanto->ease1 = pchanfrom->ease1;
+ pchanto->ease2 = pchanfrom->ease2;
pchanto->scaleIn = pchanfrom->scaleIn;
pchanto->scaleOut = pchanfrom->scaleOut;
diff --git a/source/blender/blenkernel/intern/addon.c b/source/blender/blenkernel/intern/addon.c
index 0ef12397fe7..689e0fb5ee6 100644
--- a/source/blender/blenkernel/intern/addon.c
+++ b/source/blender/blenkernel/intern/addon.c
@@ -27,13 +27,58 @@
#include <stddef.h>
#include <stdlib.h>
+#include "RNA_types.h"
+
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
+#include "BLI_string.h"
+#include "BLI_listbase.h"
#include "BKE_addon.h" /* own include */
+#include "BKE_idprop.h"
+
+#include "DNA_listBase.h"
+#include "DNA_userdef_types.h"
+
#include "MEM_guardedalloc.h"
+/* -------------------------------------------------------------------- */
+/** \name Add-on New/Free
+ * \{ */
+
+bAddon *BKE_addon_new(void)
+{
+ bAddon *addon = MEM_callocN(sizeof(bAddon), "bAddon");
+ return addon;
+}
+
+bAddon *BKE_addon_ensure(ListBase *addon_list, const char *module)
+{
+ bAddon *addon = BLI_findstring(addon_list, module, offsetof(bAddon, module));
+ if (addon == NULL) {
+ addon = BKE_addon_new();
+ BLI_strncpy(addon->module, module, sizeof(addon->module));
+ BLI_addtail(addon_list, addon);
+ }
+ return addon;
+}
+
+void BKE_addon_free(bAddon *addon)
+{
+ if (addon->prop) {
+ IDP_FreeProperty(addon->prop);
+ MEM_freeN(addon->prop);
+ }
+ MEM_freeN(addon);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Add-on Preference API
+ * \{ */
+
static GHash *global_addonpreftype_hash = NULL;
@@ -81,3 +126,5 @@ void BKE_addon_pref_type_free(void)
BLI_ghash_free(global_addonpreftype_hash, NULL, MEM_freeN);
global_addonpreftype_hash = NULL;
}
+
+/** \} */
diff --git a/source/blender/blenkernel/intern/anim_sys.c b/source/blender/blenkernel/intern/anim_sys.c
index 0b637355ecf..e2c371348e5 100644
--- a/source/blender/blenkernel/intern/anim_sys.c
+++ b/source/blender/blenkernel/intern/anim_sys.c
@@ -74,6 +74,10 @@
#include "nla_private.h"
+#include "atomic_ops.h"
+
+#include "DEG_depsgraph.h"
+
/* ***************************************** */
/* AnimData API */
@@ -241,7 +245,7 @@ void BKE_animdata_free(ID *id, const bool do_id_user)
}
/* free nla data */
- free_nladata(&adt->nla_tracks);
+ BKE_nla_tracks_free(&adt->nla_tracks);
/* free drivers - stored as a list of F-Curves */
free_fcurves(&adt->drivers);
@@ -259,7 +263,7 @@ void BKE_animdata_free(ID *id, const bool do_id_user)
/* Copying -------------------------------------------- */
/* Make a copy of the given AnimData - to be used when copying datablocks */
-AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action)
+AnimData *BKE_animdata_copy(Main *bmain, AnimData *adt, const bool do_action)
{
AnimData *dadt;
@@ -270,8 +274,9 @@ AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action)
/* make a copy of action - at worst, user has to delete copies... */
if (do_action) {
- dadt->action = BKE_action_copy(G.main, adt->action);
- dadt->tmpact = BKE_action_copy(G.main, adt->tmpact);
+ BLI_assert(bmain != NULL);
+ BKE_id_copy_ex(bmain, (ID *)dadt->action, (ID **)&dadt->action, 0, false);
+ BKE_id_copy_ex(bmain, (ID *)dadt->tmpact, (ID **)&dadt->tmpact, 0, false);
}
else {
id_us_plus((ID *)dadt->action);
@@ -279,7 +284,7 @@ AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action)
}
/* duplicate NLA data */
- copy_nladata(&dadt->nla_tracks, &adt->nla_tracks);
+ BKE_nla_tracks_copy(&dadt->nla_tracks, &adt->nla_tracks);
/* duplicate drivers (F-Curves) */
copy_fcurves(&dadt->drivers, &adt->drivers);
@@ -291,7 +296,7 @@ AnimData *BKE_animdata_copy(AnimData *adt, const bool do_action)
return dadt;
}
-bool BKE_animdata_copy_id(ID *id_to, ID *id_from, const bool do_action)
+bool BKE_animdata_copy_id(Main *bmain, ID *id_to, ID *id_from, const bool do_action)
{
AnimData *adt;
@@ -303,7 +308,7 @@ bool BKE_animdata_copy_id(ID *id_to, ID *id_from, const bool do_action)
adt = BKE_animdata_from_id(id_from);
if (adt) {
IdAdtTemplate *iat = (IdAdtTemplate *)id_to;
- iat->adt = BKE_animdata_copy(adt, do_action);
+ iat->adt = BKE_animdata_copy(bmain, adt, do_action);
}
return true;
@@ -361,7 +366,7 @@ void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes a
if (src->nla_tracks.first) {
ListBase tracks = {NULL, NULL};
- copy_nladata(&tracks, &src->nla_tracks);
+ BKE_nla_tracks_copy(&tracks, &src->nla_tracks);
BLI_movelisttolist(&dst->nla_tracks, &tracks);
}
@@ -397,73 +402,6 @@ void BKE_animdata_merge_copy(ID *dst_id, ID *src_id, eAnimData_MergeCopy_Modes a
}
}
-/* Make Local -------------------------------------------- */
-
-static void make_local_strips(ListBase *strips)
-{
- NlaStrip *strip;
-
- for (strip = strips->first; strip; strip = strip->next) {
- if (strip->act) BKE_action_make_local(G.main, strip->act, false);
- if (strip->remap && strip->remap->target) BKE_action_make_local(G.main, strip->remap->target, false);
-
- make_local_strips(&strip->strips);
- }
-}
-
-/* Use local copy instead of linked copy of various ID-blocks */
-void BKE_animdata_make_local(AnimData *adt)
-{
- NlaTrack *nlt;
-
- /* Actions - Active and Temp */
- if (adt->action) BKE_action_make_local(G.main, adt->action, false);
- if (adt->tmpact) BKE_action_make_local(G.main, adt->tmpact, false);
- /* Remaps */
- if (adt->remap && adt->remap->target) BKE_action_make_local(G.main, adt->remap->target, false);
-
- /* Drivers */
- /* TODO: need to remap the ID-targets too? */
-
- /* NLA Data */
- for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next)
- make_local_strips(&nlt->strips);
-}
-
-
-/* When duplicating data (i.e. objects), drivers referring to the original data will
- * get updated to point to the duplicated data (if drivers belong to the new data)
- */
-void BKE_animdata_relink(AnimData *adt)
-{
- /* sanity check */
- if (adt == NULL)
- return;
-
- /* drivers */
- if (adt->drivers.first) {
- FCurve *fcu;
-
- /* check each driver against all the base paths to see if any should go */
- for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
- ChannelDriver *driver = fcu->driver;
- DriverVar *dvar;
-
- /* driver variables */
- for (dvar = driver->variables.first; dvar; dvar = dvar->next) {
- /* only change the used targets, since the others will need fixing manually anyway */
- DRIVER_TARGETS_USED_LOOPER(dvar)
- {
- if (dtar->id && dtar->id->newid) {
- dtar->id = dtar->id->newid;
- }
- }
- DRIVER_TARGETS_LOOPER_END
- }
- }
- }
-}
-
/* Sub-ID Regrouping ------------------------------------------- */
/**
@@ -591,7 +529,7 @@ void BKE_animdata_separate_by_basepath(ID *srcID, ID *dstID, ListBase *basepaths
if (srcAdt->action) {
/* set up an action if necessary, and name it in a similar way so that it can be easily found again */
if (dstAdt->action == NULL) {
- dstAdt->action = add_empty_action(G.main, srcAdt->action->id.name + 2);
+ dstAdt->action = BKE_action_add(G.main, srcAdt->action->id.name + 2);
}
else if (dstAdt->action == srcAdt->action) {
printf("Argh! Source and Destination share animation! ('%s' and '%s' both use '%s') Making new empty action\n",
@@ -599,7 +537,7 @@ void BKE_animdata_separate_by_basepath(ID *srcID, ID *dstID, ListBase *basepaths
/* TODO: review this... */
id_us_min(&dstAdt->action->id);
- dstAdt->action = add_empty_action(G.main, dstAdt->action->id.name + 2);
+ dstAdt->action = BKE_action_add(G.main, dstAdt->action->id.name + 2);
}
/* loop over base paths, trying to fix for each one... */
@@ -690,6 +628,8 @@ char *BKE_animdata_driver_path_hack(bContext *C, PointerRNA *ptr, PropertyRNA *p
}
break;
}
+ default:
+ break;
}
/* fix RNA pointer, as we've now changed the ID root by changing the paths */
@@ -862,8 +802,7 @@ static void nlastrips_path_rename_fix(ID *owner_id, const char *prefix, const ch
}
}
-/* ----------------------- */
-
+/* Rename Sub-ID Entities in RNA Paths ----------------------- */
/* Fix up the given RNA-Path
*
@@ -881,7 +820,7 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char *
/* if no action, no need to proceed */
if (ELEM(NULL, owner_id, old_path)) {
- printf("early abort\n");
+ if (G.debug & G_DEBUG) printf("%s: early abort\n", __func__);
return old_path;
}
@@ -904,9 +843,9 @@ char *BKE_animsys_fix_rna_path_rename(ID *owner_id, char *old_path, const char *
}
/* fix given path */
- printf("%s | %s | oldpath = %p ", oldN, newN, old_path);
+ if (G.debug & G_DEBUG) printf("%s | %s | oldpath = %p ", oldN, newN, old_path);
result = rna_path_rename_fix(owner_id, prefix, oldN, newN, old_path, verify_paths);
- printf("result = %p\n", result);
+ if (G.debug & G_DEBUG) printf("path rename result = %p\n", result);
/* free the temp names */
MEM_freeN(oldN);
@@ -1009,8 +948,7 @@ void BKE_animdata_fix_paths_rename(ID *owner_id, AnimData *adt, ID *ref_id, cons
MEM_freeN(newN);
}
-/* *************************** */
-/* remove of individual paths */
+/* Remove FCurves with Prefix -------------------------------------- */
/* Check RNA-Paths for a list of F-Curves */
static void fcurves_path_remove_fix(const char *prefix, ListBase *curves)
@@ -1038,7 +976,6 @@ static void nlastrips_path_remove_fix(const char *prefix, ListBase *strips)
/* recursively check strips, fixing only actions... */
for (strip = strips->first; strip; strip = strip->next) {
-
/* fix strip's action */
if (strip->act)
fcurves_path_remove_fix(prefix, &strip->act->curves);
@@ -1061,7 +998,6 @@ void BKE_animdata_fix_paths_remove(ID *id, const char *prefix)
/* check if there's any AnimData to start with */
if (adt) {
-
/* free fcurves */
if (adt->action)
fcurves_path_remove_fix(prefix, &adt->action->curves);
@@ -1079,6 +1015,75 @@ void BKE_animdata_fix_paths_remove(ID *id, const char *prefix)
}
}
+
+/* Apply Op to All FCurves in Database --------------------------- */
+
+/* "User-Data" wrapper used by BKE_fcurves_main_cb() */
+typedef struct AllFCurvesCbWrapper {
+ ID_FCurve_Edit_Callback func; /* Operation to apply on F-Curve */
+ void *user_data; /* Custom data for that operation */
+} AllFCurvesCbWrapper;
+
+/* Helper for adt_apply_all_fcurves_cb() - Apply wrapped operator to list of F-Curves */
+static void fcurves_apply_cb(ID *id, ListBase *fcurves, ID_FCurve_Edit_Callback func, void *user_data)
+{
+ FCurve *fcu;
+
+ for (fcu = fcurves->first; fcu; fcu = fcu->next) {
+ func(id, fcu, user_data);
+ }
+}
+
+/* Helper for adt_apply_all_fcurves_cb() - Recursively go through each NLA strip */
+static void nlastrips_apply_all_curves_cb(ID *id, ListBase *strips, AllFCurvesCbWrapper *wrapper)
+{
+ NlaStrip *strip;
+
+ for (strip = strips->first; strip; strip = strip->next) {
+ /* fix strip's action */
+ if (strip->act) {
+ fcurves_apply_cb(id, &strip->act->curves, wrapper->func, wrapper->user_data);
+ }
+
+ /* check sub-strips (if metas) */
+ nlastrips_apply_all_curves_cb(id, &strip->strips, wrapper);
+ }
+}
+
+/* Helper for BKE_fcurves_main_cb() - Dispatch wrapped operator to all F-Curves */
+static void adt_apply_all_fcurves_cb(ID *id, AnimData *adt, void *wrapper_data)
+{
+ AllFCurvesCbWrapper *wrapper = wrapper_data;
+ NlaTrack *nlt;
+
+ if (adt->action) {
+ fcurves_apply_cb(id, &adt->action->curves, wrapper->func, wrapper->user_data);
+ }
+
+ if (adt->tmpact) {
+ fcurves_apply_cb(id, &adt->tmpact->curves, wrapper->func, wrapper->user_data);
+ }
+
+ /* free drivers - stored as a list of F-Curves */
+ fcurves_apply_cb(id, &adt->drivers, wrapper->func, wrapper->user_data);
+
+ /* NLA Data - Animation Data for Strips */
+ for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
+ nlastrips_apply_all_curves_cb(id, &nlt->strips, wrapper);
+ }
+}
+
+/* apply the given callback function on all F-Curves attached to data in main database */
+void BKE_fcurves_main_cb(Main *mainptr, ID_FCurve_Edit_Callback func, void *user_data)
+{
+ /* Wrap F-Curve operation stuff to pass to the general AnimData-level func */
+ AllFCurvesCbWrapper wrapper = {func, user_data};
+
+ /* Use the AnimData-based function so that we don't have to reimplement all that stuff */
+ BKE_animdata_main_cb(mainptr, adt_apply_all_fcurves_cb, &wrapper);
+}
+
+
/* Whole Database Ops -------------------------------------------- */
/* apply the given callback function on all data in main database */
@@ -1414,7 +1419,7 @@ void BKE_keyingset_free_path(KeyingSet *ks, KS_Path *ksp)
}
/* Copy all KeyingSets in the given list */
-void BKE_keyingsets_copy(ListBase *newlist, ListBase *list)
+void BKE_keyingsets_copy(ListBase *newlist, const ListBase *list)
{
KeyingSet *ksn;
KS_Path *kspn;
@@ -1586,7 +1591,8 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val
}
case PROP_INT:
{
- const int value_coerce = (int)value;
+ int value_coerce = (int)value;
+ RNA_property_int_clamp(ptr, prop, &value_coerce);
if (array_index != -1) {
if (RNA_property_int_get_index(ptr, prop, array_index) != value_coerce) {
RNA_property_int_set_index(ptr, prop, array_index, value_coerce);
@@ -1603,15 +1609,17 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val
}
case PROP_FLOAT:
{
+ float value_coerce = value;
+ RNA_property_float_clamp(ptr, prop, &value_coerce);
if (array_index != -1) {
- if (RNA_property_float_get_index(ptr, prop, array_index) != value) {
- RNA_property_float_set_index(ptr, prop, array_index, value);
+ if (RNA_property_float_get_index(ptr, prop, array_index) != value_coerce) {
+ RNA_property_float_set_index(ptr, prop, array_index, value_coerce);
written = true;
}
}
else {
- if (RNA_property_float_get(ptr, prop) != value) {
- RNA_property_float_set(ptr, prop, value);
+ if (RNA_property_float_get(ptr, prop) != value_coerce) {
+ RNA_property_float_set(ptr, prop, value_coerce);
written = true;
}
}
@@ -1659,8 +1667,11 @@ static bool animsys_write_rna_setting(PathResolvedRNA *anim_rna, const float val
/* for cases like duplifarmes it's only a temporary so don't
* notify anyone of updates */
- if (!(id->tag & LIB_TAG_ANIM_NO_RECALC)) {
- BKE_id_tag_set_atomic(id, LIB_TAG_ID_RECALC);
+ if (!(id->recalc & ID_RECALC_SKIP_ANIM_TAG)) {
+ /* NOTE: This is a bit annoying to use atomic API here, but this
+ * code is at it's EOL and removed already in 2.8 branch.
+ */
+ atomic_fetch_and_or_int32(&id->recalc, ID_RECALC);
DAG_id_type_tag(G.main, GS(id->name));
}
}
@@ -2614,8 +2625,8 @@ static void animsys_evaluate_nla(ListBase *echannels, PointerRNA *ptr, AnimData
*/
if (ptr->id.data != NULL) {
ID *id = ptr->id.data;
- if (!(id->tag & LIB_TAG_ANIM_NO_RECALC)) {
- id->tag |= LIB_TAG_ID_RECALC;
+ if (!(id->recalc & ID_RECALC_SKIP_ANIM_TAG)) {
+ id->recalc |= ID_RECALC;
DAG_id_type_tag(G.main, GS(id->name));
}
}
@@ -2909,15 +2920,13 @@ void BKE_animsys_evaluate_all_animation(Main *main, Scene *scene, float ctime)
/* ************** */
/* Evaluation API */
-#define DEBUG_PRINT if (G.debug & G_DEBUG_DEPSGRAPH) printf
-
void BKE_animsys_eval_animdata(EvaluationContext *eval_ctx, ID *id)
{
AnimData *adt = BKE_animdata_from_id(id);
Scene *scene = NULL; /* XXX: this is only needed for flushing RNA updates,
- * which should get handled as part of the graph instead...
+ * which should get handled as part of the dependency graph instead...
*/
- DEBUG_PRINT("%s on %s, time=%f\n\n", __func__, id->name, (double)eval_ctx->ctime);
+ DEG_debug_print_eval_time(__func__, id->name, id, eval_ctx->ctime);
BKE_animsys_evaluate_animdata(scene, id, adt, eval_ctx->ctime, ADT_RECALC_ANIM);
}
@@ -2930,11 +2939,8 @@ void BKE_animsys_eval_driver(EvaluationContext *eval_ctx,
PointerRNA id_ptr;
bool ok = false;
- DEBUG_PRINT("%s on %s (%s[%d])\n",
- __func__,
- id->name,
- fcu->rna_path,
- fcu->array_index);
+ DEG_debug_print_eval_subdata_index(
+ __func__, id->name, id, "fcu", fcu->rna_path, fcu, fcu->array_index);
RNA_id_pointer_create(id, &id_ptr);
@@ -2967,5 +2973,3 @@ void BKE_animsys_eval_driver(EvaluationContext *eval_ctx,
}
}
}
-
-#undef DEBUG_PRINT
diff --git a/source/blender/blenkernel/intern/appdir.c b/source/blender/blenkernel/intern/appdir.c
index 9236a1b5853..16f8d16860f 100644
--- a/source/blender/blenkernel/intern/appdir.c
+++ b/source/blender/blenkernel/intern/appdir.c
@@ -106,7 +106,8 @@ const char *BKE_appdir_folder_default(void)
static char *blender_version_decimal(const int ver)
{
static char version_str[5];
- sprintf(version_str, "%d.%02d", ver / 100, ver % 100);
+ BLI_assert(ver < 1000);
+ BLI_snprintf(version_str, sizeof(version_str), "%d.%02d", ver / 100, ver % 100);
return version_str;
}
@@ -114,18 +115,26 @@ static char *blender_version_decimal(const int ver)
* Concatenates path_base, (optional) path_sep and (optional) folder_name into targetpath,
* returning true if result points to a directory.
*/
-static bool test_path(char *targetpath, const char *path_base, const char *path_sep, const char *folder_name)
+static bool test_path(
+ char *targetpath, size_t targetpath_len,
+ const char *path_base, const char *path_sep, const char *folder_name)
{
char tmppath[FILE_MAX];
- if (path_sep) BLI_join_dirfile(tmppath, sizeof(tmppath), path_base, path_sep);
- else BLI_strncpy(tmppath, path_base, sizeof(tmppath));
+ if (path_sep) {
+ BLI_join_dirfile(tmppath, sizeof(tmppath), path_base, path_sep);
+ }
+ else {
+ BLI_strncpy(tmppath, path_base, sizeof(tmppath));
+ }
/* rare cases folder_name is omitted (when looking for ~/.config/blender/2.xx dir only) */
- if (folder_name)
- BLI_make_file_string("/", targetpath, tmppath, folder_name);
- else
- BLI_strncpy(targetpath, tmppath, sizeof(tmppath));
+ if (folder_name) {
+ BLI_join_dirfile(targetpath, targetpath_len, tmppath, folder_name);
+ }
+ else {
+ BLI_strncpy(targetpath, tmppath, targetpath_len);
+ }
/* FIXME: why is "//" on front of tmppath expanded to "/" (by BLI_join_dirfile)
* if folder_name is specified but not otherwise? */
@@ -179,7 +188,9 @@ static bool test_env_path(char *path, const char *envvar)
* \param ver To construct name of version-specific directory within bprogdir
* \return true if such a directory exists.
*/
-static bool get_path_local(char *targetpath, const char *folder_name, const char *subfolder_name, const int ver)
+static bool get_path_local(
+ char *targetpath, size_t targetpath_len,
+ const char *folder_name, const char *subfolder_name, const int ver)
{
char relfolder[FILE_MAX];
@@ -201,11 +212,14 @@ static bool get_path_local(char *targetpath, const char *folder_name, const char
/* try EXECUTABLE_DIR/2.5x/folder_name - new default directory for local blender installed files */
#ifdef __APPLE__
- static char osx_resourses[FILE_MAX]; /* due new codesign situation in OSX > 10.9.5 we must move the blender_version dir with contents to Resources */
- sprintf(osx_resourses, "%s../Resources", bprogdir);
- return test_path(targetpath, osx_resourses, blender_version_decimal(ver), relfolder);
+ /* due new codesign situation in OSX > 10.9.5 we must move the blender_version dir with contents to Resources */
+ char osx_resourses[FILE_MAX];
+ BLI_snprintf(osx_resourses, sizeof(osx_resourses), "%s../Resources", bprogdir);
+ /* Remove the '/../' added above. */
+ BLI_cleanup_path(NULL, osx_resourses);
+ return test_path(targetpath, targetpath_len, osx_resourses, blender_version_decimal(ver), relfolder);
#else
- return test_path(targetpath, bprogdir, blender_version_decimal(ver), relfolder);
+ return test_path(targetpath, targetpath_len, bprogdir, blender_version_decimal(ver), relfolder);
#endif
}
@@ -219,7 +233,7 @@ static bool is_portable_install(void)
const int ver = BLENDER_VERSION;
char path[FILE_MAX];
- return get_path_local(path, "config", NULL, ver);
+ return get_path_local(path, sizeof(path), "config", NULL, ver);
}
/**
@@ -233,20 +247,22 @@ static bool is_portable_install(void)
* \param ver Blender version, used to construct a subdirectory name
* \return true if it was able to construct such a path.
*/
-static bool get_path_user(char *targetpath, const char *folder_name, const char *subfolder_name, const char *envvar, const int ver)
+static bool get_path_user(
+ char *targetpath, size_t targetpath_len, const char *folder_name, const char *subfolder_name,
+ const char *envvar, const int ver)
{
char user_path[FILE_MAX];
const char *user_base_path;
/* for portable install, user path is always local */
- if (is_portable_install())
- return get_path_local(targetpath, folder_name, subfolder_name, ver);
-
+ if (is_portable_install()) {
+ return get_path_local(targetpath, targetpath_len, folder_name, subfolder_name, ver);
+ }
user_path[0] = '\0';
if (test_env_path(user_path, envvar)) {
if (subfolder_name) {
- return test_path(targetpath, user_path, NULL, subfolder_name);
+ return test_path(targetpath, targetpath_len, user_path, NULL, subfolder_name);
}
else {
BLI_strncpy(targetpath, user_path, FILE_MAX);
@@ -266,10 +282,10 @@ static bool get_path_user(char *targetpath, const char *folder_name, const char
#endif
if (subfolder_name) {
- return test_path(targetpath, user_path, folder_name, subfolder_name);
+ return test_path(targetpath, targetpath_len, user_path, folder_name, subfolder_name);
}
else {
- return test_path(targetpath, user_path, NULL, folder_name);
+ return test_path(targetpath, targetpath_len, user_path, NULL, folder_name);
}
}
@@ -283,11 +299,12 @@ static bool get_path_user(char *targetpath, const char *folder_name, const char
* \param ver Blender version, used to construct a subdirectory name
* \return true if it was able to construct such a path.
*/
-static bool get_path_system(char *targetpath, const char *folder_name, const char *subfolder_name, const char *envvar, const int ver)
+static bool get_path_system(
+ char *targetpath, size_t targetpath_len, const char *folder_name, const char *subfolder_name,
+ const char *envvar, const int ver)
{
char system_path[FILE_MAX];
const char *system_base_path;
- char cwd[FILE_MAX];
char relfolder[FILE_MAX];
if (folder_name) {
@@ -302,29 +319,11 @@ static bool get_path_system(char *targetpath, const char *folder_name, const cha
relfolder[0] = '\0';
}
- /* first allow developer only overrides to the system path
- * these are only used when running blender from source */
-
- /* try CWD/release/folder_name */
- if (BLI_current_working_dir(cwd, sizeof(cwd))) {
- if (test_path(targetpath, cwd, "release", relfolder)) {
- return true;
- }
- }
-
- /* try EXECUTABLE_DIR/release/folder_name */
- if (test_path(targetpath, bprogdir, "release", relfolder))
- return true;
-
- /* end developer overrides */
-
-
-
system_path[0] = '\0';
if (test_env_path(system_path, envvar)) {
if (subfolder_name) {
- return test_path(targetpath, system_path, NULL, subfolder_name);
+ return test_path(targetpath, targetpath_len, system_path, NULL, subfolder_name);
}
else {
BLI_strncpy(targetpath, system_path, FILE_MAX);
@@ -345,57 +344,63 @@ static bool get_path_system(char *targetpath, const char *folder_name, const cha
if (subfolder_name) {
/* try $BLENDERPATH/folder_name/subfolder_name */
- return test_path(targetpath, system_path, folder_name, subfolder_name);
+ return test_path(targetpath, targetpath_len, system_path, folder_name, subfolder_name);
}
else {
/* try $BLENDERPATH/folder_name */
- return test_path(targetpath, system_path, NULL, folder_name);
+ return test_path(targetpath, targetpath_len, system_path, NULL, folder_name);
}
}
-/* get a folder out of the 'folder_id' presets for paths */
-/* returns the path if found, NULL string if not */
-const char *BKE_appdir_folder_id(const int folder_id, const char *subfolder)
+/**
+ * Get a folder out of the 'folder_id' presets for paths.
+ * returns the path if found, NULL string if not
+ *
+ * \param subfolder: The name of a directory to check for,
+ * this may contain path separators but must resolve to a directory, checked with #BLI_is_dir.
+ */
+const char *BKE_appdir_folder_id_ex(
+ const int folder_id, const char *subfolder,
+ char *path, size_t path_len)
{
const int ver = BLENDER_VERSION;
- static char path[FILE_MAX] = "";
-
+
switch (folder_id) {
case BLENDER_DATAFILES: /* general case */
- if (get_path_user(path, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
- if (get_path_local(path, "datafiles", subfolder, ver)) break;
- if (get_path_system(path, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break;
+ if (get_path_user(path, path_len, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
+ if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break;
+ if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break;
return NULL;
case BLENDER_USER_DATAFILES:
- if (get_path_user(path, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
+ if (get_path_user(path, path_len, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
return NULL;
case BLENDER_SYSTEM_DATAFILES:
- if (get_path_local(path, "datafiles", subfolder, ver)) break;
- if (get_path_system(path, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break;
+ if (get_path_local(path, path_len, "datafiles", subfolder, ver)) break;
+ if (get_path_system(path, path_len, "datafiles", subfolder, "BLENDER_SYSTEM_DATAFILES", ver)) break;
return NULL;
case BLENDER_USER_AUTOSAVE:
- if (get_path_user(path, "autosave", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
+ if (get_path_user(path, path_len, "autosave", subfolder, "BLENDER_USER_DATAFILES", ver)) break;
return NULL;
case BLENDER_USER_CONFIG:
- if (get_path_user(path, "config", subfolder, "BLENDER_USER_CONFIG", ver)) break;
+ if (get_path_user(path, path_len, "config", subfolder, "BLENDER_USER_CONFIG", ver)) break;
return NULL;
case BLENDER_USER_SCRIPTS:
- if (get_path_user(path, "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver)) break;
+ if (get_path_user(path, path_len, "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver)) break;
return NULL;
case BLENDER_SYSTEM_SCRIPTS:
- if (get_path_local(path, "scripts", subfolder, ver)) break;
- if (get_path_system(path, "scripts", subfolder, "BLENDER_SYSTEM_SCRIPTS", ver)) break;
+ if (get_path_local(path, path_len, "scripts", subfolder, ver)) break;
+ if (get_path_system(path, path_len, "scripts", subfolder, "BLENDER_SYSTEM_SCRIPTS", ver)) break;
return NULL;
case BLENDER_SYSTEM_PYTHON:
- if (get_path_local(path, "python", subfolder, ver)) break;
- if (get_path_system(path, "python", subfolder, "BLENDER_SYSTEM_PYTHON", ver)) break;
+ if (get_path_local(path, path_len, "python", subfolder, ver)) break;
+ if (get_path_system(path, path_len, "python", subfolder, "BLENDER_SYSTEM_PYTHON", ver)) break;
return NULL;
default:
@@ -406,6 +411,13 @@ const char *BKE_appdir_folder_id(const int folder_id, const char *subfolder)
return path;
}
+const char *BKE_appdir_folder_id(
+ const int folder_id, const char *subfolder)
+{
+ static char path[FILE_MAX] = "";
+ return BKE_appdir_folder_id_ex(folder_id, subfolder, path, sizeof(path));
+}
+
/**
* Returns the path to a folder in the user area without checking that it actually exists first.
*/
@@ -416,16 +428,16 @@ const char *BKE_appdir_folder_id_user_notest(const int folder_id, const char *su
switch (folder_id) {
case BLENDER_USER_DATAFILES:
- get_path_user(path, "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver);
+ get_path_user(path, sizeof(path), "datafiles", subfolder, "BLENDER_USER_DATAFILES", ver);
break;
case BLENDER_USER_CONFIG:
- get_path_user(path, "config", subfolder, "BLENDER_USER_CONFIG", ver);
+ get_path_user(path, sizeof(path), "config", subfolder, "BLENDER_USER_CONFIG", ver);
break;
case BLENDER_USER_AUTOSAVE:
- get_path_user(path, "autosave", subfolder, "BLENDER_USER_AUTOSAVE", ver);
+ get_path_user(path, sizeof(path), "autosave", subfolder, "BLENDER_USER_AUTOSAVE", ver);
break;
case BLENDER_USER_SCRIPTS:
- get_path_user(path, "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver);
+ get_path_user(path, sizeof(path), "scripts", subfolder, "BLENDER_USER_SCRIPTS", ver);
break;
default:
BLI_assert(0);
@@ -469,13 +481,13 @@ const char *BKE_appdir_folder_id_version(const int folder_id, const int ver, con
bool ok;
switch (folder_id) {
case BLENDER_RESOURCE_PATH_USER:
- ok = get_path_user(path, NULL, NULL, NULL, ver);
+ ok = get_path_user(path, sizeof(path), NULL, NULL, NULL, ver);
break;
case BLENDER_RESOURCE_PATH_LOCAL:
- ok = get_path_local(path, NULL, NULL, ver);
+ ok = get_path_local(path, sizeof(path), NULL, NULL, ver);
break;
case BLENDER_RESOURCE_PATH_SYSTEM:
- ok = get_path_system(path, NULL, NULL, NULL, ver);
+ ok = get_path_system(path, sizeof(path), NULL, NULL, NULL, ver);
break;
default:
path[0] = '\0'; /* in case do_check is false */
@@ -563,6 +575,9 @@ static void where_am_i(char *fullname, const size_t maxlen, const char *name)
else {
BLI_path_program_search(fullname, maxlen, name);
}
+ /* Remove "/./" and "/../" so string comparisons can be used on the path. */
+ BLI_cleanup_path(NULL, fullname);
+
#if defined(DEBUG)
if (!STREQ(name, fullname)) {
printf("guessing '%s' == '%s'\n", name, fullname);
@@ -655,6 +670,51 @@ bool BKE_appdir_program_python_search(
return is_found;
}
+/** Keep in sync with `bpy.utils.app_template_paths()` */
+static const char *app_template_directory_search[2] = {
+ "startup" SEP_STR "bl_app_templates_user",
+ "startup" SEP_STR "bl_app_templates_system",
+};
+
+static const int app_template_directory_id[2] = {
+ /* Only 'USER' */
+ BLENDER_USER_SCRIPTS,
+ /* Covers 'LOCAL' & 'SYSTEM'. */
+ BLENDER_SYSTEM_SCRIPTS,
+};
+
+/**
+ * Return true if templates exist
+ */
+bool BKE_appdir_app_template_any(void)
+{
+ char temp_dir[FILE_MAX];
+ for (int i = 0; i < 2; i++) {
+ if (BKE_appdir_folder_id_ex(
+ app_template_directory_id[i], app_template_directory_search[i],
+ temp_dir, sizeof(temp_dir)))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool BKE_appdir_app_template_id_search(const char *app_template, char *path, size_t path_len)
+{
+ for (int i = 0; i < 2; i++) {
+ char subdir[FILE_MAX];
+ BLI_join_dirfile(subdir, sizeof(subdir), app_template_directory_search[i], app_template);
+ if (BKE_appdir_folder_id_ex(
+ app_template_directory_id[i], subdir,
+ path, path_len))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
/**
* Gets the temp directory when blender first runs.
* If the default path is not found, use try $TEMP
@@ -713,7 +773,8 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c
BLI_add_slash(fullname);
#ifdef WIN32
if (userdir && userdir != fullname) {
- BLI_strncpy(userdir, fullname, maxlen); /* also set user pref to show %TEMP%. /tmp/ is just plain confusing for Windows users. */
+ /* also set user pref to show %TEMP%. /tmp/ is just plain confusing for Windows users. */
+ BLI_strncpy(userdir, fullname, maxlen);
}
#endif
}
@@ -755,7 +816,6 @@ static void where_is_temp(char *fullname, char *basename, const size_t maxlen, c
void BKE_tempdir_init(char *userdir)
{
where_is_temp(btempdir_session, btempdir_base, FILE_MAX, userdir);
-;
}
/**
diff --git a/source/blender/blenkernel/intern/armature.c b/source/blender/blenkernel/intern/armature.c
index 02cc31e5977..70a3772f388 100644
--- a/source/blender/blenkernel/intern/armature.c
+++ b/source/blender/blenkernel/intern/armature.c
@@ -64,7 +64,6 @@
#include "BKE_DerivedMesh.h"
#include "BKE_deform.h"
#include "BKE_displist.h"
-#include "BKE_global.h"
#include "BKE_idprop.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
@@ -83,7 +82,7 @@ bArmature *BKE_armature_add(Main *bmain, const char *name)
{
bArmature *arm;
- arm = BKE_libblock_alloc(bmain, ID_AR, name);
+ arm = BKE_libblock_alloc(bmain, ID_AR, name, 0);
arm->deformflag = ARM_DEF_VGROUP | ARM_DEF_ENVELOPE;
arm->flag = ARM_COL_CUSTOM; /* custom bone-group colors */
arm->layer = 1;
@@ -150,54 +149,70 @@ void BKE_armature_make_local(Main *bmain, bArmature *arm, const bool lib_local)
BKE_id_make_local_generic(bmain, &arm->id, true, lib_local);
}
-static void copy_bonechildren(Bone *newBone, Bone *oldBone, Bone *actBone, Bone **newActBone)
+static void copy_bonechildren(
+ Bone *bone_dst, const Bone *bone_src, const Bone *bone_src_act, Bone **r_bone_dst_act, const int flag)
{
- Bone *curBone, *newChildBone;
+ Bone *bone_src_child, *bone_dst_child;
- if (oldBone == actBone)
- *newActBone = newBone;
+ if (bone_src == bone_src_act) {
+ *r_bone_dst_act = bone_dst;
+ }
- if (oldBone->prop)
- newBone->prop = IDP_CopyProperty(oldBone->prop);
+ if (bone_src->prop) {
+ bone_dst->prop = IDP_CopyProperty_ex(bone_src->prop, flag);
+ }
/* Copy this bone's list */
- BLI_duplicatelist(&newBone->childbase, &oldBone->childbase);
+ BLI_duplicatelist(&bone_dst->childbase, &bone_src->childbase);
/* For each child in the list, update it's children */
- newChildBone = newBone->childbase.first;
- for (curBone = oldBone->childbase.first; curBone; curBone = curBone->next) {
- newChildBone->parent = newBone;
- copy_bonechildren(newChildBone, curBone, actBone, newActBone);
- newChildBone = newChildBone->next;
+ for (bone_src_child = bone_src->childbase.first, bone_dst_child = bone_dst->childbase.first;
+ bone_src_child;
+ bone_src_child = bone_src_child->next, bone_dst_child = bone_dst_child->next)
+ {
+ bone_dst_child->parent = bone_dst;
+ copy_bonechildren(bone_dst_child, bone_src_child, bone_src_act, r_bone_dst_act, flag);
}
}
-bArmature *BKE_armature_copy(Main *bmain, bArmature *arm)
+/**
+ * Only copy internal data of Armature ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_armature_copy_data(Main *UNUSED(bmain), bArmature *arm_dst, const bArmature *arm_src, const int flag)
{
- bArmature *newArm;
- Bone *oldBone, *newBone;
- Bone *newActBone = NULL;
+ Bone *bone_src, *bone_dst;
+ Bone *bone_dst_act = NULL;
- newArm = BKE_libblock_copy(bmain, &arm->id);
- BLI_duplicatelist(&newArm->bonebase, &arm->bonebase);
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
+
+ BLI_duplicatelist(&arm_dst->bonebase, &arm_src->bonebase);
/* Duplicate the childrens' lists */
- newBone = newArm->bonebase.first;
- for (oldBone = arm->bonebase.first; oldBone; oldBone = oldBone->next) {
- newBone->parent = NULL;
- copy_bonechildren(newBone, oldBone, arm->act_bone, &newActBone);
- newBone = newBone->next;
+ bone_dst = arm_dst->bonebase.first;
+ for (bone_src = arm_src->bonebase.first; bone_src; bone_src = bone_src->next) {
+ bone_dst->parent = NULL;
+ copy_bonechildren(bone_dst, bone_src, arm_src->act_bone, &bone_dst_act, flag_subdata);
+ bone_dst = bone_dst->next;
}
- newArm->act_bone = newActBone;
-
- newArm->edbo = NULL;
- newArm->act_edbone = NULL;
- newArm->sketch = NULL;
+ arm_dst->act_bone = bone_dst_act;
- BKE_id_copy_ensure_local(bmain, &arm->id, &newArm->id);
+ arm_dst->edbo = NULL;
+ arm_dst->act_edbone = NULL;
+ arm_dst->sketch = NULL;
+}
- return newArm;
+bArmature *BKE_armature_copy(Main *bmain, const bArmature *arm)
+{
+ bArmature *arm_copy;
+ BKE_id_copy_ex(bmain, &arm->id, (ID **)&arm_copy, 0, false);
+ return arm_copy;
}
static Bone *get_named_bone_bonechildren(ListBase *lb, const char *name)
@@ -598,8 +613,10 @@ void b_bone_spline_setup(bPoseChannel *pchan, int rest, Mat4 result_array[MAX_BB
{
const float circle_factor = length * (cubic_tangent_factor_circle_v3(h1, h2) / 0.75f);
- const float hlength1 = bone->ease1 * circle_factor;
- const float hlength2 = bone->ease2 * circle_factor;
+ const float combined_ease1 = bone->ease1 + (!rest ? pchan->ease1 : 0.0f);
+ const float combined_ease2 = bone->ease2 + (!rest ? pchan->ease2 : 0.0f);
+ const float hlength1 = combined_ease1 * circle_factor;
+ const float hlength2 = combined_ease2 * circle_factor;
/* and only now negate h2 */
mul_v3_fl(h1, hlength1);
@@ -982,6 +999,11 @@ void armature_deform_verts(Object *armOb, Object *target, DerivedMesh *dm, float
return;
}
+ if ((armOb->pose->flag & POSE_RECALC) != 0) {
+ printf("ERROR! Trying to evaluate influence of armature '%s' which needs Pose recalc!", armOb->id.name);
+ BLI_assert(0);
+ }
+
invert_m4_m4(obinv, target->obmat);
copy_m4_m4(premat, target->obmat);
mul_m4_m4m4(postmat, obinv, armOb->obmat);
@@ -1980,6 +2002,8 @@ void BKE_pose_rebuild_ex(Object *ob, bArmature *arm, const bool sort_bones)
if (counter > 1 && sort_bones) {
DAG_pose_sort(ob);
}
+#else
+ UNUSED_VARS(sort_bones);
#endif
ob->pose->flag &= ~POSE_RECALC;
diff --git a/source/blender/blenkernel/intern/armature_update.c b/source/blender/blenkernel/intern/armature_update.c
index 3bc81a69c86..ee63e618b18 100644
--- a/source/blender/blenkernel/intern/armature_update.c
+++ b/source/blender/blenkernel/intern/armature_update.c
@@ -48,17 +48,10 @@
#include "BIK_api.h"
-#include "BKE_global.h"
#include "BKE_main.h"
#include "DEG_depsgraph.h"
-#ifdef WITH_LEGACY_DEPSGRAPH
-# define DEBUG_PRINT if (!DEG_depsgraph_use_legacy() && G.debug & G_DEBUG_DEPSGRAPH) printf
-#else
-# define DEBUG_PRINT if (G.debug & G_DEBUG_DEPSGRAPH) printf
-#endif
-
/* ********************** SPLINE IK SOLVER ******************* */
/* Temporary evaluation tree data used for Spline IK */
@@ -558,15 +551,23 @@ void BKE_splineik_execute_tree(Scene *scene, Object *ob, bPoseChannel *pchan_roo
/* *************** Depsgraph evaluation callbacks ************ */
+BLI_INLINE bPoseChannel *pose_pchan_get_indexed(Object *ob, int pchan_index)
+{
+ bPose *pose = ob->pose;
+ BLI_assert(pose != NULL);
+ BLI_assert(pchan_index >= 0);
+ BLI_assert(pchan_index < MEM_allocN_len(pose->chan_array) / sizeof(bPoseChannel *));
+ return pose->chan_array[pchan_index];
+}
+
void BKE_pose_eval_init(EvaluationContext *UNUSED(eval_ctx),
- Scene *scene,
- Object *ob,
- bPose *pose)
+ Scene *UNUSED(scene),
+ Object *ob)
{
- float ctime = BKE_scene_frame_get(scene); /* not accurate... */
- bPoseChannel *pchan;
+ bPose *pose = ob->pose;
+ BLI_assert(pose != NULL);
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
BLI_assert(ob->type == OB_ARMATURE);
@@ -577,17 +578,34 @@ void BKE_pose_eval_init(EvaluationContext *UNUSED(eval_ctx),
/* imat is needed for solvers. */
invert_m4_m4(ob->imat, ob->obmat);
- /* 1. clear flags */
- for (pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
+ const int num_channels = BLI_listbase_count(&pose->chanbase);
+ pose->chan_array = MEM_malloc_arrayN(
+ num_channels, sizeof(bPoseChannel *), "pose->chan_array");
+
+ /* clear flags */
+ int pchan_index = 0;
+ for (bPoseChannel *pchan = pose->chanbase.first; pchan != NULL; pchan = pchan->next) {
pchan->flag &= ~(POSE_DONE | POSE_CHAIN | POSE_IKTREE | POSE_IKSPLINE);
+ pose->chan_array[pchan_index++] = pchan;
}
+}
- /* 2a. construct the IK tree (standard IK) */
+void BKE_pose_eval_init_ik(EvaluationContext *UNUSED(eval_ctx),
+ Scene *scene,
+ Object *ob)
+{
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
+ BLI_assert(ob->type == OB_ARMATURE);
+ const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
+ bArmature *arm = (bArmature *)ob->data;
+ if (arm->flag & ARM_RESTPOS) {
+ return;
+ }
+ /* construct the IK tree (standard IK) */
BIK_initialize_tree(scene, ob, ctime);
-
- /* 2b. construct the Spline IK trees
+ /* construct the Spline IK trees
* - this is not integrated as an IK plugin, since it should be able
- * to function in conjunction with standard IK
+ * to function in conjunction with standard IK
*/
BKE_pose_splineik_init_tree(scene, ob, ctime);
}
@@ -595,11 +613,13 @@ void BKE_pose_eval_init(EvaluationContext *UNUSED(eval_ctx),
void BKE_pose_eval_bone(EvaluationContext *UNUSED(eval_ctx),
Scene *scene,
Object *ob,
- bPoseChannel *pchan)
+ int pchan_index)
{
- bArmature *arm = (bArmature *)ob->data;
- DEBUG_PRINT("%s on %s pchan %s\n", __func__, ob->id.name, pchan->name);
+ bPoseChannel *pchan = pose_pchan_get_indexed(ob, pchan_index);
+ DEG_debug_print_eval_subdata(
+ __func__, ob->id.name, ob, "pchan", pchan->name, pchan);
BLI_assert(ob->type == OB_ARMATURE);
+ bArmature *arm = (bArmature *)ob->data;
if (arm->edbo || (arm->flag & ARM_RESTPOS)) {
Bone *bone = pchan->bone;
if (bone) {
@@ -628,11 +648,13 @@ void BKE_pose_eval_bone(EvaluationContext *UNUSED(eval_ctx),
}
void BKE_pose_constraints_evaluate(EvaluationContext *UNUSED(eval_ctx),
+ Scene *scene,
Object *ob,
- bPoseChannel *pchan)
+ int pchan_index)
{
- Scene *scene = G.main->scene.first;
- DEBUG_PRINT("%s on %s pchan %s\n", __func__, ob->id.name, pchan->name);
+ bPoseChannel *pchan = pose_pchan_get_indexed(ob, pchan_index);
+ DEG_debug_print_eval_subdata(
+ __func__, ob->id.name, ob, "pchan", pchan->name, pchan);
bArmature *arm = (bArmature *)ob->data;
if (arm->flag & ARM_RESTPOS) {
return;
@@ -649,10 +671,12 @@ void BKE_pose_constraints_evaluate(EvaluationContext *UNUSED(eval_ctx),
}
void BKE_pose_bone_done(EvaluationContext *UNUSED(eval_ctx),
- bPoseChannel *pchan)
+ struct Object *ob,
+ int pchan_index)
{
+ bPoseChannel *pchan = pose_pchan_get_indexed(ob, pchan_index);
float imat[4][4];
- DEBUG_PRINT("%s on pchan %s\n", __func__, pchan->name);
+ DEG_debug_print_eval(__func__, pchan->name, pchan);
if (pchan->bone) {
invert_m4_m4(imat, pchan->bone->arm_mat);
mul_m4_m4m4(pchan->chan_mat, pchan->pose_mat, imat);
@@ -662,44 +686,69 @@ void BKE_pose_bone_done(EvaluationContext *UNUSED(eval_ctx),
void BKE_pose_iktree_evaluate(EvaluationContext *UNUSED(eval_ctx),
Scene *scene,
Object *ob,
- bPoseChannel *rootchan)
+ int rootchan_index)
{
- float ctime = BKE_scene_frame_get(scene); /* not accurate... */
- DEBUG_PRINT("%s on %s pchan %s\n", __func__, ob->id.name, rootchan->name);
+ bPoseChannel *rootchan = pose_pchan_get_indexed(ob, rootchan_index);
+ DEG_debug_print_eval_subdata(
+ __func__, ob->id.name, ob, "rootchan", rootchan->name, rootchan);
+ BLI_assert(ob->type == OB_ARMATURE);
+ const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
+ bArmature *arm = (bArmature *)ob->data;
+ if (arm->flag & ARM_RESTPOS) {
+ return;
+ }
BIK_execute_tree(scene, ob, rootchan, ctime);
}
void BKE_pose_splineik_evaluate(EvaluationContext *UNUSED(eval_ctx),
Scene *scene,
Object *ob,
- bPoseChannel *rootchan)
+ int rootchan_index)
+
{
- float ctime = BKE_scene_frame_get(scene); /* not accurate... */
- DEBUG_PRINT("%s on %s pchan %s\n", __func__, ob->id.name, rootchan->name);
+ bPoseChannel *rootchan = pose_pchan_get_indexed(ob, rootchan_index);
+ DEG_debug_print_eval_subdata(
+ __func__, ob->id.name, ob, "rootchan", rootchan->name, rootchan);
+ BLI_assert(ob->type == OB_ARMATURE);
+ const float ctime = BKE_scene_frame_get(scene); /* not accurate... */
+ bArmature *arm = (bArmature *)ob->data;
+ if (arm->flag & ARM_RESTPOS) {
+ return;
+ }
BKE_splineik_execute_tree(scene, ob, rootchan, ctime);
}
void BKE_pose_eval_flush(EvaluationContext *UNUSED(eval_ctx),
Scene *scene,
- Object *ob,
- bPose *UNUSED(pose))
+ Object *ob)
{
+ bPose *pose = ob->pose;
+ BLI_assert(pose != NULL);
+
float ctime = BKE_scene_frame_get(scene); /* not accurate... */
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
BLI_assert(ob->type == OB_ARMATURE);
- /* 6. release the IK tree */
+ /* release the IK tree */
BIK_release_tree(scene, ob, ctime);
ob->recalc &= ~OB_RECALC_ALL;
+
+ BLI_assert(pose->chan_array != NULL);
+ MEM_freeN(pose->chan_array);
+ pose->chan_array = NULL;
}
void BKE_pose_eval_proxy_copy(EvaluationContext *UNUSED(eval_ctx), Object *ob)
{
- BLI_assert(ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from != NULL);
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ BLI_assert(ID_IS_LINKED(ob) && ob->proxy_from != NULL);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
if (BKE_pose_copy_result(ob->pose, ob->proxy_from->pose) == false) {
printf("Proxy copy error, lib Object: %s proxy Object: %s\n",
ob->id.name + 2, ob->proxy_from->id.name + 2);
}
+ /* Rest of operations are NO-OP in depsgraph, so can clear
+ * flag now.
+ */
+ ob->recalc &= ~OB_RECALC_ALL;
}
diff --git a/source/blender/blenkernel/intern/blender.c b/source/blender/blenkernel/intern/blender.c
index afd60102453..55b2d5b9c0d 100644
--- a/source/blender/blenkernel/intern/blender.c
+++ b/source/blender/blenkernel/intern/blender.c
@@ -45,6 +45,7 @@
#include "IMB_imbuf.h"
#include "IMB_moviecache.h"
+#include "BKE_addon.h"
#include "BKE_blender.h" /* own include */
#include "BKE_blender_version.h" /* own include */
#include "BKE_blendfile.h"
@@ -82,6 +83,10 @@ void BKE_blender_free(void)
BKE_main_free(G.main);
G.main = NULL;
+ if (G.log.file != NULL) {
+ fclose(G.log.file);
+ }
+
BKE_spacetypes_free(); /* after free main, it uses space callbacks */
IMB_exit();
@@ -100,6 +105,18 @@ void BKE_blender_free(void)
free_nodesystem();
}
+void BKE_blender_version_string(char *version_str, size_t maxncpy, short version, short subversion, bool v_prefix, bool include_subversion)
+{
+ const char *prefix = v_prefix ? "v" : "";
+
+ if (include_subversion && subversion > 0) {
+ BLI_snprintf(version_str, maxncpy, "%s%d.%02d.%d", prefix, version / 100, version % 100, subversion);
+ }
+ else {
+ BLI_snprintf(version_str, maxncpy, "%s%d.%02d", prefix, version / 100, version % 100);
+ }
+}
+
void BKE_blender_globals_init(void)
{
memset(&G, 0, sizeof(Global));
@@ -110,16 +127,15 @@ void BKE_blender_globals_init(void)
strcpy(G.ima, "//");
- if (BLENDER_SUBVERSION)
- BLI_snprintf(versionstr, sizeof(versionstr), "v%d.%02d.%d", BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
- else
- BLI_snprintf(versionstr, sizeof(versionstr), "v%d.%02d", BLENDER_VERSION / 100, BLENDER_VERSION % 100);
+ BKE_blender_version_string(versionstr, sizeof(versionstr), BLENDER_VERSION, BLENDER_SUBVERSION, true, true);
#ifndef WITH_PYTHON_SECURITY /* default */
G.f |= G_SCRIPT_AUTOEXEC;
#else
G.f &= ~G_SCRIPT_AUTOEXEC;
#endif
+
+ G.log.level = 1;
}
void BKE_blender_globals_clear(void)
@@ -141,20 +157,28 @@ static void keymap_item_free(wmKeyMapItem *kmi)
MEM_freeN(kmi->ptr);
}
-/**
- * When loading a new userdef from file,
- * or when exiting Blender.
- */
-void BKE_blender_userdef_free(void)
+void BKE_blender_userdef_data_swap(UserDef *userdef_a, UserDef *userdef_b)
+{
+ SWAP(UserDef, *userdef_a, *userdef_b);
+}
+
+void BKE_blender_userdef_data_set(UserDef *userdef)
+{
+ BKE_blender_userdef_data_swap(&U, userdef);
+ BKE_blender_userdef_data_free(userdef, true);
+}
+
+void BKE_blender_userdef_data_set_and_free(UserDef *userdef)
+{
+ BKE_blender_userdef_data_set(userdef);
+ MEM_freeN(userdef);
+}
+
+static void userdef_free_keymaps(UserDef *userdef)
{
- wmKeyMap *km;
- wmKeyMapItem *kmi;
- wmKeyMapDiffItem *kmdi;
- bAddon *addon, *addon_next;
- uiFont *font;
-
- for (km = U.user_keymaps.first; km; km = km->next) {
- for (kmdi = km->diff_items.first; kmdi; kmdi = kmdi->next) {
+ for (wmKeyMap *km = userdef->user_keymaps.first, *km_next; km; km = km_next) {
+ km_next = km->next;
+ for (wmKeyMapDiffItem *kmdi = km->diff_items.first; kmdi; kmdi = kmdi->next) {
if (kmdi->add_item) {
keymap_item_free(kmdi->add_item);
MEM_freeN(kmdi->add_item);
@@ -165,47 +189,120 @@ void BKE_blender_userdef_free(void)
}
}
- for (kmi = km->items.first; kmi; kmi = kmi->next)
+ for (wmKeyMapItem *kmi = km->items.first; kmi; kmi = kmi->next) {
keymap_item_free(kmi);
+ }
BLI_freelistN(&km->diff_items);
BLI_freelistN(&km->items);
+
+ MEM_freeN(km);
}
-
- for (addon = U.addons.first; addon; addon = addon_next) {
+ BLI_listbase_clear(&userdef->user_keymaps);
+}
+
+static void userdef_free_addons(UserDef *userdef)
+{
+ for (bAddon *addon = userdef->addons.first, *addon_next; addon; addon = addon_next) {
addon_next = addon->next;
- if (addon->prop) {
- IDP_FreeProperty(addon->prop);
- MEM_freeN(addon->prop);
- }
- MEM_freeN(addon);
+ BKE_addon_free(addon);
}
+ BLI_listbase_clear(&userdef->addons);
+}
+
+/**
+ * When loading a new userdef from file,
+ * or when exiting Blender.
+ */
+void BKE_blender_userdef_data_free(UserDef *userdef, bool clear_fonts)
+{
+#define U _invalid_access_ /* ensure no accidental global access */
+#ifdef U /* quiet warning */
+#endif
- for (font = U.uifonts.first; font; font = font->next) {
- BLF_unload_id(font->blf_id);
+ userdef_free_keymaps(userdef);
+ userdef_free_addons(userdef);
+
+ if (clear_fonts) {
+ for (uiFont *font = userdef->uifonts.first; font; font = font->next) {
+ BLF_unload_id(font->blf_id);
+ }
+ BLF_default_set(-1);
}
- BLF_default_set(-1);
+ BLI_freelistN(&userdef->autoexec_paths);
- BLI_freelistN(&U.autoexec_paths);
+ BLI_freelistN(&userdef->uistyles);
+ BLI_freelistN(&userdef->uifonts);
+ BLI_freelistN(&userdef->themes);
- BLI_freelistN(&U.uistyles);
- BLI_freelistN(&U.uifonts);
- BLI_freelistN(&U.themes);
- BLI_freelistN(&U.user_keymaps);
+#undef U
}
/**
- * Handle changes in settings that need refreshing.
+ * Write U from userdef.
+ * This function defines which settings a template will override for the user preferences.
*/
-void BKE_blender_userdef_refresh(void)
+void BKE_blender_userdef_app_template_data_swap(UserDef *userdef_a, UserDef *userdef_b)
{
- /* prevent accidents */
- if (U.pixelsize == 0) U.pixelsize = 1;
-
- BLF_default_dpi(U.pixelsize * U.dpi);
- U.widget_unit = (U.pixelsize * U.dpi * 20 + 36) / 72;
+ /* TODO:
+ * - various minor settings (add as needed).
+ */
+
+#define DATA_SWAP(id) \
+ { \
+ UserDef userdef_tmp; \
+ memcpy(&(userdef_tmp.id), &(userdef_a->id), sizeof(userdef_tmp.id)); \
+ memcpy(&(userdef_a->id), &(userdef_b->id), sizeof(userdef_tmp.id)); \
+ memcpy(&(userdef_b->id), &(userdef_tmp.id), sizeof(userdef_tmp.id)); \
+ }
+
+#define LIST_SWAP(id) { \
+ SWAP(ListBase, userdef_a->id, userdef_b->id); \
+} ((void)0)
+#define FLAG_SWAP(id, ty, flags) { \
+ CHECK_TYPE(&(userdef_a->id), ty *); \
+ const ty f = flags; \
+ const ty a = userdef_a->id; \
+ const ty b = userdef_b->id; \
+ userdef_a->id = (userdef_a->id & ~f) | (b & f); \
+ userdef_b->id = (userdef_b->id & ~f) | (a & f); \
+} ((void)0)
+
+
+ LIST_SWAP(uistyles);
+ LIST_SWAP(uifonts);
+ LIST_SWAP(themes);
+ LIST_SWAP(addons);
+ LIST_SWAP(user_keymaps);
+
+ DATA_SWAP(light);
+
+ DATA_SWAP(font_path_ui);
+ DATA_SWAP(font_path_ui_mono);
+ DATA_SWAP(keyconfigstr);
+
+ DATA_SWAP(app_flag);
+
+ /* We could add others. */
+ FLAG_SWAP(uiflag, int, USER_QUIT_PROMPT);
+
+#undef DATA_SWAP
+#undef LIST_SWAP
+#undef FLAG_SWAP
+}
+
+void BKE_blender_userdef_app_template_data_set(UserDef *userdef)
+{
+ BKE_blender_userdef_app_template_data_swap(&U, userdef);
+ BKE_blender_userdef_data_free(userdef, true);
+}
+
+void BKE_blender_userdef_app_template_data_set_and_free(UserDef *userdef)
+{
+ BKE_blender_userdef_app_template_data_set(userdef);
+ MEM_freeN(userdef);
}
/* ***************** testing for break ************* */
diff --git a/source/blender/blenkernel/intern/blender_undo.c b/source/blender/blenkernel/intern/blender_undo.c
index bc98d6f6805..6b31c8c96f9 100644
--- a/source/blender/blenkernel/intern/blender_undo.c
+++ b/source/blender/blenkernel/intern/blender_undo.c
@@ -42,28 +42,19 @@
#include "DNA_scene_types.h"
-#include "BLI_fileops.h"
-#include "BLI_listbase.h"
#include "BLI_path_util.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
-#include "IMB_imbuf.h"
-#include "IMB_moviecache.h"
-
#include "BKE_blender_undo.h" /* own include */
#include "BKE_blendfile.h"
#include "BKE_appdir.h"
-#include "BKE_brush.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_global.h"
-#include "BKE_image.h"
#include "BKE_main.h"
-#include "RE_pipeline.h"
#include "BLO_undofile.h"
-#include "BLO_readfile.h"
#include "BLO_writefile.h"
/* -------------------------------------------------------------------- */
@@ -73,44 +64,22 @@
#define UNDO_DISK 0
-typedef struct UndoElem {
- struct UndoElem *next, *prev;
- char str[FILE_MAX];
- char name[BKE_UNDO_STR_MAX];
- MemFile memfile;
- uintptr_t undosize;
-} UndoElem;
-
-static ListBase undobase = {NULL, NULL};
-static UndoElem *curundo = NULL;
-
-/**
- * Avoid bad-level call to #WM_jobs_kill_all_except()
- */
-static void (*undo_wm_job_kill_callback)(struct bContext *C) = NULL;
-
-void BKE_undo_callback_wm_kill_jobs_set(void (*callback)(struct bContext *C))
-{
- undo_wm_job_kill_callback = callback;
-}
-
-static int read_undosave(bContext *C, UndoElem *uel)
+bool BKE_memfile_undo_decode(MemFileUndoData *mfu, bContext *C)
{
char mainstr[sizeof(G.main->name)];
int success = 0, fileflags;
- /* This is needed so undoing/redoing doesn't crash with threaded previews going */
- undo_wm_job_kill_callback(C);
-
BLI_strncpy(mainstr, G.main->name, sizeof(mainstr)); /* temporal store */
fileflags = G.fileflags;
G.fileflags |= G_FILE_NO_UI;
- if (UNDO_DISK)
- success = (BKE_blendfile_read(C, uel->str, NULL) != BKE_BLENDFILE_READ_FAIL);
- else
- success = BKE_blendfile_read_from_memfile(C, &uel->memfile, NULL);
+ if (UNDO_DISK) {
+ success = (BKE_blendfile_read(C, mfu->filename, NULL, 0) != BKE_BLENDFILE_READ_FAIL);
+ }
+ else {
+ success = BKE_blendfile_read_from_memfile(C, &mfu->memfile, NULL, 0);
+ }
/* restore */
BLI_strncpy(G.main->name, mainstr, sizeof(G.main->name)); /* restore */
@@ -124,283 +93,43 @@ static int read_undosave(bContext *C, UndoElem *uel)
return success;
}
-/* name can be a dynamic string */
-void BKE_undo_write(bContext *C, const char *name)
+MemFileUndoData *BKE_memfile_undo_encode(Main *bmain, MemFileUndoData *mfu_prev)
{
- uintptr_t maxmem, totmem, memused;
- int nr /*, success */ /* UNUSED */;
- UndoElem *uel;
-
- if ((U.uiflag & USER_GLOBALUNDO) == 0) {
- return;
- }
-
- if (U.undosteps == 0) {
- return;
- }
-
- /* remove all undos after (also when curundo == NULL) */
- while (undobase.last != curundo) {
- uel = undobase.last;
- BLI_remlink(&undobase, uel);
- BLO_memfile_free(&uel->memfile);
- MEM_freeN(uel);
- }
-
- /* make new */
- curundo = uel = MEM_callocN(sizeof(UndoElem), "undo file");
- BLI_strncpy(uel->name, name, sizeof(uel->name));
- BLI_addtail(&undobase, uel);
-
- /* and limit amount to the maximum */
- nr = 0;
- uel = undobase.last;
- while (uel) {
- nr++;
- if (nr == U.undosteps) break;
- uel = uel->prev;
- }
- if (uel) {
- while (undobase.first != uel) {
- UndoElem *first = undobase.first;
- BLI_remlink(&undobase, first);
- /* the merge is because of compression */
- BLO_memfile_merge(&first->memfile, &first->next->memfile);
- MEM_freeN(first);
- }
- }
-
+ MemFileUndoData *mfu = MEM_callocN(sizeof(MemFileUndoData), __func__);
/* disk save version */
if (UNDO_DISK) {
static int counter = 0;
- char filepath[FILE_MAX];
+ char filename[FILE_MAX];
char numstr[32];
int fileflags = G.fileflags & ~(G_FILE_HISTORY); /* don't do file history on undo */
- /* calculate current filepath */
+ /* Calculate current filename. */
counter++;
counter = counter % U.undosteps;
BLI_snprintf(numstr, sizeof(numstr), "%d.blend", counter);
- BLI_make_file_string("/", filepath, BKE_tempdir_session(), numstr);
-
- /* success = */ /* UNUSED */ BLO_write_file(CTX_data_main(C), filepath, fileflags, NULL, NULL);
-
- BLI_strncpy(curundo->str, filepath, sizeof(curundo->str));
- }
- else {
- MemFile *prevfile = NULL;
-
- if (curundo->prev) prevfile = &(curundo->prev->memfile);
-
- memused = MEM_get_memory_in_use();
- /* success = */ /* UNUSED */ BLO_write_file_mem(CTX_data_main(C), prevfile, &curundo->memfile, G.fileflags);
- 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;
+ BLI_make_file_string("/", filename, BKE_tempdir_session(), numstr);
- while (undobase.first != uel) {
- UndoElem *first = undobase.first;
- BLI_remlink(&undobase, first);
- /* the merge is because of compression */
- BLO_memfile_merge(&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 */
-void BKE_undo_step(bContext *C, int step)
-{
+ /* success = */ /* UNUSED */ BLO_write_file(bmain, filename, fileflags, NULL, NULL);
- if (step == 0) {
- read_undosave(C, curundo);
- }
- else if (step == 1) {
- /* curundo should never be NULL, after restart or load file it should call undo_save */
- if (curundo == NULL || curundo->prev == NULL) {
- // XXX error("No undo available");
- }
- else {
- if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name);
- curundo = curundo->prev;
- read_undosave(C, curundo);
- }
+ BLI_strncpy(mfu->filename, filename, sizeof(mfu->filename));
}
else {
- /* curundo has to remain current situation! */
-
- if (curundo == NULL || curundo->next == NULL) {
- // XXX error("No redo available");
- }
- else {
- read_undosave(C, curundo->next);
- curundo = curundo->next;
- if (G.debug & G_DEBUG) printf("redo %s\n", curundo->name);
- }
- }
-}
-
-void BKE_undo_reset(void)
-{
- UndoElem *uel;
-
- uel = undobase.first;
- while (uel) {
- BLO_memfile_free(&uel->memfile);
- uel = uel->next;
+ MemFile *prevfile = (mfu_prev) ? &(mfu_prev->memfile) : NULL;
+ /* success = */ /* UNUSED */ BLO_write_file_mem(bmain, prevfile, &mfu->memfile, G.fileflags);
+ mfu->undo_size = mfu->memfile.size;
}
- BLI_freelistN(&undobase);
- curundo = NULL;
-}
-
-/* based on index nr it does a restore */
-void BKE_undo_number(bContext *C, int nr)
-{
- curundo = BLI_findlink(&undobase, nr);
- BKE_undo_step(C, 0);
-}
-
-/* go back to the last occurance of name in stack */
-void BKE_undo_name(bContext *C, const char *name)
-{
- UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name));
-
- if (uel && uel->prev) {
- curundo = uel->prev;
- BKE_undo_step(C, 0);
- }
-}
-
-/* name optional */
-bool BKE_undo_is_valid(const char *name)
-{
- if (name) {
- UndoElem *uel = BLI_rfindstring(&undobase, name, offsetof(UndoElem, name));
- return uel && uel->prev;
- }
+ bmain->is_memfile_undo_written = true;
- return undobase.last != undobase.first;
+ return mfu;
}
-/* get name of undo item, return null if no item with this index */
-/* if active pointer, set it to 1 if true */
-const char *BKE_undo_get_name(int nr, bool *r_active)
-{
- UndoElem *uel = BLI_findlink(&undobase, nr);
-
- if (r_active) *r_active = false;
-
- if (uel) {
- if (r_active && (uel == curundo)) {
- *r_active = true;
- }
- return uel->name;
- }
- return NULL;
-}
-
-/* return the name of the last item */
-const char *BKE_undo_get_name_last(void)
-{
- UndoElem *uel = undobase.last;
- return (uel ? uel->name : NULL);
-}
-
-/**
- * Saves .blend using undo buffer.
- *
- * \return success.
- */
-bool BKE_undo_save_file(const char *filename)
+void BKE_memfile_undo_free(MemFileUndoData *mfu)
{
- UndoElem *uel;
- MemFileChunk *chunk;
- int file, oflags;
-
- if ((U.uiflag & USER_GLOBALUNDO) == 0) {
- return false;
- }
-
- uel = curundo;
- if (uel == NULL) {
- fprintf(stderr, "No undo buffer to save recovery file\n");
- return false;
- }
-
- /* note: This is currently used for autosave and 'quit.blend', where _not_ following symlinks is OK,
- * however if this is ever executed explicitly by the user, we may want to allow writing to symlinks.
- */
-
- oflags = O_BINARY | O_WRONLY | O_CREAT | O_TRUNC;
-#ifdef O_NOFOLLOW
- /* use O_NOFOLLOW to avoid writing to a symlink - use 'O_EXCL' (CVE-2008-1103) */
- oflags |= O_NOFOLLOW;
-#else
- /* TODO(sergey): How to deal with symlinks on windows? */
-# ifndef _MSC_VER
-# warning "Symbolic links will be followed on undo save, possibly causing CVE-2008-1103"
-# endif
-#endif
- file = BLI_open(filename, oflags, 0666);
-
- if (file == -1) {
- fprintf(stderr, "Unable to save '%s': %s\n",
- filename, errno ? strerror(errno) : "Unknown error opening file");
- return false;
- }
-
- for (chunk = uel->memfile.chunks.first; chunk; chunk = chunk->next) {
- if (write(file, chunk->buf, chunk->size) != chunk->size) {
- break;
- }
- }
-
- close(file);
-
- if (chunk) {
- fprintf(stderr, "Unable to save '%s': %s\n",
- filename, errno ? strerror(errno) : "Unknown error writing file");
- return false;
- }
- return true;
-}
-
-/* sets curscene */
-Main *BKE_undo_get_main(Scene **r_scene)
-{
- Main *mainp = NULL;
- BlendFileData *bfd = BLO_read_from_memfile(G.main, G.main->name, &curundo->memfile, NULL);
-
- if (bfd) {
- mainp = bfd->main;
- if (r_scene) {
- *r_scene = bfd->curscene;
- }
-
- MEM_freeN(bfd);
- }
-
- return mainp;
+ BLO_memfile_free(&mfu->memfile);
+ MEM_freeN(mfu);
}
/** \} */
diff --git a/source/blender/blenkernel/intern/blendfile.c b/source/blender/blenkernel/intern/blendfile.c
index 54f709a1e5b..cc992a4a520 100644
--- a/source/blender/blenkernel/intern/blendfile.c
+++ b/source/blender/blenkernel/intern/blendfile.c
@@ -114,6 +114,7 @@ static void setup_app_data(
const char *filepath, ReportList *reports)
{
Scene *curscene = NULL;
+ const bool is_startup = (bfd->filename[0] == '\0');
const bool recover = (G.fileflags & G_FILE_RECOVER) != 0;
enum {
LOAD_UI = 1,
@@ -129,7 +130,7 @@ static void setup_app_data(
else if (BLI_listbase_is_empty(&bfd->main->screen)) {
mode = LOAD_UNDO;
}
- else if (G.fileflags & G_FILE_NO_UI) {
+ else if ((G.fileflags & G_FILE_NO_UI) && (is_startup == false)) {
mode = LOAD_UI_OFF;
}
else {
@@ -225,11 +226,9 @@ static void setup_app_data(
CTX_data_main_set(C, G.main);
if (bfd->user) {
-
/* only here free userdef themes... */
- BKE_blender_userdef_free();
-
- U = *bfd->user;
+ BKE_blender_userdef_data_set_and_free(bfd->user);
+ bfd->user = NULL;
/* Security issue: any blend file could include a USER block.
*
@@ -240,8 +239,6 @@ static void setup_app_data(
* enable scripts auto-execution by loading a '.blend' file.
*/
U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
-
- MEM_freeN(bfd->user);
}
/* case G_FILE_NO_UI or no screens in file */
@@ -250,7 +247,9 @@ static void setup_app_data(
CTX_data_scene_set(C, curscene);
}
else {
- G.fileflags = bfd->fileflags;
+ /* Keep state from preferences. */
+ const int fileflags_skip = G_FILE_FLAGS_RUNTIME;
+ G.fileflags = (G.fileflags & fileflags_skip) | (bfd->fileflags & ~fileflags_skip);
CTX_wm_manager_set(C, G.main->wm.first);
CTX_wm_screen_set(C, bfd->curscreen);
CTX_data_scene_set(C, bfd->curscene);
@@ -349,17 +348,23 @@ static int handle_subversion_warning(Main *main, ReportList *reports)
return 1;
}
-int BKE_blendfile_read(bContext *C, const char *filepath, ReportList *reports)
+int BKE_blendfile_read(
+ bContext *C, const char *filepath,
+ ReportList *reports, int skip_flags)
{
BlendFileData *bfd;
int retval = BKE_BLENDFILE_READ_OK;
- if (strstr(filepath, BLENDER_STARTUP_FILE) == NULL) /* don't print user-pref loading */
- printf("read blend: %s\n", filepath);
+ /* don't print user-pref loading */
+ if (strstr(filepath, BLENDER_STARTUP_FILE) == NULL) {
+ printf("Read blend: %s\n", filepath);
+ }
- bfd = BLO_read_from_file(filepath, reports);
+ bfd = BLO_read_from_file(filepath, reports, skip_flags);
if (bfd) {
- if (bfd->user) retval = BKE_BLENDFILE_READ_OK_USERPREFS;
+ if (bfd->user) {
+ retval = BKE_BLENDFILE_READ_OK_USERPREFS;
+ }
if (0 == handle_subversion_warning(bfd->main, reports)) {
BKE_main_free(bfd->main);
@@ -379,11 +384,11 @@ int BKE_blendfile_read(bContext *C, const char *filepath, ReportList *reports)
bool BKE_blendfile_read_from_memory(
bContext *C, const void *filebuf, int filelength,
- ReportList *reports, bool update_defaults)
+ ReportList *reports, int skip_flags, bool update_defaults)
{
BlendFileData *bfd;
- bfd = BLO_read_from_memory(filebuf, filelength, reports);
+ bfd = BLO_read_from_memory(filebuf, filelength, reports, skip_flags);
if (bfd) {
if (update_defaults)
BLO_update_defaults_startup_blend(bfd->main);
@@ -399,17 +404,17 @@ bool BKE_blendfile_read_from_memory(
/* memfile is the undo buffer */
bool BKE_blendfile_read_from_memfile(
bContext *C, struct MemFile *memfile,
- ReportList *reports)
+ ReportList *reports, int skip_flags)
{
BlendFileData *bfd;
- bfd = BLO_read_from_memfile(CTX_data_main(C), G.main->name, memfile, reports);
+ bfd = BLO_read_from_memfile(CTX_data_main(C), G.main->name, memfile, reports, skip_flags);
if (bfd) {
/* remove the unused screens and wm */
while (bfd->main->wm.first)
- BKE_libblock_free_ex(bfd->main, bfd->main->wm.first, true, true);
+ BKE_libblock_free(bfd->main, bfd->main->wm.first);
while (bfd->main->screen.first)
- BKE_libblock_free_ex(bfd->main, bfd->main->screen.first, true, true);
+ BKE_libblock_free(bfd->main, bfd->main->screen.first);
setup_app_data(C, bfd, "<memory1>", reports);
}
@@ -420,45 +425,116 @@ bool BKE_blendfile_read_from_memfile(
return (bfd != NULL);
}
+/**
+ * Utility to make a file 'empty' used for startup to optionally give an empty file.
+ * Handy for tests.
+ */
+void BKE_blendfile_read_make_empty(bContext *C)
+{
+ Main *bmain = CTX_data_main(C);
+
+ ListBase *lbarray[MAX_LIBARRAY];
+ ID *id;
+ int a;
+
+ a = set_listbasepointers(bmain, lbarray);
+ while (a--) {
+ id = lbarray[a]->first;
+ if (id != NULL) {
+ if (ELEM(GS(id->name), ID_SCE, ID_SCR, ID_WM)) {
+ continue;
+ }
+ while ((id = lbarray[a]->first)) {
+ BKE_libblock_delete(bmain, id);
+ }
+ }
+ }
+}
+
/* only read the userdef from a .blend */
-int BKE_blendfile_read_userdef(const char *filepath, ReportList *reports)
+UserDef *BKE_blendfile_userdef_read(const char *filepath, ReportList *reports)
{
BlendFileData *bfd;
- int retval = BKE_BLENDFILE_READ_FAIL;
+ UserDef *userdef = NULL;
- bfd = BLO_read_from_file(filepath, reports);
+ bfd = BLO_read_from_file(filepath, reports, BLO_READ_SKIP_ALL & ~BLO_READ_SKIP_USERDEF);
if (bfd) {
if (bfd->user) {
- retval = BKE_BLENDFILE_READ_OK_USERPREFS;
+ userdef = bfd->user;
+ }
+ BKE_main_free(bfd->main);
+ MEM_freeN(bfd);
+ }
+
+ return userdef;
+}
- /* only here free userdef themes... */
- BKE_blender_userdef_free();
- U = *bfd->user;
- MEM_freeN(bfd->user);
+UserDef *BKE_blendfile_userdef_read_from_memory(
+ const void *filebuf, int filelength,
+ ReportList *reports)
+{
+ BlendFileData *bfd;
+ UserDef *userdef = NULL;
+
+ bfd = BLO_read_from_memory(filebuf, filelength, reports, BLO_READ_SKIP_ALL & ~BLO_READ_SKIP_USERDEF);
+ if (bfd) {
+ if (bfd->user) {
+ userdef = bfd->user;
}
BKE_main_free(bfd->main);
MEM_freeN(bfd);
}
+ else {
+ BKE_reports_prepend(reports, "Loading failed: ");
+ }
- return retval;
+ return userdef;
}
-/* only write the userdef in a .blend */
-int BKE_blendfile_write_userdef(const char *filepath, ReportList *reports)
+
+/**
+ * Only write the userdef in a .blend
+ * \return success
+ */
+bool BKE_blendfile_userdef_write(const char *filepath, ReportList *reports)
{
Main *mainb = MEM_callocN(sizeof(Main), "empty main");
- int retval = 0;
+ bool ok = false;
if (BLO_write_file(mainb, filepath, G_FILE_USERPREFS, reports, NULL)) {
- retval = 1;
+ ok = true;
}
MEM_freeN(mainb);
- return retval;
+ return ok;
+}
+
+/**
+ * Only write the userdef in a .blend, merging with the existing blend file.
+ * \return success
+ *
+ * \note In the future we should re-evaluate user preferences,
+ * possibly splitting out system/hardware specific prefs.
+ */
+bool BKE_blendfile_userdef_write_app_template(const char *filepath, ReportList *reports)
+{
+ /* if it fails, overwrite is OK. */
+ UserDef *userdef_default = BKE_blendfile_userdef_read(filepath, NULL);
+ if (userdef_default == NULL) {
+ return BKE_blendfile_userdef_write(filepath, reports);
+ }
+
+ BKE_blender_userdef_app_template_data_swap(&U, userdef_default);
+ bool ok = BKE_blendfile_userdef_write(filepath, reports);
+ BKE_blender_userdef_app_template_data_swap(&U, userdef_default);
+ BKE_blender_userdef_data_free(userdef_default, false);
+ MEM_freeN(userdef_default);
+ return ok;
}
+
/** \} */
diff --git a/source/blender/blenkernel/intern/bmfont.c b/source/blender/blenkernel/intern/bmfont.c
index 79b3f89da20..8018629ef2a 100644
--- a/source/blender/blenkernel/intern/bmfont.c
+++ b/source/blender/blenkernel/intern/bmfont.c
@@ -52,11 +52,10 @@
#include "MEM_guardedalloc.h"
#include "IMB_imbuf_types.h"
-#include "BKE_bmfont.h"
-#include "BKE_bmfont_types.h"
-
#include "BLI_utildefines.h"
+#include "BKE_bmfont.h"
+#include "BKE_bmfont_types.h"
#include "BKE_global.h"
void printfGlyph(bmGlyph *glyph)
diff --git a/source/blender/blenkernel/intern/boids.c b/source/blender/blenkernel/intern/boids.c
index b4bc83bf94c..024c0aeb23f 100644
--- a/source/blender/blenkernel/intern/boids.c
+++ b/source/blender/blenkernel/intern/boids.c
@@ -35,7 +35,7 @@
#include "MEM_guardedalloc.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_scene_types.h"
#include "BLI_rand.h"
@@ -161,8 +161,10 @@ static int rule_goal_avoid(BoidRule *rule, BoidBrainData *bbd, BoidValues *val,
copy_v3_v3(bbd->goal_nor, efd.nor);
}
}
- else if (rule->type == eBoidRuleType_Avoid && bpa->data.mode == eBoidMode_Climbing &&
- priority > 2.0f * gabr->fear_factor) {
+ else if ((rule->type == eBoidRuleType_Avoid) &&
+ (bpa->data.mode == eBoidMode_Climbing) &&
+ (priority > 2.0f * gabr->fear_factor))
+ {
/* detach from surface and try to fly away from danger */
negate_v3_v3(efd.vec_to_point, bpa->gravity);
}
@@ -1106,7 +1108,7 @@ void boid_brain(BoidBrainData *bbd, int p, ParticleData *pa)
/* jump to go faster */
if (jump == 0 && val.jump_speed > val.max_speed && bbd->wanted_speed > val.max_speed) {
-
+ /* pass */
}
if (jump) {
@@ -1581,7 +1583,7 @@ void boid_free_settings(BoidSettings *boids)
MEM_freeN(boids);
}
}
-BoidSettings *boid_copy_settings(BoidSettings *boids)
+BoidSettings *boid_copy_settings(const BoidSettings *boids)
{
BoidSettings *nboids = NULL;
diff --git a/source/blender/blenkernel/intern/bpath.c b/source/blender/blenkernel/intern/bpath.c
index 487b8ffa2b5..e9a8de4469d 100644
--- a/source/blender/blenkernel/intern/bpath.c
+++ b/source/blender/blenkernel/intern/bpath.c
@@ -53,8 +53,8 @@
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_movieclip_types.h"
-#include "DNA_object_fluidsim.h"
-#include "DNA_object_force.h"
+#include "DNA_object_fluidsim_types.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_sequence_types.h"
@@ -243,7 +243,7 @@ static bool missing_files_find__recursive(
continue; /* cant stat, don't bother with this file, could print debug info here */
if (S_ISREG(status.st_mode)) { /* is file */
- if (STREQLEN(filename, de->d_name, FILE_MAX)) { /* name matches */
+ if (BLI_path_ncmp(filename, de->d_name, FILE_MAX) == 0) { /* name matches */
/* open the file to read its size */
size = status.st_size;
if ((size > 0) && (size > *r_filesize)) { /* find the biggest file */
@@ -425,7 +425,7 @@ void BKE_bpath_traverse_id(Main *bmain, ID *id, BPathVisitor visit_cb, const int
{
const char *absbase = (flag & BKE_BPATH_TRAVERSE_ABS) ? ID_BLEND_PATH(bmain, id) : NULL;
- if ((flag & BKE_BPATH_TRAVERSE_SKIP_LIBRARY) && ID_IS_LINKED_DATABLOCK(id)) {
+ if ((flag & BKE_BPATH_TRAVERSE_SKIP_LIBRARY) && ID_IS_LINKED(id)) {
return;
}
diff --git a/source/blender/blenkernel/intern/brush.c b/source/blender/blenkernel/intern/brush.c
index 57b707a31d3..d82c1ca56fe 100644
--- a/source/blender/blenkernel/intern/brush.c
+++ b/source/blender/blenkernel/intern/brush.c
@@ -148,11 +148,14 @@ void BKE_brush_init(Brush *brush)
BKE_brush_curve_preset(brush, CURVE_PRESET_SMOOTH);
}
-Brush *BKE_brush_add(Main *bmain, const char *name, short ob_mode)
+/**
+ * \note Resulting brush will have two users: one as a fake user, another is assumed to be used by the caller.
+ */
+Brush *BKE_brush_add(Main *bmain, const char *name, const eObjectMode ob_mode)
{
Brush *brush;
- brush = BKE_libblock_alloc(bmain, ID_BR, name);
+ brush = BKE_libblock_alloc(bmain, ID_BR, name, 0);
BKE_brush_init(brush);
@@ -161,7 +164,7 @@ Brush *BKE_brush_add(Main *bmain, const char *name, short ob_mode)
return brush;
}
-struct Brush *BKE_brush_first_search(struct Main *bmain, short ob_mode)
+struct Brush *BKE_brush_first_search(struct Main *bmain, const eObjectMode ob_mode)
{
Brush *brush;
@@ -172,34 +175,38 @@ struct Brush *BKE_brush_first_search(struct Main *bmain, short ob_mode)
return NULL;
}
-Brush *BKE_brush_copy(Main *bmain, Brush *brush)
+/**
+ * Only copy internal data of Brush ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_brush_copy_data(Main *UNUSED(bmain), Brush *brush_dst, const Brush *brush_src, const int flag)
{
- Brush *brushn;
-
- brushn = BKE_libblock_copy(bmain, &brush->id);
-
- if (brush->mtex.tex)
- id_us_plus((ID *)brush->mtex.tex);
-
- if (brush->mask_mtex.tex)
- id_us_plus((ID *)brush->mask_mtex.tex);
-
- if (brush->paint_curve)
- id_us_plus((ID *)brush->paint_curve);
-
- if (brush->icon_imbuf)
- brushn->icon_imbuf = IMB_dupImBuf(brush->icon_imbuf);
+ if (brush_src->icon_imbuf) {
+ brush_dst->icon_imbuf = IMB_dupImBuf(brush_src->icon_imbuf);
+ }
- brushn->preview = NULL;
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&brush_dst->id, &brush_src->id);
+ }
+ else {
+ brush_dst->preview = NULL;
+ }
- brushn->curve = curvemapping_copy(brush->curve);
+ brush_dst->curve = curvemapping_copy(brush_src->curve);
/* enable fake user by default */
- id_fake_user_set(&brush->id);
-
- BKE_id_copy_ensure_local(bmain, &brush->id, &brushn->id);
+ id_fake_user_set(&brush_dst->id);
+}
- return brushn;
+Brush *BKE_brush_copy(Main *bmain, const Brush *brush)
+{
+ Brush *brush_copy;
+ BKE_id_copy_ex(bmain, &brush->id, (ID **)&brush_copy, 0, false);
+ return brush_copy;
}
/** Free (or release) any data used by this brush (does not free the brush itself). */
@@ -225,7 +232,7 @@ void BKE_brush_make_local(Main *bmain, Brush *brush, const bool lib_local)
* - mixed: make copy
*/
- if (!ID_IS_LINKED_DATABLOCK(brush)) {
+ if (!ID_IS_LINKED(brush)) {
return;
}
@@ -434,9 +441,8 @@ void BKE_brush_sculpt_reset(Brush *br)
/**
* Library Operations
- * \param preset CurveMappingPreset
*/
-void BKE_brush_curve_preset(Brush *b, int preset)
+void BKE_brush_curve_preset(Brush *b, eCurveMappingPreset preset)
{
CurveMap *cm = NULL;
@@ -517,13 +523,13 @@ int BKE_brush_clone_image_delete(Brush *brush)
* region space mouse coordinates, or 3d world coordinates for 3D mapping.
*
* rgba outputs straight alpha. */
-float BKE_brush_sample_tex_3D(const Scene *scene, Brush *br,
+float BKE_brush_sample_tex_3D(const Scene *scene, const Brush *br,
const float point[3],
float rgba[4], const int thread,
struct ImagePool *pool)
{
UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
- MTex *mtex = &br->mtex;
+ const MTex *mtex = &br->mtex;
float intensity = 1.0;
bool hasrgb = false;
@@ -817,7 +823,7 @@ int BKE_brush_size_get(const Scene *scene, const Brush *brush)
return size;
}
-int BKE_brush_use_locked_size(const Scene *scene, const Brush *brush)
+bool BKE_brush_use_locked_size(const Scene *scene, const Brush *brush)
{
const short us_flag = scene->toolsettings->unified_paint_settings.flag;
@@ -826,7 +832,7 @@ int BKE_brush_use_locked_size(const Scene *scene, const Brush *brush)
(brush->flag & BRUSH_LOCK_SIZE);
}
-int BKE_brush_use_size_pressure(const Scene *scene, const Brush *brush)
+bool BKE_brush_use_size_pressure(const Scene *scene, const Brush *brush)
{
const short us_flag = scene->toolsettings->unified_paint_settings.flag;
@@ -835,7 +841,7 @@ int BKE_brush_use_size_pressure(const Scene *scene, const Brush *brush)
(brush->flag & BRUSH_SIZE_PRESSURE);
}
-int BKE_brush_use_alpha_pressure(const Scene *scene, const Brush *brush)
+bool BKE_brush_use_alpha_pressure(const Scene *scene, const Brush *brush)
{
const short us_flag = scene->toolsettings->unified_paint_settings.flag;
@@ -844,6 +850,16 @@ int BKE_brush_use_alpha_pressure(const Scene *scene, const Brush *brush)
(brush->flag & BRUSH_ALPHA_PRESSURE);
}
+bool BKE_brush_sculpt_has_secondary_color(const Brush *brush)
+{
+ return ELEM(
+ brush->sculpt_tool, SCULPT_TOOL_BLOB, SCULPT_TOOL_DRAW,
+ SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY, SCULPT_TOOL_CLAY_STRIPS,
+ SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE, SCULPT_TOOL_LAYER,
+ SCULPT_TOOL_FLATTEN, SCULPT_TOOL_FILL, SCULPT_TOOL_SCRAPE,
+ SCULPT_TOOL_MASK);
+}
+
void BKE_brush_unprojected_radius_set(Scene *scene, Brush *brush, float unprojected_radius)
{
UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
@@ -962,7 +978,7 @@ void BKE_brush_randomize_texture_coords(UnifiedPaintSettings *ups, bool mask)
}
/* Uses the brush curve control to find a strength value */
-float BKE_brush_curve_strength(Brush *br, float p, const float len)
+float BKE_brush_curve_strength(const Brush *br, float p, const float len)
{
float strength;
@@ -1050,7 +1066,8 @@ struct ImBuf *BKE_brush_gen_radial_control_imbuf(Brush *br, bool secondary)
for (i = 0; i < side; ++i) {
for (j = 0; j < side; ++j) {
const int col = texcache[i * side + j];
- im->rect_float[i * side + j] *= (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
+ im->rect_float[i * side + j] *=
+ (((char *)&col)[0] + ((char *)&col)[1] + ((char *)&col)[2]) / 3.0f / 255.0f;
}
}
diff --git a/source/blender/blenkernel/intern/bullet.c b/source/blender/blenkernel/intern/bullet.c
index 088031e16a7..c16c0f7af31 100644
--- a/source/blender/blenkernel/intern/bullet.c
+++ b/source/blender/blenkernel/intern/bullet.c
@@ -33,7 +33,7 @@
#include "MEM_guardedalloc.h"
/* types */
-#include "DNA_object_force.h" /* here is the softbody struct */
+#include "DNA_object_force_types.h" /* here is the softbody struct */
#include "BKE_bullet.h"
diff --git a/source/blender/blenkernel/intern/bvhutils.c b/source/blender/blenkernel/intern/bvhutils.c
index c0e4ef37a93..cd2c7194237 100644
--- a/source/blender/blenkernel/intern/bvhutils.c
+++ b/source/blender/blenkernel/intern/bvhutils.c
@@ -411,7 +411,7 @@ static BVHTree *bvhtree_from_editmesh_verts_create_tree(
BMVert *eve = BM_vert_at_index(em->bm, i);
BLI_bvhtree_insert(tree, i, eve->co, 1);
}
- BLI_assert(BLI_bvhtree_get_size(tree) == verts_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == verts_num_active);
BLI_bvhtree_balance(tree);
}
@@ -440,7 +440,7 @@ static BVHTree *bvhtree_from_mesh_verts_create_tree(
}
BLI_bvhtree_insert(tree, i, vert[i].co, 1);
}
- BLI_assert(BLI_bvhtree_get_size(tree) == verts_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == verts_num_active);
BLI_bvhtree_balance(tree);
}
@@ -612,7 +612,7 @@ static BVHTree *bvhtree_from_editmesh_edges_create_tree(
BLI_bvhtree_insert(tree, i, co[0], 2);
}
- BLI_assert(BLI_bvhtree_get_size(tree) == edges_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == edges_num_active);
BLI_bvhtree_balance(tree);
}
@@ -829,7 +829,7 @@ static BVHTree *bvhtree_from_mesh_faces_create_tree(
BLI_bvhtree_insert(tree, i, co[0], face[i].v4 ? 4 : 3);
}
}
- BLI_assert(BLI_bvhtree_get_size(tree) == faces_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == faces_num_active);
BLI_bvhtree_balance(tree);
}
}
@@ -917,10 +917,10 @@ BVHTree *bvhtree_from_mesh_faces(
/**
* Builds a bvh tree where nodes are the given tessellated faces (note: does not copy given mfaces!).
- * \param vert_allocated if true, vert freeing will be done when freeing data.
- * \param face_allocated if true, face freeing will be done when freeing data.
+ * \param vert_allocated: if true, vert freeing will be done when freeing data.
+ * \param face_allocated: if true, face freeing will be done when freeing data.
* \param faces_mask: if not null, true elements give which faces to add to BVH tree.
- * \param numFaces_active if >= 0, number of active faces to add to BVH tree (else will be computed from mask).
+ * \param faces_num_active: if >= 0, number of active faces to add to BVH tree (else will be computed from mask).
*/
BVHTree *bvhtree_from_mesh_faces_ex(
BVHTreeFromMesh *data, const MVert *vert, const bool vert_allocated,
@@ -990,7 +990,7 @@ static BVHTree *bvhtree_from_editmesh_looptri_create_tree(
}
}
}
- BLI_assert(BLI_bvhtree_get_size(tree) == looptri_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == looptri_num_active);
BLI_bvhtree_balance(tree);
}
}
@@ -1032,7 +1032,7 @@ static BVHTree *bvhtree_from_mesh_looptri_create_tree(
BLI_bvhtree_insert(tree, i, co[0], 3);
}
}
- BLI_assert(BLI_bvhtree_get_size(tree) == looptri_num_active);
+ BLI_assert(BLI_bvhtree_get_len(tree) == looptri_num_active);
BLI_bvhtree_balance(tree);
}
}
@@ -1137,7 +1137,6 @@ BVHTree *bvhtree_from_mesh_looptri(
const MLoopTri *looptri = NULL;
bool vert_allocated = false;
bool loop_allocated = false;
- bool looptri_allocated = false;
BLI_rw_mutex_lock(&cache_rwlock, THREAD_LOCK_READ);
tree = bvhcache_find(dm->bvhCache, BVHTREE_FROM_LOOPTRI);
@@ -1150,12 +1149,7 @@ BVHTree *bvhtree_from_mesh_looptri(
mpoly = DM_get_poly_array(dm, &poly_allocated);
mloop = DM_get_loop_array(dm, &loop_allocated);
- looptri = DM_get_looptri_array(
- dm,
- mvert,
- mpoly, dm->getNumPolys(dm),
- mloop, dm->getNumLoops(dm),
- &looptri_allocated);
+ looptri = dm->getLoopTriArray(dm);
if (poly_allocated) {
MEM_freeN(mpoly);
@@ -1193,7 +1187,7 @@ BVHTree *bvhtree_from_mesh_looptri(
data, tree, true, epsilon,
mvert, vert_allocated,
mloop, loop_allocated,
- looptri, looptri_allocated);
+ looptri, false);
}
else {
if (vert_allocated) {
@@ -1202,9 +1196,6 @@ BVHTree *bvhtree_from_mesh_looptri(
if (loop_allocated) {
MEM_freeN(mloop);
}
- if (looptri_allocated) {
- MEM_freeN((void *)looptri);
- }
memset(data, 0, sizeof(*data));
}
diff --git a/source/blender/blenkernel/intern/cachefile.c b/source/blender/blenkernel/intern/cachefile.c
index 3dce08eb756..058394fc1b1 100644
--- a/source/blender/blenkernel/intern/cachefile.c
+++ b/source/blender/blenkernel/intern/cachefile.c
@@ -42,7 +42,6 @@
#include "BKE_animsys.h"
#include "BKE_cachefile.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_modifier.h"
@@ -66,7 +65,7 @@ void BKE_cachefiles_exit(void)
void *BKE_cachefile_add(Main *bmain, const char *name)
{
- CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, name);
+ CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, name, 0);
BKE_cachefile_init(cache_file);
@@ -82,6 +81,7 @@ void BKE_cachefile_init(CacheFile *cache_file)
cache_file->is_sequence = false;
cache_file->scale = 1.0f;
cache_file->handle_mutex = BLI_mutex_alloc();
+ BLI_listbase_clear(&cache_file->object_paths);
}
/** Free (or release) any data used by this cachefile (does not free the cachefile itself). */
@@ -99,16 +99,26 @@ void BKE_cachefile_free(CacheFile *cache_file)
BLI_freelistN(&cache_file->object_paths);
}
-CacheFile *BKE_cachefile_copy(Main *bmain, CacheFile *cache_file)
+/**
+ * Only copy internal data of CacheFile ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_cachefile_copy_data(
+ Main *UNUSED(bmain), CacheFile *cache_file_dst, const CacheFile *UNUSED(cache_file_src), const int UNUSED(flag))
{
- CacheFile *new_cache_file = BKE_libblock_copy(bmain, &cache_file->id);
- new_cache_file->handle = NULL;
-
- BLI_listbase_clear(&cache_file->object_paths);
-
- BKE_id_copy_ensure_local(bmain, &cache_file->id, &new_cache_file->id);
+ cache_file_dst->handle = NULL;
+ BLI_listbase_clear(&cache_file_dst->object_paths);
+}
- return new_cache_file;
+CacheFile *BKE_cachefile_copy(Main *bmain, const CacheFile *cache_file)
+{
+ CacheFile *cache_file_copy;
+ BKE_id_copy_ex(bmain, &cache_file->id, (ID **)&cache_file_copy, 0, false);
+ return cache_file_copy;
}
void BKE_cachefile_make_local(Main *bmain, CacheFile *cache_file, const bool lib_local)
@@ -165,6 +175,7 @@ void BKE_cachefile_update_frame(Main *bmain, Scene *scene, const float ctime, co
const float time = BKE_cachefile_time_offset(cache_file, ctime, fps);
if (BKE_cachefile_filepath_get(bmain, cache_file, time, filename)) {
+ BKE_cachefile_clean(scene, cache_file);
#ifdef WITH_ALEMBIC
ABC_free_handle(cache_file->handle);
cache_file->handle = ABC_create_handle(filename, NULL);
@@ -198,8 +209,9 @@ bool BKE_cachefile_filepath_get(
float BKE_cachefile_time_offset(CacheFile *cache_file, const float time, const float fps)
{
+ const float time_offset = cache_file->frame_offset / fps;
const float frame = (cache_file->override_frame ? cache_file->frame : time);
- return cache_file->is_sequence ? frame : frame / fps;
+ return cache_file->is_sequence ? frame : frame / fps - time_offset;
}
/* TODO(kevin): replace this with some depsgraph mechanism, or something similar. */
@@ -220,7 +232,6 @@ void BKE_cachefile_clean(Scene *scene, CacheFile *cache_file)
}
#endif
mcmd->reader = NULL;
- mcmd->object_path[0] = '\0';
}
}
@@ -238,7 +249,6 @@ void BKE_cachefile_clean(Scene *scene, CacheFile *cache_file)
}
#endif
data->reader = NULL;
- data->object_path[0] = '\0';
}
}
}
diff --git a/source/blender/blenkernel/intern/camera.c b/source/blender/blenkernel/intern/camera.c
index 9cb553aa27b..132cbd07ac3 100644
--- a/source/blender/blenkernel/intern/camera.c
+++ b/source/blender/blenkernel/intern/camera.c
@@ -47,7 +47,6 @@
#include "BKE_animsys.h"
#include "BKE_camera.h"
#include "BKE_object.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_library_remap.h"
@@ -86,22 +85,31 @@ void *BKE_camera_add(Main *bmain, const char *name)
{
Camera *cam;
- cam = BKE_libblock_alloc(bmain, ID_CA, name);
+ cam = BKE_libblock_alloc(bmain, ID_CA, name, 0);
BKE_camera_init(cam);
return cam;
}
-Camera *BKE_camera_copy(Main *bmain, Camera *cam)
+/**
+ * Only copy internal data of Camera ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_camera_copy_data(Main *UNUSED(bmain), Camera *UNUSED(cam_dst), const Camera *UNUSED(cam_src), const int UNUSED(flag))
{
- Camera *camn;
-
- camn = BKE_libblock_copy(bmain, &cam->id);
-
- BKE_id_copy_ensure_local(bmain, &cam->id, &camn->id);
+ /* Nothing to do! */
+}
- return camn;
+Camera *BKE_camera_copy(Main *bmain, const Camera *cam)
+{
+ Camera *cam_copy;
+ BKE_id_copy_ex(bmain, &cam->id, (ID **)&cam_copy, 0, false);
+ return cam_copy;
}
void BKE_camera_make_local(Main *bmain, Camera *cam, const bool lib_local)
diff --git a/source/blender/blenkernel/intern/cdderivedmesh.c b/source/blender/blenkernel/intern/cdderivedmesh.c
index 7042b46330b..1a34b71643f 100644
--- a/source/blender/blenkernel/intern/cdderivedmesh.c
+++ b/source/blender/blenkernel/intern/cdderivedmesh.c
@@ -34,10 +34,12 @@
* \ingroup bke
*/
+#include "atomic_ops.h"
+
#include "BLI_math.h"
#include "BLI_edgehash.h"
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BKE_pbvh.h"
#include "BKE_cdderivedmesh.h"
@@ -285,6 +287,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
ob->sculpt->cd_face_node_offset);
pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color);
+ pbvh_show_mask_set(cddm->pbvh, ob->sculpt->show_mask);
}
@@ -300,7 +303,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
cddm->pbvh = BKE_pbvh_new();
cddm->pbvh_draw = can_pbvh_draw(ob, dm);
- looptri = MEM_mallocN(sizeof(*looptri) * looptris_num, __func__);
+ looptri = MEM_malloc_arrayN(looptris_num, sizeof(*looptri), __func__);
BKE_mesh_recalc_looptri(
me->mloop, me->mpoly,
@@ -315,6 +318,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
looptri, looptris_num);
pbvh_show_diffuse_color_set(cddm->pbvh, ob->sculpt->show_diffuse_color);
+ pbvh_show_mask_set(cddm->pbvh, ob->sculpt->show_mask);
deformed = check_sculpt_object_deformed(ob, true);
@@ -324,7 +328,7 @@ static PBVH *cdDM_getPBVH(Object *ob, DerivedMesh *dm)
int totvert;
totvert = deformdm->getNumVerts(deformdm);
- vertCos = MEM_mallocN(totvert * sizeof(float[3]), "cdDM_getPBVH vertCos");
+ vertCos = MEM_malloc_arrayN(totvert, sizeof(float[3]), "cdDM_getPBVH vertCos");
deformdm->getVertCos(deformdm, vertCos);
BKE_pbvh_apply_vertCos(cddm->pbvh, vertCos);
MEM_freeN(vertCos);
@@ -660,6 +664,11 @@ static void cdDM_drawMappedFaces(
const int *index_mp_to_orig = dm->getPolyDataArray(dm, CD_ORIGINDEX);
+ if (cddm->pbvh) {
+ if (G.debug_value == 14)
+ BKE_pbvh_draw_BB(cddm->pbvh);
+ }
+
/* fist, setup common buffers */
GPU_vertex_setup(dm);
GPU_triangle_setup(dm);
@@ -1004,9 +1013,9 @@ static void cdDM_drawMappedFacesGLSL(
tot_active_mat = dm->drawObject->totmaterial;
- matconv = MEM_callocN(sizeof(*matconv) * tot_active_mat,
+ matconv = MEM_calloc_arrayN(tot_active_mat, sizeof(*matconv),
"cdDM_drawMappedFacesGLSL.matconv");
- mat_orig_to_new = MEM_mallocN(sizeof(*mat_orig_to_new) * dm->totmat,
+ mat_orig_to_new = MEM_malloc_arrayN(dm->totmat, sizeof(*mat_orig_to_new),
"cdDM_drawMappedFacesGLSL.mat_orig_to_new");
/* part one, check what attributes are needed per material */
@@ -1295,7 +1304,7 @@ static void cdDM_buffer_copy_triangles(
const MLoopTri *lt = dm->getLoopTriArray(dm);
const int totpoly = dm->getNumPolys(dm);
- FaceCount *fc = MEM_mallocN(sizeof(*fc) * gpu_totmat, "gpumaterial.facecount");
+ FaceCount *fc = MEM_malloc_arrayN(gpu_totmat, sizeof(*fc), "gpumaterial.facecount");
for (i = 0; i < gpu_totmat; i++) {
fc[i].i_visible = 0;
@@ -1476,7 +1485,7 @@ static void cdDM_buffer_copy_uv_texpaint(
/* should have been checked for before, reassert */
BLI_assert(DM_get_loop_data_layer(dm, CD_MLOOPUV));
- uv_base = MEM_mallocN(totmaterial * sizeof(*uv_base), "texslots");
+ uv_base = MEM_malloc_arrayN(totmaterial, sizeof(*uv_base), "texslots");
for (i = 0; i < totmaterial; i++) {
uv_base[i] = DM_paint_uvlayer_active_get(dm, i);
@@ -1518,8 +1527,8 @@ static void cdDM_buffer_copy_mcol(
for (i = 0; i < totpoly; i++, mpoly++) {
for (j = 0; j < mpoly->totloop; j++) {
- copy_v3_v3_uchar(&varray[start], &mloopcol[mpoly->loopstart + j].r);
- start += 3;
+ copy_v4_v4_uchar(&varray[start], &mloopcol[mpoly->loopstart + j].r);
+ start += 4;
}
}
}
@@ -1690,10 +1699,10 @@ static void cdDM_drawobject_init_vert_points(
int tot_loops = 0;
/* allocate the array and space for links */
- gdo->vert_points = MEM_mallocN(sizeof(GPUVertPointLink) * gdo->totvert,
+ gdo->vert_points = MEM_malloc_arrayN(gdo->totvert, sizeof(GPUVertPointLink),
"GPUDrawObject.vert_points");
#ifdef USE_GPU_POINT_LINK
- gdo->vert_points_mem = MEM_callocN(sizeof(GPUVertPointLink) * gdo->totvert,
+ gdo->vert_points_mem = MEM_calloc_arrayN(gdo->totvert, sizeof(GPUVertPointLink),
"GPUDrawObject.vert_points_mem");
gdo->vert_points_usage = 0;
#endif
@@ -1748,7 +1757,7 @@ static GPUDrawObject *cdDM_GPUobject_new(DerivedMesh *dm)
/* get the number of points used by each material, treating
* each quad as two triangles */
- mat_info = MEM_callocN(sizeof(*mat_info) * dm_totmat, "GPU_drawobject_new.mat_orig_to_new");
+ mat_info = MEM_calloc_arrayN(dm_totmat, sizeof(*mat_info), "GPU_drawobject_new.mat_orig_to_new");
for (i = 0; i < totpolys; i++) {
const short mat_nr = ME_MAT_NR_TEST(mpoly[i].mat_nr, dm_totmat);
@@ -1919,25 +1928,17 @@ void CDDM_recalc_looptri(DerivedMesh *dm)
const unsigned int totloop = dm->numLoopData;
DM_ensure_looptri_data(dm);
+ BLI_assert(totpoly == 0 || cddm->dm.looptris.array_wip != NULL);
BKE_mesh_recalc_looptri(
cddm->mloop, cddm->mpoly,
cddm->mvert,
totloop, totpoly,
- cddm->dm.looptris.array);
-}
+ cddm->dm.looptris.array_wip);
-static const MLoopTri *cdDM_getLoopTriArray(DerivedMesh *dm)
-{
- if (dm->looptris.array) {
- BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
- }
- else {
- dm->recalcLoopTri(dm);
-
- /* ccdm is an exception here, that recalcLoopTri will fill in the array too */
- }
- return dm->looptris.array;
+ BLI_assert(cddm->dm.looptris.array == NULL);
+ atomic_cas_ptr((void **)&cddm->dm.looptris.array, cddm->dm.looptris.array, cddm->dm.looptris.array_wip);
+ cddm->dm.looptris.array_wip = NULL;
}
static void cdDM_free_internal(CDDerivedMesh *cddm)
@@ -1990,8 +1991,6 @@ static CDDerivedMesh *cdDM_create(const char *desc)
dm->getEdgeDataArray = DM_get_edge_data_layer;
dm->getTessFaceDataArray = DM_get_tessface_data_layer;
- dm->getLoopTriArray = cdDM_getLoopTriArray;
-
dm->calcNormals = CDDM_calc_normals;
dm->calcLoopNormals = CDDM_calc_loop_normals;
dm->calcLoopNormalsSpaceArray = CDDM_calc_loop_normals_spacearr;
@@ -2605,7 +2604,7 @@ void CDDM_calc_normals_mapping_ex(DerivedMesh *dm, const bool only_face_normals)
}
#endif
- face_nors = MEM_mallocN(sizeof(*face_nors) * dm->numPolyData, "face_nors");
+ face_nors = MEM_malloc_arrayN(dm->numPolyData, sizeof(*face_nors), "face_nors");
/* calculate face normals */
BKE_mesh_calc_normals_poly(
@@ -2986,28 +2985,31 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
const int totvert_final = totvert - tot_vtargetmap;
- MVert *mv, *mvert = MEM_mallocN(sizeof(*mvert) * totvert_final, __func__);
- int *oldv = MEM_mallocN(sizeof(*oldv) * totvert_final, __func__);
- int *newv = MEM_mallocN(sizeof(*newv) * totvert, __func__);
+ MVert *mv, *mvert = MEM_malloc_arrayN(totvert_final, sizeof(*mvert), __func__);
+ int *oldv = MEM_malloc_arrayN(totvert_final, sizeof(*oldv), __func__);
+ int *newv = MEM_malloc_arrayN(totvert, sizeof(*newv), __func__);
STACK_DECLARE(mvert);
STACK_DECLARE(oldv);
- MEdge *med, *medge = MEM_mallocN(sizeof(*medge) * totedge, __func__);
- int *olde = MEM_mallocN(sizeof(*olde) * totedge, __func__);
- int *newe = MEM_mallocN(sizeof(*newe) * totedge, __func__);
+ /* Note: create (totedge + totloop) elements because partially invalid polys due to merge may require
+ * generating new edges, and while in 99% cases we'll still end with less final edges than totedge,
+ * cases can be forged that would end requiring more... */
+ MEdge *med, *medge = MEM_malloc_arrayN((totedge + totloop), sizeof(*medge), __func__);
+ int *olde = MEM_malloc_arrayN((totedge + totloop), sizeof(*olde), __func__);
+ int *newe = MEM_malloc_arrayN((totedge + totloop), sizeof(*newe), __func__);
STACK_DECLARE(medge);
STACK_DECLARE(olde);
- MLoop *ml, *mloop = MEM_mallocN(sizeof(*mloop) * totloop, __func__);
- int *oldl = MEM_mallocN(sizeof(*oldl) * totloop, __func__);
+ MLoop *ml, *mloop = MEM_malloc_arrayN(totloop, sizeof(*mloop), __func__);
+ int *oldl = MEM_malloc_arrayN(totloop, sizeof(*oldl), __func__);
#ifdef USE_LOOPS
- int newl = MEM_mallocN(sizeof(*newl) * totloop, __func__);
+ int *newl = MEM_malloc_arrayN(totloop, sizeof(*newl), __func__);
#endif
STACK_DECLARE(mloop);
STACK_DECLARE(oldl);
- MPoly *mp, *mpoly = MEM_mallocN(sizeof(*medge) * totpoly, __func__);
- int *oldp = MEM_mallocN(sizeof(*oldp) * totpoly, __func__);
+ MPoly *mp, *mpoly = MEM_malloc_arrayN(totpoly, sizeof(*medge), __func__);
+ int *oldp = MEM_malloc_arrayN(totpoly, sizeof(*oldp), __func__);
STACK_DECLARE(mpoly);
STACK_DECLARE(oldp);
@@ -3028,7 +3030,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
STACK_INIT(mloop, totloop);
STACK_INIT(mpoly, totpoly);
- /* fill newl with destination vertex indices */
+ /* fill newv with destination vertex indices */
mv = cddm->mvert;
c = 0;
for (i = 0; i < totvert; i++, mv++) {
@@ -3085,7 +3087,7 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
/* if the targets already make up a poly, in which case the new poly is dropped */
/* This poly equality check is rather complex. We use a BLI_ghash to speed it up with a first level check */
PolyKey *mpgh;
- poly_keys = MEM_mallocN(sizeof(PolyKey) * totpoly, __func__);
+ poly_keys = MEM_malloc_arrayN(totpoly, sizeof(PolyKey), __func__);
poly_gset = BLI_gset_new_ex(poly_gset_hash_fn, poly_gset_compare_fn, __func__, totpoly);
/* Duplicates allowed because our compare function is not pure equality */
BLI_gset_flag_set(poly_gset, GHASH_FLAG_ALLOW_DUPES);
@@ -3117,83 +3119,80 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
mp = cddm->mpoly;
+ mv = cddm->mvert;
for (i = 0; i < totpoly; i++, mp++) {
MPoly *mp_new;
ml = cddm->mloop + mp->loopstart;
/* check faces with all vertices merged */
- {
- bool all_vertices_merged = true;
+ bool all_vertices_merged = true;
- for (j = 0; j < mp->totloop; j++, ml++) {
- if (vtargetmap[ml->v] == -1) {
- all_vertices_merged = false;
- break;
- }
+ for (j = 0; j < mp->totloop; j++, ml++) {
+ if (vtargetmap[ml->v] == -1) {
+ all_vertices_merged = false;
+ /* This will be used to check for poly using several time the same vert. */
+ mv[ml->v].flag &= ~ME_VERT_TMP_TAG;
+ }
+ else {
+ /* This will be used to check for poly using several time the same vert. */
+ mv[vtargetmap[ml->v]].flag &= ~ME_VERT_TMP_TAG;
}
+ }
- if (UNLIKELY(all_vertices_merged)) {
- if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_MAPPED) {
- /* In this mode, all vertices merged is enough to dump face */
- continue;
+ if (UNLIKELY(all_vertices_merged)) {
+ if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_MAPPED) {
+ /* In this mode, all vertices merged is enough to dump face */
+ continue;
+ }
+ else if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_EQUAL) {
+ /* Additional condition for face dump: target vertices must make up an identical face */
+ /* The test has 2 steps: (1) first step is fast ghash lookup, but not failproof */
+ /* (2) second step is thorough but more costly poly compare */
+ int i_poly, v_target;
+ bool found = false;
+ PolyKey pkey;
+
+ /* Use poly_gset for fast (although not 100% certain) identification of same poly */
+ /* First, make up a poly_summary structure */
+ ml = cddm->mloop + mp->loopstart;
+ pkey.hash_sum = pkey.hash_xor = 0;
+ pkey.totloops = 0;
+ for (j = 0; j < mp->totloop; j++, ml++) {
+ v_target = vtargetmap[ml->v]; /* Cannot be -1, they are all mapped */
+ pkey.hash_sum += v_target;
+ pkey.hash_xor ^= v_target;
+ pkey.totloops++;
}
- else if (merge_mode == CDDM_MERGE_VERTS_DUMP_IF_EQUAL) {
- /* Additional condition for face dump: target vertices must make up an identical face */
- /* The test has 2 steps: (1) first step is fast ghash lookup, but not failproof */
- /* (2) second step is thorough but more costly poly compare */
- int i_poly, v_target, v_prev;
- bool found = false;
- PolyKey pkey;
-
- /* Use poly_gset for fast (although not 100% certain) identification of same poly */
- /* First, make up a poly_summary structure */
+ if (BLI_gset_haskey(poly_gset, &pkey)) {
+
+ /* There might be a poly that matches this one.
+ * We could just leave it there and say there is, and do a "continue".
+ * ... but we are checking whether there is an exact poly match.
+ * It's not so costly in terms of CPU since it's very rare, just a lot of complex code.
+ */
+
+ /* Consider current loop again */
ml = cddm->mloop + mp->loopstart;
- pkey.hash_sum = pkey.hash_xor = 0;
- pkey.totloops = 0;
- v_prev = vtargetmap[(ml + mp->totloop -1)->v]; /* since it loops around, the prev of first is the last */
- for (j = 0; j < mp->totloop; j++, ml++) {
- v_target = vtargetmap[ml->v]; /* Cannot be -1, they are all mapped */
- if (v_target == v_prev) {
- /* consecutive vertices in loop map to the same target: discard */
- /* but what about last to first ? */
- continue;
+ /* Consider the target of the loop's first vert */
+ v_target = vtargetmap[ml->v];
+ /* Now see if v_target belongs to a poly that shares all vertices with source poly,
+ * in same order, or reverse order */
+
+ for (i_poly = 0; i_poly < cddm->pmap[v_target].count; i_poly++) {
+ MPoly *target_poly = cddm->mpoly + *(cddm->pmap[v_target].indices + i_poly);
+
+ if (cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, +1) ||
+ cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, -1))
+ {
+ found = true;
+ break;
}
- pkey.hash_sum += v_target;
- pkey.hash_xor ^= v_target;
- pkey.totloops++;
- v_prev = v_target;
}
- if (BLI_gset_haskey(poly_gset, &pkey)) {
-
- /* There might be a poly that matches this one.
- * We could just leave it there and say there is, and do a "continue".
- * ... but we are checking whether there is an exact poly match.
- * It's not so costly in terms of CPU since it's very rare, just a lot of complex code.
- */
-
- /* Consider current loop again */
- ml = cddm->mloop + mp->loopstart;
- /* Consider the target of the loop's first vert */
- v_target = vtargetmap[ml->v];
- /* Now see if v_target belongs to a poly that shares all vertices with source poly,
- * in same order, or reverse order */
-
- for (i_poly = 0; i_poly < cddm->pmap[v_target].count; i_poly++) {
- MPoly *target_poly = cddm->mpoly + *(cddm->pmap[v_target].indices + i_poly);
-
- if (cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, +1) ||
- cddm_poly_compare(cddm->mloop, mp, target_poly, vtargetmap, -1))
- {
- found = true;
- break;
- }
- }
- if (found) {
- /* Current poly's vertices are mapped to a poly that is strictly identical */
- /* Current poly is dumped */
- continue;
- }
+ if (found) {
+ /* Current poly's vertices are mapped to a poly that is strictly identical */
+ /* Current poly is dumped */
+ continue;
}
}
}
@@ -3207,32 +3206,121 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
ml = cddm->mloop + mp->loopstart;
c = 0;
+ MLoop *last_valid_ml = NULL;
+ MLoop *first_valid_ml = NULL;
+ bool need_edge_from_last_valid_ml = false;
+ bool need_edge_to_first_valid_ml = false;
+ int created_edges = 0;
for (j = 0; j < mp->totloop; j++, ml++) {
- unsigned int v1, v2;
+ const uint mlv = (vtargetmap[ml->v] != -1) ? vtargetmap[ml->v] : ml->v;
+#ifndef NDEBUG
+ {
+ MLoop *next_ml = cddm->mloop + mp->loopstart + ((j + 1) % mp->totloop);
+ uint next_mlv = (vtargetmap[next_ml->v] != -1) ? vtargetmap[next_ml->v] : next_ml->v;
+ med = cddm->medge + ml->e;
+ uint v1 = (vtargetmap[med->v1] != -1) ? vtargetmap[med->v1] : med->v1;
+ uint v2 = (vtargetmap[med->v2] != -1) ? vtargetmap[med->v2] : med->v2;
+ BLI_assert((mlv == v1 && next_mlv == v2) || (mlv == v2 && next_mlv == v1));
+ }
+#endif
+ /* A loop is only valid if its matching edge is, and it's not reusing a vertex already used by this poly. */
+ if (LIKELY((newe[ml->e] != -1) && ((mv[mlv].flag & ME_VERT_TMP_TAG) == 0))) {
+ mv[mlv].flag |= ME_VERT_TMP_TAG;
+
+ if (UNLIKELY(last_valid_ml != NULL && need_edge_from_last_valid_ml)) {
+ /* We need to create a new edge between last valid loop and this one! */
+ void **val_p;
+
+ uint v1 = (vtargetmap[last_valid_ml->v] != -1) ? vtargetmap[last_valid_ml->v] : last_valid_ml->v;
+ uint v2 = mlv;
+ BLI_assert(v1 != v2);
+ if (BLI_edgehash_ensure_p(ehash, v1, v2, &val_p)) {
+ last_valid_ml->e = GET_INT_FROM_POINTER(*val_p);
+ }
+ else {
+ const int new_eidx = STACK_SIZE(medge);
+ STACK_PUSH(olde, olde[last_valid_ml->e]);
+ STACK_PUSH(medge, cddm->medge[last_valid_ml->e]);
+ medge[new_eidx].v1 = last_valid_ml->v;
+ medge[new_eidx].v2 = ml->v;
+ /* DO NOT change newe mapping, could break actual values due to some deleted original edges. */
+ *val_p = SET_INT_IN_POINTER(new_eidx);
+ created_edges++;
+
+ last_valid_ml->e = new_eidx;
+ }
+ need_edge_from_last_valid_ml = false;
+ }
- med = cddm->medge + ml->e;
- v1 = (vtargetmap[med->v1] != -1) ? vtargetmap[med->v1] : med->v1;
- v2 = (vtargetmap[med->v2] != -1) ? vtargetmap[med->v2] : med->v2;
- if (LIKELY(v1 != v2)) {
#ifdef USE_LOOPS
newl[j + mp->loopstart] = STACK_SIZE(mloop);
#endif
STACK_PUSH(oldl, j + mp->loopstart);
- STACK_PUSH(mloop, *ml);
+ last_valid_ml = STACK_PUSH_RET_PTR(mloop);
+ *last_valid_ml = *ml;
+ if (first_valid_ml == NULL) {
+ first_valid_ml = last_valid_ml;
+ }
c++;
+
+ /* We absolutely HAVE to handle edge index remapping here, otherwise potential newly created edges
+ * in that part of code make remapping later totally unreliable. */
+ BLI_assert(newe[ml->e] != -1);
+ last_valid_ml->e = newe[ml->e];
+ }
+ else {
+ if (last_valid_ml != NULL) {
+ need_edge_from_last_valid_ml = true;
+ }
+ else {
+ need_edge_to_first_valid_ml = true;
+ }
+ }
+ }
+ if (UNLIKELY(last_valid_ml != NULL && !ELEM(first_valid_ml, NULL, last_valid_ml) &&
+ (need_edge_to_first_valid_ml || need_edge_from_last_valid_ml)))
+ {
+ /* We need to create a new edge between last valid loop and first valid one! */
+ void **val_p;
+
+ uint v1 = (vtargetmap[last_valid_ml->v] != -1) ? vtargetmap[last_valid_ml->v] : last_valid_ml->v;
+ uint v2 = (vtargetmap[first_valid_ml->v] != -1) ? vtargetmap[first_valid_ml->v] : first_valid_ml->v;
+ BLI_assert(v1 != v2);
+ if (BLI_edgehash_ensure_p(ehash, v1, v2, &val_p)) {
+ last_valid_ml->e = GET_INT_FROM_POINTER(*val_p);
}
+ else {
+ const int new_eidx = STACK_SIZE(medge);
+ STACK_PUSH(olde, olde[last_valid_ml->e]);
+ STACK_PUSH(medge, cddm->medge[last_valid_ml->e]);
+ medge[new_eidx].v1 = last_valid_ml->v;
+ medge[new_eidx].v2 = first_valid_ml->v;
+ /* DO NOT change newe mapping, could break actual values due to some deleted original edges. */
+ *val_p = SET_INT_IN_POINTER(new_eidx);
+ created_edges++;
+
+ last_valid_ml->e = new_eidx;
+ }
+ need_edge_to_first_valid_ml = need_edge_from_last_valid_ml = false;
}
if (UNLIKELY(c == 0)) {
+ BLI_assert(created_edges == 0);
continue;
}
else if (UNLIKELY(c < 3)) {
STACK_DISCARD(oldl, c);
STACK_DISCARD(mloop, c);
+ if (created_edges > 0) {
+ for (j = STACK_SIZE(medge) - created_edges; j < STACK_SIZE(medge); j++) {
+ BLI_edgehash_remove(ehash, medge[j].v1, medge[j].v2, NULL);
+ }
+ STACK_DISCARD(olde, created_edges);
+ STACK_DISCARD(medge, created_edges);
+ }
continue;
}
-
mp_new = STACK_PUSH_RET_PTR(mpoly);
*mp_new = *mp;
mp_new->totloop = c;
@@ -3257,10 +3345,10 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
/*update edge indices and copy customdata*/
med = medge;
for (i = 0; i < cddm2->dm.numEdgeData; i++, med++) {
- if (newv[med->v1] != -1)
- med->v1 = newv[med->v1];
- if (newv[med->v2] != -1)
- med->v2 = newv[med->v2];
+ BLI_assert(newv[med->v1] != -1);
+ med->v1 = newv[med->v1];
+ BLI_assert(newv[med->v2] != -1);
+ med->v2 = newv[med->v2];
/* Can happen in case vtargetmap contains some double chains, we do not support that. */
BLI_assert(med->v1 != med->v2);
@@ -3271,11 +3359,10 @@ DerivedMesh *CDDM_merge_verts(DerivedMesh *dm, const int *vtargetmap, const int
/*update loop indices and copy customdata*/
ml = mloop;
for (i = 0; i < cddm2->dm.numLoopData; i++, ml++) {
- if (newe[ml->e] != -1)
- ml->e = newe[ml->e];
- if (newv[ml->v] != -1)
- ml->v = newv[ml->v];
-
+ /* Edge remapping has already be done in main loop handling part above. */
+ BLI_assert(newv[ml->v] != -1);
+ ml->v = newv[ml->v];
+
CustomData_copy_data(&dm->loopData, &cddm2->dm.loopData, oldl[i], i, 1);
}
@@ -3348,7 +3435,7 @@ void CDDM_calc_edges_tessface(DerivedMesh *dm)
}
}
- numEdges = BLI_edgeset_size(eh);
+ numEdges = BLI_edgeset_len(eh);
/* write new edges into a temporary CustomData */
CustomData_reset(&edgeData);
@@ -3417,7 +3504,7 @@ void CDDM_calc_edges(DerivedMesh *dm)
}
}
- numEdges = BLI_edgehash_size(eh);
+ numEdges = BLI_edgehash_len(eh);
/* write new edges into a temporary CustomData */
CustomData_reset(&edgeData);
diff --git a/source/blender/blenkernel/intern/cloth.c b/source/blender/blenkernel/intern/cloth.c
index 28ef3f6f248..9ae295e2e3b 100644
--- a/source/blender/blenkernel/intern/cloth.c
+++ b/source/blender/blenkernel/intern/cloth.c
@@ -456,7 +456,8 @@ void clothModifier_do(ClothModifierData *clmd, Scene *scene, Object *ob, Derived
cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe, can_simulate);
if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED ||
- (!can_simulate && cache_result == PTCACHE_READ_OLD)) {
+ (!can_simulate && cache_result == PTCACHE_READ_OLD))
+ {
BKE_cloth_solver_set_positions(clmd);
cloth_to_object (ob, clmd, vertexCos);
@@ -640,7 +641,7 @@ void cloth_free_modifier_extern(ClothModifierData *clmd )
**/
static void cloth_to_object (Object *ob, ClothModifierData *clmd, float (*vertexCos)[3])
{
- unsigned int i = 0;
+ unsigned int i = 0;
Cloth *cloth = clmd->clothObject;
if (clmd->clothObject) {
@@ -807,7 +808,6 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d
if ( !dm )
return 0;
- DM_ensure_looptri(dm);
cloth_from_mesh ( clmd, dm );
// create springs
@@ -869,12 +869,6 @@ static int cloth_from_object(Object *ob, ClothModifierData *clmd, DerivedMesh *d
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
BPH_cloth_solver_init(ob, clmd);
@@ -944,37 +938,6 @@ BLI_INLINE void spring_verts_ordered_set(ClothSpring *spring, int v0, int v1)
}
}
-// be careful: 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;
-}
-
static void cloth_free_edgelist(LinkNodePair *edgelist, unsigned int mvert_num)
{
if (edgelist) {
diff --git a/source/blender/blenkernel/intern/collision.c b/source/blender/blenkernel/intern/collision.c
index ee25be36855..65742df754e 100644
--- a/source/blender/blenkernel/intern/collision.c
+++ b/source/blender/blenkernel/intern/collision.c
@@ -36,7 +36,7 @@
#include "DNA_effect_types.h"
#include "DNA_group_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_scene_types.h"
#include "DNA_meshdata_types.h"
@@ -178,8 +178,8 @@ static void collision_compute_barycentric ( float pv[3], float p1[3], float p2[3
/* dot_v3v3 */
#define INPR(v1, v2) ( (v1)[0] * (v2)[0] + (v1)[1] * (v2)[1] + (v1)[2] * (v2)[2])
- double tempV1[3], tempV2[3], tempV4[3];
- double a, b, c, d, e, f;
+ double tempV1[3], tempV2[3], tempV4[3];
+ double a, b, c, d, e, f;
VECSUB ( tempV1, p1, p3 );
VECSUB ( tempV2, p2, p3 );
@@ -801,8 +801,8 @@ int cloth_bvh_objcollision(Object *ob, ClothModifierData *clmd, float step, floa
if ( cloth->bvhselftree ) {
// search for overlapping collision pairs
overlap = BLI_bvhtree_overlap(cloth->bvhselftree, cloth->bvhselftree, &result, NULL, NULL);
-
- // #pragma omp parallel for private(k, i, j) schedule(static)
+
+ /* Could be parallelized (using BLI_task)... */
for ( k = 0; k < result; k++ ) {
float temp[3];
float length = 0;
@@ -1147,9 +1147,10 @@ static CollPair *cloth_point_collision(
return collpair;
}
-static void cloth_points_objcollisions_nearcheck(ClothModifierData * clmd, CollisionModifierData *collmd,
- CollPair **collisions, CollPair **collisions_index,
- int numresult, BVHTreeOverlap *overlap, float epsilon, double dt)
+static void cloth_points_objcollisions_nearcheck(
+ ClothModifierData *clmd, CollisionModifierData *collmd,
+ CollPair **collisions, CollPair **collisions_index,
+ int numresult, BVHTreeOverlap *overlap, float epsilon, double dt)
{
int i;
@@ -1163,8 +1164,9 @@ static void cloth_points_objcollisions_nearcheck(ClothModifierData * clmd, Colli
}
}
-static int cloth_points_objcollisions_resolve(ClothModifierData * clmd, CollisionModifierData *collmd, PartDeflect *pd,
- CollPair *collisions, CollPair *collisions_index, float dt)
+static int cloth_points_objcollisions_resolve(
+ ClothModifierData *clmd, CollisionModifierData *collmd, PartDeflect *pd,
+ CollPair *collisions, CollPair *collisions_index, float dt)
{
Cloth *cloth = clmd->clothObject;
int i = 0, mvert_num = clmd->clothObject->mvert_num;
diff --git a/source/blender/blenkernel/intern/colorband.c b/source/blender/blenkernel/intern/colorband.c
new file mode 100644
index 00000000000..f72d4df725a
--- /dev/null
+++ b/source/blender/blenkernel/intern/colorband.c
@@ -0,0 +1,629 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenkernel/intern/colorband.c
+ * \ingroup bke
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+#include "BLI_math_color.h"
+#include "BLI_heap.h"
+
+#include "DNA_key_types.h"
+#include "DNA_texture_types.h"
+
+#include "BKE_colorband.h"
+#include "BKE_material.h"
+#include "BKE_key.h"
+
+void BKE_colorband_init(ColorBand *coba, bool rangetype)
+{
+ int a;
+
+ coba->data[0].pos = 0.0;
+ coba->data[1].pos = 1.0;
+
+ if (rangetype == 0) {
+ coba->data[0].r = 0.0;
+ coba->data[0].g = 0.0;
+ coba->data[0].b = 0.0;
+ coba->data[0].a = 0.0;
+
+ coba->data[1].r = 1.0;
+ coba->data[1].g = 1.0;
+ coba->data[1].b = 1.0;
+ coba->data[1].a = 1.0;
+ }
+ else {
+ coba->data[0].r = 0.0;
+ coba->data[0].g = 0.0;
+ coba->data[0].b = 0.0;
+ coba->data[0].a = 1.0;
+
+ coba->data[1].r = 1.0;
+ coba->data[1].g = 1.0;
+ coba->data[1].b = 1.0;
+ coba->data[1].a = 1.0;
+ }
+
+ for (a = 2; a < MAXCOLORBAND; a++) {
+ coba->data[a].r = 0.5;
+ coba->data[a].g = 0.5;
+ coba->data[a].b = 0.5;
+ coba->data[a].a = 1.0;
+ coba->data[a].pos = 0.5;
+ }
+
+ coba->tot = 2;
+ coba->color_mode = COLBAND_BLEND_RGB;
+}
+
+static void colorband_init_from_table_rgba_simple(
+ ColorBand *coba,
+ const float (*array)[4], const int array_len)
+{
+ /* No Re-sample, just de-duplicate. */
+ const float eps = (1.0f / 255.0f) + 1e-6f;
+ BLI_assert(array_len < MAXCOLORBAND);
+ int stops = min_ii(MAXCOLORBAND, array_len);
+ if (stops) {
+ const float step_size = 1.0f / (float)max_ii(stops - 1, 1);
+ int i_curr = -1;
+ for (int i_step = 0; i_step < stops; i_step++) {
+ if ((i_curr != -1) && compare_v4v4(&coba->data[i_curr].r, array[i_step], eps)) {
+ continue;
+ }
+ i_curr += 1;
+ copy_v4_v4(&coba->data[i_curr].r, array[i_step]);
+ coba->data[i_curr].pos = i_step * step_size;
+ coba->data[i_curr].cur = i_curr;
+ }
+ coba->tot = i_curr + 1;
+ coba->cur = 0;
+ }
+ else {
+ /* coba is empty, set 1 black stop */
+ zero_v3(&coba->data[0].r);
+ coba->data[0].a = 1.0f;
+ coba->cur = 0;
+ coba->tot = 1;
+ }
+}
+
+
+/* -------------------------------------------------------------------- */
+/** \name Color Ramp Re-Sample
+ *
+ * Local functions for #BKE_colorband_init_from_table_rgba
+ * \{ */
+
+/**
+ * Used for calculating which samples of a color-band to remove (when simplifying).
+ */
+struct ColorResampleElem {
+ struct ColorResampleElem *next, *prev;
+ HeapNode *node;
+ float rgba[4];
+ float pos;
+};
+
+/**
+ * Measure the 'area' of each channel and combine to use as a cost for this samples removal.
+ */
+static float color_sample_remove_cost(const struct ColorResampleElem *c)
+{
+ if (c->next == NULL || c->prev == NULL) {
+ return -1.0f;
+ }
+ float area = 0.0f;
+#if 0
+ float xy_prev[2], xy_curr[2], xy_next[2];
+ xy_prev[0] = c->prev->pos;
+ xy_curr[0] = c->pos;
+ xy_next[0] = c->next->pos;
+ for (int i = 0; i < 4; i++) {
+ xy_prev[1] = c->prev->rgba[i];
+ xy_curr[1] = c->rgba[i];
+ xy_next[1] = c->next->rgba[i];
+ area += fabsf(cross_tri_v2(xy_prev, xy_curr, xy_next));
+ }
+#else
+ /* Above logic, optimized (p: previous, c: current, n: next). */
+ const float xpc = c->prev->pos - c->pos;
+ const float xnc = c->next->pos - c->pos;
+ for (int i = 0; i < 4; i++) {
+ const float ycn = c->rgba[i] - c->next->rgba[i];
+ const float ypc = c->prev->rgba[i] - c->rgba[i];
+ area += fabsf((xpc * ycn) + (ypc * xnc));
+ }
+#endif
+ return area;
+}
+
+/* TODO(campbell): create BLI_math_filter? */
+static float filter_gauss(float x)
+{
+ const float gaussfac = 1.6f;
+ const float two_gaussfac2 = 2.0f * gaussfac * gaussfac;
+ x *= 3.0f * gaussfac;
+ return 1.0f / sqrtf((float)M_PI * two_gaussfac2) * expf(-x * x / two_gaussfac2);
+}
+
+static void colorband_init_from_table_rgba_resample(
+ ColorBand *coba,
+ const float (*array)[4], const int array_len,
+ bool filter_samples)
+{
+ BLI_assert(array_len >= 2);
+ const float eps_2x = ((1.0f / 255.0f) + 1e-6f);
+ struct ColorResampleElem *c, *carr = MEM_mallocN(sizeof(*carr) * array_len, __func__);
+ int carr_len = array_len;
+ c = carr;
+ {
+ const float step_size = 1.0f / (float)(array_len - 1);
+ for (int i = 0; i < array_len; i++, c++) {
+ copy_v4_v4(carr[i].rgba, array[i]);
+ c->next = c + 1;
+ c->prev = c - 1;
+ c->pos = i * step_size;
+ }
+ }
+ carr[0].prev = NULL;
+ carr[array_len - 1].next = NULL;
+
+ /* -2 to remove endpoints. */
+ Heap *heap = BLI_heap_new_ex(array_len - 2);
+ c = carr;
+ for (int i = 0; i < array_len; i++, c++) {
+ float cost = color_sample_remove_cost(c);
+ if (cost != -1.0f) {
+ c->node = BLI_heap_insert(heap, cost, c);
+ }
+ else {
+ c->node = NULL;
+ }
+ }
+
+ while ((carr_len > 1 && !BLI_heap_is_empty(heap)) &&
+ ((carr_len >= MAXCOLORBAND) || (BLI_heap_node_value(BLI_heap_top(heap)) <= eps_2x)))
+ {
+ c = BLI_heap_pop_min(heap);
+ struct ColorResampleElem *c_next = c->next, *c_prev = c->prev;
+ c_prev->next = c_next;
+ c_next->prev = c_prev;
+ /* Clear data (not essential, avoid confusion). */
+ c->prev = c->next = NULL;
+ c->node = NULL;
+
+ /* Update adjacent */
+ for (int i = 0; i < 2; i++) {
+ struct ColorResampleElem *c_other = i ? c_next : c_prev;
+ if (c_other->node != NULL) {
+ const float cost = color_sample_remove_cost(c_other);
+ if (cost != -1.0) {
+ BLI_heap_node_value_update(heap, c_other->node, cost);
+ }
+ else {
+ BLI_heap_remove(heap, c_other->node);
+ c_other->node = NULL;
+ }
+ }
+ }
+ carr_len -= 1;
+ }
+ BLI_heap_free(heap, NULL);
+
+ /* First member is never removed. */
+ int i = 0;
+ BLI_assert(carr_len < MAXCOLORBAND);
+ if (filter_samples == false) {
+ for (c = carr; c != NULL; c = c->next, i++) {
+ copy_v4_v4(&coba->data[i].r, c->rgba);
+ coba->data[i].pos = c->pos;
+ coba->data[i].cur = i;
+ }
+ }
+ else {
+ for (c = carr; c != NULL; c = c->next, i++) {
+ const int steps_prev = c->prev ? (c - c->prev) - 1 : 0;
+ const int steps_next = c->next ? (c->next - c) - 1 : 0;
+ if (steps_prev == 0 && steps_next == 0) {
+ copy_v4_v4(&coba->data[i].r, c->rgba);
+ }
+ else {
+ float rgba[4];
+ float rgba_accum = 1;
+ copy_v4_v4(rgba, c->rgba);
+
+ if (steps_prev) {
+ const float step_size = 1.0 / (float)(steps_prev + 1);
+ int j = steps_prev;
+ for (struct ColorResampleElem *c_other = c - 1; c_other != c->prev; c_other--, j--) {
+ const float step_pos = (float)j * step_size;
+ BLI_assert(step_pos > 0.0f && step_pos < 1.0f);
+ const float f = filter_gauss(step_pos);
+ madd_v4_v4fl(rgba, c_other->rgba, f);
+ rgba_accum += f;
+ }
+ }
+ if (steps_next) {
+ const float step_size = 1.0 / (float)(steps_next + 1);
+ int j = steps_next;
+ for (struct ColorResampleElem *c_other = c + 1; c_other != c->next; c_other++, j--) {
+ const float step_pos = (float)j * step_size;
+ BLI_assert(step_pos > 0.0f && step_pos < 1.0f);
+ const float f = filter_gauss(step_pos);
+ madd_v4_v4fl(rgba, c_other->rgba, f);
+ rgba_accum += f;
+ }
+ }
+
+ mul_v4_v4fl(&coba->data[i].r, rgba, 1.0f / rgba_accum);
+ }
+ coba->data[i].pos = c->pos;
+ coba->data[i].cur = i;
+ }
+ }
+ BLI_assert(i == carr_len);
+ coba->tot = i;
+ coba->cur = 0;
+
+ MEM_freeN(carr);
+}
+
+void BKE_colorband_init_from_table_rgba(
+ ColorBand *coba,
+ const float (*array)[4], const int array_len,
+ bool filter_samples)
+{
+ /* Note, we could use MAXCOLORBAND here, but results of re-sampling are nicer,
+ * avoid different behavior when limit is hit. */
+ if (array_len < 2) {
+ /* No Re-sample, just de-duplicate. */
+ colorband_init_from_table_rgba_simple(coba, array, array_len);
+ }
+ else {
+ /* Re-sample */
+ colorband_init_from_table_rgba_resample(coba, array, array_len, filter_samples);
+ }
+}
+
+/** \} */
+
+ColorBand *BKE_colorband_add(bool rangetype)
+{
+ ColorBand *coba;
+
+ coba = MEM_callocN(sizeof(ColorBand), "colorband");
+ BKE_colorband_init(coba, rangetype);
+
+ return coba;
+}
+
+/* ------------------------------------------------------------------------- */
+
+static float colorband_hue_interp(
+ const int ipotype_hue,
+ const float mfac, const float fac,
+ float h1, float h2)
+{
+ float h_interp;
+ int mode = 0;
+
+#define HUE_INTERP(h_a, h_b) ((mfac * (h_a)) + (fac * (h_b)))
+#define HUE_MOD(h) (((h) < 1.0f) ? (h) : (h) - 1.0f)
+
+ h1 = HUE_MOD(h1);
+ h2 = HUE_MOD(h2);
+
+ BLI_assert(h1 >= 0.0f && h1 < 1.0f);
+ BLI_assert(h2 >= 0.0f && h2 < 1.0f);
+
+ switch (ipotype_hue) {
+ case COLBAND_HUE_NEAR:
+ {
+ if ((h1 < h2) && (h2 - h1) > +0.5f) mode = 1;
+ else if ((h1 > h2) && (h2 - h1) < -0.5f) mode = 2;
+ else mode = 0;
+ break;
+ }
+ case COLBAND_HUE_FAR:
+ {
+ if ((h1 < h2) && (h2 - h1) < +0.5f) mode = 1;
+ else if ((h1 > h2) && (h2 - h1) > -0.5f) mode = 2;
+ else mode = 0;
+ break;
+ }
+ case COLBAND_HUE_CCW:
+ {
+ if (h1 > h2) mode = 2;
+ else mode = 0;
+ break;
+ }
+ case COLBAND_HUE_CW:
+ {
+ if (h1 < h2) mode = 1;
+ else mode = 0;
+ break;
+ }
+ }
+
+ switch (mode) {
+ case 0:
+ h_interp = HUE_INTERP(h1, h2);
+ break;
+ case 1:
+ h_interp = HUE_INTERP(h1 + 1.0f, h2);
+ h_interp = HUE_MOD(h_interp);
+ break;
+ case 2:
+ h_interp = HUE_INTERP(h1, h2 + 1.0f);
+ h_interp = HUE_MOD(h_interp);
+ break;
+ }
+
+ BLI_assert(h_interp >= 0.0f && h_interp < 1.0f);
+
+#undef HUE_INTERP
+#undef HUE_MOD
+
+ return h_interp;
+}
+
+bool BKE_colorband_evaluate(const ColorBand *coba, float in, float out[4])
+{
+ const CBData *cbd1, *cbd2, *cbd0, *cbd3;
+ float fac;
+ int ipotype;
+ int a;
+
+ if (coba == NULL || coba->tot == 0) return false;
+
+ cbd1 = coba->data;
+
+ ipotype = (coba->color_mode == COLBAND_BLEND_RGB) ? coba->ipotype : COLBAND_INTERP_LINEAR;
+
+ if (coba->tot == 1) {
+ out[0] = cbd1->r;
+ out[1] = cbd1->g;
+ out[2] = cbd1->b;
+ out[3] = cbd1->a;
+ }
+ else if ((in <= cbd1->pos) && ELEM(ipotype, COLBAND_INTERP_LINEAR, COLBAND_INTERP_EASE)) {
+ out[0] = cbd1->r;
+ out[1] = cbd1->g;
+ out[2] = cbd1->b;
+ out[3] = cbd1->a;
+ }
+ else {
+ CBData left, right;
+
+ /* we're looking for first pos > in */
+ for (a = 0; a < coba->tot; a++, cbd1++) {
+ if (cbd1->pos > in) {
+ break;
+ }
+ }
+
+ if (a == coba->tot) {
+ cbd2 = cbd1 - 1;
+ right = *cbd2;
+ right.pos = 1.0f;
+ cbd1 = &right;
+ }
+ else if (a == 0) {
+ left = *cbd1;
+ left.pos = 0.0f;
+ cbd2 = &left;
+ }
+ else {
+ cbd2 = cbd1 - 1;
+ }
+
+ if ((in >= cbd1->pos) && ELEM(ipotype, COLBAND_INTERP_LINEAR, COLBAND_INTERP_EASE)) {
+ out[0] = cbd1->r;
+ out[1] = cbd1->g;
+ out[2] = cbd1->b;
+ out[3] = cbd1->a;
+ }
+ else {
+
+ if (cbd2->pos != cbd1->pos) {
+ fac = (in - cbd1->pos) / (cbd2->pos - cbd1->pos);
+ }
+ else {
+ /* was setting to 0.0 in 2.56 & previous, but this
+ * is incorrect for the last element, see [#26732] */
+ fac = (a != coba->tot) ? 0.0f : 1.0f;
+ }
+
+ if (ipotype == COLBAND_INTERP_CONSTANT) {
+ /* constant */
+ out[0] = cbd2->r;
+ out[1] = cbd2->g;
+ out[2] = cbd2->b;
+ out[3] = cbd2->a;
+ }
+ else if (ipotype >= COLBAND_INTERP_B_SPLINE) {
+ /* ipo from right to left: 3 2 1 0 */
+ float t[4];
+
+ if (a >= coba->tot - 1) cbd0 = cbd1;
+ else cbd0 = cbd1 + 1;
+ if (a < 2) cbd3 = cbd2;
+ else cbd3 = cbd2 - 1;
+
+ CLAMP(fac, 0.0f, 1.0f);
+
+ if (ipotype == COLBAND_INTERP_CARDINAL) {
+ key_curve_position_weights(fac, t, KEY_CARDINAL);
+ }
+ else {
+ key_curve_position_weights(fac, t, KEY_BSPLINE);
+ }
+
+ out[0] = t[3] * cbd3->r + t[2] * cbd2->r + t[1] * cbd1->r + t[0] * cbd0->r;
+ out[1] = t[3] * cbd3->g + t[2] * cbd2->g + t[1] * cbd1->g + t[0] * cbd0->g;
+ out[2] = t[3] * cbd3->b + t[2] * cbd2->b + t[1] * cbd1->b + t[0] * cbd0->b;
+ out[3] = t[3] * cbd3->a + t[2] * cbd2->a + t[1] * cbd1->a + t[0] * cbd0->a;
+ CLAMP(out[0], 0.0f, 1.0f);
+ CLAMP(out[1], 0.0f, 1.0f);
+ CLAMP(out[2], 0.0f, 1.0f);
+ CLAMP(out[3], 0.0f, 1.0f);
+ }
+ else {
+ float mfac;
+
+ if (ipotype == COLBAND_INTERP_EASE) {
+ mfac = fac * fac;
+ fac = 3.0f * mfac - 2.0f * mfac * fac;
+ }
+
+ mfac = 1.0f - fac;
+
+ if (UNLIKELY(coba->color_mode == COLBAND_BLEND_HSV)) {
+ float col1[3], col2[3];
+
+ rgb_to_hsv_v(&cbd1->r, col1);
+ rgb_to_hsv_v(&cbd2->r, col2);
+
+ out[0] = colorband_hue_interp(coba->ipotype_hue, mfac, fac, col1[0], col2[0]);
+ out[1] = mfac * col1[1] + fac * col2[1];
+ out[2] = mfac * col1[2] + fac * col2[2];
+ out[3] = mfac * cbd1->a + fac * cbd2->a;
+
+ hsv_to_rgb_v(out, out);
+ }
+ else if (UNLIKELY(coba->color_mode == COLBAND_BLEND_HSL)) {
+ float col1[3], col2[3];
+
+ rgb_to_hsl_v(&cbd1->r, col1);
+ rgb_to_hsl_v(&cbd2->r, col2);
+
+ out[0] = colorband_hue_interp(coba->ipotype_hue, mfac, fac, col1[0], col2[0]);
+ out[1] = mfac * col1[1] + fac * col2[1];
+ out[2] = mfac * col1[2] + fac * col2[2];
+ out[3] = mfac * cbd1->a + fac * cbd2->a;
+
+ hsl_to_rgb_v(out, out);
+ }
+ else {
+ /* COLBAND_BLEND_RGB */
+ out[0] = mfac * cbd1->r + fac * cbd2->r;
+ out[1] = mfac * cbd1->g + fac * cbd2->g;
+ out[2] = mfac * cbd1->b + fac * cbd2->b;
+ out[3] = mfac * cbd1->a + fac * cbd2->a;
+ }
+ }
+ }
+ }
+ return true; /* OK */
+}
+
+void BKE_colorband_evaluate_table_rgba(const 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++)
+ BKE_colorband_evaluate(coba, (float)a / (float)CM_TABLE, &(*array)[a * 4]);
+}
+
+static int vergcband(const void *a1, const void *a2)
+{
+ const CBData *x1 = a1, *x2 = a2;
+
+ if (x1->pos > x2->pos) return 1;
+ else if (x1->pos < x2->pos) return -1;
+ return 0;
+}
+
+void BKE_colorband_update_sort(ColorBand *coba)
+{
+ int a;
+
+ if (coba->tot < 2)
+ return;
+
+ for (a = 0; a < coba->tot; a++)
+ coba->data[a].cur = a;
+
+ qsort(coba->data, coba->tot, sizeof(CBData), vergcband);
+
+ for (a = 0; a < coba->tot; a++) {
+ if (coba->data[a].cur == coba->cur) {
+ coba->cur = a;
+ break;
+ }
+ }
+}
+
+CBData *BKE_colorband_element_add(struct ColorBand *coba, float position)
+{
+ if (coba->tot == MAXCOLORBAND) {
+ return NULL;
+ }
+ else {
+ CBData *xnew;
+
+ xnew = &coba->data[coba->tot];
+ xnew->pos = position;
+
+ if (coba->tot != 0) {
+ BKE_colorband_evaluate(coba, position, &xnew->r);
+ }
+ else {
+ zero_v4(&xnew->r);
+ }
+ }
+
+ coba->tot++;
+ coba->cur = coba->tot - 1;
+
+ BKE_colorband_update_sort(coba);
+
+ return coba->data + coba->cur;
+}
+
+int BKE_colorband_element_remove(struct ColorBand *coba, int index)
+{
+ int a;
+
+ if (coba->tot < 2)
+ return 0;
+
+ if (index < 0 || index >= coba->tot)
+ return 0;
+
+ coba->tot--;
+ for (a = index; a < coba->tot; a++) {
+ coba->data[a] = coba->data[a + 1];
+ }
+ if (coba->cur) coba->cur--;
+ return 1;
+}
diff --git a/source/blender/blenkernel/intern/colortools.c b/source/blender/blenkernel/intern/colortools.c
index 4f3ffed41bc..e7fa4cee587 100644
--- a/source/blender/blenkernel/intern/colortools.c
+++ b/source/blender/blenkernel/intern/colortools.c
@@ -130,7 +130,7 @@ void curvemapping_free(CurveMapping *cumap)
}
}
-void curvemapping_copy_data(CurveMapping *target, CurveMapping *cumap)
+void curvemapping_copy_data(CurveMapping *target, const CurveMapping *cumap)
{
int a;
@@ -146,7 +146,7 @@ void curvemapping_copy_data(CurveMapping *target, CurveMapping *cumap)
}
}
-CurveMapping *curvemapping_copy(CurveMapping *cumap)
+CurveMapping *curvemapping_copy(const CurveMapping *cumap)
{
if (cumap) {
CurveMapping *cumapn = MEM_dupallocN(cumap);
@@ -508,7 +508,7 @@ static void calchandle_curvemap(
if ((bezt->h2 == HD_AUTO_ANIM) && next && prev) { /* keep horizontal if extrema */
const float ydiff1 = prev->vec[1][1] - bezt->vec[1][1];
const float ydiff2 = next->vec[1][1] - bezt->vec[1][1];
- if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f)||
+ if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f) ||
(ydiff1 >= 0.0f && ydiff2 >= 0.0f))
{
bezt->vec[2][1] = bezt->vec[1][1];
@@ -1034,7 +1034,7 @@ static void save_sample_line(Scopes *scopes, const int idx, const float fx, cons
float yuv[3];
/* vectorscope*/
- rgb_to_yuv(rgb[0], rgb[1], rgb[2], &yuv[0], &yuv[1], &yuv[2]);
+ rgb_to_yuv(rgb[0], rgb[1], rgb[2], &yuv[0], &yuv[1], &yuv[2], BLI_YUV_ITU_BT709);
scopes->vecscope[idx + 0] = yuv[1];
scopes->vecscope[idx + 1] = yuv[2];
@@ -1165,7 +1165,9 @@ typedef struct ScopesUpdateDataChunk {
float min[3], max[3];
} ScopesUpdateDataChunk;
-static void scopes_update_cb(void *userdata, void *userdata_chunk, const int y, const int UNUSED(threadid))
+static void scopes_update_cb(void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict tls)
{
const ScopesUpdateData *data = userdata;
@@ -1175,7 +1177,7 @@ static void scopes_update_cb(void *userdata, void *userdata_chunk, const int y,
const unsigned char *display_buffer = data->display_buffer;
const int ycc_mode = data->ycc_mode;
- ScopesUpdateDataChunk *data_chunk = userdata_chunk;
+ ScopesUpdateDataChunk *data_chunk = tls->userdata_chunk;
unsigned int *bin_lum = data_chunk->bin_lum;
unsigned int *bin_r = data_chunk->bin_r;
unsigned int *bin_g = data_chunk->bin_g;
@@ -1259,7 +1261,8 @@ static void scopes_update_cb(void *userdata, void *userdata_chunk, const int y,
}
}
-static void scopes_update_finalize(void *userdata, void *userdata_chunk)
+static void scopes_update_finalize(void *__restrict userdata,
+ void *__restrict userdata_chunk)
{
const ScopesUpdateData *data = userdata;
const ScopesUpdateDataChunk *data_chunk = userdata_chunk;
@@ -1380,15 +1383,23 @@ void scopes_update(Scopes *scopes, ImBuf *ibuf, const ColorManagedViewSettings *
/* Keep number of threads in sync with the merge parts below. */
ScopesUpdateData data = {
- .scopes = scopes, . ibuf = ibuf,
+ .scopes = scopes, .ibuf = ibuf,
.cm_processor = cm_processor, .display_buffer = display_buffer, .ycc_mode = ycc_mode,
.bin_lum = bin_lum, .bin_r = bin_r, .bin_g = bin_g, .bin_b = bin_b, .bin_a = bin_a,
};
ScopesUpdateDataChunk data_chunk = {{0}};
INIT_MINMAX(data_chunk.min, data_chunk.max);
- BLI_task_parallel_range_finalize(0, ibuf->y, &data, &data_chunk, sizeof(data_chunk),
- scopes_update_cb, scopes_update_finalize, ibuf->y > 256, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (ibuf->y > 256);
+ settings.userdata_chunk = &data_chunk;
+ settings.userdata_chunk_size = sizeof(data_chunk);
+ settings.func_finalize = scopes_update_finalize;
+ BLI_task_parallel_range(0, ibuf->y,
+ &data,
+ scopes_update_cb,
+ &settings);
/* test for nicer distribution even - non standard, leave it out for a while */
#if 0
diff --git a/source/blender/blenkernel/intern/constraint.c b/source/blender/blenkernel/intern/constraint.c
index 58ad171ee20..28e4af32a71 100644
--- a/source/blender/blenkernel/intern/constraint.c
+++ b/source/blender/blenkernel/intern/constraint.c
@@ -790,7 +790,7 @@ static void default_get_tarmat(bConstraint *con, bConstraintOb *UNUSED(cob), bCo
ct = ctn; \
} \
} (void)0
-
+
/* --------- ChildOf Constraint ------------ */
static void childof_new_data(void *cdata)
@@ -1018,6 +1018,9 @@ static void vectomat(const float vec[3], const float target_up[3], short axis, s
u[2] = 1;
}
+ /* note: even though 'n' is normalized, don't use 'project_v3_v3v3_normalized' below
+ * because precision issues cause a problem in near degenerate states, see: T53455. */
+
/* project the up vector onto the plane specified by n */
project_v3_v3v3(proj, u, n); /* first u onto n... */
sub_v3_v3v3(proj, u, proj); /* then onto the plane */
@@ -1923,14 +1926,15 @@ static void samevolume_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *
bSameVolumeConstraint *data = con->data;
float volume = data->volume;
- float fac = 1.0f;
+ float fac = 1.0f, total_scale;
float obsize[3];
mat4_to_size(obsize, cob->matrix);
/* calculate normalizing scale factor for non-essential values */
- if (obsize[data->flag] != 0)
- fac = sqrtf(volume / obsize[data->flag]) / obsize[data->flag];
+ total_scale = obsize[0] * obsize[1] * obsize[2];
+ if (total_scale != 0)
+ fac = sqrtf(volume / total_scale);
/* apply scaling factor to the channels not being kept */
switch (data->flag) {
@@ -2637,7 +2641,7 @@ static void distlimit_evaluate(bConstraint *con, bConstraintOb *cob, ListBase *t
/* 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)) {
-
+ /* pass */
}
}
}
@@ -4387,19 +4391,17 @@ static void transformcache_copy(bConstraint *con, bConstraint *srccon)
BLI_strncpy(dst->object_path, src->object_path, sizeof(dst->object_path));
dst->cache_file = src->cache_file;
- if (dst->cache_file) {
- id_us_plus(&dst->cache_file->id);
+#ifdef WITH_ALEMBIC
+ if (dst->reader) {
+ CacheReader_incref(dst->reader);
}
+#endif
}
static void transformcache_free(bConstraint *con)
{
bTransformCacheConstraint *data = con->data;
- if (data->cache_file) {
- id_us_min(&data->cache_file->id);
- }
-
if (data->reader) {
#ifdef WITH_ALEMBIC
CacheReader_free(data->reader);
@@ -4726,7 +4728,7 @@ void BKE_constraints_id_loop(ListBase *conlist, ConstraintIDFunc func, void *use
/* helper for BKE_constraints_copy(), to be used for making sure that ID's are valid */
static void con_extern_cb(bConstraint *UNUSED(con), ID **idpoin, bool UNUSED(is_reference), void *UNUSED(userData))
{
- if (*idpoin && ID_IS_LINKED_DATABLOCK(*idpoin))
+ if (*idpoin && ID_IS_LINKED(*idpoin))
id_lib_extern(*idpoin);
}
@@ -4739,29 +4741,30 @@ static void con_fix_copied_refs_cb(bConstraint *UNUSED(con), ID **idpoin, bool i
}
/* duplicate all of the constraints in a constraint stack */
-void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern)
+void BKE_constraints_copy_ex(ListBase *dst, const ListBase *src, const int flag, bool do_extern)
{
bConstraint *con, *srccon;
-
+
BLI_listbase_clear(dst);
BLI_duplicatelist(dst, src);
-
+
for (con = dst->first, srccon = src->first; con && srccon; srccon = srccon->next, con = con->next) {
const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
-
+
/* make a new copy of the constraint's data */
con->data = MEM_dupallocN(con->data);
-
+
/* only do specific constraints if required */
if (cti) {
/* perform custom copying operations if needed */
if (cti->copy_data)
cti->copy_data(con, srccon);
-
- /* fix usercounts for all referenced data in referenced data */
- if (cti->id_looper)
+
+ /* Fix usercounts for all referenced data that need it. */
+ if (cti->id_looper && (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
cti->id_looper(con, con_fix_copied_refs_cb, NULL);
-
+ }
+
/* for proxies we don't want to make extern */
if (do_extern) {
/* go over used ID-links for this constraint to ensure that they are valid for proxies */
@@ -4772,6 +4775,11 @@ void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern)
}
}
+void BKE_constraints_copy(ListBase *dst, const ListBase *src, bool do_extern)
+{
+ BKE_constraints_copy_ex(dst, src, 0, do_extern);
+}
+
/* ......... */
bConstraint *BKE_constraints_find_name(ListBase *list, const char *name)
diff --git a/source/blender/blenkernel/intern/curve.c b/source/blender/blenkernel/intern/curve.c
index 439abb1d593..943cab0a9fc 100644
--- a/source/blender/blenkernel/intern/curve.c
+++ b/source/blender/blenkernel/intern/curve.c
@@ -41,6 +41,7 @@
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
+#include "DNA_anim_types.h"
#include "DNA_curve_types.h"
#include "DNA_material_types.h"
@@ -64,6 +65,8 @@
#include "BKE_object.h"
#include "BKE_material.h"
+#include "DEG_depsgraph.h"
+
/* globals */
/* local */
@@ -165,12 +168,12 @@ void BKE_curve_init(Curve *cu)
if (cu->type == OB_FONT) {
cu->vfont = cu->vfontb = cu->vfonti = cu->vfontbi = BKE_vfont_builtin_get();
cu->vfont->id.us += 4;
- cu->str = MEM_mallocN(12, "str");
+ cu->str = MEM_malloc_arrayN(12, sizeof(unsigned char), "str");
BLI_strncpy(cu->str, "Text", 12);
cu->len = cu->len_wchar = cu->pos = 4;
- cu->strinfo = MEM_callocN(12 * sizeof(CharInfo), "strinfo new");
+ cu->strinfo = MEM_calloc_arrayN(12, sizeof(CharInfo), "strinfo new");
cu->totbox = cu->actbox = 1;
- cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "textbox");
+ cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "textbox");
cu->tb[0].w = cu->tb[0].h = 0.0;
}
}
@@ -179,7 +182,7 @@ Curve *BKE_curve_add(Main *bmain, const char *name, int type)
{
Curve *cu;
- cu = BKE_libblock_alloc(bmain, ID_CU, name);
+ cu = BKE_libblock_alloc(bmain, ID_CU, name, 0);
cu->type = type;
BKE_curve_init(cu);
@@ -187,42 +190,39 @@ Curve *BKE_curve_add(Main *bmain, const char *name, int type)
return cu;
}
-Curve *BKE_curve_copy(Main *bmain, Curve *cu)
+/**
+ * Only copy internal data of Curve ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_curve_copy_data(Main *bmain, Curve *cu_dst, const Curve *cu_src, const int flag)
{
- Curve *cun;
- int a;
+ BLI_listbase_clear(&cu_dst->nurb);
+ BKE_nurbList_duplicate(&(cu_dst->nurb), &(cu_src->nurb));
- cun = BKE_libblock_copy(bmain, &cu->id);
+ cu_dst->mat = MEM_dupallocN(cu_src->mat);
- BLI_listbase_clear(&cun->nurb);
- BKE_nurbList_duplicate(&(cun->nurb), &(cu->nurb));
+ cu_dst->str = MEM_dupallocN(cu_src->str);
+ cu_dst->strinfo = MEM_dupallocN(cu_src->strinfo);
+ cu_dst->tb = MEM_dupallocN(cu_src->tb);
+ cu_dst->bb = MEM_dupallocN(cu_src->bb);
- cun->mat = MEM_dupallocN(cu->mat);
- for (a = 0; a < cun->totcol; a++) {
- id_us_plus((ID *)cun->mat[a]);
+ if (cu_src->key) {
+ BKE_id_copy_ex(bmain, &cu_src->key->id, (ID **)&cu_dst->key, flag, false);
}
- cun->str = MEM_dupallocN(cu->str);
- cun->strinfo = MEM_dupallocN(cu->strinfo);
- cun->tb = MEM_dupallocN(cu->tb);
- cun->bb = MEM_dupallocN(cu->bb);
-
- if (cu->key) {
- cun->key = BKE_key_copy(bmain, cu->key);
- cun->key->from = (ID *)cun;
- }
-
- cun->editnurb = NULL;
- cun->editfont = NULL;
-
- id_us_plus((ID *)cun->vfont);
- id_us_plus((ID *)cun->vfontb);
- id_us_plus((ID *)cun->vfonti);
- id_us_plus((ID *)cun->vfontbi);
-
- BKE_id_copy_ensure_local(bmain, &cu->id, &cun->id);
+ cu_dst->editnurb = NULL;
+ cu_dst->editfont = NULL;
+}
- return cun;
+Curve *BKE_curve_copy(Main *bmain, const Curve *cu)
+{
+ Curve *cu_copy;
+ BKE_id_copy_ex(bmain, &cu->id, (ID **)&cu_copy, 0, false);
+ return cu_copy;
}
void BKE_curve_make_local(Main *bmain, Curve *cu, const bool lib_local)
@@ -468,7 +468,7 @@ void BKE_nurbList_free(ListBase *lb)
BLI_listbase_clear(lb);
}
-Nurb *BKE_nurb_duplicate(Nurb *nu)
+Nurb *BKE_nurb_duplicate(const Nurb *nu)
{
Nurb *newnu;
int len;
@@ -479,13 +479,13 @@ Nurb *BKE_nurb_duplicate(Nurb *nu)
if (nu->bezt) {
newnu->bezt =
- (BezTriple *)MEM_mallocN((nu->pntsu) * sizeof(BezTriple), "duplicateNurb2");
+ (BezTriple *)MEM_malloc_arrayN(nu->pntsu, sizeof(BezTriple), "duplicateNurb2");
memcpy(newnu->bezt, nu->bezt, nu->pntsu * sizeof(BezTriple));
}
else {
len = nu->pntsu * nu->pntsv;
newnu->bp =
- (BPoint *)MEM_mallocN((len) * sizeof(BPoint), "duplicateNurb3");
+ (BPoint *)MEM_malloc_arrayN(len, sizeof(BPoint), "duplicateNurb3");
memcpy(newnu->bp, nu->bp, len * sizeof(BPoint));
newnu->knotsu = newnu->knotsv = NULL;
@@ -493,14 +493,14 @@ Nurb *BKE_nurb_duplicate(Nurb *nu)
if (nu->knotsu) {
len = KNOTSU(nu);
if (len) {
- newnu->knotsu = MEM_mallocN(len * sizeof(float), "duplicateNurb4");
+ newnu->knotsu = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb4");
memcpy(newnu->knotsu, nu->knotsu, sizeof(float) * len);
}
}
if (nu->pntsv > 1 && nu->knotsv) {
len = KNOTSV(nu);
if (len) {
- newnu->knotsv = MEM_mallocN(len * sizeof(float), "duplicateNurb5");
+ newnu->knotsv = MEM_malloc_arrayN(len, sizeof(float), "duplicateNurb5");
memcpy(newnu->knotsv, nu->knotsv, sizeof(float) * len);
}
}
@@ -523,16 +523,16 @@ Nurb *BKE_nurb_copy(Nurb *src, int pntsu, int pntsv)
newnu->knotsv = NULL;
if (src->bezt) {
- newnu->bezt = (BezTriple *)MEM_mallocN(pntsu * pntsv * sizeof(BezTriple), "copyNurb2");
+ newnu->bezt = (BezTriple *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BezTriple), "copyNurb2");
}
else {
- newnu->bp = (BPoint *)MEM_mallocN(pntsu * pntsv * sizeof(BPoint), "copyNurb3");
+ newnu->bp = (BPoint *)MEM_malloc_arrayN(pntsu * pntsv, sizeof(BPoint), "copyNurb3");
}
return newnu;
}
-void BKE_nurbList_duplicate(ListBase *lb1, ListBase *lb2)
+void BKE_nurbList_duplicate(ListBase *lb1, const ListBase *lb2)
{
Nurb *nu, *nun;
@@ -744,6 +744,7 @@ BezTriple *BKE_nurb_bezt_get_prev(Nurb *nu, BezTriple *bezt)
BezTriple *bezt_prev;
BLI_assert(ARRAY_HAS_ITEM(bezt, nu->bezt, nu->pntsu));
+ BLI_assert(nu->pntsv <= 1);
if (bezt == nu->bezt) {
if (nu->flagu & CU_NURB_CYCLIC) {
@@ -765,6 +766,7 @@ BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp)
BPoint *bp_prev;
BLI_assert(ARRAY_HAS_ITEM(bp, nu->bp, nu->pntsu));
+ BLI_assert(nu->pntsv == 1);
if (bp == nu->bp) {
if (nu->flagu & CU_NURB_CYCLIC) {
@@ -781,7 +783,7 @@ BPoint *BKE_nurb_bpoint_get_prev(Nurb *nu, BPoint *bp)
return bp_prev;
}
-void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), struct BezTriple *bezt, float r_normal[3])
+void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), BezTriple *bezt, float r_normal[3])
{
/* calculate the axis matrix from the spline */
float dir_prev[3], dir_next[3];
@@ -796,7 +798,7 @@ void BKE_nurb_bezt_calc_normal(struct Nurb *UNUSED(nu), struct BezTriple *bezt,
normalize_v3(r_normal);
}
-void BKE_nurb_bezt_calc_plane(struct Nurb *nu, struct BezTriple *bezt, float r_plane[3])
+void BKE_nurb_bezt_calc_plane(struct Nurb *nu, BezTriple *bezt, float r_plane[3])
{
float dir_prev[3], dir_next[3];
@@ -833,7 +835,7 @@ void BKE_nurb_bezt_calc_plane(struct Nurb *nu, struct BezTriple *bezt, float r_p
normalize_v3(r_plane);
}
-void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, struct BPoint *bp, float r_normal[3])
+void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, BPoint *bp, float r_normal[3])
{
BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
@@ -856,6 +858,34 @@ void BKE_nurb_bpoint_calc_normal(struct Nurb *nu, struct BPoint *bp, float r_nor
normalize_v3(r_normal);
}
+void BKE_nurb_bpoint_calc_plane(struct Nurb *nu, BPoint *bp, float r_plane[3])
+{
+ BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
+ BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
+
+ float dir_prev[3] = {0.0f}, dir_next[3] = {0.0f};
+
+ if (bp_prev) {
+ sub_v3_v3v3(dir_prev, bp_prev->vec, bp->vec);
+ normalize_v3(dir_prev);
+ }
+ if (bp_next) {
+ sub_v3_v3v3(dir_next, bp->vec, bp_next->vec);
+ normalize_v3(dir_next);
+ }
+ cross_v3_v3v3(r_plane, dir_prev, dir_next);
+
+ /* matches with bones more closely */
+ {
+ float dir_mid[3], tvec[3];
+ add_v3_v3v3(dir_mid, dir_prev, dir_next);
+ cross_v3_v3v3(tvec, r_plane, dir_mid);
+ copy_v3_v3(r_plane, tvec);
+ }
+
+ normalize_v3(r_plane);
+}
+
/* ~~~~~~~~~~~~~~~~~~~~Non Uniform Rational B Spline calculations ~~~~~~~~~~~ */
@@ -943,7 +973,7 @@ static void makeknots(Nurb *nu, short uv)
if (nu->knotsu)
MEM_freeN(nu->knotsu);
if (BKE_nurb_check_valid_u(nu)) {
- nu->knotsu = MEM_callocN(4 + sizeof(float) * KNOTSU(nu), "makeknots");
+ nu->knotsu = MEM_calloc_arrayN(KNOTSU(nu) + 1, sizeof(float), "makeknots");
if (nu->flagu & CU_NURB_CYCLIC) {
calcknots(nu->knotsu, nu->pntsu, nu->orderu, 0); /* cyclic should be uniform */
makecyclicknots(nu->knotsu, nu->pntsu, nu->orderu);
@@ -959,7 +989,7 @@ static void makeknots(Nurb *nu, short uv)
if (nu->knotsv)
MEM_freeN(nu->knotsv);
if (BKE_nurb_check_valid_v(nu)) {
- nu->knotsv = MEM_callocN(4 + sizeof(float) * KNOTSV(nu), "makeknots");
+ nu->knotsv = MEM_calloc_arrayN(KNOTSV(nu) + 1, sizeof(float), "makeknots");
if (nu->flagv & CU_NURB_CYCLIC) {
calcknots(nu->knotsv, nu->pntsv, nu->orderv, 0); /* cyclic should be uniform */
makecyclicknots(nu->knotsv, nu->pntsv, nu->orderv);
@@ -1076,7 +1106,7 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
if (len == 0)
return;
- sum = (float *)MEM_callocN(sizeof(float) * len, "makeNurbfaces1");
+ sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbfaces1");
bp = nu->bp;
i = nu->pntsu * nu->pntsv;
@@ -1097,7 +1127,7 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
uend = fp[nu->pntsu];
ustep = (uend - ustart) / ((nu->flagu & CU_NURB_CYCLIC) ? totu : totu - 1);
- basisu = (float *)MEM_mallocN(sizeof(float) * KNOTSU(nu), "makeNurbfaces3");
+ basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbfaces3");
fp = nu->knotsv;
vstart = fp[nu->orderv - 1];
@@ -1109,9 +1139,9 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
vstep = (vend - vstart) / ((nu->flagv & CU_NURB_CYCLIC) ? totv : totv - 1);
len = KNOTSV(nu);
- 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");
+ basisv = (float *)MEM_malloc_arrayN(len * totv, sizeof(float), "makeNurbfaces3");
+ jstart = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces4");
+ jend = (int *)MEM_malloc_arrayN(totv, sizeof(float), "makeNurbfaces5");
/* precalculation of basisv and jstart, jend */
if (nu->flagv & CU_NURB_CYCLIC)
@@ -1210,8 +1240,9 @@ void BKE_nurb_makeFaces(Nurb *nu, float *coord_array, int rowstride, int resolu,
basis += KNOTSV(nu);
}
u += ustep;
- if (rowstride != 0)
- in = (float *) (((unsigned char *) in) + (rowstride - 3 * totv * sizeof(*in)));
+ if (rowstride != 0) {
+ in = (float *)(((unsigned char *)in) + (rowstride - 3 * totv * sizeof(*in)));
+ }
}
/* free */
@@ -1248,7 +1279,7 @@ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *
len = nu->pntsu;
if (len == 0)
return;
- sum = (float *)MEM_callocN(sizeof(float) * len, "makeNurbcurve1");
+ sum = (float *)MEM_calloc_arrayN(len, sizeof(float), "makeNurbcurve1");
resolu = (resolu * SEGMENTSU(nu));
@@ -1265,7 +1296,7 @@ void BKE_nurb_makeCurve(Nurb *nu, float *coord_array, float *tilt_array, float *
uend = fp[nu->pntsu];
ustep = (uend - ustart) / (resolu - ((nu->flagu & CU_NURB_CYCLIC) ? 0 : 1));
- basisu = (float *)MEM_mallocN(sizeof(float) * KNOTSU(nu), "makeNurbcurve3");
+ basisu = (float *)MEM_malloc_arrayN(KNOTSU(nu), sizeof(float), "makeNurbcurve3");
if (nu->flagu & CU_NURB_CYCLIC)
cycl = nu->orderu - 1;
@@ -1516,7 +1547,7 @@ float *BKE_curve_surf_make_orco(Object *ob)
nu = nu->next;
}
/* makeNurbfaces wants zeros */
- fp = coord_array = MEM_callocN(3 * sizeof(float) * tot, "make_orco");
+ fp = coord_array = MEM_calloc_arrayN(tot, 3 * sizeof(float), "make_orco");
nu = cu->nurb.first;
while (nu) {
@@ -1627,7 +1658,7 @@ float *BKE_curve_make_orco(Scene *scene, Object *ob, int *r_numVerts)
if (r_numVerts)
*r_numVerts = numVerts;
- fp = coord_array = MEM_mallocN(3 * sizeof(float) * numVerts, "cu_orco");
+ fp = coord_array = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "cu_orco");
for (dl = disp.first; dl; dl = dl->next) {
if (dl->type == DL_INDEX3) {
for (u = 0; u < dl->nr; u++, fp += 3) {
@@ -1654,7 +1685,7 @@ float *BKE_curve_make_orco(Scene *scene, Object *ob, int *r_numVerts)
if (dl->flag & DL_CYCL_V)
sizev++;
}
- else if (dl->flag & DL_CYCL_V) {
+ else if (dl->flag & DL_CYCL_V) {
sizev++;
}
@@ -1730,7 +1761,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
if (ELEM(dl->type, DL_POLY, DL_SEGM)) {
dlnew = MEM_mallocN(sizeof(DispList), "makebevelcurve1");
*dlnew = *dl;
- dlnew->verts = MEM_mallocN(3 * sizeof(float) * dl->parts * dl->nr, "makebevelcurve1");
+ dlnew->verts = MEM_malloc_arrayN(dl->parts * dl->nr, 3 * sizeof(float), "makebevelcurve1");
memcpy(dlnew->verts, dl->verts, 3 * sizeof(float) * dl->parts * dl->nr);
if (dlnew->type == DL_SEGM)
@@ -1757,7 +1788,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
}
else if (cu->ext2 == 0.0f) {
dl = MEM_callocN(sizeof(DispList), "makebevelcurve2");
- dl->verts = MEM_mallocN(2 * sizeof(float[3]), "makebevelcurve2");
+ dl->verts = MEM_malloc_arrayN(2, sizeof(float[3]), "makebevelcurve2");
BLI_addtail(disp, dl);
dl->type = DL_SEGM;
dl->parts = 1;
@@ -1770,11 +1801,11 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
fp[3] = fp[4] = 0.0;
fp[5] = cu->ext1;
}
- else if ( (cu->flag & (CU_FRONT | CU_BACK)) == 0 && cu->ext1 == 0.0f) { // we make a full round bevel in that case
+ else if ((cu->flag & (CU_FRONT | CU_BACK)) == 0 && cu->ext1 == 0.0f) { /* we make a full round bevel in that case */
nr = 4 + 2 * cu->bevresol;
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
- dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p1");
+ dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
BLI_addtail(disp, dl);
dl->type = DL_POLY;
dl->parts = 1;
@@ -1802,11 +1833,11 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
if ((cu->flag & CU_BACK) || !(cu->flag & CU_FRONT)) {
dnr = nr = 2 + cu->bevresol;
- if ( (cu->flag & (CU_FRONT | CU_BACK)) == 0)
+ if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
nr = 3 + 2 * cu->bevresol;
-
+ }
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p1");
- dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p1");
+ dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p1");
BLI_addtail(disp, dl);
dl->type = DL_SEGM;
dl->parts = 1;
@@ -1832,7 +1863,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
nr = 2;
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p2");
- dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p2");
+ dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p2");
BLI_addtail(disp, dl);
dl->type = DL_SEGM;
dl->parts = 1;
@@ -1844,7 +1875,7 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
fp[4] = cu->ext2;
fp[5] = cu->ext1;
- if ( (cu->flag & (CU_FRONT | CU_BACK)) == 0) {
+ if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
dl = MEM_dupallocN(dl);
dl->verts = MEM_dupallocN(dl->verts);
BLI_addtail(disp, dl);
@@ -1860,11 +1891,11 @@ void BKE_curve_bevel_make(Scene *scene, Object *ob, ListBase *disp,
/* part 3, front */
if ((cu->flag & CU_FRONT) || !(cu->flag & CU_BACK)) {
dnr = nr = 2 + cu->bevresol;
- if ( (cu->flag & (CU_FRONT | CU_BACK)) == 0)
+ if ((cu->flag & (CU_FRONT | CU_BACK)) == 0) {
nr = 3 + 2 * cu->bevresol;
-
+ }
dl = MEM_callocN(sizeof(DispList), "makebevelcurve p3");
- dl->verts = MEM_mallocN(nr * sizeof(float[3]), "makebevelcurve p3");
+ dl->verts = MEM_malloc_arrayN(nr, sizeof(float[3]), "makebevelcurve p3");
BLI_addtail(disp, dl);
dl->type = DL_SEGM;
dl->flag = DL_FRONT_CURVE;
@@ -2080,7 +2111,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
if (tilt_array) {
if (nu->tilt_interp == KEY_CU_EASE) { /* May as well support for tilt also 2.47 ease interp */
*tilt_array = prevbezt->alfa +
- (bezt->alfa - prevbezt->alfa) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
+ (bezt->alfa - prevbezt->alfa) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
}
else {
key_curve_position_weights(fac, t, nu->tilt_interp);
@@ -2096,7 +2127,7 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
* Note! - this only takes the 2 points into account,
* giving much more localized results to changes in radius, sometimes you want that */
*radius_array = prevbezt->radius +
- (bezt->radius - prevbezt->radius) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
+ (bezt->radius - prevbezt->radius) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
}
else {
@@ -2104,8 +2135,9 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
if (tilt_array == NULL || nu->tilt_interp != nu->radius_interp) {
key_curve_position_weights(fac, t, nu->radius_interp);
}
- *radius_array = t[0] * pprev->radius + t[1] * prevbezt->radius +
- t[2] * bezt->radius + t[3] * next->radius;
+ *radius_array =
+ t[0] * pprev->radius + t[1] * prevbezt->radius +
+ t[2] * bezt->radius + t[3] * next->radius;
}
radius_array = POINTER_OFFSET(radius_array, stride);
@@ -2113,8 +2145,9 @@ static void alfa_bezpart(BezTriple *prevbezt, BezTriple *bezt, Nurb *nu, float *
if (weight_array) {
/* basic interpolation for now, could copy tilt interp too */
- *weight_array = prevbezt->weight +
- (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
+ *weight_array =
+ prevbezt->weight +
+ (bezt->weight - prevbezt->weight) * (3.0f * fac * fac - 2.0f * fac * fac * fac);
weight_array = POINTER_OFFSET(weight_array, stride);
}
@@ -2592,6 +2625,9 @@ void BKE_curve_bevelList_free(ListBase *bev)
if (bl->segbevcount != NULL) {
MEM_freeN(bl->segbevcount);
}
+ if (bl->bevpoints != NULL) {
+ MEM_freeN(bl->bevpoints);
+ }
MEM_freeN(bl);
}
@@ -2656,7 +2692,8 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* 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 (!BKE_nurb_check_valid_u(nu)) {
- bl = MEM_callocN(sizeof(BevList) + 1 * sizeof(BevPoint), "makeBevelList1");
+ bl = MEM_callocN(sizeof(BevList), "makeBevelList1");
+ bl->bevpoints = MEM_calloc_arrayN(1, sizeof(BevPoint), "makeBevelPoints1");
BLI_addtail(bev, bl);
bl->nr = 0;
bl->charidx = nu->charidx;
@@ -2673,10 +2710,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
if (nu->type == CU_POLY) {
len = nu->pntsu;
- bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelList2");
+ bl = MEM_callocN(sizeof(BevList), "makeBevelList2");
+ bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints2");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
- bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelList2_seglen");
- bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelList2_segbevcount");
+ bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList2_seglen");
+ bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList2_segbevcount");
}
BLI_addtail(bev, bl);
@@ -2719,10 +2757,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* in case last point is not cyclic */
len = segcount * resolu + 1;
- bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelBPoints");
+ bl = MEM_callocN(sizeof(BevList), "makeBevelBPoints");
+ bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelBPointsPoints");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
- bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelBPoints_seglen");
- bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelBPoints_segbevcount");
+ bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelBPoints_seglen");
+ bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelBPoints_segbevcount");
}
BLI_addtail(bev, bl);
@@ -2855,10 +2894,11 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
if (nu->pntsv == 1) {
len = (resolu * segcount);
- bl = MEM_callocN(sizeof(BevList) + len * sizeof(BevPoint), "makeBevelList3");
+ bl = MEM_callocN(sizeof(BevList), "makeBevelList3");
+ bl->bevpoints = MEM_calloc_arrayN(len, sizeof(BevPoint), "makeBevelPoints3");
if (need_seglen && (nu->flagu & CU_NURB_CYCLIC) == 0) {
- bl->seglen = MEM_mallocN(segcount * sizeof(float), "makeBevelList3_seglen");
- bl->segbevcount = MEM_mallocN(segcount * sizeof(int), "makeBevelList3_segbevcount");
+ bl->seglen = MEM_malloc_arrayN(segcount, sizeof(float), "makeBevelList3_seglen");
+ bl->segbevcount = MEM_malloc_arrayN(segcount, sizeof(int), "makeBevelList3_segbevcount");
}
BLI_addtail(bev, bl);
bl->nr = len;
@@ -2953,8 +2993,13 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
blnext = bl->next;
if (bl->nr && bl->dupe_nr) {
nr = bl->nr - bl->dupe_nr + 1; /* +1 because vectorbezier sets flag too */
- blnew = MEM_mallocN(sizeof(BevList) + nr * sizeof(BevPoint), "makeBevelList4");
+ blnew = MEM_callocN(sizeof(BevList), "makeBevelList4");
memcpy(blnew, bl, sizeof(BevList));
+ blnew->bevpoints = MEM_calloc_arrayN(nr, sizeof(BevPoint), "makeBevelPoints4");
+ if (!blnew->bevpoints) {
+ MEM_freeN(blnew);
+ break;
+ }
blnew->segbevcount = bl->segbevcount;
blnew->seglen = bl->seglen;
blnew->nr = 0;
@@ -2971,6 +3016,9 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
}
bevp0++;
}
+ if (bl->bevpoints != NULL) {
+ MEM_freeN(bl->bevpoints);
+ }
MEM_freeN(bl);
blnew->dupe_nr = 0;
}
@@ -2991,7 +3039,7 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
/* find extreme left points, also test (turning) direction */
if (poly > 0) {
- sd = sortdata = MEM_mallocN(sizeof(struct BevelSort) * poly, "makeBevelList5");
+ sd = sortdata = MEM_malloc_arrayN(poly, sizeof(struct BevelSort), "makeBevelList5");
bl = bev->first;
while (bl) {
if (bl->poly > 0) {
@@ -3107,7 +3155,7 @@ void BKE_curve_bevelList_make(Object *ob, ListBase *nurbs, bool for_render)
static void calchandleNurb_intern(
BezTriple *bezt, const BezTriple *prev, const BezTriple *next,
- bool is_fcurve, bool skip_align)
+ bool is_fcurve, bool skip_align, char fcurve_smoothing)
{
/* defines to avoid confusion */
#define p2_h1 ((p2) - 3)
@@ -3121,6 +3169,9 @@ static void calchandleNurb_intern(
float len_ratio;
const float eps = 1e-5;
+ /* assume normal handle until we check */
+ bezt->f5 = HD_AUTOTYPE_NORMAL;
+
if (bezt->h1 == 0 && bezt->h2 == 0) {
return;
}
@@ -3172,7 +3223,14 @@ static void calchandleNurb_intern(
tvec[2] = dvec_b[2] / len_b + dvec_a[2] / len_a;
if (is_fcurve) {
- len = tvec[0];
+ if (fcurve_smoothing != FCURVE_SMOOTH_NONE) {
+ /* force the horizontal handle size to be 1/3 of the key interval so that
+ * the X component of the parametric bezier curve is a linear spline */
+ len = 6.0f / 2.5614f;
+ }
+ else {
+ len = tvec[0];
+ }
}
else {
len = len_v3(tvec);
@@ -3183,10 +3241,12 @@ static void calchandleNurb_intern(
/* only for fcurves */
bool leftviolate = false, rightviolate = false;
- if (len_a > 5.0f * len_b)
- len_a = 5.0f * len_b;
- if (len_b > 5.0f * len_a)
- len_b = 5.0f * len_a;
+ if (!is_fcurve || fcurve_smoothing == FCURVE_SMOOTH_NONE) {
+ if (len_a > 5.0f * len_b)
+ len_a = 5.0f * len_b;
+ if (len_b > 5.0f * len_a)
+ len_b = 5.0f * len_a;
+ }
if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM)) {
len_a /= len;
@@ -3197,6 +3257,7 @@ static void calchandleNurb_intern(
float ydiff2 = next->vec[1][1] - bezt->vec[1][1];
if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f) || (ydiff1 >= 0.0f && ydiff2 >= 0.0f)) {
bezt->vec[0][1] = bezt->vec[1][1];
+ bezt->f5 = HD_AUTOTYPE_SPECIAL;
}
else { /* handles should not be beyond y coord of two others */
if (ydiff1 <= 0.0f) {
@@ -3221,8 +3282,9 @@ static void calchandleNurb_intern(
if ((bezt->h2 == HD_AUTO_ANIM) && next && prev) { /* keep horizontal if extrema */
float ydiff1 = prev->vec[1][1] - bezt->vec[1][1];
float ydiff2 = next->vec[1][1] - bezt->vec[1][1];
- if ( (ydiff1 <= 0.0f && ydiff2 <= 0.0f) || (ydiff1 >= 0.0f && ydiff2 >= 0.0f) ) {
+ if ((ydiff1 <= 0.0f && ydiff2 <= 0.0f) || (ydiff1 >= 0.0f && ydiff2 >= 0.0f)) {
bezt->vec[2][1] = bezt->vec[1][1];
+ bezt->f5 = HD_AUTOTYPE_SPECIAL;
}
else { /* handles should not be beyond y coord of two others */
if (ydiff1 <= 0.0f) {
@@ -3370,7 +3432,7 @@ static void calchandlesNurb_intern(Nurb *nu, bool skip_align)
next = bezt + 1;
while (a--) {
- calchandleNurb_intern(bezt, prev, next, 0, skip_align);
+ calchandleNurb_intern(bezt, prev, next, 0, skip_align, 0);
prev = bezt;
if (a == 1) {
if (nu->flagu & CU_NURB_CYCLIC)
@@ -3385,9 +3447,540 @@ static void calchandlesNurb_intern(Nurb *nu, bool skip_align)
}
}
-void BKE_nurb_handle_calc(BezTriple *bezt, BezTriple *prev, BezTriple *next, const bool is_fcurve)
+/* A utility function for allocating a number of arrays of the same length
+ * with easy error checking and deallocation, and an easy way to add or remove
+ * arrays that are processed in this way when changing code.
+ *
+ * floats, chars: NULL-terminated arrays of pointers to array pointers that need to be allocated.
+ *
+ * Returns: pointer to the buffer that contains all of the arrays.
+ */
+static void *allocate_arrays(int count, float ***floats, char ***chars, const char *name)
+{
+ size_t num_floats = 0, num_chars = 0;
+
+ while (floats && floats[num_floats]) {
+ num_floats++;
+ }
+
+ while (chars && chars[num_chars]) {
+ num_chars++;
+ }
+
+ void *buffer = (float *)MEM_malloc_arrayN(count, (sizeof(float) * num_floats + num_chars), name);
+
+ if (!buffer)
+ return NULL;
+
+ float *fptr = buffer;
+
+ for (int i = 0; i < num_floats; i++, fptr += count) {
+ *floats[i] = fptr;
+ }
+
+ char *cptr = (char *)fptr;
+
+ for (int i = 0; i < num_chars; i++, cptr += count) {
+ *chars[i] = cptr;
+ }
+
+ return buffer;
+}
+
+static void free_arrays(void *buffer)
+{
+ MEM_freeN(buffer);
+}
+
+/* computes in which direction to change h[i] to satisfy conditions better */
+static float bezier_relax_direction(float *a, float *b, float *c, float *d, float *h, int i, int count)
+{
+ /* current deviation between sides of the equation */
+ float state = a[i] * h[(i + count - 1) % count] +
+ b[i] * h[i] +
+ c[i] * h[(i + 1) % count] -
+ d[i];
+
+ /* only the sign is meaningful */
+ return -state * b[i];
+}
+
+static void bezier_lock_unknown(float *a, float *b, float *c, float *d, int i, float value)
+{
+ a[i] = c[i] = 0.0f;
+ b[i] = 1.0f;
+ d[i] = value;
+}
+
+static void bezier_restore_equation(float *a, float *b, float *c, float *d, float *a0, float *b0, float *c0, float *d0, int i)
+{
+ a[i] = a0[i];
+ b[i] = b0[i];
+ c[i] = c0[i];
+ d[i] = d0[i];
+}
+
+static bool tridiagonal_solve_with_limits(float *a, float *b, float *c, float *d, float *h, float *hmin, float *hmax, int solve_count)
+{
+ float *a0, *b0, *c0, *d0;
+ float **arrays[] = { &a0, &b0, &c0, &d0, NULL };
+ char *is_locked, *num_unlocks;
+ char **flagarrays[] = { &is_locked, &num_unlocks, NULL };
+
+ void *tmps = allocate_arrays(solve_count, arrays, flagarrays, "tridiagonal_solve_with_limits");
+ if (!tmps)
+ return false;
+
+ memcpy(a0, a, sizeof(float) * solve_count);
+ memcpy(b0, b, sizeof(float) * solve_count);
+ memcpy(c0, c, sizeof(float) * solve_count);
+ memcpy(d0, d, sizeof(float) * solve_count);
+
+ memset(is_locked, 0, solve_count);
+ memset(num_unlocks, 0, solve_count);
+
+ bool overshoot, unlocked;
+
+ do {
+ if (!BLI_tridiagonal_solve_cyclic(a, b, c, d, h, solve_count)) {
+ free_arrays(tmps);
+ return false;
+ }
+
+ /* first check if any handles overshoot the limits, and lock them */
+ bool all = false, locked = false;
+
+ overshoot = unlocked = false;
+
+ do {
+ for (int i = 0; i < solve_count; i++) {
+ if (h[i] >= hmin[i] && h[i] <= hmax[i])
+ continue;
+
+ overshoot = true;
+
+ float target = h[i] > hmax[i] ? hmax[i] : hmin[i];
+
+ /* heuristically only lock handles that go in the right direction if there are such ones */
+ if (target != 0.0f || all) {
+ /* mark item locked */
+ is_locked[i] = 1;
+
+ bezier_lock_unknown(a, b, c, d, i, target);
+ locked = true;
+ }
+ }
+
+ all = true;
+ } while (overshoot && !locked);
+
+ /* if no handles overshot and were locked, see if it may be a good idea to unlock some handles */
+ if (!locked) {
+ for (int i = 0; i < solve_count; i++) {
+ // to definitely avoid infinite loops limit this to 2 times
+ if (!is_locked[i] || num_unlocks[i] >= 2)
+ continue;
+
+ /* if the handle wants to move in allowable direction, release it */
+ float relax = bezier_relax_direction(a0, b0, c0, d0, h, i, solve_count);
+
+ if ((relax > 0 && h[i] < hmax[i]) || (relax < 0 && h[i] > hmin[i])) {
+ bezier_restore_equation(a, b, c, d, a0, b0, c0, d0, i);
+
+ is_locked[i] = 0;
+ num_unlocks[i]++;
+ unlocked = true;
+ }
+ }
+ }
+ } while (overshoot || unlocked);
+
+ free_arrays(tmps);
+ return true;
+}
+
+/*
+ * This function computes the handles of a series of auto bezier points
+ * on the basis of 'no acceleration discontinuities' at the points.
+ * The first and last bezier points are considered 'fixed' (their handles are not touched)
+ * The result is the smoothest possible trajectory going through intermediate points.
+ * The difficulty is that the handles depends on their neighbors.
+ *
+ * The exact solution is found by solving a tridiagonal matrix equation formed
+ * by the continuity and boundary conditions. Although theoretically handle position
+ * is affected by all other points of the curve segment, in practice the influence
+ * decreases exponentially with distance.
+ *
+ * Note: this algorithm assumes that the handle horizontal size if always 1/3 of the
+ * of the interval to the next point. This rule ensures linear interpolation of time.
+ *
+ * ^ height (co 1)
+ * | yN
+ * | yN-1 |
+ * | y2 | |
+ * | y1 | | |
+ * | y0 | | | |
+ * | | | | | |
+ * | | | | | |
+ * | | | | | |
+ * |-------t1---------t2--------- ~ --------tN-------------------> time (co 0)
+ *
+ *
+ * Mathematical basis:
+ *
+ * 1. Handle lengths on either side of each point are connected by a factor
+ * ensuring continuity of the first derivative:
+ *
+ * l[i] = t[i+1]/t[i]
+ *
+ * 2. The tridiagonal system is formed by the following equation, which is derived
+ * by differentiating the bezier curve and specifies second derivative continuity
+ * at every point:
+ *
+ * l[i]^2 * h[i-1] + (2*l[i]+2) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i]
+ *
+ * 3. If this point is adjacent to a manually set handle with X size not equal to 1/3
+ * of the horizontal interval, this equation becomes slightly more complex:
+ *
+ * l[i]^2 * h[i-1] + (3*(1-R[i-1])*l[i] + 3*(1-L[i+1])) * h[i] + 1/l[i+1] * h[i+1] = (y[i]-y[i-1])*l[i]^2 + y[i+1]-y[i]
+ *
+ * The difference between equations amounts to this, and it's obvious that when R[i-1]
+ * and L[i+1] are both 1/3, it becomes zero:
+ *
+ * ( (1-3*R[i-1])*l[i] + (1-3*L[i+1]) ) * h[i]
+ *
+ * 4. The equations for zero acceleration border conditions are basically the above
+ * equation with parts omitted, so the handle size correction also applies.
+ */
+
+
+static void bezier_eq_continuous(float *a, float *b, float *c, float *d, float *dy, float *l, int i)
+{
+ a[i] = l[i] * l[i];
+ b[i] = 2.0f * (l[i] + 1);
+ c[i] = 1.0f / l[i + 1];
+ d[i] = dy[i] * l[i] * l[i] + dy[i + 1];
+}
+
+static void bezier_eq_noaccel_right(float *a, float *b, float *c, float *d, float *dy, float *l, int i)
+{
+ a[i] = 0.0f;
+ b[i] = 2.0f;
+ c[i] = 1.0f / l[i + 1];
+ d[i] = dy[i + 1];
+}
+
+static void bezier_eq_noaccel_left(float *a, float *b, float *c, float *d, float *dy, float *l, int i)
+{
+ a[i] = l[i] * l[i];
+ b[i] = 2.0f * l[i];
+ c[i] = 0.0f;
+ d[i] = dy[i] * l[i] * l[i];
+}
+
+/* auto clamp prevents its own point going the wrong way, and adjacent handles overshooting */
+static void bezier_clamp(float *hmax, float *hmin, int i, float dy, bool no_reverse, bool no_overshoot)
+{
+ if (dy > 0) {
+ if (no_overshoot)
+ hmax[i] = min_ff(hmax[i], dy);
+ if (no_reverse)
+ hmin[i] = 0.0f;
+ }
+ else if (dy < 0) {
+ if (no_reverse)
+ hmax[i] = 0.0f;
+ if (no_overshoot)
+ hmin[i] = max_ff(hmin[i], dy);
+ }
+ else if (no_reverse || no_overshoot) {
+ hmax[i] = hmin[i] = 0.0f;
+ }
+}
+
+/* write changes to a bezier handle */
+static void bezier_output_handle_inner(BezTriple *bezt, bool right, float newval[3], bool endpoint)
{
- calchandleNurb_intern(bezt, prev, next, is_fcurve, false);
+ float tmp[3];
+
+ int idx = right ? 2 : 0;
+ char hr = right ? bezt->h2 : bezt->h1;
+ char hm = right ? bezt->h1 : bezt->h2;
+
+ /* only assign Auto/Vector handles */
+ if (!ELEM(hr, HD_AUTO, HD_AUTO_ANIM, HD_VECT))
+ return;
+
+ copy_v3_v3(bezt->vec[idx], newval);
+
+ /* fix up the Align handle if any */
+ if (ELEM(hm, HD_ALIGN, HD_ALIGN_DOUBLESIDE)) {
+ float hlen = len_v3v3(bezt->vec[1], bezt->vec[2 - idx]);
+ float h2len = len_v3v3(bezt->vec[1], bezt->vec[idx]);
+
+ sub_v3_v3v3(tmp, bezt->vec[1], bezt->vec[idx]);
+ madd_v3_v3v3fl(bezt->vec[2 - idx], bezt->vec[1], tmp, hlen / h2len);
+ }
+ /* at end points of the curve, mirror handle to the other side */
+ else if (endpoint && ELEM(hm, HD_AUTO, HD_AUTO_ANIM, HD_VECT)) {
+ sub_v3_v3v3(tmp, bezt->vec[1], bezt->vec[idx]);
+ add_v3_v3v3(bezt->vec[2 - idx], bezt->vec[1], tmp);
+ }
+}
+
+static void bezier_output_handle(BezTriple *bezt, bool right, float dy, bool endpoint)
+{
+ float tmp[3];
+
+ copy_v3_v3(tmp, bezt->vec[right ? 2 : 0]);
+
+ tmp[1] = bezt->vec[1][1] + dy;
+
+ bezier_output_handle_inner(bezt, right, tmp, endpoint);
+}
+
+static bool bezier_check_solve_end_handle(BezTriple *bezt, char htype, bool end)
+{
+ return (htype == HD_VECT) || (end && ELEM(htype, HD_AUTO, HD_AUTO_ANIM) && bezt->f5 == HD_AUTOTYPE_NORMAL);
+}
+
+static float bezier_calc_handle_adj(float hsize[2], float dx)
+{
+ /* if handles intersect in x direction, they are scaled to fit */
+ float fac = dx / (hsize[0] + dx / 3.0f);
+ if (fac < 1.0f) {
+ mul_v2_fl(hsize, fac);
+ }
+ return 1.0f - 3.0f * hsize[0] / dx;
+}
+
+static void bezier_handle_calc_smooth_fcurve(BezTriple *bezt, int total, int start, int count, bool cycle)
+{
+ float *dx, *dy, *l, *a, *b, *c, *d, *h, *hmax, *hmin;
+ float **arrays[] = { &dx, &dy, &l, &a, &b, &c, &d, &h, &hmax, &hmin, NULL };
+
+ int solve_count = count;
+
+ /* verify index ranges */
+
+ if (count < 2)
+ return;
+
+ BLI_assert(start < total - 1 && count <= total);
+ BLI_assert(start + count <= total || cycle);
+
+ bool full_cycle = (start == 0 && count == total && cycle);
+
+ BezTriple *bezt_first = &bezt[start];
+ BezTriple *bezt_last = &bezt[(start + count > total) ? start + count - total : start + count - 1];
+
+ bool solve_first = bezier_check_solve_end_handle(bezt_first, bezt_first->h2, start == 0);
+ bool solve_last = bezier_check_solve_end_handle(bezt_last, bezt_last->h1, start + count == total);
+
+ if (count == 2 && !full_cycle && solve_first == solve_last) {
+ return;
+ }
+
+ /* allocate all */
+
+ void *tmp_buffer = allocate_arrays(count, arrays, NULL, "bezier_calc_smooth_tmp");
+ if (!tmp_buffer)
+ return;
+
+ /* point locations */
+
+ dx[0] = dy[0] = NAN_FLT;
+
+ for (int i = 1, j = start + 1; i < count; i++, j++) {
+ dx[i] = bezt[j].vec[1][0] - bezt[j - 1].vec[1][0];
+ dy[i] = bezt[j].vec[1][1] - bezt[j - 1].vec[1][1];
+
+ /* when cyclic, jump from last point to first */
+ if (cycle && j == total - 1)
+ j = 0;
+ }
+
+ /* ratio of x intervals */
+
+ l[0] = l[count - 1] = 1.0f;
+
+ for (int i = 1; i < count - 1; i++) {
+ l[i] = dx[i + 1] / dx[i];
+ }
+
+ /* compute handle clamp ranges */
+
+ bool clamped_prev = false, clamped_cur = ELEM(HD_AUTO_ANIM, bezt_first->h1, bezt_first->h2);
+
+ for (int i = 0; i < count; i++) {
+ hmax[i] = FLT_MAX;
+ hmin[i] = -FLT_MAX;
+ }
+
+ for (int i = 1, j = start + 1; i < count; i++, j++) {
+ clamped_prev = clamped_cur;
+ clamped_cur = ELEM(HD_AUTO_ANIM, bezt[j].h1, bezt[j].h2);
+
+ if (cycle && j == total - 1) {
+ j = 0;
+ clamped_cur = clamped_cur || ELEM(HD_AUTO_ANIM, bezt[j].h1, bezt[j].h2);
+ }
+
+ bezier_clamp(hmax, hmin, i - 1, dy[i], clamped_prev, clamped_prev);
+ bezier_clamp(hmax, hmin, i, dy[i] * l[i], clamped_cur, clamped_cur);
+ }
+
+ /* full cycle merges first and last points into continuous loop */
+
+ float first_handle_adj = 0.0f, last_handle_adj = 0.0f;
+
+ if (full_cycle) {
+ /* reduce the number of uknowns by one */
+ int i = solve_count = count - 1;
+
+ dx[0] = dx[i];
+ dy[0] = dy[i];
+
+ l[0] = l[i] = dx[1] / dx[0];
+
+ hmin[0] = max_ff(hmin[0], hmin[i]);
+ hmax[0] = min_ff(hmax[0], hmax[i]);
+
+ solve_first = solve_last = true;
+
+ bezier_eq_continuous(a, b, c, d, dy, l, 0);
+ }
+ else {
+ float tmp[2];
+
+ /* boundary condition: fixed handles or zero curvature */
+ if (!solve_first) {
+ sub_v2_v2v2(tmp, bezt_first->vec[2], bezt_first->vec[1]);
+ first_handle_adj = bezier_calc_handle_adj(tmp, dx[1]);
+
+ bezier_lock_unknown(a, b, c, d, 0, tmp[1]);
+ }
+ else {
+ bezier_eq_noaccel_right(a, b, c, d, dy, l, 0);
+ }
+
+ if (!solve_last) {
+ sub_v2_v2v2(tmp, bezt_last->vec[1], bezt_last->vec[0]);
+ last_handle_adj = bezier_calc_handle_adj(tmp, dx[count - 1]);
+
+ bezier_lock_unknown(a, b, c, d, count - 1, tmp[1]);
+ }
+ else {
+ bezier_eq_noaccel_left(a, b, c, d, dy, l, count - 1);
+ }
+ }
+
+ /* main tridiagonal system of equations */
+
+ for (int i = 1; i < count - 1; i++) {
+ bezier_eq_continuous(a, b, c, d, dy, l, i);
+ }
+
+ /* apply correction for user-defined handles with nonstandard x positions */
+
+ if (!full_cycle) {
+ if (count > 2 || solve_last) {
+ b[1] += l[1] * first_handle_adj;
+ }
+
+ if (count > 2 || solve_first) {
+ b[count - 2] += last_handle_adj;
+ }
+ }
+
+ /* solve and output results */
+
+ if (tridiagonal_solve_with_limits(a, b, c, d, h, hmin, hmax, solve_count)) {
+ if (full_cycle) {
+ h[count - 1] = h[0];
+ }
+
+ for (int i = 1, j = start + 1; i < count - 1; i++, j++) {
+ bool end = (j == total - 1);
+
+ bezier_output_handle(&bezt[j], false, -h[i] / l[i], end);
+
+ if (end)
+ j = 0;
+
+ bezier_output_handle(&bezt[j], true, h[i], end);
+ }
+
+ if (solve_first) {
+ bezier_output_handle(bezt_first, true, h[0], start == 0);
+ }
+
+ if (solve_last) {
+ bezier_output_handle(bezt_last, false, -h[count - 1] / l[count - 1], start + count == total);
+ }
+ }
+
+ /* free all */
+
+ free_arrays(tmp_buffer);
+}
+
+static bool is_free_auto_point(BezTriple *bezt)
+{
+ return BEZT_IS_AUTOH(bezt) && bezt->f5 == HD_AUTOTYPE_NORMAL;
+}
+
+void BKE_nurb_handle_smooth_fcurve(BezTriple *bezt, int total, bool cycle)
+{
+ /* ignore cyclic extrapolation if end points are locked */
+ cycle = cycle && is_free_auto_point(&bezt[0]) && is_free_auto_point(&bezt[total - 1]);
+
+ /* if cyclic, try to find a sequence break point */
+ int search_base = 0;
+
+ if (cycle) {
+ for (int i = 1; i < total - 1; i++) {
+ if (!is_free_auto_point(&bezt[i])) {
+ search_base = i;
+ break;
+ }
+ }
+
+ /* all points of the curve are freely changeable auto handles - solve as full cycle */
+ if (search_base == 0) {
+ bezier_handle_calc_smooth_fcurve(bezt, total, 0, total, cycle);
+ return;
+ }
+ }
+
+ /* Find continuous subsequences of free auto handles and smooth them, starting at
+ * search_base. In cyclic mode these subsequences can span the cycle boundary. */
+ int start = search_base, count = 1;
+
+ for (int i = 1, j = start + 1; i < total; i++, j++) {
+ /* in cyclic mode: jump from last to first point when necessary */
+ if (j == total - 1 && cycle)
+ j = 0;
+
+ /* non auto handle closes the list (we come here at least for the last handle, see above) */
+ if (!is_free_auto_point(&bezt[j])) {
+ bezier_handle_calc_smooth_fcurve(bezt, total, start, count + 1, cycle);
+ start = j;
+ count = 1;
+ }
+ else {
+ count++;
+ }
+ }
+
+ if (count > 1) {
+ bezier_handle_calc_smooth_fcurve(bezt, total, start, count, cycle);
+ }
+}
+
+void BKE_nurb_handle_calc(BezTriple *bezt, BezTriple *prev, BezTriple *next, const bool is_fcurve, const char smoothing)
+{
+ calchandleNurb_intern(bezt, prev, next, is_fcurve, false, smoothing);
}
void BKE_nurb_handles_calc(Nurb *nu) /* first, if needed, set handle flags */
@@ -3427,7 +4020,7 @@ void BKE_nurb_handle_calc_simple(Nurb *nu, BezTriple *bezt)
if (nu->pntsu > 1) {
BezTriple *prev = BKE_nurb_bezt_get_prev(nu, bezt);
BezTriple *next = BKE_nurb_bezt_get_next(nu, bezt);
- BKE_nurb_handle_calc(bezt, prev, next, 0);
+ BKE_nurb_handle_calc(bezt, prev, next, 0, 0);
}
}
@@ -3534,7 +4127,7 @@ void BKE_nurb_handles_autocalc(Nurb *nu, int flag)
bool align = false, leftsmall = false, rightsmall = false;
/* left handle: */
- if (flag == 0 || (bezt1->f1 & flag) ) {
+ if (flag == 0 || (bezt1->f1 & flag)) {
bezt1->h1 = HD_FREE;
/* distance too short: vectorhandle */
if (len_squared_v3v3(bezt1->vec[1], bezt0->vec[1]) < eps_sq) {
@@ -3553,7 +4146,7 @@ void BKE_nurb_handles_autocalc(Nurb *nu, int flag)
}
}
/* right handle: */
- if (flag == 0 || (bezt1->f3 & flag) ) {
+ if (flag == 0 || (bezt1->f3 & flag)) {
bezt1->h2 = HD_FREE;
/* distance too short: vectorhandle */
if (len_squared_v3v3(bezt1->vec[1], bezt2->vec[1]) < eps_sq) {
@@ -3848,7 +4441,7 @@ void BKE_nurb_direction_switch(Nurb *nu)
/* and make in increasing order again */
a = KNOTSU(nu);
fp1 = nu->knotsu;
- fp2 = tempf = MEM_mallocN(sizeof(float) * a, "switchdirect");
+ fp2 = tempf = MEM_malloc_arrayN(a, sizeof(float), "switchdirect");
a--;
fp2[a] = fp1[a];
while (a--) {
@@ -3892,7 +4485,7 @@ void BKE_nurb_direction_switch(Nurb *nu)
float (*BKE_curve_nurbs_vertexCos_get(ListBase *lb, int *r_numVerts))[3]
{
int i, numVerts = *r_numVerts = BKE_nurbList_verts_count(lb);
- float *co, (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "cu_vcos");
+ float *co, (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "cu_vcos");
Nurb *nu;
co = cos[0];
@@ -3949,7 +4542,7 @@ void BK_curve_nurbs_vertexCos_apply(ListBase *lb, float (*vertexCos)[3])
float (*BKE_curve_nurbs_keyVertexCos_get(ListBase *lb, float *key))[3]
{
int i, numVerts = BKE_nurbList_verts_count(lb);
- float *co, (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "cu_vcos");
+ float *co, (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "cu_vcos");
Nurb *nu;
co = cos[0];
@@ -4012,7 +4605,7 @@ bool BKE_nurb_check_valid_u(struct Nurb *nu)
return true; /* not a nurb, lets assume its valid */
if (nu->pntsu < nu->orderu) return false;
- if (((nu->flag & CU_NURB_CYCLIC) == 0) && (nu->flagu & CU_NURB_BEZIER)) { /* Bezier U Endpoints */
+ if (((nu->flagu & CU_NURB_CYCLIC) == 0) && (nu->flagu & CU_NURB_BEZIER)) { /* Bezier U Endpoints */
if (nu->orderu == 4) {
if (nu->pntsu < 5)
return false; /* bezier with 4 orderu needs 5 points */
@@ -4033,7 +4626,7 @@ bool BKE_nurb_check_valid_v(struct Nurb *nu)
if (nu->pntsv < nu->orderv)
return false;
- if (((nu->flag & CU_NURB_CYCLIC) == 0) && (nu->flagv & CU_NURB_BEZIER)) { /* Bezier V Endpoints */
+ if (((nu->flagv & CU_NURB_CYCLIC) == 0) && (nu->flagv & CU_NURB_BEZIER)) { /* Bezier V Endpoints */
if (nu->orderv == 4) {
if (nu->pntsv < 5)
return false; /* bezier with 4 orderu needs 5 points */
@@ -4096,7 +4689,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
if (nu->type == CU_POLY) {
if (type == CU_BEZIER) { /* to Bezier with vecthandles */
nr = nu->pntsu;
- bezt = (BezTriple *)MEM_callocN(nr * sizeof(BezTriple), "setsplinetype2");
+ bezt = (BezTriple *)MEM_calloc_arrayN(nr, sizeof(BezTriple), "setsplinetype2");
nu->bezt = bezt;
a = nr;
bp = nu->bp;
@@ -4112,6 +4705,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
MEM_freeN(nu->bp);
nu->bp = NULL;
nu->pntsu = nr;
+ nu->pntsv = 0;
nu->type = CU_BEZIER;
BKE_nurb_handles_calc(nu);
}
@@ -4131,7 +4725,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
else if (nu->type == CU_BEZIER) { /* Bezier */
if (type == CU_POLY || type == CU_NURBS) {
nr = use_handles ? (3 * nu->pntsu) : nu->pntsu;
- nu->bp = MEM_callocN(nr * sizeof(BPoint), "setsplinetype");
+ nu->bp = MEM_calloc_arrayN(nr, sizeof(BPoint), "setsplinetype");
a = nu->pntsu;
bezt = nu->bezt;
bp = nu->bp;
@@ -4194,7 +4788,7 @@ bool BKE_nurb_type_convert(Nurb *nu, const short type, const bool use_handles)
return false; /* conversion impossible */
}
else {
- bezt = MEM_callocN(nr * sizeof(BezTriple), "setsplinetype2");
+ bezt = MEM_calloc_arrayN(nr, sizeof(BezTriple), "setsplinetype2");
nu->bezt = bezt;
a = nr;
bp = nu->bp;
@@ -4356,12 +4950,27 @@ void BKE_curve_nurb_vert_active_validate(Curve *cu)
bool BKE_curve_minmax(Curve *cu, bool use_radius, float min[3], float max[3])
{
ListBase *nurb_lb = BKE_curve_nurbs_get(cu);
- Nurb *nu;
-
- for (nu = nurb_lb->first; nu; nu = nu->next)
+ ListBase temp_nurb_lb = {NULL, NULL};
+ const bool is_font = (BLI_listbase_is_empty(nurb_lb)) && (cu->len != 0);
+ /* For font curves we generate temp list of splines.
+ *
+ * This is likely to be fine, this function is not supposed to be called
+ * often, and it's the only way to get meaningful bounds for fonts.
+ */
+ if (is_font) {
+ nurb_lb = &temp_nurb_lb;
+ BKE_vfont_to_curve_ex(G.main, NULL, cu, FO_EDIT, nurb_lb,
+ NULL, NULL, NULL, NULL);
+ use_radius = false;
+ }
+ /* Do bounding box based on splines. */
+ for (Nurb *nu = nurb_lb->first; nu; nu = nu->next) {
BKE_nurb_minmax(nu, use_radius, min, max);
-
- return (BLI_listbase_is_empty(nurb_lb) == false);
+ }
+ const bool result = (BLI_listbase_is_empty(nurb_lb) == false);
+ /* Cleanup if needed. */
+ BKE_nurbList_free(&temp_nurb_lb);
+ return result;
}
bool BKE_curve_center_median(Curve *cu, float cent[3])
@@ -4415,7 +5024,9 @@ bool BKE_curve_center_bounds(Curve *cu, float cent[3])
}
-void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, const float unit_scale)
+void BKE_curve_transform_ex(
+ Curve *cu, float mat[4][4],
+ const bool do_keys, const bool do_props, const float unit_scale)
{
Nurb *nu;
BPoint *bp;
@@ -4429,7 +5040,9 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons
mul_m4_v3(mat, bezt->vec[0]);
mul_m4_v3(mat, bezt->vec[1]);
mul_m4_v3(mat, bezt->vec[2]);
- bezt->radius *= unit_scale;
+ if (do_props) {
+ bezt->radius *= unit_scale;
+ }
}
BKE_nurb_handles_calc(nu);
}
@@ -4437,7 +5050,9 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons
i = nu->pntsu * nu->pntsv;
for (bp = nu->bp; i--; bp++) {
mul_m4_v3(mat, bp->vec);
- bp->radius *= unit_scale;
+ if (do_props) {
+ bp->radius *= unit_scale;
+ }
}
}
}
@@ -4453,10 +5068,12 @@ void BKE_curve_transform_ex(Curve *cu, float mat[4][4], const bool do_keys, cons
}
}
-void BKE_curve_transform(Curve *cu, float mat[4][4], const bool do_keys)
+void BKE_curve_transform(
+ Curve *cu, float mat[4][4],
+ const bool do_keys, const bool do_props)
{
float unit_scale = mat4_to_scale(mat);
- BKE_curve_transform_ex(cu, mat, do_keys, unit_scale);
+ BKE_curve_transform_ex(cu, mat, do_keys, do_props, unit_scale);
}
void BKE_curve_translate(Curve *cu, float offset[3], const bool do_keys)
@@ -4638,21 +5255,8 @@ void BKE_curve_rect_from_textbox(const struct Curve *cu, const struct TextBox *t
void BKE_curve_eval_geometry(EvaluationContext *UNUSED(eval_ctx),
Curve *curve)
{
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s on %s\n", __func__, curve->id.name);
- }
+ DEG_debug_print_eval(__func__, curve->id.name, curve);
if (curve->bb == NULL || (curve->bb->flag & BOUNDBOX_DIRTY)) {
BKE_curve_texspace_calc(curve);
}
}
-
-void BKE_curve_eval_path(EvaluationContext *UNUSED(eval_ctx),
- Curve *curve)
-{
- /* TODO(sergey): This will probably need to be a part of
- * the modifier stack still.
- */
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s on %s\n", __func__, curve->id.name);
- }
-}
diff --git a/source/blender/blenkernel/intern/curve_decimate.c b/source/blender/blenkernel/intern/curve_decimate.c
new file mode 100644
index 00000000000..1a6c4714afd
--- /dev/null
+++ b/source/blender/blenkernel/intern/curve_decimate.c
@@ -0,0 +1,339 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenkernel/intern/curve_decimate.c
+ * \ingroup bke
+ */
+
+#include "DNA_curve_types.h"
+
+#include "MEM_guardedalloc.h"
+#include "BLI_heap.h"
+#include "BLI_math_vector.h"
+
+#include "BKE_curve.h"
+
+#include "curve_fit_nd.h"
+
+#include "BLI_strict_flags.h"
+
+struct Knot {
+ struct Knot *next, *prev;
+ uint point_index; /* index in point array */
+ uint knot_index; /* index in knot array*/
+ float tan[2][3];
+ float handles[2];
+
+ HeapNode *heap_node;
+ uint can_remove : 1;
+ uint is_removed : 1;
+
+#ifndef NDEBUG
+ const float *co;
+#endif
+};
+
+struct Removal {
+ uint knot_index;
+ /* handles for prev/next knots */
+ float handles[2];
+};
+
+static float knot_remove_error_value(
+ const float tan_l[3], const float tan_r[3],
+ const float (*points)[3], const uint points_len,
+ /* avoid having to re-calculate again */
+ float r_handle_factors[2])
+{
+ const uint dims = 3;
+ float error_sq = FLT_MAX;
+ uint error_sq_index;
+ float handle_factors[2][3];
+
+ curve_fit_cubic_to_points_single_fl(
+ &points[0][0], points_len, NULL, dims, 0.0f,
+ tan_l, tan_r,
+ handle_factors[0], handle_factors[1],
+ &error_sq, &error_sq_index);
+
+ sub_v3_v3(handle_factors[0], points[0]);
+ r_handle_factors[0] = dot_v3v3(tan_l, handle_factors[0]);
+
+ sub_v3_v3(handle_factors[1], points[points_len - 1]);
+ r_handle_factors[1] = dot_v3v3(tan_r, handle_factors[1]);
+
+ return error_sq;
+}
+
+static void knot_remove_error_recalculate(
+ Heap *heap, const float (*points)[3], const uint points_len,
+ struct Knot *k, const float error_sq_max)
+{
+ BLI_assert(k->can_remove);
+ float handles[2];
+
+#ifndef NDEBUG
+ BLI_assert(equals_v3v3(points[k->prev->point_index], k->prev->co));
+ BLI_assert(equals_v3v3(points[k->next->point_index], k->next->co));
+#endif
+
+ const float (*points_offset)[3];
+ uint points_offset_len;
+
+ if (k->prev->point_index < k->next->point_index) {
+ points_offset = &points[k->prev->point_index];
+ points_offset_len = (k->next->point_index - k->prev->point_index) + 1;
+ }
+ else {
+ points_offset = &points[k->prev->point_index];
+ points_offset_len = ((k->next->point_index + points_len) - k->prev->point_index) + 1;
+ }
+
+ const float cost_sq = knot_remove_error_value(
+ k->prev->tan[1], k->next->tan[0],
+ points_offset, points_offset_len,
+ handles);
+
+ if (cost_sq < error_sq_max) {
+ struct Removal *r;
+ if (k->heap_node) {
+ r = BLI_heap_node_ptr(k->heap_node);
+ }
+ else {
+ r = MEM_mallocN(sizeof(*r), __func__);
+ r->knot_index = k->knot_index;
+ }
+
+ copy_v2_v2(r->handles, handles);
+
+ BLI_heap_insert_or_update(heap, &k->heap_node, cost_sq, r);
+ }
+ else {
+ if (k->heap_node) {
+ struct Removal *r;
+ r = BLI_heap_node_ptr(k->heap_node);
+ BLI_heap_remove(heap, k->heap_node);
+
+ MEM_freeN(r);
+
+ k->heap_node = NULL;
+ }
+ }
+}
+
+static void curve_decimate(
+ const float (*points)[3], const uint points_len,
+ struct Knot *knots, const uint knots_len,
+ float error_sq_max, const uint error_target_len)
+{
+ Heap *heap = BLI_heap_new_ex(knots_len);
+ for (uint i = 0; i < knots_len; i++) {
+ struct Knot *k = &knots[i];
+ if (k->can_remove) {
+ knot_remove_error_recalculate(heap, points, points_len, k, error_sq_max);
+ }
+ }
+
+ uint knots_len_remaining = knots_len;
+
+ while ((knots_len_remaining > error_target_len) &&
+ (BLI_heap_is_empty(heap) == false))
+ {
+ struct Knot *k;
+
+ {
+ struct Removal *r = BLI_heap_pop_min(heap);
+ k = &knots[r->knot_index];
+ k->heap_node = NULL;
+ k->prev->handles[1] = r->handles[0];
+ k->next->handles[0] = r->handles[1];
+ MEM_freeN(r);
+ }
+
+ struct Knot *k_prev = k->prev;
+ struct Knot *k_next = k->next;
+
+ /* remove ourselves */
+ k_next->prev = k_prev;
+ k_prev->next = k_next;
+
+ k->next = NULL;
+ k->prev = NULL;
+ k->is_removed = true;
+
+ if (k_prev->can_remove) {
+ knot_remove_error_recalculate(heap, points, points_len, k_prev, error_sq_max);
+ }
+
+ if (k_next->can_remove) {
+ knot_remove_error_recalculate(heap, points, points_len, k_next, error_sq_max);
+ }
+
+ knots_len_remaining -= 1;
+ }
+
+ BLI_heap_free(heap, MEM_freeN);
+}
+
+
+uint BKE_curve_decimate_bezt_array(
+ BezTriple *bezt_array, const uint bezt_array_len,
+ const uint resolu, const bool is_cyclic,
+ const char flag_test, const char flag_set,
+ const float error_sq_max, const uint error_target_len)
+{
+ const uint bezt_array_last = bezt_array_len - 1;
+ const uint points_len = BKE_curve_calc_coords_axis_len(bezt_array_len, resolu, is_cyclic, true);
+
+ float (*points)[3] = MEM_mallocN((sizeof(float[3]) * points_len * (is_cyclic ? 2 : 1)), __func__);
+
+ BKE_curve_calc_coords_axis(bezt_array, bezt_array_len, resolu, is_cyclic, false, 0, sizeof(float[3]), &points[0][0]);
+ BKE_curve_calc_coords_axis(bezt_array, bezt_array_len, resolu, is_cyclic, false, 1, sizeof(float[3]), &points[0][1]);
+ BKE_curve_calc_coords_axis(bezt_array, bezt_array_len, resolu, is_cyclic, false, 2, sizeof(float[3]), &points[0][2]);
+
+ const uint knots_len = bezt_array_len;
+ struct Knot *knots = MEM_mallocN((sizeof(*knots) * bezt_array_len), __func__);
+
+ if (is_cyclic) {
+ memcpy(points[points_len], points[0], sizeof(float[3]) * points_len);
+ }
+
+ for (uint i = 0; i < bezt_array_len; i++) {
+ knots[i].heap_node = NULL;
+ knots[i].can_remove = (bezt_array[i].f2 & flag_test) != 0;
+ knots[i].is_removed = false;
+ knots[i].next = &knots[i + 1];
+ knots[i].prev = &knots[i - 1];
+ knots[i].point_index = i * resolu;
+ knots[i].knot_index = i;
+
+ sub_v3_v3v3(knots[i].tan[0], bezt_array[i].vec[0], bezt_array[i].vec[1]);
+ knots[i].handles[0] = normalize_v3(knots[i].tan[0]);
+
+ sub_v3_v3v3(knots[i].tan[1], bezt_array[i].vec[1], bezt_array[i].vec[2]);
+ knots[i].handles[1] = -normalize_v3(knots[i].tan[1]);
+
+#ifndef NDEBUG
+ knots[i].co = bezt_array[i].vec[1];
+ BLI_assert(equals_v3v3(knots[i].co, points[knots[i].point_index]));
+#endif
+ }
+
+ if (is_cyclic) {
+ knots[0].prev = &knots[bezt_array_last];
+ knots[bezt_array_last].next = &knots[0];
+ }
+ else {
+ knots[0].prev = NULL;
+ knots[bezt_array_last].next = NULL;
+
+ /* always keep end-points */
+ knots[0].can_remove = false;
+ knots[bezt_array_last].can_remove = false;
+ }
+
+ curve_decimate(points, points_len, knots, knots_len, error_sq_max, error_target_len);
+
+ MEM_freeN(points);
+
+ uint knots_len_decimated = knots_len;
+
+ /* Update handle type on modifications. */
+#define HANDLE_UPDATE(a, b) \
+ { \
+ if (a == HD_VECT) { \
+ a = HD_FREE; \
+ } \
+ else if (a == HD_AUTO) { \
+ a = HD_ALIGN; \
+ } \
+ /* opposite handle */ \
+ if (b == HD_AUTO) { \
+ b = HD_ALIGN; \
+ } \
+ } ((void)0)
+
+ for (uint i = 0; i < bezt_array_len; i++) {
+ if (knots[i].is_removed) {
+ /* caller must remove */
+ bezt_array[i].f2 |= flag_set;
+ knots_len_decimated--;
+ }
+ else {
+ bezt_array[i].f2 &= (char)~flag_set;
+ if (is_cyclic || i != 0) {
+ uint i_prev = (i != 0) ? i - 1 : bezt_array_last;
+ if (knots[i_prev].is_removed) {
+ madd_v3_v3v3fl(bezt_array[i].vec[0], bezt_array[i].vec[1], knots[i].tan[0], knots[i].handles[0]);
+ HANDLE_UPDATE(bezt_array[i].h1, bezt_array[i].h2);
+ }
+ }
+ if (is_cyclic || i != bezt_array_last) {
+ uint i_next = (i != bezt_array_last) ? i + 1 : 0;
+ if (knots[i_next].is_removed) {
+ madd_v3_v3v3fl(bezt_array[i].vec[2], bezt_array[i].vec[1], knots[i].tan[1], knots[i].handles[1]);
+ HANDLE_UPDATE(bezt_array[i].h2, bezt_array[i].h1);
+ }
+ }
+ }
+ }
+
+#undef HANDLE_UPDATE
+
+ MEM_freeN(knots);
+
+ return knots_len_decimated;
+}
+#define SELECT 1
+
+
+void BKE_curve_decimate_nurb(
+ Nurb *nu, const uint resolu,
+ const float error_sq_max, const uint error_target_len)
+{
+ const char flag_test = BEZT_FLAG_TEMP_TAG;
+
+ const uint pntsu_dst = BKE_curve_decimate_bezt_array(
+ nu->bezt, (uint)nu->pntsu, resolu, (nu->flagu & CU_NURB_CYCLIC) != 0,
+ SELECT, flag_test,
+ error_sq_max, error_target_len);
+
+ if (pntsu_dst == (uint)nu->pntsu) {
+ return;
+ }
+
+ BezTriple *bezt_src = nu->bezt;
+ BezTriple *bezt_dst = MEM_mallocN(sizeof(BezTriple) * pntsu_dst, __func__);
+
+ int i_src = 0, i_dst = 0;
+
+ while (i_src < nu->pntsu) {
+ if ((bezt_src[i_src].f2 & flag_test) == 0) {
+ bezt_dst[i_dst] = bezt_src[i_src];
+ i_dst++;
+ }
+ i_src++;
+ }
+
+ MEM_freeN(bezt_src);
+
+ nu->bezt = bezt_dst;
+ nu->pntsu = i_dst;
+}
diff --git a/source/blender/blenkernel/intern/customdata.c b/source/blender/blenkernel/intern/customdata.c
index c9f0b8ec9ca..cf86963cf60 100644
--- a/source/blender/blenkernel/intern/customdata.c
+++ b/source/blender/blenkernel/intern/customdata.c
@@ -33,14 +33,10 @@
/** \file blender/blenkernel/intern/customdata.c
* \ingroup bke
*/
-
-
-#include <math.h>
-#include <string.h>
-#include <assert.h>
#include "MEM_guardedalloc.h"
+#include "DNA_customdata_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_ID.h"
@@ -62,20 +58,16 @@
#include "BKE_mesh_remap.h"
#include "BKE_multires.h"
-#include "data_transfer_intern.h"
-
#include "bmesh.h"
-#include <math.h>
-#include <string.h>
+/* only for customdata_data_transfer_interp_normal_normals */
+#include "data_transfer_intern.h"
/* number of layers to add when growing a CustomData object */
#define CUSTOMDATA_GROW 5
/* ensure typemap size is ok */
-BLI_STATIC_ASSERT(sizeof(((CustomData *)NULL)->typemap) /
- sizeof(((CustomData *)NULL)->typemap[0]) == CD_NUMTYPES,
- "size mismatch");
+BLI_STATIC_ASSERT(ARRAY_SIZE(((CustomData *)NULL)->typemap) == CD_NUMTYPES, "size mismatch");
/********************* Layer type information **********************/
@@ -165,7 +157,7 @@ static void layerCopy_mdeformvert(const void *source, void *dest,
MDeformVert *dvert = POINTER_OFFSET(dest, i * size);
if (dvert->totweight) {
- MDeformWeight *dw = MEM_mallocN(dvert->totweight * sizeof(*dw),
+ MDeformWeight *dw = MEM_malloc_arrayN(dvert->totweight, sizeof(*dw),
"layerCopy_mdeformvert dw");
memcpy(dw, dvert->dw, dvert->totweight * sizeof(*dw));
@@ -289,7 +281,7 @@ static void layerInterp_mdeformvert(
}
if (totweight) {
- dvert->dw = MEM_mallocN(sizeof(*dvert->dw) * totweight, __func__);
+ dvert->dw = MEM_malloc_arrayN(totweight, sizeof(*dvert->dw), __func__);
}
}
@@ -544,11 +536,11 @@ static void layerSwap_mdisps(void *data, const int *ci)
MEM_freeN(s->disps);
s->totdisp = (s->totdisp / corners) * nverts;
- s->disps = MEM_callocN(s->totdisp * sizeof(float) * 3, "mdisp swap");
+ s->disps = MEM_calloc_arrayN(s->totdisp, sizeof(float) * 3, "mdisp swap");
return;
}
- d = MEM_callocN(sizeof(float) * 3 * s->totdisp, "mdisps swap");
+ d = MEM_calloc_arrayN(s->totdisp, 3 * sizeof(float), "mdisps swap");
for (S = 0; S < corners; S++)
memcpy(d + cornersize * S, s->disps + cornersize * ci[S], cornersize * 3 * sizeof(float));
@@ -604,7 +596,7 @@ static int layerRead_mdisps(CDataFile *cdf, void *data, int count)
for (i = 0; i < count; ++i) {
if (!d[i].disps)
- d[i].disps = MEM_callocN(sizeof(float) * 3 * d[i].totdisp, "mdisps read");
+ d[i].disps = MEM_calloc_arrayN(d[i].totdisp, 3 * sizeof(float), "mdisps read");
if (!cdf_read_data(cdf, d[i].totdisp * 3 * sizeof(float), d[i].disps)) {
printf("failed to read multires displacement %d/%d %d\n", i, count, d[i].totdisp);
@@ -805,18 +797,15 @@ static void layerInterp_mloopcol(
const float *sub_weights, int count, void *dest)
{
MLoopCol *mc = dest;
- int i;
- const float *sub_weight;
struct {
float a;
float r;
float g;
float b;
- } col;
- col.a = col.r = col.g = col.b = 0;
+ } col = {0};
- sub_weight = sub_weights;
- for (i = 0; i < count; ++i) {
+ const float *sub_weight = sub_weights;
+ for (int i = 0; i < count; ++i) {
float weight = weights ? weights[i] : 1;
const MLoopCol *src = sources[i];
if (sub_weights) {
@@ -833,19 +822,16 @@ static void layerInterp_mloopcol(
col.a += src->a * weight;
}
}
-
+
+
/* Subdivide smooth or fractal can cause problems without clamping
* although weights should also not cause this situation */
- CLAMP(col.a, 0.0f, 255.0f);
- CLAMP(col.r, 0.0f, 255.0f);
- CLAMP(col.g, 0.0f, 255.0f);
- CLAMP(col.b, 0.0f, 255.0f);
- /* delay writing to the destination incase dest is in sources */
- mc->r = (int)col.r;
- mc->g = (int)col.g;
- mc->b = (int)col.b;
- mc->a = (int)col.a;
+ /* also delay writing to the destination incase dest is in sources */
+ mc->r = round_fl_to_uchar_clamp(col.r);
+ mc->g = round_fl_to_uchar_clamp(col.g);
+ mc->b = round_fl_to_uchar_clamp(col.b);
+ mc->a = round_fl_to_uchar_clamp(col.a);
}
static int layerMaxNum_mloopcol(void)
@@ -1068,15 +1054,10 @@ static void layerInterp_mcol(
/* Subdivide smooth or fractal can cause problems without clamping
* although weights should also not cause this situation */
- CLAMP(col[j].a, 0.0f, 255.0f);
- CLAMP(col[j].r, 0.0f, 255.0f);
- CLAMP(col[j].g, 0.0f, 255.0f);
- CLAMP(col[j].b, 0.0f, 255.0f);
-
- mc[j].a = (int)col[j].a;
- mc[j].r = (int)col[j].r;
- mc[j].g = (int)col[j].g;
- mc[j].b = (int)col[j].b;
+ mc[j].a = round_fl_to_uchar_clamp(col[j].a);
+ mc[j].r = round_fl_to_uchar_clamp(col[j].r);
+ mc[j].g = round_fl_to_uchar_clamp(col[j].g);
+ mc[j].b = round_fl_to_uchar_clamp(col[j].b);
}
}
@@ -1825,7 +1806,7 @@ void CustomData_set_layer_flag(struct CustomData *data, int type, int flag)
static int customData_resize(CustomData *data, int amount)
{
- CustomDataLayer *tmp = MEM_callocN(sizeof(*tmp) * (data->maxlayer + amount),
+ CustomDataLayer *tmp = MEM_calloc_arrayN((data->maxlayer + amount), sizeof(*tmp),
"CustomData->layers");
if (!tmp) return 0;
@@ -1843,7 +1824,6 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
int totelem, const char *name)
{
const LayerTypeInfo *typeInfo = layerType_getInfo(type);
- const size_t size = (size_t)totelem * typeInfo->size;
int flag = 0, index = data->totlayer;
void *newlayerdata = NULL;
@@ -1860,12 +1840,12 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
if ((alloctype == CD_ASSIGN) || (alloctype == CD_REFERENCE)) {
newlayerdata = layerdata;
}
- else if (size > 0) {
+ else if (totelem > 0 && typeInfo->size > 0) {
if (alloctype == CD_DUPLICATE && layerdata) {
- newlayerdata = MEM_mallocN(size, layerType_getName(type));
+ newlayerdata = MEM_malloc_arrayN((size_t)totelem, typeInfo->size, layerType_getName(type));
}
else {
- newlayerdata = MEM_callocN(size, layerType_getName(type));
+ newlayerdata = MEM_calloc_arrayN((size_t)totelem, typeInfo->size, layerType_getName(type));
}
if (!newlayerdata)
@@ -1876,7 +1856,7 @@ static CustomDataLayer *customData_add_layer__internal(CustomData *data, int typ
if (typeInfo->copy)
typeInfo->copy(layerdata, newlayerdata, totelem);
else
- memcpy(newlayerdata, layerdata, size);
+ memcpy(newlayerdata, layerdata, (size_t)totelem * typeInfo->size);
}
else if (alloctype == CD_DEFAULT) {
if (typeInfo->set_default)
@@ -1963,11 +1943,15 @@ void *CustomData_add_layer_named(CustomData *data, int type, int alloctype,
bool CustomData_free_layer(CustomData *data, int type, int totelem, int index)
{
- const int n = index - CustomData_get_layer_index(data, type);
+ const int index_first = CustomData_get_layer_index(data, type);
+ const int n = index - index_first;
int i;
-
- if (index < 0)
+
+ BLI_assert(index >= index_first);
+ if ((index_first == -1) || (n < 0)) {
return false;
+ }
+ BLI_assert(data->layers[index].type == type);
customData_free_layer__internal(&data->layers[index], totelem);
@@ -2012,8 +1996,10 @@ bool CustomData_free_layer_active(CustomData *data, int type, int totelem)
void CustomData_free_layers(CustomData *data, int type, int totelem)
{
- while (CustomData_has_layer(data, type))
- CustomData_free_layer_active(data, type, totelem);
+ const int index = CustomData_get_layer_index(data, type);
+ while (CustomData_free_layer(data, type, totelem, index)) {
+ /* pass */
+ }
}
bool CustomData_has_layer(const CustomData *data, int type)
@@ -2061,7 +2047,7 @@ static void *customData_duplicate_referenced_layer_index(CustomData *data, const
const LayerTypeInfo *typeInfo = layerType_getInfo(layer->type);
if (typeInfo->copy) {
- void *dst_data = MEM_mallocN((size_t)totelem * typeInfo->size, "CD duplicate ref layer");
+ void *dst_data = MEM_malloc_arrayN((size_t)totelem, typeInfo->size, "CD duplicate ref layer");
typeInfo->copy(layer->data, dst_data, totelem);
layer->data = dst_data;
}
@@ -2290,7 +2276,7 @@ void CustomData_interp(const CustomData *source, CustomData *dest,
* elements
*/
if (count > SOURCE_BUF_SIZE)
- sources = MEM_mallocN(sizeof(*sources) * count, __func__);
+ sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__);
/* interpolates a layer at a time */
dest_i = 0;
@@ -3157,7 +3143,7 @@ void CustomData_bmesh_interp(
* elements
*/
if (count > SOURCE_BUF_SIZE)
- sources = MEM_mallocN(sizeof(*sources) * count, __func__);
+ sources = MEM_malloc_arrayN(count, sizeof(*sources), __func__);
/* interpolates a layer at a time */
for (i = 0; i < data->totlayer; ++i) {
@@ -3347,7 +3333,7 @@ void CustomData_file_write_prepare(
else {
if (UNLIKELY((size_t)j >= write_layers_size)) {
if (write_layers == write_layers_buff) {
- write_layers = MEM_mallocN(sizeof(*write_layers) * (write_layers_size + chunk_size), __func__);
+ write_layers = MEM_malloc_arrayN((write_layers_size + chunk_size), sizeof(*write_layers), __func__);
if (write_layers_buff) {
memcpy(write_layers, write_layers_buff, sizeof(*write_layers) * write_layers_size);
}
@@ -4015,7 +4001,7 @@ void CustomData_data_transfer(const MeshPairRemap *me_remap, const CustomDataTra
}
if (data_src) {
- tmp_data_src = MEM_mallocN(sizeof(*tmp_data_src) * tmp_buff_size, __func__);
+ tmp_data_src = MEM_malloc_arrayN(tmp_buff_size, sizeof(*tmp_data_src), __func__);
}
if (data_type & CD_FAKE) {
diff --git a/source/blender/blenkernel/intern/customdata_file.c b/source/blender/blenkernel/intern/customdata_file.c
index 41579aaa568..d17c9ef5cc6 100644
--- a/source/blender/blenkernel/intern/customdata_file.c
+++ b/source/blender/blenkernel/intern/customdata_file.c
@@ -210,9 +210,13 @@ static int cdf_read_header(CDataFile *cdf)
if (fseek(f, offset, SEEK_SET) != 0)
return 0;
- cdf->layer = MEM_callocN(sizeof(CDataFileLayer) * header->totlayer, "CDataFileLayer");
+ cdf->layer = MEM_calloc_arrayN(header->totlayer, sizeof(CDataFileLayer), "CDataFileLayer");
cdf->totlayer = header->totlayer;
+ if (!cdf->layer) {
+ return 0;
+ }
+
for (a = 0; a < header->totlayer; a++) {
layer = &cdf->layer[a];
@@ -429,7 +433,7 @@ CDataFileLayer *cdf_layer_add(CDataFile *cdf, int type, const char *name, size_t
CDataFileLayer *newlayer, *layer;
/* expand array */
- newlayer = MEM_callocN(sizeof(CDataFileLayer) * (cdf->totlayer + 1), "CDataFileLayer");
+ newlayer = MEM_calloc_arrayN((cdf->totlayer + 1), sizeof(CDataFileLayer), "CDataFileLayer");
memcpy(newlayer, cdf->layer, sizeof(CDataFileLayer) * cdf->totlayer);
cdf->layer = newlayer;
diff --git a/source/blender/blenkernel/intern/data_transfer.c b/source/blender/blenkernel/intern/data_transfer.c
index 3bc09c0173b..38340575e74 100644
--- a/source/blender/blenkernel/intern/data_transfer.c
+++ b/source/blender/blenkernel/intern/data_transfer.c
@@ -107,7 +107,7 @@ bool BKE_object_data_transfer_get_dttypes_capacity(
}
switch (dtdata_type) {
- /* Vertex data */
+ /* Vertex data */
case DT_TYPE_MDEFORMVERT:
*r_advanced_mixing = true;
*r_threshold = true;
@@ -120,7 +120,7 @@ bool BKE_object_data_transfer_get_dttypes_capacity(
case DT_TYPE_BWEIGHT_VERT:
ret = true;
break;
- /* Edge data */
+ /* Edge data */
case DT_TYPE_SHARP_EDGE:
*r_threshold = true;
ret = true;
@@ -139,7 +139,7 @@ bool BKE_object_data_transfer_get_dttypes_capacity(
*r_threshold = true;
ret = true;
break;
- /* Loop/Poly data */
+ /* Loop/Poly data */
case DT_TYPE_UV:
ret = true;
break;
diff --git a/source/blender/blenkernel/intern/deform.c b/source/blender/blenkernel/intern/deform.c
index 13b1aab5e1c..22ff8bf4bb7 100644
--- a/source/blender/blenkernel/intern/deform.c
+++ b/source/blender/blenkernel/intern/deform.c
@@ -76,7 +76,7 @@ bDeformGroup *BKE_defgroup_new(Object *ob, const char *name)
return defgroup;
}
-void defgroup_copy_list(ListBase *outbase, ListBase *inbase)
+void defgroup_copy_list(ListBase *outbase, const ListBase *inbase)
{
bDeformGroup *defgroup, *defgroupn;
@@ -88,7 +88,7 @@ void defgroup_copy_list(ListBase *outbase, ListBase *inbase)
}
}
-bDeformGroup *defgroup_duplicate(bDeformGroup *ingroup)
+bDeformGroup *defgroup_duplicate(const bDeformGroup *ingroup)
{
bDeformGroup *outgroup;
@@ -621,8 +621,17 @@ float defvert_find_weight(const struct MDeformVert *dvert, const int defgroup)
*/
float defvert_array_find_weight_safe(const struct MDeformVert *dvert, const int index, const int defgroup)
{
- if (defgroup == -1 || dvert == NULL)
+ /* Invalid defgroup index means the vgroup selected is invalid, does not exist, in that case it is OK to return 1.0
+ * (i.e. maximum weight, as if no vgroup was selected).
+ * But in case of valid defgroup and NULL dvert data pointer, it means that vgroup **is** valid,
+ * and just totally empty, so we shall return '0.0' value then!
+ */
+ if (defgroup == -1) {
return 1.0f;
+ }
+ else if (dvert == NULL) {
+ return 0.0f;
+ }
return defvert_find_weight(dvert + index, defgroup);
}
diff --git a/source/blender/blenkernel/intern/depsgraph.c b/source/blender/blenkernel/intern/depsgraph.c
index 294a4ce76b7..c29dc6c9311 100644
--- a/source/blender/blenkernel/intern/depsgraph.c
+++ b/source/blender/blenkernel/intern/depsgraph.c
@@ -67,6 +67,7 @@
#include "BKE_action.h"
#include "BKE_DerivedMesh.h"
#include "BKE_collision.h"
+#include "BKE_curve.h"
#include "BKE_effect.h"
#include "BKE_fcurve.h"
#include "BKE_global.h"
@@ -500,7 +501,51 @@ void dag_add_forcefield_relations(DagForest *dag, Scene *scene, Object *ob, DagN
pdEndEffectors(&effectors);
}
-static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Scene *scene, Object *ob, int mask)
+static bool build_deg_tracking_constraints(DagForest *dag,
+ Scene *scene,
+ DagNode *scenenode,
+ bConstraint *con,
+ const bConstraintTypeInfo *cti,
+ DagNode *node,
+ bool is_data)
+{
+ if (!ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK,
+ CONSTRAINT_TYPE_CAMERASOLVER,
+ CONSTRAINT_TYPE_OBJECTSOLVER))
+ {
+ return false;
+ }
+ bool depends_on_camera = false;
+ if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
+ bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
+ if ((data->clip || data->flag & FOLLOWTRACK_ACTIVECLIP) && data->track[0]) {
+ depends_on_camera = true;
+ }
+ if (data->depth_ob != NULL) {
+ DagNode *node2 = dag_get_node(dag, data->depth_ob);
+ dag_add_relation(dag,
+ node2, node,
+ (is_data) ? (DAG_RL_DATA_DATA | DAG_RL_OB_DATA)
+ : (DAG_RL_DATA_OB | DAG_RL_OB_OB),
+ cti->name);
+ }
+ }
+ else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
+ depends_on_camera = true;
+ }
+ if (depends_on_camera && scene->camera != NULL) {
+ DagNode *node2 = dag_get_node(dag, scene->camera);
+ dag_add_relation(dag,
+ node2, node,
+ (is_data) ? (DAG_RL_DATA_DATA | DAG_RL_OB_DATA)
+ : (DAG_RL_DATA_OB | DAG_RL_OB_OB),
+ cti->name);
+ }
+ dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
+ return true;
+}
+
+static void build_dag_object(DagForest *dag, DagNode *scenenode, Scene *scene, Object *ob, int mask)
{
bConstraint *con;
DagNode *node;
@@ -530,8 +575,15 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Sc
const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
ListBase targets = {NULL, NULL};
bConstraintTarget *ct;
-
- if (cti && cti->get_constraint_targets) {
+
+ if (!cti) {
+ continue;
+ }
+
+ if (build_deg_tracking_constraints(dag, scene, scenenode, con, cti, node, true)) {
+ /* pass */
+ }
+ else if (cti->get_constraint_targets) {
cti->get_constraint_targets(con, &targets);
for (ct = targets.first; ct; ct = ct->next) {
@@ -544,10 +596,16 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Sc
if (ct->tar->type == OB_MESH)
node3->customdata_mask |= CD_MASK_MDEFORMVERT;
}
- else if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO, CONSTRAINT_TYPE_SPLINEIK))
+ else if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH,
+ CONSTRAINT_TYPE_CLAMPTO,
+ CONSTRAINT_TYPE_SPLINEIK,
+ CONSTRAINT_TYPE_SHRINKWRAP))
+ {
dag_add_relation(dag, node3, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name);
- else
+ }
+ else {
dag_add_relation(dag, node3, node, DAG_RL_OB_DATA, cti->name);
+ }
}
}
@@ -587,11 +645,17 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Sc
if (ob->modifiers.first) {
ModifierData *md;
-
+ ModifierUpdateDepsgraphContext ctx = {
+ .scene = scene,
+ .object = ob,
+
+ .forest = dag,
+ .obNode = node,
+ };
for (md = ob->modifiers.first; md; md = md->next) {
const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
- if (mti->updateDepgraph) mti->updateDepgraph(md, dag, bmain, scene, ob, node);
+ if (mti->updateDepgraph) mti->updateDepgraph(md, &ctx);
}
}
if (ob->parent) {
@@ -836,29 +900,7 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Sc
continue;
/* special case for camera tracking -- it doesn't use targets to define relations */
- if (ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
- int depends_on_camera = 0;
-
- if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
- bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
-
- if ((data->clip || data->flag & FOLLOWTRACK_ACTIVECLIP) && data->track[0])
- depends_on_camera = 1;
-
- if (data->depth_ob) {
- node2 = dag_get_node(dag, data->depth_ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
- }
- }
- else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER)
- depends_on_camera = 1;
-
- if (depends_on_camera && scene->camera) {
- node2 = dag_get_node(dag, scene->camera);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_OB | DAG_RL_OB_OB, cti->name);
- }
-
- dag_add_relation(dag, scenenode, node, DAG_RL_SCENE, "Scene Relation");
+ if (build_deg_tracking_constraints(dag, scene, scenenode, con, cti, node, false)) {
addtoroot = 0;
}
else if (cti->get_constraint_targets) {
@@ -881,8 +923,12 @@ static void build_dag_object(DagForest *dag, DagNode *scenenode, Main *bmain, Sc
if (obt->type == OB_MESH)
node2->customdata_mask |= CD_MASK_MDEFORMVERT;
}
- else
+ else if (cti->type == CONSTRAINT_TYPE_SHRINKWRAP) {
+ dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, cti->name);
+ }
+ else {
dag_add_relation(dag, node2, node, DAG_RL_OB_OB, cti->name);
+ }
}
addtoroot = 0;
}
@@ -906,7 +952,7 @@ static void build_dag_group(DagForest *dag, DagNode *scenenode, Main *bmain, Sce
group->id.tag |= LIB_TAG_DOIT;
for (go = group->gobject.first; go; go = go->next) {
- build_dag_object(dag, scenenode, bmain, scene, go->ob, mask);
+ build_dag_object(dag, scenenode, scene, go->ob, mask);
if (go->ob->dup_group)
build_dag_group(dag, scenenode, bmain, scene, go->ob->dup_group, mask);
}
@@ -944,9 +990,9 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask)
for (base = sce->base.first; base; base = base->next) {
ob = base->object;
ob->id.tag |= LIB_TAG_DOIT;
- build_dag_object(dag, scenenode, bmain, sce, ob, mask);
+ build_dag_object(dag, scenenode, sce, ob, mask);
if (ob->proxy)
- build_dag_object(dag, scenenode, bmain, sce, ob->proxy, mask);
+ build_dag_object(dag, scenenode, sce, ob->proxy, mask);
if (ob->dup_group)
build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask);
}
@@ -971,9 +1017,9 @@ DagForest *build_dag(Main *bmain, Scene *sce, short mask)
ob = node->ob;
if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
ob->id.tag |= LIB_TAG_DOIT;
- build_dag_object(dag, scenenode, bmain, sce, ob, mask);
+ build_dag_object(dag, scenenode, sce, ob, mask);
if (ob->proxy)
- build_dag_object(dag, scenenode, bmain, sce, ob->proxy, mask);
+ build_dag_object(dag, scenenode, sce, ob->proxy, mask);
if (ob->dup_group)
build_dag_group(dag, scenenode, bmain, sce, ob->dup_group, mask);
}
@@ -1521,7 +1567,7 @@ static bool check_object_tagged_for_update(Object *object)
if (ELEM(object->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_MBALL, OB_LATTICE)) {
ID *data_id = object->data;
- return (data_id->tag & (LIB_TAG_ID_RECALC_DATA | LIB_TAG_ID_RECALC)) != 0;
+ return (data_id->recalc & ID_RECALC_ALL) != 0;
}
return false;
@@ -1769,13 +1815,13 @@ void DAG_scene_free(Scene *sce)
static void lib_id_recalc_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC;
+ id->recalc |= ID_RECALC;
DAG_id_type_tag(bmain, GS(id->name));
}
static void lib_id_recalc_data_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC_DATA;
+ id->recalc |= ID_RECALC_DATA;
DAG_id_type_tag(bmain, GS(id->name));
}
@@ -2008,6 +2054,7 @@ void DAG_scene_flush_update(Main *bmain, Scene *sce, unsigned int lay, const sho
int lasttime;
if (!DEG_depsgraph_use_legacy()) {
+ DEG_scene_flush_update(bmain, sce);
return;
}
@@ -2256,8 +2303,18 @@ static void dag_object_time_update_flags(Main *bmain, Scene *scene, Object *ob)
break;
case OB_FONT:
cu = ob->data;
- if (BLI_listbase_is_empty(&cu->nurb) && cu->str && cu->vfont)
- ob->recalc |= OB_RECALC_DATA;
+ if (cu->str && cu->vfont) {
+ /* Can be in the curve-cache or the curve. */
+ if (ob->curve_cache && !BLI_listbase_is_empty(&ob->curve_cache->disp)) {
+ /* pass */
+ }
+ else if (!BLI_listbase_is_empty(&cu->nurb)) {
+ /* pass */
+ }
+ else {
+ ob->recalc |= OB_RECALC_DATA;
+ }
+ }
break;
case OB_LATTICE:
lt = ob->data;
@@ -2803,8 +2860,7 @@ void DAG_ids_flush_tagged(Main *bmain)
if (id && bmain->id_tag_update[BKE_idcode_to_index(GS(id->name))]) {
for (; id; id = id->next) {
- if (id->tag & (LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA)) {
-
+ if (id->recalc & ID_RECALC_ALL) {
for (dsl = listbase.first; dsl; dsl = dsl->next)
dag_id_flush_update(bmain, dsl->scene, id);
@@ -2924,13 +2980,12 @@ void DAG_ids_clear_recalc(Main *bmain)
if (id && bmain->id_tag_update[BKE_idcode_to_index(GS(id->name))]) {
for (; id; id = id->next) {
- if (id->tag & (LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA))
- id->tag &= ~(LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA);
+ id->recalc &= ~ID_RECALC_ALL;
/* some ID's contain semi-datablock nodetree */
ntree = ntreeFromID(id);
- if (ntree && (ntree->id.tag & (LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA)))
- ntree->id.tag &= ~(LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA);
+ if (ntree)
+ ntree->id.recalc &= ~ID_RECALC_ALL;
}
}
}
@@ -2953,7 +3008,7 @@ void DAG_id_tag_update_ex(Main *bmain, ID *id, short flag)
if (id == NULL) return;
- if (G.debug & G_DEBUG_DEPSGRAPH) {
+ if (G.debug & G_DEBUG_DEPSGRAPH_TAG) {
printf("%s: id=%s flag=%d\n", __func__, id->name, flag);
}
@@ -3043,7 +3098,7 @@ void DAG_id_type_tag(Main *bmain, short idtype)
DAG_id_type_tag(bmain, ID_SCE);
}
- bmain->id_tag_update[BKE_idcode_to_index(idtype)] = 1;
+ atomic_fetch_and_or_uint8((uint8_t *)&bmain->id_tag_update[BKE_idcode_to_index(idtype)], 1);
}
int DAG_id_type_tagged(Main *bmain, short idtype)
@@ -3684,7 +3739,7 @@ void DAG_print_dependencies(Main *UNUSED(bmain),
Scene *scene,
Object *UNUSED(ob))
{
- DEG_debug_graphviz(scene->depsgraph, stdout, "Depsgraph", false);
+ DEG_debug_relations_graphviz(scene->depsgraph, stdout, "Depsgraph");
}
#endif
diff --git a/source/blender/blenkernel/intern/displist.c b/source/blender/blenkernel/intern/displist.c
index f8a9d57f579..8433634f749 100644
--- a/source/blender/blenkernel/intern/displist.c
+++ b/source/blender/blenkernel/intern/displist.c
@@ -167,10 +167,12 @@ void BKE_displist_normals_add(ListBase *lb)
if (dl->nors == NULL) {
dl->nors = MEM_callocN(sizeof(float) * 3, "dlnors");
- if (dl->verts[2] < 0.0f)
+ if (dl->flag & DL_BACK_CURVE) {
dl->nors[2] = -1.0f;
- else
+ }
+ else {
dl->nors[2] = 1.0f;
+ }
}
}
else if (dl->type == DL_SURF) {
@@ -295,7 +297,10 @@ bool BKE_displist_surfindex_get(DispList *dl, int a, int *b, int *p1, int *p2, i
}
/* ****************** make displists ********************* */
-
+#ifdef __INTEL_COMPILER
+/* ICC with the optimization -02 causes crashes. */
+# pragma intel optimization_level 1
+#endif
static void curve_to_displist(Curve *cu, ListBase *nubase, ListBase *dispbase,
const bool for_render, const bool use_render_resolution)
{
@@ -469,6 +474,7 @@ void BKE_displist_fill(ListBase *dispbase, ListBase *to, const float normal_proj
sf_arena = BLI_memarena_new(BLI_SCANFILL_ARENA_SIZE, __func__);
while (cont) {
+ int dl_flag_accum = 0;
cont = 0;
totvert = 0;
nextcol = 0;
@@ -514,6 +520,7 @@ void BKE_displist_fill(ListBase *dispbase, ListBase *to, const float normal_proj
nextcol = 1;
}
}
+ dl_flag_accum |= dl->flag;
}
dl = dl->next;
}
@@ -526,6 +533,7 @@ void BKE_displist_fill(ListBase *dispbase, ListBase *to, const float normal_proj
if (tot) {
dlnew = MEM_callocN(sizeof(DispList), "filldisplist");
dlnew->type = DL_INDEX3;
+ dlnew->flag = (dl_flag_accum & (DL_BACK_CURVE | DL_FRONT_CURVE));
dlnew->col = colnr;
dlnew->nr = totvert;
dlnew->parts = tot;
@@ -603,6 +611,7 @@ static void bevels_to_filledpoly(Curve *cu, ListBase *dispbase)
dlnew->nr = dl->parts;
dlnew->parts = 1;
dlnew->type = DL_POLY;
+ dlnew->flag = DL_BACK_CURVE;
dlnew->col = dl->col;
dlnew->charidx = dl->charidx;
@@ -623,6 +632,7 @@ static void bevels_to_filledpoly(Curve *cu, ListBase *dispbase)
dlnew->nr = dl->parts;
dlnew->parts = 1;
dlnew->type = DL_POLY;
+ dlnew->flag = DL_FRONT_CURVE;
dlnew->col = dl->col;
dlnew->charidx = dl->charidx;
diff --git a/source/blender/blenkernel/intern/dynamicpaint.c b/source/blender/blenkernel/intern/dynamicpaint.c
index dc9f3b57f1f..3a70a4233b8 100644
--- a/source/blender/blenkernel/intern/dynamicpaint.c
+++ b/source/blender/blenkernel/intern/dynamicpaint.c
@@ -54,7 +54,8 @@
#include "BKE_animsys.h"
#include "BKE_armature.h"
-#include "BKE_bvhutils.h" /* bvh tree */
+#include "BKE_bvhutils.h" /* bvh tree */
+#include "BKE_colorband.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_constraint.h"
#include "BKE_customdata.h"
@@ -72,7 +73,6 @@
#include "BKE_particle.h"
#include "BKE_pointcache.h"
#include "BKE_scene.h"
-#include "BKE_texture.h"
/* for image output */
#include "IMB_imbuf_types.h"
@@ -611,16 +611,19 @@ static void freeGrid(PaintSurfaceData *data)
bData->grid = NULL;
}
-static void grid_bound_insert_cb_ex(void *userdata, void *userdata_chunk, const int i, const int UNUSED(thread_id))
+static void grid_bound_insert_cb_ex(void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict tls)
{
PaintBakeData *bData = userdata;
- Bounds3D *grid_bound = userdata_chunk;
+ Bounds3D *grid_bound = tls->userdata_chunk;
boundInsert(grid_bound, bData->realCoord[bData->s_pos[i]].v);
}
-static void grid_bound_insert_finalize(void *userdata, void *userdata_chunk)
+static void grid_bound_insert_finalize(void *__restrict userdata,
+ void *__restrict userdata_chunk)
{
PaintBakeData *bData = userdata;
VolumeGrid *grid = bData->grid;
@@ -631,12 +634,14 @@ static void grid_bound_insert_finalize(void *userdata, void *userdata_chunk)
boundInsert(&grid->grid_bounds, grid_bound->max);
}
-static void grid_cell_points_cb_ex(void *userdata, void *userdata_chunk, const int i, const int UNUSED(thread_id))
+static void grid_cell_points_cb_ex(void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict tls)
{
PaintBakeData *bData = userdata;
VolumeGrid *grid = bData->grid;
int *temp_t_index = grid->temp_t_index;
- int *s_num = userdata_chunk;
+ int *s_num = tls->userdata_chunk;
int co[3];
@@ -650,7 +655,8 @@ static void grid_cell_points_cb_ex(void *userdata, void *userdata_chunk, const i
s_num[temp_t_index[i]]++;
}
-static void grid_cell_points_finalize(void *userdata, void *userdata_chunk)
+static void grid_cell_points_finalize(void *__restrict userdata,
+ void *__restrict userdata_chunk)
{
PaintBakeData *bData = userdata;
VolumeGrid *grid = bData->grid;
@@ -664,7 +670,9 @@ static void grid_cell_points_finalize(void *userdata, void *userdata_chunk)
}
}
-static void grid_cell_bounds_cb(void *userdata, const int x)
+static void grid_cell_bounds_cb(void *__restrict userdata,
+ const int x,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PaintBakeData *bData = userdata;
VolumeGrid *grid = bData->grid;
@@ -709,10 +717,19 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
/* calculate canvas dimensions */
/* Important to init correctly our ref grid_bound... */
boundInsert(&grid->grid_bounds, bData->realCoord[bData->s_pos[0]].v);
- BLI_task_parallel_range_finalize(
- 0, sData->total_points, bData, &grid->grid_bounds, sizeof(grid->grid_bounds),
- grid_bound_insert_cb_ex, grid_bound_insert_finalize, sData->total_points > 1000, false);
-
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ settings.userdata_chunk = &grid->grid_bounds;
+ settings.userdata_chunk_size = sizeof(grid->grid_bounds);
+ settings.func_finalize = grid_bound_insert_finalize;
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ bData,
+ grid_bound_insert_cb_ex,
+ &settings);
+ }
/* get dimensions */
sub_v3_v3v3(dim, grid->grid_bounds.max, grid->grid_bounds.min);
copy_v3_v3(td, dim);
@@ -761,9 +778,19 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
if (!error) {
/* calculate number of points withing each cell */
- BLI_task_parallel_range_finalize(
- 0, sData->total_points, bData, grid->s_num, sizeof(*grid->s_num) * grid_cells,
- grid_cell_points_cb_ex, grid_cell_points_finalize, sData->total_points > 1000, false);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ settings.userdata_chunk = grid->s_num;
+ settings.userdata_chunk_size = sizeof(*grid->s_num) * grid_cells;
+ settings.func_finalize = grid_cell_points_finalize;
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ bData,
+ grid_cell_points_cb_ex,
+ &settings);
+ }
/* calculate grid indexes (not needed for first cell, which is zero). */
for (i = 1; i < grid_cells; i++) {
@@ -779,7 +806,15 @@ static void surfaceGenerateGrid(struct DynamicPaintSurface *surface)
}
/* calculate cell bounds */
- BLI_task_parallel_range(0, grid->dim[0], bData, grid_cell_bounds_cb, grid_cells > 1000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (grid_cells > 1000);
+ BLI_task_parallel_range(0, grid->dim[0],
+ bData,
+ grid_cell_bounds_cb,
+ &settings);
+ }
}
if (temp_s_num)
@@ -1092,7 +1127,7 @@ bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, str
{
CBData *ramp;
- brush->paint_ramp = add_colorband(false);
+ brush->paint_ramp = BKE_colorband_add(false);
if (!brush->paint_ramp)
return false;
ramp = brush->paint_ramp->data;
@@ -1108,7 +1143,7 @@ bool dynamicPaint_createType(struct DynamicPaintModifierData *pmd, int type, str
{
CBData *ramp;
- brush->vel_ramp = add_colorband(false);
+ brush->vel_ramp = BKE_colorband_add(false);
if (!brush->vel_ramp)
return false;
ramp = brush->vel_ramp->data;
@@ -1397,7 +1432,10 @@ typedef struct DynamicPaintSetInitColorData {
const bool scene_color_manage;
} DynamicPaintSetInitColorData;
-static void dynamic_paint_set_init_color_tex_to_vcol_cb(void *userdata, const int i)
+static void dynamic_paint_set_init_color_tex_to_vcol_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintSetInitColorData *data = userdata;
@@ -1431,7 +1469,10 @@ static void dynamic_paint_set_init_color_tex_to_vcol_cb(void *userdata, const in
}
}
-static void dynamic_paint_set_init_color_tex_to_imseq_cb(void *userdata, const int i)
+static void dynamic_paint_set_init_color_tex_to_imseq_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintSetInitColorData *data = userdata;
@@ -1469,7 +1510,10 @@ static void dynamic_paint_set_init_color_tex_to_imseq_cb(void *userdata, const i
pPoint[i].color[3] = texres.tin;
}
-static void dynamic_paint_set_init_color_vcol_to_imseq_cb(void *userdata, const int i)
+static void dynamic_paint_set_init_color_vcol_to_imseq_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintSetInitColorData *data = userdata;
@@ -1547,7 +1591,13 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface
.mloop = mloop, .mlooptri = mlooptri, .mloopuv = mloopuv, .pool = pool,
.scene_color_manage = scene_color_manage
};
- BLI_task_parallel_range(0, tottri, &data, dynamic_paint_set_init_color_tex_to_vcol_cb, tottri > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (tottri > 1000);
+ BLI_task_parallel_range(0, tottri,
+ &data,
+ dynamic_paint_set_init_color_tex_to_vcol_cb,
+ &settings);
BKE_image_pool_free(pool);
}
else if (surface->format == MOD_DPAINT_SURFACE_F_IMAGESEQ) {
@@ -1556,8 +1606,13 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface
.mlooptri = mlooptri, .mloopuv = mloopuv,
.scene_color_manage = scene_color_manage
};
- BLI_task_parallel_range(0, sData->total_points, &data, dynamic_paint_set_init_color_tex_to_imseq_cb,
- sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_set_init_color_tex_to_imseq_cb,
+ &settings);
}
}
/* vertex color layer */
@@ -1585,8 +1640,13 @@ static void dynamicPaint_setInitialColor(const Scene *scene, DynamicPaintSurface
.surface = surface,
.mlooptri = mlooptri, .mloopcol = col,
};
- BLI_task_parallel_range(0, sData->total_points, &data, dynamic_paint_set_init_color_vcol_to_imseq_cb,
- sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_set_init_color_vcol_to_imseq_cb,
+ &settings);
}
}
}
@@ -1673,7 +1733,10 @@ typedef struct DynamicPaintModifierApplyData {
MLoopCol *mloopcol_preview;
} DynamicPaintModifierApplyData;
-static void dynamic_paint_apply_surface_displace_cb(void *userdata, const int i)
+static void dynamic_paint_apply_surface_displace_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintModifierApplyData *data = userdata;
@@ -1703,12 +1766,20 @@ static void dynamicPaint_applySurfaceDisplace(DynamicPaintSurface *surface, Deri
MVert *mvert = result->getVertArray(result);
DynamicPaintModifierApplyData data = {.surface = surface, .mvert = mvert};
- BLI_task_parallel_range(0, sData->total_points, &data, dynamic_paint_apply_surface_displace_cb,
- sData->total_points > 10000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 10000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_apply_surface_displace_cb,
+ &settings);
}
}
-static void dynamic_paint_apply_surface_vpaint_blend_cb(void *userdata, const int i)
+static void dynamic_paint_apply_surface_vpaint_blend_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintModifierApplyData *data = userdata;
@@ -1719,7 +1790,10 @@ static void dynamic_paint_apply_surface_vpaint_blend_cb(void *userdata, const in
blendColors(pPoint[i].color, pPoint[i].color[3], pPoint[i].e_color, pPoint[i].e_color[3], fcolor[i]);
}
-static void dynamic_paint_apply_surface_vpaint_cb(void *userdata, const int p_index)
+static void dynamic_paint_apply_surface_vpaint_cb(
+ void *__restrict userdata,
+ const int p_index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintModifierApplyData *data = userdata;
Object *ob = data->ob;
@@ -1789,7 +1863,10 @@ static void dynamic_paint_apply_surface_vpaint_cb(void *userdata, const int p_in
}
}
-static void dynamic_paint_apply_surface_wave_cb(void *userdata, const int i)
+static void dynamic_paint_apply_surface_wave_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintModifierApplyData *data = userdata;
@@ -1836,9 +1913,16 @@ static DerivedMesh *dynamicPaint_Modifier_apply(
float (*fcolor)[4] = MEM_callocN(sizeof(*fcolor) * sData->total_points, "Temp paint color");
DynamicPaintModifierApplyData data = {.surface = surface, .fcolor = fcolor};
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_apply_surface_vpaint_blend_cb,
- sData->total_points > 1000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_apply_surface_vpaint_blend_cb,
+ &settings);
+ }
/* paint layer */
MLoopCol *mloopcol = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, surface->output_name);
@@ -1873,8 +1957,16 @@ static DerivedMesh *dynamicPaint_Modifier_apply(
data.mloopcol_wet = mloopcol_wet;
data.mloopcol_preview = mloopcol_preview;
- BLI_task_parallel_range(0, totpoly, &data, dynamic_paint_apply_surface_vpaint_cb,
- totpoly > 1000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (totpoly > 1000);
+ BLI_task_parallel_range(
+ 0, totpoly,
+ &data,
+ dynamic_paint_apply_surface_vpaint_cb,
+ &settings);
+ }
MEM_freeN(fcolor);
@@ -1897,8 +1989,8 @@ static DerivedMesh *dynamicPaint_Modifier_apply(
/* apply weights into a vertex group, if doesnt exists add a new layer */
if (defgrp_index != -1 && !dvert && (surface->output_name[0] != '\0')) {
- dvert = CustomData_add_layer_named(&result->vertData, CD_MDEFORMVERT, CD_CALLOC,
- NULL, sData->total_points, surface->output_name);
+ dvert = CustomData_add_layer(&result->vertData, CD_MDEFORMVERT, CD_CALLOC,
+ NULL, sData->total_points);
}
if (defgrp_index != -1 && dvert) {
int i;
@@ -1924,8 +2016,14 @@ static DerivedMesh *dynamicPaint_Modifier_apply(
MVert *mvert = result->getVertArray(result);
DynamicPaintModifierApplyData data = {.surface = surface, .mvert = mvert};
- BLI_task_parallel_range(0, sData->total_points, &data, dynamic_paint_apply_surface_wave_cb,
- sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_apply_surface_wave_cb,
+ &settings);
update_normals = true;
}
@@ -2060,9 +2158,6 @@ DerivedMesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, Scene *scen
if (pmd->canvas) {
DerivedMesh *ret;
- /* For now generate looptris in every case */
- DM_ensure_looptri(dm);
-
/* Update canvas data for a new frame */
dynamicPaint_frameUpdate(pmd, scene, ob, dm);
@@ -2072,9 +2167,6 @@ DerivedMesh *dynamicPaint_Modifier_do(DynamicPaintModifierData *pmd, Scene *scen
return ret;
}
else {
- /* For now generate looptris in every case */
- DM_ensure_looptri(dm);
-
/* Update canvas data for a new frame */
dynamicPaint_frameUpdate(pmd, scene, ob, dm);
@@ -2112,7 +2204,10 @@ typedef struct DynamicPaintCreateUVSurfaceData {
uint32_t *active_points;
} DynamicPaintCreateUVSurfaceData;
-static void dynamic_paint_create_uv_surface_direct_cb(void *userdata, const int ty)
+static void dynamic_paint_create_uv_surface_direct_cb(
+ void *__restrict userdata,
+ const int ty,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintCreateUVSurfaceData *data = userdata;
@@ -2209,7 +2304,10 @@ static void dynamic_paint_create_uv_surface_direct_cb(void *userdata, const int
}
}
-static void dynamic_paint_create_uv_surface_neighbor_cb(void *userdata, const int ty)
+static void dynamic_paint_create_uv_surface_neighbor_cb(
+ void *__restrict userdata,
+ const int ty,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintCreateUVSurfaceData *data = userdata;
@@ -2460,8 +2558,7 @@ static void dynamic_paint_find_island_border(
const unsigned int *other_loop_idx = mlooptri[lt_index].tri;
/* Check edges for match, looping in the same order as the outer loop. */
- for (int j = 0; j < 3; j++)
- {
+ for (int j = 0; j < 3; j++) {
const int overt0 = mloop[other_loop_idx[(j + 0)]].v;
const int overt1 = mloop[other_loop_idx[(j + 1) % 3]].v;
@@ -2525,8 +2622,7 @@ static void dynamic_paint_find_island_border(
int final_pixel[2] = { (int)floorf(tgt_pixel[0] * w), (int)floorf(tgt_pixel[1] * h) };
/* If current pixel uv is outside of texture */
- if (final_pixel[0] < 0 || final_pixel[0] >= w || final_pixel[1] < 0 || final_pixel[1] >= h)
- {
+ if (final_pixel[0] < 0 || final_pixel[0] >= w || final_pixel[1] < 0 || final_pixel[1] >= h) {
if (bdata->best_index == NOT_FOUND)
bdata->best_index = OUT_OF_TEXTURE;
@@ -2771,7 +2867,15 @@ int dynamicPaint_createUVSurface(Scene *scene, DynamicPaintSurface *surface, flo
.mlooptri = mlooptri, .mloopuv = mloopuv, .mloop = mloop, .tottri = tottri,
.faceBB = faceBB,
};
- BLI_task_parallel_range(0, h, &data, dynamic_paint_create_uv_surface_direct_cb, h > 64 || tottri > 1000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (h > 64 || tottri > 1000);
+ BLI_task_parallel_range(0, h,
+ &data,
+ dynamic_paint_create_uv_surface_direct_cb,
+ &settings);
+ }
*progress = 0.04f;
*do_update = true;
@@ -2783,7 +2887,15 @@ int dynamicPaint_createUVSurface(Scene *scene, DynamicPaintSurface *surface, flo
* (To avoid seams on uv island edges)
*/
data.active_points = &active_points;
- BLI_task_parallel_range(0, h, &data, dynamic_paint_create_uv_surface_neighbor_cb, h > 64);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (h > 64);
+ BLI_task_parallel_range(0, h,
+ &data,
+ dynamic_paint_create_uv_surface_neighbor_cb,
+ &settings);
+ }
*progress = 0.06f;
*do_update = true;
@@ -2942,7 +3054,7 @@ int dynamicPaint_createUVSurface(Scene *scene, DynamicPaintSurface *surface, flo
if (tempPoints[index].tri_index != -1) {
memcpy(&f_data->uv_p[cursor], &tempPoints[index], sizeof(PaintUVPoint));
memcpy(&f_data->barycentricWeights[cursor * aa_samples], &tempWeights[index * aa_samples],
- sizeof(*tempWeights) * aa_samples);
+ sizeof(*tempWeights) * aa_samples);
cursor++;
}
}
@@ -3003,7 +3115,10 @@ typedef struct DynamicPaintOutputSurfaceImageData {
ImBuf *ibuf;
} DynamicPaintOutputSurfaceImageData;
-static void dynamic_paint_output_surface_image_paint_cb(void *userdata, const int index)
+static void dynamic_paint_output_surface_image_paint_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintOutputSurfaceImageData *data = userdata;
@@ -3023,7 +3138,10 @@ static void dynamic_paint_output_surface_image_paint_cb(void *userdata, const in
}
}
-static void dynamic_paint_output_surface_image_displace_cb(void *userdata, const int index)
+static void dynamic_paint_output_surface_image_displace_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintOutputSurfaceImageData *data = userdata;
@@ -3047,7 +3165,10 @@ static void dynamic_paint_output_surface_image_displace_cb(void *userdata, const
ibuf->rect_float[pos + 3] = 1.0f;
}
-static void dynamic_paint_output_surface_image_wave_cb(void *userdata, const int index)
+static void dynamic_paint_output_surface_image_wave_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintOutputSurfaceImageData *data = userdata;
@@ -3069,7 +3190,10 @@ static void dynamic_paint_output_surface_image_wave_cb(void *userdata, const int
ibuf->rect_float[pos + 3] = 1.0f;
}
-static void dynamic_paint_output_surface_image_wetmap_cb(void *userdata, const int index)
+static void dynamic_paint_output_surface_image_wetmap_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintOutputSurfaceImageData *data = userdata;
@@ -3120,13 +3244,29 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam
case MOD_DPAINT_SURFACE_T_PAINT:
switch (output_layer) {
case 0:
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_output_surface_image_paint_cb, sData->total_points > 10000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 10000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_output_surface_image_paint_cb,
+ &settings);
break;
+ }
case 1:
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_output_surface_image_wetmap_cb, sData->total_points > 10000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 10000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_output_surface_image_wetmap_cb,
+ &settings);
break;
+ }
default:
BLI_assert(0);
break;
@@ -3135,9 +3275,17 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam
case MOD_DPAINT_SURFACE_T_DISPLACE:
switch (output_layer) {
case 0:
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_output_surface_image_displace_cb, sData->total_points > 10000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 10000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_output_surface_image_displace_cb,
+ &settings);
break;
+ }
case 1:
break;
default:
@@ -3148,9 +3296,17 @@ void dynamicPaint_outputSurfaceImage(DynamicPaintSurface *surface, char *filenam
case MOD_DPAINT_SURFACE_T_WAVE:
switch (output_layer) {
case 0:
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_output_surface_image_wave_cb, sData->total_points > 10000);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 10000);
+ BLI_task_parallel_range(
+ 0, sData->total_points,
+ &data,
+ dynamic_paint_output_surface_image_wave_cb,
+ &settings);
break;
+ }
case 1:
break;
default:
@@ -3470,7 +3626,7 @@ static void dynamicPaint_updatePointData(
vel_factor /= brush->max_velocity;
CLAMP(vel_factor, 0.0f, 1.0f);
- if (do_colorband(brush->vel_ramp, vel_factor, coba_res)) {
+ if (BKE_colorband_evaluate(brush->vel_ramp, vel_factor, coba_res)) {
if (brush->flags & MOD_DPAINT_VELOCITY_COLOR) {
copy_v3_v3(paint, coba_res);
}
@@ -3557,7 +3713,10 @@ typedef struct DynamicPaintBrushVelocityData {
const float timescale;
} DynamicPaintBrushVelocityData;
-static void dynamic_paint_brush_velocity_compute_cb(void *userdata, const int i)
+static void dynamic_paint_brush_velocity_compute_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintBrushVelocityData *data = userdata;
@@ -3636,7 +3795,13 @@ static void dynamicPaint_brushMeshCalculateVelocity(
.mvert_p = mvert_p, .mvert_c = mvert_c, .obmat = ob->obmat, .prev_obmat = prev_obmat,
.timescale = timescale,
};
- BLI_task_parallel_range(0, numOfVerts_c, &data, dynamic_paint_brush_velocity_compute_cb, numOfVerts_c > 10000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numOfVerts_c > 10000);
+ BLI_task_parallel_range(0, numOfVerts_c,
+ &data,
+ dynamic_paint_brush_velocity_compute_cb,
+ &settings);
dm_p->release(dm_p);
}
@@ -3707,7 +3872,9 @@ typedef struct DynamicPaintPaintData {
* Paint a brush object mesh to the surface
*/
static void dynamic_paint_paint_mesh_cell_point_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int id, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int id,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintPaintData *data = userdata;
@@ -3916,7 +4083,7 @@ static void dynamic_paint_paint_mesh_cell_point_cb_ex(
else if (hit_found == HIT_PROXIMITY) {
/* apply falloff curve to the proximity_factor */
if (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP &&
- do_colorband(brush->paint_ramp, (1.0f - proximity_factor), prox_colorband))
+ BKE_colorband_evaluate(brush->paint_ramp, (1.0f - proximity_factor), prox_colorband))
{
proximity_factor = prox_colorband[3];
}
@@ -4125,9 +4292,13 @@ static int dynamicPaint_paintMesh(DynamicPaintSurface *surface,
.brush_radius = brush_radius, .avg_brushNor = avg_brushNor, .brushVelocity = brushVelocity,
.treeData = &treeData
};
- BLI_task_parallel_range_ex(0, grid->s_num[c_index], &data, NULL, 0,
- dynamic_paint_paint_mesh_cell_point_cb_ex,
- grid->s_num[c_index] > 250, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (grid->s_num[c_index] > 250);
+ BLI_task_parallel_range(0, grid->s_num[c_index],
+ &data,
+ dynamic_paint_paint_mesh_cell_point_cb_ex,
+ &settings);
}
}
}
@@ -4148,7 +4319,9 @@ static int dynamicPaint_paintMesh(DynamicPaintSurface *surface,
* Paint a particle system to the surface
*/
static void dynamic_paint_paint_particle_cell_point_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int id, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int id,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintPaintData *data = userdata;
@@ -4345,7 +4518,7 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface,
*/
tree = BLI_kdtree_new(psys->totpart);
- /* loop through particles and insert valid ones to the tree */
+ /* loop through particles and insert valid ones to the tree */
p = 0;
for (ParticleData *pa = psys->particles; p < psys->totpart; p++, pa++) {
/* Proceed only if particle is active */
@@ -4384,7 +4557,7 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface,
}
/* begin thread safe malloc */
- BLI_begin_threaded_malloc();
+ BLI_threaded_malloc_begin();
/* only continue if particle bb is close enough to canvas bb */
if (boundsIntersectDist(&grid->grid_bounds, &part_bb, range)) {
@@ -4410,12 +4583,16 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface,
.solidradius = solidradius, .timescale = timescale, .c_index = c_index,
.treeData = tree,
};
- BLI_task_parallel_range_ex(0, grid->s_num[c_index], &data, NULL, 0,
- dynamic_paint_paint_particle_cell_point_cb_ex,
- grid->s_num[c_index] > 250, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (grid->s_num[c_index] > 250);
+ BLI_task_parallel_range(0, grid->s_num[c_index],
+ &data,
+ dynamic_paint_paint_particle_cell_point_cb_ex,
+ &settings);
}
}
- BLI_end_threaded_malloc();
+ BLI_threaded_malloc_end();
BLI_kdtree_free(tree);
return 1;
@@ -4423,7 +4600,9 @@ static int dynamicPaint_paintParticles(DynamicPaintSurface *surface,
/* paint a single point of defined proximity radius to the surface */
static void dynamic_paint_paint_single_point_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int index, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintPaintData *data = userdata;
@@ -4480,7 +4659,7 @@ static void dynamic_paint_paint_single_point_cb_ex(
/* color ramp */
if (brush->proximity_falloff == MOD_DPAINT_PRFALL_RAMP &&
- do_colorband(brush->paint_ramp, (1.0f - strength), colorband))
+ BKE_colorband_evaluate(brush->paint_ramp, (1.0f - strength), colorband))
{
strength = colorband[3];
}
@@ -4555,9 +4734,13 @@ static int dynamicPaint_paintSinglePoint(
.brush_radius = brush_radius, .brushVelocity = &brushVel,
.pointCoord = pointCoord,
};
- BLI_task_parallel_range_ex(0, sData->total_points, &data, NULL, 0,
- dynamic_paint_paint_single_point_cb_ex,
- sData->total_points > 1000, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_paint_single_point_cb_ex,
+ &settings);
return 1;
}
@@ -4569,7 +4752,10 @@ static int dynamicPaint_paintSinglePoint(
* Calculate current frame distances and directions for adjacency data
*/
-static void dynamic_paint_prepare_adjacency_cb(void *userdata, const int index)
+static void dynamic_paint_prepare_adjacency_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PaintSurfaceData *sData = userdata;
PaintBakeData *bData = sData->bData;
@@ -4608,8 +4794,13 @@ static void dynamicPaint_prepareAdjacencyData(DynamicPaintSurface *surface, cons
if (!bNeighs)
return;
- BLI_task_parallel_range(
- 0, sData->total_points, sData, dynamic_paint_prepare_adjacency_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ sData,
+ dynamic_paint_prepare_adjacency_cb,
+ &settings);
/* calculate average values (single thread).
* Note: tried to put this in threaded callback (using _finalize feature), but gave ~30% slower result! */
@@ -4796,7 +4987,10 @@ typedef struct DynamicPaintEffectData {
* Prepare data required by effects for current frame.
* Returns number of steps required
*/
-static void dynamic_paint_prepare_effect_cb(void *userdata, const int index)
+static void dynamic_paint_prepare_effect_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -4868,8 +5062,13 @@ static int dynamicPaint_prepareEffectStep(
.surface = surface, .scene = scene,
.force = *force, .effectors = effectors,
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_prepare_effect_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_prepare_effect_cb,
+ &settings);
/* calculate average values (single thread) */
for (int index = 0; index < sData->total_points; index++) {
@@ -4901,7 +5100,10 @@ static int dynamicPaint_prepareEffectStep(
/**
* Processes active effect step.
*/
-static void dynamic_paint_effect_spread_cb(void *userdata, const int index)
+static void dynamic_paint_effect_spread_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -4946,7 +5148,10 @@ static void dynamic_paint_effect_spread_cb(void *userdata, const int index)
}
}
-static void dynamic_paint_effect_shrink_cb(void *userdata, const int index)
+static void dynamic_paint_effect_shrink_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -4996,7 +5201,10 @@ static void dynamic_paint_effect_shrink_cb(void *userdata, const int index)
}
}
-static void dynamic_paint_effect_drip_cb(void *userdata, const int index)
+static void dynamic_paint_effect_drip_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -5129,8 +5337,13 @@ static void dynamicPaint_doEffectStep(
DynamicPaintEffectData data = {
.surface = surface, .prevPoint = prevPoint, .eff_scale = eff_scale,
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_effect_spread_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_effect_spread_cb,
+ &settings);
}
/*
@@ -5145,8 +5358,13 @@ static void dynamicPaint_doEffectStep(
DynamicPaintEffectData data = {
.surface = surface, .prevPoint = prevPoint, .eff_scale = eff_scale,
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_effect_shrink_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_effect_shrink_cb,
+ &settings);
}
/*
@@ -5167,14 +5385,22 @@ static void dynamicPaint_doEffectStep(
.eff_scale = eff_scale, .force = force,
.point_locks = point_locks,
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_effect_drip_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_effect_drip_cb,
+ &settings);
MEM_freeN(point_locks);
}
}
-static void dynamic_paint_border_cb(void *userdata, const int b_index)
+static void dynamic_paint_border_cb(
+ void *__restrict userdata,
+ const int b_index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -5244,11 +5470,19 @@ static void dynamicPaint_doBorderStep(DynamicPaintSurface *surface)
.surface = surface
};
- BLI_task_parallel_range(
- 0, sData->adj_data->total_border, &data, dynamic_paint_border_cb, sData->adj_data->total_border > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->adj_data->total_border > 1000);
+ BLI_task_parallel_range(0, sData->adj_data->total_border,
+ &data,
+ dynamic_paint_border_cb,
+ &settings);
}
-static void dynamic_paint_wave_step_cb(void *userdata, const int index)
+static void dynamic_paint_wave_step_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintEffectData *data = userdata;
@@ -5390,8 +5624,12 @@ static void dynamicPaint_doWaveStep(DynamicPaintSurface *surface, float timescal
.wave_speed = wave_speed, .wave_scale = wave_scale, .wave_max_slope = wave_max_slope,
.dt = dt, .min_dist = min_dist, .damp_factor = damp_factor, .reset_wave = (ss == steps - 1),
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_wave_step_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data, dynamic_paint_wave_step_cb,
+ &settings);
}
MEM_freeN(prevPoint);
@@ -5411,7 +5649,10 @@ typedef struct DynamicPaintDissolveDryData {
const float timescale;
} DynamicPaintDissolveDryData;
-static void dynamic_paint_surface_pre_step_cb(void *userdata, const int index)
+static void dynamic_paint_surface_pre_step_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintDissolveDryData *data = userdata;
@@ -5534,7 +5775,10 @@ typedef struct DynamicPaintGenerateBakeData {
const bool new_bdata;
} DynamicPaintGenerateBakeData;
-static void dynamic_paint_generate_bake_data_cb(void *userdata, const int index)
+static void dynamic_paint_generate_bake_data_cb(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const DynamicPaintGenerateBakeData *data = userdata;
@@ -5738,8 +5982,13 @@ static int dynamicPaint_generateBakeData(DynamicPaintSurface *surface, const Sce
.mvert = mvert, .canvas_verts = canvas_verts,
.do_velocity_data = do_velocity_data, .new_bdata = new_bdata,
};
- BLI_task_parallel_range(
- 0, sData->total_points, &data, dynamic_paint_generate_bake_data_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_generate_bake_data_cb,
+ &settings);
MEM_freeN(canvas_verts);
@@ -5772,8 +6021,13 @@ static int dynamicPaint_doStep(Scene *scene, Object *ob, DynamicPaintSurface *su
if (dynamic_paint_surface_needs_dry_dissolve(surface)) {
DynamicPaintDissolveDryData data = {.surface = surface, .timescale = timescale};
- BLI_task_parallel_range(0, sData->total_points, &data,
- dynamic_paint_surface_pre_step_cb, sData->total_points > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (sData->total_points > 1000);
+ BLI_task_parallel_range(0, sData->total_points,
+ &data,
+ dynamic_paint_surface_pre_step_cb,
+ &settings);
}
/*
diff --git a/source/blender/blenkernel/intern/editderivedmesh.c b/source/blender/blenkernel/intern/editderivedmesh.c
index e7c0e69b1cb..ffa7fdc3ec9 100644
--- a/source/blender/blenkernel/intern/editderivedmesh.c
+++ b/source/blender/blenkernel/intern/editderivedmesh.c
@@ -41,8 +41,10 @@
* is likely to be a little slow.
*/
+#include "atomic_ops.h"
+
#include "BLI_math.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_bitmap.h"
#include "BLI_task.h"
@@ -149,6 +151,8 @@ static void emDM_ensurePolyCenters(EditDerivedBMesh *bmdm)
const float (*vertexCos)[3];
vertexCos = bmdm->vertexCos;
+ BM_mesh_elem_index_ensure(bm, BM_VERT);
+
BM_ITER_MESH_INDEX (efa, &fiter, bm, BM_FACES_OF_MESH, i) {
BM_face_calc_center_mean_vcos(bm, efa, polyCos[i], vertexCos);
}
@@ -487,8 +491,6 @@ static void emDM_calc_loop_tangents(
EditDerivedBMesh *bmdm = (EditDerivedBMesh *)dm;
BMEditMesh *em = bmdm->em;
BMesh *bm = bmdm->em->bm;
- if (CustomData_number_of_layers(&bm->ldata, CD_MLOOPUV) == 0)
- return;
int act_uv_n = -1;
int ren_uv_n = -1;
@@ -496,7 +498,7 @@ static void emDM_calc_loop_tangents(
bool calc_ren = false;
char act_uv_name[MAX_NAME];
char ren_uv_name[MAX_NAME];
- char tangent_mask = 0;
+ short tangent_mask = 0;
DM_calc_loop_tangents_step_0(
&bm->ldata, calc_active_tangent, tangent_names, tangent_names_count,
@@ -506,6 +508,8 @@ static void emDM_calc_loop_tangents(
for (int i = 0; i < tangent_names_count; i++)
if (tangent_names[i][0])
DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, tangent_names[i]);
+ if ((tangent_mask & DM_TANGENT_MASK_ORCO) && CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, "") == -1)
+ CustomData_add_layer_named(&dm->loopData, CD_TANGENT, CD_CALLOC, NULL, dm->numLoopData, "");
if (calc_act && act_uv_name[0])
DM_add_named_tangent_layer_for_uv(&bm->ldata, &dm->loopData, dm->numLoopData, act_uv_name);
if (calc_ren && ren_uv_name[0])
@@ -572,7 +576,17 @@ static void emDM_calc_loop_tangents(
continue;
/* needed for orco lookups */
htype_index |= BM_VERT;
+ dm->tangent_mask |= DM_TANGENT_MASK_ORCO;
+ }
+ else {
+ /* Fill the resulting tangent_mask */
+ int uv_ind = CustomData_get_named_layer_index(&bm->ldata, CD_MLOOPUV, dm->loopData.layers[index].name);
+ int uv_start = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV);
+ BLI_assert(uv_ind != -1 && uv_start != -1);
+ BLI_assert(uv_ind - uv_start < MAX_MTFACE);
+ dm->tangent_mask |= 1 << (uv_ind - uv_start);
}
+
if (mesh2tangent->precomputedFaceNormals) {
/* needed for face normal lookups */
htype_index |= BM_FACE;
@@ -582,12 +596,6 @@ static void emDM_calc_loop_tangents(
mesh2tangent->looptris = (const BMLoop *(*)[3])em->looptris;
mesh2tangent->tangent = dm->loopData.layers[index].data;
- /* Fill the resulting tangent_mask */
- int uv_ind = CustomData_get_named_layer_index(&bm->ldata, CD_MLOOPUV, dm->loopData.layers[index].name);
- int uv_start = CustomData_get_layer_index(&bm->ldata, CD_MLOOPUV);
- BLI_assert(uv_ind != -1 && uv_start != -1);
- BLI_assert(uv_ind - uv_start < MAX_MTFACE);
- dm->tangent_mask |= 1 << (uv_ind - uv_start);
BLI_task_pool_push(task_pool, emDM_calc_loop_tangents_thread, mesh2tangent, false, TASK_PRIORITY_LOW);
}
@@ -602,15 +610,20 @@ static void emDM_calc_loop_tangents(
#undef USE_LOOPTRI_DETECT_QUADS
#endif
}
+
/* Update active layer index */
- int uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, act_uv_n);
- int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name);
- CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index);
+ int act_uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, act_uv_n);
+ if (act_uv_index >= 0) {
+ int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[act_uv_index].name);
+ CustomData_set_layer_active_index(&dm->loopData, CD_TANGENT, tan_index);
+ } /* else tangent has been built from orco */
/* Update render layer index */
- uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, ren_uv_n);
- tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[uv_index].name);
- CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index);
+ int ren_uv_index = CustomData_get_layer_index_n(&bm->ldata, CD_MLOOPUV, ren_uv_n);
+ if (ren_uv_index >= 0) {
+ int tan_index = CustomData_get_named_layer_index(&dm->loopData, CD_TANGENT, bm->ldata.layers[ren_uv_index].name);
+ CustomData_set_layer_render_index(&dm->loopData, CD_TANGENT, tan_index);
+ } /* else tangent has been built from orco */
}
/** \} */
@@ -630,8 +643,9 @@ static void emDM_recalcLoopTri(DerivedMesh *dm)
int i;
DM_ensure_looptri_data(dm);
- mlooptri = dm->looptris.array;
+ mlooptri = dm->looptris.array_wip;
+ BLI_assert(tottri == 0 || mlooptri != NULL);
BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
BLI_assert(tottri == dm->looptris.num);
@@ -642,24 +656,16 @@ static void emDM_recalcLoopTri(DerivedMesh *dm)
MLoopTri *lt = &mlooptri[i];
ARRAY_SET_ITEMS(
- lt->tri,
- BM_elem_index_get(ltri[0]),
- BM_elem_index_get(ltri[1]),
- BM_elem_index_get(ltri[2]));
+ lt->tri,
+ BM_elem_index_get(ltri[0]),
+ BM_elem_index_get(ltri[1]),
+ BM_elem_index_get(ltri[2]));
lt->poly = BM_elem_index_get(ltri[0]->f);
}
-}
-static const MLoopTri *emDM_getLoopTriArray(DerivedMesh *dm)
-{
- if (dm->looptris.array) {
- BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
- }
- else {
- dm->recalcLoopTri(dm);
- }
-
- return dm->looptris.array;
+ BLI_assert(dm->looptris.array == NULL);
+ atomic_cas_ptr((void **)&dm->looptris.array, dm->looptris.array, dm->looptris.array_wip);
+ dm->looptris.array_wip = NULL;
}
static void emDM_foreachMappedVert(
@@ -1030,11 +1036,11 @@ static void emDM_drawMappedFaces(
if (poly_prev != GL_ZERO) glEnd();
glBegin((poly_prev = poly_type)); /* BMesh: will always be GL_TRIANGLES */
}
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[0]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[1]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[2]->v)]);
}
else {
@@ -1051,23 +1057,23 @@ static void emDM_drawMappedFaces(
if (!drawSmooth) {
glNormal3fv(polyNos[BM_elem_index_get(efa)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[0]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[1]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[2]->v)]);
}
else {
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[0])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[0]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[0]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[1])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[1]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[1]->v)]);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[2])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[2]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[2]->v)]);
@@ -1132,11 +1138,11 @@ static void emDM_drawMappedFaces(
if (poly_prev != GL_ZERO) glEnd();
glBegin((poly_prev = poly_type)); /* BMesh: will always be GL_TRIANGLES */
}
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(ltri[0]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(ltri[1]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(ltri[2]->v->co);
}
else {
@@ -1153,23 +1159,23 @@ static void emDM_drawMappedFaces(
if (!drawSmooth) {
glNormal3fv(efa->no);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(ltri[0]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(ltri[1]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(ltri[2]->v->co);
}
else {
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[0])]);
else glNormal3fv(ltri[0]->v->no);
glVertex3fv(ltri[0]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[1])]);
else glNormal3fv(ltri[1]->v->no);
glVertex3fv(ltri[1]->v->co);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[2])]);
else glNormal3fv(ltri[2]->v->no);
glVertex3fv(ltri[2]->v->co);
@@ -1292,32 +1298,32 @@ static void emDM_drawFacesTex_common(
glNormal3fv(polyNos[BM_elem_index_get(efa)]);
glTexCoord2fv(luv[0]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[0]->v)]);
glTexCoord2fv(luv[1]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[1]->v)]);
glTexCoord2fv(luv[2]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(vertexCos[BM_elem_index_get(ltri[2]->v)]);
}
else {
glTexCoord2fv(luv[0]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[0])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[0]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[0]->v)]);
glTexCoord2fv(luv[1]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[1])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[1]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[1]->v)]);
glTexCoord2fv(luv[2]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[2])]);
else glNormal3fv(vertexNos[BM_elem_index_get(ltri[2]->v)]);
glVertex3fv(vertexCos[BM_elem_index_get(ltri[2]->v)]);
@@ -1356,32 +1362,32 @@ static void emDM_drawFacesTex_common(
glNormal3fv(efa->no);
glTexCoord2fv(luv[0]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
glVertex3fv(ltri[0]->v->co);
glTexCoord2fv(luv[1]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
glVertex3fv(ltri[1]->v->co);
glTexCoord2fv(luv[2]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
glVertex3fv(ltri[2]->v->co);
}
else {
glTexCoord2fv(luv[0]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[0]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[0]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[0])]);
else glNormal3fv(ltri[0]->v->no);
glVertex3fv(ltri[0]->v->co);
glTexCoord2fv(luv[1]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[1]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[1]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[1])]);
else glNormal3fv(ltri[1]->v->no);
glVertex3fv(ltri[1]->v->co);
glTexCoord2fv(luv[2]->uv);
- if (has_vcol_any) glColor3ubv((const GLubyte *)&(lcol[2]->r));
+ if (has_vcol_any) glColor4ubv((const GLubyte *)&(lcol[2]->r));
if (lnors) glNormal3fv(lnors[BM_elem_index_get(ltri[2])]);
else glNormal3fv(ltri[2]->v->no);
glVertex3fv(ltri[2]->v->co);
@@ -2053,20 +2059,25 @@ static void *emDM_getTessFaceDataArray(DerivedMesh *dm, int type)
/* 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) {
- const int type_from = (type == CD_MTFACE) ? CD_MTEXPOLY : CD_MLOOPCOL;
- int index;
const char *bmdata;
char *data;
- index = CustomData_get_layer_index(&bm->pdata, type_from);
+ bool has_type_source = false;
- if (index != -1) {
+ if (type == CD_MTFACE) {
+ has_type_source = CustomData_has_layer(&bm->pdata, CD_MTEXPOLY);
+ }
+ else {
+ has_type_source = CustomData_has_layer(&bm->ldata, CD_MLOOPCOL);
+ }
+
+ if (has_type_source) {
/* offset = bm->pdata.layers[index].offset; */ /* UNUSED */
BMLoop *(*looptris)[3] = bmdm->em->looptris;
const int size = CustomData_sizeof(type);
int i, j;
DM_add_tessface_layer(dm, type, CD_CALLOC, NULL);
- index = CustomData_get_layer_index(&dm->faceData, type);
+ const int index = CustomData_get_layer_index(&dm->faceData, type);
dm->faceData.layers[index].flag |= CD_FLAG_TEMPORARY;
data = datalayer = DM_get_tessface_data_layer(dm, type);
@@ -2243,8 +2254,6 @@ DerivedMesh *getEditDerivedBMesh(
bmdm->dm.getNumLoops = emDM_getNumLoops;
bmdm->dm.getNumPolys = emDM_getNumPolys;
- bmdm->dm.getLoopTriArray = emDM_getLoopTriArray;
-
bmdm->dm.getVert = emDM_getVert;
bmdm->dm.getVertCo = emDM_getVertCo;
bmdm->dm.getVertNo = emDM_getVertNo;
@@ -2625,7 +2634,7 @@ static void statvis_calc_distort(
vertexCos[BM_elem_index_get(l_iter->next->v)]);
}
else {
- BM_loop_calc_face_normal(l_iter, no_corner);
+ BM_loop_calc_face_normal_safe(l_iter, no_corner);
}
/* simple way to detect (what is most likely) concave */
if (dot_v3v3(f_no, no_corner) < 0.0f) {
diff --git a/source/blender/blenkernel/intern/editlattice.c b/source/blender/blenkernel/intern/editlattice.c
new file mode 100644
index 00000000000..cef3c970c7a
--- /dev/null
+++ b/source/blender/blenkernel/intern/editlattice.c
@@ -0,0 +1,147 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenkernel/intern/editlattice.c
+ * \ingroup bke
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_listBase.h"
+#include "DNA_object_types.h"
+#include "DNA_key_types.h"
+#include "DNA_lattice_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_curve_types.h"
+
+#include "BLI_math_vector.h"
+#include "BLI_listbase.h"
+
+#include "BKE_deform.h"
+#include "BKE_key.h"
+
+#include "BKE_editlattice.h" /* own include */
+
+void BKE_editlattice_free(Object *ob)
+{
+ Lattice *lt = ob->data;
+
+ if (lt->editlatt) {
+ Lattice *editlt = lt->editlatt->latt;
+
+ if (editlt->def) {
+ MEM_freeN(editlt->def);
+ }
+ if (editlt->dvert) {
+ BKE_defvert_array_free(editlt->dvert, editlt->pntsu * editlt->pntsv * editlt->pntsw);
+ }
+ MEM_freeN(editlt);
+ MEM_freeN(lt->editlatt);
+
+ lt->editlatt = NULL;
+ }
+}
+
+void BKE_editlattice_make(Object *obedit)
+{
+ Lattice *lt = obedit->data;
+ KeyBlock *actkey;
+
+ BKE_editlattice_free(obedit);
+
+ actkey = BKE_keyblock_from_object(obedit);
+ if (actkey) {
+ BKE_keyblock_convert_to_lattice(actkey, lt);
+ }
+ lt->editlatt = MEM_callocN(sizeof(EditLatt), "editlatt");
+ lt->editlatt->latt = MEM_dupallocN(lt);
+ lt->editlatt->latt->def = MEM_dupallocN(lt->def);
+
+ if (lt->dvert) {
+ int tot = lt->pntsu * lt->pntsv * lt->pntsw;
+ lt->editlatt->latt->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
+ BKE_defvert_array_copy(lt->editlatt->latt->dvert, lt->dvert, tot);
+ }
+
+ if (lt->key) {
+ lt->editlatt->shapenr = obedit->shapenr;
+ }
+}
+
+void BKE_editlattice_load(Object *obedit)
+{
+ Lattice *lt, *editlt;
+ KeyBlock *actkey;
+ BPoint *bp;
+ float *fp;
+ int tot;
+
+ lt = obedit->data;
+ editlt = lt->editlatt->latt;
+
+ if (lt->editlatt->shapenr) {
+ actkey = BLI_findlink(&lt->key->block, lt->editlatt->shapenr - 1);
+
+ /* active key: vertices */
+ tot = editlt->pntsu * editlt->pntsv * editlt->pntsw;
+
+ if (actkey->data) {
+ MEM_freeN(actkey->data);
+ }
+
+ fp = actkey->data = MEM_callocN(lt->key->elemsize * tot, "actkey->data");
+ actkey->totelem = tot;
+
+ bp = editlt->def;
+ while (tot--) {
+ copy_v3_v3(fp, bp->vec);
+ fp += 3;
+ bp++;
+ }
+ }
+ else {
+ MEM_freeN(lt->def);
+
+ lt->def = MEM_dupallocN(editlt->def);
+
+ lt->flag = editlt->flag;
+
+ lt->pntsu = editlt->pntsu;
+ lt->pntsv = editlt->pntsv;
+ lt->pntsw = editlt->pntsw;
+
+ lt->typeu = editlt->typeu;
+ lt->typev = editlt->typev;
+ lt->typew = editlt->typew;
+ lt->actbp = editlt->actbp;
+ }
+
+ if (lt->dvert) {
+ BKE_defvert_array_free(lt->dvert, lt->pntsu * lt->pntsv * lt->pntsw);
+ lt->dvert = NULL;
+ }
+
+ if (editlt->dvert) {
+ tot = lt->pntsu * lt->pntsv * lt->pntsw;
+
+ lt->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
+ BKE_defvert_array_copy(lt->dvert, editlt->dvert, tot);
+ }
+}
diff --git a/source/blender/blenkernel/intern/effect.c b/source/blender/blenkernel/intern/effect.c
index fe8f5ebdca6..e47af83e00e 100644
--- a/source/blender/blenkernel/intern/effect.c
+++ b/source/blender/blenkernel/intern/effect.c
@@ -42,7 +42,7 @@
#include "DNA_listBase.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_particle_types.h"
#include "DNA_texture_types.h"
#include "DNA_scene_types.h"
@@ -504,28 +504,28 @@ float effector_falloff(EffectorCache *eff, EffectorData *efd, EffectedPoint *UNU
falloff=0.0f;
else {
switch (eff->pd->falloff) {
- case PFIELD_FALL_SPHERE:
- falloff*= falloff_func_dist(eff->pd, efd->distance);
- break;
-
- case PFIELD_FALL_TUBE:
- falloff*= falloff_func_dist(eff->pd, ABS(fac));
- if (falloff == 0.0f)
+ case PFIELD_FALL_SPHERE:
+ falloff*= falloff_func_dist(eff->pd, efd->distance);
break;
- madd_v3_v3v3fl(temp, efd->vec_to_point2, efd->nor, -fac);
- r_fac= len_v3(temp);
- falloff*= falloff_func_rad(eff->pd, r_fac);
- break;
- case PFIELD_FALL_CONE:
- falloff*= falloff_func_dist(eff->pd, ABS(fac));
- if (falloff == 0.0f)
+ case PFIELD_FALL_TUBE:
+ falloff*= falloff_func_dist(eff->pd, ABS(fac));
+ if (falloff == 0.0f)
+ break;
+
+ madd_v3_v3v3fl(temp, efd->vec_to_point2, efd->nor, -fac);
+ r_fac= len_v3(temp);
+ falloff*= falloff_func_rad(eff->pd, r_fac);
break;
+ case PFIELD_FALL_CONE:
+ falloff*= falloff_func_dist(eff->pd, ABS(fac));
+ if (falloff == 0.0f)
+ break;
- r_fac= RAD2DEGF(saacos(fac/len_v3(efd->vec_to_point)));
- falloff*= falloff_func_rad(eff->pd, r_fac);
+ r_fac= RAD2DEGF(saacos(fac/len_v3(efd->vec_to_point)));
+ falloff*= falloff_func_rad(eff->pd, r_fac);
- break;
+ break;
}
}
@@ -848,6 +848,14 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected
break;
case PFIELD_FORCE:
normalize_v3(force);
+ if (pd->flag & PFIELD_GRAVITATION){ /* Option: Multiply by 1/distance^2 */
+ if (efd->distance < FLT_EPSILON){
+ strength = 0.0f;
+ }
+ else {
+ strength *= powf(efd->distance, -2.0f);
+ }
+ }
mul_v3_fl(force, strength * efd->falloff);
break;
case PFIELD_VORTEX:
@@ -978,19 +986,19 @@ static void do_physical_effector(EffectorCache *eff, EffectorData *efd, Effected
*/
void pdDoEffectors(ListBase *effectors, ListBase *colliders, EffectorWeights *weights, EffectedPoint *point, float *force, float *impulse)
{
-/*
- * 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)
- */
+ /*
+ * 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)
+ */
EffectorCache *eff;
EffectorData efd;
int p=0, tot = 1, step = 1;
diff --git a/source/blender/blenkernel/intern/fcurve.c b/source/blender/blenkernel/intern/fcurve.c
index c67a61a5aad..905f103250a 100644
--- a/source/blender/blenkernel/intern/fcurve.c
+++ b/source/blender/blenkernel/intern/fcurve.c
@@ -61,6 +61,7 @@
#include "BKE_curve.h"
#include "BKE_global.h"
#include "BKE_object.h"
+#include "BKE_nla.h"
#include "RNA_access.h"
@@ -86,12 +87,11 @@ void free_fcurve(FCurve *fcu)
return;
/* free curve data */
- if (fcu->bezt) MEM_freeN(fcu->bezt);
- if (fcu->fpt) MEM_freeN(fcu->fpt);
+ MEM_SAFE_FREE(fcu->bezt);
+ MEM_SAFE_FREE(fcu->fpt);
/* free RNA-path, as this were allocated when getting the path string */
- if (fcu->rna_path)
- MEM_freeN(fcu->rna_path);
+ MEM_SAFE_FREE(fcu->rna_path);
/* free extra data - i.e. modifiers, and driver */
fcurve_free_driver(fcu);
@@ -126,7 +126,7 @@ void free_fcurves(ListBase *list)
/* ---------------------- Copy --------------------------- */
/* duplicate an F-Curve */
-FCurve *copy_fcurve(FCurve *fcu)
+FCurve *copy_fcurve(const FCurve *fcu)
{
FCurve *fcu_d;
@@ -336,7 +336,7 @@ FCurve *rna_get_fcurve_context_ui(
if (r_action) *r_action = NULL;
/* Special case for NLA Control Curves... */
- if (ptr->type == &RNA_NlaStrip) {
+ if (BKE_nlastrip_has_curves_for_property(ptr, prop)) {
NlaStrip *strip = (NlaStrip *)ptr->data;
/* Set the special flag, since it cannot be a normal action/driver
@@ -804,7 +804,7 @@ void bezt_add_to_cfra_elem(ListBase *lb, BezTriple *bezt)
for (ce = lb->first; ce; ce = ce->next) {
/* double key? */
- if (ce->cfra == bezt->vec[1][0]) {
+ if (IS_EQT(ce->cfra, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) {
if (bezt->f2 & SELECT) ce->sel = bezt->f2;
return;
}
@@ -882,6 +882,46 @@ void fcurve_store_samples(FCurve *fcu, void *data, int start, int end, FcuSample
* that the handles are correctly
*/
+/* Checks if the F-Curve has a Cycles modifier with simple settings that warrant transition smoothing */
+bool BKE_fcurve_is_cyclic(FCurve *fcu)
+{
+ FModifier *fcm = fcu->modifiers.first;
+
+ if (!fcm || fcm->type != FMODIFIER_TYPE_CYCLES)
+ return false;
+
+ if (fcm->flag & (FMODIFIER_FLAG_DISABLED | FMODIFIER_FLAG_MUTED))
+ return false;
+
+ if (fcm->flag & (FMODIFIER_FLAG_RANGERESTRICT | FMODIFIER_FLAG_USEINFLUENCE))
+ return false;
+
+ FMod_Cycles *data = (FMod_Cycles *)fcm->data;
+
+ return data && data->after_cycles == 0 && data->before_cycles == 0 &&
+ ELEM(data->before_mode, FCM_EXTRAPOLATE_CYCLIC, FCM_EXTRAPOLATE_CYCLIC_OFFSET) &&
+ ELEM(data->after_mode, FCM_EXTRAPOLATE_CYCLIC, FCM_EXTRAPOLATE_CYCLIC_OFFSET);
+}
+
+/* Shifts 'in' by the difference in coordinates between 'to' and 'from', using 'out' as the output buffer.
+ * When 'to' and 'from' are end points of the loop, this moves the 'in' point one loop cycle.
+ */
+static BezTriple *cycle_offset_triple(bool cycle, BezTriple *out, const BezTriple *in, const BezTriple *from, const BezTriple *to)
+{
+ if (!cycle)
+ return NULL;
+
+ memcpy(out, in, sizeof(BezTriple));
+
+ float delta[3];
+ sub_v3_v3v3(delta, to->vec[1], from->vec[1]);
+
+ for (int i = 0; i < 3; i++)
+ add_v3_v3(out->vec[i], delta);
+
+ return out;
+}
+
/* This function recalculates the handles of an F-Curve
* If the BezTriples have been rearranged, sort them first before using this.
*/
@@ -897,10 +937,16 @@ void calchandles_fcurve(FCurve *fcu)
*/
if (ELEM(NULL, fcu, fcu->bezt) || (a < 2) /*|| ELEM(fcu->ipo, BEZT_IPO_CONST, BEZT_IPO_LIN)*/)
return;
-
+
+ /* if the first modifier is Cycles, smooth the curve through the cycle */
+ BezTriple *first = &fcu->bezt[0], *last = &fcu->bezt[fcu->totvert - 1];
+ BezTriple tmp;
+
+ bool cycle = BKE_fcurve_is_cyclic(fcu) && BEZT_IS_AUTOH(first) && BEZT_IS_AUTOH(last);
+
/* get initial pointers */
bezt = fcu->bezt;
- prev = NULL;
+ prev = cycle_offset_triple(cycle, &tmp, &fcu->bezt[fcu->totvert - 2], last, first);
next = (bezt + 1);
/* loop over all beztriples, adjusting handles */
@@ -910,25 +956,50 @@ void calchandles_fcurve(FCurve *fcu)
if (bezt->vec[2][0] < bezt->vec[1][0]) bezt->vec[2][0] = bezt->vec[1][0];
/* calculate auto-handles */
- BKE_nurb_handle_calc(bezt, prev, next, true);
+ BKE_nurb_handle_calc(bezt, prev, next, true, fcu->auto_smoothing);
/* for automatic ease in and out */
- if (ELEM(bezt->h1, HD_AUTO, HD_AUTO_ANIM) && ELEM(bezt->h2, HD_AUTO, HD_AUTO_ANIM)) {
+ if (BEZT_IS_AUTOH(bezt) && !cycle) {
/* only do this on first or last beztriple */
if ((a == 0) || (a == fcu->totvert - 1)) {
/* set both handles to have same horizontal value as keyframe */
if (fcu->extend == FCURVE_EXTRAPOLATE_CONSTANT) {
bezt->vec[0][1] = bezt->vec[2][1] = bezt->vec[1][1];
+ /* remember that these keyframes are special, they don't need to be adjusted */
+ bezt->f5 = HD_AUTOTYPE_SPECIAL;
}
}
}
+
+ /* avoid total smoothing failure on duplicate keyframes (can happen during grab) */
+ if (prev && prev->vec[1][0] >= bezt->vec[1][0]) {
+ prev->f5 = bezt->f5 = HD_AUTOTYPE_SPECIAL;
+ }
/* advance pointers for next iteration */
prev = bezt;
- if (a == 1) next = NULL;
- else next++;
+
+ if (a == 1) {
+ next = cycle_offset_triple(cycle, &tmp, &fcu->bezt[1], first, last);
+ }
+ else {
+ next++;
+ }
+
bezt++;
}
+
+ /* if cyclic extrapolation and Auto Clamp has triggered, ensure it is symmetric */
+ if (cycle && (first->f5 != HD_AUTOTYPE_NORMAL || last->f5 != HD_AUTOTYPE_NORMAL)) {
+ first->vec[0][1] = first->vec[2][1] = first->vec[1][1];
+ last->vec[0][1] = last->vec[2][1] = last->vec[1][1];
+ first->f5 = last->f5 = HD_AUTOTYPE_SPECIAL;
+ }
+
+ /* do a second pass for auto handle: compute the handle to have 0 accelaration step */
+ if (fcu->auto_smoothing != FCURVE_SMOOTH_NONE) {
+ BKE_nurb_handle_smooth_fcurve(fcu->bezt, fcu->totvert, cycle);
+ }
}
void testhandles_fcurve(FCurve *fcu, const bool use_handle)
@@ -1217,6 +1288,7 @@ bool driver_get_variable_property(
return true;
}
+#if 0
/* Helper function to obtain a pointer to a Pose Channel (for evaluating drivers) */
static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dtar)
{
@@ -1239,6 +1311,32 @@ static bPoseChannel *dtar_get_pchan_ptr(ChannelDriver *driver, DriverTarget *dta
return NULL;
}
}
+#endif
+
+static short driver_check_valid_targets(ChannelDriver *driver, DriverVar *dvar)
+{
+ short valid_targets = 0;
+
+ DRIVER_TARGETS_USED_LOOPER(dvar)
+ {
+ Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
+
+ /* check if this target has valid data */
+ if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
+ /* invalid target, so will not have enough targets */
+ driver->flag |= DRIVER_FLAG_INVALID;
+ dtar->flag |= DTAR_FLAG_INVALID;
+ }
+ else {
+ /* target seems to be OK now... */
+ dtar->flag &= ~DTAR_FLAG_INVALID;
+ valid_targets++;
+ }
+ }
+ DRIVER_TARGETS_LOOPER_END
+
+ return valid_targets;
+}
/* ......... */
@@ -1252,62 +1350,54 @@ static float dvar_eval_singleProp(ChannelDriver *driver, DriverVar *dvar)
/* evaluate 'rotation difference' driver variable */
static float dvar_eval_rotDiff(ChannelDriver *driver, DriverVar *dvar)
{
- DriverTarget *dtar1 = &dvar->targets[0];
- DriverTarget *dtar2 = &dvar->targets[1];
- bPoseChannel *pchan, *pchan2;
- float q1[4], q2[4], quat[4], angle;
-
- /* get pose channels, and check if we've got two */
- pchan = dtar_get_pchan_ptr(driver, dtar1);
- pchan2 = dtar_get_pchan_ptr(driver, dtar2);
-
- if (ELEM(NULL, pchan, pchan2)) {
- /* disable this driver, since it doesn't work correctly... */
- driver->flag |= DRIVER_FLAG_INVALID;
-
- /* check what the error was */
- if ((pchan == NULL) && (pchan2 == NULL)) {
- if (G.debug & G_DEBUG) {
- printf("Driver Evaluation Error: Rotational difference failed - first 2 targets invalid\n");
- }
-
- dtar1->flag |= DTAR_FLAG_INVALID;
- dtar2->flag |= DTAR_FLAG_INVALID;
- }
- else if (pchan == NULL) {
- if (G.debug & G_DEBUG) {
- printf("Driver Evaluation Error: Rotational difference failed - first target not valid PoseChannel\n");
- }
-
- dtar1->flag |= DTAR_FLAG_INVALID;
- dtar2->flag &= ~DTAR_FLAG_INVALID;
- }
- else if (pchan2 == NULL) {
- if (G.debug & G_DEBUG) {
- printf("Driver Evaluation Error: Rotational difference failed - second target not valid PoseChannel\n");
- }
-
- dtar1->flag &= ~DTAR_FLAG_INVALID;
- dtar2->flag |= DTAR_FLAG_INVALID;
+ short valid_targets = driver_check_valid_targets(driver, dvar);
+
+ /* make sure we have enough valid targets to use - all or nothing for now... */
+ if (driver_check_valid_targets(driver, dvar) != 2) {
+ if (G.debug & G_DEBUG) {
+ printf("RotDiff DVar: not enough valid targets (n = %d) (a = %p, b = %p)\n",
+ valid_targets, dvar->targets[0].id, dvar->targets[1].id);
}
-
- /* stop here... */
return 0.0f;
}
- else {
- dtar1->flag &= ~DTAR_FLAG_INVALID;
- dtar2->flag &= ~DTAR_FLAG_INVALID;
+
+ float (*mat[2])[4];
+
+ /* NOTE: for now, these are all just worldspace */
+ for (int i = 0; i < 2; i++) {
+ /* get pointer to loc values to store in */
+ DriverTarget *dtar = &dvar->targets[i];
+ Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
+ bPoseChannel *pchan;
+
+ /* after the checks above, the targets should be valid here... */
+ BLI_assert((ob != NULL) && (GS(ob->id.name) == ID_OB));
+
+ /* try to get posechannel */
+ pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
+
+ /* check if object or bone */
+ if (pchan) {
+ /* bone */
+ mat[i] = pchan->pose_mat;
+ }
+ else {
+ /* object */
+ mat[i] = ob->obmat;
+ }
}
-
+
+ float q1[4], q2[4], quat[4], angle;
+
/* use the final posed locations */
- mat4_to_quat(q1, pchan->pose_mat);
- mat4_to_quat(q2, pchan2->pose_mat);
-
+ mat4_to_quat(q1, mat[0]);
+ mat4_to_quat(q2, mat[1]);
+
invert_qt_normalized(q1);
mul_qt_qtqt(quat, q1, q2);
angle = 2.0f * (saacos(quat[0]));
angle = ABS(angle);
-
+
return (angle > (float)M_PI) ? (float)((2.0f * (float)M_PI) - angle) : (float)(angle);
}
@@ -1317,32 +1407,8 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar)
{
float loc1[3] = {0.0f, 0.0f, 0.0f};
float loc2[3] = {0.0f, 0.0f, 0.0f};
- short valid_targets = 0;
-
- /* Perform two passes
- *
- * FIRST PASS - to just check that everything works...
- * NOTE: we use loops here to reduce code duplication, though in practice,
- * there can only be 2 items or else we run into some problems later
- */
- DRIVER_TARGETS_USED_LOOPER(dvar)
- {
- Object *ob = (Object *)dtar_id_ensure_proxy_from(dtar->id);
-
- /* check if this target has valid data */
- if ((ob == NULL) || (GS(ob->id.name) != ID_OB)) {
- /* invalid target, so will not have enough targets */
- driver->flag |= DRIVER_FLAG_INVALID;
- dtar->flag |= DTAR_FLAG_INVALID;
- }
- else {
- /* target seems to be OK now... */
- dtar->flag &= ~DTAR_FLAG_INVALID;
- valid_targets++;
- }
- }
- DRIVER_TARGETS_LOOPER_END
-
+ short valid_targets = driver_check_valid_targets(driver, dvar);
+
/* make sure we have enough valid targets to use - all or nothing for now... */
if (valid_targets < dvar->num_targets) {
if (G.debug & G_DEBUG) {
@@ -1351,8 +1417,7 @@ static float dvar_eval_locDiff(ChannelDriver *driver, DriverVar *dvar)
}
return 0.0f;
}
-
-
+
/* SECOND PASS: get two location values */
/* NOTE: for now, these are all just worldspace */
DRIVER_TARGETS_USED_LOOPER(dvar)
@@ -1525,11 +1590,9 @@ static float dvar_eval_transChan(ChannelDriver *driver, DriverVar *dvar)
return 0.0f;
}
else if (dtar->transChan >= DTAR_TRANSCHAN_SCALEX) {
- /* extract scale, and choose the right axis */
- float scale[3];
-
- mat4_to_size(scale, mat);
- return scale[dtar->transChan - DTAR_TRANSCHAN_SCALEX];
+ /* Extract scale, and choose the right axis,
+ * inline 'mat4_to_size'. */
+ return len_v3(mat[dtar->transChan - DTAR_TRANSCHAN_SCALEX]);
}
else if (dtar->transChan >= DTAR_TRANSCHAN_ROTX) {
/* extract rotation as eulers (if needed)
@@ -1570,7 +1633,7 @@ static DriverVarTypeInfo dvar_types[MAX_DVAR_TYPES] = {
BEGIN_DVAR_TYPEDEF(DVAR_TYPE_ROT_DIFF)
dvar_eval_rotDiff, /* eval callback */
2, /* number of targets used */
- {"Bone 1", "Bone 2"}, /* UI names for targets */
+ {"Object/Bone 1", "Object/Bone 2"}, /* UI names for targets */
{DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY, DTAR_FLAG_STRUCT_REF | DTAR_FLAG_ID_OB_ONLY} /* flags */
END_DVAR_TYPEDEF,
@@ -1710,7 +1773,7 @@ void driver_variable_name_validate(DriverVar *dvar)
/* 1) Must start with a letter */
/* XXX: We assume that valid unicode letters in other languages are ok too, hence the blacklisting */
- if (ELEM(dvar->name[0], '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) {
+ if (IN_RANGE_INCL(dvar->name[0], '0', '9')) {
dvar->flag |= DVAR_FLAG_INVALID_START_NUM;
}
else if (dvar->name[0] == '_') {
@@ -1811,7 +1874,7 @@ void fcurve_free_driver(FCurve *fcu)
}
/* This makes a copy of the given driver */
-ChannelDriver *fcurve_copy_driver(ChannelDriver *driver)
+ChannelDriver *fcurve_copy_driver(const ChannelDriver *driver)
{
ChannelDriver *ndriver;
@@ -1951,7 +2014,7 @@ float evaluate_driver(PathResolvedRNA *anim_rna, ChannelDriver *driver, const fl
BLI_mutex_unlock(&python_driver_lock);
}
#else /* WITH_PYTHON*/
- (void)evaltime;
+ UNUSED_VARS(anim_rna, evaltime);
#endif /* WITH_PYTHON*/
break;
}
diff --git a/source/blender/blenkernel/intern/fluidsim.c b/source/blender/blenkernel/intern/fluidsim.c
index 8247336d915..7dc6e3575b2 100644
--- a/source/blender/blenkernel/intern/fluidsim.c
+++ b/source/blender/blenkernel/intern/fluidsim.c
@@ -40,8 +40,8 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "DNA_object_fluidsim.h"
-#include "DNA_object_force.h" // for pointcache
+#include "DNA_object_fluidsim_types.h"
+#include "DNA_object_force_types.h" // for pointcache
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
@@ -54,7 +54,6 @@
#include "BKE_customdata.h"
#include "BKE_DerivedMesh.h"
#include "BKE_fluidsim.h"
-#include "BKE_global.h"
#include "BKE_modifier.h"
#include "BKE_mesh.h"
@@ -80,8 +79,6 @@ void initElbeemMesh(struct Scene *scene, struct Object *ob,
dm = mesh_create_derived_index_render(scene, ob, CD_MASK_BAREMESH, modifierIndex);
- DM_ensure_looptri(dm);
-
mvert = dm->getVertArray(dm);
mloop = dm->getLoopArray(dm);
looptri = dm->getLoopTriArray(dm);
diff --git a/source/blender/blenkernel/intern/fmodifier.c b/source/blender/blenkernel/intern/fmodifier.c
index 2c301c04100..f1834bdf8a6 100644
--- a/source/blender/blenkernel/intern/fmodifier.c
+++ b/source/blender/blenkernel/intern/fmodifier.c
@@ -116,7 +116,7 @@ static void fcm_generator_free(FModifier *fcm)
MEM_freeN(data->coefficients);
}
-static void fcm_generator_copy(FModifier *fcm, FModifier *src)
+static void fcm_generator_copy(FModifier *fcm, const FModifier *src)
{
FMod_Generator *gen = (FMod_Generator *)fcm->data;
FMod_Generator *ogen = (FMod_Generator *)src->data;
@@ -386,7 +386,7 @@ static void fcm_envelope_free(FModifier *fcm)
MEM_freeN(env->data);
}
-static void fcm_envelope_copy(FModifier *fcm, FModifier *src)
+static void fcm_envelope_copy(FModifier *fcm, const FModifier *src)
{
FMod_Envelope *env = (FMod_Envelope *)fcm->data;
FMod_Envelope *oenv = (FMod_Envelope *)src->data;
@@ -877,7 +877,7 @@ static void fcm_python_new_data(void *mdata)
data->prop->type = IDP_GROUP;
}
-static void fcm_python_copy(FModifier *fcm, FModifier *src)
+static void fcm_python_copy(FModifier *fcm, const FModifier *src)
{
FMod_Python *pymod = (FMod_Python *)fcm->data;
FMod_Python *opymod = (FMod_Python *)src->data;
@@ -1040,7 +1040,7 @@ static void fmods_init_typeinfo(void)
/* This function should be used for getting the appropriate type-info when only
* a F-Curve modifier type is known
*/
-const FModifierTypeInfo *get_fmodifier_typeinfo(int type)
+const FModifierTypeInfo *get_fmodifier_typeinfo(const int type)
{
/* initialize the type-info list? */
if (FMI_INIT) {
@@ -1065,7 +1065,7 @@ const FModifierTypeInfo *get_fmodifier_typeinfo(int type)
/* This function should always be used to get the appropriate type-info, as it
* has checks which prevent segfaults in some weird cases.
*/
-const FModifierTypeInfo *fmodifier_get_typeinfo(FModifier *fcm)
+const FModifierTypeInfo *fmodifier_get_typeinfo(const FModifier *fcm)
{
/* only return typeinfo for valid modifiers */
if (fcm)
@@ -1077,7 +1077,7 @@ const FModifierTypeInfo *fmodifier_get_typeinfo(FModifier *fcm)
/* API --------------------------- */
/* Add a new F-Curve Modifier to the given F-Curve of a certain type */
-FModifier *add_fmodifier(ListBase *modifiers, int type)
+FModifier *add_fmodifier(ListBase *modifiers, int type, FCurve *owner_fcu)
{
const FModifierTypeInfo *fmi = get_fmodifier_typeinfo(type);
FModifier *fcm;
@@ -1098,6 +1098,7 @@ FModifier *add_fmodifier(ListBase *modifiers, int type)
fcm = MEM_callocN(sizeof(FModifier), "F-Curve Modifier");
fcm->type = type;
fcm->flag = FMODIFIER_FLAG_EXPANDED;
+ fcm->curve = owner_fcu;
fcm->influence = 1.0f;
BLI_addtail(modifiers, fcm);
@@ -1111,13 +1112,17 @@ FModifier *add_fmodifier(ListBase *modifiers, int type)
/* init custom settings if necessary */
if (fmi->new_data)
fmi->new_data(fcm->data);
+
+ /* update the fcurve if the Cycles modifier is added */
+ if ((owner_fcu) && (type == FMODIFIER_TYPE_CYCLES))
+ calchandles_fcurve(owner_fcu);
/* return modifier for further editing */
return fcm;
}
/* Make a copy of the specified F-Modifier */
-FModifier *copy_fmodifier(FModifier *src)
+FModifier *copy_fmodifier(const FModifier *src)
{
const FModifierTypeInfo *fmi = fmodifier_get_typeinfo(src);
FModifier *dst;
@@ -1129,6 +1134,7 @@ FModifier *copy_fmodifier(FModifier *src)
/* copy the base data, clearing the links */
dst = MEM_dupallocN(src);
dst->next = dst->prev = NULL;
+ dst->curve = NULL;
/* make a new copy of the F-Modifier's data */
dst->data = MEM_dupallocN(src->data);
@@ -1142,7 +1148,7 @@ FModifier *copy_fmodifier(FModifier *src)
}
/* Duplicate all of the F-Modifiers in the Modifier stacks */
-void copy_fmodifiers(ListBase *dst, ListBase *src)
+void copy_fmodifiers(ListBase *dst, const ListBase *src)
{
FModifier *fcm, *srcfcm;
@@ -1157,6 +1163,7 @@ void copy_fmodifiers(ListBase *dst, ListBase *src)
/* make a new copy of the F-Modifier's data */
fcm->data = MEM_dupallocN(fcm->data);
+ fcm->curve = NULL;
/* only do specific constraints if required */
if (fmi && fmi->copy_data)
@@ -1173,6 +1180,9 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm)
if (fcm == NULL)
return false;
+ /* removing the cycles modifier requires a handle update */
+ FCurve *update_fcu = (fcm->type == FMODIFIER_TYPE_CYCLES) ? fcm->curve : NULL;
+
/* free modifier's special data (stored inside fcm->data) */
if (fcm->data) {
if (fmi && fmi->free_data)
@@ -1185,6 +1195,11 @@ bool remove_fmodifier(ListBase *modifiers, FModifier *fcm)
/* remove modifier from stack */
if (modifiers) {
BLI_freelinkN(modifiers, fcm);
+
+ /* update the fcurve if the Cycles modifier is removed */
+ if (update_fcu)
+ calchandles_fcurve(update_fcu);
+
return true;
}
else {
diff --git a/source/blender/blenkernel/intern/font.c b/source/blender/blenkernel/intern/font.c
index 580842fe176..5545eba8764 100644
--- a/source/blender/blenkernel/intern/font.c
+++ b/source/blender/blenkernel/intern/font.c
@@ -106,6 +106,23 @@ void BKE_vfont_free(struct VFont *vf)
}
}
+void BKE_vfont_copy_data(Main *UNUSED(bmain), VFont *vfont_dst, const VFont *UNUSED(vfont_src), const int flag)
+{
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
+
+ /* Just to be sure, should not have any value actually after reading time. */
+ vfont_dst->temp_pf = NULL;
+
+ if (vfont_dst->packedfile) {
+ vfont_dst->packedfile = dupPackedFile(vfont_dst->packedfile);
+ }
+
+ if (vfont_dst->data) {
+ vfont_dst->data = BLI_vfontdata_copy(vfont_dst->data, flag_subdata);
+ }
+}
+
static void *builtin_font_data = NULL;
static int builtin_font_size = 0;
@@ -249,7 +266,7 @@ VFont *BKE_vfont_load(Main *bmain, const char *filepath)
vfd = BLI_vfontdata_from_freetypefont(pf);
if (vfd) {
- vfont = BKE_libblock_alloc(bmain, ID_VF, filename);
+ vfont = BKE_libblock_alloc(bmain, ID_VF, filename, 0);
vfont->data = vfd;
/* if there's a font name, use it for the ID name */
@@ -365,7 +382,7 @@ static void build_underline(Curve *cu, ListBase *nubase, const rctf *rect,
nu2->orderv = 1;
nu2->flagu = CU_NURB_CYCLIC;
- bp = (BPoint *)MEM_callocN(4 * sizeof(BPoint), "underline_bp");
+ bp = (BPoint *)MEM_calloc_arrayN(4, sizeof(BPoint), "underline_bp");
copy_v4_fl4(bp[0].vec, rect->xmin, (rect->ymax + yofs), 0.0f, 1.0f);
copy_v4_fl4(bp[1].vec, rect->xmax, (rect->ymax + yofs), 0.0f, 1.0f);
@@ -464,7 +481,7 @@ static void buildchar(Main *bmain, Curve *cu, ListBase *nubase, unsigned int cha
/* nu2->trim.last = 0; */
i = nu2->pntsu;
- bezt2 = (BezTriple *)MEM_mallocN(i * sizeof(BezTriple), "duplichar_bezt2");
+ bezt2 = (BezTriple *)MEM_malloc_arrayN(i, sizeof(BezTriple), "duplichar_bezt2");
if (bezt2 == NULL) {
MEM_freeN(nu2);
break;
@@ -618,11 +635,10 @@ struct TempLineInfo {
int wspace_nr; /* number of whitespaces of line */
};
-bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, int mode, ListBase *r_nubase,
+bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, Curve *cu, int mode, ListBase *r_nubase,
const wchar_t **r_text, int *r_text_len, bool *r_text_free,
struct CharTrans **r_chartransdata)
{
- Curve *cu = ob->data;
EditFont *ef = cu->editfont;
EditFontSelBox *selboxes = NULL;
VFont *vfont, *oldvfont;
@@ -653,7 +669,7 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, int mode, ListBase *r_nubase
/* remark: do calculations including the trailing '\0' of a string
* because the cursor can be at that location */
- BLI_assert(ob->type == OB_FONT);
+ BLI_assert(ob == NULL || ob->type == OB_FONT);
/* Set font data */
vfont = cu->vfont;
@@ -676,38 +692,48 @@ bool BKE_vfont_to_curve_ex(Main *bmain, Object *ob, int mode, ListBase *r_nubase
slen = cu->len_wchar;
/* Create unicode string */
- mem_tmp = MEM_mallocN(((slen + 1) * sizeof(wchar_t)), "convertedmem");
+ mem_tmp = MEM_malloc_arrayN((slen + 1), sizeof(wchar_t), "convertedmem");
+ if (!mem_tmp) {
+ return ok;
+ }
BLI_strncpy_wchar_from_utf8(mem_tmp, cu->str, slen + 1);
if (cu->strinfo == NULL) { /* old file */
- cu->strinfo = MEM_callocN((slen + 4) * sizeof(CharInfo), "strinfo compat");
+ cu->strinfo = MEM_calloc_arrayN((slen + 4), sizeof(CharInfo), "strinfo compat");
}
custrinfo = cu->strinfo;
+ if (!custrinfo) {
+ return ok;
+ }
mem = mem_tmp;
}
if (cu->tb == NULL)
- cu->tb = MEM_callocN(MAXTEXTBOX * sizeof(TextBox), "TextBox compat");
+ cu->tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBox compat");
- if (ef) {
+ if (ef != NULL && ob != NULL) {
if (ef->selboxes)
MEM_freeN(ef->selboxes);
- if (BKE_vfont_select_get(ob, &selstart, &selend))
- ef->selboxes = MEM_callocN((selend - selstart + 1) * sizeof(EditFontSelBox), "font selboxes");
- else
+ if (BKE_vfont_select_get(ob, &selstart, &selend)) {
+ ef->selboxes_len = (selend - selstart) + 1;
+ ef->selboxes = MEM_calloc_arrayN(ef->selboxes_len, sizeof(EditFontSelBox), "font selboxes");
+ }
+ else {
+ ef->selboxes_len = 0;
ef->selboxes = NULL;
+ }
selboxes = ef->selboxes;
}
/* calc offset and rotation of each char */
- ct = chartransdata = MEM_callocN((slen + 1) * sizeof(struct CharTrans), "buildtext");
+ ct = chartransdata = MEM_calloc_arrayN((slen + 1), sizeof(struct CharTrans), "buildtext");
/* We assume the worst case: 1 character per line (is freed at end anyway) */
- lineinfo = MEM_mallocN(sizeof(*lineinfo) * (slen * 2 + 1), "lineinfo");
+ lineinfo = MEM_malloc_arrayN((slen * 2 + 1), sizeof(*lineinfo), "lineinfo");
linedist = cu->linedist;
@@ -1054,8 +1080,13 @@ makebreak:
float distfac, imat[4][4], imat3[3][3], cmat[3][3];
float minx, maxx, miny, maxy;
float timeofs, sizefac;
-
- invert_m4_m4(imat, ob->obmat);
+
+ if (ob != NULL) {
+ invert_m4_m4(imat, ob->obmat);
+ }
+ else {
+ unit_m4(imat);
+ }
copy_m3_m4(imat3, imat);
copy_m3_m4(cmat, cu->textoncurve->obmat);
@@ -1237,7 +1268,7 @@ makebreak:
cha = towupper(cha);
}
- if (info->mat_nr > (ob->totcol)) {
+ if (ob == NULL || info->mat_nr > (ob->totcol)) {
/* printf("Error: Illegal material index (%d) in text object, setting to 0\n", info->mat_nr); */
info->mat_nr = 0;
}
@@ -1313,7 +1344,7 @@ bool BKE_vfont_to_curve_nubase(Main *bmain, Object *ob, int mode, ListBase *r_nu
{
BLI_assert(ob->type == OB_FONT);
- return BKE_vfont_to_curve_ex(bmain, ob, mode, r_nubase,
+ return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, r_nubase,
NULL, NULL, NULL, NULL);
}
@@ -1321,7 +1352,7 @@ bool BKE_vfont_to_curve(Main *bmain, Object *ob, int mode)
{
Curve *cu = ob->data;
- return BKE_vfont_to_curve_ex(bmain, ob, mode, &cu->nurb, NULL, NULL, NULL, NULL);
+ return BKE_vfont_to_curve_ex(bmain, ob, ob->data, mode, &cu->nurb, NULL, NULL, NULL, NULL);
}
@@ -1353,12 +1384,12 @@ void BKE_vfont_clipboard_set(const wchar_t *text_buf, const CharInfo *info_buf,
/* clean previous buffers*/
BKE_vfont_clipboard_free();
- text = MEM_mallocN((len + 1) * sizeof(wchar_t), __func__);
+ text = MEM_malloc_arrayN((len + 1), sizeof(wchar_t), __func__);
if (text == NULL) {
return;
}
- info = MEM_mallocN(len * sizeof(CharInfo), __func__);
+ info = MEM_malloc_arrayN(len, sizeof(CharInfo), __func__);
if (info == NULL) {
MEM_freeN(text);
return;
diff --git a/source/blender/blenkernel/intern/freestyle.c b/source/blender/blenkernel/intern/freestyle.c
index 0a0b023df82..686fe3bda93 100644
--- a/source/blender/blenkernel/intern/freestyle.c
+++ b/source/blender/blenkernel/intern/freestyle.c
@@ -34,17 +34,17 @@
#include "DNA_freestyle_types.h"
#include "DNA_group_types.h"
-#include "BKE_freestyle.h"
-#include "BKE_library.h"
-#include "BKE_linestyle.h"
-
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_string_utils.h"
+#include "BKE_freestyle.h"
+#include "BKE_library.h"
+#include "BKE_linestyle.h"
+
// function declarations
static FreestyleLineSet *alloc_lineset(void);
-static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset);
+static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset, const int flag);
static FreestyleModuleConfig *alloc_module(void);
static void copy_module(FreestyleModuleConfig *new_module, FreestyleModuleConfig *module);
@@ -79,7 +79,7 @@ void BKE_freestyle_config_free(FreestyleConfig *config)
BLI_freelistN(&config->modules);
}
-void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config)
+void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *config, const int flag)
{
FreestyleLineSet *lineset, *new_lineset;
FreestyleModuleConfig *module, *new_module;
@@ -93,7 +93,7 @@ void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *con
BLI_listbase_clear(&new_config->linesets);
for (lineset = (FreestyleLineSet *)config->linesets.first; lineset; lineset = lineset->next) {
new_lineset = alloc_lineset();
- copy_lineset(new_lineset, lineset);
+ copy_lineset(new_lineset, lineset, flag);
BLI_addtail(&new_config->linesets, (void *)new_lineset);
}
@@ -105,11 +105,9 @@ void BKE_freestyle_config_copy(FreestyleConfig *new_config, FreestyleConfig *con
}
}
-static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset)
+static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *lineset, const int flag)
{
new_lineset->linestyle = lineset->linestyle;
- if (new_lineset->linestyle)
- id_us_plus(&new_lineset->linestyle->id);
new_lineset->flags = lineset->flags;
new_lineset->selection = lineset->selection;
new_lineset->qi = lineset->qi;
@@ -118,10 +116,12 @@ static void copy_lineset(FreestyleLineSet *new_lineset, FreestyleLineSet *linese
new_lineset->edge_types = lineset->edge_types;
new_lineset->exclude_edge_types = lineset->exclude_edge_types;
new_lineset->group = lineset->group;
- if (new_lineset->group) {
- id_us_plus(&new_lineset->group->id);
- }
strcpy(new_lineset->name, lineset->name);
+
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)new_lineset->linestyle);
+ id_us_plus((ID *)new_lineset->group);
+ }
}
static FreestyleModuleConfig *alloc_module(void)
diff --git a/source/blender/blenkernel/intern/gpencil.c b/source/blender/blenkernel/intern/gpencil.c
index 30fc8915d46..ee0d0b41898 100644
--- a/source/blender/blenkernel/intern/gpencil.c
+++ b/source/blender/blenkernel/intern/gpencil.c
@@ -627,7 +627,7 @@ bGPdata *BKE_gpencil_data_addnew(const char name[])
bGPdata *gpd;
/* allocate memory for a new block */
- gpd = BKE_libblock_alloc(G.main, ID_GD, name);
+ gpd = BKE_libblock_alloc(G.main, ID_GD, name, 0);
/* initial settings */
gpd->flag = (GP_DATA_DISPINFO | GP_DATA_EXPAND);
@@ -753,47 +753,62 @@ bGPDlayer *BKE_gpencil_layer_duplicate(const bGPDlayer *gpl_src)
return gpl_dst;
}
-/* make a copy of a given gpencil datablock */
-bGPdata *BKE_gpencil_data_duplicate(Main *bmain, bGPdata *gpd_src, bool internal_copy)
+/**
+ * Only copy internal data of GreasePencil ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_gpencil_copy_data(Main *UNUSED(bmain), bGPdata *gpd_dst, const bGPdata *gpd_src, const int UNUSED(flag))
{
- const bGPDlayer *gpl_src;
- bGPDlayer *gpl_dst;
- bGPdata *gpd_dst;
+ /* copy layers */
+ BLI_listbase_clear(&gpd_dst->layers);
+ for (const bGPDlayer *gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) {
+ /* make a copy of source layer and its data */
+ bGPDlayer *gpl_dst = BKE_gpencil_layer_duplicate(gpl_src); /* TODO here too could add unused flags... */
+ BLI_addtail(&gpd_dst->layers, gpl_dst);
+ }
- /* error checking */
- if (gpd_src == NULL) {
- return NULL;
+ /* copy palettes */
+ BLI_listbase_clear(&gpd_dst->palettes);
+ for (const bGPDpalette *palette_src = gpd_src->palettes.first; palette_src; palette_src = palette_src->next) {
+ bGPDpalette *palette_dst = BKE_gpencil_palette_duplicate(palette_src); /* TODO here too could add unused flags... */
+ BLI_addtail(&gpd_dst->palettes, palette_dst);
}
-
- /* make a copy of the base-data */
+}
+
+/* make a copy of a given gpencil datablock */
+bGPdata *BKE_gpencil_data_duplicate(Main *bmain, const bGPdata *gpd_src, bool internal_copy)
+{
+ /* Yuck and super-uber-hyper yuck!!!
+ * Should be replaceable with a no-main copy (LIB_ID_COPY_NO_MAIN etc.), but not sure about it,
+ * so for now keep old code for that one. */
if (internal_copy) {
+ const bGPDlayer *gpl_src;
+ bGPDlayer *gpl_dst;
+ bGPdata *gpd_dst;
+
/* make a straight copy for undo buffers used during stroke drawing */
gpd_dst = MEM_dupallocN(gpd_src);
+
+ /* copy layers */
+ BLI_listbase_clear(&gpd_dst->layers);
+ for (gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) {
+ /* make a copy of source layer and its data */
+ gpl_dst = BKE_gpencil_layer_duplicate(gpl_src);
+ BLI_addtail(&gpd_dst->layers, gpl_dst);
+ }
+
+ /* return new */
+ return gpd_dst;
}
else {
- /* make a copy when others use this */
- gpd_dst = BKE_libblock_copy(bmain, &gpd_src->id);
+ bGPdata *gpd_copy;
+ BKE_id_copy_ex(bmain, &gpd_src->id, (ID **)&gpd_copy, 0, false);
+ return gpd_copy;
}
-
- /* copy layers */
- BLI_listbase_clear(&gpd_dst->layers);
- for (gpl_src = gpd_src->layers.first; gpl_src; gpl_src = gpl_src->next) {
- /* make a copy of source layer and its data */
- gpl_dst = BKE_gpencil_layer_duplicate(gpl_src);
- BLI_addtail(&gpd_dst->layers, gpl_dst);
- }
- if (!internal_copy) {
- /* copy palettes */
- bGPDpalette *palette_src, *palette_dst;
- BLI_listbase_clear(&gpd_dst->palettes);
- for (palette_src = gpd_src->palettes.first; palette_src; palette_src = palette_src->next) {
- palette_dst = BKE_gpencil_palette_duplicate(palette_src);
- BLI_addtail(&gpd_dst->palettes, palette_dst);
- }
- }
-
- /* return new */
- return gpd_dst;
}
void BKE_gpencil_make_local(Main *bmain, bGPdata *gpd, const bool lib_local)
diff --git a/source/blender/blenkernel/intern/group.c b/source/blender/blenkernel/intern/group.c
index 9b011dbb003..6dc8cc5aff1 100644
--- a/source/blender/blenkernel/intern/group.c
+++ b/source/blender/blenkernel/intern/group.c
@@ -79,7 +79,9 @@ Group *BKE_group_add(Main *bmain, const char *name)
{
Group *group;
- group = BKE_libblock_alloc(bmain, ID_GR, name);
+ group = BKE_libblock_alloc(bmain, ID_GR, name, 0);
+ id_us_min(&group->id);
+ id_us_ensure_real(&group->id);
group->layer = (1 << 20) - 1;
group->preview = NULL;
@@ -87,19 +89,32 @@ Group *BKE_group_add(Main *bmain, const char *name)
return group;
}
-Group *BKE_group_copy(Main *bmain, Group *group)
+/**
+ * Only copy internal data of Group ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_group_copy_data(Main *UNUSED(bmain), Group *group_dst, const Group *group_src, const int flag)
{
- Group *groupn;
-
- groupn = BKE_libblock_copy(bmain, &group->id);
- BLI_duplicatelist(&groupn->gobject, &group->gobject);
+ BLI_duplicatelist(&group_dst->gobject, &group_src->gobject);
/* Do not copy group's preview (same behavior as for objects). */
- groupn->preview = NULL;
-
- BKE_id_copy_ensure_local(bmain, &group->id, &groupn->id);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */
+ BKE_previewimg_id_copy(&group_dst->id, &group_src->id);
+ }
+ else {
+ group_dst->preview = NULL;
+ }
+}
- return groupn;
+Group *BKE_group_copy(Main *bmain, const Group *group)
+{
+ Group *group_copy;
+ BKE_id_copy_ex(bmain, &group->id, (ID **)&group_copy, 0, false);
+ return group_copy;
}
void BKE_group_make_local(Main *bmain, Group *group, const bool lib_local)
@@ -253,18 +268,6 @@ Group *BKE_group_object_find(Group *group, Object *ob)
return NULL;
}
-void BKE_group_tag_recalc(Group *group)
-{
- GroupObject *go;
-
- if (group == NULL) return;
-
- for (go = group->gobject.first; go; go = go->next) {
- if (go->ob)
- go->ob->recalc = go->recalc;
- }
-}
-
bool BKE_group_is_animated(Group *group, Object *UNUSED(parent))
{
GroupObject *go;
diff --git a/source/blender/blenkernel/intern/icons.c b/source/blender/blenkernel/intern/icons.c
index 7669c4ba112..3ac8abd55f6 100644
--- a/source/blender/blenkernel/intern/icons.c
+++ b/source/blender/blenkernel/intern/icons.c
@@ -48,7 +48,9 @@
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
+#include "BLI_linklist_lockfree.h"
#include "BLI_string.h"
+#include "BLI_threads.h"
#include "BKE_icons.h"
#include "BKE_global.h" /* only for G.background test */
@@ -71,6 +73,13 @@ static int gFirstIconId = 1;
static GHash *gCachedPreviews = NULL;
+/* Queue of icons for deferred deletion. */
+typedef struct DeferredIconDeleteNode {
+ struct DeferredIconDeleteNode *next;
+ int icon_id;
+} DeferredIconDeleteNode;
+static LockfreeLinkList g_icon_delete_queue;
+
static void icon_free(void *val)
{
Icon *icon = val;
@@ -90,6 +99,7 @@ static void icon_free(void *val)
* after the integer number range is used up */
static int get_next_free_id(void)
{
+ BLI_assert(BLI_thread_is_main());
int startId = gFirstIconId;
/* if we haven't used up the int number range, we just return the next int */
@@ -110,11 +120,15 @@ static int get_next_free_id(void)
void BKE_icons_init(int first_dyn_id)
{
+ BLI_assert(BLI_thread_is_main());
+
gNextIconId = first_dyn_id;
gFirstIconId = first_dyn_id;
- if (!gIcons)
+ if (!gIcons) {
gIcons = BLI_ghash_int_new(__func__);
+ BLI_linklist_lockfree_init(&g_icon_delete_queue);
+ }
if (!gCachedPreviews) {
gCachedPreviews = BLI_ghash_str_new(__func__);
@@ -123,6 +137,8 @@ void BKE_icons_init(int first_dyn_id)
void BKE_icons_free(void)
{
+ BLI_assert(BLI_thread_is_main());
+
if (gIcons) {
BLI_ghash_free(gIcons, NULL, icon_free);
gIcons = NULL;
@@ -132,6 +148,22 @@ void BKE_icons_free(void)
BLI_ghash_free(gCachedPreviews, MEM_freeN, BKE_previewimg_freefunc);
gCachedPreviews = NULL;
}
+
+ BLI_linklist_lockfree_free(&g_icon_delete_queue, MEM_freeN);
+}
+
+void BKE_icons_deferred_free(void)
+{
+ BLI_assert(BLI_thread_is_main());
+
+ for (DeferredIconDeleteNode *node =
+ (DeferredIconDeleteNode *)BLI_linklist_lockfree_begin(&g_icon_delete_queue);
+ node != NULL;
+ node = node->next)
+ {
+ BLI_ghash_remove(gIcons, SET_INT_IN_POINTER(node->icon_id), NULL, icon_free);
+ }
+ BLI_linklist_lockfree_clear(&g_icon_delete_queue, MEM_freeN);
}
static PreviewImage *previewimg_create_ex(size_t deferred_data_size)
@@ -204,7 +236,7 @@ void BKE_previewimg_clear(struct PreviewImage *prv)
}
}
-PreviewImage *BKE_previewimg_copy(PreviewImage *prv)
+PreviewImage *BKE_previewimg_copy(const PreviewImage *prv)
{
PreviewImage *prv_img = NULL;
int i;
@@ -222,7 +254,7 @@ PreviewImage *BKE_previewimg_copy(PreviewImage *prv)
}
/** Duplicate preview image from \a id and clear icon_id, to be used by datablock copy functions. */
-void BKE_previewimg_id_copy(ID *new_id, ID *old_id)
+void BKE_previewimg_id_copy(ID *new_id, const ID *old_id)
{
PreviewImage **old_prv_p = BKE_previewimg_id_get_p(old_id);
PreviewImage **new_prv_p = BKE_previewimg_id_get_p(new_id);
@@ -239,7 +271,7 @@ void BKE_previewimg_id_copy(ID *new_id, ID *old_id)
}
}
-PreviewImage **BKE_previewimg_id_get_p(ID *id)
+PreviewImage **BKE_previewimg_id_get_p(const ID *id)
{
switch (GS(id->name)) {
#define ID_PRV_CASE(id_code, id_struct) case id_code: { return &((id_struct *)id)->preview; } ((void)0)
@@ -253,6 +285,8 @@ PreviewImage **BKE_previewimg_id_get_p(ID *id)
ID_PRV_CASE(ID_GR, Group);
ID_PRV_CASE(ID_SCE, Scene);
#undef ID_PRV_CASE
+ default:
+ break;
}
return NULL;
@@ -429,23 +463,30 @@ void BKE_previewimg_ensure(PreviewImage *prv, const int size)
}
}
-void BKE_icon_changed(int id)
+void BKE_icon_changed(const int icon_id)
{
+ BLI_assert(BLI_thread_is_main());
+
Icon *icon = NULL;
- if (!id || G.background) return;
+ if (!icon_id || G.background) return;
- icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(id));
+ icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
if (icon) {
- PreviewImage *prv = BKE_previewimg_id_ensure((ID *)icon->obj);
+ /* We *only* expect ID-tied icons here, not non-ID icon/preview! */
+ BLI_assert(icon->id_type != 0);
+
+ /* Do not enforce creation of previews for valid ID types using BKE_previewimg_id_ensure() here ,
+ * we only want to ensure *existing* preview images are properly tagged as changed/invalid, that's all. */
+ PreviewImage **p_prv = BKE_previewimg_id_get_p((ID *)icon->obj);
- /* all previews changed */
- if (prv) {
+ /* If we have previews, they all are now invalid changed. */
+ if (p_prv && *p_prv) {
int i;
for (i = 0; i < NUM_ICON_SIZES; ++i) {
- prv->flag[i] |= PRV_CHANGED;
- prv->changed_timestamp[i]++;
+ (*p_prv)->flag[i] |= PRV_CHANGED;
+ (*p_prv)->changed_timestamp[i]++;
}
}
}
@@ -453,12 +494,14 @@ void BKE_icon_changed(int id)
static int icon_id_ensure_create_icon(struct ID *id)
{
+ BLI_assert(BLI_thread_is_main());
+
Icon *new_icon = NULL;
new_icon = MEM_mallocN(sizeof(Icon), __func__);
new_icon->obj = id;
- new_icon->type = GS(id->name);
+ new_icon->id_type = GS(id->name);
/* next two lines make sure image gets created */
new_icon->drawinfo = NULL;
@@ -534,7 +577,7 @@ int BKE_icon_preview_ensure(ID *id, PreviewImage *preview)
new_icon = MEM_mallocN(sizeof(Icon), __func__);
new_icon->obj = preview;
- new_icon->type = 0; /* Special, tags as non-ID icon/preview. */
+ new_icon->id_type = 0; /* Special, tags as non-ID icon/preview. */
/* next two lines make sure image gets created */
new_icon->drawinfo = NULL;
@@ -545,8 +588,10 @@ int BKE_icon_preview_ensure(ID *id, PreviewImage *preview)
return preview->icon_id;
}
-Icon *BKE_icon_get(int icon_id)
+Icon *BKE_icon_get(const int icon_id)
{
+ BLI_assert(BLI_thread_is_main());
+
Icon *icon = NULL;
icon = BLI_ghash_lookup(gIcons, SET_INT_IN_POINTER(icon_id));
@@ -559,8 +604,10 @@ Icon *BKE_icon_get(int icon_id)
return icon;
}
-void BKE_icon_set(int icon_id, struct Icon *icon)
+void BKE_icon_set(const int icon_id, struct Icon *icon)
{
+ BLI_assert(BLI_thread_is_main());
+
void **val_p;
if (BLI_ghash_ensure_p(gIcons, SET_INT_IN_POINTER(icon_id), &val_p)) {
@@ -571,18 +618,34 @@ void BKE_icon_set(int icon_id, struct Icon *icon)
*val_p = icon;
}
-void BKE_icon_id_delete(struct ID *id)
+static void icon_add_to_deferred_delete_queue(int icon_id)
{
- if (!id->icon_id) return; /* no icon defined for library object */
+ DeferredIconDeleteNode *node =
+ MEM_mallocN(sizeof(DeferredIconDeleteNode), __func__);
+ node->icon_id = icon_id;
+ BLI_linklist_lockfree_insert(&g_icon_delete_queue,
+ (LockfreeLinkNode *)node);
+}
- BLI_ghash_remove(gIcons, SET_INT_IN_POINTER(id->icon_id), NULL, icon_free);
+void BKE_icon_id_delete(struct ID *id)
+{
+ const int icon_id = id->icon_id;
+ if (!icon_id) return; /* no icon defined for library object */
id->icon_id = 0;
+
+ if (!BLI_thread_is_main()) {
+ icon_add_to_deferred_delete_queue(icon_id);
+ return;
+ }
+
+ BKE_icons_deferred_free();
+ BLI_ghash_remove(gIcons, SET_INT_IN_POINTER(icon_id), NULL, icon_free);
}
/**
* Remove icon and free data.
*/
-void BKE_icon_delete(int icon_id)
+void BKE_icon_delete(const int icon_id)
{
Icon *icon;
@@ -591,7 +654,7 @@ void BKE_icon_delete(int icon_id)
icon = BLI_ghash_popkey(gIcons, SET_INT_IN_POINTER(icon_id), NULL);
if (icon) {
- if (icon->type) {
+ if (icon->id_type != 0) {
((ID *)(icon->obj))->icon_id = 0;
}
else {
diff --git a/source/blender/blenkernel/intern/idprop.c b/source/blender/blenkernel/intern/idprop.c
index b2641b110f8..5c13ba7907d 100644
--- a/source/blender/blenkernel/intern/idprop.c
+++ b/source/blender/blenkernel/intern/idprop.c
@@ -90,7 +90,7 @@ IDProperty *IDP_NewIDPArray(const char *name)
return prop;
}
-IDProperty *IDP_CopyIDPArray(const IDProperty *array)
+IDProperty *IDP_CopyIDPArray(const IDProperty *array, const int flag)
{
/* don't use MEM_dupallocN because this may be part of an array */
IDProperty *narray, *tmp;
@@ -109,7 +109,7 @@ IDProperty *IDP_CopyIDPArray(const IDProperty *array)
* then free it. this makes for more maintainable
* code than simply reimplementing the copy functions
* in this loop.*/
- tmp = IDP_CopyProperty(GETPROP(narray, i));
+ tmp = IDP_CopyProperty_ex(GETPROP(narray, i), flag);
memcpy(GETPROP(narray, i), tmp, sizeof(IDProperty));
MEM_freeN(tmp);
}
@@ -117,31 +117,35 @@ IDProperty *IDP_CopyIDPArray(const IDProperty *array)
return narray;
}
-void IDP_FreeIDPArray(IDProperty *prop)
+static void IDP_FreeIDPArray(IDProperty *prop, const bool do_id_user)
{
int i;
BLI_assert(prop->type == IDP_IDPARRAY);
for (i = 0; i < prop->len; i++)
- IDP_FreeProperty(GETPROP(prop, i));
+ IDP_FreeProperty_ex(GETPROP(prop, i), do_id_user);
if (prop->data.pointer)
MEM_freeN(prop->data.pointer);
}
-/*shallow copies item*/
+/* shallow copies item */
void IDP_SetIndexArray(IDProperty *prop, int index, IDProperty *item)
{
IDProperty *old;
BLI_assert(prop->type == IDP_IDPARRAY);
+ if (index >= prop->len || index < 0)
+ return;
+
old = GETPROP(prop, index);
- if (index >= prop->len || index < 0) return;
- if (item != old) IDP_FreeProperty(old);
-
- memcpy(GETPROP(prop, index), item, sizeof(IDProperty));
+ if (item != old) {
+ IDP_FreeProperty(old);
+
+ memcpy(old, item, sizeof(IDProperty));
+ }
}
IDProperty *IDP_GetIndexArray(IDProperty *prop, int index)
@@ -281,9 +285,9 @@ void IDP_FreeArray(IDProperty *prop)
}
-static IDProperty *idp_generic_copy(const IDProperty *prop)
+static IDProperty *idp_generic_copy(const IDProperty *prop, const int UNUSED(flag))
{
- IDProperty *newp = MEM_callocN(sizeof(IDProperty), "IDProperty array dup");
+ IDProperty *newp = MEM_callocN(sizeof(IDProperty), __func__);
BLI_strncpy(newp->name, prop->name, MAX_IDPROP_NAME);
newp->type = prop->type;
@@ -294,9 +298,9 @@ static IDProperty *idp_generic_copy(const IDProperty *prop)
return newp;
}
-static IDProperty *IDP_CopyArray(const IDProperty *prop)
+static IDProperty *IDP_CopyArray(const IDProperty *prop, const int flag)
{
- IDProperty *newp = idp_generic_copy(prop);
+ IDProperty *newp = idp_generic_copy(prop, flag);
if (prop->data.pointer) {
newp->data.pointer = MEM_dupallocN(prop->data.pointer);
@@ -306,7 +310,7 @@ static IDProperty *IDP_CopyArray(const IDProperty *prop)
int a;
for (a = 0; a < prop->len; a++)
- array[a] = IDP_CopyProperty(array[a]);
+ array[a] = IDP_CopyProperty_ex(array[a], flag);
}
}
newp->len = prop->len;
@@ -359,12 +363,12 @@ IDProperty *IDP_NewString(const char *st, const char *name, int maxlen)
return prop;
}
-static IDProperty *IDP_CopyString(const IDProperty *prop)
+static IDProperty *IDP_CopyString(const IDProperty *prop, const int flag)
{
IDProperty *newp;
BLI_assert(prop->type == IDP_STRING);
- newp = idp_generic_copy(prop);
+ newp = idp_generic_copy(prop, flag);
if (prop->data.pointer)
newp->data.pointer = MEM_dupallocN(prop->data.pointer);
@@ -433,22 +437,26 @@ void IDP_FreeString(IDProperty *prop)
/* -------------------------------------------------------------------- */
-/* ID Type (not in use yet) */
+/* ID Type */
-/** \name IDProperty ID API (unused)
+/** \name IDProperty ID API
* \{ */
-void IDP_LinkID(IDProperty *prop, ID *id)
-{
- if (prop->data.pointer)
- id_us_min(((ID *)prop->data.pointer));
- prop->data.pointer = id;
- id_us_plus(id);
-}
-void IDP_UnlinkID(IDProperty *prop)
+static IDProperty *IDP_CopyID(const IDProperty *prop, const int flag)
{
- id_us_min(((ID *)prop->data.pointer));
+ IDProperty *newp;
+
+ BLI_assert(prop->type == IDP_ID);
+ newp = idp_generic_copy(prop, flag);
+
+ newp->data.pointer = prop->data.pointer;
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus(IDP_Id(newp));
+ }
+
+ return newp;
}
+
/** \} */
@@ -461,16 +469,16 @@ void IDP_UnlinkID(IDProperty *prop)
/**
* Checks if a property with the same name as prop exists, and if so replaces it.
*/
-static IDProperty *IDP_CopyGroup(const IDProperty *prop)
+static IDProperty *IDP_CopyGroup(const IDProperty *prop, const int flag)
{
IDProperty *newp, *link;
BLI_assert(prop->type == IDP_GROUP);
- newp = idp_generic_copy(prop);
+ newp = idp_generic_copy(prop, flag);
newp->len = prop->len;
for (link = prop->data.group.first; link; link = link->next) {
- BLI_addtail(&newp->data.group, IDP_CopyProperty(link));
+ BLI_addtail(&newp->data.group, IDP_CopyProperty_ex(link, flag));
}
return newp;
@@ -499,14 +507,9 @@ void IDP_SyncGroupValues(IDProperty *dest, const IDProperty *src)
break;
default:
{
- IDProperty *tmp = other;
- IDProperty *copy = IDP_CopyProperty(prop);
-
- BLI_insertlinkafter(&dest->data.group, other, copy);
- BLI_remlink(&dest->data.group, tmp);
-
- IDP_FreeProperty(tmp);
- MEM_freeN(tmp);
+ BLI_insertlinkreplace(&dest->data.group, other, IDP_CopyProperty(prop));
+ IDP_FreeProperty(other);
+ MEM_freeN(other);
break;
}
}
@@ -526,11 +529,9 @@ void IDP_SyncGroupTypes(IDProperty *dst, const IDProperty *src, const bool do_ar
if ((prop_dst->type != prop_src->type || prop_dst->subtype != prop_src->subtype) ||
(do_arraylen && ELEM(prop_dst->type, IDP_ARRAY, IDP_IDPARRAY) && (prop_src->len != prop_dst->len)))
{
- IDP_FreeFromGroup(dst, prop_dst);
- prop_dst = IDP_CopyProperty(prop_src);
-
- dst->len++;
- BLI_insertlinkbefore(&dst->data.group, prop_dst_next, prop_dst);
+ BLI_insertlinkreplace(&dst->data.group, prop_dst, IDP_CopyProperty(prop_src));
+ IDP_FreeProperty(prop_dst);
+ MEM_freeN(prop_dst);
}
else if (prop_dst->type == IDP_GROUP) {
IDP_SyncGroupTypes(prop_dst, prop_src, do_arraylen);
@@ -555,11 +556,7 @@ void IDP_ReplaceGroupInGroup(IDProperty *dest, const IDProperty *src)
for (prop = src->data.group.first; prop; prop = prop->next) {
for (loop = dest->data.group.first; loop; loop = loop->next) {
if (STREQ(loop->name, prop->name)) {
- IDProperty *copy = IDP_CopyProperty(prop);
-
- BLI_insertlinkafter(&dest->data.group, loop, copy);
-
- BLI_remlink(&dest->data.group, loop);
+ BLI_insertlinkreplace(&dest->data.group, loop, IDP_CopyProperty(prop));
IDP_FreeProperty(loop);
MEM_freeN(loop);
break;
@@ -586,9 +583,7 @@ void IDP_ReplaceInGroup_ex(IDProperty *group, IDProperty *prop, IDProperty *prop
BLI_assert(prop_exist == IDP_GetPropertyFromGroup(group, prop->name));
if ((prop_exist = IDP_GetPropertyFromGroup(group, prop->name))) {
- BLI_insertlinkafter(&group->data.group, prop_exist, prop);
-
- BLI_remlink(&group->data.group, prop_exist);
+ BLI_insertlinkreplace(&group->data.group, prop_exist, prop);
IDP_FreeProperty(prop_exist);
MEM_freeN(prop_exist);
}
@@ -719,13 +714,13 @@ IDProperty *IDP_GetPropertyTypeFromGroup(IDProperty *prop, const char *name, con
* 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. */
-static void IDP_FreeGroup(IDProperty *prop)
+static void IDP_FreeGroup(IDProperty *prop, const bool do_id_user)
{
IDProperty *loop;
BLI_assert(prop->type == IDP_GROUP);
for (loop = prop->data.group.first; loop; loop = loop->next) {
- IDP_FreeProperty(loop);
+ IDP_FreeProperty_ex(loop, do_id_user);
}
BLI_freelistN(&prop->data.group);
}
@@ -737,14 +732,58 @@ static void IDP_FreeGroup(IDProperty *prop)
/** \name IDProperty Main API
* \{ */
+IDProperty *IDP_CopyProperty_ex(const IDProperty *prop, const int flag)
+{
+ switch (prop->type) {
+ case IDP_GROUP: return IDP_CopyGroup(prop, flag);
+ case IDP_STRING: return IDP_CopyString(prop, flag);
+ case IDP_ID: return IDP_CopyID(prop, flag);
+ case IDP_ARRAY: return IDP_CopyArray(prop, flag);
+ case IDP_IDPARRAY: return IDP_CopyIDPArray(prop, flag);
+ default: return idp_generic_copy(prop, flag);
+ }
+}
+
IDProperty *IDP_CopyProperty(const IDProperty *prop)
{
+ return IDP_CopyProperty_ex(prop, 0);
+}
+
+/* Updates ID pointers after an object has been copied */
+/* TODO Nuke this once its only user has been correctly converted to use generic ID management from BKE_library! */
+void IDP_RelinkProperty(struct IDProperty *prop)
+{
+ if (!prop)
+ return;
+
switch (prop->type) {
- case IDP_GROUP: return IDP_CopyGroup(prop);
- case IDP_STRING: return IDP_CopyString(prop);
- case IDP_ARRAY: return IDP_CopyArray(prop);
- case IDP_IDPARRAY: return IDP_CopyIDPArray(prop);
- default: return idp_generic_copy(prop);
+ case IDP_GROUP:
+ {
+ for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
+ IDP_RelinkProperty(loop);
+ }
+ break;
+ }
+ case IDP_IDPARRAY:
+ {
+ IDProperty *idp_array = IDP_Array(prop);
+ for (int i = 0; i < prop->len; i++) {
+ IDP_RelinkProperty(&idp_array[i]);
+ }
+ break;
+ }
+ case IDP_ID:
+ {
+ ID *id = IDP_Id(prop);
+ if (id && id->newid) {
+ id_us_min(IDP_Id(prop));
+ prop->data.pointer = id->newid;
+ id_us_plus(IDP_Id(prop));
+ }
+ break;
+ }
+ default:
+ break; /* Nothing to do for other IDProp types. */
}
}
@@ -839,11 +878,14 @@ bool IDP_EqualsProperties_ex(IDProperty *prop1, IDProperty *prop2, const bool is
if (prop1->len != prop2->len)
return false;
- for (i = 0; i < prop1->len; i++)
- if (!IDP_EqualsProperties(&array1[i], &array2[i]))
+ for (i = 0; i < prop1->len; i++) {
+ if (!IDP_EqualsProperties_ex(&array1[i], &array2[i], is_strict))
return false;
+ }
return true;
}
+ case IDP_ID:
+ return (IDP_Id(prop1) == IDP_Id(prop2));
default:
/* should never get here */
BLI_assert(0);
@@ -867,17 +909,19 @@ bool IDP_EqualsProperties(IDProperty *prop1, IDProperty *prop2)
* The union is simple to use; see the top of this header file for its definition.
* An example of using this function:
*
- * IDPropertyTemplate val;
- * IDProperty *group, *idgroup, *color;
- * group = IDP_New(IDP_GROUP, val, "group1"); //groups don't need a template.
+ * \code{.c}
+ * IDPropertyTemplate val;
+ * IDProperty *group, *idgroup, *color;
+ * group = IDP_New(IDP_GROUP, val, "group1"); //groups don't need a template.
*
- * val.array.len = 4
- * val.array.type = IDP_FLOAT;
- * color = IDP_New(IDP_ARRAY, val, "color1");
+ * val.array.len = 4
+ * val.array.type = IDP_FLOAT;
+ * color = IDP_New(IDP_ARRAY, val, "color1");
*
- * idgroup = IDP_GetProperties(some_id, 1);
- * IDP_AddToGroup(idgroup, color);
- * IDP_AddToGroup(idgroup, group);
+ * idgroup = IDP_GetProperties(some_id, 1);
+ * IDP_AddToGroup(idgroup, color);
+ * IDP_AddToGroup(idgroup, group);
+ * \endcode
*
* Note that you MUST either attach the id property to an id property group with
* IDP_AddToGroup or MEM_freeN the property, doing anything else might result in
@@ -897,7 +941,7 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char *
*(float *)&prop->data.val = val->f;
break;
case IDP_DOUBLE:
- prop = MEM_callocN(sizeof(IDProperty), "IDProperty float");
+ prop = MEM_callocN(sizeof(IDProperty), "IDProperty double");
*(double *)&prop->data.val = val->d;
break;
case IDP_ARRAY:
@@ -917,6 +961,7 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char *
prop->len = prop->totallen = val->array.len;
break;
}
+ printf("%s: bad array type.\n", __func__);
return NULL;
}
case IDP_STRING:
@@ -963,6 +1008,14 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char *
/* heh I think all needed values are set properly by calloc anyway :) */
break;
}
+ case IDP_ID:
+ {
+ prop = MEM_callocN(sizeof(IDProperty), "IDProperty datablock");
+ prop->data.pointer = (void *)val->id;
+ prop->type = IDP_ID;
+ id_us_plus(IDP_Id(prop));
+ break;
+ }
default:
{
prop = MEM_callocN(sizeof(IDProperty), "IDProperty array");
@@ -977,11 +1030,10 @@ IDProperty *IDP_New(const char type, const IDPropertyTemplate *val, const char *
}
/**
- * \note this will free all child properties of list arrays and groups!
- * Also, note that this does NOT unlink anything! Plus it doesn't free
- * the actual struct IDProperty struct either.
+ * \note This will free allocated data, all child properties of arrays and groups, and unlink IDs!
+ * But it does not free the actual IDProperty struct itself.
*/
-void IDP_FreeProperty(IDProperty *prop)
+void IDP_FreeProperty_ex(IDProperty *prop, const bool do_id_user)
{
switch (prop->type) {
case IDP_ARRAY:
@@ -991,14 +1043,24 @@ void IDP_FreeProperty(IDProperty *prop)
IDP_FreeString(prop);
break;
case IDP_GROUP:
- IDP_FreeGroup(prop);
+ IDP_FreeGroup(prop, do_id_user);
break;
case IDP_IDPARRAY:
- IDP_FreeIDPArray(prop);
+ IDP_FreeIDPArray(prop, do_id_user);
+ break;
+ case IDP_ID:
+ if (do_id_user) {
+ id_us_min(IDP_Id(prop));
+ }
break;
}
}
+void IDP_FreeProperty(IDProperty *prop)
+{
+ IDP_FreeProperty_ex(prop, true);
+}
+
void IDP_ClearProperty(IDProperty *prop)
{
IDP_FreeProperty(prop);
@@ -1006,18 +1068,4 @@ void IDP_ClearProperty(IDProperty *prop)
prop->len = prop->totallen = 0;
}
-/**
- * Unlinks any struct IDProperty<->ID linkage that might be going on.
- *
- * \note currently unused
- */
-void IDP_UnlinkProperty(IDProperty *prop)
-{
- switch (prop->type) {
- case IDP_ID:
- IDP_UnlinkID(prop);
- break;
- }
-}
-
/** \} */
diff --git a/source/blender/blenkernel/intern/image.c b/source/blender/blenkernel/intern/image.c
index 318f6480aaf..e8b5ce77613 100644
--- a/source/blender/blenkernel/intern/image.c
+++ b/source/blender/blenkernel/intern/image.c
@@ -46,6 +46,7 @@
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
#include "IMB_moviecache.h"
+#include "IMB_metadata.h"
#ifdef WITH_OPENEXR
# include "intern/openexr/openexr_multi.h"
@@ -62,6 +63,7 @@
#include "BLI_blenlib.h"
#include "BLI_math_vector.h"
+#include "BLI_mempool.h"
#include "BLI_threads.h"
#include "BLI_timecode.h" /* for stamp timecode format */
#include "BLI_utildefines.h"
@@ -111,9 +113,9 @@ static void image_add_view(Image *ima, const char *viewname, const char *filepat
/* quick lookup: supports 1 million frames, thousand passes */
#define IMA_MAKE_INDEX(frame, index) (((frame) << 10) + (index))
#define IMA_INDEX_FRAME(index) ((index) >> 10)
-/*
+#if 0
#define IMA_INDEX_PASS(index) (index & ~1023)
-*/
+#endif
/* ******** IMAGE CACHE ************* */
@@ -150,7 +152,7 @@ static void imagecache_put(Image *image, int index, ImBuf *ibuf)
if (image->cache == NULL) {
// char cache_name[64];
- // BLI_snprintf(cache_name, sizeof(cache_name), "Image Datablock %s", image->id.name);
+ // SNPRINTF(cache_name, "Image Datablock %s", image->id.name);
image->cache = IMB_moviecache_create("Image Datablock Cache", sizeof(ImageCacheKey),
imagecache_hashhash, imagecache_hashcmp);
@@ -302,8 +304,11 @@ static void image_free_anims(Image *ima)
* Simply free the image data from memory,
* on display the image can load again (except for render buffers).
*/
-void BKE_image_free_buffers(Image *ima)
+void BKE_image_free_buffers_ex(Image *ima, bool do_lock)
{
+ if (do_lock) {
+ BLI_spin_lock(&image_spin);
+ }
image_free_cached_frames(ima);
image_free_anims(ima);
@@ -322,6 +327,15 @@ void BKE_image_free_buffers(Image *ima)
}
ima->ok = IMA_OK;
+
+ if (do_lock) {
+ BLI_spin_unlock(&image_spin);
+ }
+}
+
+void BKE_image_free_buffers(Image *ima)
+{
+ BKE_image_free_buffers_ex(ima, false);
}
/** Free (or release) any data used by this image (does not free the image itself). */
@@ -381,7 +395,7 @@ static Image *image_alloc(Main *bmain, const char *name, short source, short typ
{
Image *ima;
- ima = BKE_libblock_alloc(bmain, ID_IM, name);
+ ima = BKE_libblock_alloc(bmain, ID_IM, name, 0);
if (ima) {
image_init(ima, source, type);
}
@@ -423,7 +437,7 @@ static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src)
BLI_listbase_clear(lb_dst);
for (imapf_src = lb_src->first; imapf_src; imapf_src = imapf_src->next) {
ImagePackedFile *imapf_dst = MEM_mallocN(sizeof(ImagePackedFile), "Image Packed Files (copy)");
- BLI_strncpy(imapf_dst->filepath, imapf_src->filepath, sizeof(imapf_dst->filepath));
+ STRNCPY(imapf_dst->filepath, imapf_src->filepath);
if (imapf_src->packedfile)
imapf_dst->packedfile = dupPackedFile(imapf_src->packedfile);
@@ -432,39 +446,53 @@ static void copy_image_packedfiles(ListBase *lb_dst, const ListBase *lb_src)
}
}
-/* empty image block, of similar type and filename */
-Image *BKE_image_copy(Main *bmain, Image *ima)
+/**
+ * Only copy internal data of Image ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_image_copy_data(Main *UNUSED(bmain), Image *ima_dst, const Image *ima_src, const int flag)
{
- Image *nima = image_alloc(bmain, ima->id.name + 2, ima->source, ima->type);
-
- BLI_strncpy(nima->name, ima->name, sizeof(ima->name));
+ BKE_color_managed_colorspace_settings_copy(&ima_dst->colorspace_settings, &ima_src->colorspace_settings);
- nima->flag = ima->flag;
- nima->tpageflag = ima->tpageflag;
+ copy_image_packedfiles(&ima_dst->packedfiles, &ima_src->packedfiles);
- nima->gen_x = ima->gen_x;
- nima->gen_y = ima->gen_y;
- nima->gen_type = ima->gen_type;
- copy_v4_v4(nima->gen_color, ima->gen_color);
+ ima_dst->stereo3d_format = MEM_dupallocN(ima_src->stereo3d_format);
+ BLI_duplicatelist(&ima_dst->views, &ima_src->views);
- nima->animspeed = ima->animspeed;
-
- nima->aspx = ima->aspx;
- nima->aspy = ima->aspy;
-
- BKE_color_managed_colorspace_settings_copy(&nima->colorspace_settings, &ima->colorspace_settings);
-
- copy_image_packedfiles(&nima->packedfiles, &ima->packedfiles);
+ /* Cleanup stuff that cannot be copied. */
+ ima_dst->cache = NULL;
+ ima_dst->rr = NULL;
+ for (int i = 0; i < IMA_MAX_RENDER_SLOT; i++) {
+ ima_dst->renders[i] = NULL;
+ }
- /* nima->stere3d_format is already allocated by image_alloc... */
- *nima->stereo3d_format = *ima->stereo3d_format;
- BLI_duplicatelist(&nima->views, &ima->views);
+ BLI_listbase_clear(&ima_dst->anims);
- BKE_previewimg_id_copy(&nima->id, &ima->id);
+ ima_dst->totbind = 0;
+ for (int i = 0; i < TEXTARGET_COUNT; i++) {
+ ima_dst->bindcode[i] = 0;
+ ima_dst->gputexture[i] = NULL;
+ }
+ ima_dst->repbind = NULL;
- BKE_id_copy_ensure_local(bmain, &ima->id, &nima->id);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&ima_dst->id, &ima_src->id);
+ }
+ else {
+ ima_dst->preview = NULL;
+ }
+}
- return nima;
+/* empty image block, of similar type and filename */
+Image *BKE_image_copy(Main *bmain, const Image *ima)
+{
+ Image *ima_copy;
+ BKE_id_copy_ex(bmain, &ima->id, (ID **)&ima_copy, 0, false);
+ return ima_copy;
}
void BKE_image_make_local(Main *bmain, Image *ima, const bool lib_local)
@@ -565,7 +593,7 @@ Image *BKE_image_load(Main *bmain, const char *filepath)
int file;
char str[FILE_MAX];
- BLI_strncpy(str, filepath, sizeof(str));
+ STRNCPY(str, filepath);
BLI_path_abs(str, bmain->name);
/* exists? */
@@ -575,7 +603,7 @@ Image *BKE_image_load(Main *bmain, const char *filepath)
close(file);
ima = image_alloc(bmain, BLI_path_basename(filepath), IMA_SRC_FILE, IMA_TYPE_IMAGE);
- BLI_strncpy(ima->name, filepath, sizeof(ima->name));
+ STRNCPY(ima->name, filepath);
if (BLI_testextensie_array(filepath, imb_ext_movie))
ima->source = IMA_SRC_MOVIE;
@@ -594,13 +622,13 @@ Image *BKE_image_load_exists_ex(const char *filepath, bool *r_exists)
Image *ima;
char str[FILE_MAX], strtest[FILE_MAX];
- BLI_strncpy(str, filepath, sizeof(str));
+ STRNCPY(str, filepath);
BLI_path_abs(str, G.main->name);
/* first search an identical filepath */
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));
+ STRNCPY(strtest, ima->name);
BLI_path_abs(strtest, ID_BLEND_PATH(G.main, &ima->id));
if (BLI_path_cmp(strtest, str) == 0) {
@@ -641,7 +669,7 @@ static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char
if (colorspace_settings->name[0] == '\0') {
const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_FLOAT);
- BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
+ STRNCPY(colorspace_settings->name, colorspace);
}
if (ibuf != NULL) {
@@ -655,7 +683,7 @@ static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char
if (colorspace_settings->name[0] == '\0') {
const char *colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_DEFAULT_BYTE);
- BLI_strncpy(colorspace_settings->name, colorspace, sizeof(colorspace_settings->name));
+ STRNCPY(colorspace_settings->name, colorspace);
}
if (ibuf != NULL) {
@@ -668,7 +696,7 @@ static ImBuf *add_ibuf_size(unsigned int width, unsigned int height, const char
return NULL;
}
- BLI_strncpy(ibuf->name, name, sizeof(ibuf->name));
+ STRNCPY(ibuf->name, name);
ibuf->userflags |= IB_BITMAPDIRTY;
switch (gen_type) {
@@ -698,7 +726,7 @@ Image *BKE_image_add_generated(
int view_id;
const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
- /* BLI_strncpy(ima->name, name, FILE_MAX); */ /* don't do this, this writes in ain invalid filepath! */
+ /* STRNCPY(ima->name, name); */ /* don't do this, this writes in ain invalid filepath! */
ima->gen_x = width;
ima->gen_y = height;
ima->gen_type = gen_type;
@@ -739,7 +767,7 @@ Image *BKE_image_add_from_imbuf(ImBuf *ibuf, const char *name)
ima = image_alloc(G.main, name, IMA_SRC_FILE, IMA_TYPE_IMAGE);
if (ima) {
- BLI_strncpy(ima->name, ibuf->name, FILE_MAX);
+ STRNCPY(ima->name, ibuf->name);
image_assign_ibuf(ima, ibuf, IMA_NO_INDEX, 0);
ima->ok = IMA_OK_LOADED;
}
@@ -785,7 +813,7 @@ static void image_memorypack_multiview(Image *ima)
pf->size = ibuf->encodedsize;
imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile");
- BLI_strncpy(imapf->filepath, iv->filepath, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, iv->filepath);
imapf->packedfile = pf;
BLI_addtail(&ima->packedfiles, imapf);
@@ -835,7 +863,7 @@ void BKE_image_memorypack(Image *ima)
pf->size = ibuf->encodedsize;
imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image PackedFile");
- BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, ima->name);
imapf->packedfile = pf;
BLI_addtail(&ima->packedfiles, imapf);
@@ -861,7 +889,7 @@ void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
BLI_addtail(&ima->packedfiles, imapf);
imapf->packedfile = newPackedFile(reports, ima->name, basepath);
if (imapf->packedfile) {
- BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, ima->name);
}
else {
BLI_freelinkN(&ima->packedfiles, imapf);
@@ -875,7 +903,7 @@ void BKE_image_packfiles(ReportList *reports, Image *ima, const char *basepath)
imapf->packedfile = newPackedFile(reports, iv->filepath, basepath);
if (imapf->packedfile) {
- BLI_strncpy(imapf->filepath, iv->filepath, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, iv->filepath);
}
else {
BLI_freelinkN(&ima->packedfiles, imapf);
@@ -895,7 +923,7 @@ void BKE_image_packfiles_from_mem(ReportList *reports, Image *ima, char *data, c
ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), __func__);
BLI_addtail(&ima->packedfiles, imapf);
imapf->packedfile = newPackedFileMemory(data, data_len);
- BLI_strncpy(imapf->filepath, ima->name, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, ima->name);
}
}
@@ -1176,7 +1204,6 @@ bool BKE_imtype_is_movie(const char imtype)
switch (imtype) {
case R_IMF_IMTYPE_AVIRAW:
case R_IMF_IMTYPE_AVIJPEG:
- case R_IMF_IMTYPE_QUICKTIME:
case R_IMF_IMTYPE_FFMPEG:
case R_IMF_IMTYPE_H264:
case R_IMF_IMTYPE_THEORA:
@@ -1238,7 +1265,7 @@ char BKE_imtype_valid_channels(const char imtype, bool write_file)
switch (imtype) {
case R_IMF_IMTYPE_BMP:
if (write_file) break;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case R_IMF_IMTYPE_TARGA:
case R_IMF_IMTYPE_RAWTGA:
case R_IMF_IMTYPE_IRIS:
@@ -1248,7 +1275,6 @@ char BKE_imtype_valid_channels(const char imtype, bool write_file)
case R_IMF_IMTYPE_MULTILAYER:
case R_IMF_IMTYPE_DDS:
case R_IMF_IMTYPE_JP2:
- case R_IMF_IMTYPE_QUICKTIME:
case R_IMF_IMTYPE_DPX:
chan_flag |= IMA_CHAN_FLAG_ALPHA;
break;
@@ -1311,7 +1337,6 @@ char BKE_imtype_from_arg(const char *imtype_arg)
else if (STREQ(imtype_arg, "AVIRAW")) return R_IMF_IMTYPE_AVIRAW;
else if (STREQ(imtype_arg, "AVIJPEG")) return R_IMF_IMTYPE_AVIJPEG;
else if (STREQ(imtype_arg, "PNG")) return R_IMF_IMTYPE_PNG;
- else if (STREQ(imtype_arg, "QUICKTIME")) return R_IMF_IMTYPE_QUICKTIME;
else if (STREQ(imtype_arg, "BMP")) return R_IMF_IMTYPE_BMP;
#ifdef WITH_HDR
else if (STREQ(imtype_arg, "HDR")) return R_IMF_IMTYPE_RADHDR;
@@ -1422,7 +1447,7 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF
}
}
#endif
- else { // R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90, R_IMF_IMTYPE_QUICKTIME etc
+ else { // R_IMF_IMTYPE_AVIRAW, R_IMF_IMTYPE_AVIJPEG, R_IMF_IMTYPE_JPEG90 etc
if (!(BLI_testextensie_n(string, extension_test = ".jpg", ".jpeg", NULL)))
extension = extension_test;
}
@@ -1430,9 +1455,7 @@ static bool do_add_image_extension(char *string, const char imtype, const ImageF
if (extension) {
/* prefer this in many cases to avoid .png.tga, but in certain cases it breaks */
/* remove any other known image extension */
- if (BLI_testextensie_array(string, imb_ext_image) ||
- (G.have_quicktime && BLI_testextensie_array(string, imb_ext_image_qt)))
- {
+ if (BLI_testextensie_array(string, imb_ext_image)) {
return BLI_replace_extension(string, FILE_MAX, extension);
}
else {
@@ -1585,6 +1608,14 @@ void BKE_imbuf_to_image_format(struct ImageFormatData *im_format, const ImBuf *i
#define STAMP_NAME_SIZE ((MAX_ID_NAME - 2) + 16)
/* could allow access externally - 512 is for long names,
* STAMP_NAME_SIZE is for id names, allowing them some room for description */
+typedef struct StampDataCustomField {
+ struct StampDataCustomField *next, *prev;
+ /* TODO(sergey): Think of better size here, maybe dynamically allocated even. */
+ char key[512];
+ char value[512];
+ /* TODO(sergey): Support non-string values. */
+} StampDataCustomField;
+
typedef struct StampData {
char file[512];
char note[512];
@@ -1592,23 +1623,36 @@ typedef struct StampData {
char marker[512];
char time[512];
char frame[512];
+ char frame_range[512];
char camera[STAMP_NAME_SIZE];
char cameralens[STAMP_NAME_SIZE];
char scene[STAMP_NAME_SIZE];
char strip[STAMP_NAME_SIZE];
char rendertime[STAMP_NAME_SIZE];
char memory[STAMP_NAME_SIZE];
+
+ /* Custom fields are used to put extra meta information header from render
+ * engine to the result image.
+ *
+ * NOTE: This fields are not stamped onto the image. At least for now.
+ */
+ ListBase custom_fields;
} StampData;
#undef STAMP_NAME_SIZE
-static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix)
+/**
+ * \param do_prefix: Include a label like "File ", "Date ", etc. in the stamp data strings.
+ * \param use_dynamic: Also include data that can change on a per-frame basis.
+ */
+static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int do_prefix,
+ bool use_dynamic)
{
char text[256];
struct tm *tl;
time_t t;
if (scene->r.stamp & R_STAMP_FILENAME) {
- BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
+ SNPRINTF(stamp_data->file, do_prefix ? "File %s" : "%s", G.relbase_valid ? G.main->name : "<untitled>");
}
else {
stamp_data->file[0] = '\0';
@@ -1616,7 +1660,7 @@ static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int d
if (scene->r.stamp & R_STAMP_NOTE) {
/* Never do prefix for Note */
- BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", scene->r.stamp_udata);
+ SNPRINTF(stamp_data->note, "%s", scene->r.stamp_udata);
}
else {
stamp_data->note[0] = '\0';
@@ -1625,108 +1669,125 @@ static void stampdata(Scene *scene, Object *camera, StampData *stamp_data, int d
if (scene->r.stamp & R_STAMP_DATE) {
t = time(NULL);
tl = localtime(&t);
- BLI_snprintf(text, sizeof(text), "%04d/%02d/%02d %02d:%02d:%02d", tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
- BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), do_prefix ? "Date %s" : "%s", text);
+ SNPRINTF(text, "%04d/%02d/%02d %02d:%02d:%02d",
+ tl->tm_year + 1900, tl->tm_mon + 1, tl->tm_mday, tl->tm_hour, tl->tm_min, tl->tm_sec);
+ SNPRINTF(stamp_data->date, do_prefix ? "Date %s" : "%s", text);
}
else {
stamp_data->date[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_MARKER) {
+ if (use_dynamic && scene->r.stamp & R_STAMP_MARKER) {
const char *name = BKE_scene_find_last_marker_name(scene, CFRA);
- if (name) BLI_strncpy(text, name, sizeof(text));
- else BLI_strncpy(text, "<none>", sizeof(text));
+ if (name) STRNCPY(text, name);
+ else STRNCPY(text, "<none>");
- BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), do_prefix ? "Marker %s" : "%s", text);
+ SNPRINTF(stamp_data->marker, do_prefix ? "Marker %s" : "%s", text);
}
else {
stamp_data->marker[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_TIME) {
+ if (use_dynamic && scene->r.stamp & R_STAMP_TIME) {
const short timecode_style = USER_TIMECODE_SMPTE_FULL;
BLI_timecode_string_from_time(text, sizeof(text), 0, FRA2TIME(scene->r.cfra), FPS, timecode_style);
- BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), do_prefix ? "Timecode %s" : "%s", text);
+ SNPRINTF(stamp_data->time, do_prefix ? "Timecode %s" : "%s", text);
}
else {
stamp_data->time[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_FRAME) {
+ if (use_dynamic && scene->r.stamp & R_STAMP_FRAME) {
char fmtstr[32];
int digits = 1;
if (scene->r.efra > 9)
- digits = 1 + (int) log10(scene->r.efra);
+ digits = integer_digits_i(scene->r.efra);
- BLI_snprintf(fmtstr, sizeof(fmtstr), do_prefix ? "Frame %%0%di" : "%%0%di", digits);
- BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), fmtstr, scene->r.cfra);
+ SNPRINTF(fmtstr, do_prefix ? "Frame %%0%di" : "%%0%di", digits);
+ SNPRINTF(stamp_data->frame, fmtstr, scene->r.cfra);
}
else {
stamp_data->frame[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_CAMERA) {
- BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
+ if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
+ SNPRINTF(stamp_data->frame_range,
+ do_prefix ? "Frame Range %d:%d" : "%d:%d",
+ scene->r.sfra, scene->r.efra);
+ }
+ else {
+ stamp_data->frame_range[0] = '\0';
+ }
+
+ if (use_dynamic && scene->r.stamp & R_STAMP_CAMERA) {
+ SNPRINTF(stamp_data->camera, do_prefix ? "Camera %s" : "%s", camera ? camera->id.name + 2 : "<none>");
}
else {
stamp_data->camera[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_CAMERALENS) {
+ if (use_dynamic && scene->r.stamp & R_STAMP_CAMERALENS) {
if (camera && camera->type == OB_CAMERA) {
- BLI_snprintf(text, sizeof(text), "%.2f", ((Camera *)camera->data)->lens);
+ SNPRINTF(text, "%.2f", ((Camera *)camera->data)->lens);
}
else {
- BLI_strncpy(text, "<none>", sizeof(text));
+ STRNCPY(text, "<none>");
}
- BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), do_prefix ? "Lens %s" : "%s", text);
+ SNPRINTF(stamp_data->cameralens, do_prefix ? "Lens %s" : "%s", text);
}
else {
stamp_data->cameralens[0] = '\0';
}
if (scene->r.stamp & R_STAMP_SCENE) {
- BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
+ SNPRINTF(stamp_data->scene, do_prefix ? "Scene %s" : "%s", scene->id.name + 2);
}
else {
stamp_data->scene[0] = '\0';
}
- if (scene->r.stamp & R_STAMP_SEQSTRIP) {
+ if (use_dynamic && scene->r.stamp & R_STAMP_SEQSTRIP) {
Sequence *seq = BKE_sequencer_foreground_frame_get(scene, scene->r.cfra);
- if (seq) BLI_strncpy(text, seq->name + 2, sizeof(text));
- else BLI_strncpy(text, "<none>", sizeof(text));
+ if (seq) STRNCPY(text, seq->name + 2);
+ else STRNCPY(text, "<none>");
- BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), do_prefix ? "Strip %s" : "%s", text);
+ SNPRINTF(stamp_data->strip, do_prefix ? "Strip %s" : "%s", text);
}
else {
stamp_data->strip[0] = '\0';
}
{
- Render *re = RE_GetRender(scene->id.name);
+ Render *re = RE_GetSceneRender(scene);
RenderStats *stats = re ? RE_GetStats(re) : NULL;
- if (stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
+ if (use_dynamic && stats && (scene->r.stamp & R_STAMP_RENDERTIME)) {
BLI_timecode_string_from_time_simple(text, sizeof(text), stats->lastframetime);
- BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), do_prefix ? "RenderTime %s" : "%s", text);
+ SNPRINTF(stamp_data->rendertime, do_prefix ? "RenderTime %s" : "%s", text);
}
else {
stamp_data->rendertime[0] = '\0';
}
- if (stats && (scene->r.stamp & R_STAMP_MEMORY)) {
- BLI_snprintf(stamp_data->memory, sizeof(stamp_data->memory), do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
+ if (use_dynamic && stats && (scene->r.stamp & R_STAMP_MEMORY)) {
+ SNPRINTF(stamp_data->memory, do_prefix ? "Peak Memory %.2fM" : "%.2fM", stats->mem_peak);
}
else {
stamp_data->memory[0] = '\0';
}
}
+ if (scene->r.stamp & R_STAMP_FRAME_RANGE) {
+ SNPRINTF(stamp_data->frame_range,
+ do_prefix ? "Frame Range %d:%d" : "%d:%d", scene->r.sfra, scene->r.efra);
+ }
+ else {
+ stamp_data->frame_range[0] = '\0';
+ }
}
/* Will always add prefix. */
@@ -1735,73 +1796,73 @@ static void stampdata_from_template(StampData *stamp_data,
const StampData *stamp_data_template)
{
if (scene->r.stamp & R_STAMP_FILENAME) {
- BLI_snprintf(stamp_data->file, sizeof(stamp_data->file), "File %s", stamp_data_template->file);
+ SNPRINTF(stamp_data->file, "File %s", stamp_data_template->file);
}
else {
stamp_data->file[0] = '\0';
}
if (scene->r.stamp & R_STAMP_NOTE) {
- BLI_snprintf(stamp_data->note, sizeof(stamp_data->note), "%s", stamp_data_template->note);
+ SNPRINTF(stamp_data->note, "%s", stamp_data_template->note);
}
else {
stamp_data->note[0] = '\0';
}
if (scene->r.stamp & R_STAMP_DATE) {
- BLI_snprintf(stamp_data->date, sizeof(stamp_data->date), "Date %s", stamp_data_template->date);
+ SNPRINTF(stamp_data->date, "Date %s", stamp_data_template->date);
}
else {
stamp_data->date[0] = '\0';
}
if (scene->r.stamp & R_STAMP_MARKER) {
- BLI_snprintf(stamp_data->marker, sizeof(stamp_data->marker), "Marker %s", stamp_data_template->marker);
+ SNPRINTF(stamp_data->marker, "Marker %s", stamp_data_template->marker);
}
else {
stamp_data->marker[0] = '\0';
}
if (scene->r.stamp & R_STAMP_TIME) {
- BLI_snprintf(stamp_data->time, sizeof(stamp_data->time), "Timecode %s", stamp_data_template->time);
+ SNPRINTF(stamp_data->time, "Timecode %s", stamp_data_template->time);
}
else {
stamp_data->time[0] = '\0';
}
if (scene->r.stamp & R_STAMP_FRAME) {
- BLI_snprintf(stamp_data->frame, sizeof(stamp_data->frame), "Frame %s", stamp_data_template->frame);
+ SNPRINTF(stamp_data->frame, "Frame %s", stamp_data_template->frame);
}
else {
stamp_data->frame[0] = '\0';
}
if (scene->r.stamp & R_STAMP_CAMERA) {
- BLI_snprintf(stamp_data->camera, sizeof(stamp_data->camera), "Camera %s", stamp_data_template->camera);
+ SNPRINTF(stamp_data->camera, "Camera %s", stamp_data_template->camera);
}
else {
stamp_data->camera[0] = '\0';
}
if (scene->r.stamp & R_STAMP_CAMERALENS) {
- BLI_snprintf(stamp_data->cameralens, sizeof(stamp_data->cameralens), "Lens %s", stamp_data_template->cameralens);
+ SNPRINTF(stamp_data->cameralens, "Lens %s", stamp_data_template->cameralens);
}
else {
stamp_data->cameralens[0] = '\0';
}
if (scene->r.stamp & R_STAMP_SCENE) {
- BLI_snprintf(stamp_data->scene, sizeof(stamp_data->scene), "Scene %s", stamp_data_template->scene);
+ SNPRINTF(stamp_data->scene, "Scene %s", stamp_data_template->scene);
}
else {
stamp_data->scene[0] = '\0';
}
if (scene->r.stamp & R_STAMP_SEQSTRIP) {
- BLI_snprintf(stamp_data->strip, sizeof(stamp_data->strip), "Strip %s", stamp_data_template->strip);
+ SNPRINTF(stamp_data->strip, "Strip %s", stamp_data_template->strip);
}
else {
stamp_data->strip[0] = '\0';
}
if (scene->r.stamp & R_STAMP_RENDERTIME) {
- BLI_snprintf(stamp_data->rendertime, sizeof(stamp_data->rendertime), "RenderTime %s", stamp_data_template->rendertime);
+ SNPRINTF(stamp_data->rendertime, "RenderTime %s", stamp_data_template->rendertime);
}
else {
stamp_data->rendertime[0] = '\0';
}
if (scene->r.stamp & R_STAMP_MEMORY) {
- BLI_snprintf(stamp_data->memory, sizeof(stamp_data->memory), "Peak Memory %s", stamp_data_template->memory);
+ SNPRINTF(stamp_data->memory, "Peak Memory %s", stamp_data_template->memory);
}
else {
stamp_data->memory[0] = '\0';
@@ -1847,7 +1908,7 @@ void BKE_image_stamp_buf(
display = IMB_colormanagement_display_get_named(display_device);
if (stamp_data_template == NULL) {
- stampdata(scene, camera, &stamp_data, (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0);
+ stampdata(scene, camera, &stamp_data, (scene->r.stamp & R_STAMP_HIDE_LABELS) == 0, true);
}
else {
stampdata_from_template(&stamp_data, scene, stamp_data_template);
@@ -2068,13 +2129,28 @@ void BKE_render_result_stamp_info(Scene *scene, Object *camera, struct RenderRes
}
if (!allocate_only)
- stampdata(scene, camera, stamp_data, 0);
+ stampdata(scene, camera, stamp_data, 0, true);
if (!rr->stamp_data) {
rr->stamp_data = stamp_data;
}
}
+struct StampData *BKE_stamp_info_from_scene_static(Scene *scene)
+{
+ struct StampData *stamp_data;
+
+ if (!(scene && (scene->r.stamp & R_STAMP_ALL)))
+ return NULL;
+
+ /* Memory is allocated here (instead of by the caller) so that the caller
+ * doesn't have to know the size of the StampData struct. */
+ stamp_data = MEM_callocN(sizeof(StampData), __func__);
+ stampdata(scene, NULL, stamp_data, 0, false);
+
+ return stamp_data;
+}
+
void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCallback callback, bool noskip)
{
if ((callback == NULL) || (stamp_data == NULL)) {
@@ -2092,6 +2168,7 @@ void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCall
CALL(marker, "Marker");
CALL(time, "Time");
CALL(frame, "Frame");
+ CALL(frame_range, "FrameRange");
CALL(camera, "Camera");
CALL(cameralens, "Lens");
CALL(scene, "Scene");
@@ -2099,31 +2176,67 @@ void BKE_stamp_info_callback(void *data, struct StampData *stamp_data, StampCall
CALL(rendertime, "RenderTime");
CALL(memory, "Memory");
+ for (StampDataCustomField *custom_field = stamp_data->custom_fields.first;
+ custom_field != NULL;
+ custom_field = custom_field->next)
+ {
+ if (noskip || custom_field->value[0]) {
+ callback(data, custom_field->key, custom_field->value, sizeof(custom_field->value));
+ }
+ }
+
#undef CALL
}
+void BKE_render_result_stamp_data(RenderResult *rr, const char *key, const char *value)
+{
+ StampData *stamp_data;
+ if (rr->stamp_data == NULL) {
+ rr->stamp_data = MEM_callocN(sizeof(StampData), "RenderResult.stamp_data");
+ }
+ stamp_data = rr->stamp_data;
+ StampDataCustomField *field = MEM_mallocN(sizeof(StampDataCustomField),
+ "StampData Custom Field");
+ STRNCPY(field->key, key);
+ STRNCPY(field->value, value);
+ BLI_addtail(&stamp_data->custom_fields, field);
+}
+
+void BKE_stamp_data_free(struct StampData *stamp_data)
+{
+ if (stamp_data == NULL) {
+ return;
+ }
+ BLI_freelistN(&stamp_data->custom_fields);
+ MEM_freeN(stamp_data);
+}
+
/* wrap for callback only */
-static void metadata_change_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
+static void metadata_set_field(void *data, const char *propname, char *propvalue, int UNUSED(len))
{
- IMB_metadata_change_field(data, propname, propvalue);
+ /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
+ struct ImBuf *imbuf = data;
+ IMB_metadata_set_field(imbuf->metadata, propname, propvalue);
}
static void metadata_get_field(void *data, const char *propname, char *propvalue, int len)
{
- IMB_metadata_get_field(data, propname, propvalue, len);
+ /* We know it is an ImBuf* because that's what we pass to BKE_stamp_info_callback. */
+ struct ImBuf *imbuf = data;
+ IMB_metadata_get_field(imbuf->metadata, propname, propvalue, len);
}
void BKE_imbuf_stamp_info(RenderResult *rr, struct ImBuf *ibuf)
{
struct StampData *stamp_data = rr->stamp_data;
-
- BKE_stamp_info_callback(ibuf, stamp_data, metadata_change_field, false);
+ IMB_metadata_ensure(&ibuf->metadata);
+ BKE_stamp_info_callback(ibuf, stamp_data, metadata_set_field, false);
}
void BKE_stamp_info_from_imbuf(RenderResult *rr, struct ImBuf *ibuf)
{
struct StampData *stamp_data = rr->stamp_data;
-
+ IMB_metadata_ensure(&ibuf->metadata);
BKE_stamp_info_callback(ibuf, stamp_data, metadata_get_field, true);
}
@@ -2216,8 +2329,10 @@ void BKE_imbuf_write_prepare(ImBuf *ibuf, const ImageFormatData *imf)
ibuf->foptions.flag |= OPENEXR_HALF;
ibuf->foptions.flag |= (imf->exr_codec & OPENEXR_COMPRESS);
- if (!(imf->flag & R_IMF_FLAG_ZBUF))
- ibuf->zbuf_float = NULL; /* signal for exr saving */
+ if (!(imf->flag & R_IMF_FLAG_ZBUF)) {
+ /* Signal for exr saving. */
+ IMB_freezbuffloatImBuf(ibuf);
+ }
}
#endif
@@ -2476,7 +2591,7 @@ void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *
bool do_reset;
const bool is_multiview = (rd->scemode & R_MULTIVIEW) != 0;
- BLI_lock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_lock(LOCK_DRAW_IMAGE);
if (!BKE_scene_multiview_is_stereo3d(rd))
iuser->flag &= ~IMA_SHOW_STEREO;
@@ -2510,7 +2625,7 @@ void BKE_image_verify_viewer_views(const RenderData *rd, Image *ima, ImageUser *
BLI_spin_unlock(&image_spin);
}
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
}
void BKE_image_walk_all_users(const Main *mainp, void *customdata,
@@ -2668,7 +2783,7 @@ void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
if (BKE_image_has_packedfile(ima)) {
const int totfiles = image_num_files(ima);
- if (totfiles != BLI_listbase_count_ex(&ima->packedfiles, totfiles + 1)) {
+ if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
/* in case there are new available files to be loaded */
image_free_packedfiles(ima);
BKE_image_packfiles(NULL, ima, ID_BLEND_PATH(G.main, &ima->id));
@@ -2737,7 +2852,6 @@ void BKE_image_signal(Image *ima, ImageUser *iuser, int signal)
}
}
-#define PASSTYPE_UNSET -1
/* return renderpass for a given pass index and active view */
/* fallback to available if there are missing passes for active view */
static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const int view, int *r_passindex)
@@ -2746,7 +2860,7 @@ static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const
RenderPass *rpass;
int rp_index = 0;
- int rp_passtype = PASSTYPE_UNSET;
+ const char *rp_name = "";
for (rpass = rl->passes.first; rpass; rpass = rpass->next, rp_index++) {
if (rp_index == pass) {
@@ -2756,12 +2870,12 @@ static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const
break;
}
else {
- rp_passtype = rpass->passtype;
+ rp_name = rpass->name;
}
}
/* multiview */
- else if ((rp_passtype != PASSTYPE_UNSET) &&
- (rpass->passtype == rp_passtype) &&
+ else if (rp_name[0] &&
+ STREQ(rpass->name, rp_name) &&
(rpass->view_id == view))
{
rpass_ret = rpass;
@@ -2781,7 +2895,6 @@ static RenderPass *image_render_pass_get(RenderLayer *rl, const int pass, const
return rpass_ret;
}
-#undef PASSTYPE_UNSET
/* if layer or pass changes, we need an index for the imbufs list */
/* note it is called for rendered results, but it doesnt use the index! */
@@ -2799,7 +2912,7 @@ RenderPass *BKE_image_multilayer_index(RenderResult *rr, ImageUser *iuser)
bool is_stereo = (iuser->flag & IMA_SHOW_STEREO) && RE_RenderResult_is_stereo(rr);
rv_index = is_stereo ? iuser->multiview_eye : iuser->view;
- if (RE_HasFakeLayer(rr)) rl_index += 1;
+ if (RE_HasCombinedLayer(rr)) rl_index += 1;
for (rl = rr->layers.first; rl; rl = rl->next, rl_index++) {
if (iuser->layer == rl_index) {
@@ -2825,7 +2938,7 @@ void BKE_image_multiview_index(Image *ima, ImageUser *iuser)
iuser->multi_index = iuser->multiview_eye;
}
else {
- if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_ex(&ima->views, iuser->view + 1))) {
+ if ((iuser->view < 0) || (iuser->view >= BLI_listbase_count_at_most(&ima->views, iuser->view + 1))) {
iuser->multi_index = iuser->view = 0;
}
else {
@@ -2855,14 +2968,15 @@ bool BKE_image_is_multilayer(Image *ima)
bool BKE_image_is_multiview(Image *ima)
{
- return (BLI_listbase_count_ex(&ima->views, 2) > 1);
+ ImageView *view = ima->views.first;
+ return (view && (view->next || view->name[0]));
}
bool BKE_image_is_stereo(Image *ima)
{
return BKE_image_is_multiview(ima) &&
(BLI_findstring(&ima->views, STEREO_LEFT_NAME, offsetof(ImageView, name)) &&
- BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
+ BLI_findstring(&ima->views, STEREO_RIGHT_NAME, offsetof(ImageView, name)));
}
static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
@@ -2887,7 +3001,7 @@ static void image_init_multilayer_multiview(Image *ima, RenderResult *rr)
if (rr) {
for (RenderView *rv = rr->views.first; rv; rv = rv->next) {
ImageView *iv = MEM_callocN(sizeof(ImageView), "Viewer Image View");
- BLI_strncpy(iv->name, rv->name, sizeof(iv->name));
+ STRNCPY(iv->name, rv->name);
BLI_addtail(&ima->views, iv);
}
}
@@ -2902,7 +3016,7 @@ RenderResult *BKE_image_acquire_renderresult(Scene *scene, Image *ima)
}
else if (ima->type == IMA_TYPE_R_RESULT) {
if (ima->render_slot == ima->last_render_slot)
- rr = RE_AcquireResultRead(RE_GetRender(scene->id.name));
+ rr = RE_AcquireResultRead(RE_GetSceneRender(scene));
else
rr = ima->renders[ima->render_slot];
@@ -2920,7 +3034,7 @@ void BKE_image_release_renderresult(Scene *scene, Image *ima)
}
else if (ima->type == IMA_TYPE_R_RESULT) {
if (ima->render_slot == ima->last_render_slot)
- RE_ReleaseResult(RE_GetRender(scene->id.name));
+ RE_ReleaseResult(RE_GetSceneRender(scene));
}
}
@@ -2940,7 +3054,7 @@ void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
{
/* called right before rendering, ima->renders contains render
* result pointers for everything but the current render */
- Render *re = RE_GetRender(scene->id.name);
+ Render *re = RE_GetSceneRender(scene);
int slot = ima->render_slot, last = ima->last_render_slot;
if (slot != last) {
@@ -2961,51 +3075,6 @@ void BKE_image_backup_render(Scene *scene, Image *ima, bool free_current_slot)
ima->last_render_slot = slot;
}
-/**************************** multiview save openexr *********************************/
-#ifdef WITH_OPENEXR
-static const char *image_get_view_cb(void *base, const int view_id)
-{
- Image *ima = base;
- ImageView *iv = BLI_findlink(&ima->views, view_id);
- return iv ? iv->name : "";
-}
-#endif /* WITH_OPENEXR */
-
-#ifdef WITH_OPENEXR
-static ImBuf *image_get_buffer_cb(void *base, const int view_id)
-{
- Image *ima = base;
- ImageUser iuser = {0};
-
- iuser.view = view_id;
- iuser.ok = 1;
-
- BKE_image_multiview_index(ima, &iuser);
-
- return image_acquire_ibuf(ima, &iuser, NULL);
-}
-#endif /* WITH_OPENEXR */
-
-bool BKE_image_save_openexr_multiview(Image *ima, ImBuf *ibuf, const char *filepath, const int flags)
-{
-#ifdef WITH_OPENEXR
- char name[FILE_MAX];
- bool ok;
-
- BLI_strncpy(name, filepath, sizeof(name));
- BLI_path_abs(name, G.main->name);
-
- ibuf->userdata = ima;
- ok = IMB_exr_multiview_save(ibuf, name, flags, BLI_listbase_count(&ima->views), image_get_view_cb, image_get_buffer_cb);
- ibuf->userdata = NULL;
-
- return ok;
-#else
- UNUSED_VARS(ima, ibuf, filepath, flags);
- return false;
-#endif
-}
-
/**************************** multiview load openexr *********************************/
static void image_add_view(Image *ima, const char *viewname, const char *filepath)
@@ -3013,8 +3082,8 @@ static void image_add_view(Image *ima, const char *viewname, const char *filepat
ImageView *iv;
iv = MEM_mallocN(sizeof(ImageView), "Viewer Image View");
- BLI_strncpy(iv->name, viewname, sizeof(iv->name));
- BLI_strncpy(iv->filepath, filepath, sizeof(iv->filepath));
+ STRNCPY(iv->name, viewname);
+ STRNCPY(iv->filepath, filepath);
/* For stereo drawing we need to ensure:
* STEREO_LEFT_NAME == STEREO_LEFT_ID and
@@ -3038,51 +3107,6 @@ static void image_add_view(Image *ima, const char *viewname, const char *filepat
}
}
-#ifdef WITH_OPENEXR
-static void image_add_view_cb(void *base, const char *str)
-{
- Image *ima = base;
- image_add_view(ima, str, ima->name);
-}
-
-static void image_add_buffer_cb(void *base, const char *str, ImBuf *ibuf, const int frame)
-{
- Image *ima = base;
- int id;
- bool predivide = (ima->alpha_mode == IMA_ALPHA_PREMUL);
- const char *colorspace = ima->colorspace_settings.name;
- const char *to_colorspace = IMB_colormanagement_role_colorspace_name_get(COLOR_ROLE_SCENE_LINEAR);
-
- if (ibuf == NULL)
- return;
-
- id = BLI_findstringindex(&ima->views, str, offsetof(ImageView, name));
-
- if (id == -1)
- return;
-
- if (ibuf->channels >= 3)
- IMB_colormanagement_transform(ibuf->rect_float, ibuf->x, ibuf->y, ibuf->channels,
- colorspace, to_colorspace, predivide);
-
- image_assign_ibuf(ima, ibuf, id, frame);
- IMB_freeImBuf(ibuf);
-}
-#endif /* WITH_OPENEXR */
-
-/* after imbuf load, openexr type can return with a exrhandle open */
-/* in that case we have to build a render-result */
-#ifdef WITH_OPENEXR
-static void image_create_multiview(Image *ima, ImBuf *ibuf, const int frame)
-{
- BKE_image_free_views(ima);
-
- IMB_exr_multiview_convert(ibuf->userdata, ima, image_add_view_cb, image_add_buffer_cb, frame);
-
- IMB_exr_close(ibuf->userdata);
-}
-#endif /* WITH_OPENEXR */
-
/* after imbuf load, openexr type can return with a exrhandle open */
/* in that case we have to build a render-result */
#ifdef WITH_OPENEXR
@@ -3194,16 +3218,10 @@ static ImBuf *load_sequence_single(Image *ima, ImageUser *iuser, int frame, cons
if (ibuf) {
#ifdef WITH_OPENEXR
- /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
- /* handle singlelayer multiview case assign ibuf based on available views */
- if (IMB_exr_has_singlelayer_multiview(ibuf->userdata)) {
- image_create_multiview(ima, ibuf, frame);
- IMB_freeImBuf(ibuf);
- ibuf = NULL;
- }
- else if (IMB_exr_has_multilayer(ibuf->userdata)) {
- /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
+ /* Handle multilayer and multiview cases, don't assign ibuf here.
+ * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
+ if (IMB_exr_has_multilayer(ibuf->userdata)) {
image_create_multilayer(ima, ibuf, frame);
ima->type = IMA_TYPE_MULTILAYER;
IMB_freeImBuf(ibuf);
@@ -3387,7 +3405,7 @@ static ImBuf *image_load_movie_file(Image *ima, ImageUser *iuser, int frame)
const int totfiles = image_num_files(ima);
int i;
- if (totfiles != BLI_listbase_count_ex(&ima->anims, totfiles + 1)) {
+ if (totfiles != BLI_listbase_count_at_most(&ima->anims, totfiles + 1)) {
image_free_anims(ima);
for (i = 0; i < totfiles; i++) {
@@ -3492,14 +3510,9 @@ static ImBuf *load_image_single(
if (ibuf) {
#ifdef WITH_OPENEXR
if (ibuf->ftype == IMB_FTYPE_OPENEXR && ibuf->userdata) {
- if (IMB_exr_has_singlelayer_multiview(ibuf->userdata)) {
- /* handle singlelayer multiview case assign ibuf based on available views */
- image_create_multiview(ima, ibuf, cfra);
- IMB_freeImBuf(ibuf);
- ibuf = NULL;
- }
- else if (IMB_exr_has_multilayer(ibuf->userdata)) {
- /* handle multilayer case, don't assign ibuf. will be handled in BKE_image_acquire_ibuf */
+ /* Handle multilayer and multiview cases, don't assign ibuf here.
+ * will be set layer in BKE_image_acquire_ibuf from ima->rr. */
+ if (IMB_exr_has_multilayer(ibuf->userdata)) {
image_create_multilayer(ima, ibuf, cfra);
ima->type = IMA_TYPE_MULTILAYER;
IMB_freeImBuf(ibuf);
@@ -3520,7 +3533,7 @@ static ImBuf *load_image_single(
ImagePackedFile *imapf = MEM_mallocN(sizeof(ImagePackedFile), "Image Packefile");
BLI_addtail(&ima->packedfiles, imapf);
- BLI_strncpy(imapf->filepath, filepath, sizeof(imapf->filepath));
+ STRNCPY(imapf->filepath, filepath);
imapf->packedfile = newPackedFile(NULL, filepath, ID_BLEND_PATH(G.main, &ima->id));
}
}
@@ -3548,7 +3561,7 @@ static ImBuf *image_load_image_file(Image *ima, ImageUser *iuser, int cfra)
/* this should never happen, but just playing safe */
if (has_packed) {
- if (totfiles != BLI_listbase_count_ex(&ima->packedfiles, totfiles + 1)) {
+ if (totfiles != BLI_listbase_count_at_most(&ima->packedfiles, totfiles + 1)) {
image_free_packedfiles(ima);
has_packed = false;
}
@@ -3665,7 +3678,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc
if (!r_lock)
return NULL;
- re = RE_GetRender(iuser->scene->id.name);
+ re = RE_GetSceneRender(iuser->scene);
channels = 4;
layer = iuser->layer;
@@ -3693,7 +3706,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc
/* release is done in BKE_image_release_ibuf using r_lock */
if (from_render) {
- BLI_lock_thread(LOCK_VIEWER);
+ BLI_thread_lock(LOCK_VIEWER);
*r_lock = re;
rv = NULL;
}
@@ -3751,7 +3764,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc
}
for (rpass = rl->passes.first; rpass; rpass = rpass->next)
- if (rpass->passtype == SCE_PASS_Z)
+ if (STREQ(rpass->name, RE_PASSNAME_Z) && rpass->view_id == actview)
rectz = rpass->rect;
}
}
@@ -3786,7 +3799,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc
}
/* invalidate color managed buffers if render result changed */
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_thread_lock(LOCK_COLORMANAGE);
if (ibuf->x != rres.rectx || ibuf->y != rres.recty || ibuf->rect_float != rectf) {
ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
}
@@ -3827,7 +3840,7 @@ static ImBuf *image_get_render_result(Image *ima, ImageUser *iuser, void **r_loc
ibuf->flags &= ~IB_zbuffloat;
}
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_thread_unlock(LOCK_COLORMANAGE);
ibuf->dither = dither;
@@ -4029,7 +4042,7 @@ static ImBuf *image_acquire_ibuf(Image *ima, ImageUser *iuser, void **r_lock)
/* requires lock/unlock, otherwise don't return image */
if (r_lock) {
/* unlock in BKE_image_release_ibuf */
- BLI_lock_thread(LOCK_VIEWER);
+ BLI_thread_lock(LOCK_VIEWER);
*r_lock = ima;
/* XXX anim play for viewer nodes not yet supported */
@@ -4082,11 +4095,11 @@ void BKE_image_release_ibuf(Image *ima, ImBuf *ibuf, void *lock)
if (lock) {
/* for getting image during threaded render / compositing, need to release */
if (lock == ima) {
- BLI_unlock_thread(LOCK_VIEWER); /* viewer image */
+ BLI_thread_unlock(LOCK_VIEWER); /* viewer image */
}
else if (lock) {
RE_ReleaseResultImage(lock); /* render result */
- BLI_unlock_thread(LOCK_VIEWER); /* view image imbuf */
+ BLI_thread_unlock(LOCK_VIEWER); /* view image imbuf */
}
}
@@ -4132,33 +4145,32 @@ typedef struct ImagePoolEntry {
typedef struct ImagePool {
ListBase image_buffers;
+ BLI_mempool *memory_pool;
} ImagePool;
ImagePool *BKE_image_pool_new(void)
{
ImagePool *pool = MEM_callocN(sizeof(ImagePool), "Image Pool");
+ pool->memory_pool = BLI_mempool_create(sizeof(ImagePoolEntry), 0, 128, BLI_MEMPOOL_NOP);
return pool;
}
void BKE_image_pool_free(ImagePool *pool)
{
- ImagePoolEntry *entry, *next_entry;
-
- /* use single lock to dereference all the image buffers */
+ /* Use single lock to dereference all the image buffers. */
BLI_spin_lock(&image_spin);
-
- for (entry = pool->image_buffers.first; entry; entry = next_entry) {
- next_entry = entry->next;
-
- if (entry->ibuf)
+ for (ImagePoolEntry *entry = pool->image_buffers.first;
+ entry != NULL;
+ entry = entry->next)
+ {
+ if (entry->ibuf) {
IMB_freeImBuf(entry->ibuf);
-
- MEM_freeN(entry);
+ }
}
-
BLI_spin_unlock(&image_spin);
+ BLI_mempool_destroy(pool->memory_pool);
MEM_freeN(pool);
}
@@ -4210,7 +4222,7 @@ ImBuf *BKE_image_pool_acquire_ibuf(Image *ima, ImageUser *iuser, ImagePool *pool
ibuf = image_acquire_ibuf(ima, iuser, NULL);
- entry = MEM_callocN(sizeof(ImagePoolEntry), "Image Pool Entry");
+ entry = BLI_mempool_alloc(pool->memory_pool);
entry->image = ima;
entry->frame = frame;
entry->index = index;
@@ -4340,7 +4352,7 @@ void BKE_image_update_frame(const Main *bmain, int cfra)
void BKE_image_user_file_path(ImageUser *iuser, Image *ima, char *filepath)
{
- if (BKE_image_is_multiview(ima) && (ima->rr == NULL)) {
+ if (BKE_image_is_multiview(ima)) {
ImageView *iv = BLI_findlink(&ima->views, iuser->view);
if (iv->filepath[0])
BLI_strncpy(filepath, iv->filepath, FILE_MAX);
@@ -4676,7 +4688,7 @@ static void image_update_views_format(Image *ima, ImageUser *iuser)
for (srv = scene->r.views.first; srv; srv = srv->next) {
if (BKE_scene_multiview_is_render_view_active(&scene->r, srv)) {
char filepath[FILE_MAX];
- BLI_snprintf(filepath, sizeof(filepath), "%s%s%s", prefix, srv->suffix, ext);
+ SNPRINTF(filepath, "%s%s%s", prefix, srv->suffix, ext);
image_add_view(ima, srv->name, filepath);
}
}
@@ -4687,7 +4699,7 @@ static void image_update_views_format(Image *ima, ImageUser *iuser)
int file;
char str[FILE_MAX];
- BLI_strncpy(str, iv->filepath, sizeof(str));
+ STRNCPY(str, iv->filepath);
BLI_path_abs(str, G.main->name);
/* exists? */
diff --git a/source/blender/blenkernel/intern/image_gen.c b/source/blender/blenkernel/intern/image_gen.c
index 2c8399adece..1f1f4c9d341 100644
--- a/source/blender/blenkernel/intern/image_gen.c
+++ b/source/blender/blenkernel/intern/image_gen.c
@@ -132,7 +132,7 @@ static void image_buf_fill_checker_slice(unsigned char *rect,
float hsv[3] = {0.0f, 0.9f, 0.9f};
float rgb[3];
- float dark_linear_color, bright_linear_color;
+ float dark_linear_color = 0.0f, bright_linear_color = 0.0f;
if (rect_float != NULL) {
dark_linear_color = srgb_to_linearrgb(0.25f);
bright_linear_color = srgb_to_linearrgb(0.58f);
diff --git a/source/blender/blenkernel/intern/ipo.c b/source/blender/blenkernel/intern/ipo.c
index f3a85dcee2b..fcbc25ebad5 100644
--- a/source/blender/blenkernel/intern/ipo.c
+++ b/source/blender/blenkernel/intern/ipo.c
@@ -1192,7 +1192,7 @@ static void icu_to_fcurves(ID *id, ListBase *groups, ListBase *list, IpoCurve *i
/* Add a new FModifier (Cyclic) instead of setting extend value
* as that's the new equivalent of that option.
*/
- FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES);
+ FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, fcu);
FMod_Cycles *data = (FMod_Cycles *)fcm->data;
/* if 'offset' one is in use, set appropriate settings */
@@ -1559,7 +1559,7 @@ static void ipo_to_animdata(ID *id, Ipo *ipo, char actname[], char constname[],
BLI_snprintf(nameBuf, sizeof(nameBuf), "CDA:%s", ipo->id.name + 2);
- adt->action = add_empty_action(G.main, nameBuf);
+ adt->action = BKE_action_add(G.main, nameBuf);
if (G.debug & G_DEBUG) printf("\t\tadded new action - '%s'\n", nameBuf);
}
@@ -1663,7 +1663,7 @@ static void nlastrips_to_animdata(ID *id, ListBase *strips)
/* trying to add to the current failed (no space),
* so add a new track to the stack, and add to that...
*/
- nlt = add_nlatrack(adt, NULL);
+ nlt = BKE_nlatrack_add(adt, NULL);
BKE_nlatrack_add_strip(nlt, strip);
}
@@ -2107,7 +2107,7 @@ void do_versions_ipos_to_animato(Main *main)
bAction *new_act;
/* add a new action for this, and convert all data into that action */
- new_act = add_empty_action(main, id->name + 2);
+ new_act = BKE_action_add(main, id->name + 2);
ipo_to_animato(NULL, ipo, NULL, NULL, NULL, NULL, &new_act->curves, &drivers);
new_act->idroot = ipo->blocktype;
}
diff --git a/source/blender/blenkernel/intern/key.c b/source/blender/blenkernel/intern/key.c
index 8a7c1dd2833..fd42556067e 100644
--- a/source/blender/blenkernel/intern/key.c
+++ b/source/blender/blenkernel/intern/key.c
@@ -107,7 +107,7 @@ Key *BKE_key_add(ID *id) /* common function */
Key *key;
char *el;
- key = BKE_libblock_alloc(G.main, ID_KE, "Key");
+ key = BKE_libblock_alloc(G.main, ID_KE, "Key", 0);
key->type = KEY_NORMAL;
key->from = id;
@@ -146,36 +146,48 @@ Key *BKE_key_add(ID *id) /* common function */
key->elemsize = 16;
break;
+
+ default:
+ break;
}
return key;
}
-Key *BKE_key_copy(Main *bmain, Key *key)
+/**
+ * Only copy internal data of ShapeKey ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_key_copy_data(Main *UNUSED(bmain), Key *key_dst, const Key *key_src, const int UNUSED(flag))
{
- Key *keyn;
- KeyBlock *kbn, *kb;
-
- keyn = BKE_libblock_copy(bmain, &key->id);
-
- BLI_duplicatelist(&keyn->block, &key->block);
-
- kb = key->block.first;
- kbn = keyn->block.first;
- while (kbn) {
-
- if (kbn->data) kbn->data = MEM_dupallocN(kbn->data);
- if (kb == key->refkey) keyn->refkey = kbn;
-
- kbn = kbn->next;
- kb = kb->next;
- }
+ BLI_duplicatelist(&key_dst->block, &key_src->block);
- BKE_id_copy_ensure_local(bmain, &key->id, &keyn->id);
+ KeyBlock *kb_dst, *kb_src;
+ for (kb_src = key_src->block.first, kb_dst = key_dst->block.first;
+ kb_dst;
+ kb_src = kb_src->next, kb_dst = kb_dst->next)
+ {
+ if (kb_dst->data) {
+ kb_dst->data = MEM_dupallocN(kb_dst->data);
+ }
+ if (kb_src == key_src->refkey) {
+ key_dst->refkey = kb_dst;
+ }
+ }
+}
- return keyn;
+Key *BKE_key_copy(Main *bmain, const Key *key)
+{
+ Key *key_copy;
+ BKE_id_copy_ex(bmain, &key->id, (ID **)&key_copy, 0, false);
+ return key_copy;
}
+/* XXX TODO get rid of this! */
Key *BKE_key_copy_nolib(Key *key)
{
Key *keyn;
@@ -1397,6 +1409,8 @@ Key **BKE_key_from_id_p(ID *id)
Lattice *lt = (Lattice *)id;
return &lt->key;
}
+ default:
+ break;
}
return NULL;
diff --git a/source/blender/blenkernel/intern/lamp.c b/source/blender/blenkernel/intern/lamp.c
index 69a2067f4e6..2714c4f43a1 100644
--- a/source/blender/blenkernel/intern/lamp.c
+++ b/source/blender/blenkernel/intern/lamp.c
@@ -47,7 +47,6 @@
#include "BKE_animsys.h"
#include "BKE_colortools.h"
#include "BKE_icons.h"
-#include "BKE_global.h"
#include "BKE_lamp.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
@@ -109,42 +108,62 @@ Lamp *BKE_lamp_add(Main *bmain, const char *name)
{
Lamp *la;
- la = BKE_libblock_alloc(bmain, ID_LA, name);
+ la = BKE_libblock_alloc(bmain, ID_LA, name, 0);
BKE_lamp_init(la);
return la;
}
-Lamp *BKE_lamp_copy(Main *bmain, Lamp *la)
+/**
+ * Only copy internal data of Lamp ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_lamp_copy_data(Main *bmain, Lamp *la_dst, const Lamp *la_src, const int flag)
{
- Lamp *lan;
- int a;
-
- lan = BKE_libblock_copy(bmain, &la->id);
-
- for (a = 0; a < MAX_MTEX; a++) {
- if (lan->mtex[a]) {
- lan->mtex[a] = MEM_mallocN(sizeof(MTex), "copylamptex");
- memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
- id_us_plus((ID *)lan->mtex[a]->tex);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (la_dst->mtex[a]) {
+ la_dst->mtex[a] = MEM_mallocN(sizeof(*la_dst->mtex[a]), __func__);
+ *la_dst->mtex[a] = *la_src->mtex[a];
}
}
-
- lan->curfalloff = curvemapping_copy(la->curfalloff);
- if (la->nodetree)
- lan->nodetree = ntreeCopyTree(bmain, la->nodetree);
+ la_dst->curfalloff = curvemapping_copy(la_src->curfalloff);
- BKE_previewimg_id_copy(&lan->id, &la->id);
+ if (la_src->nodetree) {
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)la_src->nodetree, (ID **)&la_dst->nodetree, flag, false);
+ }
- BKE_id_copy_ensure_local(bmain, &la->id, &lan->id);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&la_dst->id, &la_src->id);
+ }
+ else {
+ la_dst->preview = NULL;
+ }
+}
- return lan;
+Lamp *BKE_lamp_copy(Main *bmain, const Lamp *la)
+{
+ Lamp *la_copy;
+ BKE_id_copy_ex(bmain, &la->id, (ID **)&la_copy, 0, false);
+ return la_copy;
}
-Lamp *localize_lamp(Lamp *la)
+Lamp *BKE_lamp_localize(Lamp *la)
{
+ /* TODO replace with something like
+ * Lamp *la_copy;
+ * BKE_id_copy_ex(bmain, &la->id, (ID **)&la_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false);
+ * return la_copy;
+ *
+ * ... Once f*** nodes are fully converted to that too :( */
+
Lamp *lan;
int a;
@@ -152,7 +171,7 @@ Lamp *localize_lamp(Lamp *la)
for (a = 0; a < MAX_MTEX; a++) {
if (lan->mtex[a]) {
- lan->mtex[a] = MEM_mallocN(sizeof(MTex), "localize_lamp");
+ lan->mtex[a] = MEM_mallocN(sizeof(MTex), __func__);
memcpy(lan->mtex[a], la->mtex[a], sizeof(MTex));
}
}
diff --git a/source/blender/blenkernel/intern/lattice.c b/source/blender/blenkernel/intern/lattice.c
index b0671f33094..4b9748133d7 100644
--- a/source/blender/blenkernel/intern/lattice.c
+++ b/source/blender/blenkernel/intern/lattice.c
@@ -55,7 +55,6 @@
#include "BKE_curve.h"
#include "BKE_depsgraph.h"
#include "BKE_displist.h"
-#include "BKE_global.h"
#include "BKE_key.h"
#include "BKE_lattice.h"
#include "BKE_library.h"
@@ -67,7 +66,7 @@
#include "BKE_deform.h"
-/* Workaround for cyclic depenndnecy with curves.
+/* Workaround for cyclic dependency with curves.
* In such case curve_cache might not be ready yet,
*/
#define CYCLIC_DEPENDENCY_WORKAROUND
@@ -270,39 +269,46 @@ Lattice *BKE_lattice_add(Main *bmain, const char *name)
{
Lattice *lt;
- lt = BKE_libblock_alloc(bmain, ID_LT, name);
+ lt = BKE_libblock_alloc(bmain, ID_LT, name, 0);
BKE_lattice_init(lt);
return lt;
}
-Lattice *BKE_lattice_copy(Main *bmain, Lattice *lt)
+/**
+ * Only copy internal data of Lattice ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_lattice_copy_data(Main *bmain, Lattice *lt_dst, const Lattice *lt_src, const int flag)
{
- Lattice *ltn;
+ lt_dst->def = MEM_dupallocN(lt_src->def);
- ltn = BKE_libblock_copy(bmain, &lt->id);
- ltn->def = MEM_dupallocN(lt->def);
-
- if (lt->key) {
- ltn->key = BKE_key_copy(bmain, ltn->key);
- ltn->key->from = (ID *)ltn;
- }
-
- if (lt->dvert) {
- int tot = lt->pntsu * lt->pntsv * lt->pntsw;
- ltn->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
- BKE_defvert_array_copy(ltn->dvert, lt->dvert, tot);
+ if (lt_src->key) {
+ BKE_id_copy_ex(bmain, &lt_src->key->id, (ID **)&lt_dst->key, flag, false);
}
- ltn->editlatt = NULL;
+ if (lt_src->dvert) {
+ int tot = lt_src->pntsu * lt_src->pntsv * lt_src->pntsw;
+ lt_dst->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
+ BKE_defvert_array_copy(lt_dst->dvert, lt_src->dvert, tot);
+ }
- BKE_id_copy_ensure_local(bmain, &lt->id, &ltn->id);
+ lt_dst->editlatt = NULL;
+}
- return ltn;
+Lattice *BKE_lattice_copy(Main *bmain, const Lattice *lt)
+{
+ Lattice *lt_copy;
+ BKE_id_copy_ex(bmain, &lt->id, (ID **)&lt_copy, 0, false);
+ return lt_copy;
}
-/** Free (or release) any data used by this lattice (does not free the lattice itself). */
+ /** Free (or release) any data used by this lattice (does not free the lattice itself). */
void BKE_lattice_free(Lattice *lt)
{
BKE_animdata_free(&lt->id, false);
diff --git a/source/blender/blenkernel/intern/library.c b/source/blender/blenkernel/intern/library.c
index 6b4b492b212..292f37b5ce9 100644
--- a/source/blender/blenkernel/intern/library.c
+++ b/source/blender/blenkernel/intern/library.c
@@ -133,6 +133,12 @@
#include "atomic_ops.h"
+//#define DEBUG_TIME
+
+#ifdef DEBUG_TIME
+# include "PIL_time_utildefines.h"
+#endif
+
/* GS reads the memory pointed at in a specific ordering.
* only use this definition, makes little and big endian systems
* work fine, in conjunction with MAKE_ID */
@@ -156,7 +162,7 @@ void BKE_id_lib_local_paths(Main *bmain, Library *lib, ID *id)
void id_lib_extern(ID *id)
{
- if (id && ID_IS_LINKED_DATABLOCK(id)) {
+ if (id && ID_IS_LINKED(id)) {
BLI_assert(BKE_idcode_is_linkable(GS(id->name)));
if (id->tag & LIB_TAG_INDIRECT) {
id->tag -= LIB_TAG_INDIRECT;
@@ -301,9 +307,9 @@ void BKE_id_expand_local(Main *bmain, ID *id)
/**
* Ensure new (copied) ID is fully made local.
*/
-void BKE_id_copy_ensure_local(Main *bmain, ID *old_id, ID *new_id)
+void BKE_id_copy_ensure_local(Main *bmain, const ID *old_id, ID *new_id)
{
- if (ID_IS_LINKED_DATABLOCK(old_id)) {
+ if (ID_IS_LINKED(old_id)) {
BKE_id_expand_local(bmain, new_id);
BKE_id_lib_local_paths(bmain, old_id->lib, new_id);
}
@@ -322,7 +328,7 @@ void BKE_id_make_local_generic(Main *bmain, ID *id, const bool id_in_mainlist, c
* In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
*/
- if (!ID_IS_LINKED_DATABLOCK(id)) {
+ if (!ID_IS_LINKED(id)) {
return;
}
@@ -377,7 +383,6 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
switch ((ID_Type)GS(id->name)) {
case ID_SCE:
- /* Partially implemented (has no copy...). */
if (!test) BKE_scene_make_local(bmain, (Scene *)id, lib_local);
return true;
case ID_OB:
@@ -417,14 +422,12 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
if (!test) BKE_world_make_local(bmain, (World *)id, lib_local);
return true;
case ID_VF:
- /* Partially implemented (has no copy...). */
if (!test) BKE_vfont_make_local(bmain, (VFont *)id, lib_local);
return true;
case ID_TXT:
if (!test) BKE_text_make_local(bmain, (Text *)id, lib_local);
return true;
case ID_SO:
- /* Partially implemented (has no copy...). */
if (!test) BKE_sound_make_local(bmain, (bSound *)id, lib_local);
return true;
case ID_GR:
@@ -478,114 +481,203 @@ bool id_make_local(Main *bmain, ID *id, const bool test, const bool lib_local)
return false;
}
+struct IDCopyLibManagementData {
+ const ID *id_src;
+ ID *id_dst;
+ int flag;
+};
+
+/* Increases usercount as required, and remap self ID pointers. */
+static int id_copy_libmanagement_cb(void *user_data, ID *UNUSED(id_self), ID **id_pointer, int cb_flag)
+{
+ struct IDCopyLibManagementData *data = user_data;
+ ID *id = *id_pointer;
+
+ /* Remap self-references to new copied ID. */
+ if (id == data->id_src) {
+ /* We cannot use id_self here, it is not *always* id_dst (thanks to $£!+@#&/? nodetrees). */
+ id = *id_pointer = data->id_dst;
+ }
+
+ /* Increase used IDs refcount if needed and required. */
+ if ((data->flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0 && (cb_flag & IDWALK_CB_USER)) {
+ id_us_plus(id);
+ }
+
+ return IDWALK_RET_NOP;
+}
+
/**
- * Invokes the appropriate copy method for the block and returns the result in
- * newid, unless test. Returns true if the block can be copied.
+ * Generic entry point for copying a datablock (new API).
+ *
+ * \note Copy is only affecting given data-block (no ID used by copied one will be affected, besides usercount).
+ * There is only one exception, if LIB_ID_COPY_ACTIONS is defined, actions used by animdata will be duplicated.
+ *
+ * \note Usercount of new copy is always set to 1.
+ *
+ * \param bmain Main database, may be NULL only if LIB_ID_CREATE_NO_MAIN is specified.
+ * \param id Source datablock.
+ * \param r_newid Pointer to new (copied) ID pointer.
+ * \param flag Set of copy options, see DNA_ID.h enum for details (leave to zero for default, full copy).
+ * \param test If set, do not do any copy, just test whether copy is supported.
+ * \return False when copying that ID type is not supported, true otherwise.
*/
-bool id_copy(Main *bmain, ID *id, ID **newid, bool test)
+/* XXX TODO remove test thing, *all* IDs should be copyable that way! */
+bool BKE_id_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag, const bool test)
{
- if (!test) {
- *newid = NULL;
+#define LIB_ID_TYPES_NOCOPY ID_LI, ID_SCR, ID_WM, /* Not supported */ \
+ ID_IP /* Deprecated */
+
+ BLI_assert(test || (r_newid != NULL));
+ /* Early output is source is NULL. */
+ if (id == NULL) {
+ return false;
+ }
+ /* Make sure destination pointer is all good. */
+ if ((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0) {
+ if (r_newid != NULL) {
+ *r_newid = NULL;
+ }
+ }
+ else {
+ if (r_newid != NULL && *r_newid != NULL) {
+ /* Allow some garbage non-initialized memory to go in. */
+ const size_t size = BKE_libblock_get_alloc_info(GS(id->name), NULL);
+ memset(*r_newid, 0, size);
+ }
+ }
+ if (ELEM(GS(id->name), LIB_ID_TYPES_NOCOPY)) {
+ return false;
+ }
+ else if (test) {
+ return true;
}
- /* conventions:
- * - make shallow copy, only this ID block
- * - id.us of the new ID is set to 1 */
+ BKE_libblock_copy_ex(bmain, id, r_newid, flag);
+
switch ((ID_Type)GS(id->name)) {
+ case ID_SCE:
+ BKE_scene_copy_data(bmain, (Scene *)*r_newid, (Scene *)id, flag);
+ break;
case ID_OB:
- if (!test) *newid = (ID *)BKE_object_copy(bmain, (Object *)id);
- return true;
+ BKE_object_copy_data(bmain, (Object *)*r_newid, (Object *)id, flag);
+ break;
case ID_ME:
- if (!test) *newid = (ID *)BKE_mesh_copy(bmain, (Mesh *)id);
- return true;
+ BKE_mesh_copy_data(bmain, (Mesh *)*r_newid, (Mesh *)id, flag);
+ break;
case ID_CU:
- if (!test) *newid = (ID *)BKE_curve_copy(bmain, (Curve *)id);
- return true;
+ BKE_curve_copy_data(bmain, (Curve *)*r_newid, (Curve *)id, flag);
+ break;
case ID_MB:
- if (!test) *newid = (ID *)BKE_mball_copy(bmain, (MetaBall *)id);
- return true;
+ BKE_mball_copy_data(bmain, (MetaBall *)*r_newid, (MetaBall *)id, flag);
+ break;
case ID_MA:
- if (!test) *newid = (ID *)BKE_material_copy(bmain, (Material *)id);
- return true;
+ BKE_material_copy_data(bmain, (Material *)*r_newid, (Material *)id, flag);
+ break;
case ID_TE:
- if (!test) *newid = (ID *)BKE_texture_copy(bmain, (Tex *)id);
- return true;
+ BKE_texture_copy_data(bmain, (Tex *)*r_newid, (Tex *)id, flag);
+ break;
case ID_IM:
- if (!test) *newid = (ID *)BKE_image_copy(bmain, (Image *)id);
- return true;
+ BKE_image_copy_data(bmain, (Image *)*r_newid, (Image *)id, flag);
+ break;
case ID_LT:
- if (!test) *newid = (ID *)BKE_lattice_copy(bmain, (Lattice *)id);
- return true;
+ BKE_lattice_copy_data(bmain, (Lattice *)*r_newid, (Lattice *)id, flag);
+ break;
case ID_LA:
- if (!test) *newid = (ID *)BKE_lamp_copy(bmain, (Lamp *)id);
- return true;
+ BKE_lamp_copy_data(bmain, (Lamp *)*r_newid, (Lamp *)id, flag);
+ break;
case ID_SPK:
- if (!test) *newid = (ID *)BKE_speaker_copy(bmain, (Speaker *)id);
- return true;
+ BKE_speaker_copy_data(bmain, (Speaker *)*r_newid, (Speaker *)id, flag);
+ break;
case ID_CA:
- if (!test) *newid = (ID *)BKE_camera_copy(bmain, (Camera *)id);
- return true;
+ BKE_camera_copy_data(bmain, (Camera *)*r_newid, (Camera *)id, flag);
+ break;
case ID_KE:
- if (!test) *newid = (ID *)BKE_key_copy(bmain, (Key *)id);
- return true;
+ BKE_key_copy_data(bmain, (Key *)*r_newid, (Key *)id, flag);
+ break;
case ID_WO:
- if (!test) *newid = (ID *)BKE_world_copy(bmain, (World *)id);
- return true;
+ BKE_world_copy_data(bmain, (World *)*r_newid, (World *)id, flag);
+ break;
case ID_TXT:
- if (!test) *newid = (ID *)BKE_text_copy(bmain, (Text *)id);
- return true;
+ BKE_text_copy_data(bmain, (Text *)*r_newid, (Text *)id, flag);
+ break;
case ID_GR:
- if (!test) *newid = (ID *)BKE_group_copy(bmain, (Group *)id);
- return true;
+ BKE_group_copy_data(bmain, (Group *)*r_newid, (Group *)id, flag);
+ break;
case ID_AR:
- if (!test) *newid = (ID *)BKE_armature_copy(bmain, (bArmature *)id);
- return true;
+ BKE_armature_copy_data(bmain, (bArmature *)*r_newid, (bArmature *)id, flag);
+ break;
case ID_AC:
- if (!test) *newid = (ID *)BKE_action_copy(bmain, (bAction *)id);
- return true;
+ BKE_action_copy_data(bmain, (bAction *)*r_newid, (bAction *)id, flag);
+ break;
case ID_NT:
- if (!test) *newid = (ID *)ntreeCopyTree(bmain, (bNodeTree *)id);
- return true;
+ BKE_node_tree_copy_data(bmain, (bNodeTree *)*r_newid, (bNodeTree *)id, flag);
+ break;
case ID_BR:
- if (!test) *newid = (ID *)BKE_brush_copy(bmain, (Brush *)id);
- return true;
+ BKE_brush_copy_data(bmain, (Brush *)*r_newid, (Brush *)id, flag);
+ break;
case ID_PA:
- if (!test) *newid = (ID *)BKE_particlesettings_copy(bmain, (ParticleSettings *)id);
- return true;
+ BKE_particlesettings_copy_data(bmain, (ParticleSettings *)*r_newid, (ParticleSettings *)id, flag);
+ break;
case ID_GD:
- if (!test) *newid = (ID *)BKE_gpencil_data_duplicate(bmain, (bGPdata *)id, false);
- return true;
+ BKE_gpencil_copy_data(bmain, (bGPdata *)*r_newid, (bGPdata *)id, flag);
+ break;
case ID_MC:
- if (!test) *newid = (ID *)BKE_movieclip_copy(bmain, (MovieClip *)id);
- return true;
+ BKE_movieclip_copy_data(bmain, (MovieClip *)*r_newid, (MovieClip *)id, flag);
+ break;
case ID_MSK:
- if (!test) *newid = (ID *)BKE_mask_copy(bmain, (Mask *)id);
- return true;
+ BKE_mask_copy_data(bmain, (Mask *)*r_newid, (Mask *)id, flag);
+ break;
case ID_LS:
- if (!test) *newid = (ID *)BKE_linestyle_copy(bmain, (FreestyleLineStyle *)id);
- return true;
+ BKE_linestyle_copy_data(bmain, (FreestyleLineStyle *)*r_newid, (FreestyleLineStyle *)id, flag);
+ break;
case ID_PAL:
- if (!test) *newid = (ID *)BKE_palette_copy(bmain, (Palette *)id);
- return true;
+ BKE_palette_copy_data(bmain, (Palette *)*r_newid, (Palette *)id, flag);
+ break;
case ID_PC:
- if (!test) *newid = (ID *)BKE_paint_curve_copy(bmain, (PaintCurve *)id);
- return true;
+ BKE_paint_curve_copy_data(bmain, (PaintCurve *)*r_newid, (PaintCurve *)id, flag);
+ break;
case ID_CF:
- if (!test) *newid = (ID *)BKE_cachefile_copy(bmain, (CacheFile *)id);
- return true;
- case ID_SCE:
+ BKE_cachefile_copy_data(bmain, (CacheFile *)*r_newid, (CacheFile *)id, flag);
+ break;
+ case ID_SO:
+ BKE_sound_copy_data(bmain, (bSound *)*r_newid, (bSound *)id, flag);
+ break;
+ case ID_VF:
+ BKE_vfont_copy_data(bmain, (VFont *)*r_newid, (VFont *)id, flag);
+ break;
case ID_LI:
case ID_SCR:
case ID_WM:
- return false; /* can't be copied from here */
- case ID_VF:
- case ID_SO:
- return false; /* not implemented */
case ID_IP:
- return false; /* deprecated */
+ BLI_assert(0); /* Should have been rejected at start of function! */
+ break;
}
-
- return false;
+
+ /* Update ID refcount, remap pointers to self in new ID. */
+ struct IDCopyLibManagementData data = {.id_src = id, .id_dst = *r_newid, .flag = flag};
+ BKE_library_foreach_ID_link(bmain, *r_newid, id_copy_libmanagement_cb, &data, IDWALK_NOP);
+
+ /* Do not make new copy local in case we are copying outside of main...
+ * XXX TODO: is this behavior OK, or should we need own flag to control that? */
+ if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
+ BLI_assert((flag & LIB_ID_COPY_KEEP_LIB) == 0);
+ BKE_id_copy_ensure_local(bmain, id, *r_newid);
+ }
+ else {
+ (*r_newid)->lib = id->lib;
+ }
+
+ return true;
+}
+
+/**
+ * Invokes the appropriate copy method for the block and returns the result in
+ * newid, unless test. Returns true if the block can be copied.
+ */
+bool id_copy(Main *bmain, const ID *id, ID **newid, bool test)
+{
+ return BKE_id_copy_ex(bmain, id, newid, 0, test);
}
/** Does *not* set ID->newid pointer. */
@@ -617,6 +709,103 @@ bool id_single_user(bContext *C, ID *id, PointerRNA *ptr, PropertyRNA *prop)
return false;
}
+static int libblock_management_us_plus(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag)
+{
+ if (cb_flag & IDWALK_CB_USER) {
+ id_us_plus(*id_pointer);
+ }
+ if (cb_flag & IDWALK_CB_USER_ONE) {
+ id_us_ensure_real(*id_pointer);
+ }
+
+ return IDWALK_RET_NOP;
+}
+
+static int libblock_management_us_min(void *UNUSED(user_data), ID *UNUSED(id_self), ID **id_pointer, int cb_flag)
+{
+ if (cb_flag & IDWALK_CB_USER) {
+ id_us_min(*id_pointer);
+ }
+ /* We can do nothing in IDWALK_CB_USER_ONE case! */
+
+ return IDWALK_RET_NOP;
+}
+
+/** Add a 'NO_MAIN' datablock to given main (also sets usercounts of its IDs if needed). */
+void BKE_libblock_management_main_add(Main *bmain, void *idv)
+{
+ ID *id = idv;
+
+ BLI_assert(bmain != NULL);
+ if ((id->tag & LIB_TAG_NO_MAIN) == 0) {
+ return;
+ }
+
+ if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
+ /* We cannot add non-allocated ID to Main! */
+ return;
+ }
+
+ /* We cannot allow non-userrefcounting IDs in Main database! */
+ if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
+ BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
+ }
+
+ ListBase *lb = which_libbase(bmain, GS(id->name));
+ BKE_main_lock(bmain);
+ BLI_addtail(lb, id);
+ new_id(lb, id, NULL);
+ /* alphabetic insertion: is in new_id */
+ id->tag &= ~(LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT);
+ bmain->is_memfile_undo_written = false;
+ BKE_main_unlock(bmain);
+}
+
+/** Remove a datablock from given main (set it to 'NO_MAIN' status). */
+void BKE_libblock_management_main_remove(Main *bmain, void *idv)
+{
+ ID *id = idv;
+
+ BLI_assert(bmain != NULL);
+ if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
+ return;
+ }
+
+ /* For now, allow userrefcounting IDs to get out of Main - can be handy in some cases... */
+
+ ListBase *lb = which_libbase(bmain, GS(id->name));
+ BKE_main_lock(bmain);
+ BLI_remlink(lb, id);
+ id->tag |= LIB_TAG_NO_MAIN;
+ bmain->is_memfile_undo_written = false;
+ BKE_main_unlock(bmain);
+}
+
+void BKE_libblock_management_usercounts_set(Main *bmain, void *idv)
+{
+ ID *id = idv;
+
+ if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) == 0) {
+ return;
+ }
+
+ BKE_library_foreach_ID_link(bmain, id, libblock_management_us_plus, NULL, IDWALK_NOP);
+ id->tag &= ~LIB_TAG_NO_USER_REFCOUNT;
+}
+
+void BKE_libblock_management_usercounts_clear(Main *bmain, void *idv)
+{
+ ID *id = idv;
+
+ /* We do not allow IDs in Main database to not be userrefcounting. */
+ if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0 || (id->tag & LIB_TAG_NO_MAIN) != 0) {
+ return;
+ }
+
+ BKE_library_foreach_ID_link(bmain, id, libblock_management_us_min, NULL, IDWALK_NOP);
+ id->tag |= LIB_TAG_NO_USER_REFCOUNT;
+}
+
ListBase *which_libbase(Main *mainlib, short type)
{
switch ((ID_Type)type) {
@@ -772,7 +961,7 @@ void BKE_main_lib_objects_recalc_all(Main *bmain)
/* flag for full recalc */
for (ob = bmain->object.first; ob; ob = ob->id.next) {
- if (ID_IS_LINKED_DATABLOCK(ob)) {
+ if (ID_IS_LINKED(ob)) {
DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
}
}
@@ -852,118 +1041,72 @@ int set_listbasepointers(Main *main, ListBase **lb)
* **************************** */
/**
+ * Get allocation size fo a given datablock type and optionally allocation name.
+ */
+size_t BKE_libblock_get_alloc_info(short type, const char **name)
+{
+#define CASE_RETURN(id_code, type) \
+ case id_code: \
+ do { \
+ if (name != NULL) { \
+ *name = #type; \
+ } \
+ return sizeof(type); \
+ } while(0)
+
+ switch ((ID_Type)type) {
+ CASE_RETURN(ID_SCE, Scene);
+ CASE_RETURN(ID_LI, Library);
+ CASE_RETURN(ID_OB, Object);
+ CASE_RETURN(ID_ME, Mesh);
+ CASE_RETURN(ID_CU, Curve);
+ CASE_RETURN(ID_MB, MetaBall);
+ CASE_RETURN(ID_MA, Material);
+ CASE_RETURN(ID_TE, Tex);
+ CASE_RETURN(ID_IM, Image);
+ CASE_RETURN(ID_LT, Lattice);
+ CASE_RETURN(ID_LA, Lamp);
+ CASE_RETURN(ID_CA, Camera);
+ CASE_RETURN(ID_IP, Ipo);
+ CASE_RETURN(ID_KE, Key);
+ CASE_RETURN(ID_WO, World);
+ CASE_RETURN(ID_SCR, bScreen);
+ CASE_RETURN(ID_VF, VFont);
+ CASE_RETURN(ID_TXT, Text);
+ CASE_RETURN(ID_SPK, Speaker);
+ CASE_RETURN(ID_SO, bSound);
+ CASE_RETURN(ID_GR, Group);
+ CASE_RETURN(ID_AR, bArmature);
+ CASE_RETURN(ID_AC, bAction);
+ CASE_RETURN(ID_NT, bNodeTree);
+ CASE_RETURN(ID_BR, Brush);
+ CASE_RETURN(ID_PA, ParticleSettings);
+ CASE_RETURN(ID_WM, wmWindowManager);
+ CASE_RETURN(ID_GD, bGPdata);
+ CASE_RETURN(ID_MC, MovieClip);
+ CASE_RETURN(ID_MSK, Mask);
+ CASE_RETURN(ID_LS, FreestyleLineStyle);
+ CASE_RETURN(ID_PAL, Palette);
+ CASE_RETURN(ID_PC, PaintCurve);
+ CASE_RETURN(ID_CF, CacheFile);
+ }
+ return 0;
+#undef CASE_RETURN
+}
+
+/**
* Allocates and returns memory of the right size for the specified block type,
* initialized to zero.
*/
void *BKE_libblock_alloc_notest(short type)
{
- ID *id = NULL;
-
- switch ((ID_Type)type) {
- case ID_SCE:
- id = MEM_callocN(sizeof(Scene), "scene");
- break;
- case ID_LI:
- id = MEM_callocN(sizeof(Library), "library");
- break;
- case ID_OB:
- id = MEM_callocN(sizeof(Object), "object");
- break;
- case ID_ME:
- id = MEM_callocN(sizeof(Mesh), "mesh");
- break;
- case ID_CU:
- id = MEM_callocN(sizeof(Curve), "curve");
- break;
- case ID_MB:
- id = MEM_callocN(sizeof(MetaBall), "mball");
- break;
- case ID_MA:
- id = MEM_callocN(sizeof(Material), "mat");
- break;
- case ID_TE:
- id = MEM_callocN(sizeof(Tex), "tex");
- break;
- case ID_IM:
- id = MEM_callocN(sizeof(Image), "image");
- break;
- case ID_LT:
- id = MEM_callocN(sizeof(Lattice), "latt");
- break;
- case ID_LA:
- id = MEM_callocN(sizeof(Lamp), "lamp");
- break;
- case ID_CA:
- id = MEM_callocN(sizeof(Camera), "camera");
- break;
- case ID_IP:
- id = MEM_callocN(sizeof(Ipo), "ipo");
- break;
- case ID_KE:
- id = MEM_callocN(sizeof(Key), "key");
- break;
- case ID_WO:
- id = MEM_callocN(sizeof(World), "world");
- break;
- case ID_SCR:
- id = MEM_callocN(sizeof(bScreen), "screen");
- break;
- case ID_VF:
- id = MEM_callocN(sizeof(VFont), "vfont");
- break;
- case ID_TXT:
- id = MEM_callocN(sizeof(Text), "text");
- break;
- case ID_SPK:
- id = MEM_callocN(sizeof(Speaker), "speaker");
- break;
- case ID_SO:
- id = MEM_callocN(sizeof(bSound), "sound");
- break;
- case ID_GR:
- id = MEM_callocN(sizeof(Group), "group");
- break;
- case ID_AR:
- id = MEM_callocN(sizeof(bArmature), "armature");
- break;
- case ID_AC:
- id = MEM_callocN(sizeof(bAction), "action");
- break;
- case ID_NT:
- id = MEM_callocN(sizeof(bNodeTree), "nodetree");
- break;
- case ID_BR:
- id = MEM_callocN(sizeof(Brush), "brush");
- break;
- case ID_PA:
- id = MEM_callocN(sizeof(ParticleSettings), "ParticleSettings");
- break;
- case ID_WM:
- id = MEM_callocN(sizeof(wmWindowManager), "Window manager");
- break;
- case ID_GD:
- id = MEM_callocN(sizeof(bGPdata), "Grease Pencil");
- break;
- case ID_MC:
- id = MEM_callocN(sizeof(MovieClip), "Movie Clip");
- break;
- case ID_MSK:
- id = MEM_callocN(sizeof(Mask), "Mask");
- break;
- case ID_LS:
- id = MEM_callocN(sizeof(FreestyleLineStyle), "Freestyle Line Style");
- break;
- case ID_PAL:
- id = MEM_callocN(sizeof(Palette), "Palette");
- break;
- case ID_PC:
- id = MEM_callocN(sizeof(PaintCurve), "Paint Curve");
- break;
- case ID_CF:
- id = MEM_callocN(sizeof(CacheFile), "Cache File");
- break;
+ const char *name;
+ size_t size = BKE_libblock_get_alloc_info(type, &name);
+ if (size != 0) {
+ return MEM_callocN(size, name);
}
- return id;
+ BLI_assert(!"Request to allocate unknown data type");
+ return NULL;
}
/**
@@ -972,23 +1115,45 @@ void *BKE_libblock_alloc_notest(short type)
* The user count is set to 1, all other content (apart from name and links) being
* initialized to zero.
*/
-void *BKE_libblock_alloc(Main *bmain, short type, const char *name)
+void *BKE_libblock_alloc(Main *bmain, short type, const char *name, const int flag)
{
- ID *id = NULL;
- ListBase *lb = which_libbase(bmain, type);
-
- id = BKE_libblock_alloc_notest(type);
+ BLI_assert((flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
+
+ ID *id = BKE_libblock_alloc_notest(type);
+
if (id) {
- BKE_main_lock(bmain);
- BLI_addtail(lb, id);
- id->us = 1;
+ if ((flag & LIB_ID_CREATE_NO_MAIN) != 0) {
+ id->tag |= LIB_TAG_NO_MAIN;
+ }
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0) {
+ id->tag |= LIB_TAG_NO_USER_REFCOUNT;
+ }
+
id->icon_id = 0;
- *( (short *)id->name) = type;
- new_id(lb, id, name);
- /* alphabetic insertion: is in new_id */
- BKE_main_unlock(bmain);
+ *((short *)id->name) = type;
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id->us = 1;
+ }
+ if ((flag & LIB_ID_CREATE_NO_MAIN) == 0) {
+ ListBase *lb = which_libbase(bmain, type);
+
+ BKE_main_lock(bmain);
+ BLI_addtail(lb, id);
+ new_id(lb, id, name);
+ bmain->is_memfile_undo_written = false;
+ /* alphabetic insertion: is in new_id */
+ BKE_main_unlock(bmain);
+
+ /* TODO to be removed from here! */
+ if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0) {
+ DAG_id_type_tag(bmain, type);
+ }
+ }
+ else {
+ BLI_strncpy(id->name + 2, name, sizeof(id->name) - 2);
+ }
}
- DAG_id_type_tag(bmain, type);
+
return id;
}
@@ -1111,70 +1276,81 @@ void BKE_libblock_init_empty(ID *id)
/* by spec, animdata is first item after ID */
/* and, trust that BKE_animdata_from_id() will only find AnimData for valid ID-types */
-static void id_copy_animdata(ID *id, const bool do_action)
+static void id_copy_animdata(Main *bmain, ID *id, const bool do_action)
{
AnimData *adt = BKE_animdata_from_id(id);
if (adt) {
IdAdtTemplate *iat = (IdAdtTemplate *)id;
- iat->adt = BKE_animdata_copy(iat->adt, do_action); /* could be set to false, need to investigate */
+ iat->adt = BKE_animdata_copy(bmain, iat->adt, do_action); /* could be set to false, need to investigate */
}
}
-/* material nodes use this since they are not treated as libdata */
-void BKE_libblock_copy_data(ID *id, const ID *id_from, const bool do_action)
+void BKE_libblock_copy_ex(Main *bmain, const ID *id, ID **r_newid, const int flag)
{
- if (id_from->properties)
- id->properties = IDP_CopyProperty(id_from->properties);
+ ID *new_id = *r_newid;
- /* the duplicate should get a copy of the animdata */
- id_copy_animdata(id, do_action);
-}
+ /* Grrrrrrrrr... Not adding 'root' nodetrees to bmain.... grrrrrrrrrrrrrrrrrrrr! */
+ /* This is taken from original ntree copy code, might be weak actually? */
+ const bool use_nodetree_alloc_exception = ((GS(id->name) == ID_NT) && (bmain != NULL) &&
+ (BLI_findindex(&bmain->nodetree, id) < 0));
-/* used everywhere in blenkernel */
-void *BKE_libblock_copy(Main *bmain, ID *id)
-{
- ID *idn;
- size_t idn_len;
-
- idn = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2);
+ BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || bmain != NULL);
+ BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) != 0 || (flag & LIB_ID_CREATE_NO_ALLOCATE) == 0);
+ BLI_assert((flag & LIB_ID_CREATE_NO_MAIN) == 0 || (flag & LIB_ID_CREATE_NO_USER_REFCOUNT) != 0);
- assert(idn != NULL);
+ if ((flag & LIB_ID_CREATE_NO_ALLOCATE) != 0) {
+ /* r_newid already contains pointer to allocated memory. */
+ /* TODO do we want to memset(0) whole mem before filling it? */
+ BLI_strncpy(new_id->name, id->name, sizeof(new_id->name));
+ new_id->us = 0;
+ new_id->tag |= LIB_TAG_NOT_ALLOCATED | LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT;
+ /* TODO Do we want/need to copy more from ID struct itself? */
+ }
+ else {
+ new_id = BKE_libblock_alloc(bmain, GS(id->name), id->name + 2, flag | (use_nodetree_alloc_exception ? LIB_ID_CREATE_NO_MAIN : 0));
+ }
+ BLI_assert(new_id != NULL);
- idn_len = MEM_allocN_len(idn);
- if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
+ const size_t id_len = BKE_libblock_get_alloc_info(GS(new_id->name), NULL);
+ const size_t id_offset = sizeof(ID);
+ if ((int)id_len - (int)id_offset > 0) { /* signed to allow neg result */ /* XXX ????? */
const char *cp = (const char *)id;
- char *cpn = (char *)idn;
+ char *cpn = (char *)new_id;
- memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
+ memcpy(cpn + id_offset, cp + id_offset, id_len - id_offset);
}
- BKE_libblock_copy_data(idn, id, false);
-
- return idn;
+ if (id->properties) {
+ new_id->properties = IDP_CopyProperty_ex(id->properties, flag);
+ }
+
+ /* the duplicate should get a copy of the animdata */
+ BLI_assert((flag & LIB_ID_COPY_ACTIONS) == 0 || (flag & LIB_ID_CREATE_NO_MAIN) == 0);
+ id_copy_animdata(bmain, new_id, (flag & LIB_ID_COPY_ACTIONS) != 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0);
+
+ if ((flag & LIB_ID_CREATE_NO_DEG_TAG) == 0 && (flag & LIB_ID_CREATE_NO_MAIN) == 0) {
+ DAG_id_type_tag(bmain, GS(new_id->name));
+ }
+
+ *r_newid = new_id;
}
-void *BKE_libblock_copy_nolib(ID *id, const bool do_action)
+/* used everywhere in blenkernel */
+void *BKE_libblock_copy(Main *bmain, const ID *id)
{
ID *idn;
- size_t idn_len;
- idn = BKE_libblock_alloc_notest(GS(id->name));
- assert(idn != NULL);
+ BKE_libblock_copy_ex(bmain, id, &idn, 0);
- BLI_strncpy(idn->name, id->name, sizeof(idn->name));
-
- idn_len = MEM_allocN_len(idn);
- if ((int)idn_len - (int)sizeof(ID) > 0) { /* signed to allow neg result */
- const char *cp = (const char *)id;
- char *cpn = (char *)idn;
-
- memcpy(cpn + sizeof(ID), cp + sizeof(ID), idn_len - sizeof(ID));
- }
+ return idn;
+}
- idn->us = 1;
+void *BKE_libblock_copy_nolib(const ID *id, const bool do_action)
+{
+ ID *idn;
- BKE_libblock_copy_data(idn, id, do_action);
+ BKE_libblock_copy_ex(NULL, id, &idn, LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | (do_action ? LIB_ID_COPY_ACTIONS : 0));
return idn;
}
@@ -1464,7 +1640,7 @@ static ID *is_dupid(ListBase *lb, ID *id, const char *name)
for (idtest = lb->first; idtest; idtest = idtest->next) {
/* if idtest is not a lib */
- if (id != idtest && !ID_IS_LINKED_DATABLOCK(idtest)) {
+ if (id != idtest && !ID_IS_LINKED(idtest)) {
/* do not test alphabetic! */
/* optimized */
if (idtest->name[2] == name[0]) {
@@ -1529,7 +1705,7 @@ static bool check_for_dupid(ListBase *lb, ID *id, char *name)
for (idtest = lb->first; idtest; idtest = idtest->next) {
int nrtest;
if ( (id != idtest) &&
- !ID_IS_LINKED_DATABLOCK(idtest) &&
+ !ID_IS_LINKED(idtest) &&
(*name == *(idtest->name + 2)) &&
STREQLEN(name, idtest->name + 2, left_len) &&
(BLI_split_name_num(leftest, &nrtest, idtest->name + 2, '.') == left_len)
@@ -1611,13 +1787,9 @@ bool new_id(ListBase *lb, ID *id, const char *tname)
char name[MAX_ID_NAME - 2];
/* if library, don't rename */
- if (ID_IS_LINKED_DATABLOCK(id))
+ if (ID_IS_LINKED(id))
return false;
- /* if no libdata given, look up based on ID */
- if (lb == NULL)
- lb = which_libbase(G.main, GS(id->name));
-
/* if no name given, use name of current ID
* else make a copy (tname args can be const) */
if (tname == NULL)
@@ -1716,10 +1888,19 @@ static void library_make_local_copying_check(ID *id, GSet *loop_tags, MainIDRela
for (; entry != NULL; entry = entry->next) {
ID *par_id = (ID *)entry->id_pointer; /* used_to_user stores ID pointer, not pointer to ID pointer... */
- /* Shapekeys are considered 'private' to their owner ID here, and never tagged (since they cannot be linked),
- * so we have to switch effective parent to their owner. */
- if (GS(par_id->name) == ID_KE) {
- par_id = ((Key *)par_id)->from;
+ /* Our oh-so-beloved 'from' pointers... */
+ if (entry->usage_flag & IDWALK_CB_LOOPBACK) {
+ /* We totally disregard Object->proxy_from 'usage' here, this one would only generate fake positives. */
+ if (GS(par_id->name) == ID_OB) {
+ BLI_assert(((Object *)par_id)->proxy_from == (Object *)id);
+ continue;
+ }
+
+ /* Shapekeys are considered 'private' to their owner ID here, and never tagged (since they cannot be linked),
+ * so we have to switch effective parent to their owner. */
+ if (GS(par_id->name) == ID_KE) {
+ par_id = ((Key *)par_id)->from;
+ }
}
if (par_id->lib == NULL) {
@@ -1763,7 +1944,7 @@ static void library_make_local_copying_check(ID *id, GSet *loop_tags, MainIDRela
*
* Current version uses regular id_make_local callback, with advanced pre-processing step to detect all cases of
* IDs currently indirectly used, but which will be used by local data only once this function is finished.
- * This allows to avoid any uneeded duplication of IDs, and hence all time lost afterwards to remove
+ * This allows to avoid any unneeded duplication of IDs, and hence all time lost afterwards to remove
* orphaned linked data-blocks...
*/
void BKE_library_make_local(
@@ -1777,9 +1958,18 @@ void BKE_library_make_local(
LinkNode *copied_ids = NULL;
MemArena *linklist_mem = BLI_memarena_new(512 * sizeof(*todo_ids), __func__);
+ GSet *done_ids = BLI_gset_ptr_new(__func__);
+
+#ifdef DEBUG_TIME
+ TIMEIT_START(make_local);
+#endif
+
BKE_main_relations_create(bmain);
- GSet *done_ids = BLI_gset_ptr_new(__func__);
+#ifdef DEBUG_TIME
+ printf("Pre-compute current ID relations: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
/* Step 1: Detect datablocks to make local. */
for (a = set_listbasepointers(bmain, lbarray); a--; ) {
@@ -1830,12 +2020,17 @@ void BKE_library_make_local(
}
}
+#ifdef DEBUG_TIME
+ printf("Step 1: Detect datablocks to make local: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
/* Step 2: Check which datablocks we can directly make local (because they are only used by already, or future,
* local data), others will need to be duplicated. */
GSet *loop_tags = BLI_gset_ptr_new(__func__);
for (LinkNode *it = todo_ids; it; it = it->next) {
library_make_local_copying_check(it->link, loop_tags, bmain->relations, done_ids);
- BLI_assert(BLI_gset_size(loop_tags) == 0);
+ BLI_assert(BLI_gset_len(loop_tags) == 0);
}
BLI_gset_free(loop_tags, NULL);
BLI_gset_free(done_ids, NULL);
@@ -1843,6 +2038,11 @@ void BKE_library_make_local(
/* Next step will most likely add new IDs, better to get rid of this mapping now. */
BKE_main_relations_free(bmain);
+#ifdef DEBUG_TIME
+ printf("Step 2: Check which datablocks we can directly make local: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
/* Step 3: Make IDs local, either directly (quick and simple), or using generic process,
* which involves more complex checks and might instead create a local copy of original linked ID. */
for (LinkNode *it = todo_ids, *it_next; it; it = it_next) {
@@ -1863,7 +2063,7 @@ void BKE_library_make_local(
/* Special case for objects because we don't want proxy pointers to be
* cleared yet. This will happen down the road in this function.
*/
- BKE_object_make_local_ex(bmain, (Object*)id, true, false);
+ BKE_object_make_local_ex(bmain, (Object *)id, true, false);
}
else {
id_make_local(bmain, id, false, true);
@@ -1883,11 +2083,16 @@ void BKE_library_make_local(
}
}
+#ifdef DEBUG_TIME
+ printf("Step 3: Make IDs local: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
/* At this point, we are done with directly made local IDs. Now we have to handle duplicated ones, since their
* remaining linked original counterpart may not be needed anymore... */
todo_ids = NULL;
- /* Step 4: We have to remap local usages of old (linked) ID to new (local) id in a separated loop,
+ /* Step 4: We have to remap local usages of old (linked) ID to new (local) ID in a separated loop,
* as lbarray ordering is not enough to ensure us we did catch all dependencies
* (e.g. if making local a parent object before its child...). See T48907. */
/* TODO This is now the biggest step by far (in term of processing time). We may be able to gain here by
@@ -1911,6 +2116,11 @@ void BKE_library_make_local(
}
}
+#ifdef DEBUG_TIME
+ printf("Step 4: Remap local usages of old (linked) ID to new (local) ID: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
/* Note: Keeping both version of the code (old one being safer, since it still has checks against unused IDs)
* for now, we can remove old one once it has been tested for some time in master... */
#if 1
@@ -1940,8 +2150,8 @@ void BKE_library_make_local(
* was not used locally would be a nasty bug! */
if (is_local || is_lib) {
printf("Warning, made-local proxy object %s will loose its link to %s, "
- "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
- id->newid->name, ob->proxy->id.name, is_local, is_lib);
+ "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
+ id->newid->name, ob->proxy->id.name, is_local, is_lib);
}
else {
/* we can switch the proxy'ing from the linked-in to the made-local proxy.
@@ -1955,6 +2165,12 @@ void BKE_library_make_local(
}
}
}
+
+#ifdef DEBUG_TIME
+ printf("Step 5: Proxy 'remapping' hack: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
#else
LinkNode *linked_loop_candidates = NULL;
@@ -1991,8 +2207,8 @@ void BKE_library_make_local(
* was not used locally would be a nasty bug! */
else if (is_local || is_lib) {
printf("Warning, made-local proxy object %s will loose its link to %s, "
- "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
- id->newid->name, ob->proxy->id.name, is_local, is_lib);
+ "because the linked-in proxy is referenced (is_local=%i, is_lib=%i).\n",
+ id->newid->name, ob->proxy->id.name, is_local, is_lib);
}
else {
/* we can switch the proxy'ing from the linked-in to the made-local proxy.
@@ -2033,6 +2249,11 @@ void BKE_library_make_local(
}
}
+#ifdef DEBUG_TIME
+ printf("Step 5: Remove linked datablocks that have been copied and ended fully localized: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
/* Step 6: Try to find circle dependencies between indirectly-linked-only datablocks.
* Those are fake 'usages' that prevent their deletion. See T49775 for nice ugly case. */
BKE_library_unused_linked_data_set_tag(bmain, false);
@@ -2069,10 +2290,38 @@ void BKE_library_make_local(
it->link = NULL;
}
}
+
+#ifdef DEBUG_TIME
+ printf("Step 6: Try to find circle dependencies between indirectly-linked-only datablocks: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
+#endif
+
+#endif
+
+ /* This is probably more of a hack than something we should do here, but...
+ * Issue is, the whole copying + remapping done in complex cases above may leave pose channels of armatures
+ * in complete invalid state (more precisely, the bone pointers of the pchans - very crappy cross-datablocks
+ * relationship), se we tag it to be fully recomputed, but this does not seems to be enough in some cases,
+ * and evaluation code ends up trying to evaluate a not-yet-updated armature object's deformations.
+ * Try "make all local" in 04_01_H.lighting.blend from Agent327 without this, e.g. */
+ for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
+ if (ob->data != NULL && ob->type == OB_ARMATURE && ob->pose != NULL && ob->pose->flag & POSE_RECALC) {
+ BKE_pose_rebuild(ob, ob->data);
+ }
+ }
+
+#ifdef DEBUG_TIME
+ printf("Hack: Forcefully rebuild armature object poses: Done.\n");
+ TIMEIT_VALUE_PRINT(make_local);
#endif
BKE_main_id_clear_newpoins(bmain);
BLI_memarena_free(linklist_mem);
+
+#ifdef DEBUG_TIME
+ printf("Cleanup and finish: Done.\n");
+ TIMEIT_END(make_local);
+#endif
}
/**
@@ -2084,7 +2333,6 @@ void BLI_libblock_ensure_unique_name(Main *bmain, const char *name)
ListBase *lb;
ID *idtest;
-
lb = which_libbase(bmain, GS(name));
if (lb == NULL) return;
@@ -2143,10 +2391,10 @@ void BKE_library_filepath_set(Library *lib, const char *filepath)
void BKE_id_tag_set_atomic(ID *id, int tag)
{
- atomic_fetch_and_or_uint32((uint32_t *)&id->tag, tag);
+ atomic_fetch_and_or_int32(&id->tag, tag);
}
void BKE_id_tag_clear_atomic(ID *id, int tag)
{
- atomic_fetch_and_and_uint32((uint32_t *)&id->tag, ~tag);
+ atomic_fetch_and_and_int32(&id->tag, ~tag);
}
diff --git a/source/blender/blenkernel/intern/library_query.c b/source/blender/blenkernel/intern/library_query.c
index 9685f1f5af6..d59658a2a07 100644
--- a/source/blender/blenkernel/intern/library_query.c
+++ b/source/blender/blenkernel/intern/library_query.c
@@ -33,6 +33,7 @@
#include "DNA_actuator_types.h"
#include "DNA_anim_types.h"
+#include "DNA_armature_types.h"
#include "DNA_brush_types.h"
#include "DNA_camera_types.h"
#include "DNA_constraint_types.h"
@@ -50,7 +51,7 @@
#include "DNA_movieclip_types.h"
#include "DNA_mask_types.h"
#include "DNA_node_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_rigidbody_types.h"
#include "DNA_scene_types.h"
#include "DNA_sensor_types.h"
@@ -70,10 +71,12 @@
#include "BKE_animsys.h"
#include "BKE_constraint.h"
#include "BKE_fcurve.h"
+#include "BKE_idprop.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_main.h"
#include "BKE_modifier.h"
+#include "BKE_node.h"
#include "BKE_particle.h"
#include "BKE_rigidbody.h"
#include "BKE_sca.h"
@@ -82,7 +85,9 @@
#define FOREACH_FINALIZE _finalize
-#define FOREACH_FINALIZE_VOID FOREACH_FINALIZE: (void)0
+#define FOREACH_FINALIZE_VOID \
+ if (0) { goto FOREACH_FINALIZE; } \
+ FOREACH_FINALIZE: ((void)0)
#define FOREACH_CALLBACK_INVOKE_ID_PP(_data, id_pp, _cb_flag) \
CHECK_TYPE(id_pp, ID **); \
@@ -140,6 +145,37 @@ typedef struct LibraryForeachIDData {
BLI_LINKSTACK_DECLARE(ids_todo, ID *);
} LibraryForeachIDData;
+static void library_foreach_idproperty_ID_link(LibraryForeachIDData *data, IDProperty *prop, int flag)
+{
+ if (!prop)
+ return;
+
+ switch (prop->type) {
+ case IDP_GROUP:
+ {
+ for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
+ library_foreach_idproperty_ID_link(data, loop, flag);
+ }
+ break;
+ }
+ case IDP_IDPARRAY:
+ {
+ IDProperty *loop = IDP_Array(prop);
+ for (int i = 0; i < prop->len; i++) {
+ library_foreach_idproperty_ID_link(data, &loop[i], flag);
+ }
+ break;
+ }
+ case IDP_ID:
+ FOREACH_CALLBACK_INVOKE_ID(data, prop->data.pointer, flag);
+ break;
+ default:
+ break; /* Nothing to do here with other types of IDProperties... */
+ }
+
+ FOREACH_FINALIZE_VOID;
+}
+
static void library_foreach_rigidbodyworldSceneLooper(
struct RigidBodyWorld *UNUSED(rbw), ID **id_pointer, void *user_data, int cb_flag)
{
@@ -265,6 +301,17 @@ static void library_foreach_paint(LibraryForeachIDData *data, Paint *paint)
FOREACH_FINALIZE_VOID;
}
+static void library_foreach_bone(LibraryForeachIDData *data, Bone *bone)
+{
+ library_foreach_idproperty_ID_link(data, bone->prop, IDWALK_CB_USER);
+
+ for (Bone *curbone = bone->childbase.first; curbone; curbone = curbone->next) {
+ library_foreach_bone(data, curbone);
+ }
+
+ FOREACH_FINALIZE_VOID;
+}
+
static void library_foreach_ID_as_subdata_link(
ID **id_pp, LibraryIDLinkCallback callback, void *user_data, int flag, LibraryForeachIDData *data)
{
@@ -323,12 +370,12 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
for (; id != NULL; id = (flag & IDWALK_RECURSE) ? BLI_LINKSTACK_POP(data.ids_todo) : NULL) {
data.self_id = id;
- data.cb_flag = ID_IS_LINKED_DATABLOCK(id) ? IDWALK_CB_INDIRECT_USAGE : 0;
+ data.cb_flag = ID_IS_LINKED(id) ? IDWALK_CB_INDIRECT_USAGE : 0;
if (bmain != NULL && bmain->relations != NULL && (flag & IDWALK_READONLY)) {
/* Note that this is minor optimization, even in worst cases (like id being an object with lots of
* drivers and constraints and modifiers, or material etc. with huge node tree),
- * but we might as well use it (Main->relations is always assumed valid, it's responsability of code
+ * but we might as well use it (Main->relations is always assumed valid, it's responsibility of code
* creating it to free it, especially if/when it starts modifying Main database). */
MainIDRelationsEntry *entry = BLI_ghash_lookup(bmain->relations->id_user_to_used, id);
for (; entry != NULL; entry = entry->next) {
@@ -337,6 +384,8 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
continue;
}
+ library_foreach_idproperty_ID_link(&data, id->properties, IDWALK_CB_USER);
+
AnimData *adt = BKE_animdata_from_id(id);
if (adt) {
library_foreach_animationData(&data, adt);
@@ -402,6 +451,7 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
CALLBACK_INVOKE(seq->clip, IDWALK_CB_USER);
CALLBACK_INVOKE(seq->mask, IDWALK_CB_USER);
CALLBACK_INVOKE(seq->sound, IDWALK_CB_USER);
+ library_foreach_idproperty_ID_link(&data, seq->prop, IDWALK_CB_USER);
for (SequenceModifierData *smd = seq->modifiers.first; smd; smd = smd->next) {
CALLBACK_INVOKE(smd->mask_id, IDWALK_CB_USER);
}
@@ -462,7 +512,8 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
/* Object is special, proxies make things hard... */
const int data_cb_flag = data.cb_flag;
- const int proxy_cb_flag = (object->proxy || object->proxy_group) ? IDWALK_CB_INDIRECT_USAGE : 0;
+ const int proxy_cb_flag = ((data.flag & IDWALK_NO_INDIRECT_PROXY_DATA_USAGE) == 0 && (object->proxy || object->proxy_group)) ?
+ IDWALK_CB_INDIRECT_USAGE : 0;
/* object data special case */
data.cb_flag |= proxy_cb_flag;
@@ -488,9 +539,9 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
* Since this field is set/owned by 'user' of this ID (and not ID itself), it is only indirect usage
* if proxy object is linked... Twisted. */
if (object->proxy_from) {
- data.cb_flag = ID_IS_LINKED_DATABLOCK(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0;
+ data.cb_flag = ID_IS_LINKED(object->proxy_from) ? IDWALK_CB_INDIRECT_USAGE : 0;
}
- CALLBACK_INVOKE(object->proxy_from, IDWALK_CB_NOP);
+ CALLBACK_INVOKE(object->proxy_from, IDWALK_CB_LOOPBACK);
data.cb_flag = data_cb_flag;
CALLBACK_INVOKE(object->poselib, IDWALK_CB_USER);
@@ -515,6 +566,7 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
data.cb_flag |= proxy_cb_flag;
for (pchan = object->pose->chanbase.first; pchan; pchan = pchan->next) {
+ library_foreach_idproperty_ID_link(&data, pchan->prop, IDWALK_CB_USER);
CALLBACK_INVOKE(pchan->custom, IDWALK_CB_USER);
BKE_constraints_id_loop(&pchan->constraints, library_foreach_constraintObjectLooper, &data);
}
@@ -554,6 +606,16 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
break;
}
+ case ID_AR:
+ {
+ bArmature *arm = (bArmature *)id;
+
+ for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
+ library_foreach_bone(&data, bone);
+ }
+ break;
+ }
+
case ID_ME:
{
Mesh *mesh = (Mesh *) id;
@@ -629,6 +691,9 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
library_foreach_ID_as_subdata_link((ID **)&material->nodetree, callback, user_data, flag, &data);
}
CALLBACK_INVOKE(material->group, IDWALK_CB_USER);
+ if (material->texpaintslot != NULL) {
+ CALLBACK_INVOKE(material->texpaintslot->ima, IDWALK_CB_NOP);
+ }
break;
}
@@ -684,12 +749,8 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
case ID_KE:
{
- /* XXX Only ID pointer from shapekeys is the 'from' one, which is not actually ID usage.
- * Maybe we should even nuke it from here, not 100% sure yet...
- * (see also foreach_libblock_id_users_callback).
- */
Key *key = (Key *) id;
- CALLBACK_INVOKE_ID(key->from, IDWALK_CB_NOP);
+ CALLBACK_INVOKE_ID(key->from, IDWALK_CB_LOOPBACK);
break;
}
@@ -736,9 +797,27 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
{
bNodeTree *ntree = (bNodeTree *) id;
bNode *node;
+ bNodeSocket *sock;
+
CALLBACK_INVOKE(ntree->gpd, IDWALK_CB_USER);
+
for (node = ntree->nodes.first; node; node = node->next) {
CALLBACK_INVOKE_ID(node->id, IDWALK_CB_USER);
+
+ library_foreach_idproperty_ID_link(&data, node->prop, IDWALK_CB_USER);
+ for (sock = node->inputs.first; sock; sock = sock->next) {
+ library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
+ }
+ for (sock = node->outputs.first; sock; sock = sock->next) {
+ library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
+ }
+ }
+
+ for (sock = ntree->inputs.first; sock; sock = sock->next) {
+ library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
+ }
+ for (sock = ntree->outputs.first; sock; sock = sock->next) {
+ library_foreach_idproperty_ID_link(&data, sock->prop, IDWALK_CB_USER);
}
break;
}
@@ -892,14 +971,21 @@ void BKE_library_foreach_ID_link(Main *bmain, ID *id, LibraryIDLinkCallback call
}
break;
}
+ case ID_GD:
+ {
+ bGPdata *gpencil = (bGPdata *) id;
+
+ for (bGPDlayer *gp_layer = gpencil->layers.first; gp_layer; gp_layer = gp_layer->next) {
+ CALLBACK_INVOKE(gp_layer->parent, IDWALK_CB_NOP);
+ }
+ break;
+ }
/* Nothing needed for those... */
case ID_IM:
case ID_VF:
case ID_TXT:
case ID_SO:
- case ID_AR:
- case ID_GD:
case ID_WM:
case ID_PAL:
case ID_PC:
@@ -948,9 +1034,25 @@ void BKE_library_update_ID_link_user(ID *id_dst, ID *id_src, const int cb_flag)
*/
/* XXX This has to be fully rethink, basing check on ID type is not really working anymore (and even worth once
* IDProps will support ID pointers), we'll have to do some quick checks on IDs themselves... */
-bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id_type_used)
+bool BKE_library_id_can_use_idtype(ID *id_owner, const short id_type_used)
{
- if (id_type_can_have_animdata(id_type_owner)) {
+ /* any type of ID can be used in custom props. */
+ if (id_owner->properties) {
+ return true;
+ }
+
+ const short id_type_owner = GS(id_owner->name);
+
+ /* IDProps of armature bones and nodes, and bNode->id can use virtually any type of ID. */
+ if (ELEM(id_type_owner, ID_NT, ID_AR)) {
+ return true;
+ }
+
+ if (ntreeFromID(id_owner)) {
+ return true;
+ }
+
+ if (BKE_animdata_from_id(id_owner)) {
return true; /* AnimationData can use virtually any kind of datablocks, through drivers especially. */
}
@@ -959,8 +1061,7 @@ bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id
return ELEM(id_type_used, ID_LI);
case ID_SCE:
return (ELEM(id_type_used, ID_OB, ID_WO, ID_SCE, ID_MC, ID_MA, ID_GR, ID_TXT,
- ID_LS, ID_MSK, ID_SO, ID_GD, ID_BR, ID_PAL, ID_IM, ID_NT) ||
- BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ ID_LS, ID_MSK, ID_SO, ID_GD, ID_BR, ID_PAL, ID_IM, ID_NT));
case ID_OB:
/* Could be the following, but simpler to just always say 'yes' here. */
#if 0
@@ -971,19 +1072,19 @@ bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id
return true;
#endif
case ID_ME:
- return ELEM(id_type_used, ID_ME, ID_KE, ID_MA);
+ return ELEM(id_type_used, ID_ME, ID_KE, ID_MA, ID_IM);
case ID_CU:
return ELEM(id_type_used, ID_OB, ID_KE, ID_MA, ID_VF);
case ID_MB:
return ELEM(id_type_used, ID_MA);
case ID_MA:
- return (ELEM(id_type_used, ID_TE, ID_GR) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ return (ELEM(id_type_used, ID_TE, ID_GR));
case ID_TE:
- return (ELEM(id_type_used, ID_IM, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ return (ELEM(id_type_used, ID_IM, ID_OB));
case ID_LT:
return ELEM(id_type_used, ID_KE);
case ID_LA:
- return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ return (ELEM(id_type_used, ID_TE));
case ID_CA:
return ELEM(id_type_used, ID_OB);
case ID_KE:
@@ -991,7 +1092,7 @@ bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id
case ID_SCR:
return ELEM(id_type_used, ID_SCE);
case ID_WO:
- return (ELEM(id_type_used, ID_TE) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ return (ELEM(id_type_used, ID_TE));
case ID_SPK:
return ELEM(id_type_used, ID_SO);
case ID_GR:
@@ -1012,7 +1113,7 @@ bool BKE_library_idtype_can_use_idtype(const short id_type_owner, const short id
case ID_MSK:
return ELEM(id_type_used, ID_MC); /* WARNING! mask->parent.id, not typed. */
case ID_LS:
- return (ELEM(id_type_used, ID_TE, ID_OB) || BKE_library_idtype_can_use_idtype(ID_NT, id_type_used));
+ return (ELEM(id_type_used, ID_TE, ID_OB));
case ID_IM:
case ID_VF:
case ID_TXT:
@@ -1045,20 +1146,15 @@ typedef struct IDUsersIter {
int count_direct, count_indirect; /* Set by callback. */
} IDUsersIter;
-static int foreach_libblock_id_users_callback(void *user_data, ID *self_id, ID **id_p, int cb_flag)
+static int foreach_libblock_id_users_callback(void *user_data, ID *UNUSED(self_id), ID **id_p, int cb_flag)
{
IDUsersIter *iter = user_data;
if (*id_p) {
- /* XXX This is actually some kind of hack...
- * Issue is, shapekeys' 'from' ID pointer is not actually ID usage.
- * Maybe we should even nuke it from BKE_library_foreach_ID_link, not 100% sure yet...
+ /* 'Loopback' ID pointers (the ugly 'from' ones, Object->proxy_from and Key->from).
+ * Those are not actually ID usage, we can ignore them here.
*/
- if ((GS(self_id->name) == ID_KE) && (((Key *)self_id)->from == *id_p)) {
- return IDWALK_RET_NOP;
- }
- /* XXX another hack, for similar reasons as above one. */
- if ((GS(self_id->name) == ID_OB) && (((Object *)self_id)->proxy_from == (Object *)*id_p)) {
+ if (cb_flag & IDWALK_CB_LOOPBACK) {
return IDWALK_RET_NOP;
}
@@ -1118,7 +1214,7 @@ static bool library_ID_is_used(Main *bmain, void *idv, const bool check_linked)
while (i-- && !is_defined) {
ID *id_curr = lb_array[i]->first;
- if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
+ if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
continue;
}
@@ -1170,7 +1266,7 @@ void BKE_library_ID_test_usages(Main *bmain, void *idv, bool *is_used_local, boo
while (i-- && !is_defined) {
ID *id_curr = lb_array[i]->first;
- if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(id->name))) {
+ if (!id_curr || !BKE_library_id_can_use_idtype(id_curr, GS(id->name))) {
continue;
}
diff --git a/source/blender/blenkernel/intern/library_remap.c b/source/blender/blenkernel/intern/library_remap.c
index a408b498f18..31dc46a55f0 100644
--- a/source/blender/blenkernel/intern/library_remap.c
+++ b/source/blender/blenkernel/intern/library_remap.c
@@ -179,27 +179,38 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id
* on the other hand since they get reset to lib data on file open/reload it is indirect too...
* Edit Mode is also a 'skip direct' case. */
const bool is_obj = (GS(id->name) == ID_OB);
+ const bool is_obj_proxy = (is_obj && (((Object *)id)->proxy || ((Object *)id)->proxy_group));
const bool is_obj_editmode = (is_obj && BKE_object_is_in_editmode((Object *)id));
const bool is_never_null = ((cb_flag & IDWALK_CB_NEVER_NULL) && (new_id == NULL) &&
(id_remap_data->flag & ID_REMAP_FORCE_NEVER_NULL_USAGE) == 0);
const bool skip_never_null = (id_remap_data->flag & ID_REMAP_SKIP_NEVER_NULL_USAGE) != 0;
#ifdef DEBUG_PRINT
- printf("In %s: Remapping %s (%p) to %s (%p) (skip_indirect: %d)\n",
- id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, skip_indirect);
+ printf("In %s: Remapping %s (%p) to %s (%p) (is_indirect: %d, skip_indirect: %d)\n",
+ id->name, old_id->name, old_id, new_id ? new_id->name : "<NONE>", new_id, is_indirect, skip_indirect);
#endif
if ((id_remap_data->flag & ID_REMAP_FLAG_NEVER_NULL_USAGE) && (cb_flag & IDWALK_CB_NEVER_NULL)) {
id->tag |= LIB_TAG_DOIT;
}
- /* Special hack in case it's Object->data and we are in edit mode (skipped_direct too). */
+ /* Special hack in case it's Object->data and we are in edit mode, and new_id is not NULL
+ * (otherwise, we follow common NEVER_NULL flags).
+ * (skipped_indirect too). */
if ((is_never_null && skip_never_null) ||
- (is_obj_editmode && (((Object *)id)->data == *id_p)) ||
+ (is_obj_editmode && (((Object *)id)->data == *id_p) && new_id != NULL) ||
(skip_indirect && is_indirect))
{
if (is_indirect) {
id_remap_data->skipped_indirect++;
+ if (is_obj) {
+ Object *ob = (Object *)id;
+ if (ob->data == *id_p && ob->proxy != NULL) {
+ /* And another 'Proudly brought to you by Proxy Hell' hack!
+ * This will allow us to avoid clearing 'LIB_EXTERN' flag of obdata of proxies... */
+ id_remap_data->skipped_direct++;
+ }
+ }
}
else if (is_never_null || is_obj_editmode) {
id_remap_data->skipped_direct++;
@@ -231,7 +242,7 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id
/* We cannot affect old_id->us directly, LIB_TAG_EXTRAUSER(_SET) are assumed to be set as needed,
* that extra user is processed in final handling... */
}
- if (!is_indirect) {
+ if (!is_indirect || is_obj_proxy) {
id_remap_data->status |= ID_REMAP_IS_LINKED_DIRECT;
}
}
@@ -240,7 +251,7 @@ static int foreach_libblock_remap_callback(void *user_data, ID *id_self, ID **id
return IDWALK_RET_NOP;
}
-/* Some reamapping unfortunately require extra and/or specific handling, tackle those here. */
+/* Some remapping unfortunately require extra and/or specific handling, tackle those here. */
static void libblock_remap_data_preprocess_scene_base_unlink(
IDRemap *r_id_remap_data, Scene *sce, Base *base, const bool skip_indirect, const bool is_indirect)
{
@@ -317,7 +328,7 @@ static void libblock_remap_data_preprocess(IDRemap *r_id_remap_data)
}
}
-static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain, Object *old_ob, Object *new_ob)
+static void libblock_remap_data_postprocess_object_update(Main *bmain, Object *old_ob, Object *new_ob)
{
if (old_ob->flag & OB_FROMGROUP) {
/* Note that for Scene's BaseObject->flag, either we:
@@ -336,6 +347,13 @@ static void libblock_remap_data_postprocess_object_fromgroup_update(Main *bmain,
new_ob->flag |= OB_FROMGROUP;
}
}
+ if (old_ob->type == OB_MBALL) {
+ for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
+ if (ob->type == OB_MBALL && BKE_mball_is_basis_for(ob, old_ob)) {
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
+ }
+ }
}
static void libblock_remap_data_postprocess_group_scene_unlink(Main *UNUSED(bmain), Scene *sce, ID *old_id)
@@ -418,6 +436,7 @@ ATTR_NONNULL(1) static void libblock_remap_data(
IDRemap id_remap_data;
ListBase *lb_array[MAX_LIBARRAY];
int i;
+ const int foreach_id_flags = (remap_flags & ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE) != 0 ? IDWALK_NO_INDIRECT_PROXY_DATA_USAGE : IDWALK_NOP;
if (r_id_remap_data == NULL) {
r_id_remap_data = &id_remap_data;
@@ -438,7 +457,7 @@ ATTR_NONNULL(1) static void libblock_remap_data(
#endif
r_id_remap_data->id = id;
libblock_remap_data_preprocess(r_id_remap_data);
- BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
+ BKE_library_foreach_ID_link(NULL, id, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
}
else {
i = set_listbasepointers(bmain, lb_array);
@@ -447,20 +466,16 @@ ATTR_NONNULL(1) static void libblock_remap_data(
* objects actually using given old_id... sounds rather unlikely currently, though, so this will do for now. */
while (i--) {
- ID *id_curr = lb_array[i]->first;
-
- if (!id_curr || !BKE_library_idtype_can_use_idtype(GS(id_curr->name), GS(old_id->name))) {
- continue;
- }
-
- for (; id_curr; id_curr = id_curr->next) {
- /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
- * the user count handling...
- * XXX No more true (except for debug usage of those skipping counters). */
- r_id_remap_data->id = id_curr;
- libblock_remap_data_preprocess(r_id_remap_data);
- BKE_library_foreach_ID_link(
- NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, IDWALK_NOP);
+ for (ID *id_curr = lb_array[i]->first; id_curr; id_curr = id_curr->next) {
+ if (BKE_library_id_can_use_idtype(id_curr, GS(old_id->name))) {
+ /* Note that we cannot skip indirect usages of old_id here (if requested), we still need to check it for
+ * the user count handling...
+ * XXX No more true (except for debug usage of those skipping counters). */
+ r_id_remap_data->id = id_curr;
+ libblock_remap_data_preprocess(r_id_remap_data);
+ BKE_library_foreach_ID_link(
+ NULL, id_curr, foreach_libblock_remap_callback, (void *)r_id_remap_data, foreach_id_flags);
+ }
}
}
}
@@ -529,8 +544,12 @@ void BKE_libblock_remap_locked(
id_us_clear_real(old_id);
}
- BLI_assert(old_id->us - skipped_refcounted >= 0);
- UNUSED_VARS_NDEBUG(skipped_refcounted);
+ if (old_id->us - skipped_refcounted < 0) {
+ printf("Error in remapping process from '%s' (%p) to '%s' (%p): "
+ "wrong user count in old ID after process (summing up to %d)\n",
+ old_id->name, old_id, new_id ? new_id->name : "<NULL>", new_id, old_id->us - skipped_refcounted);
+ BLI_assert(0);
+ }
if (skipped_direct == 0) {
/* old_id is assumed to not be used directly anymore... */
@@ -545,7 +564,7 @@ void BKE_libblock_remap_locked(
*/
switch (GS(old_id->name)) {
case ID_OB:
- libblock_remap_data_postprocess_object_fromgroup_update(bmain, (Object *)old_id, (Object *)new_id);
+ libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
break;
case ID_GR:
if (!new_id) { /* Only affects us in case group was unlinked. */
@@ -655,8 +674,7 @@ void BKE_libblock_relink_ex(
switch (GS(old_id->name)) {
case ID_OB:
{
- libblock_remap_data_postprocess_object_fromgroup_update(
- bmain, (Object *)old_id, (Object *)new_id);
+ libblock_remap_data_postprocess_object_update(bmain, (Object *)old_id, (Object *)new_id);
break;
}
case ID_GR:
@@ -671,7 +689,7 @@ void BKE_libblock_relink_ex(
else {
/* No choice but to check whole objects/groups. */
for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
- libblock_remap_data_postprocess_object_fromgroup_update(bmain, ob, NULL);
+ libblock_remap_data_postprocess_object_update(bmain, ob, NULL);
}
for (Group *grp = bmain->group.first; grp; grp = grp->id.next) {
libblock_remap_data_postprocess_group_scene_unlink(bmain, sce, NULL);
@@ -716,44 +734,25 @@ static int id_relink_to_newid_looper(void *UNUSED(user_data), ID *UNUSED(self_id
*/
void BKE_libblock_relink_to_newid(ID *id)
{
- if (ID_IS_LINKED_DATABLOCK(id))
+ if (ID_IS_LINKED(id))
return;
BKE_library_foreach_ID_link(NULL, id, id_relink_to_newid_looper, NULL, 0);
}
-void BKE_libblock_free_data(Main *UNUSED(bmain), ID *id)
+void BKE_libblock_free_data(ID *id, const bool do_id_user)
{
if (id->properties) {
- IDP_FreeProperty(id->properties);
+ IDP_FreeProperty_ex(id->properties, do_id_user);
MEM_freeN(id->properties);
}
+
+ /* XXX TODO remove animdata handling from each type's freeing func, and do it here, like for copy! */
}
-/**
- * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
- *
- * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
- * (only applies to main database)
- * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
- * \a id.
- */
-void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
+void BKE_libblock_free_datablock(ID *id, const int UNUSED(flag))
{
- ID *id = idv;
- short type = GS(id->name);
- ListBase *lb = which_libbase(bmain, type);
-
- DAG_id_type_tag(bmain, type);
-
-#ifdef WITH_PYTHON
- BPY_id_release(id);
-#endif
-
- if (do_id_user) {
- BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
- }
-
+ const short type = GS(id->name);
switch (type) {
case ID_SCE:
BKE_scene_free((Scene *)id);
@@ -859,6 +858,122 @@ void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const b
BKE_cachefile_free((CacheFile *)id);
break;
}
+}
+
+
+void BKE_id_free_ex(Main *bmain, void *idv, int flag, const bool use_flag_from_idtag)
+{
+ ID *id = idv;
+
+ if (use_flag_from_idtag) {
+ if ((id->tag & LIB_TAG_NO_MAIN) != 0) {
+ flag |= LIB_ID_FREE_NO_MAIN;
+ }
+ else {
+ flag &= ~LIB_ID_FREE_NO_MAIN;
+ }
+
+ if ((id->tag & LIB_TAG_NO_USER_REFCOUNT) != 0) {
+ flag |= LIB_ID_FREE_NO_USER_REFCOUNT;
+ }
+ else {
+ flag &= ~LIB_ID_FREE_NO_USER_REFCOUNT;
+ }
+
+ if ((id->tag & LIB_TAG_NOT_ALLOCATED) != 0) {
+ flag |= LIB_ID_FREE_NOT_ALLOCATED;
+ }
+ else {
+ flag &= ~LIB_ID_FREE_NOT_ALLOCATED;
+ }
+ }
+
+ BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || bmain != NULL);
+ BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NOT_ALLOCATED) == 0);
+ BLI_assert((flag & LIB_ID_FREE_NO_MAIN) != 0 || (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
+
+ const short type = GS(id->name);
+
+ if (bmain && (flag & LIB_ID_FREE_NO_DEG_TAG) == 0) {
+ DAG_id_type_tag(bmain, type);
+ }
+
+#ifdef WITH_PYTHON
+ BPY_id_release(id);
+#endif
+
+ if ((flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0) {
+ BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
+ }
+
+ BKE_libblock_free_datablock(id, flag);
+
+ /* avoid notifying on removed data */
+ if (bmain) {
+ BKE_main_lock(bmain);
+ }
+
+ if ((flag & LIB_ID_FREE_NO_UI_USER) == 0) {
+ if (free_notifier_reference_cb) {
+ free_notifier_reference_cb(id);
+ }
+
+ if (remap_editor_id_reference_cb) {
+ remap_editor_id_reference_cb(id, NULL);
+ }
+ }
+
+ if ((flag & LIB_ID_FREE_NO_MAIN) == 0) {
+ ListBase *lb = which_libbase(bmain, type);
+ BLI_remlink(lb, id);
+ }
+
+ BKE_libblock_free_data(id, (flag & LIB_ID_FREE_NO_USER_REFCOUNT) == 0);
+
+ if (bmain) {
+ BKE_main_unlock(bmain);
+ }
+
+ if ((flag & LIB_ID_FREE_NOT_ALLOCATED) == 0) {
+ MEM_freeN(id);
+ }
+}
+
+void BKE_id_free(Main *bmain, void *idv)
+{
+ BKE_id_free_ex(bmain, idv, 0, true);
+}
+
+/**
+ * used in headerbuttons.c image.c mesh.c screen.c sound.c and library.c
+ *
+ * \param do_id_user: if \a true, try to release other ID's 'references' hold by \a idv.
+ * (only applies to main database)
+ * \param do_ui_user: similar to do_id_user but makes sure UI does not hold references to
+ * \a id.
+ */
+void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const bool do_ui_user)
+{
+ ID *id = idv;
+ short type = GS(id->name);
+ ListBase *lb = which_libbase(bmain, type);
+
+ DAG_id_type_tag(bmain, type);
+
+#ifdef WITH_PYTHON
+#ifdef WITH_PYTHON_SAFETY
+ BPY_id_release(id);
+#endif
+ if (id->py_instance) {
+ BPY_DECREF_RNA_INVALIDATE(id->py_instance);
+ }
+#endif
+
+ if (do_id_user) {
+ BKE_libblock_relink_ex(bmain, id, NULL, NULL, true);
+ }
+
+ BKE_libblock_free_datablock(id, 0);
/* avoid notifying on removed data */
BKE_main_lock(bmain);
@@ -875,7 +990,7 @@ void BKE_libblock_free_ex(Main *bmain, void *idv, const bool do_id_user, const b
BLI_remlink(lb, id);
- BKE_libblock_free_data(bmain, id);
+ BKE_libblock_free_data(id, do_id_user);
BKE_main_unlock(bmain);
MEM_freeN(id);
diff --git a/source/blender/blenkernel/intern/linestyle.c b/source/blender/blenkernel/intern/linestyle.c
index 1eb909bd9f9..e00884c8a9d 100644
--- a/source/blender/blenkernel/intern/linestyle.c
+++ b/source/blender/blenkernel/intern/linestyle.c
@@ -44,13 +44,12 @@
#include "BLI_string_utils.h"
#include "BLI_utildefines.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_freestyle.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_linestyle.h"
#include "BKE_node.h"
-#include "BKE_texture.h"
#include "BKE_colortools.h"
#include "BKE_animsys.h"
@@ -119,7 +118,7 @@ FreestyleLineStyle *BKE_linestyle_new(struct Main *bmain, const char *name)
{
FreestyleLineStyle *linestyle;
- linestyle = (FreestyleLineStyle *)BKE_libblock_alloc(bmain, ID_LS, name);
+ linestyle = (FreestyleLineStyle *)BKE_libblock_alloc(bmain, ID_LS, name, 0);
BKE_linestyle_init(linestyle);
@@ -155,73 +154,57 @@ void BKE_linestyle_free(FreestyleLineStyle *linestyle)
BKE_linestyle_geometry_modifier_remove(linestyle, m);
}
-FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, FreestyleLineStyle *linestyle)
+/**
+ * Only copy internal data of Linestyle ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_linestyle_copy_data(
+ struct Main *bmain, FreestyleLineStyle *linestyle_dst, const FreestyleLineStyle *linestyle_src, const int flag)
{
- FreestyleLineStyle *new_linestyle;
- LineStyleModifier *m;
- int a;
-
- new_linestyle = BKE_linestyle_new(bmain, linestyle->id.name + 2);
- BKE_linestyle_free(new_linestyle);
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
- for (a = 0; a < MAX_MTEX; a++) {
- if (linestyle->mtex[a]) {
- new_linestyle->mtex[a] = MEM_mallocN(sizeof(MTex), "BKE_linestyle_copy");
- memcpy(new_linestyle->mtex[a], linestyle->mtex[a], sizeof(MTex));
- id_us_plus((ID *)new_linestyle->mtex[a]->tex);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (linestyle_src->mtex[a]) {
+ linestyle_dst->mtex[a] = MEM_mallocN(sizeof(*linestyle_dst->mtex[a]), __func__);
+ *linestyle_dst->mtex[a] = *linestyle_src->mtex[a];
}
}
- if (linestyle->nodetree) {
- new_linestyle->nodetree = ntreeCopyTree(bmain, linestyle->nodetree);
+
+ if (linestyle_src->nodetree) {
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)linestyle_src->nodetree, (ID **)&linestyle_dst->nodetree, flag, false);
}
- new_linestyle->r = linestyle->r;
- new_linestyle->g = linestyle->g;
- new_linestyle->b = linestyle->b;
- new_linestyle->alpha = linestyle->alpha;
- new_linestyle->thickness = linestyle->thickness;
- new_linestyle->thickness_position = linestyle->thickness_position;
- new_linestyle->thickness_ratio = linestyle->thickness_ratio;
- new_linestyle->flag = linestyle->flag;
- new_linestyle->caps = linestyle->caps;
- new_linestyle->chaining = linestyle->chaining;
- new_linestyle->rounds = linestyle->rounds;
- new_linestyle->split_length = linestyle->split_length;
- new_linestyle->min_angle = linestyle->min_angle;
- new_linestyle->max_angle = linestyle->max_angle;
- new_linestyle->min_length = linestyle->min_length;
- new_linestyle->max_length = linestyle->max_length;
- new_linestyle->chain_count = linestyle->chain_count;
- new_linestyle->split_dash1 = linestyle->split_dash1;
- new_linestyle->split_gap1 = linestyle->split_gap1;
- new_linestyle->split_dash2 = linestyle->split_dash2;
- new_linestyle->split_gap2 = linestyle->split_gap2;
- new_linestyle->split_dash3 = linestyle->split_dash3;
- new_linestyle->split_gap3 = linestyle->split_gap3;
- new_linestyle->dash1 = linestyle->dash1;
- new_linestyle->gap1 = linestyle->gap1;
- new_linestyle->dash2 = linestyle->dash2;
- new_linestyle->gap2 = linestyle->gap2;
- new_linestyle->dash3 = linestyle->dash3;
- new_linestyle->gap3 = linestyle->gap3;
- new_linestyle->panel = linestyle->panel;
- new_linestyle->sort_key = linestyle->sort_key;
- new_linestyle->integration_type = linestyle->integration_type;
- new_linestyle->texstep = linestyle->texstep;
- new_linestyle->pr_texture = linestyle->pr_texture;
- new_linestyle->use_nodes = linestyle->use_nodes;
- for (m = (LineStyleModifier *)linestyle->color_modifiers.first; m; m = m->next)
- BKE_linestyle_color_modifier_copy(new_linestyle, m);
- for (m = (LineStyleModifier *)linestyle->alpha_modifiers.first; m; m = m->next)
- BKE_linestyle_alpha_modifier_copy(new_linestyle, m);
- for (m = (LineStyleModifier *)linestyle->thickness_modifiers.first; m; m = m->next)
- BKE_linestyle_thickness_modifier_copy(new_linestyle, m);
- for (m = (LineStyleModifier *)linestyle->geometry_modifiers.first; m; m = m->next)
- BKE_linestyle_geometry_modifier_copy(new_linestyle, m);
-
- BKE_id_copy_ensure_local(bmain, &linestyle->id, &new_linestyle->id);
-
- return new_linestyle;
+ LineStyleModifier *m;
+ BLI_listbase_clear(&linestyle_dst->color_modifiers);
+ for (m = (LineStyleModifier *)linestyle_src->color_modifiers.first; m; m = m->next) {
+ BKE_linestyle_color_modifier_copy(linestyle_dst, m, flag_subdata);
+ }
+ BLI_listbase_clear(&linestyle_dst->alpha_modifiers);
+ for (m = (LineStyleModifier *)linestyle_src->alpha_modifiers.first; m; m = m->next) {
+ BKE_linestyle_alpha_modifier_copy(linestyle_dst, m, flag_subdata);
+ }
+ BLI_listbase_clear(&linestyle_dst->thickness_modifiers);
+ for (m = (LineStyleModifier *)linestyle_src->thickness_modifiers.first; m; m = m->next) {
+ BKE_linestyle_thickness_modifier_copy(linestyle_dst, m, flag_subdata);
+ }
+ BLI_listbase_clear(&linestyle_dst->geometry_modifiers);
+ for (m = (LineStyleModifier *)linestyle_src->geometry_modifiers.first; m; m = m->next) {
+ BKE_linestyle_geometry_modifier_copy(linestyle_dst, m, flag_subdata);
+ }
+}
+
+FreestyleLineStyle *BKE_linestyle_copy(struct Main *bmain, const FreestyleLineStyle *linestyle)
+{
+ FreestyleLineStyle *linestyle_copy;
+ BKE_id_copy_ex(bmain, &linestyle->id, (ID **)&linestyle_copy, 0, false);
+ return linestyle_copy;
}
void BKE_linestyle_make_local(struct Main *bmain, FreestyleLineStyle *linestyle, const bool lib_local)
@@ -232,6 +215,10 @@ void BKE_linestyle_make_local(struct Main *bmain, FreestyleLineStyle *linestyle,
FreestyleLineStyle *BKE_linestyle_active_from_scene(Scene *scene)
{
SceneRenderLayer *actsrl = BLI_findlink(&scene->r.layers, scene->r.actlay);
+ if (!actsrl) {
+ return NULL;
+ }
+
FreestyleConfig *config = &actsrl->freestyleConfig;
FreestyleLineSet *lineset = BKE_freestyle_lineset_get_active(config);
@@ -311,39 +298,39 @@ LineStyleModifier *BKE_linestyle_color_modifier_add(FreestyleLineStyle *linestyl
switch (type) {
case LS_MODIFIER_ALONG_STROKE:
- ((LineStyleColorModifier_AlongStroke *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_AlongStroke *)m)->color_ramp = BKE_colorband_add(true);
break;
case LS_MODIFIER_DISTANCE_FROM_CAMERA:
- ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_DistanceFromCamera *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_DistanceFromCamera *)m)->range_min = 0.0f;
((LineStyleColorModifier_DistanceFromCamera *)m)->range_max = 10000.0f;
break;
case LS_MODIFIER_DISTANCE_FROM_OBJECT:
((LineStyleColorModifier_DistanceFromObject *)m)->target = NULL;
- ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_DistanceFromObject *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_DistanceFromObject *)m)->range_min = 0.0f;
((LineStyleColorModifier_DistanceFromObject *)m)->range_max = 10000.0f;
break;
case LS_MODIFIER_MATERIAL:
- ((LineStyleColorModifier_Material *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_Material *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_Material *)m)->mat_attr = LS_MODIFIER_MATERIAL_LINE;
break;
case LS_MODIFIER_TANGENT:
- ((LineStyleColorModifier_Tangent *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_Tangent *)m)->color_ramp = BKE_colorband_add(true);
break;
case LS_MODIFIER_NOISE:
- ((LineStyleColorModifier_Noise *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_Noise *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_Noise *)m)->amplitude = 10.0f;
((LineStyleColorModifier_Noise *)m)->period = 10.0f;
((LineStyleColorModifier_Noise *)m)->seed = 512;
break;
case LS_MODIFIER_CREASE_ANGLE:
- ((LineStyleColorModifier_CreaseAngle *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_CreaseAngle *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_CreaseAngle *)m)->min_angle = 0.0f;
((LineStyleColorModifier_CreaseAngle *)m)->max_angle = DEG2RADF(180.0f);
break;
case LS_MODIFIER_CURVATURE_3D:
- ((LineStyleColorModifier_Curvature_3D *)m)->color_ramp = add_colorband(1);
+ ((LineStyleColorModifier_Curvature_3D *)m)->color_ramp = BKE_colorband_add(true);
((LineStyleColorModifier_Curvature_3D *)m)->min_curvature = 0.0f;
((LineStyleColorModifier_Curvature_3D *)m)->max_curvature = 0.5f;
break;
@@ -355,7 +342,8 @@ LineStyleModifier *BKE_linestyle_color_modifier_add(FreestyleLineStyle *linestyl
return m;
}
-LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m)
+LineStyleModifier *BKE_linestyle_color_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag)
{
LineStyleModifier *new_m;
@@ -388,9 +376,10 @@ LineStyleModifier *BKE_linestyle_color_modifier_copy(FreestyleLineStyle *linesty
{
LineStyleColorModifier_DistanceFromObject *p = (LineStyleColorModifier_DistanceFromObject *)m;
LineStyleColorModifier_DistanceFromObject *q = (LineStyleColorModifier_DistanceFromObject *)new_m;
- if (p->target)
- id_us_plus(&p->target->id);
q->target = p->target;
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)q->target);
+ }
q->color_ramp = MEM_dupallocN(p->color_ramp);
q->range_min = p->range_min;
q->range_max = p->range_max;
@@ -594,7 +583,8 @@ LineStyleModifier *BKE_linestyle_alpha_modifier_add(FreestyleLineStyle *linestyl
return m;
}
-LineStyleModifier *BKE_linestyle_alpha_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m)
+LineStyleModifier *BKE_linestyle_alpha_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int UNUSED(flag))
{
LineStyleModifier *new_m;
@@ -863,7 +853,8 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_add(FreestyleLineStyle *line
return m;
}
-LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m)
+LineStyleModifier *BKE_linestyle_thickness_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int flag)
{
LineStyleModifier *new_m;
@@ -901,9 +892,10 @@ LineStyleModifier *BKE_linestyle_thickness_modifier_copy(FreestyleLineStyle *lin
{
LineStyleThicknessModifier_DistanceFromObject *p = (LineStyleThicknessModifier_DistanceFromObject *)m;
LineStyleThicknessModifier_DistanceFromObject *q = (LineStyleThicknessModifier_DistanceFromObject *)new_m;
- if (p->target)
- id_us_plus(&p->target->id);
q->target = p->target;
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)q->target);
+ }
q->curve = curvemapping_copy(p->curve);
q->flags = p->flags;
q->range_min = p->range_min;
@@ -1195,7 +1187,8 @@ LineStyleModifier *BKE_linestyle_geometry_modifier_add(FreestyleLineStyle *lines
return m;
}
-LineStyleModifier *BKE_linestyle_geometry_modifier_copy(FreestyleLineStyle *linestyle, LineStyleModifier *m)
+LineStyleModifier *BKE_linestyle_geometry_modifier_copy(
+ FreestyleLineStyle *linestyle, const LineStyleModifier *m, const int UNUSED(flag))
{
LineStyleModifier *new_m;
diff --git a/source/blender/blenkernel/intern/mask.c b/source/blender/blenkernel/intern/mask.c
index 6f23b82c6df..b5742dbdbb7 100644
--- a/source/blender/blenkernel/intern/mask.c
+++ b/source/blender/blenkernel/intern/mask.c
@@ -51,7 +51,7 @@
#include "BKE_animsys.h"
#include "BKE_curve.h"
-#include "BKE_global.h"
+#include "BKE_depsgraph.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_mask.h"
@@ -192,7 +192,7 @@ void BKE_mask_layer_rename(Mask *mask, MaskLayer *masklay, char *oldname, char *
BKE_animdata_fix_paths_rename_all(&mask->id, "layers", oldname, masklay->name);
}
-MaskLayer *BKE_mask_layer_copy(MaskLayer *masklay)
+MaskLayer *BKE_mask_layer_copy(const MaskLayer *masklay)
{
MaskLayer *masklay_new;
MaskSpline *spline;
@@ -236,7 +236,7 @@ MaskLayer *BKE_mask_layer_copy(MaskLayer *masklay)
return masklay_new;
}
-void BKE_mask_layer_copy_list(ListBase *masklayers_new, ListBase *masklayers)
+void BKE_mask_layer_copy_list(ListBase *masklayers_new, const ListBase *masklayers)
{
MaskLayer *layer;
@@ -794,7 +794,7 @@ static Mask *mask_alloc(Main *bmain, const char *name)
{
Mask *mask;
- mask = BKE_libblock_alloc(bmain, ID_MSK, name);
+ mask = BKE_libblock_alloc(bmain, ID_MSK, name, 0);
id_fake_user_set(&mask->id);
@@ -817,10 +817,13 @@ Mask *BKE_mask_new(Main *bmain, const char *name)
mask->sfra = 1;
mask->efra = 100;
+ DAG_relations_tag_update(bmain);
+
return mask;
}
/* TODO(sergey): Use generic BKE_libblock_copy_nolib() instead. */
+/* TODO(bastien): Use new super cool & generic BKE_id_copy_ex() instead! */
Mask *BKE_mask_copy_nolib(Mask *mask)
{
Mask *mask_new;
@@ -840,22 +843,29 @@ Mask *BKE_mask_copy_nolib(Mask *mask)
return mask_new;
}
-Mask *BKE_mask_copy(Main *bmain, Mask *mask)
+/**
+ * Only copy internal data of Mask ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_mask_copy_data(Main *UNUSED(bmain), Mask *mask_dst, const Mask *mask_src, const int UNUSED(flag))
{
- Mask *mask_new;
-
- mask_new = BKE_libblock_copy(bmain, &mask->id);
+ BLI_listbase_clear(&mask_dst->masklayers);
- BLI_listbase_clear(&mask_new->masklayers);
-
- BKE_mask_layer_copy_list(&mask_new->masklayers, &mask->masklayers);
+ BKE_mask_layer_copy_list(&mask_dst->masklayers, &mask_src->masklayers); /* TODO add unused flag to those as well. */
/* enable fake user by default */
- id_fake_user_set(&mask->id);
-
- BKE_id_copy_ensure_local(bmain, &mask->id, &mask_new->id);
+ id_fake_user_set(&mask_dst->id);
+}
- return mask_new;
+Mask *BKE_mask_copy(Main *bmain, const Mask *mask)
+{
+ Mask *mask_copy;
+ BKE_id_copy_ex(bmain, &mask->id, (ID **)&mask_copy, 0, false);
+ return mask_copy;
}
void BKE_mask_make_local(Main *bmain, Mask *mask, const bool lib_local)
@@ -906,7 +916,7 @@ void BKE_mask_spline_free_list(ListBase *splines)
}
}
-static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot_point)
+static MaskSplinePoint *mask_spline_points_copy(const MaskSplinePoint *points, int tot_point)
{
MaskSplinePoint *npoints;
int i;
@@ -923,7 +933,7 @@ static MaskSplinePoint *mask_spline_points_copy(MaskSplinePoint *points, int tot
return npoints;
}
-MaskSpline *BKE_mask_spline_copy(MaskSpline *spline)
+MaskSpline *BKE_mask_spline_copy(const MaskSpline *spline)
{
MaskSpline *nspline = MEM_callocN(sizeof(MaskSpline), "new spline");
@@ -1171,17 +1181,6 @@ void BKE_mask_point_parent_matrix_get(MaskSplinePoint *point, float ctime, float
}
}
-static void mask_evaluate_apply_point_parent(MaskSplinePoint *point, float ctime)
-{
- float parent_matrix[3][3];
-
- BKE_mask_point_parent_matrix_get(point, ctime, parent_matrix);
-
- mul_m3_v2(parent_matrix, point->bezt.vec[0]);
- mul_m3_v2(parent_matrix, point->bezt.vec[1]);
- mul_m3_v2(parent_matrix, point->bezt.vec[2]);
-}
-
static void mask_calc_point_handle(MaskSplinePoint *point, MaskSplinePoint *point_prev, MaskSplinePoint *point_next)
{
BezTriple *bezt = &point->bezt;
@@ -1196,14 +1195,14 @@ static void mask_calc_point_handle(MaskSplinePoint *point, MaskSplinePoint *poin
#if 1
if (bezt_prev || bezt_next) {
- BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
+ BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0, 0);
}
#else
if (handle_type == HD_VECT) {
- BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
+ BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0, 0);
}
else if (handle_type == HD_AUTO) {
- BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0);
+ BKE_nurb_handle_calc(bezt, bezt_prev, bezt_next, 0, 0);
}
else if (handle_type == HD_ALIGN || handle_type == HD_ALIGN_DOUBLESIDE) {
float v1[3], v2[3];
@@ -1397,80 +1396,12 @@ void BKE_mask_spline_ensure_deform(MaskSpline *spline)
void BKE_mask_layer_evaluate(MaskLayer *masklay, const float ctime, const bool do_newframe)
{
- /* animation if available */
+ /* Animation if available. */
if (do_newframe) {
- MaskLayerShape *masklay_shape_a;
- MaskLayerShape *masklay_shape_b;
- int found;
-
- if ((found = BKE_mask_layer_shape_find_frame_range(masklay, ctime,
- &masklay_shape_a, &masklay_shape_b)))
- {
- if (found == 1) {
-#if 0
- printf("%s: exact %d %d (%d)\n", __func__, (int)ctime, BLI_listbase_count(&masklay->splines_shapes),
- masklay_shape_a->frame);
-#endif
-
- BKE_mask_layer_shape_to_mask(masklay, masklay_shape_a);
- }
- else if (found == 2) {
- float w = masklay_shape_b->frame - masklay_shape_a->frame;
-#if 0
- printf("%s: tween %d %d (%d %d)\n", __func__, (int)ctime, BLI_listbase_count(&masklay->splines_shapes),
- masklay_shape_a->frame, masklay_shape_b->frame);
-#endif
- BKE_mask_layer_shape_to_mask_interp(masklay, masklay_shape_a, masklay_shape_b,
- (ctime - masklay_shape_a->frame) / w);
- }
- else {
- /* always fail, should never happen */
- BLI_assert(found == 2);
- }
- }
- }
- /* animation done... */
-
- BKE_mask_layer_calc_handles(masklay);
-
- /* update deform */
- {
- MaskSpline *spline;
-
- for (spline = masklay->splines.first; spline; spline = spline->next) {
- int i;
- bool need_handle_recalc = false;
-
- BKE_mask_spline_ensure_deform(spline);
-
- for (i = 0; i < spline->tot_point; i++) {
- MaskSplinePoint *point = &spline->points[i];
- MaskSplinePoint *point_deform = &spline->points_deform[i];
-
- BKE_mask_point_free(point_deform);
-
- *point_deform = *point;
- point_deform->uw = point->uw ? MEM_dupallocN(point->uw) : NULL;
-
- mask_evaluate_apply_point_parent(point_deform, ctime);
-
- if (ELEM(point->bezt.h1, HD_AUTO, HD_VECT)) {
- need_handle_recalc = true;
- }
- }
-
- /* if the spline has auto or vector handles, these need to be recalculated after deformation */
- if (need_handle_recalc) {
- for (i = 0; i < spline->tot_point; i++) {
- MaskSplinePoint *point_deform = &spline->points_deform[i];
- if (ELEM(point_deform->bezt.h1, HD_AUTO, HD_VECT)) {
- BKE_mask_calc_handle_point(spline, point_deform);
- }
- }
- }
- /* end extra calc handles loop */
- }
+ BKE_mask_layer_evaluate_animation(masklay, ctime);
}
+ /* Update deform. */
+ BKE_mask_layer_evaluate_deform(masklay, ctime);
}
void BKE_mask_evaluate(Mask *mask, const float ctime, const bool do_newframe)
@@ -1531,8 +1462,8 @@ void BKE_mask_update_scene(Main *bmain, Scene *scene)
Mask *mask;
for (mask = bmain->mask.first; mask; mask = mask->id.next) {
- if (mask->id.tag & (LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA)) {
- bool do_new_frame = (mask->id.tag & LIB_TAG_ID_RECALC_DATA) != 0;
+ if (mask->id.recalc & ID_RECALC_ALL) {
+ bool do_new_frame = (mask->id.recalc & ID_RECALC_DATA) != 0;
BKE_mask_evaluate_all_masks(bmain, CFRA, do_new_frame);
}
}
diff --git a/source/blender/blenkernel/intern/mask_evaluate.c b/source/blender/blenkernel/intern/mask_evaluate.c
index 1b275f455f4..e2a9691e577 100644
--- a/source/blender/blenkernel/intern/mask_evaluate.c
+++ b/source/blender/blenkernel/intern/mask_evaluate.c
@@ -42,8 +42,10 @@
#include "DNA_mask_types.h"
#include "BKE_curve.h"
+#include "BKE_depsgraph.h"
#include "BKE_mask.h"
+#include "DEG_depsgraph.h"
unsigned int BKE_mask_spline_resolution(MaskSpline *spline, int width, int height)
{
@@ -810,3 +812,109 @@ float *BKE_mask_point_segment_diff(MaskSpline *spline, MaskSplinePoint *point,
return diff_points;
}
+
+static void mask_evaluate_apply_point_parent(MaskSplinePoint *point, float ctime)
+{
+ float parent_matrix[3][3];
+ BKE_mask_point_parent_matrix_get(point, ctime, parent_matrix);
+ mul_m3_v2(parent_matrix, point->bezt.vec[0]);
+ mul_m3_v2(parent_matrix, point->bezt.vec[1]);
+ mul_m3_v2(parent_matrix, point->bezt.vec[2]);
+}
+
+void BKE_mask_layer_evaluate_animation(MaskLayer *masklay, const float ctime)
+{
+ /* animation if available */
+ MaskLayerShape *masklay_shape_a;
+ MaskLayerShape *masklay_shape_b;
+ int found;
+ if ((found = BKE_mask_layer_shape_find_frame_range(
+ masklay, ctime, &masklay_shape_a, &masklay_shape_b)))
+ {
+ if (found == 1) {
+#if 0
+ printf("%s: exact %d %d (%d)\n",
+ __func__,
+ (int)ctime,
+ BLI_listbase_count(&masklay->splines_shapes),
+ masklay_shape_a->frame);
+#endif
+ BKE_mask_layer_shape_to_mask(masklay, masklay_shape_a);
+ }
+ else if (found == 2) {
+ float w = masklay_shape_b->frame - masklay_shape_a->frame;
+#if 0
+ printf("%s: tween %d %d (%d %d)\n",
+ __func__,
+ (int)ctime,
+ BLI_listbase_count(&masklay->splines_shapes),
+ masklay_shape_a->frame, masklay_shape_b->frame);
+#endif
+ BKE_mask_layer_shape_to_mask_interp(
+ masklay,
+ masklay_shape_a, masklay_shape_b,
+ (ctime - masklay_shape_a->frame) / w);
+ }
+ else {
+ /* always fail, should never happen */
+ BLI_assert(found == 2);
+ }
+ }
+}
+
+void BKE_mask_layer_evaluate_deform(MaskLayer *masklay, const float ctime)
+{
+ BKE_mask_layer_calc_handles(masklay);
+ for (MaskSpline *spline = masklay->splines.first;
+ spline != NULL;
+ spline = spline->next)
+ {
+ bool need_handle_recalc = false;
+ BKE_mask_spline_ensure_deform(spline);
+ for (int i = 0; i < spline->tot_point; i++) {
+ MaskSplinePoint *point = &spline->points[i];
+ MaskSplinePoint *point_deform = &spline->points_deform[i];
+ BKE_mask_point_free(point_deform);
+ *point_deform = *point;
+ point_deform->uw = point->uw ? MEM_dupallocN(point->uw) : NULL;
+ mask_evaluate_apply_point_parent(point_deform, ctime);
+ if (ELEM(point->bezt.h1, HD_AUTO, HD_VECT)) {
+ need_handle_recalc = true;
+ }
+ }
+ /* if the spline has auto or vector handles, these need to be
+ * recalculated after deformation.
+ */
+ if (need_handle_recalc) {
+ for (int i = 0; i < spline->tot_point; i++) {
+ MaskSplinePoint *point_deform = &spline->points_deform[i];
+ if (ELEM(point_deform->bezt.h1, HD_AUTO, HD_VECT)) {
+ BKE_mask_calc_handle_point(spline, point_deform);
+ }
+ }
+ }
+ /* end extra calc handles loop */
+ }
+}
+
+void BKE_mask_eval_animation(struct EvaluationContext *eval_ctx, Mask *mask)
+{
+ DEG_debug_print_eval(__func__, mask->id.name, mask);
+ for (MaskLayer *mask_layer = mask->masklayers.first;
+ mask_layer != NULL;
+ mask_layer = mask_layer->next)
+ {
+ BKE_mask_layer_evaluate_animation(mask_layer, eval_ctx->ctime);
+ }
+}
+
+void BKE_mask_eval_update(struct EvaluationContext *eval_ctx, Mask *mask)
+{
+ DEG_debug_print_eval(__func__, mask->id.name, mask);
+ for (MaskLayer *mask_layer = mask->masklayers.first;
+ mask_layer != NULL;
+ mask_layer = mask_layer->next)
+ {
+ BKE_mask_layer_evaluate_deform(mask_layer, eval_ctx->ctime);
+ }
+}
diff --git a/source/blender/blenkernel/intern/mask_rasterize.c b/source/blender/blenkernel/intern/mask_rasterize.c
index 13ec970c65c..76d16334630 100644
--- a/source/blender/blenkernel/intern/mask_rasterize.c
+++ b/source/blender/blenkernel/intern/mask_rasterize.c
@@ -80,6 +80,7 @@
#include "BLI_math.h"
#include "BLI_rect.h"
+#include "BLI_task.h"
#include "BLI_listbase.h"
#include "BLI_linklist.h"
@@ -1423,15 +1424,42 @@ float BKE_maskrasterize_handle_sample(MaskRasterHandle *mr_handle, const float x
return value;
}
+
+typedef struct MaskRasterizeBufferData {
+ MaskRasterHandle *mr_handle;
+ float x_inv, y_inv;
+ float x_px_ofs, y_px_ofs;
+ uint width;
+
+ float *buffer;
+} MaskRasterizeBufferData;
+
+static void maskrasterize_buffer_cb(
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ MaskRasterizeBufferData *data = userdata;
+
+ MaskRasterHandle *mr_handle = data->mr_handle;
+ float *buffer = data->buffer;
+
+ const uint width = data->width;
+ const float x_inv = data->x_inv;
+ const float x_px_ofs = data->x_px_ofs;
+
+ uint i = (uint)y * width;
+ float xy[2];
+ xy[1] = ((float)y * data->y_inv) + data->y_px_ofs;
+ for (uint x = 0; x < width; x++, i++) {
+ xy[0] = ((float)x * x_inv) + x_px_ofs;
+
+ buffer[i] = BKE_maskrasterize_handle_sample(mr_handle, xy);
+ }
+}
+
/**
- * \brief Rasterize a buffer from a single mask
- *
- * We could get some speedup by inlining #BKE_maskrasterize_handle_sample
- * and calculating each layer then blending buffers, but this function is only
- * used by the sequencer - so better have the caller thread.
- *
- * Since #BKE_maskrasterize_handle_sample is used threaded elsewhere,
- * we can simply use openmp here for some speedup.
+ * \brief Rasterize a buffer from a single mask (threaded execution).
*/
void BKE_maskrasterize_buffer(MaskRasterHandle *mr_handle,
const unsigned int width, const unsigned int height,
@@ -1439,33 +1467,21 @@ void BKE_maskrasterize_buffer(MaskRasterHandle *mr_handle,
{
const float x_inv = 1.0f / (float)width;
const float y_inv = 1.0f / (float)height;
- const float x_px_ofs = x_inv * 0.5f;
- const float y_px_ofs = y_inv * 0.5f;
-#ifdef _MSC_VER
- int y; /* msvc requires signed for some reason */
-
- /* ignore sign mismatch */
-# pragma warning(push)
-# pragma warning(disable:4018)
-#else
- unsigned int y;
-#endif
-
-#pragma omp parallel for private(y)
- for (y = 0; y < height; y++) {
- unsigned int i = y * width;
- unsigned int x;
- float xy[2];
- xy[1] = ((float)y * y_inv) + y_px_ofs;
- for (x = 0; x < width; x++, i++) {
- xy[0] = ((float)x * x_inv) + x_px_ofs;
-
- buffer[i] = BKE_maskrasterize_handle_sample(mr_handle, xy);
- }
- }
-
-#ifdef _MSC_VER
-# pragma warning(pop)
-#endif
+ MaskRasterizeBufferData data = {
+ .mr_handle = mr_handle,
+ .x_inv = x_inv,
+ .y_inv = y_inv,
+ .x_px_ofs = x_inv * 0.5f,
+ .y_px_ofs = y_inv * 0.5f,
+ .width = width,
+ .buffer = buffer
+ };
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((size_t)height * width > 10000);
+ BLI_task_parallel_range(0, (int)height,
+ &data,
+ maskrasterize_buffer_cb,
+ &settings);
}
diff --git a/source/blender/blenkernel/intern/material.c b/source/blender/blenkernel/intern/material.c
index 54945242fe4..01f16625386 100644
--- a/source/blender/blenkernel/intern/material.c
+++ b/source/blender/blenkernel/intern/material.c
@@ -212,50 +212,74 @@ Material *BKE_material_add(Main *bmain, const char *name)
{
Material *ma;
- ma = BKE_libblock_alloc(bmain, ID_MA, name);
+ ma = BKE_libblock_alloc(bmain, ID_MA, name, 0);
BKE_material_init(ma);
return ma;
}
-/* XXX keep synced with next function */
-Material *BKE_material_copy(Main *bmain, Material *ma)
+/**
+ * Only copy internal data of Material ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_material_copy_data(Main *bmain, Material *ma_dst, const Material *ma_src, const int flag)
{
- Material *man;
- int a;
-
- man = BKE_libblock_copy(bmain, &ma->id);
-
- id_lib_extern((ID *)man->group);
-
- for (a = 0; a < MAX_MTEX; a++) {
- if (ma->mtex[a]) {
- man->mtex[a] = MEM_mallocN(sizeof(MTex), "copymaterial");
- memcpy(man->mtex[a], ma->mtex[a], sizeof(MTex));
- id_us_plus((ID *)man->mtex[a]->tex);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (ma_src->mtex[a]) {
+ ma_dst->mtex[a] = MEM_mallocN(sizeof(*ma_dst->mtex[a]), __func__);
+ *ma_dst->mtex[a] = *ma_src->mtex[a];
}
}
-
- if (ma->ramp_col) man->ramp_col = MEM_dupallocN(ma->ramp_col);
- if (ma->ramp_spec) man->ramp_spec = MEM_dupallocN(ma->ramp_spec);
-
- if (ma->nodetree) {
- man->nodetree = ntreeCopyTree(bmain, ma->nodetree);
+
+ if (ma_src->ramp_col) {
+ ma_dst->ramp_col = MEM_dupallocN(ma_src->ramp_col);
+ }
+ if (ma_src->ramp_spec) {
+ ma_dst->ramp_spec = MEM_dupallocN(ma_src->ramp_spec);
}
- BKE_previewimg_id_copy(&man->id, &ma->id);
+ if (ma_src->nodetree) {
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)ma_src->nodetree, (ID **)&ma_dst->nodetree, flag, false);
+ }
- BLI_listbase_clear(&man->gpumaterial);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&ma_dst->id, &ma_src->id);
+ }
+ else {
+ ma_dst->preview = NULL;
+ }
- BKE_id_copy_ensure_local(bmain, &ma->id, &man->id);
+ if (ma_src->texpaintslot != NULL) {
+ ma_dst->texpaintslot = MEM_dupallocN(ma_src->texpaintslot);
+ }
- return man;
+ BLI_listbase_clear(&ma_dst->gpumaterial);
+}
+
+Material *BKE_material_copy(Main *bmain, const Material *ma)
+{
+ Material *ma_copy;
+ BKE_id_copy_ex(bmain, &ma->id, (ID **)&ma_copy, 0, false);
+ return ma_copy;
}
/* XXX (see above) material copy without adding to main dbase */
-Material *localize_material(Material *ma)
+Material *BKE_material_localize(Material *ma)
{
+ /* TODO replace with something like
+ * Material *ma_copy;
+ * BKE_id_copy_ex(bmain, &ma->id, (ID **)&ma_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false);
+ * return ma_copy;
+ *
+ * ... Once f*** nodes are fully converted to that too :( */
+
Material *man;
int a;
@@ -343,6 +367,8 @@ Material ***give_matarar_id(ID *id)
return &(((Curve *)id)->mat);
case ID_MB:
return &(((MetaBall *)id)->mat);
+ default:
+ break;
}
return NULL;
}
@@ -359,6 +385,8 @@ short *give_totcolp_id(ID *id)
return &(((Curve *)id)->totcol);
case ID_MB:
return &(((MetaBall *)id)->totcol);
+ default:
+ break;
}
return NULL;
}
@@ -378,6 +406,8 @@ static void material_data_index_remove_id(ID *id, short index)
case ID_MB:
/* meta-elems don't have materials atm */
break;
+ default:
+ break;
}
}
@@ -396,6 +426,8 @@ static void material_data_index_clear_id(ID *id)
case ID_MB:
/* meta-elems don't have materials atm */
break;
+ default:
+ break;
}
}
@@ -690,8 +722,8 @@ void assign_material(Object *ob, Material *ma, short act, int assign_type)
if (act < 1) act = 1;
/* prevent crashing when using accidentally */
- BLI_assert(!ID_IS_LINKED_DATABLOCK(ob));
- if (ID_IS_LINKED_DATABLOCK(ob)) return;
+ BLI_assert(!ID_IS_LINKED(ob));
+ if (ID_IS_LINKED(ob)) return;
/* test arraylens */
@@ -964,7 +996,7 @@ static void do_init_render_material(Material *ma, int r_mode, float *amb)
Group *group;
for (group = G.main->group.first; group; group = group->id.next) {
- if (!ID_IS_LINKED_DATABLOCK(group) && STREQ(group->id.name, ma->group->id.name)) {
+ if (!ID_IS_LINKED(group) && STREQ(group->id.name, ma->group->id.name)) {
ma->group = group;
}
}
@@ -1179,7 +1211,6 @@ void material_drivers_update(Scene *scene, Material *ma, float ctime)
bool BKE_object_material_slot_remove(Object *ob)
{
Material *mao, ***matarar;
- Object *obt;
short *totcolp;
short a, actcol;
@@ -1227,11 +1258,13 @@ bool BKE_object_material_slot_remove(Object *ob)
}
actcol = ob->actcol;
- obt = G.main->object.first;
- while (obt) {
-
+
+ for (Object *obt = G.main->object.first; obt; obt = obt->id.next) {
if (obt->data == ob->data) {
-
+ /* Can happen when object material lists are used, see: T52953 */
+ if (actcol > obt->totcol) {
+ continue;
+ }
/* WATCH IT: do not use actcol from ob or from obt (can become zero) */
mao = obt->mat[actcol - 1];
if (mao)
@@ -1251,7 +1284,6 @@ bool BKE_object_material_slot_remove(Object *ob)
obt->matbits = NULL;
}
}
- obt = obt->id.next;
}
/* check indices from mesh */
@@ -2073,7 +2105,7 @@ int do_version_tface(Main *main)
/* 1st part: marking mesh materials to update */
for (me = main->mesh.first; me; me = me->id.next) {
- if (ID_IS_LINKED_DATABLOCK(me)) continue;
+ if (ID_IS_LINKED(me)) continue;
/* get the active tface layer */
index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE);
@@ -2127,7 +2159,7 @@ int do_version_tface(Main *main)
* at doversion time: direct_link might not have happened on it,
* so ma->mtex is not pointing to valid memory yet.
* later we could, but it's better not */
- else if (ID_IS_LINKED_DATABLOCK(ma))
+ else if (ID_IS_LINKED(ma))
continue;
/* material already marked as disputed */
@@ -2192,7 +2224,7 @@ int do_version_tface(Main *main)
/* we shouldn't loop through the materials created in the loop. make the loop stop at its original length) */
for (ma = main->mat.first, a = 0; ma; ma = ma->id.next, a++) {
- if (ID_IS_LINKED_DATABLOCK(ma)) continue;
+ if (ID_IS_LINKED(ma)) continue;
/* disputed material */
if (ma->game.flag == MAT_BGE_DISPUTED) {
diff --git a/source/blender/blenkernel/intern/mball.c b/source/blender/blenkernel/intern/mball.c
index 97033a9555d..dfc49c996b1 100644
--- a/source/blender/blenkernel/intern/mball.c
+++ b/source/blender/blenkernel/intern/mball.c
@@ -96,33 +96,36 @@ MetaBall *BKE_mball_add(Main *bmain, const char *name)
{
MetaBall *mb;
- mb = BKE_libblock_alloc(bmain, ID_MB, name);
+ mb = BKE_libblock_alloc(bmain, ID_MB, name, 0);
BKE_mball_init(mb);
return mb;
}
-MetaBall *BKE_mball_copy(Main *bmain, MetaBall *mb)
+/**
+ * Only copy internal data of MetaBall ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_mball_copy_data(Main *UNUSED(bmain), MetaBall *mb_dst, const MetaBall *mb_src, const int UNUSED(flag))
{
- MetaBall *mbn;
- int a;
-
- mbn = BKE_libblock_copy(bmain, &mb->id);
+ BLI_duplicatelist(&mb_dst->elems, &mb_src->elems);
- BLI_duplicatelist(&mbn->elems, &mb->elems);
-
- mbn->mat = MEM_dupallocN(mb->mat);
- for (a = 0; a < mbn->totcol; a++) {
- id_us_plus((ID *)mbn->mat[a]);
- }
+ mb_dst->mat = MEM_dupallocN(mb_src->mat);
- mbn->editelems = NULL;
- mbn->lastelem = NULL;
-
- BKE_id_copy_ensure_local(bmain, &mb->id, &mbn->id);
+ mb_dst->editelems = NULL;
+ mb_dst->lastelem = NULL;
+}
- return mbn;
+MetaBall *BKE_mball_copy(Main *bmain, const MetaBall *mb)
+{
+ MetaBall *mb_copy;
+ BKE_id_copy_ex(bmain, &mb->id, (ID **)&mb_copy, 0, false);
+ return mb_copy;
}
void BKE_mball_make_local(Main *bmain, MetaBall *mb, const bool lib_local)
@@ -470,7 +473,7 @@ bool BKE_mball_center_bounds(MetaBall *mb, float r_cent[3])
return false;
}
-void BKE_mball_transform(MetaBall *mb, float mat[4][4])
+void BKE_mball_transform(MetaBall *mb, float mat[4][4], const bool do_props)
{
MetaElem *me;
float quat[4];
@@ -482,14 +485,17 @@ void BKE_mball_transform(MetaBall *mb, float mat[4][4])
for (me = mb->elems.first; me; me = me->next) {
mul_m4_v3(mat, &me->x);
mul_qt_qtqt(me->quat, quat, me->quat);
- me->rad *= scale;
- /* hrmf, probably elems shouldn't be
- * treating scale differently - campbell */
- if (!MB_TYPE_SIZE_SQUARED(me->type)) {
- mul_v3_fl(&me->expx, scale);
- }
- else {
- mul_v3_fl(&me->expx, scale_sqrt);
+
+ if (do_props) {
+ me->rad *= scale;
+ /* hrmf, probably elems shouldn't be
+ * treating scale differently - campbell */
+ if (!MB_TYPE_SIZE_SQUARED(me->type)) {
+ mul_v3_fl(&me->expx, scale);
+ }
+ else {
+ mul_v3_fl(&me->expx, scale_sqrt);
+ }
}
}
}
diff --git a/source/blender/blenkernel/intern/mball_tessellate.c b/source/blender/blenkernel/intern/mball_tessellate.c
index 5c0b09f0ff0..a1ae3a7f572 100644
--- a/source/blender/blenkernel/intern/mball_tessellate.c
+++ b/source/blender/blenkernel/intern/mball_tessellate.c
@@ -316,12 +316,12 @@ static float densfunc(const MetaElem *ball, float x, float y, float z)
if (dvec[2] > ball->expz) dvec[2] -= ball->expz;
else if (dvec[2] < -ball->expz) dvec[2] += ball->expz;
else dvec[2] = 0.0;
- /* fall through */
+ ATTR_FALLTHROUGH;
case MB_PLANE:
if (dvec[1] > ball->expy) dvec[1] -= ball->expy;
else if (dvec[1] < -ball->expy) dvec[1] += ball->expy;
else dvec[1] = 0.0;
- /* fall through */
+ ATTR_FALLTHROUGH;
case MB_TUBE:
if (dvec[0] > ball->expx) dvec[0] -= ball->expx;
else if (dvec[0] < -ball->expx) dvec[0] += ball->expx;
@@ -412,24 +412,18 @@ static void make_face(PROCESS *process, int i1, int i2, int i3, int i4)
cur[0] = i1;
cur[1] = i2;
cur[2] = i3;
-
- if (i4 == 0) {
- cur[3] = i3;
- }
- else {
- cur[3] = i4;
- }
+ cur[3] = i4;
#ifdef USE_ACCUM_NORMAL
- if (i4 == 0) {
+ if (i4 == i3) {
normal_tri_v3(n, process->co[i1], process->co[i2], process->co[i3]);
- accumulate_vertex_normals(
+ accumulate_vertex_normals_v3(
process->no[i1], process->no[i2], process->no[i3], NULL, n,
process->co[i1], process->co[i2], process->co[i3], NULL);
}
else {
normal_quad_v3(n, process->co[i1], process->co[i2], process->co[i3], process->co[i4]);
- accumulate_vertex_normals(
+ accumulate_vertex_normals_v3(
process->no[i1], process->no[i2], process->no[i3], process->no[i4], n,
process->co[i1], process->co[i2], process->co[i3], process->co[i4]);
}
@@ -526,40 +520,23 @@ static void docube(PROCESS *process, CUBE *cube)
if (count > 2) {
switch (count) {
case 3:
- make_face(process, indexar[2], indexar[1], indexar[0], 0);
+ make_face(process, indexar[2], indexar[1], indexar[0], indexar[0]); /* triangle */
break;
case 4:
- if (indexar[0] == 0) make_face(process, indexar[0], indexar[3], indexar[2], indexar[1]);
- else make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
+ make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
break;
case 5:
- if (indexar[0] == 0) make_face(process, indexar[0], indexar[3], indexar[2], indexar[1]);
- else make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
-
- make_face(process, indexar[4], indexar[3], indexar[0], 0);
+ make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
+ make_face(process, indexar[4], indexar[3], indexar[0], indexar[0]); /* triangle */
break;
case 6:
- if (indexar[0] == 0) {
- make_face(process, indexar[0], indexar[3], indexar[2], indexar[1]);
- make_face(process, indexar[0], indexar[5], indexar[4], indexar[3]);
- }
- else {
- make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
- make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]);
- }
+ make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
+ make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]);
break;
case 7:
- if (indexar[0] == 0) {
- make_face(process, indexar[0], indexar[3], indexar[2], indexar[1]);
- make_face(process, indexar[0], indexar[5], indexar[4], indexar[3]);
- }
- else {
- make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
- make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]);
- }
-
- make_face(process, indexar[6], indexar[5], indexar[0], 0);
-
+ make_face(process, indexar[3], indexar[2], indexar[1], indexar[0]);
+ make_face(process, indexar[5], indexar[4], indexar[3], indexar[0]);
+ make_face(process, indexar[6], indexar[5], indexar[0], indexar[0]); /* triangle */
break;
}
}
@@ -660,7 +637,7 @@ static void makecubetable(void)
for (i = 0; i < 256; i++) {
for (e = 0; e < 12; e++) done[e] = 0;
for (c = 0; c < 8; c++) pos[c] = MB_BIT(i, c);
- for (e = 0; e < 12; e++)
+ for (e = 0; e < 12; e++) {
if (!done[e] && (pos[corner1[e]] != pos[corner2[e]])) {
INTLIST *ints = NULL;
INTLISTS *lists = MEM_callocN(sizeof(INTLISTS), "mball_intlist");
@@ -687,6 +664,7 @@ static void makecubetable(void)
lists->next = cubetable[i];
cubetable[i] = lists;
}
+ }
}
for (i = 0; i < 256; i++) {
@@ -1193,10 +1171,10 @@ static void init_meta(EvaluationContext *eval_ctx, PROCESS *process, Scene *scen
break;
case MB_CUBE: /* cube is "expanded" by expz, expy and expx */
expz += ml->expz;
- /* fall through */
+ ATTR_FALLTHROUGH;
case MB_PLANE: /* plane is "expanded" by expy and expx */
expy += ml->expy;
- /* fall through */
+ ATTR_FALLTHROUGH;
case MB_TUBE: /* tube is "expanded" by expx */
expx += ml->expx;
break;
diff --git a/source/blender/blenkernel/intern/mesh.c b/source/blender/blenkernel/intern/mesh.c
index 918032b2df8..fd56534146d 100644
--- a/source/blender/blenkernel/intern/mesh.c
+++ b/source/blender/blenkernel/intern/mesh.c
@@ -494,53 +494,56 @@ Mesh *BKE_mesh_add(Main *bmain, const char *name)
{
Mesh *me;
- me = BKE_libblock_alloc(bmain, ID_ME, name);
+ me = BKE_libblock_alloc(bmain, ID_ME, name, 0);
BKE_mesh_init(me);
return me;
}
-Mesh *BKE_mesh_copy(Main *bmain, Mesh *me)
+/**
+ * Only copy internal data of Mesh ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_mesh_copy_data(Main *bmain, Mesh *me_dst, const Mesh *me_src, const int flag)
{
- Mesh *men;
- int a;
- const int do_tessface = ((me->totface != 0) && (me->totpoly == 0)); /* only do tessface if we have no polys */
-
- men = BKE_libblock_copy(bmain, &me->id);
-
- men->mat = MEM_dupallocN(me->mat);
- for (a = 0; a < men->totcol; a++) {
- id_us_plus((ID *)men->mat[a]);
- }
- id_us_plus((ID *)men->texcomesh);
+ const bool do_tessface = ((me_src->totface != 0) && (me_src->totpoly == 0)); /* only do tessface if we have no polys */
- CustomData_copy(&me->vdata, &men->vdata, CD_MASK_MESH, CD_DUPLICATE, men->totvert);
- CustomData_copy(&me->edata, &men->edata, CD_MASK_MESH, CD_DUPLICATE, men->totedge);
- CustomData_copy(&me->ldata, &men->ldata, CD_MASK_MESH, CD_DUPLICATE, men->totloop);
- CustomData_copy(&me->pdata, &men->pdata, CD_MASK_MESH, CD_DUPLICATE, men->totpoly);
+ me_dst->mat = MEM_dupallocN(me_src->mat);
+
+ CustomData_copy(&me_src->vdata, &me_dst->vdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totvert);
+ CustomData_copy(&me_src->edata, &me_dst->edata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totedge);
+ CustomData_copy(&me_src->ldata, &me_dst->ldata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totloop);
+ CustomData_copy(&me_src->pdata, &me_dst->pdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totpoly);
if (do_tessface) {
- CustomData_copy(&me->fdata, &men->fdata, CD_MASK_MESH, CD_DUPLICATE, men->totface);
+ CustomData_copy(&me_src->fdata, &me_dst->fdata, CD_MASK_MESH, CD_DUPLICATE, me_dst->totface);
}
else {
- mesh_tessface_clear_intern(men, false);
+ mesh_tessface_clear_intern(me_dst, false);
}
- BKE_mesh_update_customdata_pointers(men, do_tessface);
+ BKE_mesh_update_customdata_pointers(me_dst, do_tessface);
- men->edit_btmesh = NULL;
+ me_dst->edit_btmesh = NULL;
- men->mselect = MEM_dupallocN(men->mselect);
- men->bb = MEM_dupallocN(men->bb);
+ me_dst->mselect = MEM_dupallocN(me_dst->mselect);
+ me_dst->bb = MEM_dupallocN(me_dst->bb);
- if (me->key) {
- men->key = BKE_key_copy(bmain, me->key);
- men->key->from = (ID *)men;
+ /* TODO Do we want to add flag to prevent this? */
+ if (me_src->key) {
+ BKE_id_copy_ex(bmain, &me_src->key->id, (ID **)&me_dst->key, flag, false);
}
+}
- BKE_id_copy_ensure_local(bmain, &me->id, &men->id);
-
- return men;
+Mesh *BKE_mesh_copy(Main *bmain, const Mesh *me)
+{
+ Mesh *me_copy;
+ BKE_id_copy_ex(bmain, &me->id, (ID **)&me_copy, 0, false);
+ return me_copy;
}
BMesh *BKE_mesh_to_bmesh(
@@ -779,7 +782,7 @@ float (*BKE_mesh_orco_verts_get(Object *ob))[3]
float (*vcos)[3] = NULL;
/* Get appropriate vertex coordinates */
- vcos = MEM_callocN(sizeof(*vcos) * me->totvert, "orco mesh");
+ vcos = MEM_calloc_arrayN(me->totvert, sizeof(*vcos), "orco mesh");
mvert = tme->mvert;
totvert = min_ii(tme->totvert, me->totvert);
@@ -1000,7 +1003,7 @@ static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge,
BKE_mesh_poly_edgehash_insert(eh, mp, mloop + mp->loopstart);
}
- totedge_new = BLI_edgehash_size(eh);
+ totedge_new = BLI_edgehash_len(eh);
#ifdef DEBUG
/* ensure that theres no overlap! */
@@ -1018,7 +1021,7 @@ static void make_edges_mdata_extend(MEdge **r_alledge, int *r_totedge,
unsigned int e_index = totedge;
*r_alledge = medge = (*r_alledge ? MEM_reallocN(*r_alledge, sizeof(MEdge) * (totedge + totedge_new)) :
- MEM_callocN(sizeof(MEdge) * totedge_new, __func__));
+ MEM_calloc_arrayN(totedge_new, sizeof(MEdge), __func__));
medge += totedge;
totedge += totedge_new;
@@ -1097,7 +1100,7 @@ int BKE_mesh_nurbs_displist_to_mdata(
MLoopUV *mloopuv = NULL;
MEdge *medge;
const float *data;
- int a, b, ofs, vertcount, startvert, totvert = 0, totedge = 0, totloop = 0, totvlak = 0;
+ int a, b, ofs, vertcount, startvert, totvert = 0, totedge = 0, totloop = 0, totpoly = 0;
int p1, p2, p3, p4, *index;
const bool conv_polys = ((CU_DO_2DFILL(cu) == false) || /* 2d polys are filled with DL_INDEX3 displists */
(ob->type == OB_SURF)); /* surf polys are never filled */
@@ -1119,14 +1122,14 @@ int BKE_mesh_nurbs_displist_to_mdata(
int tot;
totvert += dl->parts * dl->nr;
tot = (dl->parts - 1 + ((dl->flag & DL_CYCL_V) == 2)) * (dl->nr - 1 + (dl->flag & DL_CYCL_U));
- totvlak += tot;
+ totpoly += tot;
totloop += tot * 4;
}
else if (dl->type == DL_INDEX3) {
int tot;
totvert += dl->nr;
tot = dl->parts;
- totvlak += tot;
+ totpoly += tot;
totloop += tot * 3;
}
dl = dl->next;
@@ -1138,13 +1141,13 @@ int BKE_mesh_nurbs_displist_to_mdata(
return -1;
}
- *r_allvert = mvert = MEM_callocN(sizeof(MVert) * totvert, "nurbs_init mvert");
- *r_alledge = medge = MEM_callocN(sizeof(MEdge) * totedge, "nurbs_init medge");
- *r_allloop = mloop = MEM_callocN(sizeof(MLoop) * totvlak * 4, "nurbs_init mloop"); // totloop
- *r_allpoly = mpoly = MEM_callocN(sizeof(MPoly) * totvlak, "nurbs_init mloop");
+ *r_allvert = mvert = MEM_calloc_arrayN(totvert, sizeof(MVert), "nurbs_init mvert");
+ *r_alledge = medge = MEM_calloc_arrayN(totedge, sizeof(MEdge), "nurbs_init medge");
+ *r_allloop = mloop = MEM_calloc_arrayN(totpoly, 4 * sizeof(MLoop), "nurbs_init mloop"); // totloop
+ *r_allpoly = mpoly = MEM_calloc_arrayN(totpoly, sizeof(MPoly), "nurbs_init mloop");
if (r_alluv)
- *r_alluv = mloopuv = MEM_callocN(sizeof(MLoopUV) * totvlak * 4, "nurbs_init mloopuv");
+ *r_alluv = mloopuv = MEM_calloc_arrayN(totpoly, 4 * sizeof(MLoopUV), "nurbs_init mloopuv");
/* verts and faces */
vertcount = 0;
@@ -1323,13 +1326,14 @@ int BKE_mesh_nurbs_displist_to_mdata(
dl = dl->next;
}
-
- if (totvlak) {
- make_edges_mdata_extend(r_alledge, &totedge,
- *r_allpoly, *r_allloop, totvlak);
+
+ if (totpoly) {
+ make_edges_mdata_extend(
+ r_alledge, &totedge,
+ *r_allpoly, *r_allloop, totpoly);
}
- *r_totpoly = totvlak;
+ *r_totpoly = totpoly;
*r_totloop = totloop;
*r_totedge = totedge;
*r_totvert = totvert;
@@ -1339,7 +1343,7 @@ int BKE_mesh_nurbs_displist_to_mdata(
/* this may fail replacing ob->data, be sure to check ob->type */
-void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv)
+void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use_orco_uv, const char *obdata_name)
{
Main *bmain = G.main;
Object *ob1;
@@ -1366,7 +1370,7 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use
}
/* make mesh */
- me = BKE_mesh_add(bmain, "Mesh");
+ me = BKE_mesh_add(bmain, obdata_name);
me->totvert = totvert;
me->totedge = totedge;
me->totloop = totloop;
@@ -1386,21 +1390,30 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use
BKE_mesh_calc_normals(me);
}
else {
- me = BKE_mesh_add(bmain, "Mesh");
+ me = BKE_mesh_add(bmain, obdata_name);
DM_to_mesh(dm, me, ob, CD_MASK_MESH, false);
}
me->totcol = cu->totcol;
me->mat = cu->mat;
+ /* Copy evaluated texture space from curve to mesh.
+ *
+ * Note that we disable auto texture space feature since that will cause
+ * texture space to evaluate differently for curve and mesh, since curve
+ * uses CV to calculate bounding box, and mesh uses what is coming from
+ * tessellated curve.
+ */
+ me->texflag = cu->texflag & ~CU_AUTOSPACE;
+ copy_v3_v3(me->loc, cu->loc);
+ copy_v3_v3(me->size, cu->size);
+ copy_v3_v3(me->rot, cu->rot);
BKE_mesh_texspace_calc(me);
cu->mat = NULL;
cu->totcol = 0;
- if (ob->data) {
- BKE_libblock_free(bmain, ob->data);
- }
+ /* Do not decrement ob->data usercount here, it's done at end of func with BKE_libblock_free_us() call. */
ob->data = me;
ob->type = OB_MESH;
@@ -1410,11 +1423,14 @@ void BKE_mesh_from_nurbs_displist(Object *ob, ListBase *dispbase, const bool use
if (ob1->data == cu) {
ob1->type = OB_MESH;
+ id_us_min((ID *)ob1->data);
ob1->data = ob->data;
- id_us_plus((ID *)ob->data);
+ id_us_plus((ID *)ob1->data);
}
ob1 = ob1->id.next;
}
+
+ BKE_libblock_free_us(bmain, cu);
}
void BKE_mesh_from_nurbs(Object *ob)
@@ -1427,7 +1443,7 @@ void BKE_mesh_from_nurbs(Object *ob)
disp = ob->curve_cache->disp;
}
- BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv);
+ BKE_mesh_from_nurbs_displist(ob, &disp, use_orco_uv, cu->id.name);
}
typedef struct EdgeLink {
@@ -1472,7 +1488,7 @@ void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int e
ListBase edges = {NULL, NULL};
/* get boundary edges */
- edge_users = MEM_callocN(sizeof(int) * dm_totedge, __func__);
+ edge_users = MEM_calloc_arrayN(dm_totedge, sizeof(int), __func__);
for (i = 0, mp = mpoly; i < dm_totpoly; i++, mp++) {
MLoop *ml = &mloop[mp->loopstart];
int j;
@@ -1568,7 +1584,7 @@ void BKE_mesh_to_curve_nurblist(DerivedMesh *dm, ListBase *nurblist, const int e
nu->flagu = CU_NURB_ENDPOINT | (closed ? CU_NURB_CYCLIC : 0); /* endpoint */
nu->resolu = 12;
- nu->bp = (BPoint *)MEM_callocN(sizeof(BPoint) * totpoly, "bpoints");
+ nu->bp = (BPoint *)MEM_calloc_arrayN(totpoly, sizeof(BPoint), "bpoints");
/* add points */
vl = polyline.first;
@@ -1724,7 +1740,7 @@ void BKE_mesh_smooth_flag_set(Object *meshOb, int enableSmooth)
float (*BKE_mesh_vertexCos_get(const Mesh *me, int *r_numVerts))[3]
{
int i, numVerts = me->totvert;
- float (*cos)[3] = MEM_mallocN(sizeof(*cos) * numVerts, "vertexcos1");
+ float (*cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(*cos), "vertexcos1");
if (r_numVerts) *r_numVerts = numVerts;
for (i = 0; i < numVerts; i++)
@@ -1860,7 +1876,7 @@ void BKE_mesh_ensure_navmesh(Mesh *me)
int i;
int numFaces = me->totpoly;
int *recastData;
- recastData = (int *)MEM_mallocN(numFaces * sizeof(int), __func__);
+ recastData = (int *)MEM_malloc_arrayN(numFaces, sizeof(int), __func__);
for (i = 0; i < numFaces; i++) {
recastData[i] = i + 1;
}
@@ -1948,7 +1964,7 @@ void BKE_mesh_mselect_validate(Mesh *me)
return;
mselect_src = me->mselect;
- mselect_dst = MEM_mallocN(sizeof(MSelect) * (me->totselect), "Mesh selection history");
+ mselect_dst = MEM_malloc_arrayN((me->totselect), sizeof(MSelect), "Mesh selection history");
for (i_src = 0, i_dst = 0; i_src < me->totselect; i_src++) {
int index = mselect_src[i_src].index;
@@ -2055,6 +2071,12 @@ void BKE_mesh_mselect_active_set(Mesh *me, int index, int type)
(me->mselect[me->totselect - 1].type == type));
}
+/**
+ * Compute 'split' (aka loop, or per face corner's) normals.
+ *
+ * \param r_lnors_spacearr Allows to get computed loop normal space array. That data, among other things,
+ * contains 'smooth fan' info, useful e.g. to split geometry along sharp edges...
+ */
void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spacearr)
{
float (*r_loopnors)[3];
@@ -2062,6 +2084,11 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac
short (*clnors)[2] = NULL;
bool free_polynors = false;
+ /* Note that we enforce computing clnors when the clnor space array is requested by caller here.
+ * However, we obviously only use the autosmooth angle threshold only in case autosmooth is enabled. */
+ const bool use_split_normals = (r_lnors_spacearr != NULL) || ((mesh->flag & ME_AUTOSMOOTH) != 0);
+ const float split_angle = (mesh->flag & ME_AUTOSMOOTH) != 0 ? mesh->smoothresh : (float)M_PI;
+
if (CustomData_has_layer(&mesh->ldata, CD_NORMAL)) {
r_loopnors = CustomData_get_layer(&mesh->ldata, CD_NORMAL);
memset(r_loopnors, 0, sizeof(float[3]) * mesh->totloop);
@@ -2080,7 +2107,7 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac
free_polynors = false;
}
else {
- polynors = MEM_mallocN(sizeof(float[3]) * mesh->totpoly, __func__);
+ polynors = MEM_malloc_arrayN(mesh->totpoly, sizeof(float[3]), __func__);
BKE_mesh_calc_normals_poly(
mesh->mvert, NULL, mesh->totvert,
mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly, polynors, false);
@@ -2090,7 +2117,7 @@ void BKE_mesh_calc_normals_split_ex(Mesh *mesh, MLoopNorSpaceArray *r_lnors_spac
BKE_mesh_normals_loop_split(
mesh->mvert, mesh->totvert, mesh->medge, mesh->totedge,
mesh->mloop, r_loopnors, mesh->totloop, mesh->mpoly, (const float (*)[3])polynors, mesh->totpoly,
- (mesh->flag & ME_AUTOSMOOTH) != 0, mesh->smoothresh, r_lnors_spacearr, clnors, NULL);
+ use_split_normals, split_angle, r_lnors_spacearr, clnors, NULL);
if (free_polynors) {
MEM_freeN(polynors);
@@ -2122,116 +2149,73 @@ typedef struct SplitFaceNewEdge {
/* Detect needed new vertices, and update accordingly loops' vertex indices.
* WARNING! Leaves mesh in invalid state. */
static int split_faces_prepare_new_verts(
- const Mesh *mesh, MLoopNorSpaceArray *lnors_spacearr, SplitFaceNewVert **new_verts, MemArena *memarena,
- bool *r_need_vnors_recalc)
+ const Mesh *mesh, MLoopNorSpaceArray *lnors_spacearr, SplitFaceNewVert **new_verts, MemArena *memarena)
{
- /* Note: if lnors_spacearr is NULL, ther is no autosmooth handling, and we only split out flat polys. */
+ /* This is now mandatory, trying to do the job in simple way without that data is doomed to fail, even when only
+ * dealing with smooth/flat faces one can find cases that no simple algorithm can handle properly. */
+ BLI_assert(lnors_spacearr != NULL);
+
const int num_loops = mesh->totloop;
int num_verts = mesh->totvert;
MVert *mvert = mesh->mvert;
MLoop *mloop = mesh->mloop;
BLI_bitmap *verts_used = BLI_BITMAP_NEW(num_verts, __func__);
+ BLI_bitmap *done_loops = BLI_BITMAP_NEW(num_loops, __func__);
- if (lnors_spacearr) {
- BLI_bitmap *done_loops = BLI_BITMAP_NEW(num_loops, __func__);
-
- MLoop *ml = mloop;
- MLoopNorSpace **lnor_space = lnors_spacearr->lspacearr;
- for (int loop_idx = 0; loop_idx < num_loops; loop_idx++, ml++, lnor_space++) {
- if (!BLI_BITMAP_TEST(done_loops, loop_idx)) {
- const int vert_idx = ml->v;
- const bool vert_used = BLI_BITMAP_TEST_BOOL(verts_used, vert_idx);
- /* If vert is already used by another smooth fan, we need a new vert for this one. */
- const int new_vert_idx = vert_used ? num_verts++ : vert_idx;
-
- if ((*lnor_space)->loops) {
- for (LinkNode *lnode = (*lnor_space)->loops; lnode; lnode = lnode->next) {
- const int ml_fan_idx = GET_INT_FROM_POINTER(lnode->link);
- BLI_BITMAP_ENABLE(done_loops, ml_fan_idx);
- if (vert_used) {
- mloop[ml_fan_idx].v = new_vert_idx;
- }
- }
+ MLoop *ml = mloop;
+ MLoopNorSpace **lnor_space = lnors_spacearr->lspacearr;
+
+ BLI_assert(lnors_spacearr->data_type == MLNOR_SPACEARR_LOOP_INDEX);
+
+ for (int loop_idx = 0; loop_idx < num_loops; loop_idx++, ml++, lnor_space++) {
+ if (!BLI_BITMAP_TEST(done_loops, loop_idx)) {
+ const int vert_idx = ml->v;
+ const bool vert_used = BLI_BITMAP_TEST_BOOL(verts_used, vert_idx);
+ /* If vert is already used by another smooth fan, we need a new vert for this one. */
+ const int new_vert_idx = vert_used ? num_verts++ : vert_idx;
+
+ BLI_assert(*lnor_space);
+
+ if ((*lnor_space)->flags & MLNOR_SPACE_IS_SINGLE) {
+ /* Single loop in this fan... */
+ BLI_assert(GET_INT_FROM_POINTER((*lnor_space)->loops) == loop_idx);
+ BLI_BITMAP_ENABLE(done_loops, loop_idx);
+ if (vert_used) {
+ ml->v = new_vert_idx;
}
- else {
- /* Single loop in this fan... */
- BLI_BITMAP_ENABLE(done_loops, loop_idx);
+ }
+ else {
+ for (LinkNode *lnode = (*lnor_space)->loops; lnode; lnode = lnode->next) {
+ const int ml_fan_idx = GET_INT_FROM_POINTER(lnode->link);
+ BLI_BITMAP_ENABLE(done_loops, ml_fan_idx);
if (vert_used) {
- ml->v = new_vert_idx;
+ mloop[ml_fan_idx].v = new_vert_idx;
}
}
-
- if (!vert_used) {
- BLI_BITMAP_ENABLE(verts_used, vert_idx);
- /* We need to update that vertex's normal here, we won't go over it again. */
- /* This is important! *DO NOT* set vnor to final computed lnor, vnor should always be defined to
- * 'automatic normal' value computed from its polys, not some custom normal.
- * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */
- normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor);
- }
- else {
- /* Add new vert to list. */
- SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert));
- new_vert->orig_index = vert_idx;
- new_vert->new_index = new_vert_idx;
- new_vert->vnor = (*lnor_space)->vec_lnor; /* See note above. */
- new_vert->next = *new_verts;
- *new_verts = new_vert;
- }
}
- }
- MEM_freeN(done_loops);
- }
- else {
- /* No loop normal spaces available, we only split out flat polys. */
- const int num_polys = mesh->totpoly;
- const MPoly *mpoly = mesh->mpoly;
-
- /* We do that in two loops, to keep original edges/verts to smooth polys preferencially. */
- const MPoly *mp = mpoly;
- for (int i = 0; i < num_polys; i++, mp++) {
- if (mp->flag & ME_SMOOTH) {
- const MLoop *ml = &mloop[mp->loopstart];
- for (int j = 0; j < mp->totloop; j++, ml++) {
- /* Just mark the vertex as used/reserved, that way neighbor flat polys, if any,
- * will have to create their own. */
- BLI_BITMAP_ENABLE(verts_used, ml->v);
- }
+ if (!vert_used) {
+ BLI_BITMAP_ENABLE(verts_used, vert_idx);
+ /* We need to update that vertex's normal here, we won't go over it again. */
+ /* This is important! *DO NOT* set vnor to final computed lnor, vnor should always be defined to
+ * 'automatic normal' value computed from its polys, not some custom normal.
+ * Fortunately, that's the loop normal space's 'lnor' reference vector. ;) */
+ normal_float_to_short_v3(mvert[vert_idx].no, (*lnor_space)->vec_lnor);
}
- }
-
- mp = mpoly;
- for (int i = 0; i < num_polys; i++, mp++) {
- if (!(mp->flag & ME_SMOOTH)) {
- MLoop *ml = &mloop[mp->loopstart];
- for (int j = 0; j < mp->totloop; j++, ml++) {
- const int vert_idx = ml->v;
-
- if (BLI_BITMAP_TEST(verts_used, vert_idx)) {
- /* Add new vert to list. */
- const int new_vert_idx = num_verts++;
- ml->v = new_vert_idx;
-
- SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert));
- new_vert->orig_index = vert_idx;
- new_vert->new_index = new_vert_idx;
- new_vert->vnor = NULL; /* See note below about normals. */
- new_vert->next = *new_verts;
- *new_verts = new_vert;
- }
- else {
- BLI_BITMAP_ENABLE(verts_used, vert_idx);
- }
- }
- /* Note: there is no way to get new normals for smooth vertices here (and we don't have direct access
- * to poly normals either for flat ones), so we'll have to recompute all vnors at the end... */
- *r_need_vnors_recalc = true;
+ else {
+ /* Add new vert to list. */
+ SplitFaceNewVert *new_vert = BLI_memarena_alloc(memarena, sizeof(*new_vert));
+ new_vert->orig_index = vert_idx;
+ new_vert->new_index = new_vert_idx;
+ new_vert->vnor = (*lnor_space)->vec_lnor; /* See note above. */
+ new_vert->next = *new_verts;
+ *new_verts = new_vert;
}
}
}
+ MEM_freeN(done_loops);
MEM_freeN(verts_used);
return num_verts - mesh->totvert;
@@ -2258,16 +2242,18 @@ static int split_faces_prepare_new_edges(
for (int loop_idx = 0; loop_idx < mp->totloop; loop_idx++, ml++) {
void **eval;
if (!BLI_edgehash_ensure_p(edges_hash, ml_prev->v, ml->v, &eval)) {
+ const int edge_idx = ml_prev->e;
+
/* That edge has not been encountered yet, define it. */
- if (BLI_BITMAP_TEST(edges_used, ml_prev->e)) {
+ if (BLI_BITMAP_TEST(edges_used, edge_idx)) {
/* Original edge has already been used, we need to define a new one. */
- const int edge_idx = num_edges++;
- *eval = SET_INT_IN_POINTER(edge_idx);
- ml_prev->e = edge_idx;
+ const int new_edge_idx = num_edges++;
+ *eval = SET_INT_IN_POINTER(new_edge_idx);
+ ml_prev->e = new_edge_idx;
SplitFaceNewEdge *new_edge = BLI_memarena_alloc(memarena, sizeof(*new_edge));
- new_edge->orig_index = ml_prev->e;
- new_edge->new_index = edge_idx;
+ new_edge->orig_index = edge_idx;
+ new_edge->new_index = new_edge_idx;
new_edge->v1 = ml_prev->v;
new_edge->v2 = ml->v;
new_edge->next = *new_edges;
@@ -2275,7 +2261,6 @@ static int split_faces_prepare_new_edges(
}
else {
/* We can re-use original edge. */
- const int edge_idx = ml_prev->e;
medge[edge_idx].v1 = ml_prev->v;
medge[edge_idx].v2 = ml->v;
*eval = SET_INT_IN_POINTER(edge_idx);
@@ -2308,6 +2293,7 @@ static void split_faces_split_new_verts(
MVert *new_mv = &mvert[mesh->totvert - 1];
for (int i = mesh->totvert - 1; i >= num_verts ; i--, new_mv--, new_verts = new_verts->next) {
BLI_assert(new_verts->new_index == i);
+ BLI_assert(new_verts->new_index != new_verts->orig_index);
CustomData_copy_data(&mesh->vdata, &mesh->vdata, new_verts->orig_index, i, 1);
if (new_verts->vnor) {
normal_float_to_short_v3(new_mv->no, new_verts->vnor);
@@ -2326,6 +2312,7 @@ static void split_faces_split_new_edges(
MEdge *new_med = &medge[mesh->totedge - 1];
for (int i = mesh->totedge - 1; i >= num_edges ; i--, new_med--, new_edges = new_edges->next) {
BLI_assert(new_edges->new_index == i);
+ BLI_assert(new_edges->new_index != new_edges->orig_index);
CustomData_copy_data(&mesh->edata, &mesh->edata, new_edges->orig_index, i, 1);
new_med->v1 = new_edges->v1;
new_med->v2 = new_edges->v2;
@@ -2347,46 +2334,41 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals)
}
BKE_mesh_tessface_clear(mesh);
- MLoopNorSpaceArray *lnors_spacearr = NULL;
- MemArena *memarena;
- bool need_vnors_recalc = false;
-
- if (mesh->flag & ME_AUTOSMOOTH) {
- lnors_spacearr = MEM_callocN(sizeof(*lnors_spacearr), __func__);
- /* Compute loop normals and loop normal spaces (a.k.a. smooth fans of faces around vertices). */
- BKE_mesh_calc_normals_split_ex(mesh, lnors_spacearr);
- /* Stealing memarena from loop normals space array. */
- memarena = lnors_spacearr->mem;
- }
- else {
- /* We still have to split out flat faces... */
- memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
- }
+ MLoopNorSpaceArray lnors_spacearr = {NULL};
+ /* Compute loop normals and loop normal spaces (a.k.a. smooth fans of faces around vertices). */
+ BKE_mesh_calc_normals_split_ex(mesh, &lnors_spacearr);
+ /* Stealing memarena from loop normals space array. */
+ MemArena *memarena = lnors_spacearr.mem;
SplitFaceNewVert *new_verts = NULL;
SplitFaceNewEdge *new_edges = NULL;
/* Detect loop normal spaces (a.k.a. smooth fans) that will need a new vert. */
- const int num_new_verts = split_faces_prepare_new_verts(mesh, lnors_spacearr, &new_verts, memarena, &need_vnors_recalc);
+ const int num_new_verts = split_faces_prepare_new_verts(mesh, &lnors_spacearr, &new_verts, memarena);
if (num_new_verts > 0) {
/* Reminder: beyond this point, there is no way out, mesh is in invalid state (due to early-reassignment of
* loops' vertex and edge indices to new, to-be-created split ones). */
const int num_new_edges = split_faces_prepare_new_edges(mesh, &new_edges, memarena);
- BLI_assert(num_new_edges > 0);
+ /* We can have to split a vertex without having to add a single new edge... */
+ const bool do_edges = (num_new_edges > 0);
/* Reallocate all vert and edge related data. */
mesh->totvert += num_new_verts;
- mesh->totedge += num_new_edges;
CustomData_realloc(&mesh->vdata, mesh->totvert);
- CustomData_realloc(&mesh->edata, mesh->totedge);
+ if (do_edges) {
+ mesh->totedge += num_new_edges;
+ CustomData_realloc(&mesh->edata, mesh->totedge);
+ }
/* Update pointers to a newly allocated memory. */
BKE_mesh_update_customdata_pointers(mesh, false);
/* Perform actual split of vertices and edges. */
split_faces_split_new_verts(mesh, new_verts, num_new_verts);
- split_faces_split_new_edges(mesh, new_edges, num_new_edges);
+ if (do_edges) {
+ split_faces_split_new_edges(mesh, new_edges, num_new_edges);
+ }
}
/* Note: after this point mesh is expected to be valid again. */
@@ -2396,18 +2378,9 @@ void BKE_mesh_split_faces(Mesh *mesh, bool free_loop_normals)
CustomData_free_layers(&mesh->ldata, CD_NORMAL, mesh->totloop);
}
- if (lnors_spacearr) {
- /* Also frees new_verts/edges temp data, since we used its memarena to allocate them. */
- BKE_lnor_spacearr_free(lnors_spacearr);
- MEM_freeN(lnors_spacearr);
- }
- else {
- BLI_memarena_free(memarena);
- }
+ /* Also frees new_verts/edges temp data, since we used its memarena to allocate them. */
+ BKE_lnor_spacearr_free(&lnors_spacearr);
- if (need_vnors_recalc) {
- BKE_mesh_calc_normals(mesh);
- }
#ifdef VALIDATE_MESH
BKE_mesh_validate(mesh, true, true);
#endif
@@ -2436,7 +2409,9 @@ Mesh *BKE_mesh_new_from_object(
int uv_from_orco;
/* copies object and modifiers (but not the data) */
- Object *tmpobj = BKE_object_copy_ex(bmain, ob, true);
+ Object *tmpobj;
+ /* TODO: make it temp copy outside bmain! */
+ BKE_id_copy_ex(bmain, &ob->id, (ID **)&tmpobj, LIB_ID_COPY_CACHES, false);
tmpcu = (Curve *)tmpobj->data;
id_us_min(&tmpcu->id);
@@ -2455,11 +2430,16 @@ Mesh *BKE_mesh_new_from_object(
/* if getting the original caged mesh, delete object modifiers */
if (cage)
- BKE_object_free_modifiers(tmpobj);
+ BKE_object_free_modifiers(tmpobj, 0);
/* copies the data */
copycu = tmpobj->data = BKE_curve_copy(bmain, (Curve *) ob->data);
+ /* make sure texture space is calculated for a copy of curve,
+ * it will be used for the final result.
+ */
+ BKE_curve_texspace_calc(copycu);
+
/* temporarily set edit so we get updates from edit mode, but
* also because for text datablocks copying it while in edit
* mode gives invalid data structures */
@@ -2476,7 +2456,7 @@ Mesh *BKE_mesh_new_from_object(
/* convert object type to mesh */
uv_from_orco = (tmpcu->flag & CU_UV_ORCO) != 0;
- BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco);
+ BKE_mesh_from_nurbs_displist(tmpobj, &dispbase, uv_from_orco, tmpcu->id.name + 2);
tmpmesh = tmpobj->data;
@@ -2490,8 +2470,6 @@ Mesh *BKE_mesh_new_from_object(
return NULL;
}
- BKE_mesh_texspace_copy_from_object(tmpmesh, ob);
-
BKE_libblock_free_us(bmain, tmpobj);
/* XXX The curve to mesh conversion is convoluted... But essentially, BKE_mesh_from_nurbs_displist()
@@ -2512,7 +2490,7 @@ Mesh *BKE_mesh_new_from_object(
if (ob != basis_ob)
return NULL; /* only do basis metaball */
- tmpmesh = BKE_mesh_add(bmain, "Mesh");
+ tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2);
/* BKE_mesh_add gives us a user count we don't need */
id_us_min(&tmpmesh->id);
@@ -2520,7 +2498,7 @@ Mesh *BKE_mesh_new_from_object(
ListBase disp = {NULL, NULL};
/* TODO(sergey): This is gonna to work for until EvaluationContext
* only contains for_render flag. As soon as CoW is
- * implemented, this is to be rethinked.
+ * implemented, this is to be rethought.
*/
EvaluationContext eval_ctx;
DEG_evaluation_context_init(&eval_ctx, DAG_EVAL_RENDER);
@@ -2567,7 +2545,7 @@ Mesh *BKE_mesh_new_from_object(
else
dm = mesh_create_derived_view(sce, ob, mask);
- tmpmesh = BKE_mesh_add(bmain, "Mesh");
+ tmpmesh = BKE_mesh_add(bmain, ((ID *)ob->data)->name + 2);
DM_to_mesh(dm, tmpmesh, ob, mask, true);
/* Copy autosmooth settings from original mesh. */
@@ -2659,9 +2637,7 @@ Mesh *BKE_mesh_new_from_object(
void BKE_mesh_eval_geometry(EvaluationContext *UNUSED(eval_ctx),
Mesh *mesh)
{
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s on %s\n", __func__, mesh->id.name);
- }
+ DEG_debug_print_eval(__func__, mesh->id.name, mesh);
if (mesh->bb == NULL || (mesh->bb->flag & BOUNDBOX_DIRTY)) {
BKE_mesh_texspace_calc(mesh);
}
diff --git a/source/blender/blenkernel/intern/mesh_evaluate.c b/source/blender/blenkernel/intern/mesh_evaluate.c
index 003b7b784d5..a67c9de6deb 100644
--- a/source/blender/blenkernel/intern/mesh_evaluate.c
+++ b/source/blender/blenkernel/intern/mesh_evaluate.c
@@ -43,7 +43,7 @@
#include "BLI_math.h"
#include "BLI_edgehash.h"
#include "BLI_bitmap.h"
-#include "BLI_polyfill2d.h"
+#include "BLI_polyfill_2d.h"
#include "BLI_linklist.h"
#include "BLI_linklist_stack.h"
#include "BLI_alloca.h"
@@ -127,8 +127,8 @@ void BKE_mesh_calc_normals_mapping_ex(
return;
}
- if (!pnors) pnors = MEM_callocN(sizeof(float[3]) * (size_t)numPolys, __func__);
- /* if (!fnors) fnors = MEM_callocN(sizeof(float[3]) * numFaces, "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */
+ if (!pnors) pnors = MEM_calloc_arrayN((size_t)numPolys, sizeof(float[3]), __func__);
+ /* if (!fnors) fnors = MEM_calloc_arrayN(numFaces, sizeof(float[3]), "face nors mesh.c"); */ /* NO NEED TO ALLOC YET */
if (only_face_normals == false) {
@@ -173,10 +173,14 @@ typedef struct MeshCalcNormalsData {
const MLoop *mloop;
MVert *mverts;
float (*pnors)[3];
+ float (*lnors_weighted)[3];
float (*vnors)[3];
} MeshCalcNormalsData;
-static void mesh_calc_normals_poly_task_cb(void *userdata, const int pidx)
+static void mesh_calc_normals_poly_cb(
+ void *__restrict userdata,
+ const int pidx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
MeshCalcNormalsData *data = userdata;
const MPoly *mp = &data->mpolys[pidx];
@@ -184,7 +188,10 @@ static void mesh_calc_normals_poly_task_cb(void *userdata, const int pidx)
BKE_mesh_calc_poly_normal(mp, data->mloop + mp->loopstart, data->mverts, data->pnors[pidx]);
}
-static void mesh_calc_normals_poly_accum_task_cb(void *userdata, const int pidx)
+static void mesh_calc_normals_poly_prepare_cb(
+ void *__restrict userdata,
+ const int pidx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
MeshCalcNormalsData *data = userdata;
const MPoly *mp = &data->mpolys[pidx];
@@ -193,7 +200,7 @@ static void mesh_calc_normals_poly_accum_task_cb(void *userdata, const int pidx)
float pnor_temp[3];
float *pnor = data->pnors ? data->pnors[pidx] : pnor_temp;
- float (*vnors)[3] = data->vnors;
+ float (*lnors_weighted)[3] = data->lnors_weighted;
const int nverts = mp->totloop;
float (*edgevecbuf)[3] = BLI_array_alloca(edgevecbuf, (size_t)nverts);
@@ -220,42 +227,61 @@ static void mesh_calc_normals_poly_accum_task_cb(void *userdata, const int pidx)
v_prev = v_curr;
}
if (UNLIKELY(normalize_v3(pnor) == 0.0f)) {
- pnor[2] = 1.0f; /* other axis set to 0.0 */
+ pnor[2] = 1.0f; /* other axes set to 0.0 */
}
}
/* accumulate angle weighted face normal */
- /* inline version of #accumulate_vertex_normals_poly */
+ /* inline version of #accumulate_vertex_normals_poly_v3,
+ * split between this threaded callback and #mesh_calc_normals_poly_accum_cb. */
{
const float *prev_edge = edgevecbuf[nverts - 1];
for (i = 0; i < nverts; i++) {
+ const int lidx = mp->loopstart + i;
const float *cur_edge = edgevecbuf[i];
/* calculate angle between the two poly edges incident on
* this vertex */
const float fac = saacos(-dot_v3v3(cur_edge, prev_edge));
- /* accumulate */
- for (int k = 3; k--; ) {
- atomic_add_and_fetch_fl(&vnors[ml[i].v][k], pnor[k] * fac);
- }
+ /* Store for later accumulation */
+ mul_v3_v3fl(lnors_weighted[lidx], pnor, fac);
+
prev_edge = cur_edge;
}
}
+}
+
+static void mesh_calc_normals_poly_finalize_cb(
+ void *__restrict userdata,
+ const int vidx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ MeshCalcNormalsData *data = userdata;
+ MVert *mv = &data->mverts[vidx];
+ float *no = data->vnors[vidx];
+
+ if (UNLIKELY(normalize_v3(no) == 0.0f)) {
+ /* following Mesh convention; we use vertex coordinate itself for normal in this case */
+ normalize_v3_v3(no, mv->co);
+ }
+
+ normal_float_to_short_v3(mv->no, no);
}
void BKE_mesh_calc_normals_poly(
MVert *mverts, float (*r_vertnors)[3], int numVerts,
const MLoop *mloop, const MPoly *mpolys,
- int UNUSED(numLoops), int numPolys, float (*r_polynors)[3],
+ int numLoops, int numPolys, float (*r_polynors)[3],
const bool only_face_normals)
{
float (*pnors)[3] = r_polynors;
- float (*vnors)[3] = r_vertnors;
- bool free_vnors = false;
- int i;
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1024;
if (only_face_normals) {
BLI_assert((pnors != NULL) || (numPolys == 0));
@@ -265,13 +291,17 @@ void BKE_mesh_calc_normals_poly(
.mpolys = mpolys, .mloop = mloop, .mverts = mverts, .pnors = pnors,
};
- BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_task_cb, (numPolys > BKE_MESH_OMP_LIMIT));
+ BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_cb, &settings);
return;
}
+ float (*vnors)[3] = r_vertnors;
+ float (*lnors_weighted)[3] = MEM_malloc_arrayN((size_t)numLoops, sizeof(*lnors_weighted), __func__);
+ bool free_vnors = false;
+
/* first go through and calculate normals for all the polys */
if (vnors == NULL) {
- vnors = MEM_callocN(sizeof(*vnors) * (size_t)numVerts, __func__);
+ vnors = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vnors), __func__);
free_vnors = true;
}
else {
@@ -279,38 +309,39 @@ void BKE_mesh_calc_normals_poly(
}
MeshCalcNormalsData data = {
- .mpolys = mpolys, .mloop = mloop, .mverts = mverts, .pnors = pnors, .vnors = vnors,
+ .mpolys = mpolys, .mloop = mloop, .mverts = mverts,
+ .pnors = pnors, .lnors_weighted = lnors_weighted, .vnors = vnors
};
- BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_accum_task_cb, (numPolys > BKE_MESH_OMP_LIMIT));
-
- for (i = 0; i < numVerts; i++) {
- MVert *mv = &mverts[i];
- float *no = vnors[i];
-
- if (UNLIKELY(normalize_v3(no) == 0.0f)) {
- /* following Mesh convention; we use vertex coordinate itself for normal in this case */
- normalize_v3_v3(no, mv->co);
- }
+ /* Compute poly normals, and prepare weighted loop normals. */
+ BLI_task_parallel_range(0, numPolys, &data, mesh_calc_normals_poly_prepare_cb, &settings);
- normal_float_to_short_v3(mv->no, no);
+ /* Actually accumulate weighted loop normals into vertex ones. */
+ /* Unfortunately, not possible to thread that (not in a reasonable, totally lock- and barrier-free fashion),
+ * since several loops will point to the same vertex... */
+ for (int lidx = 0; lidx < numLoops; lidx++) {
+ add_v3_v3(vnors[mloop[lidx].v], data.lnors_weighted[lidx]);
}
+ /* Normalize and validate computed vertex normals. */
+ BLI_task_parallel_range(0, numVerts, &data, mesh_calc_normals_poly_finalize_cb, &settings);
+
if (free_vnors) {
MEM_freeN(vnors);
}
+ MEM_freeN(lnors_weighted);
}
void BKE_mesh_calc_normals(Mesh *mesh)
{
#ifdef DEBUG_TIME
- TIMEIT_START(BKE_mesh_calc_normals);
+ TIMEIT_START_AVERAGED(BKE_mesh_calc_normals);
#endif
BKE_mesh_calc_normals_poly(mesh->mvert, NULL, mesh->totvert,
mesh->mloop, mesh->mpoly, mesh->totloop, mesh->totpoly,
NULL, false);
#ifdef DEBUG_TIME
- TIMEIT_END(BKE_mesh_calc_normals);
+ TIMEIT_END_AVERAGED(BKE_mesh_calc_normals);
#endif
}
@@ -319,10 +350,14 @@ void BKE_mesh_calc_normals_tessface(
const MFace *mfaces, int numFaces,
float (*r_faceNors)[3])
{
- float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms");
- float (*fnors)[3] = (r_faceNors) ? r_faceNors : MEM_callocN(sizeof(*fnors) * (size_t)numFaces, "meshnormals");
+ float (*tnorms)[3] = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms");
+ float (*fnors)[3] = (r_faceNors) ? r_faceNors : MEM_calloc_arrayN((size_t)numFaces, sizeof(*fnors), "meshnormals");
int i;
+ if (!tnorms || !fnors) {
+ goto cleanup;
+ }
+
for (i = 0; i < numFaces; i++) {
const MFace *mf = &mfaces[i];
float *f_no = fnors[i];
@@ -334,8 +369,9 @@ void BKE_mesh_calc_normals_tessface(
else
normal_tri_v3(f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co);
- accumulate_vertex_normals(tnorms[mf->v1], tnorms[mf->v2], tnorms[mf->v3], n4,
- f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co, c4);
+ accumulate_vertex_normals_v3(
+ tnorms[mf->v1], tnorms[mf->v2], tnorms[mf->v3], n4,
+ f_no, mverts[mf->v1].co, mverts[mf->v2].co, mverts[mf->v3].co, c4);
}
/* following Mesh convention; we use vertex coordinate itself for normal in this case */
@@ -350,6 +386,7 @@ void BKE_mesh_calc_normals_tessface(
normal_float_to_short_v3(mv->no, no);
}
+cleanup:
MEM_freeN(tnorms);
if (fnors != r_faceNors)
@@ -362,10 +399,14 @@ void BKE_mesh_calc_normals_looptri(
const MLoopTri *looptri, int looptri_num,
float (*r_tri_nors)[3])
{
- float (*tnorms)[3] = MEM_callocN(sizeof(*tnorms) * (size_t)numVerts, "tnorms");
- float (*fnors)[3] = (r_tri_nors) ? r_tri_nors : MEM_callocN(sizeof(*fnors) * (size_t)looptri_num, "meshnormals");
+ float (*tnorms)[3] = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tnorms), "tnorms");
+ float (*fnors)[3] = (r_tri_nors) ? r_tri_nors : MEM_calloc_arrayN((size_t)looptri_num, sizeof(*fnors), "meshnormals");
int i;
+ if (!tnorms || !fnors) {
+ goto cleanup;
+ }
+
for (i = 0; i < looptri_num; i++) {
const MLoopTri *lt = &looptri[i];
float *f_no = fnors[i];
@@ -379,7 +420,7 @@ void BKE_mesh_calc_normals_looptri(
f_no,
mverts[vtri[0]].co, mverts[vtri[1]].co, mverts[vtri[2]].co);
- accumulate_vertex_normals_tri(
+ accumulate_vertex_normals_tri_v3(
tnorms[vtri[0]], tnorms[vtri[1]], tnorms[vtri[2]],
f_no, mverts[vtri[0]].co, mverts[vtri[1]].co, mverts[vtri[2]].co);
}
@@ -396,13 +437,14 @@ void BKE_mesh_calc_normals_looptri(
normal_float_to_short_v3(mv->no, no);
}
+cleanup:
MEM_freeN(tnorms);
if (fnors != r_tri_nors)
MEM_freeN(fnors);
}
-void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoops)
+void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoops, const char data_type)
{
if (!(lnors_spacearr->lspacearr && lnors_spacearr->loops_pool)) {
MemArena *mem;
@@ -414,6 +456,8 @@ void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr, const int numLoo
lnors_spacearr->lspacearr = BLI_memarena_calloc(mem, sizeof(MLoopNorSpace *) * (size_t)numLoops);
lnors_spacearr->loops_pool = BLI_memarena_alloc(mem, sizeof(LinkNode) * (size_t)numLoops);
}
+ BLI_assert(ELEM(data_type, MLNOR_SPACEARR_BMLOOP_PTR, MLNOR_SPACEARR_LOOP_INDEX));
+ lnors_spacearr->data_type = data_type;
}
void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr)
@@ -507,12 +551,32 @@ void BKE_lnor_space_define(MLoopNorSpace *lnor_space, const float lnor[3],
}
}
-void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space, const int ml_index,
- const bool do_add_loop)
+/**
+ * Add a new given loop to given lnor_space.
+ * Depending on \a lnor_space->data_type, we expect \a bm_loop to be a pointer to BMLoop struct (in case of BMLOOP_PTR),
+ * or NULL (in case of LOOP_INDEX), loop index is then stored in pointer.
+ * If \a is_single is set, the BMLoop or loop index is directly stored in \a lnor_space->loops pointer (since there
+ * is only one loop in this fan), else it is added to the linked list of loops in the fan.
+ */
+void BKE_lnor_space_add_loop(
+ MLoopNorSpaceArray *lnors_spacearr, MLoopNorSpace *lnor_space,
+ const int ml_index, void *bm_loop, const bool is_single)
{
+ BLI_assert((lnors_spacearr->data_type == MLNOR_SPACEARR_LOOP_INDEX && bm_loop == NULL) ||
+ (lnors_spacearr->data_type == MLNOR_SPACEARR_BMLOOP_PTR && bm_loop != NULL));
+
lnors_spacearr->lspacearr[ml_index] = lnor_space;
- if (do_add_loop) {
- BLI_linklist_prepend_nlink(&lnor_space->loops, SET_INT_IN_POINTER(ml_index), &lnors_spacearr->loops_pool[ml_index]);
+ if (bm_loop == NULL) {
+ bm_loop = SET_INT_IN_POINTER(ml_index);
+ }
+ if (is_single) {
+ BLI_assert(lnor_space->loops == NULL);
+ lnor_space->flags |= MLNOR_SPACE_IS_SINGLE;
+ lnor_space->loops = bm_loop;
+ }
+ else {
+ BLI_assert((lnor_space->flags & MLNOR_SPACE_IS_SINGLE) == 0);
+ BLI_linklist_prepend_nlink(&lnor_space->loops, bm_loop, &lnors_spacearr->loops_pool[ml_index]);
}
}
@@ -630,7 +694,6 @@ typedef struct LoopSplitTaskDataCommon {
* Note we do not need to protect it, though, since two different tasks will *always* affect different
* elements in the arrays. */
MLoopNorSpaceArray *lnors_spacearr;
- BLI_bitmap *sharp_verts;
float (*loopnors)[3];
short (*clnors_data)[2];
@@ -639,15 +702,13 @@ typedef struct LoopSplitTaskDataCommon {
const MEdge *medges;
const MLoop *mloops;
const MPoly *mpolys;
- const int (*edge_to_loops)[2];
- const int *loop_to_poly;
+ int (*edge_to_loops)[2];
+ int *loop_to_poly;
const float (*polynors)[3];
+ int numEdges;
+ int numLoops;
int numPolys;
-
- /* ***** Workers communication. ***** */
- ThreadQueue *task_queue;
-
} LoopSplitTaskDataCommon;
#define INDEX_UNSET INT_MIN
@@ -655,6 +716,197 @@ typedef struct LoopSplitTaskDataCommon {
/* See comment about edge_to_loops below. */
#define IS_EDGE_SHARP(_e2l) (ELEM((_e2l)[1], INDEX_UNSET, INDEX_INVALID))
+static void mesh_edges_sharp_tag(
+ LoopSplitTaskDataCommon *data,
+ const bool check_angle, const float split_angle, const bool do_sharp_edges_tag)
+{
+ const MVert *mverts = data->mverts;
+ const MEdge *medges = data->medges;
+ const MLoop *mloops = data->mloops;
+
+ const MPoly *mpolys = data->mpolys;
+
+ const int numEdges = data->numEdges;
+ const int numPolys = data->numPolys;
+
+ float (*loopnors)[3] = data->loopnors; /* Note: loopnors may be NULL here. */
+ const float (*polynors)[3] = data->polynors;
+
+ int (*edge_to_loops)[2] = data->edge_to_loops;
+ int *loop_to_poly = data->loop_to_poly;
+
+ BLI_bitmap *sharp_edges = do_sharp_edges_tag ? BLI_BITMAP_NEW(numEdges, __func__) : NULL;
+
+ const MPoly *mp;
+ int mp_index;
+
+ const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
+
+ for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
+ const MLoop *ml_curr;
+ int *e2l;
+ int ml_curr_index = mp->loopstart;
+ const int ml_last_index = (ml_curr_index + mp->totloop) - 1;
+
+ ml_curr = &mloops[ml_curr_index];
+
+ for (; ml_curr_index <= ml_last_index; ml_curr++, ml_curr_index++) {
+ e2l = edge_to_loops[ml_curr->e];
+
+ loop_to_poly[ml_curr_index] = mp_index;
+
+ /* Pre-populate all loop normals as if their verts were all-smooth, this way we don't have to compute
+ * those later!
+ */
+ if (loopnors) {
+ normal_short_to_float_v3(loopnors[ml_curr_index], mverts[ml_curr->v].no);
+ }
+
+ /* Check whether current edge might be smooth or sharp */
+ if ((e2l[0] | e2l[1]) == 0) {
+ /* 'Empty' edge until now, set e2l[0] (and e2l[1] to INDEX_UNSET to tag it as unset). */
+ e2l[0] = ml_curr_index;
+ /* We have to check this here too, else we might miss some flat faces!!! */
+ e2l[1] = (mp->flag & ME_SMOOTH) ? INDEX_UNSET : INDEX_INVALID;
+ }
+ else if (e2l[1] == INDEX_UNSET) {
+ const bool is_angle_sharp = (check_angle &&
+ dot_v3v3(polynors[loop_to_poly[e2l[0]]], polynors[mp_index]) < split_angle_cos);
+
+ /* Second loop using this edge, time to test its sharpness.
+ * An edge is sharp if it is tagged as such, or its face is not smooth,
+ * or both poly have opposed (flipped) normals, i.e. both loops on the same edge share the same vertex,
+ * or angle between both its polys' normals is above split_angle value.
+ */
+ if (!(mp->flag & ME_SMOOTH) || (medges[ml_curr->e].flag & ME_SHARP) ||
+ ml_curr->v == mloops[e2l[0]].v ||
+ is_angle_sharp)
+ {
+ /* Note: we are sure that loop != 0 here ;) */
+ e2l[1] = INDEX_INVALID;
+
+ /* We want to avoid tagging edges as sharp when it is already defined as such by
+ * other causes than angle threshold... */
+ if (do_sharp_edges_tag && is_angle_sharp) {
+ BLI_BITMAP_SET(sharp_edges, ml_curr->e, true);
+ }
+ }
+ else {
+ e2l[1] = ml_curr_index;
+ }
+ }
+ else if (!IS_EDGE_SHARP(e2l)) {
+ /* More than two loops using this edge, tag as sharp if not yet done. */
+ e2l[1] = INDEX_INVALID;
+
+ /* We want to avoid tagging edges as sharp when it is already defined as such by
+ * other causes than angle threshold... */
+ if (do_sharp_edges_tag) {
+ BLI_BITMAP_SET(sharp_edges, ml_curr->e, false);
+ }
+ }
+ /* Else, edge is already 'disqualified' (i.e. sharp)! */
+ }
+ }
+
+ /* If requested, do actual tagging of edges as sharp in another loop. */
+ if (do_sharp_edges_tag) {
+ MEdge *me;
+ int me_index;
+ for (me = (MEdge *)medges, me_index = 0; me_index < numEdges; me++, me_index++) {
+ if (BLI_BITMAP_TEST(sharp_edges, me_index)) {
+ me->flag |= ME_SHARP;
+ }
+ }
+
+ MEM_freeN(sharp_edges);
+ }
+}
+
+/** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
+ *
+ * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
+ */
+void BKE_edges_sharp_from_angle_set(
+ const struct MVert *mverts, const int UNUSED(numVerts),
+ struct MEdge *medges, const int numEdges,
+ struct MLoop *mloops, const int numLoops,
+ struct MPoly *mpolys, const float (*polynors)[3], const int numPolys,
+ const float split_angle)
+{
+ if (split_angle >= (float)M_PI) {
+ /* Nothing to do! */
+ return;
+ }
+
+ /* Mapping edge -> loops. See BKE_mesh_normals_loop_split() for details. */
+ int (*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__);
+
+ /* Simple mapping from a loop to its polygon index. */
+ int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__);
+
+ LoopSplitTaskDataCommon common_data = {
+ .mverts = mverts,
+ .medges = medges,
+ .mloops = mloops,
+ .mpolys = mpolys,
+ .edge_to_loops = edge_to_loops,
+ .loop_to_poly = loop_to_poly,
+ .polynors = polynors,
+ .numEdges = numEdges,
+ .numPolys = numPolys,
+ };
+
+ mesh_edges_sharp_tag(&common_data, true, split_angle, true);
+
+ MEM_freeN(edge_to_loops);
+ MEM_freeN(loop_to_poly);
+}
+
+void BKE_mesh_loop_manifold_fan_around_vert_next(
+ const MLoop *mloops, const MPoly *mpolys,
+ const int *loop_to_poly, const int *e2lfan_curr, const uint mv_pivot_index,
+ const MLoop **r_mlfan_curr, int *r_mlfan_curr_index, int *r_mlfan_vert_index, int *r_mpfan_curr_index)
+{
+ const MLoop *mlfan_next;
+ const MPoly *mpfan_next;
+
+ /* Warning! This is rather complex!
+ * We have to find our next edge around the vertex (fan mode).
+ * First we find the next loop, which is either previous or next to mlfan_curr_index, depending
+ * whether both loops using current edge are in the same direction or not, and whether
+ * mlfan_curr_index actually uses the vertex we are fanning around!
+ * mlfan_curr_index is the index of mlfan_next here, and mlfan_next is not the real next one
+ * (i.e. not the future mlfan_curr)...
+ */
+ *r_mlfan_curr_index = (e2lfan_curr[0] == *r_mlfan_curr_index) ? e2lfan_curr[1] : e2lfan_curr[0];
+ *r_mpfan_curr_index = loop_to_poly[*r_mlfan_curr_index];
+
+ BLI_assert(*r_mlfan_curr_index >= 0);
+ BLI_assert(*r_mpfan_curr_index >= 0);
+
+ mlfan_next = &mloops[*r_mlfan_curr_index];
+ mpfan_next = &mpolys[*r_mpfan_curr_index];
+ if (((*r_mlfan_curr)->v == mlfan_next->v && (*r_mlfan_curr)->v == mv_pivot_index) ||
+ ((*r_mlfan_curr)->v != mlfan_next->v && (*r_mlfan_curr)->v != mv_pivot_index))
+ {
+ /* We need the previous loop, but current one is our vertex's loop. */
+ *r_mlfan_vert_index = *r_mlfan_curr_index;
+ if (--(*r_mlfan_curr_index) < mpfan_next->loopstart) {
+ *r_mlfan_curr_index = mpfan_next->loopstart + mpfan_next->totloop - 1;
+ }
+ }
+ else {
+ /* We need the next loop, which is also our vertex's loop. */
+ if (++(*r_mlfan_curr_index) >= mpfan_next->loopstart + mpfan_next->totloop) {
+ *r_mlfan_curr_index = mpfan_next->loopstart;
+ }
+ *r_mlfan_vert_index = *r_mlfan_curr_index;
+ }
+ *r_mlfan_curr = &mloops[*r_mlfan_curr_index];
+ /* And now we are back in sync, mlfan_curr_index is the index of mlfan_curr! Pff! */
+}
+
static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopSplitTaskData *data)
{
MLoopNorSpaceArray *lnors_spacearr = common_data->lnors_spacearr;
@@ -680,7 +932,7 @@ static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopS
*/
copy_v3_v3(*lnor, polynors[mp_index]);
- /* printf("BASIC: handling loop %d / edge %d / vert %d / poly %d\n", ml_curr_index, ml_curr->e, ml_curr->v, mp_index); */
+// printf("BASIC: handling loop %d / edge %d / vert %d / poly %d\n", ml_curr_index, ml_curr->e, ml_curr->v, mp_index);
/* If needed, generate this (simple!) lnor space. */
if (lnors_spacearr) {
@@ -700,7 +952,7 @@ static void split_loop_nor_single_do(LoopSplitTaskDataCommon *common_data, LoopS
BKE_lnor_space_define(lnor_space, *lnor, vec_curr, vec_prev, NULL);
/* We know there is only one loop in this space, no need to create a linklist in this case... */
- BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, false);
+ BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, ml_curr_index, NULL, true);
if (clnors_data) {
BKE_lnor_space_custom_data_to_normal(lnor_space, clnors_data[ml_curr_index], *lnor);
@@ -747,8 +999,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli
const MEdge *me_org = &medges[ml_curr->e]; /* ml_curr would be mlfan_prev if we needed that one */
const int *e2lfan_curr;
float vec_curr[3], vec_prev[3], vec_org[3];
- const MLoop *mlfan_curr, *mlfan_next;
- const MPoly *mpfan_next;
+ const MLoop *mlfan_curr;
float lnor[3] = {0.0f, 0.0f, 0.0f};
/* mlfan_vert_index: the loop of our current edge might not be the loop of our current vertex! */
int mlfan_curr_index, mlfan_vert_index, mpfan_curr_index;
@@ -787,7 +1038,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli
}
}
- /* printf("FAN: vert %d, start edge %d\n", mv_pivot_index, ml_curr->e); */
+// printf("FAN: vert %d, start edge %d\n", mv_pivot_index, ml_curr->e);
while (true) {
const MEdge *me_curr = &medges[mlfan_curr->e];
@@ -803,10 +1054,10 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli
normalize_v3(vec_curr);
}
- /* printf("\thandling edge %d / loop %d\n", mlfan_curr->e, mlfan_curr_index); */
+// printf("\thandling edge %d / loop %d\n", mlfan_curr->e, mlfan_curr_index);
{
- /* Code similar to accumulate_vertex_normals_poly. */
+ /* Code similar to accumulate_vertex_normals_poly_v3. */
/* Calculate angle between the two poly edges incident on this vertex. */
const float fac = saacos(dot_v3v3(vec_curr, vec_prev));
/* Accumulate */
@@ -834,7 +1085,7 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli
if (lnors_spacearr) {
/* Assign current lnor space to current 'vertex' loop. */
- BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, mlfan_vert_index, true);
+ BKE_lnor_space_add_loop(lnors_spacearr, lnor_space, mlfan_vert_index, NULL, false);
if (me_curr != me_org) {
/* We store here all edges-normalized vectors processed. */
BLI_stack_push(edge_vectors, vec_curr);
@@ -845,46 +1096,16 @@ static void split_loop_nor_fan_do(LoopSplitTaskDataCommon *common_data, LoopSpli
/* Current edge is sharp and we have finished with this fan of faces around this vert,
* or this vert is smooth, and we have completed a full turn around it.
*/
- /* printf("FAN: Finished!\n"); */
+// printf("FAN: Finished!\n");
break;
}
copy_v3_v3(vec_prev, vec_curr);
- /* Warning! This is rather complex!
- * We have to find our next edge around the vertex (fan mode).
- * First we find the next loop, which is either previous or next to mlfan_curr_index, depending
- * whether both loops using current edge are in the same direction or not, and whether
- * mlfan_curr_index actually uses the vertex we are fanning around!
- * mlfan_curr_index is the index of mlfan_next here, and mlfan_next is not the real next one
- * (i.e. not the future mlfan_curr)...
- */
- mlfan_curr_index = (e2lfan_curr[0] == mlfan_curr_index) ? e2lfan_curr[1] : e2lfan_curr[0];
- mpfan_curr_index = loop_to_poly[mlfan_curr_index];
-
- BLI_assert(mlfan_curr_index >= 0);
- BLI_assert(mpfan_curr_index >= 0);
-
- mlfan_next = &mloops[mlfan_curr_index];
- mpfan_next = &mpolys[mpfan_curr_index];
- if ((mlfan_curr->v == mlfan_next->v && mlfan_curr->v == mv_pivot_index) ||
- (mlfan_curr->v != mlfan_next->v && mlfan_curr->v != mv_pivot_index))
- {
- /* We need the previous loop, but current one is our vertex's loop. */
- mlfan_vert_index = mlfan_curr_index;
- if (--mlfan_curr_index < mpfan_next->loopstart) {
- mlfan_curr_index = mpfan_next->loopstart + mpfan_next->totloop - 1;
- }
- }
- else {
- /* We need the next loop, which is also our vertex's loop. */
- if (++mlfan_curr_index >= mpfan_next->loopstart + mpfan_next->totloop) {
- mlfan_curr_index = mpfan_next->loopstart;
- }
- mlfan_vert_index = mlfan_curr_index;
- }
- mlfan_curr = &mloops[mlfan_curr_index];
- /* And now we are back in sync, mlfan_curr_index is the index of mlfan_curr! Pff! */
+ /* Find next loop of the smooth fan. */
+ BKE_mesh_loop_manifold_fan_around_vert_next(
+ mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index,
+ &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index);
e2lfan_curr = edge_to_loops[mlfan_curr->e];
}
@@ -955,31 +1176,25 @@ static void loop_split_worker_do(
}
}
-static void loop_split_worker(TaskPool * __restrict UNUSED(pool), void *taskdata, int UNUSED(threadid))
+static void loop_split_worker(TaskPool * __restrict pool, void *taskdata, int UNUSED(threadid))
{
- LoopSplitTaskDataCommon *common_data = taskdata;
- LoopSplitTaskData *data_buff;
+ LoopSplitTaskDataCommon *common_data = BLI_task_pool_userdata(pool);
+ LoopSplitTaskData *data = taskdata;
/* Temp edge vectors stack, only used when computing lnor spacearr. */
BLI_Stack *edge_vectors = common_data->lnors_spacearr ? BLI_stack_new(sizeof(float[3]), __func__) : NULL;
#ifdef DEBUG_TIME
- TIMEIT_START(loop_split_worker);
+ TIMEIT_START_AVERAGED(loop_split_worker);
#endif
- while ((data_buff = BLI_thread_queue_pop(common_data->task_queue))) {
- LoopSplitTaskData *data = data_buff;
- int i;
-
- for (i = 0; i < LOOP_SPLIT_TASK_BLOCK_SIZE; i++, data++) {
- /* A NULL ml_curr is used to tag ended data! */
- if (data->ml_curr == NULL) {
- break;
- }
- loop_split_worker_do(common_data, data, edge_vectors);
+ for (int i = 0; i < LOOP_SPLIT_TASK_BLOCK_SIZE; i++, data++) {
+ /* A NULL ml_curr is used to tag ended data! */
+ if (data->ml_curr == NULL) {
+ break;
}
- MEM_freeN(data_buff);
+ loop_split_worker_do(common_data, data, edge_vectors);
}
if (edge_vectors) {
@@ -987,49 +1202,117 @@ static void loop_split_worker(TaskPool * __restrict UNUSED(pool), void *taskdata
}
#ifdef DEBUG_TIME
- TIMEIT_END(loop_split_worker);
+ TIMEIT_END_AVERAGED(loop_split_worker);
#endif
}
-/* Note we use data_buff to detect whether we are in threaded context or not, in later case it is NULL. */
-static void loop_split_generator_do(LoopSplitTaskDataCommon *common_data, const bool threaded)
+/* Check whether gievn loop is part of an unknown-so-far cyclic smooth fan, or not.
+ * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once. */
+static bool loop_split_generator_check_cyclic_smooth_fan(
+ const MLoop *mloops, const MPoly *mpolys,
+ const int (*edge_to_loops)[2], const int *loop_to_poly, const int *e2l_prev, BLI_bitmap *skip_loops,
+ const MLoop *ml_curr, const MLoop *ml_prev, const int ml_curr_index, const int ml_prev_index,
+ const int mp_curr_index)
+{
+ const unsigned int mv_pivot_index = ml_curr->v; /* The vertex we are "fanning" around! */
+ const int *e2lfan_curr;
+ const MLoop *mlfan_curr;
+ /* mlfan_vert_index: the loop of our current edge might not be the loop of our current vertex! */
+ int mlfan_curr_index, mlfan_vert_index, mpfan_curr_index;
+
+ e2lfan_curr = e2l_prev;
+ if (IS_EDGE_SHARP(e2lfan_curr)) {
+ /* Sharp loop, so not a cyclic smooth fan... */
+ return false;
+ }
+
+ mlfan_curr = ml_prev;
+ mlfan_curr_index = ml_prev_index;
+ mlfan_vert_index = ml_curr_index;
+ mpfan_curr_index = mp_curr_index;
+
+ BLI_assert(mlfan_curr_index >= 0);
+ BLI_assert(mlfan_vert_index >= 0);
+ BLI_assert(mpfan_curr_index >= 0);
+
+ BLI_assert(!BLI_BITMAP_TEST(skip_loops, mlfan_vert_index));
+ BLI_BITMAP_ENABLE(skip_loops, mlfan_vert_index);
+
+ while (true) {
+ /* Find next loop of the smooth fan. */
+ BKE_mesh_loop_manifold_fan_around_vert_next(
+ mloops, mpolys, loop_to_poly, e2lfan_curr, mv_pivot_index,
+ &mlfan_curr, &mlfan_curr_index, &mlfan_vert_index, &mpfan_curr_index);
+
+ e2lfan_curr = edge_to_loops[mlfan_curr->e];
+
+ if (IS_EDGE_SHARP(e2lfan_curr)) {
+ /* Sharp loop/edge, so not a cyclic smooth fan... */
+ return false;
+ }
+ /* Smooth loop/edge... */
+ else if (BLI_BITMAP_TEST(skip_loops, mlfan_vert_index)) {
+ if (mlfan_vert_index == ml_curr_index) {
+ /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
+ * use initial ml_curr/ml_prev edge as start for this smooth fan. */
+ return true;
+ }
+ /* ... already checked in some previous looping, we can abort. */
+ return false;
+ }
+ else {
+ /* ... we can skip it in future, and keep checking the smooth fan. */
+ BLI_BITMAP_ENABLE(skip_loops, mlfan_vert_index);
+ }
+ }
+}
+
+static void loop_split_generator(TaskPool *pool, LoopSplitTaskDataCommon *common_data)
{
MLoopNorSpaceArray *lnors_spacearr = common_data->lnors_spacearr;
- BLI_bitmap *sharp_verts = common_data->sharp_verts;
float (*loopnors)[3] = common_data->loopnors;
const MLoop *mloops = common_data->mloops;
const MPoly *mpolys = common_data->mpolys;
+ const int *loop_to_poly = common_data->loop_to_poly;
const int (*edge_to_loops)[2] = common_data->edge_to_loops;
+ const int numLoops = common_data->numLoops;
const int numPolys = common_data->numPolys;
const MPoly *mp;
int mp_index;
- LoopSplitTaskData *data, *data_buff = NULL, data_mem;
+ const MLoop *ml_curr;
+ const MLoop *ml_prev;
+ int ml_curr_index;
+ int ml_prev_index;
+
+ BLI_bitmap *skip_loops = BLI_BITMAP_NEW(numLoops, __func__);
+
+ LoopSplitTaskData *data_buff = NULL;
int data_idx = 0;
/* Temp edge vectors stack, only used when computing lnor spacearr (and we are not multi-threading). */
- BLI_Stack *edge_vectors = (lnors_spacearr && !data_buff) ? BLI_stack_new(sizeof(float[3]), __func__) : NULL;
+ BLI_Stack *edge_vectors = NULL;
#ifdef DEBUG_TIME
- TIMEIT_START(loop_split_generator);
+ TIMEIT_START_AVERAGED(loop_split_generator);
#endif
- if (!threaded) {
- memset(&data_mem, 0, sizeof(data_mem));
- data = &data_mem;
+ if (!pool) {
+ if (lnors_spacearr) {
+ edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
+ }
}
/* We now know edges that can be smoothed (with their vector, and their two loops), and edges that will be hard!
* Now, time to generate the normals.
*/
for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
- const MLoop *ml_curr, *ml_prev;
float (*lnors)[3];
const int ml_last_index = (mp->loopstart + mp->totloop) - 1;
- int ml_curr_index = mp->loopstart;
- int ml_prev_index = ml_last_index;
+ ml_curr_index = mp->loopstart;
+ ml_prev_index = ml_last_index;
ml_curr = &mloops[ml_curr_index];
ml_prev = &mloops[ml_prev_index];
@@ -1039,23 +1322,40 @@ static void loop_split_generator_do(LoopSplitTaskDataCommon *common_data, const
const int *e2l_curr = edge_to_loops[ml_curr->e];
const int *e2l_prev = edge_to_loops[ml_prev->e];
- if (!IS_EDGE_SHARP(e2l_curr) && (!lnors_spacearr || BLI_BITMAP_TEST_BOOL(sharp_verts, ml_curr->v))) {
- /* A smooth edge, and we are not generating lnor_spacearr, or the related vertex is sharp.
- * We skip it because it is either:
- * - in the middle of a 'smooth fan' already computed (or that will be as soon as we hit
- * one of its ends, i.e. one of its two sharp edges), or...
- * - the related vertex is a "full smooth" one, in which case pre-populated normals from vertex
- * are just fine (or it has already be handled in a previous loop in case of needed lnors spacearr)!
- */
- /* printf("Skipping loop %d / edge %d / vert %d(%d)\n", ml_curr_index, ml_curr->e, ml_curr->v, sharp_verts[ml_curr->v]); */
+// printf("Checking loop %d / edge %u / vert %u (sharp edge: %d, skiploop: %d)...",
+// ml_curr_index, ml_curr->e, ml_curr->v, IS_EDGE_SHARP(e2l_curr), BLI_BITMAP_TEST_BOOL(skip_loops, ml_curr_index));
+
+ /* A smooth edge, we have to check for cyclic smooth fan case.
+ * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
+ * 'entry point', otherwise we can skip it. */
+ /* Note: In theory, we could make loop_split_generator_check_cyclic_smooth_fan() store
+ * mlfan_vert_index'es and edge indexes in two stacks, to avoid having to fan again around the vert during
+ * actual computation of clnor & clnorspace. However, this would complicate the code, add more memory usage,
+ * and despite its logical complexity, loop_manifold_fan_around_vert_next() is quite cheap in term of
+ * CPU cycles, so really think it's not worth it. */
+ if (!IS_EDGE_SHARP(e2l_curr) &&
+ (BLI_BITMAP_TEST(skip_loops, ml_curr_index) ||
+ !loop_split_generator_check_cyclic_smooth_fan(
+ mloops, mpolys, edge_to_loops, loop_to_poly, e2l_prev, skip_loops,
+ ml_curr, ml_prev, ml_curr_index, ml_prev_index, mp_index)))
+ {
+// printf("SKIPPING!\n");
}
else {
- if (threaded) {
+ LoopSplitTaskData *data, data_local;
+
+// printf("PROCESSING!\n");
+
+ if (pool) {
if (data_idx == 0) {
- data_buff = MEM_callocN(sizeof(*data_buff) * LOOP_SPLIT_TASK_BLOCK_SIZE, __func__);
+ data_buff = MEM_calloc_arrayN(LOOP_SPLIT_TASK_BLOCK_SIZE, sizeof(*data_buff), __func__);
}
data = &data_buff[data_idx];
}
+ else {
+ data = &data_local;
+ memset(data, 0, sizeof(*data));
+ }
if (IS_EDGE_SHARP(e2l_curr) && IS_EDGE_SHARP(e2l_prev)) {
data->lnor = lnors;
@@ -1091,22 +1391,18 @@ static void loop_split_generator_do(LoopSplitTaskDataCommon *common_data, const
data->mp_index = mp_index;
if (lnors_spacearr) {
data->lnor_space = BKE_lnor_space_create(lnors_spacearr);
- /* Tag related vertex as sharp, to avoid fanning around it again (in case it was a smooth one).
- * This *has* to be done outside of workers tasks! */
- BLI_BITMAP_ENABLE(sharp_verts, ml_curr->v);
}
}
- if (threaded) {
+ if (pool) {
data_idx++;
if (data_idx == LOOP_SPLIT_TASK_BLOCK_SIZE) {
- BLI_thread_queue_push(common_data->task_queue, data_buff);
+ BLI_task_pool_push(pool, loop_split_worker, data_buff, true, TASK_PRIORITY_LOW);
data_idx = 0;
}
}
else {
loop_split_worker_do(common_data, data, edge_vectors);
- memset(data, 0, sizeof(data_mem));
}
}
@@ -1115,41 +1411,30 @@ static void loop_split_generator_do(LoopSplitTaskDataCommon *common_data, const
}
}
- if (threaded) {
- /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, everything is fine. */
- if (LIKELY(data_idx)) {
- BLI_thread_queue_push(common_data->task_queue, data_buff);
- }
-
- /* This will signal all other worker threads to wake up and finish! */
- BLI_thread_queue_nowait(common_data->task_queue);
+ /* Last block of data... Since it is calloc'ed and we use first NULL item as stopper, everything is fine. */
+ if (pool && data_idx) {
+ BLI_task_pool_push(pool, loop_split_worker, data_buff, true, TASK_PRIORITY_LOW);
}
if (edge_vectors) {
BLI_stack_free(edge_vectors);
}
+ MEM_freeN(skip_loops);
#ifdef DEBUG_TIME
- TIMEIT_END(loop_split_generator);
+ TIMEIT_END_AVERAGED(loop_split_generator);
#endif
}
-static void loop_split_generator(TaskPool * __restrict UNUSED(pool), void *taskdata, int UNUSED(threadid))
-{
- LoopSplitTaskDataCommon *common_data = taskdata;
-
- loop_split_generator_do(common_data, true);
-}
-
/**
* Compute split normals, i.e. vertex normals associated with each poly (hence 'loop normals').
* Useful to materialize sharp edges (or non-smooth faces) without actually modifying the geometry (splitting edges).
*/
void BKE_mesh_normals_loop_split(
- const MVert *mverts, const int numVerts, MEdge *medges, const int numEdges,
+ const MVert *mverts, const int UNUSED(numVerts), MEdge *medges, const int numEdges,
MLoop *mloops, float (*r_loopnors)[3], const int numLoops,
MPoly *mpolys, const float (*polynors)[3], const int numPolys,
- const bool use_split_normals, float split_angle,
+ const bool use_split_normals, const float split_angle,
MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], int *r_loop_to_poly)
{
/* For now this is not supported. If we do not use split normals, we do not generate anything fancy! */
@@ -1184,8 +1469,6 @@ void BKE_mesh_normals_loop_split(
return;
}
- {
-
/* Mapping edge -> loops.
* If that edge is used by more than two loops (polys), it is always sharp (and tagged as such, see below).
* We also use the second loop index as a kind of flag: smooth edge: > 0,
@@ -1195,149 +1478,64 @@ void BKE_mesh_normals_loop_split(
* store the negated value of loop index instead of INDEX_INVALID to retrieve the real value later in code).
* Note also that lose edges always have both values set to 0!
*/
- int (*edge_to_loops)[2] = MEM_callocN(sizeof(int[2]) * (size_t)numEdges, __func__);
+ int (*edge_to_loops)[2] = MEM_calloc_arrayN((size_t)numEdges, sizeof(*edge_to_loops), __func__);
/* Simple mapping from a loop to its polygon index. */
- int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : MEM_mallocN(sizeof(int) * (size_t)numLoops, __func__);
+ int *loop_to_poly = r_loop_to_poly ? r_loop_to_poly : MEM_malloc_arrayN((size_t)numLoops, sizeof(*loop_to_poly), __func__);
- MPoly *mp;
- int mp_index, me_index;
- bool check_angle = (split_angle < (float)M_PI);
- int i;
+ /* When using custom loop normals, disable the angle feature! */
+ const bool check_angle = (split_angle < (float)M_PI) && (clnors_data == NULL);
- BLI_bitmap *sharp_verts = NULL;
MLoopNorSpaceArray _lnors_spacearr = {NULL};
- LoopSplitTaskDataCommon common_data = {NULL};
-
#ifdef DEBUG_TIME
- TIMEIT_START(BKE_mesh_normals_loop_split);
+ TIMEIT_START_AVERAGED(BKE_mesh_normals_loop_split);
#endif
- if (check_angle) {
- /* When using custom loop normals, disable the angle feature! */
- if (clnors_data) {
- check_angle = false;
- }
- else {
- split_angle = cosf(split_angle);
- }
- }
-
if (!r_lnors_spacearr && clnors_data) {
/* We need to compute lnor spacearr if some custom lnor data are given to us! */
r_lnors_spacearr = &_lnors_spacearr;
}
if (r_lnors_spacearr) {
- BKE_lnor_spacearr_init(r_lnors_spacearr, numLoops);
- sharp_verts = BLI_BITMAP_NEW((size_t)numVerts, __func__);
- }
-
- /* This first loop check which edges are actually smooth, and compute edge vectors. */
- for (mp = mpolys, mp_index = 0; mp_index < numPolys; mp++, mp_index++) {
- MLoop *ml_curr;
- int *e2l;
- int ml_curr_index = mp->loopstart;
- const int ml_last_index = (ml_curr_index + mp->totloop) - 1;
-
- ml_curr = &mloops[ml_curr_index];
-
- for (; ml_curr_index <= ml_last_index; ml_curr++, ml_curr_index++) {
- e2l = edge_to_loops[ml_curr->e];
-
- loop_to_poly[ml_curr_index] = mp_index;
-
- /* Pre-populate all loop normals as if their verts were all-smooth, this way we don't have to compute
- * those later!
- */
- normal_short_to_float_v3(r_loopnors[ml_curr_index], mverts[ml_curr->v].no);
-
- /* Check whether current edge might be smooth or sharp */
- if ((e2l[0] | e2l[1]) == 0) {
- /* 'Empty' edge until now, set e2l[0] (and e2l[1] to INDEX_UNSET to tag it as unset). */
- e2l[0] = ml_curr_index;
- /* We have to check this here too, else we might miss some flat faces!!! */
- e2l[1] = (mp->flag & ME_SMOOTH) ? INDEX_UNSET : INDEX_INVALID;
- }
- else if (e2l[1] == INDEX_UNSET) {
- /* Second loop using this edge, time to test its sharpness.
- * An edge is sharp if it is tagged as such, or its face is not smooth,
- * or both poly have opposed (flipped) normals, i.e. both loops on the same edge share the same vertex,
- * or angle between both its polys' normals is above split_angle value.
- */
- if (!(mp->flag & ME_SMOOTH) || (medges[ml_curr->e].flag & ME_SHARP) ||
- ml_curr->v == mloops[e2l[0]].v ||
- (check_angle && dot_v3v3(polynors[loop_to_poly[e2l[0]]], polynors[mp_index]) < split_angle))
- {
- /* Note: we are sure that loop != 0 here ;) */
- e2l[1] = INDEX_INVALID;
- }
- else {
- e2l[1] = ml_curr_index;
- }
- }
- else if (!IS_EDGE_SHARP(e2l)) {
- /* More than two loops using this edge, tag as sharp if not yet done. */
- e2l[1] = INDEX_INVALID;
- }
- /* Else, edge is already 'disqualified' (i.e. sharp)! */
- }
- }
-
- if (r_lnors_spacearr) {
- /* Tag vertices that have at least one sharp edge as 'sharp' (used for the lnor spacearr computation).
- * XXX This third loop over edges is a bit disappointing, could not find any other way yet.
- * Not really performance-critical anyway.
- */
- for (me_index = 0; me_index < numEdges; me_index++) {
- const int *e2l = edge_to_loops[me_index];
- const MEdge *me = &medges[me_index];
- if (IS_EDGE_SHARP(e2l)) {
- BLI_BITMAP_ENABLE(sharp_verts, me->v1);
- BLI_BITMAP_ENABLE(sharp_verts, me->v2);
- }
- }
+ BKE_lnor_spacearr_init(r_lnors_spacearr, numLoops, MLNOR_SPACEARR_LOOP_INDEX);
}
/* Init data common to all tasks. */
- common_data.lnors_spacearr = r_lnors_spacearr;
- common_data.loopnors = r_loopnors;
- common_data.clnors_data = clnors_data;
-
- common_data.mverts = mverts;
- common_data.medges = medges;
- common_data.mloops = mloops;
- common_data.mpolys = mpolys;
- common_data.sharp_verts = sharp_verts;
- common_data.edge_to_loops = (const int(*)[2])edge_to_loops;
- common_data.loop_to_poly = loop_to_poly;
- common_data.polynors = polynors;
- common_data.numPolys = numPolys;
+ LoopSplitTaskDataCommon common_data = {
+ .lnors_spacearr = r_lnors_spacearr,
+ .loopnors = r_loopnors,
+ .clnors_data = clnors_data,
+ .mverts = mverts,
+ .medges = medges,
+ .mloops = mloops,
+ .mpolys = mpolys,
+ .edge_to_loops = edge_to_loops,
+ .loop_to_poly = loop_to_poly,
+ .polynors = polynors,
+ .numEdges = numEdges,
+ .numLoops = numLoops,
+ .numPolys = numPolys,
+ };
+
+ /* This first loop check which edges are actually smooth, and compute edge vectors. */
+ mesh_edges_sharp_tag(&common_data, check_angle, split_angle, false);
if (numLoops < LOOP_SPLIT_TASK_BLOCK_SIZE * 8) {
/* Not enough loops to be worth the whole threading overhead... */
- loop_split_generator_do(&common_data, false);
+ loop_split_generator(NULL, &common_data);
}
else {
TaskScheduler *task_scheduler;
TaskPool *task_pool;
- int nbr_workers;
-
- common_data.task_queue = BLI_thread_queue_init();
task_scheduler = BLI_task_scheduler_get();
- task_pool = BLI_task_pool_create(task_scheduler, NULL);
+ task_pool = BLI_task_pool_create(task_scheduler, &common_data);
+
+ loop_split_generator(task_pool, &common_data);
- nbr_workers = max_ii(2, BLI_task_scheduler_num_threads(task_scheduler));
- for (i = 1; i < nbr_workers; i++) {
- BLI_task_pool_push(task_pool, loop_split_worker, &common_data, false, TASK_PRIORITY_HIGH);
- }
- BLI_task_pool_push(task_pool, loop_split_generator, &common_data, false, TASK_PRIORITY_HIGH);
BLI_task_pool_work_and_wait(task_pool);
BLI_task_pool_free(task_pool);
-
- BLI_thread_queue_free(common_data.task_queue);
}
MEM_freeN(edge_to_loops);
@@ -1346,17 +1544,14 @@ void BKE_mesh_normals_loop_split(
}
if (r_lnors_spacearr) {
- MEM_freeN(sharp_verts);
if (r_lnors_spacearr == &_lnors_spacearr) {
BKE_lnor_spacearr_free(r_lnors_spacearr);
}
}
#ifdef DEBUG_TIME
- TIMEIT_END(BKE_mesh_normals_loop_split);
+ TIMEIT_END_AVERAGED(BKE_mesh_normals_loop_split);
#endif
-
- }
}
#undef INDEX_UNSET
@@ -1386,8 +1581,8 @@ static void mesh_normals_loop_custom_set(
*/
MLoopNorSpaceArray lnors_spacearr = {NULL};
BLI_bitmap *done_loops = BLI_BITMAP_NEW((size_t)numLoops, __func__);
- float (*lnors)[3] = MEM_callocN(sizeof(*lnors) * (size_t)numLoops, __func__);
- int *loop_to_poly = MEM_mallocN(sizeof(int) * (size_t)numLoops, __func__);
+ float (*lnors)[3] = MEM_calloc_arrayN((size_t)numLoops, sizeof(*lnors), __func__);
+ int *loop_to_poly = MEM_malloc_arrayN((size_t)numLoops, sizeof(int), __func__);
/* In this case we always consider split nors as ON, and do not want to use angle to define smooth fans! */
const bool use_split_normals = true;
const float split_angle = (float)M_PI;
@@ -1416,6 +1611,8 @@ static void mesh_normals_loop_custom_set(
}
}
+ BLI_assert(lnors_spacearr.data_type == MLNOR_SPACEARR_LOOP_INDEX);
+
/* Now, check each current smooth fan (one lnor space per smooth fan!), and if all its matching custom lnors
* are not (enough) equal, add sharp edges as needed.
* This way, next time we run BKE_mesh_normals_loop_split(), we'll get lnor spacearr/smooth fans matching
@@ -1439,7 +1636,7 @@ static void mesh_normals_loop_custom_set(
if (!BLI_BITMAP_TEST(done_loops, i)) {
/* Notes:
- * * In case of mono-loop smooth fan, loops is NULL, so everything is fine (we have nothing to do).
+ * * In case of mono-loop smooth fan, we have nothing to do.
* * Loops in this linklist are ordered (in reversed order compared to how they were discovered by
* BKE_mesh_normals_loop_split(), but this is not a problem). Which means if we find a
* mismatching clnor, we know all remaining loops will have to be in a new, different smooth fan/
@@ -1447,6 +1644,11 @@ static void mesh_normals_loop_custom_set(
* * In smooth fan case, we compare each clnor against a ref one, to avoid small differences adding
* up into a real big one in the end!
*/
+ if (lnors_spacearr.lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) {
+ BLI_BITMAP_ENABLE(done_loops, i);
+ continue;
+ }
+
LinkNode *loops = lnors_spacearr.lspacearr[i]->loops;
MLoop *prev_ml = NULL;
const float *org_nor = NULL;
@@ -1494,9 +1696,6 @@ static void mesh_normals_loop_custom_set(
medges[(prev_ml->e == mlp->e) ? prev_ml->e : ml->e].flag |= ME_SHARP;
}
}
-
- /* For single loops, where lnors_spacearr.lspacearr[i]->loops is NULL. */
- BLI_BITMAP_ENABLE(done_loops, i);
}
}
@@ -1526,7 +1725,15 @@ static void mesh_normals_loop_custom_set(
* computed 2D factors).
*/
LinkNode *loops = lnors_spacearr.lspacearr[i]->loops;
- if (loops) {
+ if (lnors_spacearr.lspacearr[i]->flags & MLNOR_SPACE_IS_SINGLE) {
+ BLI_assert(GET_INT_FROM_POINTER(loops) == i);
+ const int nidx = use_vertices ? (int)mloops[i].v : i;
+ float *nor = r_custom_loopnors[nidx];
+
+ BKE_lnor_space_custom_normal_to_data(lnors_spacearr.lspacearr[i], nor, r_clnors_data[i]);
+ BLI_BITMAP_DISABLE(done_loops, i);
+ }
+ else {
int nbr_nors = 0;
float avg_nor[3];
short clnor_data_tmp[2], *clnor_data;
@@ -1553,13 +1760,6 @@ static void mesh_normals_loop_custom_set(
clnor_data[1] = clnor_data_tmp[1];
}
}
- else {
- const int nidx = use_vertices ? (int)mloops[i].v : i;
- float *nor = r_custom_loopnors[nidx];
-
- BKE_lnor_space_custom_normal_to_data(lnors_spacearr.lspacearr[i], nor, r_clnors_data[i]);
- BLI_BITMAP_DISABLE(done_loops, i);
- }
}
}
@@ -1592,8 +1792,8 @@ void BKE_mesh_normals_loop_custom_from_vertices_set(
/**
* Computes average per-vertex normals from given custom loop normals.
*
- * @param clnors The computed custom loop normals.
- * @param r_vert_clnors The (already allocated) array where to store averaged per-vertex normals.
+ * \param clnors: The computed custom loop normals.
+ * \param r_vert_clnors: The (already allocated) array where to store averaged per-vertex normals.
*/
void BKE_mesh_normals_loop_to_vertex(
const int numVerts, const MLoop *mloops, const int numLoops,
@@ -1602,7 +1802,7 @@ void BKE_mesh_normals_loop_to_vertex(
const MLoop *ml;
int i;
- int *vert_loops_nbr = MEM_callocN(sizeof(*vert_loops_nbr) * (size_t)numVerts, __func__);
+ int *vert_loops_nbr = MEM_calloc_arrayN((size_t)numVerts, sizeof(*vert_loops_nbr), __func__);
copy_vn_fl((float *)r_vert_clnors, 3 * numVerts, 0.0f);
@@ -1956,8 +2156,66 @@ float BKE_mesh_calc_poly_area(
}
}
-/* note, results won't be correct if polygon is non-planar */
-static float mesh_calc_poly_planar_area_centroid(
+/**
+ * Calculate the volume and volume-weighted centroid of the volume formed by the polygon and the origin.
+ * Results will be negative if the origin is "outside" the polygon
+ * (+ve normal side), but the polygon may be non-planar with no effect.
+ *
+ * Method from:
+ * - http://forums.cgsociety.org/archive/index.php?t-756235.html
+ * - http://www.globalspec.com/reference/52702/203279/4-8-the-centroid-of-a-tetrahedron
+ *
+ * \note
+ * - Volume is 6x actual volume, and centroid is 4x actual volume-weighted centroid
+ * (so division can be done once at the end).
+ * - Results will have bias if polygon is non-planar.
+ * - The resulting volume will only be correct if the mesh is manifold and has consistent face winding
+ * (non-contiguous face normals or holes in the mesh surface).
+ */
+static float mesh_calc_poly_volume_centroid(
+ const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray,
+ float r_cent[3])
+{
+ const float *v_pivot, *v_step1;
+ float total_volume = 0.0f;
+
+ zero_v3(r_cent);
+
+ v_pivot = mvarray[loopstart[0].v].co;
+ v_step1 = mvarray[loopstart[1].v].co;
+
+ for (int i = 2; i < mpoly->totloop; i++) {
+ const float *v_step2 = mvarray[loopstart[i].v].co;
+
+ /* Calculate the 6x volume of the tetrahedron formed by the 3 vertices
+ * of the triangle and the origin as the fourth vertex */
+ float v_cross[3];
+ cross_v3_v3v3(v_cross, v_pivot, v_step1);
+ const float tetra_volume = dot_v3v3 (v_cross, v_step2);
+ total_volume += tetra_volume;
+
+ /* Calculate the centroid of the tetrahedron formed by the 3 vertices
+ * of the triangle and the origin as the fourth vertex.
+ * The centroid is simply the average of the 4 vertices.
+ *
+ * Note that the vector is 4x the actual centroid so the division can be done once at the end. */
+ for (uint j = 0; j < 3; j++) {
+ r_cent[j] += tetra_volume * (v_pivot[j] + v_step1[j] + v_step2[j]);
+ }
+
+ v_step1 = v_step2;
+ }
+
+ return total_volume;
+}
+
+/**
+ * \note
+ * - Results won't be correct if polygon is non-planar.
+ * - This has the advantage over #mesh_calc_poly_volume_centroid
+ * that it doesn't depend on solid geometry, instead it weights the surface by volume.
+ */
+static float mesh_calc_poly_area_centroid(
const MPoly *mpoly, const MLoop *loopstart, const MVert *mvarray,
float r_cent[3])
{
@@ -2102,7 +2360,7 @@ bool BKE_mesh_center_bounds(const Mesh *me, float r_cent[3])
return false;
}
-bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3])
+bool BKE_mesh_center_of_surface(const Mesh *me, float r_cent[3])
{
int i = me->totpoly;
MPoly *mpoly;
@@ -2114,7 +2372,7 @@ bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3])
/* calculate a weighted average of polygon centroids */
for (mpoly = me->mpoly; i--; mpoly++) {
- poly_area = mesh_calc_poly_planar_area_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent);
+ poly_area = mesh_calc_poly_area_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent);
madd_v3_v3fl(r_cent, poly_cent, poly_area);
total_area += poly_area;
@@ -2131,6 +2389,43 @@ bool BKE_mesh_center_centroid(const Mesh *me, float r_cent[3])
return (me->totpoly != 0);
}
+
+/**
+ * \note Mesh must be manifold with consistent face-winding, see #mesh_calc_poly_volume_centroid for details.
+ */
+bool BKE_mesh_center_of_volume(const Mesh *me, float r_cent[3])
+{
+ int i = me->totpoly;
+ MPoly *mpoly;
+ float poly_volume;
+ float total_volume = 0.0f;
+ float poly_cent[3];
+
+ zero_v3(r_cent);
+
+ /* calculate a weighted average of polyhedron centroids */
+ for (mpoly = me->mpoly; i--; mpoly++) {
+ poly_volume = mesh_calc_poly_volume_centroid(mpoly, me->mloop + mpoly->loopstart, me->mvert, poly_cent);
+
+ /* poly_cent is already volume-weighted, so no need to multiply by the volume */
+ add_v3_v3(r_cent, poly_cent);
+ total_volume += poly_volume;
+ }
+ /* otherwise we get NAN for 0 polys */
+ if (total_volume != 0.0f) {
+ /* multipy by 0.25 to get the correct centroid */
+ /* no need to divide volume by 6 as the centroid is weighted by 6x the volume, so it all cancels out */
+ mul_v3_fl(r_cent, 0.25f / total_volume);
+ }
+
+ /* this can happen for non-manifold objects, fallback to median */
+ if (UNLIKELY(!is_finite_v3(r_cent))) {
+ return BKE_mesh_center_median(me, r_cent);
+ }
+
+ return (me->totpoly != 0);
+}
+
/** \} */
@@ -2238,6 +2533,7 @@ void BKE_mesh_calc_volume(
}
}
+/** \} */
/* -------------------------------------------------------------------- */
@@ -2499,9 +2795,9 @@ int BKE_mesh_recalc_tessellation(
/* allocate the length of totfaces, avoid many small reallocs,
* if all faces are tri's it will be correct, quads == 2x allocs */
/* take care. we are _not_ calloc'ing so be sure to initialize each field */
- mface_to_poly_map = MEM_mallocN(sizeof(*mface_to_poly_map) * (size_t)looptri_num, __func__);
- mface = MEM_mallocN(sizeof(*mface) * (size_t)looptri_num, __func__);
- lindices = MEM_mallocN(sizeof(*lindices) * (size_t)looptri_num, __func__);
+ mface_to_poly_map = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*mface_to_poly_map), __func__);
+ mface = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*mface), __func__);
+ lindices = MEM_malloc_arrayN((size_t)looptri_num, sizeof(*lindices), __func__);
mface_index = 0;
mp = mpoly;
@@ -2617,7 +2913,7 @@ int BKE_mesh_recalc_tessellation(
mul_v2_m3v3(projverts[j], axis_mat, mvert[ml->v].co);
}
- BLI_polyfill_calc_arena((const float (*)[2])projverts, mp_totloop, 1, tris, arena);
+ BLI_polyfill_calc_arena(projverts, mp_totloop, 1, tris, arena);
/* apply fill */
for (j = 0; j < totfilltri; j++) {
@@ -2771,9 +3067,22 @@ void BKE_mesh_recalc_looptri(
}
else if (mp_totloop == 4) {
ML_TO_MLT(0, 1, 2);
+ MLoopTri *mlt_a = mlt;
mlooptri_index++;
ML_TO_MLT(0, 2, 3);
+ MLoopTri *mlt_b = mlt;
mlooptri_index++;
+
+ if (UNLIKELY(is_quad_flip_v3_first_third_fast(
+ mvert[mloop[mlt_a->tri[0]].v].co,
+ mvert[mloop[mlt_a->tri[1]].v].co,
+ mvert[mloop[mlt_a->tri[2]].v].co,
+ mvert[mloop[mlt_b->tri[2]].v].co)))
+ {
+ /* flip out of degenerate 0-2 state. */
+ mlt_a->tri[2] = mlt_b->tri[2];
+ mlt_b->tri[0] = mlt_a->tri[1];
+ }
}
#endif /* USE_TESSFACE_SPEEDUP */
else {
@@ -2816,7 +3125,7 @@ void BKE_mesh_recalc_looptri(
mul_v2_m3v3(projverts[j], axis_mat, mvert[ml->v].co);
}
- BLI_polyfill_calc_arena((const float (*)[2])projverts, mp_totloop, 1, tris, arena);
+ BLI_polyfill_calc_arena(projverts, mp_totloop, 1, tris, arena);
/* apply fill */
for (j = 0; j < totfilltri; j++) {
@@ -2881,7 +3190,7 @@ int BKE_mesh_mpoly_to_mface(struct CustomData *fdata, struct CustomData *ldata,
const bool hasLNor = CustomData_has_layer(ldata, CD_NORMAL);
/* over-alloc, ngons will be skipped */
- mface = MEM_mallocN(sizeof(*mface) * (size_t)totpoly, __func__);
+ mface = MEM_malloc_arrayN((size_t)totpoly, sizeof(*mface), __func__);
mpoly = CustomData_get_layer(pdata, CD_MPOLY);
mloop = CustomData_get_layer(ldata, CD_MLOOP);
@@ -3049,7 +3358,6 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata,
else {
const int side = (int)sqrtf((float)(fd->totdisp / corners));
const int side_sq = side * side;
- const size_t disps_size = sizeof(float[3]) * (size_t)side_sq;
for (i = 0; i < tot; i++, disps += side_sq, ld++) {
ld->totdisp = side_sq;
@@ -3058,12 +3366,12 @@ static void bm_corners_to_loops_ex(ID *id, CustomData *fdata, CustomData *ldata,
if (ld->disps)
MEM_freeN(ld->disps);
- ld->disps = MEM_mallocN(disps_size, "converted loop mdisps");
+ ld->disps = MEM_malloc_arrayN((size_t)side_sq, sizeof(float[3]), "converted loop mdisps");
if (fd->disps) {
- memcpy(ld->disps, disps, disps_size);
+ memcpy(ld->disps, disps, (size_t)side_sq * sizeof(float[3]));
}
else {
- memset(ld->disps, 0, disps_size);
+ memset(ld->disps, 0, (size_t)side_sq * sizeof(float[3]));
}
}
}
@@ -3125,7 +3433,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
CustomData_free(pdata, totpoly_i);
totpoly = totface_i;
- mpoly = MEM_callocN(sizeof(MPoly) * (size_t)totpoly, "mpoly converted");
+ mpoly = MEM_calloc_arrayN((size_t)totpoly, sizeof(MPoly), "mpoly converted");
CustomData_add_layer(pdata, CD_MPOLY, CD_ASSIGN, mpoly, totpoly);
numTex = CustomData_number_of_layers(fdata, CD_MTFACE);
@@ -3137,7 +3445,7 @@ void BKE_mesh_convert_mfaces_to_mpolys_ex(ID *id, CustomData *fdata, CustomData
totloop += mf->v4 ? 4 : 3;
}
- mloop = MEM_callocN(sizeof(MLoop) * (size_t)totloop, "mloop converted");
+ mloop = MEM_calloc_arrayN((size_t)totloop, sizeof(MLoop), "mloop converted");
CustomData_add_layer(ldata, CD_MLOOP, CD_ASSIGN, mloop, totloop);
@@ -3536,7 +3844,7 @@ void BKE_mesh_calc_relative_deform(
const MPoly *mp;
int i;
- int *vert_accum = MEM_callocN(sizeof(*vert_accum) * (size_t)totvert, __func__);
+ int *vert_accum = MEM_calloc_arrayN((size_t)totvert, sizeof(*vert_accum), __func__);
memset(vert_cos_new, '\0', sizeof(*vert_cos_new) * (size_t)totvert);
diff --git a/source/blender/blenkernel/intern/mesh_mapping.c b/source/blender/blenkernel/intern/mesh_mapping.c
index 8562988b5e1..0143125490e 100644
--- a/source/blender/blenkernel/intern/mesh_mapping.c
+++ b/source/blender/blenkernel/intern/mesh_mapping.c
@@ -117,7 +117,7 @@ UvVertMap *BKE_mesh_uv_vert_map_create(
}
if (use_winding) {
- winding[a] = cross_poly_v2((const float (*)[2])tf_uv, (unsigned int)nverts) > 0;
+ winding[a] = cross_poly_v2(tf_uv, (unsigned int)nverts) > 0;
}
}
}
@@ -165,7 +165,7 @@ UvVertMap *BKE_mesh_uv_vert_map_create(
vmap->vert[a] = newvlist;
}
- if (use_winding) {
+ if (use_winding) {
MEM_freeN(winding);
}
diff --git a/source/blender/blenkernel/intern/mesh_remap.c b/source/blender/blenkernel/intern/mesh_remap.c
index c5fa9b15896..0af4dae4506 100644
--- a/source/blender/blenkernel/intern/mesh_remap.c
+++ b/source/blender/blenkernel/intern/mesh_remap.c
@@ -36,7 +36,7 @@
#include "BLI_bitmap.h"
#include "BLI_math.h"
#include "BLI_memarena.h"
-#include "BLI_polyfill2d.h"
+#include "BLI_polyfill_2d.h"
#include "BLI_rand.h"
#include "BKE_bvhutils.h"
@@ -1184,7 +1184,6 @@ void BKE_mesh_remap_calc_loops_from_dm(
bool polys_allocated_src;
MPoly *polys_src = DM_get_poly_array(dm_src, &polys_allocated_src);
const int num_polys_src = dm_src->getNumPolys(dm_src);
- bool looptri_allocated_src = false;
const MLoopTri *looptri_src = NULL;
int num_looptri_src = 0;
@@ -1374,17 +1373,11 @@ void BKE_mesh_remap_calc_loops_from_dm(
if (dirty_tess_flag) {
dm_src->dirty &= ~dirty_tess_flag;
}
- DM_ensure_looptri(dm_src);
if (dirty_tess_flag) {
dm_src->dirty |= dirty_tess_flag;
}
- looptri_src = DM_get_looptri_array(
- dm_src,
- verts_src,
- polys_src, num_polys_src,
- loops_src, num_loops_src,
- &looptri_allocated_src);
+ looptri_src = dm_src->getLoopTriArray(dm_src);
num_looptri_src = dm_src->getNumLoopTri(dm_src);
looptri_active = BLI_BITMAP_NEW((size_t)num_looptri_src, __func__);
@@ -1403,7 +1396,7 @@ void BKE_mesh_remap_calc_loops_from_dm(
&treedata[tindex],
verts_src, verts_allocated_src,
loops_src, loops_allocated_src,
- looptri_src, num_looptri_src, looptri_allocated_src,
+ looptri_src, num_looptri_src, false,
looptri_active, num_looptri_active, bvh_epsilon, 2, 6);
if (verts_allocated_src) {
verts_allocated_src = false; /* Only 'give' our verts once, to first tree! */
@@ -1411,9 +1404,6 @@ void BKE_mesh_remap_calc_loops_from_dm(
if (loops_allocated_src) {
loops_allocated_src = false; /* Only 'give' our loops once, to first tree! */
}
- if (looptri_allocated_src) {
- looptri_allocated_src = false; /* Only 'give' our looptri once, to first tree! */
- }
}
MEM_freeN(looptri_active);
@@ -1492,6 +1482,7 @@ void BKE_mesh_remap_calc_loops_from_dm(
for (i = vert_to_refelem_map_src[nearest.index].count; i--;) {
const int index_src = vert_to_refelem_map_src[nearest.index].indices[i];
+ BLI_assert(index_src != -1);
const float dot = dot_v3v3(nors_src[index_src], *nor_dst);
pidx_src = (mode == MREMAP_MODE_LOOP_NEAREST_LOOPNOR) ?
@@ -1532,7 +1523,12 @@ void BKE_mesh_remap_calc_loops_from_dm(
}
}
}
- if (mode == MREMAP_MODE_LOOP_NEAREST_POLYNOR) {
+ if (best_index_src == -1) {
+ /* We found no item to map back from closest vertex... */
+ best_nor_dot = -1.0f;
+ hit_dist = FLT_MAX;
+ }
+ else if (mode == MREMAP_MODE_LOOP_NEAREST_POLYNOR) {
/* Our best_index_src is a poly one for now!
* Have to find its loop matching our closest vertex. */
mp_src = &polys_src[best_index_src];
@@ -1928,9 +1924,6 @@ void BKE_mesh_remap_calc_loops_from_dm(
if (polys_allocated_src) {
MEM_freeN(polys_src);
}
- if (looptri_allocated_src) {
- MEM_freeN((void *)looptri_src);
- }
if (vert_to_loop_map_src) {
MEM_freeN(vert_to_loop_map_src);
}
@@ -2182,7 +2175,7 @@ void BKE_mesh_remap_calc_polys_from_dm(
tri_vidx_2d[1][2] = 3;
}
else {
- BLI_polyfill_calc((const float(*)[2])poly_vcos_2d, (unsigned int)mp->totloop, -1,
+ BLI_polyfill_calc(poly_vcos_2d, (unsigned int)mp->totloop, -1,
(unsigned int (*)[3])tri_vidx_2d);
}
diff --git a/source/blender/blenkernel/intern/mesh_validate.c b/source/blender/blenkernel/intern/mesh_validate.c
index ba890b005d8..b0577fdd50d 100644
--- a/source/blender/blenkernel/intern/mesh_validate.c
+++ b/source/blender/blenkernel/intern/mesh_validate.c
@@ -62,8 +62,8 @@ typedef union {
} EdgeUUID;
typedef struct SortFace {
- EdgeUUID es[4];
- unsigned int index;
+ EdgeUUID es[4];
+ unsigned int index;
} SortFace;
/* Used to detect polys (faces) using exactly the same vertices. */
@@ -126,28 +126,28 @@ static int search_face_cmp(const void *v1, const void *v2)
if (sfa->es[0].edval > sfb->es[0].edval) {
return 1;
}
- else if (sfa->es[0].edval < sfb->es[0].edval) {
+ else if (sfa->es[0].edval < sfb->es[0].edval) {
return -1;
}
- else if (sfa->es[1].edval > sfb->es[1].edval) {
+ else if (sfa->es[1].edval > sfb->es[1].edval) {
return 1;
}
- else if (sfa->es[1].edval < sfb->es[1].edval) {
+ else if (sfa->es[1].edval < sfb->es[1].edval) {
return -1;
}
- else if (sfa->es[2].edval > sfb->es[2].edval) {
+ else if (sfa->es[2].edval > sfb->es[2].edval) {
return 1;
}
- else if (sfa->es[2].edval < sfb->es[2].edval) {
+ else if (sfa->es[2].edval < sfb->es[2].edval) {
return -1;
}
- else if (sfa->es[3].edval > sfb->es[3].edval) {
+ else if (sfa->es[3].edval > sfb->es[3].edval) {
return 1;
}
- else if (sfa->es[3].edval < sfb->es[3].edval) {
+ else if (sfa->es[3].edval < sfb->es[3].edval) {
return -1;
}
@@ -584,8 +584,8 @@ bool BKE_mesh_validate_arrays(Mesh *mesh,
int prev_e = ml->e;
ml->e = GET_INT_FROM_POINTER(BLI_edgehash_lookup(edge_hash, v1, v2));
fix_flag.loops_edge = true;
- PRINT_ERR("\tPoly %u has invalid edge reference (%d), fixed using edge %u\n",
- sp->index, prev_e, ml->e);
+ PRINT_ERR("\tPoly %u has invalid edge reference (%d, is_removed: %d), fixed using edge %u\n",
+ sp->index, prev_e, IS_REMOVED_EDGE(me), ml->e);
}
else {
PRINT_ERR("\tPoly %u has invalid edge reference (%u)\n", sp->index, ml->e);
@@ -1486,7 +1486,7 @@ void BKE_mesh_calc_edges(Mesh *mesh, bool update, const bool select)
}
}
- totedge = BLI_edgehash_size(eh);
+ totedge = BLI_edgehash_len(eh);
/* write new edges into a temporary CustomData */
CustomData_reset(&edata);
diff --git a/source/blender/blenkernel/intern/modifier.c b/source/blender/blenkernel/intern/modifier.c
index 2276d56b9c6..ce04f3c31e2 100644
--- a/source/blender/blenkernel/intern/modifier.c
+++ b/source/blender/blenkernel/intern/modifier.c
@@ -59,6 +59,8 @@
#include "BKE_appdir.h"
#include "BKE_key.h"
+#include "BKE_library.h"
+#include "BKE_library_query.h"
#include "BKE_multires.h"
#include "BKE_DerivedMesh.h"
@@ -134,16 +136,38 @@ ModifierData *modifier_new(int type)
return md;
}
-void modifier_free(ModifierData *md)
+static void modifier_free_data_id_us_cb(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin, int cb_flag)
+{
+ ID *id = *idpoin;
+ if (id != NULL && (cb_flag & IDWALK_CB_USER) != 0) {
+ id_us_min(id);
+ }
+}
+
+void modifier_free_ex(ModifierData *md, const int flag)
{
const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ if (mti->foreachIDLink) {
+ mti->foreachIDLink(md, NULL, modifier_free_data_id_us_cb, NULL);
+ }
+ else if (mti->foreachObjectLink) {
+ mti->foreachObjectLink(md, NULL, (ObjectWalkFunc)modifier_free_data_id_us_cb, NULL);
+ }
+ }
+
if (mti->freeData) mti->freeData(md);
if (md->error) MEM_freeN(md->error);
MEM_freeN(md);
}
+void modifier_free(ModifierData *md)
+{
+ modifier_free_ex(md, 0);
+}
+
bool modifier_unique_name(ListBase *modifiers, ModifierData *md)
{
if (modifiers && md) {
@@ -269,14 +293,37 @@ void modifier_copyData_generic(const ModifierData *md_src, ModifierData *md_dst)
memcpy(md_dst_data, md_src_data, (size_t)mti->structSize - data_size);
}
-void modifier_copyData(ModifierData *md, ModifierData *target)
+static void modifier_copy_data_id_us_cb(void *UNUSED(userData), Object *UNUSED(ob), ID **idpoin, int cb_flag)
+{
+ ID *id = *idpoin;
+ if (id != NULL && (cb_flag & IDWALK_CB_USER) != 0) {
+ id_us_plus(id);
+ }
+}
+
+void modifier_copyData_ex(ModifierData *md, ModifierData *target, const int flag)
{
const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
target->mode = md->mode;
- if (mti->copyData)
+ if (mti->copyData) {
mti->copyData(md, target);
+ }
+
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ if (mti->foreachIDLink) {
+ mti->foreachIDLink(target, NULL, modifier_copy_data_id_us_cb, NULL);
+ }
+ else if (mti->foreachObjectLink) {
+ mti->foreachObjectLink(target, NULL, (ObjectWalkFunc)modifier_copy_data_id_us_cb, NULL);
+ }
+ }
+}
+
+void modifier_copyData(ModifierData *md, ModifierData *target)
+{
+ modifier_copyData_ex(md, target, 0);
}
@@ -409,6 +456,11 @@ bool modifiers_isParticleEnabled(Object *ob)
return (md && md->mode & (eModifierMode_Realtime | eModifierMode_Render));
}
+/**
+ * Check whether is enabled.
+ *
+ * \param scene Current scene, may be NULL, in which case isDisabled callback of the modifier is never called.
+ */
bool modifier_isEnabled(struct Scene *scene, ModifierData *md, int required_mode)
{
const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
@@ -416,7 +468,7 @@ bool modifier_isEnabled(struct Scene *scene, ModifierData *md, int required_mode
md->scene = scene;
if ((md->mode & required_mode) != required_mode) return false;
- if (mti->isDisabled && mti->isDisabled(md, required_mode == eModifierMode_Render)) return false;
+ if (scene != NULL && mti->isDisabled && mti->isDisabled(md, required_mode == eModifierMode_Render)) return false;
if (md->mode & eModifierMode_DisableTemporary) return false;
if ((required_mode & eModifierMode_Editmode) && !(mti->flags & eModifierTypeFlag_SupportsEditmode)) return false;
@@ -708,7 +760,7 @@ void test_object_modifiers(Object *ob)
*/
const char *modifier_path_relbase(Object *ob)
{
- if (G.relbase_valid || ID_IS_LINKED_DATABLOCK(ob)) {
+ if (G.relbase_valid || ID_IS_LINKED(ob)) {
return ID_BLEND_PATH(G.main, &ob->id);
}
else {
diff --git a/source/blender/blenkernel/intern/modifiers_bmesh.c b/source/blender/blenkernel/intern/modifiers_bmesh.c
index 0838630a6cb..a1172d3f110 100644
--- a/source/blender/blenkernel/intern/modifiers_bmesh.c
+++ b/source/blender/blenkernel/intern/modifiers_bmesh.c
@@ -62,7 +62,7 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
{
MVert *mv, *mvert;
MEdge *me, *medge;
- MPoly /* *mpoly, */ /* UNUSED */ *mp;
+ MPoly *mpoly, *mp;
MLoop *mloop;
BMVert *v, **vtable;
BMEdge *e, **etable;
@@ -70,7 +70,6 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
BMFace *f;
int i, j, totvert, totedge /* , totface */ /* UNUSED */ ;
bool is_init = (bm->totvert == 0) && (bm->totedge == 0) && (bm->totface == 0);
- bool is_cddm = (dm->type == DM_TYPE_CDDM); /* duplicate the arrays for non cddm */
char has_orig_htype = 0;
int cd_vert_bweight_offset;
@@ -106,7 +105,8 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
etable = MEM_mallocN(sizeof(*etable) * totedge, __func__);
/*do verts*/
- mv = mvert = is_cddm ? dm->getVertArray(dm) : dm->dupVertArray(dm);
+ bool vert_allocated;
+ mv = mvert = DM_get_vert_array(dm, &vert_allocated);;
for (i = 0; i < totvert; i++, mv++) {
v = BM_vert_create(bm, mv->co, NULL, BM_CREATE_SKIP_CD);
normal_short_to_float_v3(v->no, mv->no);
@@ -124,11 +124,12 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
*orig_index = ORIGINDEX_NONE;
}
}
- if (!is_cddm) MEM_freeN(mvert);
+ if (vert_allocated) MEM_freeN(mvert);
if (is_init) bm->elem_index_dirty &= ~BM_VERT;
/*do edges*/
- me = medge = is_cddm ? dm->getEdgeArray(dm) : dm->dupEdgeArray(dm);
+ bool edge_allocated;
+ me = medge = DM_get_edge_array(dm, &edge_allocated);
for (i = 0; i < totedge; i++, me++) {
//BLI_assert(BM_edge_exists(vtable[me->v1], vtable[me->v2]) == NULL);
e = BM_edge_create(bm, vtable[me->v1], vtable[me->v2], NULL, BM_CREATE_SKIP_CD);
@@ -147,13 +148,14 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
*orig_index = ORIGINDEX_NONE;
}
}
- if (!is_cddm) MEM_freeN(medge);
+ if (edge_allocated) MEM_freeN(medge);
if (is_init) bm->elem_index_dirty &= ~BM_EDGE;
/* do faces */
/* note: i_alt is aligned with bmesh faces which may not always align with mpolys */
- mp = dm->getPolyArray(dm);
- mloop = dm->getLoopArray(dm);
+ bool poly_allocated, loop_allocated;
+ mpoly = mp = DM_get_poly_array(dm, &poly_allocated);
+ mloop = DM_get_loop_array(dm, &loop_allocated);
face_normals = (dm->dirty & DM_DIRTY_NORMALS) ? NULL : CustomData_get_layer(&dm->polyData, CD_NORMAL);
for (i = 0; i < dm->numPolyData; i++, mp++) {
BMLoop *l_iter;
@@ -194,6 +196,8 @@ void DM_to_bmesh_ex(DerivedMesh *dm, BMesh *bm, const bool calc_face_normal)
*orig_index = ORIGINDEX_NONE;
}
}
+ if (poly_allocated) MEM_freeN(mpoly);
+ if (loop_allocated) MEM_freeN(mloop);
if (is_init) bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
MEM_freeN(vtable);
diff --git a/source/blender/blenkernel/intern/movieclip.c b/source/blender/blenkernel/intern/movieclip.c
index 6794a8e8f93..9ed715d7591 100644
--- a/source/blender/blenkernel/intern/movieclip.c
+++ b/source/blender/blenkernel/intern/movieclip.c
@@ -73,6 +73,8 @@
#include "IMB_imbuf.h"
#include "IMB_moviecache.h"
+#include "DEG_depsgraph.h"
+
#ifdef WITH_OPENEXR
# include "intern/openexr/openexr_multi.h"
#endif
@@ -588,7 +590,7 @@ static MovieClip *movieclip_alloc(Main *bmain, const char *name)
{
MovieClip *clip;
- clip = BKE_libblock_alloc(bmain, ID_MC, name);
+ clip = BKE_libblock_alloc(bmain, ID_MC, name, 0);
clip->aspx = clip->aspy = 1.0f;
@@ -924,7 +926,7 @@ static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip,
/* cache isn't threadsafe itself and also loading of movies
* can't happen from concurrent threads that's why we use lock here */
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
/* try to obtain cached postprocessed frame first */
if (need_postprocessed_frame(user, postprocess_flag)) {
@@ -974,7 +976,7 @@ static ImBuf *movieclip_get_postprocessed_ibuf(MovieClip *clip,
}
}
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
return ibuf;
}
@@ -1200,6 +1202,23 @@ int BKE_movieclip_get_duration(MovieClip *clip)
return clip->len;
}
+float BKE_movieclip_get_fps(MovieClip *clip)
+{
+ if (clip->source != MCLIP_SRC_MOVIE) {
+ return 0.0f;
+ }
+ movieclip_open_anim_file(clip);
+ if (clip->anim == NULL) {
+ return 0.0f;
+ }
+ short frs_sec;
+ float frs_sec_base;
+ if (IMB_anim_get_fps(clip->anim, &frs_sec, &frs_sec_base, true)) {
+ return (float)frs_sec / frs_sec_base;
+ }
+ return 0.0f;
+}
+
void BKE_movieclip_get_aspect(MovieClip *clip, float *aspx, float *aspy)
{
*aspx = 1.0;
@@ -1408,13 +1427,13 @@ static void movieclip_build_proxy_ibuf(MovieClip *clip, ImBuf *ibuf, int cfra, i
* could be solved in a way that thread only prepares memory
* buffer and write to disk happens separately
*/
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
BLI_make_existing_file(name);
if (IMB_saveiff(scaleibuf, name, IB_rect) == 0)
perror(name);
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
IMB_freeImBuf(scaleibuf);
}
@@ -1488,25 +1507,33 @@ void BKE_movieclip_free(MovieClip *clip)
BKE_animdata_free((ID *) clip, false);
}
-MovieClip *BKE_movieclip_copy(Main *bmain, MovieClip *clip)
+/**
+ * Only copy internal data of MovieClip ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_movieclip_copy_data(Main *UNUSED(bmain), MovieClip *clip_dst, const MovieClip *clip_src, const int flag)
{
- MovieClip *clip_new;
-
- clip_new = BKE_libblock_copy(bmain, &clip->id);
-
- clip_new->anim = NULL;
- clip_new->cache = NULL;
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
- BKE_tracking_copy(&clip_new->tracking, &clip->tracking);
- clip_new->tracking_context = NULL;
+ clip_dst->anim = NULL;
+ clip_dst->cache = NULL;
- id_us_plus((ID *)clip_new->gpd);
+ BKE_tracking_copy(&clip_dst->tracking, &clip_src->tracking, flag_subdata);
+ clip_dst->tracking_context = NULL;
- BKE_color_managed_colorspace_settings_copy(&clip_new->colorspace_settings, &clip->colorspace_settings);
-
- BKE_id_copy_ensure_local(bmain, &clip->id, &clip_new->id);
+ BKE_color_managed_colorspace_settings_copy(&clip_dst->colorspace_settings, &clip_src->colorspace_settings);
+}
- return clip_new;
+MovieClip *BKE_movieclip_copy(Main *bmain, const MovieClip *clip)
+{
+ MovieClip *clip_copy;
+ BKE_id_copy_ex(bmain, &clip->id, (ID **)&clip_copy, 0, false);
+ return clip_copy;
}
void BKE_movieclip_make_local(Main *bmain, MovieClip *clip, const bool lib_local)
@@ -1514,12 +1541,12 @@ void BKE_movieclip_make_local(Main *bmain, MovieClip *clip, const bool lib_local
BKE_id_make_local_generic(bmain, &clip->id, true, lib_local);
}
-float BKE_movieclip_remap_scene_to_clip_frame(MovieClip *clip, float framenr)
+float BKE_movieclip_remap_scene_to_clip_frame(const MovieClip *clip, float framenr)
{
return framenr - (float) clip->start_frame + 1.0f;
}
-float BKE_movieclip_remap_clip_to_scene_frame(MovieClip *clip, float framenr)
+float BKE_movieclip_remap_clip_to_scene_frame(const MovieClip *clip, float framenr)
{
return framenr + (float) clip->start_frame - 1.0f;
}
@@ -1550,9 +1577,9 @@ ImBuf *BKE_movieclip_anim_ibuf_for_frame(MovieClip *clip, MovieClipUser *user)
ImBuf *ibuf = NULL;
if (clip->source == MCLIP_SRC_MOVIE) {
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
ibuf = movieclip_load_movie_file(clip, user, user->framenr, clip->flag);
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
}
return ibuf;
@@ -1562,9 +1589,9 @@ bool BKE_movieclip_has_cached_frame(MovieClip *clip, MovieClipUser *user)
{
bool has_frame = false;
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
has_frame = has_imbuf_cache(clip, user, clip->flag);
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
return has_frame;
}
@@ -1575,9 +1602,15 @@ bool BKE_movieclip_put_frame_if_possible(MovieClip *clip,
{
bool result;
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
result = put_imbuf_cache(clip, user, ibuf, clip->flag, false);
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
return result;
}
+
+void BKE_movieclip_eval_update(struct EvaluationContext *UNUSED(eval_ctx), MovieClip *clip)
+{
+ DEG_debug_print_eval(__func__, clip->id.name, clip);
+ BKE_tracking_dopesheet_tag_update(&clip->tracking);
+}
diff --git a/source/blender/blenkernel/intern/multires.c b/source/blender/blenkernel/intern/multires.c
index 9679b585e6f..9c8fc9bfd0c 100644
--- a/source/blender/blenkernel/intern/multires.c
+++ b/source/blender/blenkernel/intern/multires.c
@@ -44,6 +44,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
+#include "BLI_task.h"
#include "BKE_pbvh.h"
#include "BKE_ccg.h"
@@ -439,7 +440,7 @@ int multiresModifier_reshapeFromDeformMod(Scene *scene, MultiresModifierData *mm
/* Create DerivedMesh for deformation modifier */
dm = get_multires_dm(scene, mmd, ob);
numVerts = dm->getNumVerts(dm);
- deformedVerts = MEM_mallocN(sizeof(float[3]) * numVerts, "multiresReshape_deformVerts");
+ deformedVerts = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "multiresReshape_deformVerts");
dm->getVertCos(dm, deformedVerts);
mti->deformVerts(md, ob, dm, deformedVerts, numVerts, 0);
@@ -532,7 +533,7 @@ static void multires_reallocate_mdisps(int totloop, MDisps *mdisps, int lvl)
/* reallocate displacements to be filled in */
for (i = 0; i < totloop; ++i) {
int totdisp = multires_grid_tot[lvl];
- float (*disps)[3] = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
+ float (*disps)[3] = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disps");
if (mdisps[i].disps)
MEM_freeN(mdisps[i].disps);
@@ -596,7 +597,7 @@ static void multires_grid_paint_mask_downsample(GridPaintMask *gpm, int level)
{
if (level < gpm->level) {
int gridsize = BKE_ccg_gridsize(level);
- float *data = MEM_callocN(sizeof(float) * SQUARE(gridsize),
+ float *data = MEM_calloc_arrayN(SQUARE(gridsize), sizeof(float),
"multires_grid_paint_mask_downsample");
int x, y;
@@ -641,7 +642,7 @@ static void multires_del_higher(MultiresModifierData *mmd, Object *ob, int lvl)
float (*disps)[3], (*ndisps)[3], (*hdisps)[3];
int totdisp = multires_grid_tot[lvl];
- disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disps");
+ disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disps");
ndisps = disps;
hdisps = mdisp->disps;
@@ -784,7 +785,7 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob)
cddm = CDDM_from_mesh(me);
pmap = cddm->getPolyMap(ob, cddm);
- origco = MEM_callocN(sizeof(float) * 3 * me->totvert, "multires apply base origco");
+ origco = MEM_calloc_arrayN(me->totvert, 3 * sizeof(float), "multires apply base origco");
for (i = 0; i < me->totvert; ++i)
copy_v3_v3(origco[i], me->mvert[i].co);
@@ -824,8 +825,8 @@ void multiresModifier_base_apply(MultiresModifierData *mmd, Object *ob)
* BKE_mesh_calc_poly_normal_coords() */
fake_poly.totloop = p->totloop;
fake_poly.loopstart = 0;
- fake_loops = MEM_mallocN(sizeof(MLoop) * p->totloop, "fake_loops");
- fake_co = MEM_mallocN(sizeof(float) * 3 * p->totloop, "fake_co");
+ fake_loops = MEM_malloc_arrayN(p->totloop, sizeof(MLoop), "fake_loops");
+ fake_co = MEM_malloc_arrayN(p->totloop, 3 * sizeof(float), "fake_co");
for (k = 0; k < p->totloop; ++k) {
int vndx = me->mloop[p->loopstart + k].v;
@@ -922,11 +923,11 @@ static void multires_subdivide(MultiresModifierData *mmd, Object *ob, int totlvl
lowGridData = lowdm->getGridData(lowdm);
lowdm->getGridKey(lowdm, &lowGridKey);
- subGridData = MEM_callocN(sizeof(float *) * numGrids, "subGridData*");
+ subGridData = MEM_calloc_arrayN(numGrids, sizeof(float *), "subGridData*");
for (i = 0; i < numGrids; ++i) {
/* backup subsurf grids */
- subGridData[i] = MEM_callocN(highGridKey.elem_size * highGridSize * highGridSize, "subGridData");
+ subGridData[i] = MEM_calloc_arrayN(highGridKey.elem_size, highGridSize * highGridSize, "subGridData");
memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize);
/* overwrite with current displaced grids */
@@ -1002,6 +1003,117 @@ static void grid_tangent_matrix(float mat[3][3], const CCGKey *key,
copy_v3_v3(mat[2], CCG_grid_elem_no(key, grid, x, y));
}
+
+typedef struct MultiresThreadedData {
+ DispOp op;
+ CCGElem **gridData, **subGridData;
+ CCGKey *key;
+ CCGKey *sub_key;
+ MPoly *mpoly;
+ MDisps *mdisps;
+ GridPaintMask *grid_paint_mask;
+ int *gridOffset;
+ int gridSize, dGridSize, dSkip;
+ float (*smat)[3];
+} MultiresThreadedData;
+
+static void multires_disp_run_cb(
+ void *__restrict userdata,
+ const int pidx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ MultiresThreadedData *tdata = userdata;
+
+ DispOp op = tdata->op;
+ CCGElem **gridData = tdata->gridData;
+ CCGElem **subGridData = tdata->subGridData;
+ CCGKey *key = tdata->key;
+ MPoly *mpoly = tdata->mpoly;
+ MDisps *mdisps = tdata->mdisps;
+ GridPaintMask *grid_paint_mask = tdata->grid_paint_mask;
+ int *gridOffset = tdata->gridOffset;
+ int gridSize = tdata->gridSize;
+ int dGridSize = tdata->dGridSize;
+ int dSkip = tdata->dSkip;
+
+ const int numVerts = mpoly[pidx].totloop;
+ int S, x, y, gIndex = gridOffset[pidx];
+
+ for (S = 0; S < numVerts; ++S, ++gIndex) {
+ GridPaintMask *gpm = grid_paint_mask ? &grid_paint_mask[gIndex] : NULL;
+ MDisps *mdisp = &mdisps[mpoly[pidx].loopstart + S];
+ CCGElem *grid = gridData[gIndex];
+ CCGElem *subgrid = subGridData[gIndex];
+ float (*dispgrid)[3] = NULL;
+
+ dispgrid = mdisp->disps;
+
+ /* if needed, reallocate multires paint mask */
+ if (gpm && gpm->level < key->level) {
+ gpm->level = key->level;
+ if (gpm->data) {
+ MEM_freeN(gpm->data);
+ }
+ gpm->data = MEM_calloc_arrayN(key->grid_area, sizeof(float), "gpm.data");
+ }
+
+ for (y = 0; y < gridSize; y++) {
+ for (x = 0; x < gridSize; x++) {
+ float *co = CCG_grid_elem_co(key, grid, x, y);
+ float *sco = CCG_grid_elem_co(key, subgrid, x, y);
+ float *data = dispgrid[dGridSize * y * dSkip + x * dSkip];
+ float mat[3][3], disp[3], d[3], mask;
+
+ /* construct tangent space matrix */
+ grid_tangent_matrix(mat, key, x, y, subgrid);
+
+ switch (op) {
+ case APPLY_DISPLACEMENTS:
+ /* Convert displacement to object space
+ * and add to grid points */
+ mul_v3_m3v3(disp, mat, data);
+ add_v3_v3v3(co, sco, disp);
+ break;
+ case CALC_DISPLACEMENTS:
+ /* Calculate displacement between new and old
+ * grid points and convert to tangent space */
+ sub_v3_v3v3(disp, co, sco);
+ invert_m3(mat);
+ mul_v3_m3v3(data, mat, disp);
+ break;
+ case ADD_DISPLACEMENTS:
+ /* Convert subdivided displacements to tangent
+ * space and add to the original displacements */
+ invert_m3(mat);
+ mul_v3_m3v3(d, mat, co);
+ add_v3_v3(data, d);
+ break;
+ }
+
+ if (gpm) {
+ switch (op) {
+ case APPLY_DISPLACEMENTS:
+ /* Copy mask from gpm to DM */
+ *CCG_grid_elem_mask(key, grid, x, y) =
+ paint_grid_paint_mask(gpm, key->level, x, y);
+ break;
+ case CALC_DISPLACEMENTS:
+ /* Copy mask from DM to gpm */
+ mask = *CCG_grid_elem_mask(key, grid, x, y);
+ gpm->data[y * gridSize + x] = CLAMPIS(mask, 0, 1);
+ break;
+ case ADD_DISPLACEMENTS:
+ /* Add mask displacement to gpm */
+ gpm->data[y * gridSize + x] +=
+ *CCG_grid_elem_mask(key, grid, x, y);
+ break;
+ }
+ }
+ }
+ }
+ }
+}
+
/* XXX WARNING: subsurf elements from dm and oldGridData *must* be of the same format (size),
* because this code uses CCGKey's info from dm to access oldGridData's normals
* (through the call to grid_tangent_matrix())! */
@@ -1014,7 +1126,7 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm
MDisps *mdisps = CustomData_get_layer(&me->ldata, CD_MDISPS);
GridPaintMask *grid_paint_mask = NULL;
int *gridOffset;
- int i, k, /*numGrids, */ gridSize, dGridSize, dSkip;
+ int i, gridSize, dGridSize, dSkip;
int totloop, totpoly;
/* this happens in the dm made by bmesh_mdisps_space_set */
@@ -1050,98 +1162,34 @@ static void multiresModifier_disp_run(DerivedMesh *dm, Mesh *me, DerivedMesh *dm
if (key.has_mask)
grid_paint_mask = CustomData_get_layer(&me->ldata, CD_GRID_PAINT_MASK);
- k = 0; /*current loop/mdisp index within the mloop array*/
-
-#pragma omp parallel for private(i) if (totloop * gridSize * gridSize >= CCG_OMP_LIMIT)
-
- for (i = 0; i < totpoly; ++i) {
- const int numVerts = mpoly[i].totloop;
- int S, x, y, gIndex = gridOffset[i];
-
- for (S = 0; S < numVerts; ++S, ++gIndex, ++k) {
- GridPaintMask *gpm = grid_paint_mask ? &grid_paint_mask[gIndex] : NULL;
- MDisps *mdisp = &mdisps[mpoly[i].loopstart + S];
- CCGElem *grid = gridData[gIndex];
- CCGElem *subgrid = subGridData[gIndex];
- float (*dispgrid)[3] = NULL;
-
- /* when adding new faces in edit mode, need to allocate disps */
- if (!mdisp->disps)
-#pragma omp critical
- {
- multires_reallocate_mdisps(totloop, mdisps, totlvl);
- }
-
- dispgrid = mdisp->disps;
-
- /* if needed, reallocate multires paint mask */
- if (gpm && gpm->level < key.level) {
- gpm->level = key.level;
-#pragma omp critical
- {
- if (gpm->data)
- MEM_freeN(gpm->data);
- gpm->data = MEM_callocN(sizeof(float) * key.grid_area, "gpm.data");
- }
- }
+ /* when adding new faces in edit mode, need to allocate disps */
+ for (i = 0; i < totloop; ++i) {
+ if (mdisps[i].disps == NULL) {
+ multires_reallocate_mdisps(totloop, mdisps, totlvl);
+ break;
+ }
+ }
- for (y = 0; y < gridSize; y++) {
- for (x = 0; x < gridSize; x++) {
- float *co = CCG_grid_elem_co(&key, grid, x, y);
- float *sco = CCG_grid_elem_co(&key, subgrid, x, y);
- float *data = dispgrid[dGridSize * y * dSkip + x * dSkip];
- float mat[3][3], disp[3], d[3], mask;
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
- /* construct tangent space matrix */
- grid_tangent_matrix(mat, &key, x, y, subgrid);
+ MultiresThreadedData data = {
+ .op = op,
+ .gridData = gridData,
+ .subGridData = subGridData,
+ .key = &key,
+ .mpoly = mpoly,
+ .mdisps = mdisps,
+ .grid_paint_mask = grid_paint_mask,
+ .gridOffset = gridOffset,
+ .gridSize = gridSize,
+ .dGridSize = dGridSize,
+ .dSkip = dSkip
+ };
- switch (op) {
- case APPLY_DISPLACEMENTS:
- /* Convert displacement to object space
- * and add to grid points */
- mul_v3_m3v3(disp, mat, data);
- add_v3_v3v3(co, sco, disp);
- break;
- case CALC_DISPLACEMENTS:
- /* Calculate displacement between new and old
- * grid points and convert to tangent space */
- sub_v3_v3v3(disp, co, sco);
- invert_m3(mat);
- mul_v3_m3v3(data, mat, disp);
- break;
- case ADD_DISPLACEMENTS:
- /* Convert subdivided displacements to tangent
- * space and add to the original displacements */
- invert_m3(mat);
- mul_v3_m3v3(d, mat, co);
- add_v3_v3(data, d);
- break;
- }
+ BLI_task_parallel_range(0, totpoly, &data, multires_disp_run_cb, &settings);
- if (gpm) {
- switch (op) {
- case APPLY_DISPLACEMENTS:
- /* Copy mask from gpm to DM */
- *CCG_grid_elem_mask(&key, grid, x, y) =
- paint_grid_paint_mask(gpm, key.level, x, y);
- break;
- case CALC_DISPLACEMENTS:
- /* Copy mask from DM to gpm */
- mask = *CCG_grid_elem_mask(&key, grid, x, y);
- gpm->data[y * gridSize + x] = CLAMPIS(mask, 0, 1);
- break;
- case ADD_DISPLACEMENTS:
- /* Add mask displacement to gpm */
- gpm->data[y * gridSize + x] +=
- *CCG_grid_elem_mask(&key, grid, x, y);
- break;
- }
- }
- }
- }
- }
- }
-
if (op == APPLY_DISPLACEMENTS) {
ccgSubSurf_stitchFaces(ccgdm->ss, 0, NULL, 0);
ccgSubSurf_updateNormals(ccgdm->ss, NULL, 0);
@@ -1199,12 +1247,12 @@ void multires_modifier_update_mdisps(struct DerivedMesh *dm)
BLI_assert(highGridKey.elem_size == lowGridKey.elem_size);
- subGridData = MEM_callocN(sizeof(CCGElem *) * numGrids, "subGridData*");
- diffGrid = MEM_callocN(lowGridKey.elem_size * lowGridSize * lowGridSize, "diff");
+ subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
+ diffGrid = MEM_calloc_arrayN(lowGridKey.elem_size, lowGridSize * lowGridSize, "diff");
for (i = 0; i < numGrids; ++i) {
/* backup subsurf grids */
- subGridData[i] = MEM_callocN(highGridKey.elem_size * highGridSize * highGridSize, "subGridData");
+ subGridData[i] = MEM_calloc_arrayN(highGridKey.elem_size, highGridSize * highGridSize, "subGridData");
memcpy(subGridData[i], highGridData[i], highGridKey.elem_size * highGridSize * highGridSize);
/* write difference of subsurf and displaced low level into high subsurf */
@@ -1315,10 +1363,10 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
gridData = subsurf->getGridData(subsurf);
subsurf->getGridKey(subsurf, &key);
- subGridData = MEM_callocN(sizeof(CCGElem *) * numGrids, "subGridData*");
+ subGridData = MEM_calloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
for (i = 0; i < numGrids; i++) {
- subGridData[i] = MEM_callocN(key.elem_size * gridSize * gridSize, "subGridData");
+ subGridData[i] = MEM_calloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData");
memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize);
}
@@ -1332,8 +1380,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
k = 0; /*current loop/mdisp index within the mloop array*/
- //#pragma omp parallel for private(i) if (dm->numLoopData * gridSize * gridSize >= CCG_OMP_LIMIT)
-
+ /* TODO: Use BLI_task parallel range for that one too? */
for (i = 0; i < dm->numPolyData; ++i) {
const int numVerts = mpoly[i].totloop;
int S, x, y, gIndex = gridOffset[i];
@@ -1348,7 +1395,7 @@ void multires_set_space(DerivedMesh *dm, Object *ob, int from, int to)
if (!mdisp->disps) {
mdisp->totdisp = gridSize * gridSize;
mdisp->level = totlvl;
- mdisp->disps = MEM_callocN(sizeof(float) * 3 * mdisp->totdisp, "disp in multires_set_space");
+ mdisp->disps = MEM_calloc_arrayN(mdisp->totdisp, 3 * sizeof(float), "disp in multires_set_space");
}
dispgrid = mdisp->disps;
@@ -1463,10 +1510,10 @@ DerivedMesh *multires_make_derived_from_derived(DerivedMesh *dm,
gridData = result->getGridData(result);
result->getGridKey(result, &key);
- subGridData = MEM_mallocN(sizeof(CCGElem *) * numGrids, "subGridData*");
+ subGridData = MEM_malloc_arrayN(numGrids, sizeof(CCGElem *), "subGridData*");
for (i = 0; i < numGrids; i++) {
- subGridData[i] = MEM_mallocN(key.elem_size * gridSize * gridSize, "subGridData");
+ subGridData[i] = MEM_malloc_arrayN(key.elem_size, gridSize * gridSize, "subGridData");
memcpy(subGridData[i], gridData[i], key.elem_size * gridSize * gridSize);
}
@@ -1556,7 +1603,7 @@ static void old_mdisps_convert(MFace *mface, MDisps *mdisp)
int x, y, S;
float (*disps)[3], (*out)[3], u = 0.0f, v = 0.0f; /* Quite gcc barking. */
- disps = MEM_callocN(sizeof(float) * 3 * newtotdisp, "multires disps");
+ disps = MEM_calloc_arrayN(newtotdisp, 3 * sizeof(float), "multires disps");
out = disps;
for (S = 0; S < nvert; S++) {
@@ -1603,7 +1650,7 @@ void multires_load_old_250(Mesh *me)
int totdisp = mdisps[i].totdisp / nvert;
for (j = 0; j < nvert; j++, k++) {
- mdisps2[k].disps = MEM_callocN(sizeof(float) * 3 * totdisp, "multires disp in conversion");
+ mdisps2[k].disps = MEM_calloc_arrayN(totdisp, 3 * sizeof(float), "multires disp in conversion");
mdisps2[k].totdisp = totdisp;
mdisps2[k].level = mdisps[i].level;
memcpy(mdisps2[k].disps, mdisps[i].disps + totdisp * j, totdisp);
@@ -1663,8 +1710,8 @@ static void create_old_vert_face_map(ListBase **map, IndexNode **mem, const Mult
int i, j;
IndexNode *node = NULL;
- (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert face map");
- (*mem) = MEM_callocN(sizeof(IndexNode) * totface * 4, "vert face map mem");
+ (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert face map");
+ (*mem) = MEM_calloc_arrayN(totface, 4 * sizeof(IndexNode), "vert face map mem");
node = *mem;
/* Find the users */
@@ -1682,8 +1729,8 @@ static void create_old_vert_edge_map(ListBase **map, IndexNode **mem, const Mult
int i, j;
IndexNode *node = NULL;
- (*map) = MEM_callocN(sizeof(ListBase) * totvert, "vert edge map");
- (*mem) = MEM_callocN(sizeof(IndexNode) * totedge * 2, "vert edge map mem");
+ (*map) = MEM_calloc_arrayN(totvert, sizeof(ListBase), "vert edge map");
+ (*mem) = MEM_calloc_arrayN(totedge, 2 * sizeof(IndexNode), "vert edge map mem");
node = *mem;
/* Find the users */
@@ -1865,7 +1912,11 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl)
vsrc = mr->verts;
vdst = dm->getVertArray(dm);
totvert = (unsigned int)dm->getNumVerts(dm);
- vvmap = MEM_callocN(sizeof(int) * totvert, "multires vvmap");
+ vvmap = MEM_calloc_arrayN(totvert, sizeof(int), "multires vvmap");
+
+ if (!vvmap) {
+ return;
+ }
lvl1 = mr->levels.first;
/* Load base verts */
@@ -1950,10 +2001,10 @@ static void multires_load_old_dm(DerivedMesh *dm, Mesh *me, int totlvl)
}
/* calculate vert to edge/face maps for each level (except the last) */
- fmap = MEM_callocN(sizeof(ListBase *) * (mr->level_count - 1), "multires fmap");
- emap = MEM_callocN(sizeof(ListBase *) * (mr->level_count - 1), "multires emap");
- fmem = MEM_callocN(sizeof(IndexNode *) * (mr->level_count - 1), "multires fmem");
- emem = MEM_callocN(sizeof(IndexNode *) * (mr->level_count - 1), "multires emem");
+ fmap = MEM_calloc_arrayN((mr->level_count - 1), sizeof(ListBase *), "multires fmap");
+ emap = MEM_calloc_arrayN((mr->level_count - 1), sizeof(ListBase *), "multires emap");
+ fmem = MEM_calloc_arrayN((mr->level_count - 1), sizeof(IndexNode *), "multires fmem");
+ emem = MEM_calloc_arrayN((mr->level_count - 1), sizeof(IndexNode *), "multires emem");
lvl = lvl1;
for (i = 0; i < (unsigned int)mr->level_count - 1; ++i) {
create_old_vert_face_map(fmap + i, fmem + i, lvl->faces, lvl->totvert, lvl->totface);
@@ -2174,6 +2225,56 @@ static void multires_sync_levels(Scene *scene, Object *ob_src, Object *ob_dst)
}
}
+static void multires_apply_smat_cb(
+ void *__restrict userdata,
+ const int pidx,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ MultiresThreadedData *tdata = userdata;
+
+ CCGElem **gridData = tdata->gridData;
+ CCGElem **subGridData = tdata->subGridData;
+ CCGKey *dm_key = tdata->key;
+ CCGKey *subdm_key = tdata->sub_key;
+ MPoly *mpoly = tdata->mpoly;
+ MDisps *mdisps = tdata->mdisps;
+ int *gridOffset = tdata->gridOffset;
+ int gridSize = tdata->gridSize;
+ int dGridSize = tdata->dGridSize;
+ int dSkip = tdata->dSkip;
+ float (*smat)[3] = tdata->smat;
+
+ const int numVerts = mpoly[pidx].totloop;
+ MDisps *mdisp = &mdisps[mpoly[pidx].loopstart];
+ int S, x, y, gIndex = gridOffset[pidx];
+
+ for (S = 0; S < numVerts; ++S, ++gIndex, mdisp++) {
+ CCGElem *grid = gridData[gIndex];
+ CCGElem *subgrid = subGridData[gIndex];
+ float (*dispgrid)[3] = mdisp->disps;
+
+ for (y = 0; y < gridSize; y++) {
+ for (x = 0; x < gridSize; x++) {
+ float *co = CCG_grid_elem_co(dm_key, grid, x, y);
+ float *sco = CCG_grid_elem_co(subdm_key, subgrid, x, y);
+ float *data = dispgrid[dGridSize * y * dSkip + x * dSkip];
+ float mat[3][3], disp[3];
+
+ /* construct tangent space matrix */
+ grid_tangent_matrix(mat, dm_key, x, y, grid);
+
+ /* scale subgrid coord and calculate displacement */
+ mul_m3_v3(smat, sco);
+ sub_v3_v3v3(disp, sco, co);
+
+ /* convert difference to tangent space */
+ invert_m3(mat);
+ mul_v3_m3v3(data, mat, disp);
+ }
+ }
+ }
+}
+
static void multires_apply_smat(Scene *scene, Object *ob, float smat[3][3])
{
DerivedMesh *dm = NULL, *cddm = NULL, *subdm = NULL;
@@ -2205,7 +2306,7 @@ static void multires_apply_smat(Scene *scene, Object *ob, float smat[3][3])
cddm = mesh_get_derived_deform(scene, ob, CD_MASK_BAREMESH);
totvert = cddm->getNumVerts(cddm);
- vertCos = MEM_mallocN(sizeof(*vertCos) * totvert, "multiresScale vertCos");
+ vertCos = MEM_malloc_arrayN(totvert, sizeof(*vertCos), "multiresScale vertCos");
cddm->getVertCos(cddm, vertCos);
for (i = 0; i < totvert; i++)
mul_m3_v3(smat, vertCos[i]);
@@ -2226,38 +2327,25 @@ static void multires_apply_smat(Scene *scene, Object *ob, float smat[3][3])
dGridSize = multires_side_tot[high_mmd.totlvl];
dSkip = (dGridSize - 1) / (gridSize - 1);
-#pragma omp parallel for private(i) if (me->totloop * gridSize * gridSize >= CCG_OMP_LIMIT)
- for (i = 0; i < me->totpoly; ++i) {
- const int numVerts = mpoly[i].totloop;
- MDisps *mdisp = &mdisps[mpoly[i].loopstart];
- int S, x, y, gIndex = gridOffset[i];
-
- for (S = 0; S < numVerts; ++S, ++gIndex, mdisp++) {
- CCGElem *grid = gridData[gIndex];
- CCGElem *subgrid = subGridData[gIndex];
- float (*dispgrid)[3] = mdisp->disps;
-
- for (y = 0; y < gridSize; y++) {
- for (x = 0; x < gridSize; x++) {
- float *co = CCG_grid_elem_co(&dm_key, grid, x, y);
- float *sco = CCG_grid_elem_co(&subdm_key, subgrid, x, y);
- float *data = dispgrid[dGridSize * y * dSkip + x * dSkip];
- float mat[3][3], disp[3];
-
- /* construct tangent space matrix */
- grid_tangent_matrix(mat, &dm_key, x, y, grid);
-
- /* scale subgrid coord and calculate displacement */
- mul_m3_v3(smat, sco);
- sub_v3_v3v3(disp, sco, co);
-
- /* convert difference to tangent space */
- invert_m3(mat);
- mul_v3_m3v3(data, mat, disp);
- }
- }
- }
- }
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = CCG_TASK_LIMIT;
+
+ MultiresThreadedData data = {
+ .gridData = gridData,
+ .subGridData = subGridData,
+ .key = &dm_key,
+ .sub_key = &subdm_key,
+ .mpoly = mpoly,
+ .mdisps = mdisps,
+ .gridOffset = gridOffset,
+ .gridSize = gridSize,
+ .dGridSize = dGridSize,
+ .dSkip = dSkip,
+ .smat = smat
+ };
+
+ BLI_task_parallel_range(0, me->totpoly, &data, multires_apply_smat_cb, &settings);
dm->release(dm);
subdm->release(subdm);
@@ -2326,7 +2414,7 @@ void multires_topology_changed(Mesh *me)
if (!mdisp->totdisp || !mdisp->disps) {
if (grid) {
mdisp->totdisp = grid;
- mdisp->disps = MEM_callocN(3 * mdisp->totdisp * sizeof(float), "mdisp topology");
+ mdisp->disps = MEM_calloc_arrayN(3 * sizeof(float), mdisp->totdisp, "mdisp topology");
}
continue;
diff --git a/source/blender/blenkernel/intern/nla.c b/source/blender/blenkernel/intern/nla.c
index 148fc3827e0..e239037df70 100644
--- a/source/blender/blenkernel/intern/nla.c
+++ b/source/blender/blenkernel/intern/nla.c
@@ -75,7 +75,7 @@
/* Remove the given NLA strip from the NLA track it occupies, free the strip's data,
* and the strip itself.
*/
-void free_nlastrip(ListBase *strips, NlaStrip *strip)
+void BKE_nlastrip_free(ListBase *strips, NlaStrip *strip)
{
NlaStrip *cs, *csn;
@@ -86,7 +86,7 @@ void free_nlastrip(ListBase *strips, NlaStrip *strip)
/* free child-strips */
for (cs = strip->strips.first; cs; cs = csn) {
csn = cs->next;
- free_nlastrip(&strip->strips, cs);
+ BKE_nlastrip_free(&strip->strips, cs);
}
/* remove reference to action */
@@ -113,7 +113,7 @@ void free_nlastrip(ListBase *strips, NlaStrip *strip)
/* Remove the given NLA track from the set of NLA tracks, free the track's data,
* and the track itself.
*/
-void free_nlatrack(ListBase *tracks, NlaTrack *nlt)
+void BKE_nlatrack_free(ListBase *tracks, NlaTrack *nlt)
{
NlaStrip *strip, *stripn;
@@ -124,7 +124,7 @@ void free_nlatrack(ListBase *tracks, NlaTrack *nlt)
/* free strips */
for (strip = nlt->strips.first; strip; strip = stripn) {
stripn = strip->next;
- free_nlastrip(&nlt->strips, strip);
+ BKE_nlastrip_free(&nlt->strips, strip);
}
/* free NLA track itself now */
@@ -137,7 +137,7 @@ void free_nlatrack(ListBase *tracks, NlaTrack *nlt)
/* Free the elements of type NLA Tracks provided in the given list, but do not free
* the list itself since that is not free-standing
*/
-void free_nladata(ListBase *tracks)
+void BKE_nla_tracks_free(ListBase *tracks)
{
NlaTrack *nlt, *nltn;
@@ -148,7 +148,7 @@ void free_nladata(ListBase *tracks)
/* free tracks one by one */
for (nlt = tracks->first; nlt; nlt = nltn) {
nltn = nlt->next;
- free_nlatrack(tracks, nlt);
+ BKE_nlatrack_free(tracks, nlt);
}
/* clear the list's pointers to be safe */
@@ -162,7 +162,7 @@ void free_nladata(ListBase *tracks)
*
* \param use_same_action When true, the existing action is used (instead of being duplicated)
*/
-NlaStrip *copy_nlastrip(NlaStrip *strip, const bool use_same_action)
+NlaStrip *BKE_nlastrip_copy(NlaStrip *strip, const bool use_same_action)
{
NlaStrip *strip_d;
NlaStrip *cs, *cs_d;
@@ -195,7 +195,7 @@ NlaStrip *copy_nlastrip(NlaStrip *strip, const bool use_same_action)
BLI_listbase_clear(&strip_d->strips);
for (cs = strip->strips.first; cs; cs = cs->next) {
- cs_d = copy_nlastrip(cs, use_same_action);
+ cs_d = BKE_nlastrip_copy(cs, use_same_action);
BLI_addtail(&strip_d->strips, cs_d);
}
@@ -204,7 +204,7 @@ NlaStrip *copy_nlastrip(NlaStrip *strip, const bool use_same_action)
}
/* Copy NLA Track */
-NlaTrack *copy_nlatrack(NlaTrack *nlt, const bool use_same_actions)
+NlaTrack *BKE_nlatrack_copy(NlaTrack *nlt, const bool use_same_actions)
{
NlaStrip *strip, *strip_d;
NlaTrack *nlt_d;
@@ -221,7 +221,7 @@ NlaTrack *copy_nlatrack(NlaTrack *nlt, const bool use_same_actions)
BLI_listbase_clear(&nlt_d->strips);
for (strip = nlt->strips.first; strip; strip = strip->next) {
- strip_d = copy_nlastrip(strip, use_same_actions);
+ strip_d = BKE_nlastrip_copy(strip, use_same_actions);
BLI_addtail(&nlt_d->strips, strip_d);
}
@@ -230,7 +230,7 @@ NlaTrack *copy_nlatrack(NlaTrack *nlt, const bool use_same_actions)
}
/* Copy all NLA data */
-void copy_nladata(ListBase *dst, ListBase *src)
+void BKE_nla_tracks_copy(ListBase *dst, ListBase *src)
{
NlaTrack *nlt, *nlt_d;
@@ -245,7 +245,7 @@ void copy_nladata(ListBase *dst, ListBase *src)
for (nlt = src->first; nlt; nlt = nlt->next) {
/* make a copy, and add the copy to the destination list */
// XXX: we need to fix this sometime
- nlt_d = copy_nlatrack(nlt, true);
+ nlt_d = BKE_nlatrack_copy(nlt, true);
BLI_addtail(dst, nlt_d);
}
}
@@ -255,7 +255,7 @@ void copy_nladata(ListBase *dst, ListBase *src)
/* Add a NLA Track to the given AnimData
* - prev: NLA-Track to add the new one after
*/
-NlaTrack *add_nlatrack(AnimData *adt, NlaTrack *prev)
+NlaTrack *BKE_nlatrack_add(AnimData *adt, NlaTrack *prev)
{
NlaTrack *nlt;
@@ -285,8 +285,8 @@ NlaTrack *add_nlatrack(AnimData *adt, NlaTrack *prev)
return nlt;
}
-/* Add a NLA Strip referencing the given Action */
-NlaStrip *add_nlastrip(bAction *act)
+/* Create a NLA Strip referencing the given Action */
+NlaStrip *BKE_nlastrip_new(bAction *act)
{
NlaStrip *strip;
@@ -327,7 +327,7 @@ NlaStrip *add_nlastrip(bAction *act)
}
/* Add new NLA-strip to the top of the NLA stack - i.e. into the last track if space, or a new one otherwise */
-NlaStrip *add_nlastrip_to_stack(AnimData *adt, bAction *act)
+NlaStrip *BKE_nlastack_add_strip(AnimData *adt, bAction *act)
{
NlaStrip *strip;
NlaTrack *nlt;
@@ -337,7 +337,7 @@ NlaStrip *add_nlastrip_to_stack(AnimData *adt, bAction *act)
return NULL;
/* create a new NLA strip */
- strip = add_nlastrip(act);
+ strip = BKE_nlastrip_new(act);
if (strip == NULL)
return NULL;
@@ -346,7 +346,7 @@ NlaStrip *add_nlastrip_to_stack(AnimData *adt, bAction *act)
/* trying to add to the last track failed (no track or no space),
* so add a new track to the stack, and add to that...
*/
- nlt = add_nlatrack(adt, NULL);
+ nlt = BKE_nlatrack_add(adt, NULL);
BKE_nlatrack_add_strip(nlt, strip);
}
@@ -358,7 +358,7 @@ NlaStrip *add_nlastrip_to_stack(AnimData *adt, bAction *act)
}
/* Add a NLA Strip referencing the given speaker's sound */
-NlaStrip *add_nla_soundstrip(Scene *scene, Speaker *speaker)
+NlaStrip *BKE_nla_add_soundstrip(Scene *scene, Speaker *speaker)
{
NlaStrip *strip = MEM_callocN(sizeof(NlaStrip), "NlaSoundStrip");
@@ -751,7 +751,7 @@ void BKE_nlastrips_clear_metastrip(ListBase *strips, NlaStrip *strip)
}
/* free the meta-strip now */
- free_nlastrip(strips, strip);
+ BKE_nlastrip_free(strips, strip);
}
/* Remove meta-strips (i.e. flatten the list of strips) from the top-level of the list of strips
@@ -1387,11 +1387,17 @@ void BKE_nlastrip_validate_fcurves(NlaStrip *strip)
/* set default flags */
fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED);
+ fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL;
/* store path - make copy, and store that */
fcu->rna_path = BLI_strdupn("influence", 9);
- /* TODO: insert a few keyframes to ensure default behavior? */
+ /* insert keyframe to ensure current value stays on first refresh */
+ fcu->bezt = MEM_callocN(sizeof(BezTriple), "nlastrip influence bezt");
+ fcu->totvert = 1;
+
+ fcu->bezt->vec[1][0] = strip->start;
+ fcu->bezt->vec[1][1] = strip->influence;
}
}
@@ -1408,6 +1414,7 @@ void BKE_nlastrip_validate_fcurves(NlaStrip *strip)
/* set default flags */
fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED);
+ fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL;
/* store path - make copy, and store that */
fcu->rna_path = BLI_strdupn("strip_time", 10);
@@ -1417,6 +1424,40 @@ void BKE_nlastrip_validate_fcurves(NlaStrip *strip)
}
}
+/* Check if the given RNA pointer + property combo should be handled by
+ * NLA strip curves or not.
+ */
+bool BKE_nlastrip_has_curves_for_property(const PointerRNA *ptr, const PropertyRNA *prop)
+{
+ /* sanity checks */
+ if (ELEM(NULL, ptr, prop))
+ return false;
+
+ /* 1) Must be NLA strip */
+ if (ptr->type == &RNA_NlaStrip) {
+ /* 2) Must be one of the predefined properties */
+ static PropertyRNA *prop_influence = NULL;
+ static PropertyRNA *prop_time = NULL;
+ static bool needs_init = true;
+
+ /* Init the properties on first use */
+ if (needs_init) {
+ prop_influence = RNA_struct_type_find_property(&RNA_NlaStrip, "influence");
+ prop_time = RNA_struct_type_find_property(&RNA_NlaStrip, "strip_time");
+
+ needs_init = false;
+ }
+
+ /* Check if match */
+ if (ELEM(prop, prop_influence, prop_time)) {
+ return true;
+ }
+ }
+
+ /* No criteria met */
+ return false;
+}
+
/* Sanity Validation ------------------------------------ */
static bool nla_editbone_name_check(void *arg, const char *name)
@@ -1673,7 +1714,7 @@ bool BKE_nla_action_stash(AnimData *adt)
}
}
- nlt = add_nlatrack(adt, prev_track);
+ nlt = BKE_nlatrack_add(adt, prev_track);
BLI_assert(nlt != NULL);
/* we need to ensure that if there wasn't any previous instance, it must go to tbe bottom of the stack */
@@ -1688,7 +1729,7 @@ bool BKE_nla_action_stash(AnimData *adt)
/* add the action as a strip in this new track
* NOTE: a new user is created here
*/
- strip = add_nlastrip(adt->action);
+ strip = BKE_nlastrip_new(adt->action);
BLI_assert(strip != NULL);
BKE_nlatrack_add_strip(nlt, strip);
@@ -1724,7 +1765,8 @@ bool BKE_nla_action_stash(AnimData *adt)
void BKE_nla_action_pushdown(AnimData *adt)
{
NlaStrip *strip;
-
+ const bool is_first = (adt) && (adt->nla_tracks.first == NULL);
+
/* sanity checks */
/* TODO: need to report the error for this */
if (ELEM(NULL, adt, adt->action))
@@ -1740,7 +1782,7 @@ void BKE_nla_action_pushdown(AnimData *adt)
}
/* add a new NLA strip to the track, which references the active action */
- strip = add_nlastrip_to_stack(adt, adt->action);
+ strip = BKE_nlastack_add_strip(adt, adt->action);
/* do other necessary work on strip */
if (strip) {
@@ -1748,6 +1790,32 @@ void BKE_nla_action_pushdown(AnimData *adt)
id_us_min(&adt->action->id);
adt->action = NULL;
+ /* copy current "action blending" settings from adt to the strip,
+ * as it was keyframed with these settings, so omitting them will
+ * change the effect [T54233]
+ *
+ * NOTE: We only do this when there are no tracks
+ */
+ if (is_first == false) {
+ strip->blendmode = adt->act_blendmode;
+ strip->influence = adt->act_influence;
+ strip->extendmode = adt->act_extendmode;
+
+ if (adt->act_influence < 1.0f) {
+ /* enable "user-controlled" influence (which will insert a default keyframe)
+ * so that the influence doesn't get lost on the new update
+ *
+ * NOTE: An alternative way would have been to instead hack the influence
+ * to not get always get reset to full strength if NLASTRIP_FLAG_USR_INFLUENCE
+ * is disabled but auto-blending isn't being used. However, that approach
+ * is a bit hacky/hard to discover, and may cause backwards compatability issues,
+ * so it's better to just do it this way.
+ */
+ strip->flag |= NLASTRIP_FLAG_USR_INFLUENCE;
+ BKE_nlastrip_validate_fcurves(strip);
+ }
+ }
+
/* if the strip is the first one in the track it lives in, check if there
* are strips in any other tracks that may be before this, and set the extend
* mode accordingly
@@ -1757,7 +1825,8 @@ void BKE_nla_action_pushdown(AnimData *adt)
* so that it doesn't override strips in previous tracks
*/
/* FIXME: this needs to be more automated, since user can rearrange strips */
- strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD;
+ if (strip->extendmode == NLASTRIP_EXTEND_HOLD)
+ strip->extendmode = NLASTRIP_EXTEND_HOLD_FORWARD;
}
/* make strip the active one... */
diff --git a/source/blender/blenkernel/intern/node.c b/source/blender/blenkernel/intern/node.c
index 3f3b4896653..5d4b1ae8170 100644
--- a/source/blender/blenkernel/intern/node.c
+++ b/source/blender/blenkernel/intern/node.c
@@ -506,6 +506,26 @@ static bNodeSocket *make_socket(bNodeTree *ntree, bNode *UNUSED(node), int in_ou
return sock;
}
+void nodeModifySocketType(bNodeTree *ntree, bNode *UNUSED(node), bNodeSocket *sock,
+ int type, int subtype)
+{
+ const char *idname = nodeStaticSocketType(type, subtype);
+
+ if (!idname) {
+ printf("Error: static node socket type %d undefined\n", type);
+ return;
+ }
+
+ if (sock->default_value) {
+ MEM_freeN(sock->default_value);
+ sock->default_value = NULL;
+ }
+
+ sock->type = type;
+ BLI_strncpy(sock->idname, idname, sizeof(sock->idname));
+ node_socket_set_typeinfo(ntree, sock, nodeSocketTypeFind(idname));
+}
+
bNodeSocket *nodeAddSocket(bNodeTree *ntree, bNode *node, int in_out, const char *idname,
const char *identifier, const char *name)
{
@@ -902,80 +922,100 @@ bNode *nodeAddStaticNode(const struct bContext *C, bNodeTree *ntree, int type)
return nodeAddNode(C, ntree, idname);
}
-static void node_socket_copy(bNodeSocket *dst, bNodeSocket *src)
+static void node_socket_copy(bNodeSocket *sock_dst, bNodeSocket *sock_src, const int flag)
{
- src->new_sock = dst;
-
- if (src->prop)
- dst->prop = IDP_CopyProperty(src->prop);
-
- if (src->default_value)
- dst->default_value = MEM_dupallocN(src->default_value);
-
- dst->stack_index = 0;
+ sock_src->new_sock = sock_dst;
+
+ if (sock_src->prop) {
+ sock_dst->prop = IDP_CopyProperty_ex(sock_src->prop, flag);
+ }
+
+ if (sock_src->default_value) {
+ sock_dst->default_value = MEM_dupallocN(sock_src->default_value);
+ }
+
+ sock_dst->stack_index = 0;
/* XXX some compositor node (e.g. image, render layers) still store
* some persistent buffer data here, need to clear this to avoid dangling pointers.
*/
- dst->cache = NULL;
+ sock_dst->cache = NULL;
}
/* keep socket listorder identical, for copying links */
/* ntree is the target tree */
-bNode *nodeCopyNode(struct bNodeTree *ntree, struct bNode *node)
+bNode *BKE_node_copy_ex(bNodeTree *ntree, bNode *node_src, const int flag)
{
- bNode *nnode = MEM_callocN(sizeof(bNode), "dupli node");
- bNodeSocket *sock, *oldsock;
- bNodeLink *link, *oldlink;
+ bNode *node_dst = MEM_callocN(sizeof(bNode), "dupli node");
+ bNodeSocket *sock_dst, *sock_src;
+ bNodeLink *link_dst, *link_src;
- *nnode = *node;
+ *node_dst = *node_src;
/* can be called for nodes outside a node tree (e.g. clipboard) */
if (ntree) {
- nodeUniqueName(ntree, nnode);
+ nodeUniqueName(ntree, node_dst);
- BLI_addtail(&ntree->nodes, nnode);
+ BLI_addtail(&ntree->nodes, node_dst);
}
- BLI_duplicatelist(&nnode->inputs, &node->inputs);
- oldsock = node->inputs.first;
- for (sock = nnode->inputs.first; sock; sock = sock->next, oldsock = oldsock->next)
- node_socket_copy(sock, oldsock);
-
- BLI_duplicatelist(&nnode->outputs, &node->outputs);
- oldsock = node->outputs.first;
- for (sock = nnode->outputs.first; sock; sock = sock->next, oldsock = oldsock->next)
- node_socket_copy(sock, oldsock);
-
- if (node->prop)
- nnode->prop = IDP_CopyProperty(node->prop);
-
- BLI_duplicatelist(&nnode->internal_links, &node->internal_links);
- oldlink = node->internal_links.first;
- for (link = nnode->internal_links.first; link; link = link->next, oldlink = oldlink->next) {
- link->fromnode = nnode;
- link->tonode = nnode;
- link->fromsock = link->fromsock->new_sock;
- link->tosock = link->tosock->new_sock;
+ BLI_duplicatelist(&node_dst->inputs, &node_src->inputs);
+ for (sock_dst = node_dst->inputs.first, sock_src = node_src->inputs.first;
+ sock_dst != NULL;
+ sock_dst = sock_dst->next, sock_src = sock_src->next)
+ {
+ node_socket_copy(sock_dst, sock_src, flag);
}
-
- /* don't increase node->id users, freenode doesn't decrement either */
-
- if (node->typeinfo->copyfunc)
- node->typeinfo->copyfunc(ntree, nnode, node);
-
- node->new_node = nnode;
- nnode->new_node = NULL;
-
- if (nnode->typeinfo->copyfunc_api) {
+
+ BLI_duplicatelist(&node_dst->outputs, &node_src->outputs);
+ for (sock_dst = node_dst->outputs.first, sock_src = node_src->outputs.first;
+ sock_dst != NULL;
+ sock_dst = sock_dst->next, sock_src = sock_src->next)
+ {
+ node_socket_copy(sock_dst, sock_src, flag);
+ }
+
+ if (node_src->prop) {
+ node_dst->prop = IDP_CopyProperty_ex(node_src->prop, flag);
+ }
+
+ BLI_duplicatelist(&node_dst->internal_links, &node_src->internal_links);
+ for (link_dst = node_dst->internal_links.first, link_src = node_src->internal_links.first;
+ link_dst != NULL;
+ link_dst = link_dst->next, link_src = link_src->next)
+ {
+ link_dst->fromnode = node_dst;
+ link_dst->tonode = node_dst;
+ link_dst->fromsock = link_dst->fromsock->new_sock;
+ link_dst->tosock = link_dst->tosock->new_sock;
+ }
+
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus(node_dst->id);
+ }
+
+ if (node_src->typeinfo->copyfunc) {
+ node_src->typeinfo->copyfunc(ntree, node_dst, node_src);
+ }
+
+ node_src->new_node = node_dst;
+ node_dst->new_node = NULL;
+
+ if (node_dst->typeinfo->copyfunc_api) {
PointerRNA ptr;
- RNA_pointer_create((ID *)ntree, &RNA_Node, nnode, &ptr);
-
- nnode->typeinfo->copyfunc_api(&ptr, node);
+ RNA_pointer_create((ID *)ntree, &RNA_Node, node_dst, &ptr);
+
+ node_dst->typeinfo->copyfunc_api(&ptr, node_src);
}
-
- if (ntree)
+
+ if (ntree) {
ntree->update |= NTREE_UPDATE_NODES;
-
- return nnode;
+ }
+
+ return node_dst;
+}
+
+bNode *nodeCopyNode(bNodeTree *ntree, bNode *node)
+{
+ return BKE_node_copy_ex(ntree, node, LIB_ID_CREATE_NO_USER_REFCOUNT);
}
/* also used via rna api, so we check for proper input output direction */
@@ -1172,7 +1212,7 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname)
* node groups and other tree types are created as library data.
*/
if (bmain) {
- ntree = BKE_libblock_alloc(bmain, ID_NT, name);
+ ntree = BKE_libblock_alloc(bmain, ID_NT, name, 0);
}
else {
ntree = MEM_callocN(sizeof(bNodeTree), "new node tree");
@@ -1191,119 +1231,98 @@ bNodeTree *ntreeAddTree(Main *bmain, const char *name, const char *idname)
return ntree;
}
-/* Warning: this function gets called during some rather unexpected times
- * - this gets called when executing compositing updates (for threaded previews)
- * - when the nodetree datablock needs to be copied (i.e. when users get copied)
- * - for scene duplication use ntreeSwapID() after so we don't have stale pointers.
+/**
+ * Only copy internal data of NodeTree ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
*
- * do_make_extern: keep enabled for general use, only reason _not_ to enable is when
- * copying for internal use (threads for eg), where you wont want it to modify the
- * scene data.
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
*/
-static bNodeTree *ntreeCopyTree_internal(bNodeTree *ntree, Main *bmain, bool skip_database, bool do_id_user, bool do_make_extern, bool copy_previews)
+void BKE_node_tree_copy_data(Main *UNUSED(bmain), bNodeTree *ntree_dst, const bNodeTree *ntree_src, const int flag)
{
- bNodeTree *newtree;
- bNode *node /*, *nnode */ /* UNUSED */, *last;
- bNodeSocket *sock, *oldsock;
- bNodeLink *link;
-
- if (ntree == NULL) return NULL;
-
- /* is ntree part of library? */
- if (bmain && !skip_database && BLI_findindex(&bmain->nodetree, ntree) >= 0) {
- newtree = BKE_libblock_copy(bmain, &ntree->id);
- }
- else {
- newtree = BKE_libblock_copy_nolib(&ntree->id, true);
- }
+ bNodeSocket *sock_dst, *sock_src;
+ bNodeLink *link_dst;
- id_us_plus((ID *)newtree->gpd);
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
/* in case a running nodetree is copied */
- newtree->execdata = NULL;
+ ntree_dst->execdata = NULL;
- newtree->duplilock = NULL;
-
- BLI_listbase_clear(&newtree->nodes);
- BLI_listbase_clear(&newtree->links);
-
- last = ntree->nodes.last;
- for (node = ntree->nodes.first; node; node = node->next) {
+ ntree_dst->duplilock = NULL;
- /* ntreeUserDecrefID inline */
- if (do_id_user) {
- id_us_plus(node->id);
- }
+ BLI_listbase_clear(&ntree_dst->nodes);
+ BLI_listbase_clear(&ntree_dst->links);
- if (do_make_extern) {
- id_lib_extern(node->id);
- }
-
- node->new_node = NULL;
- /* nnode = */ nodeCopyNode(newtree, node); /* sets node->new */
-
- /* make sure we don't copy new nodes again! */
- if (node == last)
- break;
+ for (bNode *node_src = ntree_src->nodes.first; node_src; node_src = node_src->next) {
+ BKE_node_copy_ex(ntree_dst, node_src, flag_subdata);
}
-
+
/* copy links */
- BLI_duplicatelist(&newtree->links, &ntree->links);
- for (link = newtree->links.first; link; link = link->next) {
- link->fromnode = (link->fromnode ? link->fromnode->new_node : NULL);
- link->fromsock = (link->fromsock ? link->fromsock->new_sock : NULL);
- link->tonode = (link->tonode ? link->tonode->new_node : NULL);
- link->tosock = (link->tosock ? link->tosock->new_sock : NULL);
+ BLI_duplicatelist(&ntree_dst->links, &ntree_src->links);
+ for (link_dst = ntree_dst->links.first; link_dst; link_dst = link_dst->next) {
+ link_dst->fromnode = (link_dst->fromnode ? link_dst->fromnode->new_node : NULL);
+ link_dst->fromsock = (link_dst->fromsock ? link_dst->fromsock->new_sock : NULL);
+ link_dst->tonode = (link_dst->tonode ? link_dst->tonode->new_node : NULL);
+ link_dst->tosock = (link_dst->tosock ? link_dst->tosock->new_sock : NULL);
/* update the link socket's pointer */
- if (link->tosock)
- link->tosock->link = link;
+ if (link_dst->tosock) {
+ link_dst->tosock->link = link_dst;
+ }
}
-
+
/* copy interface sockets */
- BLI_duplicatelist(&newtree->inputs, &ntree->inputs);
- oldsock = ntree->inputs.first;
- for (sock = newtree->inputs.first; sock; sock = sock->next, oldsock = oldsock->next)
- node_socket_copy(sock, oldsock);
-
- BLI_duplicatelist(&newtree->outputs, &ntree->outputs);
- oldsock = ntree->outputs.first;
- for (sock = newtree->outputs.first; sock; sock = sock->next, oldsock = oldsock->next)
- node_socket_copy(sock, oldsock);
-
+ BLI_duplicatelist(&ntree_dst->inputs, &ntree_src->inputs);
+ for (sock_dst = ntree_dst->inputs.first, sock_src = ntree_src->inputs.first;
+ sock_dst != NULL;
+ sock_dst = sock_dst->next, sock_src = sock_src->next)
+ {
+ node_socket_copy(sock_dst, sock_src, flag_subdata);
+ }
+
+ BLI_duplicatelist(&ntree_dst->outputs, &ntree_src->outputs);
+ for (sock_dst = ntree_dst->outputs.first, sock_src = ntree_src->outputs.first;
+ sock_dst != NULL;
+ sock_dst = sock_dst->next, sock_src = sock_src->next)
+ {
+ node_socket_copy(sock_dst, sock_src, flag_subdata);
+ }
+
/* copy preview hash */
- if (ntree->previews && copy_previews) {
+ if (ntree_src->previews && (flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
bNodeInstanceHashIterator iter;
-
- newtree->previews = BKE_node_instance_hash_new("node previews");
-
- NODE_INSTANCE_HASH_ITER(iter, ntree->previews) {
+
+ ntree_dst->previews = BKE_node_instance_hash_new("node previews");
+
+ NODE_INSTANCE_HASH_ITER(iter, ntree_src->previews) {
bNodeInstanceKey key = BKE_node_instance_hash_iterator_get_key(&iter);
bNodePreview *preview = BKE_node_instance_hash_iterator_get_value(&iter);
- BKE_node_instance_hash_insert(newtree->previews, key, BKE_node_preview_copy(preview));
+ BKE_node_instance_hash_insert(ntree_dst->previews, key, BKE_node_preview_copy(preview));
}
}
- else
- newtree->previews = NULL;
-
+ else {
+ ntree_dst->previews = NULL;
+ }
+
/* update node->parent pointers */
- for (node = newtree->nodes.first; node; node = node->next) {
- if (node->parent)
- node->parent = node->parent->new_node;
+ for (bNode *node_dst = ntree_dst->nodes.first, *node_src = ntree_src->nodes.first; node_dst; node_dst = node_dst->next, node_src = node_src->next) {
+ if (node_dst->parent) {
+ node_dst->parent = node_dst->parent->new_node;
+ }
}
-
- /* node tree will generate its own interface type */
- newtree->interface_type = NULL;
-
- BKE_id_copy_ensure_local(bmain, &ntree->id, &newtree->id);
- return newtree;
+ /* node tree will generate its own interface type */
+ ntree_dst->interface_type = NULL;
}
-bNodeTree *ntreeCopyTree_ex(bNodeTree *ntree, Main *bmain, const bool do_id_user)
+bNodeTree *ntreeCopyTree_ex(const bNodeTree *ntree, Main *bmain, const bool do_id_user)
{
- return ntreeCopyTree_internal(ntree, bmain, false, do_id_user, true, true);
+ bNodeTree *ntree_copy;
+ BKE_id_copy_ex(bmain, (ID *)ntree, (ID **)&ntree_copy, do_id_user ? 0 : LIB_ID_CREATE_NO_USER_REFCOUNT, false);
+ return ntree_copy;
}
-bNodeTree *ntreeCopyTree(Main *bmain, bNodeTree *ntree)
+bNodeTree *ntreeCopyTree(Main *bmain, const bNodeTree *ntree)
{
return ntreeCopyTree_ex(ntree, bmain, true);
}
@@ -1326,7 +1345,7 @@ void ntreeUserDecrefID(bNodeTree *ntree)
/* *************** Node Preview *********** */
/* XXX this should be removed eventually ...
- * Currently BKE functions are modelled closely on previous code,
+ * Currently BKE functions are modeled closely on previous code,
* using BKE_node_preview_init_tree to set up previews for a whole node tree in advance.
* This should be left more to the individual node tree implementations.
*/
@@ -1698,11 +1717,12 @@ static void node_free_node_ex(bNodeTree *ntree, bNode *node, bool remove_animdat
ntreeTexEndExecTree(ntree->execdata);
ntree->execdata = NULL;
}
-
- if (node->typeinfo->freefunc)
- node->typeinfo->freefunc(node);
}
-
+
+ if (node->typeinfo->freefunc) {
+ node->typeinfo->freefunc(node);
+ }
+
for (sock = node->inputs.first; sock; sock = nextsock) {
nextsock = sock->next;
node_socket_free(ntree, sock, node);
@@ -1828,7 +1848,7 @@ void ntreeFreeTree(bNodeTree *ntree)
if (tntree == ntree)
break;
if (tntree == NULL) {
- BKE_libblock_free_data(G.main, &ntree->id);
+ BKE_libblock_free_data(&ntree->id, true);
}
}
@@ -1991,10 +2011,11 @@ bNodeTree *ntreeLocalize(bNodeTree *ntree)
adt->tmpact = NULL;
}
- /* Make full copy.
+ /* Make full copy outside of Main database.
* Note: previews are not copied here.
*/
- ltree = ntreeCopyTree_internal(ntree, G.main, true, false, false, false);
+ BKE_id_copy_ex(G.main, (ID *)ntree, (ID **)&ltree,
+ LIB_ID_CREATE_NO_MAIN | LIB_ID_CREATE_NO_USER_REFCOUNT | LIB_ID_COPY_NO_PREVIEW, false);
ltree->flag |= NTREE_IS_LOCALIZED;
for (node = ltree->nodes.first; node; node = node->next) {
@@ -2234,7 +2255,7 @@ static void ntree_interface_type_create(bNodeTree *ntree)
/* register a subtype of PropertyGroup */
srna = RNA_def_struct_ptr(&BLENDER_RNA, identifier, &RNA_PropertyGroup);
RNA_def_struct_ui_text(srna, name, description);
- RNA_def_struct_duplicate_pointers(srna);
+ RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna);
/* associate the RNA type with the node tree */
ntree->interface_type = srna;
@@ -2273,10 +2294,10 @@ StructRNA *ntreeInterfaceTypeGet(bNodeTree *ntree, int create)
ntree_interface_identifier(ntree, base, identifier, sizeof(identifier), name, description);
/* rename the RNA type */
- RNA_def_struct_free_pointers(srna);
- RNA_def_struct_identifier(srna, identifier);
+ RNA_def_struct_free_pointers(&BLENDER_RNA, srna);
+ RNA_def_struct_identifier(&BLENDER_RNA, srna, identifier);
RNA_def_struct_ui_text(srna, name, description);
- RNA_def_struct_duplicate_pointers(srna);
+ RNA_def_struct_duplicate_pointers(&BLENDER_RNA, srna);
}
}
else if (create) {
@@ -2629,7 +2650,7 @@ void BKE_node_clipboard_add_node(bNode *node)
node_info->id = node->id;
if (node->id) {
BLI_strncpy(node_info->id_name, node->id->name, sizeof(node_info->id_name));
- if (ID_IS_LINKED_DATABLOCK(node->id)) {
+ if (ID_IS_LINKED(node->id)) {
BLI_strncpy(node_info->library_name, node->id->lib->filepath, sizeof(node_info->library_name));
}
else {
@@ -2766,7 +2787,7 @@ int BKE_node_instance_hash_haskey(bNodeInstanceHash *hash, bNodeInstanceKey key)
int BKE_node_instance_hash_size(bNodeInstanceHash *hash)
{
- return BLI_ghash_size(hash->ghash);
+ return BLI_ghash_len(hash->ghash);
}
void BKE_node_instance_hash_clear_tags(bNodeInstanceHash *hash)
@@ -3172,12 +3193,24 @@ void nodeSynchronizeID(bNode *node, bool copy_to_id)
void nodeLabel(bNodeTree *ntree, bNode *node, char *label, int maxlen)
{
- if (node->label[0] != '\0')
+ label[0] = '\0';
+
+ if (node->label[0] != '\0') {
BLI_strncpy(label, node->label, maxlen);
- else if (node->typeinfo->labelfunc)
+ }
+ else if (node->typeinfo->labelfunc) {
node->typeinfo->labelfunc(ntree, node, label, maxlen);
- else
- BLI_strncpy(label, IFACE_(node->typeinfo->ui_name), maxlen);
+ }
+
+ /* The previous methods (labelfunc) could not provide an adequate label for the node. */
+ if (label[0] == '\0') {
+ /* Kind of hacky and weak... Ideally would be better to use RNA here. :| */
+ const char *tmp = CTX_IFACE_(BLT_I18NCONTEXT_ID_NODETREE, node->typeinfo->ui_name);
+ if (tmp == node->typeinfo->ui_name) {
+ tmp = IFACE_(node->typeinfo->ui_name);
+ }
+ BLI_strncpy(label, tmp, maxlen);
+ }
}
static void node_type_base_defaults(bNodeType *ntype)
@@ -3555,6 +3588,9 @@ static void registerShaderNodes(void)
register_node_type_sh_hue_sat();
register_node_type_sh_attribute();
+ register_node_type_sh_bevel();
+ register_node_type_sh_displacement();
+ register_node_type_sh_vector_displacement();
register_node_type_sh_geometry();
register_node_type_sh_light_path();
register_node_type_sh_light_falloff();
@@ -3568,6 +3604,7 @@ static void registerShaderNodes(void)
register_node_type_sh_background();
register_node_type_sh_bsdf_anisotropic();
register_node_type_sh_bsdf_diffuse();
+ register_node_type_sh_bsdf_principled();
register_node_type_sh_bsdf_glossy();
register_node_type_sh_bsdf_glass();
register_node_type_sh_bsdf_translucent();
@@ -3579,6 +3616,7 @@ static void registerShaderNodes(void)
register_node_type_sh_holdout();
register_node_type_sh_volume_absorption();
register_node_type_sh_volume_scatter();
+ register_node_type_sh_volume_principled();
register_node_type_sh_subsurface_scattering();
register_node_type_sh_mix_shader();
register_node_type_sh_add_shader();
diff --git a/source/blender/blenkernel/intern/object.c b/source/blender/blenkernel/intern/object.c
index 6e754755cf3..22a4db94d07 100644
--- a/source/blender/blenkernel/intern/object.c
+++ b/source/blender/blenkernel/intern/object.c
@@ -127,6 +127,7 @@
#endif
#include "CCGSubSurf.h"
+#include "atomic_ops.h"
#include "GPU_material.h"
@@ -200,12 +201,12 @@ void BKE_object_free_curve_cache(Object *ob)
}
}
-void BKE_object_free_modifiers(Object *ob)
+void BKE_object_free_modifiers(Object *ob, const int flag)
{
ModifierData *md;
while ((md = BLI_pophead(&ob->modifiers))) {
- modifier_free(md);
+ modifier_free_ex(md, flag);
}
/* particle modifiers were freed, so free the particlesystems as well */
@@ -240,7 +241,7 @@ void BKE_object_modifier_hook_reset(Object *ob, HookModifierData *hmd)
}
}
-bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
+bool BKE_object_support_modifier_type_check(const Object *ob, int modifier_type)
{
const ModifierTypeInfo *mti;
@@ -267,7 +268,7 @@ bool BKE_object_support_modifier_type_check(Object *ob, int modifier_type)
void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_src)
{
ModifierData *md;
- BKE_object_free_modifiers(ob_dst);
+ BKE_object_free_modifiers(ob_dst, 0);
if (!ELEM(ob_dst->type, OB_MESH, OB_CURVE, OB_SURF, OB_FONT, OB_LATTICE)) {
/* only objects listed above can have modifiers and linking them to objects
@@ -311,7 +312,7 @@ void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_sr
modifier_unique_name(&ob_dst->modifiers, nmd);
}
- BKE_object_copy_particlesystems(ob_dst, ob_src);
+ BKE_object_copy_particlesystems(ob_dst, ob_src, 0);
/* TODO: smoke?, cloth? */
}
@@ -319,19 +320,24 @@ void BKE_object_link_modifiers(struct Object *ob_dst, const struct Object *ob_sr
/* free data derived from mesh, called when mesh changes or is freed */
void BKE_object_free_derived_caches(Object *ob)
{
- /* also serves as signal to remake texspace */
+ /* Also serves as signal to remake texspace.
+ *
+ * NOTE: This function can be called from threads on different objects
+ * sharing same data datablock. So we need to ensure atomic nature of
+ * data modification here.
+ */
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
if (me && me->bb) {
- me->bb->flag |= BOUNDBOX_DIRTY;
+ atomic_fetch_and_or_int32(&me->bb->flag, BOUNDBOX_DIRTY);
}
}
else if (ELEM(ob->type, OB_SURF, OB_CURVE, OB_FONT)) {
Curve *cu = ob->data;
if (cu && cu->bb) {
- cu->bb->flag |= BOUNDBOX_DIRTY;
+ atomic_fetch_and_or_int32(&cu->bb->flag, BOUNDBOX_DIRTY);
}
}
@@ -404,7 +410,8 @@ void BKE_object_free(Object *ob)
{
BKE_animdata_free((ID *)ob, false);
- BKE_object_free_modifiers(ob);
+ /* BKE_<id>_free shall never touch to ID->us. Never ever. */
+ BKE_object_free_modifiers(ob, LIB_ID_CREATE_NO_USER_REFCOUNT);
MEM_SAFE_FREE(ob->mat);
MEM_SAFE_FREE(ob->matbits);
@@ -461,7 +468,7 @@ void BKE_object_free(Object *ob)
}
/* actual check for internal data, not context or flags */
-bool BKE_object_is_in_editmode(Object *ob)
+bool BKE_object_is_in_editmode(const Object *ob)
{
if (ob->data == NULL)
return false;
@@ -504,13 +511,13 @@ bool BKE_object_is_in_editmode(Object *ob)
return false;
}
-bool BKE_object_is_in_editmode_vgroup(Object *ob)
+bool BKE_object_is_in_editmode_vgroup(const Object *ob)
{
return (OB_TYPE_SUPPORT_VGROUP(ob->type) &&
BKE_object_is_in_editmode(ob));
}
-bool BKE_object_is_in_wpaint_select_vert(Object *ob)
+bool BKE_object_is_in_wpaint_select_vert(const Object *ob)
{
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
@@ -522,7 +529,7 @@ bool BKE_object_is_in_wpaint_select_vert(Object *ob)
return false;
}
-bool BKE_object_exists_check(Object *obtest)
+bool BKE_object_exists_check(const Object *obtest)
{
Object *ob;
@@ -664,7 +671,7 @@ Object *BKE_object_add_only_object(Main *bmain, int type, const char *name)
if (!name)
name = get_obdata_defname(type);
- ob = BKE_libblock_alloc(bmain, ID_OB, name);
+ ob = BKE_libblock_alloc(bmain, ID_OB, name, 0);
/* default object vars */
ob->type = type;
@@ -831,7 +838,7 @@ struct Object *BKE_object_lod_matob_get(Object *ob, Scene *scene)
#endif /* WITH_GAMEENGINE */
-SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
+SoftBody *copy_softbody(const SoftBody *sb, const int flag)
{
SoftBody *sbn;
@@ -839,7 +846,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
sbn = MEM_dupallocN(sb);
- if (copy_caches == false) {
+ if ((flag & LIB_ID_COPY_CACHES) == 0) {
sbn->totspring = sbn->totpoint = 0;
sbn->bpoint = NULL;
sbn->bspring = NULL;
@@ -868,7 +875,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
sbn->scratch = NULL;
- sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, copy_caches);
+ sbn->pointcache = BKE_ptcache_copy_list(&sbn->ptcaches, &sb->ptcaches, flag);
if (sb->effector_weights)
sbn->effector_weights = MEM_dupallocN(sb->effector_weights);
@@ -876,7 +883,7 @@ SoftBody *copy_softbody(const SoftBody *sb, bool copy_caches)
return sbn;
}
-BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
+BulletSoftBody *copy_bulletsoftbody(const BulletSoftBody *bsb, const int UNUSED(flag))
{
BulletSoftBody *bsbn;
@@ -887,7 +894,7 @@ BulletSoftBody *copy_bulletsoftbody(BulletSoftBody *bsb)
return bsbn;
}
-ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
+ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys, const int flag)
{
ParticleSystem *psysn;
ParticleData *pa;
@@ -924,7 +931,7 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
if (psys->clmd) {
psysn->clmd = (ClothModifierData *)modifier_new(eModifierType_Cloth);
- modifier_copyData((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd);
+ modifier_copyData_ex((ModifierData *)psys->clmd, (ModifierData *)psysn->clmd, flag);
psys->hair_in_dm = psys->hair_out_dm = NULL;
}
@@ -942,7 +949,8 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
BLI_listbase_clear(&psysn->childcachebufs);
psysn->renderdata = NULL;
- psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, false);
+ /* XXX Never copy caches here? */
+ psysn->pointcache = BKE_ptcache_copy_list(&psysn->ptcaches, &psys->ptcaches, flag & ~LIB_ID_COPY_CACHES);
/* XXX - from reading existing code this seems correct but intended usage of
* pointcache should /w cloth should be added in 'ParticleSystem' - campbell */
@@ -950,12 +958,14 @@ ParticleSystem *BKE_object_copy_particlesystem(ParticleSystem *psys)
psysn->clmd->point_cache = psysn->pointcache;
}
- id_us_plus((ID *)psysn->part);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)psysn->part);
+ }
return psysn;
}
-void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src)
+void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src, const int flag)
{
ParticleSystem *psys, *npsys;
ModifierData *md;
@@ -967,7 +977,7 @@ void BKE_object_copy_particlesystems(Object *ob_dst, const Object *ob_src)
BLI_listbase_clear(&ob_dst->particlesystem);
for (psys = ob_src->particlesystem.first; psys; psys = psys->next) {
- npsys = BKE_object_copy_particlesystem(psys);
+ npsys = BKE_object_copy_particlesystem(psys, flag);
BLI_addtail(&ob_dst->particlesystem, npsys);
@@ -1004,23 +1014,25 @@ void BKE_object_copy_softbody(Object *ob_dst, const Object *ob_src)
{
if (ob_src->soft) {
ob_dst->softflag = ob_src->softflag;
- ob_dst->soft = copy_softbody(ob_src->soft, false);
+ ob_dst->soft = copy_softbody(ob_src->soft, 0);
}
}
-static void copy_object_pose(Object *obn, Object *ob)
+static void copy_object_pose(Object *obn, const Object *ob, const int flag)
{
bPoseChannel *chan;
/* note: need to clear obn->pose pointer first, so that BKE_pose_copy_data works (otherwise there's a crash) */
obn->pose = NULL;
- BKE_pose_copy_data(&obn->pose, ob->pose, 1); /* 1 = copy constraints */
+ BKE_pose_copy_data_ex(&obn->pose, ob->pose, flag, true); /* true = copy constraints */
for (chan = obn->pose->chanbase.first; chan; chan = chan->next) {
bConstraint *con;
chan->flag &= ~(POSE_LOC | POSE_ROT | POSE_SIZE);
+ /* XXX Remapping object pointing onto itself should be handled by generic BKE_library_remap stuff, but...
+ * the flush_constraint_targets callback am not sure about, so will delay that for now. */
for (con = chan->constraints.first; con; con = con->next) {
const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
ListBase targets = {NULL, NULL};
@@ -1041,17 +1053,14 @@ static void copy_object_pose(Object *obn, Object *ob)
}
}
-static void copy_object_lod(Object *obn, Object *ob)
+static void copy_object_lod(Object *obn, const Object *ob, const int UNUSED(flag))
{
BLI_duplicatelist(&obn->lodlevels, &ob->lodlevels);
- if (obn->lodlevels.first)
- ((LodLevel *)obn->lodlevels.first)->source = obn;
-
obn->currentlod = (LodLevel *)obn->lodlevels.first;
}
-bool BKE_object_pose_context_check(Object *ob)
+bool BKE_object_pose_context_check(const Object *ob)
{
if ((ob) &&
(ob->type == OB_ARMATURE) &&
@@ -1092,97 +1101,99 @@ void BKE_object_transform_copy(Object *ob_tar, const Object *ob_src)
copy_v3_v3(ob_tar->size, ob_src->size);
}
-Object *BKE_object_copy_ex(Main *bmain, Object *ob, bool copy_caches)
+/**
+ * Only copy internal data of Object ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_object_copy_data(Main *UNUSED(bmain), Object *ob_dst, const Object *ob_src, const int flag)
{
- Object *obn;
ModifierData *md;
- int a;
- obn = BKE_libblock_copy(bmain, &ob->id);
-
- if (ob->totcol) {
- obn->mat = MEM_dupallocN(ob->mat);
- obn->matbits = MEM_dupallocN(ob->matbits);
- obn->totcol = ob->totcol;
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
+
+ if (ob_src->totcol) {
+ ob_dst->mat = MEM_dupallocN(ob_src->mat);
+ ob_dst->matbits = MEM_dupallocN(ob_src->matbits);
+ ob_dst->totcol = ob_src->totcol;
}
- if (ob->iuser) obn->iuser = MEM_dupallocN(ob->iuser);
+ if (ob_src->iuser) ob_dst->iuser = MEM_dupallocN(ob_src->iuser);
- if (ob->bb) obn->bb = MEM_dupallocN(ob->bb);
- obn->flag &= ~OB_FROMGROUP;
+ if (ob_src->bb) ob_dst->bb = MEM_dupallocN(ob_src->bb);
+ ob_dst->flag &= ~OB_FROMGROUP;
- BLI_listbase_clear(&obn->modifiers);
+ BLI_listbase_clear(&ob_dst->modifiers);
- for (md = ob->modifiers.first; md; md = md->next) {
+ for (md = ob_src->modifiers.first; md; md = md->next) {
ModifierData *nmd = modifier_new(md->type);
BLI_strncpy(nmd->name, md->name, sizeof(nmd->name));
- modifier_copyData(md, nmd);
- BLI_addtail(&obn->modifiers, nmd);
+ modifier_copyData_ex(md, nmd, flag_subdata);
+ BLI_addtail(&ob_dst->modifiers, nmd);
}
- BLI_listbase_clear(&obn->prop);
- BKE_bproperty_copy_list(&obn->prop, &ob->prop);
+ BLI_listbase_clear(&ob_dst->prop);
+ BKE_bproperty_copy_list(&ob_dst->prop, &ob_src->prop);
- BKE_sca_logic_copy(obn, ob);
+ BKE_sca_logic_copy(ob_dst, ob_src, flag_subdata);
- if (ob->pose) {
- copy_object_pose(obn, ob);
+ if (ob_src->pose) {
+ copy_object_pose(ob_dst, ob_src, flag_subdata);
/* backwards compat... non-armatures can get poses in older files? */
- if (ob->type == OB_ARMATURE)
- BKE_pose_rebuild(obn, obn->data);
+ if (ob_src->type == OB_ARMATURE)
+ BKE_pose_rebuild(ob_dst, ob_dst->data);
}
- defgroup_copy_list(&obn->defbase, &ob->defbase);
- BKE_constraints_copy(&obn->constraints, &ob->constraints, true);
-
- obn->mode = OB_MODE_OBJECT;
- obn->sculpt = NULL;
+ defgroup_copy_list(&ob_dst->defbase, &ob_src->defbase);
+ BKE_constraints_copy_ex(&ob_dst->constraints, &ob_src->constraints, flag_subdata, true);
- /* increase user numbers */
- id_us_plus((ID *)obn->data);
- id_us_plus((ID *)obn->gpd);
- id_us_plus((ID *)obn->dup_group);
+ ob_dst->mode = OB_MODE_OBJECT;
+ ob_dst->sculpt = NULL;
- for (a = 0; a < obn->totcol; a++) id_us_plus((ID *)obn->mat[a]);
-
- if (ob->pd) {
- obn->pd = MEM_dupallocN(ob->pd);
- if (obn->pd->tex)
- id_us_plus(&(obn->pd->tex->id));
- if (obn->pd->rng)
- obn->pd->rng = MEM_dupallocN(ob->pd->rng);
+ if (ob_src->pd) {
+ ob_dst->pd = MEM_dupallocN(ob_src->pd);
+ if (ob_dst->pd->rng) {
+ ob_dst->pd->rng = MEM_dupallocN(ob_src->pd->rng);
+ }
}
- obn->soft = copy_softbody(ob->soft, copy_caches);
- obn->bsoft = copy_bulletsoftbody(ob->bsoft);
- obn->rigidbody_object = BKE_rigidbody_copy_object(ob);
- obn->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob);
+ ob_dst->soft = copy_softbody(ob_src->soft, flag_subdata);
+ ob_dst->bsoft = copy_bulletsoftbody(ob_src->bsoft, flag_subdata);
+ ob_dst->rigidbody_object = BKE_rigidbody_copy_object(ob_src, flag_subdata);
+ ob_dst->rigidbody_constraint = BKE_rigidbody_copy_constraint(ob_src, flag_subdata);
- BKE_object_copy_particlesystems(obn, ob);
+ BKE_object_copy_particlesystems(ob_dst, ob_src, flag_subdata);
- obn->derivedDeform = NULL;
- obn->derivedFinal = NULL;
+ ob_dst->derivedDeform = NULL;
+ ob_dst->derivedFinal = NULL;
- BLI_listbase_clear(&obn->gpulamp);
- BLI_listbase_clear(&obn->pc_ids);
+ BLI_listbase_clear(&ob_dst->gpulamp);
+ BLI_listbase_clear(&ob_dst->pc_ids);
- obn->mpath = NULL;
+ ob_dst->mpath = NULL;
- copy_object_lod(obn, ob);
+ copy_object_lod(ob_dst, ob_src, flag_subdata);
- /* Copy runtime surve data. */
- obn->curve_cache = NULL;
-
- BKE_id_copy_ensure_local(bmain, &ob->id, &obn->id);
+ /* Do not copy runtime curve data. */
+ ob_dst->curve_cache = NULL;
/* Do not copy object's preview (mostly due to the fact renderers create temp copy of objects). */
- obn->preview = NULL;
-
- return obn;
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0 && false) { /* XXX TODO temp hack */
+ BKE_previewimg_id_copy(&ob_dst->id, &ob_src->id);
+ }
+ else {
+ ob_dst->preview = NULL;
+ }
}
/* copy objects, will re-initialize cached simulation data */
-Object *BKE_object_copy(Main *bmain, Object *ob)
+Object *BKE_object_copy(Main *bmain, const Object *ob)
{
- return BKE_object_copy_ex(bmain, ob, false);
+ Object *ob_copy;
+ BKE_id_copy_ex(bmain, &ob->id, (ID **)&ob_copy, 0, false);
+ return ob_copy;
}
void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, const bool clear_proxy)
@@ -1195,7 +1206,7 @@ void BKE_object_make_local_ex(Main *bmain, Object *ob, const bool lib_local, con
* In case we make a whole lib's content local, we always want to localize, and we skip remapping (done later).
*/
- if (!ID_IS_LINKED_DATABLOCK(ob)) {
+ if (!ID_IS_LINKED(ob)) {
return;
}
@@ -1235,17 +1246,17 @@ void BKE_object_make_local(Main *bmain, Object *ob, const bool lib_local)
}
/* Returns true if the Object is from an external blend file (libdata) */
-bool BKE_object_is_libdata(Object *ob)
+bool BKE_object_is_libdata(const Object *ob)
{
- return (ob && ID_IS_LINKED_DATABLOCK(ob));
+ return (ob && ID_IS_LINKED(ob));
}
/* Returns true if the Object data is from an external blend file (libdata) */
-bool BKE_object_obdata_is_libdata(Object *ob)
+bool BKE_object_obdata_is_libdata(const Object *ob)
{
/* Linked objects with local obdata are forbidden! */
- BLI_assert(!ob || !ob->data || (ID_IS_LINKED_DATABLOCK(ob) ? ID_IS_LINKED_DATABLOCK(ob->data) : true));
- return (ob && ob->data && ID_IS_LINKED_DATABLOCK(ob->data));
+ BLI_assert(!ob || !ob->data || (ID_IS_LINKED(ob) ? ID_IS_LINKED(ob->data) : true));
+ return (ob && ob->data && ID_IS_LINKED(ob->data));
}
/* *************** PROXY **************** */
@@ -1292,7 +1303,7 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
/* only on local objects because this causes indirect links
* 'a -> b -> c', blend to point directly to a.blend
* when a.blend has a proxy thats linked into c.blend */
- if (!ID_IS_LINKED_DATABLOCK(ob))
+ if (!ID_IS_LINKED(ob))
id_lib_extern((ID *)dtar->id);
}
}
@@ -1310,7 +1321,7 @@ void BKE_object_copy_proxy_drivers(Object *ob, Object *target)
void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
{
/* paranoia checks */
- if (ID_IS_LINKED_DATABLOCK(ob) || !ID_IS_LINKED_DATABLOCK(target)) {
+ if (ID_IS_LINKED(ob) || !ID_IS_LINKED(target)) {
printf("cannot make proxy\n");
return;
}
@@ -1380,7 +1391,7 @@ void BKE_object_make_proxy(Object *ob, Object *target, Object *gob)
/* type conversions */
if (target->type == OB_ARMATURE) {
- copy_object_pose(ob, target); /* data copy, object pointers in constraints */
+ copy_object_pose(ob, target, 0); /* data copy, object pointers in constraints */
BKE_pose_rest(ob->pose); /* clear all transforms in channels */
BKE_pose_rebuild(ob, ob->data); /* set all internal links */
@@ -2576,6 +2587,28 @@ bool BKE_object_parent_loop_check(const Object *par, const Object *ob)
return BKE_object_parent_loop_check(par->parent, ob);
}
+static void object_handle_update_proxy(EvaluationContext *eval_ctx,
+ Scene *scene,
+ Object *object,
+ const bool do_proxy_update)
+{
+ /* The case when this is a group proxy, object_update is called in group.c */
+ if (object->proxy == NULL) {
+ return;
+ }
+ /* set pointer in library proxy target, for copying, but restore it */
+ object->proxy->proxy_from = object;
+ // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
+
+ /* the no-group proxy case, we call update */
+ if (object->proxy_group == NULL) {
+ if (do_proxy_update) {
+ // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
+ BKE_object_handle_update(eval_ctx, scene, object->proxy);
+ }
+ }
+}
+
/* proxy rule: lib_object->proxy_from == the one we borrow from, only set temporal and cleared here */
/* local_object->proxy == pointer to library object, saved in files and read */
@@ -2589,75 +2622,49 @@ void BKE_object_handle_update_ex(EvaluationContext *eval_ctx,
RigidBodyWorld *rbw,
const bool do_proxy_update)
{
- if (ob->recalc & OB_RECALC_ALL) {
- /* speed optimization for animation lookups */
- if (ob->pose) {
- BKE_pose_channels_hash_make(ob->pose);
- if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
- BKE_pose_update_constraint_flags(ob->pose);
- }
+ if ((ob->recalc & OB_RECALC_ALL) == 0) {
+ object_handle_update_proxy(eval_ctx, scene, ob, do_proxy_update);
+ return;
+ }
+ /* Speed optimization for animation lookups. */
+ if (ob->pose != NULL) {
+ BKE_pose_channels_hash_make(ob->pose);
+ if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
+ BKE_pose_update_constraint_flags(ob->pose);
}
-
- if (ob->recalc & OB_RECALC_DATA) {
- if (ob->type == OB_ARMATURE) {
- /* this happens for reading old files and to match library armatures
- * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
- * is evaluated on the rebuilt pose, otherwise we get incorrect poses
- * on file load */
- if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
- BKE_pose_rebuild(ob, ob->data);
- }
+ }
+ if (ob->recalc & OB_RECALC_DATA) {
+ if (ob->type == OB_ARMATURE) {
+ /* this happens for reading old files and to match library armatures
+ * with poses we do it ahead of BKE_object_where_is_calc to ensure animation
+ * is evaluated on the rebuilt pose, otherwise we get incorrect poses
+ * on file load */
+ if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC))
+ BKE_pose_rebuild(ob, ob->data);
}
-
- /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers,
- * which is only in BKE_object_where_is_calc now */
- /* XXX: should this case be OB_RECALC_OB instead? */
- if (ob->recalc & OB_RECALC_ALL) {
-
- if (G.debug & G_DEBUG_DEPSGRAPH)
- printf("recalcob %s\n", ob->id.name + 2);
-
- /* handle proxy copy for target */
- if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from) {
- // printf("ob proxy copy, lib ob %s proxy %s\n", ob->id.name, ob->proxy_from->id.name);
- if (ob->proxy_from->proxy_group) { /* transform proxy into group space */
- Object *obg = ob->proxy_from->proxy_group;
- float imat[4][4];
- invert_m4_m4(imat, obg->obmat);
- mul_m4_m4m4(ob->obmat, imat, ob->proxy_from->obmat);
- if (obg->dup_group) { /* should always be true */
- add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
- }
- }
- else
- copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
- }
- else
- BKE_object_where_is_calc_ex(scene, rbw, ob, NULL);
+ }
+ /* XXX new animsys warning: depsgraph tag OB_RECALC_DATA should not skip drivers,
+ * which is only in BKE_object_where_is_calc now */
+ /* XXX: should this case be OB_RECALC_OB instead? */
+ if (ob->recalc & OB_RECALC_ALL) {
+ if (G.debug & G_DEBUG_DEPSGRAPH_EVAL) {
+ printf("recalcob %s\n", ob->id.name + 2);
}
-
- if (ob->recalc & OB_RECALC_DATA) {
- BKE_object_handle_data_update(eval_ctx, scene, ob);
+ /* Handle proxy copy for target. */
+ if (!BKE_object_eval_proxy_copy(eval_ctx, ob)) {
+ BKE_object_where_is_calc_ex(scene, rbw, ob, NULL);
}
+ }
- ob->recalc &= ~OB_RECALC_ALL;
+ if (ob->recalc & OB_RECALC_DATA) {
+ BKE_object_handle_data_update(eval_ctx, scene, ob);
}
- /* the case when this is a group proxy, object_update is called in group.c */
- if (ob->proxy) {
- /* set pointer in library proxy target, for copying, but restore it */
- ob->proxy->proxy_from = ob;
- // printf("set proxy pointer for later group stuff %s\n", ob->id.name);
+ ob->recalc &= ~OB_RECALC_ALL;
- /* the no-group proxy case, we call update */
- if (ob->proxy_group == NULL) {
- if (do_proxy_update) {
- // printf("call update, lib ob %s proxy %s\n", ob->proxy->id.name, ob->id.name);
- BKE_object_handle_update(eval_ctx, scene, ob->proxy);
- }
- }
- }
+ object_handle_update_proxy(eval_ctx, scene, ob, do_proxy_update);
}
+
/* WARNING: "scene" here may not be the scene object actually resides in.
* When dealing with background-sets, "scene" is actually the active scene.
* e.g. "scene" <-- set 1 <-- set 2 ("ob" lives here) <-- set 3 <-- ... <-- set n
@@ -2672,7 +2679,7 @@ void BKE_object_sculpt_modifiers_changed(Object *ob)
{
SculptSession *ss = ob->sculpt;
- if (ss) {
+ if (ss && ss->building_vp_handle == false) {
if (!ss->cache) {
/* we free pbvh on changes, except during sculpt since it can't deal with
* changing PVBH node organization, we hope topology does not change in
@@ -2683,6 +2690,9 @@ void BKE_object_sculpt_modifiers_changed(Object *ob)
}
BKE_sculptsession_free_deformMats(ob->sculpt);
+
+ /* In vertex/weight paint, force maps to be rebuilt. */
+ BKE_sculptsession_free_vwpaint_data(ob->sculpt);
}
else {
PBVHNode **nodes;
@@ -3020,7 +3030,7 @@ bool BKE_object_flag_test_recursive(const Object *ob, short flag)
}
}
-bool BKE_object_is_child_recursive(Object *ob_parent, Object *ob_child)
+bool BKE_object_is_child_recursive(const Object *ob_parent, const Object *ob_child)
{
for (ob_child = ob_child->parent; ob_child; ob_child = ob_child->parent) {
if (ob_child == ob_parent) {
diff --git a/source/blender/blenkernel/intern/object_deform.c b/source/blender/blenkernel/intern/object_deform.c
index ccf2aec5c7a..61533e13d7a 100644
--- a/source/blender/blenkernel/intern/object_deform.c
+++ b/source/blender/blenkernel/intern/object_deform.c
@@ -42,7 +42,7 @@
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
@@ -457,6 +457,70 @@ void BKE_object_defgroup_remove_all(struct Object *ob)
BKE_object_defgroup_remove_all_ex(ob, false);
}
+/**
+ * Compute mapping for vertex groups with matching name, -1 is used for no remapping.
+ * Returns null if no remapping is required.
+ * The returned array has to be freed.
+ */
+int *BKE_object_defgroup_index_map_create(Object *ob_src, Object *ob_dst, int *r_map_len)
+{
+ /* Build src to merged mapping of vgroup indices. */
+ if (BLI_listbase_is_empty(&ob_src->defbase) || BLI_listbase_is_empty(&ob_dst->defbase)) {
+ *r_map_len = 0;
+ return NULL;
+ }
+
+ bDeformGroup *dg_src;
+ *r_map_len = BLI_listbase_count(&ob_src->defbase);
+ int *vgroup_index_map = MEM_malloc_arrayN(*r_map_len, sizeof(*vgroup_index_map), "defgroup index map create");
+ bool is_vgroup_remap_needed = false;
+ int i;
+
+ for (dg_src = ob_src->defbase.first, i = 0; dg_src; dg_src = dg_src->next, i++) {
+ vgroup_index_map[i] = defgroup_name_index(ob_dst, dg_src->name);
+ is_vgroup_remap_needed = is_vgroup_remap_needed || (vgroup_index_map[i] != i);
+ }
+
+ if (!is_vgroup_remap_needed) {
+ MEM_freeN(vgroup_index_map);
+ vgroup_index_map = NULL;
+ *r_map_len = 0;
+ }
+
+ return vgroup_index_map;
+}
+
+void BKE_object_defgroup_index_map_apply(MDeformVert *dvert, int dvert_len, const int *map, int map_len)
+{
+ if (map == NULL || map_len == 0) {
+ return;
+ }
+
+ MDeformVert *dv = dvert;
+ for (int i = 0; i < dvert_len; i++, dv++) {
+ int totweight = dv->totweight;
+ for (int j = 0; j < totweight; j++) {
+ int def_nr = dv->dw[j].def_nr;
+ if ((uint)def_nr < (uint)map_len && map[def_nr] != -1) {
+ dv->dw[j].def_nr = map[def_nr];
+ }
+ else {
+ totweight--;
+ dv->dw[j] = dv->dw[totweight];
+ j--;
+ }
+ }
+ if (totweight != dv->totweight) {
+ if (totweight) {
+ dv->dw = MEM_reallocN(dv->dw, sizeof(*dv->dw) * totweight);
+ }
+ else {
+ MEM_SAFE_FREE(dv->dw);
+ }
+ dv->totweight = totweight;
+ }
+ }
+}
/**
* Get MDeformVert vgroup data from given object. Should only be used in Object mode.
@@ -481,6 +545,8 @@ bool BKE_object_defgroup_array_get(ID *id, MDeformVert **dvert_arr, int *dvert_t
*dvert_tot = lt->pntsu * lt->pntsv * lt->pntsw;
return true;
}
+ default:
+ break;
}
}
@@ -537,7 +603,7 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot)
BLI_ghash_insert(gh, dg->name, NULL);
}
- BLI_assert(BLI_ghash_size(gh) == defbase_tot);
+ BLI_assert(BLI_ghash_len(gh) == defbase_tot);
/* now loop through the armature modifiers and identify deform bones */
for (md = ob->modifiers.first; md; md = !md->next && step1 ? (step1 = 0), modifiers_getVirtualModifierList(ob, &virtualModifierData) : md->next) {
@@ -572,7 +638,7 @@ bool *BKE_object_defgroup_validmap_get(Object *ob, const int defbase_tot)
defgroup_validmap[i] = (BLI_ghash_lookup(gh, dg->name) != NULL);
}
- BLI_assert(i == BLI_ghash_size(gh));
+ BLI_assert(i == BLI_ghash_len(gh));
BLI_ghash_free(gh, NULL, NULL);
diff --git a/source/blender/blenkernel/intern/object_dupli.c b/source/blender/blenkernel/intern/object_dupli.c
index e3b801b3193..56d5cb609fc 100644
--- a/source/blender/blenkernel/intern/object_dupli.c
+++ b/source/blender/blenkernel/intern/object_dupli.c
@@ -64,6 +64,7 @@
#include "BLI_strict_flags.h"
+#include "BLI_hash.h"
/* Dupli-Geometry */
@@ -180,6 +181,23 @@ static DupliObject *make_dupli(const DupliContext *ctx,
if (ob->type == OB_MBALL)
dob->no_draw = true;
+ /* random number */
+ /* the logic here is designed to match Cycles */
+ dob->random_id = BLI_hash_string(dob->ob->id.name + 2);
+
+ if (dob->persistent_id[0] != INT_MAX) {
+ for (i = 0; i < MAX_DUPLI_RECUR * 2; i++) {
+ dob->random_id = BLI_hash_int_2d(dob->random_id, (unsigned int)dob->persistent_id[i]);
+ }
+ }
+ else {
+ dob->random_id = BLI_hash_int_2d(dob->random_id, 0);
+ }
+
+ if (ctx->object != ob) {
+ dob->random_id ^= BLI_hash_int(BLI_hash_string(ctx->object->id.name + 2));
+ }
+
return dob;
}
@@ -325,7 +343,7 @@ static void make_duplis_group(const DupliContext *ctx)
}
}
-const DupliGenerator gen_dupli_group = {
+static const DupliGenerator gen_dupli_group = {
OB_DUPLIGROUP, /* type */
make_duplis_group /* make_duplis */
};
@@ -361,7 +379,7 @@ static void make_duplis_frames(const DupliContext *ctx)
/* special flag to avoid setting recalc flags to notify the depsgraph of
* updates, as this is not a permanent change to the object */
- ob->id.tag |= LIB_TAG_ANIM_NO_RECALC;
+ ob->id.recalc |= ID_RECALC_SKIP_ANIM_TAG;
for (scene->r.cfra = ob->dupsta; scene->r.cfra <= dupend; scene->r.cfra++) {
int ok = 1;
@@ -403,7 +421,7 @@ static void make_duplis_frames(const DupliContext *ctx)
*ob = copyob;
}
-const DupliGenerator gen_dupli_frames = {
+static const DupliGenerator gen_dupli_frames = {
OB_DUPLIFRAMES, /* type */
make_duplis_frames /* make_duplis */
};
@@ -529,10 +547,15 @@ static void make_duplis_verts(const DupliContext *ctx)
BMEditMesh *em = BKE_editmesh_from_object(parent);
CustomDataMask dm_mask = (use_texcoords ? CD_MASK_BAREMESH | CD_MASK_ORCO : CD_MASK_BAREMESH);
- if (em)
+ if (ctx->eval_ctx->mode == DAG_EVAL_RENDER) {
+ vdd.dm = mesh_create_derived_render(scene, parent, dm_mask);
+ }
+ else if (em) {
vdd.dm = editbmesh_get_derived_cage(scene, parent, em, dm_mask);
- else
+ }
+ else {
vdd.dm = mesh_get_derived_final(scene, parent, dm_mask);
+ }
vdd.edit_btmesh = me->edit_btmesh;
if (use_texcoords)
@@ -548,7 +571,7 @@ static void make_duplis_verts(const DupliContext *ctx)
vdd.dm->release(vdd.dm);
}
-const DupliGenerator gen_dupli_verts = {
+static const DupliGenerator gen_dupli_verts = {
OB_DUPLIVERTS, /* type */
make_duplis_verts /* make_duplis */
};
@@ -607,7 +630,7 @@ static void make_duplis_font(const DupliContext *ctx)
/* in par the family name is stored, use this to find the other objects */
- BKE_vfont_to_curve_ex(G.main, par, FO_DUPLI, NULL,
+ BKE_vfont_to_curve_ex(G.main, par, par->data, FO_DUPLI, NULL,
&text, &text_len, &text_free, &chartransdata);
if (text == NULL || chartransdata == NULL) {
@@ -661,7 +684,7 @@ static void make_duplis_font(const DupliContext *ctx)
MEM_freeN(chartransdata);
}
-const DupliGenerator gen_dupli_verts_font = {
+static const DupliGenerator gen_dupli_verts_font = {
OB_DUPLIVERTS, /* type */
make_duplis_font /* make_duplis */
};
@@ -792,10 +815,15 @@ static void make_duplis_faces(const DupliContext *ctx)
BMEditMesh *em = BKE_editmesh_from_object(parent);
CustomDataMask dm_mask = (use_texcoords ? CD_MASK_BAREMESH | CD_MASK_ORCO | CD_MASK_MLOOPUV : CD_MASK_BAREMESH);
- if (em)
+ if (ctx->eval_ctx->mode == DAG_EVAL_RENDER) {
+ fdd.dm = mesh_create_derived_render(scene, parent, dm_mask);
+ }
+ else if (em) {
fdd.dm = editbmesh_get_derived_cage(scene, parent, em, dm_mask);
- else
+ }
+ else {
fdd.dm = mesh_get_derived_final(scene, parent, dm_mask);
+ }
if (use_texcoords) {
CustomData *ml_data = fdd.dm->getLoopDataLayout(fdd.dm);
@@ -819,7 +847,7 @@ static void make_duplis_faces(const DupliContext *ctx)
fdd.dm->release(fdd.dm);
}
-const DupliGenerator gen_dupli_faces = {
+static const DupliGenerator gen_dupli_faces = {
OB_DUPLIFACES, /* type */
make_duplis_faces /* make_duplis */
};
@@ -1140,7 +1168,7 @@ static void make_duplis_particles(const DupliContext *ctx)
}
}
-const DupliGenerator gen_dupli_particles = {
+static const DupliGenerator gen_dupli_particles = {
OB_DUPLIPARTS, /* type */
make_duplis_particles /* make_duplis */
};
diff --git a/source/blender/blenkernel/intern/object_update.c b/source/blender/blenkernel/intern/object_update.c
index 5cb704e4737..e2e28d4b251 100644
--- a/source/blender/blenkernel/intern/object_update.c
+++ b/source/blender/blenkernel/intern/object_update.c
@@ -54,25 +54,19 @@
#include "BKE_editmesh.h"
#include "BKE_object.h"
#include "BKE_particle.h"
+#include "BKE_pointcache.h"
#include "BKE_scene.h"
#include "BKE_material.h"
#include "BKE_image.h"
#include "DEG_depsgraph.h"
-#ifdef WITH_LEGACY_DEPSGRAPH
-# define DEBUG_PRINT if (!DEG_depsgraph_use_legacy() && G.debug & G_DEBUG_DEPSGRAPH) printf
-#else
-# define DEBUG_PRINT if (G.debug & G_DEBUG_DEPSGRAPH) printf
-#endif
-
static ThreadMutex material_lock = BLI_MUTEX_INITIALIZER;
void BKE_object_eval_local_transform(EvaluationContext *UNUSED(eval_ctx),
- Scene *UNUSED(scene),
Object *ob)
{
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
/* calculate local matrix */
BKE_object_to_mat4(ob, ob->obmat);
@@ -90,7 +84,7 @@ void BKE_object_eval_parent(EvaluationContext *UNUSED(eval_ctx),
float tmat[4][4];
float locmat[4][4];
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
/* get local matrix (but don't calculate it, as that was done already!) */
// XXX: redundant?
@@ -119,7 +113,7 @@ void BKE_object_eval_constraints(EvaluationContext *UNUSED(eval_ctx),
bConstraintOb *cob;
float ctime = BKE_scene_frame_get(scene);
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
/* evaluate constraints stack */
/* TODO: split this into:
@@ -137,25 +131,13 @@ void BKE_object_eval_constraints(EvaluationContext *UNUSED(eval_ctx),
void BKE_object_eval_done(EvaluationContext *UNUSED(eval_ctx), Object *ob)
{
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
/* Set negative scale flag in object. */
if (is_negative_m4(ob->obmat)) ob->transflag |= OB_NEG_SCALE;
else ob->transflag &= ~OB_NEG_SCALE;
}
-void BKE_object_eval_modifier(struct EvaluationContext *eval_ctx,
- struct Scene *scene,
- struct Object *ob,
- struct ModifierData *md)
-{
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
- (void) eval_ctx; /* Ignored. */
- (void) scene; /* Ignored. */
- (void) ob; /* Ignored. */
- (void) md; /* Ignored. */
-}
-
void BKE_object_handle_data_update(EvaluationContext *eval_ctx,
Scene *scene,
Object *ob)
@@ -165,7 +147,7 @@ void BKE_object_handle_data_update(EvaluationContext *eval_ctx,
Key *key;
float ctime = BKE_scene_frame_get(scene);
- if (G.debug & G_DEBUG_DEPSGRAPH)
+ if (G.debug & G_DEBUG_DEPSGRAPH_EVAL)
printf("recalcdata %s\n", ob->id.name + 2);
/* TODO(sergey): Only used by legacy depsgraph. */
@@ -203,7 +185,7 @@ void BKE_object_handle_data_update(EvaluationContext *eval_ctx,
break;
}
case OB_ARMATURE:
- if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from) {
+ if (ID_IS_LINKED(ob) && ob->proxy_from) {
if (BKE_pose_copy_result(ob->pose, ob->proxy_from->pose) == false) {
printf("Proxy copy error, lib Object: %s proxy Object: %s\n",
ob->id.name + 2, ob->proxy_from->id.name + 2);
@@ -307,33 +289,36 @@ void BKE_object_handle_data_update(EvaluationContext *eval_ctx,
/* quick cache removed */
}
-void BKE_object_eval_uber_transform(EvaluationContext *UNUSED(eval_ctx),
- Scene *UNUSED(scene),
- Object *ob)
+bool BKE_object_eval_proxy_copy(EvaluationContext *UNUSED(eval_ctx),
+ Object *object)
{
- /* TODO(sergey): Currently it's a duplicate of logic in BKE_object_handle_update_ex(). */
- // XXX: it's almost redundant now...
-
/* Handle proxy copy for target, */
- if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from) {
- if (ob->proxy_from->proxy_group) {
+ if (ID_IS_LINKED(object) && object->proxy_from) {
+ if (object->proxy_from->proxy_group) {
/* Transform proxy into group space. */
- Object *obg = ob->proxy_from->proxy_group;
+ Object *obg = object->proxy_from->proxy_group;
float imat[4][4];
invert_m4_m4(imat, obg->obmat);
- mul_m4_m4m4(ob->obmat, imat, ob->proxy_from->obmat);
+ mul_m4_m4m4(object->obmat, imat, object->proxy_from->obmat);
/* Should always be true. */
if (obg->dup_group) {
- add_v3_v3(ob->obmat[3], obg->dup_group->dupli_ofs);
+ add_v3_v3(object->obmat[3], obg->dup_group->dupli_ofs);
}
}
- else
- copy_m4_m4(ob->obmat, ob->proxy_from->obmat);
+ else {
+ copy_m4_m4(object->obmat, object->proxy_from->obmat);
+ }
+ return true;
}
+ return false;
+}
- ob->recalc &= ~(OB_RECALC_OB | OB_RECALC_TIME);
- if (ob->data == NULL) {
- ob->recalc &= ~OB_RECALC_DATA;
+void BKE_object_eval_uber_transform(EvaluationContext *eval_ctx, Object *object)
+{
+ BKE_object_eval_proxy_copy(eval_ctx, object);
+ object->recalc &= ~(OB_RECALC_OB | OB_RECALC_TIME);
+ if (object->data == NULL) {
+ object->recalc &= ~OB_RECALC_DATA;
}
}
@@ -341,9 +326,33 @@ void BKE_object_eval_uber_data(EvaluationContext *eval_ctx,
Scene *scene,
Object *ob)
{
- DEBUG_PRINT("%s on %s\n", __func__, ob->id.name);
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
BLI_assert(ob->type != OB_ARMATURE);
BKE_object_handle_data_update(eval_ctx, scene, ob);
ob->recalc &= ~(OB_RECALC_DATA | OB_RECALC_TIME);
}
+
+void BKE_object_eval_cloth(EvaluationContext *UNUSED(eval_ctx),
+ Scene *scene,
+ Object *object)
+{
+ DEG_debug_print_eval(__func__, object->id.name, object);
+ BKE_ptcache_object_reset(scene, object, PTCACHE_RESET_DEPSGRAPH);
+}
+
+void BKE_object_eval_transform_all(EvaluationContext *eval_ctx,
+ Scene *scene,
+ Object *object)
+{
+ /* This mimics full transform update chain from new depsgraph. */
+ BKE_object_eval_local_transform(eval_ctx, object);
+ if (object->parent != NULL) {
+ BKE_object_eval_parent(eval_ctx, scene, object);
+ }
+ if (!BLI_listbase_is_empty(&object->constraints)) {
+ BKE_object_eval_constraints(eval_ctx, scene, object);
+ }
+ BKE_object_eval_uber_transform(eval_ctx, object);
+ BKE_object_eval_done(eval_ctx, object);
+}
diff --git a/source/blender/blenkernel/intern/ocean.c b/source/blender/blenkernel/intern/ocean.c
index 621ac9c2480..2d8527f23d6 100644
--- a/source/blender/blenkernel/intern/ocean.c
+++ b/source/blender/blenkernel/intern/ocean.c
@@ -334,10 +334,10 @@ void BKE_ocean_eval_uv(struct Ocean *oc, struct OceanResult *ocr, float u, float
i1 = i1 % oc->_M;
j1 = j1 % oc->_N;
-
#define BILERP(m) (interpf(interpf(m[i1 * oc->_N + j1], m[i0 * oc->_N + j1], frac_x), \
interpf(m[i1 * oc->_N + j0], m[i0 * oc->_N + j0], frac_x), \
frac_z))
+
{
if (oc->_do_disp_y) {
ocr->disp[1] = BILERP(oc->_disp_y);
@@ -502,7 +502,10 @@ typedef struct OceanSimulateData {
float chop_amount;
} OceanSimulateData;
-static void ocean_compute_htilda(void *userdata, const int i)
+static void ocean_compute_htilda(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
OceanSimulateData *osd = userdata;
const Ocean *o = osd->o;
@@ -748,7 +751,10 @@ void BKE_ocean_simulate(struct Ocean *o, float t, float scale, float chop_amount
* This is not optimal in all cases, but remains reasonably simple and should be OK most of the time. */
/* compute a new htilda */
- BLI_task_parallel_range(0, o->_M, &osd, ocean_compute_htilda, o->_M > 16);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (o->_M > 16);
+ BLI_task_parallel_range(0, o->_M, &osd, ocean_compute_htilda, &settings);
if (o->_do_disp_y) {
BLI_task_pool_push(pool, ocean_compute_displacement_y, NULL, false, TASK_PRIORITY_HIGH);
@@ -911,7 +917,7 @@ void BKE_ocean_init(struct Ocean *o, int M, int N, float Lx, float Lz, float V,
o->_fft_in = (fftw_complex *)MEM_mallocN(o->_M * (1 + o->_N / 2) * sizeof(fftw_complex), "ocean_fft_in");
o->_htilda = (fftw_complex *)MEM_mallocN(o->_M * (1 + o->_N / 2) * sizeof(fftw_complex), "ocean_htilda");
- BLI_lock_thread(LOCK_FFTW);
+ BLI_thread_lock(LOCK_FFTW);
if (o->_do_disp_y) {
o->_disp_y = (double *)MEM_mallocN(o->_M * o->_N * sizeof(double), "ocean_disp_y");
@@ -957,7 +963,7 @@ void BKE_ocean_init(struct Ocean *o, int M, int N, float Lx, float Lz, float V,
o->_Jxz_plan = fftw_plan_dft_c2r_2d(o->_M, o->_N, o->_fft_in_jxz, o->_Jxz, FFTW_ESTIMATE);
}
- BLI_unlock_thread(LOCK_FFTW);
+ BLI_thread_unlock(LOCK_FFTW);
BLI_rw_mutex_unlock(&o->oceanmutex);
@@ -972,7 +978,7 @@ void BKE_ocean_free_data(struct Ocean *oc)
BLI_rw_mutex_lock(&oc->oceanmutex, THREAD_LOCK_WRITE);
- BLI_lock_thread(LOCK_FFTW);
+ BLI_thread_lock(LOCK_FFTW);
if (oc->_do_disp_y) {
fftw_destroy_plan(oc->_disp_y_plan);
@@ -1010,7 +1016,7 @@ void BKE_ocean_free_data(struct Ocean *oc)
MEM_freeN(oc->_Jxz);
}
- BLI_unlock_thread(LOCK_FFTW);
+ BLI_thread_unlock(LOCK_FFTW);
if (oc->_fft_in)
MEM_freeN(oc->_fft_in);
diff --git a/source/blender/blenkernel/intern/outliner_treehash.c b/source/blender/blenkernel/intern/outliner_treehash.c
index f31ba34a984..9db9b2ddf54 100644
--- a/source/blender/blenkernel/intern/outliner_treehash.c
+++ b/source/blender/blenkernel/intern/outliner_treehash.c
@@ -28,14 +28,14 @@
#include <stdlib.h>
-#include "BKE_outliner_treehash.h"
-
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
#include "BLI_mempool.h"
#include "DNA_outliner_types.h"
+#include "BKE_outliner_treehash.h"
+
#include "MEM_guardedalloc.h"
typedef struct TseGroup {
@@ -112,7 +112,7 @@ static void fill_treehash(void *treehash, BLI_mempool *treestore)
void *BKE_outliner_treehash_create_from_treestore(BLI_mempool *treestore)
{
- GHash *treehash = BLI_ghash_new_ex(tse_hash, tse_cmp, "treehash", BLI_mempool_count(treestore));
+ GHash *treehash = BLI_ghash_new_ex(tse_hash, tse_cmp, "treehash", BLI_mempool_len(treestore));
fill_treehash(treehash, treestore);
return treehash;
}
@@ -126,7 +126,7 @@ void *BKE_outliner_treehash_rebuild_from_treestore(void *treehash, BLI_mempool *
{
BLI_assert(treehash);
- BLI_ghash_clear_ex(treehash, NULL, free_treehash_group, BLI_mempool_count(treestore));
+ BLI_ghash_clear_ex(treehash, NULL, free_treehash_group, BLI_mempool_len(treestore));
fill_treehash(treehash, treestore);
return treehash;
}
diff --git a/source/blender/blenkernel/intern/packedFile.c b/source/blender/blenkernel/intern/packedFile.c
index 489fc2f3710..f17c10765b8 100644
--- a/source/blender/blenkernel/intern/packedFile.c
+++ b/source/blender/blenkernel/intern/packedFile.c
@@ -232,7 +232,7 @@ void packAll(Main *bmain, ReportList *reports, bool verbose)
int tot = 0;
for (ima = bmain->image.first; ima; ima = ima->id.next) {
- if (BKE_image_has_packedfile(ima) == false && !ID_IS_LINKED_DATABLOCK(ima)) {
+ if (BKE_image_has_packedfile(ima) == false && !ID_IS_LINKED(ima)) {
if (ima->source == IMA_SRC_FILE) {
BKE_image_packfiles(reports, ima, ID_BLEND_PATH(bmain, &ima->id));
tot ++;
@@ -245,14 +245,14 @@ void packAll(Main *bmain, ReportList *reports, bool verbose)
}
for (vfont = bmain->vfont.first; vfont; vfont = vfont->id.next) {
- if (vfont->packedfile == NULL && !ID_IS_LINKED_DATABLOCK(vfont) && BKE_vfont_is_builtin(vfont) == false) {
+ if (vfont->packedfile == NULL && !ID_IS_LINKED(vfont) && BKE_vfont_is_builtin(vfont) == false) {
vfont->packedfile = newPackedFile(reports, vfont->name, bmain->name);
tot ++;
}
}
for (sound = bmain->sound.first; sound; sound = sound->id.next) {
- if (sound->packedfile == NULL && !ID_IS_LINKED_DATABLOCK(sound)) {
+ if (sound->packedfile == NULL && !ID_IS_LINKED(sound)) {
sound->packedfile = newPackedFile(reports, sound->name, bmain->name);
tot++;
}
@@ -354,16 +354,15 @@ int writePackedFile(ReportList *reports, const char *filename, PackedFile *pf, i
return (ret_value);
}
-
-/*
+
+/**
* This function compares a packed file to a 'real' file.
* It returns an integer indicating if:
*
- * PF_EQUAL - the packed file and original file are identical
- * PF_DIFFERENT - the packed file and original file differ
- * PF_NOFILE - the original file doens't exist
+ * - PF_EQUAL: the packed file and original file are identical
+ * - PF_DIFFERENT: the packed file and original file differ
+ * - PF_NOFILE: the original file doens't exist
*/
-
int checkPackedFile(const char *filename, PackedFile *pf)
{
BLI_stat_t st;
@@ -450,7 +449,7 @@ char *unpackFile(ReportList *reports, const char *abs_name, const char *local_na
break;
}
/* else create it */
- /* fall-through */
+ ATTR_FALLTHROUGH;
}
case PF_WRITE_LOCAL:
if (writePackedFile(reports, local_name, pf, 1) == RET_OK) {
@@ -471,7 +470,7 @@ char *unpackFile(ReportList *reports, const char *abs_name, const char *local_na
break;
}
/* else create it */
- /* fall-through */
+ ATTR_FALLTHROUGH;
}
case PF_WRITE_ORIGINAL:
if (writePackedFile(reports, abs_name, pf, 1) == RET_OK) {
@@ -522,6 +521,8 @@ static void unpack_generate_paths(
case ID_IM:
BLI_snprintf(r_relpath, relpathlen, "//textures/%s", tempname);
break;
+ default:
+ break;
}
{
@@ -712,6 +713,8 @@ bool BKE_pack_check(ID *id)
Library *li = (Library *)id;
return li->packedfile != NULL;
}
+ default:
+ break;
}
return false;
}
@@ -750,5 +753,7 @@ void BKE_unpack_id(Main *bmain, ID *id, ReportList *reports, int how)
BKE_reportf(reports, RPT_ERROR, "Cannot unpack individual Library file, '%s'", li->name);
break;
}
+ default:
+ break;
}
}
diff --git a/source/blender/blenkernel/intern/paint.c b/source/blender/blenkernel/intern/paint.c
index 6b954f060d3..144ec029db1 100644
--- a/source/blender/blenkernel/intern/paint.c
+++ b/source/blender/blenkernel/intern/paint.c
@@ -49,6 +49,7 @@
#include "BKE_brush.h"
#include "BKE_colortools.h"
+#include "BKE_deform.h"
#include "BKE_main.h"
#include "BKE_context.h"
#include "BKE_crazyspace.h"
@@ -71,7 +72,7 @@ const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255};
const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255};
const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255};
-static OverlayControlFlags overlay_flags = 0;
+static eOverlayControlFlags overlay_flags = 0;
void BKE_paint_invalidate_overlay_tex(Scene *scene, const Tex *tex)
{
@@ -103,12 +104,12 @@ void BKE_paint_invalidate_overlay_all(void)
PAINT_INVALID_OVERLAY_CURVE);
}
-OverlayControlFlags BKE_paint_get_overlay_flags(void)
+eOverlayControlFlags BKE_paint_get_overlay_flags(void)
{
return overlay_flags;
}
-void BKE_paint_set_overlay_override(OverlayFlags flags)
+void BKE_paint_set_overlay_override(eOverlayFlags flags)
{
if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) {
if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE)
@@ -123,12 +124,12 @@ void BKE_paint_set_overlay_override(OverlayFlags flags)
}
}
-void BKE_paint_reset_overlay_invalid(OverlayControlFlags flag)
+void BKE_paint_reset_overlay_invalid(eOverlayControlFlags flag)
{
overlay_flags &= ~(flag);
}
-Paint *BKE_paint_get_active_from_paintmode(Scene *sce, PaintMode mode)
+Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode)
{
if (sce) {
ToolSettings *ts = sce->toolsettings;
@@ -207,34 +208,15 @@ Paint *BKE_paint_get_active_from_context(const bContext *C)
return &ts->imapaint.paint;
}
}
- else if (obact) {
- switch (obact->mode) {
- case OB_MODE_SCULPT:
- return &ts->sculpt->paint;
- case OB_MODE_VERTEX_PAINT:
- return &ts->vpaint->paint;
- case OB_MODE_WEIGHT_PAINT:
- return &ts->wpaint->paint;
- case OB_MODE_TEXTURE_PAINT:
- return &ts->imapaint.paint;
- case OB_MODE_EDIT:
- if (ts->use_uv_sculpt)
- return &ts->uvsculpt->paint;
- return &ts->imapaint.paint;
- default:
- return &ts->imapaint.paint;
- }
- }
else {
- /* default to image paint */
- return &ts->imapaint.paint;
+ return BKE_paint_get_active(sce);
}
}
return NULL;
}
-PaintMode BKE_paintmode_get_active_from_context(const bContext *C)
+ePaintMode BKE_paintmode_get_active_from_context(const bContext *C)
{
Scene *sce = CTX_data_scene(C);
SpaceImage *sima;
@@ -309,24 +291,31 @@ PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name)
{
PaintCurve *pc;
- pc = BKE_libblock_alloc(bmain, ID_PC, name);
+ pc = BKE_libblock_alloc(bmain, ID_PC, name, 0);
return pc;
}
-PaintCurve *BKE_paint_curve_copy(Main *bmain, PaintCurve *pc)
+/**
+ * Only copy internal data of PaintCurve ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_paint_curve_copy_data(Main *UNUSED(bmain), PaintCurve *pc_dst, const PaintCurve *pc_src, const int UNUSED(flag))
{
- PaintCurve *pc_new;
-
- pc_new = BKE_libblock_copy(bmain, &pc->id);
-
- if (pc->tot_points != 0) {
- pc_new->points = MEM_dupallocN(pc->points);
+ if (pc_src->tot_points != 0) {
+ pc_dst->points = MEM_dupallocN(pc_src->points);
}
+}
- BKE_id_copy_ensure_local(bmain, &pc->id, &pc_new->id);
-
- return pc_new;
+PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc)
+{
+ PaintCurve *pc_copy;
+ BKE_id_copy_ex(bmain, &pc->id, (ID **)&pc_copy, 0, false);
+ return pc_copy;
}
void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local)
@@ -365,7 +354,7 @@ void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_inde
/* remove colour from palette. Must be certain color is inside the palette! */
void BKE_palette_color_remove(Palette *palette, PaletteColor *color)
{
- if (BLI_listbase_count_ex(&palette->colors, palette->active_color) == palette->active_color) {
+ if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) == palette->active_color) {
palette->active_color--;
}
@@ -388,7 +377,7 @@ Palette *BKE_palette_add(Main *bmain, const char *name)
{
Palette *palette;
- palette = BKE_libblock_alloc(bmain, ID_PAL, name);
+ palette = BKE_libblock_alloc(bmain, ID_PAL, name, 0);
/* enable fake user by default */
id_fake_user_set(&palette->id);
@@ -396,17 +385,24 @@ Palette *BKE_palette_add(Main *bmain, const char *name)
return palette;
}
-Palette *BKE_palette_copy(Main *bmain, Palette *palette)
+/**
+ * Only copy internal data of Palette ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag))
{
- Palette *palette_new;
-
- palette_new = BKE_libblock_copy(bmain, &palette->id);
-
- BLI_duplicatelist(&palette_new->colors, &palette->colors);
-
- BKE_id_copy_ensure_local(bmain, &palette->id, &palette_new->id);
+ BLI_duplicatelist(&palette_dst->colors, &palette_src->colors);
+}
- return palette_new;
+Palette *BKE_palette_copy(Main *bmain, const Palette *palette)
+{
+ Palette *palette_copy;
+ BKE_id_copy_ex(bmain, &palette->id, (ID **)&palette_copy, 0, false);
+ return palette_copy;
}
void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local)
@@ -452,7 +448,7 @@ bool BKE_paint_select_vert_test(Object *ob)
(ob->type == OB_MESH) &&
(ob->data != NULL) &&
(((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) &&
- (ob->mode & OB_MODE_WEIGHT_PAINT)
+ (ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT)
);
}
@@ -481,7 +477,7 @@ void BKE_paint_cavity_curve_preset(Paint *p, int preset)
curvemapping_changed(p->cavity_curve, false);
}
-short BKE_paint_object_mode_from_paint_mode(PaintMode mode)
+eObjectMode BKE_paint_object_mode_from_paint_mode(ePaintMode mode)
{
switch (mode) {
case ePaintSculpt:
@@ -502,7 +498,7 @@ short BKE_paint_object_mode_from_paint_mode(PaintMode mode)
}
}
-void BKE_paint_init(Scene *sce, PaintMode mode, const char col[3])
+void BKE_paint_init(Scene *sce, ePaintMode mode, const char col[3])
{
UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings;
Brush *brush;
@@ -511,11 +507,13 @@ void BKE_paint_init(Scene *sce, PaintMode mode, const char col[3])
/* If there's no brush, create one */
brush = BKE_paint_brush(paint);
if (brush == NULL) {
- short ob_mode = BKE_paint_object_mode_from_paint_mode(mode);
+ eObjectMode ob_mode = BKE_paint_object_mode_from_paint_mode(mode);
brush = BKE_brush_first_search(G.main, ob_mode);
- if (!brush)
+ if (!brush) {
brush = BKE_brush_add(G.main, "Brush", ob_mode);
+ id_us_min(&brush->id); /* fake user only */
+ }
BKE_paint_brush_set(paint, brush);
}
@@ -537,12 +535,15 @@ void BKE_paint_free(Paint *paint)
* still do a id_us_plus(), rather then if we were copying between 2 existing
* scenes where a matching value should decrease the existing user count as
* with paint_brush_set() */
-void BKE_paint_copy(Paint *src, Paint *tar)
+void BKE_paint_copy(Paint *src, Paint *tar, const int flag)
{
tar->brush = src->brush;
- id_us_plus((ID *)tar->brush);
- id_us_plus((ID *)tar->palette);
tar->cavity_curve = curvemapping_copy(src->cavity_curve);
+
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)tar->brush);
+ id_us_plus((ID *)tar->palette);
+ }
}
void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3])
@@ -620,8 +621,9 @@ void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, f
ups->brush_rotation_sec = 0.0f;
}
-void paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2])
+bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2])
{
+ bool ok = false;
if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) {
const float r = RAKE_THRESHHOLD;
float rotation;
@@ -637,16 +639,20 @@ void paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, cons
ups->last_rake_angle = rotation;
paint_update_brush_rake_rotation(ups, brush, rotation);
+ ok = true;
}
/* make sure we reset here to the last rotation to avoid accumulating
* values in case a random rotation is also added */
else {
paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle);
+ ok = false;
}
}
else {
ups->brush_rotation = ups->brush_rotation_sec = 0.0f;
+ ok = true;
}
+ return ok;
}
void BKE_sculptsession_free_deformMats(SculptSession *ss)
@@ -656,6 +662,33 @@ void BKE_sculptsession_free_deformMats(SculptSession *ss)
MEM_SAFE_FREE(ss->deform_imats);
}
+void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss)
+{
+ struct SculptVertexPaintGeomMap *gmap = NULL;
+ if (ss->mode_type == OB_MODE_VERTEX_PAINT) {
+ gmap = &ss->mode.vpaint.gmap;
+
+ MEM_SAFE_FREE(ss->mode.vpaint.previous_color);
+ }
+ else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) {
+ gmap = &ss->mode.wpaint.gmap;
+
+ MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight);
+ if (ss->mode.wpaint.dvert_prev) {
+ BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert);
+ MEM_freeN(ss->mode.wpaint.dvert_prev);
+ ss->mode.wpaint.dvert_prev = NULL;
+ }
+ }
+ else {
+ return;
+ }
+ MEM_SAFE_FREE(gmap->vert_to_loop);
+ MEM_SAFE_FREE(gmap->vert_map_mem);
+ MEM_SAFE_FREE(gmap->vert_to_poly);
+ MEM_SAFE_FREE(gmap->poly_map_mem);
+}
+
/* Write out the sculpt dynamic-topology BMesh to the Mesh */
static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder)
{
@@ -747,6 +780,8 @@ void BKE_sculptsession_free(Object *ob)
if (ss->deform_imats)
MEM_freeN(ss->deform_imats);
+ BKE_sculptsession_free_vwpaint_data(ob->sculpt);
+
MEM_freeN(ss);
ob->sculpt = NULL;
@@ -830,6 +865,9 @@ void BKE_sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob,
ss->modifiers_active = sculpt_modifiers_active(scene, sd, ob);
ss->show_diffuse_color = (sd->flags & SCULPT_SHOW_DIFFUSE) != 0;
+ ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0;
+
+ ss->building_vp_handle = false;
if (need_mask) {
if (mmd == NULL) {
@@ -841,7 +879,7 @@ void BKE_sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob,
if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) {
#if 1
BKE_sculpt_mask_layers_ensure(ob, mmd);
-#else /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
+#else /* if we wanted to support adding mask data while multi-res painting, we would need to do this */
if ((ED_sculpt_mask_layers_ensure(ob, mmd) & ED_SCULPT_MASK_LAYER_CALC_LOOP)) {
/* remake the derived mesh */
ob->recalc |= OB_RECALC_DATA;
@@ -859,7 +897,8 @@ void BKE_sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob,
dm = mesh_get_derived_final(scene, ob, CD_MASK_BAREMESH);
- if (mmd) {
+ /* VWPaint require mesh info for loop lookup, so require sculpt mode here */
+ if (mmd && ob->mode & OB_MODE_SCULPT) {
ss->multires = mmd;
ss->totvert = dm->getNumVerts(dm);
ss->totpoly = dm->getNumPolys(dm);
@@ -881,6 +920,7 @@ void BKE_sculpt_update_mesh_elements(Scene *scene, Sculpt *sd, Object *ob,
ss->pmap = (need_pmap && dm->getPolyMap) ? dm->getPolyMap(ob, dm) : NULL;
pbvh_show_diffuse_color_set(ss->pbvh, ss->show_diffuse_color);
+ pbvh_show_mask_set(ss->pbvh, ss->show_mask);
if (ss->modifiers_active) {
if (!ss->orig_cos) {
@@ -998,3 +1038,39 @@ int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd)
return ret;
}
+
+void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene)
+{
+ Sculpt *sd = scene->toolsettings->sculpt;
+ if (sd == NULL) {
+ sd = scene->toolsettings->sculpt = MEM_callocN(sizeof(Sculpt), __func__);
+
+ /* Turn on X plane mirror symmetry by default */
+ sd->paint.symmetry_flags |= PAINT_SYMM_X;
+ sd->paint.flags |= PAINT_SHOW_BRUSH;
+
+ /* Make sure at least dyntopo subdivision is enabled */
+ sd->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
+ }
+
+ if (!sd->detail_size) {
+ sd->detail_size = 12;
+ }
+ if (!sd->detail_percent) {
+ sd->detail_percent = 25;
+ }
+ if (sd->constant_detail == 0.0f) {
+ sd->constant_detail = 3.0f;
+ }
+
+ /* Set sane default tiling offsets */
+ if (!sd->paint.tile_offset[0]) {
+ sd->paint.tile_offset[0] = 1.0f;
+ }
+ if (!sd->paint.tile_offset[1]) {
+ sd->paint.tile_offset[1] = 1.0f;
+ }
+ if (!sd->paint.tile_offset[2]) {
+ sd->paint.tile_offset[2] = 1.0f;
+ }
+}
diff --git a/source/blender/blenkernel/intern/particle.c b/source/blender/blenkernel/intern/particle.c
index 228ae6afaba..7602523b97c 100644
--- a/source/blender/blenkernel/intern/particle.c
+++ b/source/blender/blenkernel/intern/particle.c
@@ -88,6 +88,8 @@
#include "RE_render_ext.h"
+#include "particle_private.h"
+
unsigned int PSYS_FRAND_SEED_OFFSET[PSYS_FRAND_COUNT];
unsigned int PSYS_FRAND_SEED_MULTIPLIER[PSYS_FRAND_COUNT];
float PSYS_FRAND_BASE[PSYS_FRAND_COUNT];
@@ -107,9 +109,6 @@ static void get_child_modifier_parameters(ParticleSettings *part, ParticleThread
ChildParticle *cpa, short cpa_from, int cpa_num, float *cpa_fuv, float *orco, ParticleTexture *ptex);
static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSettings *part, ParticleData *par,
int child_index, int face_index, const float fw[4], float *orco, ParticleTexture *ptex, int event, float cfra);
-extern void do_child_modifiers(ParticleThreadContext *ctx, ParticleSimulationData *sim,
- ParticleTexture *ptex, const float par_co[3], const float par_vel[3], const float par_rot[4], const float par_orco[3],
- ChildParticle *cpa, const float orco[3], float mat[4][4], ParticleKey *state, float t);
/* few helpers for countall etc. */
int count_particles(ParticleSystem *psys)
@@ -253,11 +252,16 @@ struct LatticeDeformData *psys_create_lattice_deform_data(ParticleSimulationData
if (psys_in_edit_mode(sim->scene, sim->psys) == 0) {
Object *lattice = NULL;
ModifierData *md = (ModifierData *)psys_get_modifier(sim->ob, sim->psys);
+ int mode = G.is_rendering ? eModifierMode_Render : eModifierMode_Realtime;
for (; md; md = md->next) {
if (md->type == eModifierType_Lattice) {
- LatticeModifierData *lmd = (LatticeModifierData *)md;
- lattice = lmd->object;
+ if (md->mode & mode) {
+ LatticeModifierData *lmd = (LatticeModifierData *)md;
+ lattice = lmd->object;
+ sim->psys->lattice_strength = lmd->strength;
+ }
+
break;
}
}
@@ -401,6 +405,8 @@ void BKE_particlesettings_free(ParticleSettings *part)
curvemapping_free(part->clumpcurve);
if (part->roughcurve)
curvemapping_free(part->roughcurve);
+ if (part->twistcurve)
+ curvemapping_free(part->twistcurve);
free_partdeflect(part->pd);
free_partdeflect(part->pd2);
@@ -543,7 +549,8 @@ void psys_free_pdd(ParticleSystem *psys)
psys->pdd->vedata = NULL;
psys->pdd->totpoint = 0;
- psys->pdd->tot_vec_size = 0;
+ psys->pdd->totpart = 0;
+ psys->pdd->partsize = 0;
}
}
/* free everything */
@@ -590,7 +597,7 @@ void psys_free(Object *ob, ParticleSystem *psys)
BLI_bvhtree_free(psys->bvhtree);
BLI_kdtree_free(psys->tree);
-
+
if (psys->fluid_springs)
MEM_freeN(psys->fluid_springs);
@@ -658,8 +665,9 @@ void psys_render_set(Object *ob, ParticleSystem *psys, float viewmat[4][4], floa
psys->renderdata = data;
/* Hair can and has to be recalculated if everything isn't displayed. */
- if (psys->part->disp != 100 && psys->part->type == PART_HAIR)
+ if (psys->part->disp != 100 && ELEM(psys->part->type, PART_HAIR, PART_FLUID)) {
psys->recalc |= PSYS_RECALC_RESET;
+ }
}
void psys_render_restore(Object *ob, ParticleSystem *psys)
@@ -732,7 +740,7 @@ void psys_render_restore(Object *ob, ParticleSystem *psys)
if (disp != render_disp) {
/* Hair can and has to be recalculated if everything isn't displayed. */
- if (psys->part->type == PART_HAIR) {
+ if (ELEM(psys->part->type, PART_HAIR, PART_FLUID)) {
psys->recalc |= PSYS_RECALC_RESET;
}
else {
@@ -1790,11 +1798,6 @@ void psys_particle_on_emitter(ParticleSystemModifierData *psmd, int from, int in
/* Path Cache */
/************************************************/
-extern void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3], const float par_rot[4], float time, float freq, float shape, float amplitude, float flat,
- short type, short axis, float obmat[4][4], int smooth_start);
-extern float do_clump(ParticleKey *state, const float par_co[3], float time, const float orco_offset[3], float clumpfac, float clumppow, float pa_clump,
- bool use_clump_noise, float clump_noise_size, CurveMapping *clumpcurve);
-
void precalc_guides(ParticleSimulationData *sim, ListBase *effectors)
{
EffectedPoint point;
@@ -2133,6 +2136,7 @@ static bool psys_thread_context_init_path(
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);
+ ctx->vg_twist = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_TWIST);
if (psys->part->flag & PART_CHILD_EFFECT)
ctx->vg_effector = psys_cache_vgroup(ctx->dm, psys, PSYS_VG_EFFECTOR);
@@ -2151,6 +2155,13 @@ static bool psys_thread_context_init_path(
else {
ctx->roughcurve = NULL;
}
+ if ((part->child_flag & PART_CHILD_USE_TWIST_CURVE) && part->twistcurve) {
+ ctx->twistcurve = curvemapping_copy(part->twistcurve);
+ curvemapping_changed_all(ctx->twistcurve);
+ }
+ else {
+ ctx->twistcurve = NULL;
+ }
return true;
}
@@ -2295,7 +2306,19 @@ static void psys_thread_create_path(ParticleTask *task, struct ChildParticle *cp
/* get the original coordinates (orco) for texture usage */
cpa_from = part->from;
- cpa_num = pa->num;
+
+ /*
+ * NOTE: Should in theory be the same as:
+ cpa_num = psys_particle_dm_face_lookup(
+ ctx->sim.psmd->dm_final,
+ ctx->sim.psmd->dm_deformed,
+ pa->num, pa->fuv,
+ NULL);
+ */
+ cpa_num = (ELEM(pa->num_dmcache, DMCACHE_ISCHILD, DMCACHE_NOTFOUND))
+ ? pa->num
+ : pa->num_dmcache;
+
/* XXX hack to avoid messed up particle num and subsequent crash (#40733) */
if (cpa_num > ctx->sim.psmd->dm_final->getNumTessFaces(ctx->sim.psmd->dm_final))
cpa_num = 0;
@@ -2706,7 +2729,7 @@ void psys_cache_paths(ParticleSimulationData *sim, float cfra, const bool use_re
/* lattices have to be calculated separately to avoid mixups between effector calculations */
if (psys->lattice_deform_data) {
for (k = 0, ca = cache[p]; k <= segments; k++, ca++)
- calc_latt_deform(psys->lattice_deform_data, ca->co, 1.0f);
+ calc_latt_deform(psys->lattice_deform_data, ca->co, psys->lattice_strength);
}
}
@@ -2787,7 +2810,9 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf
/* frs_sec = (psys || edit->pid.flag & PTCACHE_VEL_PER_SEC) ? 25.0f : 1.0f; */ /* UNUSED */
- if (pset->brushtype == PE_BRUSH_WEIGHT) {
+ const bool use_weight = (pset->brushtype == PE_BRUSH_WEIGHT) && (psys != NULL) && (psys->particles != NULL);
+
+ if (use_weight) {
; /* use weight painting colors now... */
}
else {
@@ -2817,10 +2842,11 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf
/* should init_particle_interpolation set this ? */
- if (pset->brushtype == PE_BRUSH_WEIGHT) {
+ if (use_weight) {
pind.hkey[0] = NULL;
/* pa != NULL since the weight brush is only available for hair */
- pind.hkey[1] = pa->hair;
+ pind.hkey[0] = pa->hair;
+ pind.hkey[1] = pa->hair + 1;
}
@@ -2877,13 +2903,27 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf
}
/* selection coloring in edit mode */
- if (pset->brushtype == PE_BRUSH_WEIGHT) {
- float t2;
-
+ if (use_weight) {
if (k == 0) {
weight_to_rgb(ca->col, pind.hkey[1]->weight);
}
else {
+ /* warning: copied from 'do_particle_interpolation' (without 'mvert' array stepping) */
+ float real_t;
+ if (result.time < 0.0f) {
+ real_t = -result.time;
+ }
+ else {
+ real_t = pind.hkey[0]->time + t * (pind.hkey[0][pa->totkey - 1].time - pind.hkey[0]->time);
+ }
+
+ while (pind.hkey[1]->time < real_t) {
+ pind.hkey[1]++;
+ }
+ pind.hkey[0] = pind.hkey[1] - 1;
+ /* end copy */
+
+
float w1[3], w2[3];
keytime = (t - (*pind.ekey[0]->time)) / ((*pind.ekey[1]->time) - (*pind.ekey[0]->time));
@@ -2892,13 +2932,6 @@ void psys_cache_edit_paths(Scene *scene, Object *ob, PTCacheEdit *edit, float cf
interp_v3_v3v3(ca->col, w1, w2, keytime);
}
-
- /* at the moment this is only used for weight painting.
- * will need to move out of this check if its used elsewhere. */
- t2 = birthtime + ((float)k / (float)segments) * (dietime - birthtime);
-
- while (pind.hkey[1]->time < t2) pind.hkey[1]++;
- pind.hkey[0] = pind.hkey[1] - 1;
}
else {
if ((ekey + (pind.ekey[0] - point->keys))->flag & PEK_SELECT) {
@@ -3130,9 +3163,9 @@ ModifierData *object_add_particle_system(Scene *scene, Object *ob, const char *n
psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
BLI_addtail(&ob->particlesystem, psys);
- psys->part = psys_new_settings(DATA_("ParticleSettings"), NULL);
+ psys->part = BKE_particlesettings_add(NULL, DATA_("ParticleSettings"));
- if (BLI_listbase_count_ex(&ob->particlesystem, 2) > 1)
+ if (BLI_listbase_count_at_most(&ob->particlesystem, 2) > 1)
BLI_snprintf(psys->name, sizeof(psys->name), DATA_("ParticleSystem %i"), BLI_listbase_count(&ob->particlesystem));
else
BLI_strncpy(psys->name, DATA_("ParticleSystem"), sizeof(psys->name));
@@ -3288,14 +3321,14 @@ static void default_particle_settings(ParticleSettings *part)
}
-ParticleSettings *psys_new_settings(const char *name, Main *main)
+ParticleSettings *BKE_particlesettings_add(Main *main, const char *name)
{
ParticleSettings *part;
if (main == NULL)
main = G.main;
- part = BKE_libblock_alloc(main, ID_PA, name);
+ part = BKE_libblock_alloc(main, ID_PA, name, 0);
default_particle_settings(part);
@@ -3326,38 +3359,60 @@ void BKE_particlesettings_rough_curve_init(ParticleSettings *part)
part->roughcurve = cumap;
}
-ParticleSettings *BKE_particlesettings_copy(Main *bmain, ParticleSettings *part)
+void BKE_particlesettings_twist_curve_init(ParticleSettings *part)
{
- ParticleSettings *partn;
- int a;
+ CurveMapping *cumap = curvemapping_add(1, 0.0f, 0.0f, 1.0f, 1.0f);
- partn = BKE_libblock_copy(bmain, &part->id);
+ cumap->cm[0].curve[0].x = 0.0f;
+ cumap->cm[0].curve[0].y = 1.0f;
+ cumap->cm[0].curve[1].x = 1.0f;
+ cumap->cm[0].curve[1].y = 1.0f;
- partn->pd = MEM_dupallocN(part->pd);
- partn->pd2 = MEM_dupallocN(part->pd2);
- partn->effector_weights = MEM_dupallocN(part->effector_weights);
- partn->fluid = MEM_dupallocN(part->fluid);
+ part->twistcurve = cumap;
+}
- if (part->clumpcurve)
- partn->clumpcurve = curvemapping_copy(part->clumpcurve);
- if (part->roughcurve)
- partn->roughcurve = curvemapping_copy(part->roughcurve);
-
- partn->boids = boid_copy_settings(part->boids);
+/**
+ * Only copy internal data of ParticleSettings ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_particlesettings_copy_data(
+ Main *UNUSED(bmain), ParticleSettings *part_dst, const ParticleSettings *part_src, const int UNUSED(flag))
+{
+ part_dst->pd = MEM_dupallocN(part_src->pd);
+ part_dst->pd2 = MEM_dupallocN(part_src->pd2);
+ part_dst->effector_weights = MEM_dupallocN(part_src->effector_weights);
+ part_dst->fluid = MEM_dupallocN(part_src->fluid);
- for (a = 0; a < MAX_MTEX; a++) {
- if (part->mtex[a]) {
- partn->mtex[a] = MEM_mallocN(sizeof(MTex), "psys_copy_tex");
- memcpy(partn->mtex[a], part->mtex[a], sizeof(MTex));
- id_us_plus((ID *)partn->mtex[a]->tex);
+ if (part_src->clumpcurve) {
+ part_dst->clumpcurve = curvemapping_copy(part_src->clumpcurve);
+ }
+ if (part_src->roughcurve) {
+ part_dst->roughcurve = curvemapping_copy(part_src->roughcurve);
+ }
+ if (part_src->twistcurve) {
+ part_dst->twistcurve = curvemapping_copy(part_src->twistcurve);
+ }
+
+ part_dst->boids = boid_copy_settings(part_src->boids);
+
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (part_src->mtex[a]) {
+ part_dst->mtex[a] = MEM_dupallocN(part_src->mtex[a]);
}
}
- BLI_duplicatelist(&partn->dupliweights, &part->dupliweights);
-
- BKE_id_copy_ensure_local(bmain, &part->id, &partn->id);
+ BLI_duplicatelist(&part_dst->dupliweights, &part_src->dupliweights);
+}
- return partn;
+ParticleSettings *BKE_particlesettings_copy(Main *bmain, const ParticleSettings *part)
+{
+ ParticleSettings *part_copy;
+ BKE_id_copy_ex(bmain, &part->id, (ID **)&part_copy, 0, false);
+ return part_copy;
}
void BKE_particlesettings_make_local(Main *bmain, ParticleSettings *part, const bool lib_local)
@@ -3369,7 +3424,8 @@ void BKE_particlesettings_make_local(Main *bmain, ParticleSettings *part, const
/* Textures */
/************************************************/
-static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, const float fuv[4], char *name, float *texco)
+static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int index, const float fuv[4],
+ char *name, float *texco, bool from_vert)
{
MFace *mf;
MTFace *tf;
@@ -3385,11 +3441,15 @@ static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, co
if (pa) {
i = ELEM(pa->num_dmcache, DMCACHE_NOTFOUND, DMCACHE_ISCHILD) ? pa->num : pa->num_dmcache;
- if (i >= dm->getNumTessFaces(dm))
+ if ((!from_vert && i >= dm->getNumTessFaces(dm)) ||
+ (from_vert && i >= dm->getNumVerts(dm)))
+ {
i = -1;
+ }
+ }
+ else {
+ i = index;
}
- else
- i = face_index;
if (i == -1) {
texco[0] = 0.0f;
@@ -3397,7 +3457,22 @@ static int get_particle_uv(DerivedMesh *dm, ParticleData *pa, int face_index, co
texco[2] = 0.0f;
}
else {
- mf = dm->getTessFaceData(dm, i, CD_MFACE);
+ if (from_vert) {
+ mf = dm->getTessFaceDataArray(dm, CD_MFACE);
+
+ /* This finds the first face to contain the emitting vertex,
+ * this is not ideal, but is mostly fine as UV seams generally
+ * map to equal-colored parts of a texture */
+ for (int j = 0; j < dm->getNumTessFaces(dm); j++, mf++) {
+ if (ELEM(i, mf->v1, mf->v2, mf->v3, mf->v4)) {
+ i = j;
+ break;
+ }
+ }
+ }
+ else {
+ mf = dm->getTessFaceData(dm, i, CD_MFACE);
+ }
psys_interpolate_uvs(&tf[i], mf->v4, fuv, texco);
@@ -3440,6 +3515,7 @@ static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSetti
ptex->ivel = ptex->life = ptex->exist = ptex->size = ptex->damp =
ptex->gravity = ptex->field = ptex->time = ptex->clump = ptex->kink_freq = ptex->kink_amp =
ptex->effector = ptex->rough1 = ptex->rough2 = ptex->roughe = 1.0f;
+ ptex->twist = 1.0f;
ptex->length = 1.0f - part->randlength * psys_frand(psys, child_index + 26);
ptex->length *= part->clength_thres < psys_frand(psys, child_index + 27) ? part->clength : 1.0f;
@@ -3464,9 +3540,13 @@ static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSetti
mul_m4_v3(mtex->object->imat, texvec);
break;
case TEXCO_UV:
- if (fw && get_particle_uv(dm, NULL, face_index, fw, mtex->uvname, texvec))
+ if (fw && get_particle_uv(dm, NULL, face_index, fw, mtex->uvname,
+ texvec, (part->from == PART_FROM_VERT)))
+ {
break;
- /* no break, failed to get uv's, so let's try orco's */
+ }
+ /* no break, failed to get uv's, so let's try orco's */
+ ATTR_FALLTHROUGH;
case TEXCO_ORCO:
copy_v3_v3(texvec, orco);
break;
@@ -3488,6 +3568,7 @@ static void get_cpa_texture(DerivedMesh *dm, ParticleSystem *psys, ParticleSetti
SET_PARTICLE_TEXTURE(PAMAP_KINK_AMP, ptex->kink_amp, mtex->kinkampfac);
SET_PARTICLE_TEXTURE(PAMAP_KINK_FREQ, ptex->kink_freq, mtex->kinkfac);
SET_PARTICLE_TEXTURE(PAMAP_DENS, ptex->exist, mtex->padensfac);
+ SET_PARTICLE_TEXTURE(PAMAP_TWIST, ptex->twist, mtex->twistfac);
}
}
@@ -3513,6 +3594,7 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex
ptex->ivel = ptex->life = ptex->exist = ptex->size = ptex->damp =
ptex->gravity = ptex->field = ptex->length = ptex->clump = ptex->kink_freq = ptex->kink_amp =
ptex->effector = ptex->rough1 = ptex->rough2 = ptex->roughe = 1.0f;
+ ptex->twist = 1.0f;
ptex->time = (float)(pa - sim->psys->particles) / (float)sim->psys->totpart;
@@ -3536,9 +3618,13 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex
mul_m4_v3(mtex->object->imat, texvec);
break;
case TEXCO_UV:
- if (get_particle_uv(sim->psmd->dm_final, pa, 0, pa->fuv, mtex->uvname, texvec))
+ if (get_particle_uv(sim->psmd->dm_final, pa, 0, pa->fuv, mtex->uvname,
+ texvec, (part->from == PART_FROM_VERT)))
+ {
break;
- /* no break, failed to get uv's, so let's try orco's */
+ }
+ /* no break, failed to get uv's, so let's try orco's */
+ ATTR_FALLTHROUGH;
case TEXCO_ORCO:
psys_particle_on_emitter(sim->psmd, sim->psys->part->from, pa->num, pa->num_dmcache, pa->fuv, pa->foffset, co, 0, 0, 0, texvec, 0);
@@ -3583,6 +3669,7 @@ void psys_get_texture(ParticleSimulationData *sim, ParticleData *pa, ParticleTex
SET_PARTICLE_TEXTURE(PAMAP_GRAVITY, ptex->gravity, mtex->gravityfac);
SET_PARTICLE_TEXTURE(PAMAP_DAMP, ptex->damp, mtex->dampfac);
SET_PARTICLE_TEXTURE(PAMAP_LENGTH, ptex->length, mtex->lengthfac);
+ SET_PARTICLE_TEXTURE(PAMAP_TWIST, ptex->twist, mtex->twistfac);
}
}
@@ -3637,10 +3724,17 @@ float psys_get_child_size(ParticleSystem *psys, ChildParticle *cpa, float UNUSED
ParticleSettings *part = psys->part;
float size; // time XXX
- if (part->childtype == PART_CHILD_FACES)
- size = part->size;
- else
+ if (part->childtype == PART_CHILD_FACES) {
+ int w = 0;
+ size = 0.0;
+ while (w < 4 && cpa->pa[w] >= 0) {
+ size += cpa->w[w] * (psys->particles + cpa->pa[w])->size;
+ w++;
+ }
+ }
+ else {
size = psys->particles[cpa->parent].size;
+ }
size *= part->childsize;
@@ -3674,6 +3768,8 @@ static void get_child_modifier_parameters(ParticleSettings *part, ParticleThread
ptex->roughe *= psys_interpolate_value_from_verts(ctx->dm, cpa_from, cpa_num, cpa_fuv, ctx->vg_roughe);
if (ctx->vg_effector)
ptex->effector *= psys_interpolate_value_from_verts(ctx->dm, cpa_from, cpa_num, cpa_fuv, ctx->vg_effector);
+ if (ctx->vg_twist)
+ ptex->twist *= psys_interpolate_value_from_verts(ctx->dm, cpa_from, cpa_num, cpa_fuv, ctx->vg_twist);
}
/* get's hair (or keyed) particles state at the "path time" specified in state->time */
void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey *state, const bool vel)
@@ -3746,7 +3842,7 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey *
}
if (psys->lattice_deform_data && edit == 0)
- calc_latt_deform(psys->lattice_deform_data, state->co, 1.0f);
+ calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength);
}
}
}
@@ -3879,7 +3975,18 @@ void psys_get_particle_on_path(ParticleSimulationData *sim, int p, ParticleKey *
copy_particle_key(&tstate, state, 1);
/* apply different deformations to the child path */
- do_child_modifiers(NULL, sim, &ptex, par->co, par->vel, par->rot, par_orco, cpa, orco, hairmat, state, t);
+ ParticleChildModifierContext modifier_ctx = {NULL};
+ modifier_ctx.thread_ctx = NULL;
+ modifier_ctx.sim = sim;
+ modifier_ctx.ptex = &ptex;
+ modifier_ctx.cpa = cpa;
+ modifier_ctx.orco = orco;
+ modifier_ctx.par_co = par->co;
+ modifier_ctx.par_vel = par->vel;
+ modifier_ctx.par_rot = par->rot;
+ modifier_ctx.par_orco = par_orco;
+ modifier_ctx.parent_keys = psys->childcache ? psys->childcache[p - totpart] : NULL;
+ do_child_modifiers(&modifier_ctx, hairmat, state, t);
/* try to estimate correct velocity */
if (vel) {
@@ -3982,10 +4089,22 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta
CLAMP(t, 0.0f, 1.0f);
unit_m4(mat);
- do_child_modifiers(NULL, sim, NULL, key1->co, key1->vel, key1->rot, par_orco, cpa, cpa->fuv, mat, state, t);
+ ParticleChildModifierContext modifier_ctx = {NULL};
+ modifier_ctx.thread_ctx = NULL;
+ modifier_ctx.sim = sim;
+ modifier_ctx.ptex = NULL;
+ modifier_ctx.cpa = cpa;
+ modifier_ctx.orco = cpa->fuv;
+ modifier_ctx.par_co = key1->co;
+ modifier_ctx.par_vel = key1->vel;
+ modifier_ctx.par_rot = key1->rot;
+ modifier_ctx.par_orco = par_orco;
+ modifier_ctx.parent_keys = psys->childcache ? psys->childcache[p - totpart] : NULL;
+
+ do_child_modifiers(&modifier_ctx, mat, state, t);
if (psys->lattice_deform_data)
- calc_latt_deform(psys->lattice_deform_data, state->co, 1.0f);
+ calc_latt_deform(psys->lattice_deform_data, state->co, psys->lattice_strength);
}
else {
if (pa->state.time == cfra || ELEM(part->phystype, PART_PHYS_NO, PART_PHYS_KEYED))
@@ -4044,7 +4163,7 @@ int psys_get_particle_state(ParticleSimulationData *sim, int p, ParticleKey *sta
}
if (sim->psys->lattice_deform_data)
- calc_latt_deform(sim->psys->lattice_deform_data, state->co, 1.0f);
+ calc_latt_deform(sim->psys->lattice_deform_data, state->co, psys->lattice_strength);
}
return 1;
@@ -4291,7 +4410,7 @@ void psys_apply_hair_lattice(Scene *scene, Object *ob, ParticleSystem *psys)
hkey = pa->hair;
for (h = 0; h < pa->totkey; h++, hkey++) {
mul_m4_v3(hairmat, hkey->co);
- calc_latt_deform(psys->lattice_deform_data, hkey->co, 1.0f);
+ calc_latt_deform(psys->lattice_deform_data, hkey->co, psys->lattice_strength);
mul_m4_v3(imat, hkey->co);
}
}
diff --git a/source/blender/blenkernel/intern/particle_child.c b/source/blender/blenkernel/intern/particle_child.c
index 842de869291..c921e1ea107 100644
--- a/source/blender/blenkernel/intern/particle_child.c
+++ b/source/blender/blenkernel/intern/particle_child.c
@@ -37,15 +37,9 @@
#include "BKE_colortools.h"
#include "BKE_particle.h"
-struct Material;
+#include "particle_private.h"
-void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3], const float par_rot[4], float time, float freq, float shape, float amplitude, float flat,
- short type, short axis, float obmat[4][4], int smooth_start);
-float do_clump(ParticleKey *state, const float par_co[3], float time, const float orco_offset[3], float clumpfac, float clumppow, float pa_clump,
- bool use_clump_noise, float clump_noise_size, CurveMapping *clumpcurve);
-void do_child_modifiers(ParticleThreadContext *ctx, ParticleSimulationData *sim,
- ParticleTexture *ptex, const float par_co[3], const float par_vel[3], const float par_rot[4], const float par_orco[3],
- ChildParticle *cpa, const float orco[3], float mat[4][4], ParticleKey *state, float t);
+struct Material;
static void get_strand_normal(Material *ma, const float surfnor[3], float surfdist, float nor[3])
{
@@ -67,7 +61,7 @@ static void get_strand_normal(Material *ma, const float surfnor[3], float surfdi
else {
copy_v3_v3(vnor, nor);
}
-
+
if (ma->strand_surfnor > 0.0f) {
if (ma->strand_surfnor > surfdist) {
blend = (ma->strand_surfnor - surfdist) / ma->strand_surfnor;
@@ -85,7 +79,7 @@ typedef struct ParticlePathIterator {
ParticleCacheKey *key;
int index;
float time;
-
+
ParticleCacheKey *parent_key;
float parent_rotation[4];
} ParticlePathIterator;
@@ -94,11 +88,11 @@ static void psys_path_iter_get(ParticlePathIterator *iter, ParticleCacheKey *key
ParticleCacheKey *parent, int index)
{
BLI_assert(index >= 0 && index < totkeys);
-
+
iter->key = keys + index;
iter->index = index;
iter->time = (float)index / (float)(totkeys - 1);
-
+
if (parent) {
iter->parent_key = parent + index;
if (index > 0)
@@ -114,7 +108,7 @@ static void psys_path_iter_get(ParticlePathIterator *iter, ParticleCacheKey *key
typedef struct ParticlePathModifier {
struct ParticlePathModifier *next, *prev;
-
+
void (*apply)(ParticleCacheKey *keys, int totkeys, ParticleCacheKey *parent_keys);
} ParticlePathModifier;
@@ -133,7 +127,7 @@ static void do_kink_spiral_deform(ParticleKey *state, const float dir[3], const
{
/* Creates a logarithmic spiral:
* r(theta) = a * exp(b * theta)
- *
+ *
* The "density" parameter b is defined by the shape parameter
* and goes up to the Golden Spiral for 1.0
* https://en.wikipedia.org/wiki/Golden_spiral
@@ -142,33 +136,33 @@ static void do_kink_spiral_deform(ParticleKey *state, const float dir[3], const
/* angle of the spiral against the curve (rotated opposite to make a smooth transition) */
const float start_angle = ((b != 0.0f) ? atanf(1.0f / b) :
(float)-M_PI_2) + (b > 0.0f ? -(float)M_PI_2 : (float)M_PI_2);
-
+
float spiral_axis[3], rot[3][3];
float vec[3];
-
+
float theta = freq * time * 2.0f * (float)M_PI;
float radius = amplitude * expf(b * theta);
-
+
/* a bit more intuitive than using negative frequency for this */
if (amplitude < 0.0f)
theta = -theta;
-
+
cross_v3_v3v3(spiral_axis, dir, kink);
normalize_v3(spiral_axis);
-
+
mul_v3_v3fl(vec, kink, -radius);
-
+
axis_angle_normalized_to_mat3(rot, spiral_axis, theta);
mul_m3_v3(rot, vec);
-
+
madd_v3_v3fl(vec, kink, amplitude);
-
+
axis_angle_normalized_to_mat3(rot, spiral_axis, -start_angle);
mul_m3_v3(rot, vec);
-
+
add_v3_v3v3(result, spiral_start, vec);
}
-
+
copy_v3_v3(state->co, result);
}
@@ -180,7 +174,7 @@ static void do_kink_spiral(ParticleThreadContext *ctx, ParticleTexture *ptex, co
const int seed = ctx->sim.psys->child_seed + (int)(cpa - ctx->sim.psys->child);
const int totkeys = ctx->segments + 1;
const int extrakeys = ctx->extra_segments;
-
+
float kink_amp_random = part->kink_amp_random;
float kink_amp = part->kink_amp * (1.0f - kink_amp_random * psys_frand(ctx->sim.psys, 93541 + seed));
float kink_freq = part->kink_freq;
@@ -189,11 +183,11 @@ static void do_kink_spiral(ParticleThreadContext *ctx, ParticleTexture *ptex, co
float rough1 = part->rough1;
float rough2 = part->rough2;
float rough_end = part->rough_end;
-
+
ParticlePathIterator iter;
ParticleCacheKey *key;
int k;
-
+
float dir[3];
float spiral_start[3] = {0.0f, 0.0f, 0.0f};
float spiral_start_time = 0.0f;
@@ -204,7 +198,7 @@ static void do_kink_spiral(ParticleThreadContext *ctx, ParticleTexture *ptex, co
float cut_time;
int start_index = 0, end_index = 0;
float kink_base[3];
-
+
if (ptex) {
kink_amp *= ptex->kink_amp;
kink_freq *= ptex->kink_freq;
@@ -212,44 +206,53 @@ static void do_kink_spiral(ParticleThreadContext *ctx, ParticleTexture *ptex, co
rough2 *= ptex->rough2;
rough_end *= ptex->roughe;
}
-
+
cut_time = (totkeys - 1) * ptex->length;
zero_v3(spiral_start);
-
+
for (k = 0, key = keys; k < totkeys-1; k++, key++) {
if ((float)(k + 1) >= cut_time) {
float fac = cut_time - (float)k;
ParticleCacheKey *par = parent_keys + k;
-
+
start_index = k + 1;
end_index = start_index + extrakeys;
-
+
spiral_start_time = ((float)k + fac) / (float)(totkeys - 1);
interp_v3_v3v3(spiral_start, key->co, (key+1)->co, fac);
-
+
interp_v3_v3v3(spiral_par_co, par->co, (par+1)->co, fac);
interp_v3_v3v3(spiral_par_vel, par->vel, (par+1)->vel, fac);
interp_qt_qtqt(spiral_par_rot, par->rot, (par+1)->rot, fac);
-
+
break;
}
}
-
+
zero_v3(dir);
-
+
zero_v3(kink_base);
kink_base[part->kink_axis] = 1.0f;
mul_mat3_m4_v3(ctx->sim.ob->obmat, kink_base);
-
+
+ /* Fill in invariant part of modifier context. */
+ ParticleChildModifierContext modifier_ctx = {NULL};
+ modifier_ctx.thread_ctx = ctx;
+ modifier_ctx.sim = &ctx->sim;
+ modifier_ctx.ptex = ptex;
+ modifier_ctx.cpa = cpa;
+ modifier_ctx.orco = orco;
+ modifier_ctx.parent_keys = parent_keys;
+
for (k = 0, key = keys; k < end_index; k++, key++) {
float par_time;
float *par_co, *par_vel, *par_rot;
-
+
psys_path_iter_get(&iter, keys, end_index, NULL, k);
if (k < start_index) {
sub_v3_v3v3(dir, (key+1)->co, key->co);
normalize_v3(dir);
-
+
par_time = (float)k / (float)(totkeys - 1);
par_co = parent_keys[k].co;
par_vel = parent_keys[k].vel;
@@ -258,36 +261,42 @@ static void do_kink_spiral(ParticleThreadContext *ctx, ParticleTexture *ptex, co
else {
float spiral_time = (float)(k - start_index) / (float)(extrakeys-1);
float kink[3], tmp[3];
-
+
/* use same time value for every point on the spiral */
par_time = spiral_start_time;
par_co = spiral_par_co;
par_vel = spiral_par_vel;
par_rot = spiral_par_rot;
-
+
project_v3_v3v3(tmp, kink_base, dir);
sub_v3_v3v3(kink, kink_base, tmp);
normalize_v3(kink);
-
+
if (kink_axis_random > 0.0f) {
float a = kink_axis_random * (psys_frand(ctx->sim.psys, 7112 + seed) * 2.0f - 1.0f) * (float)M_PI;
float rot[3][3];
-
+
axis_angle_normalized_to_mat3(rot, dir, a);
mul_m3_v3(rot, kink);
}
-
+
do_kink_spiral_deform((ParticleKey *)key, dir, kink, spiral_time, kink_freq, kink_shape, kink_amp, spiral_start);
}
-
- /* apply different deformations to the child path */
- do_child_modifiers(ctx, &ctx->sim, ptex, par_co, par_vel, par_rot, parent_orco, cpa, orco, hairmat, (ParticleKey *)key, par_time);
+
+ /* Fill in variant part of modifier context. */
+ modifier_ctx.par_co = par_co;
+ modifier_ctx.par_vel = par_vel;
+ modifier_ctx.par_rot = par_rot;
+ modifier_ctx.par_orco = parent_orco;
+
+ /* Apply different deformations to the child path/ */
+ do_child_modifiers(&modifier_ctx, hairmat, (ParticleKey *)key, par_time);
}
-
+
totlen = 0.0f;
for (k = 0, key = keys; k < end_index-1; k++, key++)
totlen += len_v3v3((key+1)->co, key->co);
-
+
*r_totkeys = end_index;
*r_max_length = totlen;
}
@@ -318,12 +327,12 @@ void psys_apply_child_modifiers(ParticleThreadContext *ctx, struct ListBase *mod
struct Material *ma = ctx->ma;
const bool draw_col_ma = (part->draw_col == PART_DRAW_COL_MAT);
const bool use_length_check = !ELEM(part->kink, PART_KINK_SPIRAL);
-
+
ParticlePathModifier *mod;
ParticleCacheKey *key;
int totkeys, k;
float max_length;
-
+
#if 0 /* TODO for the future: use true particle modifiers that work on the whole curve */
for (mod = modifiers->first; mod; mod = mod->next) {
mod->apply(keys, totkeys, parent_keys);
@@ -331,44 +340,61 @@ void psys_apply_child_modifiers(ParticleThreadContext *ctx, struct ListBase *mod
#else
(void)modifiers;
(void)mod;
-
+
if (part->kink == PART_KINK_SPIRAL) {
do_kink_spiral(ctx, ptex, parent_orco, cpa, orco, hairmat, keys, parent_keys, &totkeys, &max_length);
keys->segments = totkeys - 1;
}
else {
- ParticlePathIterator iter;
-
+ /* Fill in invariant part of modifier context. */
+ ParticleChildModifierContext modifier_ctx = {NULL};
+ modifier_ctx.thread_ctx = ctx;
+ modifier_ctx.sim = &ctx->sim;
+ modifier_ctx.ptex = ptex;
+ modifier_ctx.cpa = cpa;
+ modifier_ctx.orco = orco;
+ modifier_ctx.parent_keys = parent_keys;
+
totkeys = ctx->segments + 1;
max_length = ptex->length;
-
+
for (k = 0, key = keys; k < totkeys; k++, key++) {
- ParticleKey *par;
-
+ ParticlePathIterator iter;
psys_path_iter_get(&iter, keys, totkeys, parent_keys, k);
- par = (ParticleKey *)iter.parent_key;
-
- /* apply different deformations to the child path */
- do_child_modifiers(ctx, &ctx->sim, ptex, par->co, par->vel, iter.parent_rotation, parent_orco, cpa, orco, hairmat, (ParticleKey *)key, iter.time);
+
+ ParticleKey *par = (ParticleKey *)iter.parent_key;
+
+ /* Fill in variant part of modifier context. */
+ modifier_ctx.par_co = par->co;
+ modifier_ctx.par_vel = par->vel;
+ modifier_ctx.par_rot = iter.parent_rotation;
+ modifier_ctx.par_orco = parent_orco;
+
+ /* Apply different deformations to the child path. */
+ do_child_modifiers(&modifier_ctx, hairmat, (ParticleKey *)key, iter.time);
}
}
{
const float step_length = 1.0f / (float)(totkeys - 1);
-
float cur_length = 0.0f;
-
+
+ if (max_length <= 0.0f) {
+ keys->segments = -1;
+ totkeys = 0;
+ }
+
/* we have to correct velocity because of kink & clump */
for (k = 0, key = keys; k < totkeys; ++k, ++key) {
if (k >= 2) {
sub_v3_v3v3((key-1)->vel, key->co, (key-2)->co);
mul_v3_fl((key-1)->vel, 0.5);
-
+
if (ma && draw_col_ma)
get_strand_normal(ma, ornor, cur_length, (key-1)->vel);
}
-
- if (use_length_check && k > 1) {
+
+ if (use_length_check && k > 0) {
float dvec[3];
/* check if path needs to be cut before actual end of data points */
if (!check_path_length(k, keys, key, max_length, step_length, &cur_length, dvec)) {
@@ -384,7 +410,7 @@ void psys_apply_child_modifiers(ParticleThreadContext *ctx, struct ListBase *mod
/* last key */
sub_v3_v3v3(key->vel, key->co, (key-1)->co);
}
-
+
if (ma && draw_col_ma) {
copy_v3_v3(key->col, &ma->r);
get_strand_normal(ma, ornor, cur_length, key->vel);
@@ -415,7 +441,7 @@ void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3],
}
t = time * freq * (float)M_PI;
-
+
if (smooth_start) {
dt = fabsf(t);
/* smooth the beginning of kink */
@@ -430,7 +456,7 @@ void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3],
if (obmat)
mul_mat3_m4_v3(obmat, kink);
-
+
mul_qt_v3(par_rot, kink);
/* make sure kink is normal to strand */
@@ -446,12 +472,12 @@ void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3],
case PART_KINK_CURL:
{
float curl_offset[3];
-
+
/* rotate kink vector around strand tangent */
mul_v3_v3fl(curl_offset, kink, amplitude);
axis_angle_to_quat(q1, par_vel, t);
mul_qt_v3(q1, curl_offset);
-
+
interp_v3_v3v3(par_vec, state->co, par_co, flat);
add_v3_v3v3(result, par_vec, curl_offset);
break;
@@ -490,7 +516,7 @@ void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3],
float z_vec[3] = {0.f, 0.f, 1.f};
float vec_one[3], state_co[3];
float inp_y, inp_z, length;
-
+
if (par_rot) {
mul_qt_v3(par_rot, y_vec);
mul_qt_v3(par_rot, z_vec);
@@ -559,10 +585,10 @@ static float do_clump_level(float result[3], const float co[3], const float par_
float clumpfac, float clumppow, float pa_clump, CurveMapping *clumpcurve)
{
float clump = 0.0f;
-
+
if (clumpcurve) {
- clump = pa_clump * (1.0f - CLAMPIS(curvemapping_evaluateF(clumpcurve, 0, time), 0.0f, 1.0f));
-
+ clump = pa_clump * (1.0f - clamp_f(curvemapping_evaluateF(clumpcurve, 0, time), 0.0f, 1.0f));
+
interp_v3_v3v3(result, co, par_co, clump);
}
else if (clumpfac != 0.0f) {
@@ -580,7 +606,7 @@ static float do_clump_level(float result[3], const float co[3], const float par_
interp_v3_v3v3(result, co, par_co, clump);
}
-
+
return clump;
}
@@ -588,21 +614,21 @@ float do_clump(ParticleKey *state, const float par_co[3], float time, const floa
bool use_clump_noise, float clump_noise_size, CurveMapping *clumpcurve)
{
float clump;
-
+
if (use_clump_noise && clump_noise_size != 0.0f) {
float center[3], noisevec[3];
float da[4], pa[12];
-
+
mul_v3_v3fl(noisevec, orco_offset, 1.0f / clump_noise_size);
voronoi(noisevec[0], noisevec[1], noisevec[2], da, pa, 1.0f, 0);
mul_v3_fl(&pa[0], clump_noise_size);
add_v3_v3v3(center, par_co, &pa[0]);
-
+
do_clump_level(state->co, state->co, center, time, clumpfac, clumppow, pa_clump, clumpcurve);
}
-
+
clump = do_clump_level(state->co, state->co, par_co, time, clumpfac, clumppow, pa_clump, clumpcurve);
-
+
return clump;
}
@@ -647,27 +673,117 @@ static void do_rough_curve(const float loc[3], float mat[4][4], float time, floa
{
float rough[3];
float rco[3];
-
+
if (!roughcurve)
return;
-
- fac *= CLAMPIS(curvemapping_evaluateF(roughcurve, 0, time), 0.0f, 1.0f);
-
+
+ fac *= clamp_f(curvemapping_evaluateF(roughcurve, 0, time), 0.0f, 1.0f);
+
copy_v3_v3(rco, loc);
mul_v3_fl(rco, time);
rough[0] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[0], rco[1], rco[2], 2, 0, 2);
rough[1] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[1], rco[2], rco[0], 2, 0, 2);
rough[2] = -1.0f + 2.0f * BLI_gTurbulence(size, rco[2], rco[0], rco[1], 2, 0, 2);
-
+
madd_v3_v3fl(state->co, mat[0], fac * rough[0]);
madd_v3_v3fl(state->co, mat[1], fac * rough[1]);
madd_v3_v3fl(state->co, mat[2], fac * rough[2]);
}
-void do_child_modifiers(ParticleThreadContext *ctx, ParticleSimulationData *sim, ParticleTexture *ptex,
- const float par_co[3], const float par_vel[3], const float par_rot[4], const float par_orco[3],
- ChildParticle *cpa, const float orco[3], float mat[4][4], ParticleKey *state, float t)
+static int twist_num_segments(const ParticleChildModifierContext *modifier_ctx)
+{
+ ParticleThreadContext *thread_ctx = modifier_ctx->thread_ctx;
+ return (thread_ctx != NULL) ? thread_ctx->segments
+ : modifier_ctx->sim->psys->part->draw_step;
+}
+
+static void twist_get_axis(const ParticleChildModifierContext *modifier_ctx,
+ const float time, float r_axis[3])
+{
+ const int num_segments = twist_num_segments(modifier_ctx);
+ const int index = clamp_i(time * num_segments, 0, num_segments);
+ if (index > 0) {
+ sub_v3_v3v3(r_axis,
+ modifier_ctx->parent_keys[index].co,
+ modifier_ctx->parent_keys[index - 1].co);
+ }
+ else {
+ sub_v3_v3v3(r_axis,
+ modifier_ctx->parent_keys[index + 1].co,
+ modifier_ctx->parent_keys[index].co);
+ }
+}
+
+static float curvemapping_integrate_clamped(CurveMapping *curve,
+ float start, float end, float step)
+{
+ float integral = 0.0f;
+ float x = start;
+ while (x < end) {
+ float y = curvemapping_evaluateF(curve, 0, x);
+ y = clamp_f(y, 0.0f, 1.0f);
+ /* TODO(sergey): Clamp last step to end. */
+ integral += y * step;
+ x += step;
+ }
+ return integral;
+}
+
+static void do_twist(const ParticleChildModifierContext *modifier_ctx,
+ ParticleKey *state, const float time)
+{
+ ParticleThreadContext *thread_ctx = modifier_ctx->thread_ctx;
+ ParticleSimulationData *sim = modifier_ctx->sim;
+ ParticleTexture *ptex = modifier_ctx->ptex;
+ ParticleSettings *part = sim->psys->part;
+ /* Early output checks. */
+ if (part->childtype != PART_CHILD_PARTICLES) {
+ /* Interpolated children behave weird with twist. */
+ return;
+ }
+ if (part->twist == 0.0f) {
+ /* No twist along the strand. */
+ return;
+ }
+ /* Dependent on whether it's threaded update or not, curve comes
+ * from different places.
+ */
+ CurveMapping *twist_curve = NULL;
+ if (part->child_flag & PART_CHILD_USE_TWIST_CURVE) {
+ twist_curve = (thread_ctx != NULL) ? thread_ctx->twistcurve
+ : part->twistcurve;
+ }
+ /* Axis of rotation. */
+ float axis[3];
+ twist_get_axis(modifier_ctx, time, axis);
+ /* Angle of rotation. */
+ float angle = part->twist;
+ if (ptex != NULL) {
+ angle *= (ptex->twist - 0.5f) * 2.0f;
+ }
+ if (twist_curve != NULL) {
+ const int num_segments = twist_num_segments(modifier_ctx);
+ angle *= curvemapping_integrate_clamped(twist_curve,
+ 0.0f, time,
+ 1.0f / num_segments);
+ }
+ else {
+ angle *= time;
+ }
+ /* Perform rotation around parent curve. */
+ float vec[3];
+ sub_v3_v3v3(vec, state->co, modifier_ctx->par_co);
+ rotate_v3_v3v3fl(state->co, vec, axis, angle * 2.0f * M_PI);
+ add_v3_v3(state->co, modifier_ctx->par_co);
+}
+
+void do_child_modifiers(const ParticleChildModifierContext *modifier_ctx,
+ float mat[4][4], ParticleKey *state, float t)
{
+ ParticleThreadContext *ctx = modifier_ctx->thread_ctx;
+ ParticleSimulationData *sim = modifier_ctx->sim;
+ ParticleTexture *ptex = modifier_ctx->ptex;
+ ChildParticle *cpa = modifier_ctx->cpa;
ParticleSettings *part = sim->psys->part;
CurveMapping *clumpcurve = NULL, *roughcurve = NULL;
int i = cpa - sim->psys->child;
@@ -696,6 +812,8 @@ void do_child_modifiers(ParticleThreadContext *ctx, ParticleSimulationData *sim,
rough_end *= ptex->roughe;
}
+ do_twist(modifier_ctx, state, t);
+
if (part->flag & PART_CHILD_EFFECT)
/* state is safe to cast, since only co and vel are used */
guided = do_guides(sim->psys->part, sim->psys->effectors, (ParticleKey *)state, cpa->parent, t);
@@ -703,33 +821,51 @@ void do_child_modifiers(ParticleThreadContext *ctx, ParticleSimulationData *sim,
if (guided == 0) {
float orco_offset[3];
float clump;
-
- sub_v3_v3v3(orco_offset, orco, par_orco);
- clump = do_clump(state, par_co, t, orco_offset, part->clumpfac, part->clumppow, ptex ? ptex->clump : 1.f,
- part->child_flag & PART_CHILD_USE_CLUMP_NOISE, part->clump_noise_size, clumpcurve);
+
+ sub_v3_v3v3(orco_offset, modifier_ctx->orco, modifier_ctx->par_orco);
+ clump = do_clump(state,
+ modifier_ctx->par_co,
+ t,
+ orco_offset,
+ part->clumpfac,
+ part->clumppow,
+ ptex ? ptex->clump : 1.0f,
+ part->child_flag & PART_CHILD_USE_CLUMP_NOISE,
+ part->clump_noise_size,
+ clumpcurve);
if (kink_freq != 0.f) {
kink_amp *= (1.f - kink_amp_clump * clump);
-
- do_kink(state, par_co, par_vel, par_rot, t, kink_freq, part->kink_shape,
- kink_amp, part->kink_flat, part->kink, part->kink_axis,
- sim->ob->obmat, smooth_start);
+
+ do_kink(state,
+ modifier_ctx->par_co,
+ modifier_ctx->par_vel,
+ modifier_ctx->par_rot,
+ t,
+ kink_freq,
+ part->kink_shape,
+ kink_amp,
+ part->kink_flat,
+ part->kink,
+ part->kink_axis,
+ sim->ob->obmat,
+ smooth_start);
}
}
if (roughcurve) {
- do_rough_curve(orco, mat, t, rough1, part->rough1_size, roughcurve, state);
+ do_rough_curve(modifier_ctx->orco, mat, t, rough1, part->rough1_size, roughcurve, state);
}
else {
if (rough1 > 0.f)
- do_rough(orco, mat, t, rough1, part->rough1_size, 0.0, state);
-
+ do_rough(modifier_ctx->orco, mat, t, rough1, part->rough1_size, 0.0, state);
+
if (rough2 > 0.f) {
float vec[3];
psys_frand_vec(sim->psys, i + 27, vec);
do_rough(vec, mat, t, rough2, part->rough2_size, part->rough2_thres, state);
}
-
+
if (rough_end > 0.f) {
float vec[3];
psys_frand_vec(sim->psys, i + 27, vec);
diff --git a/source/blender/blenkernel/intern/particle_distribute.c b/source/blender/blenkernel/intern/particle_distribute.c
index 44cf5b119c1..d1c6dbe421c 100644
--- a/source/blender/blenkernel/intern/particle_distribute.c
+++ b/source/blender/blenkernel/intern/particle_distribute.c
@@ -36,9 +36,10 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_kdtree.h"
#include "BLI_math.h"
+#include "BLI_math_geom.h"
#include "BLI_rand.h"
#include "BLI_sort.h"
#include "BLI_task.h"
@@ -213,14 +214,22 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys)
copy_v3_v3(co2, co1);
co2[a] += delta[a] + 0.001f*d;
co1[a] -= 0.001f*d;
-
+
+ struct IsectRayPrecalc isect_precalc;
+ float ray_direction[3];
+ sub_v3_v3v3(ray_direction, co2, co1);
+ isect_ray_tri_watertight_v3_precalc(&isect_precalc, ray_direction);
+
/* lets intersect the faces */
for (i=0; i<totface; i++,mface++) {
copy_v3_v3(v1, mvert[mface->v1].co);
copy_v3_v3(v2, mvert[mface->v2].co);
copy_v3_v3(v3, mvert[mface->v3].co);
- bool intersects_tri = isect_axial_line_segment_tri_v3(a, co1, co2, v2, v3, v1, &lambda);
+ bool intersects_tri = isect_ray_tri_watertight_v3(co1,
+ &isect_precalc,
+ v1, v2, v3,
+ &lambda, NULL);
if (intersects_tri) {
if (from==PART_FROM_FACE)
(pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
@@ -231,7 +240,12 @@ static void distribute_grid(DerivedMesh *dm, ParticleSystem *psys)
if (mface->v4 && (!intersects_tri || from==PART_FROM_VOLUME)) {
copy_v3_v3(v4, mvert[mface->v4].co);
- if (isect_axial_line_segment_tri_v3(a, co1, co2, v4, v1, v3, &lambda)) {
+ if (isect_ray_tri_watertight_v3(
+ co1,
+ &isect_precalc,
+ v1, v3, v4,
+ &lambda, NULL))
+ {
if (from==PART_FROM_FACE)
(pa+(int)(lambda*size[a])*a0mul)->flag &= ~PARS_UNEXIST;
else
@@ -427,12 +441,37 @@ static int distribute_binary_search(float *sum, int n, float value)
static void distribute_from_verts_exec(ParticleTask *thread, ParticleData *pa, int p)
{
ParticleThreadContext *ctx= thread->ctx;
- int rng_skip_tot= PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */
+ MFace *mface;
+
+ mface = ctx->dm->getTessFaceDataArray(ctx->dm, CD_MFACE);
+
+ int rng_skip_tot = PSYS_RND_DIST_SKIP; /* count how many rng_* calls wont need skipping */
/* TODO_PARTICLE - use original index */
- pa->num= ctx->index[p];
- pa->fuv[0] = 1.0f;
- pa->fuv[1] = pa->fuv[2] = pa->fuv[3] = 0.0;
+ pa->num = ctx->index[p];
+
+ zero_v4(pa->fuv);
+
+ if (pa->num != DMCACHE_NOTFOUND && pa->num < ctx->dm->getNumVerts(ctx->dm)) {
+
+ /* This finds the first face to contain the emitting vertex,
+ * this is not ideal, but is mostly fine as UV seams generally
+ * map to equal-colored parts of a texture */
+ for (int i = 0; i < ctx->dm->getNumTessFaces(ctx->dm); i++, mface++) {
+ if (ELEM(pa->num, mface->v1, mface->v2, mface->v3, mface->v4)) {
+ unsigned int *vert = &mface->v1;
+
+ for (int j = 0; j < 4; j++, vert++) {
+ if (*vert == pa->num) {
+ pa->fuv[j] = 1.0f;
+ break;
+ }
+ }
+
+ break;
+ }
+ }
+ }
#if ONLY_WORKING_WITH_PA_VERTS
if (ctx->tree) {
@@ -766,7 +805,7 @@ static void distribute_invalid(Scene *scene, ParticleSystem *psys, int from)
}
}
-/* Creates a distribution of coordinates on a DerivedMesh */
+/* Creates a distribution of coordinates on a DerivedMesh */
/* This is to denote functionality that does not yet work with mesh - only derived mesh */
static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, ParticleSimulationData *sim, int from)
{
@@ -873,10 +912,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti
else
dm= CDDM_from_mesh((Mesh*)ob->data);
- /* BMESH ONLY, for verts we don't care about tessfaces */
- if (from != PART_FROM_VERT) {
- DM_ensure_tessface(dm);
- }
+ DM_ensure_tessface(dm);
/* we need orco for consistent distributions */
if (!CustomData_has_layer(&dm->vertData, CD_ORCO))
@@ -919,9 +955,9 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti
return 0;
}
- element_weight = MEM_callocN(sizeof(float)*totelem, "particle_distribution_weights");
- particle_element= MEM_callocN(sizeof(int)*totpart, "particle_distribution_indexes");
- jitter_offset = MEM_callocN(sizeof(float)*totelem, "particle_distribution_jitoff");
+ element_weight = MEM_callocN(sizeof(float) * totelem, "particle_distribution_weights");
+ particle_element = MEM_callocN(sizeof(int) * totpart, "particle_distribution_indexes");
+ jitter_offset = MEM_callocN(sizeof(float) * totelem, "particle_distribution_jitoff");
/* Calculate weights from face areas */
if ((part->flag&PART_EDISTR || children) && from != PART_FROM_VERT) {
@@ -1070,13 +1106,10 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti
/* This is to address tricky issues with vertex-emitting when user tries (and expects) exact 1-1 vert/part
* distribution (see T47983 and its two example files). It allows us to consider pos as
* 'midpoint between v and v+1' (or 'p and p+1', depending whether we have more vertices than particles or not),
- * and avoid stumbling over float imprecisions in element_sum. */
- if (from == PART_FROM_VERT) {
- pos = (totpart < totmapped) ? 0.5 / (double)totmapped : step * 0.5; /* We choose the smaller step. */
- }
- else {
- pos = 0.0;
- }
+ * and avoid stumbling over float impression in element_sum.
+ * Note: moved face and volume distribution to this as well (instead of starting at zero),
+ * for the same reasons, see T52682. */
+ pos = (totpart < totmapped) ? 0.5 / (double)totmapped : step * 0.5; /* We choose the smaller step. */
for (i = 0, p = 0; p < totpart; p++, pos += step) {
for ( ; (i < totmapped - 1) && (pos > (double)element_sum[i]); i++);
@@ -1092,7 +1125,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti
/* For hair, sort by origindex (allows optimization's in rendering), */
/* however with virtual parents the children need to be in random order. */
- if (part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents!=0.0f)) {
+ if (part->type == PART_HAIR && !(part->childtype==PART_CHILD_FACES && part->parents != 0.0f)) {
int *orig_index = NULL;
if (from == PART_FROM_VERT) {
@@ -1115,7 +1148,7 @@ static int psys_thread_context_init_distribute(ParticleThreadContext *ctx, Parti
if (jitlevel == 0) {
jitlevel= totpart/totelem;
- if (part->flag & PART_EDISTR) jitlevel*= 2; /* looks better in general, not very scietific */
+ if (part->flag & PART_EDISTR) jitlevel*= 2; /* looks better in general, not very scientific */
if (jitlevel<3) jitlevel= 3;
}
diff --git a/source/blender/blenkernel/intern/particle_system.c b/source/blender/blenkernel/intern/particle_system.c
index 943dc781246..94c1dd0c7c3 100644
--- a/source/blender/blenkernel/intern/particle_system.c
+++ b/source/blender/blenkernel/intern/particle_system.c
@@ -48,7 +48,7 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_curve_types.h"
#include "DNA_scene_types.h"
@@ -58,7 +58,7 @@
#include "BLI_utildefines.h"
#include "BLI_edgehash.h"
#include "BLI_rand.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_kdtree.h"
@@ -76,7 +76,6 @@
#include "BKE_effect.h"
#include "BKE_library_query.h"
#include "BKE_particle.h"
-#include "BKE_global.h"
#include "BKE_DerivedMesh.h"
#include "BKE_object.h"
@@ -93,10 +92,11 @@
#include "PIL_time.h"
#include "RE_shader_ext.h"
+#include "DEG_depsgraph.h"
/* fluid sim particle import */
#ifdef WITH_MOD_FLUID
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "LBM_fluidsim.h"
#include <zlib.h>
#include <string.h>
@@ -497,6 +497,8 @@ void psys_thread_context_free(ParticleThreadContext *ctx)
MEM_freeN(ctx->vg_rough2);
if (ctx->vg_roughe)
MEM_freeN(ctx->vg_roughe);
+ if (ctx->vg_twist)
+ MEM_freeN(ctx->vg_twist);
if (ctx->sim.psys->lattice_deform_data) {
end_latt_deform(ctx->sim.psys->lattice_deform_data);
@@ -519,6 +521,9 @@ void psys_thread_context_free(ParticleThreadContext *ctx)
if (ctx->roughcurve != NULL) {
curvemapping_free(ctx->roughcurve);
}
+ if (ctx->twistcurve != NULL) {
+ curvemapping_free(ctx->twistcurve);
+ }
}
static void initialize_particle_texture(ParticleSimulationData *sim, ParticleData *pa, int p)
@@ -530,18 +535,20 @@ static void initialize_particle_texture(ParticleSimulationData *sim, ParticleDat
psys_get_texture(sim, pa, &ptex, PAMAP_INIT, 0.f);
switch (part->type) {
- case PART_EMITTER:
- if (ptex.exist < psys_frand(psys, p+125))
- pa->flag |= PARS_UNEXIST;
- pa->time = part->sta + (part->end - part->sta)*ptex.time;
- break;
- case PART_HAIR:
- if (ptex.exist < psys_frand(psys, p+125))
- pa->flag |= PARS_UNEXIST;
- pa->time = 0.f;
- break;
- case PART_FLUID:
- break;
+ case PART_EMITTER:
+ if (ptex.exist < psys_frand(psys, p + 125)) {
+ pa->flag |= PARS_UNEXIST;
+ }
+ pa->time = part->sta + (part->end - part->sta)*ptex.time;
+ break;
+ case PART_HAIR:
+ if (ptex.exist < psys_frand(psys, p + 125)) {
+ pa->flag |= PARS_UNEXIST;
+ }
+ pa->time = 0.f;
+ break;
+ case PART_FLUID:
+ break;
}
}
@@ -1000,7 +1007,7 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime,
part=psys->part;
/* get precise emitter matrix if particle is born */
- if (part->type!=PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
+ if (part->type != PART_HAIR && dtime > 0.f && pa->time < cfra && pa->time >= sim->psys->cfra) {
evaluate_emitter_anim(sim->scene, sim->ob, pa->time);
psys->flag |= PSYS_OB_ANIM_RESTORE;
@@ -1054,8 +1061,10 @@ void reset_particle(ParticleSimulationData *sim, ParticleData *pa, float dtime,
pa->dietime = pa->time + pa->lifetime;
- if (sim->psys->pointcache && sim->psys->pointcache->flag & PTCACHE_BAKED &&
- sim->psys->pointcache->mem_cache.first) {
+ if ((sim->psys->pointcache) &&
+ (sim->psys->pointcache->flag & PTCACHE_BAKED) &&
+ (sim->psys->pointcache->mem_cache.first))
+ {
float dietime = psys_get_dietime_from_cache(sim->psys->pointcache, p);
pa->dietime = MIN2(pa->dietime, dietime);
}
@@ -1183,7 +1192,7 @@ static void set_keyed_keys(ParticleSimulationData *sim)
key->time = pa->time;
}
- if (psys->flag & PSYS_KEYED_TIMING && pt->duration!=0.0f)
+ if (psys->flag & PSYS_KEYED_TIMING && pt->duration != 0.0f)
k++;
ksim.psys->flag |= keyed_flag;
@@ -2319,21 +2328,21 @@ static void collision_point_on_surface(float p[3], ParticleCollisionElement *pce
}
case 3:
{
- float p0[3], e1[3], e2[3], nor[3];
+ float p0[3], e1[3], e2[3], nor[3];
- sub_v3_v3v3(e1, pce->x1, pce->x0);
- sub_v3_v3v3(e2, pce->x2, pce->x0);
- sub_v3_v3v3(p0, p, pce->x0);
+ sub_v3_v3v3(e1, pce->x1, pce->x0);
+ sub_v3_v3v3(e2, pce->x2, pce->x0);
+ sub_v3_v3v3(p0, p, pce->x0);
- cross_v3_v3v3(nor, e1, e2);
- normalize_v3(nor);
+ cross_v3_v3v3(nor, e1, e2);
+ normalize_v3(nor);
- if (pce->inv_nor == 1)
- negate_v3(nor);
+ if (pce->inv_nor == 1)
+ negate_v3(nor);
- madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
- madd_v3_v3fl(co, e1, pce->uv[0]);
- madd_v3_v3fl(co, e2, pce->uv[1]);
+ madd_v3_v3v3fl(co, pce->x0, nor, col->radius);
+ madd_v3_v3fl(co, e1, pce->uv[0]);
+ madd_v3_v3fl(co, e2, pce->uv[1]);
break;
}
}
@@ -3042,10 +3051,12 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int
/* calculate maximum segment length */
max_length = 0.0f;
LOOP_PARTICLES {
- for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
- float length = len_v3v3(key->co, (key-1)->co);
- if (max_length < length)
- max_length = length;
+ if (!(pa->flag & PARS_UNEXIST)) {
+ for (k=1, key=pa->hair+1; k<pa->totkey; k++,key++) {
+ float length = len_v3v3(key->co, (key-1)->co);
+ if (max_length < length)
+ max_length = length;
+ }
}
}
@@ -3057,76 +3068,78 @@ static void hair_create_input_dm(ParticleSimulationData *sim, int totpoint, int
/* make vgroup for pin roots etc.. */
hair_index = 1;
LOOP_PARTICLES {
- float root_mat[4][4];
- float bending_stiffness;
- bool use_hair;
-
- pa->hair_index = hair_index;
- use_hair = psys_hair_use_simulation(pa, max_length);
-
- psys_mat_hair_to_object(sim->ob, sim->psmd->dm_final, psys->part->from, pa, hairmat);
- mul_m4_m4m4(root_mat, sim->ob->obmat, hairmat);
- normalize_m4(root_mat);
-
- bending_stiffness = CLAMPIS(1.0f - part->bending_random * psys_frand(psys, p + 666), 0.0f, 1.0f);
-
- for (k=0, key=pa->hair; k<pa->totkey; k++,key++) {
- ClothHairData *hair;
- float *co, *co_next;
-
- co = key->co;
- co_next = (key+1)->co;
-
- /* create fake root before actual root to resist bending */
- if (k==0) {
- hair = &psys->clmd->hairdata[pa->hair_index - 1];
+ if (!(pa->flag & PARS_UNEXIST)) {
+ float root_mat[4][4];
+ float bending_stiffness;
+ bool use_hair;
+
+ pa->hair_index = hair_index;
+ use_hair = psys_hair_use_simulation(pa, max_length);
+
+ psys_mat_hair_to_object(sim->ob, sim->psmd->dm_final, psys->part->from, pa, hairmat);
+ mul_m4_m4m4(root_mat, sim->ob->obmat, hairmat);
+ normalize_m4(root_mat);
+
+ bending_stiffness = CLAMPIS(1.0f - part->bending_random * psys_frand(psys, p + 666), 0.0f, 1.0f);
+
+ for (k=0, key=pa->hair; k<pa->totkey; k++,key++) {
+ ClothHairData *hair;
+ float *co, *co_next;
+
+ co = key->co;
+ co_next = (key+1)->co;
+
+ /* create fake root before actual root to resist bending */
+ if (k==0) {
+ hair = &psys->clmd->hairdata[pa->hair_index - 1];
+ copy_v3_v3(hair->loc, root_mat[3]);
+ copy_m3_m4(hair->rot, root_mat);
+
+ hair->radius = hair_radius;
+ hair->bending_stiffness = bending_stiffness;
+
+ add_v3_v3v3(mvert->co, co, co);
+ sub_v3_v3(mvert->co, co_next);
+ mul_m4_v3(hairmat, mvert->co);
+
+ medge->v1 = pa->hair_index - 1;
+ medge->v2 = pa->hair_index;
+
+ dvert = hair_set_pinning(dvert, 1.0f);
+
+ mvert++;
+ medge++;
+ }
+
+ /* store root transform in cloth data */
+ hair = &psys->clmd->hairdata[pa->hair_index + k];
copy_v3_v3(hair->loc, root_mat[3]);
copy_m3_m4(hair->rot, root_mat);
-
+
hair->radius = hair_radius;
hair->bending_stiffness = bending_stiffness;
-
- add_v3_v3v3(mvert->co, co, co);
- sub_v3_v3(mvert->co, co_next);
+
+ copy_v3_v3(mvert->co, co);
mul_m4_v3(hairmat, mvert->co);
-
- medge->v1 = pa->hair_index - 1;
- medge->v2 = pa->hair_index;
-
- dvert = hair_set_pinning(dvert, 1.0f);
-
+
+ if (k) {
+ medge->v1 = pa->hair_index + k - 1;
+ medge->v2 = pa->hair_index + k;
+ }
+
+ /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */
+ if (use_hair)
+ dvert = hair_set_pinning(dvert, key->weight);
+ else
+ dvert = hair_set_pinning(dvert, 1.0f);
+
mvert++;
- medge++;
- }
-
- /* store root transform in cloth data */
- hair = &psys->clmd->hairdata[pa->hair_index + k];
- copy_v3_v3(hair->loc, root_mat[3]);
- copy_m3_m4(hair->rot, root_mat);
-
- hair->radius = hair_radius;
- hair->bending_stiffness = bending_stiffness;
-
- copy_v3_v3(mvert->co, co);
- mul_m4_v3(hairmat, mvert->co);
-
- if (k) {
- medge->v1 = pa->hair_index + k - 1;
- medge->v2 = pa->hair_index + k;
+ if (k)
+ medge++;
}
-
- /* roots and disabled hairs should be 1.0, the rest can be anything from 0.0 to 1.0 */
- if (use_hair)
- dvert = hair_set_pinning(dvert, key->weight);
- else
- dvert = hair_set_pinning(dvert, 1.0f);
-
- mvert++;
- if (k)
- medge++;
+
+ hair_index += pa->totkey + 1;
}
-
- hair_index += pa->totkey + 1;
}
}
@@ -3152,9 +3165,11 @@ static void do_hair_dynamics(ParticleSimulationData *sim)
totpoint = 0;
totedge = 0;
LOOP_PARTICLES {
- /* "out" dm contains all hairs */
- totedge += pa->totkey;
- totpoint += pa->totkey + 1; /* +1 for virtual root point */
+ if (!(pa->flag & PARS_UNEXIST)) {
+ /* "out" dm contains all hairs */
+ totedge += pa->totkey;
+ totpoint += pa->totkey + 1; /* +1 for virtual root point */
+ }
}
realloc_roots = false; /* whether hair root info array has to be reallocated */
@@ -3365,14 +3380,16 @@ typedef struct DynamicStepSolverTaskData {
} DynamicStepSolverTaskData;
static void dynamics_step_sph_ddr_task_cb_ex(
- void *userdata, void *userdata_chunk, const int p, const int UNUSED(thread_id))
+ void *__restrict userdata,
+ const int p,
+ const ParallelRangeTLS *__restrict tls)
{
DynamicStepSolverTaskData *data = userdata;
ParticleSimulationData *sim = data->sim;
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
- SPHData *sphdata = userdata_chunk;
+ SPHData *sphdata = tls->userdata_chunk;
ParticleData *pa;
@@ -3399,7 +3416,9 @@ static void dynamics_step_sph_ddr_task_cb_ex(
}
static void dynamics_step_sph_classical_basic_integrate_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int p, const int UNUSED(thread_id))
+ void *__restrict userdata,
+ const int p,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
DynamicStepSolverTaskData *data = userdata;
ParticleSimulationData *sim = data->sim;
@@ -3415,13 +3434,15 @@ static void dynamics_step_sph_classical_basic_integrate_task_cb_ex(
}
static void dynamics_step_sph_classical_calc_density_task_cb_ex(
- void *userdata, void *userdata_chunk, const int p, const int UNUSED(thread_id))
+ void *__restrict userdata,
+ const int p,
+ const ParallelRangeTLS *__restrict tls)
{
DynamicStepSolverTaskData *data = userdata;
ParticleSimulationData *sim = data->sim;
ParticleSystem *psys = sim->psys;
- SPHData *sphdata = userdata_chunk;
+ SPHData *sphdata = tls->userdata_chunk;
ParticleData *pa;
@@ -3433,14 +3454,16 @@ static void dynamics_step_sph_classical_calc_density_task_cb_ex(
}
static void dynamics_step_sph_classical_integrate_task_cb_ex(
- void *userdata, void *userdata_chunk, const int p, const int UNUSED(thread_id))
+ void *__restrict userdata,
+ const int p,
+ const ParallelRangeTLS *__restrict tls)
{
DynamicStepSolverTaskData *data = userdata;
ParticleSimulationData *sim = data->sim;
ParticleSystem *psys = sim->psys;
ParticleSettings *part = psys->part;
- SPHData *sphdata = userdata_chunk;
+ SPHData *sphdata = tls->userdata_chunk;
ParticleData *pa;
@@ -3631,9 +3654,16 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra)
/* Apply SPH forces using double-density relaxation algorithm
* (Clavat et. al.) */
- BLI_task_parallel_range_ex(
- 0, psys->totpart, &task_data, &sphdata, sizeof(sphdata),
- dynamics_step_sph_ddr_task_cb_ex, psys->totpart > 100, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (psys->totpart > 100);
+ settings.userdata_chunk = &sphdata;
+ settings.userdata_chunk_size = sizeof(sphdata);
+ BLI_task_parallel_range(
+ 0, psys->totpart,
+ &task_data,
+ dynamics_step_sph_ddr_task_cb_ex,
+ &settings);
sph_springs_modify(psys, timestep);
}
@@ -3643,21 +3673,46 @@ static void dynamics_step(ParticleSimulationData *sim, float cfra)
* and Monaghan). Note that, unlike double-density relaxation,
* this algorithm is separated into distinct loops. */
- BLI_task_parallel_range_ex(
- 0, psys->totpart, &task_data, NULL, 0,
- dynamics_step_sph_classical_basic_integrate_task_cb_ex, psys->totpart > 100, true);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (psys->totpart > 100);
+ BLI_task_parallel_range(
+ 0, psys->totpart,
+ &task_data,
+ dynamics_step_sph_classical_basic_integrate_task_cb_ex,
+ &settings);
+ }
/* calculate summation density */
/* Note that we could avoid copying sphdata for each thread here (it's only read here),
* but doubt this would gain us anything except confusion... */
- BLI_task_parallel_range_ex(
- 0, psys->totpart, &task_data, &sphdata, sizeof(sphdata),
- dynamics_step_sph_classical_calc_density_task_cb_ex, psys->totpart > 100, true);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (psys->totpart > 100);
+ settings.userdata_chunk = &sphdata;
+ settings.userdata_chunk_size = sizeof(sphdata);
+ BLI_task_parallel_range(
+ 0, psys->totpart,
+ &task_data,
+ dynamics_step_sph_classical_calc_density_task_cb_ex,
+ &settings);
+ }
/* do global forces & effectors */
- BLI_task_parallel_range_ex(
- 0, psys->totpart, &task_data, &sphdata, sizeof(sphdata),
- dynamics_step_sph_classical_integrate_task_cb_ex, psys->totpart > 100, true);
+ {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (psys->totpart > 100);
+ settings.userdata_chunk = &sphdata;
+ settings.userdata_chunk_size = sizeof(sphdata);
+ BLI_task_parallel_range(
+ 0, psys->totpart,
+ &task_data,
+ dynamics_step_sph_classical_integrate_task_cb_ex,
+ &settings);
+ }
}
BLI_spin_end(&task_data.spin);
@@ -4350,13 +4405,10 @@ void BKE_particlesystem_id_loop(ParticleSystem *psys, ParticleSystemIDFunc func,
/* **** Depsgraph evaluation **** */
-void BKE_particle_system_eval(EvaluationContext *UNUSED(eval_ctx),
- Scene *scene,
- Object *ob,
- ParticleSystem *psys)
+void BKE_particle_system_eval_init(EvaluationContext *UNUSED(eval_ctx),
+ Scene *scene,
+ Object *ob)
{
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s on %s:%s\n", __func__, ob->id.name, psys->name);
- }
+ DEG_debug_print_eval(__func__, ob->id.name, ob);
BKE_ptcache_object_reset(scene, ob, PTCACHE_RESET_DEPSGRAPH);
}
diff --git a/source/blender/blenkernel/intern/pbvh.c b/source/blender/blenkernel/intern/pbvh.c
index 4fe4d6e75a6..51d50b061de 100644
--- a/source/blender/blenkernel/intern/pbvh.c
+++ b/source/blender/blenkernel/intern/pbvh.c
@@ -34,6 +34,7 @@
#include "BKE_pbvh.h"
#include "BKE_ccg.h"
+#include "BKE_subsurf.h"
#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
#include "BKE_mesh.h" /* for BKE_mesh_calc_normals */
@@ -606,6 +607,11 @@ void BKE_pbvh_build_grids(PBVH *bvh, CCGElem **grids,
MEM_freeN(prim_bbc);
}
+void BKE_pbvh_set_ccgdm(PBVH *bvh, CCGDerivedMesh *ccgdm)
+{
+ bvh->ccgdm = ccgdm;
+}
+
PBVH *BKE_pbvh_new(void)
{
PBVH *bvh = MEM_callocN(sizeof(PBVH), "pbvh");
@@ -620,7 +626,7 @@ void BKE_pbvh_free(PBVH *bvh)
if (node->flag & PBVH_Leaf) {
if (node->draw_buffers)
- GPU_free_pbvh_buffers(node->draw_buffers);
+ GPU_pbvh_buffers_free(node->draw_buffers);
if (node->vert_indices)
MEM_freeN((void *)node->vert_indices);
if (node->face_vert_indices)
@@ -635,7 +641,7 @@ void BKE_pbvh_free(PBVH *bvh)
BLI_gset_free(node->bm_other_verts, NULL);
}
}
- GPU_free_pbvh_buffer_multires(&bvh->grid_common_gpu_buffer);
+ GPU_pbvh_multires_buffers_free(&bvh->grid_common_gpu_buffer);
if (bvh->deformed) {
if (bvh->verts) {
@@ -932,7 +938,10 @@ typedef struct PBVHUpdateData {
int flag;
} PBVHUpdateData;
-static void pbvh_update_normals_accum_task_cb(void *userdata, const int n)
+static void pbvh_update_normals_accum_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PBVHUpdateData *data = userdata;
@@ -985,7 +994,10 @@ static void pbvh_update_normals_accum_task_cb(void *userdata, const int n)
}
}
-static void pbvh_update_normals_store_task_cb(void *userdata, const int n)
+static void pbvh_update_normals_store_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PBVHUpdateData *data = userdata;
PBVH *bvh = data->bvh;
@@ -1001,9 +1013,7 @@ static void pbvh_update_normals_store_task_cb(void *userdata, const int n)
MVert *mvert = &bvh->verts[v];
/* mvert is shared between nodes, hence between threads. */
- if (atomic_fetch_and_and_uint8(
- (uint8_t *)&mvert->flag, (uint8_t)~ME_VERT_PBVH_UPDATE) & ME_VERT_PBVH_UPDATE)
- {
+ if (atomic_fetch_and_and_char(&mvert->flag, (char)~ME_VERT_PBVH_UPDATE) & ME_VERT_PBVH_UPDATE) {
normalize_v3(vnors[v]);
normal_float_to_short_v3(mvert->no, vnors[v]);
}
@@ -1046,14 +1056,21 @@ static void pbvh_update_normals(PBVH *bvh, PBVHNode **nodes,
.fnors = fnors, .vnors = vnors,
};
- BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_accum_task_cb, totnode > PBVH_THREADED_LIMIT);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
- BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_store_task_cb, totnode > PBVH_THREADED_LIMIT);
+ BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_accum_task_cb, &settings);
+
+ BLI_task_parallel_range(0, totnode, &data, pbvh_update_normals_store_task_cb, &settings);
MEM_freeN(vnors);
}
-static void pbvh_update_BB_redraw_task_cb(void *userdata, const int n)
+static void pbvh_update_BB_redraw_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PBVHUpdateData *data = userdata;
PBVH *bvh = data->bvh;
@@ -1080,7 +1097,18 @@ void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag)
.flag = flag,
};
- BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, totnode > PBVH_THREADED_LIMIT);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (totnode > PBVH_THREADED_LIMIT);
+ BLI_task_parallel_range(0, totnode, &data, pbvh_update_BB_redraw_task_cb, &settings);
+}
+
+static int pbvh_get_buffers_update_flags(PBVH *bvh)
+{
+ int update_flags = 0;
+ update_flags |= bvh->show_diffuse_color ? GPU_PBVH_BUFFERS_SHOW_DIFFUSE_COLOR : 0;
+ update_flags |= bvh->show_mask ? GPU_PBVH_BUFFERS_SHOW_MASK : 0;
+ return update_flags;
}
static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
@@ -1090,11 +1118,11 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
PBVHNode *node = nodes[n];
if (node->flag & PBVH_RebuildDrawBuffers) {
- GPU_free_pbvh_buffers(node->draw_buffers);
+ GPU_pbvh_buffers_free(node->draw_buffers);
switch (bvh->type) {
case PBVH_GRIDS:
node->draw_buffers =
- GPU_build_grid_pbvh_buffers(node->prim_indices,
+ GPU_pbvh_grid_buffers_build(node->prim_indices,
node->totprim,
bvh->grid_hidden,
bvh->gridkey.grid_size,
@@ -1102,7 +1130,7 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
break;
case PBVH_FACES:
node->draw_buffers =
- GPU_build_mesh_pbvh_buffers(node->face_vert_indices,
+ GPU_pbvh_mesh_buffers_build(node->face_vert_indices,
bvh->mpoly, bvh->mloop, bvh->looptri,
bvh->verts,
node->prim_indices,
@@ -1110,42 +1138,45 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
break;
case PBVH_BMESH:
node->draw_buffers =
- GPU_build_bmesh_pbvh_buffers(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING);
+ GPU_pbvh_bmesh_buffers_build(bvh->flags & PBVH_DYNTOPO_SMOOTH_SHADING);
break;
}
-
+
node->flag &= ~PBVH_RebuildDrawBuffers;
}
if (node->flag & PBVH_UpdateDrawBuffers) {
+ const int update_flags = pbvh_get_buffers_update_flags(bvh);
switch (bvh->type) {
case PBVH_GRIDS:
- GPU_update_grid_pbvh_buffers(node->draw_buffers,
- bvh->grids,
- bvh->grid_flag_mats,
- node->prim_indices,
- node->totprim,
- &bvh->gridkey,
- bvh->show_diffuse_color);
+ GPU_pbvh_grid_buffers_update(
+ node->draw_buffers,
+ bvh->grids,
+ bvh->grid_flag_mats,
+ node->prim_indices,
+ node->totprim,
+ &bvh->gridkey,
+ update_flags);
break;
case PBVH_FACES:
- GPU_update_mesh_pbvh_buffers(node->draw_buffers,
- bvh->verts,
- node->vert_indices,
- node->uniq_verts +
- node->face_verts,
- CustomData_get_layer(bvh->vdata,
- CD_PAINT_MASK),
- node->face_vert_indices,
- bvh->show_diffuse_color);
+ GPU_pbvh_mesh_buffers_update(
+ node->draw_buffers,
+ bvh->verts,
+ node->vert_indices,
+ node->uniq_verts +
+ node->face_verts,
+ CustomData_get_layer(bvh->vdata, CD_PAINT_MASK),
+ node->face_vert_indices,
+ update_flags);
break;
case PBVH_BMESH:
- GPU_update_bmesh_pbvh_buffers(node->draw_buffers,
- bvh->bm,
- node->bm_faces,
- node->bm_unique_verts,
- node->bm_other_verts,
- bvh->show_diffuse_color);
+ GPU_pbvh_bmesh_buffers_update(
+ node->draw_buffers,
+ bvh->bm,
+ node->bm_faces,
+ node->bm_unique_verts,
+ node->bm_other_verts,
+ update_flags);
break;
}
@@ -1154,17 +1185,17 @@ static void pbvh_update_draw_buffers(PBVH *bvh, PBVHNode **nodes, int totnode)
}
}
-static void pbvh_draw_BB(PBVH *bvh)
+void BKE_pbvh_draw_BB(PBVH *bvh)
{
- GPU_init_draw_pbvh_BB();
+ GPU_pbvh_BB_draw_init();
for (int a = 0; a < bvh->totnode; a++) {
PBVHNode *node = &bvh->nodes[a];
- GPU_draw_pbvh_BB(node->vb.bmin, node->vb.bmax, ((node->flag & PBVH_Leaf) != 0));
+ GPU_pbvh_BB_draw(node->vb.bmin, node->vb.bmax, ((node->flag & PBVH_Leaf) != 0));
}
- GPU_end_draw_pbvh_BB();
+ GPU_pbvh_BB_draw_end();
}
static int pbvh_flush_bb(PBVH *bvh, PBVHNode *node, int flag)
@@ -1263,7 +1294,7 @@ void BKE_pbvh_get_grid_updates(PBVH *bvh, bool clear, void ***r_gridfaces, int *
pbvh_iter_end(&iter);
- const int tot = BLI_gset_size(face_set);
+ const int tot = BLI_gset_len(face_set);
if (tot == 0) {
*r_totface = 0;
*r_gridfaces = NULL;
@@ -1327,6 +1358,12 @@ void BKE_pbvh_get_grid_key(const PBVH *bvh, CCGKey *key)
*key = bvh->gridkey;
}
+CCGDerivedMesh *BKE_pbvh_get_ccgdm(const PBVH *bvh)
+{
+ return bvh->ccgdm;
+}
+
+
BMesh *BKE_pbvh_get_bmesh(PBVH *bvh)
{
BLI_assert(bvh->type == PBVH_BMESH);
@@ -1396,8 +1433,8 @@ void BKE_pbvh_node_num_verts(
if (r_uniquevert) *r_uniquevert = node->uniq_verts;
break;
case PBVH_BMESH:
- tot = BLI_gset_size(node->bm_unique_verts);
- if (r_totvert) *r_totvert = tot + BLI_gset_size(node->bm_other_verts);
+ tot = BLI_gset_len(node->bm_unique_verts);
+ if (r_totvert) *r_totvert = tot + BLI_gset_len(node->bm_other_verts);
if (r_uniquevert) *r_uniquevert = tot;
break;
}
@@ -1525,14 +1562,16 @@ void BKE_pbvh_raycast(
bool ray_face_intersection_quad(
const float ray_start[3], const float ray_normal[3],
const float t0[3], const float t1[3], const float t2[3], const float t3[3],
- float *dist)
+ float *depth)
{
- float dist_test;
+ float depth_test;
- if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist_test, NULL, 0.1f) && (dist_test < *dist)) ||
- (isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t2, t3, &dist_test, NULL, 0.1f) && (dist_test < *dist)))
+ if ((isect_ray_tri_epsilon_v3(
+ ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)) ||
+ (isect_ray_tri_epsilon_v3(
+ ray_start, ray_normal, t0, t2, t3, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
{
- *dist = dist_test;
+ *depth = depth_test;
return true;
}
else {
@@ -1543,12 +1582,82 @@ bool ray_face_intersection_quad(
bool ray_face_intersection_tri(
const float ray_start[3], const float ray_normal[3],
const float t0[3], const float t1[3], const float t2[3],
- float *dist)
+ float *depth)
+{
+ float depth_test;
+
+ if ((isect_ray_tri_epsilon_v3(
+ ray_start, ray_normal, t0, t1, t2, &depth_test, NULL, 0.1f) && (depth_test < *depth)))
+ {
+ *depth = depth_test;
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+/* Take advantage of the fact we know this wont be an intersection.
+ * Just handle ray-tri edges. */
+static float dist_squared_ray_to_tri_v3_fast(
+ const float ray_origin[3], const float ray_direction[3],
+ const float v0[3], const float v1[3], const float v2[3],
+ float r_point[3], float *r_depth)
+{
+ const float *tri[3] = {v0, v1, v2};
+ float dist_sq_best = FLT_MAX;
+ for (int i = 0, j = 2; i < 3; j = i++) {
+ float point_test[3], depth_test = FLT_MAX;
+ const float dist_sq_test = dist_squared_ray_to_seg_v3(
+ ray_origin, ray_direction, tri[i], tri[j], point_test, &depth_test);
+ if (dist_sq_test < dist_sq_best || i == 0) {
+ copy_v3_v3(r_point, point_test);
+ *r_depth = depth_test;
+ dist_sq_best = dist_sq_test;
+ }
+ }
+ return dist_sq_best;
+}
+
+bool ray_face_nearest_quad(
+ const float ray_start[3], const float ray_normal[3],
+ const float t0[3], const float t1[3], const float t2[3], const float t3[3],
+ float *depth, float *dist_sq)
+{
+ float dist_sq_test;
+ float co[3], depth_test;
+
+ if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
+ ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
+ {
+ *dist_sq = dist_sq_test;
+ *depth = depth_test;
+ if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
+ ray_start, ray_normal, t0, t2, t3, co, &depth_test)) < *dist_sq))
+ {
+ *dist_sq = dist_sq_test;
+ *depth = depth_test;
+ }
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+bool ray_face_nearest_tri(
+ const float ray_start[3], const float ray_normal[3],
+ const float t0[3], const float t1[3], const float t2[3],
+ float *depth, float *dist_sq)
{
- float dist_test;
+ float dist_sq_test;
+ float co[3], depth_test;
- if ((isect_ray_tri_epsilon_v3(ray_start, ray_normal, t0, t1, t2, &dist_test, NULL, 0.1f) && (dist_test < *dist))) {
- *dist = dist_test;
+ if (((dist_sq_test = dist_squared_ray_to_tri_v3_fast(
+ ray_start, ray_normal, t0, t1, t2, co, &depth_test)) < *dist_sq))
+ {
+ *dist_sq = dist_sq_test;
+ *depth = depth_test;
return true;
}
else {
@@ -1560,7 +1669,7 @@ static bool pbvh_faces_node_raycast(
PBVH *bvh, const PBVHNode *node,
float (*origco)[3],
const float ray_start[3], const float ray_normal[3],
- float *dist)
+ float *depth)
{
const MVert *vert = bvh->verts;
const MLoop *mloop = bvh->mloop;
@@ -1582,7 +1691,7 @@ static bool pbvh_faces_node_raycast(
origco[face_verts[0]],
origco[face_verts[1]],
origco[face_verts[2]],
- dist);
+ depth);
}
else {
/* intersect with current coordinates */
@@ -1591,7 +1700,7 @@ static bool pbvh_faces_node_raycast(
vert[mloop[lt->tri[0]].v].co,
vert[mloop[lt->tri[1]].v].co,
vert[mloop[lt->tri[2]].v].co,
- dist);
+ depth);
}
}
@@ -1602,7 +1711,7 @@ static bool pbvh_grids_node_raycast(
PBVH *bvh, PBVHNode *node,
float (*origco)[3],
const float ray_start[3], const float ray_normal[3],
- float *dist)
+ float *depth)
{
const int totgrid = node->totprim;
const int gridsize = bvh->gridkey.grid_size;
@@ -1632,7 +1741,7 @@ static bool pbvh_grids_node_raycast(
origco[y * gridsize + x + 1],
origco[(y + 1) * gridsize + x + 1],
origco[(y + 1) * gridsize + x],
- dist);
+ depth);
}
else {
hit |= ray_face_intersection_quad(
@@ -1641,7 +1750,7 @@ static bool pbvh_grids_node_raycast(
CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
- dist);
+ depth);
}
}
}
@@ -1656,7 +1765,7 @@ static bool pbvh_grids_node_raycast(
bool BKE_pbvh_node_raycast(
PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
const float ray_start[3], const float ray_normal[3],
- float *dist)
+ float *depth)
{
bool hit = false;
@@ -1667,16 +1776,16 @@ bool BKE_pbvh_node_raycast(
case PBVH_FACES:
hit |= pbvh_faces_node_raycast(
bvh, node, origco,
- ray_start, ray_normal, dist);
+ ray_start, ray_normal, depth);
break;
case PBVH_GRIDS:
hit |= pbvh_grids_node_raycast(
bvh, node, origco,
- ray_start, ray_normal, dist);
+ ray_start, ray_normal, depth);
break;
case PBVH_BMESH:
hit = pbvh_bmesh_node_raycast(
- node, ray_start, ray_normal, dist, use_origco);
+ node, ray_start, ray_normal, depth, use_origco);
break;
}
@@ -1727,6 +1836,176 @@ void BKE_pbvh_raycast_project_ray_root(
}
}
+/* -------------------------------------------------------------------- */
+
+typedef struct {
+ struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
+ bool original;
+} FindNearestRayData;
+
+static bool nearest_to_ray_aabb_dist_sq(PBVHNode *node, void *data_v)
+{
+ FindNearestRayData *rcd = data_v;
+ const float *bb_min, *bb_max;
+
+ if (rcd->original) {
+ /* BKE_pbvh_node_get_original_BB */
+ bb_min = node->orig_vb.bmin;
+ bb_max = node->orig_vb.bmax;
+ }
+ else {
+ /* BKE_pbvh_node_get_BB */
+ bb_min = node->vb.bmin;
+ bb_max = node->vb.bmax;
+ }
+
+ float co_dummy[3], depth;
+ node->tmin = dist_squared_ray_to_aabb_v3(&rcd->dist_ray_to_aabb_precalc, bb_min, bb_max, co_dummy, &depth);
+ /* Ideally we would skip distances outside the range. */
+ return depth > 0.0f;
+}
+
+void BKE_pbvh_find_nearest_to_ray(
+ PBVH *bvh, BKE_pbvh_SearchNearestCallback cb, void *data,
+ const float ray_start[3], const float ray_normal[3],
+ bool original)
+{
+ FindNearestRayData ncd;
+
+ dist_squared_ray_to_aabb_v3_precalc(&ncd.dist_ray_to_aabb_precalc, ray_start, ray_normal);
+ ncd.original = original;
+
+ BKE_pbvh_search_callback_occluded(bvh, nearest_to_ray_aabb_dist_sq, &ncd, cb, data);
+}
+
+
+static bool pbvh_faces_node_nearest_to_ray(
+ PBVH *bvh, const PBVHNode *node,
+ float (*origco)[3],
+ const float ray_start[3], const float ray_normal[3],
+ float *depth, float *dist_sq)
+{
+ const MVert *vert = bvh->verts;
+ const MLoop *mloop = bvh->mloop;
+ const int *faces = node->prim_indices;
+ int i, totface = node->totprim;
+ bool hit = false;
+
+ for (i = 0; i < totface; ++i) {
+ const MLoopTri *lt = &bvh->looptri[faces[i]];
+ const int *face_verts = node->face_vert_indices[i];
+
+ if (paint_is_face_hidden(lt, vert, mloop))
+ continue;
+
+ if (origco) {
+ /* intersect with backuped original coordinates */
+ hit |= ray_face_nearest_tri(
+ ray_start, ray_normal,
+ origco[face_verts[0]],
+ origco[face_verts[1]],
+ origco[face_verts[2]],
+ depth, dist_sq);
+ }
+ else {
+ /* intersect with current coordinates */
+ hit |= ray_face_nearest_tri(
+ ray_start, ray_normal,
+ vert[mloop[lt->tri[0]].v].co,
+ vert[mloop[lt->tri[1]].v].co,
+ vert[mloop[lt->tri[2]].v].co,
+ depth, dist_sq);
+ }
+ }
+
+ return hit;
+}
+
+static bool pbvh_grids_node_nearest_to_ray(
+ PBVH *bvh, PBVHNode *node,
+ float (*origco)[3],
+ const float ray_start[3], const float ray_normal[3],
+ float *depth, float *dist_sq)
+{
+ const int totgrid = node->totprim;
+ const int gridsize = bvh->gridkey.grid_size;
+ bool hit = false;
+
+ for (int i = 0; i < totgrid; ++i) {
+ CCGElem *grid = bvh->grids[node->prim_indices[i]];
+ BLI_bitmap *gh;
+
+ if (!grid)
+ continue;
+
+ gh = bvh->grid_hidden[node->prim_indices[i]];
+
+ for (int y = 0; y < gridsize - 1; ++y) {
+ for (int x = 0; x < gridsize - 1; ++x) {
+ /* check if grid face is hidden */
+ if (gh) {
+ if (paint_is_grid_face_hidden(gh, gridsize, x, y))
+ continue;
+ }
+
+ if (origco) {
+ hit |= ray_face_nearest_quad(
+ ray_start, ray_normal,
+ origco[y * gridsize + x],
+ origco[y * gridsize + x + 1],
+ origco[(y + 1) * gridsize + x + 1],
+ origco[(y + 1) * gridsize + x],
+ depth, dist_sq);
+ }
+ else {
+ hit |= ray_face_nearest_quad(
+ ray_start, ray_normal,
+ CCG_grid_elem_co(&bvh->gridkey, grid, x, y),
+ CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y),
+ CCG_grid_elem_co(&bvh->gridkey, grid, x + 1, y + 1),
+ CCG_grid_elem_co(&bvh->gridkey, grid, x, y + 1),
+ depth, dist_sq);
+ }
+ }
+ }
+
+ if (origco)
+ origco += gridsize * gridsize;
+ }
+
+ return hit;
+}
+
+bool BKE_pbvh_node_find_nearest_to_ray(
+ PBVH *bvh, PBVHNode *node, float (*origco)[3], bool use_origco,
+ const float ray_start[3], const float ray_normal[3],
+ float *depth, float *dist_sq)
+{
+ bool hit = false;
+
+ if (node->flag & PBVH_FullyHidden)
+ return false;
+
+ switch (bvh->type) {
+ case PBVH_FACES:
+ hit |= pbvh_faces_node_nearest_to_ray(
+ bvh, node, origco,
+ ray_start, ray_normal, depth, dist_sq);
+ break;
+ case PBVH_GRIDS:
+ hit |= pbvh_grids_node_nearest_to_ray(
+ bvh, node, origco,
+ ray_start, ray_normal, depth, dist_sq);
+ break;
+ case PBVH_BMESH:
+ hit = pbvh_bmesh_node_nearest_to_ray(
+ node, ray_start, ray_normal, depth, dist_sq, use_origco);
+ break;
+ }
+
+ return hit;
+}
+
typedef struct {
DMSetMaterial setMaterial;
bool wireframe;
@@ -1756,7 +2035,7 @@ void BKE_pbvh_node_draw(PBVHNode *node, void *data_v)
#endif
if (!(node->flag & PBVH_FullyHidden)) {
- GPU_draw_pbvh_buffers(node->draw_buffers,
+ GPU_pbvh_buffers_draw(node->draw_buffers,
data->setMaterial,
data->wireframe,
data->fast);
@@ -1831,6 +2110,16 @@ static void pbvh_node_check_diffuse_changed(PBVH *bvh, PBVHNode *node)
node->flag |= PBVH_UpdateDrawBuffers;
}
+static void pbvh_node_check_mask_changed(PBVH *bvh, PBVHNode *node)
+{
+ if (!node->draw_buffers) {
+ return;
+ }
+ if (GPU_pbvh_buffers_mask_changed(node->draw_buffers, bvh->show_mask)) {
+ node->flag |= PBVH_UpdateDrawBuffers;
+ }
+}
+
void BKE_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*fnors)[3],
DMSetMaterial setMaterial, bool wireframe, bool fast)
{
@@ -1838,8 +2127,10 @@ void BKE_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*fnors)[3],
PBVHNode **nodes;
int totnode;
- for (int a = 0; a < bvh->totnode; a++)
+ for (int a = 0; a < bvh->totnode; a++) {
pbvh_node_check_diffuse_changed(bvh, &bvh->nodes[a]);
+ pbvh_node_check_mask_changed(bvh, &bvh->nodes[a]);
+ }
BKE_pbvh_search_gather(bvh, update_search_cb, SET_INT_IN_POINTER(PBVH_UpdateNormals | PBVH_UpdateDrawBuffers),
&nodes, &totnode);
@@ -1858,7 +2149,7 @@ void BKE_pbvh_draw(PBVH *bvh, float (*planes)[4], float (*fnors)[3],
}
if (G.debug_value == 14)
- pbvh_draw_BB(bvh);
+ BKE_pbvh_draw_BB(bvh);
}
void BKE_pbvh_grids_update(PBVH *bvh, CCGElem **grids, void **gridfaces,
@@ -2089,3 +2380,8 @@ void pbvh_show_diffuse_color_set(PBVH *bvh, bool show_diffuse_color)
bvh->show_diffuse_color = !has_mask || show_diffuse_color;
}
+
+void pbvh_show_mask_set(PBVH *bvh, bool show_mask)
+{
+ bvh->show_mask = show_mask;
+}
diff --git a/source/blender/blenkernel/intern/pbvh_bmesh.c b/source/blender/blenkernel/intern/pbvh_bmesh.c
index a821578db1a..e32a5d0681e 100644
--- a/source/blender/blenkernel/intern/pbvh_bmesh.c
+++ b/source/blender/blenkernel/intern/pbvh_bmesh.c
@@ -255,7 +255,7 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde
const int cd_face_node_offset = bvh->cd_face_node_offset;
PBVHNode *n = &bvh->nodes[node_index];
- if (BLI_gset_size(n->bm_faces) <= bvh->leaf_limit) {
+ if (BLI_gset_len(n->bm_faces) <= bvh->leaf_limit) {
/* Node limit not exceeded */
pbvh_bmesh_node_finalize(bvh, node_index, cd_vert_node_offset, cd_face_node_offset);
return;
@@ -289,8 +289,8 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde
*c2 = &bvh->nodes[children + 1];
c1->flag |= PBVH_Leaf;
c2->flag |= PBVH_Leaf;
- c1->bm_faces = BLI_gset_ptr_new_ex("bm_faces", BLI_gset_size(n->bm_faces) / 2);
- c2->bm_faces = BLI_gset_ptr_new_ex("bm_faces", BLI_gset_size(n->bm_faces) / 2);
+ c1->bm_faces = BLI_gset_ptr_new_ex("bm_faces", BLI_gset_len(n->bm_faces) / 2);
+ c2->bm_faces = BLI_gset_ptr_new_ex("bm_faces", BLI_gset_len(n->bm_faces) / 2);
/* Partition the parent node's faces between the two children */
GSET_ITER (gs_iter, n->bm_faces) {
@@ -305,11 +305,11 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde
/* Enforce at least one primitive in each node */
GSet *empty = NULL, *other;
- if (BLI_gset_size(c1->bm_faces) == 0) {
+ if (BLI_gset_len(c1->bm_faces) == 0) {
empty = c1->bm_faces;
other = c2->bm_faces;
}
- else if (BLI_gset_size(c2->bm_faces) == 0) {
+ else if (BLI_gset_len(c2->bm_faces) == 0) {
empty = c2->bm_faces;
other = c1->bm_faces;
}
@@ -352,7 +352,7 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde
n->layer_disp = NULL;
if (n->draw_buffers) {
- GPU_free_pbvh_buffers(n->draw_buffers);
+ GPU_pbvh_buffers_free(n->draw_buffers);
n->draw_buffers = NULL;
}
n->flag &= ~PBVH_Leaf;
@@ -375,7 +375,7 @@ static void pbvh_bmesh_node_split(PBVH *bvh, const BBC *bbc_array, int node_inde
static bool pbvh_bmesh_node_limit_ensure(PBVH *bvh, int node_index)
{
GSet *bm_faces = bvh->nodes[node_index].bm_faces;
- const int bm_faces_size = BLI_gset_size(bm_faces);
+ const int bm_faces_size = BLI_gset_len(bm_faces);
if (bm_faces_size <= bvh->leaf_limit) {
/* Node limit not exceeded */
return false;
@@ -555,9 +555,9 @@ static int pbvh_bmesh_node_vert_use_count(PBVH *bvh, PBVHNode *node, BMVert *v)
#endif
#define pbvh_bmesh_node_vert_use_count_is_equal(bvh, node, v, n) \
- (pbvh_bmesh_node_vert_use_count_ex(bvh, node, v, (n) + 1) == n)
+ (pbvh_bmesh_node_vert_use_count_at_most(bvh, node, v, (n) + 1) == n)
-static int pbvh_bmesh_node_vert_use_count_ex(PBVH *bvh, PBVHNode *node, BMVert *v, const int count_max)
+static int pbvh_bmesh_node_vert_use_count_at_most(PBVH *bvh, PBVHNode *node, BMVert *v, const int count_max)
{
int count = 0;
BMFace *f;
@@ -718,20 +718,24 @@ static void pbvh_bmesh_node_drop_orig(PBVHNode *node)
/****************************** EdgeQueue *****************************/
-typedef struct {
+struct EdgeQueue;
+
+typedef struct EdgeQueue {
Heap *heap;
const float *center;
+ float center_proj[3]; /* for when we use projected coords. */
float radius_squared;
float limit_len_squared;
#ifdef USE_EDGEQUEUE_EVEN_SUBDIV
float limit_len;
#endif
-#ifdef USE_EDGEQUEUE_FRONTFACE
+ bool (*edge_queue_tri_in_range)(const struct EdgeQueue *q, BMFace *f);
+
const float *view_normal;
+#ifdef USE_EDGEQUEUE_FRONTFACE
unsigned int use_view_normal : 1;
#endif
-
} EdgeQueue;
typedef struct {
@@ -785,7 +789,6 @@ static bool edge_queue_tri_in_sphere(const EdgeQueue *q, BMFace *f)
float c[3];
/* Get closest point in triangle to sphere center */
- // BM_iter_as_array(NULL, BM_VERTS_OF_FACE, f, (void **)v_tri, 3);
BM_face_as_array_vert_tri(f, v_tri);
closest_on_tri_to_point_v3(c, q->center, v_tri[0]->co, v_tri[1]->co, v_tri[2]->co);
@@ -794,6 +797,25 @@ static bool edge_queue_tri_in_sphere(const EdgeQueue *q, BMFace *f)
return len_squared_v3v3(q->center, c) <= q->radius_squared;
}
+static bool edge_queue_tri_in_circle(const EdgeQueue *q, BMFace *f)
+{
+ BMVert *v_tri[3];
+ float c[3];
+ float tri_proj[3][3];
+
+ /* Get closest point in triangle to sphere center */
+ BM_face_as_array_vert_tri(f, v_tri);
+
+ project_plane_normalized_v3_v3v3(tri_proj[0], v_tri[0]->co, q->view_normal);
+ project_plane_normalized_v3_v3v3(tri_proj[1], v_tri[1]->co, q->view_normal);
+ project_plane_normalized_v3_v3v3(tri_proj[2], v_tri[2]->co, q->view_normal);
+
+ closest_on_tri_to_point_v3(c, q->center_proj, tri_proj[0], tri_proj[1], tri_proj[2]);
+
+ /* Check if triangle intersects the sphere */
+ return len_squared_v3v3(q->center_proj, c) <= q->radius_squared;
+}
+
/* Return true if the vertex mask is less than 1.0, false otherwise */
static bool check_mask(EdgeQueueContext *eq_ctx, BMVert *v)
{
@@ -929,7 +951,7 @@ static void long_edge_queue_face_add(
}
#endif
- if (edge_queue_tri_in_sphere(eq_ctx->q, f)) {
+ if (eq_ctx->q->edge_queue_tri_in_range(eq_ctx->q, f)) {
/* Check each edge of the face */
BMLoop *l_first = BM_FACE_FIRST_LOOP(f);
BMLoop *l_iter = l_first;
@@ -960,7 +982,7 @@ static void short_edge_queue_face_add(
}
#endif
- if (edge_queue_tri_in_sphere(eq_ctx->q, f)) {
+ if (eq_ctx->q->edge_queue_tri_in_range(eq_ctx->q, f)) {
BMLoop *l_iter;
BMLoop *l_first;
@@ -984,7 +1006,7 @@ static void short_edge_queue_face_add(
static void long_edge_queue_create(
EdgeQueueContext *eq_ctx,
PBVH *bvh, const float center[3], const float view_normal[3],
- float radius)
+ float radius, const bool use_frontface, const bool use_projected)
{
eq_ctx->q->heap = BLI_heap_new();
eq_ctx->q->center = center;
@@ -994,13 +1016,22 @@ static void long_edge_queue_create(
eq_ctx->q->limit_len = bvh->bm_max_edge_len;
#endif
-#ifdef USE_EDGEQUEUE_FRONTFACE
eq_ctx->q->view_normal = view_normal;
- eq_ctx->q->use_view_normal = (view_normal != NULL);
+
+#ifdef USE_EDGEQUEUE_FRONTFACE
+ eq_ctx->q->use_view_normal = use_frontface;
#else
- UNUSED_VARS(view_normal);
+ UNUSED_VARS(use_frontface);
#endif
+ if (use_projected) {
+ eq_ctx->q->edge_queue_tri_in_range = edge_queue_tri_in_circle;
+ project_plane_normalized_v3_v3v3(eq_ctx->q->center_proj, center, view_normal);
+ }
+ else {
+ eq_ctx->q->edge_queue_tri_in_range = edge_queue_tri_in_sphere;
+ }
+
#ifdef USE_EDGEQUEUE_TAG_VERIFY
pbvh_bmesh_edge_tag_verify(bvh);
#endif
@@ -1037,7 +1068,7 @@ static void long_edge_queue_create(
static void short_edge_queue_create(
EdgeQueueContext *eq_ctx,
PBVH *bvh, const float center[3], const float view_normal[3],
- float radius)
+ float radius, const bool use_frontface, const bool use_projected)
{
eq_ctx->q->heap = BLI_heap_new();
eq_ctx->q->center = center;
@@ -1047,13 +1078,22 @@ static void short_edge_queue_create(
eq_ctx->q->limit_len = bvh->bm_min_edge_len;
#endif
-#ifdef USE_EDGEQUEUE_FRONTFACE
eq_ctx->q->view_normal = view_normal;
- eq_ctx->q->use_view_normal = (view_normal != NULL);
+
+#ifdef USE_EDGEQUEUE_FRONTFACE
+ eq_ctx->q->use_view_normal = use_frontface;
#else
- UNUSED_VARS(view_normal);
+ UNUSED_VARS(use_frontface);
#endif
+ if (use_projected) {
+ eq_ctx->q->edge_queue_tri_in_range = edge_queue_tri_in_circle;
+ project_plane_normalized_v3_v3v3(eq_ctx->q->center_proj, center, view_normal);
+ }
+ else {
+ eq_ctx->q->edge_queue_tri_in_range = edge_queue_tri_in_sphere;
+ }
+
for (int n = 0; n < bvh->totnode; n++) {
PBVHNode *node = &bvh->nodes[n];
@@ -1132,7 +1172,7 @@ static void pbvh_bmesh_split_edge(
*
* - faces wind anticlockwise in this example.
* - original edge is ``(v1, v2)``
- * - oroginal face is ``(v1, v2, v3)``
+ * - original face is ``(v1, v2, v3)``
*
* <pre>
* + v3(v_opp)
@@ -1198,7 +1238,7 @@ static bool pbvh_bmesh_subdivide_long_edges(
bool any_subdivided = false;
while (!BLI_heap_is_empty(eq_ctx->q->heap)) {
- BMVert **pair = BLI_heap_popmin(eq_ctx->q->heap);
+ BMVert **pair = BLI_heap_pop_min(eq_ctx->q->heap);
BMVert *v1 = pair[0], *v2 = pair[1];
BMEdge *e;
@@ -1286,7 +1326,7 @@ static void pbvh_bmesh_collapse_edge(
/* Note: this could be done with BM_vert_splice(), but that
* requires handling other issues like duplicate edges, so doesn't
* really buy anything. */
- BLI_buffer_empty(deleted_faces);
+ BLI_buffer_clear(deleted_faces);
BMLoop *l;
@@ -1415,7 +1455,7 @@ static bool pbvh_bmesh_collapse_short_edges(
GHash *deleted_verts = BLI_ghash_ptr_new("deleted_verts");
while (!BLI_heap_is_empty(eq_ctx->q->heap)) {
- BMVert **pair = BLI_heap_popmin(eq_ctx->q->heap);
+ BMVert **pair = BLI_heap_pop_min(eq_ctx->q->heap);
BMVert *v1 = pair[0], *v2 = pair[1];
BLI_mempool_free(eq_ctx->pool, pair);
pair = NULL;
@@ -1466,7 +1506,7 @@ static bool pbvh_bmesh_collapse_short_edges(
bool pbvh_bmesh_node_raycast(
PBVHNode *node, const float ray_start[3],
- const float ray_normal[3], float *dist,
+ const float ray_normal[3], float *depth,
bool use_original)
{
bool hit = false;
@@ -1479,7 +1519,7 @@ bool pbvh_bmesh_node_raycast(
node->bm_orco[t[0]],
node->bm_orco[t[1]],
node->bm_orco[t[2]],
- dist);
+ depth);
}
}
else {
@@ -1498,7 +1538,7 @@ bool pbvh_bmesh_node_raycast(
v_tri[0]->co,
v_tri[1]->co,
v_tri[2]->co,
- dist);
+ depth);
}
}
}
@@ -1509,7 +1549,7 @@ bool pbvh_bmesh_node_raycast(
bool BKE_pbvh_bmesh_node_raycast_detail(
PBVHNode *node,
const float ray_start[3], const float ray_normal[3],
- float *dist, float *r_detail)
+ float *depth, float *r_detail)
{
if (node->flag & PBVH_FullyHidden)
return 0;
@@ -1531,7 +1571,7 @@ bool BKE_pbvh_bmesh_node_raycast_detail(
v_tri[0]->co,
v_tri[1]->co,
v_tri[2]->co,
- dist);
+ depth);
if (hit_local) {
f_hit = f;
@@ -1554,6 +1594,47 @@ bool BKE_pbvh_bmesh_node_raycast_detail(
return hit;
}
+bool pbvh_bmesh_node_nearest_to_ray(
+ PBVHNode *node, const float ray_start[3],
+ const float ray_normal[3], float *depth, float *dist_sq,
+ bool use_original)
+{
+ bool hit = false;
+
+ if (use_original && node->bm_tot_ortri) {
+ for (int i = 0; i < node->bm_tot_ortri; i++) {
+ const int *t = node->bm_ortri[i];
+ hit |= ray_face_nearest_tri(
+ ray_start, ray_normal,
+ node->bm_orco[t[0]],
+ node->bm_orco[t[1]],
+ node->bm_orco[t[2]],
+ depth, dist_sq);
+ }
+ }
+ else {
+ GSetIterator gs_iter;
+
+ GSET_ITER (gs_iter, node->bm_faces) {
+ BMFace *f = BLI_gsetIterator_getKey(&gs_iter);
+
+ BLI_assert(f->len == 3);
+ if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
+ BMVert *v_tri[3];
+
+ BM_face_as_array_vert_tri(f, v_tri);
+ hit |= ray_face_nearest_tri(
+ ray_start, ray_normal,
+ v_tri[0]->co,
+ v_tri[1]->co,
+ v_tri[2]->co,
+ depth, dist_sq);
+ }
+ }
+ }
+
+ return hit;
+}
void pbvh_bmesh_normals_update(PBVHNode **nodes, int totnode)
{
@@ -1854,7 +1935,7 @@ void BKE_pbvh_build_bmesh(
bool BKE_pbvh_bmesh_update_topology(
PBVH *bvh, PBVHTopologyUpdateMode mode,
const float center[3], const float view_normal[3],
- float radius)
+ float radius, const bool use_frontface, const bool use_projected)
{
/* 2 is enough for edge faces - manifold edge */
BLI_buffer_declare_static(BMLoop *, edge_loops, BLI_BUFFER_NOP, 2);
@@ -1877,7 +1958,7 @@ bool BKE_pbvh_bmesh_update_topology(
cd_vert_mask_offset, cd_vert_node_offset, cd_face_node_offset,
};
- short_edge_queue_create(&eq_ctx, bvh, center, view_normal, radius);
+ short_edge_queue_create(&eq_ctx, bvh, center, view_normal, radius, use_frontface, use_projected);
modified |= pbvh_bmesh_collapse_short_edges(
&eq_ctx, bvh, &deleted_faces);
BLI_heap_free(q.heap, NULL);
@@ -1892,7 +1973,7 @@ bool BKE_pbvh_bmesh_update_topology(
cd_vert_mask_offset, cd_vert_node_offset, cd_face_node_offset,
};
- long_edge_queue_create(&eq_ctx, bvh, center, view_normal, radius);
+ long_edge_queue_create(&eq_ctx, bvh, center, view_normal, radius, use_frontface, use_projected);
modified |= pbvh_bmesh_subdivide_long_edges(
&eq_ctx, bvh, &edge_loops);
BLI_heap_free(q.heap, NULL);
@@ -1930,10 +2011,10 @@ void BKE_pbvh_bmesh_node_save_orig(PBVHNode *node)
if (node->bm_orco)
return;
- const int totvert = BLI_gset_size(node->bm_unique_verts) +
- BLI_gset_size(node->bm_other_verts);
+ const int totvert = BLI_gset_len(node->bm_unique_verts) +
+ BLI_gset_len(node->bm_other_verts);
- const int tottri = BLI_gset_size(node->bm_faces);
+ const int tottri = BLI_gset_len(node->bm_faces);
node->bm_orco = MEM_mallocN(sizeof(*node->bm_orco) * totvert, __func__);
node->bm_ortri = MEM_mallocN(sizeof(*node->bm_ortri) * tottri, __func__);
@@ -2108,12 +2189,12 @@ static void pbvh_bmesh_verify(PBVH *bvh)
int totface = 0, totvert = 0;
for (int i = 0; i < bvh->totnode; i++) {
PBVHNode *n = &bvh->nodes[i];
- totface += n->bm_faces ? BLI_gset_size(n->bm_faces) : 0;
- totvert += n->bm_unique_verts ? BLI_gset_size(n->bm_unique_verts) : 0;
+ totface += n->bm_faces ? BLI_gset_len(n->bm_faces) : 0;
+ totvert += n->bm_unique_verts ? BLI_gset_len(n->bm_unique_verts) : 0;
}
- BLI_assert(totface == BLI_gset_size(faces_all));
- BLI_assert(totvert == BLI_gset_size(verts_all));
+ BLI_assert(totface == BLI_gset_len(faces_all));
+ BLI_assert(totvert == BLI_gset_len(verts_all));
}
{
diff --git a/source/blender/blenkernel/intern/pbvh_intern.h b/source/blender/blenkernel/intern/pbvh_intern.h
index 19d3b31bd31..afd539b2273 100644
--- a/source/blender/blenkernel/intern/pbvh_intern.h
+++ b/source/blender/blenkernel/intern/pbvh_intern.h
@@ -149,6 +149,8 @@ struct PBVH {
* objects in sculpt mode with different sizes at the same time, so now storing that common gpu buffer
* in an opaque pointer per pbvh. See T47637. */
struct GridCommonGPUBuffer *grid_common_gpu_buffer;
+ /* The ccgdm is required for CD_ORIGINDEX lookup in vertex paint + multires */
+ struct CCGDerivedMesh *ccgdm;
/* Only used during BVH build and update,
* don't need to remain valid after */
@@ -162,6 +164,7 @@ struct PBVH {
bool deformed;
bool show_diffuse_color;
+ bool show_mask;
/* Dynamic topology */
BMesh *bm;
@@ -183,11 +186,21 @@ void pbvh_grow_nodes(PBVH *bvh, int totnode);
bool ray_face_intersection_quad(
const float ray_start[3], const float ray_normal[3],
const float *t0, const float *t1, const float *t2, const float *t3,
- float *r_dist);
+ float *depth);
bool ray_face_intersection_tri(
const float ray_start[3], const float ray_normal[3],
const float *t0, const float *t1, const float *t2,
- float *r_dist);
+ float *depth);
+
+bool ray_face_nearest_quad(
+ const float ray_start[3], const float ray_normal[3],
+ const float *t0, const float *t1, const float *t2, const float *t3,
+ float *r_depth, float *r_dist_sq);
+bool ray_face_nearest_tri(
+ const float ray_start[3], const float ray_normal[3],
+ const float *t0, const float *t1, const float *t2,
+ float *r_depth, float *r_dist_sq);
+
void pbvh_update_BB_redraw(PBVH *bvh, PBVHNode **nodes, int totnode, int flag);
/* pbvh_bmesh.c */
@@ -195,6 +208,10 @@ bool pbvh_bmesh_node_raycast(
PBVHNode *node, const float ray_start[3],
const float ray_normal[3], float *dist,
bool use_original);
+bool pbvh_bmesh_node_nearest_to_ray(
+ PBVHNode *node, const float ray_start[3],
+ const float ray_normal[3], float *depth, float *dist_sq,
+ bool use_original);
void pbvh_bmesh_normals_update(PBVHNode **nodes, int totnode);
diff --git a/source/blender/blenkernel/intern/pointcache.c b/source/blender/blenkernel/intern/pointcache.c
index 30eb8dcb287..89885bdca26 100644
--- a/source/blender/blenkernel/intern/pointcache.c
+++ b/source/blender/blenkernel/intern/pointcache.c
@@ -40,7 +40,7 @@
#include "DNA_dynamicpaint_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_particle_types.h"
#include "DNA_rigidbody_types.h"
#include "DNA_scene_types.h"
@@ -440,9 +440,9 @@ static void ptcache_particle_extra_write(void *psys_v, PTCacheMem *pm, int UNUSE
PTCacheExtra *extra = NULL;
if (psys->part->phystype == PART_PHYS_FLUID &&
- psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS &&
- psys->tot_fluidsprings && psys->fluid_springs) {
-
+ psys->part->fluid && psys->part->fluid->flag & SPH_VISCOELASTIC_SPRINGS &&
+ psys->tot_fluidsprings && psys->fluid_springs)
+ {
extra = MEM_callocN(sizeof(PTCacheExtra), "Point cache: fluid extra data");
extra->type = BPHYS_EXTRA_FLUID_SPRINGS;
@@ -789,8 +789,9 @@ static int ptcache_smoke_read(PTCacheFile *pf, void *smoke_v)
/* check if resolution has changed */
if (sds->res[0] != ch_res[0] ||
- sds->res[1] != ch_res[1] ||
- sds->res[2] != ch_res[2]) {
+ sds->res[1] != ch_res[1] ||
+ sds->res[2] != ch_res[2])
+ {
if (sds->flags & MOD_SMOKE_ADAPTIVE_DOMAIN)
reallocate = 1;
else
@@ -972,20 +973,20 @@ static int ptcache_smoke_openvdb_write(struct OpenVDBWriter *writer, void *smoke
smoke_turbulence_export(sds->wt, &dens, &react, &flame, &fuel, &r, &g, &b, &tcu, &tcv, &tcw);
- wt_density_grid = OpenVDB_export_grid_fl(writer, "density", dens, sds->res_wt, sds->fluidmat_wt, NULL);
+ wt_density_grid = OpenVDB_export_grid_fl(writer, "density", dens, sds->res_wt, sds->fluidmat_wt, sds->clipping, NULL);
clip_grid = wt_density_grid;
if (fluid_fields & SM_ACTIVE_FIRE) {
- OpenVDB_export_grid_fl(writer, "flame", flame, sds->res_wt, sds->fluidmat_wt, wt_density_grid);
- OpenVDB_export_grid_fl(writer, "fuel", fuel, sds->res_wt, sds->fluidmat_wt, wt_density_grid);
- OpenVDB_export_grid_fl(writer, "react", react, sds->res_wt, sds->fluidmat_wt, wt_density_grid);
+ OpenVDB_export_grid_fl(writer, "flame", flame, sds->res_wt, sds->fluidmat_wt, sds->clipping, wt_density_grid);
+ OpenVDB_export_grid_fl(writer, "fuel", fuel, sds->res_wt, sds->fluidmat_wt, sds->clipping, wt_density_grid);
+ OpenVDB_export_grid_fl(writer, "react", react, sds->res_wt, sds->fluidmat_wt, sds->clipping, wt_density_grid);
}
if (fluid_fields & SM_ACTIVE_COLORS) {
- OpenVDB_export_grid_vec(writer, "color", r, g, b, sds->res_wt, sds->fluidmat_wt, VEC_INVARIANT, true, wt_density_grid);
+ OpenVDB_export_grid_vec(writer, "color", r, g, b, sds->res_wt, sds->fluidmat_wt, VEC_INVARIANT, true, sds->clipping, wt_density_grid);
}
- OpenVDB_export_grid_vec(writer, "texture coordinates", tcu, tcv, tcw, sds->res, sds->fluidmat, VEC_INVARIANT, false, wt_density_grid);
+ OpenVDB_export_grid_vec(writer, "texture coordinates", tcu, tcv, tcw, sds->res, sds->fluidmat, VEC_INVARIANT, false, sds->clipping, wt_density_grid);
}
if (sds->fluid) {
@@ -999,33 +1000,33 @@ static int ptcache_smoke_openvdb_write(struct OpenVDBWriter *writer, void *smoke
OpenVDBWriter_add_meta_fl(writer, "blender/smoke/dx", dx);
OpenVDBWriter_add_meta_fl(writer, "blender/smoke/dt", dt);
- const char *name = (!sds->wt) ? "density" : "density low";
- density_grid = OpenVDB_export_grid_fl(writer, name, dens, sds->res, sds->fluidmat, NULL);
+ const char *name = (!sds->wt) ? "density" : "density_low";
+ density_grid = OpenVDB_export_grid_fl(writer, name, dens, sds->res, sds->fluidmat, sds->clipping, NULL);
clip_grid = sds->wt ? clip_grid : density_grid;
- OpenVDB_export_grid_fl(writer, "shadow", sds->shadow, sds->res, sds->fluidmat, NULL);
+ OpenVDB_export_grid_fl(writer, "shadow", sds->shadow, sds->res, sds->fluidmat, sds->clipping, NULL);
if (fluid_fields & SM_ACTIVE_HEAT) {
- OpenVDB_export_grid_fl(writer, "heat", heat, sds->res, sds->fluidmat, clip_grid);
- OpenVDB_export_grid_fl(writer, "heat old", heatold, sds->res, sds->fluidmat, clip_grid);
+ OpenVDB_export_grid_fl(writer, "heat", heat, sds->res, sds->fluidmat, sds->clipping, clip_grid);
+ OpenVDB_export_grid_fl(writer, "heat_old", heatold, sds->res, sds->fluidmat, sds->clipping, clip_grid);
}
if (fluid_fields & SM_ACTIVE_FIRE) {
- name = (!sds->wt) ? "flame" : "flame low";
- OpenVDB_export_grid_fl(writer, name, flame, sds->res, sds->fluidmat, density_grid);
- name = (!sds->wt) ? "fuel" : "fuel low";
- OpenVDB_export_grid_fl(writer, name, fuel, sds->res, sds->fluidmat, density_grid);
- name = (!sds->wt) ? "react" : "react low";
- OpenVDB_export_grid_fl(writer, name, react, sds->res, sds->fluidmat, density_grid);
+ name = (!sds->wt) ? "flame" : "flame_low";
+ OpenVDB_export_grid_fl(writer, name, flame, sds->res, sds->fluidmat, sds->clipping, density_grid);
+ name = (!sds->wt) ? "fuel" : "fuel_low";
+ OpenVDB_export_grid_fl(writer, name, fuel, sds->res, sds->fluidmat, sds->clipping, density_grid);
+ name = (!sds->wt) ? "react" : "react_low";
+ OpenVDB_export_grid_fl(writer, name, react, sds->res, sds->fluidmat, sds->clipping, density_grid);
}
if (fluid_fields & SM_ACTIVE_COLORS) {
- name = (!sds->wt) ? "color" : "color low";
- OpenVDB_export_grid_vec(writer, name, r, g, b, sds->res, sds->fluidmat, VEC_INVARIANT, true, density_grid);
+ name = (!sds->wt) ? "color" : "color_low";
+ OpenVDB_export_grid_vec(writer, name, r, g, b, sds->res, sds->fluidmat, VEC_INVARIANT, true, sds->clipping, density_grid);
}
- OpenVDB_export_grid_vec(writer, "velocity", vx, vy, vz, sds->res, sds->fluidmat, VEC_CONTRAVARIANT_RELATIVE, false, clip_grid);
- OpenVDB_export_grid_ch(writer, "obstacles", obstacles, sds->res, sds->fluidmat, NULL);
+ OpenVDB_export_grid_vec(writer, "velocity", vx, vy, vz, sds->res, sds->fluidmat, VEC_CONTRAVARIANT_RELATIVE, false, sds->clipping, clip_grid);
+ OpenVDB_export_grid_ch(writer, "obstacles", obstacles, sds->res, sds->fluidmat, sds->clipping, NULL);
}
return 1;
@@ -1104,25 +1105,25 @@ static int ptcache_smoke_openvdb_read(struct OpenVDBReader *reader, void *smoke_
OpenVDB_import_grid_fl(reader, "shadow", &sds->shadow, sds->res);
- const char *name = (!sds->wt) ? "density" : "density low";
+ const char *name = (!sds->wt) ? "density" : "density_low";
OpenVDB_import_grid_fl(reader, name, &dens, sds->res);
if (cache_fields & SM_ACTIVE_HEAT) {
OpenVDB_import_grid_fl(reader, "heat", &heat, sds->res);
- OpenVDB_import_grid_fl(reader, "heat old", &heatold, sds->res);
+ OpenVDB_import_grid_fl(reader, "heat_old", &heatold, sds->res);
}
if (cache_fields & SM_ACTIVE_FIRE) {
- name = (!sds->wt) ? "flame" : "flame low";
+ name = (!sds->wt) ? "flame" : "flame_low";
OpenVDB_import_grid_fl(reader, name, &flame, sds->res);
- name = (!sds->wt) ? "fuel" : "fuel low";
+ name = (!sds->wt) ? "fuel" : "fuel_low";
OpenVDB_import_grid_fl(reader, name, &fuel, sds->res);
- name = (!sds->wt) ? "react" : "react low";
+ name = (!sds->wt) ? "react" : "react_low";
OpenVDB_import_grid_fl(reader, name, &react, sds->res);
}
if (cache_fields & SM_ACTIVE_COLORS) {
- name = (!sds->wt) ? "color" : "color low";
+ name = (!sds->wt) ? "color" : "color_low";
OpenVDB_import_grid_vec(reader, name, &r, &g, &b, sds->res);
}
@@ -2197,8 +2198,8 @@ static void ptcache_data_copy(void *from[], void *to[])
{
int i;
for (i=0; i<BPHYS_TOT_DATA; i++) {
- /* note, durian file 03.4b_comp crashes if to[i] is not tested
- * its NULL, not sure if this should be fixed elsewhere but for now its needed */
+ /* note, durian file 03.4b_comp crashes if to[i] is not tested
+ * its NULL, not sure if this should be fixed elsewhere but for now its needed */
if (from[i] && to[i])
memcpy(to[i], from[i], ptcache_data_size[i]);
}
@@ -3449,7 +3450,7 @@ void BKE_ptcache_free_list(ListBase *ptcaches)
}
}
-static PointCache *ptcache_copy(PointCache *cache, bool copy_data)
+static PointCache *ptcache_copy(PointCache *cache, const bool copy_data)
{
PointCache *ncache;
@@ -3492,14 +3493,15 @@ static PointCache *ptcache_copy(PointCache *cache, bool copy_data)
}
/* returns first point cache */
-PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcaches_old, bool copy_data)
+PointCache *BKE_ptcache_copy_list(ListBase *ptcaches_new, const ListBase *ptcaches_old, const int flag)
{
PointCache *cache = ptcaches_old->first;
BLI_listbase_clear(ptcaches_new);
- for (; cache; cache=cache->next)
- BLI_addtail(ptcaches_new, ptcache_copy(cache, copy_data));
+ for (; cache; cache=cache->next) {
+ BLI_addtail(ptcaches_new, ptcache_copy(cache, (flag & LIB_ID_COPY_CACHES) != 0));
+ }
return ptcaches_new->first;
}
@@ -3618,9 +3620,13 @@ void BKE_ptcache_bake(PTCacheBaker *baker)
psys_get_pointcache_start_end(scene, pid->calldata, &cache->startframe, &cache->endframe);
}
- if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) &&
- (render || bake))
- {
+ // XXX workaround for regression inroduced in ee3fadd, needs looking into
+ if (pid->type == PTCACHE_TYPE_RIGIDBODY) {
+ if ((cache->flag & PTCACHE_REDO_NEEDED || (cache->flag & PTCACHE_SIMULATION_VALID)==0) && (render || bake)) {
+ BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
+ }
+ }
+ else if (((cache->flag & PTCACHE_BAKED) == 0) && (render || bake)) {
BKE_ptcache_id_clear(pid, PTCACHE_CLEAR_ALL, 0);
}
diff --git a/source/blender/blenkernel/intern/property.c b/source/blender/blenkernel/intern/property.c
index dc4063b42ed..b163f623d21 100644
--- a/source/blender/blenkernel/intern/property.c
+++ b/source/blender/blenkernel/intern/property.c
@@ -65,7 +65,7 @@ void BKE_bproperty_free_list(ListBase *lb)
}
}
-bProperty *BKE_bproperty_copy(bProperty *prop)
+bProperty *BKE_bproperty_copy(const bProperty *prop)
{
bProperty *propn;
@@ -80,7 +80,7 @@ bProperty *BKE_bproperty_copy(bProperty *prop)
return propn;
}
-void BKE_bproperty_copy_list(ListBase *lbn, ListBase *lbo)
+void BKE_bproperty_copy_list(ListBase *lbn, const ListBase *lbo)
{
bProperty *prop, *propn;
BKE_bproperty_free_list(lbn); /* in case we are copying to an object with props */
diff --git a/source/blender/blenkernel/intern/rigidbody.c b/source/blender/blenkernel/intern/rigidbody.c
index 5353cc26295..b8873cca0fb 100644
--- a/source/blender/blenkernel/intern/rigidbody.c
+++ b/source/blender/blenkernel/intern/rigidbody.c
@@ -50,7 +50,7 @@
#include "DNA_group_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_rigidbody_types.h"
#include "DNA_scene_types.h"
@@ -66,6 +66,8 @@
#include "BKE_rigidbody.h"
#include "BKE_scene.h"
+#include "DEG_depsgraph.h"
+
/* ************************************** */
/* Memory Management */
@@ -184,7 +186,7 @@ void BKE_rigidbody_free_constraint(Object *ob)
* be added to relevant groups later...
*/
-RigidBodyOb *BKE_rigidbody_copy_object(Object *ob)
+RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int UNUSED(flag))
{
RigidBodyOb *rboN = NULL;
@@ -204,7 +206,7 @@ RigidBodyOb *BKE_rigidbody_copy_object(Object *ob)
return rboN;
}
-RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob)
+RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int UNUSED(flag))
{
RigidBodyCon *rbcN = NULL;
@@ -291,8 +293,6 @@ static rbCollisionShape *rigidbody_get_shape_trimesh_from_mesh(Object *ob)
if (dm == NULL)
return NULL;
- DM_ensure_looptri(dm);
-
mvert = dm->getVertArray(dm);
totvert = dm->getNumVerts(dm);
looptri = dm->getLoopTriArray(dm);
@@ -524,8 +524,6 @@ void BKE_rigidbody_calc_volume(Object *ob, float *r_vol)
if (dm == NULL)
return;
- DM_ensure_looptri(dm);
-
mvert = dm->getVertArray(dm);
totvert = dm->getNumVerts(dm);
lt = dm->getLoopTriArray(dm);
@@ -609,8 +607,6 @@ void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3])
if (dm == NULL)
return;
- DM_ensure_looptri(dm);
-
mvert = dm->getVertArray(dm);
totvert = dm->getNumVerts(dm);
looptri = dm->getLoopTriArray(dm);
@@ -704,6 +700,39 @@ static void rigidbody_validate_sim_object(RigidBodyWorld *rbw, Object *ob, bool
/* --------------------- */
+static void rigidbody_constraint_set_limits(RigidBodyCon *rbc, void (*set_limits)(rbConstraint*,int,float,float))
+{
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
+
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
+
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
+
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
+
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
+
+ if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
+ else
+ set_limits(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
+}
+
/**
* Create physics sim representation of constraint given rigid body constraint settings
*
@@ -822,40 +851,13 @@ static void rigidbody_validate_sim_constraint(RigidBodyWorld *rbw, Object *ob, b
RB_constraint_set_damping_6dof_spring(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->spring_damping_ang_z);
RB_constraint_set_equilibrium_6dof_spring(rbc->physics_constraint);
- /* fall-through */
- case RBC_TYPE_6DOF:
- if (rbc->type == RBC_TYPE_6DOF) /* a litte awkward but avoids duplicate code for limits */
- rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
-
- if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_X)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, rbc->limit_lin_x_lower, rbc->limit_lin_x_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_X, 0.0f, -1.0f);
-
- if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Y)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, rbc->limit_lin_y_lower, rbc->limit_lin_y_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Y, 0.0f, -1.0f);
-
- if (rbc->flag & RBC_FLAG_USE_LIMIT_LIN_Z)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, rbc->limit_lin_z_lower, rbc->limit_lin_z_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_LIN_Z, 0.0f, -1.0f);
-
- if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_X)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, rbc->limit_ang_x_lower, rbc->limit_ang_x_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_X, 0.0f, -1.0f);
- if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Y)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, rbc->limit_ang_y_lower, rbc->limit_ang_y_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Y, 0.0f, -1.0f);
+ rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof_spring);
+ break;
+ case RBC_TYPE_6DOF:
+ rbc->physics_constraint = RB_constraint_new_6dof(loc, rot, rb1, rb2);
- if (rbc->flag & RBC_FLAG_USE_LIMIT_ANG_Z)
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, rbc->limit_ang_z_lower, rbc->limit_ang_z_upper);
- else
- RB_constraint_set_limits_6dof(rbc->physics_constraint, RB_LIMIT_ANG_Z, 0.0f, -1.0f);
+ rigidbody_constraint_set_limits(rbc, RB_constraint_set_limits_6dof);
break;
case RBC_TYPE_MOTOR:
rbc->physics_constraint = RB_constraint_new_motor(loc, rot, rb1, rb2);
@@ -945,24 +947,26 @@ RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene)
return rbw;
}
-RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw)
+RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag)
{
- RigidBodyWorld *rbwn = MEM_dupallocN(rbw);
+ RigidBodyWorld *rbw_copy = MEM_dupallocN(rbw);
- if (rbw->effector_weights)
- rbwn->effector_weights = MEM_dupallocN(rbw->effector_weights);
- if (rbwn->group)
- id_us_plus(&rbwn->group->id);
- if (rbwn->constraints)
- id_us_plus(&rbwn->constraints->id);
+ if (rbw->effector_weights) {
+ rbw_copy->effector_weights = MEM_dupallocN(rbw->effector_weights);
+ }
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)rbw_copy->group);
+ id_us_plus((ID *)rbw_copy->constraints);
+ }
- rbwn->pointcache = BKE_ptcache_copy_list(&rbwn->ptcaches, &rbw->ptcaches, false);
+ /* XXX Never copy caches here? */
+ rbw_copy->pointcache = BKE_ptcache_copy_list(&rbw_copy->ptcaches, &rbw->ptcaches, flag & ~LIB_ID_COPY_CACHES);
- rbwn->objects = NULL;
- rbwn->physics_world = NULL;
- rbwn->numbodies = 0;
+ rbw_copy->objects = NULL;
+ rbw_copy->physics_world = NULL;
+ rbw_copy->numbodies = 0;
- return rbwn;
+ return rbw_copy;
}
void BKE_rigidbody_world_groups_relink(RigidBodyWorld *rbw)
@@ -1486,24 +1490,60 @@ void BKE_rigidbody_sync_transforms(RigidBodyWorld *rbw, Object *ob, float ctime)
void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], float quat[4], float rotAxis[3], float rotAngle)
{
RigidBodyOb *rbo = ob->rigidbody_object;
+ bool correct_delta = !(rbo->flag & RBO_FLAG_KINEMATIC || rbo->type == RBO_TYPE_PASSIVE);
/* return rigid body and object to their initial states */
copy_v3_v3(rbo->pos, ob->loc);
copy_v3_v3(ob->loc, loc);
+ if (correct_delta) {
+ add_v3_v3(rbo->pos, ob->dloc);
+ }
+
if (ob->rotmode > 0) {
- eulO_to_quat(rbo->orn, ob->rot, ob->rotmode);
+ float qt[4];
+ eulO_to_quat(qt, ob->rot, ob->rotmode);
+
+ if (correct_delta) {
+ float dquat[4];
+ eulO_to_quat(dquat, ob->drot, ob->rotmode);
+
+ mul_qt_qtqt(rbo->orn, dquat, qt);
+ }
+ else {
+ copy_qt_qt(rbo->orn, qt);
+ }
+
copy_v3_v3(ob->rot, rot);
}
else if (ob->rotmode == ROT_MODE_AXISANGLE) {
- axis_angle_to_quat(rbo->orn, ob->rotAxis, ob->rotAngle);
+ float qt[4];
+ axis_angle_to_quat(qt, ob->rotAxis, ob->rotAngle);
+
+ if (correct_delta) {
+ float dquat[4];
+ axis_angle_to_quat(dquat, ob->drotAxis, ob->drotAngle);
+
+ mul_qt_qtqt(rbo->orn, dquat, qt);
+ }
+ else {
+ copy_qt_qt(rbo->orn, qt);
+ }
+
copy_v3_v3(ob->rotAxis, rotAxis);
ob->rotAngle = rotAngle;
}
else {
- copy_qt_qt(rbo->orn, ob->quat);
+ if (correct_delta) {
+ mul_qt_qtqt(rbo->orn, ob->dquat, ob->quat);
+ }
+ else {
+ copy_qt_qt(rbo->orn, ob->quat);
+ }
+
copy_qt_qt(ob->quat, quat);
}
+
if (rbo->physics_object) {
/* allow passive objects to return to original transform */
if (rbo->type == RBO_TYPE_PASSIVE)
@@ -1515,8 +1555,9 @@ void BKE_rigidbody_aftertrans_update(Object *ob, float loc[3], float rot[3], flo
void BKE_rigidbody_cache_reset(RigidBodyWorld *rbw)
{
- if (rbw)
+ if (rbw) {
rbw->pointcache->flag |= PTCACHE_OUTDATED;
+ }
}
/* ------------------ */
@@ -1582,7 +1623,7 @@ void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
// RB_TODO deal with interpolated, old and baked results
bool can_simulate = (ctime == rbw->ltime + 1) && !(cache->flag & PTCACHE_BAKED);
- if (BKE_ptcache_read(&pid, ctime, can_simulate)) {
+ if (BKE_ptcache_read(&pid, ctime, can_simulate) == PTCACHE_READ_EXACT) {
BKE_ptcache_validate(cache, (int)ctime);
rbw->ltime = ctime;
return;
@@ -1622,13 +1663,13 @@ void BKE_rigidbody_do_simulation(Scene *scene, float ctime)
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
-struct RigidBodyOb *BKE_rigidbody_copy_object(Object *ob) { return NULL; }
-struct RigidBodyCon *BKE_rigidbody_copy_constraint(Object *ob) { return NULL; }
+struct RigidBodyOb *BKE_rigidbody_copy_object(const Object *ob, const int flag) { return NULL; }
+struct RigidBodyCon *BKE_rigidbody_copy_constraint(const Object *ob, const int flag) { return NULL; }
void BKE_rigidbody_validate_sim_world(Scene *scene, RigidBodyWorld *rbw, bool rebuild) {}
void BKE_rigidbody_calc_volume(Object *ob, float *r_vol) { if (r_vol) *r_vol = 0.0f; }
void BKE_rigidbody_calc_center_of_mass(Object *ob, float r_center[3]) { zero_v3(r_center); }
struct RigidBodyWorld *BKE_rigidbody_create_world(Scene *scene) { return NULL; }
-struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw) { return NULL; }
+struct RigidBodyWorld *BKE_rigidbody_world_copy(RigidBodyWorld *rbw, const int flag) { return NULL; }
void BKE_rigidbody_world_groups_relink(struct RigidBodyWorld *rbw) {}
void BKE_rigidbody_world_id_loop(struct RigidBodyWorld *rbw, RigidbodyWorldIDFunc func, void *userdata) {}
struct RigidBodyOb *BKE_rigidbody_create_object(Scene *scene, Object *ob, short type) { return NULL; }
@@ -1656,11 +1697,7 @@ void BKE_rigidbody_rebuild_sim(EvaluationContext *UNUSED(eval_ctx),
Scene *scene)
{
float ctime = BKE_scene_frame_get(scene);
-
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s at %f\n", __func__, ctime);
- }
-
+ DEG_debug_print_eval_time(__func__, scene->id.name, scene, ctime);
/* rebuild sim data (i.e. after resetting to start of timeline) */
if (BKE_scene_check_rigidbody_active(scene)) {
BKE_rigidbody_rebuild_world(scene, ctime);
@@ -1671,11 +1708,7 @@ void BKE_rigidbody_eval_simulation(EvaluationContext *UNUSED(eval_ctx),
Scene *scene)
{
float ctime = BKE_scene_frame_get(scene);
-
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s at %f\n", __func__, ctime);
- }
-
+ DEG_debug_print_eval_time(__func__, scene->id.name, scene, ctime);
/* evaluate rigidbody sim */
if (BKE_scene_check_rigidbody_active(scene)) {
BKE_rigidbody_do_simulation(scene, ctime);
@@ -1688,11 +1721,7 @@ void BKE_rigidbody_object_sync_transforms(EvaluationContext *UNUSED(eval_ctx),
{
RigidBodyWorld *rbw = scene->rigidbody_world;
float ctime = BKE_scene_frame_get(scene);
-
- if (G.debug & G_DEBUG_DEPSGRAPH) {
- printf("%s on %s\n", __func__, ob->id.name);
- }
-
+ DEG_debug_print_eval_time(__func__, ob->id.name, ob, ctime);
/* read values pushed into RBO from sim/cache... */
BKE_rigidbody_sync_transforms(rbw, ob, ctime);
}
diff --git a/source/blender/blenkernel/intern/sca.c b/source/blender/blenkernel/intern/sca.c
index 7920d8b5696..fb81ed4d47f 100644
--- a/source/blender/blenkernel/intern/sca.c
+++ b/source/blender/blenkernel/intern/sca.c
@@ -72,7 +72,7 @@ void free_sensors(ListBase *lb)
}
}
-bSensor *copy_sensor(bSensor *sens)
+bSensor *copy_sensor(bSensor *sens, const int UNUSED(flag))
{
bSensor *sensn;
@@ -87,14 +87,14 @@ bSensor *copy_sensor(bSensor *sens)
return sensn;
}
-void copy_sensors(ListBase *lbn, ListBase *lbo)
+void copy_sensors(ListBase *lbn, const ListBase *lbo, const int flag)
{
bSensor *sens, *sensn;
lbn->first= lbn->last= NULL;
sens= lbo->first;
while (sens) {
- sensn= copy_sensor(sens);
+ sensn= copy_sensor(sens, flag);
BLI_addtail(lbn, sensn);
sens= sens->next;
}
@@ -234,7 +234,7 @@ void free_controllers(ListBase *lb)
}
}
-bController *copy_controller(bController *cont)
+bController *copy_controller(bController *cont, const int UNUSED(flag))
{
bController *contn;
@@ -251,14 +251,14 @@ bController *copy_controller(bController *cont)
return contn;
}
-void copy_controllers(ListBase *lbn, ListBase *lbo)
+void copy_controllers(ListBase *lbn, const ListBase *lbo, const int flag)
{
bController *cont, *contn;
lbn->first= lbn->last= NULL;
cont= lbo->first;
while (cont) {
- contn= copy_controller(cont);
+ contn= copy_controller(cont, flag);
BLI_addtail(lbn, contn);
cont= cont->next;
}
@@ -359,7 +359,7 @@ void free_actuators(ListBase *lb)
}
}
-bActuator *copy_actuator(bActuator *act)
+bActuator *copy_actuator(bActuator *act, const int flag)
{
bActuator *actn;
@@ -374,29 +374,31 @@ bActuator *copy_actuator(bActuator *act)
case ACT_SHAPEACTION:
{
bActionActuator *aa = (bActionActuator *)act->data;
- if (aa->act)
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
id_us_plus((ID *)aa->act);
+ }
break;
}
case ACT_SOUND:
{
bSoundActuator *sa = (bSoundActuator *)act->data;
- if (sa->sound)
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
id_us_plus((ID *)sa->sound);
+ }
break;
}
}
return actn;
}
-void copy_actuators(ListBase *lbn, ListBase *lbo)
+void copy_actuators(ListBase *lbn, const ListBase *lbo, const int flag)
{
bActuator *act, *actn;
lbn->first= lbn->last= NULL;
act= lbo->first;
while (act) {
- actn= copy_actuator(act);
+ actn= copy_actuator(act, flag);
BLI_addtail(lbn, actn);
act= act->next;
}
@@ -783,11 +785,11 @@ void BKE_sca_logic_links_remap(Main *bmain, Object *ob_old, Object *ob_new)
* Handle the copying of logic data into a new object, including internal logic links update.
* External links (links between logic bricks of different objects) must be handled separately.
*/
-void BKE_sca_logic_copy(Object *ob_new, Object *ob)
+void BKE_sca_logic_copy(Object *ob_new, const Object *ob, const int flag)
{
- copy_sensors(&ob_new->sensors, &ob->sensors);
- copy_controllers(&ob_new->controllers, &ob->controllers);
- copy_actuators(&ob_new->actuators, &ob->actuators);
+ copy_sensors(&ob_new->sensors, &ob->sensors, flag);
+ copy_controllers(&ob_new->controllers, &ob->controllers, flag);
+ copy_actuators(&ob_new->actuators, &ob->actuators, flag);
for (bSensor *sens = ob_new->sensors.first; sens; sens = sens->next) {
if (sens->flag & SENS_NEW) {
diff --git a/source/blender/blenkernel/intern/scene.c b/source/blender/blenkernel/intern/scene.c
index 1e8c1a0db05..41a4998c1ea 100644
--- a/source/blender/blenkernel/intern/scene.c
+++ b/source/blender/blenkernel/intern/scene.c
@@ -125,17 +125,6 @@ void free_avicodecdata(AviCodecData *acd)
}
}
-void free_qtcodecdata(QuicktimeCodecData *qcd)
-{
- if (qcd) {
- if (qcd->cdParms) {
- MEM_freeN(qcd->cdParms);
- qcd->cdParms = NULL;
- qcd->cdSize = 0;
- }
- }
-}
-
static void remove_sequencer_fcurves(Scene *sce)
{
AnimData *adt = BKE_animdata_from_id(&sce->id);
@@ -154,210 +143,299 @@ static void remove_sequencer_fcurves(Scene *sce)
}
}
-Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
+/* flag -- copying options (see BKE_library.h's LIB_ID_COPY_... flags for more). */
+ToolSettings *BKE_toolsettings_copy(ToolSettings *toolsettings, const int flag)
{
- Scene *scen;
- SceneRenderLayer *srl, *new_srl;
- FreestyleLineSet *lineset;
- ToolSettings *ts;
- Base *base, *obase;
-
- if (type == SCE_COPY_EMPTY) {
- ListBase rl, rv;
- scen = BKE_scene_add(bmain, sce->id.name + 2);
-
- rl = scen->r.layers;
- rv = scen->r.views;
- curvemapping_free_data(&scen->r.mblur_shutter_curve);
- scen->r = sce->r;
- scen->r.layers = rl;
- scen->r.actlay = 0;
- scen->r.views = rv;
- scen->unit = sce->unit;
- scen->physics_settings = sce->physics_settings;
- scen->gm = sce->gm;
- scen->audio = sce->audio;
+ if (toolsettings == NULL) {
+ return NULL;
+ }
+ ToolSettings *ts = MEM_dupallocN(toolsettings);
+ if (ts->vpaint) {
+ ts->vpaint = MEM_dupallocN(ts->vpaint);
+ BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint, flag);
+ }
+ if (ts->wpaint) {
+ ts->wpaint = MEM_dupallocN(ts->wpaint);
+ BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint, flag);
+ }
+ if (ts->sculpt) {
+ ts->sculpt = MEM_dupallocN(ts->sculpt);
+ BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint, flag);
+ }
+ if (ts->uvsculpt) {
+ ts->uvsculpt = MEM_dupallocN(ts->uvsculpt);
+ BKE_paint_copy(&ts->uvsculpt->paint, &ts->uvsculpt->paint, flag);
+ }
- if (sce->id.properties)
- scen->id.properties = IDP_CopyProperty(sce->id.properties);
+ BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint, flag);
+ ts->imapaint.paintcursor = NULL;
+ ts->particle.paintcursor = NULL;
+ ts->particle.scene = NULL;
+ ts->particle.object = NULL;
- MEM_freeN(scen->toolsettings);
- BKE_sound_destroy_scene(scen);
+ /* duplicate Grease Pencil Drawing Brushes */
+ BLI_listbase_clear(&ts->gp_brushes);
+ for (bGPDbrush *brush = toolsettings->gp_brushes.first; brush; brush = brush->next) {
+ bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
+ BLI_addtail(&ts->gp_brushes, newbrush);
}
- else {
- scen = BKE_libblock_copy(bmain, &sce->id);
- BLI_duplicatelist(&(scen->base), &(sce->base));
-
- id_us_plus((ID *)scen->world);
- id_us_plus((ID *)scen->set);
- /* id_us_plus((ID *)scen->gm.dome.warptext); */ /* XXX Not refcounted? see readfile.c */
-
- scen->ed = NULL;
- scen->theDag = NULL;
- scen->depsgraph = NULL;
- scen->obedit = NULL;
- scen->stats = NULL;
- scen->fps_info = NULL;
-
- if (sce->rigidbody_world)
- scen->rigidbody_world = BKE_rigidbody_world_copy(sce->rigidbody_world);
-
- BLI_duplicatelist(&(scen->markers), &(sce->markers));
- BLI_duplicatelist(&(scen->transform_spaces), &(sce->transform_spaces));
- BLI_duplicatelist(&(scen->r.layers), &(sce->r.layers));
- BLI_duplicatelist(&(scen->r.views), &(sce->r.views));
- BKE_keyingsets_copy(&(scen->keyingsets), &(sce->keyingsets));
- if (sce->nodetree) {
- /* ID's are managed on both copy and switch */
- scen->nodetree = ntreeCopyTree(bmain, sce->nodetree);
- BKE_libblock_relink_ex(bmain, scen->nodetree, &sce->id, &scen->id, false);
- }
+ /* duplicate Grease Pencil interpolation curve */
+ ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
+ return ts;
+}
- obase = sce->base.first;
- base = scen->base.first;
- while (base) {
- id_us_plus(&base->object->id);
- if (obase == sce->basact) scen->basact = base;
-
- obase = obase->next;
- base = base->next;
+void BKE_toolsettings_free(ToolSettings *toolsettings)
+{
+ if (toolsettings == NULL) {
+ return;
+ }
+ if (toolsettings->vpaint) {
+ BKE_paint_free(&toolsettings->vpaint->paint);
+ MEM_freeN(toolsettings->vpaint);
+ }
+ if (toolsettings->wpaint) {
+ BKE_paint_free(&toolsettings->wpaint->paint);
+ MEM_freeN(toolsettings->wpaint);
+ }
+ if (toolsettings->sculpt) {
+ BKE_paint_free(&toolsettings->sculpt->paint);
+ MEM_freeN(toolsettings->sculpt);
+ }
+ if (toolsettings->uvsculpt) {
+ BKE_paint_free(&toolsettings->uvsculpt->paint);
+ MEM_freeN(toolsettings->uvsculpt);
+ }
+ BKE_paint_free(&toolsettings->imapaint.paint);
+
+ /* free Grease Pencil Drawing Brushes */
+ BKE_gpencil_free_brushes(&toolsettings->gp_brushes);
+ BLI_freelistN(&toolsettings->gp_brushes);
+
+ /* free Grease Pencil interpolation curve */
+ if (toolsettings->gp_interpolate.custom_ipo) {
+ curvemapping_free(toolsettings->gp_interpolate.custom_ipo);
+ }
+
+ MEM_freeN(toolsettings);
+}
+
+/**
+ * Only copy internal data of Scene ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_scene_copy_data(Main *bmain, Scene *sce_dst, const Scene *sce_src, const int flag)
+{
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
+
+ sce_dst->ed = NULL;
+ sce_dst->theDag = NULL;
+ sce_dst->depsgraph = NULL;
+ sce_dst->obedit = NULL;
+ sce_dst->stats = NULL;
+ sce_dst->fps_info = NULL;
+
+ BLI_duplicatelist(&(sce_dst->base), &(sce_src->base));
+ for (Base *base_dst = sce_dst->base.first, *base_src = sce_src->base.first;
+ base_dst;
+ base_dst = base_dst->next, base_src = base_src->next)
+ {
+ if (base_src == sce_src->basact) {
+ sce_dst->basact = base_dst;
}
+ }
- /* copy action and remove animation used by sequencer */
- BKE_animdata_copy_id_action(&scen->id, false);
+ BLI_duplicatelist(&(sce_dst->markers), &(sce_src->markers));
+ BLI_duplicatelist(&(sce_dst->transform_spaces), &(sce_src->transform_spaces));
+ BLI_duplicatelist(&(sce_dst->r.layers), &(sce_src->r.layers));
+ BLI_duplicatelist(&(sce_dst->r.views), &(sce_src->r.views));
+ BKE_keyingsets_copy(&(sce_dst->keyingsets), &(sce_src->keyingsets));
- if (type != SCE_COPY_FULL)
- remove_sequencer_fcurves(scen);
+ if (sce_src->nodetree) {
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)sce_src->nodetree, (ID **)&sce_dst->nodetree, flag, false);
+ BKE_libblock_relink_ex(bmain, sce_dst->nodetree, (void *)(&sce_src->id), &sce_dst->id, false);
+ }
- /* copy Freestyle settings */
- new_srl = scen->r.layers.first;
- for (srl = sce->r.layers.first; srl; srl = srl->next) {
- BKE_freestyle_config_copy(&new_srl->freestyleConfig, &srl->freestyleConfig);
- if (type == SCE_COPY_FULL) {
- for (lineset = new_srl->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
- if (lineset->linestyle) {
- id_us_plus((ID *)lineset->linestyle);
- lineset->linestyle = BKE_linestyle_copy(bmain, lineset->linestyle);
- }
- }
- }
- new_srl = new_srl->next;
+ if (sce_src->rigidbody_world) {
+ sce_dst->rigidbody_world = BKE_rigidbody_world_copy(sce_src->rigidbody_world, flag_subdata);
+ }
+
+ /* copy Freestyle settings */
+ for (SceneRenderLayer *srl_dst = sce_dst->r.layers.first, *srl_src = sce_src->r.layers.first;
+ srl_src;
+ srl_dst = srl_dst->next, srl_src = srl_src->next)
+ {
+ if (srl_dst->prop != NULL) {
+ srl_dst->prop = IDP_CopyProperty_ex(srl_dst->prop, flag_subdata);
}
+ BKE_freestyle_config_copy(&srl_dst->freestyleConfig, &srl_src->freestyleConfig, flag_subdata);
}
/* copy color management settings */
- BKE_color_managed_display_settings_copy(&scen->display_settings, &sce->display_settings);
- BKE_color_managed_view_settings_copy(&scen->view_settings, &sce->view_settings);
- BKE_color_managed_colorspace_settings_copy(&scen->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
+ BKE_color_managed_display_settings_copy(&sce_dst->display_settings, &sce_src->display_settings);
+ BKE_color_managed_view_settings_copy(&sce_dst->view_settings, &sce_src->view_settings);
+ BKE_color_managed_colorspace_settings_copy(&sce_dst->sequencer_colorspace_settings, &sce_src->sequencer_colorspace_settings);
- BKE_color_managed_display_settings_copy(&scen->r.im_format.display_settings, &sce->r.im_format.display_settings);
- BKE_color_managed_view_settings_copy(&scen->r.im_format.view_settings, &sce->r.im_format.view_settings);
+ BKE_color_managed_display_settings_copy(&sce_dst->r.im_format.display_settings, &sce_src->r.im_format.display_settings);
+ BKE_color_managed_view_settings_copy(&sce_dst->r.im_format.view_settings, &sce_src->r.im_format.view_settings);
- BKE_color_managed_display_settings_copy(&scen->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
- BKE_color_managed_view_settings_copy(&scen->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
+ BKE_color_managed_display_settings_copy(&sce_dst->r.bake.im_format.display_settings, &sce_src->r.bake.im_format.display_settings);
+ BKE_color_managed_view_settings_copy(&sce_dst->r.bake.im_format.view_settings, &sce_src->r.bake.im_format.view_settings);
- curvemapping_copy_data(&scen->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
+ curvemapping_copy_data(&sce_dst->r.mblur_shutter_curve, &sce_src->r.mblur_shutter_curve);
/* tool settings */
- scen->toolsettings = MEM_dupallocN(sce->toolsettings);
-
- ts = scen->toolsettings;
- if (ts) {
- if (ts->vpaint) {
- ts->vpaint = MEM_dupallocN(ts->vpaint);
- ts->vpaint->paintcursor = NULL;
- ts->vpaint->vpaint_prev = NULL;
- ts->vpaint->wpaint_prev = NULL;
- BKE_paint_copy(&ts->vpaint->paint, &ts->vpaint->paint);
- }
- if (ts->wpaint) {
- ts->wpaint = MEM_dupallocN(ts->wpaint);
- ts->wpaint->paintcursor = NULL;
- ts->wpaint->vpaint_prev = NULL;
- ts->wpaint->wpaint_prev = NULL;
- BKE_paint_copy(&ts->wpaint->paint, &ts->wpaint->paint);
- }
- if (ts->sculpt) {
- ts->sculpt = MEM_dupallocN(ts->sculpt);
- BKE_paint_copy(&ts->sculpt->paint, &ts->sculpt->paint);
- }
+ sce_dst->toolsettings = BKE_toolsettings_copy(sce_dst->toolsettings, flag_subdata);
- BKE_paint_copy(&ts->imapaint.paint, &ts->imapaint.paint);
- ts->imapaint.paintcursor = NULL;
- id_us_plus((ID *)ts->imapaint.stencil);
- ts->particle.paintcursor = NULL;
-
- /* duplicate Grease Pencil Drawing Brushes */
- BLI_listbase_clear(&ts->gp_brushes);
- for (bGPDbrush *brush = sce->toolsettings->gp_brushes.first; brush; brush = brush->next) {
- bGPDbrush *newbrush = BKE_gpencil_brush_duplicate(brush);
- BLI_addtail(&ts->gp_brushes, newbrush);
- }
-
- /* duplicate Grease Pencil interpolation curve */
- ts->gp_interpolate.custom_ipo = curvemapping_copy(ts->gp_interpolate.custom_ipo);
- }
-
/* make a private copy of the avicodecdata */
- if (sce->r.avicodecdata) {
- scen->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
- scen->r.avicodecdata->lpFormat = MEM_dupallocN(scen->r.avicodecdata->lpFormat);
- scen->r.avicodecdata->lpParms = MEM_dupallocN(scen->r.avicodecdata->lpParms);
- }
-
- /* make a private copy of the qtcodecdata */
- if (sce->r.qtcodecdata) {
- scen->r.qtcodecdata = MEM_dupallocN(sce->r.qtcodecdata);
- scen->r.qtcodecdata->cdParms = MEM_dupallocN(scen->r.qtcodecdata->cdParms);
+ if (sce_src->r.avicodecdata) {
+ sce_dst->r.avicodecdata = MEM_dupallocN(sce_src->r.avicodecdata);
+ sce_dst->r.avicodecdata->lpFormat = MEM_dupallocN(sce_dst->r.avicodecdata->lpFormat);
+ sce_dst->r.avicodecdata->lpParms = MEM_dupallocN(sce_dst->r.avicodecdata->lpParms);
}
-
- if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
- scen->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
+
+ if (sce_src->r.ffcodecdata.properties) { /* intentionally check sce_dst not sce_src. */ /* XXX ??? comment outdated... */
+ sce_dst->r.ffcodecdata.properties = IDP_CopyProperty_ex(sce_src->r.ffcodecdata.properties, flag_subdata);
}
- /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
- * are done outside of blenkernel with ED_objects_single_users! */
+ /* before scene copy */
+ BKE_sound_create_scene(sce_dst);
- /* camera */
- if (type == SCE_COPY_LINK_DATA || type == SCE_COPY_FULL) {
- ID_NEW_REMAP(scen->camera);
+ /* Copy sequencer, this is local data! */
+ if (sce_src->ed) {
+ sce_dst->ed = MEM_callocN(sizeof(*sce_dst->ed), __func__);
+ sce_dst->ed->seqbasep = &sce_dst->ed->seqbase;
+ BKE_sequence_base_dupli_recursive(
+ sce_src, sce_dst, &sce_dst->ed->seqbase, &sce_src->ed->seqbase, SEQ_DUPE_ALL, flag_subdata);
}
-
- /* before scene copy */
- BKE_sound_create_scene(scen);
- /* world */
- if (type == SCE_COPY_FULL) {
- if (scen->world) {
- id_us_plus((ID *)scen->world);
- scen->world = BKE_world_copy(bmain, scen->world);
- BKE_animdata_copy_id_action((ID *)scen->world, false);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&sce_dst->id, &sce_src->id);
+ }
+ else {
+ sce_dst->preview = NULL;
+ }
+}
+
+Scene *BKE_scene_copy(Main *bmain, Scene *sce, int type)
+{
+ Scene *sce_copy;
+
+ /* TODO this should/could most likely be replaced by call to more generic code at some point...
+ * But for now, let's keep it well isolated here. */
+ if (type == SCE_COPY_EMPTY) {
+ ListBase rl, rv;
+
+ sce_copy = BKE_scene_add(bmain, sce->id.name + 2);
+
+ rl = sce_copy->r.layers;
+ rv = sce_copy->r.views;
+ curvemapping_free_data(&sce_copy->r.mblur_shutter_curve);
+ sce_copy->r = sce->r;
+ sce_copy->r.layers = rl;
+ sce_copy->r.actlay = 0;
+ sce_copy->r.views = rv;
+ sce_copy->unit = sce->unit;
+ sce_copy->physics_settings = sce->physics_settings;
+ sce_copy->gm = sce->gm;
+ sce_copy->audio = sce->audio;
+
+ if (sce->id.properties)
+ sce_copy->id.properties = IDP_CopyProperty(sce->id.properties);
+
+ MEM_freeN(sce_copy->toolsettings);
+ BKE_sound_destroy_scene(sce_copy);
+
+ /* copy color management settings */
+ BKE_color_managed_display_settings_copy(&sce_copy->display_settings, &sce->display_settings);
+ BKE_color_managed_view_settings_copy(&sce_copy->view_settings, &sce->view_settings);
+ BKE_color_managed_colorspace_settings_copy(&sce_copy->sequencer_colorspace_settings, &sce->sequencer_colorspace_settings);
+
+ BKE_color_managed_display_settings_copy(&sce_copy->r.im_format.display_settings, &sce->r.im_format.display_settings);
+ BKE_color_managed_view_settings_copy(&sce_copy->r.im_format.view_settings, &sce->r.im_format.view_settings);
+
+ BKE_color_managed_display_settings_copy(&sce_copy->r.bake.im_format.display_settings, &sce->r.bake.im_format.display_settings);
+ BKE_color_managed_view_settings_copy(&sce_copy->r.bake.im_format.view_settings, &sce->r.bake.im_format.view_settings);
+
+ curvemapping_copy_data(&sce_copy->r.mblur_shutter_curve, &sce->r.mblur_shutter_curve);
+
+ /* tool settings */
+ sce_copy->toolsettings = BKE_toolsettings_copy(sce->toolsettings, 0);
+
+ /* make a private copy of the avicodecdata */
+ if (sce->r.avicodecdata) {
+ sce_copy->r.avicodecdata = MEM_dupallocN(sce->r.avicodecdata);
+ sce_copy->r.avicodecdata->lpFormat = MEM_dupallocN(sce_copy->r.avicodecdata->lpFormat);
+ sce_copy->r.avicodecdata->lpParms = MEM_dupallocN(sce_copy->r.avicodecdata->lpParms);
}
- if (sce->ed) {
- scen->ed = MEM_callocN(sizeof(Editing), "addseq");
- scen->ed->seqbasep = &scen->ed->seqbase;
- BKE_sequence_base_dupli_recursive(sce, scen, &scen->ed->seqbase, &sce->ed->seqbase, SEQ_DUPE_ALL);
+ if (sce->r.ffcodecdata.properties) { /* intentionally check scen not sce. */
+ sce_copy->r.ffcodecdata.properties = IDP_CopyProperty(sce->r.ffcodecdata.properties);
}
+
+ /* before scene copy */
+ BKE_sound_create_scene(sce_copy);
+
+ /* grease pencil */
+ sce_copy->gpd = NULL;
+
+ sce_copy->preview = NULL;
+
+ return sce_copy;
}
-
- /* grease pencil */
- if (scen->gpd) {
+ else {
+ BKE_id_copy_ex(bmain, (ID *)sce, (ID **)&sce_copy, LIB_ID_COPY_ACTIONS, false);
+ id_us_min(&sce_copy->id);
+ id_us_ensure_real(&sce_copy->id);
+
+ /* Extra actions, most notably SCE_FULL_COPY also duplicates several 'children' datablocks... */
+
if (type == SCE_COPY_FULL) {
- scen->gpd = BKE_gpencil_data_duplicate(bmain, scen->gpd, false);
- }
- else if (type == SCE_COPY_EMPTY) {
- scen->gpd = NULL;
+ /* Copy Freestyle LineStyle datablocks. */
+ for (SceneRenderLayer *srl_dst = sce_copy->r.layers.first; srl_dst; srl_dst = srl_dst->next) {
+ for (FreestyleLineSet *lineset = srl_dst->freestyleConfig.linesets.first; lineset; lineset = lineset->next) {
+ if (lineset->linestyle) {
+ /* XXX Not copying anim/actions here? */
+ BKE_id_copy_ex(bmain, (ID *)lineset->linestyle, (ID **)&lineset->linestyle, 0, false);
+ }
+ }
+ }
+
+ /* Full copy of world (included animations) */
+ if (sce_copy->world) {
+ BKE_id_copy_ex(bmain, (ID *)sce_copy->world, (ID **)&sce_copy->world, LIB_ID_COPY_ACTIONS, false);
+ }
+
+ /* Full copy of GreasePencil. */
+ /* XXX Not copying anim/actions here? */
+ if (sce_copy->gpd) {
+ BKE_id_copy_ex(bmain, (ID *)sce_copy->gpd, (ID **)&sce_copy->gpd, 0, false);
+ }
}
else {
- id_us_plus((ID *)scen->gpd);
+ /* Remove sequencer if not full copy */
+ /* XXX Why in Hell? :/ */
+ remove_sequencer_fcurves(sce_copy);
+ BKE_sequencer_editing_free(sce_copy);
}
- }
- BKE_previewimg_id_copy(&scen->id, &sce->id);
+ /* NOTE: part of SCE_COPY_LINK_DATA and SCE_COPY_FULL operations
+ * are done outside of blenkernel with ED_objects_single_users! */
- return scen;
+ /* camera */
+ if (ELEM(type, SCE_COPY_LINK_DATA, SCE_COPY_FULL)) {
+ ID_NEW_REMAP(sce_copy->camera);
+ }
+
+ return sce_copy;
+ }
}
void BKE_scene_groups_relink(Scene *sce)
@@ -406,57 +484,27 @@ void BKE_scene_free(Scene *sce)
MEM_freeN(sce->r.avicodecdata);
sce->r.avicodecdata = NULL;
}
- if (sce->r.qtcodecdata) {
- free_qtcodecdata(sce->r.qtcodecdata);
- 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;
}
-
+
for (srl = sce->r.layers.first; srl; srl = srl->next) {
+ if (srl->prop != NULL) {
+ IDP_FreeProperty(srl->prop);
+ MEM_freeN(srl->prop);
+ }
BKE_freestyle_config_free(&srl->freestyleConfig);
}
-
+
BLI_freelistN(&sce->markers);
BLI_freelistN(&sce->transform_spaces);
BLI_freelistN(&sce->r.layers);
BLI_freelistN(&sce->r.views);
- if (sce->toolsettings) {
- if (sce->toolsettings->vpaint) {
- BKE_paint_free(&sce->toolsettings->vpaint->paint);
- MEM_freeN(sce->toolsettings->vpaint);
- }
- if (sce->toolsettings->wpaint) {
- BKE_paint_free(&sce->toolsettings->wpaint->paint);
- MEM_freeN(sce->toolsettings->wpaint);
- }
- if (sce->toolsettings->sculpt) {
- BKE_paint_free(&sce->toolsettings->sculpt->paint);
- MEM_freeN(sce->toolsettings->sculpt);
- }
- if (sce->toolsettings->uvsculpt) {
- BKE_paint_free(&sce->toolsettings->uvsculpt->paint);
- MEM_freeN(sce->toolsettings->uvsculpt);
- }
- BKE_paint_free(&sce->toolsettings->imapaint.paint);
-
- /* free Grease Pencil Drawing Brushes */
- BKE_gpencil_free_brushes(&sce->toolsettings->gp_brushes);
- BLI_freelistN(&sce->toolsettings->gp_brushes);
-
- /* free Grease Pencil interpolation curve */
- if (sce->toolsettings->gp_interpolate.custom_ipo) {
- curvemapping_free(sce->toolsettings->gp_interpolate.custom_ipo);
- }
-
- MEM_freeN(sce->toolsettings);
- sce->toolsettings = NULL;
- }
+ BKE_toolsettings_free(sce->toolsettings);
+ sce->toolsettings = NULL;
DAG_scene_free(sce);
if (sce->depsgraph)
@@ -566,7 +614,7 @@ void BKE_scene_init(Scene *sce)
sce->r.seq_prev_type = OB_SOLID;
sce->r.seq_rend_type = OB_SOLID;
- sce->r.seq_flag = R_SEQ_GL_PREV;
+ sce->r.seq_flag = 0;
sce->r.threads = 1;
@@ -660,7 +708,8 @@ void BKE_scene_init(Scene *sce)
pset->draw_step = 2;
pset->fade_frames = 2;
pset->selectmode = SCE_SELECT_PATH;
- for (a = 0; a < PE_TOT_BRUSH; a++) {
+
+ for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
pset->brush[a].strength = 0.5f;
pset->brush[a].size = 50;
pset->brush[a].step = 10;
@@ -825,7 +874,7 @@ Scene *BKE_scene_add(Main *bmain, const char *name)
{
Scene *sce;
- sce = BKE_libblock_alloc(bmain, ID_SCE, name);
+ sce = BKE_libblock_alloc(bmain, ID_SCE, name, 0);
id_us_min(&sce->id);
id_us_ensure_real(&sce->id);
@@ -1063,6 +1112,10 @@ Object *BKE_scene_camera_find(Scene *sc)
#ifdef DURIAN_CAMERA_SWITCH
Object *BKE_scene_camera_switch_find(Scene *scene)
{
+ if (scene->r.mode & R_NO_CAMERA_SWITCH) {
+ return NULL;
+ }
+
TimeMarker *m;
int cfra = scene->r.cfra;
int frame = -(MAXFRAME + 1);
@@ -1438,6 +1491,8 @@ typedef struct ThreadedObjectUpdateState {
bool has_mballs;
#endif
+ int num_threads;
+
/* Execution statistics */
bool has_updated_objects;
ListBase *statistics;
@@ -1486,7 +1541,7 @@ static void scene_update_object_func(TaskPool * __restrict pool, void *taskdata,
double start_time = 0.0;
bool add_to_stats = false;
- if (G.debug & G_DEBUG_DEPSGRAPH) {
+ if (G.debug & G_DEBUG_DEPSGRAPH_EVAL) {
if (object->recalc & OB_RECALC_ALL) {
printf("Thread %d: update object %s\n", threadid, object->id.name);
}
@@ -1509,8 +1564,6 @@ static void scene_update_object_func(TaskPool * __restrict pool, void *taskdata,
if (add_to_stats) {
StatisicsEntry *entry;
- BLI_assert(threadid < BLI_pool_get_num_threads(pool));
-
entry = MEM_mallocN(sizeof(StatisicsEntry), "update thread statistics");
entry->object = object;
entry->start_time = start_time;
@@ -1539,10 +1592,9 @@ static void scene_update_object_add_task(void *node, void *user_data)
static void print_threads_statistics(ThreadedObjectUpdateState *state)
{
- int i, tot_thread;
double finish_time;
- if ((G.debug & G_DEBUG_DEPSGRAPH) == 0) {
+ if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
return;
}
@@ -1567,10 +1619,9 @@ static void print_threads_statistics(ThreadedObjectUpdateState *state)
}
#else
finish_time = PIL_check_seconds_timer();
- tot_thread = BLI_system_thread_count();
int total_objects = 0;
- for (i = 0; i < tot_thread; i++) {
+ for (int i = 0; i < state->num_threads; i++) {
int thread_total_objects = 0;
double thread_total_time = 0.0;
StatisicsEntry *entry;
@@ -1630,10 +1681,11 @@ static bool scene_need_update_objects(Main *bmain)
static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
{
- TaskScheduler *task_scheduler = BLI_task_scheduler_get();
+ TaskScheduler *task_scheduler;
TaskPool *task_pool;
ThreadedObjectUpdateState state;
bool need_singlethread_pass;
+ bool need_free_scheduler;
/* Early check for whether we need to invoke all the task-based
* things (spawn new ppol, traverse dependency graph and so on).
@@ -1650,13 +1702,23 @@ static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene
state.scene = scene;
state.scene_parent = scene_parent;
+ if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
+ task_scheduler = BLI_task_scheduler_create(1);
+ need_free_scheduler = true;
+ }
+ else {
+ task_scheduler = BLI_task_scheduler_get();
+ need_free_scheduler = false;
+ }
+
/* Those are only needed when blender is run with --debug argument. */
- if (G.debug & G_DEBUG_DEPSGRAPH) {
+ if (G.debug & G_DEBUG_DEPSGRAPH_EVAL) {
const int tot_thread = BLI_task_scheduler_num_threads(task_scheduler);
state.statistics = MEM_callocN(tot_thread * sizeof(*state.statistics),
"scene update objects stats");
state.has_updated_objects = false;
state.base_time = PIL_check_seconds_timer();
+ state.num_threads = tot_thread;
}
#ifdef MBALL_SINGLETHREAD_HACK
@@ -1664,15 +1726,12 @@ static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene
#endif
task_pool = BLI_task_pool_create(task_scheduler, &state);
- if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
- BLI_pool_set_num_threads(task_pool, 1);
- }
DAG_threaded_update_begin(scene, scene_update_object_add_task, task_pool);
BLI_task_pool_work_and_wait(task_pool);
BLI_task_pool_free(task_pool);
- if (G.debug & G_DEBUG_DEPSGRAPH) {
+ if (G.debug & G_DEBUG_DEPSGRAPH_EVAL) {
print_threads_statistics(&state);
MEM_freeN(state.statistics);
}
@@ -1699,6 +1758,10 @@ static void scene_update_objects(EvaluationContext *eval_ctx, Main *bmain, Scene
if (need_singlethread_pass) {
scene_update_all_bases(eval_ctx, scene, scene_parent);
}
+
+ if (need_free_scheduler) {
+ BLI_task_scheduler_free(task_scheduler);
+ }
}
static void scene_update_tagged_recursive(EvaluationContext *eval_ctx, Main *bmain, Scene *scene, Scene *scene_parent)
@@ -1757,12 +1820,16 @@ static void prepare_mesh_for_viewport_render(Main *bmain, Scene *scene)
if (obedit) {
Mesh *mesh = obedit->data;
if ((obedit->type == OB_MESH) &&
- ((obedit->id.tag & LIB_TAG_ID_RECALC_ALL) ||
- (mesh->id.tag & LIB_TAG_ID_RECALC_ALL)))
+ ((obedit->id.recalc & ID_RECALC_ALL) ||
+ (mesh->id.recalc & ID_RECALC_ALL)))
{
if (check_rendered_viewport_visible(bmain)) {
BMesh *bm = mesh->edit_btmesh->bm;
- BM_mesh_bm_to_me(bm, mesh, (&(struct BMeshToMeshParams){0}));
+ BM_mesh_bm_to_me(
+ bm, mesh,
+ (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
DAG_id_tag_update(&mesh->id, 0);
}
}
@@ -1782,7 +1849,7 @@ void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *sc
/* (re-)build dependency graph if needed */
for (sce_iter = scene; sce_iter; sce_iter = sce_iter->set) {
DAG_scene_relations_update(bmain, sce_iter);
- /* Uncomment this to check if graph was properly tagged for update. */
+ /* Uncomment this to check if dependency graph was properly tagged for update. */
#if 0
#ifdef WITH_LEGACY_DEPSGRAPH
if (use_new_eval)
@@ -1820,8 +1887,6 @@ void BKE_scene_update_tagged(EvaluationContext *eval_ctx, Main *bmain, Scene *sc
#endif
{
DEG_evaluate_on_refresh(eval_ctx, scene->depsgraph, scene);
- /* TODO(sergey): This is to beocme a node in new depsgraph. */
- BKE_mask_update_scene(bmain, scene);
}
/* update sound system animation (TODO, move to depsgraph) */
@@ -1896,7 +1961,7 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain,
#ifdef WITH_LEGACY_DEPSGRAPH
bool use_new_eval = !DEG_depsgraph_use_legacy();
#else
- /* TODO(sergey): Pass to evaluation routines instead of storing layer in the graph? */
+ /* TODO(sergey): Pass to evaluation routines instead of storing layer in the dependency graph? */
(void) do_invisible_flush;
#endif
@@ -1938,11 +2003,10 @@ void BKE_scene_update_for_newframe_ex(EvaluationContext *eval_ctx, Main *bmain,
/* Following 2 functions are recursive
* so don't call within 'scene_update_tagged_recursive' */
DAG_scene_update_flags(bmain, sce, lay, true, do_invisible_flush); // only stuff that moves or needs display still
+ BKE_mask_evaluate_all_masks(bmain, ctime, true);
}
#endif
- BKE_mask_evaluate_all_masks(bmain, ctime, true);
-
/* Update animated cache files for modifiers. */
BKE_cachefile_update_frame(bmain, sce, ctime, (((double)sce->r.frs_sec) / (double)sce->r.frs_sec_base));
@@ -2053,6 +2117,11 @@ bool BKE_scene_remove_render_layer(Main *bmain, Scene *scene, SceneRenderLayer *
BKE_freestyle_config_free(&srl->freestyleConfig);
+ if (srl->prop) {
+ IDP_FreeProperty(srl->prop);
+ MEM_freeN(srl->prop);
+ }
+
BLI_remlink(&scene->r.layers, srl);
MEM_freeN(srl);
@@ -2115,7 +2184,7 @@ bool BKE_scene_remove_render_view(Scene *scene, SceneRenderView *srv)
int get_render_subsurf_level(const RenderData *r, int lvl, bool for_render)
{
- if (r->mode & R_SIMPLIFY) {
+ if (r->mode & R_SIMPLIFY) {
if (for_render)
return min_ii(r->simplify_subsurf_render, lvl);
else
@@ -2286,6 +2355,14 @@ int BKE_scene_num_threads(const Scene *scene)
return BKE_render_num_threads(&scene->r);
}
+int BKE_render_preview_pixel_size(const RenderData *r)
+{
+ if (r->preview_pixel_size == 0) {
+ return (U.pixelsize > 1.5f) ? 2 : 1;
+ }
+ return r->preview_pixel_size;
+}
+
/* Apply the needed correction factor to value, based on unit_type (only length-related are affected currently)
* and unit->scale_length.
*/
diff --git a/source/blender/blenkernel/intern/screen.c b/source/blender/blenkernel/intern/screen.c
index 857bd5447c8..2b1cf0a01df 100644
--- a/source/blender/blenkernel/intern/screen.c
+++ b/source/blender/blenkernel/intern/screen.c
@@ -181,6 +181,7 @@ ARegion *BKE_area_region_copy(SpaceType *st, ARegion *ar)
BLI_listbase_clear(&newar->ui_lists);
newar->swinid = 0;
newar->regiontimer = NULL;
+ newar->headerstr = NULL;
/* use optional regiondata callback */
if (ar->regiondata) {
@@ -380,6 +381,9 @@ void BKE_screen_free(bScreen *sc)
BLI_freelistN(&sc->vertbase);
BLI_freelistN(&sc->edgebase);
BLI_freelistN(&sc->areabase);
+
+ /* Region and timer are freed by the window manager. */
+ MEM_SAFE_FREE(sc->tool_tip);
}
/* for depsgraph */
@@ -616,7 +620,7 @@ void BKE_screen_view3d_twmode_remove(View3D *v3d, const int i)
{
const int selected_index = (v3d->twmode - V3D_MANIP_CUSTOM);
if (selected_index == i) {
- v3d->twmode = V3D_MANIP_GLOBAL; /* fallback to global */
+ v3d->twmode = V3D_MANIP_GLOBAL; /* fallback to global */
}
else if (selected_index > i) {
v3d->twmode--;
diff --git a/source/blender/blenkernel/intern/seqeffects.c b/source/blender/blenkernel/intern/seqeffects.c
index 298671beedb..176d1224979 100644
--- a/source/blender/blenkernel/intern/seqeffects.c
+++ b/source/blender/blenkernel/intern/seqeffects.c
@@ -52,6 +52,9 @@
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
#include "IMB_colormanagement.h"
+#include "IMB_metadata.h"
+
+#include "BLI_math_color_blend.h"
#include "RNA_access.h"
@@ -59,9 +62,10 @@
#include "BLF_api.h"
-static void slice_get_byte_buffers(const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2,
- const ImBuf *ibuf3, const ImBuf *out, int start_line, unsigned char **rect1,
- unsigned char **rect2, unsigned char **rect3, unsigned char **rect_out)
+static void slice_get_byte_buffers(
+ const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2,
+ const ImBuf *ibuf3, const ImBuf *out, int start_line, unsigned char **rect1,
+ unsigned char **rect2, unsigned char **rect3, unsigned char **rect_out)
{
int offset = 4 * start_line * context->rectx;
@@ -75,9 +79,10 @@ static void slice_get_byte_buffers(const SeqRenderData *context, const ImBuf *ib
*rect3 = (unsigned char *)ibuf3->rect + offset;
}
-static void slice_get_float_buffers(const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2,
- const ImBuf *ibuf3, const ImBuf *out, int start_line,
- float **rect1, float **rect2, float **rect3, float **rect_out)
+static void slice_get_float_buffers(
+ const SeqRenderData *context, const ImBuf *ibuf1, const ImBuf *ibuf2,
+ const ImBuf *ibuf3, const ImBuf *out, int start_line,
+ float **rect1, float **rect2, float **rect3, float **rect_out)
{
int offset = 4 * start_line * context->rectx;
@@ -171,7 +176,9 @@ static void init_alpha_over_or_under(Sequence *seq)
seq->seq1 = seq2;
}
-static void do_alphaover_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2, unsigned char *out)
+static void do_alphaover_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
float fac2, mfac, fac, fac4;
int xo;
@@ -236,7 +243,9 @@ static void do_alphaover_effect_byte(float facf0, float facf1, int x, int y, un
}
}
-static void do_alphaover_effect_float(float facf0, float facf1, int x, int y, float *rect1, float *rect2, float *out)
+static void do_alphaover_effect_float(
+ float facf0, float facf1, int x, int y,
+ float *rect1, float *rect2, float *out)
{
float fac2, mfac, fac, fac4;
int xo;
@@ -299,9 +308,10 @@ static void do_alphaover_effect_float(float facf0, float facf1, int x, int y, f
}
}
-static void do_alphaover_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0,
- float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
- int start_line, int total_lines, ImBuf *out)
+static void do_alphaover_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0,
+ float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
+ int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -321,7 +331,9 @@ static void do_alphaover_effect(const SeqRenderData *context, Sequence *UNUSED(s
/*********************** Alpha Under *************************/
-static void do_alphaunder_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2, unsigned char *out)
+static void do_alphaunder_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
float fac2, fac, fac4;
int xo;
@@ -393,7 +405,9 @@ static void do_alphaunder_effect_byte(float facf0, float facf1, int x, int y, un
}
}
-static void do_alphaunder_effect_float(float facf0, float facf1, int x, int y, float *rect1, float *rect2, float *out)
+static void do_alphaunder_effect_float(
+ float facf0, float facf1, int x, int y,
+ float *rect1, float *rect2, float *out)
{
float fac2, fac, fac4;
int xo;
@@ -467,9 +481,10 @@ static void do_alphaunder_effect_float(float facf0, float facf1, int x, int y,
}
}
-static void do_alphaunder_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
- float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
- int start_line, int total_lines, ImBuf *out)
+static void do_alphaunder_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
+ float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
+ int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -489,7 +504,9 @@ static void do_alphaunder_effect(const SeqRenderData *context, Sequence *UNUSED(
/*********************** Cross *************************/
-static void do_cross_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2, unsigned char *out)
+static void do_cross_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
int fac1, fac2, fac3, fac4;
int xo;
@@ -577,9 +594,10 @@ static void do_cross_effect_float(float facf0, float facf1, int x, int y, float
}
}
-static void do_cross_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
- float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
- int start_line, int total_lines, ImBuf *out)
+static void do_cross_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
+ float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
+ int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -684,7 +702,7 @@ static float invGammaCorrect(float c)
else if (i >= RE_GAMMA_TABLE_SIZE) res = powf(c, valid_inv_gamma);
else res = inv_gamma_range_table[i] +
((c - color_domain_table[i]) * inv_gamfactor_table[i]);
-
+
return res;
}
@@ -737,8 +755,9 @@ static void free_gammacross(Sequence *UNUSED(seq))
{
}
-static void do_gammacross_effect_byte(float facf0, float UNUSED(facf1), int x, int y, unsigned char *rect1,
- unsigned char *rect2, unsigned char *out)
+static void do_gammacross_effect_byte(
+ float facf0, float UNUSED(facf1), int x, int y, unsigned char *rect1,
+ unsigned char *rect2, unsigned char *out)
{
float fac1, fac2;
int xo;
@@ -788,8 +807,9 @@ static void do_gammacross_effect_byte(float facf0, float UNUSED(facf1), int x,
}
}
-static void do_gammacross_effect_float(float facf0, float UNUSED(facf1), int x, int y, float *rect1,
- float *rect2, float *out)
+static void do_gammacross_effect_float(
+ float facf0, float UNUSED(facf1), int x, int y, float *rect1,
+ float *rect2, float *out)
{
float fac1, fac2;
int xo;
@@ -831,9 +851,10 @@ static struct ImBuf *gammacross_init_execution(const SeqRenderData *context, ImB
return out;
}
-static void do_gammacross_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
- float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
- int start_line, int total_lines, ImBuf *out)
+static void do_gammacross_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
+ float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3),
+ int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -853,8 +874,9 @@ static void do_gammacross_effect(const SeqRenderData *context, Sequence *UNUSED(
/*********************** Add *************************/
-static void do_add_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2,
- unsigned char *out)
+static void do_add_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
int xo, fac1, fac3;
unsigned char *cp1, *cp2, *rt;
@@ -940,8 +962,9 @@ static void do_add_effect_float(float facf0, float facf1, int x, int y, float *r
}
}
-static void do_add_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+static void do_add_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -961,7 +984,9 @@ static void do_add_effect(const SeqRenderData *context, Sequence *UNUSED(seq), f
/*********************** Sub *************************/
-static void do_sub_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2, unsigned char *out)
+static void do_sub_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
int xo, fac1, fac3;
unsigned char *cp1, *cp2, *rt;
@@ -1003,7 +1028,9 @@ static void do_sub_effect_byte(float facf0, float facf1, int x, int y, unsigned
}
}
-static void do_sub_effect_float(float UNUSED(facf0), float facf1, int x, int y, float *rect1, float *rect2, float *out)
+static void do_sub_effect_float(
+ float UNUSED(facf0), float facf1, int x, int y,
+ float *rect1, float *rect2, float *out)
{
int xo;
float /* fac1, */ fac3_inv;
@@ -1047,8 +1074,9 @@ static void do_sub_effect_float(float UNUSED(facf0), float facf1, int x, int y,
}
}
-static void do_sub_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+static void do_sub_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -1072,7 +1100,9 @@ static void do_sub_effect(const SeqRenderData *context, Sequence *UNUSED(seq), f
#define XOFF 8
#define YOFF 8
-static void do_drop_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect2i, unsigned char *rect1i, unsigned char *outi)
+static void do_drop_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect2i, unsigned char *rect1i, unsigned char *outi)
{
int temp, fac, fac1, fac2;
unsigned char *rt1, *rt2, *out;
@@ -1112,7 +1142,9 @@ static void do_drop_effect_byte(float facf0, float facf1, int x, int y, unsigned
memcpy(out, rt1, sizeof(*out) * yoff * 4 * width);
}
-static void do_drop_effect_float(float facf0, float facf1, int x, int y, float *rect2i, float *rect1i, float *outi)
+static void do_drop_effect_float(
+ float facf0, float facf1, int x, int y,
+ float *rect2i, float *rect1i, float *outi)
{
float temp, fac, fac1, fac2;
float *rt1, *rt2, *out;
@@ -1154,8 +1186,9 @@ static void do_drop_effect_float(float facf0, float facf1, int x, int y, float *
/*********************** Mul *************************/
-static void do_mul_effect_byte(float facf0, float facf1, int x, int y, unsigned char *rect1, unsigned char *rect2,
- unsigned char *out)
+static void do_mul_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
int xo, fac1, fac3;
unsigned char *rt1, *rt2, *rt;
@@ -1202,7 +1235,9 @@ static void do_mul_effect_byte(float facf0, float facf1, int x, int y, unsigned
}
}
-static void do_mul_effect_float(float facf0, float facf1, int x, int y, float *rect1, float *rect2, float *out)
+static void do_mul_effect_float(
+ float facf0, float facf1, int x, int y,
+ float *rect1, float *rect2, float *out)
{
int xo;
float fac1, fac3;
@@ -1247,8 +1282,9 @@ static void do_mul_effect_float(float facf0, float facf1, int x, int y, float *r
}
}
-static void do_mul_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+static void do_mul_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
@@ -1266,6 +1302,284 @@ static void do_mul_effect(const SeqRenderData *context, Sequence *UNUSED(seq), f
}
}
+/*********************** Blend Mode ***************************************/
+typedef void (*IMB_blend_func_byte)(unsigned char *dst, const unsigned char *src1, const unsigned char *src2);
+typedef void (*IMB_blend_func_float)(float *dst, const float *src1, const float *src2);
+
+BLI_INLINE void apply_blend_function_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out, IMB_blend_func_byte blend_function)
+{
+ int xo;
+ unsigned char *rt1, *rt2, *rt;
+ unsigned int achannel;
+ xo = x;
+ rt1 = rect1;
+ rt2 = rect2;
+ rt = out;
+ while (y--) {
+ for (x = xo; x > 0; x--) {
+ achannel = rt2[3];
+ rt2[3] = (unsigned int) achannel * facf0;
+ blend_function(rt, rt1, rt2);
+ rt2[3] = achannel;
+ rt[3] = rt2[3];
+ rt1 += 4;
+ rt2 += 4;
+ rt += 4;
+ }
+ if (y == 0) {
+ break;
+ }
+ y--;
+ for (x = xo; x > 0; x--) {
+ achannel = rt2[3];
+ rt2[3] = (unsigned int) achannel * facf1;
+ blend_function(rt, rt1, rt2);
+ rt2[3] = achannel;
+ rt[3] = rt2[3];
+ rt1 += 4;
+ rt2 += 4;
+ rt += 4;
+ }
+ }
+}
+
+BLI_INLINE void apply_blend_function_float(
+ float facf0, float facf1, int x, int y,
+ float *rect1, float *rect2, float *out, IMB_blend_func_float blend_function)
+{
+ int xo;
+ float *rt1, *rt2, *rt;
+ float achannel;
+ xo = x;
+ rt1 = rect1;
+ rt2 = rect2;
+ rt = out;
+ while (y--) {
+ for (x = xo; x > 0; x--) {
+ achannel = rt2[3];
+ rt2[3] = achannel * facf0;
+ blend_function(rt, rt1, rt2);
+ rt2[3] = achannel;
+ rt[3] = rt2[3];
+ rt1 += 4;
+ rt2 += 4;
+ rt += 4;
+ }
+ if (y == 0) {
+ break;
+ }
+ y--;
+ for (x = xo; x > 0; x--) {
+ achannel = rt2[3];
+ rt2[3] = achannel * facf1;
+ blend_function(rt, rt1, rt2);
+ rt2[3] = achannel;
+ rt[3] = rt2[3];
+ rt1 += 4;
+ rt2 += 4;
+ rt += 4;
+ }
+ }
+}
+
+static void do_blend_effect_float(
+ float facf0, float facf1, int x, int y,
+ float *rect1, float *rect2, int btype, float *out)
+{
+ switch (btype) {
+ case SEQ_TYPE_ADD:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_add_float);
+ break;
+ case SEQ_TYPE_SUB:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_sub_float);
+ break;
+ case SEQ_TYPE_MUL:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_mul_float);
+ break;
+ case SEQ_TYPE_DARKEN:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_darken_float);
+ break;
+ case SEQ_TYPE_BURN:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_burn_float);
+ break;
+ case SEQ_TYPE_LINEAR_BURN:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_linearburn_float);
+ break;
+ case SEQ_TYPE_SCREEN:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_screen_float);
+ break;
+ case SEQ_TYPE_LIGHTEN:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_lighten_float);
+ break;
+ case SEQ_TYPE_DODGE:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_dodge_float);
+ break;
+ case SEQ_TYPE_OVERLAY:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_overlay_float);
+ break;
+ case SEQ_TYPE_SOFT_LIGHT:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_softlight_float);
+ break;
+ case SEQ_TYPE_HARD_LIGHT:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_hardlight_float);
+ break;
+ case SEQ_TYPE_PIN_LIGHT:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_pinlight_float);
+ break;
+ case SEQ_TYPE_LIN_LIGHT:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_linearlight_float);
+ break;
+ case SEQ_TYPE_VIVID_LIGHT:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_vividlight_float);
+ break;
+ case SEQ_TYPE_BLEND_COLOR:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_color_float);
+ break;
+ case SEQ_TYPE_HUE:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_hue_float);
+ break;
+ case SEQ_TYPE_SATURATION:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_saturation_float);
+ break;
+ case SEQ_TYPE_VALUE:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_luminosity_float);
+ break;
+ case SEQ_TYPE_DIFFERENCE:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_difference_float);
+ break;
+ case SEQ_TYPE_EXCLUSION:
+ apply_blend_function_float(facf0, facf1, x, y, rect1, rect2, out, blend_color_exclusion_float);
+ break;
+ default:
+ break;
+ }
+}
+
+static void do_blend_effect_byte(
+ float facf0, float facf1, int x, int y,
+ unsigned char *rect1, unsigned char *rect2, int btype, unsigned char *out)
+{
+ switch (btype) {
+ case SEQ_TYPE_ADD:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_add_byte);
+ break;
+ case SEQ_TYPE_SUB:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_sub_byte);
+ break;
+ case SEQ_TYPE_MUL:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_mul_byte);
+ break;
+ case SEQ_TYPE_DARKEN:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_darken_byte);
+ break;
+ case SEQ_TYPE_BURN:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_burn_byte);
+ break;
+ case SEQ_TYPE_LINEAR_BURN:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_linearburn_byte);
+ break;
+ case SEQ_TYPE_SCREEN:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_screen_byte);
+ break;
+ case SEQ_TYPE_LIGHTEN:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_lighten_byte);
+ break;
+ case SEQ_TYPE_DODGE:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_dodge_byte);
+ break;
+ case SEQ_TYPE_OVERLAY:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_overlay_byte);
+ break;
+ case SEQ_TYPE_SOFT_LIGHT:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_softlight_byte);
+ break;
+ case SEQ_TYPE_HARD_LIGHT:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_hardlight_byte);
+ break;
+ case SEQ_TYPE_PIN_LIGHT:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_pinlight_byte);
+ break;
+ case SEQ_TYPE_LIN_LIGHT:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_linearlight_byte);
+ break;
+ case SEQ_TYPE_VIVID_LIGHT:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_vividlight_byte);
+ break;
+ case SEQ_TYPE_BLEND_COLOR:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_color_byte);
+ break;
+ case SEQ_TYPE_HUE:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_hue_byte);
+ break;
+ case SEQ_TYPE_SATURATION:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_saturation_byte);
+ break;
+ case SEQ_TYPE_VALUE:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_luminosity_byte);
+ break;
+ case SEQ_TYPE_DIFFERENCE:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_difference_byte);
+ break;
+ case SEQ_TYPE_EXCLUSION:
+ apply_blend_function_byte(facf0, facf1, x, y, rect1, rect2, out, blend_color_exclusion_byte);
+ break;
+ default:
+ break;
+ }
+}
+
+static void do_blend_mode_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+{
+ if (out->rect_float) {
+ float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
+ slice_get_float_buffers(context, ibuf1, ibuf2, NULL, out, start_line, &rect1, &rect2, NULL, &rect_out);
+ do_blend_effect_float(facf0, facf1, context->rectx, total_lines, rect1, rect2, seq->blend_mode, rect_out);
+ }
+ else {
+ unsigned char *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
+ slice_get_byte_buffers(context, ibuf1, ibuf2, NULL, out, start_line, &rect1, &rect2, NULL, &rect_out);
+ do_blend_effect_byte(facf0, facf1, context->rectx, total_lines, rect1, rect2, seq->blend_mode, rect_out);
+ }
+}
+/*********************** Color Mix Effect *************************/
+static void init_colormix_effect(Sequence *seq)
+{
+ ColorMixVars *data;
+
+ if (seq->effectdata) {
+ MEM_freeN(seq->effectdata);
+ }
+ seq->effectdata = MEM_callocN(sizeof(ColorMixVars), "colormixvars");
+ data = (ColorMixVars *) seq->effectdata;
+ data->blend_effect = SEQ_TYPE_OVERLAY;
+ data->factor = 1.0f;
+}
+
+static void do_colormix_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float UNUSED(facf0), float UNUSED(facf1),
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+{
+ float facf;
+
+ ColorMixVars *data = seq->effectdata;
+ facf = data->factor;
+
+ if (out->rect_float) {
+ float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
+ slice_get_float_buffers(context, ibuf1, ibuf2, NULL, out, start_line, &rect1, &rect2, NULL, &rect_out);
+ do_blend_effect_float(facf, facf, context->rectx, total_lines, rect1, rect2, data->blend_effect, rect_out);
+ }
+ else {
+ unsigned char *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
+ slice_get_byte_buffers(context, ibuf1, ibuf2, NULL, out, start_line, &rect1, &rect2, NULL, &rect_out);
+ do_blend_effect_byte(facf, facf, context->rectx, total_lines, rect1, rect2, data->blend_effect, rect_out);
+ }
+}
+
/*********************** Wipe *************************/
typedef struct WipeZone {
@@ -1453,12 +1767,13 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f
if (output != output) output = 1;
if (wipe->forward) output = 1 - output;
break;
- /* BOX WIPE IS NOT WORKING YET */
+ /* BOX WIPE IS NOT WORKING YET */
/* case DO_CROSS_WIPE: */
/* BOX WIPE IS NOT WORKING YET */
#if 0
case DO_BOX_WIPE:
- if (invert) facf0 = 1 - facf0;
+ if (!wipe->forward)
+ facf0 = 1.0f - facf0; /* Go the other direction */
width = (int)(wipe->edgeWidth * ((xo + yo) / 2.0));
hwidth = (float)width / 2.0;
@@ -1476,22 +1791,23 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f
if (b2 < b1 && b2 < b3) {
if (hwidth < pointdist)
- output = in_band(wipezone, hwidth, hyp, facf0, 0, 1);
+ output = in_band(hwidth, hyp, 0, 1);
}
else if (b2 > b1 && b2 > b3) {
if (hwidth < pointdist)
- output = in_band(wipezone, hwidth, hyp2, facf0, 0, 1);
+ output = in_band(hwidth, hyp2, 0, 1);
}
else {
if (hyp < hwidth && hyp2 > hwidth)
- output = in_band(wipezone, hwidth, hyp, facf0, 1, 1);
+ output = in_band(hwidth, hyp, 1, 1);
else if (hyp > hwidth && hyp2 < hwidth)
- output = in_band(wipezone, hwidth, hyp2, facf0, 1, 1);
+ output = in_band(hwidth, hyp2, 1, 1);
else
- output = in_band(wipezone, hwidth, hyp2, facf0, 1, 1) * in_band(wipezone, hwidth, hyp, facf0, 1, 1);
+ output = in_band(hwidth, hyp2, 1, 1) * in_band(hwidth, hyp, 1, 1);
}
- if (invert) facf0 = 1 - facf0;
+ if (!wipe->forward)
+ facf0 = 1.0f - facf0; /* Go the other direction */
angle = -1 / angle;
b1 = posy / 2 - (-angle) * posx / 2;
b3 = (yo - posy / 2) - (-angle) * (xo - posx / 2);
@@ -1502,19 +1818,19 @@ static float check_zone(WipeZone *wipezone, int x, int y, Sequence *seq, float f
if (b2 < b1 && b2 < b3) {
if (hwidth < pointdist)
- output *= in_band(wipezone, hwidth, hyp, facf0, 0, 1);
+ output *= in_band(hwidth, hyp, 0, 1);
}
else if (b2 > b1 && b2 > b3) {
if (hwidth < pointdist)
- output *= in_band(wipezone, hwidth, hyp2, facf0, 0, 1);
+ output *= in_band(hwidth, hyp2, 0, 1);
}
else {
if (hyp < hwidth && hyp2 > hwidth)
- output *= in_band(wipezone, hwidth, hyp, facf0, 1, 1);
+ output *= in_band(hwidth, hyp, 1, 1);
else if (hyp > hwidth && hyp2 < hwidth)
- output *= in_band(wipezone, hwidth, hyp2, facf0, 1, 1);
+ output *= in_band(hwidth, hyp2, 1, 1);
else
- output *= in_band(wipezone, hwidth, hyp2, facf0, 1, 1) * in_band(wipezone, hwidth, hyp, facf0, 1, 1);
+ output *= in_band(hwidth, hyp2, 1, 1) * in_band(hwidth, hyp, 1, 1);
}
break;
@@ -1570,8 +1886,9 @@ static void copy_wipe_effect(Sequence *dst, Sequence *src)
dst->effectdata = MEM_dupallocN(src->effectdata);
}
-static void do_wipe_effect_byte(Sequence *seq, float facf0, float UNUSED(facf1), int x, int y, unsigned char *rect1,
- unsigned char *rect2, unsigned char *out)
+static void do_wipe_effect_byte(
+ Sequence *seq, float facf0, float UNUSED(facf1), int x, int y,
+ unsigned char *rect1, unsigned char *rect2, unsigned char *out)
{
WipeZone wipezone;
WipeVars *wipe = (WipeVars *)seq->effectdata;
@@ -1636,8 +1953,9 @@ static void do_wipe_effect_byte(Sequence *seq, float facf0, float UNUSED(facf1),
}
}
-static void do_wipe_effect_float(Sequence *seq, float facf0, float UNUSED(facf1), int x, int y, float *rect1,
- float *rect2, float *out)
+static void do_wipe_effect_float(
+ Sequence *seq, float facf0, float UNUSED(facf1), int x, int y,
+ float *rect1, float *rect2, float *out)
{
WipeZone wipezone;
WipeVars *wipe = (WipeVars *)seq->effectdata;
@@ -1695,18 +2013,21 @@ static void do_wipe_effect_float(Sequence *seq, float facf0, float UNUSED(facf1)
}
}
-static ImBuf *do_wipe_effect(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_wipe_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
if (out->rect_float) {
- do_wipe_effect_float(seq, facf0, facf1, context->rectx, context->recty, ibuf1->rect_float,
- ibuf2->rect_float, out->rect_float);
+ do_wipe_effect_float(
+ seq, facf0, facf1, context->rectx, context->recty, ibuf1->rect_float,
+ ibuf2->rect_float, out->rect_float);
}
else {
- do_wipe_effect_byte(seq, facf0, facf1, context->rectx, context->recty, (unsigned char *) ibuf1->rect,
- (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
+ do_wipe_effect_byte(
+ seq, facf0, facf1, context->rectx, context->recty, (unsigned char *) ibuf1->rect,
+ (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
}
return out;
@@ -1754,8 +2075,9 @@ static void copy_transform_effect(Sequence *dst, Sequence *src)
dst->effectdata = MEM_dupallocN(src->effectdata);
}
-static void transform_image(int x, int y, ImBuf *ibuf1, ImBuf *out, float scale_x, float scale_y,
- float translate_x, float translate_y, float rotate, int interpolation)
+static void transform_image(
+ int x, int y, ImBuf *ibuf1, ImBuf *out, float scale_x, float scale_y,
+ float translate_x, float translate_y, float rotate, int interpolation)
{
int xo, yo, xi, yi;
float xt, yt, xr, yr;
@@ -1835,8 +2157,9 @@ static void do_transform(Scene *scene, Sequence *seq, float UNUSED(facf0), int x
}
-static ImBuf *do_transform_effect(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0,
- float UNUSED(facf1), ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_transform_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0,
+ float UNUSED(facf1), ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
@@ -1861,7 +2184,7 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i
float *filter = NULL;
int x, y, i, fx, fy;
int index, ix, halfWidth;
- float fval, k, curColor[3], curColor2[3], weight = 0;
+ float fval, k, curColor[4], curColor2[4], weight = 0;
/* If we're not really blurring, bail out */
if (blur <= 0)
@@ -1906,47 +2229,38 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i
for (y = 0; y < height; y++) {
/* Do the left & right strips */
for (x = 0; x < halfWidth; x++) {
- index = (x + y * width) * 4;
fx = 0;
- curColor[0] = curColor[1] = curColor[2] = 0.0f;
- curColor2[0] = curColor2[1] = curColor2[2] = 0.0f;
+ zero_v4(curColor);
+ zero_v4(curColor2);
for (i = x - halfWidth; i < x + halfWidth; i++) {
if ((i >= 0) && (i < width)) {
- curColor[0] += map[(i + y * width) * 4 + GlowR] * filter[fx];
- curColor[1] += map[(i + y * width) * 4 + GlowG] * filter[fx];
- curColor[2] += map[(i + y * width) * 4 + GlowB] * filter[fx];
+ index = (i + y * width) * 4;
+ madd_v4_v4fl(curColor, map + index, filter[fx]);
- curColor2[0] += map[(width - 1 - i + y * width) * 4 + GlowR] * filter[fx];
- curColor2[1] += map[(width - 1 - i + y * width) * 4 + GlowG] * filter[fx];
- curColor2[2] += map[(width - 1 - i + y * width) * 4 + GlowB] * filter[fx];
+ index = (width - 1 - i + y * width) * 4;
+ madd_v4_v4fl(curColor2, map + index, filter[fx]);
}
fx++;
}
- temp[index + GlowR] = curColor[0];
- temp[index + GlowG] = curColor[1];
- temp[index + GlowB] = curColor[2];
-
- temp[((width - 1 - x + y * width) * 4) + GlowR] = curColor2[0];
- temp[((width - 1 - x + y * width) * 4) + GlowG] = curColor2[1];
- temp[((width - 1 - x + y * width) * 4) + GlowB] = curColor2[2];
+ index = (x + y * width) * 4;
+ copy_v4_v4(temp + index, curColor);
+ index = (width - 1 - x + y * width) * 4;
+ copy_v4_v4(temp + index, curColor2);
}
/* Do the main body */
for (x = halfWidth; x < width - halfWidth; x++) {
- index = (x + y * width) * 4;
fx = 0;
- zero_v3(curColor);
+ zero_v4(curColor);
for (i = x - halfWidth; i < x + halfWidth; i++) {
- curColor[0] += map[(i + y * width) * 4 + GlowR] * filter[fx];
- curColor[1] += map[(i + y * width) * 4 + GlowG] * filter[fx];
- curColor[2] += map[(i + y * width) * 4 + GlowB] * filter[fx];
+ index = (i + y * width) * 4;
+ madd_v4_v4fl(curColor, map + index, filter[fx]);
fx++;
}
- temp[index + GlowR] = curColor[0];
- temp[index + GlowG] = curColor[1];
- temp[index + GlowB] = curColor[2];
+ index = (x + y * width) * 4;
+ copy_v4_v4(temp + index, curColor);
}
}
@@ -1957,46 +2271,39 @@ static void RVBlurBitmap2_float(float *map, int width, int height, float blur, i
for (x = 0; x < width; x++) {
/* Do the top & bottom strips */
for (y = 0; y < halfWidth; y++) {
- index = (x + y * width) * 4;
fy = 0;
- zero_v3(curColor);
- zero_v3(curColor2);
+ zero_v4(curColor);
+ zero_v4(curColor2);
for (i = y - halfWidth; i < y + halfWidth; i++) {
if ((i >= 0) && (i < height)) {
/* Bottom */
- curColor[0] += map[(x + i * width) * 4 + GlowR] * filter[fy];
- curColor[1] += map[(x + i * width) * 4 + GlowG] * filter[fy];
- curColor[2] += map[(x + i * width) * 4 + GlowB] * filter[fy];
+ index = (x + i * width) * 4;
+ madd_v4_v4fl(curColor, map + index, filter[fy]);
/* Top */
- curColor2[0] += map[(x + (height - 1 - i) * width) * 4 + GlowR] * filter[fy];
- curColor2[1] += map[(x + (height - 1 - i) * width) * 4 + GlowG] * filter[fy];
- curColor2[2] += map[(x + (height - 1 - i) * width) * 4 + GlowB] * filter[fy];
+ index = (x + (height - 1 - i) * width) * 4;
+ madd_v4_v4fl(curColor2, map + index, filter[fy]);
}
fy++;
}
- temp[index + GlowR] = curColor[0];
- temp[index + GlowG] = curColor[1];
- temp[index + GlowB] = curColor[2];
- temp[((x + (height - 1 - y) * width) * 4) + GlowR] = curColor2[0];
- temp[((x + (height - 1 - y) * width) * 4) + GlowG] = curColor2[1];
- temp[((x + (height - 1 - y) * width) * 4) + GlowB] = curColor2[2];
+ index = (x + y * width) * 4;
+ copy_v4_v4(temp + index, curColor);
+
+ index = (x + (height - 1 - y) * width) * 4;
+ copy_v4_v4(temp + index, curColor2);
}
/* Do the main body */
for (y = halfWidth; y < height - halfWidth; y++) {
- index = (x + y * width) * 4;
fy = 0;
- zero_v3(curColor);
+ zero_v4(curColor);
for (i = y - halfWidth; i < y + halfWidth; i++) {
- curColor[0] += map[(x + i * width) * 4 + GlowR] * filter[fy];
- curColor[1] += map[(x + i * width) * 4 + GlowG] * filter[fy];
- curColor[2] += map[(x + i * width) * 4 + GlowB] * filter[fy];
+ index = (x + i * width) * 4;
+ madd_v4_v4fl(curColor, map + index, filter[fy]);
fy++;
}
- temp[index + GlowR] = curColor[0];
- temp[index + GlowG] = curColor[1];
- temp[index + GlowB] = curColor[2];
+ index = (x + y * width) * 4;
+ copy_v4_v4(temp + index, curColor);
}
}
@@ -2015,15 +2322,17 @@ static void RVAddBitmaps_float(float *a, float *b, float *c, int width, int heig
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
index = (x + y * width) * 4;
- c[index + GlowR] = MIN2(1.0f, a[index + GlowR] + b[index + GlowR]);
- c[index + GlowG] = MIN2(1.0f, a[index + GlowG] + b[index + GlowG]);
- c[index + GlowB] = MIN2(1.0f, a[index + GlowB] + b[index + GlowB]);
- c[index + GlowA] = MIN2(1.0f, a[index + GlowA] + b[index + GlowA]);
+ c[index + GlowR] = min_ff(1.0f, a[index + GlowR] + b[index + GlowR]);
+ c[index + GlowG] = min_ff(1.0f, a[index + GlowG] + b[index + GlowG]);
+ c[index + GlowB] = min_ff(1.0f, a[index + GlowB] + b[index + GlowB]);
+ c[index + GlowA] = min_ff(1.0f, a[index + GlowA] + b[index + GlowA]);
}
}
}
-static void RVIsolateHighlights_float(float *in, float *out, int width, int height, float threshold, float boost, float clamp)
+static void RVIsolateHighlights_float(
+ float *in, float *out, int width, int height,
+ float threshold, float boost, float clamp)
{
int x, y, index;
float intensity;
@@ -2035,10 +2344,10 @@ static void RVIsolateHighlights_float(float *in, float *out, int width, int heig
/* Isolate the intensity */
intensity = (in[index + GlowR] + in[index + GlowG] + in[index + GlowB] - threshold);
if (intensity > 0) {
- out[index + GlowR] = MIN2(clamp, (in[index + GlowR] * boost * intensity));
- out[index + GlowG] = MIN2(clamp, (in[index + GlowG] * boost * intensity));
- out[index + GlowB] = MIN2(clamp, (in[index + GlowB] * boost * intensity));
- out[index + GlowA] = MIN2(clamp, (in[index + GlowA] * boost * intensity));
+ out[index + GlowR] = min_ff(clamp, (in[index + GlowR] * boost * intensity));
+ out[index + GlowG] = min_ff(clamp, (in[index + GlowG] * boost * intensity));
+ out[index + GlowB] = min_ff(clamp, (in[index + GlowB] * boost * intensity));
+ out[index + GlowA] = min_ff(clamp, (in[index + GlowA] * boost * intensity));
}
else {
out[index + GlowR] = 0;
@@ -2086,8 +2395,9 @@ static void copy_glow_effect(Sequence *dst, Sequence *src)
dst->effectdata = MEM_dupallocN(src->effectdata);
}
-static void do_glow_effect_byte(Sequence *seq, int render_size, float facf0, float UNUSED(facf1), int x, int y,
- unsigned char *rect1, unsigned char *UNUSED(rect2), unsigned char *out)
+static void do_glow_effect_byte(
+ Sequence *seq, int render_size, float facf0, float UNUSED(facf1), int x, int y,
+ unsigned char *rect1, unsigned char *UNUSED(rect2), unsigned char *out)
{
float *outbuf, *inbuf;
GlowVars *glow = (GlowVars *)seq->effectdata;
@@ -2110,8 +2420,9 @@ static void do_glow_effect_byte(Sequence *seq, int render_size, float facf0, flo
MEM_freeN(outbuf);
}
-static void do_glow_effect_float(Sequence *seq, int render_size, float facf0, float UNUSED(facf1), int x, int y,
- float *rect1, float *UNUSED(rect2), float *out)
+static void do_glow_effect_float(
+ Sequence *seq, int render_size, float facf0, float UNUSED(facf1), int x, int y,
+ float *rect1, float *UNUSED(rect2), float *out)
{
float *outbuf = out;
float *inbuf = rect1;
@@ -2123,20 +2434,23 @@ static void do_glow_effect_float(Sequence *seq, int render_size, float facf0, fl
RVAddBitmaps_float(inbuf, outbuf, outbuf, x, y);
}
-static ImBuf *do_glow_effect(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_glow_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
int render_size = 100 * context->rectx / context->scene->r.xsch;
if (out->rect_float) {
- do_glow_effect_float(seq, render_size, facf0, facf1, context->rectx, context->recty,
- ibuf1->rect_float, ibuf2->rect_float, out->rect_float);
+ do_glow_effect_float(
+ seq, render_size, facf0, facf1, context->rectx, context->recty,
+ ibuf1->rect_float, ibuf2->rect_float, out->rect_float);
}
else {
- do_glow_effect_byte(seq, render_size, facf0, facf1, context->rectx, context->recty,
- (unsigned char *) ibuf1->rect, (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
+ do_glow_effect_byte(
+ seq, render_size, facf0, facf1, context->rectx, context->recty,
+ (unsigned char *) ibuf1->rect, (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
}
return out;
@@ -2180,8 +2494,9 @@ static int early_out_color(Sequence *UNUSED(seq), float UNUSED(facf0), float UNU
return EARLY_NO_INPUT;
}
-static ImBuf *do_solid_color(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_solid_color(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
@@ -2273,8 +2588,9 @@ static int early_out_multicam(Sequence *UNUSED(seq), float UNUSED(facf0), float
return EARLY_NO_INPUT;
}
-static ImBuf *do_multicam(const SeqRenderData *context, Sequence *seq, float cfra, float UNUSED(facf0), float UNUSED(facf1),
- ImBuf *UNUSED(ibuf1), ImBuf *UNUSED(ibuf2), ImBuf *UNUSED(ibuf3))
+static ImBuf *do_multicam(
+ const SeqRenderData *context, Sequence *seq, float cfra, float UNUSED(facf0), float UNUSED(facf1),
+ ImBuf *UNUSED(ibuf1), ImBuf *UNUSED(ibuf2), ImBuf *UNUSED(ibuf3))
{
ImBuf *i;
ImBuf *out;
@@ -2355,8 +2671,9 @@ static ImBuf *do_adjustment_impl(const SeqRenderData *context, Sequence *seq, fl
return i;
}
-static ImBuf *do_adjustment(const SeqRenderData *context, Sequence *seq, float cfra, float UNUSED(facf0), float UNUSED(facf1),
- ImBuf *UNUSED(ibuf1), ImBuf *UNUSED(ibuf2), ImBuf *UNUSED(ibuf3))
+static ImBuf *do_adjustment(
+ const SeqRenderData *context, Sequence *seq, float cfra, float UNUSED(facf0), float UNUSED(facf1),
+ ImBuf *UNUSED(ibuf1), ImBuf *UNUSED(ibuf2), ImBuf *UNUSED(ibuf3))
{
ImBuf *i = NULL;
ImBuf *out;
@@ -2571,26 +2888,30 @@ void BKE_sequence_effect_speed_rebuild_map(Scene *scene, Sequence *seq, bool for
}
}
-static ImBuf *do_speed_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
- float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_speed_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra),
+ float facf0, float facf1, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
if (out->rect_float) {
- do_cross_effect_float(facf0, facf1, context->rectx, context->recty,
- ibuf1->rect_float, ibuf2->rect_float, out->rect_float);
+ do_cross_effect_float(
+ facf0, facf1, context->rectx, context->recty,
+ ibuf1->rect_float, ibuf2->rect_float, out->rect_float);
}
else {
- do_cross_effect_byte(facf0, facf1, context->rectx, context->recty,
- (unsigned char *) ibuf1->rect, (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
+ do_cross_effect_byte(
+ facf0, facf1, context->rectx, context->recty,
+ (unsigned char *) ibuf1->rect, (unsigned char *) ibuf2->rect, (unsigned char *) out->rect);
}
return out;
}
/*********************** overdrop *************************/
-static void do_overdrop_effect(const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
+static void do_overdrop_effect(
+ const SeqRenderData *context, Sequence *UNUSED(seq), float UNUSED(cfra), float facf0, float facf1,
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *UNUSED(ibuf3), int start_line, int total_lines, ImBuf *out)
{
int x = context->rectx;
int y = total_lines;
@@ -2684,13 +3005,14 @@ static float *make_gaussian_blur_kernel(float rad, int size)
return gausstab;
}
-static void do_gaussian_blur_effect_byte_x(Sequence *seq,
- int start_line,
- int x, int y,
- int frame_width,
- int UNUSED(frame_height),
- unsigned char *rect,
- unsigned char *out)
+static void do_gaussian_blur_effect_byte_x(
+ Sequence *seq,
+ int start_line,
+ int x, int y,
+ int frame_width,
+ int UNUSED(frame_height),
+ unsigned char *rect,
+ unsigned char *out)
{
#define INDEX(_x, _y) (((_y) * (x) + (_x)) * 4)
GaussianBlurVars *data = seq->effectdata;
@@ -2736,13 +3058,14 @@ static void do_gaussian_blur_effect_byte_x(Sequence *seq,
#undef INDEX
}
-static void do_gaussian_blur_effect_byte_y(Sequence *seq,
- int start_line,
- int x, int y,
- int UNUSED(frame_width),
- int frame_height,
- unsigned char *rect,
- unsigned char *out)
+static void do_gaussian_blur_effect_byte_y(
+ Sequence *seq,
+ int start_line,
+ int x, int y,
+ int UNUSED(frame_width),
+ int frame_height,
+ unsigned char *rect,
+ unsigned char *out)
{
#define INDEX(_x, _y) (((_y) * (x) + (_x)) * 4)
GaussianBlurVars *data = seq->effectdata;
@@ -2788,13 +3111,14 @@ static void do_gaussian_blur_effect_byte_y(Sequence *seq,
#undef INDEX
}
-static void do_gaussian_blur_effect_float_x(Sequence *seq,
- int start_line,
- int x, int y,
- int frame_width,
- int UNUSED(frame_height),
- float *rect,
- float *out)
+static void do_gaussian_blur_effect_float_x(
+ Sequence *seq,
+ int start_line,
+ int x, int y,
+ int frame_width,
+ int UNUSED(frame_height),
+ float *rect,
+ float *out)
{
#define INDEX(_x, _y) (((_y) * (x) + (_x)) * 4)
GaussianBlurVars *data = seq->effectdata;
@@ -2831,13 +3155,14 @@ static void do_gaussian_blur_effect_float_x(Sequence *seq,
#undef INDEX
}
-static void do_gaussian_blur_effect_float_y(Sequence *seq,
- int start_line,
- int x, int y,
- int UNUSED(frame_width),
- int frame_height,
- float *rect,
- float *out)
+static void do_gaussian_blur_effect_float_y(
+ Sequence *seq,
+ int start_line,
+ int x, int y,
+ int UNUSED(frame_width),
+ int frame_height,
+ float *rect,
+ float *out)
{
#define INDEX(_x, _y) (((_y) * (x) + (_x)) * 4)
GaussianBlurVars *data = seq->effectdata;
@@ -2876,113 +3201,123 @@ static void do_gaussian_blur_effect_float_y(Sequence *seq,
#undef INDEX
}
-static void do_gaussian_blur_effect_x_cb(const SeqRenderData *context,
- Sequence *seq,
- ImBuf *ibuf,
- int start_line,
- int total_lines,
- ImBuf *out)
+static void do_gaussian_blur_effect_x_cb(
+ const SeqRenderData *context,
+ Sequence *seq,
+ ImBuf *ibuf,
+ int start_line,
+ int total_lines,
+ ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
- slice_get_float_buffers(context,
- ibuf,
- NULL,
- NULL,
- out,
- start_line,
- &rect1,
- &rect2,
- NULL,
- &rect_out);
-
- do_gaussian_blur_effect_float_x(seq,
- start_line,
- context->rectx,
- total_lines,
- context->rectx,
- context->recty,
- ibuf->rect_float,
- rect_out);
+ slice_get_float_buffers(
+ context,
+ ibuf,
+ NULL,
+ NULL,
+ out,
+ start_line,
+ &rect1,
+ &rect2,
+ NULL,
+ &rect_out);
+
+ do_gaussian_blur_effect_float_x(
+ seq,
+ start_line,
+ context->rectx,
+ total_lines,
+ context->rectx,
+ context->recty,
+ ibuf->rect_float,
+ rect_out);
}
else {
unsigned char *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
- slice_get_byte_buffers(context,
- ibuf,
- NULL,
- NULL,
- out,
- start_line,
- &rect1,
- &rect2,
- NULL,
- &rect_out);
-
- do_gaussian_blur_effect_byte_x(seq,
- start_line,
- context->rectx,
- total_lines,
- context->rectx,
- context->recty,
- (unsigned char *) ibuf->rect,
- rect_out);
- }
-}
-
-static void do_gaussian_blur_effect_y_cb(const SeqRenderData *context,
- Sequence *seq,
- ImBuf *ibuf,
- int start_line,
- int total_lines,
- ImBuf *out)
+ slice_get_byte_buffers(
+ context,
+ ibuf,
+ NULL,
+ NULL,
+ out,
+ start_line,
+ &rect1,
+ &rect2,
+ NULL,
+ &rect_out);
+
+ do_gaussian_blur_effect_byte_x(
+ seq,
+ start_line,
+ context->rectx,
+ total_lines,
+ context->rectx,
+ context->recty,
+ (unsigned char *) ibuf->rect,
+ rect_out);
+ }
+}
+
+static void do_gaussian_blur_effect_y_cb(
+ const SeqRenderData *context,
+ Sequence *seq,
+ ImBuf *ibuf,
+ int start_line,
+ int total_lines,
+ ImBuf *out)
{
if (out->rect_float) {
float *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
- slice_get_float_buffers(context,
- ibuf,
- NULL,
- NULL,
- out,
- start_line,
- &rect1,
- &rect2,
- NULL,
- &rect_out);
-
- do_gaussian_blur_effect_float_y(seq,
- start_line,
- context->rectx,
- total_lines,
- context->rectx,
- context->recty,
- ibuf->rect_float,
- rect_out);
+ slice_get_float_buffers(
+ context,
+ ibuf,
+ NULL,
+ NULL,
+ out,
+ start_line,
+ &rect1,
+ &rect2,
+ NULL,
+ &rect_out);
+
+ do_gaussian_blur_effect_float_y(
+ seq,
+ start_line,
+ context->rectx,
+ total_lines,
+ context->rectx,
+ context->recty,
+ ibuf->rect_float,
+ rect_out);
}
else {
unsigned char *rect1 = NULL, *rect2 = NULL, *rect_out = NULL;
- slice_get_byte_buffers(context,
- ibuf,
- NULL,
- NULL,
- out,
- start_line,
- &rect1,
- &rect2,
- NULL,
- &rect_out);
-
- do_gaussian_blur_effect_byte_y(seq,
- start_line,
- context->rectx,
- total_lines,
- context->rectx,
- context->recty,
- (unsigned char *) ibuf->rect,
- rect_out);
+ slice_get_byte_buffers(
+ context,
+ ibuf,
+ NULL,
+ NULL,
+ out,
+ start_line,
+ &rect1,
+ &rect2,
+ NULL,
+ &rect_out);
+
+ do_gaussian_blur_effect_byte_y(
+ seq,
+ start_line,
+ context->rectx,
+ total_lines,
+ context->rectx,
+ context->recty,
+ (unsigned char *) ibuf->rect,
+ rect_out);
}
}
@@ -3001,10 +3336,11 @@ typedef struct RenderGaussianBlurEffectThread {
int start_line, tot_line;
} RenderGaussianBlurEffectThread;
-static void render_effect_execute_init_handle(void *handle_v,
- int start_line,
- int tot_line,
- void *init_data_v)
+static void render_effect_execute_init_handle(
+ void *handle_v,
+ int start_line,
+ int tot_line,
+ void *init_data_v)
{
RenderGaussianBlurEffectThread *handle = (RenderGaussianBlurEffectThread *) handle_v;
RenderGaussianBlurEffectInitData *init_data = (RenderGaussianBlurEffectInitData *) init_data_v;
@@ -3021,36 +3357,39 @@ static void render_effect_execute_init_handle(void *handle_v,
static void *render_effect_execute_do_x_thread(void *thread_data_v)
{
RenderGaussianBlurEffectThread *thread_data = (RenderGaussianBlurEffectThread *) thread_data_v;
- do_gaussian_blur_effect_x_cb(thread_data->context,
- thread_data->seq,
- thread_data->ibuf,
- thread_data->start_line,
- thread_data->tot_line,
- thread_data->out);
+ do_gaussian_blur_effect_x_cb(
+ thread_data->context,
+ thread_data->seq,
+ thread_data->ibuf,
+ thread_data->start_line,
+ thread_data->tot_line,
+ thread_data->out);
return NULL;
}
static void *render_effect_execute_do_y_thread(void *thread_data_v)
{
RenderGaussianBlurEffectThread *thread_data = (RenderGaussianBlurEffectThread *) thread_data_v;
- do_gaussian_blur_effect_y_cb(thread_data->context,
- thread_data->seq,
- thread_data->ibuf,
- thread_data->start_line,
- thread_data->tot_line,
- thread_data->out);
+ do_gaussian_blur_effect_y_cb(
+ thread_data->context,
+ thread_data->seq,
+ thread_data->ibuf,
+ thread_data->start_line,
+ thread_data->tot_line,
+ thread_data->out);
return NULL;
}
-static ImBuf *do_gaussian_blur_effect(const SeqRenderData *context,
- Sequence *seq,
- float UNUSED(cfra),
- float UNUSED(facf0),
- float UNUSED(facf1),
- ImBuf *ibuf1,
- ImBuf *UNUSED(ibuf2),
- ImBuf *UNUSED(ibuf3))
+static ImBuf *do_gaussian_blur_effect(
+ const SeqRenderData *context,
+ Sequence *seq,
+ float UNUSED(cfra),
+ float UNUSED(facf0),
+ float UNUSED(facf1),
+ ImBuf *ibuf1,
+ ImBuf *UNUSED(ibuf2),
+ ImBuf *UNUSED(ibuf3))
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, NULL, NULL);
@@ -3061,22 +3400,24 @@ static ImBuf *do_gaussian_blur_effect(const SeqRenderData *context,
init_data.ibuf = ibuf1;
init_data.out = out;
- IMB_processor_apply_threaded(out->y,
- sizeof(RenderGaussianBlurEffectThread),
- &init_data,
- render_effect_execute_init_handle,
- render_effect_execute_do_x_thread);
+ IMB_processor_apply_threaded(
+ out->y,
+ sizeof(RenderGaussianBlurEffectThread),
+ &init_data,
+ render_effect_execute_init_handle,
+ render_effect_execute_do_x_thread);
ibuf1 = out;
init_data.ibuf = ibuf1;
out = prepare_effect_imbufs(context, ibuf1, NULL, NULL);
init_data.out = out;
- IMB_processor_apply_threaded(out->y,
- sizeof(RenderGaussianBlurEffectThread),
- &init_data,
- render_effect_execute_init_handle,
- render_effect_execute_do_y_thread);
+ IMB_processor_apply_threaded(
+ out->y,
+ sizeof(RenderGaussianBlurEffectThread),
+ &init_data,
+ render_effect_execute_init_handle,
+ render_effect_execute_do_y_thread);
IMB_freeImBuf(ibuf1);
@@ -3120,8 +3461,9 @@ static int early_out_text(Sequence *seq, float UNUSED(facf0), float UNUSED(facf1
return EARLY_NO_INPUT;
}
-static ImBuf *do_text_effect(const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float UNUSED(facf0), float UNUSED(facf1),
- ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
+static ImBuf *do_text_effect(
+ const SeqRenderData *context, Sequence *seq, float UNUSED(cfra), float UNUSED(facf0), float UNUSED(facf1),
+ ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *ibuf3)
{
ImBuf *out = prepare_effect_imbufs(context, ibuf1, ibuf2, ibuf3);
TextVars *data = seq->effectdata;
@@ -3352,6 +3694,36 @@ static struct SeqEffectHandle get_sequence_effect_impl(int seq_type)
rval.execute_slice = do_mul_effect;
rval.early_out = early_out_mul_input2;
break;
+ case SEQ_TYPE_SCREEN:
+ case SEQ_TYPE_OVERLAY:
+ case SEQ_TYPE_BURN:
+ case SEQ_TYPE_LINEAR_BURN:
+ case SEQ_TYPE_DARKEN:
+ case SEQ_TYPE_LIGHTEN:
+ case SEQ_TYPE_DODGE:
+ case SEQ_TYPE_SOFT_LIGHT:
+ case SEQ_TYPE_HARD_LIGHT:
+ case SEQ_TYPE_PIN_LIGHT:
+ case SEQ_TYPE_LIN_LIGHT:
+ case SEQ_TYPE_VIVID_LIGHT:
+ case SEQ_TYPE_BLEND_COLOR:
+ case SEQ_TYPE_HUE:
+ case SEQ_TYPE_SATURATION:
+ case SEQ_TYPE_VALUE:
+ case SEQ_TYPE_DIFFERENCE:
+ case SEQ_TYPE_EXCLUSION:
+ rval.multithreaded = true;
+ rval.execute_slice = do_blend_mode_effect;
+ rval.early_out = early_out_mul_input2;
+ break;
+ case SEQ_TYPE_COLORMIX:
+ rval.multithreaded = true;
+ rval.init = init_colormix_effect;
+ rval.free = free_effect_default;
+ rval.copy = copy_effect_default;
+ rval.execute_slice = do_colormix_effect;
+ rval.early_out = early_out_mul_input2;
+ break;
case SEQ_TYPE_ALPHAOVER:
rval.multithreaded = true;
rval.init = init_alpha_over_or_under;
diff --git a/source/blender/blenkernel/intern/seqmodifier.c b/source/blender/blenkernel/intern/seqmodifier.c
index 89c2f76c661..e2f74dbab3c 100644
--- a/source/blender/blenkernel/intern/seqmodifier.c
+++ b/source/blender/blenkernel/intern/seqmodifier.c
@@ -202,21 +202,22 @@ static void whiteBalance_apply_threaded(int width, int height, unsigned char *re
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
int pixel_index = (y * width + x) * 4;
- float result[4], mask[3] = {1.0f, 1.0f, 1.0f};
+ float rgba[4], result[4], mask[3] = {1.0f, 1.0f, 1.0f};
if (rect_float) {
- copy_v3_v3(result, rect_float + pixel_index);
+ copy_v3_v3(rgba, rect_float + pixel_index);
}
else {
- straight_uchar_to_premul_float(result, rect + pixel_index);
+ straight_uchar_to_premul_float(rgba, rect + pixel_index);
}
+ copy_v4_v4(result, rgba);
#if 0
mul_v3_v3(result, multiplier);
#else
/* similar to division without the clipping */
for (int i = 0; i < 3; i++) {
- result[i] = 1.0f - powf(1.0f - result[i], multiplier[i]);
+ result[i] = 1.0f - powf(1.0f - rgba[i], multiplier[i]);
}
#endif
@@ -227,9 +228,9 @@ static void whiteBalance_apply_threaded(int width, int height, unsigned char *re
rgb_uchar_to_float(mask, mask_rect + pixel_index);
}
- result[0] = result[0] * (1.0f - mask[0]) + result[0] * mask[0];
- result[1] = result[1] * (1.0f - mask[1]) + result[1] * mask[1];
- result[2] = result[2] * (1.0f - mask[2]) + result[2] * mask[2];
+ result[0] = rgba[0] * (1.0f - mask[0]) + result[0] * mask[0];
+ result[1] = rgba[1] * (1.0f - mask[1]) + result[1] * mask[1];
+ result[2] = rgba[2] * (1.0f - mask[2]) + result[2] * mask[2];
if (rect_float) {
copy_v3_v3(rect_float + pixel_index, result);
diff --git a/source/blender/blenkernel/intern/sequencer.c b/source/blender/blenkernel/intern/sequencer.c
index 6a491ba5ec4..0cc151c3645 100644
--- a/source/blender/blenkernel/intern/sequencer.c
+++ b/source/blender/blenkernel/intern/sequencer.c
@@ -84,6 +84,7 @@
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
#include "IMB_colormanagement.h"
+#include "IMB_metadata.h"
#include "BKE_context.h"
#include "BKE_sound.h"
@@ -377,6 +378,8 @@ static void seqclipboard_ptr_restore(Main *bmain, ID **id_pt)
}
break;
}
+ default:
+ break;
}
}
@@ -480,9 +483,12 @@ void BKE_sequencer_editing_free(Scene *scene)
static void sequencer_imbuf_assign_spaces(Scene *scene, ImBuf *ibuf)
{
+#if 0
+ /* Bute buffer is supposed to be in sequencer working space already. */
if (ibuf->rect != NULL) {
IMB_colormanagement_assign_rect_colorspace(ibuf, scene->sequencer_colorspace_settings.name);
}
+#endif
if (ibuf->rect_float != NULL) {
IMB_colormanagement_assign_float_colorspace(ibuf, scene->sequencer_colorspace_settings.name);
}
@@ -514,7 +520,7 @@ void BKE_sequencer_imbuf_to_sequencer_space(Scene *scene, ImBuf *ibuf, bool make
* artifacts which will then not happen in final render.
*/
IMB_colormanagement_transform_byte_threaded(
- (unsigned char*)ibuf->rect, ibuf->x, ibuf->y, ibuf->channels,
+ (unsigned char *)ibuf->rect, ibuf->x, ibuf->y, ibuf->channels,
from_colorspace, to_colorspace);
}
else {
@@ -523,7 +529,7 @@ void BKE_sequencer_imbuf_to_sequencer_space(Scene *scene, ImBuf *ibuf, bool make
*/
imb_addrectfloatImBuf(ibuf);
IMB_colormanagement_transform_from_byte_threaded(
- ibuf->rect_float, (unsigned char*)ibuf->rect,
+ ibuf->rect_float, (unsigned char *)ibuf->rect,
ibuf->x, ibuf->y, ibuf->channels,
from_colorspace, to_colorspace);
/* We don't need byte buffer anymore. */
@@ -937,6 +943,8 @@ void BKE_sequence_reload_new_file(Scene *scene, Sequence *seq, const bool lock_r
return;
}
+ IMB_anim_load_metadata(sanim->anim);
+
seq->len = IMB_anim_get_duration(sanim->anim, seq->strip->proxy ? seq->strip->proxy->tc : IMB_TC_RECORD_RUN);
seq->anim_preseek = IMB_anim_get_preseek(sanim->anim);
@@ -1155,6 +1163,7 @@ static const char *give_seqname_by_type(int type)
case SEQ_TYPE_ALPHAOVER: return "Alpha Over";
case SEQ_TYPE_ALPHAUNDER: return "Alpha Under";
case SEQ_TYPE_OVERDROP: return "Over Drop";
+ case SEQ_TYPE_COLORMIX: return "Color Mix";
case SEQ_TYPE_WIPE: return "Wipe";
case SEQ_TYPE_GLOW: return "Glow";
case SEQ_TYPE_TRANSFORM: return "Transform";
@@ -1670,6 +1679,11 @@ static bool seq_proxy_get_fname(Editing *ed, Sequence *seq, int cfra, int render
else if (seq->type == SEQ_TYPE_IMAGE) {
fname[0] = 0;
}
+ else {
+ /* We could make a name here, except non-movie's don't generate proxies,
+ * cancel until other types of sequence strips are supported. */
+ return false;
+ }
BLI_path_append(dir, sizeof(dir), fname);
BLI_path_abs(name, G.main->name);
}
@@ -1775,7 +1789,7 @@ static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int c
if (proxy->anim == NULL) {
return NULL;
}
-
+
seq_open_anim_file(context->scene, seq, true);
sanim = seq->anims.first;
@@ -1783,7 +1797,7 @@ static ImBuf *seq_proxy_fetch(const SeqRenderData *context, Sequence *seq, int c
return IMB_anim_absolute(proxy->anim, frameno, IMB_TC_NONE, IMB_PROXY_NONE);
}
-
+
if (seq_proxy_get_fname(ed, seq, cfra, render_size, name, context->view_id) == 0) {
return NULL;
}
@@ -2082,7 +2096,7 @@ void BKE_sequencer_proxy_set(struct Sequence *seq, bool value)
}
}
else {
- seq->flag ^= SEQ_USE_PROXY;
+ seq->flag &= ~SEQ_USE_PROXY;
}
}
@@ -2944,7 +2958,7 @@ static ImBuf *seq_render_movie_strip(const SeqRenderData *context, Sequence *seq
int totviews;
int i;
- if (totfiles != BLI_listbase_count_ex(&seq->anims, totfiles + 1))
+ if (totfiles != BLI_listbase_count_at_most(&seq->anims, totfiles + 1))
goto monoview_movie;
totviews = BKE_scene_multiview_num_views_get(&context->scene->r);
@@ -3193,11 +3207,12 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
int scemode;
int cfra;
float subframe;
+
#ifdef DURIAN_CAMERA_SWITCH
- ListBase markers;
+ int mode;
#endif
} orig_data;
-
+
/* Old info:
* Hack! This function can be called from do_render_seq(), in that case
* the seq->scene can already have a Render initialized with same name,
@@ -3233,7 +3248,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
const bool is_background = G.background;
const bool do_seq_gl = is_rendering ?
0 /* (context->scene->r.seq_flag & R_SEQ_GL_REND) */ :
- (context->scene->r.seq_flag & R_SEQ_GL_PREV) != 0;
+ (context->scene->r.seq_prev_type) != OB_RENDER;
// bool have_seq = false; /* UNUSED */
bool have_comp = false;
bool use_gpencil = true;
@@ -3257,7 +3272,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
orig_data.cfra = scene->r.cfra;
orig_data.subframe = scene->r.subframe;
#ifdef DURIAN_CAMERA_SWITCH
- orig_data.markers = scene->markers;
+ orig_data.mode = scene->r.mode;
#endif
BKE_scene_frame_set(scene, frame);
@@ -3280,21 +3295,28 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
/* prevent eternal loop */
scene->r.scemode &= ~R_DOSEQ;
-
+
#ifdef DURIAN_CAMERA_SWITCH
/* stooping to new low's in hackyness :( */
- BLI_listbase_clear(&scene->markers);
+ scene->r.mode |= R_NO_CAMERA_SWITCH;
#endif
is_frame_update = (orig_data.cfra != scene->r.cfra) || (orig_data.subframe != scene->r.subframe);
if ((sequencer_view3d_cb && do_seq_gl && camera) && is_thread_main) {
char err_out[256] = "unknown";
- int width = (scene->r.xsch * scene->r.size) / 100;
- int height = (scene->r.ysch * scene->r.size) / 100;
+ const int width = (scene->r.xsch * scene->r.size) / 100;
+ const int height = (scene->r.ysch * scene->r.size) / 100;
const bool use_background = (scene->r.alphamode == R_ADDSKY);
const char *viewname = BKE_scene_multiview_render_view_name_get(&scene->r, context->view_id);
+ unsigned int draw_flags = SEQ_OFSDRAW_NONE;
+ draw_flags |= (use_gpencil) ? SEQ_OFSDRAW_USE_GPENCIL : 0;
+ draw_flags |= (use_background) ? SEQ_OFSDRAW_USE_BACKGROUND : 0;
+ draw_flags |= (context->gpu_full_samples) ? SEQ_OFSDRAW_USE_FULL_SAMPLE : 0;
+ draw_flags |= (context->scene->r.seq_flag & R_SEQ_SOLID_TEX) ? SEQ_OFSDRAW_USE_SOLID_TEX : 0;
+ draw_flags |= (context->scene->r.seq_flag & R_SEQ_CAMERA_DOF) ? SEQ_OFSDRAW_USE_CAMERA_DOF : 0;
+
/* for old scene this can be uninitialized,
* should probably be added to do_versions at some point if the functionality stays */
if (context->scene->r.seq_prev_type == 0)
@@ -3304,18 +3326,15 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
BKE_scene_update_for_newframe(context->eval_ctx, context->bmain, scene, scene->lay);
ibuf = sequencer_view3d_cb(
/* set for OpenGL render (NULL when scrubbing) */
- scene, camera, width, height, IB_rect,
- context->scene->r.seq_prev_type,
- (context->scene->r.seq_flag & R_SEQ_SOLID_TEX) != 0,
- use_gpencil, use_background, scene->r.alphamode,
- context->gpu_samples, context->gpu_full_samples, viewname,
+ scene, camera, width, height, IB_rect, draw_flags, context->scene->r.seq_prev_type,
+ scene->r.alphamode, context->gpu_samples, viewname,
context->gpu_fx, context->gpu_offscreen, err_out);
if (ibuf == NULL) {
fprintf(stderr, "seq_render_scene_strip failed to get opengl buffer: %s\n", err_out);
}
}
else {
- Render *re = RE_GetRender(scene->id.name);
+ Render *re = RE_GetSceneRender(scene);
const int totviews = BKE_scene_multiview_num_views_get(&scene->r);
int i;
ImBuf **ibufs_arr;
@@ -3332,7 +3351,7 @@ static ImBuf *seq_render_scene_strip(const SeqRenderData *context, Sequence *seq
*/
if (!is_thread_main || is_rendering == false || is_background || context->eval_ctx->mode == DAG_EVAL_RENDER) {
if (re == NULL)
- re = RE_NewRender(scene->id.name);
+ re = RE_NewSceneRender(scene);
BKE_scene_update_for_newframe(context->eval_ctx, context->bmain, scene, scene->lay);
RE_BlenderFrame(re, context->bmain, scene, NULL, camera, scene->lay, frame, false);
@@ -3399,7 +3418,7 @@ finally:
#ifdef DURIAN_CAMERA_SWITCH
/* stooping to new low's in hackyness :( */
- scene->markers = orig_data.markers;
+ scene->r.mode &= ~(orig_data.mode & R_NO_CAMERA_SWITCH);
#endif
return ibuf;
@@ -4190,9 +4209,10 @@ static bool update_changed_seq_recurs(Scene *scene, Sequence *seq, Sequence *cha
if (free_imbuf) {
if (ibuf_change) {
- if (seq->type == SEQ_TYPE_MOVIE)
+ if (seq->type == SEQ_TYPE_MOVIE) {
BKE_sequence_free_anim(seq);
- if (seq->type == SEQ_TYPE_SPEED) {
+ }
+ else if (seq->type == SEQ_TYPE_SPEED) {
BKE_sequence_effect_speed_rebuild_map(scene, seq, true);
}
}
@@ -4473,8 +4493,11 @@ Sequence *BKE_sequencer_foreground_frame_get(Scene *scene, int frame)
for (seq = ed->seqbasep->first; seq; seq = seq->next) {
if (seq->flag & SEQ_MUTE || seq->startdisp > frame || seq->enddisp <= frame)
continue;
- /* only use elements you can see - not */
- if (ELEM(seq->type, SEQ_TYPE_IMAGE, SEQ_TYPE_META, SEQ_TYPE_SCENE, SEQ_TYPE_MOVIE, SEQ_TYPE_COLOR)) {
+ /* Only use strips that generate an image, not ones that combine
+ * other strips or apply some effect. */
+ if (ELEM(seq->type, SEQ_TYPE_IMAGE, SEQ_TYPE_META, SEQ_TYPE_SCENE,
+ SEQ_TYPE_MOVIE, SEQ_TYPE_COLOR, SEQ_TYPE_TEXT))
+ {
if (seq->machine > best_machine) {
best_seq = seq;
best_machine = seq->machine;
@@ -5135,6 +5158,40 @@ void BKE_sequence_init_colorspace(Sequence *seq)
}
}
+float BKE_sequence_get_fps(Scene *scene, Sequence *seq)
+{
+ switch (seq->type) {
+ case SEQ_TYPE_MOVIE:
+ {
+ seq_open_anim_file(scene, seq, true);
+ if (BLI_listbase_is_empty(&seq->anims)) {
+ return 0.0f;
+ }
+ StripAnim *strip_anim = seq->anims.first;
+ if (strip_anim->anim == NULL) {
+ return 0.0f;
+ }
+ short frs_sec;
+ float frs_sec_base;
+ if (IMB_anim_get_fps(strip_anim->anim, &frs_sec, &frs_sec_base, true)) {
+ return (float)frs_sec / frs_sec_base;
+ }
+ break;
+ }
+ case SEQ_TYPE_MOVIECLIP:
+ if (seq->clip != NULL) {
+ return BKE_movieclip_get_fps(seq->clip);
+ }
+ break;
+ case SEQ_TYPE_SCENE:
+ if (seq->scene != NULL) {
+ return (float)seq->scene->r.frs_sec / seq->scene->r.frs_sec_base;
+ }
+ break;
+ }
+ return 0.0f;
+}
+
/* NOTE: this function doesn't fill in image names */
Sequence *BKE_sequencer_add_image_strip(bContext *C, ListBase *seqbasep, SeqLoadInfo *seq_load)
{
@@ -5182,6 +5239,7 @@ Sequence *BKE_sequencer_add_sound_strip(bContext *C, ListBase *seqbasep, SeqLoad
sound = BKE_sound_new_file(bmain, seq_load->path); /* handles relative paths */
if (sound->playback_handle == NULL) {
+ BKE_libblock_free(bmain, sound);
#if 0
if (op)
BKE_report(op->reports, RPT_ERROR, "Unsupported audio format");
@@ -5326,6 +5384,8 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad
}
}
+ IMB_anim_load_metadata(anim_arr[0]);
+
seq->anim_preseek = IMB_anim_get_preseek(anim_arr[0]);
BLI_strncpy(seq->name + 2, "Movie", SEQ_NAME_MAXSTR - 2);
BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seq);
@@ -5369,9 +5429,8 @@ Sequence *BKE_sequencer_add_movie_strip(bContext *C, ListBase *seqbasep, SeqLoad
return seq;
}
-static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dupe_flag)
+static Sequence *seq_dupli(const Scene *scene_src, Scene *scene_dst, Sequence *seq, int dupe_flag, const int flag)
{
- Scene *sce_audio = scene_to ? scene_to : scene;
Sequence *seqn = MEM_dupallocN(seq);
seq->tmp = seqn;
@@ -5395,7 +5454,7 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup
}
if (seq->prop) {
- seqn->prop = IDP_CopyProperty(seq->prop);
+ seqn->prop = IDP_CopyProperty_ex(seq->prop, flag);
}
if (seqn->modifiers.first) {
@@ -5414,7 +5473,7 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup
else if (seq->type == SEQ_TYPE_SCENE) {
seqn->strip->stripdata = NULL;
if (seq->scene_sound)
- seqn->scene_sound = BKE_sound_scene_add_scene_sound_defaults(sce_audio, seqn);
+ seqn->scene_sound = BKE_sound_scene_add_scene_sound_defaults(scene_dst, seqn);
}
else if (seq->type == SEQ_TYPE_MOVIECLIP) {
/* avoid assert */
@@ -5431,9 +5490,11 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup
seqn->strip->stripdata =
MEM_dupallocN(seq->strip->stripdata);
if (seq->scene_sound)
- seqn->scene_sound = BKE_sound_add_scene_sound_defaults(sce_audio, seqn);
+ seqn->scene_sound = BKE_sound_add_scene_sound_defaults(scene_dst, seqn);
- id_us_plus((ID *)seqn->sound);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)seqn->sound);
+ }
}
else if (seq->type == SEQ_TYPE_IMAGE) {
seqn->strip->stripdata =
@@ -5453,11 +5514,15 @@ static Sequence *seq_dupli(Scene *scene, Scene *scene_to, Sequence *seq, int dup
BLI_assert(0);
}
- if (dupe_flag & SEQ_DUPE_UNIQUE_NAME)
- BKE_sequence_base_unique_name_recursive(&scene->ed->seqbase, seqn);
+ if (scene_src == scene_dst) {
+ if (dupe_flag & SEQ_DUPE_UNIQUE_NAME) {
+ BKE_sequence_base_unique_name_recursive(&scene_dst->ed->seqbase, seqn);
+ }
- if (dupe_flag & SEQ_DUPE_ANIM)
- BKE_sequencer_dupe_animdata(scene, seq->name + 2, seqn->name + 2);
+ if (dupe_flag & SEQ_DUPE_ANIM) {
+ BKE_sequencer_dupe_animdata(scene_dst, seq->name + 2, seqn->name + 2);
+ }
+ }
return seqn;
}
@@ -5484,16 +5549,16 @@ static void seq_new_fix_links_recursive(Sequence *seq)
}
}
-Sequence *BKE_sequence_dupli_recursive(Scene *scene, Scene *scene_to, Sequence *seq, int dupe_flag)
+Sequence *BKE_sequence_dupli_recursive(const Scene *scene_src, Scene *scene_dst, Sequence *seq, int dupe_flag)
{
Sequence *seqn;
seq->tmp = NULL;
- seqn = seq_dupli(scene, scene_to, seq, dupe_flag);
+ seqn = seq_dupli(scene_src, scene_dst, seq, dupe_flag, 0);
if (seq->type == SEQ_TYPE_META) {
Sequence *s;
for (s = seq->seqbase.first; s; s = s->next) {
- Sequence *n = BKE_sequence_dupli_recursive(scene, scene_to, s, dupe_flag);
+ Sequence *n = BKE_sequence_dupli_recursive(scene_src, scene_dst, s, dupe_flag);
if (n) {
BLI_addtail(&seqn->seqbase, n);
}
@@ -5506,19 +5571,19 @@ Sequence *BKE_sequence_dupli_recursive(Scene *scene, Scene *scene_to, Sequence *
}
void BKE_sequence_base_dupli_recursive(
- Scene *scene, Scene *scene_to, ListBase *nseqbase, ListBase *seqbase,
- int dupe_flag)
+ const Scene *scene_src, Scene *scene_dst, ListBase *nseqbase, const ListBase *seqbase,
+ int dupe_flag, const int flag)
{
Sequence *seq;
Sequence *seqn = NULL;
- Sequence *last_seq = BKE_sequencer_active_get(scene);
+ Sequence *last_seq = BKE_sequencer_active_get((Scene *)scene_src);
/* always include meta's strips */
int dupe_flag_recursive = dupe_flag | SEQ_DUPE_ALL;
for (seq = seqbase->first; seq; seq = seq->next) {
seq->tmp = NULL;
if ((seq->flag & SELECT) || (dupe_flag & SEQ_DUPE_ALL)) {
- seqn = seq_dupli(scene, scene_to, seq, dupe_flag);
+ seqn = seq_dupli(scene_src, scene_dst, seq, dupe_flag, flag);
if (seqn) { /*should never fail */
if (dupe_flag & SEQ_DUPE_CONTEXT) {
seq->flag &= ~SEQ_ALLSEL;
@@ -5528,13 +5593,13 @@ void BKE_sequence_base_dupli_recursive(
BLI_addtail(nseqbase, seqn);
if (seq->type == SEQ_TYPE_META) {
BKE_sequence_base_dupli_recursive(
- scene, scene_to, &seqn->seqbase, &seq->seqbase,
- dupe_flag_recursive);
+ scene_src, scene_dst, &seqn->seqbase, &seq->seqbase,
+ dupe_flag_recursive, flag);
}
if (dupe_flag & SEQ_DUPE_CONTEXT) {
if (seq == last_seq) {
- BKE_sequencer_active_set(scene, seqn);
+ BKE_sequencer_active_set(scene_dst, seqn);
}
}
}
diff --git a/source/blender/blenkernel/intern/shrinkwrap.c b/source/blender/blenkernel/intern/shrinkwrap.c
index 7094d5a3547..618f495dbf1 100644
--- a/source/blender/blenkernel/intern/shrinkwrap.c
+++ b/source/blender/blenkernel/intern/shrinkwrap.c
@@ -88,13 +88,15 @@ typedef struct ShrinkwrapCalcCBData {
* for each vertex performs a nearest vertex search on the tree
*/
static void shrinkwrap_calc_nearest_vertex_cb_ex(
- void *userdata, void *userdata_chunk, const int i, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict tls)
{
ShrinkwrapCalcCBData *data = userdata;
ShrinkwrapCalcData *calc = data->calc;
BVHTreeFromMesh *treeData = data->treeData;
- BVHTreeNearest *nearest = userdata_chunk;
+ BVHTreeNearest *nearest = tls->userdata_chunk;
float *co = calc->vertexCos[i];
float tmp_co[3];
@@ -152,6 +154,9 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
BVHTreeNearest nearest = NULL_BVHTreeNearest;
+ if (calc->target != NULL && calc->target->getNumVerts(calc->target) == 0) {
+ return;
+ }
TIMEIT_BENCH(bvhtree_from_mesh_verts(&treeData, calc->target, 0.0, 2, 6), bvhtree_verts);
if (treeData.tree == NULL) {
@@ -164,9 +169,14 @@ static void shrinkwrap_calc_nearest_vertex(ShrinkwrapCalcData *calc)
nearest.dist_sq = FLT_MAX;
ShrinkwrapCalcCBData data = {.calc = calc, .treeData = &treeData};
- BLI_task_parallel_range_ex(
- 0, calc->numVerts, &data, &nearest, sizeof(nearest), shrinkwrap_calc_nearest_vertex_cb_ex,
- calc->numVerts > BKE_MESH_OMP_LIMIT, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (calc->numVerts > BKE_MESH_OMP_LIMIT);
+ settings.userdata_chunk = &nearest;
+ settings.userdata_chunk_size = sizeof(nearest);
+ BLI_task_parallel_range(0, calc->numVerts,
+ &data, shrinkwrap_calc_nearest_vertex_cb_ex,
+ &settings);
free_bvhtree_from_mesh(&treeData);
}
@@ -254,7 +264,9 @@ bool BKE_shrinkwrap_project_normal(
}
static void shrinkwrap_calc_normal_projection_cb_ex(
- void *userdata, void *userdata_chunk, const int i, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict tls)
{
ShrinkwrapCalcCBData *data = userdata;
@@ -269,7 +281,7 @@ static void shrinkwrap_calc_normal_projection_cb_ex(
float *proj_axis = data->proj_axis;
SpaceTransform *local2aux = data->local2aux;
- BVHTreeRayHit *hit = userdata_chunk;
+ BVHTreeRayHit *hit = tls->userdata_chunk;
const float proj_limit_squared = calc->smd->projLimit * calc->smd->projLimit;
float *co = calc->vertexCos[i];
@@ -376,6 +388,9 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for
if ((calc->smd->shrinkOpts & (MOD_SHRINKWRAP_PROJECT_ALLOW_POS_DIR | MOD_SHRINKWRAP_PROJECT_ALLOW_NEG_DIR)) == 0)
return;
+ if (calc->target != NULL && calc->target->getNumPolys(calc->target) == 0) {
+ return;
+ }
/* Prepare data to retrieve the direction in which we should project each vertex */
if (calc->smd->projAxis == MOD_SHRINKWRAP_PROJECT_OVER_NORMAL) {
@@ -432,7 +447,7 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for
if (targ_tree) {
BVHTree *aux_tree = NULL;
void *aux_callback = NULL;
- if (auxMesh != NULL) {
+ if (auxMesh != NULL && auxMesh->getNumPolys(auxMesh) != 0) {
/* use editmesh to avoid array allocation */
if (calc->smd->auxTarget && auxMesh->type == DM_TYPE_EDITBMESH) {
emaux = BKE_editmesh_from_object(calc->smd->auxTarget);
@@ -457,9 +472,15 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for
.auxData = auxData, .aux_tree = aux_tree, .aux_callback = aux_callback,
.proj_axis = proj_axis, .local2aux = &local2aux,
};
- BLI_task_parallel_range_ex(
- 0, calc->numVerts, &data, &hit, sizeof(hit), shrinkwrap_calc_normal_projection_cb_ex,
- calc->numVerts > BKE_MESH_OMP_LIMIT, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (calc->numVerts > BKE_MESH_OMP_LIMIT);
+ settings.userdata_chunk = &hit;
+ settings.userdata_chunk_size = sizeof(hit);
+ BLI_task_parallel_range(0, calc->numVerts,
+ &data,
+ shrinkwrap_calc_normal_projection_cb_ex,
+ &settings);
}
/* free data structures */
@@ -489,13 +510,15 @@ static void shrinkwrap_calc_normal_projection(ShrinkwrapCalcData *calc, bool for
* NN matches for each vertex
*/
static void shrinkwrap_calc_nearest_surface_point_cb_ex(
- void *userdata, void *userdata_chunk, const int i, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict tls)
{
ShrinkwrapCalcCBData *data = userdata;
ShrinkwrapCalcData *calc = data->calc;
BVHTreeFromMesh *treeData = data->treeData;
- BVHTreeNearest *nearest = userdata_chunk;
+ BVHTreeNearest *nearest = tls->userdata_chunk;
float *co = calc->vertexCos[i];
float tmp_co[3];
@@ -560,6 +583,10 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
BVHTreeFromMesh treeData = NULL_BVHTreeFromMesh;
BVHTreeNearest nearest = NULL_BVHTreeNearest;
+ if (calc->target->getNumPolys(calc->target) == 0) {
+ return;
+ }
+
/* Create a bvh-tree of the given target */
bvhtree_from_mesh_looptri(&treeData, calc->target, 0.0, 2, 6);
if (treeData.tree == NULL) {
@@ -573,9 +600,15 @@ static void shrinkwrap_calc_nearest_surface_point(ShrinkwrapCalcData *calc)
/* Find the nearest vertex */
ShrinkwrapCalcCBData data = {.calc = calc, .treeData = &treeData};
- BLI_task_parallel_range_ex(
- 0, calc->numVerts, &data, &nearest, sizeof(nearest), shrinkwrap_calc_nearest_surface_point_cb_ex,
- calc->numVerts > BKE_MESH_OMP_LIMIT, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (calc->numVerts > BKE_MESH_OMP_LIMIT);
+ settings.userdata_chunk = &nearest;
+ settings.userdata_chunk_size = sizeof(nearest);
+ BLI_task_parallel_range(0, calc->numVerts,
+ &data,
+ shrinkwrap_calc_nearest_surface_point_cb_ex,
+ &settings);
free_bvhtree_from_mesh(&treeData);
}
diff --git a/source/blender/blenkernel/intern/smoke.c b/source/blender/blenkernel/intern/smoke.c
index d0ef5cfc092..0ea4007c95f 100644
--- a/source/blender/blenkernel/intern/smoke.c
+++ b/source/blender/blenkernel/intern/smoke.c
@@ -72,7 +72,6 @@
#include "BKE_customdata.h"
#include "BKE_deform.h"
#include "BKE_DerivedMesh.h"
-#include "BKE_global.h"
#include "BKE_effect.h"
#include "BKE_main.h"
#include "BKE_modifier.h"
@@ -168,11 +167,11 @@ void smoke_reallocate_highres_fluid(SmokeDomainSettings *sds, float dx, int res[
}
/* smoke_turbulence_init uses non-threadsafe functions from fftw3 lib (like fftw_plan & co). */
- BLI_lock_thread(LOCK_FFTW);
+ BLI_thread_lock(LOCK_FFTW);
sds->wt = smoke_turbulence_init(res, sds->amplify + 1, sds->noise, BKE_tempdir_session(), use_fire, use_colors);
- BLI_unlock_thread(LOCK_FFTW);
+ BLI_thread_unlock(LOCK_FFTW);
sds->res_wt[0] = res[0] * (sds->amplify + 1);
sds->res_wt[1] = res[1] * (sds->amplify + 1);
@@ -523,8 +522,8 @@ void smokeModifier_createType(struct SmokeModifierData *smd)
smd->domain->burning_rate = 0.75f;
smd->domain->flame_smoke = 1.0f;
smd->domain->flame_vorticity = 0.5f;
- smd->domain->flame_ignition = 1.25f;
- smd->domain->flame_max_temp = 1.75f;
+ smd->domain->flame_ignition = 1.5f;
+ smd->domain->flame_max_temp = 3.0f;
/* color */
smd->domain->flame_smoke_color[0] = 0.7f;
smd->domain->flame_smoke_color[1] = 0.7f;
@@ -551,6 +550,8 @@ void smokeModifier_createType(struct SmokeModifierData *smd)
smd->domain->coba = NULL;
smd->domain->coba_field = FLUID_FIELD_DENSITY;
+
+ smd->domain->clipping = 1e-3f;
}
else if (smd->type & MOD_SMOKE_TYPE_FLOW)
{
@@ -677,7 +678,7 @@ void smokeModifier_copy(struct SmokeModifierData *smd, struct SmokeModifierData
tsmd->flow->texture_size = smd->flow->texture_size;
tsmd->flow->texture_offset = smd->flow->texture_offset;
- BLI_strncpy(tsmd->flow->uvlayer_name, tsmd->flow->uvlayer_name, sizeof(tsmd->flow->uvlayer_name));
+ BLI_strncpy(tsmd->flow->uvlayer_name, smd->flow->uvlayer_name, sizeof(tsmd->flow->uvlayer_name));
tsmd->flow->vgroup_density = smd->flow->vgroup_density;
tsmd->flow->type = smd->flow->type;
@@ -738,7 +739,10 @@ typedef struct ObstaclesFromDMData {
int *num_obstacles;
} ObstaclesFromDMData;
-static void obstacles_from_derivedmesh_task_cb(void *userdata, const int z)
+static void obstacles_from_derivedmesh_task_cb(
+ void *__restrict userdata,
+ const int z,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
ObstaclesFromDMData *data = userdata;
SmokeDomainSettings *sds = data->sds;
@@ -868,8 +872,13 @@ static void obstacles_from_derivedmesh(
.velocityX = velocityX, .velocityY = velocityY, .velocityZ = velocityZ,
.num_obstacles = num_obstacles
};
- BLI_task_parallel_range(
- sds->res_min[2], sds->res_max[2], &data, obstacles_from_derivedmesh_task_cb, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
+ BLI_task_parallel_range(sds->res_min[2], sds->res_max[2],
+ &data,
+ obstacles_from_derivedmesh_task_cb,
+ &settings);
}
/* free bvh tree */
free_bvhtree_from_mesh(&treeData);
@@ -1096,8 +1105,9 @@ static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_mult
/* initialize with first input if in range */
if (x >= em1.min[0] && x < em1.max[0] &&
- y >= em1.min[1] && y < em1.max[1] &&
- z >= em1.min[2] && z < em1.max[2]) {
+ y >= em1.min[1] && y < em1.max[1] &&
+ z >= em1.min[2] && z < em1.max[2])
+ {
int index_in = smoke_get_index(x - em1.min[0], em1.res[0], y - em1.min[1], em1.res[1], z - em1.min[2]);
/* values */
@@ -1109,8 +1119,9 @@ static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_mult
/* apply second input if in range */
if (x >= em2->min[0] && x < em2->max[0] &&
- y >= em2->min[1] && y < em2->max[1] &&
- z >= em2->min[2] && z < em2->max[2]) {
+ y >= em2->min[1] && y < em2->max[1] &&
+ z >= em2->min[2] && z < em2->max[2])
+ {
int index_in = smoke_get_index(x - em2->min[0], em2->res[0], y - em2->min[1], em2->res[1], z - em2->min[2]);
/* values */
@@ -1140,8 +1151,9 @@ static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_mult
/* initialize with first input if in range */
if (x >= em1.hmin[0] && x < em1.hmax[0] &&
- y >= em1.hmin[1] && y < em1.hmax[1] &&
- z >= em1.hmin[2] && z < em1.hmax[2]) {
+ y >= em1.hmin[1] && y < em1.hmax[1] &&
+ z >= em1.hmin[2] && z < em1.hmax[2])
+ {
int index_in = smoke_get_index(x - em1.hmin[0], em1.hres[0], y - em1.hmin[1], em1.hres[1], z - em1.hmin[2]);
/* values */
output->influence_high[index_out] = em1.influence_high[index_in];
@@ -1149,8 +1161,9 @@ static void em_combineMaps(EmissionMap *output, EmissionMap *em2, int hires_mult
/* apply second input if in range */
if (x >= em2->hmin[0] && x < em2->hmax[0] &&
- y >= em2->hmin[1] && y < em2->hmax[1] &&
- z >= em2->hmin[2] && z < em2->hmax[2]) {
+ y >= em2->hmin[1] && y < em2->hmax[1] &&
+ z >= em2->hmin[2] && z < em2->hmax[2])
+ {
int index_in = smoke_get_index(x - em2->hmin[0], em2->hres[0], y - em2->hmin[1], em2->hres[1], z - em2->hmin[2]);
/* values */
@@ -1184,7 +1197,10 @@ typedef struct EmitFromParticlesData {
float hr_smooth;
} EmitFromParticlesData;
-static void emit_from_particles_task_cb(void *userdata, const int z)
+static void emit_from_particles_task_cb(
+ void *__restrict userdata,
+ const int z,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
EmitFromParticlesData *data = userdata;
SmokeFlowSettings *sfs = data->sfs;
@@ -1274,6 +1290,8 @@ static void emit_from_particles(
curvemapping_changed_all(psys->part->clumpcurve);
if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve)
curvemapping_changed_all(psys->part->roughcurve);
+ if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve)
+ curvemapping_changed_all(psys->part->twistcurve);
/* initialize particle cache */
if (psys->part->type == PART_HAIR) {
@@ -1395,7 +1413,13 @@ static void emit_from_particles(
.solid = solid, .smooth = smooth, .hr_smooth = hr_smooth,
};
- BLI_task_parallel_range(min[2], max[2], &data, emit_from_particles_task_cb, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
+ BLI_task_parallel_range(min[2], max[2],
+ &data,
+ emit_from_particles_task_cb,
+ &settings);
}
if (sfs->flags & MOD_SMOKE_FLOW_USE_PART_SIZE) {
@@ -1567,7 +1591,10 @@ typedef struct EmitFromDMData {
int *min, *max, *res;
} EmitFromDMData;
-static void emit_from_derivedmesh_task_cb(void *userdata, const int z)
+static void emit_from_derivedmesh_task_cb(
+ void *__restrict userdata,
+ const int z,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
EmitFromDMData *data = userdata;
EmissionMap *em = data->em;
@@ -1720,7 +1747,13 @@ static void emit_from_derivedmesh(Object *flow_ob, SmokeDomainSettings *sds, Smo
.flow_center = flow_center, .min = min, .max = max, .res = res,
};
- BLI_task_parallel_range(min[2], max[2], &data, emit_from_derivedmesh_task_cb, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
+ BLI_task_parallel_range(min[2], max[2],
+ &data,
+ emit_from_derivedmesh_task_cb,
+ &settings);
}
/* free bvh tree */
free_bvhtree_from_mesh(&treeData);
@@ -2436,7 +2469,10 @@ typedef struct UpdateEffectorsData {
unsigned char *obstacle;
} UpdateEffectorsData;
-static void update_effectors_task_cb(void *userdata, const int x)
+static void update_effectors_task_cb(
+ void *__restrict userdata,
+ const int x,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
UpdateEffectorsData *data = userdata;
SmokeDomainSettings *sds = data->sds;
@@ -2510,7 +2546,13 @@ static void update_effectors(Scene *scene, Object *ob, SmokeDomainSettings *sds,
data.velocity_z = smoke_get_velocity_z(sds->fluid);
data.obstacle = smoke_get_obstacle(sds->fluid);
- BLI_task_parallel_range(0, sds->res[0], &data, update_effectors_task_cb, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.scheduling_mode = TASK_SCHEDULING_DYNAMIC;
+ BLI_task_parallel_range(0, sds->res[0],
+ &data,
+ update_effectors_task_cb,
+ &settings);
}
pdEndEffectors(&effectors);
@@ -2692,7 +2734,6 @@ static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object *
if (smd->flow->dm) smd->flow->dm->release(smd->flow->dm);
smd->flow->dm = CDDM_copy(dm);
- DM_ensure_looptri(smd->flow->dm);
if (scene->r.cfra > smd->time)
{
@@ -2715,7 +2756,6 @@ static void smokeModifier_process(SmokeModifierData *smd, Scene *scene, Object *
smd->coll->dm->release(smd->coll->dm);
smd->coll->dm = CDDM_copy(dm);
- DM_ensure_looptri(smd->coll->dm);
}
smd->time = scene->r.cfra;
diff --git a/source/blender/blenkernel/intern/softbody.c b/source/blender/blenkernel/intern/softbody.c
index 03cf33083da..c3527af90ca 100644
--- a/source/blender/blenkernel/intern/softbody.c
+++ b/source/blender/blenkernel/intern/softbody.c
@@ -676,11 +676,13 @@ static void add_2nd_order_roller(Object *ob, float UNUSED(stiffness), int *count
notthis = bs->v2;
}
else {
- if (v0 == bs->v2) {
- bpo = sb->bpoint+bs->v1;
- notthis = bs->v1;
- }
- else {printf("oops we should not get here - add_2nd_order_springs");}
+ if (v0 == bs->v2) {
+ bpo = sb->bpoint+bs->v1;
+ notthis = bs->v1;
+ }
+ else {
+ printf("oops we should not get here - add_2nd_order_springs");
+ }
}
if (bpo) {/* so now we have a 2nd order humpdidump */
for (c=bpo->nofsprings;c>0;c--) {
@@ -1602,12 +1604,12 @@ static void sb_sfesf_threads_run(Scene *scene, struct Object *ob, float timenow,
sb_threads[i].tot= totthread;
}
if (totthread > 1) {
- BLI_init_threads(&threads, exec_scan_for_ext_spring_forces, totthread);
+ BLI_threadpool_init(&threads, exec_scan_for_ext_spring_forces, totthread);
for (i=0; i<totthread; i++)
- BLI_insert_thread(&threads, &sb_threads[i]);
+ BLI_threadpool_insert(&threads, &sb_threads[i]);
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
}
else
exec_scan_for_ext_spring_forces(&sb_threads[0]);
@@ -1856,19 +1858,21 @@ static void dfdx_spring(int ia, int ic, int op, float dir[3], float L, float len
float m, delta_ij;
int i, j;
if (L < len) {
- for (i=0;i<3;i++)
+ 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]));
EIG_linear_solver_matrix_add(ia+i, op+ic+j, m);
}
+ }
}
else {
- for (i=0;i<3;i++)
+ for (i=0;i<3;i++) {
for (j=0;j<3;j++) {
m=factor*dir[i]*dir[j];
EIG_linear_solver_matrix_add(ia+i, op+ic+j, m);
}
+ }
}
}
@@ -1975,12 +1979,12 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo
/* intitialize */
if (sb) {
- /* check conditions for various options */
- /* +++ 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));
- /* --- could be done on object level to squeeze out the last bits of it */
+ /* check conditions for various options */
+ /* +++ 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));
+ /* --- could be done on object level to squeeze out the last bits of it */
}
else {
printf("Error expected a SB here\n");
@@ -2011,7 +2015,8 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo
float compare;
float bstune = sb->ballstiff;
- for (c=sb->totpoint, obp= sb->bpoint; c>=ifirst+bb; c--, obp++) {
+ /* running in a slice we must not assume anything done with obp neither alter the data of obp */
+ for (c=sb->totpoint, obp= sb->bpoint; c>0; c--, obp++) {
compare = (obp->colball + bp->colball);
sub_v3_v3v3(def, bp->pos, obp->pos);
/* rather check the AABBoxes before ever calulating the real distance */
@@ -2036,13 +2041,6 @@ static int _softbody_calc_forces_slice_in_a_thread(Scene *scene, Object *ob, flo
madd_v3_v3fl(bp->force, def, f * (1.0f - sb->balldamp));
madd_v3_v3fl(bp->force, dvel, sb->balldamp);
-
- /* exploit force(a, b) == -force(b, a) part2/2 */
- sub_v3_v3v3(dvel, velcenter, obp->vec);
- mul_v3_fl(dvel, _final_mass(ob, bp));
-
- madd_v3_v3fl(obp->force, dvel, sb->balldamp);
- madd_v3_v3fl(obp->force, def, -f * (1.0f - sb->balldamp));
}
}
}
@@ -2218,12 +2216,12 @@ static void sb_cf_threads_run(Scene *scene, Object *ob, float forcetime, float t
if (totthread > 1) {
- BLI_init_threads(&threads, exec_softbody_calc_forces, totthread);
+ BLI_threadpool_init(&threads, exec_softbody_calc_forces, totthread);
for (i=0; i<totthread; i++)
- BLI_insert_thread(&threads, &sb_threads[i]);
+ BLI_threadpool_insert(&threads, &sb_threads[i]);
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
}
else
exec_softbody_calc_forces(&sb_threads[0]);
@@ -2233,9 +2231,9 @@ static void sb_cf_threads_run(Scene *scene, Object *ob, float forcetime, float t
static void softbody_calc_forcesEx(Scene *scene, Object *ob, float forcetime, float timenow)
{
-/* rule we never alter free variables :bp->vec bp->pos in here !
- * this will ruin adaptive stepsize AKA heun! (BM)
- */
+ /* 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;*/ /* UNUSED */
ListBase *do_effector = NULL;
@@ -2781,7 +2779,7 @@ static void apply_spring_memory(Object *ob)
l = len_v3v3(bp1->pos, bp2->pos);
r = bs->len/l;
if (( r > 1.05f) || (r < 0.95f)) {
- bs->len = ((100.0f - b) * bs->len + b*l)/100.0f;
+ bs->len = ((100.0f - b) * bs->len + b*l)/100.0f;
}
}
}
@@ -2829,10 +2827,10 @@ static void springs_from_mesh(Object *ob)
sb= ob->soft;
if (me && sb) {
- /* using bp->origS as a container for spring calcualtions here
- * will be overwritten sbObjectStep() to receive
- * actual modifier stack positions
- */
+ /* using bp->origS as a container for spring calcualtions here
+ * will be overwritten sbObjectStep() to receive
+ * actual modifier stack positions
+ */
if (me->totvert) {
bp= ob->soft->bpoint;
for (a=0; a<me->totvert; a++, bp++) {
@@ -3410,7 +3408,7 @@ static void softbody_update_positions(Object *ob, SoftBody *sb, float (*vertexCo
* lloc, lrot, lscale are allowed to be NULL, just in case you don't need it.
* should be pretty useful for pythoneers :)
* not! velocity .. 2nd order stuff
- * vcloud_estimate_transform see
+ * vcloud_estimate_transform_v3 see
*/
void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float lscale[3][3])
@@ -3434,7 +3432,7 @@ void SB_estimate_transform(Object *ob, float lloc[3], float lrot[3][3], float ls
copy_v3_v3(opos[a], bp->pos);
}
- vcloud_estimate_transform(sb->totpoint, opos, NULL, rpos, NULL, com, rcom, lrot, lscale);
+ vcloud_estimate_transform_v3(sb->totpoint, opos, NULL, rpos, NULL, com, rcom, lrot, lscale);
//sub_v3_v3(com, rcom);
if (lloc) copy_v3_v3(lloc, com);
copy_v3_v3(sb->lcom, com);
@@ -3495,16 +3493,16 @@ static void softbody_reset(Object *ob, SoftBody *sb, float (*vertexCos)[3], int
SB_estimate_transform(ob, NULL, NULL, NULL);
}
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:
+ 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;
}
}
@@ -3724,7 +3722,8 @@ void sbObjectStep(Scene *scene, Object *ob, float cfra, float (*vertexCos)[3], i
cache_result = BKE_ptcache_read(&pid, (float)framenr+scene->r.subframe, can_simulate);
if (cache_result == PTCACHE_READ_EXACT || cache_result == PTCACHE_READ_INTERPOLATED ||
- (!can_simulate && cache_result == PTCACHE_READ_OLD)) {
+ (!can_simulate && cache_result == PTCACHE_READ_OLD))
+ {
softbody_to_object(ob, vertexCos, numVerts, sb->local);
BKE_ptcache_validate(cache, framenr);
diff --git a/source/blender/blenkernel/intern/sound.c b/source/blender/blenkernel/intern/sound.c
index 8469351c54a..45d1f969d64 100644
--- a/source/blender/blenkernel/intern/sound.c
+++ b/source/blender/blenkernel/intern/sound.c
@@ -83,7 +83,7 @@ bSound *BKE_sound_new_file(struct Main *bmain, const char *filepath)
BLI_path_abs(str, path);
- sound = BKE_libblock_alloc(bmain, ID_SO, BLI_path_basename(filepath));
+ sound = BKE_libblock_alloc(bmain, ID_SO, BLI_path_basename(filepath), 0);
BLI_strncpy(sound->name, filepath, FILE_MAX);
/* sound->type = SOUND_TYPE_FILE; */ /* XXX unused currently */
@@ -155,6 +155,34 @@ void BKE_sound_free(bSound *sound)
}
}
+/**
+ * Only copy internal data of Sound ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_sound_copy_data(Main *bmain, bSound *sound_dst, const bSound *UNUSED(sound_src), const int UNUSED(flag))
+{
+ sound_dst->handle = NULL;
+ sound_dst->cache = NULL;
+ sound_dst->waveform = NULL;
+ sound_dst->playback_handle = NULL;
+ sound_dst->spinlock = NULL; /* Think this is OK? Otherwise, easy to create new spinlock here... */
+
+ /* Just to be sure, should not have any value actually after reading time. */
+ sound_dst->ipo = NULL;
+ sound_dst->newpackedfile = NULL;
+
+ if (sound_dst->packedfile) {
+ sound_dst->packedfile = dupPackedFile(sound_dst->packedfile);
+ }
+
+ /* Initialize whole runtime (audaspace) stuff. */
+ BKE_sound_load(bmain, sound_dst);
+}
+
void BKE_sound_make_local(Main *bmain, bSound *sound, const bool lib_local)
{
BKE_id_make_local_generic(bmain, &sound->id, true, lib_local);
diff --git a/source/blender/blenkernel/intern/speaker.c b/source/blender/blenkernel/intern/speaker.c
index ee6886e3fb2..1d2e12f34ac 100644
--- a/source/blender/blenkernel/intern/speaker.c
+++ b/source/blender/blenkernel/intern/speaker.c
@@ -32,7 +32,6 @@
#include "BLI_utildefines.h"
#include "BKE_animsys.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_library_remap.h"
@@ -61,25 +60,31 @@ void *BKE_speaker_add(Main *bmain, const char *name)
{
Speaker *spk;
- spk = BKE_libblock_alloc(bmain, ID_SPK, name);
+ spk = BKE_libblock_alloc(bmain, ID_SPK, name, 0);
BKE_speaker_init(spk);
return spk;
}
-Speaker *BKE_speaker_copy(Main *bmain, Speaker *spk)
+/**
+ * Only copy internal data of Speaker ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_speaker_copy_data(Main *UNUSED(bmain), Speaker *UNUSED(spk_dst), const Speaker *UNUSED(spk_src), const int UNUSED(flag))
{
- Speaker *spkn;
-
- spkn = BKE_libblock_copy(bmain, &spk->id);
-
- if (spkn->sound)
- id_us_plus(&spkn->sound->id);
-
- BKE_id_copy_ensure_local(bmain, &spk->id, &spkn->id);
+ /* Nothing to do! */
+}
- return spkn;
+Speaker *BKE_speaker_copy(Main *bmain, const Speaker *spk)
+{
+ Speaker *spk_copy;
+ BKE_id_copy_ex(bmain, &spk->id, (ID **)&spk_copy, 0, false);
+ return spk_copy;
}
void BKE_speaker_make_local(Main *bmain, Speaker *spk, const bool lib_local)
diff --git a/source/blender/blenkernel/intern/subsurf_ccg.c b/source/blender/blenkernel/intern/subsurf_ccg.c
index c4665c40ec4..8e46cabff02 100644
--- a/source/blender/blenkernel/intern/subsurf_ccg.c
+++ b/source/blender/blenkernel/intern/subsurf_ccg.c
@@ -42,6 +42,8 @@
#include <math.h>
#include <float.h>
+#include "atomic_ops.h"
+
#include "MEM_guardedalloc.h"
#include "DNA_mesh_types.h"
@@ -56,6 +58,7 @@
#include "BLI_edgehash.h"
#include "BLI_math.h"
#include "BLI_memarena.h"
+#include "BLI_task.h"
#include "BLI_threads.h"
#include "BKE_pbvh.h"
@@ -64,6 +67,7 @@
#include "BKE_global.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
+#include "BKE_modifier.h"
#include "BKE_multires.h"
#include "BKE_paint.h"
#include "BKE_scene.h"
@@ -88,9 +92,6 @@
/* assumes MLoop's are layed out 4 for each poly, in order */
#define USE_LOOP_LAYOUT_FAST
-static ThreadRWMutex loops_cache_rwlock = BLI_RWLOCK_INITIALIZER;
-static ThreadRWMutex origindex_cache_rwlock = BLI_RWLOCK_INITIALIZER;
-
static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
int drawInteriorEdges,
int useSubsurfUv,
@@ -360,7 +361,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
#ifdef USE_DYNSIZE
CCGVertHDL fverts[nverts];
#else
- BLI_array_empty(fverts);
+ BLI_array_clear(fverts);
BLI_array_grow_items(fverts, nverts);
#endif
@@ -399,7 +400,7 @@ static int ss_sync_from_uv(CCGSubSurf *ss, CCGSubSurf *origss, DerivedMesh *dm,
#ifdef USE_DYNSIZE
CCGVertHDL fverts[nverts];
#else
- BLI_array_empty(fverts);
+ BLI_array_clear(fverts);
BLI_array_grow_items(fverts, nverts);
#endif
@@ -743,7 +744,7 @@ static void ss_sync_ccg_from_derivedmesh(CCGSubSurf *ss,
#ifdef USE_DYNSIZE
CCGVertHDL fVerts[mp->totloop];
#else
- BLI_array_empty(fVerts);
+ BLI_array_clear(fVerts);
BLI_array_grow_items(fVerts, mp->totloop);
#endif
@@ -1477,77 +1478,107 @@ static void ccgDM_copyFinalFaceArray(DerivedMesh *dm, MFace *mface)
}
}
+typedef struct CopyFinalLoopArrayData {
+ CCGDerivedMesh *ccgdm;
+ MLoop *mloop;
+ int grid_size;
+ int *grid_offset;
+ int edge_size;
+ size_t mloop_index;
+} CopyFinalLoopArrayData;
+
+static void copyFinalLoopArray_task_cb(
+ void *__restrict userdata,
+ const int iter,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ CopyFinalLoopArrayData *data = userdata;
+ CCGDerivedMesh *ccgdm = data->ccgdm;
+ CCGSubSurf *ss = ccgdm->ss;
+ const int grid_size = data->grid_size;
+ const int edge_size = data->edge_size;
+ CCGFace *f = ccgdm->faceMap[iter].face;
+ const int num_verts = ccgSubSurf_getFaceNumVerts(f);
+ const int grid_index = data->grid_offset[iter];
+ const size_t loop_index = 4 * (size_t)grid_index * (grid_size - 1) * (grid_size - 1);
+ MLoop *ml = &data->mloop[loop_index];
+ for (int S = 0; S < num_verts; S++) {
+ for (int y = 0; y < grid_size - 1; y++) {
+ for (int x = 0; x < grid_size - 1; x++) {
+
+ uint v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
+ edge_size, grid_size);
+ uint v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
+ edge_size, grid_size);
+ uint v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
+ edge_size, grid_size);
+ uint v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
+ edge_size, grid_size);
+
+ ml->v = v1;
+ ml->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
+ ml++;
+
+ ml->v = v2;
+ ml->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
+ ml++;
+
+ ml->v = v3;
+ ml->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
+ ml++;
+
+ ml->v = v4;
+ ml->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
+ ml++;
+ }
+ }
+ }
+}
+
static void ccgDM_copyFinalLoopArray(DerivedMesh *dm, MLoop *mloop)
{
CCGDerivedMesh *ccgdm = (CCGDerivedMesh *) dm;
CCGSubSurf *ss = ccgdm->ss;
- int index;
- int totface;
- int gridSize = ccgSubSurf_getGridSize(ss);
- int edgeSize = ccgSubSurf_getEdgeSize(ss);
- int i = 0;
- MLoop *mv;
- /* DMFlagMat *faceFlags = ccgdm->faceFlags; */ /* UNUSED */
if (!ccgdm->ehash) {
- BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE);
+ BLI_mutex_lock(&ccgdm->loops_cache_lock);
if (!ccgdm->ehash) {
MEdge *medge;
+ EdgeHash *ehash;
- ccgdm->ehash = BLI_edgehash_new_ex(__func__, ccgdm->dm.numEdgeData);
+ ehash = BLI_edgehash_new_ex(__func__, ccgdm->dm.numEdgeData);
medge = ccgdm->dm.getEdgeArray((DerivedMesh *)ccgdm);
- for (i = 0; i < ccgdm->dm.numEdgeData; i++) {
- BLI_edgehash_insert(ccgdm->ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
+ for (int i = 0; i < ccgdm->dm.numEdgeData; i++) {
+ BLI_edgehash_insert(ehash, medge[i].v1, medge[i].v2, SET_INT_IN_POINTER(i));
}
+
+ atomic_cas_ptr((void **)&ccgdm->ehash, ccgdm->ehash, ehash);
}
- BLI_rw_mutex_unlock(&loops_cache_rwlock);
+ BLI_mutex_unlock(&ccgdm->loops_cache_lock);
}
- BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_READ);
- totface = ccgSubSurf_getNumFaces(ss);
- mv = mloop;
- for (index = 0; index < totface; index++) {
- CCGFace *f = ccgdm->faceMap[index].face;
- int x, y, S, numVerts = ccgSubSurf_getFaceNumVerts(f);
- /* int flag = (faceFlags) ? faceFlags[index * 2]: ME_SMOOTH; */ /* UNUSED */
- /* int mat_nr = (faceFlags) ? faceFlags[index * 2 + 1]: 0; */ /* UNUSED */
-
- for (S = 0; S < numVerts; S++) {
- for (y = 0; y < gridSize - 1; y++) {
- for (x = 0; x < gridSize - 1; x++) {
- unsigned int v1, v2, v3, v4;
-
- v1 = getFaceIndex(ss, f, S, x + 0, y + 0,
- edgeSize, gridSize);
+ CopyFinalLoopArrayData data;
+ data.ccgdm = ccgdm;
+ data.mloop = mloop;
+ data.grid_size = ccgSubSurf_getGridSize(ss);
+ data.grid_offset = dm->getGridOffset(dm);
+ data.edge_size = ccgSubSurf_getEdgeSize(ss);
- v2 = getFaceIndex(ss, f, S, x + 0, y + 1,
- edgeSize, gridSize);
- v3 = getFaceIndex(ss, f, S, x + 1, y + 1,
- edgeSize, gridSize);
- v4 = getFaceIndex(ss, f, S, x + 1, y + 0,
- edgeSize, gridSize);
-
- mv->v = v1;
- mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v1, v2));
- mv++; i++;
-
- mv->v = v2;
- mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v2, v3));
- mv++; i++;
+ /* NOTE: For a dense subdivision we've got enough work for each face and
+ * hence can dedicate whole thread to single face. For less dense
+ * subdivision we handle multiple faces per thread.
+ */
+ data.mloop_index = data.grid_size >= 5 ? 1 : 8;
- mv->v = v3;
- mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v3, v4));
- mv++; i++;
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1;
- mv->v = v4;
- mv->e = GET_UINT_FROM_POINTER(BLI_edgehash_lookup(ccgdm->ehash, v4, v1));
- mv++; i++;
- }
- }
- }
- }
- BLI_rw_mutex_unlock(&loops_cache_rwlock);
+ BLI_task_parallel_range(0, ccgSubSurf_getNumFaces(ss),
+ &data,
+ copyFinalLoopArray_task_cb,
+ &settings);
}
static void ccgDM_copyFinalPolyArray(DerivedMesh *dm, MPoly *mpoly)
@@ -2196,12 +2227,12 @@ static void ccgDM_buffer_copy_color(
for (S = 0; S < numVerts; S++) {
for (y = 0; y < gridFaces; y++) {
for (x = 0; x < gridFaces; x++) {
- copy_v3_v3_uchar(&varray[start + 0], &mloopcol[iface * 16 + 0]);
- copy_v3_v3_uchar(&varray[start + 3], &mloopcol[iface * 16 + 12]);
- copy_v3_v3_uchar(&varray[start + 6], &mloopcol[iface * 16 + 8]);
- copy_v3_v3_uchar(&varray[start + 9], &mloopcol[iface * 16 + 4]);
+ copy_v4_v4_uchar(&varray[start + 0], &mloopcol[iface * 16 + 0]);
+ copy_v4_v4_uchar(&varray[start + 4], &mloopcol[iface * 16 + 12]);
+ copy_v4_v4_uchar(&varray[start + 8], &mloopcol[iface * 16 + 8]);
+ copy_v4_v4_uchar(&varray[start + 12], &mloopcol[iface * 16 + 4]);
- start += 12;
+ start += 16;
iface++;
}
}
@@ -3681,6 +3712,11 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm,
int gridFaces = gridSize - 1, totface;
int prev_mat_nr = -1;
+ if (ccgdm->pbvh) {
+ if (G.debug_value == 14)
+ BKE_pbvh_draw_BB(ccgdm->pbvh);
+ }
+
#ifdef WITH_OPENSUBDIV
if (ccgdm->useGpuBackend) {
int new_matnr;
@@ -3791,16 +3827,16 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm,
float *c = CCG_grid_elem_co(&key, faceGridData, x + 1, y + 1);
float *d = CCG_grid_elem_co(&key, faceGridData, x, y + 1);
- if (cp) glColor3ubv(&cp[4]);
+ if (cp) glColor4ubv(&cp[4]);
glNormal3fv(ln[1]);
glVertex3fv(d);
- if (cp) glColor3ubv(&cp[8]);
+ if (cp) glColor4ubv(&cp[8]);
glNormal3fv(ln[2]);
glVertex3fv(c);
- if (cp) glColor3ubv(&cp[12]);
+ if (cp) glColor4ubv(&cp[12]);
glNormal3fv(ln[3]);
glVertex3fv(b);
- if (cp) glColor3ubv(&cp[0]);
+ if (cp) glColor4ubv(&cp[0]);
glNormal3fv(ln[0]);
glVertex3fv(a);
@@ -3818,10 +3854,10 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm,
a = CCG_grid_elem(&key, faceGridData, x, y + 0);
b = CCG_grid_elem(&key, faceGridData, x, y + 1);
- if (cp) glColor3ubv(&cp[0]);
+ if (cp) glColor4ubv(&cp[0]);
glNormal3fv(CCG_elem_no(&key, a));
glVertex3fv(CCG_elem_co(&key, a));
- if (cp) glColor3ubv(&cp[4]);
+ if (cp) glColor4ubv(&cp[4]);
glNormal3fv(CCG_elem_no(&key, b));
glVertex3fv(CCG_elem_co(&key, b));
@@ -3833,10 +3869,10 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm,
a = CCG_grid_elem(&key, faceGridData, x, y + 0);
b = CCG_grid_elem(&key, faceGridData, x, y + 1);
- if (cp) glColor3ubv(&cp[12]);
+ if (cp) glColor4ubv(&cp[12]);
glNormal3fv(CCG_elem_no(&key, a));
glVertex3fv(CCG_elem_co(&key, a));
- if (cp) glColor3ubv(&cp[8]);
+ if (cp) glColor4ubv(&cp[8]);
glNormal3fv(CCG_elem_no(&key, b));
glVertex3fv(CCG_elem_co(&key, b));
@@ -3856,13 +3892,13 @@ static void ccgDM_drawMappedFaces(DerivedMesh *dm,
ccgDM_glNormalFast(a, b, c, d);
- if (cp) glColor3ubv(&cp[4]);
+ if (cp) glColor4ubv(&cp[4]);
glVertex3fv(d);
- if (cp) glColor3ubv(&cp[8]);
+ if (cp) glColor4ubv(&cp[8]);
glVertex3fv(c);
- if (cp) glColor3ubv(&cp[12]);
+ if (cp) glColor4ubv(&cp[12]);
glVertex3fv(b);
- if (cp) glColor3ubv(&cp[0]);
+ if (cp) glColor4ubv(&cp[0]);
glVertex3fv(a);
if (cp) cp += 16;
@@ -4024,10 +4060,12 @@ static void ccgDM_release(DerivedMesh *dm)
if (ccgdm->gridOffset) MEM_freeN(ccgdm->gridOffset);
if (ccgdm->gridFlagMats) MEM_freeN(ccgdm->gridFlagMats);
if (ccgdm->gridHidden) {
- int i, numGrids = dm->getNumGrids(dm);
- for (i = 0; i < numGrids; i++) {
- if (ccgdm->gridHidden[i])
+ /* Using dm->getNumGrids(dm) accesses freed memory */
+ uint numGrids = ccgdm->numGrid;
+ for (uint i = 0; i < numGrids; i++) {
+ if (ccgdm->gridHidden[i]) {
MEM_freeN(ccgdm->gridHidden[i]);
+ }
}
MEM_freeN(ccgdm->gridHidden);
}
@@ -4041,6 +4079,10 @@ static void ccgDM_release(DerivedMesh *dm)
MEM_freeN(ccgdm->edgeMap);
MEM_freeN(ccgdm->faceMap);
}
+
+ BLI_mutex_end(&ccgdm->loops_cache_lock);
+ BLI_rw_mutex_end(&ccgdm->origindex_cache_rwlock);
+
MEM_freeN(ccgdm);
}
}
@@ -4055,14 +4097,14 @@ static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type)
int a, index, totnone, totorig;
/* Avoid re-creation if the layer exists already */
- BLI_rw_mutex_lock(&origindex_cache_rwlock, THREAD_LOCK_READ);
+ BLI_rw_mutex_lock(&ccgdm->origindex_cache_rwlock, THREAD_LOCK_READ);
origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
- BLI_rw_mutex_unlock(&origindex_cache_rwlock);
+ BLI_rw_mutex_unlock(&ccgdm->origindex_cache_rwlock);
if (origindex) {
return origindex;
}
- BLI_rw_mutex_lock(&origindex_cache_rwlock, THREAD_LOCK_WRITE);
+ BLI_rw_mutex_lock(&ccgdm->origindex_cache_rwlock, THREAD_LOCK_WRITE);
DM_add_vert_layer(dm, CD_ORIGINDEX, CD_CALLOC, NULL);
origindex = DM_get_vert_data_layer(dm, CD_ORIGINDEX);
@@ -4077,7 +4119,7 @@ static void *ccgDM_get_vert_data_layer(DerivedMesh *dm, int type)
CCGVert *v = ccgdm->vertMap[index].vert;
origindex[a] = ccgDM_getVertMapIndex(ccgdm->ss, v);
}
- BLI_rw_mutex_unlock(&origindex_cache_rwlock);
+ BLI_rw_mutex_unlock(&ccgdm->origindex_cache_rwlock);
return origindex;
}
@@ -4331,6 +4373,7 @@ static void ccgdm_create_grids(DerivedMesh *dm)
ccgdm->gridFaces = gridFaces;
ccgdm->gridOffset = gridOffset;
ccgdm->gridFlagMats = gridFlagMats;
+ ccgdm->numGrid = numGrids;
}
static CCGElem **ccgDM_getGridData(DerivedMesh *dm)
@@ -4402,7 +4445,7 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm)
{
CCGDerivedMesh *ccgdm = (CCGDerivedMesh *)dm;
CCGKey key;
- int numGrids, grid_pbvh;
+ int numGrids;
CCG_key_top_level(&key, ccgdm->ss);
@@ -4414,28 +4457,85 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm)
if (!ob->sculpt)
return NULL;
- grid_pbvh = ccgDM_use_grid_pbvh(ccgdm);
+ bool grid_pbvh = ccgDM_use_grid_pbvh(ccgdm);
+ if ((ob->mode & OB_MODE_SCULPT) == 0) {
+ /* In vwpaint, we may use a grid_pbvh for multires/subsurf, under certain conditions.
+ * More complex cases break 'history' trail back to original vertices, in that case we fall back to
+ * deformed cage only (i.e. original deformed mesh). */
+ VirtualModifierData virtualModifierData;
+ ModifierData *md = modifiers_getVirtualModifierList(ob, &virtualModifierData);
+
+ grid_pbvh = true;
+ bool has_one_ccg_modifier = false;
+ for (; md; md = md->next) {
+ /* We can only accept to use this ccgdm if:
+ * - it's the only active ccgdm in the stack.
+ * - there is no topology-modifying modifier in the stack.
+ * Otherwise, there is no way to map back to original geometry from grid-generated PBVH.
+ */
+ const ModifierTypeInfo *mti = modifierType_getInfo(md->type);
+
+ if (!modifier_isEnabled(NULL, md, eModifierMode_Realtime)) {
+ continue;
+ }
+ if (ELEM(mti->type, eModifierTypeType_OnlyDeform, eModifierTypeType_NonGeometrical)) {
+ continue;
+ }
+
+ if (ELEM(md->type, eModifierType_Subsurf, eModifierType_Multires)) {
+ if (has_one_ccg_modifier) {
+ /* We only allow a single active ccg modifier in the stack. */
+ grid_pbvh = false;
+ break;
+ }
+ has_one_ccg_modifier = true;
+ continue;
+ }
+
+ /* Any other non-deforming modifier makes it impossible to use grid pbvh. */
+ grid_pbvh = false;
+ break;
+ }
+ }
if (ob->sculpt->pbvh) {
+ /* Note that we have to clean up exisitng pbvh instead of updating it in case it does not match current
+ * grid_pbvh status. */
if (grid_pbvh) {
- /* pbvh's grids, gridadj and gridfaces points to data inside ccgdm
- * but this can be freed on ccgdm release, this updates the pointers
- * when the ccgdm gets remade, the assumption is that the topology
- * does not change. */
- ccgdm_create_grids(dm);
- BKE_pbvh_grids_update(ob->sculpt->pbvh, ccgdm->gridData, (void **)ccgdm->gridFaces,
- ccgdm->gridFlagMats, ccgdm->gridHidden);
+ if (BKE_pbvh_get_ccgdm(ob->sculpt->pbvh) != NULL) {
+ /* pbvh's grids, gridadj and gridfaces points to data inside ccgdm
+ * but this can be freed on ccgdm release, this updates the pointers
+ * when the ccgdm gets remade, the assumption is that the topology
+ * does not change. */
+ ccgdm_create_grids(dm);
+ BKE_pbvh_grids_update(ob->sculpt->pbvh, ccgdm->gridData, (void **)ccgdm->gridFaces,
+ ccgdm->gridFlagMats, ccgdm->gridHidden);
+ }
+ else {
+ BKE_pbvh_free(ob->sculpt->pbvh);
+ ob->sculpt->pbvh = NULL;
+ }
+ }
+ else if (BKE_pbvh_get_ccgdm(ob->sculpt->pbvh) != NULL) {
+ BKE_pbvh_free(ob->sculpt->pbvh);
+ ob->sculpt->pbvh = NULL;
}
ccgdm->pbvh = ob->sculpt->pbvh;
}
- if (ccgdm->pbvh)
+ if (ccgdm->pbvh) {
+ /* For grid pbvh, keep track of ccgdm */
+ if (grid_pbvh) {
+ BKE_pbvh_set_ccgdm(ccgdm->pbvh, ccgdm);
+ }
return ccgdm->pbvh;
+ }
- /* no pbvh exists yet, we need to create one. only in case of multires
+ /* No pbvh exists yet, we need to create one. only in case of multires
* we build a pbvh over the modified mesh, in other cases the base mesh
* is being sculpted, so we build a pbvh from that. */
+ /* Note: vwpaint tries to always build a pbvh over the modified mesh. */
if (grid_pbvh) {
ccgdm_create_grids(dm);
@@ -4461,11 +4561,29 @@ static struct PBVH *ccgDM_getPBVH(Object *ob, DerivedMesh *dm)
ob->sculpt->pbvh = ccgdm->pbvh = BKE_pbvh_new();
BKE_pbvh_build_mesh(ccgdm->pbvh, me->mpoly, me->mloop, me->mvert, me->totvert, &me->vdata,
looptri, looptris_num);
+
+ if (ob->sculpt->modifiers_active && ob->derivedDeform != NULL) {
+ DerivedMesh *deformdm = ob->derivedDeform;
+ float (*vertCos)[3];
+ int totvert;
+
+ totvert = deformdm->getNumVerts(deformdm);
+ vertCos = MEM_malloc_arrayN(totvert, sizeof(float[3]), "ccgDM_getPBVH vertCos");
+ deformdm->getVertCos(deformdm, vertCos);
+ BKE_pbvh_apply_vertCos(ccgdm->pbvh, vertCos);
+ MEM_freeN(vertCos);
+ }
}
- if (ccgdm->pbvh)
+ if (ccgdm->pbvh != NULL) {
pbvh_show_diffuse_color_set(ccgdm->pbvh, ob->sculpt->show_diffuse_color);
+ pbvh_show_mask_set(ccgdm->pbvh, ob->sculpt->show_mask);
+ }
+ /* For grid pbvh, keep track of ccgdm. */
+ if (grid_pbvh && ccgdm->pbvh) {
+ BKE_pbvh_set_ccgdm(ccgdm->pbvh, ccgdm);
+ }
return ccgdm->pbvh;
}
@@ -4474,16 +4592,17 @@ static void ccgDM_recalcTessellation(DerivedMesh *UNUSED(dm))
/* Nothing to do: CCG handles creating its own tessfaces */
}
+/* WARNING! *MUST* be called in an 'loops_cache_rwlock' protected thread context! */
static void ccgDM_recalcLoopTri(DerivedMesh *dm)
{
- BLI_rw_mutex_lock(&loops_cache_rwlock, THREAD_LOCK_WRITE);
- MLoopTri *mlooptri;
+ MLoopTri *mlooptri = dm->looptris.array;
const int tottri = dm->numPolyData * 2;
int i, poly_index;
DM_ensure_looptri_data(dm);
- mlooptri = dm->looptris.array;
+ mlooptri = dm->looptris.array_wip;
+ BLI_assert(tottri == 0 || mlooptri != NULL);
BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
BLI_assert(tottri == dm->looptris.num);
@@ -4502,19 +4621,10 @@ static void ccgDM_recalcLoopTri(DerivedMesh *dm)
lt->tri[2] = (poly_index * 4) + 2;
lt->poly = poly_index;
}
- BLI_rw_mutex_unlock(&loops_cache_rwlock);
-}
-static const MLoopTri *ccgDM_getLoopTriArray(DerivedMesh *dm)
-{
- if (dm->looptris.array) {
- BLI_assert(poly_to_tri_count(dm->numPolyData, dm->numLoopData) == dm->looptris.num);
- }
- else {
- dm->recalcLoopTri(dm);
- }
-
- return dm->looptris.array;
+ BLI_assert(dm->looptris.array == NULL);
+ atomic_cas_ptr((void **)&dm->looptris.array, dm->looptris.array, dm->looptris.array_wip);
+ dm->looptris.array_wip = NULL;
}
static void ccgDM_calcNormals(DerivedMesh *dm)
@@ -4533,8 +4643,6 @@ static void set_default_ccgdm_callbacks(CCGDerivedMesh *ccgdm)
ccgdm->dm.getNumPolys = ccgDM_getNumPolys;
ccgdm->dm.getNumTessFaces = ccgDM_getNumTessFaces;
- ccgdm->dm.getLoopTriArray = ccgDM_getLoopTriArray;
-
ccgdm->dm.getVert = ccgDM_getFinalVert;
ccgdm->dm.getEdge = ccgDM_getFinalEdge;
ccgdm->dm.getTessFace = ccgDM_getFinalFace;
@@ -4732,7 +4840,7 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm,
*((int *)ccgSubSurf_getFaceUserData(ss, f)) = vertNum;
#ifndef USE_DYNSIZE
- BLI_array_empty(loopidx);
+ BLI_array_clear(loopidx);
BLI_array_grow_items(loopidx, numVerts);
#endif
for (s = 0; s < numVerts; s++) {
@@ -4740,7 +4848,7 @@ static void set_ccgdm_all_geometry(CCGDerivedMesh *ccgdm,
}
#ifndef USE_DYNSIZE
- BLI_array_empty(vertidx);
+ BLI_array_clear(vertidx);
BLI_array_grow_items(vertidx, numVerts);
#endif
for (s = 0; s < numVerts; s++) {
@@ -5030,6 +5138,9 @@ static CCGDerivedMesh *getCCGDerivedMesh(CCGSubSurf *ss,
ccgdm->dm.numLoopData = ccgdm->dm.numPolyData * 4;
ccgdm->dm.numTessFaceData = 0;
+ BLI_mutex_init(&ccgdm->loops_cache_lock);
+ BLI_rw_mutex_init(&ccgdm->origindex_cache_rwlock);
+
return ccgdm;
}
diff --git a/source/blender/blenkernel/intern/text.c b/source/blender/blenkernel/intern/text.c
index 298790a9e9b..b650b6e9fb8 100644
--- a/source/blender/blenkernel/intern/text.c
+++ b/source/blender/blenkernel/intern/text.c
@@ -121,36 +121,66 @@
*
*/
+
+/* Undo opcodes */
+
+enum {
+ /* Complex editing */
+ /* 1 - opcode is followed by 1 byte for ascii character and opcode (repeat)) */
+ /* 2 - opcode is followed by 2 bytes for utf-8 character and opcode (repeat)) */
+ /* 3 - opcode is followed by 3 bytes for utf-8 character and opcode (repeat)) */
+ /* 4 - opcode is followed by 4 bytes for unicode character and opcode (repeat)) */
+ UNDO_INSERT_1 = 013,
+ UNDO_INSERT_2 = 014,
+ UNDO_INSERT_3 = 015,
+ UNDO_INSERT_4 = 016,
+
+ UNDO_BS_1 = 017,
+ UNDO_BS_2 = 020,
+ UNDO_BS_3 = 021,
+ UNDO_BS_4 = 022,
+
+ UNDO_DEL_1 = 023,
+ UNDO_DEL_2 = 024,
+ UNDO_DEL_3 = 025,
+ UNDO_DEL_4 = 026,
+
+ /* Text block (opcode is followed
+ * by 4 character length ID + the text
+ * block itself + the 4 character length
+ * ID (repeat) and opcode (repeat)) */
+ UNDO_DBLOCK = 027, /* Delete block */
+ UNDO_IBLOCK = 030, /* Insert block */
+
+ /* Misc */
+ UNDO_INDENT = 032,
+ UNDO_UNINDENT = 033,
+ UNDO_COMMENT = 034,
+ UNDO_UNCOMMENT = 035,
+
+ UNDO_MOVE_LINES_UP = 036,
+ UNDO_MOVE_LINES_DOWN = 037,
+
+ UNDO_DUPLICATE = 040,
+};
+
/***/
static void txt_pop_first(Text *text);
static void txt_pop_last(Text *text);
-static void txt_undo_add_blockop(Text *text, int op, const char *buf);
+static void txt_undo_add_blockop(Text *text, TextUndoBuf *utxt, int op, const char *buf);
static void txt_delete_line(Text *text, TextLine *line);
-static void txt_delete_sel(Text *text);
+static void txt_delete_sel(Text *text, TextUndoBuf *utxt);
static void txt_make_dirty(Text *text);
/***/
-static unsigned char undoing;
-
-/* allow to switch off undoing externally */
-void txt_set_undostate(int u)
-{
- undoing = u;
-}
-
-int txt_get_undostate(void)
-{
- return undoing;
-}
-
-static void init_undo_text(Text *text)
-{
- text->undo_pos = -1;
- text->undo_len = TXT_INIT_UNDO;
- text->undo_buf = MEM_mallocN(text->undo_len, "undo buf");
-}
+/**
+ * Set to true when undoing (so we don't generate undo steps while undoing).
+ *
+ * Also use to disable undo entirely.
+ */
+static bool undoing;
/**
* \note caller must handle `undo_buf` and `compiled` members.
@@ -179,7 +209,6 @@ void BKE_text_free(Text *text)
BKE_text_free_lines(text);
MEM_SAFE_FREE(text->name);
- MEM_SAFE_FREE(text->undo_buf);
#ifdef WITH_PYTHON
BPY_text_free_code(text);
#endif
@@ -193,8 +222,6 @@ void BKE_text_init(Text *ta)
ta->name = NULL;
- init_undo_text(ta);
-
ta->nlines = 1;
ta->flags = TXT_ISDIRTY | TXT_ISMEM;
if ((U.flag & USER_TXT_TABSTOSPACES_DISABLE) == 0)
@@ -224,7 +251,7 @@ Text *BKE_text_add(Main *bmain, const char *name)
{
Text *ta;
- ta = BKE_libblock_alloc(bmain, ID_TXT, name);
+ ta = BKE_libblock_alloc(bmain, ID_TXT, name, 0);
BKE_text_init(ta);
@@ -376,10 +403,6 @@ bool BKE_text_reload(Text *text)
txt_make_dirty(text);
/* clear undo buffer */
- MEM_freeN(text->undo_buf);
- init_undo_text(text);
-
-
if (BLI_stat(filepath_abs, &st) != -1) {
text->mtime = st.st_mtime;
}
@@ -410,7 +433,7 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const
return false;
}
- ta = BKE_libblock_alloc(bmain, ID_TXT, BLI_path_basename(filepath_abs));
+ ta = BKE_libblock_alloc(bmain, ID_TXT, BLI_path_basename(filepath_abs), 0);
ta->id.us = 0;
BLI_listbase_clear(&ta->lines);
@@ -428,8 +451,6 @@ Text *BKE_text_load_ex(Main *bmain, const char *file, const char *relpath, const
}
/* clear undo buffer */
- init_undo_text(ta);
-
if (BLI_stat(filepath_abs, &st) != -1) {
ta->mtime = st.st_mtime;
}
@@ -449,53 +470,47 @@ Text *BKE_text_load(Main *bmain, const char *file, const char *relpath)
return BKE_text_load_ex(bmain, file, relpath, false);
}
-Text *BKE_text_copy(Main *bmain, Text *ta)
+/**
+ * Only copy internal data of Text ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_text_copy_data(Main *UNUSED(bmain), Text *ta_dst, const Text *ta_src, const int UNUSED(flag))
{
- Text *tan;
- TextLine *line, *tmp;
-
- tan = BKE_libblock_copy(bmain, &ta->id);
-
/* file name can be NULL */
- if (ta->name) {
- tan->name = BLI_strdup(ta->name);
- }
- else {
- tan->name = NULL;
+ if (ta_src->name) {
+ ta_dst->name = BLI_strdup(ta_src->name);
}
- tan->flags = ta->flags | TXT_ISDIRTY;
-
- BLI_listbase_clear(&tan->lines);
- tan->curl = tan->sell = NULL;
- tan->compiled = NULL;
-
- tan->nlines = ta->nlines;
+ ta_dst->flags |= TXT_ISDIRTY;
- line = ta->lines.first;
- /* Walk down, reconstructing */
- while (line) {
- tmp = (TextLine *) MEM_mallocN(sizeof(TextLine), "textline");
- tmp->line = MEM_mallocN(line->len + 1, "textline_string");
- tmp->format = NULL;
-
- strcpy(tmp->line, line->line);
+ BLI_listbase_clear(&ta_dst->lines);
+ ta_dst->curl = ta_dst->sell = NULL;
+ ta_dst->compiled = NULL;
- tmp->len = line->len;
-
- BLI_addtail(&tan->lines, tmp);
-
- line = line->next;
- }
+ /* Walk down, reconstructing */
+ for (TextLine *line_src = ta_src->lines.first; line_src; line_src = line_src->next) {
+ TextLine *line_dst = MEM_mallocN(sizeof(*line_dst), __func__);
- tan->curl = tan->sell = tan->lines.first;
- tan->curc = tan->selc = 0;
+ line_dst->line = BLI_strdup(line_src->line);
+ line_dst->format = NULL;
+ line_dst->len = line_src->len;
- init_undo_text(tan);
+ BLI_addtail(&ta_dst->lines, line_dst);
+ }
- BKE_id_copy_ensure_local(bmain, &ta->id, &tan->id);
+ ta_dst->curl = ta_dst->sell = ta_dst->lines.first;
+ ta_dst->curc = ta_dst->selc = 0;
+}
- return tan;
+Text *BKE_text_copy(Main *bmain, const Text *ta)
+{
+ Text *ta_copy;
+ BKE_id_copy_ex(bmain, &ta->id, (ID **)&ta_copy, 0, false);
+ return ta_copy;
}
void BKE_text_make_local(Main *bmain, Text *text, const bool lib_local)
@@ -503,27 +518,28 @@ void BKE_text_make_local(Main *bmain, Text *text, const bool lib_local)
BKE_id_make_local_generic(bmain, &text->id, true, lib_local);
}
-void BKE_text_clear(Text *text) /* called directly from rna */
+void BKE_text_clear(Text *text, TextUndoBuf *utxt) /* called directly from rna */
{
- int oldstate;
+ const bool undoing_orig = undoing;
+ undoing = (utxt == NULL);
- oldstate = txt_get_undostate();
- txt_set_undostate(1);
txt_sel_all(text);
- txt_delete_sel(text);
- txt_set_undostate(oldstate);
+ txt_delete_sel(text, utxt);
+
+ undoing = undoing_orig;
txt_make_dirty(text);
}
-void BKE_text_write(Text *text, const char *str) /* called directly from rna */
+void BKE_text_write(Text *text, TextUndoBuf *utxt, const char *str) /* called directly from rna */
{
- int oldstate;
+ const bool undoing_orig = undoing;
+ undoing = (utxt == NULL);
- oldstate = txt_get_undostate();
- txt_insert_buf(text, str);
+ txt_insert_buf(text, utxt, str);
txt_move_eof(text, 0);
- txt_set_undostate(oldstate);
+
+ undoing = undoing_orig;
txt_make_dirty(text);
}
@@ -1114,7 +1130,7 @@ bool txt_has_sel(Text *text)
return ((text->curl != text->sell) || (text->curc != text->selc));
}
-static void txt_delete_sel(Text *text)
+static void txt_delete_sel(Text *text, TextUndoBuf *utxt)
{
TextLine *tmpl;
char *buf;
@@ -1128,7 +1144,7 @@ static void txt_delete_sel(Text *text)
if (!undoing) {
buf = txt_sel_to_buf(text);
- txt_undo_add_blockop(text, UNDO_DBLOCK, buf);
+ txt_undo_add_blockop(text, utxt, UNDO_DBLOCK, buf);
MEM_freeN(buf);
}
@@ -1369,89 +1385,107 @@ char *txt_sel_to_buf(Text *text)
return buf;
}
-void txt_insert_buf(Text *text, const char *in_buffer)
+void txt_insert_buf(Text *text, TextUndoBuf *utxt, const char *in_buffer)
{
- int l = 0, u, len;
+ const bool undoing_orig = undoing;
+ int l = 0, len;
size_t i = 0, j;
TextLine *add;
char *buffer;
if (!in_buffer) return;
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
len = strlen(in_buffer);
buffer = BLI_strdupn(in_buffer, len);
len += txt_extended_ascii_as_utf8(&buffer);
- if (!undoing) txt_undo_add_blockop(text, UNDO_IBLOCK, buffer);
-
- u = undoing;
- undoing = 1;
+ if (!undoing) {
+ txt_undo_add_blockop(text, utxt, UNDO_IBLOCK, buffer);
+ }
+ undoing = true;
/* Read the first line (or as close as possible */
- while (buffer[i] && buffer[i] != '\n')
- txt_add_raw_char(text, BLI_str_utf8_as_unicode_step(buffer, &i));
+ while (buffer[i] && buffer[i] != '\n') {
+ txt_add_raw_char(text, utxt, BLI_str_utf8_as_unicode_step(buffer, &i));
+ }
- if (buffer[i] == '\n') txt_split_curline(text);
- else { undoing = u; MEM_freeN(buffer); return; }
- i++;
+ if (buffer[i] == '\n') {
+ txt_split_curline(text, utxt);
+ i++;
- while (i < len) {
- l = 0;
+ while (i < len) {
+ l = 0;
- while (buffer[i] && buffer[i] != '\n') {
- i++; l++;
- }
-
- if (buffer[i] == '\n') {
- add = txt_new_linen(buffer + (i - l), l);
- BLI_insertlinkbefore(&text->lines, text->curl, add);
- i++;
- }
- else {
- for (j = i - l; j < i && j < len; )
- txt_add_raw_char(text, BLI_str_utf8_as_unicode_step(buffer, &j));
- break;
+ while (buffer[i] && buffer[i] != '\n') {
+ i++;
+ l++;
+ }
+
+ if (buffer[i] == '\n') {
+ add = txt_new_linen(buffer + (i - l), l);
+ BLI_insertlinkbefore(&text->lines, text->curl, add);
+ i++;
+ }
+ else {
+ for (j = i - l; j < i && j < len; ) {
+ txt_add_raw_char(text, utxt, BLI_str_utf8_as_unicode_step(buffer, &j));
+ }
+ break;
+ }
}
}
-
- MEM_freeN(buffer);
- undoing = u;
+ MEM_freeN(buffer);
+ undoing = undoing_orig;
}
/******************/
/* Undo functions */
/******************/
-static bool max_undo_test(Text *text, int x)
+static bool max_undo_test(TextUndoBuf *utxt, int x)
{
- while (text->undo_pos + x >= text->undo_len) {
- if (text->undo_len * 2 > TXT_MAX_UNDO) {
- /* XXX error("Undo limit reached, buffer cleared\n"); */
- MEM_freeN(text->undo_buf);
- init_undo_text(text);
- return false;
- }
- else {
- void *tmp = text->undo_buf;
- text->undo_buf = MEM_callocN(text->undo_len * 2, "undo buf");
- memcpy(text->undo_buf, tmp, text->undo_len);
- text->undo_len *= 2;
- MEM_freeN(tmp);
- }
- }
+ /* Normally over-allocating is preferred,
+ * however in this case the buffer is small enough and re-allocation
+ * fast enough for each undo step that it's not a problem to allocate each time.
+ * This also saves on some memory when we have many text buffers
+ * that would have an empty undo memory allocated.
+ */
+ /* Add one for the null terminator. */
+ utxt->len = utxt->pos + x + 1;
+ if (utxt->len > TXT_MAX_UNDO) {
+ /* XXX error("Undo limit reached, buffer cleared\n"); */
+ MEM_freeN(utxt->buf);
+ return false;
+ }
+ else {
+ /* Small reallocations on each undo step is fine. */
+ utxt->buf = MEM_recallocN(utxt->buf, utxt->len);
+ }
return true;
}
+static void txt_undo_end(Text *UNUSED(text), TextUndoBuf *utxt)
+{
+ int undo_pos_end = utxt->pos + 1;
+ BLI_assert(undo_pos_end + 1 == utxt->len);
+ utxt->buf[undo_pos_end] = '\0';
+}
+
+/* Call once undo is done. */
+#ifndef NDEBUG
+
+#endif
+
#if 0 /* UNUSED */
-static void dump_buffer(Text *text)
+static void dump_buffer(TextUndoBuf *utxt)
{
int i = 0;
-
- while (i++ < text->undo_pos) printf("%d: %d %c\n", i, text->undo_buf[i], text->undo_buf[i]);
+
+ while (i++ < utxt->undo_pos) printf("%d: %d %c\n", i, utxt->buf[i], utxt->buf[i]);
}
/* Note: this function is outdated and must be updated if needed for future use */
@@ -1466,10 +1500,10 @@ void txt_print_undo(Text *text)
printf("---< Undo Buffer >---\n");
- printf("UndoPosition is %d\n", text->undo_pos);
+ printf("UndoPosition is %d\n", utxt->pos);
- while (i <= text->undo_pos) {
- op = text->undo_buf[i];
+ while (i <= utxt->pos) {
+ op = utxt->buf[i];
if (op == UNDO_INSERT_1) {
ops = "Insert ascii ";
@@ -1535,15 +1569,15 @@ void txt_print_undo(Text *text)
printf(" - Char is ");
switch (op) {
case UNDO_INSERT_1: case UNDO_BS_1: case UNDO_DEL_1:
- printf("%c", text->undo_buf[i]);
+ printf("%c", utxt->buf[i]);
i++;
break;
case UNDO_INSERT_2: case UNDO_BS_2: case UNDO_DEL_2:
- printf("%c%c", text->undo_buf[i], text->undo_buf[i + 1]);
+ printf("%c%c", utxt->buf[i], utxt->buf[i + 1]);
i += 2;
break;
case UNDO_INSERT_3: case UNDO_BS_3: case UNDO_DEL_3:
- printf("%c%c%c", text->undo_buf[i], text->undo_buf[i + 1], text->undo_buf[i + 2]);
+ printf("%c%c%c", utxt->buf[i], utxt->buf[i + 1], utxt->buf[i + 2]);
i += 3;
break;
case UNDO_INSERT_4: case UNDO_BS_4: case UNDO_DEL_4:
@@ -1551,10 +1585,10 @@ void txt_print_undo(Text *text)
unsigned int uc;
char c[BLI_UTF8_MAX + 1];
size_t c_len;
- uc = text->undo_buf[i]; i++;
- uc = uc + (text->undo_buf[i] << 8); i++;
- uc = uc + (text->undo_buf[i] << 16); i++;
- uc = uc + (text->undo_buf[i] << 24); i++;
+ uc = utxt->buf[i]; i++;
+ uc = uc + (utxt->buf[i] << 8); i++;
+ uc = uc + (utxt->buf[i] << 16); i++;
+ uc = uc + (utxt->buf[i] << 24); i++;
c_len = BLI_str_utf8_from_unicode(uc, c);
c[c_len] = '\0';
puts(c);
@@ -1565,44 +1599,44 @@ void txt_print_undo(Text *text)
else if (op == UNDO_DBLOCK || op == UNDO_IBLOCK) {
i++;
- linep = text->undo_buf[i]; i++;
- linep = linep + (text->undo_buf[i] << 8); i++;
- linep = linep + (text->undo_buf[i] << 16); i++;
- linep = linep + (text->undo_buf[i] << 24); i++;
+ linep = utxt->buf[i]; i++;
+ linep = linep + (utxt->buf[i] << 8); i++;
+ linep = linep + (utxt->buf[i] << 16); i++;
+ linep = linep + (utxt->buf[i] << 24); i++;
printf(" (length %d) <", linep);
while (linep > 0) {
- putchar(text->undo_buf[i]);
+ putchar(utxt->buf[i]);
linep--; i++;
}
- linep = text->undo_buf[i]; i++;
- linep = linep + (text->undo_buf[i] << 8); i++;
- linep = linep + (text->undo_buf[i] << 16); i++;
- linep = linep + (text->undo_buf[i] << 24); i++;
+ linep = utxt->buf[i]; i++;
+ linep = linep + (utxt->buf[i] << 8); i++;
+ linep = linep + (utxt->buf[i] << 16); i++;
+ linep = linep + (utxt->buf[i] << 24); i++;
printf("> (%d)", linep);
}
else if (op == UNDO_INDENT || op == UNDO_UNINDENT) {
i++;
- charp = text->undo_buf[i]; i++;
- charp = charp + (text->undo_buf[i] << 8); i++;
+ charp = utxt->buf[i]; i++;
+ charp = charp + (utxt->buf[i] << 8); i++;
- linep = text->undo_buf[i]; i++;
- linep = linep + (text->undo_buf[i] << 8); i++;
- linep = linep + (text->undo_buf[i] << 16); i++;
- linep = linep + (text->undo_buf[i] << 24); i++;
+ linep = utxt->buf[i]; i++;
+ linep = linep + (utxt->buf[i] << 8); i++;
+ linep = linep + (utxt->buf[i] << 16); i++;
+ linep = linep + (utxt->buf[i] << 24); i++;
printf("to <%d, %d> ", linep, charp);
- charp = text->undo_buf[i]; i++;
- charp = charp + (text->undo_buf[i] << 8); i++;
+ charp = utxt->buf[i]; i++;
+ charp = charp + (utxt->buf[i] << 8); i++;
- linep = text->undo_buf[i]; i++;
- linep = linep + (text->undo_buf[i] << 8); i++;
- linep = linep + (text->undo_buf[i] << 16); i++;
- linep = linep + (text->undo_buf[i] << 24); i++;
+ linep = utxt->buf[i]; i++;
+ linep = linep + (utxt->buf[i] << 8); i++;
+ linep = linep + (utxt->buf[i] << 16); i++;
+ linep = linep + (utxt->buf[i] << 24); i++;
printf("from <%d, %d>", linep, charp);
}
@@ -1633,104 +1667,114 @@ static void txt_undo_store_uint32(char *undo_buf, int *undo_pos, unsigned int va
(*undo_pos)++;
}
-/* store the cur cursor to the undo buffer */
-static void txt_undo_store_cur(Text *text)
+/* store the cur cursor to the undo buffer (6 bytes)*/
+static void txt_undo_store_cur(Text *text, TextUndoBuf *utxt)
{
- txt_undo_store_uint16(text->undo_buf, &text->undo_pos, text->curc);
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, txt_get_span(text->lines.first, text->curl));
+ txt_undo_store_uint16(utxt->buf, &utxt->pos, text->curc);
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, txt_get_span(text->lines.first, text->curl));
}
-/* store the sel cursor to the undo buffer */
-static void txt_undo_store_sel(Text *text)
+/* store the sel cursor to the undo buffer (6 bytes) */
+static void txt_undo_store_sel(Text *text, TextUndoBuf *utxt)
{
- txt_undo_store_uint16(text->undo_buf, &text->undo_pos, text->selc);
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, txt_get_span(text->lines.first, text->sell));
+ txt_undo_store_uint16(utxt->buf, &utxt->pos, text->selc);
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, txt_get_span(text->lines.first, text->sell));
}
-/* store both cursors to the undo buffer */
-static void txt_undo_store_cursors(Text *text)
+/* store both cursors to the undo buffer (12 bytes) */
+static void txt_undo_store_cursors(Text *text, TextUndoBuf *utxt)
{
- txt_undo_store_cur(text);
- txt_undo_store_sel(text);
+ txt_undo_store_cur(text, utxt);
+ txt_undo_store_sel(text, utxt);
}
/* store an operator along with a block of data */
-static void txt_undo_add_blockop(Text *text, int op, const char *buf)
+static void txt_undo_add_blockop(Text *text, TextUndoBuf *utxt, int op, const char *buf)
{
unsigned int length = strlen(buf);
-
- if (!max_undo_test(text, length + 11 + 12))
- return;
-
- text->undo_pos++;
- text->undo_buf[text->undo_pos] = op;
- text->undo_pos++;
-
- txt_undo_store_cursors(text);
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, length);
-
- strncpy(text->undo_buf + text->undo_pos, buf, length);
- text->undo_pos += length;
-
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, length);
- text->undo_buf[text->undo_pos] = op;
-
- text->undo_buf[text->undo_pos + 1] = 0;
+ if (!max_undo_test(utxt, 2 + 12 + 4 + length + 4 + 1)) {
+ return;
+ }
+ /* 2 bytes */
+ utxt->pos++;
+ utxt->buf[utxt->pos] = op;
+ utxt->pos++;
+ /* 12 bytes */
+ txt_undo_store_cursors(text, utxt);
+ /* 4 bytes */
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, length);
+ /* 'length' bytes */
+ strncpy(utxt->buf + utxt->pos, buf, length);
+ utxt->pos += length;
+ /* 4 bytes */
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, length);
+ /* 1 byte */
+ utxt->buf[utxt->pos] = op;
+
+ txt_undo_end(text, utxt);
}
/* store a regular operator */
-void txt_undo_add_op(Text *text, int op)
+void txt_undo_add_op(Text *text, TextUndoBuf *utxt, int op)
{
- if (!max_undo_test(text, 15))
+ if (!max_undo_test(utxt, 2 + 12 + 1)) {
return;
+ }
- text->undo_pos++;
- text->undo_buf[text->undo_pos] = op;
+ /* 2 bytes */
+ utxt->pos++;
+ utxt->buf[utxt->pos] = op;
+ utxt->pos++;
+ /* 12 bytes */
+ txt_undo_store_cursors(text, utxt);
+ /* 1 byte */
+ utxt->buf[utxt->pos] = op;
- text->undo_pos++;
-
- txt_undo_store_cursors(text);
-
- text->undo_buf[text->undo_pos] = op;
- text->undo_buf[text->undo_pos + 1] = 0;
+ txt_undo_end(text, utxt);
}
/* store an operator for a single character */
-static void txt_undo_add_charop(Text *text, int op_start, unsigned int c)
+static void txt_undo_add_charop(Text *text, TextUndoBuf *utxt, int op_start, unsigned int c)
{
char utf8[BLI_UTF8_MAX];
size_t i, utf8_size = BLI_str_utf8_from_unicode(c, utf8);
- if (!max_undo_test(text, 3 + utf8_size + 12))
- return;
-
- text->undo_pos++;
-
- if (utf8_size < 4) {
- text->undo_buf[text->undo_pos] = op_start + utf8_size - 1;
- text->undo_pos++;
-
- txt_undo_store_cur(text);
-
+ if (utf8_size < 4 && 0) {
+ if (!max_undo_test(utxt, 2 + 6 + utf8_size + 1)) {
+ return;
+ }
+ /* 2 bytes */
+ utxt->pos++;
+ utxt->buf[utxt->pos] = op_start + utf8_size - 1;
+ utxt->pos++;
+ /* 6 bytes */
+ txt_undo_store_cur(text, utxt);
+ /* 'utf8_size' bytes */
for (i = 0; i < utf8_size; i++) {
- text->undo_buf[text->undo_pos] = utf8[i];
- text->undo_pos++;
+ utxt->buf[utxt->pos] = utf8[i];
+ utxt->pos++;
}
-
- text->undo_buf[text->undo_pos] = op_start + utf8_size - 1;
+ /* 1 byte */
+ utxt->buf[utxt->pos] = op_start + utf8_size - 1;
}
else {
- text->undo_buf[text->undo_pos] = op_start + 3;
- text->undo_pos++;
-
- txt_undo_store_cursors(text);
-
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, c);
- text->undo_buf[text->undo_pos] = op_start + 3;
+ if (!max_undo_test(utxt, 2 + 6 + 4 + 1)) {
+ return;
+ }
+ /* 2 bytes */
+ utxt->pos++;
+ utxt->buf[utxt->pos] = op_start + 3;
+ utxt->pos++;
+ /* 6 bytes */
+ txt_undo_store_cur(text, utxt);
+ /* 4 bytes */
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, c);
+ /* 1 byte */
+ utxt->buf[utxt->pos] = op_start + 3;
}
- text->undo_buf[text->undo_pos + 1] = 0;
+ txt_undo_end(text, utxt);
}
/* extends Link */
@@ -1744,7 +1788,7 @@ struct LinkInt {
* of the lines that should not be indented back.
*/
static void txt_undo_add_unprefix_op(
- Text *text, char undo_op,
+ Text *text, TextUndoBuf *utxt, char undo_op,
const ListBase *line_index_mask, const int line_index_mask_len)
{
struct LinkInt *idata;
@@ -1752,30 +1796,35 @@ static void txt_undo_add_unprefix_op(
BLI_assert(BLI_listbase_count(line_index_mask) == line_index_mask_len);
/* OP byte + UInt32 count + counted UInt32 line numbers + UInt32 count + 12-bytes selection + OP byte */
- if (!max_undo_test(text, 1 + 4 + (line_index_mask_len * 4) + 4 + 12 + 1)) {
+ if (!max_undo_test(utxt, 2 + 4 + (line_index_mask_len * 4) + 4 + 12 + 1)) {
return;
}
- /* Opening buffer sequence with OP */
- text->undo_pos++;
- text->undo_buf[text->undo_pos] = undo_op;
- text->undo_pos++;
- /* Adding number of line numbers to read */
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, line_index_mask_len);
+ /* 2 bytes */
+ utxt->pos++;
+ utxt->buf[utxt->pos] = undo_op;
+ utxt->pos++;
+ /* Adding number of line numbers to read
+ * 4 bytes */
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, line_index_mask_len);
- /* Adding linenumbers of lines that shall not be indented if undoing */
+ /* Adding linenumbers of lines that shall not be indented if undoing.
+ * 'line_index_mask_len * 4' bytes */
for (idata = line_index_mask->first; idata; idata = idata->next) {
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, idata->value);
- }
-
- /* Adding number of line numbers to read again */
- txt_undo_store_uint32(text->undo_buf, &text->undo_pos, line_index_mask_len);
- /* Adding current selection */
- txt_undo_store_cursors(text);
- /* Closing with OP (same as above) */
- text->undo_buf[text->undo_pos] = undo_op;
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, idata->value);
+ }
+
+ /* Adding number of line numbers to read again.
+ * 4 bytes */
+ txt_undo_store_uint32(utxt->buf, &utxt->pos, line_index_mask_len);
+ /* Adding current selection.
+ * 12 bytes */
+ txt_undo_store_cursors(text, utxt);
+ /* Closing with OP (same as above).
+ * 1 byte */
+ utxt->buf[utxt->pos] = undo_op;
/* Marking as last undo operation */
- text->undo_buf[text->undo_pos + 1] = 0;
+ txt_undo_end(text, utxt);
}
static unsigned short txt_undo_read_uint16(const char *undo_buf, int *undo_pos)
@@ -1918,7 +1967,7 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s
unicode = BLI_str_utf8_as_unicode(utf8);
break;
case 4: /* 32-bit unicode symbol */
- unicode = txt_undo_read_uint32(undo_buf, undo_pos);
+ unicode = txt_redo_read_uint32(undo_buf, undo_pos);
break;
default:
/* should never happen */
@@ -1930,9 +1979,9 @@ static unsigned int txt_redo_read_unicode(const char *undo_buf, int *undo_pos, s
return unicode;
}
-void txt_do_undo(Text *text)
+void txt_do_undo(Text *text, TextUndoBuf *utxt)
{
- int op = text->undo_buf[text->undo_pos];
+ int op = utxt->buf[utxt->pos];
int prev_flags;
unsigned int linep;
unsigned int uni_char;
@@ -1941,11 +1990,11 @@ void txt_do_undo(Text *text)
unsigned short charp;
char *buf;
- if (text->undo_pos < 0) {
+ if (utxt->pos < 0) {
return;
}
- text->undo_pos--;
+ utxt->pos--;
undoing = 1;
@@ -1954,16 +2003,16 @@ void txt_do_undo(Text *text)
case UNDO_INSERT_2:
case UNDO_INSERT_3:
case UNDO_INSERT_4:
- text->undo_pos -= op - UNDO_INSERT_1 + 1;
+ utxt->pos -= op - UNDO_INSERT_1 + 1;
/* get and restore the cursors */
- txt_undo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
- txt_delete_char(text);
+ txt_delete_char(text, utxt);
- text->undo_pos--;
+ utxt->pos--;
break;
case UNDO_BS_1:
@@ -1971,16 +2020,16 @@ void txt_do_undo(Text *text)
case UNDO_BS_3:
case UNDO_BS_4:
charp = op - UNDO_BS_1 + 1;
- uni_char = txt_undo_read_unicode(text->undo_buf, &text->undo_pos, charp);
+ uni_char = txt_undo_read_unicode(utxt->buf, &utxt->pos, charp);
/* get and restore the cursors */
- txt_undo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
- txt_add_char(text, uni_char);
+ txt_add_char(text, utxt, uni_char);
- text->undo_pos--;
+ utxt->pos--;
break;
case UNDO_DEL_1:
@@ -1988,50 +2037,50 @@ void txt_do_undo(Text *text)
case UNDO_DEL_3:
case UNDO_DEL_4:
charp = op - UNDO_DEL_1 + 1;
- uni_char = txt_undo_read_unicode(text->undo_buf, &text->undo_pos, charp);
+ uni_char = txt_undo_read_unicode(utxt->buf, &utxt->pos, charp);
/* get and restore the cursors */
- txt_undo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_undo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
- txt_add_char(text, uni_char);
+ txt_add_char(text, utxt, uni_char);
txt_move_left(text, 0);
- text->undo_pos--;
+ utxt->pos--;
break;
case UNDO_DBLOCK:
{
int i;
/* length of the string in the buffer */
- linep = txt_undo_read_uint32(text->undo_buf, &text->undo_pos);
+ linep = txt_undo_read_uint32(utxt->buf, &utxt->pos);
buf = MEM_mallocN(linep + 1, "dblock buffer");
for (i = 0; i < linep; i++) {
- buf[(linep - 1) - i] = text->undo_buf[text->undo_pos];
- text->undo_pos--;
+ buf[(linep - 1) - i] = utxt->buf[utxt->pos];
+ utxt->pos--;
}
buf[i] = 0;
/* skip over the length that was stored again */
- text->undo_pos -= 4;
+ utxt->pos -= 4;
/* Get the cursor positions */
- txt_undo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
/* move cur to location that needs buff inserted */
txt_move_to(text, curln, curc, 0);
- txt_insert_buf(text, buf);
+ txt_insert_buf(text, utxt, buf);
MEM_freeN(buf);
/* restore the cursors */
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
- text->undo_pos--;
+ utxt->pos--;
break;
}
@@ -2039,23 +2088,23 @@ void txt_do_undo(Text *text)
{
int i;
/* length of the string in the buffer */
- linep = txt_undo_read_uint32(text->undo_buf, &text->undo_pos);
+ linep = txt_undo_read_uint32(utxt->buf, &utxt->pos);
/* txt_backspace_char removes utf8-characters, not bytes */
buf = MEM_mallocN(linep + 1, "iblock buffer");
for (i = 0; i < linep; i++) {
- buf[(linep - 1) - i] = text->undo_buf[text->undo_pos];
- text->undo_pos--;
+ buf[(linep - 1) - i] = utxt->buf[utxt->pos];
+ utxt->pos--;
}
buf[i] = 0;
linep = BLI_strlen_utf8(buf);
MEM_freeN(buf);
/* skip over the length that was stored again */
- text->undo_pos -= 4;
+ utxt->pos -= 4;
/* get and restore the cursors */
- txt_undo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
@@ -2071,9 +2120,9 @@ void txt_do_undo(Text *text)
text->flags = prev_flags;
}
- txt_delete_selected(text);
+ txt_delete_selected(text, utxt);
- text->undo_pos--;
+ utxt->pos--;
break;
}
case UNDO_INDENT:
@@ -2082,37 +2131,37 @@ void txt_do_undo(Text *text)
case UNDO_MOVE_LINES_UP:
case UNDO_MOVE_LINES_DOWN:
/* get and restore the cursors */
- txt_undo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
if (op == UNDO_INDENT) {
- txt_unindent(text);
+ txt_unindent(text, utxt);
}
else if (op == UNDO_COMMENT) {
- txt_uncomment(text);
+ txt_uncomment(text, utxt);
}
else if (op == UNDO_DUPLICATE) {
txt_delete_line(text, text->curl->next);
}
else if (op == UNDO_MOVE_LINES_UP) {
- txt_move_lines(text, TXT_MOVE_LINE_DOWN);
+ txt_move_lines(text, utxt, TXT_MOVE_LINE_DOWN);
}
else if (op == UNDO_MOVE_LINES_DOWN) {
- txt_move_lines(text, TXT_MOVE_LINE_UP);
+ txt_move_lines(text, utxt, TXT_MOVE_LINE_UP);
}
- text->undo_pos--;
+ utxt->pos--;
break;
case UNDO_UNINDENT:
case UNDO_UNCOMMENT:
{
- void (*txt_prefix_fn)(Text *);
- void (*txt_unprefix_fn)(Text *);
+ void (*txt_prefix_fn)(Text *, TextUndoBuf *);
+ void (*txt_unprefix_fn)(Text *, TextUndoBuf *);
int count;
int i;
/* Get and restore the cursors */
- txt_undo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_undo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
@@ -2126,30 +2175,30 @@ void txt_do_undo(Text *text)
txt_unprefix_fn = txt_uncomment;
}
- txt_prefix_fn(text);
+ txt_prefix_fn(text, utxt);
/* Get the count */
- count = txt_undo_read_uint32(text->undo_buf, &text->undo_pos);
+ count = txt_undo_read_uint32(utxt->buf, &utxt->pos);
/* Iterate! */
txt_pop_sel(text);
for (i = 0; i < count; i++) {
- txt_move_to(text, txt_undo_read_uint32(text->undo_buf, &text->undo_pos), 0, 0);
+ txt_move_to(text, txt_undo_read_uint32(utxt->buf, &utxt->pos), 0, 0);
/* Un-un-unindent/comment */
- txt_unprefix_fn(text);
+ txt_unprefix_fn(text, utxt);
}
/* Restore selection */
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
/* Jumo over count */
- txt_undo_read_uint32(text->undo_buf, &text->undo_pos);
+ txt_undo_read_uint32(utxt->buf, &utxt->pos);
/* Jump over closing OP byte */
- text->undo_pos--;
+ utxt->pos--;
break;
}
default:
//XXX error("Undo buffer error - resetting");
- text->undo_pos = -1;
+ utxt->pos = -1;
break;
}
@@ -2157,7 +2206,7 @@ void txt_do_undo(Text *text)
undoing = 0;
}
-void txt_do_redo(Text *text)
+void txt_do_redo(Text *text, TextUndoBuf *utxt)
{
char op;
char *buf;
@@ -2167,11 +2216,11 @@ void txt_do_redo(Text *text)
unsigned int curln, selln;
unsigned short curc, selc;
- text->undo_pos++;
- op = text->undo_buf[text->undo_pos];
+ utxt->pos++;
+ op = utxt->buf[utxt->pos];
if (!op) {
- text->undo_pos--;
+ utxt->pos--;
return;
}
@@ -2182,35 +2231,35 @@ void txt_do_redo(Text *text)
case UNDO_INSERT_2:
case UNDO_INSERT_3:
case UNDO_INSERT_4:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
charp = op - UNDO_INSERT_1 + 1;
- uni_uchar = txt_redo_read_unicode(text->undo_buf, &text->undo_pos, charp);
+ uni_uchar = txt_redo_read_unicode(utxt->buf, &utxt->pos, charp);
- txt_add_char(text, uni_uchar);
+ txt_add_char(text, utxt, uni_uchar);
break;
case UNDO_BS_1:
case UNDO_BS_2:
case UNDO_BS_3:
case UNDO_BS_4:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
- text->undo_pos += op - UNDO_BS_1 + 1;
+ utxt->pos += op - UNDO_BS_1 + 1;
/* move right so we backspace the correct char */
txt_move_right(text, 0);
- txt_backspace_char(text);
+ txt_backspace_char(text, utxt);
break;
@@ -2218,60 +2267,60 @@ void txt_do_redo(Text *text)
case UNDO_DEL_2:
case UNDO_DEL_3:
case UNDO_DEL_4:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cur(text->undo_buf, &text->undo_pos, &curln, &curc);
+ txt_redo_read_cur(utxt->buf, &utxt->pos, &curln, &curc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
- text->undo_pos += op - UNDO_DEL_1 + 1;
+ utxt->pos += op - UNDO_DEL_1 + 1;
- txt_delete_char(text);
+ txt_delete_char(text, utxt);
break;
case UNDO_DBLOCK:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_redo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
/* length of the block */
- linep = txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
+ linep = txt_redo_read_uint32(utxt->buf, &utxt->pos);
- text->undo_pos += linep;
+ utxt->pos += linep;
/* skip over the length that was stored again */
- text->undo_pos += 4;
+ utxt->pos += 4;
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
break;
case UNDO_IBLOCK:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_redo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, curln, curc, 1);
/* length of the block */
- linep = txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
+ linep = txt_redo_read_uint32(utxt->buf, &utxt->pos);
buf = MEM_mallocN(linep + 1, "iblock buffer");
- memcpy(buf, &text->undo_buf[text->undo_pos], linep);
- text->undo_pos += linep;
+ memcpy(buf, &utxt->buf[utxt->pos], linep);
+ utxt->pos += linep;
buf[linep] = 0;
- txt_insert_buf(text, buf);
+ txt_insert_buf(text, utxt, buf);
MEM_freeN(buf);
/* skip over the length that was stored again */
- text->undo_pos += 4;
+ utxt->pos += 4;
break;
@@ -2281,38 +2330,38 @@ void txt_do_redo(Text *text)
case UNDO_DUPLICATE:
case UNDO_MOVE_LINES_UP:
case UNDO_MOVE_LINES_DOWN:
- text->undo_pos++;
+ utxt->pos++;
/* get and restore the cursors */
- txt_redo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_redo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
if (op == UNDO_INDENT) {
- txt_indent(text);
+ txt_indent(text, utxt);
}
else if (op == UNDO_COMMENT) {
- txt_comment(text);
+ txt_comment(text, utxt);
}
else if (op == UNDO_UNCOMMENT) {
- txt_uncomment(text);
+ txt_uncomment(text, utxt);
}
else if (op == UNDO_DUPLICATE) {
- txt_duplicate_line(text);
+ txt_duplicate_line(text, utxt);
}
else if (op == UNDO_MOVE_LINES_UP) {
/* offset the cursor by + 1 */
txt_move_to(text, curln + 1, curc, 0);
txt_move_to(text, selln + 1, selc, 1);
- txt_move_lines(text, TXT_MOVE_LINE_UP);
+ txt_move_lines(text, utxt, TXT_MOVE_LINE_UP);
}
else if (op == UNDO_MOVE_LINES_DOWN) {
/* offset the cursor by - 1 */
txt_move_to(text, curln - 1, curc, 0);
txt_move_to(text, selln - 1, selc, 1);
- txt_move_lines(text, TXT_MOVE_LINE_DOWN);
+ txt_move_lines(text, utxt, TXT_MOVE_LINE_DOWN);
}
/* re-restore the cursors since they got moved when redoing */
@@ -2325,24 +2374,24 @@ void txt_do_redo(Text *text)
int count;
int i;
- text->undo_pos++;
+ utxt->pos++;
/* Scan all the stuff described in txt_undo_add_unindent_op */
- count = txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
+ count = txt_redo_read_uint32(utxt->buf, &utxt->pos);
for (i = 0; i < count; i++) {
- txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
+ txt_redo_read_uint32(utxt->buf, &utxt->pos);
}
/* Count again */
- txt_redo_read_uint32(text->undo_buf, &text->undo_pos);
+ txt_redo_read_uint32(utxt->buf, &utxt->pos);
/* Get the selection and re-unindent */
- txt_redo_read_cursors(text->undo_buf, &text->undo_pos, &curln, &curc, &selln, &selc);
+ txt_redo_read_cursors(utxt->buf, &utxt->pos, &curln, &curc, &selln, &selc);
txt_move_to(text, curln, curc, 0);
txt_move_to(text, selln, selc, 1);
- txt_unindent(text);
+ txt_unindent(text, utxt);
break;
}
default:
//XXX error("Undo buffer error - resetting");
- text->undo_pos = -1;
+ utxt->pos = -1;
break;
}
@@ -2354,16 +2403,16 @@ void txt_do_redo(Text *text)
/* Line editing functions */
/**************************/
-void txt_split_curline(Text *text)
+void txt_split_curline(Text *text, TextUndoBuf *utxt)
{
TextLine *ins;
char *left, *right;
if (!text->curl) return;
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
- if (!undoing) txt_undo_add_charop(text, UNDO_INSERT_1, '\n');
+ if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, '\n');
/* Make the two half strings */
@@ -2435,7 +2484,7 @@ static void txt_combine_lines(Text *text, TextLine *linea, TextLine *lineb)
txt_clean_text(text);
}
-void txt_duplicate_line(Text *text)
+void txt_duplicate_line(Text *text, TextUndoBuf *utxt)
{
TextLine *textline;
@@ -2448,18 +2497,18 @@ void txt_duplicate_line(Text *text)
txt_make_dirty(text);
txt_clean_text(text);
- if (!undoing) txt_undo_add_op(text, UNDO_DUPLICATE);
+ if (!undoing) txt_undo_add_op(text, utxt, UNDO_DUPLICATE);
}
}
-void txt_delete_char(Text *text)
+void txt_delete_char(Text *text, TextUndoBuf *utxt)
{
unsigned int c = '\n';
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
txt_make_dirty(text);
return;
}
@@ -2485,24 +2534,24 @@ void txt_delete_char(Text *text)
txt_make_dirty(text);
txt_clean_text(text);
- if (!undoing) txt_undo_add_charop(text, UNDO_DEL_1, c);
+ if (!undoing) txt_undo_add_charop(text, utxt, UNDO_DEL_1, c);
}
-void txt_delete_word(Text *text)
+void txt_delete_word(Text *text, TextUndoBuf *utxt)
{
txt_jump_right(text, true, true);
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
txt_make_dirty(text);
}
-void txt_backspace_char(Text *text)
+void txt_backspace_char(Text *text, TextUndoBuf *utxt)
{
unsigned int c = '\n';
if (!text->curl) return;
if (txt_has_sel(text)) { /* deleting a selection */
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
txt_make_dirty(text);
return;
}
@@ -2534,13 +2583,13 @@ void txt_backspace_char(Text *text)
txt_make_dirty(text);
txt_clean_text(text);
- if (!undoing) txt_undo_add_charop(text, UNDO_BS_1, c);
+ if (!undoing) txt_undo_add_charop(text, utxt, UNDO_BS_1, c);
}
-void txt_backspace_word(Text *text)
+void txt_backspace_word(Text *text, TextUndoBuf *utxt)
{
txt_jump_left(text, true, true);
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
txt_make_dirty(text);
}
@@ -2549,17 +2598,17 @@ void txt_backspace_word(Text *text)
* Remember to change this string according to max tab size */
static char tab_to_spaces[] = " ";
-static void txt_convert_tab_to_spaces(Text *text)
+static void txt_convert_tab_to_spaces(Text *text, TextUndoBuf *utxt)
{
/* sb aims to pad adjust the tab-width needed so that the right number of spaces
* is added so that the indention of the line is the right width (i.e. aligned
* to multiples of TXT_TABSIZE)
*/
const char *sb = &tab_to_spaces[text->curc % TXT_TABSIZE];
- txt_insert_buf(text, sb);
+ txt_insert_buf(text, utxt, sb);
}
-static bool txt_add_char_intern(Text *text, unsigned int add, bool replace_tabs)
+static bool txt_add_char_intern(Text *text, TextUndoBuf *utxt, unsigned int add, bool replace_tabs)
{
char *tmp, ch[BLI_UTF8_MAX];
size_t add_len;
@@ -2567,19 +2616,19 @@ static bool txt_add_char_intern(Text *text, unsigned int add, bool replace_tabs)
if (!text->curl) return 0;
if (add == '\n') {
- txt_split_curline(text);
+ txt_split_curline(text, utxt);
return true;
}
/* insert spaces rather than tabs */
if (add == '\t' && replace_tabs) {
- txt_convert_tab_to_spaces(text);
+ txt_convert_tab_to_spaces(text, utxt);
return true;
}
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
- if (!undoing) txt_undo_add_charop(text, UNDO_INSERT_1, add);
+ if (!undoing) txt_undo_add_charop(text, utxt, UNDO_INSERT_1, add);
add_len = BLI_str_utf8_from_unicode(add, ch);
@@ -2601,23 +2650,23 @@ static bool txt_add_char_intern(Text *text, unsigned int add, bool replace_tabs)
return 1;
}
-bool txt_add_char(Text *text, unsigned int add)
+bool txt_add_char(Text *text, TextUndoBuf *utxt, unsigned int add)
{
- return txt_add_char_intern(text, add, (text->flags & TXT_TABSTOSPACES) != 0);
+ return txt_add_char_intern(text, utxt, add, (text->flags & TXT_TABSTOSPACES) != 0);
}
-bool txt_add_raw_char(Text *text, unsigned int add)
+bool txt_add_raw_char(Text *text, TextUndoBuf *utxt, unsigned int add)
{
- return txt_add_char_intern(text, add, 0);
+ return txt_add_char_intern(text, utxt, add, 0);
}
-void txt_delete_selected(Text *text)
+void txt_delete_selected(Text *text, TextUndoBuf *utxt)
{
- txt_delete_sel(text);
+ txt_delete_sel(text, utxt);
txt_make_dirty(text);
}
-bool txt_replace_char(Text *text, unsigned int add)
+bool txt_replace_char(Text *text, TextUndoBuf *utxt, unsigned int add)
{
unsigned int del;
size_t del_size = 0, add_size;
@@ -2627,7 +2676,7 @@ bool txt_replace_char(Text *text, unsigned int add)
/* 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') {
- return txt_add_char(text, add);
+ return txt_add_char(text, utxt, add);
}
del = BLI_str_utf8_as_unicode_and_size(text->curl->line + text->curc, &del_size);
@@ -2655,10 +2704,10 @@ bool txt_replace_char(Text *text, unsigned int add)
/* Should probably create a new op for this */
if (!undoing) {
- txt_undo_add_charop(text, UNDO_INSERT_1, add);
+ txt_undo_add_charop(text, utxt, UNDO_INSERT_1, add);
text->curc -= add_size;
txt_pop_sel(text);
- txt_undo_add_charop(text, UNDO_DEL_1, del);
+ txt_undo_add_charop(text, utxt, UNDO_DEL_1, del);
text->curc += add_size;
txt_pop_sel(text);
}
@@ -2798,7 +2847,7 @@ static void txt_select_unprefix(
/* caller must handle undo */
}
-void txt_comment(Text *text)
+void txt_comment(Text *text, TextUndoBuf *utxt)
{
const char *prefix = "#";
@@ -2809,11 +2858,11 @@ void txt_comment(Text *text)
txt_select_prefix(text, prefix);
if (!undoing) {
- txt_undo_add_op(text, UNDO_COMMENT);
+ txt_undo_add_op(text, utxt, UNDO_COMMENT);
}
}
-void txt_uncomment(Text *text)
+void txt_uncomment(Text *text, TextUndoBuf *utxt)
{
const char *prefix = "#";
ListBase line_index_mask;
@@ -2826,13 +2875,13 @@ void txt_uncomment(Text *text)
txt_select_unprefix(text, prefix, &line_index_mask, &line_index_mask_len);
if (!undoing) {
- txt_undo_add_unprefix_op(text, UNDO_UNCOMMENT, &line_index_mask, line_index_mask_len);
+ txt_undo_add_unprefix_op(text, utxt, UNDO_UNCOMMENT, &line_index_mask, line_index_mask_len);
}
BLI_freelistN(&line_index_mask);
}
-void txt_indent(Text *text)
+void txt_indent(Text *text, TextUndoBuf *utxt)
{
const char *prefix = (text->flags & TXT_TABSTOSPACES) ? tab_to_spaces : "\t";
@@ -2843,11 +2892,11 @@ void txt_indent(Text *text)
txt_select_prefix(text, prefix);
if (!undoing) {
- txt_undo_add_op(text, UNDO_INDENT);
+ txt_undo_add_op(text, utxt, UNDO_INDENT);
}
}
-void txt_unindent(Text *text)
+void txt_unindent(Text *text, TextUndoBuf *utxt)
{
const char *prefix = (text->flags & TXT_TABSTOSPACES) ? tab_to_spaces : "\t";
ListBase line_index_mask;
@@ -2860,13 +2909,13 @@ void txt_unindent(Text *text)
txt_select_unprefix(text, prefix, &line_index_mask, &line_index_mask_len);
if (!undoing) {
- txt_undo_add_unprefix_op(text, UNDO_UNINDENT, &line_index_mask, line_index_mask_len);
+ txt_undo_add_unprefix_op(text, utxt, UNDO_UNINDENT, &line_index_mask, line_index_mask_len);
}
BLI_freelistN(&line_index_mask);
}
-void txt_move_lines(struct Text *text, const int direction)
+void txt_move_lines(struct Text *text, TextUndoBuf *utxt, const int direction)
{
TextLine *line_other;
@@ -2893,7 +2942,7 @@ void txt_move_lines(struct Text *text, const int direction)
txt_clean_text(text);
if (!undoing) {
- txt_undo_add_op(text, (direction == TXT_MOVE_LINE_DOWN) ? UNDO_MOVE_LINES_DOWN : UNDO_MOVE_LINES_UP);
+ txt_undo_add_op(text, utxt, (direction == TXT_MOVE_LINE_DOWN) ? UNDO_MOVE_LINES_DOWN : UNDO_MOVE_LINES_UP);
}
}
diff --git a/source/blender/blenkernel/intern/texture.c b/source/blender/blenkernel/intern/texture.c
index 60990c03b0e..250408642bb 100644
--- a/source/blender/blenkernel/intern/texture.c
+++ b/source/blender/blenkernel/intern/texture.c
@@ -55,9 +55,9 @@
#include "IMB_imbuf.h"
-#include "BKE_global.h"
#include "BKE_main.h"
+#include "BKE_colorband.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_library_remap.h"
@@ -185,7 +185,7 @@ void BKE_texture_colormapping_default(ColorMapping *colormap)
{
memset(colormap, 0, sizeof(ColorMapping));
- init_colorband(&colormap->coba, true);
+ BKE_colorband_init(&colormap->coba, true);
colormap->bright = 1.0;
colormap->contrast = 1.0;
@@ -198,365 +198,6 @@ void BKE_texture_colormapping_default(ColorMapping *colormap)
colormap->blend_factor = 0.0f;
}
-/* ****************** COLORBAND ******************* */
-
-void init_colorband(ColorBand *coba, bool rangetype)
-{
- int a;
-
- coba->data[0].pos = 0.0;
- coba->data[1].pos = 1.0;
-
- if (rangetype == 0) {
- coba->data[0].r = 0.0;
- coba->data[0].g = 0.0;
- coba->data[0].b = 0.0;
- coba->data[0].a = 0.0;
-
- coba->data[1].r = 1.0;
- coba->data[1].g = 1.0;
- coba->data[1].b = 1.0;
- coba->data[1].a = 1.0;
- }
- else {
- coba->data[0].r = 0.0;
- coba->data[0].g = 0.0;
- coba->data[0].b = 0.0;
- coba->data[0].a = 1.0;
-
- coba->data[1].r = 1.0;
- coba->data[1].g = 1.0;
- coba->data[1].b = 1.0;
- coba->data[1].a = 1.0;
- }
-
- for (a = 2; a < MAXCOLORBAND; a++) {
- coba->data[a].r = 0.5;
- coba->data[a].g = 0.5;
- coba->data[a].b = 0.5;
- coba->data[a].a = 1.0;
- coba->data[a].pos = 0.5;
- }
-
- coba->tot = 2;
- coba->color_mode = COLBAND_BLEND_RGB;
-}
-
-ColorBand *add_colorband(bool rangetype)
-{
- ColorBand *coba;
-
- coba = MEM_callocN(sizeof(ColorBand), "colorband");
- init_colorband(coba, rangetype);
-
- return coba;
-}
-
-/* ------------------------------------------------------------------------- */
-
-static float colorband_hue_interp(
- const int ipotype_hue,
- const float mfac, const float fac,
- float h1, float h2)
-{
- float h_interp;
- int mode = 0;
-
-#define HUE_INTERP(h_a, h_b) ((mfac * (h_a)) + (fac * (h_b)))
-#define HUE_MOD(h) (((h) < 1.0f) ? (h) : (h) - 1.0f)
-
- h1 = HUE_MOD(h1);
- h2 = HUE_MOD(h2);
-
- BLI_assert(h1 >= 0.0f && h1 < 1.0f);
- BLI_assert(h2 >= 0.0f && h2 < 1.0f);
-
- switch (ipotype_hue) {
- case COLBAND_HUE_NEAR:
- {
- if ((h1 < h2) && (h2 - h1) > +0.5f) mode = 1;
- else if ((h1 > h2) && (h2 - h1) < -0.5f) mode = 2;
- else mode = 0;
- break;
- }
- case COLBAND_HUE_FAR:
- {
- if ((h1 < h2) && (h2 - h1) < +0.5f) mode = 1;
- else if ((h1 > h2) && (h2 - h1) > -0.5f) mode = 2;
- else mode = 0;
- break;
- }
- case COLBAND_HUE_CCW:
- {
- if (h1 > h2) mode = 2;
- else mode = 0;
- break;
- }
- case COLBAND_HUE_CW:
- {
- if (h1 < h2) mode = 1;
- else mode = 0;
- break;
- }
- }
-
- switch (mode) {
- case 0:
- h_interp = HUE_INTERP(h1, h2);
- break;
- case 1:
- h_interp = HUE_INTERP(h1 + 1.0f, h2);
- h_interp = HUE_MOD(h_interp);
- break;
- case 2:
- h_interp = HUE_INTERP(h1, h2 + 1.0f);
- h_interp = HUE_MOD(h_interp);
- break;
- }
-
- BLI_assert(h_interp >= 0.0f && h_interp < 1.0f);
-
-#undef HUE_INTERP
-#undef HUE_MOD
-
- return h_interp;
-}
-
-bool do_colorband(const ColorBand *coba, float in, float out[4])
-{
- const CBData *cbd1, *cbd2, *cbd0, *cbd3;
- float fac;
- int ipotype;
- int a;
-
- if (coba == NULL || coba->tot == 0) return false;
-
- cbd1 = coba->data;
-
- ipotype = (coba->color_mode == COLBAND_BLEND_RGB) ? coba->ipotype : COLBAND_INTERP_LINEAR;
-
- if (coba->tot == 1) {
- out[0] = cbd1->r;
- out[1] = cbd1->g;
- out[2] = cbd1->b;
- out[3] = cbd1->a;
- }
- else if ((in <= cbd1->pos) && ELEM(ipotype, COLBAND_INTERP_LINEAR, COLBAND_INTERP_EASE)) {
- out[0] = cbd1->r;
- out[1] = cbd1->g;
- out[2] = cbd1->b;
- out[3] = cbd1->a;
- }
- else {
- CBData left, right;
-
- /* we're looking for first pos > in */
- for (a = 0; a < coba->tot; a++, cbd1++) {
- if (cbd1->pos > in) {
- break;
- }
- }
-
- if (a == coba->tot) {
- cbd2 = cbd1 - 1;
- right = *cbd2;
- right.pos = 1.0f;
- cbd1 = &right;
- }
- else if (a == 0) {
- left = *cbd1;
- left.pos = 0.0f;
- cbd2 = &left;
- }
- else {
- cbd2 = cbd1 - 1;
- }
-
- if ((in >= cbd1->pos) && ELEM(ipotype, COLBAND_INTERP_LINEAR, COLBAND_INTERP_EASE)) {
- out[0] = cbd1->r;
- out[1] = cbd1->g;
- out[2] = cbd1->b;
- out[3] = cbd1->a;
- }
- else {
-
- if (cbd2->pos != cbd1->pos) {
- fac = (in - cbd1->pos) / (cbd2->pos - cbd1->pos);
- }
- else {
- /* was setting to 0.0 in 2.56 & previous, but this
- * is incorrect for the last element, see [#26732] */
- fac = (a != coba->tot) ? 0.0f : 1.0f;
- }
-
- if (ipotype == COLBAND_INTERP_CONSTANT) {
- /* constant */
- out[0] = cbd2->r;
- out[1] = cbd2->g;
- out[2] = cbd2->b;
- out[3] = cbd2->a;
- }
- else if (ipotype >= COLBAND_INTERP_B_SPLINE) {
- /* ipo from right to left: 3 2 1 0 */
- float t[4];
-
- if (a >= coba->tot - 1) cbd0 = cbd1;
- else cbd0 = cbd1 + 1;
- if (a < 2) cbd3 = cbd2;
- else cbd3 = cbd2 - 1;
-
- CLAMP(fac, 0.0f, 1.0f);
-
- if (ipotype == COLBAND_INTERP_CARDINAL) {
- key_curve_position_weights(fac, t, KEY_CARDINAL);
- }
- else {
- key_curve_position_weights(fac, t, KEY_BSPLINE);
- }
-
- out[0] = t[3] * cbd3->r + t[2] * cbd2->r + t[1] * cbd1->r + t[0] * cbd0->r;
- out[1] = t[3] * cbd3->g + t[2] * cbd2->g + t[1] * cbd1->g + t[0] * cbd0->g;
- out[2] = t[3] * cbd3->b + t[2] * cbd2->b + t[1] * cbd1->b + t[0] * cbd0->b;
- out[3] = t[3] * cbd3->a + t[2] * cbd2->a + t[1] * cbd1->a + t[0] * cbd0->a;
- CLAMP(out[0], 0.0f, 1.0f);
- CLAMP(out[1], 0.0f, 1.0f);
- CLAMP(out[2], 0.0f, 1.0f);
- CLAMP(out[3], 0.0f, 1.0f);
- }
- else {
- float mfac;
-
- if (ipotype == COLBAND_INTERP_EASE) {
- mfac = fac * fac;
- fac = 3.0f * mfac - 2.0f * mfac * fac;
- }
-
- mfac = 1.0f - fac;
-
- if (UNLIKELY(coba->color_mode == COLBAND_BLEND_HSV)) {
- float col1[3], col2[3];
-
- rgb_to_hsv_v(&cbd1->r, col1);
- rgb_to_hsv_v(&cbd2->r, col2);
-
- out[0] = colorband_hue_interp(coba->ipotype_hue, mfac, fac, col1[0], col2[0]);
- out[1] = mfac * col1[1] + fac * col2[1];
- out[2] = mfac * col1[2] + fac * col2[2];
- out[3] = mfac * cbd1->a + fac * cbd2->a;
-
- hsv_to_rgb_v(out, out);
- }
- else if (UNLIKELY(coba->color_mode == COLBAND_BLEND_HSL)) {
- float col1[3], col2[3];
-
- rgb_to_hsl_v(&cbd1->r, col1);
- rgb_to_hsl_v(&cbd2->r, col2);
-
- out[0] = colorband_hue_interp(coba->ipotype_hue, mfac, fac, col1[0], col2[0]);
- out[1] = mfac * col1[1] + fac * col2[1];
- out[2] = mfac * col1[2] + fac * col2[2];
- out[3] = mfac * cbd1->a + fac * cbd2->a;
-
- hsl_to_rgb_v(out, out);
- }
- else {
- /* COLBAND_BLEND_RGB */
- out[0] = mfac * cbd1->r + fac * cbd2->r;
- out[1] = mfac * cbd1->g + fac * cbd2->g;
- out[2] = mfac * cbd1->b + fac * cbd2->b;
- out[3] = mfac * cbd1->a + fac * cbd2->a;
- }
- }
- }
- }
- return true; /* 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]);
-}
-
-static int vergcband(const void *a1, const void *a2)
-{
- const CBData *x1 = a1, *x2 = a2;
-
- if (x1->pos > x2->pos) return 1;
- else if (x1->pos < x2->pos) return -1;
- return 0;
-}
-
-void colorband_update_sort(ColorBand *coba)
-{
- int a;
-
- if (coba->tot < 2)
- return;
-
- for (a = 0; a < coba->tot; a++)
- coba->data[a].cur = a;
-
- qsort(coba->data, coba->tot, sizeof(CBData), vergcband);
-
- for (a = 0; a < coba->tot; a++) {
- if (coba->data[a].cur == coba->cur) {
- coba->cur = a;
- break;
- }
- }
-}
-
-CBData *colorband_element_add(struct ColorBand *coba, float position)
-{
- if (coba->tot == MAXCOLORBAND) {
- return NULL;
- }
- else {
- CBData *xnew;
-
- xnew = &coba->data[coba->tot];
- xnew->pos = position;
-
- if (coba->tot != 0) {
- do_colorband(coba, position, &xnew->r);
- }
- else {
- zero_v4(&xnew->r);
- }
- }
-
- coba->tot++;
- coba->cur = coba->tot - 1;
-
- colorband_update_sort(coba);
-
- return coba->data + coba->cur;
-}
-
-int colorband_element_remove(struct ColorBand *coba, int index)
-{
- int a;
-
- if (coba->tot < 2)
- return 0;
-
- if (index < 0 || index >= coba->tot)
- return 0;
-
- for (a = index; a < coba->tot; a++) {
- coba->data[a] = coba->data[a + 1];
- }
- if (coba->cur) coba->cur--;
- coba->tot--;
- return 1;
-}
-
/* ******************* TEX ************************ */
/** Free (or release) any data used by this texture (does not free the texure itself). */
@@ -707,7 +348,7 @@ Tex *BKE_texture_add(Main *bmain, const char *name)
{
Tex *tex;
- tex = BKE_libblock_alloc(bmain, ID_TE, name);
+ tex = BKE_libblock_alloc(bmain, ID_TE, name, 0);
BKE_texture_default(tex);
@@ -770,6 +411,7 @@ void BKE_texture_mtex_default(MTex *mtex)
mtex->kinkfac = 1.0f;
mtex->kinkampfac = 1.0f;
mtex->roughfac = 1.0f;
+ mtex->twistfac = 1.0f;
mtex->padensfac = 1.0f;
mtex->lifefac = 1.0f;
mtex->sizefac = 1.0f;
@@ -846,41 +488,73 @@ MTex *BKE_texture_mtex_add_id(ID *id, int slot)
/* ------------------------------------------------------------------------- */
-Tex *BKE_texture_copy(Main *bmain, Tex *tex)
+/**
+ * Only copy internal data of Texture ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_texture_copy_data(Main *bmain, Tex *tex_dst, const Tex *tex_src, const int flag)
{
- Tex *texn;
-
- texn = BKE_libblock_copy(bmain, &tex->id);
- if (BKE_texture_is_image_user(tex)) {
- id_us_plus((ID *)texn->ima);
+ /* We never handle usercount here for own data. */
+ const int flag_subdata = flag | LIB_ID_CREATE_NO_USER_REFCOUNT;
+
+ if (!BKE_texture_is_image_user(tex_src)) {
+ tex_dst->ima = NULL;
}
- else {
- texn->ima = NULL;
+
+ if (tex_dst->coba) {
+ tex_dst->coba = MEM_dupallocN(tex_dst->coba);
+ }
+ if (tex_dst->env) {
+ tex_dst->env = BKE_texture_envmap_copy(tex_dst->env, flag_subdata);
+ }
+ if (tex_dst->pd) {
+ tex_dst->pd = BKE_texture_pointdensity_copy(tex_dst->pd, flag_subdata);
+ }
+ if (tex_dst->vd) {
+ tex_dst->vd = MEM_dupallocN(tex_dst->vd);
+ }
+ if (tex_dst->ot) {
+ tex_dst->ot = BKE_texture_ocean_copy(tex_dst->ot, flag_subdata);
}
-
- if (texn->coba) texn->coba = MEM_dupallocN(texn->coba);
- if (texn->env) texn->env = BKE_texture_envmap_copy(texn->env);
- if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd);
- if (texn->vd) texn->vd = MEM_dupallocN(texn->vd);
- if (texn->ot) texn->ot = BKE_texture_ocean_copy(texn->ot);
- if (tex->nodetree) {
- if (tex->nodetree->execdata) {
- ntreeTexEndExecTree(tex->nodetree->execdata);
+ if (tex_src->nodetree) {
+ if (tex_src->nodetree->execdata) {
+ ntreeTexEndExecTree(tex_src->nodetree->execdata);
}
- texn->nodetree = ntreeCopyTree(bmain, tex->nodetree);
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)tex_src->nodetree, (ID **)&tex_dst->nodetree, flag, false);
}
- BKE_previewimg_id_copy(&texn->id, &tex->id);
-
- BKE_id_copy_ensure_local(bmain, &tex->id, &texn->id);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&tex_dst->id, &tex_src->id);
+ }
+ else {
+ tex_dst->preview = NULL;
+ }
+}
- return texn;
+Tex *BKE_texture_copy(Main *bmain, const Tex *tex)
+{
+ Tex *tex_copy;
+ BKE_id_copy_ex(bmain, &tex->id, (ID **)&tex_copy, 0, false);
+ return tex_copy;
}
/* texture copy without adding to main dbase */
Tex *BKE_texture_localize(Tex *tex)
{
+ /* TODO replace with something like
+ * Tex *tex_copy;
+ * BKE_id_copy_ex(bmain, &tex->id, (ID **)&tex_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false);
+ * return tex_copy;
+ *
+ * ... Once f*** nodes are fully converted to that too :( */
+
Tex *texn;
texn = BKE_libblock_copy_nolib(&tex->id, false);
@@ -889,17 +563,17 @@ Tex *BKE_texture_localize(Tex *tex)
if (texn->coba) texn->coba = MEM_dupallocN(texn->coba);
if (texn->env) {
- texn->env = BKE_texture_envmap_copy(texn->env);
+ texn->env = BKE_texture_envmap_copy(texn->env, LIB_ID_CREATE_NO_USER_REFCOUNT);
id_us_min(&texn->env->ima->id);
}
- if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd);
+ if (texn->pd) texn->pd = BKE_texture_pointdensity_copy(texn->pd, LIB_ID_CREATE_NO_USER_REFCOUNT);
if (texn->vd) {
texn->vd = MEM_dupallocN(texn->vd);
if (texn->vd->dataset)
texn->vd->dataset = MEM_dupallocN(texn->vd->dataset);
}
if (texn->ot) {
- texn->ot = BKE_texture_ocean_copy(tex->ot);
+ texn->ot = BKE_texture_ocean_copy(tex->ot, LIB_ID_CREATE_NO_USER_REFCOUNT);
}
texn->preview = NULL;
@@ -1099,6 +773,8 @@ void set_active_mtex(ID *id, short act)
case ID_PA:
((ParticleSettings *)id)->texact = act;
break;
+ default:
+ break;
}
}
@@ -1131,6 +807,10 @@ void set_current_material_texture(Material *ma, Tex *newtex)
ma->mtex[act] = BKE_texture_mtex_add();
/* Reset this slot's ON/OFF toggle, for materials, when slot was empty. */
ma->septex &= ~(1 << act);
+ /* For volumes the default UV texture coordinates are not available. */
+ if (ma->material_type == MA_TYPE_VOLUME) {
+ ma->mtex[act]->texco = TEXCO_ORCO;
+ }
}
ma->mtex[act]->tex = newtex;
@@ -1263,16 +943,20 @@ EnvMap *BKE_texture_envmap_add(void)
/* ------------------------------------------------------------------------- */
-EnvMap *BKE_texture_envmap_copy(EnvMap *env)
+EnvMap *BKE_texture_envmap_copy(const EnvMap *env, const int flag)
{
EnvMap *envn;
int a;
envn = MEM_dupallocN(env);
envn->ok = 0;
- for (a = 0; a < 6; a++) envn->cube[a] = NULL;
- if (envn->ima) id_us_plus((ID *)envn->ima);
-
+ for (a = 0; a < 6; a++) {
+ envn->cube[a] = NULL;
+ }
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus((ID *)envn->ima);
+ }
+
return envn;
}
@@ -1315,7 +999,7 @@ void BKE_texture_pointdensity_init_data(PointDensity *pd)
pd->noise_depth = 1;
pd->noise_fac = 1.0f;
pd->noise_influence = TEX_PD_NOISE_STATIC;
- pd->coba = add_colorband(true);
+ pd->coba = BKE_colorband_add(true);
pd->speed_scale = 1.0f;
pd->totpoints = 0;
pd->object = NULL;
@@ -1336,14 +1020,16 @@ PointDensity *BKE_texture_pointdensity_add(void)
return pd;
}
-PointDensity *BKE_texture_pointdensity_copy(PointDensity *pd)
+PointDensity *BKE_texture_pointdensity_copy(const PointDensity *pd, const int UNUSED(flag))
{
PointDensity *pdn;
pdn = MEM_dupallocN(pd);
pdn->point_tree = NULL;
pdn->point_data = NULL;
- if (pdn->coba) pdn->coba = MEM_dupallocN(pdn->coba);
+ if (pdn->coba) {
+ pdn->coba = MEM_dupallocN(pdn->coba);
+ }
pdn->falloff_curve = curvemapping_copy(pdn->falloff_curve); /* can be NULL */
return pdn;
}
@@ -1430,7 +1116,7 @@ OceanTex *BKE_texture_ocean_add(void)
return ot;
}
-OceanTex *BKE_texture_ocean_copy(struct OceanTex *ot)
+OceanTex *BKE_texture_ocean_copy(const OceanTex *ot, const int UNUSED(flag))
{
OceanTex *otn = MEM_dupallocN(ot);
@@ -1519,3 +1205,33 @@ void BKE_texture_get_value(
{
BKE_texture_get_value_ex(scene, texture, tex_co, texres, NULL, use_color_management);
}
+
+static void texture_nodes_fetch_images_for_pool(Tex *texture, bNodeTree *ntree, struct ImagePool *pool)
+{
+ for (bNode *node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == SH_NODE_TEX_IMAGE && node->id != NULL) {
+ Image *image = (Image *)node->id;
+ BKE_image_pool_acquire_ibuf(image, &texture->iuser, pool);
+ }
+ else if (node->type == NODE_GROUP && node->id != NULL) {
+ /* TODO(sergey): Do we need to control recursion here? */
+ bNodeTree *nested_tree = (bNodeTree *)node->id;
+ texture_nodes_fetch_images_for_pool(texture, nested_tree, pool);
+ }
+ }
+}
+
+/* Make sure all images used by texture are loaded into pool. */
+void BKE_texture_fetch_images_for_pool(Tex *texture, struct ImagePool *pool)
+{
+ if (texture->nodetree != NULL) {
+ texture_nodes_fetch_images_for_pool(texture, texture->nodetree, pool);
+ }
+ else {
+ if (texture->type == TEX_IMAGE) {
+ if (texture->ima != NULL) {
+ BKE_image_pool_acquire_ibuf(texture->ima, &texture->iuser, pool);
+ }
+ }
+ }
+}
diff --git a/source/blender/blenkernel/intern/tracking.c b/source/blender/blenkernel/intern/tracking.c
index 990d250b854..f9d34534a45 100644
--- a/source/blender/blenkernel/intern/tracking.c
+++ b/source/blender/blenkernel/intern/tracking.c
@@ -190,7 +190,7 @@ void BKE_tracking_free(MovieTracking *tracking)
}
/* Copy the whole list of tracks. */
-static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHash *tracks_mapping)
+static void tracking_tracks_copy(ListBase *tracks_dst, const ListBase *tracks_src, GHash *tracks_mapping, const int flag)
{
MovieTrackingTrack *track_dst, *track_src;
@@ -202,7 +202,9 @@ static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHa
if (track_src->markers) {
track_dst->markers = MEM_dupallocN(track_src->markers);
}
- id_us_plus(&track_dst->gpd->id);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus(&track_dst->gpd->id);
+ }
BLI_addtail(tracks_dst, track_dst);
BLI_ghash_insert(tracks_mapping, track_src, track_dst);
}
@@ -210,7 +212,8 @@ static void tracking_tracks_copy(ListBase *tracks_dst, ListBase *tracks_src, GHa
/* copy the whole list of plane tracks (need whole MovieTracking structures due to embedded pointers to tracks).
* WARNING: implies tracking_[dst/src] and their tracks have already been copied. */
-static void tracking_plane_tracks_copy(ListBase *plane_tracks_dst, ListBase *plane_tracks_src, GHash *tracks_mapping)
+static void tracking_plane_tracks_copy(
+ ListBase *plane_tracks_dst, const ListBase *plane_tracks_src, GHash *tracks_mapping, const int flag)
{
MovieTrackingPlaneTrack *plane_track_dst, *plane_track_src;
@@ -225,14 +228,17 @@ static void tracking_plane_tracks_copy(ListBase *plane_tracks_dst, ListBase *pla
for (int i = 0; i < plane_track_dst->point_tracksnr; i++) {
plane_track_dst->point_tracks[i] = BLI_ghash_lookup(tracks_mapping, plane_track_src->point_tracks[i]);
}
- id_us_plus(&plane_track_dst->image->id);
+ if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) {
+ id_us_plus(&plane_track_dst->image->id);
+ }
BLI_addtail(plane_tracks_dst, plane_track_dst);
}
}
/* Copy reconstruction structure. */
static void tracking_reconstruction_copy(
- MovieTrackingReconstruction *reconstruction_dst, MovieTrackingReconstruction *reconstruction_src)
+ MovieTrackingReconstruction *reconstruction_dst, const MovieTrackingReconstruction *reconstruction_src,
+ const int UNUSED(flag))
{
*reconstruction_dst = *reconstruction_src;
if (reconstruction_src->cameras) {
@@ -242,23 +248,25 @@ static void tracking_reconstruction_copy(
/* Copy stabilization structure. */
static void tracking_stabilization_copy(
- MovieTrackingStabilization *stabilization_dst, MovieTrackingStabilization *stabilization_src)
+ MovieTrackingStabilization *stabilization_dst, const MovieTrackingStabilization *stabilization_src,
+ const int UNUSED(flag))
{
*stabilization_dst = *stabilization_src;
}
/* Copy tracking object. */
static void tracking_object_copy(
- MovieTrackingObject *object_dst, MovieTrackingObject *object_src, GHash *tracks_mapping)
+ MovieTrackingObject *object_dst, const MovieTrackingObject *object_src, GHash *tracks_mapping, const int flag)
{
*object_dst = *object_src;
- tracking_tracks_copy(&object_dst->tracks, &object_src->tracks, tracks_mapping);
- tracking_plane_tracks_copy(&object_dst->plane_tracks, &object_src->plane_tracks, tracks_mapping);
- tracking_reconstruction_copy(&object_dst->reconstruction, &object_src->reconstruction);
+ tracking_tracks_copy(&object_dst->tracks, &object_src->tracks, tracks_mapping, flag);
+ tracking_plane_tracks_copy(&object_dst->plane_tracks, &object_src->plane_tracks, tracks_mapping, flag);
+ tracking_reconstruction_copy(&object_dst->reconstruction, &object_src->reconstruction, flag);
}
/* Copy list of tracking objects. */
-static void tracking_objects_copy(ListBase *objects_dst, ListBase *objects_src, GHash *tracks_mapping)
+static void tracking_objects_copy(
+ ListBase *objects_dst, const ListBase *objects_src, GHash *tracks_mapping, const int flag)
{
MovieTrackingObject *object_dst, *object_src;
@@ -266,22 +274,22 @@ static void tracking_objects_copy(ListBase *objects_dst, ListBase *objects_src,
for (object_src = objects_src->first; object_src != NULL; object_src = object_src->next) {
object_dst = MEM_mallocN(sizeof(*object_dst), __func__);
- tracking_object_copy(object_dst, object_src, tracks_mapping);
+ tracking_object_copy(object_dst, object_src, tracks_mapping, flag);
BLI_addtail(objects_dst, object_dst);
}
}
/* Copy tracking structure content. */
-void BKE_tracking_copy(MovieTracking *tracking_dst, MovieTracking *tracking_src)
+void BKE_tracking_copy(MovieTracking *tracking_dst, const MovieTracking *tracking_src, const int flag)
{
GHash *tracks_mapping = BLI_ghash_ptr_new(__func__);
*tracking_dst = *tracking_src;
- tracking_tracks_copy(&tracking_dst->tracks, &tracking_src->tracks, tracks_mapping);
- tracking_plane_tracks_copy(&tracking_dst->plane_tracks, &tracking_src->plane_tracks, tracks_mapping);
- tracking_reconstruction_copy(&tracking_dst->reconstruction, &tracking_src->reconstruction);
- tracking_stabilization_copy(&tracking_dst->stabilization, &tracking_src->stabilization);
+ tracking_tracks_copy(&tracking_dst->tracks, &tracking_src->tracks, tracks_mapping, flag);
+ tracking_plane_tracks_copy(&tracking_dst->plane_tracks, &tracking_src->plane_tracks, tracks_mapping, flag);
+ tracking_reconstruction_copy(&tracking_dst->reconstruction, &tracking_src->reconstruction, flag);
+ tracking_stabilization_copy(&tracking_dst->stabilization, &tracking_src->stabilization, flag);
if (tracking_src->act_track) {
tracking_dst->act_track = BLI_ghash_lookup(tracks_mapping, tracking_src->act_track);
}
@@ -299,7 +307,7 @@ void BKE_tracking_copy(MovieTracking *tracking_dst, MovieTracking *tracking_src)
}
/* Warning! Will override tracks_mapping. */
- tracking_objects_copy(&tracking_dst->objects, &tracking_src->objects, tracks_mapping);
+ tracking_objects_copy(&tracking_dst->objects, &tracking_src->objects, tracks_mapping, flag);
/* Those remaining are runtime data, they will be reconstructed as needed, do not bother copying them. */
tracking_dst->dopesheet.ok = false;
@@ -974,8 +982,11 @@ static void track_mask_set_pixel_cb(int x, int x_end, int y, void *user_data)
}
static void track_mask_gpencil_layer_rasterize(int frame_width, int frame_height,
- MovieTrackingMarker *marker, bGPDlayer *layer,
- float *mask, int mask_width, int mask_height)
+ const float region_min[2],
+ bGPDlayer *layer,
+ float *mask,
+ int mask_width,
+ int mask_height)
{
bGPDframe *frame = layer->frames.first;
TrackMaskSetPixelData data;
@@ -994,8 +1005,8 @@ static void track_mask_gpencil_layer_rasterize(int frame_width, int frame_height
point = mask_points = MEM_callocN(2 * stroke->totpoints * sizeof(int),
"track mask rasterization points");
for (int i = 0; i < stroke->totpoints; i++, point += 2) {
- point[0] = (stroke_points[i].x - marker->search_min[0]) * frame_width;
- point[1] = (stroke_points[i].y - marker->search_min[1]) * frame_height;
+ point[0] = stroke_points[i].x * frame_width - region_min[0];
+ point[1] = stroke_points[i].y * frame_height - region_min[1];
}
/* TODO: add an option to control whether AA is enabled or not */
BLI_bitmap_draw_2d_poly_v2i_n(
@@ -1010,26 +1021,42 @@ static void track_mask_gpencil_layer_rasterize(int frame_width, int frame_height
}
}
-float *BKE_tracking_track_get_mask(int frame_width, int frame_height,
- MovieTrackingTrack *track, MovieTrackingMarker *marker)
+/* Region is in pixel space, relative to marker's center. */
+float *tracking_track_get_mask_for_region(int frame_width, int frame_height,
+ const float region_min[2],
+ const float region_max[2],
+ MovieTrackingTrack *track)
{
float *mask = NULL;
bGPDlayer *layer = track_mask_gpencil_layer_get(track);
- int mask_width, mask_height;
-
- mask_width = (marker->search_max[0] - marker->search_min[0]) * frame_width;
- mask_height = (marker->search_max[1] - marker->search_min[1]) * frame_height;
-
- if (layer) {
+ if (layer != NULL) {
+ const int mask_width = region_max[0] - region_min[0];
+ const int mask_height = region_max[1] - region_min[1];
mask = MEM_callocN(mask_width * mask_height * sizeof(float), "track mask");
-
- track_mask_gpencil_layer_rasterize(frame_width, frame_height, marker, layer,
- mask, mask_width, mask_height);
+ track_mask_gpencil_layer_rasterize(frame_width, frame_height,
+ region_min,
+ layer,
+ mask,
+ mask_width, mask_height);
}
-
return mask;
}
+float *BKE_tracking_track_get_mask(int frame_width, int frame_height,
+ MovieTrackingTrack *track,
+ MovieTrackingMarker *marker)
+{
+ /* Convert normalized space marker's search area to pixel-space region. */
+ const float region_min[2] = {marker->search_min[0] * frame_width,
+ marker->search_min[1] * frame_height};
+ const float region_max[2] = {marker->search_max[0] * frame_width,
+ marker->search_max[1] * frame_height};
+ return tracking_track_get_mask_for_region(frame_width, frame_height,
+ region_min,
+ region_max,
+ track);
+}
+
float BKE_tracking_track_get_weight_for_marker(MovieClip *clip, MovieTrackingTrack *track, MovieTrackingMarker *marker)
{
FCurve *weight_fcurve;
@@ -2877,3 +2904,155 @@ void BKE_tracking_dopesheet_update(MovieTracking *tracking)
dopesheet->ok = true;
}
+
+/* NOTE: Returns NULL if the track comes from camera object, */
+MovieTrackingObject *BKE_tracking_find_object_for_track(
+ const MovieTracking *tracking,
+ const MovieTrackingTrack *track)
+{
+ const ListBase *tracksbase = &tracking->tracks;
+ if (BLI_findindex(tracksbase, track) != -1) {
+ return NULL;
+ }
+ MovieTrackingObject *object = tracking->objects.first;
+ while (object != NULL) {
+ if (BLI_findindex(&object->tracks, track) != -1) {
+ return object;
+ }
+ object = object->next;
+ }
+ return NULL;
+}
+
+ListBase *BKE_tracking_find_tracks_list_for_track(
+ MovieTracking *tracking,
+ const MovieTrackingTrack *track)
+{
+ MovieTrackingObject *object = BKE_tracking_find_object_for_track(tracking,
+ track);
+ if (object != NULL) {
+ return &object->tracks;
+ }
+ return &tracking->tracks;
+}
+
+/* NOTE: Returns NULL if the track comes from camera object, */
+MovieTrackingObject *BKE_tracking_find_object_for_plane_track(
+ const MovieTracking *tracking,
+ const MovieTrackingPlaneTrack *plane_track)
+{
+ const ListBase *plane_tracks_base = &tracking->plane_tracks;
+ if (BLI_findindex(plane_tracks_base, plane_track) != -1) {
+ return NULL;
+ }
+ MovieTrackingObject *object = tracking->objects.first;
+ while (object != NULL) {
+ if (BLI_findindex(&object->plane_tracks, plane_track) != -1) {
+ return object;
+ }
+ object = object->next;
+ }
+ return NULL;
+}
+
+ListBase *BKE_tracking_find_tracks_list_for_plane_track(
+ MovieTracking *tracking,
+ const MovieTrackingPlaneTrack *plane_track)
+{
+ MovieTrackingObject *object =
+ BKE_tracking_find_object_for_plane_track(tracking, plane_track);
+ if (object != NULL) {
+ return &object->plane_tracks;
+ }
+ return &tracking->plane_tracks;
+}
+
+void BKE_tracking_get_rna_path_for_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track,
+ char *rna_path,
+ size_t rna_path_len)
+{
+ MovieTrackingObject *object =
+ BKE_tracking_find_object_for_track(tracking, track);
+ char track_name_esc[MAX_NAME * 2];
+ BLI_strescape(track_name_esc, track->name, sizeof(track_name_esc));
+ if (object == NULL) {
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.tracks[\"%s\"]",
+ track_name_esc);
+ }
+ else {
+ char object_name_esc[MAX_NAME * 2];
+ BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.objects[\"%s\"].tracks[\"%s\"]",
+ object_name_esc,
+ track_name_esc);
+ }
+}
+
+void BKE_tracking_get_rna_path_prefix_for_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingTrack *track,
+ char *rna_path,
+ size_t rna_path_len)
+{
+ MovieTrackingObject *object =
+ BKE_tracking_find_object_for_track(tracking, track);
+ if (object == NULL) {
+ BLI_snprintf(rna_path, rna_path_len, "tracking.tracks");
+ }
+ else {
+ char object_name_esc[MAX_NAME * 2];
+ BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.objects[\"%s\"]",
+ object_name_esc);
+ }
+}
+
+void BKE_tracking_get_rna_path_for_plane_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track,
+ char *rna_path,
+ size_t rna_path_len)
+{
+ MovieTrackingObject *object =
+ BKE_tracking_find_object_for_plane_track(tracking, plane_track);
+ char track_name_esc[MAX_NAME * 2];
+ BLI_strescape(track_name_esc, plane_track->name, sizeof(track_name_esc));
+ if (object == NULL) {
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.plane_tracks[\"%s\"]",
+ track_name_esc);
+ }
+ else {
+ char object_name_esc[MAX_NAME * 2];
+ BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.objects[\"%s\"].plane_tracks[\"%s\"]",
+ object_name_esc,
+ track_name_esc);
+ }
+}
+
+void BKE_tracking_get_rna_path_prefix_for_plane_track(
+ const struct MovieTracking *tracking,
+ const struct MovieTrackingPlaneTrack *plane_track,
+ char *rna_path,
+ size_t rna_path_len)
+{
+ MovieTrackingObject *object =
+ BKE_tracking_find_object_for_plane_track(tracking, plane_track);
+ if (object == NULL) {
+ BLI_snprintf(rna_path, rna_path_len, "tracking.plane_tracks");
+ }
+ else {
+ char object_name_esc[MAX_NAME * 2];
+ BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
+ BLI_snprintf(rna_path, rna_path_len,
+ "tracking.objects[\"%s\"].plane_tracks",
+ object_name_esc);
+ }
+}
diff --git a/source/blender/blenkernel/intern/tracking_auto.c b/source/blender/blenkernel/intern/tracking_auto.c
index 3b56ea271d0..1cb474e6202 100644
--- a/source/blender/blenkernel/intern/tracking_auto.c
+++ b/source/blender/blenkernel/intern/tracking_auto.c
@@ -30,14 +30,17 @@
*/
#include <stdlib.h>
+#include "atomic_ops.h"
#include "MEM_guardedalloc.h"
#include "DNA_movieclip_types.h"
#include "DNA_object_types.h" /* SELECT */
-#include "BLI_threads.h"
#include "BLI_utildefines.h"
+#include "BLI_listbase.h"
+#include "BLI_task.h"
+#include "BLI_threads.h"
#include "BLI_math.h"
#include "BKE_movieclip.h"
@@ -76,12 +79,17 @@ typedef struct AutoTrackContext {
int num_tracks; /* Number of tracks being tracked. */
AutoTrackOptions *options; /* Per-tracking track options. */
+ /* Array of all tracks, indexed by track_index. */
+ MovieTrackingTrack **tracks;
+
bool backwards;
bool sequence;
int first_frame;
int sync_frame;
bool first_sync;
SpinLock spin_lock;
+
+ bool step_ok;
} AutoTrackContext;
static void normalized_to_libmv_frame(const float normalized[2],
@@ -228,17 +236,15 @@ static void libmv_marker_to_dna_marker(libmv_Marker *libmv_marker,
}
}
-static bool check_track_trackable(MovieClip *clip,
+static bool check_track_trackable(const MovieClip *clip,
MovieTrackingTrack *track,
- MovieClipUser *user)
+ const MovieClipUser *user)
{
if (TRACK_SELECTED(track) &&
(track->flag & (TRACK_LOCKED | TRACK_HIDDEN)) == 0)
{
- MovieTrackingMarker *marker;
- int frame;
- frame = BKE_movieclip_remap_scene_to_clip_frame(clip, user->framenr);
- marker = BKE_tracking_marker_get(track, frame);
+ int frame = BKE_movieclip_remap_scene_to_clip_frame(clip, user->framenr);
+ const MovieTrackingMarker *marker = BKE_tracking_marker_get(track, frame);
return (marker->flag & MARKER_DISABLED) == 0;
}
return false;
@@ -275,6 +281,108 @@ static bool tracking_check_marker_margin(libmv_Marker *libmv_marker,
return true;
}
+/* Provide Libmv side of auto track all information about given tracks. */
+static void fill_autotrack_tracks(const int frame_width,
+ const int frame_height,
+ const ListBase *tracksbase,
+ const bool backwards,
+ struct libmv_AutoTrack *autotrack)
+{
+ /* Count number of markers to be put to a context. */
+ size_t num_trackable_markers = 0;
+ for (MovieTrackingTrack *track = tracksbase->first;
+ track != NULL;
+ track = track->next)
+ {
+ for (int i = 0; i < track->markersnr; ++i) {
+ const MovieTrackingMarker *marker = track->markers + i;
+ if ((marker->flag & MARKER_DISABLED) == 0) {
+ num_trackable_markers++;
+ }
+ }
+ }
+ /* Early output if we don't have any markers. */
+ if (num_trackable_markers == 0) {
+ return;
+ }
+ /* Allocate memory for all the markers. */
+ libmv_Marker *libmv_markers = MEM_mallocN(
+ sizeof(libmv_Marker) * num_trackable_markers,
+ "libmv markers array");
+ /* Fill in markers array. */
+ int track_index = 0, num_filled_libmv_markers = 0;
+ for (MovieTrackingTrack *track = tracksbase->first;
+ track != NULL;
+ track = track->next)
+ {
+ for (int i = 0; i < track->markersnr; ++i) {
+ MovieTrackingMarker *marker = track->markers + i;
+ if ((marker->flag & MARKER_DISABLED) != 0) {
+ continue;
+ }
+ dna_marker_to_libmv_marker(
+ track,
+ marker,
+ 0,
+ track_index,
+ frame_width, frame_height,
+ backwards,
+ &libmv_markers[num_filled_libmv_markers++]);
+ }
+ /* Put all markers to autotrack at once. */
+ track_index++;
+ }
+ /* Add all markers to autotrack. */
+ libmv_autoTrackSetMarkers(autotrack,
+ libmv_markers,
+ num_trackable_markers);
+ /* Free temporary memory. */
+ MEM_freeN(libmv_markers);
+}
+
+static void create_per_track_tracking_options(const MovieClip *clip,
+ const MovieClipUser *user,
+ const ListBase *tracksbase,
+ AutoTrackContext *context)
+{
+ /* Count number of trackable tracks. */
+ for (MovieTrackingTrack *track = tracksbase->first;
+ track != NULL;
+ track = track->next)
+ {
+ if (check_track_trackable(clip, track, user)) {
+ context->num_tracks++;
+ }
+ }
+ /* Allocate required memory. */
+ context->options =
+ MEM_callocN(sizeof(AutoTrackOptions) * context->num_tracks,
+ "auto track options");
+ /* Fill in all the settings. */
+ int i = 0, track_index = 0;
+ for (MovieTrackingTrack *track = tracksbase->first;
+ track != NULL;
+ track = track->next)
+ {
+ if (!check_track_trackable(clip, track, user)) {
+ ++track_index;
+ continue;
+ }
+ AutoTrackOptions *options = &context->options[i++];
+ /* TODO(sergey): Single clip only for now. */
+ options->clip_index = 0;
+ options->track_index = track_index;
+ options->track = track;
+ tracking_configure_tracker(track,
+ NULL,
+ &options->track_region_options);
+ options->use_keyframe_match =
+ track->pattern_match == TRACK_MATCH_KEYFRAME;
+ context->tracks[track_index] = track;
+ ++track_index;
+ }
+}
+
AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip,
MovieClipUser *user,
const bool backwards,
@@ -283,16 +391,13 @@ AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip,
AutoTrackContext *context = MEM_callocN(sizeof(AutoTrackContext),
"autotrack context");
MovieTracking *tracking = &clip->tracking;
- MovieTrackingTrack *track;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
- int i, track_index, frame_width, frame_height;
-
+ int frame_width, frame_height;
+ /* get size of frame to convert normalized coordinates to a picture ones. */
BKE_movieclip_get_size(clip, user, &frame_width, &frame_height);
-
/* TODO(sergey): Currently using only a single clip. */
context->clips[0] = clip;
context->num_clips = 1;
-
context->user = *user;
context->user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
context->user.render_flag = 0;
@@ -303,148 +408,124 @@ AutoTrackContext *BKE_autotrack_context_new(MovieClip *clip,
context->first_frame = user->framenr;
context->sync_frame = user->framenr;
context->first_sync = true;
-
BLI_spin_init(&context->spin_lock);
-
+ const int num_total_tracks = BLI_listbase_count(tracksbase);
+ context->tracks =
+ MEM_callocN(sizeof(MovieTrackingTrack *) * num_total_tracks,
+ "auto track pointers");
+ /* Initialize image accessor. */
context->image_accessor =
- tracking_image_accessor_new(context->clips, 1, user->framenr);
+ tracking_image_accessor_new(context->clips, 1,
+ context->tracks, num_total_tracks,
+ user->framenr);
+ /* Initialize auto track context and provide all information about currently
+ * tracked markers.
+ */
context->autotrack =
- libmv_autoTrackNew(context->image_accessor->libmv_accessor);
-
- /* Fill in Autotrack with all markers we know. */
- track_index = 0;
- for (track = tracksbase->first;
- track;
- track = track->next)
- {
- if (check_track_trackable(clip, track, user)) {
- context->num_tracks++;
- }
-
- for (i = 0; i < track->markersnr; ++i) {
- MovieTrackingMarker *marker = track->markers + i;
- if ((marker->flag & MARKER_DISABLED) == 0) {
- libmv_Marker libmv_marker;
- dna_marker_to_libmv_marker(track,
- marker,
- 0,
- track_index,
- frame_width,
- frame_height,
- backwards,
- &libmv_marker);
- libmv_autoTrackAddMarker(context->autotrack,
- &libmv_marker);
- }
- }
- track_index++;
- }
-
+ libmv_autoTrackNew(context->image_accessor->libmv_accessor);
+ fill_autotrack_tracks(frame_width, frame_height,
+ tracksbase,
+ backwards,
+ context->autotrack);
/* Create per-track tracking options. */
- context->options =
- MEM_callocN(sizeof(AutoTrackOptions) * context->num_tracks,
- "auto track options");
- i = track_index = 0;
- for (track = tracksbase->first;
- track;
- track = track->next)
- {
- if (check_track_trackable(clip, track, user)) {
- AutoTrackOptions *options = &context->options[i++];
- /* TODO(sergey): Single clip only for now. */
- options->clip_index = 0;
- options->track_index = track_index;
- options->track = track;
- tracking_configure_tracker(track,
- NULL,
- &options->track_region_options);
- options->use_keyframe_match =
- track->pattern_match == TRACK_MATCH_KEYFRAME;
- }
- ++track_index;
- }
-
+ create_per_track_tracking_options(clip, user, tracksbase, context);
return context;
}
-bool BKE_autotrack_context_step(AutoTrackContext *context)
+static void autotrack_context_step_cb(
+ void *__restrict userdata,
+ const int track,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
- int frame_delta = context->backwards ? -1 : 1;
- bool ok = false;
- int track;
-
-#pragma omp parallel for if (context->num_tracks > 1)
- for (track = 0; track < context->num_tracks; ++track) {
- AutoTrackOptions *options = &context->options[track];
- if (options->is_failed) {
- continue;
- }
- libmv_Marker libmv_current_marker,
- libmv_reference_marker,
- libmv_tracked_marker;
- libmv_TrackRegionResult libmv_result;
- int frame = BKE_movieclip_remap_scene_to_clip_frame(
- context->clips[options->clip_index],
- context->user.framenr);
- bool has_marker;
+ AutoTrackContext *context = userdata;
+ const int frame_delta = context->backwards ? -1 : 1;
+ AutoTrackOptions *options = &context->options[track];
+ if (options->is_failed) {
+ return;
+ }
+ libmv_Marker libmv_current_marker,
+ libmv_reference_marker,
+ libmv_tracked_marker;
+ libmv_TrackRegionResult libmv_result;
+ const int frame = BKE_movieclip_remap_scene_to_clip_frame(
+ context->clips[options->clip_index],
+ context->user.framenr);
+ BLI_spin_lock(&context->spin_lock);
+ const bool has_marker = libmv_autoTrackGetMarker(context->autotrack,
+ options->clip_index,
+ frame,
+ options->track_index,
+ &libmv_current_marker);
+ BLI_spin_unlock(&context->spin_lock);
+ /* Check whether we've got marker to sync with. */
+ if (!has_marker) {
+ return;
+ }
+ /* Check whether marker is going outside of allowed frame margin. */
+ if (!tracking_check_marker_margin(&libmv_current_marker,
+ options->track->margin,
+ context->frame_width,
+ context->frame_height))
+ {
+ return;
+ }
+ libmv_tracked_marker = libmv_current_marker;
+ libmv_tracked_marker.frame = frame + frame_delta;
+ /* Update reference frame. */
+ if (options->use_keyframe_match) {
+ libmv_tracked_marker.reference_frame =
+ libmv_current_marker.reference_frame;
+ libmv_autoTrackGetMarker(context->autotrack,
+ options->clip_index,
+ libmv_tracked_marker.reference_frame,
+ options->track_index,
+ &libmv_reference_marker);
+ }
+ else {
+ libmv_tracked_marker.reference_frame = frame;
+ libmv_reference_marker = libmv_current_marker;
+ }
+ /* Perform actual tracking. */
+ if (libmv_autoTrackMarker(context->autotrack,
+ &options->track_region_options,
+ &libmv_tracked_marker,
+ &libmv_result))
+ {
BLI_spin_lock(&context->spin_lock);
- has_marker = libmv_autoTrackGetMarker(context->autotrack,
- options->clip_index,
- frame,
- options->track_index,
- &libmv_current_marker);
+ libmv_autoTrackAddMarker(context->autotrack, &libmv_tracked_marker);
BLI_spin_unlock(&context->spin_lock);
-
- if (has_marker) {
- if (!tracking_check_marker_margin(&libmv_current_marker,
- options->track->margin,
- context->frame_width,
- context->frame_height))
- {
- continue;
- }
-
- libmv_tracked_marker = libmv_current_marker;
- libmv_tracked_marker.frame = frame + frame_delta;
-
- if (options->use_keyframe_match) {
- libmv_tracked_marker.reference_frame =
- libmv_current_marker.reference_frame;
- libmv_autoTrackGetMarker(context->autotrack,
- options->clip_index,
- libmv_tracked_marker.reference_frame,
- options->track_index,
- &libmv_reference_marker);
- }
- else {
- libmv_tracked_marker.reference_frame = frame;
- libmv_reference_marker = libmv_current_marker;
- }
-
- if (libmv_autoTrackMarker(context->autotrack,
- &options->track_region_options,
- &libmv_tracked_marker,
- &libmv_result))
- {
- BLI_spin_lock(&context->spin_lock);
- libmv_autoTrackAddMarker(context->autotrack,
- &libmv_tracked_marker);
- BLI_spin_unlock(&context->spin_lock);
- }
- else {
- options->is_failed = true;
- options->failed_frame = frame + frame_delta;
- }
- ok = true;
- }
+ }
+ else {
+ options->is_failed = true;
+ options->failed_frame = frame + frame_delta;
}
+ /* Note: Atomic is probably not actually needed here, I doubt we could get
+ * any other result than a true bool anyway.
+ * But for sake of consistency, and since it costs nothing...
+ */
+ atomic_fetch_and_or_uint8((uint8_t *)&context->step_ok, true);
+}
+
+bool BKE_autotrack_context_step(AutoTrackContext *context)
+{
+ const int frame_delta = context->backwards ? -1 : 1;
+ context->step_ok = false;
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (context->num_tracks > 1);
+ BLI_task_parallel_range(0, context->num_tracks,
+ context,
+ autotrack_context_step_cb,
+ &settings);
+
+ /* Advance the frame. */
BLI_spin_lock(&context->spin_lock);
context->user.framenr += frame_delta;
BLI_spin_unlock(&context->spin_lock);
-
- return ok;
+ return context->step_ok;
}
void BKE_autotrack_context_sync(AutoTrackContext *context)
@@ -546,8 +627,9 @@ void BKE_autotrack_context_finish(AutoTrackContext *context)
if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
int track;
for (track = 0; track < context->num_tracks; ++track) {
- if (BKE_tracking_plane_track_has_point_track(plane_track,
- context->options[track].track))
+ if (BKE_tracking_plane_track_has_point_track(
+ plane_track,
+ context->options[track].track))
{
BKE_tracking_track_plane_from_existing_motion(
plane_track,
@@ -565,6 +647,7 @@ void BKE_autotrack_context_free(AutoTrackContext *context)
libmv_autoTrackDestroy(context->autotrack);
tracking_image_accessor_destroy(context->image_accessor);
MEM_freeN(context->options);
+ MEM_freeN(context->tracks);
BLI_spin_end(&context->spin_lock);
MEM_freeN(context);
}
diff --git a/source/blender/blenkernel/intern/tracking_region_tracker.c b/source/blender/blenkernel/intern/tracking_region_tracker.c
index dd7def16ca8..106dd125575 100644
--- a/source/blender/blenkernel/intern/tracking_region_tracker.c
+++ b/source/blender/blenkernel/intern/tracking_region_tracker.c
@@ -189,7 +189,7 @@ void tracking_configure_tracker(const MovieTrackingTrack *track, float *mask,
options->image1_mask = NULL;
}
-/* Peform tracking from a reference_marker to destination_ibuf.
+/* Perform tracking from a reference_marker to destination_ibuf.
* Uses marker as an initial position guess.
*
* Returns truth if tracker returned success, puts result
diff --git a/source/blender/blenkernel/intern/tracking_stabilize.c b/source/blender/blenkernel/intern/tracking_stabilize.c
index 36b24fbb2dc..cbf1a02a46c 100644
--- a/source/blender/blenkernel/intern/tracking_stabilize.c
+++ b/source/blender/blenkernel/intern/tracking_stabilize.c
@@ -41,13 +41,14 @@
#include "BLI_utildefines.h"
#include "BLI_sort_utils.h"
+#include "BLI_ghash.h"
#include "BLI_math_vector.h"
#include "BLI_math.h"
+#include "BLI_task.h"
#include "BKE_tracking.h"
#include "BKE_movieclip.h"
#include "BKE_fcurve.h"
-#include "BLI_ghash.h"
#include "MEM_guardedalloc.h"
#include "IMB_imbuf_types.h"
@@ -203,7 +204,7 @@ static float get_animated_scaleinf(StabContext *ctx, int framenr)
static void get_animated_target_pos(StabContext *ctx,
int framenr,
- float target_pos[2])
+ float target_pos[2])
{
target_pos[0] = fetch_from_fcurve(ctx->target_pos[0],
framenr,
@@ -755,7 +756,8 @@ static void average_marker_positions(StabContext *ctx, int framenr, float r_ref_
if (ok) {
r_ref_pos[0] /= weight_sum;
r_ref_pos[1] /= weight_sum;
- } else {
+ }
+ else {
/* No usable tracking data on any track on this frame.
* Use data from neighbouring frames to extrapolate...
*/
@@ -784,7 +786,8 @@ static void average_marker_positions(StabContext *ctx, int framenr, float r_ref_
* Also default to this frame when we're in a gap */
average_marker_positions(ctx, next_lower, r_ref_pos);
- } else if (next_higher < MAXFRAME) {
+ }
+ else if (next_higher < MAXFRAME) {
average_marker_positions(ctx, next_higher, r_ref_pos);
}
use_values_from_fcurves(ctx, false);
@@ -1167,7 +1170,8 @@ static void stabilization_calculate_data(StabContext *ctx,
if (ctx->stab->flag & TRACKING_STABILIZE_SCALE) {
*r_scale = expf(scale_step * scaleinf); /* Averaged in log scale */
- } else {
+ }
+ else {
*r_scale = 1.0f;
}
@@ -1180,8 +1184,8 @@ static void stabilization_calculate_data(StabContext *ctx,
*/
get_animated_target_pos(ctx, framenr, target_pos);
sub_v2_v2(r_translation, target_pos);
- *r_angle -= get_animated_target_rot(ctx,framenr);
- target_scale = get_animated_target_scale(ctx,framenr);
+ *r_angle -= get_animated_target_rot(ctx, framenr);
+ target_scale = get_animated_target_scale(ctx, framenr);
if (target_scale != 0.0f) {
*r_scale /= target_scale;
/* target_scale is an expected/intended reference zoom value */
@@ -1488,6 +1492,38 @@ void BKE_tracking_stabilization_data_get(MovieClip *clip,
discard_stabilization_working_context(ctx);
}
+
+typedef void (*interpolation_func)(struct ImBuf *, struct ImBuf *, float, float, int, int);
+
+typedef struct TrackingStabilizeFrameInterpolationData {
+ ImBuf *ibuf;
+ ImBuf *tmpibuf;
+ float (*mat)[4];
+
+ interpolation_func interpolation;
+} TrackingStabilizeFrameInterpolationData;
+
+static void tracking_stabilize_frame_interpolation_cb(
+ void *__restrict userdata,
+ const int j,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ TrackingStabilizeFrameInterpolationData *data = userdata;
+ ImBuf *ibuf = data->ibuf;
+ ImBuf *tmpibuf = data->tmpibuf;
+ float (*mat)[4] = data->mat;
+
+ interpolation_func interpolation = data->interpolation;
+
+ for (int i = 0; i < tmpibuf->x; i++) {
+ float vec[3] = {i, j, 0.0f};
+
+ mul_v3_m4v3(vec, mat, vec);
+
+ interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
+ }
+}
+
/* Stabilize given image buffer using stabilization data for a specified
* frame number.
*
@@ -1508,8 +1544,8 @@ ImBuf *BKE_tracking_stabilize_frame(MovieClip *clip,
int width = ibuf->x, height = ibuf->y;
float pixel_aspect = tracking->camera.pixel_aspect;
float mat[4][4];
- int j, filter = tracking->stabilization.filter;
- void (*interpolation)(struct ImBuf *, struct ImBuf *, float, float, int, int) = NULL;
+ int filter = tracking->stabilization.filter;
+ interpolation_func interpolation = NULL;
int ibuf_flags;
if (translation)
@@ -1560,24 +1596,18 @@ ImBuf *BKE_tracking_stabilize_frame(MovieClip *clip,
/* fallback to default interpolation method */
interpolation = nearest_interpolation;
- /* This function is only used for display in clip editor and
- * sequencer only, which would only benefit of using threads
- * here.
- *
- * But need to keep an eye on this if the function will be
- * used in other cases.
- */
-#pragma omp parallel for if (tmpibuf->y > 128)
- for (j = 0; j < tmpibuf->y; j++) {
- int i;
- for (i = 0; i < tmpibuf->x; i++) {
- float vec[3] = {i, j, 0.0f};
-
- mul_v3_m4v3(vec, mat, vec);
-
- interpolation(ibuf, tmpibuf, vec[0], vec[1], i, j);
- }
- }
+ TrackingStabilizeFrameInterpolationData data = {
+ .ibuf = ibuf, .tmpibuf = tmpibuf, .mat = mat,
+ .interpolation = interpolation
+ };
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (tmpibuf->y > 128);
+ BLI_task_parallel_range(0, tmpibuf->y,
+ &data,
+ tracking_stabilize_frame_interpolation_cb,
+ &settings);
if (tmpibuf->rect_float)
tmpibuf->userflags |= IB_RECT_INVALID;
diff --git a/source/blender/blenkernel/intern/tracking_util.c b/source/blender/blenkernel/intern/tracking_util.c
index 1c056cda68d..8c1b846db84 100644
--- a/source/blender/blenkernel/intern/tracking_util.c
+++ b/source/blender/blenkernel/intern/tracking_util.c
@@ -58,6 +58,15 @@
#include "libmv-capi.h"
+/* Uncomment this to have caching-specific debug prints. */
+// #define DEBUG_CACHE
+
+#ifdef DEBUG_CACHE
+# define CACHE_PRINTF(...) printf(__VA_ARGS__)
+#else
+# define CACHE_PRINTF(...)
+#endif
+
/*********************** Tracks map *************************/
TracksMap *tracks_map_new(const char *object_name, bool is_camera, int num_tracks, int customdata_size)
@@ -523,6 +532,8 @@ typedef struct AccessCacheKey {
int frame;
int downscale;
libmv_InputMode input_mode;
+ bool has_region;
+ float region_min[2], region_max[2];
int64_t transform_key;
} AccessCacheKey;
@@ -537,23 +548,44 @@ static bool accesscache_hashcmp(const void *a_v, const void *b_v)
{
const AccessCacheKey *a = (const AccessCacheKey *) a_v;
const AccessCacheKey *b = (const AccessCacheKey *) b_v;
-
-#define COMPARE_FIELD(field)
- { \
- if (a->clip_index != b->clip_index) { \
- return false; \
- } \
- } (void) 0
-
- COMPARE_FIELD(clip_index);
- COMPARE_FIELD(frame);
- COMPARE_FIELD(downscale);
- COMPARE_FIELD(input_mode);
- COMPARE_FIELD(transform_key);
-
-#undef COMPARE_FIELD
-
- return true;
+ if (a->clip_index != b->clip_index ||
+ a->frame != b->frame ||
+ a->downscale != b->downscale ||
+ a->input_mode != b->input_mode ||
+ a->has_region != b->has_region ||
+ a->transform_key != b->transform_key)
+ {
+ return true;
+ }
+ /* If there is region applied, compare it. */
+ if (a->has_region) {
+ if (!equals_v2v2(a->region_min, b->region_min) ||
+ !equals_v2v2(a->region_max, b->region_max))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void accesscache_construct_key(AccessCacheKey *key,
+ int clip_index,
+ int frame,
+ libmv_InputMode input_mode,
+ int downscale,
+ const libmv_Region *region,
+ int64_t transform_key)
+{
+ key->clip_index = clip_index;
+ key->frame = frame;
+ key->input_mode = input_mode;
+ key->downscale = downscale;
+ key->has_region = (region != NULL);
+ if (key->has_region) {
+ copy_v2_v2(key->region_min, region->min);
+ copy_v2_v2(key->region_max, region->max);
+ }
+ key->transform_key = transform_key;
}
static void accesscache_put(TrackingImageAccessor *accessor,
@@ -561,15 +593,13 @@ static void accesscache_put(TrackingImageAccessor *accessor,
int frame,
libmv_InputMode input_mode,
int downscale,
+ const libmv_Region *region,
int64_t transform_key,
ImBuf *ibuf)
{
AccessCacheKey key;
- key.clip_index = clip_index;
- key.frame = frame;
- key.input_mode = input_mode;
- key.downscale = downscale;
- key.transform_key = transform_key;
+ accesscache_construct_key(&key, clip_index, frame, input_mode, downscale,
+ region, transform_key);
IMB_moviecache_put(accessor->cache, &key, ibuf);
}
@@ -578,14 +608,12 @@ static ImBuf *accesscache_get(TrackingImageAccessor *accessor,
int frame,
libmv_InputMode input_mode,
int downscale,
+ const libmv_Region *region,
int64_t transform_key)
{
AccessCacheKey key;
- key.clip_index = clip_index;
- key.frame = frame;
- key.input_mode = input_mode;
- key.downscale = downscale;
- key.transform_key = transform_key;
+ accesscache_construct_key(&key, clip_index, frame, input_mode, downscale,
+ region, transform_key);
return IMB_moviecache_get(accessor->cache, &key);
}
@@ -674,29 +702,37 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor,
{
ImBuf *ibuf, *orig_ibuf, *final_ibuf;
int64_t transform_key = 0;
-
if (transform != NULL) {
transform_key = libmv_frameAccessorgetTransformKey(transform);
}
-
/* First try to get fully processed image from the cache. */
+ BLI_spin_lock(&accessor->cache_lock);
ibuf = accesscache_get(accessor,
clip_index,
frame,
input_mode,
downscale,
+ region,
transform_key);
+ BLI_spin_unlock(&accessor->cache_lock);
if (ibuf != NULL) {
+ CACHE_PRINTF("Used cached buffer for frame %d\n", frame);
+ /* This is a little heuristic here: if we re-used image once, this is
+ * a high probability of the image to be related to a keyframe matched
+ * reference image. Those images we don't want to be thrown away because
+ * if we toss them out we'll be re-calculating them at the next
+ * iteration.
+ */
+ ibuf->userflags |= IB_PERSISTENT;
return ibuf;
}
-
+ CACHE_PRINTF("Calculate new buffer for frame %d\n", frame);
/* And now we do postprocessing of the original frame. */
orig_ibuf = accessor_get_preprocessed_ibuf(accessor, clip_index, frame);
-
if (orig_ibuf == NULL) {
return NULL;
}
-
+ /* Cut a region if requested. */
if (region != NULL) {
int width = region->max[0] - region->min[0],
height = region->max[1] - region->min[1];
@@ -751,12 +787,12 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor,
* in the cache which is nice on the one hand (faster re-use of the
* frames) but on the other hand it bumps the memory usage up.
*/
- BLI_lock_thread(LOCK_MOVIECLIP);
+ BLI_thread_lock(LOCK_MOVIECLIP);
IMB_float_from_rect(orig_ibuf);
- BLI_unlock_thread(LOCK_MOVIECLIP);
+ BLI_thread_unlock(LOCK_MOVIECLIP);
final_ibuf = orig_ibuf;
}
-
+ /* Downscale if needed. */
if (downscale > 0) {
if (final_ibuf == orig_ibuf) {
final_ibuf = IMB_dupImBuf(orig_ibuf);
@@ -765,7 +801,7 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor,
orig_ibuf->x / (1 << downscale),
orig_ibuf->y / (1 << downscale));
}
-
+ /* Apply possible transformation. */
if (transform != NULL) {
libmv_FloatImage input_image, output_image;
ibuf_to_float_image(final_ibuf, &input_image);
@@ -778,12 +814,13 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor,
final_ibuf = float_image_to_ibuf(&output_image);
libmv_floatImageDestroy(&output_image);
}
-
+ /* Transform number of channels. */
if (input_mode == LIBMV_IMAGE_MODE_RGBA) {
BLI_assert(orig_ibuf->channels == 3 || orig_ibuf->channels == 4);
/* pass */
}
else /* if (input_mode == LIBMV_IMAGE_MODE_MONO) */ {
+ BLI_assert(input_mode == LIBMV_IMAGE_MODE_MONO);
if (final_ibuf->channels != 1) {
ImBuf *grayscale_ibuf = make_grayscale_ibuf_copy(final_ibuf);
if (final_ibuf != orig_ibuf) {
@@ -793,37 +830,25 @@ static ImBuf *accessor_get_ibuf(TrackingImageAccessor *accessor,
final_ibuf = grayscale_ibuf;
}
}
-
- /* it's possible processing still didn't happen at this point,
+ /* It's possible processing still didn't happen at this point,
* but we really need a copy of the buffer to be transformed
* and to be put to the cache.
*/
if (final_ibuf == orig_ibuf) {
final_ibuf = IMB_dupImBuf(orig_ibuf);
}
-
IMB_freeImBuf(orig_ibuf);
-
- /* We put postprocessed frame to the cache always for now,
- * not the smartest thing in the world, but who cares at this point.
- */
-
- /* TODO(sergey): Disable cache for now, because we don't store region
- * in the cache key and can't check whether cached version is usable for
- * us or not.
- *
- * Need to think better about what to cache and when.
- */
- if (false) {
- accesscache_put(accessor,
- clip_index,
- frame,
- input_mode,
- downscale,
- transform_key,
- final_ibuf);
- }
-
+ BLI_spin_lock(&accessor->cache_lock);
+ /* Put final buffer to cache. */
+ accesscache_put(accessor,
+ clip_index,
+ frame,
+ input_mode,
+ downscale,
+ region,
+ transform_key,
+ final_ibuf);
+ BLI_spin_unlock(&accessor->cache_lock);
return final_ibuf;
}
@@ -875,8 +900,64 @@ static void accessor_release_image_callback(libmv_CacheKey cache_key)
IMB_freeImBuf(ibuf);
}
+static libmv_CacheKey accessor_get_mask_for_track_callback(
+ libmv_FrameAccessorUserData *user_data,
+ int clip_index,
+ int frame,
+ int track_index,
+ const libmv_Region *region,
+ float **r_destination,
+ int *r_width,
+ int *r_height)
+{
+ /* Perform sanity checks first. */
+ TrackingImageAccessor *accessor = (TrackingImageAccessor *) user_data;
+ BLI_assert(clip_index < accessor->num_clips);
+ BLI_assert(track_index < accessor->num_tracks);
+ MovieTrackingTrack *track = accessor->tracks[track_index];
+ /* Early output, track does not use mask. */
+ if ((track->algorithm_flag & TRACK_ALGORITHM_FLAG_USE_MASK) == 0) {
+ return NULL;
+ }
+ MovieClip *clip = accessor->clips[clip_index];
+ /* Construct fake user so we can access movie clip. */
+ MovieClipUser user;
+ int scene_frame = BKE_movieclip_remap_clip_to_scene_frame(clip, frame);
+ BKE_movieclip_user_set_frame(&user, scene_frame);
+ user.render_size = MCLIP_PROXY_RENDER_SIZE_FULL;
+ user.render_flag = 0;
+ /* Get frame width and height so we can convert stroke coordinates
+ * and other things from normalized to pixel space.
+ */
+ int frame_width, frame_height;
+ BKE_movieclip_get_size(clip, &user, &frame_width, &frame_height);
+ /* Actual mask sampling. */
+ MovieTrackingMarker *marker = BKE_tracking_marker_get_exact(track, frame);
+ const float region_min[2] = {region->min[0] - marker->pos[0] * frame_width,
+ region->min[1] - marker->pos[1] * frame_height};
+ const float region_max[2] = {region->max[0] - marker->pos[0] * frame_width,
+ region->max[1] - marker->pos[1] * frame_height};
+ *r_destination = tracking_track_get_mask_for_region(frame_width, frame_height,
+ region_min,
+ region_max,
+ track);
+ *r_width = region->max[0] - region->min[0];
+ *r_height = region->max[1] - region->min[1];
+ return *r_destination;
+}
+
+static void accessor_release_mask_callback(libmv_CacheKey cache_key)
+{
+ if (cache_key != NULL) {
+ float *mask = (float *)cache_key;
+ MEM_freeN(mask);
+ }
+}
+
TrackingImageAccessor *tracking_image_accessor_new(MovieClip *clips[MAX_ACCESSOR_CLIP],
int num_clips,
+ MovieTrackingTrack **tracks,
+ int num_tracks,
int start_frame)
{
TrackingImageAccessor *accessor =
@@ -891,12 +972,18 @@ TrackingImageAccessor *tracking_image_accessor_new(MovieClip *clips[MAX_ACCESSOR
memcpy(accessor->clips, clips, num_clips * sizeof(MovieClip *));
accessor->num_clips = num_clips;
+ accessor->tracks = tracks;
+ accessor->num_tracks = num_tracks;
accessor->start_frame = start_frame;
accessor->libmv_accessor =
libmv_FrameAccessorNew((libmv_FrameAccessorUserData *) accessor,
accessor_get_image_callback,
- accessor_release_image_callback);
+ accessor_release_image_callback,
+ accessor_get_mask_for_track_callback,
+ accessor_release_mask_callback);
+
+ BLI_spin_init(&accessor->cache_lock);
return accessor;
}
@@ -905,5 +992,6 @@ void tracking_image_accessor_destroy(TrackingImageAccessor *accessor)
{
IMB_moviecache_free(accessor->cache);
libmv_FrameAccessorDestroy(accessor->libmv_accessor);
+ BLI_spin_end(&accessor->cache_lock);
MEM_freeN(accessor);
}
diff --git a/source/blender/blenkernel/intern/undo_system.c b/source/blender/blenkernel/intern/undo_system.c
new file mode 100644
index 00000000000..5a0081bff16
--- /dev/null
+++ b/source/blender/blenkernel/intern/undo_system.c
@@ -0,0 +1,841 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenkernel/intern/undo_system.c
+ * \ingroup bke
+ *
+ * Used by ED_undo.h, internal implementation.
+ */
+
+#include <string.h>
+
+#include "CLG_log.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_sys_types.h"
+#include "BLI_listbase.h"
+#include "BLI_string.h"
+#include "BLI_sort_utils.h"
+
+#include "DNA_listBase.h"
+#include "DNA_windowmanager_types.h"
+
+#include "BKE_context.h"
+#include "BKE_global.h"
+#include "BKE_main.h"
+#include "BKE_undo_system.h"
+
+#include "MEM_guardedalloc.h"
+
+#define undo_stack _wm_undo_stack_disallow /* pass in as a variable always. */
+
+/** Odd requirement of Blender that we always keep a memfile undo in the stack. */
+#define WITH_GLOBAL_UNDO_KEEP_ONE
+
+/** Make sure all ID's created at the point we add an undo step that uses ID's. */
+#define WITH_GLOBAL_UNDO_ENSURE_UPDATED
+
+/** We only need this locally. */
+static CLG_LogRef LOG = {"bke.undosys"};
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Nested Undo Checks
+ *
+ * Make sure we're not running undo operations from 'step_encode', 'step_decode' callbacks.
+ * bugs caused by this situation aren't _that_ hard to spot but aren't always so obvious.
+ * Best we have a check which shows the problem immediately.
+ *
+ * \{ */
+#define WITH_NESTED_UNDO_CHECK
+
+#ifdef WITH_NESTED_UNDO_CHECK
+static bool g_undo_callback_running = false;
+# define UNDO_NESTED_ASSERT(state) BLI_assert(g_undo_callback_running == state)
+# define UNDO_NESTED_CHECK_BEGIN { \
+ UNDO_NESTED_ASSERT(false); \
+ g_undo_callback_running = true; \
+} ((void)0)
+# define UNDO_NESTED_CHECK_END { \
+ UNDO_NESTED_ASSERT(true); \
+ g_undo_callback_running = false; \
+} ((void)0)
+#else
+# define UNDO_NESTED_ASSERT(state) ((void)0)
+# define UNDO_NESTED_CHECK_BEGIN ((void)0)
+# define UNDO_NESTED_CHECK_END ((void)0)
+#endif
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Public Undo Types
+ *
+ * Unfortunately we need this for a handful of places.
+ */
+const UndoType *BKE_UNDOSYS_TYPE_IMAGE = NULL;
+const UndoType *BKE_UNDOSYS_TYPE_MEMFILE = NULL;
+const UndoType *BKE_UNDOSYS_TYPE_PAINTCURVE = NULL;
+const UndoType *BKE_UNDOSYS_TYPE_PARTICLE = NULL;
+const UndoType *BKE_UNDOSYS_TYPE_SCULPT = NULL;
+const UndoType *BKE_UNDOSYS_TYPE_TEXT = NULL;
+/** \} */
+
+/* UndoType */
+
+static ListBase g_undo_types = {NULL, NULL};
+
+static const UndoType *BKE_undosys_type_from_context(bContext *C)
+{
+ for (const UndoType *ut = g_undo_types.first; ut; ut = ut->next) {
+ /* No poll means we don't check context. */
+ if (ut->poll && ut->poll(C)) {
+ return ut;
+ }
+ }
+ return NULL;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Callback Wrappers
+ *
+ * #UndoRefID is simply a way to avoid inlining name copy and lookups,
+ * since it's easy to forget a single case when done inline (crashing in some cases).
+ *
+ * \{ */
+
+static void undosys_id_ref_store(void *UNUSED(user_data), UndoRefID *id_ref)
+{
+ BLI_assert(id_ref->name[0] == '\0');
+ if (id_ref->ptr) {
+ BLI_strncpy(id_ref->name, id_ref->ptr->name, sizeof(id_ref->name));
+ /* Not needed, just prevents stale data access. */
+ id_ref->ptr = NULL;
+ }
+}
+
+static void undosys_id_ref_resolve(void *user_data, UndoRefID *id_ref)
+{
+ /* Note: we could optimize this, for now it's not too bad since it only runs when we access undo! */
+ Main *bmain = user_data;
+ ListBase *lb = which_libbase(bmain, GS(id_ref->name));
+ for (ID *id = lb->first; id; id = id->next) {
+ if (STREQ(id_ref->name, id->name) && (id->lib == NULL)) {
+ id_ref->ptr = id;
+ break;
+ }
+ }
+}
+
+static bool undosys_step_encode(bContext *C, UndoStep *us)
+{
+ CLOG_INFO(&LOG, 2, "addr=%p, name='%s', type='%s'", us, us->name, us->type->name);
+ UNDO_NESTED_CHECK_BEGIN;
+ bool ok = us->type->step_encode(C, us);
+ UNDO_NESTED_CHECK_END;
+ if (ok) {
+ if (us->type->step_foreach_ID_ref != NULL) {
+ /* Don't use from context yet because sometimes context is fake and not all members are filled in. */
+ Main *bmain = G.main;
+ us->type->step_foreach_ID_ref(us, undosys_id_ref_store, bmain);
+ }
+ }
+ if (ok == false) {
+ CLOG_INFO(&LOG, 2, "encode callback didn't create undo step");
+ }
+ return ok;
+}
+
+static void undosys_step_decode(bContext *C, UndoStep *us, int dir)
+{
+ CLOG_INFO(&LOG, 2, "addr=%p, name='%s', type='%s'", us, us->name, us->type->name);
+ if (us->type->step_foreach_ID_ref) {
+ /* Don't use from context yet because sometimes context is fake and not all members are filled in. */
+ Main *bmain = G.main;
+ us->type->step_foreach_ID_ref(us, undosys_id_ref_resolve, bmain);
+ }
+
+ UNDO_NESTED_CHECK_BEGIN;
+ us->type->step_decode(C, us, dir);
+ UNDO_NESTED_CHECK_END;
+}
+
+static void undosys_step_free_and_unlink(UndoStack *ustack, UndoStep *us)
+{
+ CLOG_INFO(&LOG, 2, "addr=%p, name='%s', type='%s'", us, us->name, us->type->name);
+ UNDO_NESTED_CHECK_BEGIN;
+ us->type->step_free(us);
+ UNDO_NESTED_CHECK_END;
+
+ BLI_remlink(&ustack->steps, us);
+ MEM_freeN(us);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Stack
+ * \{ */
+
+#ifndef NDEBUG
+static void undosys_stack_validate(UndoStack *ustack, bool expect_non_empty)
+{
+ if (ustack->step_active != NULL) {
+ BLI_assert(!BLI_listbase_is_empty(&ustack->steps));
+ BLI_assert(BLI_findindex(&ustack->steps, ustack->step_active) != -1);
+ }
+ if (expect_non_empty) {
+ BLI_assert(!BLI_listbase_is_empty(&ustack->steps));
+ }
+}
+#else
+static void undosys_stack_validate(UndoStack *ustack, bool expect_non_empty)
+{
+ UNUSED_VARS(ustack, expect_non_empty);
+}
+#endif
+
+UndoStack *BKE_undosys_stack_create(void)
+{
+ UndoStack *ustack = MEM_callocN(sizeof(UndoStack), __func__);
+ return ustack;
+}
+
+void BKE_undosys_stack_destroy(UndoStack *ustack)
+{
+ BKE_undosys_stack_clear(ustack);
+ MEM_freeN(ustack);
+}
+
+void BKE_undosys_stack_clear(UndoStack *ustack)
+{
+ UNDO_NESTED_ASSERT(false);
+ CLOG_INFO(&LOG, 1, "steps=%d", BLI_listbase_count(&ustack->steps));
+ for (UndoStep *us = ustack->steps.last, *us_prev; us; us = us_prev) {
+ us_prev = us->prev;
+ undosys_step_free_and_unlink(ustack, us);
+ }
+ BLI_listbase_clear(&ustack->steps);
+ ustack->step_active = NULL;
+}
+
+static bool undosys_stack_push_main(UndoStack *ustack, const char *name, struct Main *bmain)
+{
+ UNDO_NESTED_ASSERT(false);
+ CLOG_INFO(&LOG, 1, "'%s'", name);
+ bContext *C_temp = CTX_create();
+ CTX_data_main_set(C_temp, bmain);
+ bool ok = BKE_undosys_step_push_with_type(ustack, C_temp, name, BKE_UNDOSYS_TYPE_MEMFILE);
+ CTX_free(C_temp);
+ return ok;
+}
+
+void BKE_undosys_stack_init_from_main(UndoStack *ustack, struct Main *bmain)
+{
+ UNDO_NESTED_ASSERT(false);
+ undosys_stack_push_main(ustack, "original", bmain);
+}
+
+/* name optional */
+bool BKE_undosys_stack_has_undo(UndoStack *ustack, const char *name)
+{
+ if (name) {
+ UndoStep *us = BLI_rfindstring(&ustack->steps, name, offsetof(UndoStep, name));
+ return us && us->prev;
+ }
+
+ return !BLI_listbase_is_empty(&ustack->steps);
+}
+
+UndoStep *BKE_undosys_stack_active_with_type(UndoStack *ustack, const UndoType *ut)
+{
+ UndoStep *us = ustack->step_active;
+ while (us && (us->type != ut)) {
+ us = us->prev;
+ }
+ return us;
+}
+
+UndoStep *BKE_undosys_stack_init_or_active_with_type(UndoStack *ustack, const UndoType *ut)
+{
+ UNDO_NESTED_ASSERT(false);
+ CLOG_INFO(&LOG, 1, "type='%s'", ut->name);
+ if (ustack->step_init && (ustack->step_init->type == ut)) {
+ return ustack->step_init;
+ }
+ return BKE_undosys_stack_active_with_type(ustack, ut);
+}
+
+/**
+ * \param steps: Limit the number of undo steps.
+ * \param memory_limit: Limit the amount of memory used by the undo stack.
+ */
+void BKE_undosys_stack_limit_steps_and_memory(UndoStack *ustack, int steps, size_t memory_limit)
+{
+ UNDO_NESTED_ASSERT(false);
+ if (!(steps || memory_limit)) {
+ return;
+ }
+
+ CLOG_INFO(&LOG, 1, "steps=%d, memory_limit=%zu", steps, memory_limit);
+ UndoStep *us;
+#ifdef WITH_GLOBAL_UNDO_KEEP_ONE
+ UndoStep *us_exclude = NULL;
+#endif
+ /* keep at least two (original + other) */
+ size_t data_size_all = 0;
+ size_t us_count = 0;
+ for (us = ustack->steps.last; us && us->prev; us = us->prev) {
+ if (memory_limit) {
+ data_size_all += us->data_size;
+ if (data_size_all > memory_limit) {
+ break;
+ }
+ }
+ if (steps) {
+ if (us_count == steps) {
+ break;
+ }
+ if (us->skip == false) {
+ us_count += 1;
+ }
+ }
+ }
+
+ if (us) {
+ if (us->prev && us->prev->prev) {
+ us = us->prev;
+ }
+
+#ifdef WITH_GLOBAL_UNDO_KEEP_ONE
+ /* Hack, we need to keep at least one BKE_UNDOSYS_TYPE_MEMFILE. */
+ if (us->type != BKE_UNDOSYS_TYPE_MEMFILE) {
+ us_exclude = us->prev;
+ while (us_exclude && us->type != BKE_UNDOSYS_TYPE_MEMFILE) {
+ us_exclude = us_exclude->prev;
+ }
+ if (us_exclude) {
+ BLI_remlink(&ustack->steps, us_exclude);
+ }
+ }
+#endif
+ /* Free from first to last, free functions may update de-duplication info (see #MemFileUndoStep). */
+ while (ustack->steps.first != us) {
+ UndoStep *us_first = ustack->steps.first;
+ BLI_assert(us_first != ustack->step_active);
+ undosys_step_free_and_unlink(ustack, us_first);
+ }
+
+#ifdef WITH_GLOBAL_UNDO_KEEP_ONE
+ if (us_exclude) {
+ BLI_addhead(&ustack->steps, us_exclude);
+ }
+#endif
+ }
+}
+
+/** \} */
+
+UndoStep *BKE_undosys_step_push_init_with_type(UndoStack *ustack, bContext *C, const char *name, const UndoType *ut)
+{
+ UNDO_NESTED_ASSERT(false);
+ /* We could detect and clean this up (but it should never happen!). */
+ BLI_assert(ustack->step_init == NULL);
+ if (ut->step_encode_init) {
+ undosys_stack_validate(ustack, false);
+ UndoStep *us = MEM_callocN(ut->step_size, __func__);
+ CLOG_INFO(&LOG, 1, "addr=%p, name='%s', type='%s'", us, name, ut->name);
+ if (name != NULL) {
+ BLI_strncpy(us->name, name, sizeof(us->name));
+ }
+ us->type = ut;
+ ustack->step_init = us;
+ ut->step_encode_init(C, us);
+ undosys_stack_validate(ustack, true);
+ return us;
+ }
+ else {
+ return NULL;
+ }
+}
+
+UndoStep *BKE_undosys_step_push_init(UndoStack *ustack, bContext *C, const char *name)
+{
+ UNDO_NESTED_ASSERT(false);
+ /* We could detect and clean this up (but it should never happen!). */
+ BLI_assert(ustack->step_init == NULL);
+ const UndoType *ut = BKE_undosys_type_from_context(C);
+ if (ut == NULL) {
+ return NULL;
+ }
+ return BKE_undosys_step_push_init_with_type(ustack, C, name, ut);
+}
+
+bool BKE_undosys_step_push_with_type(UndoStack *ustack, bContext *C, const char *name, const UndoType *ut)
+{
+ UNDO_NESTED_ASSERT(false);
+ undosys_stack_validate(ustack, false);
+ bool is_not_empty = ustack->step_active != NULL;
+
+ /* Remove all undos after (also when 'ustack->step_active == NULL'). */
+ while (ustack->steps.last != ustack->step_active) {
+ UndoStep *us_iter = ustack->steps.last;
+ undosys_step_free_and_unlink(ustack, us_iter);
+ undosys_stack_validate(ustack, is_not_empty);
+ }
+
+ if (ustack->step_active) {
+ BLI_assert(BLI_findindex(&ustack->steps, ustack->step_active) != -1);
+ }
+
+#ifdef WITH_GLOBAL_UNDO_ENSURE_UPDATED
+ if (ut->step_foreach_ID_ref != NULL) {
+ Main *bmain = G.main;
+ if (bmain->is_memfile_undo_written == false) {
+ const char *name_internal = "MemFile Internal";
+ if (undosys_stack_push_main(ustack, name_internal, bmain)) {
+ UndoStep *us = ustack->steps.last;
+ BLI_assert(STREQ(us->name, name_internal));
+ us->skip = true;
+ }
+ }
+ }
+#endif
+
+ UndoStep *us = ustack->step_init ? ustack->step_init : MEM_callocN(ut->step_size, __func__);
+ ustack->step_init = NULL;
+ if (us->name[0] == '\0') {
+ BLI_strncpy(us->name, name, sizeof(us->name));
+ }
+ us->type = ut;
+ /* initialized, not added yet. */
+
+ if (undosys_step_encode(C, us)) {
+ ustack->step_active = us;
+ BLI_addtail(&ustack->steps, us);
+ undosys_stack_validate(ustack, true);
+ return true;
+ }
+ else {
+ MEM_freeN(us);
+ undosys_stack_validate(ustack, true);
+ return false;
+ }
+}
+
+bool BKE_undosys_step_push(UndoStack *ustack, bContext *C, const char *name)
+{
+ UNDO_NESTED_ASSERT(false);
+ const UndoType *ut = ustack->step_init ? ustack->step_init->type : BKE_undosys_type_from_context(C);
+ if (ut == NULL) {
+ return false;
+ }
+ return BKE_undosys_step_push_with_type(ustack, C, name, ut);
+}
+
+
+/**
+ * Useful when we want to diff against previous undo data but can't be sure the types match.
+ */
+UndoStep *BKE_undosys_step_same_type_next(UndoStep *us)
+{
+ if (us) {
+ const UndoType *ut = us->type;
+ while ((us = us->next)) {
+ if (us->type == ut) {
+ return us;
+ }
+ }
+
+ }
+ return us;
+}
+
+/**
+ * Useful when we want to diff against previous undo data but can't be sure the types match.
+ */
+UndoStep *BKE_undosys_step_same_type_prev(UndoStep *us)
+{
+ if (us) {
+ const UndoType *ut = us->type;
+ while ((us = us->prev)) {
+ if (us->type == ut) {
+ return us;
+ }
+ }
+
+ }
+ return us;
+}
+
+UndoStep *BKE_undosys_step_find_by_name_with_type(UndoStack *ustack, const char *name, const UndoType *ut)
+{
+ for (UndoStep *us = ustack->steps.last; us; us = us->prev) {
+ if (us->type == ut) {
+ if (STREQ(name, us->name)) {
+ return us;
+ }
+ }
+ }
+ return NULL;
+}
+
+UndoStep *BKE_undosys_step_find_by_name(UndoStack *ustack, const char *name)
+{
+ return BLI_rfindstring(&ustack->steps, name, offsetof(UndoStep, name));
+}
+
+UndoStep *BKE_undosys_step_find_by_type(UndoStack *ustack, const UndoType *ut)
+{
+ for (UndoStep *us = ustack->steps.last; us; us = us->prev) {
+ if (us->type == ut) {
+ return us;
+ }
+ }
+ return NULL;
+}
+
+bool BKE_undosys_step_undo_with_data_ex(
+ UndoStack *ustack, bContext *C, UndoStep *us,
+ bool use_skip)
+{
+ UNDO_NESTED_ASSERT(false);
+ if (us) {
+ undosys_stack_validate(ustack, true);
+ }
+ UndoStep *us_prev = us ? us->prev : NULL;
+ if (us && us->type->mode == BKE_UNDOTYPE_MODE_STORE) {
+ /* The current state is a copy, we need to load the previous state. */
+ us = us_prev;
+ }
+
+ if (us != NULL) {
+ CLOG_INFO(&LOG, 1, "addr=%p, name='%s', type='%s'", us, us->name, us->type->name);
+ undosys_step_decode(C, us, -1);
+ ustack->step_active = us_prev;
+ undosys_stack_validate(ustack, true);
+ if (use_skip) {
+ if (ustack->step_active && ustack->step_active->skip) {
+ CLOG_INFO(&LOG, 2, "undo continue with skip %p '%s', type='%s'", us, us->name, us->type->name);
+ BKE_undosys_step_undo_with_data(ustack, C, ustack->step_active);
+ }
+ }
+ return true;
+ }
+ return false;
+}
+bool BKE_undosys_step_undo_with_data(UndoStack *ustack, bContext *C, UndoStep *us)
+{
+ return BKE_undosys_step_undo_with_data_ex(ustack, C, us, true);
+}
+
+bool BKE_undosys_step_undo(UndoStack *ustack, bContext *C)
+{
+ return BKE_undosys_step_undo_with_data(ustack, C, ustack->step_active);
+}
+
+void BKE_undosys_step_undo_from_index(UndoStack *ustack, bContext *C, int index)
+{
+ UndoStep *us = BLI_findlink(&ustack->steps, index);
+ BLI_assert(us->skip == false);
+ BKE_undosys_step_load_data(ustack, C, us);
+}
+
+bool BKE_undosys_step_redo_with_data_ex(
+ UndoStack *ustack, bContext *C, UndoStep *us,
+ bool use_skip)
+{
+ UNDO_NESTED_ASSERT(false);
+ UndoStep *us_next = us ? us->next : NULL;
+ /* Unlike undo accumulate, we always use the next. */
+ us = us_next;
+
+ if (us != NULL) {
+ CLOG_INFO(&LOG, 1, "addr=%p, name='%s', type='%s'", us, us->name, us->type->name);
+ undosys_step_decode(C, us, 1);
+ ustack->step_active = us_next;
+ if (use_skip) {
+ if (ustack->step_active && ustack->step_active->skip) {
+ CLOG_INFO(&LOG, 2, "redo continue with skip %p '%s', type='%s'", us, us->name, us->type->name);
+ BKE_undosys_step_redo_with_data(ustack, C, ustack->step_active);
+ }
+ }
+ return true;
+ }
+ return false;
+}
+bool BKE_undosys_step_redo_with_data(UndoStack *ustack, bContext *C, UndoStep *us)
+{
+ return BKE_undosys_step_redo_with_data_ex(ustack, C, us, true);
+}
+
+bool BKE_undosys_step_redo(UndoStack *ustack, bContext *C)
+{
+ return BKE_undosys_step_redo_with_data(ustack, C, ustack->step_active);
+}
+
+bool BKE_undosys_step_load_data(UndoStack *ustack, bContext *C, UndoStep *us)
+{
+ UNDO_NESTED_ASSERT(false);
+ const int index_active = BLI_findindex(&ustack->steps, ustack->step_active);
+ const int index_target = BLI_findindex(&ustack->steps, us);
+ BLI_assert(!ELEM(-1, index_active, index_target));
+ bool ok = true;
+
+ if (index_target < index_active) {
+ uint i = index_active - index_target;
+ while (i-- && ok) {
+ ok = BKE_undosys_step_undo_with_data_ex(ustack, C, ustack->step_active, false);
+ }
+ }
+ else if (index_target > index_active) {
+ uint i = index_target - index_active;
+ while (i-- && ok) {
+ ok = BKE_undosys_step_redo_with_data_ex(ustack, C, ustack->step_active, false);
+ }
+ }
+
+ if (ok) {
+ BLI_assert(ustack->step_active == us);
+ }
+
+ return ok;
+}
+
+bool BKE_undosys_step_undo_compat_only(UndoStack *ustack, bContext *C, int step)
+{
+ if (step == 0) {
+ return BKE_undosys_step_undo_with_data(ustack, C, ustack->step_active);
+ }
+ else if (step == 1) {
+ return BKE_undosys_step_undo(ustack, C);
+ }
+ else {
+ return BKE_undosys_step_redo(ustack, C);
+ }
+}
+/**
+ * Similar to #WM_operatortype_append
+ */
+UndoType *BKE_undosys_type_append(void (*undosys_fn)(UndoType *))
+{
+ UndoType *ut;
+
+ ut = MEM_callocN(sizeof(UndoType), __func__);
+
+ undosys_fn(ut);
+
+ BLI_assert(ut->mode != 0);
+
+ BLI_addtail(&g_undo_types, ut);
+
+ return ut;
+}
+
+void BKE_undosys_type_free_all(void)
+{
+ UndoType *ut;
+ while ((ut = BLI_pophead(&g_undo_types))) {
+ MEM_freeN(ut);
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ID Reference Utilities
+ *
+ * Unfortunately we need this for a handful of places.
+ */
+
+static void UNUSED_FUNCTION(BKE_undosys_foreach_ID_ref(
+ UndoStack *ustack, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data))
+{
+ for (UndoStep *us = ustack->steps.first; us; us = us->next) {
+ const UndoType *ut = us->type;
+ if (ut->step_foreach_ID_ref != NULL) {
+ ut->step_foreach_ID_ref(us, foreach_ID_ref_fn, user_data);
+ }
+ }
+}
+
+typedef struct UndoIDPtrMapItem {
+ /** Never changes (matches undo data). Use as sort key for binary search. */
+ const void *ptr;
+ /** Write the new pointers here. */
+ uint index;
+} UndoIDPtrMapItem;
+
+typedef struct UndoIDPtrMap {
+ UndoRefID *refs;
+ /**
+ * Pointer map, update 'dst' members before use.
+ * This is always sorted (adds some overhead when adding, in practice it's acceptable since).
+ */
+ UndoIDPtrMapItem *pmap;
+
+ /** Length for both 'refs' & 'pmap' */
+ uint len;
+ uint len_alloc;
+} UndoIDPtrMap;
+
+#ifdef DEBUG
+# define PMAP_DEFAULT_ALLOC 1
+#else
+# define PMAP_DEFAULT_ALLOC 32
+#endif
+
+void BKE_undosys_ID_map_foreach_ID_ref(
+ UndoIDPtrMap *map,
+ UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ for (uint i = 0; i < map->len; i++) {
+ foreach_ID_ref_fn(user_data, &map->refs[i]);
+ }
+}
+
+/**
+ * Return true when found, otherwise index is set to the index we should insert.
+ */
+static bool undosys_ID_map_lookup_index(const UndoIDPtrMap *map, const void *key, uint *r_index)
+{
+ const UndoIDPtrMapItem *pmap = map->pmap;
+ const uint len = map->len;
+ if (len == 0) {
+ if (*r_index) {
+ *r_index = 0;
+ }
+ return false;
+ }
+ int min = 0, max = len - 1;
+ while (min <= max) {
+ const uint mid = (min + max) / 2;
+ if (pmap[mid].ptr < key) {
+ min = mid + 1;
+ }
+ else if (pmap[mid].ptr == key) {
+ if (r_index) {
+ *r_index = mid;
+ }
+ return true;
+ }
+ else if (pmap[mid].ptr > key) {
+ max = mid - 1;
+ }
+ }
+ if (r_index) {
+ *r_index = min;
+ }
+ return false;
+}
+
+/**
+ * A set of ID's use for efficient decoding, so we can map pointers back to the newly loaded data
+ * without performing full look ups each time.
+ *
+ * This can be used as an old_pointer -> new_pointer lookup.
+ */
+UndoIDPtrMap *BKE_undosys_ID_map_create(void)
+{
+ UndoIDPtrMap *map = MEM_mallocN(sizeof(*map), __func__);
+ map->len_alloc = PMAP_DEFAULT_ALLOC;
+ map->refs = MEM_mallocN(sizeof(*map->refs) * map->len_alloc, __func__);
+ map->pmap = MEM_mallocN(sizeof(*map->pmap) * map->len_alloc, __func__);
+ map->len = 0;
+ return map;
+}
+void BKE_undosys_ID_map_destroy(UndoIDPtrMap *idpmap)
+{
+ MEM_SAFE_FREE(idpmap->refs);
+ MEM_SAFE_FREE(idpmap->pmap);
+ MEM_freeN(idpmap);
+}
+
+void BKE_undosys_ID_map_add(UndoIDPtrMap *map, ID *id)
+{
+ uint index;
+ if (id->lib != NULL) {
+ return;
+ }
+
+ if (undosys_ID_map_lookup_index(map, id, &index)) {
+ return; /* exists. */
+ }
+
+ const uint len_src = map->len;
+ const uint len_dst = map->len + 1;
+ if (len_dst > map->len_alloc) {
+ map->len_alloc *= 2;
+ BLI_assert(map->len_alloc >= len_dst);
+ map->pmap = MEM_reallocN(map->pmap, sizeof(*map->pmap) * map->len_alloc);
+ map->refs = MEM_reallocN(map->refs, sizeof(*map->refs) * map->len_alloc);
+ }
+
+#if 0 /* Will be done automatically in callback. */
+ BLI_strncpy(map->refs[len_src].name, id->name, sizeof(id->name));
+#else
+ map->refs[len_src].name[0] = '\0';
+#endif
+ map->refs[len_src].ptr = id;
+
+ if (len_src != 0 && index != len_src) {
+ memmove(&map->pmap[index + 1], &map->pmap[index], sizeof(*map->pmap) * (len_src - index));
+ }
+ map->pmap[index].ptr = id;
+ map->pmap[index].index = len_src;
+
+ map->len = len_dst;
+}
+
+ID *BKE_undosys_ID_map_lookup(const UndoIDPtrMap *map, const ID *id_src)
+{
+ /* We should only ever lookup indices which exist! */
+ uint index;
+ if (!undosys_ID_map_lookup_index(map, id_src, &index)) {
+ BLI_assert(0);
+ }
+ index = map->pmap[index].index;
+ ID *id_dst = map->refs[index].ptr;
+ BLI_assert(id_dst != NULL);
+ BLI_assert(STREQ(id_dst->name, map->refs[index].name));
+ return id_dst;
+}
+
+void BKE_undosys_ID_map_add_with_prev(UndoIDPtrMap *map, ID *id, ID **id_prev)
+{
+ if (id == *id_prev) {
+ return;
+ }
+ *id_prev = id;
+ BKE_undosys_ID_map_add(map, id);
+}
+
+ID *BKE_undosys_ID_map_lookup_with_prev(const UndoIDPtrMap *map, ID *id_src, ID *id_prev_match[2])
+{
+ if (id_src == id_prev_match[0]) {
+ return id_prev_match[1];
+ }
+ else {
+ ID *id_dst = BKE_undosys_ID_map_lookup(map, id_src);
+ id_prev_match[0] = id_src;
+ id_prev_match[1] = id_dst;
+ return id_dst;
+ }
+}
+
+/** \} */
diff --git a/source/blender/blenkernel/intern/unit.c b/source/blender/blenkernel/intern/unit.c
index c0a373395dc..8606da0743b 100644
--- a/source/blender/blenkernel/intern/unit.c
+++ b/source/blender/blenkernel/intern/unit.c
@@ -372,6 +372,12 @@ static size_t unit_as_string(char *str, int len_max, double value, int prec, con
value_conv = value / unit->scalar;
+ /* Adjust precision to expected number of significant digits.
+ * Note that here, we shall not have to worry about very big/small numbers, units are expected to replace
+ * 'scientific notation' in those cases. */
+ prec -= integer_digits_d(value_conv);
+ CLAMP(prec, 0, 6);
+
/* Convert to a string */
len = BLI_snprintf_rlen(str, len_max, "%.*f", prec, value_conv);
@@ -442,12 +448,15 @@ size_t bUnit_AsString(char *str, int len_max, double value, int prec, int system
size_t i;
i = unit_as_string(str, len_max, value_a, prec, usys, unit_a, '\0');
+ prec -= integer_digits_d(value_a / unit_b->scalar) - integer_digits_d(value_b / unit_b->scalar);
+ prec = max_ii(prec, 0);
+
/* is there enough space for at least 1 char of the next unit? */
if (i + 2 < len_max) {
str[i++] = ' ';
/* use low precision since this is a smaller unit */
- i += unit_as_string(str + i, len_max - i, value_b, prec ? 1 : 0, usys, unit_b, '\0');
+ i += unit_as_string(str + i, len_max - i, value_b, prec, usys, unit_b, '\0');
}
return i;
}
diff --git a/source/blender/blenkernel/intern/world.c b/source/blender/blenkernel/intern/world.c
index caa9a1e357f..5736c9331bf 100644
--- a/source/blender/blenkernel/intern/world.c
+++ b/source/blender/blenkernel/intern/world.c
@@ -43,7 +43,6 @@
#include "BLI_listbase.h"
#include "BKE_animsys.h"
-#include "BKE_global.h"
#include "BKE_icons.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
@@ -108,47 +107,65 @@ void BKE_world_init(World *wrld)
wrld->mistdist = 25.0f;
}
-World *add_world(Main *bmain, const char *name)
+World *BKE_world_add(Main *bmain, const char *name)
{
World *wrld;
- wrld = BKE_libblock_alloc(bmain, ID_WO, name);
+ wrld = BKE_libblock_alloc(bmain, ID_WO, name, 0);
BKE_world_init(wrld);
return wrld;
}
-World *BKE_world_copy(Main *bmain, World *wrld)
+/**
+ * Only copy internal data of World ID from source to already allocated/initialized destination.
+ * You probably nerver want to use that directly, use id_copy or BKE_id_copy_ex for typical needs.
+ *
+ * WARNING! This function will not handle ID user count!
+ *
+ * \param flag Copying options (see BKE_library.h's LIB_ID_COPY_... flags for more).
+ */
+void BKE_world_copy_data(Main *bmain, World *wrld_dst, const World *wrld_src, const int flag)
{
- World *wrldn;
- int a;
-
- wrldn = BKE_libblock_copy(bmain, &wrld->id);
-
- for (a = 0; a < MAX_MTEX; a++) {
- if (wrld->mtex[a]) {
- wrldn->mtex[a] = MEM_mallocN(sizeof(MTex), "BKE_world_copy");
- memcpy(wrldn->mtex[a], wrld->mtex[a], sizeof(MTex));
- id_us_plus((ID *)wrldn->mtex[a]->tex);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (wrld_src->mtex[a]) {
+ wrld_dst->mtex[a] = MEM_dupallocN(wrld_src->mtex[a]);
}
}
- if (wrld->nodetree) {
- wrldn->nodetree = ntreeCopyTree(bmain, wrld->nodetree);
+ if (wrld_src->nodetree) {
+ /* Note: nodetree is *not* in bmain, however this specific case is handled at lower level
+ * (see BKE_libblock_copy_ex()). */
+ BKE_id_copy_ex(bmain, (ID *)wrld_src->nodetree, (ID **)&wrld_dst->nodetree, flag, false);
}
-
- BKE_previewimg_id_copy(&wrldn->id, &wrld->id);
- BLI_listbase_clear(&wrldn->gpumaterial);
+ BLI_listbase_clear(&wrld_dst->gpumaterial);
- BKE_id_copy_ensure_local(bmain, &wrld->id, &wrldn->id);
+ if ((flag & LIB_ID_COPY_NO_PREVIEW) == 0) {
+ BKE_previewimg_id_copy(&wrld_dst->id, &wrld_src->id);
+ }
+ else {
+ wrld_dst->preview = NULL;
+ }
+}
- return wrldn;
+World *BKE_world_copy(Main *bmain, const World *wrld)
+{
+ World *wrld_copy;
+ BKE_id_copy_ex(bmain, &wrld->id, (ID **)&wrld_copy, 0, false);
+ return wrld_copy;
}
-World *localize_world(World *wrld)
+World *BKE_world_localize(World *wrld)
{
+ /* TODO replace with something like
+ * World *wrld_copy;
+ * BKE_id_copy_ex(bmain, &wrld->id, (ID **)&wrld_copy, LIB_ID_COPY_NO_MAIN | LIB_ID_COPY_NO_PREVIEW | LIB_ID_COPY_NO_USER_REFCOUNT, false);
+ * return wrld_copy;
+ *
+ * ... Once f*** nodes are fully converted to that too :( */
+
World *wrldn;
int a;
@@ -156,7 +173,7 @@ World *localize_world(World *wrld)
for (a = 0; a < MAX_MTEX; a++) {
if (wrld->mtex[a]) {
- wrldn->mtex[a] = MEM_mallocN(sizeof(MTex), "localize_world");
+ wrldn->mtex[a] = MEM_mallocN(sizeof(MTex), __func__);
memcpy(wrldn->mtex[a], wrld->mtex[a], sizeof(MTex));
}
}
diff --git a/source/blender/blenkernel/intern/writeavi.c b/source/blender/blenkernel/intern/writeavi.c
index 89b2caa5ac7..2fb4ed03603 100644
--- a/source/blender/blenkernel/intern/writeavi.c
+++ b/source/blender/blenkernel/intern/writeavi.c
@@ -80,10 +80,6 @@ static void *context_create_avi(void);
static void context_free_avi(void *context_v);
#endif /* WITH_AVI */
-#ifdef WITH_QUICKTIME
-# include "quicktime_export.h"
-#endif
-
#ifdef WITH_FFMPEG
# include "BKE_writeffmpeg.h"
#endif
@@ -115,16 +111,6 @@ bMovieHandle *BKE_movie_handle_get(const char imtype)
#endif
/* do the platform specific handles */
-#ifdef WITH_QUICKTIME
- if (imtype == R_IMF_IMTYPE_QUICKTIME) {
- mh.start_movie = start_qt;
- mh.append_movie = append_qt;
- mh.end_movie = end_qt;
- mh.get_movie_path = filepath_qt;
- mh.context_create = context_create_qt;
- mh.context_free = context_free_qt;
- }
-#endif
#ifdef WITH_FFMPEG
if (ELEM(imtype, R_IMF_IMTYPE_FFMPEG, R_IMF_IMTYPE_H264, R_IMF_IMTYPE_XVID, R_IMF_IMTYPE_THEORA)) {
mh.start_movie = BKE_ffmpeg_start;
diff --git a/source/blender/blenkernel/intern/writeffmpeg.c b/source/blender/blenkernel/intern/writeffmpeg.c
index 9994d479ce7..d7fcd896e11 100644
--- a/source/blender/blenkernel/intern/writeffmpeg.c
+++ b/source/blender/blenkernel/intern/writeffmpeg.c
@@ -53,6 +53,7 @@
#include "BKE_global.h"
#include "BKE_idprop.h"
+#include "BKE_image.h"
#include "BKE_main.h"
#include "BKE_report.h"
#include "BKE_sound.h"
@@ -62,6 +63,8 @@
#include "ffmpeg_compat.h"
+struct StampData;
+
typedef struct FFMpegContext {
int ffmpeg_type;
int ffmpeg_codec;
@@ -75,7 +78,7 @@ typedef struct FFMpegContext {
bool ffmpeg_preview;
int ffmpeg_crf; /* set to 0 to not use CRF mode; we have another flag for lossless anyway. */
- int ffmpeg_preset; /* see FFMpegPreset */
+ int ffmpeg_preset; /* see eFFMpegPreset */
AVFormatContext *outfile;
AVStream *video_stream;
@@ -94,6 +97,8 @@ typedef struct FFMpegContext {
bool audio_deinterleave;
int audio_sample_size;
+ struct StampData *stamp_data;
+
#ifdef WITH_AUDASPACE
AUD_Device *audio_mixdown_device;
#endif
@@ -158,7 +163,7 @@ static int write_audio_frame(FFMpegContext *context)
for (channel = 0; channel < c->channels; channel++) {
for (i = 0; i < frame->nb_samples; i++) {
memcpy(context->audio_deinterleave_buffer + (i + channel * frame->nb_samples) * context->audio_sample_size,
- context->audio_input_buffer + (c->channels * i + channel) * context->audio_sample_size, context->audio_sample_size);
+ context->audio_input_buffer + (c->channels * i + channel) * context->audio_sample_size, context->audio_sample_size);
}
}
@@ -568,7 +573,8 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int
if (context->ffmpeg_crf >= 0) {
ffmpeg_dict_set_int(&opts, "crf", context->ffmpeg_crf);
- } else {
+ }
+ else {
c->bit_rate = context->ffmpeg_video_bitrate * 1000;
c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
@@ -576,24 +582,33 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int
}
if (context->ffmpeg_preset) {
- char const * preset_name;
- switch(context->ffmpeg_preset) {
- case FFM_PRESET_ULTRAFAST: preset_name = "ultrafast"; break;
- case FFM_PRESET_SUPERFAST: preset_name = "superfast"; break;
- case FFM_PRESET_VERYFAST: preset_name = "veryfast"; break;
- case FFM_PRESET_FASTER: preset_name = "faster"; break;
- case FFM_PRESET_FAST: preset_name = "fast"; break;
- case FFM_PRESET_MEDIUM: preset_name = "medium"; break;
- case FFM_PRESET_SLOW: preset_name = "slow"; break;
- case FFM_PRESET_SLOWER: preset_name = "slower"; break;
- case FFM_PRESET_VERYSLOW: preset_name = "veryslow"; break;
+ /* 'preset' is used by h.264, 'deadline' is used by webm/vp9. I'm not
+ * setting those properties conditionally based on the video codec,
+ * as the FFmpeg encoder simply ignores unknown settings anyway. */
+ char const *preset_name = NULL; /* used by h.264 */
+ char const *deadline_name = NULL; /* used by webm/vp9 */
+ switch (context->ffmpeg_preset) {
+ case FFM_PRESET_GOOD:
+ preset_name = "medium";
+ deadline_name = "good";
+ break;
+ case FFM_PRESET_BEST:
+ preset_name = "slower";
+ deadline_name = "best";
+ break;
+ case FFM_PRESET_REALTIME:
+ preset_name = "superfast";
+ deadline_name = "realtime";
+ break;
default:
printf("Unknown preset number %i, ignoring.\n", context->ffmpeg_preset);
- preset_name = NULL;
}
if (preset_name != NULL) {
av_dict_set(&opts, "preset", preset_name, 0);
}
+ if (deadline_name != NULL) {
+ av_dict_set(&opts, "deadline", deadline_name, 0);
+ }
}
#if 0
@@ -680,6 +695,7 @@ static AVStream *alloc_video_stream(FFMpegContext *context, RenderData *rd, int
/* xasp & yasp got float lately... */
st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);
+ st->avg_frame_rate = av_inv_q(c->time_base);
set_ffmpeg_properties(rd, c, "video", &opts);
@@ -834,6 +850,12 @@ static void ffmpeg_dict_set_float(AVDictionary **dict, const char *key, float va
av_dict_set(dict, key, buffer, 0);
}
+static void ffmpeg_add_metadata_callback(void *data, const char *propname, char *propvalue, int len)
+{
+ AVDictionary **metadata = (AVDictionary **)data;
+ av_dict_set(metadata, propname, propvalue, 0);
+}
+
static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int rectx, int recty, const char *suffix, ReportList *reports)
{
/* Handle to the output file */
@@ -992,6 +1014,11 @@ static int start_ffmpeg_impl(FFMpegContext *context, struct RenderData *rd, int
goto fail;
}
}
+
+ if (context->stamp_data != NULL) {
+ BKE_stamp_info_callback(&of->metadata, context->stamp_data, ffmpeg_add_metadata_callback, false);
+ }
+
if (avformat_write_header(of, NULL) < 0) {
BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
goto fail;
@@ -1166,6 +1193,7 @@ int BKE_ffmpeg_start(void *context_v, struct Scene *scene, RenderData *rd, int r
context->ffmpeg_autosplit_count = 0;
context->ffmpeg_preview = preview;
+ context->stamp_data = BKE_stamp_info_from_scene_static(scene);
success = start_ffmpeg_impl(context, rd, rectx, recty, suffix, reports);
#ifdef WITH_AUDASPACE
@@ -1657,7 +1685,7 @@ void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
{
BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
rd->ffcodecdata.constant_rate_factor = FFM_CRF_MEDIUM;
- rd->ffcodecdata.ffmpeg_preset = FFM_PRESET_MEDIUM;
+ rd->ffcodecdata.ffmpeg_preset = FFM_PRESET_GOOD;
rd->ffcodecdata.type = FFMPEG_MKV;
}
if (rd->ffcodecdata.type == FFMPEG_OGG) {
@@ -1732,6 +1760,7 @@ void *BKE_ffmpeg_context_create(void)
context->ffmpeg_autosplit = 0;
context->ffmpeg_autosplit_count = 0;
context->ffmpeg_preview = false;
+ context->stamp_data = NULL;
return context;
}
@@ -1739,9 +1768,13 @@ void *BKE_ffmpeg_context_create(void)
void BKE_ffmpeg_context_free(void *context_v)
{
FFMpegContext *context = context_v;
- if (context) {
- MEM_freeN(context);
+ if (context == NULL) {
+ return;
+ }
+ if (context->stamp_data) {
+ MEM_freeN(context->stamp_data);
}
+ MEM_freeN(context);
}
#endif /* WITH_FFMPEG */
diff --git a/source/blender/blenkernel/intern/writeframeserver.c b/source/blender/blenkernel/intern/writeframeserver.c
index 212af76a7e8..4757186f546 100644
--- a/source/blender/blenkernel/intern/writeframeserver.c
+++ b/source/blender/blenkernel/intern/writeframeserver.c
@@ -268,11 +268,7 @@ int BKE_frameserver_loop(void *context_v, RenderData *rd, ReportList *UNUSED(rep
struct timeval tv;
struct sockaddr_in addr;
int len, rval;
-#ifdef FREE_WINDOWS
- int socklen;
-#else
unsigned int socklen;
-#endif
char buf[4096];
FrameserverContext *context = context_v;
diff --git a/source/blender/blenkernel/particle_private.h b/source/blender/blenkernel/particle_private.h
new file mode 100644
index 00000000000..2189527118b
--- /dev/null
+++ b/source/blender/blenkernel/particle_private.h
@@ -0,0 +1,54 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation,
+ * Sergey Sharybin
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenkernel/particle_private.h
+ * \ingroup bke
+ */
+
+#ifndef __PARTICLE_PRIVATE_H__
+#define __PARTICLE_PRIVATE_H__
+
+typedef struct ParticleChildModifierContext {
+ ParticleThreadContext *thread_ctx;
+ ParticleSimulationData *sim;
+ ParticleTexture *ptex;
+ ChildParticle *cpa;
+ const float *par_co; /* float3 */
+ const float *par_vel; /* float3 */
+ const float *par_rot; /* float4 */
+ const float *par_orco; /* float3 */
+ const float *orco; /* float3 */
+ ParticleCacheKey *parent_keys;
+} ParticleChildModifierContext;
+
+void do_kink(ParticleKey *state, const float par_co[3], const float par_vel[3], const float par_rot[4], float time, float freq, float shape, float amplitude, float flat,
+ short type, short axis, float obmat[4][4], int smooth_start);
+float do_clump(ParticleKey *state, const float par_co[3], float time, const float orco_offset[3], float clumpfac, float clumppow, float pa_clump,
+ bool use_clump_noise, float clump_noise_size, CurveMapping *clumpcurve);
+void do_child_modifiers(const ParticleChildModifierContext *modifier_ctx,
+ float mat[4][4], ParticleKey *state, float t);
+
+#endif /* __PARTICLE_PRIVATE_H__ */
diff --git a/source/blender/blenkernel/tracking_private.h b/source/blender/blenkernel/tracking_private.h
index 591ee4d0d01..07236fb2096 100644
--- a/source/blender/blenkernel/tracking_private.h
+++ b/source/blender/blenkernel/tracking_private.h
@@ -105,6 +105,13 @@ struct MovieTrackingMarker *tracking_get_keyframed_marker(
int current_frame,
bool backwards);
+/*********************** Masking *************************/
+
+float *tracking_track_get_mask_for_region(int frame_width, int frame_height,
+ const float region_min[2],
+ const float region_max[2],
+ MovieTrackingTrack *track);
+
/*********************** Frame accessr *************************/
struct libmv_FrameAccessor;
@@ -114,12 +121,17 @@ typedef struct TrackingImageAccessor {
struct MovieCache *cache;
struct MovieClip *clips[MAX_ACCESSOR_CLIP];
int num_clips;
+ struct MovieTrackingTrack **tracks;
+ int num_tracks;
int start_frame;
struct libmv_FrameAccessor *libmv_accessor;
+ SpinLock cache_lock;
} TrackingImageAccessor;
TrackingImageAccessor *tracking_image_accessor_new(MovieClip *clips[MAX_ACCESSOR_CLIP],
int num_clips,
+ MovieTrackingTrack **tracks,
+ int num_tracks,
int start_frame);
void tracking_image_accessor_destroy(TrackingImageAccessor *accessor);
diff --git a/source/blender/blenlib/BLI_alloca.h b/source/blender/blenlib/BLI_alloca.h
index b44e6c66d2a..4fa69a24966 100644
--- a/source/blender/blenlib/BLI_alloca.h
+++ b/source/blender/blenlib/BLI_alloca.h
@@ -29,10 +29,6 @@
/* BLI_array_alloca / alloca */
-#if defined(__MINGW32__)
-# include <malloc.h> /* mingw needs for alloca() */
-#endif
-
#if defined(__GNUC__) || defined(__clang__)
#if defined(__cplusplus) && (__cplusplus > 199711L)
#define BLI_array_alloca(arr, realsize) \
diff --git a/source/blender/blenlib/BLI_array.h b/source/blender/blenlib/BLI_array.h
index c645ff06c00..8e94b8197ef 100644
--- a/source/blender/blenlib/BLI_array.h
+++ b/source/blender/blenlib/BLI_array.h
@@ -62,9 +62,10 @@
* Doing the realloc in a macro isn't so simple,
* so use a function the macros can use.
*/
-void _bli_array_grow_func(void **arr_p, const void *arr_static,
- const int sizeof_arr_p, const int arr_count, const int num,
- const char *alloc_str);
+void _bli_array_grow_func(
+ void **arr_p, const void *arr_static,
+ const int sizeof_arr_p, const int arr_len, const int num,
+ const char *alloc_str);
/* -------------------------------------------------------------------- */
@@ -74,18 +75,18 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
/** use ``sizeof(*(arr))`` to ensure the array exists and is an array */
#define BLI_array_declare(arr) \
- int _##arr##_count = ((void)(sizeof(*(arr))), 0); \
+ int _##arr##_len = ((void)(sizeof(*(arr))), 0); \
void *_##arr##_static = NULL
/**
* this will use stack space, up to maxstatic array elements, before
* switching to dynamic heap allocation */
#define BLI_array_staticdeclare(arr, maxstatic) \
- int _##arr##_count = 0; \
+ int _##arr##_len = 0; \
char _##arr##_static[maxstatic * sizeof(*(arr))]
/** returns the logical size of the array, not including buffering. */
-#define BLI_array_count(arr) ((void)0, _##arr##_count)
+#define BLI_array_len(arr) ((void)0, _##arr##_len)
/**
* Grow the array by a fixed number of items.
@@ -95,23 +96,23 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
#define BLI_array_reserve(arr, num) (void)( \
(((void *)(arr) == NULL) && \
((void *)(_##arr##_static) != NULL) && \
- /* don't add _##arr##_count below because it must be zero */ \
- (_bli_array_totalsize_static(arr) >= _##arr##_count + (num))) ? \
+ /* don't add _##arr##_len below because it must be zero */ \
+ (_bli_array_totalsize_static(arr) >= _##arr##_len + (num))) ? \
/* we have an empty array and a static var big enough */ \
(void)(arr = (void *)_##arr##_static) \
: \
/* use existing static array or allocate */ \
- (LIKELY(_bli_array_totalsize(arr) >= _##arr##_count + (num)) ? \
+ (LIKELY(_bli_array_totalsize(arr) >= _##arr##_len + (num)) ? \
(void)0 /* do nothing */ : \
_bli_array_grow_func((void **)&(arr), _##arr##_static, \
- sizeof(*(arr)), _##arr##_count, num, \
+ sizeof(*(arr)), _##arr##_len, num, \
"BLI_array." #arr)) \
)
/** returns length of array */
#define BLI_array_grow_items(arr, num) \
- (BLI_array_reserve(arr, num), (_##arr##_count += num))
+ (BLI_array_reserve(arr, num), (_##arr##_len += num))
#define BLI_array_grow_one(arr) \
BLI_array_grow_items(arr, 1)
@@ -119,7 +120,7 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
/** appends an item to the array. */
#define BLI_array_append(arr, item) ( \
(void) BLI_array_grow_one(arr), \
- (void) (arr[_##arr##_count - 1] = item) \
+ (void) (arr[_##arr##_len - 1] = item) \
)
/**
@@ -127,41 +128,42 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
* item is not a pointer, but actual data value.*/
#define BLI_array_append_r(arr, item) ( \
(void) BLI_array_grow_one(arr), \
- (void) (arr[_##arr##_count - 1] = item), \
- (&arr[_##arr##_count - 1]) \
+ (void) (arr[_##arr##_len - 1] = item), \
+ (&arr[_##arr##_len - 1]) \
)
/** appends (grows) & returns a pointer to the uninitialized memory */
#define BLI_array_append_ret(arr) \
- (BLI_array_reserve(arr, 1), &arr[(_##arr##_count++)])
+ (BLI_array_reserve(arr, 1), &arr[(_##arr##_len++)])
-#define BLI_array_free(arr) \
+#define BLI_array_free(arr) { \
if (arr && (char *)arr != _##arr##_static) { \
- BLI_array_fake_user(arr); \
- MEM_freeN(arr); \
- } (void)0
+ BLI_array_fake_user(arr); \
+ MEM_freeN(arr); \
+ } \
+} ((void)0)
#define BLI_array_pop(arr) ( \
- (arr && _##arr##_count) ? \
- arr[--_##arr##_count] : \
+ (arr && _##arr##_len) ? \
+ arr[--_##arr##_len] : \
NULL \
)
/**
- * resets the logical size of an array to zero, but doesn't
+ * Resets the logical size of an array to zero, but doesn't
* free the memory. */
-#define BLI_array_empty(arr) \
- { _##arr##_count = 0; } (void)0
+#define BLI_array_clear(arr) \
+ { _##arr##_len = 0; } ((void)0)
/**
- * set the count of the array, doesn't actually increase the allocated array
+ * Set the length of the array, doesn't actually increase the allocated array
* size. don't use this unless you know what you're doing. */
-#define BLI_array_count_set(arr, count) \
- { _##arr##_count = (count); }(void)0
+#define BLI_array_len_set(arr, len) \
+ { _##arr##_len = (len); } ((void)0)
/** only to prevent unused warnings */
#define BLI_array_fake_user(arr) \
- ((void)_##arr##_count, \
+ ((void)_##arr##_len, \
(void)_##arr##_static)
/** \} */
@@ -190,7 +192,7 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
#define BLI_array_fixedstack_free(arr) \
if (_##arr##_is_static) { \
MEM_freeN(arr); \
- } (void)0
+ } ((void)0)
/** \} */
diff --git a/source/blender/blenlib/BLI_array_utils.h b/source/blender/blenlib/BLI_array_utils.h
index a46c87cec40..9a510bcfc3b 100644
--- a/source/blender/blenlib/BLI_array_utils.h
+++ b/source/blender/blenlib/BLI_array_utils.h
@@ -74,10 +74,18 @@ bool _bli_array_iter_span(
bool use_wrap, bool use_delimit_bounds,
bool (*test_fn)(const void *arr_item, void *user_data), void *user_data,
unsigned int span_step[2], unsigned int *r_span_len);
-#define BLI_array_iter_span(arr, arr_len, use_wrap, use_delimit_bounds, test_fn, user_data, \
- span_step, r_span_len) \
+#define BLI_array_iter_span( \
+ arr, arr_len, use_wrap, use_delimit_bounds, test_fn, user_data, \
+ span_step, r_span_len) \
_bli_array_iter_span( \
arr, arr_len, sizeof(*(arr)), use_wrap, use_delimit_bounds, test_fn, user_data, \
span_step, r_span_len)
+bool _bli_array_is_zeroed(
+ const void *arr,
+ unsigned int arr_len, size_t arr_stride);
+#define BLI_array_is_zeroed(arr, arr_len) \
+ _bli_array_is_zeroed( \
+ arr, arr_len, sizeof(*(arr)))
+
#endif /* __BLI_ARRAY_UTILS_H__ */
diff --git a/source/blender/blenlib/BLI_assert.h b/source/blender/blenlib/BLI_assert.h
new file mode 100644
index 00000000000..b66b95b21fe
--- /dev/null
+++ b/source/blender/blenlib/BLI_assert.h
@@ -0,0 +1,106 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_ASSERT_H__
+#define __BLI_ASSERT_H__
+
+/** \file BLI_assert.h
+ * \ingroup bli
+ *
+ * Defines:
+ * - #BLI_assert
+ * - #BLI_STATIC_ASSERT
+ * - #BLI_STATIC_ASSERT_ALIGN
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef NDEBUG /* for BLI_assert */
+#include <stdio.h>
+#endif
+
+/* BLI_assert(), default only to print
+ * for aborting need to define WITH_ASSERT_ABORT
+ */
+/* For 'abort' only. */
+#include <stdlib.h>
+
+#ifndef NDEBUG
+# include "BLI_system.h"
+ /* _BLI_ASSERT_PRINT_POS */
+# if defined(__GNUC__)
+# define _BLI_ASSERT_PRINT_POS(a) \
+ fprintf(stderr, "BLI_assert failed: %s:%d, %s(), at \'%s\'\n", __FILE__, __LINE__, __func__, #a)
+# elif defined(_MSC_VER)
+# define _BLI_ASSERT_PRINT_POS(a) \
+ fprintf(stderr, "BLI_assert failed: %s:%d, %s(), at \'%s\'\n", __FILE__, __LINE__, __FUNCTION__, #a)
+# else
+# define _BLI_ASSERT_PRINT_POS(a) \
+ fprintf(stderr, "BLI_assert failed: %s:%d, at \'%s\'\n", __FILE__, __LINE__, #a)
+# endif
+ /* _BLI_ASSERT_ABORT */
+# ifdef WITH_ASSERT_ABORT
+# define _BLI_ASSERT_ABORT abort
+# else
+# define _BLI_ASSERT_ABORT() (void)0
+# endif
+ /* BLI_assert */
+# define BLI_assert(a) \
+ (void)((!(a)) ? ((BLI_system_backtrace(stderr), _BLI_ASSERT_PRINT_POS(a), _BLI_ASSERT_ABORT(), NULL)) : NULL)
+#else
+# define BLI_assert(a) ((void)0)
+#endif
+
+/* C++ can't use _Static_assert, expects static_assert() but c++0x only,
+ * Coverity also errors out. */
+#if (!defined(__cplusplus)) && \
+ (!defined(__COVERITY__)) && \
+ (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406)) /* gcc4.6+ only */
+# define BLI_STATIC_ASSERT(a, msg) __extension__ _Static_assert(a, msg);
+#else
+/* Code adapted from http://www.pixelbeat.org/programming/gcc/static_assert.html */
+/* Note we need the two concats below because arguments to ## are not expanded, so we need to
+ * expand __LINE__ with one indirection before doing the actual concatenation. */
+# define _BLI_ASSERT_CONCAT_(a, b) a##b
+# define _BLI_ASSERT_CONCAT(a, b) _BLI_ASSERT_CONCAT_(a, b)
+ /* These can't be used after statements in c89. */
+# if defined(__COUNTER__) /* MSVC */
+# define BLI_STATIC_ASSERT(a, msg) \
+ ; enum { _BLI_ASSERT_CONCAT(static_assert_, __COUNTER__) = 1 / (int)(!!(a)) };
+# else /* older gcc, clang... */
+ /* This can't be used twice on the same line so ensure if using in headers
+ * that the headers are not included twice (by wrapping in #ifndef...#endif)
+ * Note it doesn't cause an issue when used on same line of separate modules
+ * compiled with gcc -combine -fwhole-program. */
+# define BLI_STATIC_ASSERT(a, msg) \
+ ; enum { _BLI_ASSERT_CONCAT(assert_line_, __LINE__) = 1 / (int)(!!(a)) };
+# endif
+#endif
+
+#define BLI_STATIC_ASSERT_ALIGN(st, align) \
+ BLI_STATIC_ASSERT((sizeof(st) % (align) == 0), "Structure must be strictly aligned")
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BLI_ASSERT_H__ */
diff --git a/source/blender/blenlib/BLI_bitmap_draw_2d.h b/source/blender/blenlib/BLI_bitmap_draw_2d.h
index fe890e94f1b..7036196425a 100644
--- a/source/blender/blenlib/BLI_bitmap_draw_2d.h
+++ b/source/blender/blenlib/BLI_bitmap_draw_2d.h
@@ -27,11 +27,15 @@
void BLI_bitmap_draw_2d_line_v2v2i(
const int p1[2], const int p2[2],
- bool (*callback)(int, int, void *), void *userData);
+ bool (*callback)(int, int, void *), void *user_data);
+
+void BLI_bitmap_draw_2d_tri_v2i(
+ const int p1[2], const int p2[2], const int p3[2],
+ void (*callback)(int x, int x_end, int y, void *), void *user_data);
void BLI_bitmap_draw_2d_poly_v2i_n(
const int xmin, const int ymin, const int xmax, const int ymax,
- const int polyXY[][2], const int polyCorners,
- void (*callback)(int x, int x_end, int y, void *), void *userData);
+ const int verts[][2], const int verts_len,
+ void (*callback)(int x, int x_end, int y, void *), void *user_data);
#endif /* __BLI_BITMAP_DRAW_2D_H__ */
diff --git a/source/blender/blenlib/BLI_boxpack2d.h b/source/blender/blenlib/BLI_boxpack_2d.h
index b02e3423f88..80e89bdb04f 100644
--- a/source/blender/blenlib/BLI_boxpack2d.h
+++ b/source/blender/blenlib/BLI_boxpack_2d.h
@@ -25,10 +25,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_BOXPACK2D_H__
-#define __BLI_BOXPACK2D_H__
+#ifndef __BLI_BOXPACK_2D_H__
+#define __BLI_BOXPACK_2D_H__
-/** \file BLI_boxpack2d.h
+/** \file BLI_boxpack_2d.h
* \ingroup bli
*/
@@ -39,7 +39,7 @@ typedef struct BoxPack {
float y;
float w;
float h;
-
+
/* Verts this box uses
* (BL,TR,TL,BR) / 0,1,2,3 */
struct BoxVert *v[4];
@@ -49,5 +49,5 @@ typedef struct BoxPack {
void BLI_box_pack_2d(BoxPack *boxarray, const unsigned int len, float *tot_width, float *tot_height);
-#endif
+#endif /* __BLI_BOXPACK_2D_H__ */
diff --git a/source/blender/blenlib/BLI_buffer.h b/source/blender/blenlib/BLI_buffer.h
index 0c0845daf19..0d2ef0dc9b3 100644
--- a/source/blender/blenlib/BLI_buffer.h
+++ b/source/blender/blenlib/BLI_buffer.h
@@ -77,7 +77,7 @@ enum {
(BLI_buffer_at(buffer_, type_, (buffer_)->count - 1) = val_) \
)
-#define BLI_buffer_empty(buffer_) { \
+#define BLI_buffer_clear(buffer_) { \
(buffer_)->count = 0; \
} (void)0
diff --git a/source/blender/blenlib/BLI_compiler_attrs.h b/source/blender/blenlib/BLI_compiler_attrs.h
index f0d32670229..2b6baa0d67b 100644
--- a/source/blender/blenlib/BLI_compiler_attrs.h
+++ b/source/blender/blenlib/BLI_compiler_attrs.h
@@ -92,4 +92,18 @@
# define ATTR_PRINTF_FORMAT(format_param, dots_param)
#endif
+/* Use to suppress '-Wimplicit-fallthrough' (in place of 'break'). */
+#if defined(__GNUC__) && (__GNUC__ >= 7) /* gcc7.0+ only */
+# define ATTR_FALLTHROUGH __attribute__((fallthrough))
+#else
+# define ATTR_FALLTHROUGH ((void)0)
+#endif
+
+/* Declare the memory alignment in Bytes. */
+#if defined(_WIN32) && !defined(FREE_WINDOWS)
+# define ATTR_ALIGN(x) __declspec(align(x))
+#else
+# define ATTR_ALIGN(x) __attribute__((aligned(x)))
+#endif
+
#endif /* __BLI_COMPILER_ATTRS_H__ */
diff --git a/source/blender/blenlib/BLI_compiler_compat.h b/source/blender/blenlib/BLI_compiler_compat.h
index 8edbc25bcbc..0726e3bb343 100644
--- a/source/blender/blenlib/BLI_compiler_compat.h
+++ b/source/blender/blenlib/BLI_compiler_compat.h
@@ -32,11 +32,6 @@
# define alloca _alloca
#endif
-/* alloca is defined here for MinGW32 */
-#ifdef __MINGW32__
-# include <malloc.h>
-#endif
-
#if defined(__cplusplus) && ((__cplusplus >= 201103L) || defined(_MSC_VER))
# define HAS_CPP11_FEATURES
#endif
@@ -53,12 +48,7 @@ extern "C++" {
#if defined(_MSC_VER)
# define BLI_INLINE static __forceinline
#else
-# if (defined(__APPLE__) && defined(__ppc__))
-/* static inline __attribute__ here breaks osx ppc gcc42 build */
-# define BLI_INLINE static __attribute__((always_inline)) __attribute__((__unused__))
-# else
-# define BLI_INLINE static inline __attribute__((always_inline)) __attribute__((__unused__))
-# endif
+# define BLI_INLINE static inline __attribute__((always_inline)) __attribute__((__unused__))
#endif
#endif /* __BLI_COMPILER_COMPAT_H__ */
diff --git a/source/blender/blenlib/BLI_console.h b/source/blender/blenlib/BLI_console.h
new file mode 100644
index 00000000000..bf433f78f70
--- /dev/null
+++ b/source/blender/blenlib/BLI_console.h
@@ -0,0 +1,42 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Srrgey Sharybin.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_CONSOLE_H__
+#define __BLI_CONSOLE_H__
+
+/** \file BLI_console.h
+ * \ingroup bli
+ * \brief Set of utility functions and constants to work with consoles.
+ */
+
+/* Format string where one could BLI_snprintf() R, G and B values
+ * and get proper marker to start colored output in the console.
+ */
+#define TRUECOLOR_ANSI_COLOR_FORMAT "\x1b[38;2;%d;%d;%dm"
+
+/* Marker which indicates that colored output is finished. */
+#define TRUECOLOR_ANSI_COLOR_FINISH "\x1b[0m"
+
+#endif /* __BLI_CONSOLE_H__ */
diff --git a/source/blender/blenlib/BLI_convexhull2d.h b/source/blender/blenlib/BLI_convexhull_2d.h
index 4b82071ede8..000d28acdde 100644
--- a/source/blender/blenlib/BLI_convexhull2d.h
+++ b/source/blender/blenlib/BLI_convexhull_2d.h
@@ -18,10 +18,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_CONVEXHULL2D_H__
-#define __BLI_CONVEXHULL2D_H__
+#ifndef __BLI_CONVEXHULL_2D_H__
+#define __BLI_CONVEXHULL_2D_H__
-/** \file BLI_convexhull2d.h
+/** \file BLI_convexhull_2d.h
* \ingroup bli
*/
@@ -31,4 +31,4 @@ int BLI_convexhull_2d(const float (*points)[2], const int n, int r_points[]);
float BLI_convexhull_aabb_fit_hull_2d(const float (*points_hull)[2], unsigned int n);
float BLI_convexhull_aabb_fit_points_2d(const float (*points)[2], unsigned int n);
-#endif /* __BLI_CONVEXHULL2D_H__ */
+#endif /* __BLI_CONVEXHULL_2D_H__ */
diff --git a/source/blender/blenlib/BLI_dial.h b/source/blender/blenlib/BLI_dial_2d.h
index ad7680fe03e..dbd71a8ad3f 100644
--- a/source/blender/blenlib/BLI_dial.h
+++ b/source/blender/blenlib/BLI_dial_2d.h
@@ -18,10 +18,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_DIAL_H__
-#define __BLI_DIAL_H__
+#ifndef __BLI_DIAL_2D_H__
+#define __BLI_DIAL_2D_H__
-/** \file BLI_dial.h
+/** \file BLI_dial_2d.h
* \ingroup bli
*
* \note dials act similar to old rotation based phones and output an angle.
@@ -52,8 +52,8 @@
typedef struct Dial Dial;
-Dial *BLI_dial_initialize(float start_position[2], float threshold);
+Dial *BLI_dial_initialize(const float start_position[2], float threshold);
-float BLI_dial_angle(Dial *dial, float current_position[2]);
+float BLI_dial_angle(Dial *dial, const float current_position[2]);
-#endif /* __BLI_DIAL_H__ */
+#endif /* __BLI_DIAL_2D_H__ */
diff --git a/source/blender/blenlib/BLI_dynstr.h b/source/blender/blenlib/BLI_dynstr.h
index 7aa1c30e449..b26accc7f78 100644
--- a/source/blender/blenlib/BLI_dynstr.h
+++ b/source/blender/blenlib/BLI_dynstr.h
@@ -43,11 +43,14 @@
#include "BLI_compiler_attrs.h"
struct DynStr;
+struct MemArena;
/** The abstract DynStr type */
typedef struct DynStr DynStr;
DynStr *BLI_dynstr_new(void) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+DynStr *BLI_dynstr_new_memarena(void) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+
void BLI_dynstr_append(DynStr *__restrict ds, const char *cstr) ATTR_NONNULL();
void BLI_dynstr_nappend(DynStr *__restrict ds, const char *cstr, int len) ATTR_NONNULL();
@@ -56,8 +59,9 @@ void BLI_dynstr_vappendf(DynStr *__restrict ds, const char *__restrict format
int BLI_dynstr_get_len(DynStr *ds) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
char *BLI_dynstr_get_cstring(DynStr *ds) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-
void BLI_dynstr_get_cstring_ex(DynStr *__restrict ds, char *__restrict str) ATTR_NONNULL();
+
+void BLI_dynstr_clear(DynStr *ds) ATTR_NONNULL();
void BLI_dynstr_free(DynStr *ds) ATTR_NONNULL();
#endif /* __BLI_DYNSTR_H__ */
diff --git a/source/blender/blenlib/BLI_edgehash.h b/source/blender/blenlib/BLI_edgehash.h
index 20272dd97cd..41789201265 100644
--- a/source/blender/blenlib/BLI_edgehash.h
+++ b/source/blender/blenlib/BLI_edgehash.h
@@ -59,7 +59,7 @@ bool BLI_edgehash_remove(EdgeHash *eh, unsigned int v0, unsigned int
void *BLI_edgehash_popkey(EdgeHash *eh, unsigned int v0, unsigned int v1) ATTR_WARN_UNUSED_RESULT;
bool BLI_edgehash_haskey(EdgeHash *eh, unsigned int v0, unsigned int v1) ATTR_WARN_UNUSED_RESULT;
-int BLI_edgehash_size(EdgeHash *eh) ATTR_WARN_UNUSED_RESULT;
+int BLI_edgehash_len(EdgeHash *eh) ATTR_WARN_UNUSED_RESULT;
void BLI_edgehash_clear_ex(EdgeHash *eh, EdgeHashFreeFP valfreefp,
const unsigned int nentries_reserve);
void BLI_edgehash_clear(EdgeHash *eh, EdgeHashFreeFP valfreefp);
@@ -104,7 +104,7 @@ typedef struct EdgeSetIterator EdgeSetIterator;
EdgeSet *BLI_edgeset_new_ex(const char *info,
const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
EdgeSet *BLI_edgeset_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-int BLI_edgeset_size(EdgeSet *es) ATTR_WARN_UNUSED_RESULT;
+int BLI_edgeset_len(EdgeSet *es) ATTR_WARN_UNUSED_RESULT;
bool BLI_edgeset_add(EdgeSet *es, unsigned int v0, unsigned int v1);
void BLI_edgeset_insert(EdgeSet *es, unsigned int v0, unsigned int v1);
bool BLI_edgeset_haskey(EdgeSet *eh, unsigned int v0, unsigned int v1) ATTR_WARN_UNUSED_RESULT;
diff --git a/source/blender/blenlib/BLI_fileops.h b/source/blender/blenlib/BLI_fileops.h
index 91d139c7085..bb23c63bdb3 100644
--- a/source/blender/blenlib/BLI_fileops.h
+++ b/source/blender/blenlib/BLI_fileops.h
@@ -35,6 +35,7 @@
#include <stdio.h>
#include <sys/stat.h>
+#include <stdint.h>
#ifdef __cplusplus
extern "C" {
@@ -65,10 +66,8 @@ int BLI_create_symlink(const char *path, const char *to) ATTR_NONNULL();
/* keep in sync with the definition of struct direntry in BLI_fileops_types.h */
#ifdef WIN32
-# if defined(_MSC_VER) || defined(__MINGW64__)
+# if defined(_MSC_VER)
typedef struct _stat64 BLI_stat_t;
-# elif defined(__MINGW32__)
-typedef struct _stati64 BLI_stat_t;
# else
typedef struct _stat BLI_stat_t;
# endif
diff --git a/source/blender/blenlib/BLI_fileops_types.h b/source/blender/blenlib/BLI_fileops_types.h
index 0cf8c8ddb4a..0ffa3276f1f 100644
--- a/source/blender/blenlib/BLI_fileops_types.h
+++ b/source/blender/blenlib/BLI_fileops_types.h
@@ -35,7 +35,7 @@
#include <sys/stat.h>
-#if defined(WIN32) && !defined(FREE_WINDOWS)
+#if defined(WIN32)
typedef unsigned int mode_t;
#endif
@@ -50,10 +50,8 @@ struct direntry {
const char *relname;
const char *path;
#ifdef WIN32 /* keep in sync with the definition of BLI_stat_t in BLI_fileops.h */
-# if defined(_MSC_VER) || defined(__MINGW64__)
+# if defined(_MSC_VER)
struct _stat64 s;
-# elif defined(__MINGW32__)
- struct _stati64 s;
# else
struct _stat s;
# endif
diff --git a/source/blender/blenlib/BLI_fnmatch.h b/source/blender/blenlib/BLI_fnmatch.h
index f69f5b39869..06fa5048622 100644
--- a/source/blender/blenlib/BLI_fnmatch.h
+++ b/source/blender/blenlib/BLI_fnmatch.h
@@ -28,7 +28,7 @@
extern "C" {
#endif
-#if defined WIN32 && !defined _LIBC || defined __sun
+#if defined WIN32 && !defined _LIBC
#if defined(__cplusplus) || (defined(__STDC__) && __STDC__)
#undef __P
@@ -53,7 +53,7 @@ extern "C" {
#define FNM_NOESCAPE (1 << 1) /* Backslashes don't quote special chars. */
#define FNM_PERIOD (1 << 2) /* Leading `.' is matched only explicitly. */
-#if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 2 || defined(_GNU_SOURCE) || defined(__SUNPRO_C)
+#if !defined(_POSIX_C_SOURCE) || _POSIX_C_SOURCE < 2 || defined(_GNU_SOURCE)
#define FNM_FILE_NAME FNM_PATHNAME /* Preferred GNU name. */
#define FNM_LEADING_DIR (1 << 3) /* Ignore `/...' after a match. */
#define FNM_CASEFOLD (1 << 4) /* Compare without regard to case. */
@@ -72,7 +72,7 @@ extern int fnmatch __P((const char *__pattern, const char *__string,
# define _GNU_SOURCE
# endif
# include <fnmatch.h>
-#endif /* defined WIN32 && !defined _LIBC || defined __sun */
+#endif /* defined WIN32 && !defined _LIBC */
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_ghash.h b/source/blender/blenlib/BLI_ghash.h
index 7e3a009ede8..7003eb039dd 100644
--- a/source/blender/blenlib/BLI_ghash.h
+++ b/source/blender/blenlib/BLI_ghash.h
@@ -20,16 +20,18 @@
*
* The Original Code is: all of this file.
*
- * Contributor(s): none yet.
- *
* ***** END GPL LICENSE BLOCK *****
*/
-
+
#ifndef __BLI_GHASH_H__
#define __BLI_GHASH_H__
/** \file BLI_ghash.h
* \ingroup bli
+ *
+ * GHash is a hash-map implementation (unordered key, value pairs).
+ *
+ * This is also used to implement a 'set' (see #GSet below).
*/
#include "BLI_sys_types.h" /* for bool */
@@ -43,7 +45,7 @@ extern "C" {
#ifndef GHASH_INTERNAL_API
# ifdef __GNUC__
# undef _GHASH_INTERNAL_ATTR
-# define _GHASH_INTERNAL_ATTR __attribute__ ((deprecated))
+# define _GHASH_INTERNAL_ATTR __attribute__ ((deprecated)) /* not deprecated, just private. */
# endif
#endif
@@ -79,34 +81,46 @@ enum {
#endif
};
-/* *** */
+/** \name GHash API
+ *
+ * Defined in ``BLI_ghash.c``
+ * \{ */
-GHash *BLI_ghash_new_ex(GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_new(GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_copy(GHash *gh, GHashKeyCopyFP keycopyfp,
- GHashValCopyFP valcopyfp) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_new_ex(
+ GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_new(
+ GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_copy(
+ GHash *gh, GHashKeyCopyFP keycopyfp,
+ GHashValCopyFP valcopyfp) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp);
void BLI_ghash_reserve(GHash *gh, const unsigned int nentries_reserve);
void BLI_ghash_insert(GHash *gh, void *key, void *val);
bool BLI_ghash_reinsert(GHash *gh, void *key, void *val, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp);
+void *BLI_ghash_replace_key(GHash *gh, void *key);
void *BLI_ghash_lookup(GHash *gh, const void *key) ATTR_WARN_UNUSED_RESULT;
void *BLI_ghash_lookup_default(GHash *gh, const void *key, void *val_default) ATTR_WARN_UNUSED_RESULT;
void **BLI_ghash_lookup_p(GHash *gh, const void *key) ATTR_WARN_UNUSED_RESULT;
bool BLI_ghash_ensure_p(GHash *gh, void *key, void ***r_val) ATTR_WARN_UNUSED_RESULT;
bool BLI_ghash_ensure_p_ex(GHash *gh, const void *key, void ***r_key, void ***r_val) ATTR_WARN_UNUSED_RESULT;
bool BLI_ghash_remove(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp);
-void BLI_ghash_clear(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp);
-void BLI_ghash_clear_ex(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp,
- const unsigned int nentries_reserve);
+void BLI_ghash_clear(
+ GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp);
+void BLI_ghash_clear_ex(
+ GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp,
+ const unsigned int nentries_reserve);
void *BLI_ghash_popkey(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp) ATTR_WARN_UNUSED_RESULT;
bool BLI_ghash_haskey(GHash *gh, const void *key) ATTR_WARN_UNUSED_RESULT;
bool BLI_ghash_pop(GHash *gh, GHashIterState *state, void **r_key, void **r_val) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-unsigned int BLI_ghash_size(GHash *gh) ATTR_WARN_UNUSED_RESULT;
+unsigned int BLI_ghash_len(GHash *gh) ATTR_WARN_UNUSED_RESULT;
void BLI_ghash_flag_set(GHash *gh, unsigned int flag);
void BLI_ghash_flag_clear(GHash *gh, unsigned int flag);
-/* *** */
+/** \} */
+
+/** \name GHash Iterator
+ * \{ */
GHashIterator *BLI_ghashIterator_new(GHash *gh) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
@@ -141,80 +155,15 @@ BLI_INLINE bool BLI_ghashIterator_done(GHashIterator *ghi) { return !ghi
BLI_ghashIterator_done(&gh_iter_) == false; \
BLI_ghashIterator_step(&gh_iter_), i_++)
-/** \name Callbacks for GHash
- *
- * \note '_p' suffix denotes void pointer arg,
- * so we can have functions that take correctly typed args too.
- * \{ */
-
-unsigned int BLI_ghashutil_ptrhash(const void *key);
-bool BLI_ghashutil_ptrcmp(const void *a, const void *b);
-
-unsigned int BLI_ghashutil_strhash_n(const char *key, size_t n);
-#define BLI_ghashutil_strhash(key) ( \
- CHECK_TYPE_ANY(key, char *, const char *, const char * const), \
- BLI_ghashutil_strhash_p(key))
-unsigned int BLI_ghashutil_strhash_p(const void *key);
-unsigned int BLI_ghashutil_strhash_p_murmur(const void *key);
-bool BLI_ghashutil_strcmp(const void *a, const void *b);
-
-#define BLI_ghashutil_inthash(key) ( \
- CHECK_TYPE_ANY(&(key), int *, const int *), \
- BLI_ghashutil_uinthash((unsigned int)key))
-unsigned int BLI_ghashutil_uinthash(unsigned int key);
-unsigned int BLI_ghashutil_inthash_p(const void *ptr);
-unsigned int BLI_ghashutil_inthash_p_murmur(const void *ptr);
-unsigned int BLI_ghashutil_inthash_p_simple(const void *ptr);
-bool BLI_ghashutil_intcmp(const void *a, const void *b);
-
-
-unsigned int BLI_ghashutil_uinthash_v4(const unsigned int key[4]);
-#define BLI_ghashutil_inthash_v4(key) ( \
- CHECK_TYPE_ANY(key, int *, const int *), \
- BLI_ghashutil_uinthash_v4((const unsigned int *)key))
-#define BLI_ghashutil_inthash_v4_p \
- ((GSetHashFP)BLI_ghashutil_uinthash_v4)
-#define BLI_ghashutil_uinthash_v4_p \
- ((GSetHashFP)BLI_ghashutil_uinthash_v4)
-unsigned int BLI_ghashutil_uinthash_v4_murmur(const unsigned int key[4]);
-#define BLI_ghashutil_inthash_v4_murmur(key) ( \
- CHECK_TYPE_ANY(key, int *, const int *), \
- BLI_ghashutil_uinthash_v4_murmur((const unsigned int *)key))
-#define BLI_ghashutil_inthash_v4_p_murmur \
- ((GSetHashFP)BLI_ghashutil_uinthash_v4_murmur)
-#define BLI_ghashutil_uinthash_v4_p_murmur \
- ((GSetHashFP)BLI_ghashutil_uinthash_v4_murmur)
-bool BLI_ghashutil_uinthash_v4_cmp(const void *a, const void *b);
-#define BLI_ghashutil_inthash_v4_cmp \
- BLI_ghashutil_uinthash_v4_cmp
-
/** \} */
-GHash *BLI_ghash_ptr_new_ex(const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_ptr_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_str_new_ex(const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_str_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_int_new_ex(const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_int_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_pair_new_ex(const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GHash *BLI_ghash_pair_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-
-typedef struct GHashPair {
- const void *first;
- const void *second;
-} GHashPair;
-
-GHashPair *BLI_ghashutil_pairalloc(const void *first, const void *second);
-unsigned int BLI_ghashutil_pairhash(const void *ptr);
-bool BLI_ghashutil_paircmp(const void *a, const void *b);
-void BLI_ghashutil_pairfree(void *ptr);
-
-
-/* *** */
+/** \name GSet API
+ * A 'set' implementation (unordered collection of unique elements).
+ *
+ * Internally this is a 'GHash' without any keys,
+ * which is why this API's are in the same header & source file.
+ *
+ * \{ */
typedef struct GSet GSet;
@@ -225,20 +174,12 @@ typedef GHashKeyCopyFP GSetKeyCopyFP;
typedef GHashIterState GSetIterState;
-/* so we can cast but compiler sees as different */
-typedef struct GSetIterator {
- GHashIterator _ghi
-#ifdef __GNUC__
- __attribute__ ((deprecated))
-#endif
- ;
-} GSetIterator;
-
-GSet *BLI_gset_new_ex(GSetHashFP hashfp, GSetCmpFP cmpfp, const char *info,
- const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GSet *BLI_gset_new_ex(
+ GSetHashFP hashfp, GSetCmpFP cmpfp, const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
GSet *BLI_gset_new(GSetHashFP hashfp, GSetCmpFP cmpfp, const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
GSet *BLI_gset_copy(GSet *gs, GSetKeyCopyFP keycopyfp) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-unsigned int BLI_gset_size(GSet *gs) ATTR_WARN_UNUSED_RESULT;
+unsigned int BLI_gset_len(GSet *gs) ATTR_WARN_UNUSED_RESULT;
void BLI_gset_flag_set(GSet *gs, unsigned int flag);
void BLI_gset_flag_clear(GSet *gs, unsigned int flag);
void BLI_gset_free(GSet *gs, GSetKeyFreeFP keyfreefp);
@@ -246,6 +187,7 @@ void BLI_gset_insert(GSet *gh, void *key);
bool BLI_gset_add(GSet *gs, void *key);
bool BLI_gset_ensure_p_ex(GSet *gs, const void *key, void ***r_key);
bool BLI_gset_reinsert(GSet *gh, void *key, GSetKeyFreeFP keyfreefp);
+void *BLI_gset_replace_key(GSet *gs, void *key);
bool BLI_gset_haskey(GSet *gs, const void *key) ATTR_WARN_UNUSED_RESULT;
bool BLI_gset_pop(GSet *gs, GSetIterState *state, void **r_key) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool BLI_gset_remove(GSet *gs, const void *key, GSetKeyFreeFP keyfreefp);
@@ -253,14 +195,26 @@ void BLI_gset_clear_ex(GSet *gs, GSetKeyFreeFP keyfreefp,
const unsigned int nentries_reserve);
void BLI_gset_clear(GSet *gs, GSetKeyFreeFP keyfreefp);
-GSet *BLI_gset_ptr_new_ex(const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GSet *BLI_gset_ptr_new(const char *info);
-GSet *BLI_gset_str_new_ex(const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GSet *BLI_gset_str_new(const char *info);
-GSet *BLI_gset_pair_new_ex(const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
-GSet *BLI_gset_pair_new(const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+/* When set's are used for key & value. */
+void *BLI_gset_lookup(GSet *gh, const void *key) ATTR_WARN_UNUSED_RESULT;
+void *BLI_gset_pop_key(GSet *gs, const void *key) ATTR_WARN_UNUSED_RESULT;
+
+/** \} */
+
+/** \name GSet Iterator
+ * \{ */
/* rely on inline api for now */
+
+/* so we can cast but compiler sees as different */
+typedef struct GSetIterator {
+ GHashIterator _ghi
+#ifdef __GNUC__
+ __attribute__ ((deprecated))
+#endif
+ ;
+} GSetIterator;
+
BLI_INLINE GSetIterator *BLI_gsetIterator_new(GSet *gs) { return (GSetIterator *)BLI_ghashIterator_new((GHash *)gs); }
BLI_INLINE void BLI_gsetIterator_init(GSetIterator *gsi, GSet *gs) { BLI_ghashIterator_init((GHashIterator *)gsi, (GHash *)gs); }
BLI_INLINE void BLI_gsetIterator_free(GSetIterator *gsi) { BLI_ghashIterator_free((GHashIterator *)gsi); }
@@ -278,11 +232,15 @@ BLI_INLINE bool BLI_gsetIterator_done(GSetIterator *gsi) { return BLI_ghashItera
BLI_gsetIterator_done(&gs_iter_) == false; \
BLI_gsetIterator_step(&gs_iter_), i_++)
+/** \} */
+
+/** \name GHash/GSet Debugging API's
+ * \{ */
/* For testing, debugging only */
#ifdef GHASH_INTERNAL_API
-int BLI_ghash_buckets_size(GHash *gh);
-int BLI_gset_buckets_size(GSet *gs);
+int BLI_ghash_buckets_len(GHash *gh);
+int BLI_gset_buckets_len(GSet *gs);
double BLI_ghash_calc_quality_ex(
GHash *gh, double *r_load, double *r_variance,
@@ -293,7 +251,137 @@ double BLI_gset_calc_quality_ex(
double BLI_ghash_calc_quality(GHash *gh);
double BLI_gset_calc_quality(GSet *gs);
#endif /* GHASH_INTERNAL_API */
+/** \} */
+
+/** \name GHash/GSet Macros
+ * \{ */
+
+#define GHASH_FOREACH_BEGIN(type, var, what) \
+ do { \
+ GHashIterator gh_iter##var; \
+ GHASH_ITER(gh_iter##var, what) { \
+ type var = (type)(BLI_ghashIterator_getValue(&gh_iter##var)); \
+
+#define GHASH_FOREACH_END() \
+ } \
+ } while(0)
+
+#define GSET_FOREACH_BEGIN(type, var, what) \
+ do { \
+ GSetIterator gh_iter##var; \
+ GSET_ITER(gh_iter##var, what) { \
+ type var = (type)(BLI_gsetIterator_getKey(&gh_iter##var));
+
+#define GSET_FOREACH_END() \
+ } \
+ } while(0)
+
+/** \} */
+
+/** \name GHash/GSet Utils
+ *
+ * Defined in ``BLI_ghash_utils.c``
+ * \{ */
+
+/**
+ * Callbacks for GHash (``BLI_ghashutil_``)
+ *
+ * \note '_p' suffix denotes void pointer arg,
+ * so we can have functions that take correctly typed args too.
+ */
+
+unsigned int BLI_ghashutil_ptrhash(const void *key);
+bool BLI_ghashutil_ptrcmp(const void *a, const void *b);
+
+unsigned int BLI_ghashutil_strhash_n(const char *key, size_t n);
+#define BLI_ghashutil_strhash(key) ( \
+ CHECK_TYPE_ANY(key, char *, const char *, const char * const), \
+ BLI_ghashutil_strhash_p(key))
+unsigned int BLI_ghashutil_strhash_p(const void *key);
+unsigned int BLI_ghashutil_strhash_p_murmur(const void *key);
+bool BLI_ghashutil_strcmp(const void *a, const void *b);
+
+#define BLI_ghashutil_inthash(key) ( \
+ CHECK_TYPE_ANY(&(key), int *, const int *), \
+ BLI_ghashutil_uinthash((unsigned int)key))
+unsigned int BLI_ghashutil_uinthash(unsigned int key);
+unsigned int BLI_ghashutil_inthash_p(const void *ptr);
+unsigned int BLI_ghashutil_inthash_p_murmur(const void *ptr);
+unsigned int BLI_ghashutil_inthash_p_simple(const void *ptr);
+bool BLI_ghashutil_intcmp(const void *a, const void *b);
+
+size_t BLI_ghashutil_combine_hash(size_t hash_a, size_t hash_b);
+
+
+unsigned int BLI_ghashutil_uinthash_v4(const unsigned int key[4]);
+#define BLI_ghashutil_inthash_v4(key) ( \
+ CHECK_TYPE_ANY(key, int *, const int *), \
+ BLI_ghashutil_uinthash_v4((const unsigned int *)key))
+#define BLI_ghashutil_inthash_v4_p \
+ ((GSetHashFP)BLI_ghashutil_uinthash_v4)
+#define BLI_ghashutil_uinthash_v4_p \
+ ((GSetHashFP)BLI_ghashutil_uinthash_v4)
+unsigned int BLI_ghashutil_uinthash_v4_murmur(const unsigned int key[4]);
+#define BLI_ghashutil_inthash_v4_murmur(key) ( \
+ CHECK_TYPE_ANY(key, int *, const int *), \
+ BLI_ghashutil_uinthash_v4_murmur((const unsigned int *)key))
+#define BLI_ghashutil_inthash_v4_p_murmur \
+ ((GSetHashFP)BLI_ghashutil_uinthash_v4_murmur)
+#define BLI_ghashutil_uinthash_v4_p_murmur \
+ ((GSetHashFP)BLI_ghashutil_uinthash_v4_murmur)
+bool BLI_ghashutil_uinthash_v4_cmp(const void *a, const void *b);
+#define BLI_ghashutil_inthash_v4_cmp \
+ BLI_ghashutil_uinthash_v4_cmp
+typedef struct GHashPair {
+ const void *first;
+ const void *second;
+} GHashPair;
+
+GHashPair *BLI_ghashutil_pairalloc(const void *first, const void *second);
+unsigned int BLI_ghashutil_pairhash(const void *ptr);
+bool BLI_ghashutil_paircmp(const void *a, const void *b);
+void BLI_ghashutil_pairfree(void *ptr);
+
+/**
+ * Wrapper GHash Creation Functions
+ */
+
+GHash *BLI_ghash_ptr_new_ex(
+ const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_ptr_new(
+ const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_str_new_ex(
+ const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_str_new(
+ const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_int_new_ex(
+ const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_int_new(
+ const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_pair_new_ex(
+ const char *info,
+ const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GHash *BLI_ghash_pair_new(
+ const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+
+GSet *BLI_gset_ptr_new_ex(
+ const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GSet *BLI_gset_ptr_new(
+ const char *info);
+GSet *BLI_gset_str_new_ex(
+ const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GSet *BLI_gset_str_new(
+ const char *info);
+GSet *BLI_gset_pair_new_ex(
+ const char *info, const unsigned int nentries_reserve) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+GSet *BLI_gset_pair_new(
+ const char *info) ATTR_MALLOC ATTR_WARN_UNUSED_RESULT;
+
+/** \} */
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_gsqueue.h b/source/blender/blenlib/BLI_gsqueue.h
index 4600d6f6325..ef0e0f3ab31 100644
--- a/source/blender/blenlib/BLI_gsqueue.h
+++ b/source/blender/blenlib/BLI_gsqueue.h
@@ -36,11 +36,11 @@ typedef struct _GSQueue GSQueue;
GSQueue *BLI_gsqueue_new(size_t elem_size);
bool BLI_gsqueue_is_empty(GSQueue *gq);
-int BLI_gsqueue_size(GSQueue *gq);
+int BLI_gsqueue_len(GSQueue *gq);
void BLI_gsqueue_peek(GSQueue *gq, void *r_item);
void BLI_gsqueue_pop(GSQueue *gq, void *r_item);
void BLI_gsqueue_push(GSQueue *gq, const void *item);
-void BLI_gsqueue_pushback(GSQueue *gq, const void *item);
+void BLI_gsqueue_push_back(GSQueue *gq, const void *item);
void BLI_gsqueue_free(GSQueue *gq);
#endif /* __BLI_GSQUEUE_H__ */
diff --git a/source/blender/blenlib/BLI_hash.h b/source/blender/blenlib/BLI_hash.h
new file mode 100644
index 00000000000..f74010479a9
--- /dev/null
+++ b/source/blender/blenlib/BLI_hash.h
@@ -0,0 +1,83 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_HASH_H__
+#define __BLI_HASH_H__
+
+/** \file BLI_hash.h
+ * \ingroup bli
+ */
+
+BLI_INLINE unsigned int BLI_hash_int_2d(unsigned int kx, unsigned int ky)
+{
+#define rot(x, k) (((x) << (k)) | ((x) >> (32 - (k))))
+
+ unsigned int a, b, c;
+
+ a = b = c = 0xdeadbeef + (2 << 2) + 13;
+ a += kx;
+ b += ky;
+
+ c ^= b; c -= rot(b, 14);
+ a ^= c; a -= rot(c, 11);
+ b ^= a; b -= rot(a, 25);
+ c ^= b; c -= rot(b, 16);
+ a ^= c; a -= rot(c, 4);
+ b ^= a; b -= rot(a, 14);
+ c ^= b; c -= rot(b, 24);
+
+ return c;
+
+#undef rot
+}
+
+BLI_INLINE unsigned int BLI_hash_string(const char *str)
+{
+ unsigned int i = 0, c;
+
+ while ((c = *str++)) {
+ i = i * 37 + c;
+ }
+ return i;
+}
+
+BLI_INLINE unsigned int BLI_hash_int(unsigned int k)
+{
+ return BLI_hash_int_2d(k, 0);
+}
+
+BLI_INLINE float BLI_hash_int_01(unsigned int k)
+{
+ return (float)BLI_hash_int(k) * (1.0f / (float)0xFFFFFFFF);
+}
+
+BLI_INLINE void BLI_hash_pointer_to_color(const void *ptr, int *r, int *g, int *b)
+{
+ size_t val = (size_t)ptr;
+ const size_t hash_a = BLI_hash_int(val & 0x0000ffff);
+ const size_t hash_b = BLI_hash_int((uint)((val & 0xffff0000) >> 32));
+ const size_t hash =
+ hash_a ^ (hash_b + 0x9e3779b9 + (hash_a << 6) + (hash_a >> 2));
+ *r = (hash & 0xff0000) >> 16;
+ *g = (hash & 0x00ff00) >> 8;
+ *b = hash & 0x0000ff;
+}
+
+#endif // __BLI_HASH_H__
diff --git a/source/blender/blenlib/BLI_heap.h b/source/blender/blenlib/BLI_heap.h
index ea361097b7b..19e162d777f 100644
--- a/source/blender/blenlib/BLI_heap.h
+++ b/source/blender/blenlib/BLI_heap.h
@@ -23,7 +23,7 @@
/** \file BLI_heap.h
* \ingroup bli
- * \brief A heap / priority queue ADT
+ * \brief A min-heap / priority queue ADT
*/
struct Heap;
@@ -33,34 +33,24 @@ typedef struct HeapNode HeapNode;
typedef void (*HeapFreeFP)(void *ptr);
-/* Creates a new heap. BLI_memarena is used for allocating nodes. Removed nodes
- * are recycled, so memory usage will not shrink. */
Heap *BLI_heap_new_ex(unsigned int tot_reserve) ATTR_WARN_UNUSED_RESULT;
Heap *BLI_heap_new(void) ATTR_WARN_UNUSED_RESULT;
void BLI_heap_clear(Heap *heap, HeapFreeFP ptrfreefp) ATTR_NONNULL(1);
void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp) ATTR_NONNULL(1);
-
-/* Insert heap node with a value (often a 'cost') and pointer into the heap,
- * duplicate values are allowed. */
HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr) ATTR_NONNULL(1);
-
-/* Remove a heap node. */
+void BLI_heap_insert_or_update(Heap *heap, HeapNode **node_p, float value, void *ptr) ATTR_NONNULL(1, 2);
void BLI_heap_remove(Heap *heap, HeapNode *node) ATTR_NONNULL(1, 2);
-
-/* Return 0 if the heap is empty, 1 otherwise. */
-bool BLI_heap_is_empty(Heap *heap) ATTR_NONNULL(1);
-
-/* Return the size of the heap. */
-unsigned int BLI_heap_size(Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-
-/* Return the top node of the heap. This is the node with the lowest value. */
-HeapNode *BLI_heap_top(Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-
-/* Pop the top node off the heap and return it's pointer. */
-void *BLI_heap_popmin(Heap *heap) ATTR_NONNULL(1);
+bool BLI_heap_is_empty(const Heap *heap) ATTR_NONNULL(1);
+unsigned int BLI_heap_len(const Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+HeapNode *BLI_heap_top(const Heap *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_heap_pop_min(Heap *heap) ATTR_NONNULL(1);
+void BLI_heap_node_value_update(Heap *heap, HeapNode *node, float value) ATTR_NONNULL(1, 2);
+void BLI_heap_node_value_update_ptr(Heap *heap, HeapNode *node, float value, void *ptr) ATTR_NONNULL(1, 2);
/* Return the value or pointer of a heap node. */
-float BLI_heap_node_value(HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
-void *BLI_heap_node_ptr(HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+float BLI_heap_node_value(const HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_heap_node_ptr(const HeapNode *heap) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+/* only for gtest */
+bool BLI_heap_is_valid(const Heap *heap);
#endif /* __BLI_HEAP_H__ */
diff --git a/source/blender/blenlib/BLI_jitter.h b/source/blender/blenlib/BLI_jitter_2d.h
index 769fb445678..e2b1f21800c 100644
--- a/source/blender/blenlib/BLI_jitter.h
+++ b/source/blender/blenlib/BLI_jitter_2d.h
@@ -25,10 +25,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_JITTER_H__
-#define __BLI_JITTER_H__
+#ifndef __BLI_JITTER_2D_H__
+#define __BLI_JITTER_2D_H__
-/** \file BLI_jitter.h
+/** \file BLI_jitter_2d.h
* \ingroup bli
*/
@@ -36,5 +36,5 @@ void BLI_jitter_init(float (*jitarr)[2], int num);
void BLI_jitterate1(float (*jit1)[2], float (*jit2)[2], int num, float radius1);
void BLI_jitterate2(float (*jit1)[2], float (*jit2)[2], int num, float radius2);
-#endif
+#endif /* __BLI_JITTER_2D_H__ */
diff --git a/source/blender/blenlib/BLI_kdopbvh.h b/source/blender/blenlib/BLI_kdopbvh.h
index ba565fca522..db53035dc7b 100644
--- a/source/blender/blenlib/BLI_kdopbvh.h
+++ b/source/blender/blenlib/BLI_kdopbvh.h
@@ -36,7 +36,7 @@
*/
#ifdef __cplusplus
-extern "C" {
+extern "C" {
#endif
struct BVHTree;
@@ -62,7 +62,7 @@ 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_sq; /* squared distance to search arround */
+ float dist_sq; /* squared distance to search around */
int flags;
} BVHTreeNearest;
@@ -129,7 +129,7 @@ BVHTreeOverlap *BLI_bvhtree_overlap(
const BVHTree *tree1, const BVHTree *tree2, unsigned int *r_overlap_tot,
BVHTree_OverlapCallback callback, void *userdata);
-int BLI_bvhtree_get_size(const BVHTree *tree);
+int BLI_bvhtree_get_len(const BVHTree *tree);
float BLI_bvhtree_get_epsilon(const BVHTree *tree);
diff --git a/source/blender/blenlib/BLI_kdtree.h b/source/blender/blenlib/BLI_kdtree.h
index aa54e1c823c..18908f8c551 100644
--- a/source/blender/blenlib/BLI_kdtree.h
+++ b/source/blender/blenlib/BLI_kdtree.h
@@ -66,6 +66,10 @@ void BLI_kdtree_range_search_cb(
const KDTree *tree, const float co[3], float range,
bool (*search_cb)(void *user_data, int index, const float co[3], float dist_sq), void *user_data);
+int BLI_kdtree_calc_duplicates_fast(
+ const KDTree *tree, const float range, bool use_index_order,
+ int *doubles);
+
/* Normal use is deprecated */
/* remove __normal functions when last users drop */
int BLI_kdtree_find_nearest_n__normal(
diff --git a/source/blender/blenlib/BLI_lasso.h b/source/blender/blenlib/BLI_lasso_2d.h
index 28f21e5bd85..3644224f1d7 100644
--- a/source/blender/blenlib/BLI_lasso.h
+++ b/source/blender/blenlib/BLI_lasso_2d.h
@@ -25,10 +25,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_LASSO_H__
-#define __BLI_LASSO_H__
+#ifndef __BLI_LASSO_2D_H__
+#define __BLI_LASSO_2D_H__
-/** \file BLI_lasso.h
+/** \file BLI_lasso_2d.h
* \ingroup bli
*/
@@ -38,4 +38,4 @@ void BLI_lasso_boundbox(struct rcti *rect, const int mcords[][2], const unsigned
bool BLI_lasso_is_point_inside(const int mcords[][2], const unsigned int moves, const int sx, const int sy, const int error_value);
bool BLI_lasso_is_edge_inside(const int mcords[][2], const unsigned int moves, int x0, int y0, int x1, int y1, const int error_value);
-#endif
+#endif /* __BLI_LASSO_2D_H__ */
diff --git a/source/blender/blenlib/BLI_linklist.h b/source/blender/blenlib/BLI_linklist.h
index 367f1bb9de5..7eec54e67e1 100644
--- a/source/blender/blenlib/BLI_linklist.h
+++ b/source/blender/blenlib/BLI_linklist.h
@@ -30,9 +30,6 @@
/** \file BLI_linklist.h
* \ingroup bli
- * \brief Routines for working with singly linked lists
- * of 'links' - pointers to other data.
- *
*/
#include "BLI_compiler_attrs.h"
diff --git a/source/blender/blenlib/BLI_linklist_lockfree.h b/source/blender/blenlib/BLI_linklist_lockfree.h
new file mode 100644
index 00000000000..7e7400361e3
--- /dev/null
+++ b/source/blender/blenlib/BLI_linklist_lockfree.h
@@ -0,0 +1,88 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Sergey Sharybin.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_LINKLIST_LOCKFREE_H__
+#define __BLI_LINKLIST_LOCKFREE_H__
+
+/** \file BLI_linklist_lockfree.h
+ * \ingroup bli
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct LockfreeLinkNode {
+ struct LockfreeLinkNode *next;
+ /* NOTE: "Subclass" this structure to add custom-defined data. */
+} LockfreeLinkNode;
+
+typedef struct LockfreeLinkList {
+ /* We keep a dummy node at the beginning of the list all the time.
+ * This allows us to make sure head and tail pointers are always
+ * valid, and saves from annoying exception cases in insert().
+ */
+ LockfreeLinkNode dummy_node;
+ /* NOTE: This fields might point to a dummy node. */
+ LockfreeLinkNode *head, *tail;
+} LockfreeLinkList;
+
+typedef void (*LockfreeeLinkNodeFreeFP)(void *link);
+
+/* ************************************************************************** */
+/* NOTE: These functions are NOT safe for use from threads. */
+/* NOTE: !!! I REPEAT: DO NOT USE THEM WITHOUT EXTERNAL LOCK !!! */
+
+/* Make list ready for lock-free access. */
+void BLI_linklist_lockfree_init(LockfreeLinkList *list);
+
+/* Completely free the whole list, it is NOT re-usable after this. */
+void BLI_linklist_lockfree_free(LockfreeLinkList *list,
+ LockfreeeLinkNodeFreeFP free_func);
+
+/* Remove all the elements from the list, keep it usable for further
+ * inserts.
+ */
+void BLI_linklist_lockfree_clear(LockfreeLinkList *list,
+ LockfreeeLinkNodeFreeFP free_func);
+
+
+/* Begin iteration of lock-free linked list, starting with a
+ * first user=defined node. Will ignore the dummy node.
+ */
+LockfreeLinkNode *BLI_linklist_lockfree_begin(LockfreeLinkList *list);
+
+
+/* ************************************************************************** */
+/* NOTE: These functions are safe for use from threads. */
+
+void BLI_linklist_lockfree_insert(LockfreeLinkList *list,
+ LockfreeLinkNode *node);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BLI_LINKLIST_H__ */
diff --git a/source/blender/blenlib/BLI_linklist_stack.h b/source/blender/blenlib/BLI_linklist_stack.h
index dd92dcec936..dd6d737f111 100644
--- a/source/blender/blenlib/BLI_linklist_stack.h
+++ b/source/blender/blenlib/BLI_linklist_stack.h
@@ -60,7 +60,7 @@
} (void)0
#define BLI_LINKSTACK_SIZE(var) \
- BLI_mempool_count(var##_pool_)
+ BLI_mempool_len(var##_pool_)
/* check for typeof() */
#ifdef __GNUC__
diff --git a/source/blender/blenlib/BLI_listbase.h b/source/blender/blenlib/BLI_listbase.h
index 96349a7b066..c4ad5acfe4b 100644
--- a/source/blender/blenlib/BLI_listbase.h
+++ b/source/blender/blenlib/BLI_listbase.h
@@ -50,12 +50,14 @@ void *BLI_findlink(const struct ListBase *listbase, int number) ATTR_WARN_UNUSED
void *BLI_findstring(const struct ListBase *listbase, const char *id, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void *BLI_findstring_ptr(const struct ListBase *listbase, const char *id, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void *BLI_findptr(const struct ListBase *listbase, const void *ptr, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_listbase_bytes_find(const ListBase *listbase, const void *bytes, const size_t bytes_size, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1, 2);
/* find backwards */
void *BLI_rfindlink(const struct ListBase *listbase, int number) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void *BLI_rfindstring(const struct ListBase *listbase, const char *id, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void *BLI_rfindstring_ptr(const struct ListBase *listbase, const char *id, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void *BLI_rfindptr(const struct ListBase *listbase, const void *ptr, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+void *BLI_listbase_bytes_rfind(const ListBase *listbase, const void *bytes, const size_t bytes_size, const int offset) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1, 2);
void BLI_freelistN(struct ListBase *listbase) ATTR_NONNULL(1);
void BLI_addtail(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1);
@@ -67,15 +69,17 @@ void *BLI_poptail(ListBase *listbase) ATTR_NONNULL(1);
void BLI_addhead(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1);
void BLI_insertlinkbefore(struct ListBase *listbase, void *vnextlink, void *vnewlink) ATTR_NONNULL(1);
void BLI_insertlinkafter(struct ListBase *listbase, void *vprevlink, void *vnewlink) ATTR_NONNULL(1);
+void BLI_insertlinkreplace(ListBase *listbase, void *v_l_src, void *v_l_dst) ATTR_NONNULL(1, 2, 3);
void BLI_listbase_sort(struct ListBase *listbase, int (*cmp)(const void *, const void *)) ATTR_NONNULL(1, 2);
void BLI_listbase_sort_r(ListBase *listbase, int (*cmp)(void *, const void *, const void *), void *thunk) ATTR_NONNULL(1, 2);
bool BLI_listbase_link_move(ListBase *listbase, void *vlink, int step) ATTR_NONNULL();
void BLI_freelist(struct ListBase *listbase) ATTR_NONNULL(1);
-int BLI_listbase_count_ex(const struct ListBase *listbase, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+int BLI_listbase_count_at_most(const struct ListBase *listbase, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
int BLI_listbase_count(const struct ListBase *listbase) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void BLI_freelinkN(struct ListBase *listbase, void *vlink) ATTR_NONNULL(1);
void BLI_listbase_swaplinks(struct ListBase *listbase, void *vlinka, void *vlinkb) ATTR_NONNULL(1, 2);
+void BLI_listbases_swaplinks(struct ListBase *listbasea, struct ListBase *listbaseb, void *vlinka, void *vlinkb) ATTR_NONNULL(2, 3);
void BLI_movelisttolist(struct ListBase *dst, struct ListBase *src) ATTR_NONNULL(1, 2);
void BLI_duplicatelist(struct ListBase *dst, const struct ListBase *src) ATTR_NONNULL(1, 2);
@@ -99,31 +103,37 @@ struct LinkData *BLI_genericNodeN(void *data);
*
* \code{.c}
*
- * BLI_LISTBASE_CIRCULAR_FORWARD_BEGIN (listbase, item, item_init) {
+ * LISTBASE_CIRCULAR_FORWARD_BEGIN(listbase, item, item_init)
+ * {
* ...operate on marker...
* }
- * BLI_LISTBASE_CIRCULAR_FORWARD_END (listbase, item, item_init);
+ * LISTBASE_CIRCULAR_FORWARD_END (listbase, item, item_init);
*
* \endcode
*/
-#define BLI_LISTBASE_CIRCULAR_FORWARD_BEGIN(lb, lb_iter, lb_init) \
+#define LISTBASE_CIRCULAR_FORWARD_BEGIN(lb, lb_iter, lb_init) \
if ((lb)->first && (lb_init || (lb_init = (lb)->first))) { \
lb_iter = lb_init; \
do {
-#define BLI_LISTBASE_CIRCULAR_FORWARD_END(lb, lb_iter, lb_init) \
+#define LISTBASE_CIRCULAR_FORWARD_END(lb, lb_iter, lb_init) \
} while ((lb_iter = (lb_iter)->next ? (lb_iter)->next : (lb)->first), \
(lb_iter != lb_init)); \
}
-#define BLI_LISTBASE_CIRCULAR_BACKWARD_BEGIN(lb, lb_iter, lb_init) \
+#define LISTBASE_CIRCULAR_BACKWARD_BEGIN(lb, lb_iter, lb_init) \
if ((lb)->last && (lb_init || (lb_init = (lb)->last))) { \
lb_iter = lb_init; \
do {
-#define BLI_LISTBASE_CIRCULAR_BACKWARD_END(lb, lb_iter, lb_init) \
+#define LISTBASE_CIRCULAR_BACKWARD_END(lb, lb_iter, lb_init) \
} while ((lb_iter = (lb_iter)->prev ? (lb_iter)->prev : (lb)->last), \
(lb_iter != lb_init)); \
}
+#define LISTBASE_FOREACH(type, var, list) \
+ for (type var = (type)((list)->first); \
+ var != NULL; \
+ var = (type)(((Link*)(var))->next))
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_math_base.h b/source/blender/blenlib/BLI_math_base.h
index 0126e30d900..6f8e48d83b2 100644
--- a/source/blender/blenlib/BLI_math_base.h
+++ b/source/blender/blenlib/BLI_math_base.h
@@ -35,6 +35,7 @@
#endif
#include <math.h>
+#include "BLI_assert.h"
#include "BLI_math_inline.h"
#ifndef M_PI
@@ -129,6 +130,13 @@ MINLINE int max_iii(int a, int b, int c);
MINLINE int min_iiii(int a, int b, int c, int d);
MINLINE int max_iiii(int a, int b, int c, int d);
+MINLINE size_t min_zz(size_t a, size_t b);
+MINLINE size_t max_zz(size_t a, size_t b);
+
+MINLINE int clamp_i(int value, int min, int max);
+MINLINE float clamp_f(float value, float min, float max);
+MINLINE size_t clamp_z(size_t value, size_t min, size_t max);
+
MINLINE int compare_ff(float a, float b, const float max_diff);
MINLINE int compare_ff_relative(float a, float b, const float max_diff, const int max_ulps);
@@ -138,6 +146,10 @@ MINLINE int signum_i(float a);
MINLINE float power_of_2(float f);
+MINLINE int integer_digits_f(const float f);
+MINLINE int integer_digits_d(const double d);
+MINLINE int integer_digits_i(const int i);
+
/* these don't really fit anywhere but were being copied about a lot */
MINLINE int is_power_of_2_i(int n);
MINLINE int power_of_2_max_i(int n);
@@ -146,10 +158,37 @@ MINLINE int power_of_2_min_i(int n);
MINLINE unsigned int power_of_2_max_u(unsigned int x);
MINLINE unsigned int power_of_2_min_u(unsigned int x);
-MINLINE int iroundf(float a);
MINLINE int divide_round_i(int a, int b);
MINLINE int mod_i(int i, int n);
+MINLINE signed char round_fl_to_char(float a);
+MINLINE unsigned char round_fl_to_uchar(float a);
+MINLINE short round_fl_to_short(float a);
+MINLINE unsigned short round_fl_to_ushort(float a);
+MINLINE int round_fl_to_int(float a);
+MINLINE unsigned int round_fl_to_uint(float a);
+
+MINLINE signed char round_db_to_char(double a);
+MINLINE unsigned char round_db_to_uchar(double a);
+MINLINE short round_db_to_short(double a);
+MINLINE unsigned short round_db_to_ushort(double a);
+MINLINE int round_db_to_int(double a);
+MINLINE unsigned int round_db_to_uint(double a);
+
+MINLINE signed char round_fl_to_char_clamp(float a);
+MINLINE unsigned char round_fl_to_uchar_clamp(float a);
+MINLINE short round_fl_to_short_clamp(float a);
+MINLINE unsigned short round_fl_to_ushort_clamp(float a);
+MINLINE int round_fl_to_int_clamp(float a);
+MINLINE unsigned int round_fl_to_uint_clamp(float a);
+
+MINLINE signed char round_db_to_char_clamp(double a);
+MINLINE unsigned char round_db_to_uchar_clamp(double a);
+MINLINE short round_db_to_short_clamp(double a);
+MINLINE unsigned short round_db_to_ushort_clamp(double a);
+MINLINE int round_db_to_int_clamp(double a);
+MINLINE unsigned int round_db_to_uint_clamp(double a);
+
int pow_i(int base, int exp);
double double_round(double x, int ndigits);
diff --git a/source/blender/blenlib/BLI_math_bits.h b/source/blender/blenlib/BLI_math_bits.h
index 1ac98a682d1..86213dc271f 100644
--- a/source/blender/blenlib/BLI_math_bits.h
+++ b/source/blender/blenlib/BLI_math_bits.h
@@ -31,7 +31,24 @@ extern "C" {
#include "BLI_math_inline.h"
-MINLINE unsigned int highest_order_bit_i(unsigned int n);
+/* Search the value from LSB to MSB for a set bit. Returns index of this bit. */
+MINLINE int bitscan_forward_i(int a);
+MINLINE unsigned int bitscan_forward_uint(unsigned int a);
+
+/* Similar to above, but also clears the bit. */
+MINLINE int bitscan_forward_clear_i(int *a);
+MINLINE unsigned int bitscan_forward_clear_uint(unsigned int *a);
+
+/* Search the value from MSB to LSB for a set bit. Returns index of this bit. */
+MINLINE int bitscan_reverse_i(int a);
+MINLINE unsigned int bitscan_reverse_uint(unsigned int a);
+
+/* Similar to above, but also clears the bit. */
+MINLINE int bitscan_reverse_clear_i(int *a);
+MINLINE unsigned int bitscan_reverse_clear_uint(unsigned int *a);
+
+/* NOTE: Those functions returns 2 to the power of index of highest order bit. */
+MINLINE unsigned int highest_order_bit_uint(unsigned int n);
MINLINE unsigned short highest_order_bit_s(unsigned short n);
#ifdef __GNUC__
diff --git a/source/blender/blenlib/BLI_math_color.h b/source/blender/blenlib/BLI_math_color.h
index 5e6b1256d30..72d29164988 100644
--- a/source/blender/blenlib/BLI_math_color.h
+++ b/source/blender/blenlib/BLI_math_color.h
@@ -51,6 +51,10 @@ extern "C" {
#define BLI_YCC_ITU_BT709 1
#define BLI_YCC_JFIF_0_255 2
+/* YUV */
+#define BLI_YUV_ITU_BT601 0
+#define BLI_YUV_ITU_BT709 1
+
/******************* Conversion to RGB ********************/
void hsv_to_rgb(float h, float s, float v, float *r, float *g, float *b);
@@ -58,14 +62,14 @@ void hsv_to_rgb_v(const float hsv[3], float r_rgb[3]);
void hsl_to_rgb(float h, float c, float l, float *r, float *g, float *b);
void hsl_to_rgb_v(const float hcl[3], float r_rgb[3]);
void hex_to_rgb(char *hexcol, float *r, float *g, float *b);
-void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb);
+void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb, int colorspace);
void ycc_to_rgb(float y, float cb, float cr, float *lr, float *lg, float *lb, int colorspace);
void xyz_to_rgb(float x, float y, float z, float *r, float *g, float *b, int colorspace);
void cpack_to_rgb(unsigned int col, float *r, float *g, float *b);
/***************** Conversion from RGB ********************/
-void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv);
+void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv, int colorspace);
void rgb_to_ycc(float r, float g, float b, float *ly, float *lcb, float *lcr, int colorspace);
void rgb_to_hsv(float r, float g, float b, float *lh, float *ls, float *lv);
void rgb_to_hsv_v(const float rgb[3], float r_hsv[3]);
@@ -141,7 +145,11 @@ MINLINE void float_to_byte_dither_v3(unsigned char b[3], const float f[3], float
#define rgba_char_args_set_fl(col, r, g, b, a) \
rgba_char_args_set(col, (r) * 255, (g) * 255, (b) * 255, (a) * 255)
+#define rgba_float_args_set_ch(col, r, g, b, a) \
+ rgba_float_args_set(col, (r) / 255.0f, (g) / 255.0f, (b) / 255.0f, (a) / 255.0f)
+
MINLINE void rgba_char_args_set(char col[4], const char r, const char g, const char b, const char a);
+MINLINE void rgba_float_args_set(float col[4], const float r, const float g, const float b, const float a);
MINLINE void rgba_char_args_test_set(char col[4], const char r, const char g, const char b, const char a);
MINLINE void cpack_cpy_3ub(unsigned char r_col[3], const unsigned int pack);
@@ -160,4 +168,3 @@ void lift_gamma_gain_to_asc_cdl(float *lift, float *gamma, float *gain, float *o
#endif
#endif /* __BLI_MATH_COLOR_H__ */
-
diff --git a/source/blender/blenlib/BLI_math_geom.h b/source/blender/blenlib/BLI_math_geom.h
index f1d9c9571f2..ff80d15ea5d 100644
--- a/source/blender/blenlib/BLI_math_geom.h
+++ b/source/blender/blenlib/BLI_math_geom.h
@@ -85,6 +85,7 @@ bool is_quad_convex_v3(const float v1[3], const float v2[3], const float v3[3],
bool is_quad_convex_v2(const float v1[2], const float v2[2], const float v3[2], const float v4[2]);
bool is_poly_convex_v2(const float verts[][2], unsigned int nr);
int is_quad_flip_v3(const float v1[3], const float v2[3], const float v3[3], const float v4[3]);
+bool is_quad_flip_v3_first_third_fast(const float v0[3], const float v1[3], const float v2[3], const float v3[3]);
/********************************* Distance **********************************/
@@ -119,6 +120,26 @@ float dist_squared_ray_to_seg_v3(
const float ray_origin[3], const float ray_direction[3],
const float v0[3], const float v1[3],
float r_point[3], float *r_depth);
+
+struct DistRayAABB_Precalc {
+ float ray_origin[3];
+ float ray_direction[3];
+ float ray_inv_dir[3];
+ bool sign[3];
+};
+void dist_squared_ray_to_aabb_v3_precalc(
+ struct DistRayAABB_Precalc *neasrest_precalc,
+ const float ray_origin[3], const float ray_direction[3]);
+float dist_squared_ray_to_aabb_v3(
+ const struct DistRayAABB_Precalc *data,
+ const float bb_min[3], const float bb_max[3],
+ float r_point[3], float *r_depth);
+/* when there is no advantage to precalc. */
+float dist_squared_ray_to_aabb_v3_simple(
+ const float ray_origin[3], const float ray_direction[3],
+ const float bb_min[3], const float bb_max[3],
+ float r_point[3], float *r_depth);
+
float closest_to_line_v2(float r_close[2], const float p[2], const float l1[2], const float l2[2]);
float closest_to_line_v3(float r_close[3], const float p[3], const float l1[3], const float l2[3]);
void closest_to_line_segment_v2(float r_close[2], const float p[2], const float l1[2], const float l2[2]);
@@ -166,8 +187,14 @@ void limit_dist_v3(float v1[3], float v2[3], const float dist);
int isect_seg_seg_v2(const float a1[2], const float a2[2], const float b1[2], const float b2[2]);
int isect_seg_seg_v2_int(const int a1[2], const int a2[2], const int b1[2], const int b2[2]);
-int isect_seg_seg_v2_point(const float v0[2], const float v1[2], const float v2[2], const float v3[2], float vi[2]);
-bool isect_seg_seg_v2_simple(const float v1[2], const float v2[2], const float v3[2], const float v4[2]);
+int isect_seg_seg_v2_point_ex(
+ const float v0[2], const float v1[2], const float v2[2], const float v3[2], const float endpoint_bias,
+ float vi[2]);
+int isect_seg_seg_v2_point(
+ const float v0[2], const float v1[2], const float v2[2], const float v3[2],
+ float vi[2]);
+bool isect_seg_seg_v2_simple(
+ const float v1[2], const float v2[2], const float v3[2], const float v4[2]);
int isect_line_sphere_v3(const float l1[3], const float l2[3], const float sp[3], const float r, float r_p1[3], float r_p2[3]);
int isect_line_sphere_v2(const float l1[2], const float l2[2], const float sp[2], const float r, float r_p1[2], float r_p2[2]);
@@ -329,12 +356,18 @@ void transform_point_by_seg_v3(
const float l_dst_p1[3], const float l_dst_p2[3],
const float l_src_p1[3], const float l_src_p2[3]);
-void barycentric_weights_v2(const float v1[2], const float v2[2], const float v3[2],
- const float co[2], float w[3]);
-void barycentric_weights_v2_persp(const float v1[4], const float v2[4], const float v3[4],
- const float co[2], float w[3]);
-void barycentric_weights_v2_quad(const float v1[2], const float v2[2], const float v3[2], const float v4[2],
- const float co[2], float w[4]);
+void barycentric_weights_v2(
+ const float v1[2], const float v2[2], const float v3[2],
+ const float co[2], float w[3]);
+void barycentric_weights_v2_clamped(
+ const float v1[2], const float v2[2], const float v3[2],
+ const float co[2], float w[3]);
+void barycentric_weights_v2_persp(
+ const float v1[4], const float v2[4], const float v3[4],
+ const float co[2], float w[3]);
+void barycentric_weights_v2_quad(
+ const float v1[2], const float v2[2], const float v3[2], const float v4[2],
+ const float co[2], float w[4]);
bool barycentric_coords_v2(const float v1[2], const float v2[2], const float v3[2], const float co[2], float w[3]);
int barycentric_inside_triangle_v2(const float w[3]);
@@ -381,23 +414,23 @@ void map_to_plane_axis_angle_v2_v3v3fl(float r_co[2], const float co[3], const f
/********************************** Normals **********************************/
-void accumulate_vertex_normals_tri(
+void accumulate_vertex_normals_tri_v3(
float n1[3], float n2[3], float n3[3],
const float f_no[3],
const float co1[3], const float co2[3], const float co3[3]);
-void accumulate_vertex_normals(
+void accumulate_vertex_normals_v3(
float n1[3], float n2[3], float n3[3], float n4[3],
const float f_no[3],
const float co1[3], const float co2[3], const float co3[3], const float co4[3]);
-void accumulate_vertex_normals_poly(
+void accumulate_vertex_normals_poly_v3(
float **vertnos, const float polyno[3],
const float **vertcos, float vdiffs[][3], const int nverts);
/********************************* Tangents **********************************/
-void tangent_from_uv(
+void tangent_from_uv_v3(
const float uv1[2], const float uv2[2], const float uv3[2],
const float co1[3], const float co2[3], const float co3[3],
const float n[3],
@@ -405,9 +438,9 @@ void tangent_from_uv(
/******************************** Vector Clouds ******************************/
-void vcloud_estimate_transform(int list_size, float (*pos)[3], float *weight,
- float (*rpos)[3], float *rweight,
- float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3]);
+void vcloud_estimate_transform_v3(
+ const int list_size, const float (*pos)[3], const float *weight, const float (*rpos)[3], const float *rweight,
+ float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3]);
/****************************** Spherical Harmonics *************************/
@@ -438,7 +471,7 @@ float form_factor_hemi_poly(float p[3], float n[3],
float v1[3], float v2[3], float v3[3], float v4[3]);
void axis_dominant_v3_to_m3_negate(float r_mat[3][3], const float normal[3]);
-void axis_dominant_v3_to_m3(float r_mat[3][3], const float normal[3]);
+void axis_dominant_v3_to_m3(float r_mat[3][3], const float normal[3]);
MINLINE void axis_dominant_v3(int *r_axis_a, int *r_axis_b, const float axis[3]);
MINLINE float axis_dominant_v3_max(int *r_axis_a, int *r_axis_b, const float axis[3]) ATTR_WARN_UNUSED_RESULT;
diff --git a/source/blender/blenlib/BLI_math_inline.h b/source/blender/blenlib/BLI_math_inline.h
index 840cf24f8cf..383abda5b2f 100644
--- a/source/blender/blenlib/BLI_math_inline.h
+++ b/source/blender/blenlib/BLI_math_inline.h
@@ -44,12 +44,7 @@ extern "C" {
# define MALWAYS_INLINE MINLINE
# else
# define MINLINE static inline
-# if (defined(__APPLE__) && defined(__ppc__))
- /* static inline __attribute__ here breaks osx ppc gcc42 build */
-# define MALWAYS_INLINE static __attribute__((always_inline)) __attribute__((unused))
-# else
-# define MALWAYS_INLINE static inline __attribute__((always_inline)) __attribute__((unused))
-# endif
+# define MALWAYS_INLINE static inline __attribute__((always_inline)) __attribute__((unused))
# endif
#else
# define MINLINE
diff --git a/source/blender/blenlib/BLI_math_matrix.h b/source/blender/blenlib/BLI_math_matrix.h
index d0dfad2a02f..173ef6861e6 100644
--- a/source/blender/blenlib/BLI_math_matrix.h
+++ b/source/blender/blenlib/BLI_math_matrix.h
@@ -210,6 +210,7 @@ void scale_m4_fl(float R[4][4], float scale);
float mat3_to_scale(float M[3][3]);
float mat4_to_scale(float M[4][4]);
+float mat4_to_xy_scale(float M[4][4]);
void size_to_mat3(float R[3][3], const float size[3]);
void size_to_mat4(float R[4][4], const float size[3]);
diff --git a/source/blender/blenlib/BLI_math_rotation.h b/source/blender/blenlib/BLI_math_rotation.h
index d60be30e10d..1f206e5e234 100644
--- a/source/blender/blenlib/BLI_math_rotation.h
+++ b/source/blender/blenlib/BLI_math_rotation.h
@@ -97,6 +97,11 @@ float angle_normalized_qtqt(const float q1[4], const float q2[4]);
float angle_qt(const float q[4]);
float angle_qtqt(const float q1[4], const float q2[4]);
+float angle_signed_normalized_qt(const float q[4]);
+float angle_signed_normalized_qtqt(const float q1[4], const float q2[4]);
+float angle_signed_qt(const float q[4]);
+float angle_signed_qtqt(const float q1[4], const float q2[4]);
+
/* TODO: don't what this is, but it's not the same as mat3_to_quat */
void mat3_to_quat_is_ok(float q[4], float mat[3][3]);
@@ -218,8 +223,12 @@ float angle_wrap_deg(float angle);
float angle_compat_rad(float angle, float angle_compat);
-int mat3_from_axis_conversion(int from_forward, int from_up, int to_forward, int to_up,
- float r_mat[3][3]);
+bool mat3_from_axis_conversion(
+ int src_forward, int src_up, int dst_forward, int dst_up,
+ float r_mat[3][3]);
+bool mat3_from_axis_conversion_single(
+ int src_axis, int dst_axis,
+ float r_mat[3][3]);
#ifdef __cplusplus
}
diff --git a/source/blender/blenlib/BLI_math_solvers.h b/source/blender/blenlib/BLI_math_solvers.h
index 810c84cc830..b0193022837 100644
--- a/source/blender/blenlib/BLI_math_solvers.h
+++ b/source/blender/blenlib/BLI_math_solvers.h
@@ -48,6 +48,11 @@ bool BLI_eigen_solve_selfadjoint_m3(const float m3[3][3], float r_eigen_values[3
void BLI_svd_m3(const float m3[3][3], float r_U[3][3], float r_S[], float r_V[3][3]);
+/***************************** Simple Solvers ************************************/
+
+bool BLI_tridiagonal_solve(const float *a, const float *b, const float *c, const float *d, float *r_x, const int count);
+bool BLI_tridiagonal_solve_cyclic(const float *a, const float *b, const float *c, const float *d, float *r_x, const int count);
+
/**************************** Inline Definitions ******************************/
#if 0 /* None so far. */
# if BLI_MATH_DO_INLINE
diff --git a/source/blender/blenlib/BLI_math_vector.h b/source/blender/blenlib/BLI_math_vector.h
index 8e0884ba347..3f603311530 100644
--- a/source/blender/blenlib/BLI_math_vector.h
+++ b/source/blender/blenlib/BLI_math_vector.h
@@ -151,6 +151,7 @@ MINLINE void negate_v3_short(short r[3]);
MINLINE void negate_v3_db(double r[3]);
MINLINE void invert_v2(float r[2]);
+MINLINE void invert_v3(float r[3]);
MINLINE void abs_v2(float r[2]);
MINLINE void abs_v2_v2(float r[2], const float a[2]);
@@ -286,6 +287,8 @@ float angle_v3v3(const float a[3], const float b[3]) ATTR_WARN_UNUSED_RESULT;
float angle_v3v3v3(const float a[3], const float b[3], const float c[3]) ATTR_WARN_UNUSED_RESULT;
float cos_v3v3v3(const float p1[3], const float p2[3], const float p3[3]) ATTR_WARN_UNUSED_RESULT;
float cos_v2v2v2(const float p1[2], const float p2[2], const float p3[2]) ATTR_WARN_UNUSED_RESULT;
+float angle_on_axis_v3v3_v3(const float v1[3], const float v2[3], const float axis[3]) ATTR_WARN_UNUSED_RESULT;
+float angle_signed_on_axis_v3v3_v3(const float v1[3], const float v2[3], const float axis[3]) ATTR_WARN_UNUSED_RESULT;
float angle_normalized_v3v3(const float v1[3], const float v2[3]) ATTR_WARN_UNUSED_RESULT;
float angle_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3]) ATTR_WARN_UNUSED_RESULT;
float angle_signed_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3]) ATTR_WARN_UNUSED_RESULT;
@@ -297,14 +300,19 @@ void angle_poly_v3(float *angles, const float *verts[3], int len);
void project_v2_v2v2(float out[2], const float p[2], const float v_proj[2]);
void project_v3_v3v3(float out[3], const float p[3], const float v_proj[3]);
+void project_v2_v2v2_normalized(float out[2], const float p[2], const float v_proj[2]);
+void project_v3_v3v3_normalized(float out[3], const float p[3], const float v_proj[3]);
void project_plane_v3_v3v3(float out[3], const float p[3], const float v_plane[3]);
void project_plane_v2_v2v2(float out[2], const float p[2], const float v_plane[2]);
+void project_plane_normalized_v3_v3v3(float out[3], const float p[3], const float v_plane[3]);
+void project_plane_normalized_v2_v2v2(float out[2], const float p[2], const float v_plane[2]);
void project_v3_plane(float out[3], const float plane_no[3], const float plane_co[3]);
void reflect_v3_v3v3(float out[3], const float vec[3], const float normal[3]);
void ortho_basis_v3v3_v3(float r_n1[3], float r_n2[3], const float n[3]);
void ortho_v3_v3(float out[3], const float v[3]);
void ortho_v2_v2(float out[2], const float v[2]);
void bisect_v3_v3v3v3(float r[3], const float a[3], const float b[3], const float c[3]);
+void rotate_v2_v2fl(float r[2], const float p[2], const float angle);
void rotate_v3_v3v3fl(float v[3], const float p[3], const float axis[3], const float angle);
void rotate_normalized_v3_v3v3fl(float out[3], const float p[3], const float axis[3], const float angle);
@@ -320,6 +328,7 @@ void print_vn(const char *str, const float v[], const int n);
#define print_v4_id(v) print_v4(STRINGIFY(v), v)
#define print_vn_id(v, n) print_vn(STRINGIFY(v), v, n)
+MINLINE void normal_float_to_short_v2(short r[2], const float n[2]);
MINLINE void normal_short_to_float_v3(float r[3], const short n[3]);
MINLINE void normal_float_to_short_v3(short r[3], const float n[3]);
diff --git a/source/blender/blenlib/BLI_mempool.h b/source/blender/blenlib/BLI_mempool.h
index 0c754f551e0..45efb8d7ef1 100644
--- a/source/blender/blenlib/BLI_mempool.h
+++ b/source/blender/blenlib/BLI_mempool.h
@@ -53,7 +53,7 @@ void BLI_mempool_clear_ex(BLI_mempool *pool,
const int totelem_reserve) ATTR_NONNULL(1);
void BLI_mempool_clear(BLI_mempool *pool) ATTR_NONNULL(1);
void BLI_mempool_destroy(BLI_mempool *pool) ATTR_NONNULL(1);
-int BLI_mempool_count(BLI_mempool *pool) ATTR_NONNULL(1);
+int BLI_mempool_len(BLI_mempool *pool) ATTR_NONNULL(1);
void *BLI_mempool_findelem(BLI_mempool *pool, unsigned int index) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
void BLI_mempool_as_table(BLI_mempool *pool, void **data) ATTR_NONNULL(1, 2);
@@ -71,6 +71,8 @@ typedef struct BLI_mempool_iter {
BLI_mempool *pool;
struct BLI_mempool_chunk *curchunk;
unsigned int curindex;
+
+ struct BLI_mempool_chunk **curchunk_threaded_shared;
} BLI_mempool_iter;
/* flag */
@@ -87,6 +89,9 @@ enum {
void BLI_mempool_iternew(BLI_mempool *pool, BLI_mempool_iter *iter) ATTR_NONNULL();
void *BLI_mempool_iterstep(BLI_mempool_iter *iter) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+BLI_mempool_iter *BLI_mempool_iter_threadsafe_create(BLI_mempool *pool, const size_t num_iter) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+void BLI_mempool_iter_threadsafe_free(BLI_mempool_iter *iter_arr) ATTR_NONNULL();
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_path_util.h b/source/blender/blenlib/BLI_path_util.h
index baa1f792018..b59e7f99d59 100644
--- a/source/blender/blenlib/BLI_path_util.h
+++ b/source/blender/blenlib/BLI_path_util.h
@@ -39,20 +39,12 @@ extern "C" {
struct ListBase;
-#ifdef WIN32
-#define SEP '\\'
-#define ALTSEP '/'
-#else
-#define SEP '/'
-#define ALTSEP '\\'
-#endif
-
void BLI_setenv(const char *env, const char *val) ATTR_NONNULL(1);
void BLI_setenv_if_new(const char *env, const char *val) ATTR_NONNULL(1);
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(const char *name);
+bool BLI_make_existing_file(const char *name);
void BLI_split_dirfile(const char *string, char *dir, char *file, const size_t dirlen, const size_t filelen);
void BLI_split_dir_part(const char *string, char *dir, const size_t dirlen);
void BLI_split_file_part(const char *string, char *file, const size_t filelen);
@@ -60,7 +52,13 @@ void BLI_path_append(char *__restrict dst, const size_t maxlen,
const char *__restrict file) ATTR_NONNULL();
void BLI_join_dirfile(char *__restrict string, const size_t maxlen,
const char *__restrict dir, const char *__restrict file) ATTR_NONNULL();
+size_t BLI_path_join(
+ char *__restrict dst, const size_t dst_len,
+ const char *path_first, ...) ATTR_NONNULL(1, 3) ATTR_SENTINEL(0);
const char *BLI_path_basename(const char *path) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
+bool BLI_path_name_at_index(
+ const char *__restrict path, const int index,
+ int *__restrict r_offset, int *__restrict r_len) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
#if 0
typedef enum bli_rebase_state {
@@ -83,7 +81,6 @@ bool BLI_path_program_extensions_add_win32(char *name, const size_t maxlen);
#endif
bool BLI_path_program_search(char *fullname, const size_t maxlen, const char *name);
-void BLI_getlastdir(const char *dir, char *last, const size_t maxlen);
bool BLI_testextensie(const char *str, const char *ext) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
bool BLI_testextensie_n(const char *str, ...) ATTR_NONNULL(1) ATTR_SENTINEL(0);
bool BLI_testextensie_array(const char *str, const char **ext_array) ATTR_NONNULL() ATTR_WARN_UNUSED_RESULT;
@@ -143,6 +140,18 @@ bool BLI_path_suffix(char *string, size_t maxlen, const char *suffix, const char
# define FILE_MAX 1024
#endif
+#ifdef WIN32
+# define SEP '\\'
+# define ALTSEP '/'
+# define SEP_STR "\\"
+# define ALTSEP_STR "/"
+#else
+# define SEP '/'
+# define ALTSEP '\\'
+# define SEP_STR "/"
+# define ALTSEP_STR "\\"
+#endif
+
/* Parent and current dir helpers. */
#define FILENAME_PARENT ".."
#define FILENAME_CURRENT "."
diff --git a/source/blender/blenlib/BLI_polyfill2d.h b/source/blender/blenlib/BLI_polyfill_2d.h
index 798055f9240..099f08d4663 100644
--- a/source/blender/blenlib/BLI_polyfill2d.h
+++ b/source/blender/blenlib/BLI_polyfill_2d.h
@@ -18,8 +18,8 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_POLYFILL2D_H__
-#define __BLI_POLYFILL2D_H__
+#ifndef __BLI_POLYFILL_2D_H__
+#define __BLI_POLYFILL_2D_H__
struct MemArena;
@@ -40,4 +40,4 @@ void BLI_polyfill_calc(
/* default size of polyfill arena */
#define BLI_POLYFILL_ARENA_SIZE MEM_SIZE_OPTIMAL(1 << 14)
-#endif /* __BLI_POLYFILL2D_H__ */
+#endif /* __BLI_POLYFILL_2D_H__ */
diff --git a/source/blender/blenlib/BLI_polyfill2d_beautify.h b/source/blender/blenlib/BLI_polyfill_2d_beautify.h
index 20e53b080fe..73b52125904 100644
--- a/source/blender/blenlib/BLI_polyfill2d_beautify.h
+++ b/source/blender/blenlib/BLI_polyfill_2d_beautify.h
@@ -18,10 +18,9 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_POLYFILL2D_BEAUTIFY_H__
-#define __BLI_POLYFILL2D_BEAUTIFY_H__
+#ifndef __BLI_POLYFILL_2D_BEAUTIFY_H__
+#define __BLI_POLYFILL_2D_BEAUTIFY_H__
-struct EdgeHash;
struct Heap;
struct MemArena;
@@ -31,12 +30,16 @@ void BLI_polyfill_beautify(
unsigned int (*tris)[3],
/* structs for reuse */
- struct MemArena *arena, struct Heap *eheap, struct EdgeHash *eh);
+ struct MemArena *arena, struct Heap *eheap);
+
+float BLI_polyfill_beautify_quad_rotate_calc_ex(
+ const float v1[2], const float v2[2], const float v3[2], const float v4[2],
+ const bool lock_degenerate);
+#define BLI_polyfill_beautify_quad_rotate_calc(v1, v2, v3, v4) \
+ BLI_polyfill_beautify_quad_rotate_calc_ex(v1, v2, v3, v4, false)
-float BLI_polyfill_beautify_quad_rotate_calc(
- const float v1[2], const float v2[2], const float v3[2], const float v4[2]);
/* avoid realloc's when creating new structures for polyfill ngons */
#define BLI_POLYFILL_ALLOC_NGON_RESERVE 64
-#endif /* __BLI_POLYFILL2D_BEAUTIFY_H__ */
+#endif /* __BLI_POLYFILL_2D_BEAUTIFY_H__ */
diff --git a/source/blender/blenlib/BLI_rand.h b/source/blender/blenlib/BLI_rand.h
index f36d2faa1b8..69b23b2473f 100644
--- a/source/blender/blenlib/BLI_rand.h
+++ b/source/blender/blenlib/BLI_rand.h
@@ -101,4 +101,16 @@ RNG_THREAD_ARRAY *BLI_rng_threaded_new(void);
void BLI_rng_threaded_free(struct RNG_THREAD_ARRAY *rngarr) ATTR_NONNULL(1);
int BLI_rng_thread_rand(RNG_THREAD_ARRAY *rngarr, int thread) ATTR_WARN_UNUSED_RESULT;
+/** Low-discrepancy sequences **/
+
+/** Return the _n_th number of the given low-discrepancy sequence. */
+void BLI_halton_1D(unsigned int prime, double offset, int n, double *r);
+void BLI_halton_2D(unsigned int prime[2], double offset[2], int n, double *r);
+void BLI_halton_3D(unsigned int prime[3], double offset[3], int n, double *r);
+void BLI_hammersley_1D(unsigned int n, double *r);
+
+/** Return the whole low-discrepancy sequence up to _n_. */
+void BLI_halton_2D_sequence(unsigned int prime[2], double offset[2], int n, double *r);
+void BLI_hammersley_2D_sequence(unsigned int n, double *r);
+
#endif /* __BLI_RAND_H__ */
diff --git a/source/blender/blenlib/BLI_rect.h b/source/blender/blenlib/BLI_rect.h
index 59bf3644912..471d875c9af 100644
--- a/source/blender/blenlib/BLI_rect.h
+++ b/source/blender/blenlib/BLI_rect.h
@@ -47,12 +47,16 @@ bool BLI_rcti_is_empty(const struct rcti *rect);
bool BLI_rctf_is_empty(const struct rctf *rect);
void BLI_rctf_init(struct rctf *rect, float xmin, float xmax, float ymin, float ymax);
void BLI_rcti_init(struct rcti *rect, int xmin, int xmax, int ymin, int ymax);
+void BLI_rctf_init_pt_radius(struct rctf *rect, const float xy[2], float size);
+void BLI_rcti_init_pt_radius(struct rcti *rect, const int xy[2], int size);
void BLI_rcti_init_minmax(struct rcti *rect);
void BLI_rctf_init_minmax(struct rctf *rect);
void BLI_rcti_do_minmax_v(struct rcti *rect, const int xy[2]);
void BLI_rctf_do_minmax_v(struct rctf *rect, const float xy[2]);
void BLI_rctf_transform_pt_v(const rctf *dst, const rctf *src, float xy_dst[2], const float xy_src[2]);
+void BLI_rctf_transform_calc_m4_pivot_min_ex(const rctf *dst, const rctf *src, float matrix[4][4], uint x, uint y);
+void BLI_rctf_transform_calc_m4_pivot_min(const rctf *dst, const rctf *src, float matrix[4][4]);
void BLI_rctf_translate(struct rctf *rect, float x, float y);
void BLI_rcti_translate(struct rcti *rect, int x, int y);
@@ -95,6 +99,7 @@ void BLI_rctf_union(struct rctf *rctf1, const struct rctf *rctf2);
void BLI_rcti_rctf_copy(struct rcti *dst, const struct rctf *src);
void BLI_rctf_rcti_copy(struct rctf *dst, const struct rcti *src);
void BLI_rcti_rctf_copy_floor(struct rcti *dst, const struct rctf *src);
+void BLI_rcti_rctf_copy_round(struct rcti *dst, const struct rctf *src);
void BLI_rctf_rotate_expand(rctf *dst, const rctf *src, const float angle);
diff --git a/source/blender/blenlib/BLI_smallhash.h b/source/blender/blenlib/BLI_smallhash.h
index e096354e5b1..495fc94a53c 100644
--- a/source/blender/blenlib/BLI_smallhash.h
+++ b/source/blender/blenlib/BLI_smallhash.h
@@ -66,7 +66,7 @@ bool BLI_smallhash_remove(SmallHash *sh, uintptr_t key) ATTR_NONNULL(1);
void *BLI_smallhash_lookup(const SmallHash *sh, uintptr_t key) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
void **BLI_smallhash_lookup_p(const SmallHash *sh, uintptr_t key) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
bool BLI_smallhash_haskey(const SmallHash *sh, uintptr_t key) ATTR_NONNULL(1);
-int BLI_smallhash_count(const SmallHash *sh) ATTR_NONNULL(1);
+int BLI_smallhash_len(const SmallHash *sh) ATTR_NONNULL(1);
void *BLI_smallhash_iternext(SmallHashIter *iter, uintptr_t *key) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
void **BLI_smallhash_iternext_p(SmallHashIter *iter, uintptr_t *key) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
void *BLI_smallhash_iternew(const SmallHash *sh, SmallHashIter *iter, uintptr_t *key) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT;
diff --git a/source/blender/blenlib/BLI_sort_utils.h b/source/blender/blenlib/BLI_sort_utils.h
index e08f4e5ac83..f6bd80b30d3 100644
--- a/source/blender/blenlib/BLI_sort_utils.h
+++ b/source/blender/blenlib/BLI_sort_utils.h
@@ -32,7 +32,7 @@
* \note keep \a sort_value first,
* so cmp functions can be reused.
*/
-struct SortPointerByFloat {
+struct SortPtrByFloat {
float sort_value;
void *data;
};
@@ -42,7 +42,7 @@ struct SortIntByFloat {
int data;
};
-struct SortPointerByInt {
+struct SortPtrByInt {
int sort_value;
void *data;
};
@@ -58,4 +58,7 @@ int BLI_sortutil_cmp_float_reverse(const void *a_, const void *b_);
int BLI_sortutil_cmp_int(const void *a_, const void *b_);
int BLI_sortutil_cmp_int_reverse(const void *a_, const void *b_);
+int BLI_sortutil_cmp_ptr(const void *a_, const void *b_);
+int BLI_sortutil_cmp_ptr_reverse(const void *a_, const void *b_);
+
#endif /* __BLI_SORT_UTILS_H__ */
diff --git a/source/blender/blenlib/BLI_stack.h b/source/blender/blenlib/BLI_stack.h
index 222005ee92e..d54f2a7bab2 100644
--- a/source/blender/blenlib/BLI_stack.h
+++ b/source/blender/blenlib/BLI_stack.h
@@ -30,6 +30,10 @@
#include "BLI_compiler_attrs.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
typedef struct BLI_Stack BLI_Stack;
BLI_Stack *BLI_stack_new_ex(
@@ -55,4 +59,8 @@ size_t BLI_stack_count(const BLI_Stack *stack) ATTR_WARN_UNUSED_RESULT ATTR_NONN
bool BLI_stack_is_empty(const BLI_Stack *stack) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+#ifdef __cplusplus
+}
+#endif
+
#endif /* __BLI_STACK_H__ */
diff --git a/source/blender/blenlib/BLI_strict_flags.h b/source/blender/blenlib/BLI_strict_flags.h
index 964ee06469d..86b7285655e 100644
--- a/source/blender/blenlib/BLI_strict_flags.h
+++ b/source/blender/blenlib/BLI_strict_flags.h
@@ -30,6 +30,8 @@
#ifdef __GNUC__
# if (__GNUC__ * 100 + __GNUC_MINOR__) >= 406 /* gcc4.6+ only */
# pragma GCC diagnostic error "-Wsign-compare"
+# endif
+# if __GNUC__ >= 6 /* gcc6+ only */
# pragma GCC diagnostic error "-Wconversion"
# endif
# if (__GNUC__ * 100 + __GNUC_MINOR__) >= 408
diff --git a/source/blender/blenlib/BLI_string.h b/source/blender/blenlib/BLI_string.h
index d137806c575..48be9d1842f 100644
--- a/source/blender/blenlib/BLI_string.h
+++ b/source/blender/blenlib/BLI_string.h
@@ -103,6 +103,20 @@ int BLI_string_find_split_words(
const char delim, int r_words[][2], int words_max)
ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+/** \name String Copy/Format Macros
+ * Avoid repeating destination with `sizeof(..)`.
+ * \note `ARRAY_SIZE` allows pointers on some platforms.
+ * \{ */
+#define STRNCPY(dst, src) \
+ BLI_strncpy(dst, src, ARRAY_SIZE(dst))
+#define STRNCPY_RLEN(dst, src) \
+ BLI_strncpy_rlen(dst, src, ARRAY_SIZE(dst))
+#define SNPRINTF(dst, format, ...) \
+ BLI_snprintf(dst, ARRAY_SIZE(dst), format, __VA_ARGS__)
+#define SNPRINTF_RLEN(dst, format, ...) \
+ BLI_snprintf_rlen(dst, ARRAY_SIZE(dst), format, __VA_ARGS__)
+/** \} */
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_string_cursor_utf8.h b/source/blender/blenlib/BLI_string_cursor_utf8.h
index b4d354b7e37..e7776aa0f0d 100644
--- a/source/blender/blenlib/BLI_string_cursor_utf8.h
+++ b/source/blender/blenlib/BLI_string_cursor_utf8.h
@@ -30,26 +30,28 @@
* \ingroup bli
*/
-typedef enum strCursorJumpType {
+typedef enum eStrCursorJumpType {
STRCUR_JUMP_NONE,
STRCUR_JUMP_DELIM,
STRCUR_JUMP_ALL
-} strCursorJumpType;
+} eStrCursorJumpType;
-typedef enum strCursorJumpDirection {
+typedef enum eStrCursorJumpDirection {
STRCUR_DIR_PREV,
STRCUR_DIR_NEXT
-} strCursorJumpDirection;
+} eStrCursorJumpDirection;
bool BLI_str_cursor_step_next_utf8(const char *str, size_t maxlen, int *pos);
bool BLI_str_cursor_step_prev_utf8(const char *str, size_t maxlen, int *pos);
-void BLI_str_cursor_step_utf8(const char *str, size_t maxlen,
- int *pos, strCursorJumpDirection direction,
- strCursorJumpType jump, bool use_init_step);
+void BLI_str_cursor_step_utf8(
+ const char *str, size_t maxlen,
+ int *pos, eStrCursorJumpDirection direction,
+ eStrCursorJumpType jump, bool use_init_step);
-void BLI_str_cursor_step_wchar(const wchar_t *str, size_t maxlen,
- int *pos, strCursorJumpDirection direction,
- strCursorJumpType jump, bool use_init_step);
+void BLI_str_cursor_step_wchar(
+ const wchar_t *str, size_t maxlen,
+ int *pos, eStrCursorJumpDirection direction,
+ eStrCursorJumpType jump, bool use_init_step);
#endif /* __BLI_STRING_CURSOR_UTF8_H__ */
diff --git a/source/blender/blenlib/BLI_string_utf8.h b/source/blender/blenlib/BLI_string_utf8.h
index 32504a88b48..21542d0d6e1 100644
--- a/source/blender/blenlib/BLI_string_utf8.h
+++ b/source/blender/blenlib/BLI_string_utf8.h
@@ -77,6 +77,16 @@ size_t BLI_str_partition_ex_utf8(
#define BLI_UTF8_WIDTH_MAX 2 /* columns */
#define BLI_UTF8_ERR ((unsigned int)-1)
+/** \name String Copy/Format Macros
+ * Avoid repeating destination with `sizeof(..)`.
+ * \note `ARRAY_SIZE` allows pointers on some platforms.
+ * \{ */
+#define STRNCPY_UTF8(dst, src) \
+ BLI_strncpy_utf8(dst, src, ARRAY_SIZE(dst))
+#define STRNCPY_UTF8_RLEN(dst, src) \
+ BLI_strncpy_utf8_rlen(dst, src, ARRAY_SIZE(dst))
+/** \} */
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_string_utils.h b/source/blender/blenlib/BLI_string_utils.h
index bb19ed574bb..5701bce51ea 100644
--- a/source/blender/blenlib/BLI_string_utils.h
+++ b/source/blender/blenlib/BLI_string_utils.h
@@ -39,6 +39,7 @@ extern "C" {
#endif
#include "BLI_compiler_attrs.h"
+#include "BLI_utildefines_variadic.h"
struct ListBase;
@@ -49,6 +50,24 @@ size_t BLI_split_name_num(char *left, int *nr, const char *name, const char deli
void BLI_string_split_suffix(const char *string, char *r_body, char *r_suf, const size_t str_len);
void BLI_string_split_prefix(const char *string, char *r_pre, char *r_body, const size_t str_len);
+/* Join strings, return newly allocated string. */
+char *BLI_string_join_arrayN(
+ const char *strings[], uint strings_len) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+char *BLI_string_join_array_by_sep_charN(
+ char sep, const char *strings[], uint strings_len) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+char *BLI_string_join_array_by_sep_char_with_tableN(
+ char sep, char *table[], const char *strings[], uint strings_len) ATTR_NONNULL();
+/* Take multiple arguments, pass as (array, length). */
+#define BLI_string_joinN(...) \
+ BLI_string_join_arrayN( \
+ ((const char *[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define BLI_string_join_by_sep_charN(sep, ...) \
+ BLI_string_join_array_by_sep_charN( \
+ sep, ((const char *[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define BLI_string_join_by_sep_char_with_tableN(sep, table, ...) \
+ BLI_string_join_array_by_sep_char_with_tableN( \
+ sep, table, ((const char *[]){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+
void BLI_string_flip_side_name(char *r_name, const char *from_name, const bool strip_number, const size_t name_len);
bool BLI_uniquename_cb(
diff --git a/source/blender/blenlib/BLI_sys_types.h b/source/blender/blenlib/BLI_sys_types.h
index 9d8222c575d..80ee50621ca 100644
--- a/source/blender/blenlib/BLI_sys_types.h
+++ b/source/blender/blenlib/BLI_sys_types.h
@@ -47,7 +47,9 @@
extern "C" {
#endif
-#if defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD_kernel__) || defined(__GNU__)
+#if defined(__linux__) || defined(__GNU__) || \
+ defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD_kernel__) || \
+ defined(__HAIKU__)
/* Linux-i386, Linux-Alpha, Linux-ppc */
#include <stdint.h>
@@ -65,8 +67,8 @@ typedef uint64_t u_int64_t;
#include <inttypes.h>
-/* MinGW and MSVC >= 2010 */
-#elif defined(FREE_WINDOWS) || defined(_MSC_VER)
+/* MSVC >= 2010 */
+#elif defined(_MSC_VER)
#include <stdint.h>
#else
diff --git a/source/blender/blenlib/BLI_task.h b/source/blender/blenlib/BLI_task.h
index 967e0be6d0a..d03010af8d2 100644
--- a/source/blender/blenlib/BLI_task.h
+++ b/source/blender/blenlib/BLI_task.h
@@ -19,7 +19,9 @@
*/
#ifndef __BLI_TASK_H__
-#define __BLI_TASK_H__
+#define __BLI_TASK_H__
+
+#include <string.h> /* for memset() */
struct Link;
struct ListBase;
@@ -35,6 +37,8 @@ extern "C" {
#include "BLI_threads.h"
#include "BLI_utildefines.h"
+struct BLI_mempool;
+
/* Task Scheduler
*
* Central scheduler that holds running threads ready to execute tasks. A single
@@ -81,6 +85,7 @@ typedef void (*TaskFreeFunction)(TaskPool *__restrict pool, void *taskdata, int
TaskPool *BLI_task_pool_create(TaskScheduler *scheduler, void *userdata);
TaskPool *BLI_task_pool_create_background(TaskScheduler *scheduler, void *userdata);
+TaskPool *BLI_task_pool_create_suspended(TaskScheduler *scheduler, void *userdata);
void BLI_task_pool_free(TaskPool *pool);
void BLI_task_pool_push_ex(
@@ -95,14 +100,6 @@ void BLI_task_pool_push_from_thread(TaskPool *pool, TaskRunFunction run,
void BLI_task_pool_work_and_wait(TaskPool *pool);
/* cancel all tasks, keep worker threads running */
void BLI_task_pool_cancel(TaskPool *pool);
-/* stop all worker threads */
-void BLI_task_pool_stop(TaskPool *pool);
-
-/* get number of threads allowed to be used by this pool */
-int BLI_pool_get_num_threads(TaskPool *pool);
-
-/* set number of threads allowed to be used by this pool */
-void BLI_pool_set_num_threads(TaskPool *pool, int num_threads);
/* for worker threads, test if canceled */
bool BLI_task_pool_canceled(TaskPool *pool);
@@ -113,36 +110,85 @@ void *BLI_task_pool_userdata(TaskPool *pool);
/* optional mutex to use from run function */
ThreadMutex *BLI_task_pool_user_mutex(TaskPool *pool);
-/* number of tasks done, for stats, don't use this to make decisions */
-size_t BLI_task_pool_tasks_done(TaskPool *pool);
+/* Delayed push, use that to reduce thread overhead by accumulating
+ * all new tasks into local queue first and pushing it to scheduler
+ * from within a single mutex lock.
+ */
+void BLI_task_pool_delayed_push_begin(TaskPool *pool, int thread_id);
+void BLI_task_pool_delayed_push_end(TaskPool *pool, int thread_id);
/* Parallel for routines */
-typedef void (*TaskParallelRangeFunc)(void *userdata, const int iter);
-typedef void (*TaskParallelRangeFuncEx)(void *userdata, void *userdata_chunk, const int iter, const int thread_id);
-typedef void (*TaskParallelRangeFuncFinalize)(void *userdata, void *userdata_chunk);
-void BLI_task_parallel_range_ex(
- int start, int stop,
- void *userdata,
- void *userdata_chunk,
- const size_t userdata_chunk_size,
- TaskParallelRangeFuncEx func_ex,
- const bool use_threading,
- const bool use_dynamic_scheduling);
+
+typedef enum eTaskSchedulingMode {
+ /* Task scheduler will divide overall work into equal chunks, scheduling
+ * even chunks to all worker threads.
+ * Least run time benefit, ideal for cases when each task requires equal
+ * amount of compute power.
+ */
+ TASK_SCHEDULING_STATIC,
+ /* Task scheduler will schedule small amount of work to each worker thread.
+ * Has more run time overhead, but deals much better with cases when each
+ * part of the work requires totally different amount of compute power.
+ */
+ TASK_SCHEDULING_DYNAMIC,
+} eTaskSchedulingMode;
+
+/* Per-thread specific data passed to the callback. */
+typedef struct ParallelRangeTLS {
+ /* Identifier of the thread who this data belongs to. */
+ int thread_id;
+ /* Copy of user-specifier chunk, which is copied from original chunk to all
+ * worker threads. This is similar to OpenMP's firstprivate.
+ */
+ void *userdata_chunk;
+} ParallelRangeTLS;
+
+typedef void (*TaskParallelRangeFunc)(void *__restrict userdata,
+ const int iter,
+ const ParallelRangeTLS *__restrict tls);
+typedef void (*TaskParallelRangeFuncFinalize)(void *__restrict userdata,
+ void *__restrict userdata_chunk);
+
+typedef struct ParallelRangeSettings {
+ /* Whether caller allows to do threading of the particular range.
+ * Usually set by some equation, which forces threading off when threading
+ * overhead becomes higher than speed benefit.
+ * BLI_task_parallel_range() by itself will always use threading when range
+ * is higher than a chunk size. As in, threading will always be performed.
+ */
+ bool use_threading;
+ /* Scheduling mode to use for this parallel range invocation. */
+ eTaskSchedulingMode scheduling_mode;
+ /* Each instance of looping chunks will get a copy of this data
+ * (similar to OpenMP's firstprivate).
+ */
+ void *userdata_chunk; /* Pointer to actual data. */
+ size_t userdata_chunk_size; /* Size of that data. */
+ /* Function called from calling thread once whole range have been
+ * processed.
+ */
+ TaskParallelRangeFuncFinalize func_finalize;
+ /* Minimum allowed number of range iterators to be handled by a single
+ * thread. This allows to achieve following:
+ * - Reduce amount of threading overhead.
+ * - Partially occupy thread pool with ranges which are computationally
+ * expensive, but which are smaller than amount of available threads.
+ * For example, it's possible to multi-thread [0 .. 64] range into 4
+ * thread which will be doing 16 iterators each.
+ * This is a preferred way to tell scheduler when to start threading than
+ * having a global use_threading switch based on just range size.
+ */
+ int min_iter_per_thread;
+} ParallelRangeSettings;
+
+BLI_INLINE void BLI_parallel_range_settings_defaults(
+ ParallelRangeSettings *settings);
+
void BLI_task_parallel_range(
- int start, int stop,
+ const int start, const int stop,
void *userdata,
TaskParallelRangeFunc func,
- const bool use_threading);
-
-void BLI_task_parallel_range_finalize(
- int start, int stop,
- void *userdata,
- void *userdata_chunk,
- const size_t userdata_chunk_size,
- TaskParallelRangeFuncEx func_ex,
- TaskParallelRangeFuncFinalize func_finalize,
- const bool use_threading,
- const bool use_dynamic_scheduling);
+ const ParallelRangeSettings *settings);
typedef void (*TaskParallelListbaseFunc)(void *userdata,
struct Link *iter,
@@ -153,6 +199,29 @@ void BLI_task_parallel_listbase(
TaskParallelListbaseFunc func,
const bool use_threading);
+typedef struct MempoolIterData MempoolIterData;
+typedef void (*TaskParallelMempoolFunc)(void *userdata,
+ MempoolIterData *iter);
+void BLI_task_parallel_mempool(
+ struct BLI_mempool *mempool,
+ void *userdata,
+ TaskParallelMempoolFunc func,
+ const bool use_threading);
+
+/* TODO(sergey): Think of a better place for this. */
+BLI_INLINE void BLI_parallel_range_settings_defaults(
+ ParallelRangeSettings *settings)
+{
+ memset(settings, 0, sizeof(*settings));
+ settings->use_threading = true;
+ settings->scheduling_mode = TASK_SCHEDULING_STATIC;
+ /* NOTE: Current value mimics old behavior, but it's not ideal by any
+ * means. Would be cool to find a common value which will work good enough
+ * for both static and dynamic scheduling.
+ */
+ settings->min_iter_per_thread = 1;
+}
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenlib/BLI_threads.h b/source/blender/blenlib/BLI_threads.h
index 0b1b4d8ee8c..66eb5cfd22b 100644
--- a/source/blender/blenlib/BLI_threads.h
+++ b/source/blender/blenlib/BLI_threads.h
@@ -55,19 +55,19 @@ void BLI_threadapi_exit(void);
struct TaskScheduler *BLI_task_scheduler_get(void);
-void BLI_init_threads(struct ListBase *threadbase, void *(*do_thread)(void *), int tot);
+void BLI_threadpool_init(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);
+int BLI_threadpool_available_thread_index(struct ListBase *threadbase);
+void BLI_threadpool_insert(struct ListBase *threadbase, void *callerdata);
+void BLI_threadpool_remove(struct ListBase *threadbase, void *callerdata);
+void BLI_threadpool_remove_index(struct ListBase *threadbase, int index);
+void BLI_threadpool_clear(struct ListBase *threadbase);
+void BLI_threadpool_end(struct ListBase *threadbase);
int BLI_thread_is_main(void);
-void BLI_begin_threaded_malloc(void);
-void BLI_end_threaded_malloc(void);
+void BLI_threaded_malloc_begin(void);
+void BLI_threaded_malloc_end(void);
/* System Information */
@@ -91,8 +91,8 @@ int BLI_system_num_threads_override_get(void);
#define LOCK_FFTW 9
#define LOCK_VIEW3D 10
-void BLI_lock_thread(int type);
-void BLI_unlock_thread(int type);
+void BLI_thread_lock(int type);
+void BLI_thread_unlock(int type);
/* Mutex Lock */
@@ -111,8 +111,10 @@ void BLI_mutex_unlock(ThreadMutex *mutex);
/* Spin Lock */
-#ifdef __APPLE__
+#if defined(__APPLE__)
typedef OSSpinLock SpinLock;
+#elif defined(_MSC_VER)
+typedef volatile int SpinLock;
#else
typedef pthread_spinlock_t SpinLock;
#endif
@@ -175,7 +177,7 @@ void BLI_thread_queue_free(ThreadQueue *queue);
void BLI_thread_queue_push(ThreadQueue *queue, void *work);
void *BLI_thread_queue_pop(ThreadQueue *queue);
void *BLI_thread_queue_pop_timeout(ThreadQueue *queue, int ms);
-int BLI_thread_queue_size(ThreadQueue *queue);
+int BLI_thread_queue_len(ThreadQueue *queue);
bool BLI_thread_queue_is_empty(ThreadQueue *queue);
void BLI_thread_queue_wait_finish(ThreadQueue *queue);
diff --git a/source/blender/blenlib/BLI_utildefines.h b/source/blender/blenlib/BLI_utildefines.h
index 746eb922c65..46b3748c7ce 100644
--- a/source/blender/blenlib/BLI_utildefines.h
+++ b/source/blender/blenlib/BLI_utildefines.h
@@ -39,34 +39,10 @@ extern "C" {
/* avoid many includes for now */
#include "BLI_sys_types.h"
#include "BLI_compiler_compat.h"
+#include "BLI_utildefines_variadic.h"
-#ifndef NDEBUG /* for BLI_assert */
-#include <stdio.h>
-#endif
-
-
-/* varargs macros (keep first so others can use) */
-/* --- internal helpers --- */
-#define _VA_NARGS_GLUE(x, y) x y
-#define _VA_NARGS_RETURN_COUNT(\
- _1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, \
- _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, \
- _33_, _34_, _35_, _36_, _37_, _38_, _39_, _40_, _41_, _42_, _43_, _44_, _45_, _46_, _47_, _48_, \
- _49_, _50_, _51_, _52_, _53_, _54_, _55_, _56_, _57_, _58_, _59_, _60_, _61_, _62_, _63_, _64_, \
- count, ...) count
-#define _VA_NARGS_EXPAND(args) _VA_NARGS_RETURN_COUNT args
-/* 64 args max */
-#define _VA_NARGS_COUNT(...) _VA_NARGS_EXPAND((__VA_ARGS__, \
- 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, \
- 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, \
- 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, \
- 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
-#define _VA_NARGS_OVERLOAD_MACRO2(name, count) name##count
-#define _VA_NARGS_OVERLOAD_MACRO1(name, count) _VA_NARGS_OVERLOAD_MACRO2(name, count)
-#define _VA_NARGS_OVERLOAD_MACRO(name, count) _VA_NARGS_OVERLOAD_MACRO1(name, count)
-/* --- expose for re-use --- */
-#define VA_NARGS_CALL_OVERLOAD(name, ...) \
- _VA_NARGS_GLUE(_VA_NARGS_OVERLOAD_MACRO(name, _VA_NARGS_COUNT(__VA_ARGS__)), (__VA_ARGS__))
+/* We could remove in future. */
+#include "BLI_assert.h"
/* useful for finding bad use of min/max */
#if 0
@@ -435,7 +411,7 @@ extern "C" {
} (void)0
/* assuming a static array */
-#if defined(__GNUC__) && !defined(__cplusplus) && !defined(__clang__)
+#if defined(__GNUC__) && !defined(__cplusplus) && !defined(__clang__) && !defined(__INTEL_COMPILER)
# define ARRAY_SIZE(arr) \
((sizeof(struct {int isnt_array : ((const void *)&(arr) == &(arr)[0]);}) * 0) + \
(sizeof(arr) / sizeof(*(arr))))
@@ -532,6 +508,16 @@ extern bool BLI_memory_is_zero(const void *arr, const size_t arr_size);
#define SET_UINT_IN_POINTER(i) ((void *)(uintptr_t)(i))
#define GET_UINT_FROM_POINTER(i) ((void)0, ((unsigned int)(uintptr_t)(i)))
+/* Set flag from a single test */
+#define SET_FLAG_FROM_TEST(value, test, flag) \
+{ \
+ if (test) { \
+ (value) |= (flag); \
+ } \
+ else { \
+ (value) &= ~(flag); \
+ } \
+} ((void)0)
/* Macro to convert a value to string in the preprocessor
* STRINGIFY_ARG: gives the argument as a string
@@ -628,52 +614,6 @@ extern bool BLI_memory_is_zero(const void *arr, const size_t arr_size);
# define UNUSED_VARS_NDEBUG UNUSED_VARS
#endif
-
-/* BLI_assert(), default only to print
- * for aborting need to define WITH_ASSERT_ABORT
- */
-#ifndef NDEBUG
-# include "BLI_system.h"
-# ifdef WITH_ASSERT_ABORT
-# define _BLI_DUMMY_ABORT abort
-# else
-# define _BLI_DUMMY_ABORT() (void)0
-# endif
-# if defined(__GNUC__) || defined(_MSC_VER) /* check __func__ is available */
-# define BLI_assert(a) \
- (void)((!(a)) ? ( \
- ( \
- BLI_system_backtrace(stderr), \
- fprintf(stderr, \
- "BLI_assert failed: %s:%d, %s(), at \'%s\'\n", \
- __FILE__, __LINE__, __func__, STRINGIFY(a)), \
- _BLI_DUMMY_ABORT(), \
- NULL)) : NULL)
-# else
-# define BLI_assert(a) \
- (void)((!(a)) ? ( \
- ( \
- fprintf(stderr, \
- "BLI_assert failed: %s:%d, at \'%s\'\n", \
- __FILE__, __LINE__, STRINGIFY(a)), \
- _BLI_DUMMY_ABORT(), \
- NULL)) : NULL)
-# endif
-#else
-# define BLI_assert(a) (void)0
-#endif
-
-/* C++ can't use _Static_assert, expects static_assert() but c++0x only,
- * Coverity also errors out. */
-#if (!defined(__cplusplus)) && \
- (!defined(__COVERITY__)) && \
- (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406)) /* gcc4.6+ only */
-# define BLI_STATIC_ASSERT(a, msg) __extension__ _Static_assert(a, msg);
-#else
- /* TODO msvc, clang */
-# define BLI_STATIC_ASSERT(a, msg)
-#endif
-
/* hints for branch prediction, only use in code that runs a _lot_ where */
#ifdef __GNUC__
# define LIKELY(x) __builtin_expect(!!(x), 1)
diff --git a/source/blender/blenlib/BLI_utildefines_iter.h b/source/blender/blenlib/BLI_utildefines_iter.h
new file mode 100644
index 00000000000..094c1a4b3dc
--- /dev/null
+++ b/source/blender/blenlib/BLI_utildefines_iter.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_UTILDEFINES_ITER_H__
+#define __BLI_UTILDEFINES_ITER_H__
+
+/** \file BLI_utildefines_iter.h
+ * \ingroup bli
+ *
+ * General looping helpers, use `BLI_FOREACH` prefix.
+ */
+
+/**
+ * Even value distribution.
+ *
+ * \a src must be larger than \a dst,
+ * \a dst defines the number of iterations, their values are evenly spaced.
+ *
+ * The following pairs represent (src, dst) arguments and the values they loop over.
+ * <pre>
+ * (19, 4) -> [2, 7, 11. 16]
+ * (100, 5) -> [9, 29, 49, 69, 89]
+ * (100, 3) -> [16, 49, 83]
+ * (100, 100) -> [0..99]
+ * </pre>
+ * \note this is mainly useful for numbers that might not divide evenly into eachother.
+ */
+#define BLI_FOREACH_SPARSE_RANGE(src, dst, i) \
+for (int _src = (src), _src2 = _src * 2, _dst2 = (dst) * 2, _error = _dst2 - _src, i = 0, _delta; \
+ ((void)(_delta = divide_floor_i(_error, _dst2)), \
+ (void)(i -= _delta), \
+ (i < _src)); \
+ _error -= (_delta * _dst2) + _src2)
+
+#endif /* __BLI_UTILDEFINES_ITER_H__ */
diff --git a/source/blender/blenlib/BLI_stackdefines.h b/source/blender/blenlib/BLI_utildefines_stack.h
index 42b11eb9a2b..224add91504 100644
--- a/source/blender/blenlib/BLI_stackdefines.h
+++ b/source/blender/blenlib/BLI_utildefines_stack.h
@@ -18,10 +18,10 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_STACKDEFINES_H__
-#define __BLI_STACKDEFINES_H__
+#ifndef __BLI_UTILDEFINES_STACK_H__
+#define __BLI_UTILDEFINES_STACK_H__
-/** \file BLI_stackdefines.h
+/** \file BLI_utildefines_stack.h
* \ingroup bli
*
* Macro's for a simple array based stack
@@ -77,13 +77,13 @@
SWAP(typeof(stack_a), stack_a, stack_b); \
SWAP(unsigned int, _##stack_a##_index, _##stack_b##_index); \
_STACK_SWAP_TOTALLOC(stack_a, stack_b); \
- } ((void)0)
+} ((void)0)
#else
#define STACK_SWAP(stack_a, stack_b) { \
SWAP(void *, stack_a, stack_b); \
SWAP(unsigned int, _##stack_a##_index, _##stack_b##_index); \
_STACK_SWAP_TOTALLOC(stack_a, stack_b); \
- } ((void)0)
+} ((void)0)
#endif
-#endif /* __BLI_STACKDEFINES_H__ */
+#endif /* __BLI_UTILDEFINES_STACK_H__ */
diff --git a/source/blender/blenlib/BLI_utildefines_variadic.h b/source/blender/blenlib/BLI_utildefines_variadic.h
new file mode 100644
index 00000000000..7c15754fd83
--- /dev/null
+++ b/source/blender/blenlib/BLI_utildefines_variadic.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BLI_UTILDEFINES_VARIADIC_H__
+#define __BLI_UTILDEFINES_VARIADIC_H__
+
+/** \file BLI_utildefines_variadic.h
+ * \ingroup bli
+ */
+
+/* --- internal helpers --- */
+#define _VA_NARGS_GLUE(x, y) x y
+#define _VA_NARGS_RETURN_COUNT(\
+ _1_, _2_, _3_, _4_, _5_, _6_, _7_, _8_, _9_, _10_, _11_, _12_, _13_, _14_, _15_, _16_, \
+ _17_, _18_, _19_, _20_, _21_, _22_, _23_, _24_, _25_, _26_, _27_, _28_, _29_, _30_, _31_, _32_, \
+ _33_, _34_, _35_, _36_, _37_, _38_, _39_, _40_, _41_, _42_, _43_, _44_, _45_, _46_, _47_, _48_, \
+ _49_, _50_, _51_, _52_, _53_, _54_, _55_, _56_, _57_, _58_, _59_, _60_, _61_, _62_, _63_, _64_, \
+ count, ...) count
+#define _VA_NARGS_EXPAND(args) _VA_NARGS_RETURN_COUNT args
+#define _VA_NARGS_OVERLOAD_MACRO2(name, count) name##count
+#define _VA_NARGS_OVERLOAD_MACRO1(name, count) _VA_NARGS_OVERLOAD_MACRO2(name, count)
+#define _VA_NARGS_OVERLOAD_MACRO(name, count) _VA_NARGS_OVERLOAD_MACRO1(name, count)
+/* --- expose for re-use --- */
+/* 64 args max */
+#define VA_NARGS_COUNT(...) _VA_NARGS_EXPAND((__VA_ARGS__, \
+ 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, \
+ 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, \
+ 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, \
+ 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
+#define VA_NARGS_CALL_OVERLOAD(name, ...) \
+ _VA_NARGS_GLUE(_VA_NARGS_OVERLOAD_MACRO(name, VA_NARGS_COUNT(__VA_ARGS__)), (__VA_ARGS__))
+
+#endif /* __BLI_UTILDEFINES_VARIADIC_H__ */
diff --git a/source/blender/blenlib/BLI_vfontdata.h b/source/blender/blenlib/BLI_vfontdata.h
index 8a7079b6c5f..0cd50319a33 100644
--- a/source/blender/blenlib/BLI_vfontdata.h
+++ b/source/blender/blenlib/BLI_vfontdata.h
@@ -52,8 +52,10 @@ typedef struct VChar {
} VChar;
VFontData *BLI_vfontdata_from_freetypefont(struct PackedFile *pf);
+VFontData *BLI_vfontdata_copy(const VFontData *vfont_src, const int flag);
VChar *BLI_vfontchar_from_freetypefont(struct VFont *vfont, unsigned long character);
+VChar *BLI_vfontchar_copy(const VChar *vchar_src, const int flag);
#endif
diff --git a/source/blender/blenlib/BLI_voronoi.h b/source/blender/blenlib/BLI_voronoi_2d.h
index 9d32061bf97..8d1ff2d4c2b 100644
--- a/source/blender/blenlib/BLI_voronoi.h
+++ b/source/blender/blenlib/BLI_voronoi_2d.h
@@ -23,12 +23,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#ifndef __BLI_VORONOI_H__
-#define __BLI_VORONOI_H__
+#ifndef __BLI_VORONOI_2D_H__
+#define __BLI_VORONOI_2D_H__
struct ListBase;
-/** \file BLI_voronoi.h
+/** \file BLI_voronoi_2d.h
* \ingroup bli
*/
@@ -67,4 +67,4 @@ void BLI_voronoi_triangulate(const VoronoiSite *sites, int sites_total, struct L
VoronoiTriangulationPoint **triangulated_points_r, int *triangulated_points_total_r,
int (**triangles_r)[3], int *triangles_total_r);
-#endif /* __BLI_VORONOI_H__ */
+#endif /* __BLI_VORONOI_2D_H__ */
diff --git a/source/blender/blenlib/BLI_winstuff.h b/source/blender/blenlib/BLI_winstuff.h
index b421b7dbb90..6fbbed01400 100644
--- a/source/blender/blenlib/BLI_winstuff.h
+++ b/source/blender/blenlib/BLI_winstuff.h
@@ -37,15 +37,6 @@
# error "This include is for Windows only!"
#endif
-#ifdef FREE_WINDOWS
-# ifdef WINVER
-# undef WINVER
-# endif
-
-/* Some stuff requires WINVER 0x500, but mingw's default is 0x400 */
-# define WINVER 0x0501
-#endif
-
#define WIN32_LEAN_AND_MEAN
#ifndef WIN32_SKIP_HKEY_PROTECTION
@@ -94,7 +85,7 @@ extern "C" {
# define snprintf _snprintf
#endif
-#if defined(_MSC_VER) || (defined(FREE_WINDOWS) && !defined(FREE_WINDOWS64))
+#if defined(_MSC_VER)
# define R_OK 4
# define W_OK 2
// not accepted by access() on windows
@@ -102,28 +93,22 @@ extern "C" {
# define F_OK 0
#endif
-#ifndef FREE_WINDOWS
typedef unsigned int mode_t;
-#endif
/* use functions that take a 64 bit offset for files larger than 4GB */
-#ifndef FREE_WINDOWS
-# include <stdio.h>
-# define fseek(stream, offset, origin) _fseeki64(stream, offset, origin)
-# define ftell(stream) _ftelli64(stream)
-# define lseek(fd, offset, origin) _lseeki64(fd, offset, origin)
-# define tell(fd) _telli64(fd)
-#endif
+#include <stdio.h>
+#define fseek(stream, offset, origin) _fseeki64(stream, offset, origin)
+#define ftell(stream) _ftelli64(stream)
+#define lseek(fd, offset, origin) _lseeki64(fd, offset, origin)
+#define tell(fd) _telli64(fd)
+
-/* mingw using _SSIZE_T_ to declare ssize_t type */
#ifndef _SSIZE_T_
# define _SSIZE_T_
/* python uses HAVE_SSIZE_T */
# ifndef HAVE_SSIZE_T
# define HAVE_SSIZE_T 1
-# ifndef FREE_WINDOWS64
typedef long ssize_t;
-# endif
# endif
#endif
diff --git a/source/blender/blenlib/CMakeLists.txt b/source/blender/blenlib/CMakeLists.txt
index 3277519c66e..f8fc2bfdcff 100644
--- a/source/blender/blenlib/CMakeLists.txt
+++ b/source/blender/blenlib/CMakeLists.txt
@@ -41,14 +41,16 @@ set(INC_SYS
set(SRC
intern/BLI_args.c
intern/BLI_array.c
- intern/BLI_dial.c
+ intern/BLI_dial_2d.c
intern/BLI_dynstr.c
intern/BLI_filelist.c
intern/BLI_ghash.c
+ intern/BLI_ghash_utils.c
intern/BLI_heap.c
intern/BLI_kdopbvh.c
intern/BLI_kdtree.c
intern/BLI_linklist.c
+ intern/BLI_linklist_lockfree.c
intern/BLI_memarena.c
intern/BLI_mempool.c
intern/DLRB_tree.c
@@ -57,10 +59,10 @@ set(SRC
intern/array_utils.c
intern/astar.c
intern/bitmap_draw_2d.c
- intern/boxpack2d.c
+ intern/boxpack_2d.c
intern/buffer.c
intern/callbacks.c
- intern/convexhull2d.c
+ intern/convexhull_2d.c
intern/dynlib.c
intern/easing.c
intern/edgehash.c
@@ -72,8 +74,8 @@ set(SRC
intern/gsqueue.c
intern/hash_md5.c
intern/hash_mm2a.c
- intern/jitter.c
- intern/lasso.c
+ intern/jitter_2d.c
+ intern/lasso_2d.c
intern/list_sort_impl.h
intern/listbase.c
intern/math_base.c
@@ -94,8 +96,8 @@ set(SRC
intern/memory_utils.c
intern/noise.c
intern/path_util.c
- intern/polyfill2d.c
- intern/polyfill2d_beautify.c
+ intern/polyfill_2d.c
+ intern/polyfill_2d_beautify.c
intern/quadric.c
intern/rand.c
intern/rct.c
@@ -116,7 +118,7 @@ set(SRC
intern/time.c
intern/timecode.c
intern/uvproject.c
- intern/voronoi.c
+ intern/voronoi_2d.c
intern/voxel.c
intern/winstuff.c
intern/winstuff_dir.c
@@ -131,14 +133,15 @@ set(SRC
BLI_bitmap.h
BLI_bitmap_draw_2d.h
BLI_blenlib.h
- BLI_boxpack2d.h
+ BLI_boxpack_2d.h
BLI_buffer.h
BLI_callbacks.h
BLI_compiler_attrs.h
BLI_compiler_compat.h
BLI_compiler_typecheck.h
- BLI_convexhull2d.h
- BLI_dial.h
+ BLI_console.h
+ BLI_convexhull_2d.h
+ BLI_dial_2d.h
BLI_dlrbTree.h
BLI_dynlib.h
BLI_dynstr.h
@@ -152,15 +155,16 @@ set(SRC
BLI_ghash.h
BLI_graph.h
BLI_gsqueue.h
+ BLI_hash.h
BLI_hash_md5.h
BLI_hash_mm2a.h
BLI_heap.h
- BLI_jitter.h
+ BLI_jitter_2d.h
BLI_kdopbvh.h
BLI_kdtree.h
- BLI_lasso.h
+ BLI_lasso_2d.h
BLI_link_utils.h
- BLI_linklist.h
+ BLI_linklist_lockfree.h
BLI_linklist_stack.h
BLI_listbase.h
BLI_math.h
@@ -181,8 +185,8 @@ set(SRC
BLI_mempool.h
BLI_noise.h
BLI_path_util.h
- BLI_polyfill2d.h
- BLI_polyfill2d_beautify.h
+ BLI_polyfill_2d.h
+ BLI_polyfill_2d_beautify.h
BLI_quadric.h
BLI_rand.h
BLI_rect.h
@@ -191,7 +195,6 @@ set(SRC
BLI_sort.h
BLI_sort_utils.h
BLI_stack.h
- BLI_stackdefines.h
BLI_strict_flags.h
BLI_string.h
BLI_string_cursor_utf8.h
@@ -203,9 +206,12 @@ set(SRC
BLI_threads.h
BLI_timecode.h
BLI_utildefines.h
+ BLI_utildefines_iter.h
+ BLI_utildefines_stack.h
+ BLI_utildefines_variadic.h
BLI_uvproject.h
BLI_vfontdata.h
- BLI_voronoi.h
+ BLI_voronoi_2d.h
BLI_voxel.h
BLI_winstuff.h
PIL_time.h
diff --git a/source/blender/blenlib/intern/BLI_args.c b/source/blender/blenlib/intern/BLI_args.c
index 340ae52120c..4eebcd46374 100644
--- a/source/blender/blenlib/intern/BLI_args.c
+++ b/source/blender/blenlib/intern/BLI_args.c
@@ -73,10 +73,10 @@ struct bArgs {
int *passes;
};
-static unsigned int case_strhash(const void *ptr)
+static uint case_strhash(const void *ptr)
{
const char *s = ptr;
- unsigned int i = 0;
+ uint i = 0;
unsigned char c;
while ( (c = tolower(*s++)) )
@@ -85,7 +85,7 @@ static unsigned int case_strhash(const void *ptr)
return i;
}
-static unsigned int keyhash(const void *ptr)
+static uint keyhash(const void *ptr)
{
const bAKey *k = ptr;
return case_strhash(k->arg); /* ^ BLI_ghashutil_inthash((void *)k->pass); */
diff --git a/source/blender/blenlib/intern/BLI_array.c b/source/blender/blenlib/intern/BLI_array.c
index f681d222e69..d16dd36763d 100644
--- a/source/blender/blenlib/intern/BLI_array.c
+++ b/source/blender/blenlib/intern/BLI_array.c
@@ -66,21 +66,23 @@
/**
* This function is only to be called via macros.
*
- * \note The caller must adjust \a arr_count
+ * \note The caller must adjust \a arr_len
*/
-void _bli_array_grow_func(void **arr_p, const void *arr_static,
- const int sizeof_arr_p, const int arr_count, const int num,
- const char *alloc_str)
+void _bli_array_grow_func(
+ void **arr_p, const void *arr_static,
+ const int sizeof_arr_p, const int arr_len, const int num,
+ const char *alloc_str)
{
void *arr = *arr_p;
void *arr_tmp;
- arr_tmp = MEM_mallocN(sizeof_arr_p *
- ((num < arr_count) ?
- (arr_count * 2 + 2) : (arr_count + num)), alloc_str);
+ arr_tmp = MEM_mallocN(
+ sizeof_arr_p *
+ ((num < arr_len) ?
+ (arr_len * 2 + 2) : (arr_len + num)), alloc_str);
if (arr) {
- memcpy(arr_tmp, arr, sizeof_arr_p * arr_count);
+ memcpy(arr_tmp, arr, sizeof_arr_p * arr_len);
if (arr != arr_static) {
MEM_freeN(arr);
@@ -91,6 +93,6 @@ void _bli_array_grow_func(void **arr_p, const void *arr_static,
/* caller must do */
#if 0
- arr_count += num;
+ arr_len += num;
#endif
}
diff --git a/source/blender/blenlib/intern/BLI_dial.c b/source/blender/blenlib/intern/BLI_dial_2d.c
index cfbb52847fd..d31367c5e87 100644
--- a/source/blender/blenlib/intern/BLI_dial.c
+++ b/source/blender/blenlib/intern/BLI_dial_2d.c
@@ -18,7 +18,11 @@
* ***** END GPL LICENSE BLOCK *****
*/
-#include "BLI_dial.h"
+/** \file blender/blenlib/intern/BLI_dial_2d.c
+ * \ingroup bli
+ */
+
+#include "BLI_dial_2d.h"
#include "BLI_math.h"
#include "MEM_guardedalloc.h"
@@ -46,7 +50,7 @@ struct Dial {
};
-Dial *BLI_dial_initialize(float start_position[2], float threshold)
+Dial *BLI_dial_initialize(const float start_position[2], float threshold)
{
Dial *dial = MEM_callocN(sizeof(Dial), "dial");
@@ -56,7 +60,7 @@ Dial *BLI_dial_initialize(float start_position[2], float threshold)
return dial;
}
-float BLI_dial_angle(Dial *dial, float current_position[2])
+float BLI_dial_angle(Dial *dial, const float current_position[2])
{
float current_direction[2];
diff --git a/source/blender/blenlib/intern/BLI_dynstr.c b/source/blender/blenlib/intern/BLI_dynstr.c
index ecd4a6e6b09..bce6614beb5 100644
--- a/source/blender/blenlib/intern/BLI_dynstr.c
+++ b/source/blender/blenlib/intern/BLI_dynstr.c
@@ -35,6 +35,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
+#include "BLI_memarena.h"
#include "BLI_string.h"
#include "BLI_dynstr.h"
@@ -64,6 +65,7 @@ struct DynStrElem {
struct DynStr {
DynStrElem *elems, *last;
int curlen;
+ MemArena *memarena;
};
/***/
@@ -78,11 +80,32 @@ DynStr *BLI_dynstr_new(void)
DynStr *ds = MEM_mallocN(sizeof(*ds), "DynStr");
ds->elems = ds->last = NULL;
ds->curlen = 0;
+ ds->memarena = NULL;
return ds;
}
/**
+ * Create a new DynStr.
+ *
+ * \return Pointer to a new DynStr.
+ */
+DynStr *BLI_dynstr_new_memarena(void)
+{
+ DynStr *ds = MEM_mallocN(sizeof(*ds), "DynStr");
+ ds->elems = ds->last = NULL;
+ ds->curlen = 0;
+ ds->memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
+
+ return ds;
+}
+
+BLI_INLINE void *dynstr_alloc(DynStr *__restrict ds, size_t size)
+{
+ return ds->memarena ? BLI_memarena_alloc(ds->memarena, size) : malloc(size);
+}
+
+/**
* Append a c-string to a DynStr.
*
* \param ds The DynStr to append to.
@@ -90,10 +113,10 @@ DynStr *BLI_dynstr_new(void)
*/
void BLI_dynstr_append(DynStr *__restrict ds, const char *cstr)
{
- DynStrElem *dse = malloc(sizeof(*dse));
+ DynStrElem *dse = dynstr_alloc(ds, sizeof(*dse));
int cstrlen = strlen(cstr);
- dse->str = malloc(cstrlen + 1);
+ dse->str = dynstr_alloc(ds, cstrlen + 1);
memcpy(dse->str, cstr, cstrlen + 1);
dse->next = NULL;
@@ -114,10 +137,10 @@ void BLI_dynstr_append(DynStr *__restrict ds, const char *cstr)
*/
void BLI_dynstr_nappend(DynStr *__restrict ds, const char *cstr, int len)
{
- DynStrElem *dse = malloc(sizeof(*dse));
+ DynStrElem *dse = dynstr_alloc(ds, sizeof(*dse));
int cstrlen = BLI_strnlen(cstr, len);
- dse->str = malloc(cstrlen + 1);
+ dse->str = dynstr_alloc(ds, cstrlen + 1);
memcpy(dse->str, cstr, cstrlen);
dse->str[cstrlen] = '\0';
dse->next = NULL;
@@ -296,22 +319,41 @@ char *BLI_dynstr_get_cstring(DynStr *ds)
}
/**
+ * Clear the DynStr
+ *
+ * \param ds The DynStr to clear.
+ */
+void BLI_dynstr_clear(DynStr *ds)
+{
+ if (ds->memarena) {
+ BLI_memarena_clear(ds->memarena);
+ }
+ else {
+ for (DynStrElem *dse_next, *dse = ds->elems; dse; dse = dse_next) {
+ dse_next = dse->next;
+
+ free(dse->str);
+ free(dse);
+ }
+ }
+
+ ds->elems = ds->last = NULL;
+ ds->curlen = 0;
+}
+
+/**
* Free the DynStr
*
* \param ds The DynStr to free.
*/
void BLI_dynstr_free(DynStr *ds)
{
- DynStrElem *dse;
-
- for (dse = ds->elems; dse; ) {
- DynStrElem *n = dse->next;
-
- free(dse->str);
- free(dse);
-
- dse = n;
+ if (ds->memarena) {
+ BLI_memarena_free(ds->memarena);
}
-
+ else {
+ BLI_dynstr_clear(ds);
+ }
+
MEM_freeN(ds);
}
diff --git a/source/blender/blenlib/intern/BLI_ghash.c b/source/blender/blenlib/intern/BLI_ghash.c
index 944ee18e6b2..ec75c140159 100644
--- a/source/blender/blenlib/intern/BLI_ghash.c
+++ b/source/blender/blenlib/intern/BLI_ghash.c
@@ -43,25 +43,35 @@
#include "BLI_sys_types.h" /* for intptr_t support */
#include "BLI_utildefines.h"
-#include "BLI_hash_mm2a.h"
#include "BLI_mempool.h"
#define GHASH_INTERNAL_API
-#include "BLI_ghash.h"
+#include "BLI_ghash.h" /* own include */
+
+/* keep last */
#include "BLI_strict_flags.h"
+/* -------------------------------------------------------------------- */
+/** \name Structs & Constants
+ * \{ */
+
#define GHASH_USE_MODULO_BUCKETS
-/* Also used by smallhash! */
-const unsigned int hashsizes[] = {
- 5, 11, 17, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209,
- 16411, 32771, 65537, 131101, 262147, 524309, 1048583, 2097169,
- 4194319, 8388617, 16777259, 33554467, 67108879, 134217757,
+/**
+ * Next prime after `2^n` (skipping 2 & 3).
+ *
+ * \note Also used by: `BLI_edgehash` & `BLI_smallhash`.
+ */
+const uint hashsizes[] = {
+ 5, 11, 17, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209,
+ 16411, 32771, 65537, 131101, 262147, 524309, 1048583, 2097169,
+ 4194319, 8388617, 16777259, 33554467, 67108879, 134217757,
268435459
};
#ifdef GHASH_USE_MODULO_BUCKETS
# define GHASH_MAX_SIZE 27
+BLI_STATIC_ASSERT(ARRAY_SIZE(hashsizes) == GHASH_MAX_SIZE, "Invalid 'hashsizes' size");
#else
# define GHASH_BUCKET_BIT_MIN 2
# define GHASH_BUCKET_BIT_MAX 28 /* About 268M of buckets... */
@@ -77,8 +87,6 @@ const unsigned int hashsizes[] = {
#define GHASH_LIMIT_GROW(_nbkt) (((_nbkt) * 3) / 4)
#define GHASH_LIMIT_SHRINK(_nbkt) (((_nbkt) * 3) / 16)
-/***/
-
/* WARNING! Keep in sync with ugly _gh_Entry in header!!! */
typedef struct Entry {
struct Entry *next;
@@ -103,18 +111,23 @@ struct GHash {
Entry **buckets;
struct BLI_mempool *entrypool;
- unsigned int nbuckets;
- unsigned int limit_grow, limit_shrink;
+ uint nbuckets;
+ uint limit_grow, limit_shrink;
#ifdef GHASH_USE_MODULO_BUCKETS
- unsigned int cursize, size_min;
+ uint cursize, size_min;
#else
- unsigned int bucket_mask, bucket_bit, bucket_bit_min;
+ uint bucket_mask, bucket_bit, bucket_bit_min;
#endif
- unsigned int nentries;
- unsigned int flag;
+ uint nentries;
+ uint flag;
};
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Utility API
+ * \{ */
BLI_INLINE void ghash_entry_copy(
GHash *gh_dst, Entry *dst, GHash *gh_src, Entry *src,
@@ -132,16 +145,10 @@ BLI_INLINE void ghash_entry_copy(
}
}
-/* -------------------------------------------------------------------- */
-/* GHash API */
-
-/** \name Internal Utility API
- * \{ */
-
/**
* Get the full hash for a key.
*/
-BLI_INLINE unsigned int ghash_keyhash(GHash *gh, const void *key)
+BLI_INLINE uint ghash_keyhash(GHash *gh, const void *key)
{
return gh->hashfp(key);
}
@@ -149,7 +156,7 @@ BLI_INLINE unsigned int ghash_keyhash(GHash *gh, const void *key)
/**
* Get the full hash for an entry.
*/
-BLI_INLINE unsigned int ghash_entryhash(GHash *gh, const Entry *e)
+BLI_INLINE uint ghash_entryhash(GHash *gh, const Entry *e)
{
return gh->hashfp(e->key);
}
@@ -157,7 +164,7 @@ BLI_INLINE unsigned int ghash_entryhash(GHash *gh, const Entry *e)
/**
* Get the bucket-index for an already-computed full hash.
*/
-BLI_INLINE unsigned int ghash_bucket_index(GHash *gh, const unsigned int hash)
+BLI_INLINE uint ghash_bucket_index(GHash *gh, const uint hash)
{
#ifdef GHASH_USE_MODULO_BUCKETS
return hash % gh->nbuckets;
@@ -169,7 +176,7 @@ BLI_INLINE unsigned int ghash_bucket_index(GHash *gh, const unsigned int hash)
/**
* Find the index of next used bucket, starting from \a curr_bucket (\a gh is assumed non-empty).
*/
-BLI_INLINE unsigned int ghash_find_next_bucket_index(GHash *gh, unsigned int curr_bucket)
+BLI_INLINE uint ghash_find_next_bucket_index(GHash *gh, uint curr_bucket)
{
if (curr_bucket >= gh->nbuckets) {
curr_bucket = 0;
@@ -194,12 +201,12 @@ BLI_INLINE unsigned int ghash_find_next_bucket_index(GHash *gh, unsigned int cur
/**
* Expand buckets to the next size up or down.
*/
-static void ghash_buckets_resize(GHash *gh, const unsigned int nbuckets)
+static void ghash_buckets_resize(GHash *gh, const uint nbuckets)
{
Entry **buckets_old = gh->buckets;
Entry **buckets_new;
- const unsigned int nbuckets_old = gh->nbuckets;
- unsigned int i;
+ const uint nbuckets_old = gh->nbuckets;
+ uint i;
BLI_assert((gh->nbuckets != nbuckets) || !gh->buckets);
// printf("%s: %d -> %d\n", __func__, nbuckets_old, nbuckets);
@@ -261,9 +268,9 @@ static void ghash_buckets_resize(GHash *gh, const unsigned int nbuckets)
* or small enough to require less buckets, and resize \a gh accordingly.
*/
static void ghash_buckets_expand(
- GHash *gh, const unsigned int nentries, const bool user_defined)
+ GHash *gh, const uint nentries, const bool user_defined)
{
- unsigned int new_nbuckets;
+ uint new_nbuckets;
if (LIKELY(gh->buckets && (nentries < gh->limit_grow))) {
return;
@@ -305,9 +312,9 @@ static void ghash_buckets_expand(
}
static void ghash_buckets_contract(
- GHash *gh, const unsigned int nentries, const bool user_defined, const bool force_shrink)
+ GHash *gh, const uint nentries, const bool user_defined, const bool force_shrink)
{
- unsigned int new_nbuckets;
+ uint new_nbuckets;
if (!(force_shrink || (gh->flag & GHASH_FLAG_ALLOW_SHRINK))) {
return;
@@ -355,7 +362,7 @@ static void ghash_buckets_contract(
/**
* Clear and reset \a gh buckets, reserve again buckets for given number of entries.
*/
-BLI_INLINE void ghash_buckets_reset(GHash *gh, const unsigned int nentries)
+BLI_INLINE void ghash_buckets_reset(GHash *gh, const uint nentries)
{
MEM_SAFE_FREE(gh->buckets);
@@ -383,7 +390,7 @@ BLI_INLINE void ghash_buckets_reset(GHash *gh, const unsigned int nentries)
* Takes hash and bucket_index arguments to avoid calling #ghash_keyhash and #ghash_bucket_index multiple times.
*/
BLI_INLINE Entry *ghash_lookup_entry_ex(
- GHash *gh, const void *key, const unsigned int bucket_index)
+ GHash *gh, const void *key, const uint bucket_index)
{
Entry *e;
/* If we do not store GHash, not worth computing it for each entry here!
@@ -404,7 +411,7 @@ BLI_INLINE Entry *ghash_lookup_entry_ex(
*/
BLI_INLINE Entry *ghash_lookup_entry_prev_ex(
GHash *gh, const void *key,
- Entry **r_e_prev, const unsigned int bucket_index)
+ Entry **r_e_prev, const uint bucket_index)
{
/* If we do not store GHash, not worth computing it for each entry here!
* Typically, comparison function will be quicker, and since it's needed in the end anyway... */
@@ -424,13 +431,14 @@ BLI_INLINE Entry *ghash_lookup_entry_prev_ex(
*/
BLI_INLINE Entry *ghash_lookup_entry(GHash *gh, const void *key)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
return ghash_lookup_entry_ex(gh, key, bucket_index);
}
-static GHash *ghash_new(GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
- const unsigned int nentries_reserve, const unsigned int flag)
+static GHash *ghash_new(
+ GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
+ const uint nentries_reserve, const uint flag)
{
GHash *gh = MEM_mallocN(sizeof(*gh), info);
@@ -451,7 +459,7 @@ static GHash *ghash_new(GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
* Takes hash and bucket_index arguments to avoid calling #ghash_keyhash and #ghash_bucket_index multiple times.
*/
BLI_INLINE void ghash_insert_ex(
- GHash *gh, void *key, void *val, const unsigned int bucket_index)
+ GHash *gh, void *key, void *val, const uint bucket_index)
{
GHashEntry *e = BLI_mempool_alloc(gh->entrypool);
@@ -470,7 +478,7 @@ BLI_INLINE void ghash_insert_ex(
* Insert function that takes a pre-allocated entry.
*/
BLI_INLINE void ghash_insert_ex_keyonly_entry(
- GHash *gh, void *key, const unsigned int bucket_index,
+ GHash *gh, void *key, const uint bucket_index,
Entry *e)
{
BLI_assert((gh->flag & GHASH_FLAG_ALLOW_DUPES) || (BLI_ghash_haskey(gh, key) == 0));
@@ -486,7 +494,7 @@ BLI_INLINE void ghash_insert_ex_keyonly_entry(
* Insert function that doesn't set the value (use for GSet)
*/
BLI_INLINE void ghash_insert_ex_keyonly(
- GHash *gh, void *key, const unsigned int bucket_index)
+ GHash *gh, void *key, const uint bucket_index)
{
Entry *e = BLI_mempool_alloc(gh->entrypool);
@@ -502,8 +510,8 @@ BLI_INLINE void ghash_insert_ex_keyonly(
BLI_INLINE void ghash_insert(GHash *gh, void *key, void *val)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
ghash_insert_ex(gh, key, val, bucket_index);
}
@@ -512,8 +520,8 @@ BLI_INLINE bool ghash_insert_safe(
GHash *gh, void *key, void *val, const bool override,
GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
GHashEntry *e = (GHashEntry *)ghash_lookup_entry_ex(gh, key, bucket_index);
BLI_assert(!(gh->flag & GHASH_FLAG_IS_GSET));
@@ -541,8 +549,8 @@ BLI_INLINE bool ghash_insert_safe_keyonly(
GHash *gh, void *key, const bool override,
GHashKeyFreeFP keyfreefp)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
Entry *e = ghash_lookup_entry_ex(gh, key, bucket_index);
BLI_assert((gh->flag & GHASH_FLAG_IS_GSET) != 0);
@@ -568,7 +576,7 @@ BLI_INLINE bool ghash_insert_safe_keyonly(
static Entry *ghash_remove_ex(
GHash *gh, const void *key,
GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp,
- const unsigned int bucket_index)
+ const uint bucket_index)
{
Entry *e_prev;
Entry *e = ghash_lookup_entry_prev_ex(gh, key, &e_prev, bucket_index);
@@ -601,7 +609,7 @@ static Entry *ghash_remove_ex(
*/
static Entry *ghash_pop(GHash *gh, GHashIterState *state)
{
- unsigned int curr_bucket = state->curr_bucket;
+ uint curr_bucket = state->curr_bucket;
if (gh->nentries == 0) {
return NULL;
}
@@ -626,7 +634,7 @@ static void ghash_free_cb(
GHash *gh,
GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
{
- unsigned int i;
+ uint i;
BLI_assert(keyfreefp || valfreefp);
BLI_assert(!valfreefp || !(gh->flag & GHASH_FLAG_IS_GSET));
@@ -651,9 +659,9 @@ static void ghash_free_cb(
static GHash *ghash_copy(GHash *gh, GHashKeyCopyFP keycopyfp, GHashValCopyFP valcopyfp)
{
GHash *gh_new;
- unsigned int i;
+ uint i;
/* This allows us to be sure to get the same number of buckets in gh_new as in ghash. */
- const unsigned int reserve_nentries_new = MAX2(GHASH_LIMIT_GROW(gh->nbuckets) - 1, gh->nentries);
+ const uint reserve_nentries_new = MAX2(GHASH_LIMIT_GROW(gh->nbuckets) - 1, gh->nentries);
BLI_assert(!valcopyfp || !(gh->flag & GHASH_FLAG_IS_GSET));
@@ -685,8 +693,8 @@ static GHash *ghash_copy(GHash *gh, GHashKeyCopyFP keycopyfp, GHashValCopyFP val
/** \} */
-
-/** \name Public API
+/* -------------------------------------------------------------------- */
+/** \name GHash Public API
* \{ */
/**
@@ -699,8 +707,9 @@ static GHash *ghash_copy(GHash *gh, GHashKeyCopyFP keycopyfp, GHashValCopyFP val
* Use this to avoid resizing buckets if the size is known or can be closely approximated.
* \return An empty GHash.
*/
-GHash *BLI_ghash_new_ex(GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
- const unsigned int nentries_reserve)
+GHash *BLI_ghash_new_ex(
+ GHashHashFP hashfp, GHashCmpFP cmpfp, const char *info,
+ const uint nentries_reserve)
{
return ghash_new(hashfp, cmpfp, info, nentries_reserve, 0);
}
@@ -724,7 +733,7 @@ GHash *BLI_ghash_copy(GHash *gh, GHashKeyCopyFP keycopyfp, GHashValCopyFP valcop
/**
* Reserve given amount of entries (resize \a gh accordingly if needed).
*/
-void BLI_ghash_reserve(GHash *gh, const unsigned int nentries_reserve)
+void BLI_ghash_reserve(GHash *gh, const uint nentries_reserve)
{
ghash_buckets_expand(gh, nentries_reserve, true);
ghash_buckets_contract(gh, nentries_reserve, true, false);
@@ -733,7 +742,7 @@ void BLI_ghash_reserve(GHash *gh, const unsigned int nentries_reserve)
/**
* \return size of the GHash.
*/
-unsigned int BLI_ghash_size(GHash *gh)
+uint BLI_ghash_len(GHash *gh)
{
return gh->nentries;
}
@@ -763,6 +772,28 @@ bool BLI_ghash_reinsert(GHash *gh, void *key, void *val, GHashKeyFreeFP keyfreef
}
/**
+ * Replaces the key of an item in the \a gh.
+ *
+ * Use when a key is re-allocated or it's memory location is changed.
+ *
+ * \returns The previous key or NULL if not found, the caller may free if it's needed.
+ */
+void *BLI_ghash_replace_key(GHash *gh, void *key)
+{
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
+ GHashEntry *e = (GHashEntry *)ghash_lookup_entry_ex(gh, key, bucket_index);
+ if (e != NULL) {
+ void *key_prev = e->e.key;
+ e->e.key = key;
+ return key_prev;
+ }
+ else {
+ return NULL;
+ }
+}
+
+/**
* Lookup the value of \a key in \a gh.
*
* \param key The key to lookup.
@@ -821,8 +852,8 @@ void **BLI_ghash_lookup_p(GHash *gh, const void *key)
*/
bool BLI_ghash_ensure_p(GHash *gh, void *key, void ***r_val)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
GHashEntry *e = (GHashEntry *)ghash_lookup_entry_ex(gh, key, bucket_index);
const bool haskey = (e != NULL);
@@ -844,8 +875,8 @@ bool BLI_ghash_ensure_p(GHash *gh, void *key, void ***r_val)
bool BLI_ghash_ensure_p_ex(
GHash *gh, const void *key, void ***r_key, void ***r_val)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
GHashEntry *e = (GHashEntry *)ghash_lookup_entry_ex(gh, key, bucket_index);
const bool haskey = (e != NULL);
@@ -871,8 +902,8 @@ bool BLI_ghash_ensure_p_ex(
*/
bool BLI_ghash_remove(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
Entry *e = ghash_remove_ex(gh, key, keyfreefp, valfreefp, bucket_index);
if (e) {
BLI_mempool_free(gh->entrypool, e);
@@ -894,8 +925,8 @@ bool BLI_ghash_remove(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp, GHas
*/
void *BLI_ghash_popkey(GHash *gh, const void *key, GHashKeyFreeFP keyfreefp)
{
- const unsigned int hash = ghash_keyhash(gh, key);
- const unsigned int bucket_index = ghash_bucket_index(gh, hash);
+ const uint hash = ghash_keyhash(gh, key);
+ const uint bucket_index = ghash_bucket_index(gh, hash);
GHashEntry *e = (GHashEntry *)ghash_remove_ex(gh, key, keyfreefp, NULL, bucket_index);
BLI_assert(!(gh->flag & GHASH_FLAG_IS_GSET));
if (e) {
@@ -952,8 +983,9 @@ bool BLI_ghash_pop(
* \param valfreefp Optional callback to free the value.
* \param nentries_reserve Optionally reserve the number of members that the hash will hold.
*/
-void BLI_ghash_clear_ex(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp,
- const unsigned int nentries_reserve)
+void BLI_ghash_clear_ex(
+ GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp,
+ const uint nentries_reserve)
{
if (keyfreefp || valfreefp)
ghash_free_cb(gh, keyfreefp, valfreefp);
@@ -979,7 +1011,7 @@ void BLI_ghash_clear(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfree
*/
void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreefp)
{
- BLI_assert((int)gh->nentries == BLI_mempool_count(gh->entrypool));
+ BLI_assert((int)gh->nentries == BLI_mempool_len(gh->entrypool));
if (keyfreefp || valfreefp)
ghash_free_cb(gh, keyfreefp, valfreefp);
@@ -991,7 +1023,7 @@ void BLI_ghash_free(GHash *gh, GHashKeyFreeFP keyfreefp, GHashValFreeFP valfreef
/**
* Sets a GHash flag.
*/
-void BLI_ghash_flag_set(GHash *gh, unsigned int flag)
+void BLI_ghash_flag_set(GHash *gh, uint flag)
{
gh->flag |= flag;
}
@@ -999,24 +1031,21 @@ void BLI_ghash_flag_set(GHash *gh, unsigned int flag)
/**
* Clear a GHash flag.
*/
-void BLI_ghash_flag_clear(GHash *gh, unsigned int flag)
+void BLI_ghash_flag_clear(GHash *gh, uint flag)
{
gh->flag &= ~flag;
}
/** \} */
-
/* -------------------------------------------------------------------- */
-/* GHash Iterator API */
-
-/** \name Iterator API
+/** \name GHash Iterator API
* \{ */
/**
* Create a new 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.
+ * BLI_ghash_len(gh) times before becoming done.
*
* \param gh The GHash to iterate over.
* \return Pointer to a new DynStr.
@@ -1031,7 +1060,7 @@ 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.
+ * step exactly BLI_ghash_len(gh) times before becoming done.
*
* \param ghi The GHashIterator to initialize.
* \param gh The GHash to iterate over.
@@ -1132,224 +1161,14 @@ bool BLI_ghashIterator_done(GHashIterator *ghi)
/** \} */
-
-/** \name Generic Key Hash & Comparison Functions
- * \{ */
-
-/***/
-
-#if 0
-/* works but slower */
-unsigned int BLI_ghashutil_ptrhash(const void *key)
-{
- return (unsigned int)(intptr_t)key;
-}
-#else
-/* based python3.3's pointer hashing function */
-unsigned int BLI_ghashutil_ptrhash(const void *key)
-{
- size_t y = (size_t)key;
- /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
- * excessive hash collisions for dicts and sets */
- y = (y >> 4) | (y << (8 * sizeof(void *) - 4));
- return (unsigned int)y;
-}
-#endif
-bool BLI_ghashutil_ptrcmp(const void *a, const void *b)
-{
- return (a != b);
-}
-
-unsigned int BLI_ghashutil_uinthash_v4(const unsigned int key[4])
-{
- unsigned int hash;
- hash = key[0];
- hash *= 37;
- hash += key[1];
- hash *= 37;
- hash += key[2];
- hash *= 37;
- hash += key[3];
- return hash;
-}
-unsigned int BLI_ghashutil_uinthash_v4_murmur(const unsigned int key[4])
-{
- return BLI_hash_mm2((const unsigned char *)key, sizeof(int) * 4 /* sizeof(key) */, 0);
-}
-
-bool BLI_ghashutil_uinthash_v4_cmp(const void *a, const void *b)
-{
- return (memcmp(a, b, sizeof(unsigned int[4])) != 0);
-}
-
-unsigned int BLI_ghashutil_uinthash(unsigned int key)
-{
- key += ~(key << 16);
- key ^= (key >> 5);
- key += (key << 3);
- key ^= (key >> 13);
- key += ~(key << 9);
- key ^= (key >> 17);
-
- return key;
-}
-
-unsigned int BLI_ghashutil_inthash_p(const void *ptr)
-{
- uintptr_t key = (uintptr_t)ptr;
-
- key += ~(key << 16);
- key ^= (key >> 5);
- key += (key << 3);
- key ^= (key >> 13);
- key += ~(key << 9);
- key ^= (key >> 17);
-
- return (unsigned int)(key & 0xffffffff);
-}
-
-unsigned int BLI_ghashutil_inthash_p_murmur(const void *ptr)
-{
- uintptr_t key = (uintptr_t)ptr;
-
- return BLI_hash_mm2((const unsigned char *)&key, sizeof(key), 0);
-}
-
-unsigned int BLI_ghashutil_inthash_p_simple(const void *ptr)
-{
- return GET_UINT_FROM_POINTER(ptr);
-}
-
-bool BLI_ghashutil_intcmp(const void *a, const void *b)
-{
- return (a != b);
-}
-
-/**
- * This function implements the widely used "djb" hash apparently posted
- * by Daniel Bernstein to comp.lang.c some time ago. The 32 bit
- * unsigned hash value starts at 5381 and for each byte 'c' in the
- * string, is updated: ``hash = hash * 33 + c``. This
- * function uses the signed value of each byte.
- *
- * note: this is the same hash method that glib 2.34.0 uses.
- */
-unsigned int BLI_ghashutil_strhash_n(const char *key, size_t n)
-{
- const signed char *p;
- unsigned int h = 5381;
-
- for (p = (const signed char *)key; n-- && *p != '\0'; p++) {
- h = (h << 5) + h + (unsigned int)*p;
- }
-
- return h;
-}
-unsigned int BLI_ghashutil_strhash_p(const void *ptr)
-{
- const signed char *p;
- unsigned int h = 5381;
-
- for (p = ptr; *p != '\0'; p++) {
- h = (h << 5) + h + (unsigned int)*p;
- }
-
- return h;
-}
-unsigned int BLI_ghashutil_strhash_p_murmur(const void *ptr)
-{
- const unsigned char *key = ptr;
-
- return BLI_hash_mm2(key, strlen((const char *)key) + 1, 0);
-}
-bool BLI_ghashutil_strcmp(const void *a, const void *b)
-{
- return (a == b) ? false : !STREQ(a, b);
-}
-
-GHashPair *BLI_ghashutil_pairalloc(const void *first, const void *second)
-{
- GHashPair *pair = MEM_mallocN(sizeof(GHashPair), "GHashPair");
- pair->first = first;
- pair->second = second;
- return pair;
-}
-
-unsigned int BLI_ghashutil_pairhash(const void *ptr)
-{
- const GHashPair *pair = ptr;
- unsigned int hash = BLI_ghashutil_ptrhash(pair->first);
- return hash ^ BLI_ghashutil_ptrhash(pair->second);
-}
-
-bool BLI_ghashutil_paircmp(const void *a, const void *b)
-{
- const GHashPair *A = a;
- const GHashPair *B = b;
-
- return (BLI_ghashutil_ptrcmp(A->first, B->first) ||
- BLI_ghashutil_ptrcmp(A->second, B->second));
-}
-
-void BLI_ghashutil_pairfree(void *ptr)
-{
- MEM_freeN(ptr);
-}
-
-/** \} */
-
-
-/** \name Convenience GHash Creation Functions
- * \{ */
-
-GHash *BLI_ghash_ptr_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_ghash_new_ex(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, info, nentries_reserve);
-}
-GHash *BLI_ghash_ptr_new(const char *info)
-{
- return BLI_ghash_ptr_new_ex(info, 0);
-}
-
-GHash *BLI_ghash_str_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_ghash_new_ex(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, info, nentries_reserve);
-}
-GHash *BLI_ghash_str_new(const char *info)
-{
- return BLI_ghash_str_new_ex(info, 0);
-}
-
-GHash *BLI_ghash_int_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_ghash_new_ex(BLI_ghashutil_inthash_p, BLI_ghashutil_intcmp, info, nentries_reserve);
-}
-GHash *BLI_ghash_int_new(const char *info)
-{
- return BLI_ghash_int_new_ex(info, 0);
-}
-
-GHash *BLI_ghash_pair_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_ghash_new_ex(BLI_ghashutil_pairhash, BLI_ghashutil_paircmp, info, nentries_reserve);
-}
-GHash *BLI_ghash_pair_new(const char *info)
-{
- return BLI_ghash_pair_new_ex(info, 0);
-}
-
-/** \} */
-
-
/* -------------------------------------------------------------------- */
-/* GSet API */
-
-/* Use ghash API to give 'set' functionality */
-
-/** \name GSet Functions
+/** \name GSet Public API
+ *
+ * Use ghash API to give 'set' functionality
* \{ */
-GSet *BLI_gset_new_ex(GSetHashFP hashfp, GSetCmpFP cmpfp, const char *info,
- const unsigned int nentries_reserve)
+GSet *BLI_gset_new_ex(
+ GSetHashFP hashfp, GSetCmpFP cmpfp, const char *info,
+ const uint nentries_reserve)
{
return (GSet *)ghash_new(hashfp, cmpfp, info, nentries_reserve, GHASH_FLAG_IS_GSET);
}
@@ -1367,7 +1186,7 @@ GSet *BLI_gset_copy(GSet *gs, GHashKeyCopyFP keycopyfp)
return (GSet *)ghash_copy((GHash *)gs, keycopyfp, NULL);
}
-unsigned int BLI_gset_size(GSet *gs)
+uint BLI_gset_len(GSet *gs)
{
return ((GHash *)gs)->nentries;
}
@@ -1378,8 +1197,8 @@ unsigned int BLI_gset_size(GSet *gs)
*/
void BLI_gset_insert(GSet *gs, void *key)
{
- const unsigned int hash = ghash_keyhash((GHash *)gs, key);
- const unsigned int bucket_index = ghash_bucket_index((GHash *)gs, hash);
+ const uint hash = ghash_keyhash((GHash *)gs, key);
+ const uint bucket_index = ghash_bucket_index((GHash *)gs, hash);
ghash_insert_ex_keyonly((GHash *)gs, key, bucket_index);
}
@@ -1402,8 +1221,8 @@ bool BLI_gset_add(GSet *gs, void *key)
*/
bool BLI_gset_ensure_p_ex(GSet *gs, const void *key, void ***r_key)
{
- const unsigned int hash = ghash_keyhash((GHash *)gs, key);
- const unsigned int bucket_index = ghash_bucket_index((GHash *)gs, hash);
+ const uint hash = ghash_keyhash((GHash *)gs, key);
+ const uint bucket_index = ghash_bucket_index((GHash *)gs, hash);
GSetEntry *e = (GSetEntry *)ghash_lookup_entry_ex((GHash *)gs, key, bucket_index);
const bool haskey = (e != NULL);
@@ -1429,6 +1248,18 @@ bool BLI_gset_reinsert(GSet *gs, void *key, GSetKeyFreeFP keyfreefp)
return ghash_insert_safe_keyonly((GHash *)gs, key, true, keyfreefp);
}
+/**
+ * Replaces the key to the set if it's found.
+ * Matching #BLI_ghash_replace_key
+ *
+ * \returns The old key or NULL if not found.
+ */
+void *BLI_gset_replace_key(GSet *gs, void *key)
+{
+ return BLI_ghash_replace_key((GHash *)gs, key);
+}
+
+
bool BLI_gset_remove(GSet *gs, const void *key, GSetKeyFreeFP keyfreefp)
{
return BLI_ghash_remove((GHash *)gs, key, keyfreefp, NULL);
@@ -1465,11 +1296,13 @@ bool BLI_gset_pop(
}
}
-void BLI_gset_clear_ex(GSet *gs, GSetKeyFreeFP keyfreefp,
- const unsigned int nentries_reserve)
+void BLI_gset_clear_ex(
+ GSet *gs, GSetKeyFreeFP keyfreefp,
+ const uint nentries_reserve)
{
- BLI_ghash_clear_ex((GHash *)gs, keyfreefp, NULL,
- nentries_reserve);
+ BLI_ghash_clear_ex(
+ (GHash *)gs, keyfreefp, NULL,
+ nentries_reserve);
}
void BLI_gset_clear(GSet *gs, GSetKeyFreeFP keyfreefp)
@@ -1482,52 +1315,56 @@ void BLI_gset_free(GSet *gs, GSetKeyFreeFP keyfreefp)
BLI_ghash_free((GHash *)gs, keyfreefp, NULL);
}
-void BLI_gset_flag_set(GSet *gs, unsigned int flag)
+void BLI_gset_flag_set(GSet *gs, uint flag)
{
((GHash *)gs)->flag |= flag;
}
-void BLI_gset_flag_clear(GSet *gs, unsigned int flag)
+void BLI_gset_flag_clear(GSet *gs, uint flag)
{
((GHash *)gs)->flag &= ~flag;
}
/** \} */
-
-/** \name Convenience GSet Creation Functions
+/* -------------------------------------------------------------------- */
+/** \name GSet Combined Key/Value Usage
+ *
+ * \note Not typical ``set`` use, only use when the pointer identity matters.
+ * This can be useful when the key references data stored outside the GSet.
* \{ */
-GSet *BLI_gset_ptr_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_gset_new_ex(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, info, nentries_reserve);
-}
-GSet *BLI_gset_ptr_new(const char *info)
-{
- return BLI_gset_ptr_new_ex(info, 0);
-}
-
-GSet *BLI_gset_str_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_gset_new_ex(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, info, nentries_reserve);
-}
-GSet *BLI_gset_str_new(const char *info)
+/**
+ * Returns the pointer to the key if it's found.
+ */
+void *BLI_gset_lookup(GSet *gs, const void *key)
{
- return BLI_gset_str_new_ex(info, 0);
+ Entry *e = ghash_lookup_entry((GHash *)gs, key);
+ return e ? e->key : NULL;
}
-GSet *BLI_gset_pair_new_ex(const char *info, const unsigned int nentries_reserve)
-{
- return BLI_gset_new_ex(BLI_ghashutil_pairhash, BLI_ghashutil_paircmp, info, nentries_reserve);
-}
-GSet *BLI_gset_pair_new(const char *info)
+/**
+ * Returns the pointer to the key if it's found, removing it from the GSet.
+ * \note Caller must handle freeing.
+ */
+void *BLI_gset_pop_key(GSet *gs, const void *key)
{
- return BLI_gset_pair_new_ex(info, 0);
+ const uint hash = ghash_keyhash((GHash *)gs, key);
+ const uint bucket_index = ghash_bucket_index((GHash *)gs, hash);
+ Entry *e = ghash_remove_ex((GHash *)gs, key, NULL, NULL, bucket_index);
+ if (e) {
+ void *key_ret = e->key;
+ BLI_mempool_free(((GHash *)gs)->entrypool, e);
+ return key_ret;
+ }
+ else {
+ return NULL;
+ }
}
/** \} */
-
+/* -------------------------------------------------------------------- */
/** \name Debugging & Introspection
* \{ */
@@ -1536,13 +1373,13 @@ GSet *BLI_gset_pair_new(const char *info)
/**
* \return number of buckets in the GHash.
*/
-int BLI_ghash_buckets_size(GHash *gh)
+int BLI_ghash_buckets_len(GHash *gh)
{
return (int)gh->nbuckets;
}
-int BLI_gset_buckets_size(GSet *gs)
+int BLI_gset_buckets_len(GSet *gs)
{
- return BLI_ghash_buckets_size((GHash *)gs);
+ return BLI_ghash_buckets_len((GHash *)gs);
}
/**
@@ -1556,7 +1393,7 @@ double BLI_ghash_calc_quality_ex(
double *r_prop_empty_buckets, double *r_prop_overloaded_buckets, int *r_biggest_bucket)
{
double mean;
- unsigned int i;
+ uint i;
if (gh->nentries == 0) {
if (r_load) {
@@ -1639,8 +1476,9 @@ double BLI_gset_calc_quality_ex(
GSet *gs, double *r_load, double *r_variance,
double *r_prop_empty_buckets, double *r_prop_overloaded_buckets, int *r_biggest_bucket)
{
- return BLI_ghash_calc_quality_ex((GHash *)gs, r_load, r_variance,
- r_prop_empty_buckets, r_prop_overloaded_buckets, r_biggest_bucket);
+ return BLI_ghash_calc_quality_ex(
+ (GHash *)gs, r_load, r_variance,
+ r_prop_empty_buckets, r_prop_overloaded_buckets, r_biggest_bucket);
}
double BLI_ghash_calc_quality(GHash *gh)
diff --git a/source/blender/blenlib/intern/BLI_ghash_utils.c b/source/blender/blenlib/intern/BLI_ghash_utils.c
new file mode 100644
index 00000000000..6554ee7c92f
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_ghash_utils.c
@@ -0,0 +1,288 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 *****
+ */
+
+/** \file blender/blenlib/intern/BLI_ghash_utils.c
+ * \ingroup bli
+ *
+ * Helper functions and implementations of standard data types for #GHash
+ * (not it's implementation).
+ */
+
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_hash_mm2a.h"
+#include "BLI_ghash.h" /* own include */
+
+/* keep last */
+#include "BLI_strict_flags.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Generic Key Hash & Comparison Functions
+ * \{ */
+
+#if 0
+/* works but slower */
+uint BLI_ghashutil_ptrhash(const void *key)
+{
+ return (uint)(intptr_t)key;
+}
+#else
+/* based python3.3's pointer hashing function */
+uint BLI_ghashutil_ptrhash(const void *key)
+{
+ size_t y = (size_t)key;
+ /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
+ * excessive hash collisions for dicts and sets */
+ y = (y >> 4) | (y << (8 * sizeof(void *) - 4));
+ return (uint)y;
+}
+#endif
+bool BLI_ghashutil_ptrcmp(const void *a, const void *b)
+{
+ return (a != b);
+}
+
+uint BLI_ghashutil_uinthash_v4(const uint key[4])
+{
+ uint hash;
+ hash = key[0];
+ hash *= 37;
+ hash += key[1];
+ hash *= 37;
+ hash += key[2];
+ hash *= 37;
+ hash += key[3];
+ return hash;
+}
+uint BLI_ghashutil_uinthash_v4_murmur(const uint key[4])
+{
+ return BLI_hash_mm2((const unsigned char *)key, sizeof(int) * 4 /* sizeof(key) */, 0);
+}
+
+bool BLI_ghashutil_uinthash_v4_cmp(const void *a, const void *b)
+{
+ return (memcmp(a, b, sizeof(uint[4])) != 0);
+}
+
+uint BLI_ghashutil_uinthash(uint key)
+{
+ key += ~(key << 16);
+ key ^= (key >> 5);
+ key += (key << 3);
+ key ^= (key >> 13);
+ key += ~(key << 9);
+ key ^= (key >> 17);
+
+ return key;
+}
+
+uint BLI_ghashutil_inthash_p(const void *ptr)
+{
+ uintptr_t key = (uintptr_t)ptr;
+
+ key += ~(key << 16);
+ key ^= (key >> 5);
+ key += (key << 3);
+ key ^= (key >> 13);
+ key += ~(key << 9);
+ key ^= (key >> 17);
+
+ return (uint)(key & 0xffffffff);
+}
+
+uint BLI_ghashutil_inthash_p_murmur(const void *ptr)
+{
+ uintptr_t key = (uintptr_t)ptr;
+
+ return BLI_hash_mm2((const unsigned char *)&key, sizeof(key), 0);
+}
+
+uint BLI_ghashutil_inthash_p_simple(const void *ptr)
+{
+ return GET_UINT_FROM_POINTER(ptr);
+}
+
+bool BLI_ghashutil_intcmp(const void *a, const void *b)
+{
+ return (a != b);
+}
+
+size_t BLI_ghashutil_combine_hash(size_t hash_a, size_t hash_b)
+{
+ return hash_a ^ (hash_b + 0x9e3779b9 + (hash_a << 6) + (hash_a >> 2));
+}
+
+/**
+ * This function implements the widely used "djb" hash apparently posted
+ * by Daniel Bernstein to comp.lang.c some time ago. The 32 bit
+ * unsigned hash value starts at 5381 and for each byte 'c' in the
+ * string, is updated: ``hash = hash * 33 + c``. This
+ * function uses the signed value of each byte.
+ *
+ * note: this is the same hash method that glib 2.34.0 uses.
+ */
+uint BLI_ghashutil_strhash_n(const char *key, size_t n)
+{
+ const signed char *p;
+ uint h = 5381;
+
+ for (p = (const signed char *)key; n-- && *p != '\0'; p++) {
+ h = (uint)((h << 5) + h) + (uint)*p;
+ }
+
+ return h;
+}
+uint BLI_ghashutil_strhash_p(const void *ptr)
+{
+ const signed char *p;
+ uint h = 5381;
+
+ for (p = ptr; *p != '\0'; p++) {
+ h = (uint)((h << 5) + h) + (uint)*p;
+ }
+
+ return h;
+}
+uint BLI_ghashutil_strhash_p_murmur(const void *ptr)
+{
+ const unsigned char *key = ptr;
+
+ return BLI_hash_mm2(key, strlen((const char *)key) + 1, 0);
+}
+bool BLI_ghashutil_strcmp(const void *a, const void *b)
+{
+ return (a == b) ? false : !STREQ(a, b);
+}
+
+GHashPair *BLI_ghashutil_pairalloc(const void *first, const void *second)
+{
+ GHashPair *pair = MEM_mallocN(sizeof(GHashPair), "GHashPair");
+ pair->first = first;
+ pair->second = second;
+ return pair;
+}
+
+uint BLI_ghashutil_pairhash(const void *ptr)
+{
+ const GHashPair *pair = ptr;
+ uint hash = BLI_ghashutil_ptrhash(pair->first);
+ return hash ^ BLI_ghashutil_ptrhash(pair->second);
+}
+
+bool BLI_ghashutil_paircmp(const void *a, const void *b)
+{
+ const GHashPair *A = a;
+ const GHashPair *B = b;
+
+ return (BLI_ghashutil_ptrcmp(A->first, B->first) ||
+ BLI_ghashutil_ptrcmp(A->second, B->second));
+}
+
+void BLI_ghashutil_pairfree(void *ptr)
+{
+ MEM_freeN(ptr);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Convenience GHash Creation Functions
+ * \{ */
+
+GHash *BLI_ghash_ptr_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_ghash_new_ex(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, info, nentries_reserve);
+}
+GHash *BLI_ghash_ptr_new(const char *info)
+{
+ return BLI_ghash_ptr_new_ex(info, 0);
+}
+
+GHash *BLI_ghash_str_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_ghash_new_ex(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, info, nentries_reserve);
+}
+GHash *BLI_ghash_str_new(const char *info)
+{
+ return BLI_ghash_str_new_ex(info, 0);
+}
+
+GHash *BLI_ghash_int_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_ghash_new_ex(BLI_ghashutil_inthash_p, BLI_ghashutil_intcmp, info, nentries_reserve);
+}
+GHash *BLI_ghash_int_new(const char *info)
+{
+ return BLI_ghash_int_new_ex(info, 0);
+}
+
+GHash *BLI_ghash_pair_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_ghash_new_ex(BLI_ghashutil_pairhash, BLI_ghashutil_paircmp, info, nentries_reserve);
+}
+GHash *BLI_ghash_pair_new(const char *info)
+{
+ return BLI_ghash_pair_new_ex(info, 0);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Convenience GSet Creation Functions
+ * \{ */
+
+GSet *BLI_gset_ptr_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_gset_new_ex(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, info, nentries_reserve);
+}
+GSet *BLI_gset_ptr_new(const char *info)
+{
+ return BLI_gset_ptr_new_ex(info, 0);
+}
+
+GSet *BLI_gset_str_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_gset_new_ex(BLI_ghashutil_strhash_p, BLI_ghashutil_strcmp, info, nentries_reserve);
+}
+GSet *BLI_gset_str_new(const char *info)
+{
+ return BLI_gset_str_new_ex(info, 0);
+}
+
+GSet *BLI_gset_pair_new_ex(const char *info, const uint nentries_reserve)
+{
+ return BLI_gset_new_ex(BLI_ghashutil_pairhash, BLI_ghashutil_paircmp, info, nentries_reserve);
+}
+GSet *BLI_gset_pair_new(const char *info)
+{
+ return BLI_gset_pair_new_ex(info, 0);
+}
+
+/** \} */
diff --git a/source/blender/blenlib/intern/BLI_heap.c b/source/blender/blenlib/intern/BLI_heap.c
index d7fd1caa8da..0c71e75e40f 100644
--- a/source/blender/blenlib/intern/BLI_heap.c
+++ b/source/blender/blenlib/intern/BLI_heap.c
@@ -23,7 +23,7 @@
/** \file blender/blenlib/intern/BLI_heap.c
* \ingroup bli
*
- * A heap / priority queue ADT.
+ * A min-heap / priority queue ADT.
*/
#include <stdlib.h>
@@ -38,15 +38,15 @@
/***/
struct HeapNode {
- void *ptr;
- float value;
- unsigned int index;
+ void *ptr;
+ float value;
+ uint index;
};
struct HeapNode_Chunk {
struct HeapNode_Chunk *prev;
- unsigned int size;
- unsigned int bufsize;
+ uint size;
+ uint bufsize;
struct HeapNode buf[0];
};
@@ -58,11 +58,11 @@ struct HeapNode_Chunk {
* \note keep type in sync with tot_nodes in heap_node_alloc_chunk.
*/
#define HEAP_CHUNK_DEFAULT_NUM \
- ((unsigned int)((MEM_SIZE_OPTIMAL((1 << 16) - sizeof(struct HeapNode_Chunk))) / sizeof(HeapNode)))
+ ((uint)((MEM_SIZE_OPTIMAL((1 << 16) - sizeof(struct HeapNode_Chunk))) / sizeof(HeapNode)))
struct Heap {
- unsigned int size;
- unsigned int bufsize;
+ uint size;
+ uint bufsize;
HeapNode **tree;
struct {
@@ -85,16 +85,16 @@ struct Heap {
#define HEAP_EQUALS(a, b) ((a)->value == (b)->value)
#endif
-BLI_INLINE void heap_swap(Heap *heap, const unsigned int i, const unsigned int j)
+BLI_INLINE void heap_swap(Heap *heap, const uint i, const uint j)
{
#if 0
- SWAP(unsigned int, heap->tree[i]->index, heap->tree[j]->index);
+ SWAP(uint, heap->tree[i]->index, heap->tree[j]->index);
SWAP(HeapNode *, heap->tree[i], heap->tree[j]);
#else
HeapNode **tree = heap->tree;
union {
- unsigned int index;
+ uint index;
HeapNode *node;
} tmp;
SWAP_TVAL(tmp.index, tree[i]->index, tree[j]->index);
@@ -102,18 +102,19 @@ BLI_INLINE void heap_swap(Heap *heap, const unsigned int i, const unsigned int j
#endif
}
-static void heap_down(Heap *heap, unsigned int i)
+static void heap_down(Heap *heap, uint i)
{
/* size won't change in the loop */
- const unsigned int size = heap->size;
+ const uint size = heap->size;
while (1) {
- const unsigned int l = HEAP_LEFT(i);
- const unsigned int r = HEAP_RIGHT(i);
- unsigned int smallest;
-
- smallest = ((l < size) && HEAP_COMPARE(heap->tree[l], heap->tree[i])) ? l : i;
+ const uint l = HEAP_LEFT(i);
+ const uint r = HEAP_RIGHT(i);
+ uint smallest = i;
+ if ((l < size) && HEAP_COMPARE(heap->tree[l], heap->tree[smallest])) {
+ smallest = l;
+ }
if ((r < size) && HEAP_COMPARE(heap->tree[r], heap->tree[smallest])) {
smallest = r;
}
@@ -127,10 +128,10 @@ static void heap_down(Heap *heap, unsigned int i)
}
}
-static void heap_up(Heap *heap, unsigned int i)
+static void heap_up(Heap *heap, uint i)
{
while (i > 0) {
- const unsigned int p = HEAP_PARENT(i);
+ const uint p = HEAP_PARENT(i);
if (HEAP_COMPARE(heap->tree[p], heap->tree[i])) {
break;
@@ -147,7 +148,7 @@ static void heap_up(Heap *heap, unsigned int i)
* \{ */
static struct HeapNode_Chunk *heap_node_alloc_chunk(
- unsigned int tot_nodes, struct HeapNode_Chunk *chunk_prev)
+ uint tot_nodes, struct HeapNode_Chunk *chunk_prev)
{
struct HeapNode_Chunk *chunk = MEM_mallocN(
sizeof(struct HeapNode_Chunk) + (sizeof(HeapNode) * tot_nodes), __func__);
@@ -188,8 +189,12 @@ static void heap_node_free(Heap *heap, HeapNode *node)
/** \name Public Heap API
* \{ */
-/* use when the size of the heap is known in advance */
-Heap *BLI_heap_new_ex(unsigned int tot_reserve)
+/**
+ * Creates a new heap. Removed nodes are recycled, so memory usage will not shrink.
+ *
+ * \note Use when the size of the heap is known in advance.
+ */
+Heap *BLI_heap_new_ex(uint tot_reserve)
{
Heap *heap = MEM_mallocN(sizeof(Heap), __func__);
/* ensure we have at least one so we can keep doubling it */
@@ -211,7 +216,7 @@ Heap *BLI_heap_new(void)
void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp)
{
if (ptrfreefp) {
- unsigned int i;
+ uint i;
for (i = 0; i < heap->size; i++) {
ptrfreefp(heap->tree[i]->ptr);
@@ -233,7 +238,7 @@ void BLI_heap_free(Heap *heap, HeapFreeFP ptrfreefp)
void BLI_heap_clear(Heap *heap, HeapFreeFP ptrfreefp)
{
if (ptrfreefp) {
- unsigned int i;
+ uint i;
for (i = 0; i < heap->size; i++) {
ptrfreefp(heap->tree[i]->ptr);
@@ -251,6 +256,10 @@ void BLI_heap_clear(Heap *heap, HeapFreeFP ptrfreefp)
heap->nodes.free = NULL;
}
+/**
+ * Insert heap node with a value (often a 'cost') and pointer into the heap,
+ * duplicate values are allowed.
+ */
HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr)
{
HeapNode *node;
@@ -275,27 +284,48 @@ HeapNode *BLI_heap_insert(Heap *heap, float value, void *ptr)
return node;
}
-bool BLI_heap_is_empty(Heap *heap)
+/**
+ * Convenience function since this is a common pattern.
+ */
+void BLI_heap_insert_or_update(Heap *heap, HeapNode **node_p, float value, void *ptr)
+{
+ if (*node_p == NULL) {
+ *node_p = BLI_heap_insert(heap, value, ptr);
+ }
+ else {
+ BLI_heap_node_value_update_ptr(heap, *node_p, value, ptr);
+ }
+}
+
+
+bool BLI_heap_is_empty(const Heap *heap)
{
return (heap->size == 0);
}
-unsigned int BLI_heap_size(Heap *heap)
+uint BLI_heap_len(const Heap *heap)
{
return heap->size;
}
-HeapNode *BLI_heap_top(Heap *heap)
+/**
+ * Return the top node of the heap.
+ * This is the node with the lowest value.
+ */
+HeapNode *BLI_heap_top(const Heap *heap)
{
return heap->tree[0];
}
-void *BLI_heap_popmin(Heap *heap)
+/**
+ * Pop the top node off the heap and return it's pointer.
+ */
+void *BLI_heap_pop_min(Heap *heap)
{
- void *ptr = heap->tree[0]->ptr;
-
BLI_assert(heap->size != 0);
+ void *ptr = heap->tree[0]->ptr;
+
heap_node_free(heap, heap->tree[0]);
if (--heap->size) {
@@ -308,28 +338,84 @@ void *BLI_heap_popmin(Heap *heap)
void BLI_heap_remove(Heap *heap, HeapNode *node)
{
- unsigned int i = node->index;
-
BLI_assert(heap->size != 0);
- while (i > 0) {
- unsigned int p = HEAP_PARENT(i);
+ uint i = node->index;
+ while (i > 0) {
+ uint p = HEAP_PARENT(i);
heap_swap(heap, p, i);
i = p;
}
- BLI_heap_popmin(heap);
+ BLI_heap_pop_min(heap);
}
-float BLI_heap_node_value(HeapNode *node)
+/**
+ * Can be used to avoid #BLI_heap_remove, #BLI_heap_insert calls,
+ * balancing the tree still has a performance cost,
+ * but is often much less than remove/insert, difference is most noticable with large heaps.
+ */
+void BLI_heap_node_value_update(Heap *heap, HeapNode *node, float value)
+{
+ if (value < node->value) {
+ node->value = value;
+ heap_up(heap, node->index);
+ }
+ else if (value > node->value) {
+ node->value = value;
+ heap_down(heap, node->index);
+ }
+}
+
+void BLI_heap_node_value_update_ptr(Heap *heap, HeapNode *node, float value, void *ptr)
+{
+ node->ptr = ptr; /* only difference */
+ if (value < node->value) {
+ node->value = value;
+ heap_up(heap, node->index);
+ }
+ else if (value > node->value) {
+ node->value = value;
+ heap_down(heap, node->index);
+ }
+}
+
+float BLI_heap_node_value(const HeapNode *node)
{
return node->value;
}
-void *BLI_heap_node_ptr(HeapNode *node)
+void *BLI_heap_node_ptr(const HeapNode *node)
{
return node->ptr;
}
+static bool heap_is_minheap(const Heap *heap, uint root)
+{
+ if (root < heap->size) {
+ const uint l = HEAP_LEFT(root);
+ if (l < heap->size) {
+ if (HEAP_COMPARE(heap->tree[l], heap->tree[root]) || !heap_is_minheap(heap, l)) {
+ return false;
+ }
+ }
+ const uint r = HEAP_RIGHT(root);
+ if (r < heap->size) {
+ if (HEAP_COMPARE(heap->tree[r], heap->tree[root]) || !heap_is_minheap(heap, r)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+/**
+ * Only for checking internal errors (gtest).
+ */
+bool BLI_heap_is_valid(const Heap *heap)
+{
+ return heap_is_minheap(heap, 0);
+}
+
/** \} */
+
diff --git a/source/blender/blenlib/intern/BLI_kdopbvh.c b/source/blender/blenlib/intern/BLI_kdopbvh.c
index 19d9711922e..44ff78ea71a 100644
--- a/source/blender/blenlib/intern/BLI_kdopbvh.c
+++ b/source/blender/blenlib/intern/BLI_kdopbvh.c
@@ -55,12 +55,20 @@
#include "BLI_stack.h"
#include "BLI_kdopbvh.h"
#include "BLI_math.h"
-#include "BLI_strict_flags.h"
#include "BLI_task.h"
+#include "BLI_strict_flags.h"
+
/* used for iterative_raycast */
// #define USE_SKIP_LINKS
+/* Use to print balanced output. */
+// #define USE_PRINT_TREE
+
+/* Check tree is valid. */
+// #define USE_VERIFY_TREE
+
+
#define MAX_TREETYPE 32
/* Setting zero so we can catch bugs in BLI_task/KDOPBVH.
@@ -129,7 +137,7 @@ typedef struct BVHOverlapData_Thread {
} BVHOverlapData_Thread;
typedef struct BVHNearestData {
- BVHTree *tree;
+ const BVHTree *tree;
const float *co;
BVHTree_NearestPointCallback callback;
void *userdata;
@@ -139,7 +147,7 @@ typedef struct BVHNearestData {
} BVHNearestData;
typedef struct BVHRayCastData {
- BVHTree *tree;
+ const BVHTree *tree;
BVHTree_RayCastCallback callback;
void *userdata;
@@ -171,9 +179,9 @@ typedef struct BVHRayCastData {
*/
const float bvhtree_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}
+ {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}
};
@@ -321,11 +329,16 @@ 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++;
+ while (a[i]->bv[axis] < x->bv[axis]) {
+ i++;
+ }
j--;
- while (x->bv[axis] < (a[j])->bv[axis]) j--;
- if (!(i < j))
+ while (x->bv[axis] < a[j]->bv[axis]) {
+ j--;
+ }
+ if (!(i < j)) {
return i;
+ }
SWAP(BVHNode *, a[i], a[j]);
i++;
}
@@ -427,19 +440,18 @@ static void sort_along_axis(BVHTree *tree, int start, int end, int axis)
* \note 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 */
-static int partition_nth_element(BVHNode **a, int _begin, int _end, int n, int axis)
+static void partition_nth_element(BVHNode **a, int begin, int end, const int n, const 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)
+ const int cut = bvh_partition(a, begin, end, bvh_medianof3(a, begin, (begin + end) / 2, end - 1, axis), axis);
+ if (cut <= n) {
begin = cut;
- else
+ }
+ else {
end = cut;
+ }
}
bvh_insertionsort(a, begin, end, axis);
-
- return n;
}
#ifdef USE_SKIP_LINKS
@@ -464,7 +476,7 @@ static void build_skip_links(BVHTree *tree, BVHNode *node, BVHNode *left, BVHNod
/*
* BVHTree bounding volumes functions
*/
-static void create_kdop_hull(BVHTree *tree, BVHNode *node, const float *co, int numpoints, int moving)
+static void create_kdop_hull(const BVHTree *tree, BVHNode *node, const float *co, int numpoints, int moving)
{
float newminmax;
float *bv = node->bv;
@@ -491,7 +503,7 @@ static void create_kdop_hull(BVHTree *tree, BVHNode *node, const float *co, int
/**
* \note 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)
+static void refit_kdop_hull(const BVHTree *tree, BVHNode *node, int start, int end)
{
float newmin, newmax;
float *bv = node->bv;
@@ -566,10 +578,12 @@ static void node_join(BVHTree *tree, BVHNode *node)
}
}
-/*
+#ifdef USE_PRINT_TREE
+
+/**
* Debug and information functions
*/
-#if 0
+
static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
{
int i;
@@ -592,26 +606,29 @@ static void bvhtree_print_tree(BVHTree *tree, BVHNode *node, int depth)
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", (int)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);
+ printf("BVHTree Info: 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 = %ubytes\n",
+ (uint)(sizeof(BVHNode) + sizeof(BVHNode *) * tree->tree_type + sizeof(float) * tree->axis));
+ printf("BV memory = %ubytes\n",
+ (uint)MEM_allocN_len(tree->nodebv));
+
+ printf("Total memory = %ubytes\n",
+ (uint)(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);
}
-#endif
-
-#if 0
+#endif /* USE_PRINT_TREE */
+#ifdef USE_VERIFY_TREE
-static void verify_tree(BVHTree *tree)
+static void bvhtree_verify(BVHTree *tree)
{
int i, j, check = 0;
@@ -649,12 +666,14 @@ static void verify_tree(BVHTree *tree)
}
}
- printf("branches: %d, leafs: %d, total: %d\n", tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
+ printf("branches: %d, leafs: %d, total: %d\n",
+ tree->totbranch, tree->totleaf, tree->totbranch + tree->totleaf);
}
-#endif
+#endif /* USE_VERIFY_TREE */
/* 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) */
+ * 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; /* */
@@ -666,7 +685,7 @@ typedef struct BVHBuildHelper {
} BVHBuildHelper;
-static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
+static void build_implicit_tree_helper(const BVHTree *tree, BVHBuildHelper *data)
{
int depth = 0;
int remain;
@@ -696,7 +715,7 @@ static void build_implicit_tree_helper(BVHTree *tree, BVHBuildHelper *data)
}
// 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)
+static int implicit_leafs_index(const BVHBuildHelper *data, const int depth, const int child_index)
{
int min_leaf_index = child_index * data->leafs_per_child[depth - 1];
if (min_leaf_index <= data->remain_leafs)
@@ -711,8 +730,8 @@ static int implicit_leafs_index(BVHBuildHelper *data, int depth, int child_index
* 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.
+ * 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.
*
* Although 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.
@@ -753,7 +772,7 @@ static int implicit_needed_branches(int tree_type, int leafs)
*
* 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)
+static void split_leafs(BVHNode **leafs_array, const int nth[], const int partitions, const int split_axis)
{
int i;
for (i = 0; i < partitions - 1; i++) {
@@ -765,27 +784,30 @@ static void split_leafs(BVHNode **leafs_array, int *nth, int partitions, int spl
}
typedef struct BVHDivNodesData {
- BVHTree *tree;
+ const BVHTree *tree;
BVHNode *branches_array;
BVHNode **leafs_array;
int tree_type;
int tree_offset;
- BVHBuildHelper *data;
+ const BVHBuildHelper *data;
int depth;
int i;
int first_of_next_level;
} BVHDivNodesData;
-static void non_recursive_bvh_div_nodes_task_cb(void *userdata, const int j)
+static void non_recursive_bvh_div_nodes_task_cb(
+ void *__restrict userdata,
+ const int j,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
BVHDivNodesData *data = userdata;
int k;
const int parent_level_index = j - data->i;
- BVHNode *parent = data->branches_array + j;
+ BVHNode *parent = &data->branches_array[j];
int nth_positions[MAX_TREETYPE + 1];
char split_axis;
@@ -824,7 +846,7 @@ static void non_recursive_bvh_div_nodes_task_cb(void *userdata, const int j)
const int child_leafs_end = implicit_leafs_index(data->data, data->depth + 1, child_level_index + 1);
if (child_leafs_end - child_leafs_begin > 1) {
- parent->children[k] = data->branches_array + child_index;
+ parent->children[k] = &data->branches_array[child_index];
parent->children[k]->parent = parent;
}
else if (child_leafs_end - child_leafs_begin == 1) {
@@ -834,9 +856,8 @@ static void non_recursive_bvh_div_nodes_task_cb(void *userdata, const int j)
else {
break;
}
-
- parent->totnode = (char)(k + 1);
}
+ parent->totnode = (char)k;
}
/**
@@ -853,9 +874,10 @@ static void non_recursive_bvh_div_nodes_task_cb(void *userdata, const int j)
* to use multithread building.
*
* To archive this is necessary to find how much leafs are accessible from a certain branch, BVHBuildHelper
- * implicit_needed_branches and implicit_leafs_index are auxiliary functions to solve that "optimal-split".
+ * #implicit_needed_branches and #implicit_leafs_index are auxiliary functions to solve that "optimal-split".
*/
-static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
+static void non_recursive_bvh_div_nodes(
+ const BVHTree *tree, BVHNode *branches_array, BVHNode **leafs_array, int num_leafs)
{
int i;
@@ -865,24 +887,23 @@ static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array,
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 */
+ {
+ /* set parent from root node to NULL */
+ BVHNode *root = &branches_array[1];
+ root->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) {
+ 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;
+ }
+ }
build_implicit_tree_helper(tree, &data);
@@ -895,16 +916,30 @@ static void non_recursive_bvh_div_nodes(BVHTree *tree, BVHNode *branches_array,
/* 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 = min_ii(first_of_next_level, num_branches + 1); /* index of last branch on this level */
+ const int i_stop = min_ii(first_of_next_level, num_branches + 1); /* index of last branch on this level */
/* Loop all branches on this level */
cb_data.first_of_next_level = first_of_next_level;
cb_data.i = i;
cb_data.depth = depth;
- BLI_task_parallel_range(
- i, end_j, &cb_data, non_recursive_bvh_div_nodes_task_cb,
- num_leafs > KDOPBVH_THREAD_LEAF_THRESHOLD);
+ if (true) {
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (num_leafs > KDOPBVH_THREAD_LEAF_THRESHOLD);
+ BLI_task_parallel_range(
+ i, i_stop,
+ &cb_data,
+ non_recursive_bvh_div_nodes_task_cb,
+ &settings);
+ }
+ else {
+ /* Less hassle for debugging. */
+ ParallelRangeTLS tls = {0};
+ for (int i_task = i; i_task < i_stop; i_task++) {
+ non_recursive_bvh_div_nodes_task_cb(&cb_data, i_task, &tls);
+ }
+ }
}
}
@@ -1016,28 +1051,33 @@ void BLI_bvhtree_free(BVHTree *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) */
+ /* This function should only be called once
+ * (some big bug goes here if its being called more than once per tree) */
BLI_assert(tree->totbranch == 0);
/* Build the implicit tree */
- non_recursive_bvh_div_nodes(tree, branches_array, leafs_array, tree->totleaf);
+ non_recursive_bvh_div_nodes(tree, tree->nodearray + (tree->totleaf - 1), 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;
+ for (int i = 0; i < tree->totbranch; i++) {
+ tree->nodes[tree->totleaf + i] = &tree->nodearray[tree->totleaf + i];
+ }
#ifdef USE_SKIP_LINKS
build_skip_links(tree, tree->nodes[tree->totleaf], NULL, NULL);
#endif
- /* bvhtree_info(tree); */
+#ifdef USE_VERIFY_TREE
+ bvhtree_verify(tree);
+#endif
+
+#ifdef USE_PRINT_TREE
+ bvhtree_info(tree);
+#endif
}
void BLI_bvhtree_insert(BVHTree *tree, int index, const float co[3], int numpoints)
@@ -1106,7 +1146,7 @@ void BLI_bvhtree_update_tree(BVHTree *tree)
* Number of times #BLI_bvhtree_insert has been called.
* mainly useful for asserts functions to check we added the correct number.
*/
-int BLI_bvhtree_get_size(const BVHTree *tree)
+int BLI_bvhtree_get_len(const BVHTree *tree)
{
return tree->totleaf;
}
@@ -1241,7 +1281,10 @@ int BLI_bvhtree_overlap_thread_num(const BVHTree *tree)
return (int)MIN2(tree->tree_type, tree->nodes[tree->totleaf]->totnode);
}
-static void bvhtree_overlap_task_cb(void *userdata, const int j)
+static void bvhtree_overlap_task_cb(
+ void *__restrict userdata,
+ const int j,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
BVHOverlapData_Thread *data = &((BVHOverlapData_Thread *)userdata)[j];
BVHOverlapData_Shared *data_shared = data->shared;
@@ -1259,7 +1302,7 @@ static void bvhtree_overlap_task_cb(void *userdata, const int j)
}
BVHTreeOverlap *BLI_bvhtree_overlap(
- const BVHTree *tree1, const BVHTree *tree2, unsigned int *r_overlap_tot,
+ const BVHTree *tree1, const BVHTree *tree2, uint *r_overlap_tot,
/* optional callback to test the overlap before adding (must be thread-safe!) */
BVHTree_OverlapCallback callback, void *userdata)
{
@@ -1306,9 +1349,14 @@ BVHTreeOverlap *BLI_bvhtree_overlap(
data[j].thread = j;
}
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (tree1->totleaf > KDOPBVH_THREAD_LEAF_THRESHOLD);
BLI_task_parallel_range(
- 0, thread_num, data, bvhtree_overlap_task_cb,
- tree1->totleaf > KDOPBVH_THREAD_LEAF_THRESHOLD);
+ 0, thread_num,
+ data,
+ bvhtree_overlap_task_cb,
+ &settings);
for (j = 0; j < thread_num; j++)
total += BLI_stack_count(data[j].overlap);
@@ -1316,13 +1364,13 @@ BVHTreeOverlap *BLI_bvhtree_overlap(
to = overlap = MEM_mallocN(sizeof(BVHTreeOverlap) * total, "BVHTreeOverlap");
for (j = 0; j < thread_num; j++) {
- unsigned int count = (unsigned int)BLI_stack_count(data[j].overlap);
+ uint count = (uint)BLI_stack_count(data[j].overlap);
BLI_stack_pop_n(data[j].overlap, to, count);
BLI_stack_free(data[j].overlap);
to += count;
}
- *r_overlap_tot = (unsigned int)total;
+ *r_overlap_tot = (uint)total;
return overlap;
}
@@ -1470,7 +1518,8 @@ static void bfs_find_nearest(BVHNearestData *data, BVHNode *node)
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)
+ 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");
@@ -1874,6 +1923,7 @@ void BLI_bvhtree_ray_cast_all(
BLI_bvhtree_ray_cast_all_ex(tree, co, dir, radius, hit_dist, callback, userdata, BVH_RAYCAST_DEFAULT);
}
+/** \} */
/* -------------------------------------------------------------------- */
@@ -1965,29 +2015,31 @@ int BLI_bvhtree_range_query(
/** \name BLI_bvhtree_walk_dfs
* \{ */
+typedef struct BVHTree_WalkData {
+ BVHTree_WalkParentCallback walk_parent_cb;
+ BVHTree_WalkLeafCallback walk_leaf_cb;
+ BVHTree_WalkOrderCallback walk_order_cb;
+ void *userdata;
+} BVHTree_WalkData;
+
/**
* Runs first among nodes children of the first node before going to the next node in the same layer.
*
* \return false to break out of the search early.
*/
static bool bvhtree_walk_dfs_recursive(
- BVHTree_WalkParentCallback walk_parent_cb,
- BVHTree_WalkLeafCallback walk_leaf_cb,
- BVHTree_WalkOrderCallback walk_order_cb,
- const BVHNode *node, void *userdata)
+ BVHTree_WalkData *walk_data,
+ const BVHNode *node)
{
if (node->totnode == 0) {
- return walk_leaf_cb((const BVHTreeAxisRange *)node->bv, node->index, userdata);
+ return walk_data->walk_leaf_cb((const BVHTreeAxisRange *)node->bv, node->index, walk_data->userdata);
}
else {
/* First pick the closest node to recurse into */
- if (walk_order_cb((const BVHTreeAxisRange *)node->bv, node->main_axis, userdata)) {
+ if (walk_data->walk_order_cb((const BVHTreeAxisRange *)node->bv, node->main_axis, walk_data->userdata)) {
for (int i = 0; i != node->totnode; i++) {
- if (walk_parent_cb((const BVHTreeAxisRange *)node->children[i]->bv, userdata)) {
- if (!bvhtree_walk_dfs_recursive(
- walk_parent_cb, walk_leaf_cb, walk_order_cb,
- node->children[i], userdata))
- {
+ if (walk_data->walk_parent_cb((const BVHTreeAxisRange *)node->children[i]->bv, walk_data->userdata)) {
+ if (!bvhtree_walk_dfs_recursive(walk_data, node->children[i])) {
return false;
}
}
@@ -1995,11 +2047,8 @@ static bool bvhtree_walk_dfs_recursive(
}
else {
for (int i = node->totnode - 1; i >= 0; i--) {
- if (walk_parent_cb((const BVHTreeAxisRange *)node->children[i]->bv, userdata)) {
- if (!bvhtree_walk_dfs_recursive(
- walk_parent_cb, walk_leaf_cb, walk_order_cb,
- node->children[i], userdata))
- {
+ if (walk_data->walk_parent_cb((const BVHTreeAxisRange *)node->children[i]->bv, walk_data->userdata)) {
+ if (!bvhtree_walk_dfs_recursive(walk_data, node->children[i])) {
return false;
}
}
@@ -2029,9 +2078,10 @@ void BLI_bvhtree_walk_dfs(
{
const BVHNode *root = tree->nodes[tree->totleaf];
if (root != NULL) {
+ BVHTree_WalkData walk_data = {walk_parent_cb, walk_leaf_cb, walk_order_cb, userdata};
/* first make sure the bv of root passes in the test too */
if (walk_parent_cb((const BVHTreeAxisRange *)root->bv, userdata)) {
- bvhtree_walk_dfs_recursive(walk_parent_cb, walk_leaf_cb, walk_order_cb, root, userdata);
+ bvhtree_walk_dfs_recursive(&walk_data, root);
}
}
}
diff --git a/source/blender/blenlib/intern/BLI_kdtree.c b/source/blender/blenlib/intern/BLI_kdtree.c
index a81f9b28b83..844f274a81f 100644
--- a/source/blender/blenlib/intern/BLI_kdtree.c
+++ b/source/blender/blenlib/intern/BLI_kdtree.c
@@ -33,25 +33,25 @@
#include "BLI_strict_flags.h"
typedef struct KDTreeNode_head {
- unsigned int left, right;
+ uint left, right;
float co[3];
int index;
} KDTreeNode_head;
typedef struct KDTreeNode {
- unsigned int left, right;
+ uint left, right;
float co[3];
int index;
- unsigned int d; /* range is only (0-2) */
+ uint d; /* range is only (0-2) */
} KDTreeNode;
struct KDTree {
KDTreeNode *nodes;
- unsigned int totnode;
- unsigned int root;
+ uint totnode;
+ uint root;
#ifdef DEBUG
bool is_balanced; /* ensure we call balance first */
- unsigned int maxsize; /* max size of the tree */
+ uint maxsize; /* max size of the tree */
#endif
};
@@ -59,12 +59,12 @@ struct KDTree {
#define KD_NEAR_ALLOC_INC 100 /* alloc increment for collecting nearest */
#define KD_FOUND_ALLOC_INC 50 /* alloc increment for collecting nearest */
-#define KD_NODE_UNSET ((unsigned int)-1)
+#define KD_NODE_UNSET ((uint)-1)
/**
* Creates or free a kdtree
*/
-KDTree *BLI_kdtree_new(unsigned int maxsize)
+KDTree *BLI_kdtree_new(uint maxsize)
{
KDTree *tree;
@@ -113,11 +113,11 @@ void BLI_kdtree_insert(KDTree *tree, int index, const float co[3])
#endif
}
-static unsigned int kdtree_balance(KDTreeNode *nodes, unsigned int totnode, unsigned int axis, const unsigned int ofs)
+static uint kdtree_balance(KDTreeNode *nodes, uint totnode, uint axis, const uint ofs)
{
KDTreeNode *node;
float co;
- unsigned int left, right, median, i, j;
+ uint left, right, median, i, j;
if (totnode <= 0)
return KD_NODE_UNSET;
@@ -188,11 +188,11 @@ static float squared_distance(const float v2[3], const float v1[3], const float
return dist;
}
-static unsigned int *realloc_nodes(unsigned int *stack, unsigned int *totstack, const bool is_alloc)
+static uint *realloc_nodes(uint *stack, uint *totstack, const bool is_alloc)
{
- unsigned int *stack_new = MEM_mallocN((*totstack + KD_NEAR_ALLOC_INC) * sizeof(unsigned int), "KDTree.treestack");
- memcpy(stack_new, stack, *totstack * sizeof(unsigned int));
- // memset(stack_new + *totstack, 0, sizeof(unsigned int) * KD_NEAR_ALLOC_INC);
+ uint *stack_new = MEM_mallocN((*totstack + KD_NEAR_ALLOC_INC) * sizeof(uint), "KDTree.treestack");
+ memcpy(stack_new, stack, *totstack * sizeof(uint));
+ // memset(stack_new + *totstack, 0, sizeof(uint) * KD_NEAR_ALLOC_INC);
if (is_alloc)
MEM_freeN(stack);
*totstack += KD_NEAR_ALLOC_INC;
@@ -208,9 +208,9 @@ int BLI_kdtree_find_nearest(
{
const KDTreeNode *nodes = tree->nodes;
const KDTreeNode *root, *min_node;
- unsigned int *stack, defaultstack[KD_STACK_INIT];
+ uint *stack, defaultstack[KD_STACK_INIT];
float min_dist, cur_dist;
- unsigned int totstack, cur = 0;
+ uint totstack, cur = 0;
#ifdef DEBUG
BLI_assert(tree->is_balanced == true);
@@ -307,9 +307,9 @@ int BLI_kdtree_find_nearest_cb(
const KDTreeNode *nodes = tree->nodes;
const KDTreeNode *min_node = NULL;
- unsigned int *stack, defaultstack[KD_STACK_INIT];
+ uint *stack, defaultstack[KD_STACK_INIT];
float min_dist = FLT_MAX, cur_dist;
- unsigned int totstack, cur = 0;
+ uint totstack, cur = 0;
#ifdef DEBUG
BLI_assert(tree->is_balanced == true);
@@ -397,10 +397,10 @@ finally:
}
}
-static void add_nearest(KDTreeNearest *ptn, unsigned int *found, unsigned int n, int index,
+static void add_nearest(KDTreeNearest *ptn, uint *found, uint n, int index,
float dist, const float *co)
{
- unsigned int i;
+ uint i;
if (*found < n) (*found)++;
@@ -425,14 +425,14 @@ static void add_nearest(KDTreeNearest *ptn, unsigned int *found, unsigned int n,
int BLI_kdtree_find_nearest_n__normal(
const KDTree *tree, const float co[3], const float nor[3],
KDTreeNearest r_nearest[],
- unsigned int n)
+ uint n)
{
const KDTreeNode *nodes = tree->nodes;
const KDTreeNode *root;
- unsigned int *stack, defaultstack[KD_STACK_INIT];
+ uint *stack, defaultstack[KD_STACK_INIT];
float cur_dist;
- unsigned int totstack, cur = 0;
- unsigned int i, found = 0;
+ uint totstack, cur = 0;
+ uint i, found = 0;
#ifdef DEBUG
BLI_assert(tree->is_balanced == true);
@@ -524,8 +524,8 @@ static int range_compare(const void *a, const void *b)
}
static void add_in_range(
KDTreeNearest **r_foundstack,
- unsigned int *r_foundstack_tot_alloc,
- unsigned int found,
+ uint *r_foundstack_tot_alloc,
+ uint found,
const int index, const float dist, const float *co)
{
KDTreeNearest *to;
@@ -554,10 +554,10 @@ int BLI_kdtree_range_search__normal(
KDTreeNearest **r_nearest, float range)
{
const KDTreeNode *nodes = tree->nodes;
- unsigned int *stack, defaultstack[KD_STACK_INIT];
+ uint *stack, defaultstack[KD_STACK_INIT];
KDTreeNearest *foundstack = NULL;
float range_sq = range * range, dist_sq;
- unsigned int totstack, cur = 0, found = 0, totfoundstack = 0;
+ uint totstack, cur = 0, found = 0, totfoundstack = 0;
#ifdef DEBUG
BLI_assert(tree->is_balanced == true);
@@ -624,9 +624,9 @@ void BLI_kdtree_range_search_cb(
{
const KDTreeNode *nodes = tree->nodes;
- unsigned int *stack, defaultstack[KD_STACK_INIT];
+ uint *stack, defaultstack[KD_STACK_INIT];
float range_sq = range * range, dist_sq;
- unsigned int totstack, cur = 0;
+ uint totstack, cur = 0;
#ifdef DEBUG
BLI_assert(tree->is_balanced == true);
@@ -674,3 +674,123 @@ finally:
if (stack != defaultstack)
MEM_freeN(stack);
}
+
+/**
+ * Use when we want to loop over nodes ordered by index.
+ * Requires indices to be aligned with nodes.
+ */
+static uint *kdtree_order(const KDTree *tree)
+{
+ const KDTreeNode *nodes = tree->nodes;
+ uint *order = MEM_mallocN(sizeof(uint) * tree->totnode, __func__);
+ for (uint i = 0; i < tree->totnode; i++) {
+ order[nodes[i].index] = i;
+ }
+ return order;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name BLI_kdtree_calc_duplicates_fast
+ * \{ */
+
+struct DeDuplicateParams {
+ /* Static */
+ const KDTreeNode *nodes;
+ float range;
+ float range_sq;
+ int *duplicates;
+ int *duplicates_found;
+
+ /* Per Search */
+ float search_co[3];
+ int search;
+};
+
+static void deduplicate_recursive(const struct DeDuplicateParams *p, uint i)
+{
+ const KDTreeNode *node = &p->nodes[i];
+ if (p->search_co[node->d] + p->range <= node->co[node->d]) {
+ if (node->left != KD_NODE_UNSET) {
+ deduplicate_recursive(p, node->left);
+ }
+ }
+ else if (p->search_co[node->d] - p->range >= node->co[node->d]) {
+ if (node->right != KD_NODE_UNSET) {
+ deduplicate_recursive(p, node->right);
+ }
+ }
+ else {
+ if ((p->search != node->index) && (p->duplicates[node->index] == -1)) {
+ if (compare_len_squared_v3v3(node->co, p->search_co, p->range_sq)) {
+ p->duplicates[node->index] = (int)p->search;
+ *p->duplicates_found += 1;
+ }
+ }
+ if (node->left != KD_NODE_UNSET) {
+ deduplicate_recursive(p, node->left);
+ }
+ if (node->right != KD_NODE_UNSET) {
+ deduplicate_recursive(p, node->right);
+ }
+ }
+}
+
+/**
+ * Find duplicate points in \a range.
+ * Favors speed over quality since it doesn't find the best target vertex for merging.
+ * Nodes are looped over, duplicates are added when found.
+ * Nevertheless results are predictable.
+ *
+ * \param range: Coordinates in this range are candidates to be merged.
+ * \param use_index_order: Loop over the coordinates ordered by #KDTreeNode.index
+ * At the expense of some performance, this ensures the layout of the tree doesn't influence
+ * the iteration order.
+ * \param duplicates: An array of int's the length of #KDTree.totnode
+ * Values initialized to -1 are candidates to me merged.
+ * Setting the index to it's own position in the array prevents it from being touched,
+ * although it can still be used as a target.
+ * \returns The numebr of merges found (includes any merges already in the \a duplicates array).
+ *
+ * \note Merging is always a single step (target indices wont be marked for merging).
+ */
+int BLI_kdtree_calc_duplicates_fast(
+ const KDTree *tree, const float range, bool use_index_order,
+ int *duplicates)
+{
+ int found = 0;
+ struct DeDuplicateParams p = {
+ .nodes = tree->nodes,
+ .range = range,
+ .range_sq = range * range,
+ .duplicates = duplicates,
+ .duplicates_found = &found,
+ };
+
+ if (use_index_order) {
+ uint *order = kdtree_order(tree);
+ for (uint i = 0; i < tree->totnode; i++) {
+ const uint node_index = order[i];
+ const int index = (int)i;
+ if (ELEM(duplicates[index], -1, index)) {
+ p.search = index;
+ copy_v3_v3(p.search_co, tree->nodes[node_index].co);
+ deduplicate_recursive(&p, tree->root);
+ }
+ }
+ MEM_freeN(order);
+ }
+ else {
+ for (uint i = 0; i < tree->totnode; i++) {
+ const uint node_index = i;
+ const int index = p.nodes[node_index].index;
+ if (ELEM(duplicates[index], -1, index)) {
+ p.search = index;
+ copy_v3_v3(p.search_co, tree->nodes[node_index].co);
+ deduplicate_recursive(&p, tree->root);
+ }
+ }
+ }
+ return found;
+}
+
+/** \} */
diff --git a/source/blender/blenlib/intern/BLI_linklist.c b/source/blender/blenlib/intern/BLI_linklist.c
index 1500e23d72e..051792f7f7c 100644
--- a/source/blender/blenlib/intern/BLI_linklist.c
+++ b/source/blender/blenlib/intern/BLI_linklist.c
@@ -28,6 +28,10 @@
/** \file blender/blenlib/intern/BLI_linklist.c
* \ingroup bli
+ *
+ * Routines for working with single linked lists of 'links' - pointers to other data.
+ *
+ * For double linked lists see 'BLI_listbase.h'.
*/
#include <stdlib.h>
diff --git a/source/blender/blenlib/intern/BLI_linklist_lockfree.c b/source/blender/blenlib/intern/BLI_linklist_lockfree.c
new file mode 100644
index 00000000000..ef93ce3619f
--- /dev/null
+++ b/source/blender/blenlib/intern/BLI_linklist_lockfree.c
@@ -0,0 +1,91 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Sergey Sharybin.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenlib/intern/BLI_linklist_lockfree.c
+ * \ingroup bli
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_linklist_lockfree.h"
+#include "BLI_strict_flags.h"
+
+#include "atomic_ops.h"
+
+void BLI_linklist_lockfree_init(LockfreeLinkList *list)
+{
+ list->dummy_node.next = NULL;
+ list->head = list->tail = &list->dummy_node;
+}
+
+void BLI_linklist_lockfree_free(LockfreeLinkList *list,
+ LockfreeeLinkNodeFreeFP free_func)
+{
+ if (free_func != NULL) {
+ /* NOTE: We start from a first user-added node. */
+ LockfreeLinkNode *node = list->head->next;
+ while (node != NULL) {
+ LockfreeLinkNode *node_next = node->next;
+ free_func(node);
+ node = node_next;
+ }
+ }
+}
+
+void BLI_linklist_lockfree_clear(LockfreeLinkList *list,
+ LockfreeeLinkNodeFreeFP free_func)
+{
+ BLI_linklist_lockfree_free(list, free_func);
+ BLI_linklist_lockfree_init(list);
+}
+
+void BLI_linklist_lockfree_insert(LockfreeLinkList *list,
+ LockfreeLinkNode *node)
+{
+ /* Based on:
+ *
+ * John D. Valois
+ * Implementing Lock-Free Queues
+ *
+ * http://people.csail.mit.edu/bushl2/rpi/portfolio/lockfree-grape/documents/lock-free-linked-lists.pdf
+ */
+ bool keep_working;
+ LockfreeLinkNode *tail_node;
+ node->next = NULL;
+ do {
+ tail_node = list->tail;
+ keep_working =
+ (atomic_cas_ptr((void **)&tail_node->next, NULL, node) != NULL);
+ if (keep_working) {
+ atomic_cas_ptr((void **)&list->tail, tail_node, tail_node->next);
+ }
+ } while (keep_working);
+ atomic_cas_ptr((void **)&list->tail, tail_node, node);
+}
+
+LockfreeLinkNode *BLI_linklist_lockfree_begin(LockfreeLinkList *list)
+{
+ return list->head->next;
+}
diff --git a/source/blender/blenlib/intern/BLI_mempool.c b/source/blender/blenlib/intern/BLI_mempool.c
index 783dba5510c..3a65e6c42ca 100644
--- a/source/blender/blenlib/intern/BLI_mempool.c
+++ b/source/blender/blenlib/intern/BLI_mempool.c
@@ -41,6 +41,8 @@
#include <string.h>
#include <stdlib.h>
+#include "atomic_ops.h"
+
#include "BLI_utildefines.h"
#include "BLI_mempool.h" /* own include */
@@ -127,17 +129,17 @@ struct BLI_mempool {
* this is needed for iteration so we can loop over chunks in the order added */
BLI_mempool_chunk *chunk_tail;
- unsigned int esize; /* element size in bytes */
- unsigned int csize; /* chunk size in bytes */
- unsigned int pchunk; /* number of elements per chunk */
- unsigned int flag;
+ uint esize; /* element size in bytes */
+ uint csize; /* chunk size in bytes */
+ uint pchunk; /* number of elements per chunk */
+ uint flag;
/* keeps aligned to 16 bits */
BLI_freenode *free; /* free element list. Interleaved into chunk datas. */
- unsigned int maxchunks; /* use to know how many chunks to keep for BLI_mempool_clear */
- unsigned int totused; /* number of elements currently in use */
+ uint maxchunks; /* use to know how many chunks to keep for BLI_mempool_clear */
+ uint totused; /* number of elements currently in use */
#ifdef USE_TOTALLOC
- unsigned int totalloc; /* number of elements allocated in total */
+ uint totalloc; /* number of elements allocated in total */
#endif
};
@@ -154,13 +156,13 @@ struct BLI_mempool {
/* extra bytes implicitly used for every chunk alloc */
#ifdef USE_DATA_PTR
-# define CHUNK_OVERHEAD (unsigned int)(MEM_SIZE_OVERHEAD + sizeof(BLI_mempool_chunk))
+# define CHUNK_OVERHEAD (uint)(MEM_SIZE_OVERHEAD + sizeof(BLI_mempool_chunk))
#else
-# define CHUNK_OVERHEAD (unsigned int)(MEM_SIZE_OVERHEAD)
+# define CHUNK_OVERHEAD (uint)(MEM_SIZE_OVERHEAD)
#endif
#ifdef USE_CHUNK_POW2
-static unsigned int power_of_2_max_u(unsigned int x)
+static uint power_of_2_max_u(uint x)
{
x -= 1;
x = x | (x >> 1);
@@ -172,7 +174,7 @@ static unsigned int power_of_2_max_u(unsigned int x)
}
#endif
-BLI_INLINE BLI_mempool_chunk *mempool_chunk_find(BLI_mempool_chunk *head, unsigned int index)
+BLI_INLINE BLI_mempool_chunk *mempool_chunk_find(BLI_mempool_chunk *head, uint index)
{
while (index-- && head) {
head = head->next;
@@ -187,7 +189,7 @@ BLI_INLINE BLI_mempool_chunk *mempool_chunk_find(BLI_mempool_chunk *head, unsign
* adding overhead on creation which is redundant if they aren't used.
*
*/
-BLI_INLINE unsigned int mempool_maxchunks(const unsigned int totelem, const unsigned int pchunk)
+BLI_INLINE uint mempool_maxchunks(const uint totelem, const uint pchunk)
{
return (totelem <= pchunk) ? 1 : ((totelem / pchunk) + 1);
}
@@ -217,9 +219,9 @@ static BLI_mempool_chunk *mempool_chunk_alloc(BLI_mempool *pool)
static BLI_freenode *mempool_chunk_add(BLI_mempool *pool, BLI_mempool_chunk *mpchunk,
BLI_freenode *lasttail)
{
- const unsigned int esize = pool->esize;
+ const uint esize = pool->esize;
BLI_freenode *curnode = CHUNK_DATA(mpchunk);
- unsigned int j;
+ uint j;
/* append */
if (pool->chunk_tail) {
@@ -289,12 +291,12 @@ static void mempool_chunk_free_all(BLI_mempool_chunk *mpchunk)
}
}
-BLI_mempool *BLI_mempool_create(unsigned int esize, unsigned int totelem,
- unsigned int pchunk, unsigned int flag)
+BLI_mempool *BLI_mempool_create(uint esize, uint totelem,
+ uint pchunk, uint flag)
{
BLI_mempool *pool;
BLI_freenode *lasttail = NULL;
- unsigned int i, maxchunks;
+ uint i, maxchunks;
/* allocate the pool structure */
pool = MEM_mallocN(sizeof(BLI_mempool), "memory pool");
@@ -305,7 +307,7 @@ BLI_mempool *BLI_mempool_create(unsigned int esize, unsigned int totelem,
}
if (flag & BLI_MEMPOOL_ALLOW_ITER) {
- esize = MAX2(esize, (unsigned int)sizeof(BLI_freenode));
+ esize = MAX2(esize, (uint)sizeof(BLI_freenode));
}
maxchunks = mempool_maxchunks(totelem, pchunk);
@@ -436,9 +438,9 @@ void BLI_mempool_free(BLI_mempool *pool, void *addr)
if (UNLIKELY(pool->totused == 0) &&
(pool->chunks->next))
{
- const unsigned int esize = pool->esize;
+ const uint esize = pool->esize;
BLI_freenode *curnode;
- unsigned int j;
+ uint j;
BLI_mempool_chunk *first;
first = pool->chunks;
@@ -472,12 +474,12 @@ void BLI_mempool_free(BLI_mempool *pool, void *addr)
}
}
-int BLI_mempool_count(BLI_mempool *pool)
+int BLI_mempool_len(BLI_mempool *pool)
{
return (int)pool->totused;
}
-void *BLI_mempool_findelem(BLI_mempool *pool, unsigned int index)
+void *BLI_mempool_findelem(BLI_mempool *pool, uint index)
{
BLI_assert(pool->flag & BLI_MEMPOOL_ALLOW_ITER);
@@ -512,7 +514,7 @@ void BLI_mempool_as_table(BLI_mempool *pool, void **data)
while ((elem = BLI_mempool_iterstep(&iter))) {
*p++ = elem;
}
- BLI_assert((unsigned int)(p - data) == pool->totused);
+ BLI_assert((uint)(p - data) == pool->totused);
}
/**
@@ -530,7 +532,7 @@ void **BLI_mempool_as_tableN(BLI_mempool *pool, const char *allocstr)
*/
void BLI_mempool_as_array(BLI_mempool *pool, void *data)
{
- const unsigned int esize = pool->esize;
+ const uint esize = pool->esize;
BLI_mempool_iter iter;
char *elem, *p = data;
BLI_assert(pool->flag & BLI_MEMPOOL_ALLOW_ITER);
@@ -539,7 +541,7 @@ void BLI_mempool_as_array(BLI_mempool *pool, void *data)
memcpy(p, elem, (size_t)esize);
p = NODE_STEP_NEXT(p);
}
- BLI_assert((unsigned int)(p - (char *)data) == pool->totused * esize);
+ BLI_assert((uint)(p - (char *)data) == pool->totused * esize);
}
/**
@@ -553,7 +555,7 @@ void *BLI_mempool_as_arrayN(BLI_mempool *pool, const char *allocstr)
}
/**
- * Create a new mempool iterator, \a BLI_MEMPOOL_ALLOW_ITER flag must be set.
+ * Initialize a new mempool iterator, \a BLI_MEMPOOL_ALLOW_ITER flag must be set.
*/
void BLI_mempool_iternew(BLI_mempool *pool, BLI_mempool_iter *iter)
{
@@ -562,6 +564,47 @@ void BLI_mempool_iternew(BLI_mempool *pool, BLI_mempool_iter *iter)
iter->pool = pool;
iter->curchunk = pool->chunks;
iter->curindex = 0;
+
+ iter->curchunk_threaded_shared = NULL;
+}
+
+/**
+ * Initialize an array of mempool iterators, \a BLI_MEMPOOL_ALLOW_ITER flag must be set.
+ *
+ * This is used in threaded code, to generate as much iterators as needed (each task should have its own),
+ * such that each iterator goes over its own single chunk, and only getting the next chunk to iterate over has to be
+ * protected against concurrency (which can be done in a lockless way).
+ *
+ * To be used when creating a task for each single item in the pool is totally overkill.
+ *
+ * See BLI_task_parallel_mempool implementation for detailed usage example.
+ */
+BLI_mempool_iter *BLI_mempool_iter_threadsafe_create(BLI_mempool *pool, const size_t num_iter)
+{
+ BLI_assert(pool->flag & BLI_MEMPOOL_ALLOW_ITER);
+
+ BLI_mempool_iter *iter_arr = MEM_mallocN(sizeof(*iter_arr) * num_iter, __func__);
+ BLI_mempool_chunk **curchunk_threaded_shared = MEM_mallocN(sizeof(void *), __func__);
+
+ BLI_mempool_iternew(pool, iter_arr);
+
+ *curchunk_threaded_shared = iter_arr->curchunk;
+ iter_arr->curchunk_threaded_shared = curchunk_threaded_shared;
+
+ for (size_t i = 1; i < num_iter; i++) {
+ iter_arr[i] = iter_arr[0];
+ *curchunk_threaded_shared = iter_arr[i].curchunk = (*curchunk_threaded_shared) ? (*curchunk_threaded_shared)->next : NULL;
+ }
+
+ return iter_arr;
+}
+
+void BLI_mempool_iter_threadsafe_free(BLI_mempool_iter *iter_arr)
+{
+ BLI_assert(iter_arr->curchunk_threaded_shared != NULL);
+
+ MEM_freeN(iter_arr->curchunk_threaded_shared);
+ MEM_freeN(iter_arr);
}
#if 0
@@ -571,15 +614,28 @@ static void *bli_mempool_iternext(BLI_mempool_iter *iter)
{
void *ret = NULL;
- if (!iter->curchunk || !iter->pool->totused) return NULL;
+ if (iter->curchunk == NULL || !iter->pool->totused) {
+ return ret;
+ }
ret = ((char *)CHUNK_DATA(iter->curchunk)) + (iter->pool->esize * iter->curindex);
iter->curindex++;
if (iter->curindex == iter->pool->pchunk) {
- iter->curchunk = iter->curchunk->next;
iter->curindex = 0;
+ if (iter->curchunk_threaded_shared) {
+ while (1) {
+ iter->curchunk = *iter->curchunk_threaded_shared;
+ if (iter->curchunk == NULL) {
+ return ret;
+ }
+ if (atomic_cas_ptr((void **)iter->curchunk_threaded_shared, iter->curchunk, iter->curchunk->next) == iter->curchunk) {
+ break;
+ }
+ }
+ }
+ iter->curchunk = iter->curchunk->next;
}
return ret;
@@ -609,7 +665,7 @@ void *BLI_mempool_iterstep(BLI_mempool_iter *iter)
return NULL;
}
- const unsigned int esize = iter->pool->esize;
+ const uint esize = iter->pool->esize;
BLI_freenode *curnode = POINTER_OFFSET(CHUNK_DATA(iter->curchunk), (esize * iter->curindex));
BLI_freenode *ret;
do {
@@ -620,8 +676,18 @@ void *BLI_mempool_iterstep(BLI_mempool_iter *iter)
}
else {
iter->curindex = 0;
+ if (iter->curchunk_threaded_shared) {
+ for (iter->curchunk = *iter->curchunk_threaded_shared;
+ (iter->curchunk != NULL) &&
+ (atomic_cas_ptr((void **)iter->curchunk_threaded_shared, iter->curchunk, iter->curchunk->next) != iter->curchunk);
+ iter->curchunk = *iter->curchunk_threaded_shared);
+
+ if (UNLIKELY(iter->curchunk == NULL)) {
+ return (ret->freeword == FREEWORD) ? NULL : ret;
+ }
+ }
iter->curchunk = iter->curchunk->next;
- if (iter->curchunk == NULL) {
+ if (UNLIKELY(iter->curchunk == NULL)) {
return (ret->freeword == FREEWORD) ? NULL : ret;
}
curnode = CHUNK_DATA(iter->curchunk);
@@ -643,7 +709,7 @@ void BLI_mempool_clear_ex(BLI_mempool *pool, const int totelem_reserve)
{
BLI_mempool_chunk *mpchunk;
BLI_mempool_chunk *mpchunk_next;
- unsigned int maxchunks;
+ uint maxchunks;
BLI_mempool_chunk *chunks_temp;
BLI_freenode *lasttail = NULL;
@@ -657,7 +723,7 @@ void BLI_mempool_clear_ex(BLI_mempool *pool, const int totelem_reserve)
maxchunks = pool->maxchunks;
}
else {
- maxchunks = mempool_maxchunks((unsigned int)totelem_reserve, pool->pchunk);
+ maxchunks = mempool_maxchunks((uint)totelem_reserve, pool->pchunk);
}
/* free all after pool->maxchunks */
diff --git a/source/blender/blenlib/intern/array_store.c b/source/blender/blenlib/intern/array_store.c
index 874130a315c..df93dad4c32 100644
--- a/source/blender/blenlib/intern/array_store.c
+++ b/source/blender/blenlib/intern/array_store.c
@@ -222,7 +222,7 @@ typedef uint64_t hash_key;
typedef struct BArrayInfo {
size_t chunk_stride;
- uint chunk_count;
+ // uint chunk_count; /* UNUSED (other values are derived from this) */
/* pre-calculated */
size_t chunk_byte_size;
@@ -299,7 +299,7 @@ typedef struct BChunk {
} BChunk;
/**
- * Links to store #BChunk data in #BChunkList.chunks.
+ * Links to store #BChunk data in #BChunkList.chunk_refs.
*/
typedef struct BChunkRef {
struct BChunkRef *next, *prev;
@@ -425,12 +425,12 @@ static void bchunk_list_decref(
static size_t bchunk_list_data_check(
const BChunkList *chunk_list, const uchar *data)
{
- size_t total_size = 0;
+ size_t offset = 0;
for (BChunkRef *cref = chunk_list->chunk_refs.first; cref; cref = cref->next) {
- if (memcmp(&data[total_size], cref->link->data, cref->link->data_len) != 0) {
+ if (memcmp(&data[offset], cref->link->data, cref->link->data_len) != 0) {
return false;
}
- total_size += cref->link->data_len;
+ offset += cref->link->data_len;
}
return true;
}
@@ -598,7 +598,6 @@ static void bchunk_list_append_data(
{
BLI_assert(data_len != 0);
- // printf("data_len: %d\n", data_len);
#ifdef USE_MERGE_CHUNKS
BLI_assert(data_len <= info->chunk_byte_size_max);
@@ -636,7 +635,7 @@ static void bchunk_list_append_data(
/* don't run this, instead preemptively avoid creating a chunk only to merge it (above). */
#if 0
#ifdef USE_MERGE_CHUNKS
- bchunk_list_ensure_min_size_last(info, bs_mem, chunk_list, chunk_size_min);
+ bchunk_list_ensure_min_size_last(info, bs_mem, chunk_list);
#endif
#endif
}
@@ -750,6 +749,7 @@ static void bchunk_list_fill_from_array(
ASSERT_CHUNKLIST_DATA(chunk_list, data);
}
+/** \} */
/* ---------------------------------------------------------------------------
* Internal Table Lookup Functions
@@ -764,7 +764,7 @@ static void bchunk_list_fill_from_array(
BLI_INLINE uint hash_data_single(const uchar p)
{
- return (HASH_INIT << 5) + HASH_INIT + (unsigned int)p;
+ return ((HASH_INIT << 5) + HASH_INIT) + (unsigned int)(*((signed char *)&p));
}
/* hash bytes, from BLI_ghashutil_strhash_n */
@@ -774,7 +774,7 @@ static uint hash_data(const uchar *key, size_t n)
unsigned int h = HASH_INIT;
for (p = (const signed char *)key; n--; p++) {
- h = (h << 5) + h + (unsigned int)*p;
+ h = ((h << 5) + h) + (unsigned int)*p;
}
return h;
@@ -874,12 +874,12 @@ static void hash_accum_single(hash_key *hash_array, const size_t hash_array_len,
static hash_key key_from_chunk_ref(
const BArrayInfo *info, const BChunkRef *cref,
- /* avoid reallicating each time */
+ /* avoid reallocating each time */
hash_key *hash_store, const size_t hash_store_len)
{
/* in C, will fill in a reusable array */
BChunk *chunk = cref->link;
- BLI_assert(info->accum_read_ahead_bytes * info->chunk_stride);
+ BLI_assert((info->accum_read_ahead_bytes * info->chunk_stride) != 0);
if (info->accum_read_ahead_bytes <= chunk->data_len) {
hash_key key;
@@ -896,7 +896,7 @@ static hash_key key_from_chunk_ref(
key = hash_store[0];
/* cache the key */
- if (key == HASH_TABLE_KEY_UNSET) {
+ if (UNLIKELY(key == HASH_TABLE_KEY_UNSET)) {
key = HASH_TABLE_KEY_FALLBACK;
}
chunk->key = key;
@@ -931,7 +931,7 @@ static const BChunkRef *table_lookup(
size_t size_left = data_len - offset;
hash_key key = table_hash_array[((offset - i_table_start) / info->chunk_stride)];
size_t key_index = (size_t)(key % (hash_key)table_len);
- for (BTableRef *tref = table[key_index]; tref; tref = tref->next) {
+ for (const BTableRef *tref = table[key_index]; tref; tref = tref->next) {
const BChunkRef *cref = tref->cref;
#ifdef USE_HASH_TABLE_KEY_CACHE
if (cref->link->key == key)
@@ -1014,6 +1014,10 @@ static const BChunkRef *table_lookup(
/** \} */
+/** \name Main Data De-Duplication Function
+ *
+ * \{ */
+
/**
* \param data: Data to store in the returned value.
* \param data_len_original: Length of data in bytes.
@@ -1039,10 +1043,8 @@ static BChunkList *bchunk_list_from_data_merge(
size_t i_prev = 0;
#ifdef USE_FASTPATH_CHUNKS_FIRST
- bool full_match = false;
-
{
- full_match = true;
+ bool full_match = true;
const BChunkRef *cref = chunk_list_reference->chunk_refs.first;
while (i_prev < data_len_original) {
@@ -1430,7 +1432,7 @@ BArrayStore *BLI_array_store_create(
BArrayStore *bs = MEM_callocN(sizeof(BArrayStore), __func__);
bs->info.chunk_stride = stride;
- bs->info.chunk_count = chunk_count;
+ // bs->info.chunk_count = chunk_count;
bs->info.chunk_byte_size = chunk_count * stride;
#ifdef USE_MERGE_CHUNKS
@@ -1507,6 +1509,8 @@ void BLI_array_store_clear(
BLI_mempool_clear(bs->memory.chunk);
}
+/** \} */
+
/** \name BArrayStore Statistics
* \{ */
@@ -1563,7 +1567,7 @@ BArrayState *BLI_array_store_state_add(
const void *data, const size_t data_len,
const BArrayState *state_reference)
{
- /* ensure we're aligned to the stride */
+ /* ensure we're aligned to the stride */
BLI_assert((data_len % bs->info.chunk_stride) == 0);
#ifdef USE_PARANOID_CHECKS
@@ -1762,7 +1766,7 @@ bool BLI_array_store_is_valid(
goto user_finally;
}
}
- if (!(BLI_mempool_count(bs->memory.chunk_list) == (int)BLI_ghash_size(chunk_list_map))) {
+ if (!(BLI_mempool_len(bs->memory.chunk_list) == (int)BLI_ghash_len(chunk_list_map))) {
ok = false;
goto user_finally;
}
@@ -1775,11 +1779,11 @@ bool BLI_array_store_is_valid(
totrefs += 1;
}
}
- if (!(BLI_mempool_count(bs->memory.chunk) == (int)BLI_ghash_size(chunk_map))) {
+ if (!(BLI_mempool_len(bs->memory.chunk) == (int)BLI_ghash_len(chunk_map))) {
ok = false;
goto user_finally;
}
- if (!(BLI_mempool_count(bs->memory.chunk_ref) == totrefs)) {
+ if (!(BLI_mempool_len(bs->memory.chunk_ref) == totrefs)) {
ok = false;
goto user_finally;
}
diff --git a/source/blender/blenlib/intern/array_utils.c b/source/blender/blenlib/intern/array_utils.c
index 32f0111babd..7b2d35a763c 100644
--- a/source/blender/blenlib/intern/array_utils.c
+++ b/source/blender/blenlib/intern/array_utils.c
@@ -308,3 +308,20 @@ bool _bli_array_iter_span(
return false;
}
+
+/**
+ * Simple utility to check memory is zeroed.
+ */
+bool _bli_array_is_zeroed(
+ const void *arr_v,
+ unsigned int arr_len, size_t arr_stride)
+{
+ const char *arr_step = (const char *)arr_v;
+ size_t i = arr_stride * arr_len;
+ while (i--) {
+ if (*(arr_step++)) {
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/source/blender/blenlib/intern/astar.c b/source/blender/blenlib/intern/astar.c
index 0020dbe4612..1b57dc5a683 100644
--- a/source/blender/blenlib/intern/astar.c
+++ b/source/blender/blenlib/intern/astar.c
@@ -231,7 +231,7 @@ bool BLI_astar_graph_solve(
SET_INT_IN_POINTER(node_index_src));
while (!BLI_heap_is_empty(todo_nodes)) {
- const int node_curr_idx = GET_INT_FROM_POINTER(BLI_heap_popmin(todo_nodes));
+ const int node_curr_idx = GET_INT_FROM_POINTER(BLI_heap_pop_min(todo_nodes));
BLI_AStarGNode *node_curr = &as_graph->nodes[node_curr_idx];
LinkData *ld;
diff --git a/source/blender/blenlib/intern/bitmap_draw_2d.c b/source/blender/blenlib/intern/bitmap_draw_2d.c
index e77e8cf40d0..f2ec75001b4 100644
--- a/source/blender/blenlib/intern/bitmap_draw_2d.c
+++ b/source/blender/blenlib/intern/bitmap_draw_2d.c
@@ -42,7 +42,8 @@
#include "BLI_strict_flags.h"
/* -------------------------------------------------------------------- */
-/* Draw Line */
+/** \name Draw Line
+ * \{ */
/**
* Plot a line from \a p1 to \a p2 (inclusive).
@@ -51,7 +52,7 @@
*/
void BLI_bitmap_draw_2d_line_v2v2i(
const int p1[2], const int p2[2],
- bool (*callback)(int, int, void *), void *userData)
+ bool (*callback)(int, int, void *), void *user_data)
{
/* Bresenham's line algorithm. */
int x1 = p1[0];
@@ -59,7 +60,7 @@ void BLI_bitmap_draw_2d_line_v2v2i(
int x2 = p2[0];
int y2 = p2[1];
- if (callback(x1, y1, userData) == 0) {
+ if (callback(x1, y1, user_data) == 0) {
return;
}
@@ -90,7 +91,7 @@ void BLI_bitmap_draw_2d_line_v2v2i(
x1 += sign_x;
error += delta_y_step;
- if (callback(x1, y1, userData) == 0) {
+ if (callback(x1, y1, user_data) == 0) {
return;
}
}
@@ -112,16 +113,193 @@ void BLI_bitmap_draw_2d_line_v2v2i(
y1 += sign_y;
error += delta_x_step;
- if (callback(x1, y1, userData) == 0) {
+ if (callback(x1, y1, user_data) == 0) {
return;
}
}
}
}
+/** \} */
/* -------------------------------------------------------------------- */
-/* Draw Filled Polygon */
+/** \name Draw Filled Triangle
+ * \{ */
+
+/**
+ * Fill a triangle
+ *
+ * Standard algorithm,
+ * See: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html
+ *
+ * Changes to the basic implementation:
+ *
+ * - Reuse slope calculation when drawing the second triangle.
+ * - Don't calculate the 4th point at all for the triangle split.
+ * - Order line drawing from left to right (minor detail).
+ * - 1-pixel offsets are applied so adjacent triangles don't overlap.
+ *
+ * This is not clipped, a clipped version can be added if needed.
+ */
+
+/* Macros could be moved to a shared location. */
+#define ORDERED_SWAP(ty, a, b) \
+ if (a > b) { SWAP(ty, a, b); } ((void)0)
+
+#define ORDERED_SWAP_BY(ty, a, b, by) \
+ if ((a by) > (b by)) { SWAP(ty, a, b); } ((void)0)
+
+#define ORDER_VARS2(ty, a, b) \
+ { ORDERED_SWAP(ty, a, b); } ((void)0)
+
+#define ORDER_VARS3_BY(ty, a, b, c, by) \
+ { \
+ ORDERED_SWAP_BY(ty, b, c, by); \
+ ORDERED_SWAP_BY(ty, a, c, by); \
+ ORDERED_SWAP_BY(ty, a, b, by); \
+ } ((void)0)
+
+static float inv_slope(const int a[2], const int b[2])
+{
+ return ((float)(a[0] - b[0]) /
+ (float)(a[1] - b[1]));
+}
+
+/**
+ * <pre>
+ * *---*
+ * \ /
+ * *
+ * </pre>
+ */
+static void draw_tri_flat_max(
+ const int p[2],
+ const int max_y,
+ const float inv_slope1,
+ const float inv_slope2,
+ void (*callback)(int x, int x_end, int y, void *),
+ void *user_data)
+{
+ float cur_x1 = (float)p[0];
+ float cur_x2 = cur_x1;
+ /* start-end inclusive */
+ const int min_y = p[1];
+ const int max_y_end = max_y + 1;
+ for (int scanline_y = min_y; scanline_y != max_y_end; scanline_y += 1) {
+ callback((int)cur_x1, 1 + (int)cur_x2, scanline_y, user_data);
+ cur_x1 += inv_slope1;
+ cur_x2 += inv_slope2;
+ }
+}
+
+/**
+ * <pre>
+ * *
+ * / \
+ * *---*
+ * </pre>
+ */
+static void draw_tri_flat_min(
+ const int p[2],
+ const int min_y,
+ const float inv_slope1,
+ const float inv_slope2,
+ void (*callback)(int x, int x_end, int y, void *),
+ void *user_data)
+{
+ float cur_x1 = (float)p[0];
+ float cur_x2 = cur_x1;
+ /* start-end inclusive */
+ const int max_y = p[1];
+ const int min_y_end = min_y - 1;
+ for (int scanline_y = max_y; scanline_y != min_y_end; scanline_y -= 1) {
+ callback((int)cur_x1, 1 + (int)cur_x2, scanline_y, user_data);
+ cur_x1 -= inv_slope1;
+ cur_x2 -= inv_slope2;
+ }
+}
+
+/**
+ * \note Unclipped (clipped version can be added if needed).
+ */
+void BLI_bitmap_draw_2d_tri_v2i(
+ /* all 2d */
+ const int p1[2],
+ const int p2[2],
+ const int p3[2],
+ void (*callback)(int x, int x_end, int y, void *),
+ void *user_data)
+{
+ /* At first sort the three vertices by y-coordinate ascending so p1 is the top-most vertice */
+ ORDER_VARS3_BY(const int *, p1, p2, p3, [1]);
+
+ BLI_assert(p1[1] <= p2[1] && p2[1] <= p3[1]);
+
+ /* Check for trivial case of bottom-flat triangle. */
+ if (p2[1] == p3[1]) {
+ float inv_slope1 = inv_slope(p2, p1);
+ float inv_slope2 = inv_slope(p3, p1);
+ ORDER_VARS2(float, inv_slope1, inv_slope2);
+ BLI_assert(!(inv_slope1 > inv_slope2));
+ draw_tri_flat_max(
+ p1, p2[1],
+ inv_slope1, inv_slope2,
+ callback, user_data);
+ }
+ else if (p1[1] == p2[1]) {
+ /* Check for trivial case of top-flat triangle. */
+ float inv_slope1 = inv_slope(p3, p1);
+ float inv_slope2 = inv_slope(p3, p2);
+ ORDER_VARS2(float, inv_slope2, inv_slope1);
+ BLI_assert(!(inv_slope1 < inv_slope2));
+ draw_tri_flat_min(
+ p3, p2[1] + 1, /* avoid overlap */
+ inv_slope1, inv_slope2,
+ callback, user_data);
+ }
+ else {
+ /* General case - split the triangle in a top-flat and bottom-flat one. */
+ const float inv_slope_p21 = inv_slope(p2, p1);
+ const float inv_slope_p31 = inv_slope(p3, p1);
+ const float inv_slope_p32 = inv_slope(p3, p2);
+
+ float inv_slope1_max, inv_slope2_max;
+ float inv_slope2_min, inv_slope1_min;
+
+ if (inv_slope_p21 < inv_slope_p31) {
+ inv_slope1_max = inv_slope_p21;
+ inv_slope2_max = inv_slope_p31;
+ inv_slope2_min = inv_slope_p31;
+ inv_slope1_min = inv_slope_p32;
+ }
+ else {
+ inv_slope1_max = inv_slope_p31;
+ inv_slope2_max = inv_slope_p21;
+ inv_slope2_min = inv_slope_p32;
+ inv_slope1_min = inv_slope_p31;
+ }
+
+ draw_tri_flat_max(
+ p1, p2[1],
+ inv_slope1_max, inv_slope2_max,
+ callback, user_data);
+ draw_tri_flat_min(
+ p3, p2[1] + 1, /* avoid overlap */
+ inv_slope1_min, inv_slope2_min,
+ callback, user_data);
+ }
+}
+
+#undef ORDERED_SWAP
+#undef ORDERED_SWAP_BY
+#undef ORDER_VARS2
+#undef ORDER_VARS3_BY
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Draw Filled Polygon
+ * \{ */
/* sort edge-segments on y, then x axis */
static int draw_poly_v2i_n__span_y_sort(const void *a_p, const void *b_p, void *verts_p)
@@ -162,7 +340,7 @@ static int draw_poly_v2i_n__span_y_sort(const void *a_p, const void *b_p, void *
}
/**
- * Draws a filled polyon with support for self intersections.
+ * Draws a filled polygon with support for self intersections.
*
* \param callback: Takes the x, y coords and x-span (\a x_end is not inclusive),
* note that \a x_end will always be greater than \a x, so we can use:
@@ -175,16 +353,16 @@ static int draw_poly_v2i_n__span_y_sort(const void *a_p, const void *b_p, void *
*/
void BLI_bitmap_draw_2d_poly_v2i_n(
const int xmin, const int ymin, const int xmax, const int ymax,
- const int verts[][2], const int nr,
- void (*callback)(int x, int x_end, int y, void *), void *userData)
+ const int verts[][2], const int verts_len,
+ void (*callback)(int x, int x_end, int y, void *), void *user_data)
{
/* Originally by Darel Rex Finley, 2007.
* Optimized by Campbell Barton, 2016 to track sorted intersections. */
- int (*span_y)[2] = MEM_mallocN(sizeof(*span_y) * (size_t)nr, __func__);
+ int (*span_y)[2] = MEM_mallocN(sizeof(*span_y) * (size_t)verts_len, __func__);
int span_y_len = 0;
- for (int i_curr = 0, i_prev = nr - 1; i_curr < nr; i_prev = i_curr++) {
+ for (int i_curr = 0, i_prev = verts_len - 1; i_curr < verts_len; i_prev = i_curr++) {
const int *co_prev = verts[i_prev];
const int *co_curr = verts[i_curr];
@@ -213,7 +391,7 @@ void BLI_bitmap_draw_2d_poly_v2i_n(
struct NodeX {
int span_y_index;
int x;
- } *node_x = MEM_mallocN(sizeof(*node_x) * (size_t)(nr + 1), __func__);
+ } *node_x = MEM_mallocN(sizeof(*node_x) * (size_t)(verts_len + 1), __func__);
int node_x_len = 0;
int span_y_index = 0;
@@ -294,7 +472,7 @@ void BLI_bitmap_draw_2d_poly_v2i_n(
}
/* for single call per x-span */
if (x_src < x_dst) {
- callback(x_src - xmin, x_dst - xmin, pixel_y - ymin, userData);
+ callback(x_src - xmin, x_dst - xmin, pixel_y - ymin, user_data);
}
}
}
@@ -334,3 +512,5 @@ void BLI_bitmap_draw_2d_poly_v2i_n(
MEM_freeN(span_y);
MEM_freeN(node_x);
}
+
+/** \} */
diff --git a/source/blender/blenlib/intern/boxpack2d.c b/source/blender/blenlib/intern/boxpack_2d.c
index 2db52cbda60..cf9e29209fb 100644
--- a/source/blender/blenlib/intern/boxpack2d.c
+++ b/source/blender/blenlib/intern/boxpack_2d.c
@@ -20,7 +20,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/blenlib/intern/boxpack2d.c
+/** \file blender/blenlib/intern/boxpack_2d.c
* \ingroup bli
*/
@@ -30,7 +30,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_boxpack2d.h" /* own include */
+#include "BLI_boxpack_2d.h" /* own include */
#include "BLI_sort.h" /* qsort_r */
#define qsort_r BLI_qsort_r
@@ -56,10 +56,10 @@ typedef struct BoxVert {
float x;
float y;
- int free : 8; /* vert status */
- unsigned int used : 1;
- unsigned int _pad : 23;
- unsigned int index;
+ int free : 8; /* vert status */
+ uint used : 1;
+ uint _pad : 23;
+ uint index;
struct BoxPack *trb; /* top right box */
struct BoxPack *blb; /* bottom left box */
@@ -92,7 +92,7 @@ typedef struct BoxVert {
#define BRF 8
#define CORNERFLAGS (BLF | TRF | TLF | BRF)
-BLI_INLINE int quad_flag(unsigned int q)
+BLI_INLINE int quad_flag(uint q)
{
BLI_assert(q < 4);
return (1 << q);
@@ -241,8 +241,8 @@ static int vertex_sort(const void *p1, const void *p2, void *vs_ctx_p)
const BoxVert *v1, *v2;
float a1, a2;
- v1 = &vs_ctx->vertarray[*((const unsigned int *)p1)];
- v2 = &vs_ctx->vertarray[*((const unsigned int *)p2)];
+ v1 = &vs_ctx->vertarray[*((const uint *)p1)];
+ v2 = &vs_ctx->vertarray[*((const uint *)p2)];
#ifdef USE_FREE_STRIP
/* push free verts to the end so we can strip */
@@ -280,10 +280,10 @@ static int vertex_sort(const void *p1, const void *p2, void *vs_ctx_p)
* \param len: the number of boxes in the array.
* \param r_tot_x, r_tot_y: set so you can normalize the data.
* */
-void BLI_box_pack_2d(BoxPack *boxarray, const unsigned int len, float *r_tot_x, float *r_tot_y)
+void BLI_box_pack_2d(BoxPack *boxarray, const uint len, float *r_tot_x, float *r_tot_y)
{
- unsigned int box_index, verts_pack_len, i, j, k;
- unsigned int *vertex_pack_indices; /* an array of indices used for sorting verts */
+ uint box_index, verts_pack_len, i, j, k;
+ uint *vertex_pack_indices; /* an array of indices used for sorting verts */
bool isect;
float tot_x = 0.0f, tot_y = 0.0f;
diff --git a/source/blender/blenlib/intern/convexhull2d.c b/source/blender/blenlib/intern/convexhull_2d.c
index 740f3cce4a4..38928dbbaa0 100644
--- a/source/blender/blenlib/intern/convexhull2d.c
+++ b/source/blender/blenlib/intern/convexhull_2d.c
@@ -18,7 +18,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/blenlib/intern/convexhull2d.c
+/** \file blender/blenlib/intern/convexhull_2d.c
* \ingroup bli
*/
@@ -28,7 +28,7 @@
#include "MEM_guardedalloc.h"
-#include "BLI_convexhull2d.h"
+#include "BLI_convexhull_2d.h"
#include "BLI_math.h"
#include "BLI_strict_flags.h"
#include "BLI_utildefines.h"
@@ -209,7 +209,7 @@ int BLI_convexhull_2d(const float (*points)[2], const int n, int r_points[])
memcpy(points_sort[i], points_ref[i].pt, sizeof(float[2]));
}
- tot = BLI_convexhull_2d_sorted((const float (*)[2])points_sort, n, r_points);
+ tot = BLI_convexhull_2d_sorted(points_sort, n, r_points);
/* map back to the original index values */
points_map = (int *)points_sort; /* abuse float array for temp storage */
@@ -305,7 +305,7 @@ float BLI_convexhull_aabb_fit_points_2d(const float (*points)[2], unsigned int n
index_map = MEM_mallocN(sizeof(*index_map) * n * 2, __func__);
- tot = BLI_convexhull_2d((const float (*)[2])points, (int)n, index_map);
+ tot = BLI_convexhull_2d(points, (int)n, index_map);
if (tot) {
float (*points_hull)[2];
@@ -316,7 +316,7 @@ float BLI_convexhull_aabb_fit_points_2d(const float (*points)[2], unsigned int n
copy_v2_v2(points_hull[j], points[index_map[j]]);
}
- angle = BLI_convexhull_aabb_fit_hull_2d((const float (*)[2])points_hull, (unsigned int)tot);
+ angle = BLI_convexhull_aabb_fit_hull_2d(points_hull, (unsigned int)tot);
MEM_freeN(points_hull);
}
else {
diff --git a/source/blender/blenlib/intern/edgehash.c b/source/blender/blenlib/intern/edgehash.c
index 358b5b5696f..7074a776aaf 100644
--- a/source/blender/blenlib/intern/edgehash.c
+++ b/source/blender/blenlib/intern/edgehash.c
@@ -42,7 +42,7 @@
#include "BLI_strict_flags.h"
/**************inlined code************/
-static const unsigned int _ehash_hashsizes[] = {
+static const uint _ehash_hashsizes[] = {
1, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031, 2053, 4099, 8209,
16411, 32771, 65537, 131101, 262147, 524309, 1048583, 2097169,
4194319, 8388617, 16777259, 33554467, 67108879, 134217757,
@@ -62,22 +62,22 @@ static const unsigned int _ehash_hashsizes[] = {
/* ensure v0 is smaller */
#define EDGE_ORD(v0, v1) \
if (v0 > v1) { \
- SWAP(unsigned int, v0, v1); \
+ SWAP(uint, v0, v1); \
} (void)0
/***/
typedef struct EdgeEntry {
struct EdgeEntry *next;
- unsigned int v0, v1;
+ uint v0, v1;
void *val;
} EdgeEntry;
struct EdgeHash {
EdgeEntry **buckets;
BLI_mempool *epool;
- unsigned int nbuckets, nentries;
- unsigned int cursize, flag;
+ uint nbuckets, nentries;
+ uint cursize, flag;
};
@@ -90,7 +90,7 @@ struct EdgeHash {
/**
* Compute the hash and get the bucket-index.
*/
-BLI_INLINE unsigned int edgehash_bucket_index(EdgeHash *eh, unsigned int v0, unsigned int v1)
+BLI_INLINE uint edgehash_bucket_index(EdgeHash *eh, uint v0, uint v1)
{
BLI_assert(v0 < v1);
@@ -100,7 +100,7 @@ BLI_INLINE unsigned int edgehash_bucket_index(EdgeHash *eh, unsigned int v0, uns
/**
* Check if the number of items in the GHash is large enough to require more buckets.
*/
-BLI_INLINE bool edgehash_test_expand_buckets(const unsigned int nentries, const unsigned int nbuckets)
+BLI_INLINE bool edgehash_test_expand_buckets(const uint nentries, const uint nbuckets)
{
return (nentries > nbuckets * 3);
}
@@ -108,12 +108,12 @@ BLI_INLINE bool edgehash_test_expand_buckets(const unsigned int nentries, const
/**
* Expand buckets to the next size up.
*/
-BLI_INLINE void edgehash_resize_buckets(EdgeHash *eh, const unsigned int nbuckets)
+BLI_INLINE void edgehash_resize_buckets(EdgeHash *eh, const uint nbuckets)
{
EdgeEntry **buckets_old = eh->buckets;
EdgeEntry **buckets_new;
- const unsigned int nbuckets_old = eh->nbuckets;
- unsigned int i;
+ const uint nbuckets_old = eh->nbuckets;
+ uint i;
BLI_assert(eh->nbuckets != nbuckets);
@@ -136,7 +136,7 @@ BLI_INLINE void edgehash_resize_buckets(EdgeHash *eh, const unsigned int nbucket
/**
* Increase initial bucket size to match a reserved amount.
*/
-BLI_INLINE void edgehash_buckets_reserve(EdgeHash *eh, const unsigned int nentries_reserve)
+BLI_INLINE void edgehash_buckets_reserve(EdgeHash *eh, const uint nentries_reserve)
{
while (edgehash_test_expand_buckets(nentries_reserve, eh->nbuckets)) {
eh->nbuckets = _ehash_hashsizes[++eh->cursize];
@@ -148,8 +148,8 @@ BLI_INLINE void edgehash_buckets_reserve(EdgeHash *eh, const unsigned int nentri
* Takes a \a bucket_index argument to avoid calling #edgehash_bucket_index multiple times.
*/
BLI_INLINE EdgeEntry *edgehash_lookup_entry_ex(
- EdgeHash *eh, unsigned int v0, unsigned int v1,
- const unsigned int bucket_index)
+ EdgeHash *eh, uint v0, uint v1,
+ const uint bucket_index)
{
EdgeEntry *e;
BLI_assert(v0 < v1);
@@ -167,8 +167,8 @@ BLI_INLINE EdgeEntry *edgehash_lookup_entry_ex(
* Useful when modifying buckets somehow (like removing an entry...).
*/
BLI_INLINE EdgeEntry *edgehash_lookup_entry_prev_ex(
- EdgeHash *eh, unsigned int v0, unsigned int v1,
- EdgeEntry **r_e_prev, const unsigned int bucket_index)
+ EdgeHash *eh, uint v0, uint v1,
+ EdgeEntry **r_e_prev, const uint bucket_index)
{
BLI_assert(v0 < v1);
for (EdgeEntry *e_prev = NULL, *e = eh->buckets[bucket_index]; e; e_prev = e, e = e->next) {
@@ -185,17 +185,17 @@ BLI_INLINE EdgeEntry *edgehash_lookup_entry_prev_ex(
/**
* Internal lookup function. Only wraps #edgehash_lookup_entry_ex
*/
-BLI_INLINE EdgeEntry *edgehash_lookup_entry(EdgeHash *eh, unsigned int v0, unsigned int v1)
+BLI_INLINE EdgeEntry *edgehash_lookup_entry(EdgeHash *eh, uint v0, uint v1)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
return edgehash_lookup_entry_ex(eh, v0, v1, bucket_index);
}
static EdgeHash *edgehash_new(const char *info,
- const unsigned int nentries_reserve,
- const unsigned int entry_size)
+ const uint nentries_reserve,
+ const uint entry_size)
{
EdgeHash *eh = MEM_mallocN(sizeof(*eh), info);
@@ -220,8 +220,8 @@ static EdgeHash *edgehash_new(const char *info,
* Takes a \a bucket_index argument to avoid calling #edgehash_bucket_index multiple times.
*/
BLI_INLINE void edgehash_insert_ex(
- EdgeHash *eh, unsigned int v0, unsigned int v1, void *val,
- const unsigned int bucket_index)
+ EdgeHash *eh, uint v0, uint v1, void *val,
+ const uint bucket_index)
{
EdgeEntry *e = BLI_mempool_alloc(eh->epool);
@@ -247,8 +247,8 @@ BLI_INLINE void edgehash_insert_ex(
* Insert function that doesn't set the value (use for EdgeSet)
*/
BLI_INLINE void edgehash_insert_ex_keyonly(
- EdgeHash *eh, unsigned int v0, unsigned int v1,
- const unsigned int bucket_index)
+ EdgeHash *eh, uint v0, uint v1,
+ const uint bucket_index)
{
EdgeEntry *e = BLI_mempool_alloc(eh->epool);
@@ -272,8 +272,8 @@ BLI_INLINE void edgehash_insert_ex_keyonly(
* Insert function that doesn't set the value (use for EdgeSet)
*/
BLI_INLINE void edgehash_insert_ex_keyonly_entry(
- EdgeHash *eh, unsigned int v0, unsigned int v1,
- const unsigned int bucket_index,
+ EdgeHash *eh, uint v0, uint v1,
+ const uint bucket_index,
EdgeEntry *e)
{
BLI_assert((eh->flag & EDGEHASH_FLAG_ALLOW_DUPES) || (BLI_edgehash_haskey(eh, v0, v1) == 0));
@@ -293,10 +293,10 @@ BLI_INLINE void edgehash_insert_ex_keyonly_entry(
}
}
-BLI_INLINE void edgehash_insert(EdgeHash *eh, unsigned int v0, unsigned int v1, void *val)
+BLI_INLINE void edgehash_insert(EdgeHash *eh, uint v0, uint v1, void *val)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
edgehash_insert_ex(eh, v0, v1, val, bucket_index);
}
@@ -304,9 +304,9 @@ BLI_INLINE void edgehash_insert(EdgeHash *eh, unsigned int v0, unsigned int v1,
* Remove the entry and return it, caller must free from eh->epool.
*/
BLI_INLINE EdgeEntry *edgehash_remove_ex(
- EdgeHash *eh, unsigned int v0, unsigned int v1,
+ EdgeHash *eh, uint v0, uint v1,
EdgeHashFreeFP valfreefp,
- const unsigned int bucket_index)
+ const uint bucket_index)
{
EdgeEntry *e_prev;
EdgeEntry *e = edgehash_lookup_entry_prev_ex(eh, v0, v1, &e_prev, bucket_index);
@@ -339,7 +339,7 @@ BLI_INLINE EdgeEntry *edgehash_remove_ex(
*/
static void edgehash_free_cb(EdgeHash *eh, EdgeHashFreeFP valfreefp)
{
- unsigned int i;
+ uint i;
BLI_assert(valfreefp);
@@ -365,7 +365,7 @@ static void edgehash_free_cb(EdgeHash *eh, EdgeHashFreeFP valfreefp)
/* Public API */
EdgeHash *BLI_edgehash_new_ex(const char *info,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
return edgehash_new(info,
nentries_reserve,
@@ -381,7 +381,7 @@ EdgeHash *BLI_edgehash_new(const char *info)
* Insert edge (\a v0, \a v1) into hash with given value, does
* not check for duplicates.
*/
-void BLI_edgehash_insert(EdgeHash *eh, unsigned int v0, unsigned int v1, void *val)
+void BLI_edgehash_insert(EdgeHash *eh, uint v0, uint v1, void *val)
{
edgehash_insert(eh, v0, v1, val);
}
@@ -389,12 +389,12 @@ void BLI_edgehash_insert(EdgeHash *eh, unsigned int v0, unsigned int v1, void *v
/**
* Assign a new value to a key that may already be in edgehash.
*/
-bool BLI_edgehash_reinsert(EdgeHash *eh, unsigned int v0, unsigned int v1, void *val)
+bool BLI_edgehash_reinsert(EdgeHash *eh, uint v0, uint v1, void *val)
{
IS_EDGEHASH_ASSERT(eh);
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
EdgeEntry *e = edgehash_lookup_entry_ex(eh, v0, v1, bucket_index);
if (e) {
@@ -411,7 +411,7 @@ bool BLI_edgehash_reinsert(EdgeHash *eh, unsigned int v0, unsigned int v1, void
* Return pointer to value for given edge (\a v0, \a v1),
* or NULL if key does not exist in hash.
*/
-void **BLI_edgehash_lookup_p(EdgeHash *eh, unsigned int v0, unsigned int v1)
+void **BLI_edgehash_lookup_p(EdgeHash *eh, uint v0, uint v1)
{
EdgeEntry *e = edgehash_lookup_entry(eh, v0, v1);
IS_EDGEHASH_ASSERT(eh);
@@ -432,10 +432,10 @@ void **BLI_edgehash_lookup_p(EdgeHash *eh, unsigned int v0, unsigned int v1)
* \returns true when the value didn't need to be added.
* (when false, the caller _must_ initialize the value).
*/
-bool BLI_edgehash_ensure_p(EdgeHash *eh, unsigned int v0, unsigned int v1, void ***r_val)
+bool BLI_edgehash_ensure_p(EdgeHash *eh, uint v0, uint v1, void ***r_val)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
EdgeEntry *e = edgehash_lookup_entry_ex(eh, v0, v1, bucket_index);
const bool haskey = (e != NULL);
@@ -454,7 +454,7 @@ bool BLI_edgehash_ensure_p(EdgeHash *eh, unsigned int v0, unsigned int v1, void
* to differentiate between key-value being NULL and
* lack of key then see BLI_edgehash_lookup_p().
*/
-void *BLI_edgehash_lookup(EdgeHash *eh, unsigned int v0, unsigned int v1)
+void *BLI_edgehash_lookup(EdgeHash *eh, uint v0, uint v1)
{
EdgeEntry *e = edgehash_lookup_entry(eh, v0, v1);
IS_EDGEHASH_ASSERT(eh);
@@ -464,7 +464,7 @@ void *BLI_edgehash_lookup(EdgeHash *eh, unsigned int v0, unsigned int v1)
/**
* A version of #BLI_edgehash_lookup which accepts a fallback argument.
*/
-void *BLI_edgehash_lookup_default(EdgeHash *eh, unsigned int v0, unsigned int v1, void *val_default)
+void *BLI_edgehash_lookup_default(EdgeHash *eh, uint v0, uint v1, void *val_default)
{
EdgeEntry *e = edgehash_lookup_entry(eh, v0, v1);
IS_EDGEHASH_ASSERT(eh);
@@ -478,10 +478,10 @@ void *BLI_edgehash_lookup_default(EdgeHash *eh, unsigned int v0, unsigned int v1
* \param valfreefp Optional callback to free the value.
* \return true if \a key was removed from \a eh.
*/
-bool BLI_edgehash_remove(EdgeHash *eh, unsigned int v0, unsigned int v1, EdgeHashFreeFP valfreefp)
+bool BLI_edgehash_remove(EdgeHash *eh, uint v0, uint v1, EdgeHashFreeFP valfreefp)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
EdgeEntry *e = edgehash_remove_ex(eh, v0, v1, valfreefp, bucket_index);
if (e) {
BLI_mempool_free(eh->epool, e);
@@ -500,10 +500,10 @@ bool BLI_edgehash_remove(EdgeHash *eh, unsigned int v0, unsigned int v1, EdgeHas
* \param v0, v1: The key to remove.
* \return the value of \a key int \a eh or NULL.
*/
-void *BLI_edgehash_popkey(EdgeHash *eh, unsigned int v0, unsigned int v1)
+void *BLI_edgehash_popkey(EdgeHash *eh, uint v0, uint v1)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index(eh, v0, v1);
+ const uint bucket_index = edgehash_bucket_index(eh, v0, v1);
EdgeEntry *e = edgehash_remove_ex(eh, v0, v1, NULL, bucket_index);
IS_EDGEHASH_ASSERT(eh);
if (e) {
@@ -519,7 +519,7 @@ void *BLI_edgehash_popkey(EdgeHash *eh, unsigned int v0, unsigned int v1)
/**
* Return boolean true/false if edge (v0,v1) in hash.
*/
-bool BLI_edgehash_haskey(EdgeHash *eh, unsigned int v0, unsigned int v1)
+bool BLI_edgehash_haskey(EdgeHash *eh, uint v0, uint v1)
{
return (edgehash_lookup_entry(eh, v0, v1) != NULL);
}
@@ -527,7 +527,7 @@ bool BLI_edgehash_haskey(EdgeHash *eh, unsigned int v0, unsigned int v1)
/**
* Return number of keys in hash.
*/
-int BLI_edgehash_size(EdgeHash *eh)
+int BLI_edgehash_len(EdgeHash *eh)
{
return (int)eh->nentries;
}
@@ -536,7 +536,7 @@ int BLI_edgehash_size(EdgeHash *eh)
* Remove all edges from hash.
*/
void BLI_edgehash_clear_ex(EdgeHash *eh, EdgeHashFreeFP valfreefp,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
if (valfreefp)
edgehash_free_cb(eh, valfreefp);
@@ -565,7 +565,7 @@ void BLI_edgehash_clear(EdgeHash *eh, EdgeHashFreeFP valfreefp)
void BLI_edgehash_free(EdgeHash *eh, EdgeHashFreeFP valfreefp)
{
- BLI_assert((int)eh->nentries == BLI_mempool_count(eh->epool));
+ BLI_assert((int)eh->nentries == BLI_mempool_len(eh->epool));
if (valfreefp)
edgehash_free_cb(eh, valfreefp);
@@ -577,12 +577,12 @@ void BLI_edgehash_free(EdgeHash *eh, EdgeHashFreeFP valfreefp)
}
-void BLI_edgehash_flag_set(EdgeHash *eh, unsigned int flag)
+void BLI_edgehash_flag_set(EdgeHash *eh, uint flag)
{
eh->flag |= flag;
}
-void BLI_edgehash_flag_clear(EdgeHash *eh, unsigned int flag)
+void BLI_edgehash_flag_clear(EdgeHash *eh, uint flag)
{
eh->flag &= ~flag;
}
@@ -599,7 +599,7 @@ void BLI_edgehash_flag_clear(EdgeHash *eh, unsigned int flag)
/**
* Create a new EdgeHashIterator. The hash table must not be mutated
* while the iterator is in use, and the iterator will step exactly
- * BLI_edgehash_size(eh) times before becoming done.
+ * BLI_edgehash_len(eh) times before becoming done.
*/
EdgeHashIterator *BLI_edgehashIterator_new(EdgeHash *eh)
{
@@ -611,7 +611,7 @@ EdgeHashIterator *BLI_edgehashIterator_new(EdgeHash *eh)
/**
* Init an already allocated EdgeHashIterator. The hash table must not
* be mutated while the iterator is in use, and the iterator will
- * step exactly BLI_edgehash_size(eh) times before becoming done.
+ * step exactly BLI_edgehash_len(eh) times before becoming done.
*
* \param ehi The EdgeHashIterator to initialize.
* \param eh The EdgeHash to iterate over.
@@ -664,7 +664,7 @@ void BLI_edgehashIterator_free(EdgeHashIterator *ehi)
/**
* Retrieve the key from an iterator.
*/
-void BLI_edgehashIterator_getKey(EdgeHashIterator *ehi, unsigned int *r_v0, unsigned int *r_v1)
+void BLI_edgehashIterator_getKey(EdgeHashIterator *ehi, uint *r_v0, uint *r_v1)
{
*r_v0 = ehi->curEntry->v0;
*r_v1 = ehi->curEntry->v1;
@@ -713,7 +713,7 @@ bool BLI_edgehashIterator_isDone(EdgeHashIterator *ehi)
/** \name EdgeSet Functions
* \{ */
EdgeSet *BLI_edgeset_new_ex(const char *info,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
EdgeSet *es = (EdgeSet *)edgehash_new(info,
nentries_reserve,
@@ -729,7 +729,7 @@ EdgeSet *BLI_edgeset_new(const char *info)
return BLI_edgeset_new_ex(info, 0);
}
-int BLI_edgeset_size(EdgeSet *es)
+int BLI_edgeset_len(EdgeSet *es)
{
return (int)((EdgeHash *)es)->nentries;
}
@@ -738,10 +738,10 @@ int BLI_edgeset_size(EdgeSet *es)
* Adds the key to the set (no checks for unique keys!).
* Matching #BLI_edgehash_insert
*/
-void BLI_edgeset_insert(EdgeSet *es, unsigned int v0, unsigned int v1)
+void BLI_edgeset_insert(EdgeSet *es, uint v0, uint v1)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index((EdgeHash *)es, v0, v1);
+ const uint bucket_index = edgehash_bucket_index((EdgeHash *)es, v0, v1);
edgehash_insert_ex_keyonly((EdgeHash *)es, v0, v1, bucket_index);
}
@@ -751,10 +751,10 @@ void BLI_edgeset_insert(EdgeSet *es, unsigned int v0, unsigned int v1)
*
* \note EdgeHash has no equivalent to this because typically the value would be different.
*/
-bool BLI_edgeset_add(EdgeSet *es, unsigned int v0, unsigned int v1)
+bool BLI_edgeset_add(EdgeSet *es, uint v0, uint v1)
{
EDGE_ORD(v0, v1);
- const unsigned int bucket_index = edgehash_bucket_index((EdgeHash *)es, v0, v1);
+ const uint bucket_index = edgehash_bucket_index((EdgeHash *)es, v0, v1);
EdgeEntry *e = edgehash_lookup_entry_ex((EdgeHash *)es, v0, v1, bucket_index);
if (e) {
@@ -766,7 +766,7 @@ bool BLI_edgeset_add(EdgeSet *es, unsigned int v0, unsigned int v1)
}
}
-bool BLI_edgeset_haskey(EdgeSet *es, unsigned int v0, unsigned int v1)
+bool BLI_edgeset_haskey(EdgeSet *es, uint v0, uint v1)
{
return (edgehash_lookup_entry((EdgeHash *)es, v0, v1) != NULL);
}
@@ -777,12 +777,12 @@ void BLI_edgeset_free(EdgeSet *es)
BLI_edgehash_free((EdgeHash *)es, NULL);
}
-void BLI_edgeset_flag_set(EdgeSet *es, unsigned int flag)
+void BLI_edgeset_flag_set(EdgeSet *es, uint flag)
{
((EdgeHash *)es)->flag |= flag;
}
-void BLI_edgeset_flag_clear(EdgeSet *es, unsigned int flag)
+void BLI_edgeset_flag_clear(EdgeSet *es, uint flag)
{
((EdgeHash *)es)->flag &= ~flag;
}
@@ -800,7 +800,7 @@ void BLI_edgeset_flag_clear(EdgeSet *es, unsigned int flag)
double BLI_edgehash_calc_quality(EdgeHash *eh)
{
uint64_t sum = 0;
- unsigned int i;
+ uint i;
if (eh->nentries == 0)
return -1.0;
diff --git a/source/blender/blenlib/intern/fileops.c b/source/blender/blenlib/intern/fileops.c
index db4b3bcf20c..ad53457f863 100644
--- a/source/blender/blenlib/intern/fileops.c
+++ b/source/blender/blenlib/intern/fileops.c
@@ -42,9 +42,6 @@
#include "zlib.h"
#ifdef WIN32
-# ifdef __MINGW32__
-# include <ctype.h>
-# endif
# include <io.h>
# include "BLI_winstuff.h"
# include "BLI_callbacks.h"
@@ -265,7 +262,7 @@ void *BLI_gzopen(const char *filename, const char *mode)
/* temporary #if until we update all libraries to 1.2.7
* for correct wide char path handling */
-#if ZLIB_VERNUM >= 0x1270 && !defined(FREE_WINDOWS)
+#if ZLIB_VERNUM >= 0x1270
UTF16_ENCODE(filename);
gzfile = gzopen_w(filename_16, mode);
@@ -320,7 +317,7 @@ static bool delete_recursive(const char *dir)
{
struct direntry *filelist, *fl;
bool err = false;
- unsigned int nbr, i;
+ uint nbr, i;
i = nbr = BLI_filelist_dir_contents(dir, &filelist);
fl = filelist;
@@ -624,7 +621,21 @@ static int recursive_operation(const char *startfrom, const char *startto,
if (to)
join_dirfile_alloc(&to_path, &to_alloc_len, to, dirent->d_name);
- if (dirent->d_type == DT_DIR) {
+ bool is_dir;
+
+#ifdef __HAIKU__
+ {
+ struct stat st_dir;
+ char filename[FILE_MAX];
+ BLI_path_join(filename, sizeof(filename), startfrom, dirent->d_name, NULL);
+ lstat(filename, &st_dir);
+ is_dir = S_ISDIR(st_dir.st_mode);
+ }
+#else
+ is_dir = (dirent->d_type == DT_DIR);
+#endif
+
+ if (is_dir) {
/* recursively dig into a subfolder */
ret = recursive_operation(from_path, to_path, callback_dir_pre, callback_file, callback_dir_post);
}
diff --git a/source/blender/blenlib/intern/freetypefont.c b/source/blender/blenlib/intern/freetypefont.c
index 8719c92a2a6..e990f0b663c 100644
--- a/source/blender/blenlib/intern/freetypefont.c
+++ b/source/blender/blenlib/intern/freetypefont.c
@@ -481,6 +481,22 @@ VFontData *BLI_vfontdata_from_freetypefont(PackedFile *pf)
return vfd;
}
+static void *vfontdata_copy_characters_value_cb(const void *src)
+{
+ return BLI_vfontchar_copy(src, 0);
+}
+
+VFontData *BLI_vfontdata_copy(const VFontData *vfont_src, const int UNUSED(flag))
+{
+ VFontData *vfont_dst = MEM_dupallocN(vfont_src);
+
+ if (vfont_src->characters != NULL) {
+ vfont_dst->characters = BLI_ghash_copy(vfont_src->characters, NULL, vfontdata_copy_characters_value_cb);
+ }
+
+ return vfont_dst;
+}
+
VChar *BLI_vfontchar_from_freetypefont(VFont *vfont, unsigned long character)
{
VChar *che = NULL;
@@ -503,6 +519,20 @@ VChar *BLI_vfontchar_from_freetypefont(VFont *vfont, unsigned long character)
return che;
}
+/* Yeah, this is very bad... But why is this in BLI in the first place, since it uses Nurb data?
+ * Anyway, do not feel like duplicating whole Nurb copy code here, so unless someone has a better idea... */
+#include "../../blenkernel/BKE_curve.h"
+
+VChar *BLI_vfontchar_copy(const VChar *vchar_src, const int UNUSED(flag))
+{
+ VChar *vchar_dst = MEM_dupallocN(vchar_src);
+
+ BLI_listbase_clear(&vchar_dst->nurbsbase);
+ BKE_nurbList_duplicate(&vchar_dst->nurbsbase, &vchar_src->nurbsbase);
+
+ return vchar_dst;
+}
+
#if 0
/* Freetype2 Outline struct */
diff --git a/source/blender/blenlib/intern/gsqueue.c b/source/blender/blenlib/intern/gsqueue.c
index 25da7701924..5c8c43ab92a 100644
--- a/source/blender/blenlib/intern/gsqueue.c
+++ b/source/blender/blenlib/intern/gsqueue.c
@@ -81,7 +81,7 @@ bool BLI_gsqueue_is_empty(GSQueue *gq)
/**
* Query number elements in the queue
*/
-int BLI_gsqueue_size(GSQueue *gq)
+int BLI_gsqueue_len(GSQueue *gq)
{
GSQueueElem *elem;
int size = 0;
@@ -162,7 +162,7 @@ void BLI_gsqueue_push(GSQueue *gq, const void *item)
* \param item A pointer to an appropriately
* sized structure (the size passed to BLI_gsqueue_new).
*/
-void BLI_gsqueue_pushback(GSQueue *gq, const void *item)
+void BLI_gsqueue_push_back(GSQueue *gq, const void *item)
{
GSQueueElem *elem = MEM_mallocN(sizeof(*elem) + gq->elem_size, "gqueue_push");
memcpy(elem->data, item, gq->elem_size);
diff --git a/source/blender/blenlib/intern/hash_mm2a.c b/source/blender/blenlib/intern/hash_mm2a.c
index af6ef4f355f..e8ca9244f25 100644
--- a/source/blender/blenlib/intern/hash_mm2a.c
+++ b/source/blender/blenlib/intern/hash_mm2a.c
@@ -36,6 +36,8 @@
* for temporary data.
*/
+#include "BLI_compiler_attrs.h"
+
#include "BLI_hash_mm2a.h" /* own include */
/* Helpers. */
@@ -128,10 +130,10 @@ uint32_t BLI_hash_mm2(const unsigned char *data, size_t len, uint32_t seed)
switch (len) {
case 3:
h ^= data[2] << 16;
- /* fall through */
+ ATTR_FALLTHROUGH;
case 2:
h ^= data[1] << 8;
- /* fall through */
+ ATTR_FALLTHROUGH;
case 1:
h ^= data[0];
h *= MM2A_M;
diff --git a/source/blender/blenlib/intern/jitter.c b/source/blender/blenlib/intern/jitter_2d.c
index bc2b5677fa5..26351f52c7f 100644
--- a/source/blender/blenlib/intern/jitter.c
+++ b/source/blender/blenlib/intern/jitter_2d.c
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/blenlib/intern/jitter.c
+/** \file blender/blenlib/intern/jitter_2d.c
* \ingroup bli
* \brief Jitter offset table
*/
@@ -35,7 +35,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_rand.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_strict_flags.h"
diff --git a/source/blender/blenlib/intern/lasso.c b/source/blender/blenlib/intern/lasso_2d.c
index 710da09521a..663f3ffea22 100644
--- a/source/blender/blenlib/intern/lasso.c
+++ b/source/blender/blenlib/intern/lasso_2d.c
@@ -26,7 +26,7 @@
*
*/
-/** \file blender/blenlib/intern/lasso.c
+/** \file blender/blenlib/intern/lasso_2d.c
* \ingroup bli
*/
@@ -35,7 +35,7 @@
#include "BLI_math.h"
#include "BLI_strict_flags.h"
-#include "BLI_lasso.h" /* own include */
+#include "BLI_lasso_2d.h" /* own include */
void BLI_lasso_boundbox(rcti *rect, const int mcords[][2], const unsigned int moves)
{
diff --git a/source/blender/blenlib/intern/listbase.c b/source/blender/blenlib/intern/listbase.c
index c9bf4976ae8..b87fed571b7 100644
--- a/source/blender/blenlib/intern/listbase.c
+++ b/source/blender/blenlib/intern/listbase.c
@@ -29,7 +29,9 @@
/** \file blender/blenlib/intern/listbase.c
* \ingroup bli
*
- * Manipulations on ListBase structs
+ * Manipulations on double-linked list (#ListBase structs).
+ *
+ * For single linked lists see 'BLI_linklist.h'
*/
#include <string.h>
@@ -170,6 +172,34 @@ void BLI_listbase_swaplinks(ListBase *listbase, void *vlinka, void *vlinkb)
}
/**
+ * Swaps \a vlinka and \a vlinkb from their respective lists. Assumes they are both already in their lista!
+ */
+void BLI_listbases_swaplinks(ListBase *listbasea, ListBase *listbaseb, void *vlinka, void *vlinkb)
+{
+ Link *linka = vlinka;
+ Link *linkb = vlinkb;
+ Link linkc = {NULL};
+
+ if (!linka || !linkb) {
+ return;
+ }
+
+ /* Temporary link to use as placeholder of the links positions */
+ BLI_insertlinkafter(listbasea, linka, &linkc);
+
+ /* Bring linka into linkb position */
+ BLI_remlink(listbasea, linka);
+ BLI_insertlinkafter(listbaseb, linkb, linka);
+
+ /* Bring linkb into linka position */
+ BLI_remlink(listbaseb, linkb);
+ BLI_insertlinkafter(listbasea, &linkc, linkb);
+
+ /* Remove temporary link */
+ BLI_remlink(listbasea, &linkc);
+}
+
+/**
* Removes the head from \a listbase and returns it.
*/
void *BLI_pophead(ListBase *listbase)
@@ -342,6 +372,40 @@ void BLI_insertlinkbefore(ListBase *listbase, void *vnextlink, void *vnewlink)
}
}
+
+/**
+ * Insert a link in place of another, without changing it's position in the list.
+ *
+ * Puts `vnewlink` in the position of `vreplacelink`, removing `vreplacelink`.
+ * - `vreplacelink` *must* be in the list.
+ * - `vnewlink` *must not* be in the list.
+ */
+void BLI_insertlinkreplace(ListBase *listbase, void *vreplacelink, void *vnewlink)
+{
+ Link *l_old = vreplacelink;
+ Link *l_new = vnewlink;
+
+ /* update adjacent links */
+ if (l_old->next != NULL) {
+ l_old->next->prev = l_new;
+ }
+ if (l_old->prev != NULL) {
+ l_old->prev->next = l_new;
+ }
+
+ /* set direct links */
+ l_new->next = l_old->next;
+ l_new->prev = l_old->prev;
+
+ /* update list */
+ if (listbase->first == l_old) {
+ listbase->first = l_new;
+ }
+ if (listbase->last == l_old) {
+ listbase->last = l_new;
+ }
+}
+
/**
* Reinsert \a vlink relative to its current position but offset by \a step. Doesn't move
* item if new position would exceed list (could optionally move to head/tail).
@@ -420,7 +484,7 @@ void BLI_freelistN(ListBase *listbase)
*
* \note Use to avoid redundant looping.
*/
-int BLI_listbase_count_ex(const ListBase *listbase, const int count_max)
+int BLI_listbase_count_at_most(const ListBase *listbase, const int count_max)
{
Link *link;
int count = 0;
@@ -630,7 +694,47 @@ void *BLI_rfindptr(const ListBase *listbase, const void *ptr, const int offset)
}
/**
- * Returns the 1-based index of the first element of listbase which contains the specified
+ * Finds the first element of listbase which contains the specified bytes
+ * at the specified offset, returning NULL if not found.
+ */
+void *BLI_listbase_bytes_find(const ListBase *listbase, const void *bytes, const size_t bytes_size, const int offset)
+{
+ Link *link = NULL;
+ const void *ptr_iter;
+
+ for (link = listbase->first; link; link = link->next) {
+ ptr_iter = (const void *)(((const char *)link) + offset);
+
+ if (memcmp(bytes, ptr_iter, bytes_size) == 0) {
+ return link;
+ }
+ }
+
+ return NULL;
+}
+/* same as above but find reverse */
+/**
+ * Finds the last element of listbase which contains the specified bytes
+ * at the specified offset, returning NULL if not found.
+ */
+void *BLI_listbase_bytes_rfind(const ListBase *listbase, const void *bytes, const size_t bytes_size, const int offset)
+{
+ Link *link = NULL;
+ const void *ptr_iter;
+
+ for (link = listbase->last; link; link = link->prev) {
+ ptr_iter = (const void *)(((const char *)link) + offset);
+
+ if (memcmp(bytes, ptr_iter, bytes_size) == 0) {
+ return link;
+ }
+ }
+
+ return NULL;
+}
+
+/**
+ * Returns the 0-based index of the first element of listbase which contains the specified
* null-terminated string at the specified offset, or -1 if not found.
*/
int BLI_findstringindex(const ListBase *listbase, const char *id, const int offset)
diff --git a/source/blender/blenlib/intern/math_base_inline.c b/source/blender/blenlib/intern/math_base_inline.c
index 8d2d80c2a35..4bedcbdf5bf 100644
--- a/source/blender/blenlib/intern/math_base_inline.c
+++ b/source/blender/blenlib/intern/math_base_inline.c
@@ -33,6 +33,7 @@
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
+#include <limits.h>
#ifdef __SSE2__
# include <emmintrin.h>
@@ -181,11 +182,59 @@ MINLINE unsigned power_of_2_min_u(unsigned x)
return x - (x >> 1);
}
-MINLINE int iroundf(float a)
-{
- return (int)floorf(a + 0.5f);
+/* rounding and clamping */
+
+#define _round_clamp_fl_impl(arg, ty, min, max) { \
+ float r = floorf(arg + 0.5f); \
+ if (UNLIKELY(r <= (float)min)) return (ty)min; \
+ else if (UNLIKELY(r >= (float)max)) return (ty)max; \
+ else return (ty)r; \
+}
+
+#define _round_clamp_db_impl(arg, ty, min, max) { \
+ double r = floor(arg + 0.5); \
+ if (UNLIKELY(r <= (double)min)) return (ty)min; \
+ else if (UNLIKELY(r >= (double)max)) return (ty)max; \
+ else return (ty)r; \
}
+#define _round_fl_impl(arg, ty) { return (ty)floorf(arg + 0.5f); }
+#define _round_db_impl(arg, ty) { return (ty)floor(arg + 0.5); }
+
+MINLINE signed char round_fl_to_char(float a) { _round_fl_impl(a, signed char) }
+MINLINE unsigned char round_fl_to_uchar(float a) { _round_fl_impl(a, unsigned char) }
+MINLINE short round_fl_to_short(float a) { _round_fl_impl(a, short) }
+MINLINE unsigned short round_fl_to_ushort(float a) { _round_fl_impl(a, unsigned short) }
+MINLINE int round_fl_to_int(float a) { _round_fl_impl(a, int) }
+MINLINE unsigned int round_fl_to_uint(float a) { _round_fl_impl(a, unsigned int) }
+
+MINLINE signed char round_db_to_char(double a) { _round_db_impl(a, signed char) }
+MINLINE unsigned char round_db_to_uchar(double a) { _round_db_impl(a, unsigned char) }
+MINLINE short round_db_to_short(double a) { _round_db_impl(a, short) }
+MINLINE unsigned short round_db_to_ushort(double a) { _round_db_impl(a, unsigned short) }
+MINLINE int round_db_to_int(double a) { _round_db_impl(a, int) }
+MINLINE unsigned int round_db_to_uint(double a) { _round_db_impl(a, unsigned int) }
+
+#undef _round_fl_impl
+#undef _round_db_impl
+
+MINLINE signed char round_fl_to_char_clamp(float a) { _round_clamp_fl_impl(a, signed char, SCHAR_MIN, SCHAR_MAX) }
+MINLINE unsigned char round_fl_to_uchar_clamp(float a) { _round_clamp_fl_impl(a, unsigned char, 0, UCHAR_MAX) }
+MINLINE short round_fl_to_short_clamp(float a) { _round_clamp_fl_impl(a, short, SHRT_MIN, SHRT_MAX) }
+MINLINE unsigned short round_fl_to_ushort_clamp(float a) { _round_clamp_fl_impl(a, unsigned short, 0, USHRT_MAX) }
+MINLINE int round_fl_to_int_clamp(float a) { _round_clamp_fl_impl(a, int, INT_MIN, INT_MAX) }
+MINLINE unsigned int round_fl_to_uint_clamp(float a) { _round_clamp_fl_impl(a, unsigned int, 0, UINT_MAX) }
+
+MINLINE signed char round_db_to_char_clamp(double a) { _round_clamp_db_impl(a, signed char, SCHAR_MIN, SCHAR_MAX) }
+MINLINE unsigned char round_db_to_uchar_clamp(double a) { _round_clamp_db_impl(a, unsigned char, 0, UCHAR_MAX) }
+MINLINE short round_db_to_short_clamp(double a) { _round_clamp_db_impl(a, short, SHRT_MIN, SHRT_MAX) }
+MINLINE unsigned short round_db_to_ushort_clamp(double a) { _round_clamp_db_impl(a, unsigned short, 0, USHRT_MAX) }
+MINLINE int round_db_to_int_clamp(double a) { _round_clamp_db_impl(a, int, INT_MIN, INT_MAX) }
+MINLINE unsigned int round_db_to_uint_clamp(double a) { _round_clamp_db_impl(a, unsigned int, 0, UINT_MAX) }
+
+#undef _round_clamp_fl_impl
+#undef _round_clamp_db_impl
+
/* integer division that rounds 0.5 up, particularly useful for color blending
* with integers, to avoid gradual darkening when rounding down */
MINLINE int divide_round_i(int a, int b)
@@ -194,6 +243,17 @@ MINLINE int divide_round_i(int a, int b)
}
/**
+ * Integer division that floors negative result.
+ * \note This works like Python's int division.
+ */
+MINLINE int divide_floor_i(int a, int b)
+{
+ int d = a / b;
+ int r = a % b; /* Optimizes into a single division. */
+ return r ? d - ((a < 0) ^ (b < 0)) : d;
+}
+
+/**
* modulo that handles negative numbers, works the same as Python's.
*/
MINLINE int mod_i(int i, int n)
@@ -255,6 +315,36 @@ MINLINE int max_iiii(int a, int b, int c, int d)
return max_ii(max_iii(a, b, c), d);
}
+MINLINE size_t min_zz(size_t a, size_t b)
+{
+ return (a < b) ? a : b;
+}
+MINLINE size_t max_zz(size_t a, size_t b)
+{
+ return (b < a) ? a : b;
+}
+
+MINLINE int clamp_i(int value, int min, int max)
+{
+ return min_ii(max_ii(value, min), max);
+}
+
+MINLINE float clamp_f(float value, float min, float max)
+{
+ if (value > max) {
+ return max;
+ }
+ else if (value < min) {
+ return min;
+ }
+ return value;
+}
+
+MINLINE size_t clamp_z(size_t value, size_t min, size_t max)
+{
+ return min_zz(max_zz(value, min), max);
+}
+
/**
* Almost-equal for IEEE floats, using absolute difference method.
*
@@ -278,10 +368,8 @@ MINLINE int compare_ff_relative(float a, float b, const float max_diff, const in
{
union {float f; int i;} ua, ub;
-#if 0 /* No BLI_assert in INLINE :/ */
BLI_assert(sizeof(float) == sizeof(int));
BLI_assert(max_ulps < (1 << 22));
-#endif
if (fabsf(a - b) <= max_diff) {
return 1;
@@ -314,6 +402,25 @@ MINLINE int signum_i(float a)
else return 0;
}
+/** Returns number of (base ten) *significant* digits of integer part of given float
+ * (negative in case of decimal-only floats, 0.01 returns -1 e.g.). */
+MINLINE int integer_digits_f(const float f)
+{
+ return (f == 0.0f) ? 0 : (int)floor(log10(fabs(f))) + 1;
+}
+
+/** Returns number of (base ten) *significant* digits of integer part of given double
+ * (negative in case of decimal-only floats, 0.01 returns -1 e.g.). */
+MINLINE int integer_digits_d(const double d)
+{
+ return (d == 0.0) ? 0 : (int)floor(log10(fabs(d))) + 1;
+}
+
+MINLINE int integer_digits_i(const int i)
+{
+ return (int)log10((double)i) + 1;
+}
+
/* Internal helpers for SSE2 implementation.
*
* NOTE: Are to be called ONLY from inside `#ifdef __SSE2__` !!!
@@ -366,7 +473,7 @@ MALWAYS_INLINE __m128 _bli_math_fastpow24(const __m128 arg)
*/
/* 0x3F4CCCCD = 4/5 */
/* 0x4F55A7FB = 2^(127/(4/5) - 127) * 0.994^(1/(4/5)) */
- /* error max = 0.17 avg = 0.0018 |avg| = 0.05 */
+ /* error max = 0.17, avg = 0.0018, |avg| = 0.05 */
__m128 x = _bli_math_fastpow(0x3F4CCCCD, 0x4F55A7FB, arg);
__m128 arg2 = _mm_mul_ps(arg, arg);
__m128 arg4 = _mm_mul_ps(arg2, arg2);
diff --git a/source/blender/blenlib/intern/math_bits_inline.c b/source/blender/blenlib/intern/math_bits_inline.c
index 82d7e2114c2..9b16756134e 100644
--- a/source/blender/blenlib/intern/math_bits_inline.c
+++ b/source/blender/blenlib/intern/math_bits_inline.c
@@ -25,16 +25,77 @@
#ifndef __MATH_BITS_INLINE_C__
#define __MATH_BITS_INLINE_C__
+#ifdef _MSC_VER
+# include <intrin.h>
+#endif
+
#include "BLI_math_bits.h"
-MINLINE unsigned int highest_order_bit_i(unsigned int n)
+MINLINE int bitscan_forward_i(int a)
{
- n |= (n >> 1);
- n |= (n >> 2);
- n |= (n >> 4);
- n |= (n >> 8);
- n |= (n >> 16);
- return n - (n >> 1);
+ BLI_assert(a != 0);
+#ifdef _MSC_VER
+ unsigned long ctz;
+ _BitScanForward(&ctz, a);
+ return ctz;
+#else
+ return __builtin_ctz((unsigned int)a);
+#endif
+}
+
+MINLINE unsigned int bitscan_forward_uint(unsigned int a)
+{
+ return (unsigned int)bitscan_forward_i((int)a);
+}
+
+MINLINE int bitscan_forward_clear_i(int *a)
+{
+ int i = bitscan_forward_i(*a);
+ *a &= (*a) - 1;
+ return i;
+}
+
+MINLINE unsigned int bitscan_forward_clear_uint(unsigned int *a)
+{
+ return (unsigned int)bitscan_forward_clear_i((int *)a);
+}
+
+MINLINE int bitscan_reverse_i(int a)
+{
+ BLI_assert(a != 0);
+#ifdef _MSC_VER
+ unsigned long clz;
+ _BitScanReverse(&clz, a);
+ return clz;
+#else
+ return __builtin_clz((unsigned int)a);
+#endif
+}
+
+MINLINE unsigned int bitscan_reverse_uint(unsigned int a)
+{
+ return (unsigned int)bitscan_reverse_i((int)a);
+}
+
+MINLINE int bitscan_reverse_clear_i(int *a)
+{
+ int i = bitscan_reverse_i(*a);
+ /* TODO(sergey): This could probably be optimized. */
+ *a &= ~(1 << (sizeof(int) * 8 - i - 1));
+ return i;
+}
+
+MINLINE unsigned int bitscan_reverse_clear_uint(unsigned int *a)
+{
+ return (unsigned int)bitscan_reverse_clear_i((int *)a);
+}
+
+MINLINE unsigned int highest_order_bit_uint(unsigned int n)
+{
+ if (n == 0) {
+ return 0;
+ }
+ return 1 << (sizeof(unsigned int) * 8 - bitscan_reverse_uint(n));
}
MINLINE unsigned short highest_order_bit_s(unsigned short n)
diff --git a/source/blender/blenlib/intern/math_color.c b/source/blender/blenlib/intern/math_color.c
index 6d7d24c79c3..a091595bc6c 100644
--- a/source/blender/blenlib/intern/math_color.c
+++ b/source/blender/blenlib/intern/math_color.c
@@ -83,24 +83,45 @@ void hsl_to_rgb_v(const float hsl[3], float r_rgb[3])
hsl_to_rgb(hsl[0], hsl[1], hsl[2], &r_rgb[0], &r_rgb[1], &r_rgb[2]);
}
-void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv)
+void rgb_to_yuv(float r, float g, float b, float *ly, float *lu, float *lv, int colorspace)
{
float y, u, v;
- y = 0.299f * r + 0.587f * g + 0.114f * b;
- u = -0.147f * r - 0.289f * g + 0.436f * b;
- v = 0.615f * r - 0.515f * g - 0.100f * b;
+
+ switch (colorspace) {
+ case BLI_YUV_ITU_BT601:
+ y = 0.299f * r + 0.587f * g + 0.114f * b;
+ u = -0.147f * r - 0.289f * g + 0.436f * b;
+ v = 0.615f * r - 0.515f * g - 0.100f * b;
+ break;
+ case BLI_YUV_ITU_BT709:
+ default:
+ y = 0.2126f * r + 0.7152f * g + 0.0722f * b;
+ u = -0.09991f * r - 0.33609f * g + 0.436f * b;
+ v = 0.615f * r - 0.55861f * g - 0.05639f * b;
+ break;
+ }
*ly = y;
*lu = u;
*lv = v;
}
-void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb)
+void yuv_to_rgb(float y, float u, float v, float *lr, float *lg, float *lb, int colorspace)
{
float r, g, b;
- r = y + 1.140f * v;
- g = y - 0.394f * u - 0.581f * v;
- b = y + 2.032f * u;
+
+ switch (colorspace) {
+ case BLI_YUV_ITU_BT601:
+ r = y + 1.140f * v;
+ g = y - 0.394f * u - 0.581f * v;
+ b = y + 2.032f * u;
+ break;
+ case BLI_YUV_ITU_BT709:
+ r = y + 1.28033f * v;
+ g = y - 0.21482f * u - 0.38059f * v;
+ b = y + 2.12798f * u;
+ break;
+ }
*lr = r;
*lg = g;
diff --git a/source/blender/blenlib/intern/math_color_blend_inline.c b/source/blender/blenlib/intern/math_color_blend_inline.c
index 048ab71c6dc..1af2a0cd6a2 100644
--- a/source/blender/blenlib/intern/math_color_blend_inline.c
+++ b/source/blender/blenlib/intern/math_color_blend_inline.c
@@ -439,12 +439,12 @@ MINLINE void blend_color_vividlight_byte(unsigned char dst[4], unsigned const ch
int temp;
if (src2[i] == 255) {
- temp = 255;
+ temp = (src1[i] == 0) ? 127 : 255;
}
else if (src2[i] == 0) {
- temp = 0;
+ temp = (src1[i] == 255) ? 127 : 0;
}
- else if (src2[i] > 127) {
+ else if (src2[i] > 127) {
temp = min_ii(((src1[i]) * 255) / (2 * (255 - src2[i])), 255);
}
else {
@@ -784,7 +784,7 @@ MINLINE void blend_color_add_alpha_float(float dst[4], const float src1[4], cons
MINLINE void blend_color_overlay_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -810,7 +810,7 @@ MINLINE void blend_color_overlay_float(float dst[4], const float src1[4], const
MINLINE void blend_color_hardlight_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -835,7 +835,7 @@ MINLINE void blend_color_hardlight_float(float dst[4], const float src1[4], cons
MINLINE void blend_color_burn_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -853,7 +853,7 @@ MINLINE void blend_color_burn_float(float dst[4], const float src1[4], const flo
MINLINE void blend_color_linearburn_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -872,7 +872,7 @@ MINLINE void blend_color_linearburn_float(float dst[4], const float src1[4], con
MINLINE void blend_color_dodge_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -890,7 +890,7 @@ MINLINE void blend_color_dodge_float(float dst[4], const float src1[4], const fl
MINLINE void blend_color_screen_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -908,7 +908,7 @@ MINLINE void blend_color_screen_float(float dst[4], const float src1[4], const f
MINLINE void blend_color_softlight_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -933,7 +933,7 @@ MINLINE void blend_color_softlight_float(float dst[4], const float src1[4], cons
MINLINE void blend_color_pinlight_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -959,7 +959,7 @@ MINLINE void blend_color_pinlight_float(float dst[4], const float src1[4], const
MINLINE void blend_color_linearlight_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -985,7 +985,7 @@ MINLINE void blend_color_linearlight_float(float dst[4], const float src1[4], co
MINLINE void blend_color_vividlight_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -993,10 +993,10 @@ MINLINE void blend_color_vividlight_float(float dst[4], const float src1[4], con
float temp;
if (src2[i] == 1.0f) {
- temp = 1.0f;
+ temp = (src1[i] == 0.0f) ? 0.5f : 1.0f;
}
else if (src2[i] == 0.0f) {
- temp = 0.0f;
+ temp = (src1[i] == 1.0f) ? 0.5f : 0.0f;
}
else if (src2[i] > 0.5f) {
temp = min_ff(((src1[i]) * 1.0f) / (2.0f * (1.0f - src2[i])), 1.0f);
@@ -1016,7 +1016,7 @@ MINLINE void blend_color_vividlight_float(float dst[4], const float src1[4], con
MINLINE void blend_color_difference_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -1034,7 +1034,7 @@ MINLINE void blend_color_difference_float(float dst[4], const float src1[4], con
MINLINE void blend_color_exclusion_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
int i = 3;
@@ -1053,7 +1053,7 @@ MINLINE void blend_color_exclusion_float(float dst[4], const float src1[4], cons
MINLINE void blend_color_color_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
float h1, s1, v1;
float h2, s2, v2;
@@ -1081,7 +1081,7 @@ MINLINE void blend_color_color_float(float dst[4], const float src1[4], const fl
MINLINE void blend_color_hue_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
float h1, s1, v1;
float h2, s2, v2;
@@ -1107,7 +1107,7 @@ MINLINE void blend_color_hue_float(float dst[4], const float src1[4], const floa
MINLINE void blend_color_saturation_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
float h1, s1, v1;
float h2, s2, v2;
@@ -1134,7 +1134,7 @@ MINLINE void blend_color_saturation_float(float dst[4], const float src1[4], con
MINLINE void blend_color_luminosity_float(float dst[4], const float src1[4], const float src2[4])
{
const float fac = src2[3];
- if (fac != 0.0f && fac < 1.0f) {
+ if (fac != 0.0f) {
const float mfac = 1.0f - fac;
float h1, s1, v1;
float h2, s2, v2;
diff --git a/source/blender/blenlib/intern/math_color_inline.c b/source/blender/blenlib/intern/math_color_inline.c
index 01a805a09b6..bc3a1ee3e90 100644
--- a/source/blender/blenlib/intern/math_color_inline.c
+++ b/source/blender/blenlib/intern/math_color_inline.c
@@ -239,6 +239,14 @@ MINLINE void rgba_char_args_set(char col[4], const char r, const char g, const c
col[3] = a;
}
+MINLINE void rgba_float_args_set(float col[4], const float r, const float g, const float b, const float a)
+{
+ col[0] = r;
+ col[1] = g;
+ col[2] = b;
+ col[3] = a;
+}
+
MINLINE void rgba_char_args_test_set(char col[4], const char r, const char g, const char b, const char a)
{
if (col[3] == 0) {
diff --git a/source/blender/blenlib/intern/math_geom.c b/source/blender/blenlib/intern/math_geom.c
index 3cf26ccf904..ee6a3dcc9b3 100644
--- a/source/blender/blenlib/intern/math_geom.c
+++ b/source/blender/blenlib/intern/math_geom.c
@@ -572,8 +572,8 @@ float dist_squared_to_ray_v3(
}
/**
* Find the closest point in a seg to a ray and return the distance squared.
- * \param r_point : Is the point on segment closest to ray (or to ray_origin if the ray and the segment are parallel).
- * \param depth: the distance of r_point projection on ray to the ray_origin.
+ * \param r_point: Is the point on segment closest to ray (or to ray_origin if the ray and the segment are parallel).
+ * \param r_depth: the distance of r_point projection on ray to the ray_origin.
*/
float dist_squared_ray_to_seg_v3(
const float ray_origin[3], const float ray_direction[3],
@@ -619,6 +619,152 @@ float dist_squared_ray_to_seg_v3(
return len_squared_v3(t) - SQUARE(*r_depth);
}
+/* -------------------------------------------------------------------- */
+/** \name dist_squared_to_ray_to_aabb and helpers
+ * \{ */
+
+void dist_squared_ray_to_aabb_v3_precalc(
+ struct DistRayAABB_Precalc *neasrest_precalc,
+ const float ray_origin[3], const float ray_direction[3])
+{
+ copy_v3_v3(neasrest_precalc->ray_origin, ray_origin);
+ copy_v3_v3(neasrest_precalc->ray_direction, ray_direction);
+
+ for (int i = 0; i < 3; i++) {
+ neasrest_precalc->ray_inv_dir[i] =
+ (neasrest_precalc->ray_direction[i] != 0.0f) ?
+ (1.0f / neasrest_precalc->ray_direction[i]) : FLT_MAX;
+ neasrest_precalc->sign[i] = (neasrest_precalc->ray_inv_dir[i] < 0.0f);
+ }
+}
+
+/**
+ * Returns the distance from a ray to a bound-box (projected on ray)
+ */
+float dist_squared_ray_to_aabb_v3(
+ const struct DistRayAABB_Precalc *data,
+ const float bb_min[3], const float bb_max[3],
+ float r_point[3], float *r_depth)
+{
+ // bool r_axis_closest[3];
+ float local_bvmin[3], local_bvmax[3];
+ if (data->sign[0]) {
+ local_bvmin[0] = bb_max[0];
+ local_bvmax[0] = bb_min[0];
+ }
+ else {
+ local_bvmin[0] = bb_min[0];
+ local_bvmax[0] = bb_max[0];
+ }
+ if (data->sign[1]) {
+ local_bvmin[1] = bb_max[1];
+ local_bvmax[1] = bb_min[1];
+ }
+ else {
+ local_bvmin[1] = bb_min[1];
+ local_bvmax[1] = bb_max[1];
+ }
+ if (data->sign[2]) {
+ local_bvmin[2] = bb_max[2];
+ local_bvmax[2] = bb_min[2];
+ }
+ else {
+ local_bvmin[2] = bb_min[2];
+ local_bvmax[2] = bb_max[2];
+ }
+
+ const float tmin[3] = {
+ (local_bvmin[0] - data->ray_origin[0]) * data->ray_inv_dir[0],
+ (local_bvmin[1] - data->ray_origin[1]) * data->ray_inv_dir[1],
+ (local_bvmin[2] - data->ray_origin[2]) * data->ray_inv_dir[2],
+ };
+ const float tmax[3] = {
+ (local_bvmax[0] - data->ray_origin[0]) * data->ray_inv_dir[0],
+ (local_bvmax[1] - data->ray_origin[1]) * data->ray_inv_dir[1],
+ (local_bvmax[2] - data->ray_origin[2]) * data->ray_inv_dir[2],
+ };
+ /* `va` and `vb` are the coordinates of the AABB edge closest to the ray */
+ float va[3], vb[3];
+ /* `rtmin` and `rtmax` are the minimum and maximum distances of the ray hits on the AABB */
+ float rtmin, rtmax;
+ int main_axis;
+
+ if ((tmax[0] <= tmax[1]) && (tmax[0] <= tmax[2])) {
+ rtmax = tmax[0];
+ va[0] = vb[0] = local_bvmax[0];
+ main_axis = 3;
+ // r_axis_closest[0] = data->sign[0];
+ }
+ else if ((tmax[1] <= tmax[0]) && (tmax[1] <= tmax[2])) {
+ rtmax = tmax[1];
+ va[1] = vb[1] = local_bvmax[1];
+ main_axis = 2;
+ // r_axis_closest[1] = data->sign[1];
+ }
+ else {
+ rtmax = tmax[2];
+ va[2] = vb[2] = local_bvmax[2];
+ main_axis = 1;
+ // r_axis_closest[2] = data->sign[2];
+ }
+
+ if ((tmin[0] >= tmin[1]) && (tmin[0] >= tmin[2])) {
+ rtmin = tmin[0];
+ va[0] = vb[0] = local_bvmin[0];
+ main_axis -= 3;
+ // r_axis_closest[0] = !data->sign[0];
+ }
+ else if ((tmin[1] >= tmin[0]) && (tmin[1] >= tmin[2])) {
+ rtmin = tmin[1];
+ va[1] = vb[1] = local_bvmin[1];
+ main_axis -= 1;
+ // r_axis_closest[1] = !data->sign[1];
+ }
+ else {
+ rtmin = tmin[2];
+ va[2] = vb[2] = local_bvmin[2];
+ main_axis -= 2;
+ // r_axis_closest[2] = !data->sign[2];
+ }
+ if (main_axis < 0) {
+ main_axis += 3;
+ }
+
+ /* if rtmin <= rtmax, ray intersect `AABB` */
+ if (rtmin <= rtmax) {
+ float dvec[3];
+ copy_v3_v3(r_point, local_bvmax);
+ sub_v3_v3v3(dvec, local_bvmax, data->ray_origin);
+ *r_depth = dot_v3v3(dvec, data->ray_direction);
+ return 0.0f;
+ }
+
+ if (data->sign[main_axis]) {
+ va[main_axis] = local_bvmax[main_axis];
+ vb[main_axis] = local_bvmin[main_axis];
+ }
+ else {
+ va[main_axis] = local_bvmin[main_axis];
+ vb[main_axis] = local_bvmax[main_axis];
+ }
+
+ return dist_squared_ray_to_seg_v3(
+ data->ray_origin, data->ray_direction, va, vb,
+ r_point, r_depth);
+}
+
+float dist_squared_ray_to_aabb_v3_simple(
+ const float ray_origin[3], const float ray_direction[3],
+ const float bbmin[3], const float bbmax[3],
+ float r_point[3], float *r_depth)
+{
+ struct DistRayAABB_Precalc data;
+ dist_squared_ray_to_aabb_v3_precalc(&data, ray_origin, ray_direction);
+ return dist_squared_ray_to_aabb_v3(&data, bbmin, bbmax, r_point, r_depth);
+}
+/** \} */
+
+
/* Adapted from "Real-Time Collision Detection" by Christer Ericson,
* published by Morgan Kaufmann Publishers, copyright 2005 Elsevier Inc.
*
@@ -765,18 +911,29 @@ int isect_seg_seg_v2(const float v1[2], const float v2[2], const float v3[2], co
return ISECT_LINE_LINE_NONE;
}
-/* get intersection point of two 2D segments and return intersection type:
- * -1: collinear
- * 1: intersection
+/**
+ * Get intersection point of two 2D segments.
+ *
+ * \param endpoint_bias: Bias to use when testing for end-point overlap.
+ * A positive value considers intersections that extend past the endpoints,
+ * negative values contract the endpoints.
+ * Note the bias is applied to a 0-1 factor, not scaled to the length of segments.
+ *
+ * \returns intersection type:
+ * - -1: collinear.
+ * - 1: intersection.
+ * - 0: no intersection.
*/
-int isect_seg_seg_v2_point(
+int isect_seg_seg_v2_point_ex(
const float v0[2], const float v1[2],
const float v2[2], const float v3[2],
+ const float endpoint_bias,
float r_vi[2])
{
float s10[2], s32[2], s30[2], d;
const float eps = 1e-6f;
- const float eps_sq = eps * eps;
+ const float endpoint_min = -endpoint_bias;
+ const float endpoint_max = endpoint_bias + 1.0f;
sub_v2_v2v2(s10, v1, v0);
sub_v2_v2v2(s32, v3, v2);
@@ -790,8 +947,8 @@ int isect_seg_seg_v2_point(
u = cross_v2v2(s30, s32) / d;
v = cross_v2v2(s10, s30) / d;
- if ((u >= -eps && u <= 1.0f + eps) &&
- (v >= -eps && v <= 1.0f + eps))
+ if ((u >= endpoint_min && u <= endpoint_max) &&
+ (v >= endpoint_min && v <= endpoint_max))
{
/* intersection */
float vi_test[2];
@@ -810,7 +967,7 @@ int isect_seg_seg_v2_point(
sub_v2_v2v2(s_vi_v2, vi_test, v2);
v = (dot_v2v2(s32, s_vi_v2) / dot_v2v2(s32, s32));
#endif
- if (v >= -eps && v <= 1.0f + eps) {
+ if (v >= endpoint_min && v <= endpoint_max) {
copy_v2_v2(r_vi, vi_test);
return 1;
}
@@ -828,7 +985,7 @@ int isect_seg_seg_v2_point(
float u_a, u_b;
if (equals_v2v2(v0, v1)) {
- if (len_squared_v2v2(v2, v3) > eps_sq) {
+ if (len_squared_v2v2(v2, v3) > SQUARE(eps)) {
/* use non-point segment as basis */
SWAP(const float *, v0, v2);
SWAP(const float *, v1, v3);
@@ -855,7 +1012,7 @@ int isect_seg_seg_v2_point(
if (u_a > u_b)
SWAP(float, u_a, u_b);
- if (u_a > 1.0f + eps || u_b < -eps) {
+ if (u_a > endpoint_max || u_b < endpoint_min) {
/* non-overlapping segments */
return -1;
}
@@ -871,6 +1028,15 @@ int isect_seg_seg_v2_point(
}
}
+int isect_seg_seg_v2_point(
+ const float v0[2], const float v1[2],
+ const float v2[2], const float v3[2],
+ float r_vi[2])
+{
+ const float endpoint_bias = 1e-6f;
+ return isect_seg_seg_v2_point_ex(v0, v1, v2, v3, endpoint_bias, r_vi);
+}
+
bool isect_seg_seg_v2_simple(const float v1[2], const float v2[2], const float v3[2], const float v4[2])
{
#define CCW(A, B, C) \
@@ -1828,7 +1994,7 @@ bool isect_tri_tri_epsilon_v3(
(range[0].max < range[1].min)) == 0)
{
if (r_i1 && r_i2) {
- project_plane_v3_v3v3(plane_co, plane_co, plane_no);
+ project_plane_normalized_v3_v3v3(plane_co, plane_co, plane_no);
madd_v3_v3v3fl(r_i1, plane_co, plane_no, max_ff(range[0].min, range[1].min));
madd_v3_v3v3fl(r_i2, plane_co, plane_no, min_ff(range[0].max, range[1].max));
}
@@ -2851,8 +3017,13 @@ bool barycentric_coords_v2(const float v1[2], const float v2[2], const float v3[
/**
* \note: using #cross_tri_v2 means locations outside the triangle are correctly weighted
+ *
+ * \note This is *exactly* the same calculation as #resolve_tri_uv_v2,
+ * although it has double precision and is used for texture baking, so keep both.
*/
-void barycentric_weights_v2(const float v1[2], const float v2[2], const float v3[2], const float co[2], float w[3])
+void barycentric_weights_v2(
+ const float v1[2], const float v2[2], const float v3[2],
+ const float co[2], float w[3])
{
float wtot;
@@ -2870,10 +3041,35 @@ void barycentric_weights_v2(const float v1[2], const float v2[2], const float v3
}
/**
+ * A version of #barycentric_weights_v2 that doesn't allow negative weights.
+ * Useful when negative values cause problems and points are only ever slightly outside of the triangle.
+ */
+void barycentric_weights_v2_clamped(
+ const float v1[2], const float v2[2], const float v3[2],
+ const float co[2], float w[3])
+{
+ float wtot;
+
+ w[0] = max_ff(cross_tri_v2(v2, v3, co), 0.0f);
+ w[1] = max_ff(cross_tri_v2(v3, v1, co), 0.0f);
+ w[2] = max_ff(cross_tri_v2(v1, v2, co), 0.0f);
+ wtot = w[0] + w[1] + w[2];
+
+ if (wtot != 0.0f) {
+ mul_v3_fl(w, 1.0f / wtot);
+ }
+ else { /* dummy values for zero area face */
+ copy_v3_fl(w, 1.0f / 3.0f);
+ }
+}
+
+/**
* still use 2D X,Y space but this works for verts transformed by a perspective matrix,
* using their 4th component as a weight
*/
-void barycentric_weights_v2_persp(const float v1[4], const float v2[4], const float v3[4], const float co[2], float w[3])
+void barycentric_weights_v2_persp(
+ const float v1[4], const float v2[4], const float v3[4],
+ const float co[2], float w[3])
{
float wtot;
@@ -2890,11 +3086,14 @@ void barycentric_weights_v2_persp(const float v1[4], const float v2[4], const fl
}
}
-/* same as #barycentric_weights_v2 but works with a quad,
+/**
+ * same as #barycentric_weights_v2 but works with a quad,
* note: untested for values outside the quad's bounds
- * this is #interp_weights_poly_v2 expanded for quads only */
-void barycentric_weights_v2_quad(const float v1[2], const float v2[2], const float v3[2], const float v4[2],
- const float co[2], float w[4])
+ * this is #interp_weights_poly_v2 expanded for quads only
+ */
+void barycentric_weights_v2_quad(
+ const float v1[2], const float v2[2], const float v3[2], const float v4[2],
+ const float co[2], float w[4])
{
/* note: fabsf() here is not needed for convex quads (and not used in interp_weights_poly_v2).
* but in the case of concave/bow-tie quads for the mask rasterizer it gives unreliable results
@@ -3345,6 +3544,8 @@ void interp_cubic_v3(float x[3], float v[3], const float x1[3], const float v1[3
* Barycentric reverse
*
* Compute coordinates (u, v) for point \a st with respect to triangle (\a st0, \a st1, \a st2)
+ *
+ * \note same basic result as #barycentric_weights_v2, see it's comment for details.
*/
void resolve_tri_uv_v2(float r_uv[2], const float st[2],
const float st0[2], const float st1[2], const float st2[2])
@@ -3575,7 +3776,7 @@ void orthographic_m4(float matrix[4][4], const float left, const float right, co
matrix[3][0] = -(right + left) / Xdelta;
matrix[1][1] = 2.0f / Ydelta;
matrix[3][1] = -(top + bottom) / Ydelta;
- matrix[2][2] = -2.0f / Zdelta; /* note: negate Z */
+ matrix[2][2] = -2.0f / Zdelta; /* note: negate Z */
matrix[3][2] = -(farClip + nearClip) / Zdelta;
}
@@ -3594,7 +3795,7 @@ void perspective_m4(float mat[4][4], const float left, const float right, const
}
mat[0][0] = nearClip * 2.0f / Xdelta;
mat[1][1] = nearClip * 2.0f / Ydelta;
- mat[2][0] = (right + left) / Xdelta; /* note: negate Z */
+ mat[2][0] = (right + left) / Xdelta; /* note: negate Z */
mat[2][1] = (top + bottom) / Ydelta;
mat[2][2] = -(farClip + nearClip) / Zdelta;
mat[2][3] = -1.0f;
@@ -3880,7 +4081,7 @@ void map_to_plane_axis_angle_v2_v3v3fl(float r_co[2], const float co[3], const f
/********************************* Normals **********************************/
-void accumulate_vertex_normals_tri(
+void accumulate_vertex_normals_tri_v3(
float n1[3], float n2[3], float n3[3],
const float f_no[3],
const float co1[3], const float co2[3], const float co3[3])
@@ -3914,7 +4115,7 @@ void accumulate_vertex_normals_tri(
}
}
-void accumulate_vertex_normals(
+void accumulate_vertex_normals_v3(
float n1[3], float n2[3], float n3[3], float n4[3],
const float f_no[3],
const float co1[3], const float co2[3], const float co3[3], const float co4[3])
@@ -3958,7 +4159,7 @@ void accumulate_vertex_normals(
/* Add weighted face normal component into normals of the face vertices.
* Caller must pass pre-allocated vdiffs of nverts length. */
-void accumulate_vertex_normals_poly(float **vertnos, const float polyno[3],
+void accumulate_vertex_normals_poly_v3(float **vertnos, const float polyno[3],
const float **vertcos, float vdiffs[][3], const int nverts)
{
int i;
@@ -3989,7 +4190,7 @@ void accumulate_vertex_normals_poly(float **vertnos, const float polyno[3],
/********************************* Tangents **********************************/
-void tangent_from_uv(
+void tangent_from_uv_v3(
const float uv1[2], const float uv2[2], const float uv3[3],
const float co1[3], const float co2[3], const float co3[3],
const float n[3],
@@ -4031,30 +4232,28 @@ void tangent_from_uv(
/****************************** Vector Clouds ********************************/
/* vector clouds */
-/* void vcloud_estimate_transform(int list_size, float (*pos)[3], float *weight, float (*rpos)[3], float *rweight,
- * float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3])
- *
+/**
* input
- * (
- * int list_size
- * 4 lists as pointer to array[list_size]
- * 1. current pos array of 'new' positions
- * 2. current weight array of 'new'weights (may be NULL pointer if you have no weights )
- * 3. reference rpos array of 'old' positions
- * 4. reference rweight array of 'old'weights (may be NULL pointer if you have no weights )
- * )
+ *
+ * \param list_size: 4 lists as pointer to array[list_size]
+ * \param pos: current pos array of 'new' positions
+ * \param weight: current weight array of 'new'weights (may be NULL pointer if you have no weights)
+ * \param rpos: Reference rpos array of 'old' positions
+ * \param rweight: Reference rweight array of 'old'weights (may be NULL pointer if you have no weights).
+ *
* output
- * (
- * float lloc[3] center of mass pos
- * float rloc[3] center of mass rpos
- * float lrot[3][3] rotation matrix
- * float lscale[3][3] scale matrix
+ *
+ * \param lloc: Center of mass pos.
+ * \param rloc: Center of mass rpos.
+ * \param lrot: Rotation matrix.
+ * \param lscale: Scale matrix.
+ *
* pointers may be NULL if not needed
- * )
*/
-void vcloud_estimate_transform(int list_size, float (*pos)[3], float *weight, float (*rpos)[3], float *rweight,
- float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3])
+void vcloud_estimate_transform_v3(
+ const int list_size, const float (*pos)[3], const float *weight, const float (*rpos)[3], const float *rweight,
+ float lloc[3], float rloc[3], float lrot[3][3], float lscale[3][3])
{
float accu_com[3] = {0.0f, 0.0f, 0.0f}, accu_rcom[3] = {0.0f, 0.0f, 0.0f};
float accu_weight = 0.0f, accu_rweight = 0.0f;
@@ -4732,6 +4931,18 @@ int is_quad_flip_v3(const float v1[3], const float v2[3], const float v3[3], con
return ret;
}
+bool is_quad_flip_v3_first_third_fast(const float v1[3], const float v2[3], const float v3[3], const float v4[3])
+{
+ float d_12[3], d_13[3], d_14[3];
+ float cross_a[3], cross_b[3];
+ sub_v3_v3v3(d_12, v2, v1);
+ sub_v3_v3v3(d_13, v3, v1);
+ sub_v3_v3v3(d_14, v4, v1);
+ cross_v3_v3v3(cross_a, d_12, d_13);
+ cross_v3_v3v3(cross_b, d_14, d_13);
+ return dot_v3v3(cross_a, cross_b) > 0.0f;
+}
+
/**
* Return the value which the distance between points will need to be scaled by,
* to define a handle, given both points are on a perfect circle.
diff --git a/source/blender/blenlib/intern/math_matrix.c b/source/blender/blenlib/intern/math_matrix.c
index 9a60c670ec7..311d963f64d 100644
--- a/source/blender/blenlib/intern/math_matrix.c
+++ b/source/blender/blenlib/intern/math_matrix.c
@@ -1523,6 +1523,15 @@ float mat4_to_scale(float mat[4][4])
return len_v3(unit_vec);
}
+/** Return 2D scale (in XY plane) of given mat4. */
+float mat4_to_xy_scale(float M[4][4])
+{
+ /* unit length vector in xy plane */
+ float unit_vec[3] = {(float)M_SQRT1_2, (float)M_SQRT1_2, 0.0f};
+ mul_mat3_m4_v3(M, unit_vec);
+ return len_v3(unit_vec);
+}
+
void mat3_to_rot_size(float rot[3][3], float size[3], float mat3[3][3])
{
/* keep rot as a 3x3 matrix, the caller can convert into a quat or euler */
@@ -1625,6 +1634,7 @@ void translate_m4(float mat[4][4], float Tx, float Ty, float Tz)
mat[3][2] += (Tx * mat[0][2] + Ty * mat[1][2] + Tz * mat[2][2]);
}
+/* TODO: enum for axis? */
/**
* Rotate a matrix in-place.
*
@@ -1663,6 +1673,9 @@ void rotate_m4(float mat[4][4], const char axis, const float angle)
mat[0][col] = temp;
}
break;
+ default:
+ BLI_assert(0);
+ break;
}
}
@@ -1738,16 +1751,16 @@ void blend_m4_m4m4(float out[4][4], float dst[4][4], float src[4][4], const floa
/**
* A polar-decomposition-based interpolation between matrix A and matrix B.
*
- * \note This code is about five times slower as the 'naive' interpolation done by \a blend_m3_m3m3
- * (it typically remains below 2 usec on an average i74700, while \a blend_m3_m3m3 remains below 0.4 usec).
+ * \note This code is about five times slower as the 'naive' interpolation done by #blend_m3_m3m3
+ * (it typically remains below 2 usec on an average i74700, while #blend_m3_m3m3 remains below 0.4 usec).
* However, it gives expected results even with non-uniformaly scaled matrices, see T46418 for an example.
*
* Based on "Matrix Animation and Polar Decomposition", by Ken Shoemake & Tom Duff
*
- * @return R the interpolated matrix.
- * @param A the intput matrix which is totally effective with \a t = 0.0.
- * @param B the intput matrix which is totally effective with \a t = 1.0.
- * @param t the interpolation factor.
+ * \param R: Resulting interpolated matrix.
+ * \param A: Input matrix which is totally effective with `t = 0.0`.
+ * \param B: Input matrix which is totally effective with `t = 1.0`.
+ * \param t: Interpolation factor.
*/
void interp_m3_m3m3(float R[3][3], float A[3][3], float B[3][3], const float t)
{
@@ -1777,12 +1790,12 @@ void interp_m3_m3m3(float R[3][3], float A[3][3], float B[3][3], const float t)
}
/**
- * Complete transform matrix interpolation, based on polar-decomposition-based interpolation from interp_m3_m3m3.
+ * Complete transform matrix interpolation, based on polar-decomposition-based interpolation from #interp_m3_m3m3.
*
- * @return R the interpolated matrix.
- * @param A the intput matrix which is totally effective with \a t = 0.0.
- * @param B the intput matrix which is totally effective with \a t = 1.0.
- * @param t the interpolation factor.
+ * \param R: Resulting interpolated matrix.
+ * \param A: Input matrix which is totally effective with `t = 0.0`.
+ * \param B: Input matrix which is totally effective with `t = 1.0`.
+ * \param t: Interpolation factor.
*/
void interp_m4_m4m4(float R[4][4], float A[4][4], float B[4][4], const float t)
{
diff --git a/source/blender/blenlib/intern/math_rotation.c b/source/blender/blenlib/intern/math_rotation.c
index 9b5dad3f767..29e7cf32ddc 100644
--- a/source/blender/blenlib/intern/math_rotation.c
+++ b/source/blender/blenlib/intern/math_rotation.c
@@ -84,8 +84,6 @@ void mul_qt_qtqt(float q[4], const float q1[4], const float q2[4])
* \note:
* Assumes a unit quaternion?
*
- * \note: multiplying by 3x3 matrix is ~25% faster.
- *
* in fact not, but you may want to use a unit quat, read on...
*
* Shortcut for 'q v q*' when \a v is actually a quaternion.
@@ -98,6 +96,8 @@ void mul_qt_qtqt(float q[4], const float q1[4], const float q2[4])
*
* For people used to python mathutils, its like:
* def mul_qt_v3(q, v): (q * Quaternion((0.0, v[0], v[1], v[2])) * q.conjugated())[1:]
+ *
+ * \note: multiplying by 3x3 matrix is ~25% faster.
*/
void mul_qt_v3(const float q[4], float v[3])
{
@@ -511,6 +511,14 @@ void rotation_between_quats_to_quat(float q[4], const float q1[4], const float q
}
+/* -------------------------------------------------------------------- */
+/** \name Quaternion Angle
+ *
+ * Unlike the angle between vectors, this does NOT return the shortest angle.
+ * See signed functions below for this.
+ *
+ * \{ */
+
float angle_normalized_qt(const float q[4])
{
BLI_ASSERT_UNIT_QUAT(q);
@@ -548,6 +556,64 @@ float angle_qtqt(const float q1[4], const float q2[4])
return angle_normalized_qtqt(quat1, quat2);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Quaternion Angle (Signed)
+ *
+ * Angles with quaternion calculation can exceed 180d,
+ * Having signed versions of these functions allows 'fabsf(angle_signed_qtqt(...))'
+ * to give us the shortest angle between quaternions.
+ * With higher precision than subtracting pi afterwards.
+ *
+ * \{ */
+
+float angle_signed_normalized_qt(const float q[4])
+{
+ BLI_ASSERT_UNIT_QUAT(q);
+ if (q[0] >= 0.0f) {
+ return 2.0f * saacos(q[0]);
+ }
+ else {
+ return -2.0f * saacos(-q[0]);
+ }
+}
+
+float angle_signed_normalized_qtqt(const float q1[4], const float q2[4])
+{
+ if (dot_qtqt(q1, q2) >= 0.0f) {
+ return angle_normalized_qtqt(q1, q2);
+ }
+ else {
+ float q2_copy[4];
+ negate_v4_v4(q2_copy, q2);
+ return -angle_normalized_qtqt(q1, q2_copy);
+ }
+}
+
+float angle_signed_qt(const float q[4])
+{
+ float tquat[4];
+
+ normalize_qt_qt(tquat, q);
+
+ return angle_signed_normalized_qt(tquat);
+}
+
+float angle_signed_qtqt(const float q1[4], const float q2[4])
+{
+ if (dot_qtqt(q1, q2) >= 0.0f) {
+ return angle_qtqt(q1, q2);
+ }
+ else {
+ float q2_copy[4];
+ negate_v4_v4(q2_copy, q2);
+ return -angle_qtqt(q1, q2_copy);
+ }
+}
+
+/** \} */
+
void vec_to_quat(float q[4], const float vec[3], short axis, const short upflag)
{
const float eps = 1e-4f;
@@ -2147,38 +2213,37 @@ BLI_INLINE int _axis_signed(const int axis)
return (axis < 3) ? axis : axis - 3;
}
-/*
+/**
* Each argument us an axis in ['X', 'Y', 'Z', '-X', '-Y', '-Z']
* where the first 2 are a source and the second 2 are the target.
*/
-int mat3_from_axis_conversion(int from_forward, int from_up, int to_forward, int to_up,
- float r_mat[3][3])
+bool mat3_from_axis_conversion(
+ int src_forward, int src_up, int dst_forward, int dst_up,
+ float r_mat[3][3])
{
// from functools import reduce
int value;
- unsigned int i;
- if (from_forward == to_forward && from_up == to_up) {
+ if (src_forward == dst_forward && src_up == dst_up) {
unit_m3(r_mat);
return false;
}
- if ((_axis_signed(from_forward) == _axis_signed(from_up)) ||
- (_axis_signed(to_forward) == _axis_signed(to_up)))
+ if ((_axis_signed(src_forward) == _axis_signed(src_up)) ||
+ (_axis_signed(dst_forward) == _axis_signed(dst_up)))
{
/* we could assert here! */
unit_m3(r_mat);
return false;
}
- value = ((from_forward << (0 * 3)) |
- (from_up << (1 * 3)) |
- (to_forward << (2 * 3)) |
- (to_up << (3 * 3)));
+ value = ((src_forward << (0 * 3)) |
+ (src_up << (1 * 3)) |
+ (dst_forward << (2 * 3)) |
+ (dst_up << (3 * 3)));
- for (i = 0; i < (sizeof(_axis_convert_matrix) / sizeof(*_axis_convert_matrix)); i++) {
- unsigned int j;
- for (j = 0; j < (sizeof(*_axis_convert_lut) / sizeof(*_axis_convert_lut[0])); j++) {
+ for (uint i = 0; i < (sizeof(_axis_convert_matrix) / sizeof(*_axis_convert_matrix)); i++) {
+ for (uint j = 0; j < (sizeof(*_axis_convert_lut) / sizeof(*_axis_convert_lut[0])); j++) {
if (_axis_convert_lut[i][j] == value) {
copy_m3_m3(r_mat, _axis_convert_matrix[i]);
return true;
@@ -2189,3 +2254,27 @@ int mat3_from_axis_conversion(int from_forward, int from_up, int to_forward, int
// BLI_assert(0);
return false;
}
+
+/**
+ * Use when the second axis can be guessed.
+ */
+bool mat3_from_axis_conversion_single(
+ int src_axis, int dst_axis,
+ float r_mat[3][3])
+{
+ if (src_axis == dst_axis) {
+ unit_m3(r_mat);
+ return false;
+ }
+
+ /* Pick predictable next axis. */
+ int src_axis_next = (src_axis + 1) % 3;
+ int dst_axis_next = (dst_axis + 1) % 3;
+
+ if ((src_axis < 3) != (dst_axis < 3)) {
+ /* Flip both axis so matrix sign remains positive. */
+ dst_axis_next += 3;
+ }
+
+ return mat3_from_axis_conversion(src_axis, src_axis_next, dst_axis, dst_axis_next, r_mat);
+}
diff --git a/source/blender/blenlib/intern/math_solvers.c b/source/blender/blenlib/intern/math_solvers.c
index 641e50c9bde..b8a22900ba1 100644
--- a/source/blender/blenlib/intern/math_solvers.c
+++ b/source/blender/blenlib/intern/math_solvers.c
@@ -72,3 +72,111 @@ void BLI_svd_m3(const float m3[3][3], float r_U[3][3], float r_S[3], float r_V[3
{
EIG_svd_square_matrix(3, (const float *)m3, (float *)r_U, (float *)r_S, (float *)r_V);
}
+
+/***************************** Simple Solvers ************************************/
+
+/**
+ * \brief Solve a tridiagonal system of equations:
+ *
+ * a[i] * r_x[i-1] + b[i] * r_x[i] + c[i] * r_x[i+1] = d[i]
+ *
+ * Ignores a[0] and c[count-1]. Uses the Thomas algorithm, e.g. see wiki.
+ *
+ * \param r_x output vector, may be shared with any of the input ones
+ * \return true if success
+ */
+bool BLI_tridiagonal_solve(const float *a, const float *b, const float *c, const float *d, float *r_x, const int count)
+{
+ if (count < 1)
+ return false;
+
+ size_t bytes = sizeof(double) * (unsigned)count;
+ double *c1 = (double *)MEM_mallocN(bytes * 2, "tridiagonal_c1d1");
+ double *d1 = c1 + count;
+
+ if (!c1)
+ return false;
+
+ int i;
+ double c_prev, d_prev, x_prev;
+
+ /* forward pass */
+
+ c1[0] = c_prev = ((double)c[0]) / b[0];
+ d1[0] = d_prev = ((double)d[0]) / b[0];
+
+ for (i = 1; i < count; i++) {
+ double denum = b[i] - a[i] * c_prev;
+
+ c1[i] = c_prev = c[i] / denum;
+ d1[i] = d_prev = (d[i] - a[i] * d_prev) / denum;
+ }
+
+ /* back pass */
+
+ x_prev = d_prev;
+ r_x[--i] = ((float)x_prev);
+
+ while (--i >= 0) {
+ x_prev = d1[i] - c1[i] * x_prev;
+ r_x[i] = ((float)x_prev);
+ }
+
+ MEM_freeN(c1);
+
+ return isfinite(x_prev);
+}
+
+/**
+ * \brief Solve a possibly cyclic tridiagonal system using the Sherman-Morrison formula.
+ *
+ * \param r_x output vector, may be shared with any of the input ones
+ * \return true if success
+ */
+bool BLI_tridiagonal_solve_cyclic(const float *a, const float *b, const float *c, const float *d, float *r_x, const int count)
+{
+ if (count < 1)
+ return false;
+
+ float a0 = a[0], cN = c[count - 1];
+
+ /* if not really cyclic, fall back to the simple solver */
+ if (a0 == 0.0f && cN == 0.0f) {
+ return BLI_tridiagonal_solve(a, b, c, d, r_x, count);
+ }
+
+ size_t bytes = sizeof(float) * (unsigned)count;
+ float *tmp = (float *)MEM_mallocN(bytes * 2, "tridiagonal_ex");
+ float *b2 = tmp + count;
+
+ if (!tmp)
+ return false;
+
+ /* prepare the noncyclic system; relies on tridiagonal_solve ignoring values */
+ memcpy(b2, b, bytes);
+ b2[0] -= a0;
+ b2[count - 1] -= cN;
+
+ memset(tmp, 0, bytes);
+ tmp[0] = a0;
+ tmp[count - 1] = cN;
+
+ /* solve for partial solution and adjustment vector */
+ bool success =
+ BLI_tridiagonal_solve(a, b2, c, tmp, tmp, count) &&
+ BLI_tridiagonal_solve(a, b2, c, d, r_x, count);
+
+ /* apply adjustment */
+ if (success) {
+ float coeff = (r_x[0] + r_x[count - 1]) / (1.0f + tmp[0] + tmp[count - 1]);
+
+ for (int i = 0; i < count; i++) {
+ r_x[i] -= coeff * tmp[i];
+ }
+ }
+
+ MEM_freeN(tmp);
+
+ return success;
+}
+
diff --git a/source/blender/blenlib/intern/math_statistics.c b/source/blender/blenlib/intern/math_statistics.c
index fd7418a8f7b..3a19f1d3603 100644
--- a/source/blender/blenlib/intern/math_statistics.c
+++ b/source/blender/blenlib/intern/math_statistics.c
@@ -46,7 +46,10 @@ typedef struct CovarianceData {
int nbr_cos_vn;
} CovarianceData;
-static void covariance_m_vn_ex_task_cb(void *userdata, const int a)
+static void covariance_m_vn_ex_task_cb(
+ void *__restrict userdata,
+ const int a,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
CovarianceData *data = userdata;
const float *cos_vn = data->cos_vn;
@@ -117,8 +120,14 @@ void BLI_covariance_m_vn_ex(
.covfac = covfac, .n = n, .nbr_cos_vn = nbr_cos_vn,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((nbr_cos_vn * n * n) >= 10000);
BLI_task_parallel_range(
- 0, n * n, &data, covariance_m_vn_ex_task_cb, (nbr_cos_vn * n * n) >= 10000);
+ 0, n * n,
+ &data,
+ covariance_m_vn_ex_task_cb,
+ &settings);
}
/**
diff --git a/source/blender/blenlib/intern/math_vector.c b/source/blender/blenlib/intern/math_vector.c
index dfecc3b556a..d6e48fa59e7 100644
--- a/source/blender/blenlib/intern/math_vector.c
+++ b/source/blender/blenlib/intern/math_vector.c
@@ -518,38 +518,27 @@ float angle_normalized_v2v2(const float v1[2], const float v2[2])
}
/**
- * angle between 2 vectors defined by 3 coords, about an axis. */
-float angle_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3])
+ * Angle between 2 vectors, about an axis (axis can be considered a plane).
+ */
+float angle_on_axis_v3v3_v3(const float v1[3], const float v2[3], const float axis[3])
{
- float v1_proj[3], v2_proj[3], tproj[3];
-
- sub_v3_v3v3(v1_proj, v1, v2);
- sub_v3_v3v3(v2_proj, v3, v2);
+ float v1_proj[3], v2_proj[3];
/* project the vectors onto the axis */
- project_v3_v3v3(tproj, v1_proj, axis);
- sub_v3_v3(v1_proj, tproj);
-
- project_v3_v3v3(tproj, v2_proj, axis);
- sub_v3_v3(v2_proj, tproj);
+ project_plane_normalized_v3_v3v3(v1_proj, v1, axis);
+ project_plane_normalized_v3_v3v3(v2_proj, v2, axis);
return angle_v3v3(v1_proj, v2_proj);
}
-float angle_signed_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3])
+float angle_signed_on_axis_v3v3_v3(const float v1[3], const float v2[3], const float axis[3])
{
float v1_proj[3], v2_proj[3], tproj[3];
float angle;
- sub_v3_v3v3(v1_proj, v1, v2);
- sub_v3_v3v3(v2_proj, v3, v2);
-
/* project the vectors onto the axis */
- project_v3_v3v3(tproj, v1_proj, axis);
- sub_v3_v3(v1_proj, tproj);
-
- project_v3_v3v3(tproj, v2_proj, axis);
- sub_v3_v3(v2_proj, tproj);
+ project_plane_normalized_v3_v3v3(v1_proj, v1, axis);
+ project_plane_normalized_v3_v3v3(v2_proj, v2, axis);
angle = angle_v3v3(v1_proj, v2_proj);
@@ -562,6 +551,29 @@ float angle_signed_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const
return angle;
}
+/**
+ * Angle between 2 vectors defined by 3 coords, about an axis (axis can be considered a plane).
+ */
+float angle_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3])
+{
+ float vec1[3], vec2[3];
+
+ sub_v3_v3v3(vec1, v1, v2);
+ sub_v3_v3v3(vec2, v3, v2);
+
+ return angle_on_axis_v3v3_v3(vec1, vec2, axis);
+}
+
+float angle_signed_on_axis_v3v3v3_v3(const float v1[3], const float v2[3], const float v3[3], const float axis[3])
+{
+ float vec1[3], vec2[3];
+
+ sub_v3_v3v3(vec1, v1, v2);
+ sub_v3_v3v3(vec2, v3, v2);
+
+ return angle_signed_on_axis_v3v3_v3(vec1, vec2, axis);
+}
+
void angle_tri_v3(float angles[3], const float v1[3], const float v2[3], const float v3[3])
{
float ed1[3], ed2[3], ed3[3];
@@ -640,6 +652,31 @@ void project_v3_v3v3(float out[3], const float p[3], const float v_proj[3])
}
/**
+ * Project \a p onto a unit length \a v_proj
+ */
+void project_v2_v2v2_normalized(float out[2], const float p[2], const float v_proj[2])
+{
+ BLI_ASSERT_UNIT_V2(v_proj);
+ const float mul = dot_v2v2(p, v_proj);
+
+ out[0] = mul * v_proj[0];
+ out[1] = mul * v_proj[1];
+}
+
+/**
+ * Project \a p onto a unit length \a v_proj
+ */
+void project_v3_v3v3_normalized(float out[3], const float p[3], const float v_proj[3])
+{
+ BLI_ASSERT_UNIT_V3(v_proj);
+ const float mul = dot_v3v3(p, v_proj);
+
+ out[0] = mul * v_proj[0];
+ out[1] = mul * v_proj[1];
+ out[2] = mul * v_proj[2];
+}
+
+/**
* In this case plane is a 3D vector only (no 4th component).
*
* Projecting will make \a c a copy of \a v orthogonal to \a v_plane.
@@ -669,6 +706,25 @@ void project_plane_v2_v2v2(float out[2], const float p[2], const float v_plane[2
out[1] = p[1] - (mul * v_plane[1]);
}
+void project_plane_normalized_v3_v3v3(float out[3], const float p[3], const float v_plane[3])
+{
+ BLI_ASSERT_UNIT_V3(v_plane);
+ const float mul = dot_v3v3(p, v_plane);
+
+ out[0] = p[0] - (mul * v_plane[0]);
+ out[1] = p[1] - (mul * v_plane[1]);
+ out[2] = p[2] - (mul * v_plane[2]);
+}
+
+void project_plane_normalized_v2_v2v2(float out[2], const float p[2], const float v_plane[2])
+{
+ BLI_ASSERT_UNIT_V2(v_plane);
+ const float mul = dot_v2v2(p, v_plane);
+
+ out[0] = p[0] - (mul * v_plane[0]);
+ out[1] = p[1] - (mul * v_plane[1]);
+}
+
/* project a vector on a plane defined by normal and a plane point p */
void project_v3_plane(float out[3], const float plane_no[3], const float plane_co[3])
{
@@ -697,7 +753,19 @@ void bisect_v3_v3v3v3(float out[3], const float v1[3], const float v2[3], const
/**
* Returns a reflection vector from a vector and a normal vector
- * reflect = vec - ((2 * DotVecs(vec, mirror)) * mirror)
+ * reflect = vec - ((2 * dot(vec, mirror)) * mirror).
+ *
+ * <pre>
+ * v
+ * + ^
+ * \ |
+ * \|
+ * + normal: axis of reflection
+ * /
+ * /
+ * +
+ * out: result (negate for a 'bounce').
+ * </pre>
*/
void reflect_v3_v3v3(float out[3], const float v[3], const float normal[3])
{
@@ -782,6 +850,20 @@ void ortho_v2_v2(float out[2], const float v[2])
}
/**
+ * Rotate a point \a p by \a angle around origin (0, 0)
+ */
+void rotate_v2_v2fl(float r[2], const float p[2], const float angle)
+{
+ const float co = cosf(angle);
+ const float si = sinf(angle);
+
+ BLI_assert(r != p);
+
+ r[0] = co * p[0] - si * p[1];
+ r[1] = si * p[0] + co * p[1];
+}
+
+/**
* Rotate a point \a p by \a angle around an arbitrary unit length \a axis.
* http://local.wasp.uwa.edu.au/~pbourke/geometry/
*/
@@ -808,6 +890,8 @@ void rotate_normalized_v3_v3v3fl(float out[3], const float p[3], const float axi
void rotate_v3_v3v3fl(float r[3], const float p[3], const float axis[3], const float angle)
{
+ BLI_assert(r != p);
+
float axis_n[3];
normalize_v3_v3(axis_n, axis);
diff --git a/source/blender/blenlib/intern/math_vector_inline.c b/source/blender/blenlib/intern/math_vector_inline.c
index ee5e8651bd3..08687a1ab47 100644
--- a/source/blender/blenlib/intern/math_vector_inline.c
+++ b/source/blender/blenlib/intern/math_vector_inline.c
@@ -658,6 +658,14 @@ MINLINE void invert_v2(float r[2])
r[1] = 1.0f / r[1];
}
+MINLINE void invert_v3(float r[3])
+{
+ BLI_assert(!ELEM(0.0f, r[0], r[1], r[2]));
+ r[0] = 1.0f / r[0];
+ r[1] = 1.0f / r[1];
+ r[2] = 1.0f / r[2];
+}
+
MINLINE void abs_v2(float r[2])
{
r[0] = fabsf(r[0]);
@@ -960,6 +968,12 @@ MINLINE float normalize_v3(float n[3])
return normalize_v3_v3(n, n);
}
+MINLINE void normal_float_to_short_v2(short out[2], const float in[2])
+{
+ out[0] = (short) (in[0] * 32767.0f);
+ out[1] = (short) (in[1] * 32767.0f);
+}
+
MINLINE void normal_short_to_float_v3(float out[3], const short in[3])
{
out[0] = in[0] * (1.0f / 32767.0f);
diff --git a/source/blender/blenlib/intern/noise.c b/source/blender/blenlib/intern/noise.c
index f834c5b4c74..83012694ac0 100644
--- a/source/blender/blenlib/intern/noise.c
+++ b/source/blender/blenlib/intern/noise.c
@@ -1394,6 +1394,11 @@ static float voronoi_CrS(float x, float y, float z)
/* returns unsigned cellnoise */
static float cellNoiseU(float x, float y, float z)
{
+ /* avoid precision issues on unit coordinates */
+ x = (x + 0.000001f) * 1.00001f;
+ y = (y + 0.000001f) * 1.00001f;
+ z = (z + 0.000001f) * 1.00001f;
+
int xi = (int)(floor(x));
int yi = (int)(floor(y));
int zi = (int)(floor(z));
@@ -1411,6 +1416,11 @@ float cellNoise(float x, float y, float z)
/* returns a vector/point/color in ca, using point hasharray directly */
void cellNoiseV(float x, float y, float z, float ca[3])
{
+ /* avoid precision issues on unit coordinates */
+ x = (x + 0.000001f) * 1.00001f;
+ y = (y + 0.000001f) * 1.00001f;
+ z = (z + 0.000001f) * 1.00001f;
+
int xi = (int)(floor(x));
int yi = (int)(floor(y));
int zi = (int)(floor(z));
diff --git a/source/blender/blenlib/intern/path_util.c b/source/blender/blenlib/intern/path_util.c
index 6644e6605a1..f19d6ca31d6 100644
--- a/source/blender/blenlib/intern/path_util.c
+++ b/source/blender/blenlib/intern/path_util.c
@@ -85,13 +85,13 @@ static bool BLI_path_is_abs(const char *name);
*/
int BLI_stringdec(const char *string, char *head, char *tail, unsigned short *numlen)
{
- unsigned int nums = 0, nume = 0;
+ uint nums = 0, nume = 0;
int i;
bool found_digit = false;
const char * const lslash = BLI_last_slash(string);
- const unsigned int string_len = strlen(string);
- const unsigned int lslash_len = lslash != NULL ? (int)(lslash - string) : 0;
- unsigned int name_end = string_len;
+ const uint string_len = strlen(string);
+ const uint lslash_len = lslash != NULL ? (int)(lslash - string) : 0;
+ uint name_end = string_len;
while (name_end > lslash_len && string[--name_end] != '.') {} /* name ends at dot if present */
if (name_end == lslash_len && string[name_end] != '.') name_end = string_len;
@@ -700,7 +700,7 @@ bool BLI_parent_dir(char *path)
*/
static bool stringframe_chars(const char *path, int *char_start, int *char_end)
{
- unsigned int ch_sta, ch_end, i;
+ uint ch_sta, ch_end, i;
/* Insert current frame: file### -> file001 */
ch_sta = ch_end = 0;
for (i = 0; path[i] != '\0'; i++) {
@@ -1167,52 +1167,16 @@ bool BLI_path_program_search(
}
/**
- * Copies into *last the part of *dir following the second-last slash.
- */
-void BLI_getlastdir(const char *dir, char *last, const size_t maxlen)
-{
- const char *s = dir;
- const char *lslash = NULL;
- const char *prevslash = NULL;
- while (*s) {
- if ((*s == '\\') || (*s == '/')) {
- prevslash = lslash;
- lslash = s;
- }
- s++;
- }
- if (prevslash) {
- BLI_strncpy(last, prevslash + 1, maxlen);
- }
- else {
- BLI_strncpy(last, dir, maxlen);
- }
-}
-
-
-/**
* Sets the specified environment variable to the specified value,
* and clears it if val == NULL.
*/
void BLI_setenv(const char *env, const char *val)
{
/* free windows */
-#if (defined(WIN32) || defined(WIN64)) && defined(FREE_WINDOWS)
- char *envstr;
-
- if (val)
- envstr = BLI_sprintfN("%s=%s", env, val);
- else
- envstr = BLI_sprintfN("%s=", env);
-
- putenv(envstr);
- MEM_freeN(envstr);
- /* non-free windows */
-#elif (defined(WIN32) || defined(WIN64)) /* not free windows */
+#if (defined(WIN32) || defined(WIN64))
uputenv(env, val);
-
#else
/* linux/osx/bsd */
if (val)
@@ -1258,14 +1222,16 @@ void BLI_make_exist(char *dir)
/**
* Ensures that the parent directory of *name exists.
+ *
+ * \return true on success (i.e. given path now exists on FS), false otherwise.
*/
-void BLI_make_existing_file(const char *name)
+bool BLI_make_existing_file(const char *name)
{
char di[FILE_MAX];
BLI_split_dir_part(name, di, sizeof(di));
/* make if the dir doesn't exist */
- BLI_dir_create_recursive(di);
+ return BLI_dir_create_recursive(di);
}
/**
@@ -1615,6 +1581,90 @@ void BLI_join_dirfile(char *__restrict dst, const size_t maxlen, const char *__r
}
/**
+ * Join multiple strings into a path, ensuring only a single path separator between each,
+ * and trailing slash is kept.
+ *
+ * \note If you want a trailing slash, add ``SEP_STR`` as the last path argument,
+ * duplicate slashes will be cleaned up.
+ */
+size_t BLI_path_join(char *__restrict dst, const size_t dst_len, const char *path, ...)
+{
+ if (UNLIKELY(dst_len == 0)) {
+ return 0;
+ }
+ const size_t dst_last = dst_len - 1;
+ size_t ofs = BLI_strncpy_rlen(dst, path, dst_len);
+
+ if (ofs == dst_last) {
+ return ofs;
+ }
+
+ /* remove trailing slashes, unless there are _only_ trailing slashes
+ * (allow "//" as the first argument). */
+ bool has_trailing_slash = false;
+ if (ofs != 0) {
+ size_t len = ofs;
+ while ((len != 0) && ELEM(path[len - 1], SEP, ALTSEP)) {
+ len -= 1;
+ }
+ if (len != 0) {
+ ofs = len;
+ }
+ has_trailing_slash = (path[len] != '\0');
+ }
+
+ va_list args;
+ va_start(args, path);
+ while ((path = (const char *) va_arg(args, const char *))) {
+ has_trailing_slash = false;
+ const char *path_init = path;
+ while (ELEM(path[0], SEP, ALTSEP)) {
+ path++;
+ }
+ size_t len = strlen(path);
+ if (len != 0) {
+ while ((len != 0) && ELEM(path[len - 1], SEP, ALTSEP)) {
+ len -= 1;
+ }
+
+ if (len != 0) {
+ /* the very first path may have a slash at the end */
+ if (ofs && !ELEM(dst[ofs - 1], SEP, ALTSEP)) {
+ dst[ofs++] = SEP;
+ if (ofs == dst_last) {
+ break;
+ }
+ }
+ has_trailing_slash = (path[len] != '\0');
+ if (ofs + len >= dst_last) {
+ len = dst_last - ofs;
+ }
+ memcpy(&dst[ofs], path, len);
+ ofs += len;
+ if (ofs == dst_last) {
+ break;
+ }
+ }
+ }
+ else {
+ has_trailing_slash = (path_init != path);
+ }
+ }
+ va_end(args);
+
+ if (has_trailing_slash) {
+ if ((ofs != dst_last) && (ofs != 0) && (ELEM(dst[ofs - 1], SEP, ALTSEP) == 0)) {
+ dst[ofs++] = SEP;
+ }
+ }
+
+ BLI_assert(ofs <= dst_last);
+ dst[ofs] = '\0';
+
+ return ofs;
+}
+
+/**
* like pythons os.path.basename()
*
* \return The pointer into \a path string immediately after last slash,
@@ -1626,6 +1676,71 @@ const char *BLI_path_basename(const char *path)
return filename ? filename + 1 : path;
}
+/**
+ * Get an element of the path at an index, eg:
+ * "/some/path/file.txt" where an index of...
+ * - 0 or -3: "some"
+ * - 1 or -2: "path"
+ * - 2 or -1: "file.txt"
+ *
+ * Ignores multiple slashes at any point in the path (including start/end).
+ */
+bool BLI_path_name_at_index(const char *path, const int index, int *r_offset, int *r_len)
+{
+ if (index >= 0) {
+ int index_step = 0;
+ int prev = -1;
+ int i = 0;
+ while (true) {
+ const char c = path[i];
+ if (ELEM(c, SEP, ALTSEP, '\0')) {
+ if (prev + 1 != i) {
+ prev += 1;
+ if (index_step == index) {
+ *r_offset = prev;
+ *r_len = i - prev;
+ /* printf("!!! %d %d\n", start, end); */
+ return true;
+ }
+ index_step += 1;
+ }
+ if (c == '\0') {
+ break;
+ }
+ prev = i;
+ }
+ i += 1;
+ }
+ return false;
+ }
+ else {
+ /* negative number, reverse where -1 is the last element */
+ int index_step = -1;
+ int prev = strlen(path);
+ int i = prev - 1;
+ while (true) {
+ const char c = i >= 0 ? path[i] : '\0';
+ if (ELEM(c, SEP, ALTSEP, '\0')) {
+ if (prev - 1 != i) {
+ i += 1;
+ if (index_step == index) {
+ *r_offset = i;
+ *r_len = prev - i;
+ return true;
+ }
+ index_step -= 1;
+ }
+ if (c == '\0') {
+ break;
+ }
+ prev = i;
+ }
+ i -= 1;
+ }
+ return false;
+ }
+}
+
/* UNUSED */
#if 0
/**
diff --git a/source/blender/blenlib/intern/polyfill2d_beautify.c b/source/blender/blenlib/intern/polyfill2d_beautify.c
deleted file mode 100644
index 896177f436c..00000000000
--- a/source/blender/blenlib/intern/polyfill2d_beautify.c
+++ /dev/null
@@ -1,496 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/blenlib/intern/polyfill2d_beautify.c
- * \ingroup bli
- *
- * This function is to improve the tessellation resulting from polyfill2d,
- * creating optimal topology.
- *
- * The functionality here matches #BM_mesh_beautify_fill,
- * but its far simpler to perform this operation in 2d,
- * on a simple polygon representation where we _know_:
- *
- * - The polygon is primitive with no holes with a continuous boundary.
- * - Tris have consistent winding.
- * - 2d (saves some hassles projecting face pairs on an axis for every edge-rotation)
- * also saves us having to store all previous edge-states (see #EdRotState in bmesh_beautify.c)
- *
- * \note
- *
- * No globals - keep threadsafe.
- */
-
-#include "BLI_utildefines.h"
-#include "BLI_math.h"
-
-#include "BLI_memarena.h"
-#include "BLI_edgehash.h"
-#include "BLI_heap.h"
-
-#include "BLI_polyfill2d_beautify.h" /* own include */
-
-#include "BLI_strict_flags.h"
-
-struct PolyEdge {
- /** ordered vert indices (smaller first) */
- unsigned int verts[2];
- /** ordered face indices (depends on winding compared to the edge verts)
- * - (verts[0], verts[1]) == faces[0]
- * - (verts[1], verts[0]) == faces[1]
- */
- unsigned int faces[2];
- /**
- * The face-index which isn't used by either of the edges verts [0 - 2].
- * could be calculated each time, but cleaner to store for reuse.
- */
- unsigned int faces_other_v[2];
-};
-
-
-#ifndef NDEBUG
-/**
- * Only to check for error-cases.
- */
-static void polyfill_validate_tri(unsigned int (*tris)[3], unsigned int tri_index, EdgeHash *ehash)
-{
- const unsigned int *tri = tris[tri_index];
- int j_curr;
-
- BLI_assert(!ELEM(tri[0], tri[1], tri[2]) &&
- !ELEM(tri[1], tri[0], tri[2]) &&
- !ELEM(tri[2], tri[0], tri[1]));
-
- for (j_curr = 0; j_curr < 3; j_curr++) {
- struct PolyEdge *e;
- unsigned int e_v1 = tri[(j_curr ) ];
- unsigned int e_v2 = tri[(j_curr + 1) % 3];
- e = BLI_edgehash_lookup(ehash, e_v1, e_v2);
- if (e) {
- if (e->faces[0] == tri_index) {
- BLI_assert(e->verts[0] == e_v1);
- BLI_assert(e->verts[1] == e_v2);
- }
- else if (e->faces[1] == tri_index) {
- BLI_assert(e->verts[0] == e_v2);
- BLI_assert(e->verts[1] == e_v1);
- }
- else {
- BLI_assert(0);
- }
-
- BLI_assert(e->faces[0] != e->faces[1]);
- BLI_assert(ELEM(e_v1, UNPACK3(tri)));
- BLI_assert(ELEM(e_v2, UNPACK3(tri)));
- BLI_assert(ELEM(e_v1, UNPACK2(e->verts)));
- BLI_assert(ELEM(e_v2, UNPACK2(e->verts)));
- BLI_assert(e_v1 != tris[e->faces[0]][e->faces_other_v[0]]);
- BLI_assert(e_v1 != tris[e->faces[1]][e->faces_other_v[1]]);
- BLI_assert(e_v2 != tris[e->faces[0]][e->faces_other_v[0]]);
- BLI_assert(e_v2 != tris[e->faces[1]][e->faces_other_v[1]]);
-
- BLI_assert(ELEM(tri_index, UNPACK2(e->faces)));
- }
- }
-}
-#endif
-
-BLI_INLINE bool is_boundary_edge(unsigned int i_a, unsigned int i_b, const unsigned int coord_last)
-{
- BLI_assert(i_a < i_b);
- return ((i_a + 1 == i_b) || UNLIKELY((i_a == 0) && (i_b == coord_last)));
-}
-/**
- * Assuming we have 2 triangles sharing an edge (2 - 4),
- * check if the edge running from (1 - 3) gives better results.
- *
- * \return (negative number means the edge can be rotated, lager == better).
- */
-float BLI_polyfill_beautify_quad_rotate_calc(
- const float v1[2], const float v2[2], const float v3[2], const float v4[2])
-{
- /* not a loop (only to be able to break out) */
- do {
- bool is_zero_a, is_zero_b;
-
- const float area_2x_234 = cross_tri_v2(v2, v3, v4);
- const float area_2x_241 = cross_tri_v2(v2, v4, v1);
-
- const float area_2x_123 = cross_tri_v2(v1, v2, v3);
- const float area_2x_134 = cross_tri_v2(v1, v3, v4);
-
- {
- BLI_assert((ELEM(v1, v2, v3, v4) == false) &&
- (ELEM(v2, v1, v3, v4) == false) &&
- (ELEM(v3, v1, v2, v4) == false) &&
- (ELEM(v4, v1, v2, v3) == false));
-
- is_zero_a = (fabsf(area_2x_234) <= FLT_EPSILON);
- is_zero_b = (fabsf(area_2x_241) <= FLT_EPSILON);
-
- if (is_zero_a && is_zero_b) {
- break;
- }
- }
-
- /* one of the tri's was degenerate, check we're not rotating
- * into a different degenerate shape or flipping the face */
- if ((fabsf(area_2x_123) <= FLT_EPSILON) || (fabsf(area_2x_134) <= FLT_EPSILON)) {
- /* one of the new rotations is degenerate */
- break;
- }
-
- if ((area_2x_123 >= 0.0f) != (area_2x_134 >= 0.0f)) {
- /* rotation would cause flipping */
- break;
- }
-
- {
- /* testing rule: the area divided by the perimeter,
- * check if (1-3) beats the existing (2-4) edge rotation */
- float area_a, area_b;
- float prim_a, prim_b;
- float fac_24, fac_13;
-
- float len_12, len_23, len_34, len_41, len_24, len_13;
-
- /* edges around the quad */
- len_12 = len_v2v2(v1, v2);
- len_23 = len_v2v2(v2, v3);
- len_34 = len_v2v2(v3, v4);
- len_41 = len_v2v2(v4, v1);
- /* edges crossing the quad interior */
- len_13 = len_v2v2(v1, v3);
- len_24 = len_v2v2(v2, v4);
-
- /* note, area is in fact (area * 2),
- * but in this case its OK, since we're comparing ratios */
-
- /* edge (2-4), current state */
- area_a = fabsf(area_2x_234);
- area_b = fabsf(area_2x_241);
- prim_a = len_23 + len_34 + len_24;
- prim_b = len_41 + len_12 + len_24;
- fac_24 = (area_a / prim_a) + (area_b / prim_b);
-
- /* edge (1-3), new state */
- area_a = fabsf(area_2x_123);
- area_b = fabsf(area_2x_134);
- prim_a = len_12 + len_23 + len_13;
- prim_b = len_34 + len_41 + len_13;
- fac_13 = (area_a / prim_a) + (area_b / prim_b);
-
- /* negative number if (1-3) is an improved state */
- return fac_24 - fac_13;
- }
- } while (false);
-
- return FLT_MAX;
-}
-
-static float polyedge_rotate_beauty_calc(
- const float (*coords)[2],
- const unsigned int (*tris)[3],
- const struct PolyEdge *e)
-{
- const float *v1, *v2, *v3, *v4;
-
- v1 = coords[tris[e->faces[0]][e->faces_other_v[0]]];
- v3 = coords[tris[e->faces[1]][e->faces_other_v[1]]];
- v2 = coords[e->verts[0]];
- v4 = coords[e->verts[1]];
-
- return BLI_polyfill_beautify_quad_rotate_calc(v1, v2, v3, v4);
-}
-
-static void polyedge_beauty_cost_update_single(
- const float (*coords)[2],
- const unsigned int (*tris)[3],
- const struct PolyEdge *edges,
- struct PolyEdge *e,
- Heap *eheap, HeapNode **eheap_table)
-{
- const unsigned int i = (unsigned int)(e - edges);
-
- if (eheap_table[i]) {
- BLI_heap_remove(eheap, eheap_table[i]);
- eheap_table[i] = NULL;
- }
-
- {
- /* recalculate edge */
- const float cost = polyedge_rotate_beauty_calc(coords, tris, e);
- /* We can get cases where both choices generate very small negative costs, which leads to infinite loop.
- * Anyway, costs above that are not worth recomputing, maybe we could even optimize it to a smaller limit?
- * Actually, FLT_EPSILON is too small in some cases, 1e-6f seems to work OK hopefully?
- * See T43578, T49478. */
- if (cost < -1e-6f) {
- eheap_table[i] = BLI_heap_insert(eheap, cost, e);
- }
- else {
- eheap_table[i] = NULL;
- }
- }
-}
-
-static void polyedge_beauty_cost_update(
- const float (*coords)[2],
- const unsigned int (*tris)[3],
- const struct PolyEdge *edges,
- struct PolyEdge *e,
- Heap *eheap, HeapNode **eheap_table,
- EdgeHash *ehash)
-{
- const unsigned int *tri_0 = tris[e->faces[0]];
- const unsigned int *tri_1 = tris[e->faces[1]];
- unsigned int i;
-
- struct PolyEdge *e_arr[4] = {
- BLI_edgehash_lookup(ehash,
- tri_0[(e->faces_other_v[0] ) % 3],
- tri_0[(e->faces_other_v[0] + 1) % 3]),
- BLI_edgehash_lookup(ehash,
- tri_0[(e->faces_other_v[0] + 2) % 3],
- tri_0[(e->faces_other_v[0] ) % 3]),
- BLI_edgehash_lookup(ehash,
- tri_1[(e->faces_other_v[1] ) % 3],
- tri_1[(e->faces_other_v[1] + 1) % 3]),
- BLI_edgehash_lookup(ehash,
- tri_1[(e->faces_other_v[1] + 2) % 3],
- tri_1[(e->faces_other_v[1] ) % 3]),
- };
-
-
- for (i = 0; i < 4; i++) {
- if (e_arr[i]) {
- BLI_assert(!(ELEM(e_arr[i]->faces[0], UNPACK2(e->faces)) &&
- ELEM(e_arr[i]->faces[1], UNPACK2(e->faces))));
-
- polyedge_beauty_cost_update_single(
- coords, tris, edges,
- e_arr[i],
- eheap, eheap_table);
- }
- }
-}
-
-static void polyedge_rotate(
- unsigned int (*tris)[3],
- struct PolyEdge *e,
- EdgeHash *ehash)
-{
- unsigned int e_v1_new = tris[e->faces[0]][e->faces_other_v[0]];
- unsigned int e_v2_new = tris[e->faces[1]][e->faces_other_v[1]];
-
-#ifndef NDEBUG
- polyfill_validate_tri(tris, e->faces[0], ehash);
- polyfill_validate_tri(tris, e->faces[1], ehash);
-#endif
-
- BLI_assert(e_v1_new != e_v2_new);
- BLI_assert(!ELEM(e_v2_new, UNPACK3(tris[e->faces[0]])));
- BLI_assert(!ELEM(e_v1_new, UNPACK3(tris[e->faces[1]])));
-
- tris[e->faces[0]][(e->faces_other_v[0] + 1) % 3] = e_v2_new;
- tris[e->faces[1]][(e->faces_other_v[1] + 1) % 3] = e_v1_new;
-
- e->faces_other_v[0] = (e->faces_other_v[0] + 2) % 3;
- e->faces_other_v[1] = (e->faces_other_v[1] + 2) % 3;
-
- BLI_assert((tris[e->faces[0]][e->faces_other_v[0]] != e_v1_new) &&
- (tris[e->faces[0]][e->faces_other_v[0]] != e_v2_new));
- BLI_assert((tris[e->faces[1]][e->faces_other_v[1]] != e_v1_new) &&
- (tris[e->faces[1]][e->faces_other_v[1]] != e_v2_new));
-
- BLI_edgehash_remove(ehash, e->verts[0], e->verts[1], NULL);
- BLI_edgehash_insert(ehash, e_v1_new, e_v2_new, e);
-
- if (e_v1_new < e_v2_new) {
- e->verts[0] = e_v1_new;
- e->verts[1] = e_v2_new;
- }
- else {
- /* maintain winding info */
- e->verts[0] = e_v2_new;
- e->verts[1] = e_v1_new;
-
- SWAP(unsigned int, e->faces[0], e->faces[1]);
- SWAP(unsigned int, e->faces_other_v[0], e->faces_other_v[1]);
- }
-
- /* update adjacent data */
- {
- unsigned int e_side = 0;
-
- for (e_side = 0; e_side < 2; e_side++) {
- /* 't_other' which we need to swap out is always the same edge-order */
- const unsigned int t_other = (((e->faces_other_v[e_side]) + 2)) % 3;
- unsigned int t_index = e->faces[e_side];
- unsigned int t_index_other = e->faces[!e_side];
- unsigned int *tri = tris[t_index];
-
- struct PolyEdge *e_other;
- unsigned int e_v1 = tri[(t_other ) ];
- unsigned int e_v2 = tri[(t_other + 1) % 3];
-
- e_other = BLI_edgehash_lookup(ehash, e_v1, e_v2);
- if (e_other) {
- BLI_assert(t_index != e_other->faces[0] && t_index != e_other->faces[1]);
- if (t_index_other == e_other->faces[0]) {
- e_other->faces[0] = t_index;
- e_other->faces_other_v[0] = (t_other + 2) % 3;
- BLI_assert(!ELEM(tri[e_other->faces_other_v[0]], e_v1, e_v2));
- }
- else if (t_index_other == e_other->faces[1]) {
- e_other->faces[1] = t_index;
- e_other->faces_other_v[1] = (t_other + 2) % 3;
- BLI_assert(!ELEM(tri[e_other->faces_other_v[1]], e_v1, e_v2));
- }
- else {
- BLI_assert(0);
- }
- }
- }
- }
-
-#ifndef NDEBUG
- polyfill_validate_tri(tris, e->faces[0], ehash);
- polyfill_validate_tri(tris, e->faces[1], ehash);
-#endif
-
- BLI_assert(!ELEM(tris[e->faces[0]][e->faces_other_v[0]], UNPACK2(e->verts)));
- BLI_assert(!ELEM(tris[e->faces[1]][e->faces_other_v[1]], UNPACK2(e->verts)));
-}
-
-/**
- * The intention is that this calculates the output of #BLI_polyfill_calc
- *
- *
- * \note assumes the \a coords form a boundary,
- * so any edges running along contiguous (wrapped) indices,
- * are ignored since the edges wont share 2 faces.
- */
-void BLI_polyfill_beautify(
- const float (*coords)[2],
- const unsigned int coords_tot,
- unsigned int (*tris)[3],
-
- /* structs for reuse */
- MemArena *arena, Heap *eheap, EdgeHash *ehash)
-{
- const unsigned int coord_last = coords_tot - 1;
- const unsigned int tris_tot = coords_tot - 2;
- /* internal edges only (between 2 tris) */
- const unsigned int edges_tot = tris_tot - 1;
- unsigned int edges_tot_used = 0;
- unsigned int i;
-
- HeapNode **eheap_table;
-
- struct PolyEdge *edges = BLI_memarena_alloc(arena, edges_tot * sizeof(*edges));
-
- BLI_assert(BLI_heap_size(eheap) == 0);
- BLI_assert(BLI_edgehash_size(ehash) == 0);
-
- /* first build edges */
- for (i = 0; i < tris_tot; i++) {
- unsigned int j_prev, j_curr, j_next;
- j_prev = 2;
- j_next = 1;
- for (j_curr = 0; j_curr < 3; j_next = j_prev, j_prev = j_curr++) {
- int e_index;
-
- unsigned int e_pair[2] = {
- tris[i][j_prev],
- tris[i][j_curr],
- };
-
- if (e_pair[0] > e_pair[1]) {
- SWAP(unsigned int, e_pair[0], e_pair[1]);
- e_index = 1;
- }
- else {
- e_index = 0;
- }
-
- if (!is_boundary_edge(e_pair[0], e_pair[1], coord_last)) {
- struct PolyEdge *e;
- void **val_p;
-
- if (!BLI_edgehash_ensure_p(ehash, e_pair[0], e_pair[1], &val_p)) {
- e = &edges[edges_tot_used++];
- *val_p = e;
- memcpy(e->verts, e_pair, sizeof(e->verts));
-#ifndef NDEBUG
- e->faces[!e_index] = (unsigned int)-1;
-#endif
- }
- else {
- e = *val_p;
- /* ensure each edge only ever has 2x users */
-#ifndef NDEBUG
- BLI_assert(e->faces[e_index] == (unsigned int)-1);
- BLI_assert((e->verts[0] == e_pair[0]) &&
- (e->verts[1] == e_pair[1]));
-#endif
- }
-
- e->faces[e_index] = i;
- e->faces_other_v[e_index] = j_next;
- }
- }
- }
-
- /* now perform iterative rotations */
- eheap_table = BLI_memarena_alloc(arena, sizeof(HeapNode *) * (size_t)edges_tot);
-
- // for (i = 0; i < tris_tot; i++) { polyfill_validate_tri(tris, i, eh); }
-
- /* build heap */
- for (i = 0; i < edges_tot; i++) {
- struct PolyEdge *e = &edges[i];
- const float cost = polyedge_rotate_beauty_calc(coords, (const unsigned int (*)[3])tris, e);
- if (cost < 0.0f) {
- eheap_table[i] = BLI_heap_insert(eheap, cost, e);
- }
- else {
- eheap_table[i] = NULL;
- }
- }
-
- while (BLI_heap_is_empty(eheap) == false) {
- struct PolyEdge *e = BLI_heap_popmin(eheap);
- i = (unsigned int)(e - edges);
- eheap_table[i] = NULL;
-
- polyedge_rotate(tris, e, ehash);
-
- /* recalculate faces connected on the heap */
- polyedge_beauty_cost_update(
- coords, (const unsigned int (*)[3])tris, edges,
- e,
- eheap, eheap_table, ehash);
- }
-
- BLI_heap_clear(eheap, NULL);
- BLI_edgehash_clear_ex(ehash, NULL, BLI_POLYFILL_ALLOC_NGON_RESERVE);
-
- /* MEM_freeN(eheap_table); */ /* arena */
-}
diff --git a/source/blender/blenlib/intern/polyfill2d.c b/source/blender/blenlib/intern/polyfill_2d.c
index 2969b0eccf4..8c0870f0c07 100644
--- a/source/blender/blenlib/intern/polyfill2d.c
+++ b/source/blender/blenlib/intern/polyfill_2d.c
@@ -18,7 +18,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/blenlib/intern/polyfill2d.c
+/** \file blender/blenlib/intern/polyfill_2d.c
* \ingroup bli
*
* An ear clipping algorithm to triangulate single boundary polygons.
@@ -53,7 +53,7 @@
#include "BLI_memarena.h"
#include "BLI_alloca.h"
-#include "BLI_polyfill2d.h" /* own include */
+#include "BLI_polyfill_2d.h" /* own include */
#include "BLI_strict_flags.h"
@@ -105,24 +105,24 @@ typedef bool axis_t;
/* use for sorting */
typedef struct KDTreeNode2D_head {
- unsigned int neg, pos;
- unsigned int index;
+ uint neg, pos;
+ uint index;
} KDTreeNode2D_head;
typedef struct KDTreeNode2D {
- unsigned int neg, pos;
- unsigned int index;
+ uint neg, pos;
+ uint index;
axis_t axis; /* range is only (0-1) */
- unsigned short flag;
- unsigned int parent;
+ ushort flag;
+ uint parent;
} KDTreeNode2D;
struct KDTree2D {
KDTreeNode2D *nodes;
const float (*coords)[2];
- unsigned int root;
- unsigned int totnode;
- unsigned int *nodes_map; /* index -> node lookup */
+ uint root;
+ uint totnode;
+ uint *nodes_map; /* index -> node lookup */
};
struct KDRange2D {
@@ -140,14 +140,14 @@ typedef struct PolyFill {
struct PolyIndex *indices; /* vertex aligned */
const float (*coords)[2];
- unsigned int coords_tot;
+ uint coords_tot;
#ifdef USE_CONVEX_SKIP
- unsigned int coords_tot_concave;
+ uint coords_tot_concave;
#endif
/* A polygon with n vertices has a triangulation of n-2 triangles. */
- unsigned int (*tris)[3];
- unsigned int tris_tot;
+ uint (*tris)[3];
+ uint tris_tot;
#ifdef USE_KDTREE
struct KDTree2D kdtree;
@@ -158,7 +158,7 @@ typedef struct PolyFill {
/* circular linklist */
typedef struct PolyIndex {
struct PolyIndex *next, *prev;
- unsigned int index;
+ uint index;
eSign sign;
} PolyIndex;
@@ -212,7 +212,7 @@ static eSign span_tri_v2_sign(const float v1[2], const float v2[2], const float
#ifdef USE_KDTREE
-#define KDNODE_UNSET ((unsigned int)-1)
+#define KDNODE_UNSET ((uint)-1)
enum {
KDNODE_FLAG_REMOVED = (1 << 0),
@@ -220,7 +220,7 @@ enum {
static void kdtree2d_new(
struct KDTree2D *tree,
- unsigned int tot,
+ uint tot,
const float (*coords)[2])
{
/* set by caller */
@@ -235,11 +235,11 @@ static void kdtree2d_new(
*/
static void kdtree2d_init(
struct KDTree2D *tree,
- const unsigned int coords_tot,
+ const uint coords_tot,
const PolyIndex *indices)
{
KDTreeNode2D *node;
- unsigned int i;
+ uint i;
for (i = 0, node = tree->nodes; i < coords_tot; i++) {
if (indices[i].sign != CONVEX) {
@@ -251,15 +251,15 @@ static void kdtree2d_init(
}
}
- BLI_assert(tree->totnode == (unsigned int)(node - tree->nodes));
+ BLI_assert(tree->totnode == (uint)(node - tree->nodes));
}
-static unsigned int kdtree2d_balance_recursive(
- KDTreeNode2D *nodes, unsigned int totnode, axis_t axis,
- const float (*coords)[2], const unsigned int ofs)
+static uint kdtree2d_balance_recursive(
+ KDTreeNode2D *nodes, uint totnode, axis_t axis,
+ const float (*coords)[2], const uint ofs)
{
KDTreeNode2D *node;
- unsigned int neg, pos, median, i, j;
+ uint neg, pos, median, i, j;
if (totnode <= 0) {
return KDNODE_UNSET;
@@ -317,7 +317,7 @@ static void kdtree2d_balance(
static void kdtree2d_init_mapping(
struct KDTree2D *tree)
{
- unsigned int i;
+ uint i;
KDTreeNode2D *node;
for (i = 0, node = tree->nodes; i < tree->totnode; i++, node++) {
@@ -338,9 +338,9 @@ static void kdtree2d_init_mapping(
static void kdtree2d_node_remove(
struct KDTree2D *tree,
- unsigned int index)
+ uint index)
{
- unsigned int node_index = tree->nodes_map[index];
+ uint node_index = tree->nodes_map[index];
KDTreeNode2D *node;
if (node_index == KDNODE_UNSET) {
@@ -362,7 +362,7 @@ static void kdtree2d_node_remove(
{
KDTreeNode2D *node_parent = &tree->nodes[node->parent];
- BLI_assert((unsigned int)(node - tree->nodes) == node_index);
+ BLI_assert((uint)(node - tree->nodes) == node_index);
if (node_parent->neg == node_index) {
node_parent->neg = KDNODE_UNSET;
}
@@ -383,7 +383,7 @@ static void kdtree2d_node_remove(
static bool kdtree2d_isect_tri_recursive(
const struct KDTree2D *tree,
- const unsigned int tri_index[3],
+ const uint tri_index[3],
const float *tri_coords[3],
const float tri_center[2],
const struct KDRange2D bounds[2],
@@ -411,11 +411,11 @@ static bool kdtree2d_isect_tri_recursive(
}
#define KDTREE2D_ISECT_TRI_RECURSE_NEG \
- (((node->neg != KDNODE_UNSET) && (co[node->axis] > bounds[node->axis].min)) && \
+ (((node->neg != KDNODE_UNSET) && (co[node->axis] >= bounds[node->axis].min)) && \
(kdtree2d_isect_tri_recursive(tree, tri_index, tri_coords, tri_center, bounds, \
&tree->nodes[node->neg])))
#define KDTREE2D_ISECT_TRI_RECURSE_POS \
- (((node->pos != KDNODE_UNSET) && (co[node->axis] < bounds[node->axis].max)) && \
+ (((node->pos != KDNODE_UNSET) && (co[node->axis] <= bounds[node->axis].max)) && \
(kdtree2d_isect_tri_recursive(tree, tri_index, tri_coords, tri_center, bounds, \
&tree->nodes[node->pos])))
@@ -446,10 +446,10 @@ static bool kdtree2d_isect_tri_recursive(
static bool kdtree2d_isect_tri(
struct KDTree2D *tree,
- const unsigned int ind[3])
+ const uint ind[3])
{
const float *vs[3];
- unsigned int i;
+ uint i;
struct KDRange2D bounds[2] = {
{FLT_MAX, -FLT_MAX},
{FLT_MAX, -FLT_MAX},
@@ -475,7 +475,7 @@ static bool kdtree2d_isect_tri(
#endif /* USE_KDTREE */
-static unsigned int *pf_tri_add(PolyFill *pf)
+static uint *pf_tri_add(PolyFill *pf)
{
return pf->tris[pf->tris_tot++];
}
@@ -496,7 +496,7 @@ static void pf_coord_remove(PolyFill *pf, PolyIndex *pi)
pf->indices = pi->next;
}
#ifdef DEBUG
- pi->index = (unsigned int)-1;
+ pi->index = (uint)-1;
pi->next = pi->prev = NULL;
#endif
@@ -594,7 +594,7 @@ static void pf_triangulate(PolyFill *pf)
}
if (pf->coords_tot == 3) {
- unsigned int *tri = pf_tri_add(pf);
+ uint *tri = pf_tri_add(pf);
pi_ear = pf->indices;
tri[0] = pi_ear->index; pi_ear = pi_ear->next;
tri[1] = pi_ear->index; pi_ear = pi_ear->next;
@@ -627,10 +627,10 @@ static PolyIndex *pf_ear_tip_find(
)
{
/* localize */
- const unsigned int coords_tot = pf->coords_tot;
+ const uint coords_tot = pf->coords_tot;
PolyIndex *pi_ear;
- unsigned int i;
+ uint i;
#ifdef USE_CLIP_EVEN
pi_ear = pi_ear_init;
@@ -688,7 +688,7 @@ static bool pf_ear_tip_check(PolyFill *pf, PolyIndex *pi_ear_tip)
#endif
#if defined(USE_CONVEX_SKIP) && !defined(USE_KDTREE)
- unsigned int coords_tot_concave_checked = 0;
+ uint coords_tot_concave_checked = 0;
#endif
@@ -697,13 +697,13 @@ static bool pf_ear_tip_check(PolyFill *pf, PolyIndex *pi_ear_tip)
#ifdef USE_CONVEX_SKIP_TEST
/* check if counting is wrong */
{
- unsigned int coords_tot_concave_test = 0;
- unsigned int i = pf->coords_tot;
- while (i--) {
- if (coords_sign[indices[i]] != CONVEX) {
+ uint coords_tot_concave_test = 0;
+ PolyIndex *pi_iter = pi_ear_tip;
+ do {
+ if (pi_iter->sign != CONVEX) {
coords_tot_concave_test += 1;
}
- }
+ } while ((pi_iter = pi_iter->next) != pi_ear_tip);
BLI_assert(coords_tot_concave_test == pf->coords_tot_concave);
}
#endif
@@ -720,7 +720,7 @@ static bool pf_ear_tip_check(PolyFill *pf, PolyIndex *pi_ear_tip)
#ifdef USE_KDTREE
{
- const unsigned int ind[3] = {
+ const uint ind[3] = {
pi_ear_tip->index,
pi_ear_tip->next->index,
pi_ear_tip->prev->index};
@@ -771,7 +771,7 @@ static bool pf_ear_tip_check(PolyFill *pf, PolyIndex *pi_ear_tip)
static void pf_ear_tip_cut(PolyFill *pf, PolyIndex *pi_ear_tip)
{
- unsigned int *tri = pf_tri_add(pf);
+ uint *tri = pf_tri_add(pf);
tri[0] = pi_ear_tip->prev->index;
tri[1] = pi_ear_tip->index;
@@ -786,15 +786,15 @@ static void pf_ear_tip_cut(PolyFill *pf, PolyIndex *pi_ear_tip)
static void polyfill_prepare(
PolyFill *pf,
const float (*coords)[2],
- const unsigned int coords_tot,
+ const uint coords_tot,
int coords_sign,
- unsigned int (*r_tris)[3],
+ uint (*r_tris)[3],
PolyIndex *r_indices)
{
/* localize */
PolyIndex *indices = r_indices;
- unsigned int i;
+ uint i;
/* assign all polyfill members here */
pf->indices = r_indices;
@@ -832,7 +832,7 @@ static void polyfill_prepare(
}
else {
/* reversed */
- unsigned int n = coords_tot - 1;
+ uint n = coords_tot - 1;
for (i = 0; i < coords_tot; i++) {
indices[i].next = &indices[i + 1];
indices[i].prev = &indices[i - 1];
@@ -876,9 +876,9 @@ static void polyfill_calc(
*/
void BLI_polyfill_calc_arena(
const float (*coords)[2],
- const unsigned int coords_tot,
+ const uint coords_tot,
const int coords_sign,
- unsigned int (*r_tris)[3],
+ uint (*r_tris)[3],
struct MemArena *arena)
{
@@ -932,9 +932,9 @@ void BLI_polyfill_calc_arena(
*/
void BLI_polyfill_calc(
const float (*coords)[2],
- const unsigned int coords_tot,
+ const uint coords_tot,
const int coords_sign,
- unsigned int (*r_tris)[3])
+ uint (*r_tris)[3])
{
PolyFill pf;
PolyIndex *indices = BLI_array_alloca(indices, coords_tot);
diff --git a/source/blender/blenlib/intern/polyfill_2d_beautify.c b/source/blender/blenlib/intern/polyfill_2d_beautify.c
new file mode 100644
index 00000000000..17f3205aaff
--- /dev/null
+++ b/source/blender/blenlib/intern/polyfill_2d_beautify.c
@@ -0,0 +1,440 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/blenlib/intern/polyfill_2d_beautify.c
+ * \ingroup bli
+ *
+ * This function is to improve the tessellation resulting from polyfill2d,
+ * creating optimal topology.
+ *
+ * The functionality here matches #BM_mesh_beautify_fill,
+ * but its far simpler to perform this operation in 2d,
+ * on a simple polygon representation where we _know_:
+ *
+ * - The polygon is primitive with no holes with a continuous boundary.
+ * - Tris have consistent winding.
+ * - 2d (saves some hassles projecting face pairs on an axis for every edge-rotation)
+ * also saves us having to store all previous edge-states (see #EdRotState in bmesh_beautify.c)
+ *
+ * \note
+ *
+ * No globals - keep threadsafe.
+ */
+
+#include "BLI_utildefines.h"
+#include "BLI_math.h"
+
+#include "BLI_memarena.h"
+#include "BLI_heap.h"
+
+#include "BLI_polyfill_2d_beautify.h" /* own include */
+
+#include "BLI_strict_flags.h"
+
+/* Used to find matching edges. */
+struct OrderEdge {
+ uint verts[2];
+ uint e_half;
+};
+
+/* Half edge used for rotating in-place. */
+struct HalfEdge {
+ uint v;
+ uint e_next;
+ uint e_radial;
+ uint base_index;
+};
+
+static int oedge_cmp(const void *a1, const void *a2)
+{
+ const struct OrderEdge *x1 = a1, *x2 = a2;
+ if (x1->verts[0] > x2->verts[0]) {
+ return 1;
+ }
+ else if (x1->verts[0] < x2->verts[0]) {
+ return -1;
+ }
+
+ if (x1->verts[1] > x2->verts[1]) {
+ return 1;
+ }
+ else if (x1->verts[1] < x2->verts[1]) {
+ return -1;
+ }
+
+ /* only for pradictability */
+ if (x1->e_half > x2->e_half) {
+ return 1;
+ }
+ else if (x1->e_half < x2->e_half) {
+ return -1;
+ }
+ /* Should never get here, no two edges should be the same. */
+ BLI_assert(false);
+ return 0;
+}
+
+BLI_INLINE bool is_boundary_edge(uint i_a, uint i_b, const uint coord_last)
+{
+ BLI_assert(i_a < i_b);
+ return ((i_a + 1 == i_b) || UNLIKELY((i_a == 0) && (i_b == coord_last)));
+}
+/**
+ * Assuming we have 2 triangles sharing an edge (2 - 4),
+ * check if the edge running from (1 - 3) gives better results.
+ *
+ * \param lock_degenerate: Use to avoid rotating out of a degenerate state.
+ * - When true, an existing zero area face on either side of the (2 - 4) split will return a positive value.
+ * - When false, the check must be non-biased towards either split direction.
+ *
+ * \return (negative number means the edge can be rotated, lager == better).
+ */
+float BLI_polyfill_beautify_quad_rotate_calc_ex(
+ const float v1[2], const float v2[2], const float v3[2], const float v4[2],
+ const bool lock_degenerate)
+{
+ /* not a loop (only to be able to break out) */
+ do {
+ /* Allow very small faces to be considered non-zero. */
+ const float eps_zero_area = 1e-12f;
+ const float area_2x_234 = cross_tri_v2(v2, v3, v4);
+ const float area_2x_241 = cross_tri_v2(v2, v4, v1);
+
+ const float area_2x_123 = cross_tri_v2(v1, v2, v3);
+ const float area_2x_134 = cross_tri_v2(v1, v3, v4);
+
+ BLI_assert((ELEM(v1, v2, v3, v4) == false) &&
+ (ELEM(v2, v1, v3, v4) == false) &&
+ (ELEM(v3, v1, v2, v4) == false) &&
+ (ELEM(v4, v1, v2, v3) == false));
+ /*
+ * Test for unusable (1-3) state.
+ * - Area sign flipping to check faces aren't going to point in opposite directions.
+ * - Area epsilon check that the one of the faces won't be zero area.
+ */
+ if ((area_2x_123 >= 0.0f) != (area_2x_134 >= 0.0f)) {
+ break;
+ }
+ else if ((fabsf(area_2x_123) <= eps_zero_area) || (fabsf(area_2x_134) <= eps_zero_area)) {
+ break;
+ }
+
+ /* Test for unusable (2-4) state (same as above). */
+ if ((area_2x_234 >= 0.0f) != (area_2x_241 >= 0.0f)) {
+ if (lock_degenerate) {
+ break;
+ }
+ else {
+ return -FLT_MAX; /* always rotate */
+ }
+ }
+ else if ((fabsf(area_2x_234) <= eps_zero_area) || (fabsf(area_2x_241) <= eps_zero_area)) {
+ return -FLT_MAX; /* always rotate */
+ }
+
+ {
+ /* testing rule: the area divided by the perimeter,
+ * check if (1-3) beats the existing (2-4) edge rotation */
+ float area_a, area_b;
+ float prim_a, prim_b;
+ float fac_24, fac_13;
+
+ float len_12, len_23, len_34, len_41, len_24, len_13;
+
+ /* edges around the quad */
+ len_12 = len_v2v2(v1, v2);
+ len_23 = len_v2v2(v2, v3);
+ len_34 = len_v2v2(v3, v4);
+ len_41 = len_v2v2(v4, v1);
+ /* edges crossing the quad interior */
+ len_13 = len_v2v2(v1, v3);
+ len_24 = len_v2v2(v2, v4);
+
+ /* note, area is in fact (area * 2),
+ * but in this case its OK, since we're comparing ratios */
+
+ /* edge (2-4), current state */
+ area_a = fabsf(area_2x_234);
+ area_b = fabsf(area_2x_241);
+ prim_a = len_23 + len_34 + len_24;
+ prim_b = len_41 + len_12 + len_24;
+ fac_24 = (area_a / prim_a) + (area_b / prim_b);
+
+ /* edge (1-3), new state */
+ area_a = fabsf(area_2x_123);
+ area_b = fabsf(area_2x_134);
+ prim_a = len_12 + len_23 + len_13;
+ prim_b = len_34 + len_41 + len_13;
+ fac_13 = (area_a / prim_a) + (area_b / prim_b);
+
+ /* negative number if (1-3) is an improved state */
+ return fac_24 - fac_13;
+ }
+ } while (false);
+
+ return FLT_MAX;
+}
+
+static float polyedge_rotate_beauty_calc(
+ const float (*coords)[2],
+ const struct HalfEdge *edges,
+ const struct HalfEdge *e_a)
+{
+ const struct HalfEdge *e_b = &edges[e_a->e_radial];
+
+ const struct HalfEdge *e_a_other = &edges[edges[e_a->e_next].e_next];
+ const struct HalfEdge *e_b_other = &edges[edges[e_b->e_next].e_next];
+
+ const float *v1, *v2, *v3, *v4;
+
+ v1 = coords[e_a_other->v];
+ v2 = coords[e_a->v];
+ v3 = coords[e_b_other->v];
+ v4 = coords[e_b->v];
+
+ return BLI_polyfill_beautify_quad_rotate_calc(v1, v2, v3, v4);
+}
+
+static void polyedge_beauty_cost_update_single(
+ const float (*coords)[2],
+ const struct HalfEdge *edges,
+ struct HalfEdge *e,
+ Heap *eheap, HeapNode **eheap_table)
+{
+ const uint i = e->base_index;
+ /* recalculate edge */
+ const float cost = polyedge_rotate_beauty_calc(coords, edges, e);
+ /* We can get cases where both choices generate very small negative costs, which leads to infinite loop.
+ * Anyway, costs above that are not worth recomputing, maybe we could even optimize it to a smaller limit?
+ * Actually, FLT_EPSILON is too small in some cases, 1e-6f seems to work OK hopefully?
+ * See T43578, T49478. */
+ if (cost < -1e-6f) {
+ BLI_heap_insert_or_update(eheap, &eheap_table[i], cost, e);
+ }
+ else {
+ if (eheap_table[i]) {
+ BLI_heap_remove(eheap, eheap_table[i]);
+ eheap_table[i] = NULL;
+ }
+ }
+}
+
+static void polyedge_beauty_cost_update(
+ const float (*coords)[2],
+ struct HalfEdge *edges,
+ struct HalfEdge *e,
+ Heap *eheap, HeapNode **eheap_table)
+{
+ struct HalfEdge *e_arr[4];
+ e_arr[0] = &edges[e->e_next];
+ e_arr[1] = &edges[e_arr[0]->e_next];
+
+ e = &edges[e->e_radial];
+ e_arr[2] = &edges[e->e_next];
+ e_arr[3] = &edges[e_arr[2]->e_next];
+
+ for (uint i = 0; i < 4; i++) {
+ if (e_arr[i] && e_arr[i]->base_index != UINT_MAX) {
+ polyedge_beauty_cost_update_single(
+ coords, edges,
+ e_arr[i],
+ eheap, eheap_table);
+ }
+ }
+}
+
+static void polyedge_rotate(
+ struct HalfEdge *edges,
+ struct HalfEdge *e)
+{
+ /** CCW winding, rotate internal edge to new vertical state.
+ *
+ * \code{.unparsed}
+ * Before After
+ * X X
+ * / \ /|\
+ * e4/ \e5 e4/ | \e5
+ * / e3 \ / | \
+ * X ------- X -> X e0|e3 X
+ * \ e0 / \ | /
+ * e2\ /e1 e2\ | /e1
+ * \ / \|/
+ * X X
+ * \endcode
+ */
+ struct HalfEdge *ed[6];
+ uint ed_index[6];
+
+ ed_index[0] = (uint)(e - edges);
+ ed[0] = &edges[ed_index[0]];
+ ed_index[1] = ed[0]->e_next;
+ ed[1] = &edges[ed_index[1]];
+ ed_index[2] = ed[1]->e_next;
+ ed[2] = &edges[ed_index[2]];
+
+ ed_index[3] = e->e_radial;
+ ed[3] = &edges[ed_index[3]];
+ ed_index[4] = ed[3]->e_next;
+ ed[4] = &edges[ed_index[4]];
+ ed_index[5] = ed[4]->e_next;
+ ed[5] = &edges[ed_index[5]];
+
+ ed[0]->e_next = ed_index[2];
+ ed[1]->e_next = ed_index[3];
+ ed[2]->e_next = ed_index[4];
+ ed[3]->e_next = ed_index[5];
+ ed[4]->e_next = ed_index[0];
+ ed[5]->e_next = ed_index[1];
+
+ ed[0]->v = ed[5]->v;
+ ed[3]->v = ed[2]->v;
+}
+
+/**
+ * The intention is that this calculates the output of #BLI_polyfill_calc
+ *
+ *
+ * \note assumes the \a coords form a boundary,
+ * so any edges running along contiguous (wrapped) indices,
+ * are ignored since the edges wont share 2 faces.
+ */
+void BLI_polyfill_beautify(
+ const float (*coords)[2],
+ const uint coords_tot,
+ uint (*tris)[3],
+
+ /* structs for reuse */
+ MemArena *arena, Heap *eheap)
+{
+ const uint coord_last = coords_tot - 1;
+ const uint tris_len = coords_tot - 2;
+ /* internal edges only (between 2 tris) */
+ const uint edges_len = tris_len - 1;
+
+ HeapNode **eheap_table;
+
+ const uint half_edges_len = 3 * tris_len;
+ struct HalfEdge *half_edges = BLI_memarena_alloc(arena, sizeof(*half_edges) * half_edges_len);
+ struct OrderEdge *order_edges = BLI_memarena_alloc(arena, sizeof(struct OrderEdge) * 2 * edges_len);
+ uint order_edges_len = 0;
+
+ /* first build edges */
+ for (uint i = 0; i < tris_len; i++) {
+ for (uint j_curr = 0, j_prev = 2; j_curr < 3; j_prev = j_curr++) {
+ const uint e_index_prev = (i * 3) + j_prev;
+ const uint e_index_curr = (i * 3) + j_curr;
+
+ half_edges[e_index_prev].v = tris[i][j_prev];
+ half_edges[e_index_prev].e_next = e_index_curr;
+ half_edges[e_index_prev].e_radial = UINT_MAX;
+ half_edges[e_index_prev].base_index = UINT_MAX;
+
+ uint e_pair[2] = {tris[i][j_prev], tris[i][j_curr]};
+ if (e_pair[0] > e_pair[1]) {
+ SWAP(uint, e_pair[0], e_pair[1]);
+ }
+
+ /* ensure internal edges. */
+ if (!is_boundary_edge(e_pair[0], e_pair[1], coord_last)) {
+ order_edges[order_edges_len].verts[0] = e_pair[0];
+ order_edges[order_edges_len].verts[1] = e_pair[1];
+ order_edges[order_edges_len].e_half = e_index_prev;
+ order_edges_len += 1;
+ }
+ }
+ }
+ BLI_assert(edges_len * 2 == order_edges_len);
+
+ qsort(order_edges, order_edges_len, sizeof(struct OrderEdge), oedge_cmp);
+
+ for (uint i = 0, base_index = 0; i < order_edges_len; base_index++) {
+ const struct OrderEdge *oe_a = &order_edges[i++];
+ const struct OrderEdge *oe_b = &order_edges[i++];
+ BLI_assert(oe_a->verts[0] == oe_a->verts[0] && oe_a->verts[1] == oe_a->verts[1]);
+ half_edges[oe_a->e_half].e_radial = oe_b->e_half;
+ half_edges[oe_b->e_half].e_radial = oe_a->e_half;
+ half_edges[oe_a->e_half].base_index = base_index;
+ half_edges[oe_b->e_half].base_index = base_index;
+ }
+ /* order_edges could be freed now. */
+
+ /* Now perform iterative rotations. */
+#if 0
+ eheap_table = BLI_memarena_alloc(arena, sizeof(HeapNode *) * (size_t)edges_len);
+#else
+ /* We can re-use this since its big enough. */
+ eheap_table = (void *)order_edges;
+ order_edges = NULL;
+#endif
+
+ /* Build heap. */
+ {
+ struct HalfEdge *e = half_edges;
+ for (uint i = 0; i < half_edges_len; i++, e++) {
+ /* Accounts for boundary edged too (UINT_MAX). */
+ if (e->e_radial < i) {
+ const float cost = polyedge_rotate_beauty_calc(coords, half_edges, e);
+ if (cost < 0.0f) {
+ eheap_table[e->base_index] = BLI_heap_insert(eheap, cost, e);
+ }
+ else {
+ eheap_table[e->base_index] = NULL;
+ }
+ }
+ }
+ }
+
+ while (BLI_heap_is_empty(eheap) == false) {
+ struct HalfEdge *e = BLI_heap_pop_min(eheap);
+ eheap_table[e->base_index] = NULL;
+
+ polyedge_rotate(half_edges, e);
+
+ /* recalculate faces connected on the heap */
+ polyedge_beauty_cost_update(
+ coords, half_edges,
+ e,
+ eheap, eheap_table);
+ }
+
+ BLI_heap_clear(eheap, NULL);
+
+ /* MEM_freeN(eheap_table); */ /* arena */
+
+ /* get tris from half edge. */
+ uint tri_index = 0;
+ for (uint i = 0; i < half_edges_len; i++) {
+ struct HalfEdge *e = &half_edges[i];
+ if (e->v != UINT_MAX) {
+ uint *tri = tris[tri_index++];
+
+ tri[0] = e->v;
+ e->v = UINT_MAX;
+
+ e = &half_edges[e->e_next];
+ tri[1] = e->v;
+ e->v = UINT_MAX;
+
+ e = &half_edges[e->e_next];
+ tri[2] = e->v;
+ e->v = UINT_MAX;
+ }
+ }
+}
diff --git a/source/blender/blenlib/intern/rand.c b/source/blender/blenlib/intern/rand.c
index 40d9a3da3d9..1a178db1413 100644
--- a/source/blender/blenlib/intern/rand.c
+++ b/source/blender/blenlib/intern/rand.c
@@ -41,6 +41,9 @@
#include "BLI_rand.h"
#include "BLI_math.h"
+/* defines BLI_INLINE */
+#include "BLI_utildefines.h"
+
#include "BLI_sys_types.h"
#include "BLI_strict_flags.h"
@@ -353,3 +356,101 @@ int BLI_rng_thread_rand(RNG_THREAD_ARRAY *rngarr, int thread)
return BLI_rng_get_int(&rngarr->rng_tab[thread]);
}
+/* ********* Low-discrepancy sequences ************** */
+
+/* incremental halton sequence generator, from:
+ * "Instant Radiosity", Keller A. */
+BLI_INLINE double halton_ex(double invprimes, double *offset)
+{
+ double e = fabs((1.0 - *offset) - 1e-10);
+
+ if (invprimes >= e) {
+ double lasth;
+ double h = invprimes;
+
+ do {
+ lasth = h;
+ h *= invprimes;
+ } while (h >= e);
+
+ *offset += ((lasth + h) - 1.0);
+ }
+ else {
+ *offset += invprimes;
+ }
+
+ return *offset;
+}
+
+void BLI_halton_1D(unsigned int prime, double offset, int n, double *r)
+{
+ const double invprime = 1.0 / (double)prime;
+
+ for (int s = 0; s < n; s++) {
+ *r = halton_ex(invprime, &offset);
+ }
+}
+
+void BLI_halton_2D(unsigned int prime[2], double offset[2], int n, double *r)
+{
+ const double invprimes[2] = {1.0 / (double)prime[0], 1.0 / (double)prime[1]};
+
+ for (int s = 0; s < n; s++) {
+ for (int i = 0; i < 2; i++) {
+ r[i] = halton_ex(invprimes[i], &offset[i]);
+ }
+ }
+}
+
+void BLI_halton_3D(unsigned int prime[3], double offset[3], int n, double *r)
+{
+ const double invprimes[3] = {1.0 / (double)prime[0], 1.0 / (double)prime[1], 1.0 / (double)prime[2]};
+
+ for (int s = 0; s < n; s++) {
+ for (int i = 0; i < 3; i++) {
+ r[i] = halton_ex(invprimes[i], &offset[i]);
+ }
+ }
+}
+
+void BLI_halton_2D_sequence(unsigned int prime[2], double offset[2], int n, double *r)
+{
+ const double invprimes[2] = {1.0 / (double)prime[0], 1.0 / (double)prime[1]};
+
+ for (int s = 0; s < n; s++) {
+ for (int i = 0; i < 2; i++) {
+ r[s * 2 + i] = halton_ex(invprimes[i], &offset[i]);
+ }
+ }
+}
+
+
+/* From "Sampling with Hammersley and Halton Points" TT Wong
+ * Appendix: Source Code 1 */
+BLI_INLINE double radical_inverse(unsigned int n)
+{
+ double u = 0;
+
+ /* This reverse the bitwise representation
+ * around the decimal point. */
+ for (double p = 0.5; n; p *= 0.5, n >>= 1) {
+ if (n & 1) {
+ u += p;
+ }
+ }
+
+ return u;
+}
+
+void BLI_hammersley_1D(unsigned int n, double *r)
+{
+ *r = radical_inverse(n);
+}
+
+void BLI_hammersley_2D_sequence(unsigned int n, double *r)
+{
+ for (unsigned int s = 0; s < n; s++) {
+ r[s * 2 + 0] = (double)(s + 0.5) / (double)n;
+ r[s * 2 + 1] = radical_inverse(s);
+ }
+}
diff --git a/source/blender/blenlib/intern/rct.c b/source/blender/blenlib/intern/rct.c
index ac73a981b45..764b12431d0 100644
--- a/source/blender/blenlib/intern/rct.c
+++ b/source/blender/blenlib/intern/rct.c
@@ -32,6 +32,7 @@
* A minimalist lib for functions doing stuff with rectangle structs.
*/
+#include <stdlib.h>
#include <stdio.h>
#include <math.h>
@@ -41,6 +42,9 @@
#include "DNA_vec_types.h"
#include "BLI_rect.h"
+/* avoid including BLI_math */
+static void unit_m4(float m[4][4]);
+
/**
* Determine if a rect is empty. An empty
* rect is one with a zero (or negative)
@@ -124,7 +128,7 @@ bool BLI_rctf_isect_pt_v(const rctf *rect, const float xy[2])
/**
* \returns shortest distance from \a rect to x/y (0 if inside)
-*/
+ */
int BLI_rcti_length_x(const rcti *rect, const int x)
{
@@ -351,6 +355,22 @@ void BLI_rcti_init(rcti *rect, int xmin, int xmax, int ymin, int ymax)
}
}
+void BLI_rctf_init_pt_radius(rctf *rect, const float xy[2], float size)
+{
+ rect->xmin = xy[0] - size;
+ rect->xmax = xy[0] + size;
+ rect->ymin = xy[1] - size;
+ rect->ymax = xy[1] + size;
+}
+
+void BLI_rcti_init_pt_radius(rcti *rect, const int xy[2], int size)
+{
+ rect->xmin = xy[0] - size;
+ rect->xmax = xy[0] + size;
+ rect->ymin = xy[1] - size;
+ rect->ymax = xy[1] + size;
+}
+
void BLI_rcti_init_minmax(rcti *rect)
{
rect->xmin = rect->ymin = INT_MAX;
@@ -389,6 +409,31 @@ void BLI_rctf_transform_pt_v(const rctf *dst, const rctf *src, float xy_dst[2],
xy_dst[1] = dst->ymin + ((dst->ymax - dst->ymin) * xy_dst[1]);
}
+/**
+ * Calculate a 4x4 matrix representing the transformation between two rectangles.
+ *
+ * \note Multiplying a vector by this matrix does *not* give the same value as #BLI_rctf_transform_pt_v.
+ */
+void BLI_rctf_transform_calc_m4_pivot_min_ex(
+ const rctf *dst, const rctf *src, float matrix[4][4],
+ uint x, uint y)
+{
+ BLI_assert(x < 3 && y < 3);
+
+ unit_m4(matrix);
+
+ matrix[x][x] = BLI_rctf_size_x(src) / BLI_rctf_size_x(dst);
+ matrix[y][y] = BLI_rctf_size_y(src) / BLI_rctf_size_y(dst);
+ matrix[3][x] = (src->xmin - dst->xmin) * matrix[x][x];
+ matrix[3][y] = (src->ymin - dst->ymin) * matrix[y][y];
+}
+
+void BLI_rctf_transform_calc_m4_pivot_min(
+ const rctf *dst, const rctf *src, float matrix[4][4])
+{
+ BLI_rctf_transform_calc_m4_pivot_min_ex(dst, src, matrix, 0, 1);
+}
+
void BLI_rcti_translate(rcti *rect, int x, int y)
{
rect->xmin += x;
@@ -677,6 +722,14 @@ void BLI_rcti_rctf_copy_floor(rcti *dst, const rctf *src)
dst->ymax = floorf(src->ymax);
}
+void BLI_rcti_rctf_copy_round(rcti *dst, const rctf *src)
+{
+ dst->xmin = floorf(src->xmin + 0.5f);
+ dst->xmax = floorf(src->xmax + 0.5f);
+ dst->ymin = floorf(src->ymin + 0.5f);
+ dst->ymax = floorf(src->ymax + 0.5f);
+}
+
void BLI_rctf_rcti_copy(rctf *dst, const rcti *src)
{
dst->xmin = src->xmin;
@@ -739,3 +792,12 @@ void BLI_rctf_rotate_expand(rctf *dst, const rctf *src, const float angle)
#undef ROTATE_SINCOS
/** \} */
+
+static void unit_m4(float m[4][4])
+{
+ m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1.0f;
+ m[0][1] = m[0][2] = m[0][3] = 0.0f;
+ m[1][0] = m[1][2] = m[1][3] = 0.0f;
+ m[2][0] = m[2][1] = m[2][3] = 0.0f;
+ m[3][0] = m[3][1] = m[3][2] = 0.0f;
+}
diff --git a/source/blender/blenlib/intern/smallhash.c b/source/blender/blenlib/intern/smallhash.c
index ccac221d836..56d77abed24 100644
--- a/source/blender/blenlib/intern/smallhash.c
+++ b/source/blender/blenlib/intern/smallhash.c
@@ -69,8 +69,8 @@
/* typically this re-assigns 'h' */
#define SMHASH_NEXT(h, hoff) ( \
- CHECK_TYPE_INLINE(&(h), unsigned int *), \
- CHECK_TYPE_INLINE(&(hoff), unsigned int *), \
+ CHECK_TYPE_INLINE(&(h), uint *), \
+ CHECK_TYPE_INLINE(&(hoff), uint *), \
((h) + (((hoff) = ((hoff) * 2) + 1), (hoff))) \
)
@@ -87,17 +87,17 @@ BLI_INLINE bool smallhash_val_is_used(const void *val)
#endif
}
-extern const unsigned int hashsizes[];
+extern const uint hashsizes[];
-BLI_INLINE unsigned int smallhash_key(const uintptr_t key)
+BLI_INLINE uint smallhash_key(const uintptr_t key)
{
- return (unsigned int)key;
+ return (uint)key;
}
/**
* Check if the number of items in the smallhash is large enough to require more buckets.
*/
-BLI_INLINE bool smallhash_test_expand_buckets(const unsigned int nentries, const unsigned int nbuckets)
+BLI_INLINE bool smallhash_test_expand_buckets(const uint nentries, const uint nbuckets)
{
/* (approx * 1.5) */
return (nentries + (nentries >> 1)) > nbuckets;
@@ -105,7 +105,7 @@ BLI_INLINE bool smallhash_test_expand_buckets(const unsigned int nentries, const
BLI_INLINE void smallhash_init_empty(SmallHash *sh)
{
- unsigned int i;
+ uint i;
for (i = 0; i < sh->nbuckets; i++) {
sh->buckets[i].key = SMHASH_KEY_UNUSED;
@@ -116,7 +116,7 @@ BLI_INLINE void smallhash_init_empty(SmallHash *sh)
/**
* Increase initial bucket size to match a reserved amount.
*/
-BLI_INLINE void smallhash_buckets_reserve(SmallHash *sh, const unsigned int nentries_reserve)
+BLI_INLINE void smallhash_buckets_reserve(SmallHash *sh, const uint nentries_reserve)
{
while (smallhash_test_expand_buckets(nentries_reserve, sh->nbuckets)) {
sh->nbuckets = hashsizes[++sh->cursize];
@@ -126,8 +126,8 @@ BLI_INLINE void smallhash_buckets_reserve(SmallHash *sh, const unsigned int nent
BLI_INLINE SmallHashEntry *smallhash_lookup(const SmallHash *sh, const uintptr_t key)
{
SmallHashEntry *e;
- unsigned int h = smallhash_key(key);
- unsigned int hoff = 1;
+ uint h = smallhash_key(key);
+ uint hoff = 1;
BLI_assert(key != SMHASH_KEY_UNUSED);
@@ -150,8 +150,8 @@ BLI_INLINE SmallHashEntry *smallhash_lookup(const SmallHash *sh, const uintptr_t
BLI_INLINE SmallHashEntry *smallhash_lookup_first_free(SmallHash *sh, const uintptr_t key)
{
SmallHashEntry *e;
- unsigned int h = smallhash_key(key);
- unsigned int hoff = 1;
+ uint h = smallhash_key(key);
+ uint hoff = 1;
for (e = &sh->buckets[h % sh->nbuckets];
smallhash_val_is_used(e->val);
@@ -163,12 +163,12 @@ BLI_INLINE SmallHashEntry *smallhash_lookup_first_free(SmallHash *sh, const uint
return e;
}
-BLI_INLINE void smallhash_resize_buckets(SmallHash *sh, const unsigned int nbuckets)
+BLI_INLINE void smallhash_resize_buckets(SmallHash *sh, const uint nbuckets)
{
SmallHashEntry *buckets_old = sh->buckets;
- const unsigned int nbuckets_old = sh->nbuckets;
+ const uint nbuckets_old = sh->nbuckets;
const bool was_alloc = (buckets_old != sh->buckets_stack);
- unsigned int i = 0;
+ uint i = 0;
BLI_assert(sh->nbuckets != nbuckets);
if (nbuckets <= SMSTACKSIZE) {
@@ -200,7 +200,7 @@ BLI_INLINE void smallhash_resize_buckets(SmallHash *sh, const unsigned int nbuck
}
void BLI_smallhash_init_ex(SmallHash *sh,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
/* assume 'sh' is uninitialized */
@@ -310,7 +310,7 @@ bool BLI_smallhash_haskey(const SmallHash *sh, uintptr_t key)
return (e != NULL);
}
-int BLI_smallhash_count(const SmallHash *sh)
+int BLI_smallhash_len(const SmallHash *sh)
{
return (int)sh->nentries;
}
@@ -371,7 +371,7 @@ void **BLI_smallhash_iternew_p(const SmallHash *sh, SmallHashIter *iter, uintptr
#if 0
void BLI_smallhash_print(SmallHash *sh)
{
- unsigned int i, linecol = 79, c = 0;
+ uint i, linecol = 79, c = 0;
printf("{");
for (i = 0; i < sh->nbuckets; i++) {
@@ -382,7 +382,7 @@ void BLI_smallhash_print(SmallHash *sh)
printf("--f-");
}
else {
- printf("%2x", (unsigned int)sh->buckets[i].key);
+ printf("%2x", (uint)sh->buckets[i].key);
}
if (i != sh->nbuckets - 1)
@@ -410,7 +410,7 @@ void BLI_smallhash_print(SmallHash *sh)
double BLI_smallhash_calc_quality(SmallHash *sh)
{
uint64_t sum = 0;
- unsigned int i;
+ uint i;
if (sh->nentries == 0)
return -1.0;
@@ -419,8 +419,8 @@ double BLI_smallhash_calc_quality(SmallHash *sh)
if (sh->buckets[i].key != SMHASH_KEY_UNUSED) {
uint64_t count = 0;
SmallHashEntry *e, *e_final = &sh->buckets[i];
- unsigned int h = smallhash_key(e_final->key);
- unsigned int hoff = 1;
+ uint h = smallhash_key(e_final->key);
+ uint hoff = 1;
for (e = &sh->buckets[h % sh->nbuckets];
e != e_final;
diff --git a/source/blender/blenlib/intern/sort_utils.c b/source/blender/blenlib/intern/sort_utils.c
index c75e8e7455f..2d55e77b98b 100644
--- a/source/blender/blenlib/intern/sort_utils.c
+++ b/source/blender/blenlib/intern/sort_utils.c
@@ -37,6 +37,10 @@ struct SortAnyByInt {
int sort_value;
};
+struct SortAnyByPtr {
+ const void *sort_value;
+};
+
int BLI_sortutil_cmp_float(const void *a_, const void *b_)
{
const struct SortAnyByFloat *a = a_;
@@ -72,3 +76,21 @@ int BLI_sortutil_cmp_int_reverse(const void *a_, const void *b_)
else if (a->sort_value > b->sort_value) return -1;
else return 0;
}
+
+int BLI_sortutil_cmp_ptr(const void *a_, const void *b_)
+{
+ const struct SortAnyByPtr *a = a_;
+ const struct SortAnyByPtr *b = b_;
+ if (a->sort_value > b->sort_value) return 1;
+ else if (a->sort_value < b->sort_value) return -1;
+ else return 0;
+}
+
+int BLI_sortutil_cmp_ptr_reverse(const void *a_, const void *b_)
+{
+ const struct SortAnyByPtr *a = a_;
+ const struct SortAnyByPtr *b = b_;
+ if (a->sort_value < b->sort_value) return 1;
+ else if (a->sort_value > b->sort_value) return -1;
+ else return 0;
+}
diff --git a/source/blender/blenlib/intern/storage.c b/source/blender/blenlib/intern/storage.c
index 3edc00a8c1a..f69b35ce5a9 100644
--- a/source/blender/blenlib/intern/storage.c
+++ b/source/blender/blenlib/intern/storage.c
@@ -37,14 +37,10 @@
#include <sys/stat.h>
-#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__sun__) || defined(__sun)
+#if defined(__NetBSD__) || defined(__DragonFly__) || defined(__HAIKU__)
/* Other modern unix os's should probably use this also */
# include <sys/statvfs.h>
# define USE_STATFS_STATVFS
-#elif (defined(__sparc) || defined(__sparc__)) && !defined(__FreeBSD__) && !defined(__linux__)
-# include <sys/statfs.h>
- /* 4 argument version (not common) */
-# define USE_STATFS_4ARGS
#endif
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
@@ -113,7 +109,7 @@ double BLI_dir_free_space(const char *dir)
#ifdef WIN32
DWORD sectorspc, bytesps, freec, clusters;
char tmp[4];
-
+
tmp[0] = '\\'; tmp[1] = 0; /* Just a failsafe */
if (dir[0] == '/' || dir[0] == '\\') {
tmp[0] = '\\';
@@ -139,10 +135,10 @@ double BLI_dir_free_space(const char *dir)
char name[FILE_MAXDIR], *slash;
int len = strlen(dir);
-
+
if (len >= FILE_MAXDIR) /* path too long */
return -1;
-
+
strcpy(name, dir);
if (len) {
@@ -189,12 +185,12 @@ size_t BLI_file_size(const char *path)
}
/**
- * Returns the st_mode from statting the specified path name, or 0 if it couldn't be statted
+ * Returns the st_mode from stat-ing the specified path name, or 0 if stat fails
* (most likely doesn't exist or no access).
*/
int BLI_exists(const char *name)
{
-#if defined(WIN32)
+#if defined(WIN32)
BLI_stat_t st;
wchar_t *tmp_16 = alloc_utf16_from_8(name, 1);
int len, res;
@@ -253,10 +249,8 @@ int BLI_stat(const char *path, BLI_stat_t *buffer)
int BLI_wstat(const wchar_t *path, BLI_stat_t *buffer)
{
-#if defined(_MSC_VER) || defined(__MINGW64__)
+#if defined(_MSC_VER)
return _wstat64(path, buffer);
-#elif defined(__MINGW32__)
- return _wstati64(path, buffer);
#else
return _wstat(path, buffer);
#endif
@@ -372,7 +366,7 @@ LinkNode *BLI_file_read_as_lines(const char *name)
size_t size;
if (!fp) return NULL;
-
+
fseek(fp, 0, SEEK_END);
size = (size_t)ftell(fp);
fseek(fp, 0, SEEK_SET);
@@ -385,7 +379,7 @@ LinkNode *BLI_file_read_as_lines(const char *name)
buf = MEM_mallocN(size, "file_as_lines");
if (buf) {
size_t i, last = 0;
-
+
/*
* size = because on win32 reading
* all the bytes in the file will return
@@ -395,18 +389,14 @@ LinkNode *BLI_file_read_as_lines(const char *name)
for (i = 0; i <= size; i++) {
if (i == size || buf[i] == '\n') {
char *line = BLI_strdupn(&buf[last], i - last);
-
BLI_linklist_append(&lines, line);
- /* faster to build singly-linked list in reverse order */
- /* alternatively, could process buffer in reverse order so
- * list ends up right way round to start with */
last = i + 1;
}
}
-
+
MEM_freeN(buf);
}
-
+
fclose(fp);
return lines.list;
@@ -424,23 +414,13 @@ void BLI_file_free_lines(LinkNode *lines)
bool BLI_file_older(const char *file1, const char *file2)
{
#ifdef WIN32
-#ifndef __MINGW32__
struct _stat st1, st2;
-#else
- struct _stati64 st1, st2;
-#endif
UTF16_ENCODE(file1);
UTF16_ENCODE(file2);
-
-#ifndef __MINGW32__
+
if (_wstat(file1_16, &st1)) return false;
if (_wstat(file2_16, &st2)) return false;
-#else
- if (_wstati64(file1_16, &st1)) return false;
- if (_wstati64(file2_16, &st2)) return false;
-#endif
-
UTF16_UN_ENCODE(file2);
UTF16_UN_ENCODE(file1);
diff --git a/source/blender/blenlib/intern/string.c b/source/blender/blenlib/intern/string.c
index f62ffe9e985..1a6fd082e95 100644
--- a/source/blender/blenlib/intern/string.c
+++ b/source/blender/blenlib/intern/string.c
@@ -208,7 +208,7 @@ size_t BLI_strcpy_rlen(char *__restrict dst, const char *__restrict src)
}
/**
- * Portable replacement for #vsnprintf
+ * Portable replacement for `vsnprintf`.
*/
size_t BLI_vsnprintf(char *__restrict buffer, size_t maxncpy, const char *__restrict format, va_list arg)
{
@@ -332,7 +332,7 @@ size_t BLI_strescape(char *__restrict dst, const char *__restrict src, const siz
goto escape_finish;
case '\\':
case '"':
- /* fall-through */
+ ATTR_FALLTHROUGH;
/* less common but should also be support */
case '\t':
@@ -346,7 +346,7 @@ size_t BLI_strescape(char *__restrict dst, const char *__restrict src, const siz
/* not enough space to escape */
break;
}
- /* fall-through */
+ ATTR_FALLTHROUGH;
default:
*dst = *src;
break;
@@ -503,7 +503,7 @@ int BLI_strcaseeq(const char *a, const char *b)
}
/**
- * Portable replacement for #strcasestr (not available in MSVC)
+ * Portable replacement for `strcasestr` (not available in MSVC)
*/
char *BLI_strcasestr(const char *s, const char *find)
{
@@ -931,13 +931,13 @@ size_t BLI_str_partition_ex(
if (end) {
if (from_right) {
for (tmp = end - 1; (tmp >= str) && (*tmp != *d); tmp--);
- if (tmp < str) {
+ if (tmp < str) {
tmp = NULL;
}
}
else {
tmp = func(str, *d);
- if (tmp >= end) {
+ if (tmp >= end) {
tmp = NULL;
}
}
diff --git a/source/blender/blenlib/intern/string_cursor_utf8.c b/source/blender/blenlib/intern/string_cursor_utf8.c
index 09b7ecb2277..d293490c846 100644
--- a/source/blender/blenlib/intern/string_cursor_utf8.c
+++ b/source/blender/blenlib/intern/string_cursor_utf8.c
@@ -40,7 +40,7 @@
# pragma GCC diagnostic error "-Wsign-conversion"
#endif
-typedef enum strCursorDelimType {
+typedef enum eStrCursorDelimType {
STRCUR_DELIM_NONE,
STRCUR_DELIM_ALPHANUMERIC,
STRCUR_DELIM_PUNCT,
@@ -49,9 +49,9 @@ typedef enum strCursorDelimType {
STRCUR_DELIM_QUOTE,
STRCUR_DELIM_WHITESPACE,
STRCUR_DELIM_OTHER
-} strCursorDelimType;
+} eStrCursorDelimType;
-static strCursorDelimType cursor_delim_type_unicode(const unsigned int uch)
+static eStrCursorDelimType cursor_delim_type_unicode(const uint uch)
{
switch (uch) {
case ',':
@@ -108,11 +108,11 @@ static strCursorDelimType cursor_delim_type_unicode(const unsigned int uch)
return STRCUR_DELIM_ALPHANUMERIC; /* Not quite true, but ok for now */
}
-static strCursorDelimType cursor_delim_type_utf8(const char *ch_utf8)
+static eStrCursorDelimType cursor_delim_type_utf8(const char *ch_utf8)
{
/* for full unicode support we really need to have large lookup tables to figure
* out whats what in every possible char set - and python, glib both have these. */
- unsigned int uch = BLI_str_utf8_as_unicode(ch_utf8);
+ uint uch = BLI_str_utf8_as_unicode(ch_utf8);
return cursor_delim_type_unicode(uch);
}
@@ -146,9 +146,10 @@ bool BLI_str_cursor_step_prev_utf8(const char *str, size_t UNUSED(maxlen), int *
return false;
}
-void BLI_str_cursor_step_utf8(const char *str, size_t maxlen,
- int *pos, strCursorJumpDirection direction,
- strCursorJumpType jump, bool use_init_step)
+void BLI_str_cursor_step_utf8(
+ const char *str, size_t maxlen,
+ int *pos, eStrCursorJumpDirection direction,
+ eStrCursorJumpType jump, bool use_init_step)
{
const int pos_orig = *pos;
@@ -161,13 +162,16 @@ void BLI_str_cursor_step_utf8(const char *str, size_t maxlen,
}
if (jump != STRCUR_JUMP_NONE) {
- const strCursorDelimType delim_type = (*pos) < maxlen ? cursor_delim_type_utf8(&str[*pos]) : STRCUR_DELIM_NONE;
+ const eStrCursorDelimType delim_type =
+ (*pos) < maxlen ? cursor_delim_type_utf8(&str[*pos]) : STRCUR_DELIM_NONE;
/* jump between special characters (/,\,_,-, etc.),
* look at function cursor_delim_type() for complete
* list of special character, ctr -> */
while ((*pos) < maxlen) {
if (BLI_str_cursor_step_next_utf8(str, maxlen, pos)) {
- if ((jump != STRCUR_JUMP_ALL) && (delim_type != cursor_delim_type_utf8(&str[*pos]))) {
+ if ((jump != STRCUR_JUMP_ALL) &&
+ (delim_type != cursor_delim_type_utf8(&str[*pos])))
+ {
break;
}
}
@@ -186,14 +190,17 @@ void BLI_str_cursor_step_utf8(const char *str, size_t maxlen,
}
if (jump != STRCUR_JUMP_NONE) {
- const strCursorDelimType delim_type = (*pos) > 0 ? cursor_delim_type_utf8(&str[(*pos) - 1]) : STRCUR_DELIM_NONE;
+ const eStrCursorDelimType delim_type =
+ (*pos) > 0 ? cursor_delim_type_utf8(&str[(*pos) - 1]) : STRCUR_DELIM_NONE;
/* jump between special characters (/,\,_,-, etc.),
* look at function cursor_delim_type() for complete
* list of special character, ctr -> */
while ((*pos) > 0) {
const int pos_prev = *pos;
if (BLI_str_cursor_step_prev_utf8(str, maxlen, pos)) {
- if ((jump != STRCUR_JUMP_ALL) && (delim_type != cursor_delim_type_utf8(&str[*pos]))) {
+ if ((jump != STRCUR_JUMP_ALL) &&
+ (delim_type != cursor_delim_type_utf8(&str[*pos])))
+ {
/* left only: compensate for index/change in direction */
if ((pos_orig - (*pos)) >= 1) {
*pos = pos_prev;
@@ -235,9 +242,10 @@ static bool wchar_t_step_prev(const wchar_t *UNUSED(str), size_t UNUSED(maxlen),
return true;
}
-void BLI_str_cursor_step_wchar(const wchar_t *str, size_t maxlen,
- int *pos, strCursorJumpDirection direction,
- strCursorJumpType jump, bool use_init_step)
+void BLI_str_cursor_step_wchar(
+ const wchar_t *str, size_t maxlen,
+ int *pos, eStrCursorJumpDirection direction,
+ eStrCursorJumpType jump, bool use_init_step)
{
const int pos_orig = *pos;
@@ -250,13 +258,16 @@ void BLI_str_cursor_step_wchar(const wchar_t *str, size_t maxlen,
}
if (jump != STRCUR_JUMP_NONE) {
- const strCursorDelimType delim_type = (*pos) < maxlen ? cursor_delim_type_unicode((unsigned int)str[*pos]) : STRCUR_DELIM_NONE;
+ const eStrCursorDelimType delim_type =
+ (*pos) < maxlen ? cursor_delim_type_unicode((uint)str[*pos]) : STRCUR_DELIM_NONE;
/* jump between special characters (/,\,_,-, etc.),
* look at function cursor_delim_type_unicode() for complete
* list of special character, ctr -> */
while ((*pos) < maxlen) {
if (wchar_t_step_next(str, maxlen, pos)) {
- if ((jump != STRCUR_JUMP_ALL) && (delim_type != cursor_delim_type_unicode((unsigned int)str[*pos]))) {
+ if ((jump != STRCUR_JUMP_ALL) &&
+ (delim_type != cursor_delim_type_unicode((uint)str[*pos])))
+ {
break;
}
}
@@ -275,14 +286,17 @@ void BLI_str_cursor_step_wchar(const wchar_t *str, size_t maxlen,
}
if (jump != STRCUR_JUMP_NONE) {
- const strCursorDelimType delim_type = (*pos) > 0 ? cursor_delim_type_unicode((unsigned int)str[(*pos) - 1]) : STRCUR_DELIM_NONE;
+ const eStrCursorDelimType delim_type =
+ (*pos) > 0 ? cursor_delim_type_unicode((uint)str[(*pos) - 1]) : STRCUR_DELIM_NONE;
/* jump between special characters (/,\,_,-, etc.),
* look at function cursor_delim_type() for complete
* list of special character, ctr -> */
while ((*pos) > 0) {
const int pos_prev = *pos;
if (wchar_t_step_prev(str, maxlen, pos)) {
- if ((jump != STRCUR_JUMP_ALL) && (delim_type != cursor_delim_type_unicode((unsigned int)str[*pos]))) {
+ if ((jump != STRCUR_JUMP_ALL) &&
+ (delim_type != cursor_delim_type_unicode((uint)str[*pos])))
+ {
/* left only: compensate for index/change in direction */
if ((pos_orig - (*pos)) >= 1) {
*pos = pos_prev;
@@ -300,4 +314,3 @@ void BLI_str_cursor_step_wchar(const wchar_t *str, size_t maxlen,
BLI_assert(0);
}
}
-
diff --git a/source/blender/blenlib/intern/string_utf8.c b/source/blender/blenlib/intern/string_utf8.c
index 83d4a75952f..b41f7d0be66 100644
--- a/source/blender/blenlib/intern/string_utf8.c
+++ b/source/blender/blenlib/intern/string_utf8.c
@@ -167,7 +167,7 @@ utf8_error:
/**
* Remove any invalid utf-8 byte (taking into account multi-bytes sequence of course).
*
- * @return number of stripped bytes.
+ * \return number of stripped bytes.
*/
int BLI_utf8_invalid_strip(char *str, size_t length)
{
@@ -205,11 +205,11 @@ int BLI_utf8_invalid_strip(char *str, size_t length)
while (*src != '\0' && (utf8_size = utf8_skip_data[*src]) < maxncpy) {\
maxncpy -= utf8_size; \
switch (utf8_size) { \
- case 6: *dst ++ = *src ++; \
- case 5: *dst ++ = *src ++; \
- case 4: *dst ++ = *src ++; \
- case 3: *dst ++ = *src ++; \
- case 2: *dst ++ = *src ++; \
+ case 6: *dst ++ = *src ++; ATTR_FALLTHROUGH; \
+ case 5: *dst ++ = *src ++; ATTR_FALLTHROUGH; \
+ case 4: *dst ++ = *src ++; ATTR_FALLTHROUGH; \
+ case 3: *dst ++ = *src ++; ATTR_FALLTHROUGH; \
+ case 2: *dst ++ = *src ++; ATTR_FALLTHROUGH; \
case 1: *dst ++ = *src ++; \
} \
} \
@@ -282,14 +282,14 @@ size_t BLI_strncpy_wchar_as_utf8(char *__restrict dst, const wchar_t *__restrict
#endif
while (*src && len <= maxlen_secured) {
- len += BLI_str_utf8_from_unicode((unsigned int)*src++, dst + len);
+ len += BLI_str_utf8_from_unicode((uint)*src++, dst + len);
}
/* We have to be more careful for the last six bytes, to avoid buffer overflow in case utf8-encoded char
* would be too long for our dst buffer. */
while (*src) {
char t[6];
- size_t l = BLI_str_utf8_from_unicode((unsigned int)*src++, t);
+ size_t l = BLI_str_utf8_from_unicode((uint)*src++, t);
BLI_assert(l <= 6);
if (len + l > maxlen) {
break;
@@ -309,7 +309,7 @@ size_t BLI_wstrlen_utf8(const wchar_t *src)
size_t len = 0;
while (*src) {
- len += BLI_str_utf8_from_unicode((unsigned int)*src++, NULL);
+ len += BLI_str_utf8_from_unicode((uint)*src++, NULL);
}
return len;
@@ -381,7 +381,7 @@ size_t BLI_strncpy_wchar_from_utf8(wchar_t *__restrict dst_w, const char *__rest
while (*src_c && len != maxlen) {
size_t step = 0;
- unsigned int unicode = BLI_str_utf8_as_unicode_and_size(src_c, &step);
+ uint unicode = BLI_str_utf8_as_unicode_and_size(src_c, &step);
if (unicode != BLI_UTF8_ERR) {
*dst_w = (wchar_t)unicode;
src_c += step;
@@ -416,7 +416,7 @@ int BLI_wcswidth(const wchar_t *pwcs, size_t n)
int BLI_str_utf8_char_width(const char *p)
{
- unsigned int unicode = BLI_str_utf8_as_unicode(p);
+ uint unicode = BLI_str_utf8_as_unicode(p);
if (unicode == BLI_UTF8_ERR)
return -1;
@@ -427,7 +427,7 @@ int BLI_str_utf8_char_width_safe(const char *p)
{
int columns;
- unsigned int unicode = BLI_str_utf8_as_unicode(p);
+ uint unicode = BLI_str_utf8_as_unicode(p);
if (unicode == BLI_UTF8_ERR)
return 1;
@@ -440,7 +440,7 @@ int BLI_str_utf8_char_width_safe(const char *p)
/* copied from glib's gutf8.c, added 'Err' arg */
-/* note, glib uses unsigned int for unicode, best we do the same,
+/* note, glib uses uint for unicode, best we do the same,
* though we don't typedef it - campbell */
#define UTF8_COMPUTE(Char, Mask, Len, Err) \
@@ -525,11 +525,11 @@ int BLI_str_utf8_size_safe(const char *p)
*
* Return value: the resulting character
**/
-unsigned int BLI_str_utf8_as_unicode(const char *p)
+uint BLI_str_utf8_as_unicode(const char *p)
{
int i, len;
- unsigned int mask = 0;
- unsigned int result;
+ uint mask = 0;
+ uint result;
const unsigned char c = (unsigned char) *p;
UTF8_COMPUTE(c, mask, len, -1);
@@ -541,11 +541,11 @@ unsigned int BLI_str_utf8_as_unicode(const char *p)
}
/* variant that increments the length */
-unsigned int BLI_str_utf8_as_unicode_and_size(const char *__restrict p, size_t *__restrict index)
+uint BLI_str_utf8_as_unicode_and_size(const char *__restrict p, size_t *__restrict index)
{
int i, len;
unsigned mask = 0;
- unsigned int result;
+ uint result;
const unsigned char c = (unsigned char) *p;
UTF8_COMPUTE(c, mask, len, -1);
@@ -556,11 +556,11 @@ unsigned int BLI_str_utf8_as_unicode_and_size(const char *__restrict p, size_t *
return result;
}
-unsigned int BLI_str_utf8_as_unicode_and_size_safe(const char *__restrict p, size_t *__restrict index)
+uint BLI_str_utf8_as_unicode_and_size_safe(const char *__restrict p, size_t *__restrict index)
{
int i, len;
- unsigned int mask = 0;
- unsigned int result;
+ uint mask = 0;
+ uint result;
const unsigned char c = (unsigned char) *p;
UTF8_COMPUTE(c, mask, len, -1);
@@ -575,11 +575,11 @@ unsigned int BLI_str_utf8_as_unicode_and_size_safe(const char *__restrict p, siz
/* another variant that steps over the index,
* note, currently this also falls back to latin1 for text drawing. */
-unsigned int BLI_str_utf8_as_unicode_step(const char *__restrict p, size_t *__restrict index)
+uint BLI_str_utf8_as_unicode_step(const char *__restrict p, size_t *__restrict index)
{
int i, len;
- unsigned int mask = 0;
- unsigned int result;
+ uint mask = 0;
+ uint result;
unsigned char c;
p += *index;
@@ -631,12 +631,12 @@ unsigned int BLI_str_utf8_as_unicode_step(const char *__restrict p, size_t *__re
*
* \return number of bytes written
**/
-size_t BLI_str_utf8_from_unicode(unsigned int c, char *outbuf)
+size_t BLI_str_utf8_from_unicode(uint c, char *outbuf)
{
/* If this gets modified, also update the copy in g_string_insert_unichar() */
- unsigned int len = 0;
- unsigned int first;
- unsigned int i;
+ uint len = 0;
+ uint first;
+ uint i;
if (c < 0x80) {
first = 0;
@@ -757,20 +757,20 @@ char *BLI_str_prev_char_utf8(const char *p)
}
/* end glib copy */
-size_t BLI_str_partition_utf8(const char *str, const unsigned int delim[], const char **sep, const char **suf)
+size_t BLI_str_partition_utf8(const char *str, const uint delim[], const char **sep, const char **suf)
{
return BLI_str_partition_ex_utf8(str, NULL, delim, sep, suf, false);
}
-size_t BLI_str_rpartition_utf8(const char *str, const unsigned int delim[], const char **sep, const char **suf)
+size_t BLI_str_rpartition_utf8(const char *str, const uint delim[], const char **sep, const char **suf)
{
return BLI_str_partition_ex_utf8(str, NULL, delim, sep, suf, true);
}
size_t BLI_str_partition_ex_utf8(
- const char *str, const char *end, const unsigned int delim[], const char **sep, const char **suf, const bool from_right)
+ const char *str, const char *end, const uint delim[], const char **sep, const char **suf, const bool from_right)
{
- const unsigned int *d;
+ const uint *d;
const size_t str_len = end ? (size_t)(end - str) : strlen(str);
size_t index;
@@ -783,7 +783,7 @@ size_t BLI_str_partition_ex_utf8(
*sep >= str && (!end || *sep < end) && **sep != '\0';
*sep = (char *)(from_right ? BLI_str_find_prev_char_utf8(str, *sep) : str + index))
{
- const unsigned int c = BLI_str_utf8_as_unicode_and_size(*sep, &index);
+ const uint c = BLI_str_utf8_as_unicode_and_size(*sep, &index);
if (c == BLI_UTF8_ERR) {
*suf = *sep = NULL;
diff --git a/source/blender/blenlib/intern/string_utils.c b/source/blender/blenlib/intern/string_utils.c
index 8d91a55a5ad..a693463a302 100644
--- a/source/blender/blenlib/intern/string_utils.c
+++ b/source/blender/blenlib/intern/string_utils.c
@@ -383,3 +383,91 @@ bool BLI_uniquename(ListBase *list, void *vlink, const char *defname, char delim
return BLI_uniquename_cb(uniquename_unique_check, &data, defname, delim, GIVE_STRADDR(vlink, name_offs), name_len);
}
+
+/* ------------------------------------------------------------------------- */
+/** \name Join Strings
+ *
+ * For non array versions of these functions, use the macros:
+ * - #BLI_string_joinN
+ * - #BLI_string_join_by_sep_charN
+ * - #BLI_string_join_by_sep_char_with_tableN
+ *
+ * \{ */
+
+/**
+ * Join an array of strings into a newly allocated, null terminated string.
+ */
+char *BLI_string_join_arrayN(
+ const char *strings[], uint strings_len)
+{
+ uint total_len = 1;
+ for (uint i = 0; i < strings_len; i++) {
+ total_len += strlen(strings[i]);
+ }
+ char *result = MEM_mallocN(sizeof(char) * total_len, __func__);
+ char *c = result;
+ for (uint i = 0; i < strings_len; i++) {
+ c += BLI_strcpy_rlen(c, strings[i]);
+ }
+ return result;
+}
+
+/**
+ * A version of #BLI_string_joinN that takes a separator which can be any character including '\0'.
+ */
+char *BLI_string_join_array_by_sep_charN(
+ char sep, const char *strings[], uint strings_len)
+{
+ uint total_len = 0;
+ for (uint i = 0; i < strings_len; i++) {
+ total_len += strlen(strings[i]) + 1;
+ }
+ if (total_len == 0) {
+ total_len = 1;
+ }
+
+ char *result = MEM_mallocN(sizeof(char) * total_len, __func__);
+ char *c = result;
+ if (strings_len != 0) {
+ for (uint i = 0; i < strings_len; i++) {
+ c += BLI_strcpy_rlen(c, strings[i]);
+ *c = sep;
+ c++;
+ }
+ c--;
+ }
+ *c = '\0';
+ return result;
+}
+
+/**
+ * A version of #BLI_string_join_array_by_sep_charN that takes a table array.
+ * The new location of each string is written into this array.
+ */
+char *BLI_string_join_array_by_sep_char_with_tableN(
+ char sep, char *table[], const char *strings[], uint strings_len)
+{
+ uint total_len = 0;
+ for (uint i = 0; i < strings_len; i++) {
+ total_len += strlen(strings[i]) + 1;
+ }
+ if (total_len == 0) {
+ total_len = 1;
+ }
+
+ char *result = MEM_mallocN(sizeof(char) * total_len, __func__);
+ char *c = result;
+ if (strings_len != 0) {
+ for (uint i = 0; i < strings_len; i++) {
+ table[i] = c; /* <-- only difference to BLI_string_join_array_by_sep_charN. */
+ c += BLI_strcpy_rlen(c, strings[i]);
+ *c = sep;
+ c++;
+ }
+ c--;
+ }
+ *c = '\0';
+ return result;
+}
+
+/** \} */
diff --git a/source/blender/blenlib/intern/system.c b/source/blender/blenlib/intern/system.c
index 863622f2546..ecb977c6e61 100644
--- a/source/blender/blenlib/intern/system.c
+++ b/source/blender/blenlib/intern/system.c
@@ -50,8 +50,8 @@ int BLI_cpu_support_sse2(void)
"pushl %%ebx\n\t"
"cpuid\n\t"
"popl %%ebx\n\t"
- : "=d" (d)
- : "a" (1));
+ : "=d" (d)
+ : "a" (1));
return (d & 0x04000000) != 0;
#elif (defined(_MSC_VER) && defined(_M_IX86))
/* also check cpuid for MSVC x86 */
diff --git a/source/blender/blenlib/intern/task.c b/source/blender/blenlib/intern/task.c
index fc2d9674c2f..5d3c6b35ac1 100644
--- a/source/blender/blenlib/intern/task.c
+++ b/source/blender/blenlib/intern/task.c
@@ -32,6 +32,7 @@
#include "BLI_listbase.h"
#include "BLI_math.h"
+#include "BLI_mempool.h"
#include "BLI_task.h"
#include "BLI_threads.h"
@@ -48,6 +49,39 @@
*/
#define MEMPOOL_SIZE 256
+/* Number of tasks which are pushed directly to local thread queue.
+ *
+ * This allows thread to fetch next task without locking the whole queue.
+ */
+#define LOCAL_QUEUE_SIZE 1
+
+/* Number of tasks which are allowed to be scheduled in a delayed manner.
+ *
+ * This allows to use less locks per graph node children schedule. More details
+ * could be found at TaskThreadLocalStorage::do_delayed_push.
+ */
+#define DELAYED_QUEUE_SIZE 4096
+
+#ifndef NDEBUG
+# define ASSERT_THREAD_ID(scheduler, thread_id) \
+ do { \
+ if (!BLI_thread_is_main()) { \
+ TaskThread *thread = pthread_getspecific(scheduler->tls_id_key); \
+ if (thread == NULL) { \
+ BLI_assert(thread_id == 0); \
+ } \
+ else { \
+ BLI_assert(thread_id == thread->id); \
+ } \
+ } \
+ else { \
+ BLI_assert(thread_id == 0); \
+ } \
+ } while (false)
+#else
+# define ASSERT_THREAD_ID(scheduler, thread_id)
+#endif
+
typedef struct Task {
struct Task *next, *prev;
@@ -102,13 +136,35 @@ typedef struct TaskMemPoolStats {
} TaskMemPoolStats;
#endif
+typedef struct TaskThreadLocalStorage {
+ /* Memory pool for faster task allocation.
+ * The idea is to re-use memory of finished/discarded tasks by this thread.
+ */
+ TaskMemPool task_mempool;
+
+ /* Local queue keeps thread alive by keeping small amount of tasks ready
+ * to be picked up without causing global thread locks for synchronization.
+ */
+ int num_local_queue;
+ Task *local_queue[LOCAL_QUEUE_SIZE];
+
+ /* Thread can be marked for delayed tasks push. This is helpful when it's
+ * know that lots of subsequent task pushed will happen from the same thread
+ * without "interrupting" for task execution.
+ *
+ * We try to accumulate as much tasks as possible in a local queue without
+ * any locks first, and then we push all of them into a scheduler's queue
+ * from within a single mutex lock.
+ */
+ bool do_delayed_push;
+ int num_delayed_queue;
+ Task *delayed_queue[DELAYED_QUEUE_SIZE];
+} TaskThreadLocalStorage;
+
struct TaskPool {
TaskScheduler *scheduler;
volatile size_t num;
- volatile size_t done;
- size_t num_threads;
- size_t currently_running_tasks;
ThreadMutex num_mutex;
ThreadCondition num_cond;
@@ -116,6 +172,11 @@ struct TaskPool {
ThreadMutex user_mutex;
volatile bool do_cancel;
+ volatile bool do_work;
+
+ volatile bool is_suspended;
+ ListBase suspended_queue;
+ size_t num_suspended;
/* If set, this pool may never be work_and_wait'ed, which means TaskScheduler
* has to use its special background fallback thread in case we are in
@@ -123,16 +184,20 @@ struct TaskPool {
*/
bool run_in_background;
- /* This pool is used for caching task pointers for thread id 0.
- * This could either point to a global scheduler's task_mempool[0] if the
- * pool is handled form the main thread or point to task_mempool_local
- * otherwise.
- *
- * This way we solve possible threading conflicts accessing same global
- * memory pool from multiple threads from which wait_work() is called.
+ /* This is a task scheduler's ID of a thread at which pool was constructed.
+ * It will be used to access task TLS.
+ */
+ int thread_id;
+
+ /* For the pools which are created from non-main thread which is not a
+ * scheduler worker thread we can't re-use any of scheduler's threads TLS
+ * and have to use our own one.
*/
- TaskMemPool *task_mempool;
- TaskMemPool task_mempool_local;
+ bool use_local_tls;
+ TaskThreadLocalStorage local_tls;
+#ifndef NDEBUG
+ pthread_t creator_thread_id;
+#endif
#ifdef DEBUG_STATS
TaskMemPoolStats *mempool_stats;
@@ -142,7 +207,6 @@ struct TaskPool {
struct TaskScheduler {
pthread_t *threads;
struct TaskThread *task_threads;
- TaskMemPool *task_mempool;
int num_threads;
bool background_thread_only;
@@ -151,15 +215,19 @@ struct TaskScheduler {
ThreadCondition queue_cond;
volatile bool do_exit;
+
+ /* NOTE: In pthread's TLS we store the whole TaskThread structure. */
+ pthread_key_t tls_id_key;
};
typedef struct TaskThread {
TaskScheduler *scheduler;
int id;
+ TaskThreadLocalStorage tls;
} TaskThread;
/* Helper */
-static void task_data_free(Task *task, const int thread_id)
+BLI_INLINE void task_data_free(Task *task, const int thread_id)
{
if (task->free_taskdata) {
if (task->freedata) {
@@ -171,28 +239,54 @@ static void task_data_free(Task *task, const int thread_id)
}
}
-BLI_INLINE TaskMemPool *get_task_mempool(TaskPool *pool, const int thread_id)
+BLI_INLINE void initialize_task_tls(TaskThreadLocalStorage *tls)
+{
+ memset(tls, 0, sizeof(TaskThreadLocalStorage));
+}
+
+BLI_INLINE TaskThreadLocalStorage *get_task_tls(TaskPool *pool,
+ const int thread_id)
{
+ TaskScheduler *scheduler = pool->scheduler;
+ BLI_assert(thread_id >= 0);
+ BLI_assert(thread_id <= scheduler->num_threads);
+ if (pool->use_local_tls && thread_id == 0) {
+ BLI_assert(pool->thread_id == 0);
+ BLI_assert(!BLI_thread_is_main());
+ BLI_assert(pthread_equal(pthread_self(), pool->creator_thread_id));
+ return &pool->local_tls;
+ }
if (thread_id == 0) {
- return pool->task_mempool;
+ BLI_assert(BLI_thread_is_main());
+ return &scheduler->task_threads[pool->thread_id].tls;
+ }
+ return &scheduler->task_threads[thread_id].tls;
+}
+
+BLI_INLINE void free_task_tls(TaskThreadLocalStorage *tls)
+{
+ TaskMemPool *task_mempool = &tls->task_mempool;
+ for (int i = 0; i < task_mempool->num_tasks; ++i) {
+ MEM_freeN(task_mempool->tasks[i]);
}
- return &pool->scheduler->task_mempool[thread_id];
}
static Task *task_alloc(TaskPool *pool, const int thread_id)
{
- assert(thread_id <= pool->scheduler->num_threads);
+ BLI_assert(thread_id <= pool->scheduler->num_threads);
if (thread_id != -1) {
- assert(thread_id >= 0);
- TaskMemPool *mem_pool = get_task_mempool(pool, thread_id);
+ BLI_assert(thread_id >= 0);
+ BLI_assert(thread_id <= pool->scheduler->num_threads);
+ TaskThreadLocalStorage *tls = get_task_tls(pool, thread_id);
+ TaskMemPool *task_mempool = &tls->task_mempool;
/* Try to re-use task memory from a thread local storage. */
- if (mem_pool->num_tasks > 0) {
- --mem_pool->num_tasks;
+ if (task_mempool->num_tasks > 0) {
+ --task_mempool->num_tasks;
/* Success! We've just avoided task allocation. */
#ifdef DEBUG_STATS
pool->mempool_stats[thread_id].num_reuse++;
#endif
- return mem_pool->tasks[mem_pool->num_tasks];
+ return task_mempool->tasks[task_mempool->num_tasks];
}
/* We are doomed to allocate new task data. */
#ifdef DEBUG_STATS
@@ -205,13 +299,17 @@ static Task *task_alloc(TaskPool *pool, const int thread_id)
static void task_free(TaskPool *pool, Task *task, const int thread_id)
{
task_data_free(task, thread_id);
- assert(thread_id >= 0);
- assert(thread_id <= pool->scheduler->num_threads);
- TaskMemPool *mem_pool = get_task_mempool(pool, thread_id);
- if (mem_pool->num_tasks < MEMPOOL_SIZE - 1) {
+ BLI_assert(thread_id >= 0);
+ BLI_assert(thread_id <= pool->scheduler->num_threads);
+ if (thread_id == 0) {
+ BLI_assert(pool->use_local_tls || BLI_thread_is_main());
+ }
+ TaskThreadLocalStorage *tls = get_task_tls(pool, thread_id);
+ TaskMemPool *task_mempool = &tls->task_mempool;
+ if (task_mempool->num_tasks < MEMPOOL_SIZE - 1) {
/* Successfully allowed the task to be re-used later. */
- mem_pool->tasks[mem_pool->num_tasks] = task;
- ++mem_pool->num_tasks;
+ task_mempool->tasks[task_mempool->num_tasks] = task;
+ ++task_mempool->num_tasks;
}
else {
/* Local storage saturated, no other way than just discard
@@ -237,8 +335,6 @@ static void task_pool_num_decrease(TaskPool *pool, size_t done)
BLI_assert(pool->num >= done);
pool->num -= done;
- atomic_sub_and_fetch_z(&pool->currently_running_tasks, done);
- pool->done += done;
if (pool->num == 0)
BLI_condition_notify_all(&pool->num_cond);
@@ -246,11 +342,11 @@ static void task_pool_num_decrease(TaskPool *pool, size_t done)
BLI_mutex_unlock(&pool->num_mutex);
}
-static void task_pool_num_increase(TaskPool *pool)
+static void task_pool_num_increase(TaskPool *pool, size_t new)
{
BLI_mutex_lock(&pool->num_mutex);
- pool->num++;
+ pool->num += new;
BLI_condition_notify_all(&pool->num_cond);
BLI_mutex_unlock(&pool->num_mutex);
@@ -292,17 +388,10 @@ static bool task_scheduler_thread_wait_pop(TaskScheduler *scheduler, Task **task
continue;
}
- if (atomic_add_and_fetch_z(&pool->currently_running_tasks, 1) <= pool->num_threads ||
- pool->num_threads == 0)
- {
- *task = current_task;
- found_task = true;
- BLI_remlink(&scheduler->queue, *task);
- break;
- }
- else {
- atomic_sub_and_fetch_z(&pool->currently_running_tasks, 1);
- }
+ *task = current_task;
+ found_task = true;
+ BLI_remlink(&scheduler->queue, *task);
+ break;
}
if (!found_task)
BLI_condition_wait(&scheduler->queue_cond, &scheduler->queue_mutex);
@@ -313,23 +402,51 @@ static bool task_scheduler_thread_wait_pop(TaskScheduler *scheduler, Task **task
return true;
}
+BLI_INLINE void handle_local_queue(TaskThreadLocalStorage *tls,
+ const int thread_id)
+{
+ BLI_assert(!tls->do_delayed_push);
+ while (tls->num_local_queue > 0) {
+ /* We pop task from queue before handling it so handler of the task can
+ * push next job to the local queue.
+ */
+ tls->num_local_queue--;
+ Task *local_task = tls->local_queue[tls->num_local_queue];
+ /* TODO(sergey): Double-check work_and_wait() doesn't handle other's
+ * pool tasks.
+ */
+ TaskPool *local_pool = local_task->pool;
+ local_task->run(local_pool, local_task->taskdata, thread_id);
+ task_free(local_pool, local_task, thread_id);
+ }
+ BLI_assert(!tls->do_delayed_push);
+}
+
static void *task_scheduler_thread_run(void *thread_p)
{
TaskThread *thread = (TaskThread *) thread_p;
+ TaskThreadLocalStorage *tls = &thread->tls;
TaskScheduler *scheduler = thread->scheduler;
int thread_id = thread->id;
Task *task;
+ pthread_setspecific(scheduler->tls_id_key, thread);
+
/* keep popping off tasks */
while (task_scheduler_thread_wait_pop(scheduler, &task)) {
TaskPool *pool = task->pool;
/* run task */
+ BLI_assert(!tls->do_delayed_push);
task->run(pool, task->taskdata, thread_id);
+ BLI_assert(!tls->do_delayed_push);
/* delete task */
task_free(pool, task, thread_id);
+ /* Handle all tasks from local queue. */
+ handle_local_queue(tls, thread_id);
+
/* notify pool task was done */
task_pool_num_decrease(pool, 1);
}
@@ -359,30 +476,35 @@ TaskScheduler *BLI_task_scheduler_create(int num_threads)
/* Add background-only thread if needed. */
if (num_threads == 0) {
- scheduler->background_thread_only = true;
- num_threads = 1;
+ scheduler->background_thread_only = true;
+ num_threads = 1;
}
+ scheduler->task_threads = MEM_mallocN(sizeof(TaskThread) * (num_threads + 1),
+ "TaskScheduler task threads");
+
+ /* Initialize TLS for main thread. */
+ initialize_task_tls(&scheduler->task_threads[0].tls);
+
+ pthread_key_create(&scheduler->tls_id_key, NULL);
+
/* launch threads that will be waiting for work */
if (num_threads > 0) {
int i;
scheduler->num_threads = num_threads;
scheduler->threads = MEM_callocN(sizeof(pthread_t) * num_threads, "TaskScheduler threads");
- scheduler->task_threads = MEM_callocN(sizeof(TaskThread) * num_threads, "TaskScheduler task threads");
for (i = 0; i < num_threads; i++) {
- TaskThread *thread = &scheduler->task_threads[i];
+ TaskThread *thread = &scheduler->task_threads[i + 1];
thread->scheduler = scheduler;
thread->id = i + 1;
+ initialize_task_tls(&thread->tls);
if (pthread_create(&scheduler->threads[i], NULL, task_scheduler_thread_run, thread) != 0) {
fprintf(stderr, "TaskScheduler failed to launch thread %d/%d\n", i, num_threads);
}
}
-
- scheduler->task_mempool = MEM_callocN(sizeof(*scheduler->task_mempool) * (num_threads + 1),
- "TaskScheduler task_mempool");
}
return scheduler;
@@ -398,6 +520,8 @@ void BLI_task_scheduler_free(TaskScheduler *scheduler)
BLI_condition_notify_all(&scheduler->queue_cond);
BLI_mutex_unlock(&scheduler->queue_mutex);
+ pthread_key_delete(scheduler->tls_id_key);
+
/* delete threads */
if (scheduler->threads) {
int i;
@@ -412,17 +536,12 @@ void BLI_task_scheduler_free(TaskScheduler *scheduler)
/* Delete task thread data */
if (scheduler->task_threads) {
- MEM_freeN(scheduler->task_threads);
- }
-
- /* Delete task memory pool */
- if (scheduler->task_mempool) {
- for (int i = 0; i <= scheduler->num_threads; ++i) {
- for (int j = 0; j < scheduler->task_mempool[i].num_tasks; ++j) {
- MEM_freeN(scheduler->task_mempool[i].tasks[j]);
- }
+ for (int i = 0; i < scheduler->num_threads + 1; ++i) {
+ TaskThreadLocalStorage *tls = &scheduler->task_threads[i].tls;
+ free_task_tls(tls);
}
- MEM_freeN(scheduler->task_mempool);
+
+ MEM_freeN(scheduler->task_threads);
}
/* delete leftover tasks */
@@ -445,7 +564,7 @@ int BLI_task_scheduler_num_threads(TaskScheduler *scheduler)
static void task_scheduler_push(TaskScheduler *scheduler, Task *task, TaskPriority priority)
{
- task_pool_num_increase(task->pool);
+ task_pool_num_increase(task->pool, 1);
/* add task to queue */
BLI_mutex_lock(&scheduler->queue_mutex);
@@ -459,6 +578,27 @@ static void task_scheduler_push(TaskScheduler *scheduler, Task *task, TaskPriori
BLI_mutex_unlock(&scheduler->queue_mutex);
}
+static void task_scheduler_push_all(TaskScheduler *scheduler,
+ TaskPool *pool,
+ Task **tasks,
+ int num_tasks)
+{
+ if (num_tasks == 0) {
+ return;
+ }
+
+ task_pool_num_increase(pool, num_tasks);
+
+ BLI_mutex_lock(&scheduler->queue_mutex);
+
+ for (int i = 0; i < num_tasks; i++) {
+ BLI_addhead(&scheduler->queue, tasks[i]);
+ }
+
+ BLI_condition_notify_all(&scheduler->queue_cond);
+ BLI_mutex_unlock(&scheduler->queue_mutex);
+}
+
static void task_scheduler_clear(TaskScheduler *scheduler, TaskPool *pool)
{
Task *task, *nexttask;
@@ -471,7 +611,7 @@ static void task_scheduler_clear(TaskScheduler *scheduler, TaskPool *pool)
nexttask = task->next;
if (task->pool == pool) {
- task_data_free(task, 0);
+ task_data_free(task, pool->thread_id);
BLI_freelinkN(&scheduler->queue, task);
done++;
@@ -486,7 +626,10 @@ static void task_scheduler_clear(TaskScheduler *scheduler, TaskPool *pool)
/* Task Pool */
-static TaskPool *task_pool_create_ex(TaskScheduler *scheduler, void *userdata, const bool is_background)
+static TaskPool *task_pool_create_ex(TaskScheduler *scheduler,
+ void *userdata,
+ const bool is_background,
+ const bool is_suspended)
{
TaskPool *pool = MEM_mallocN(sizeof(TaskPool), "TaskPool");
@@ -504,11 +647,13 @@ static TaskPool *task_pool_create_ex(TaskScheduler *scheduler, void *userdata, c
pool->scheduler = scheduler;
pool->num = 0;
- pool->done = 0;
- pool->num_threads = 0;
- pool->currently_running_tasks = 0;
pool->do_cancel = false;
+ pool->do_work = false;
+ pool->is_suspended = is_suspended;
+ pool->num_suspended = 0;
+ pool->suspended_queue.first = pool->suspended_queue.last = NULL;
pool->run_in_background = is_background;
+ pool->use_local_tls = false;
BLI_mutex_init(&pool->num_mutex);
BLI_condition_init(&pool->num_cond);
@@ -517,11 +662,26 @@ static TaskPool *task_pool_create_ex(TaskScheduler *scheduler, void *userdata, c
BLI_mutex_init(&pool->user_mutex);
if (BLI_thread_is_main()) {
- pool->task_mempool = scheduler->task_mempool;
+ pool->thread_id = 0;
}
else {
- pool->task_mempool = &pool->task_mempool_local;
- pool->task_mempool_local.num_tasks = 0;
+ TaskThread *thread = pthread_getspecific(scheduler->tls_id_key);
+ if (thread == NULL) {
+ /* NOTE: Task pool is created from non-main thread which is not
+ * managed by the task scheduler. We identify ourselves as thread ID
+ * 0 but we do not use scheduler's TLS storage and use our own
+ * instead to avoid any possible threading conflicts.
+ */
+ pool->thread_id = 0;
+ pool->use_local_tls = true;
+#ifndef NDEBUG
+ pool->creator_thread_id = pthread_self();
+#endif
+ initialize_task_tls(&pool->local_tls);
+ }
+ else {
+ pool->thread_id = thread->id;
+ }
}
#ifdef DEBUG_STATS
@@ -533,10 +693,10 @@ static TaskPool *task_pool_create_ex(TaskScheduler *scheduler, void *userdata, c
/* Ensure malloc will go fine from threads,
*
* This is needed because we could be in main thread here
- * and malloc could be non-threda safe at this point because
+ * and malloc could be non-thread safe at this point because
* no other jobs are running.
*/
- BLI_begin_threaded_malloc();
+ BLI_threaded_malloc_begin();
return pool;
}
@@ -548,7 +708,7 @@ static TaskPool *task_pool_create_ex(TaskScheduler *scheduler, void *userdata, c
*/
TaskPool *BLI_task_pool_create(TaskScheduler *scheduler, void *userdata)
{
- return task_pool_create_ex(scheduler, userdata, false);
+ return task_pool_create_ex(scheduler, userdata, false, false);
}
/**
@@ -563,25 +723,28 @@ TaskPool *BLI_task_pool_create(TaskScheduler *scheduler, void *userdata)
*/
TaskPool *BLI_task_pool_create_background(TaskScheduler *scheduler, void *userdata)
{
- return task_pool_create_ex(scheduler, userdata, true);
+ return task_pool_create_ex(scheduler, userdata, true, false);
+}
+
+/**
+ * Similar to BLI_task_pool_create() but does not schedule any tasks for execution
+ * for until BLI_task_pool_work_and_wait() is called. This helps reducing therading
+ * overhead when pushing huge amount of small initial tasks from the main thread.
+ */
+TaskPool *BLI_task_pool_create_suspended(TaskScheduler *scheduler, void *userdata)
+{
+ return task_pool_create_ex(scheduler, userdata, false, true);
}
void BLI_task_pool_free(TaskPool *pool)
{
- BLI_task_pool_stop(pool);
+ BLI_task_pool_cancel(pool);
BLI_mutex_end(&pool->num_mutex);
BLI_condition_end(&pool->num_cond);
BLI_mutex_end(&pool->user_mutex);
- /* Free local memory pool, those pointers are lost forever. */
- if (pool->task_mempool == &pool->task_mempool_local) {
- for (int i = 0; i < pool->task_mempool_local.num_tasks; i++) {
- MEM_freeN(pool->task_mempool_local.tasks[i]);
- }
- }
-
#ifdef DEBUG_STATS
printf("Thread ID Allocated Reused Discarded\n");
for (int i = 0; i < pool->scheduler->num_threads + 1; ++i) {
@@ -594,9 +757,18 @@ void BLI_task_pool_free(TaskPool *pool)
MEM_freeN(pool->mempool_stats);
#endif
+ if (pool->use_local_tls) {
+ free_task_tls(&pool->local_tls);
+ }
+
MEM_freeN(pool);
- BLI_end_threaded_malloc();
+ BLI_threaded_malloc_end();
+}
+
+BLI_INLINE bool task_can_use_local_queues(TaskPool *pool, int thread_id)
+{
+ return (thread_id != -1 && (thread_id != pool->thread_id || pool->do_work));
}
static void task_pool_push(
@@ -604,14 +776,49 @@ static void task_pool_push(
bool free_taskdata, TaskFreeFunction freedata, TaskPriority priority,
int thread_id)
{
+ /* Allocate task and fill it's properties. */
Task *task = task_alloc(pool, thread_id);
-
task->run = run;
task->taskdata = taskdata;
task->free_taskdata = free_taskdata;
task->freedata = freedata;
task->pool = pool;
-
+ /* For suspended pools we put everything yo a global queue first
+ * and exit as soon as possible.
+ *
+ * This tasks will be moved to actual execution when pool is
+ * activated by work_and_wait().
+ */
+ if (pool->is_suspended) {
+ BLI_addhead(&pool->suspended_queue, task);
+ atomic_fetch_and_add_z(&pool->num_suspended, 1);
+ return;
+ }
+ /* Populate to any local queue first, this is cheapest push ever. */
+ if (task_can_use_local_queues(pool, thread_id)) {
+ ASSERT_THREAD_ID(pool->scheduler, thread_id);
+ TaskThreadLocalStorage *tls = get_task_tls(pool, thread_id);
+ /* Try to push to a local execution queue.
+ * These tasks will be picked up next.
+ */
+ if (tls->num_local_queue < LOCAL_QUEUE_SIZE) {
+ tls->local_queue[tls->num_local_queue] = task;
+ tls->num_local_queue++;
+ return;
+ }
+ /* If we are in the delayed tasks push mode, we push tasks to a
+ * temporary local queue first without any locks, and then move them
+ * to global execution queue with a single lock.
+ */
+ if (tls->do_delayed_push && tls->num_delayed_queue < DELAYED_QUEUE_SIZE) {
+ tls->delayed_queue[tls->num_delayed_queue] = task;
+ tls->num_delayed_queue++;
+ return;
+ }
+ }
+ /* Do push to a global execution ppol, slowest possible method,
+ * causes quite reasonable amount of threading overhead.
+ */
task_scheduler_push(pool->scheduler, task, priority);
}
@@ -636,8 +843,25 @@ void BLI_task_pool_push_from_thread(TaskPool *pool, TaskRunFunction run,
void BLI_task_pool_work_and_wait(TaskPool *pool)
{
+ TaskThreadLocalStorage *tls = get_task_tls(pool, pool->thread_id);
TaskScheduler *scheduler = pool->scheduler;
+ if (atomic_fetch_and_and_uint8((uint8_t *)&pool->is_suspended, 0)) {
+ if (pool->num_suspended) {
+ task_pool_num_increase(pool, pool->num_suspended);
+ BLI_mutex_lock(&scheduler->queue_mutex);
+
+ BLI_movelisttolist(&scheduler->queue, &pool->suspended_queue);
+
+ BLI_condition_notify_all(&scheduler->queue_cond);
+ BLI_mutex_unlock(&scheduler->queue_mutex);
+ }
+ }
+
+ pool->do_work = true;
+
+ ASSERT_THREAD_ID(pool->scheduler, pool->thread_id);
+
BLI_mutex_lock(&pool->num_mutex);
while (pool->num != 0) {
@@ -651,16 +875,12 @@ void BLI_task_pool_work_and_wait(TaskPool *pool)
/* find task from this pool. if we get a task from another pool,
* we can get into deadlock */
- if (pool->num_threads == 0 ||
- pool->currently_running_tasks < pool->num_threads)
- {
- for (task = scheduler->queue.first; task; task = task->next) {
- if (task->pool == pool) {
- work_task = task;
- found_task = true;
- BLI_remlink(&scheduler->queue, task);
- break;
- }
+ for (task = scheduler->queue.first; task; task = task->next) {
+ if (task->pool == pool) {
+ work_task = task;
+ found_task = true;
+ BLI_remlink(&scheduler->queue, task);
+ break;
}
}
@@ -669,11 +889,15 @@ void BLI_task_pool_work_and_wait(TaskPool *pool)
/* if found task, do it, otherwise wait until other tasks are done */
if (found_task) {
/* run task */
- atomic_add_and_fetch_z(&pool->currently_running_tasks, 1);
- work_task->run(pool, work_task->taskdata, 0);
+ BLI_assert(!tls->do_delayed_push);
+ work_task->run(pool, work_task->taskdata, pool->thread_id);
+ BLI_assert(!tls->do_delayed_push);
/* delete task */
- task_free(pool, task, 0);
+ task_free(pool, task, pool->thread_id);
+
+ /* Handle all tasks from local queue. */
+ handle_local_queue(tls, pool->thread_id);
/* notify pool task was done */
task_pool_num_decrease(pool, 1);
@@ -688,22 +912,8 @@ void BLI_task_pool_work_and_wait(TaskPool *pool)
}
BLI_mutex_unlock(&pool->num_mutex);
-}
-int BLI_pool_get_num_threads(TaskPool *pool)
-{
- if (pool->num_threads != 0) {
- return pool->num_threads;
- }
- else {
- return BLI_task_scheduler_num_threads(pool->scheduler);
- }
-}
-
-void BLI_pool_set_num_threads(TaskPool *pool, int num_threads)
-{
- /* NOTE: Don't try to modify threads while tasks are running! */
- pool->num_threads = num_threads;
+ handle_local_queue(tls, pool->thread_id);
}
void BLI_task_pool_cancel(TaskPool *pool)
@@ -721,13 +931,6 @@ void BLI_task_pool_cancel(TaskPool *pool)
pool->do_cancel = false;
}
-void BLI_task_pool_stop(TaskPool *pool)
-{
- task_scheduler_clear(pool->scheduler, pool);
-
- BLI_assert(pool->num == 0);
-}
-
bool BLI_task_pool_canceled(TaskPool *pool)
{
return pool->do_cancel;
@@ -743,9 +946,28 @@ ThreadMutex *BLI_task_pool_user_mutex(TaskPool *pool)
return &pool->user_mutex;
}
-size_t BLI_task_pool_tasks_done(TaskPool *pool)
+void BLI_task_pool_delayed_push_begin(TaskPool *pool, int thread_id)
{
- return pool->done;
+ if (task_can_use_local_queues(pool, thread_id)) {
+ ASSERT_THREAD_ID(pool->scheduler, thread_id);
+ TaskThreadLocalStorage *tls = get_task_tls(pool, thread_id);
+ tls->do_delayed_push = true;
+ }
+}
+
+void BLI_task_pool_delayed_push_end(TaskPool *pool, int thread_id)
+{
+ if (task_can_use_local_queues(pool, thread_id)) {
+ ASSERT_THREAD_ID(pool->scheduler, thread_id);
+ TaskThreadLocalStorage *tls = get_task_tls(pool, thread_id);
+ BLI_assert(tls->do_delayed_push);
+ task_scheduler_push_all(pool->scheduler,
+ pool,
+ tls->delayed_queue,
+ tls->num_delayed_queue);
+ tls->do_delayed_push = false;
+ tls->num_delayed_queue = 0;
+ }
}
/* Parallel range routines */
@@ -772,7 +994,6 @@ typedef struct ParallelRangeState {
void *userdata;
TaskParallelRangeFunc func;
- TaskParallelRangeFuncEx func_ex;
int iter;
int chunk_size;
@@ -782,8 +1003,7 @@ BLI_INLINE bool parallel_range_next_iter_get(
ParallelRangeState * __restrict state,
int * __restrict iter, int * __restrict count)
{
- uint32_t uval = atomic_fetch_and_add_uint32((uint32_t *)(&state->iter), state->chunk_size);
- int previter = *(int32_t*)&uval;
+ int previter = atomic_fetch_and_add_int32(&state->iter, state->chunk_size);
*iter = previter;
*count = max_ii(0, min_ii(state->chunk_size, state->stop - previter));
@@ -794,51 +1014,67 @@ BLI_INLINE bool parallel_range_next_iter_get(
static void parallel_range_func(
TaskPool * __restrict pool,
void *userdata_chunk,
- int threadid)
+ int thread_id)
{
ParallelRangeState * __restrict state = BLI_task_pool_userdata(pool);
+ ParallelRangeTLS tls = {
+ .thread_id = thread_id,
+ .userdata_chunk = userdata_chunk,
+ };
int iter, count;
-
while (parallel_range_next_iter_get(state, &iter, &count)) {
- int i;
-
- if (state->func_ex) {
- for (i = 0; i < count; ++i) {
- state->func_ex(state->userdata, userdata_chunk, iter + i, threadid);
- }
- }
- else {
- for (i = 0; i < count; ++i) {
- state->func(state->userdata, iter + i);
- }
+ for (int i = 0; i < count; ++i) {
+ state->func(state->userdata, iter + i, &tls);
}
}
}
+static void palallel_range_single_thread(const int start, int const stop,
+ void *userdata,
+ TaskParallelRangeFunc func,
+ const ParallelRangeSettings *settings)
+{
+ void *userdata_chunk = settings->userdata_chunk;
+ const size_t userdata_chunk_size = settings->userdata_chunk_size;
+ void *userdata_chunk_local = NULL;
+ const bool use_userdata_chunk = (userdata_chunk_size != 0) && (userdata_chunk != NULL);
+ if (use_userdata_chunk) {
+ userdata_chunk_local = MALLOCA(userdata_chunk_size);
+ memcpy(userdata_chunk_local, userdata_chunk, userdata_chunk_size);
+ }
+ ParallelRangeTLS tls = {
+ .thread_id = 0,
+ .userdata_chunk = userdata_chunk_local,
+ };
+ for (int i = start; i < stop; ++i) {
+ func(userdata, i, &tls);
+ }
+ if (settings->func_finalize != NULL) {
+ settings->func_finalize(userdata, userdata_chunk_local);
+ }
+ MALLOCA_FREE(userdata_chunk_local, userdata_chunk_size);
+}
+
/**
* This function allows to parallelized for loops in a similar way to OpenMP's 'parallel for' statement.
*
- * See public API doc for description of parameters.
+ * See public API doc of ParallelRangeSettings for description of all settings.
*/
-static void task_parallel_range_ex(
- int start, int stop,
- void *userdata,
- void *userdata_chunk,
- const size_t userdata_chunk_size,
- TaskParallelRangeFunc func,
- TaskParallelRangeFuncEx func_ex,
- TaskParallelRangeFuncFinalize func_finalize,
- const bool use_threading,
- const bool use_dynamic_scheduling)
+void BLI_task_parallel_range(const int start, const int stop,
+ void *userdata,
+ TaskParallelRangeFunc func,
+ const ParallelRangeSettings *settings)
{
TaskScheduler *task_scheduler;
TaskPool *task_pool;
ParallelRangeState state;
int i, num_threads, num_tasks;
+ void *userdata_chunk = settings->userdata_chunk;
+ const size_t userdata_chunk_size = settings->userdata_chunk_size;
void *userdata_chunk_local = NULL;
void *userdata_chunk_array = NULL;
- const bool use_userdata_chunk = (func_ex != NULL) && (userdata_chunk_size != 0) && (userdata_chunk != NULL);
+ const bool use_userdata_chunk = (userdata_chunk_size != 0) && (userdata_chunk != NULL);
if (start == stop) {
return;
@@ -846,67 +1082,65 @@ static void task_parallel_range_ex(
BLI_assert(start < stop);
if (userdata_chunk_size != 0) {
- BLI_assert(func_ex != NULL && func == NULL);
BLI_assert(userdata_chunk != NULL);
}
/* If it's not enough data to be crunched, don't bother with tasks at all,
* do everything from the main thread.
*/
- if (!use_threading) {
- if (func_ex) {
- if (use_userdata_chunk) {
- userdata_chunk_local = MALLOCA(userdata_chunk_size);
- memcpy(userdata_chunk_local, userdata_chunk, userdata_chunk_size);
- }
-
- for (i = start; i < stop; ++i) {
- func_ex(userdata, userdata_chunk_local, i, 0);
- }
-
- if (func_finalize) {
- func_finalize(userdata, userdata_chunk_local);
- }
-
- MALLOCA_FREE(userdata_chunk_local, userdata_chunk_size);
- }
- else {
- for (i = start; i < stop; ++i) {
- func(userdata, i);
- }
- }
-
+ if (!settings->use_threading) {
+ palallel_range_single_thread(start, stop,
+ userdata,
+ func,
+ settings);
return;
}
task_scheduler = BLI_task_scheduler_get();
- task_pool = BLI_task_pool_create(task_scheduler, &state);
num_threads = BLI_task_scheduler_num_threads(task_scheduler);
/* The idea here is to prevent creating task for each of the loop iterations
* and instead have tasks which are evenly distributed across CPU cores and
* pull next iter to be crunched using the queue.
*/
- num_tasks = num_threads * 2;
+ num_tasks = num_threads + 2;
state.start = start;
state.stop = stop;
state.userdata = userdata;
state.func = func;
- state.func_ex = func_ex;
state.iter = start;
- if (use_dynamic_scheduling) {
- state.chunk_size = 32;
+ switch (settings->scheduling_mode) {
+ case TASK_SCHEDULING_STATIC:
+ state.chunk_size = max_ii(
+ settings->min_iter_per_thread,
+ (stop - start) / (num_tasks));
+ break;
+ case TASK_SCHEDULING_DYNAMIC:
+ /* TODO(sergey): Make it configurable from min_iter_per_thread. */
+ state.chunk_size = 32;
+ break;
}
- else {
- state.chunk_size = max_ii(1, (stop - start) / (num_tasks));
+
+ num_tasks = min_ii(num_tasks,
+ max_ii(1, (stop - start) / state.chunk_size));
+
+ if (num_tasks == 1) {
+ palallel_range_single_thread(start, stop,
+ userdata,
+ func,
+ settings);
+ return;
}
- num_tasks = min_ii(num_tasks, (stop - start) / state.chunk_size);
- atomic_fetch_and_add_uint32((uint32_t *)(&state.iter), 0);
+ task_pool = BLI_task_pool_create_suspended(task_scheduler, &state);
+
+ /* NOTE: This way we are adding a memory barrier and ensure all worker
+ * threads can read and modify the value, without any locks. */
+ atomic_fetch_and_add_int32(&state.iter, 0);
if (use_userdata_chunk) {
- userdata_chunk_array = MALLOCA(userdata_chunk_size * num_tasks);
+ userdata_chunk_array = MALLOCA(userdata_chunk_size * num_tasks);
}
for (i = 0; i < num_tasks; i++) {
@@ -918,105 +1152,24 @@ static void task_parallel_range_ex(
BLI_task_pool_push_from_thread(task_pool,
parallel_range_func,
userdata_chunk_local, false,
- TASK_PRIORITY_HIGH, 0);
+ TASK_PRIORITY_HIGH,
+ task_pool->thread_id);
}
BLI_task_pool_work_and_wait(task_pool);
BLI_task_pool_free(task_pool);
if (use_userdata_chunk) {
- if (func_finalize) {
+ if (settings->func_finalize != NULL) {
for (i = 0; i < num_tasks; i++) {
userdata_chunk_local = (char *)userdata_chunk_array + (userdata_chunk_size * i);
- func_finalize(userdata, userdata_chunk_local);
+ settings->func_finalize(userdata, userdata_chunk_local);
}
}
MALLOCA_FREE(userdata_chunk_array, userdata_chunk_size * num_tasks);
}
}
-/**
- * This function allows to parallelize for loops in a similar way to OpenMP's 'parallel for' statement.
- *
- * \param start First index to process.
- * \param stop Index to stop looping (excluded).
- * \param userdata Common userdata passed to all instances of \a func.
- * \param userdata_chunk Optional, each instance of looping chunks will get a copy of this data
- * (similar to OpenMP's firstprivate).
- * \param userdata_chunk_size Memory size of \a userdata_chunk.
- * \param func_ex Callback function (advanced version).
- * \param use_threading If \a true, actually split-execute loop in threads, else just do a sequential forloop
- * (allows caller to use any kind of test to switch on parallelization or not).
- * \param use_dynamic_scheduling If \a true, the whole range is divided in a lot of small chunks (of size 32 currently),
- * otherwise whole range is split in a few big chunks (num_threads * 2 chunks currently).
- */
-void BLI_task_parallel_range_ex(
- int start, int stop,
- void *userdata,
- void *userdata_chunk,
- const size_t userdata_chunk_size,
- TaskParallelRangeFuncEx func_ex,
- const bool use_threading,
- const bool use_dynamic_scheduling)
-{
- task_parallel_range_ex(
- start, stop, userdata, userdata_chunk, userdata_chunk_size, NULL, func_ex, NULL,
- use_threading, use_dynamic_scheduling);
-}
-
-/**
- * A simpler version of \a BLI_task_parallel_range_ex, which does not use \a use_dynamic_scheduling,
- * and does not handle 'firstprivate'-like \a userdata_chunk.
- *
- * \param start First index to process.
- * \param stop Index to stop looping (excluded).
- * \param userdata Common userdata passed to all instances of \a func.
- * \param func Callback function (simple version).
- * \param use_threading If \a true, actually split-execute loop in threads, else just do a sequential forloop
- * (allows caller to use any kind of test to switch on parallelization or not).
- */
-void BLI_task_parallel_range(
- int start, int stop,
- void *userdata,
- TaskParallelRangeFunc func,
- const bool use_threading)
-{
- task_parallel_range_ex(start, stop, userdata, NULL, 0, func, NULL, NULL, use_threading, false);
-}
-
-/**
- * This function allows to parallelize for loops in a similar way to OpenMP's 'parallel for' statement,
- * with an additional 'finalize' func called from calling thread once whole range have been processed.
- *
- * \param start First index to process.
- * \param stop Index to stop looping (excluded).
- * \param userdata Common userdata passed to all instances of \a func.
- * \param userdata_chunk Optional, each instance of looping chunks will get a copy of this data
- * (similar to OpenMP's firstprivate).
- * \param userdata_chunk_size Memory size of \a userdata_chunk.
- * \param func_ex Callback function (advanced version).
- * \param func_finalize Callback function, called after all workers have finished,
- * useful to finalize accumulative tasks.
- * \param use_threading If \a true, actually split-execute loop in threads, else just do a sequential forloop
- * (allows caller to use any kind of test to switch on parallelization or not).
- * \param use_dynamic_scheduling If \a true, the whole range is divided in a lot of small chunks (of size 32 currently),
- * otherwise whole range is split in a few big chunks (num_threads * 2 chunks currently).
- */
-void BLI_task_parallel_range_finalize(
- int start, int stop,
- void *userdata,
- void *userdata_chunk,
- const size_t userdata_chunk_size,
- TaskParallelRangeFuncEx func_ex,
- TaskParallelRangeFuncFinalize func_finalize,
- const bool use_threading,
- const bool use_dynamic_scheduling)
-{
- task_parallel_range_ex(
- start, stop, userdata, userdata_chunk, userdata_chunk_size, NULL, func_ex, func_finalize,
- use_threading, use_dynamic_scheduling);
-}
-
#undef MALLOCA
#undef MALLOCA_FREE
@@ -1103,14 +1256,14 @@ void BLI_task_parallel_listbase(
}
task_scheduler = BLI_task_scheduler_get();
- task_pool = BLI_task_pool_create(task_scheduler, &state);
+ task_pool = BLI_task_pool_create_suspended(task_scheduler, &state);
num_threads = BLI_task_scheduler_num_threads(task_scheduler);
/* The idea here is to prevent creating task for each of the loop iterations
* and instead have tasks which are evenly distributed across CPU cores and
* pull next iter to be crunched using the queue.
*/
- num_tasks = num_threads * 2;
+ num_tasks = num_threads + 2;
state.index = 0;
state.link = listbase->first;
@@ -1124,7 +1277,8 @@ void BLI_task_parallel_listbase(
BLI_task_pool_push_from_thread(task_pool,
parallel_listbase_func,
NULL, false,
- TASK_PRIORITY_HIGH, 0);
+ TASK_PRIORITY_HIGH,
+ task_pool->thread_id);
}
BLI_task_pool_work_and_wait(task_pool);
@@ -1132,3 +1286,89 @@ void BLI_task_parallel_listbase(
BLI_spin_end(&state.lock);
}
+
+
+typedef struct ParallelMempoolState {
+ void *userdata;
+ TaskParallelMempoolFunc func;
+} ParallelMempoolState;
+
+static void parallel_mempool_func(
+ TaskPool * __restrict pool,
+ void *taskdata,
+ int UNUSED(threadid))
+{
+ ParallelMempoolState * __restrict state = BLI_task_pool_userdata(pool);
+ BLI_mempool_iter *iter = taskdata;
+ MempoolIterData *item;
+
+ while ((item = BLI_mempool_iterstep(iter)) != NULL) {
+ state->func(state->userdata, item);
+ }
+}
+
+/**
+ * This function allows to parallelize for loops over Mempool items.
+ *
+ * \param mempool: The iterable BLI_mempool to loop over.
+ * \param userdata: Common userdata passed to all instances of \a func.
+ * \param func: Callback function.
+ * \param use_threading: If \a true, actually split-execute loop in threads, else just do a sequential for loop
+ * (allows caller to use any kind of test to switch on parallelization or not).
+ *
+ * \note There is no static scheduling here.
+ */
+void BLI_task_parallel_mempool(
+ BLI_mempool *mempool,
+ void *userdata,
+ TaskParallelMempoolFunc func,
+ const bool use_threading)
+{
+ TaskScheduler *task_scheduler;
+ TaskPool *task_pool;
+ ParallelMempoolState state;
+ int i, num_threads, num_tasks;
+
+ if (BLI_mempool_len(mempool) == 0) {
+ return;
+ }
+
+ if (!use_threading) {
+ BLI_mempool_iter iter;
+ BLI_mempool_iternew(mempool, &iter);
+
+ for (void *item = BLI_mempool_iterstep(&iter); item != NULL; item = BLI_mempool_iterstep(&iter)) {
+ func(userdata, item);
+ }
+ return;
+ }
+
+ task_scheduler = BLI_task_scheduler_get();
+ task_pool = BLI_task_pool_create_suspended(task_scheduler, &state);
+ num_threads = BLI_task_scheduler_num_threads(task_scheduler);
+
+ /* The idea here is to prevent creating task for each of the loop iterations
+ * and instead have tasks which are evenly distributed across CPU cores and
+ * pull next item to be crunched using the threaded-aware BLI_mempool_iter.
+ */
+ num_tasks = num_threads + 2;
+
+ state.userdata = userdata;
+ state.func = func;
+
+ BLI_mempool_iter *mempool_iterators = BLI_mempool_iter_threadsafe_create(mempool, (size_t)num_tasks);
+
+ for (i = 0; i < num_tasks; i++) {
+ /* Use this pool's pre-allocated tasks. */
+ BLI_task_pool_push_from_thread(task_pool,
+ parallel_mempool_func,
+ &mempool_iterators[i], false,
+ TASK_PRIORITY_HIGH,
+ task_pool->thread_id);
+ }
+
+ BLI_task_pool_work_and_wait(task_pool);
+ BLI_task_pool_free(task_pool);
+
+ BLI_mempool_iter_threadsafe_free(mempool_iterators);
+}
diff --git a/source/blender/blenlib/intern/threads.c b/source/blender/blenlib/intern/threads.c
index b60981802aa..761f3982e28 100644
--- a/source/blender/blenlib/intern/threads.c
+++ b/source/blender/blenlib/intern/threads.c
@@ -54,6 +54,8 @@
# include <sys/time.h>
#endif
+#include "atomic_ops.h"
+
#if defined(__APPLE__) && defined(_OPENMP) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 2) && !defined(__clang__)
# define USE_APPLE_OMP_FIX
#endif
@@ -81,13 +83,13 @@ static TaskScheduler *task_scheduler = NULL;
* int maxthreads = 2;
* int cont = 1;
*
- * BLI_init_threads(&lb, do_something_func, maxthreads);
+ * BLI_threadpool_init(&lb, do_something_func, maxthreads);
*
* while (cont) {
* if (BLI_available_threads(&lb) && !(escape loop event)) {
* // get new job (data pointer)
* // tag job 'processed
- * BLI_insert_thread(&lb, job);
+ * BLI_threadpool_insert(&lb, job);
* }
* else PIL_sleep_ms(50);
*
@@ -96,7 +98,7 @@ static TaskScheduler *task_scheduler = NULL;
* for (go over all jobs)
* if (job is ready) {
* if (job was not removed) {
- * BLI_remove_thread(&lb, job);
+ * BLI_threadpool_remove(&lb, job);
* }
* }
* else cont = 1;
@@ -108,7 +110,7 @@ static TaskScheduler *task_scheduler = NULL;
* }
* }
*
- * BLI_end_threads(&lb);
+ * BLI_threadpool_end(&lb);
*
************************************************ */
static SpinLock _malloc_lock;
@@ -124,7 +126,7 @@ static pthread_mutex_t _colormanage_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t _fftw_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t _view3d_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t mainid;
-static int thread_levels = 0; /* threads can be invoked inside threads */
+static unsigned int thread_levels = 0; /* threads can be invoked inside threads */
static int num_threads_override = 0;
/* just a max for security reasons */
@@ -181,7 +183,7 @@ TaskScheduler *BLI_task_scheduler_get(void)
* problem otherwise: scene render will kill of the mutex!
*/
-void BLI_init_threads(ListBase *threadbase, void *(*do_thread)(void *), int tot)
+void BLI_threadpool_init(ListBase *threadbase, void *(*do_thread)(void *), int tot)
{
int a;
@@ -198,9 +200,9 @@ void BLI_init_threads(ListBase *threadbase, void *(*do_thread)(void *), int tot)
tslot->avail = 1;
}
}
-
- BLI_spin_lock(&_malloc_lock);
- if (thread_levels == 0) {
+
+ unsigned int level = atomic_fetch_and_add_u(&thread_levels, 1);
+ if (level == 0) {
MEM_set_lock_callback(BLI_lock_malloc_thread, BLI_unlock_malloc_thread);
#ifdef USE_APPLE_OMP_FIX
@@ -210,9 +212,6 @@ void BLI_init_threads(ListBase *threadbase, void *(*do_thread)(void *), int tot)
thread_tls_data = pthread_getspecific(gomp_tls_key);
#endif
}
-
- thread_levels++;
- BLI_spin_unlock(&_malloc_lock);
}
/* amount of available threads */
@@ -229,7 +228,7 @@ int BLI_available_threads(ListBase *threadbase)
}
/* returns thread number, for sample patterns or threadsafe tables */
-int BLI_available_thread_index(ListBase *threadbase)
+int BLI_threadpool_available_thread_index(ListBase *threadbase)
{
ThreadSlot *tslot;
int counter = 0;
@@ -259,7 +258,7 @@ int BLI_thread_is_main(void)
return pthread_equal(pthread_self(), mainid);
}
-void BLI_insert_thread(ListBase *threadbase, void *callerdata)
+void BLI_threadpool_insert(ListBase *threadbase, void *callerdata)
{
ThreadSlot *tslot;
@@ -274,7 +273,7 @@ void BLI_insert_thread(ListBase *threadbase, void *callerdata)
printf("ERROR: could not insert thread slot\n");
}
-void BLI_remove_thread(ListBase *threadbase, void *callerdata)
+void BLI_threadpool_remove(ListBase *threadbase, void *callerdata)
{
ThreadSlot *tslot;
@@ -287,7 +286,7 @@ void BLI_remove_thread(ListBase *threadbase, void *callerdata)
}
}
-void BLI_remove_thread_index(ListBase *threadbase, int index)
+void BLI_threadpool_remove_index(ListBase *threadbase, int index)
{
ThreadSlot *tslot;
int counter = 0;
@@ -302,7 +301,7 @@ void BLI_remove_thread_index(ListBase *threadbase, int index)
}
}
-void BLI_remove_threads(ListBase *threadbase)
+void BLI_threadpool_clear(ListBase *threadbase)
{
ThreadSlot *tslot;
@@ -315,7 +314,7 @@ void BLI_remove_threads(ListBase *threadbase)
}
}
-void BLI_end_threads(ListBase *threadbase)
+void BLI_threadpool_end(ListBase *threadbase)
{
ThreadSlot *tslot;
@@ -331,11 +330,10 @@ void BLI_end_threads(ListBase *threadbase)
BLI_freelistN(threadbase);
}
- BLI_spin_lock(&_malloc_lock);
- thread_levels--;
- if (thread_levels == 0)
+ unsigned int level = atomic_sub_and_fetch_u(&thread_levels, 1);
+ if (level == 0) {
MEM_set_lock_callback(NULL, NULL);
- BLI_spin_unlock(&_malloc_lock);
+ }
}
/* System Information */
@@ -420,12 +418,12 @@ static ThreadMutex *global_mutex_from_type(const int type)
}
}
-void BLI_lock_thread(int type)
+void BLI_thread_lock(int type)
{
pthread_mutex_lock(global_mutex_from_type(type));
}
-void BLI_unlock_thread(int type)
+void BLI_thread_unlock(int type)
{
pthread_mutex_unlock(global_mutex_from_type(type));
}
@@ -474,8 +472,10 @@ void BLI_mutex_free(ThreadMutex *mutex)
void BLI_spin_init(SpinLock *spin)
{
-#ifdef __APPLE__
+#if defined(__APPLE__)
*spin = OS_SPINLOCK_INIT;
+#elif defined(_MSC_VER)
+ *spin = 0;
#else
pthread_spin_init(spin, 0);
#endif
@@ -483,8 +483,14 @@ void BLI_spin_init(SpinLock *spin)
void BLI_spin_lock(SpinLock *spin)
{
-#ifdef __APPLE__
+#if defined(__APPLE__)
OSSpinLockLock(spin);
+#elif defined(_MSC_VER)
+ while (InterlockedExchangeAcquire(spin, 1)) {
+ while (*spin) {
+ /* pass */
+ }
+ }
#else
pthread_spin_lock(spin);
#endif
@@ -492,21 +498,24 @@ void BLI_spin_lock(SpinLock *spin)
void BLI_spin_unlock(SpinLock *spin)
{
-#ifdef __APPLE__
+#if defined(__APPLE__)
OSSpinLockUnlock(spin);
+#elif defined(_MSC_VER)
+ _ReadWriteBarrier();
+ *spin = 0;
#else
pthread_spin_unlock(spin);
#endif
}
-#ifndef __APPLE__
-void BLI_spin_end(SpinLock *spin)
+#if defined(__APPLE__) || defined(_MSC_VER)
+void BLI_spin_end(SpinLock *UNUSED(spin))
{
- pthread_spin_destroy(spin);
}
#else
-void BLI_spin_end(SpinLock *UNUSED(spin))
+void BLI_spin_end(SpinLock *spin)
{
+ pthread_spin_destroy(spin);
}
#endif
@@ -764,12 +773,12 @@ void *BLI_thread_queue_pop_timeout(ThreadQueue *queue, int ms)
return work;
}
-int BLI_thread_queue_size(ThreadQueue *queue)
+int BLI_thread_queue_len(ThreadQueue *queue)
{
int size;
pthread_mutex_lock(&queue->mutex);
- size = BLI_gsqueue_size(queue->queue);
+ size = BLI_gsqueue_len(queue->queue);
pthread_mutex_unlock(&queue->mutex);
return size;
@@ -810,28 +819,24 @@ void BLI_thread_queue_wait_finish(ThreadQueue *queue)
/* ************************************************ */
-void BLI_begin_threaded_malloc(void)
+void BLI_threaded_malloc_begin(void)
{
- /* Used for debug only */
- /* BLI_assert(thread_levels >= 0); */
-
- BLI_spin_lock(&_malloc_lock);
- if (thread_levels == 0) {
+ unsigned int level = atomic_fetch_and_add_u(&thread_levels, 1);
+ if (level == 0) {
MEM_set_lock_callback(BLI_lock_malloc_thread, BLI_unlock_malloc_thread);
+ /* There is a little chance that two threads will meed to acces to a
+ * scheduler which was not yet created from main thread. which could
+ * cause scheduler created multiple times.
+ */
+ BLI_task_scheduler_get();
}
- thread_levels++;
- BLI_spin_unlock(&_malloc_lock);
}
-void BLI_end_threaded_malloc(void)
+void BLI_threaded_malloc_end(void)
{
- /* Used for debug only */
- /* BLI_assert(thread_levels >= 0); */
-
- BLI_spin_lock(&_malloc_lock);
- thread_levels--;
- if (thread_levels == 0)
+ unsigned int level = atomic_sub_and_fetch_u(&thread_levels, 1);
+ if (level == 0) {
MEM_set_lock_callback(NULL, NULL);
- BLI_spin_unlock(&_malloc_lock);
+ }
}
diff --git a/source/blender/blenlib/intern/timecode.c b/source/blender/blenlib/intern/timecode.c
index e755a7ae52c..7856bad4d99 100644
--- a/source/blender/blenlib/intern/timecode.c
+++ b/source/blender/blenlib/intern/timecode.c
@@ -94,11 +94,11 @@ size_t BLI_timecode_string_from_time(
* to cope with 'half' frames, etc., which should be fine in most cases
*/
seconds = (int)time;
- frames = iroundf((float)(((double)time - (double)seconds) * fps));
+ frames = round_fl_to_int((float)(((double)time - (double)seconds) * fps));
}
else {
/* seconds (with pixel offset rounding) */
- seconds = iroundf(time);
+ seconds = round_fl_to_int(time);
}
switch (timecode_style) {
@@ -169,7 +169,7 @@ size_t BLI_timecode_string_from_time(
/* precision of decimal part */
const int ms_dp = (power <= 0) ? (1 - power) : 1;
- const int ms = iroundf((time - (float)seconds) * 1000.0f);
+ const int ms = round_fl_to_int((time - (float)seconds) * 1000.0f);
rlen = BLI_snprintf_rlen(
str, maxncpy, "%s%02d:%02d:%02d,%0*d", neg, hours, minutes, seconds, ms_dp, ms);
@@ -183,7 +183,7 @@ size_t BLI_timecode_string_from_time(
rlen = BLI_snprintf_rlen(str, maxncpy, "%.*f", 1 - power, time_seconds);
}
else {
- rlen = BLI_snprintf_rlen(str, maxncpy, "%d", iroundf(time_seconds));
+ rlen = BLI_snprintf_rlen(str, maxncpy, "%d", round_fl_to_int(time_seconds));
}
break;
}
@@ -250,7 +250,7 @@ size_t BLI_timecode_string_from_time_seconds(
rlen = BLI_snprintf_rlen(str, maxncpy, "%.*f", 1 - power, time_seconds);
}
else {
- rlen = BLI_snprintf_rlen(str, maxncpy, "%d", iroundf(time_seconds));
+ rlen = BLI_snprintf_rlen(str, maxncpy, "%d", round_fl_to_int(time_seconds));
}
return rlen;
diff --git a/source/blender/blenlib/intern/voronoi.c b/source/blender/blenlib/intern/voronoi_2d.c
index e0cbe278ffb..40e98d5914c 100644
--- a/source/blender/blenlib/intern/voronoi.c
+++ b/source/blender/blenlib/intern/voronoi_2d.c
@@ -23,20 +23,18 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/*
+/** \file blender/blenlib/intern/voronoi_2d.c
+ * \ingroup bli
+ *
* Fortune's algorithm implemented using explanation and some code snippets from
* http://blog.ivank.net/fortunes-algorithm-and-implementation.html
*/
-/** \file blender/blenlib/intern/voronoi.c
- * \ingroup bli
- */
-
#include "MEM_guardedalloc.h"
#include "BLI_listbase.h"
#include "BLI_math.h"
-#include "BLI_voronoi.h"
+#include "BLI_voronoi_2d.h"
#include "BLI_utildefines.h"
#define VORONOI_EPS 1e-2f
diff --git a/source/blender/blenlib/intern/winstuff.c b/source/blender/blenlib/intern/winstuff.c
index 3b06b7df09a..d6834428376 100644
--- a/source/blender/blenlib/intern/winstuff.c
+++ b/source/blender/blenlib/intern/winstuff.c
@@ -160,8 +160,6 @@ void RegisterBlendExtension(void)
GetSystemDirectory(SysDir, FILE_MAXDIR);
#ifdef _WIN64
ThumbHandlerDLL = "BlendThumb64.dll";
-#elif defined(__MINGW32__)
- ThumbHandlerDLL = "BlendThumb.dll";
#else
IsWow64Process(GetCurrentProcess(), &IsWOW64);
if (IsWOW64 == true)
diff --git a/source/blender/blenloader/BLO_blend_defs.h b/source/blender/blenloader/BLO_blend_defs.h
index a6b06a080cc..6776b1c3338 100644
--- a/source/blender/blenloader/BLO_blend_defs.h
+++ b/source/blender/blenloader/BLO_blend_defs.h
@@ -75,6 +75,6 @@ enum {
ENDB = BLEND_MAKE_ID('E', 'N', 'D', 'B'),
};
-#define BLEN_THUMB_MEMSIZE_FILE(_x, _y) (sizeof(int) * (size_t)(2 + (_x) * (_y)))
+#define BLEN_THUMB_MEMSIZE_FILE(_x, _y) (sizeof(int) * (2 + (size_t)(_x) * (size_t)(_y)))
#endif /* __BLO_BLEND_DEFS_H__ */
diff --git a/source/blender/blenloader/BLO_readfile.h b/source/blender/blenloader/BLO_readfile.h
index c85cf128643..0b4ff13c7bd 100644
--- a/source/blender/blenloader/BLO_readfile.h
+++ b/source/blender/blenloader/BLO_readfile.h
@@ -51,11 +51,11 @@ struct FileData;
typedef struct BlendHandle BlendHandle;
-typedef enum BlenFileType {
+typedef enum eBlenFileType {
BLENFILETYPE_BLEND = 1,
BLENFILETYPE_PUB = 2,
BLENFILETYPE_RUNTIME = 3
-} BlenFileType;
+} eBlenFileType;
typedef struct BlendFileData {
struct Main *main;
@@ -68,14 +68,28 @@ typedef struct BlendFileData {
struct bScreen *curscreen;
struct Scene *curscene;
- BlenFileType type;
+ eBlenFileType type;
} BlendFileData;
-BlendFileData *BLO_read_from_file(const char *filepath, struct ReportList *reports);
-BlendFileData *BLO_read_from_memory(const void *mem, int memsize, struct ReportList *reports);
+
+/* skip reading some data-block types (may want to skip screen data too). */
+typedef enum eBLOReadSkip {
+ BLO_READ_SKIP_NONE = 0,
+ BLO_READ_SKIP_USERDEF = (1 << 0),
+ BLO_READ_SKIP_DATA = (1 << 1),
+} eBLOReadSkip;
+#define BLO_READ_SKIP_ALL \
+ (BLO_READ_SKIP_USERDEF | BLO_READ_SKIP_DATA)
+
+BlendFileData *BLO_read_from_file(
+ const char *filepath,
+ struct ReportList *reports, eBLOReadSkip skip_flag);
+BlendFileData *BLO_read_from_memory(
+ const void *mem, int memsize,
+ struct ReportList *reports, eBLOReadSkip skip_flag);
BlendFileData *BLO_read_from_memfile(
struct Main *oldmain, const char *filename, struct MemFile *memfile,
- struct ReportList *reports);
+ struct ReportList *reports, eBLOReadSkip skip_flag);
void BLO_blendfiledata_free(BlendFileData *bfd);
@@ -95,13 +109,22 @@ void BLO_blendhandle_close(BlendHandle *bh);
bool BLO_has_bfile_extension(const char *str);
bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, char **r_name);
+/* Options controlling behavior of append/link code.
+ * Note: merged with 'user-level' options from operators etc. in 16 lower bits
+ * (see eFileSel_Params_Flag in DNA_space_types.h). */
+typedef enum BLO_LibLinkFlags {
+ /* Generate a placeholder (empty ID) if not found in current lib file. */
+ BLO_LIBLINK_USE_PLACEHOLDERS = 1 << 16,
+ /* Force loaded ID to be tagged as LIB_TAG_INDIRECT (used in reload context only). */
+ BLO_LIBLINK_FORCE_INDIRECT = 1 << 17,
+} BLO_LinkFlags;
+
struct Main *BLO_library_link_begin(struct Main *mainvar, BlendHandle **bh, const char *filepath);
struct ID *BLO_library_link_named_part(struct Main *mainl, BlendHandle **bh, const short idcode, const char *name);
struct ID *BLO_library_link_named_part_ex(
struct Main *mainl, BlendHandle **bh,
- const short idcode, const char *name, const short flag,
- struct Scene *scene, struct View3D *v3d,
- const bool use_placeholders, const bool force_indirect);
+ const short idcode, const char *name, const int flag,
+ struct Scene *scene, struct View3D *v3d);
void BLO_library_link_end(struct Main *mainl, BlendHandle **bh, short flag, struct Scene *scene, struct View3D *v3d);
void BLO_library_link_copypaste(struct Main *mainl, BlendHandle *bh);
@@ -124,6 +147,8 @@ void BLO_update_defaults_startup_blend(struct Main *mainvar);
struct BlendThumbnail *BLO_thumbnail_from_file(const char *filepath);
+struct Main *BLO_main_from_memfile(struct MemFile *memfile, struct Main *bmain, struct Scene **r_scene);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenloader/BLO_runtime.h b/source/blender/blenloader/BLO_runtime.h
index 0a5a7d3a660..c119ea95f66 100644
--- a/source/blender/blenloader/BLO_runtime.h
+++ b/source/blender/blenloader/BLO_runtime.h
@@ -38,11 +38,14 @@ extern "C" {
#endif
struct BlendFileData;
+struct Main;
struct ReportList;
int BLO_is_a_runtime(const char *file);
struct BlendFileData *BLO_read_runtime(const char *file, struct ReportList *reports);
+bool BLO_main_validate_libraries(struct Main *bmain, struct ReportList *reports);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/blenloader/BLO_undofile.h b/source/blender/blenloader/BLO_undofile.h
index fb96ec75e62..c407ea31b9b 100644
--- a/source/blender/blenloader/BLO_undofile.h
+++ b/source/blender/blenloader/BLO_undofile.h
@@ -33,25 +33,40 @@
* \ingroup blenloader
*/
+struct Scene;
+
typedef struct {
void *next, *prev;
-
- char *buf;
- unsigned int ident, size;
-
+ const char *buf;
+ /** Size in bytes. */
+ unsigned int size;
+ /** When true, this chunk doesn't own the memory, it's shared with a previous #MemFileChunk */
+ bool is_identical;
} MemFileChunk;
typedef struct MemFile {
ListBase chunks;
- unsigned int size;
+ size_t size;
} MemFile;
+typedef struct MemFileUndoData {
+ char filename[1024]; /* FILE_MAX */
+ MemFile memfile;
+ size_t undo_size;
+} MemFileUndoData;
+
/* actually only used writefile.c */
-extern void memfile_chunk_add(MemFile *compare, MemFile *current, const char *buf, unsigned int size);
+extern void memfile_chunk_add(
+ MemFile *memfile, const char *buf, unsigned int size,
+ MemFileChunk **compchunk_step);
/* exports */
extern void BLO_memfile_free(MemFile *memfile);
extern void BLO_memfile_merge(MemFile *first, MemFile *second);
-#endif
+/* utilities */
+extern struct Main *BLO_memfile_main_get(struct MemFile *memfile, struct Main *bmain, struct Scene **r_scene);
+extern bool BLO_memfile_write_file(struct MemFile *memfile, const char *filename);
+
+#endif /* __BLO_UNDOFILE_H__ */
diff --git a/source/blender/blenloader/CMakeLists.txt b/source/blender/blenloader/CMakeLists.txt
index 8cb9ef837b2..420f651ee7f 100644
--- a/source/blender/blenloader/CMakeLists.txt
+++ b/source/blender/blenloader/CMakeLists.txt
@@ -46,6 +46,7 @@ set(INC_SYS
)
set(SRC
+ intern/blend_validate.c
intern/readblenentry.c
intern/readfile.c
intern/runtime.c
@@ -69,6 +70,12 @@ if(WITH_BUILDINFO)
add_definitions(-DWITH_BUILDINFO)
endif()
+if(WITH_PYTHON)
+ if(WITH_PYTHON_SECURITY)
+ add_definitions(-DWITH_PYTHON_SECURITY)
+ endif()
+endif()
+
if(WITH_INTERNATIONAL)
add_definitions(-DWITH_INTERNATIONAL)
endif()
diff --git a/source/blender/blenloader/intern/blend_validate.c b/source/blender/blenloader/intern/blend_validate.c
new file mode 100644
index 00000000000..d155fcfaa0d
--- /dev/null
+++ b/source/blender/blenloader/intern/blend_validate.c
@@ -0,0 +1,151 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Bastien Montagne
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ *
+ */
+
+/** \file blender/blenloader/intern/blend_validate.c
+ * \ingroup blenloader
+ *
+ * Utils to check/validate a Main is in sane state, only checks relations between datablocks and libraries for now.
+ *
+ * \note Does not *fix* anything, only reports found errors.
+ *
+ */
+
+#include <string.h> // for strrchr strncmp strstr
+
+#include "BLI_utildefines.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_linklist.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_sdna_types.h"
+#include "DNA_windowmanager_types.h"
+
+#include "BKE_library.h"
+#include "BKE_main.h"
+#include "BKE_report.h"
+
+#include "BLO_readfile.h"
+#include "BLO_runtime.h"
+
+#include "readfile.h"
+
+/* Does not fix anything, but checks that all linked data-blocks are still valid (i.e. pointing to the right library). */
+bool BLO_main_validate_libraries(struct Main *bmain, struct ReportList *reports)
+{
+ ListBase mainlist;
+ bool is_valid = true;
+
+ BKE_main_lock(bmain);
+
+ blo_split_main(&mainlist, bmain);
+
+ ListBase *lbarray[MAX_LIBARRAY];
+ int i = set_listbasepointers(bmain, lbarray);
+ while (i--) {
+ for (ID *id = lbarray[i]->first; id != NULL; id = id->next) {
+ if (id->lib != NULL) {
+ is_valid = false;
+ BKE_reportf(reports, RPT_ERROR,
+ "ID %s is in local database while being linked from library %s!\n", id->name, id->lib->name);
+ }
+ }
+ }
+
+ for (Main *curmain = bmain->next; curmain != NULL; curmain = curmain->next) {
+ Library *curlib = curmain->curlib;
+ if (curlib == NULL) {
+ BKE_reportf(reports, RPT_ERROR,
+ "Library database with NULL library datablock!\n");
+ continue;
+ }
+
+ BKE_library_filepath_set(curlib, curlib->name);
+ BlendHandle *bh = BLO_blendhandle_from_file(curlib->filepath, reports);
+
+ if (bh == NULL) {
+ continue;
+ }
+
+ i = set_listbasepointers(curmain, lbarray);
+ while (i--) {
+ ID *id = lbarray[i]->first;
+ if (id == NULL) {
+ continue;
+ }
+
+ if (GS(id->name) == ID_LI) {
+ is_valid = false;
+ BKE_reportf(reports, RPT_ERROR,
+ "Library ID %s in library %s, this should not happen!\n", id->name, curlib->name);
+ continue;
+ }
+
+ int totnames = 0;
+ LinkNode *names = BLO_blendhandle_get_datablock_names(bh, GS(id->name), &totnames);
+ for (; id != NULL; id = id->next) {
+ if (id->lib == NULL) {
+ is_valid = false;
+ BKE_reportf(reports, RPT_ERROR,
+ "ID %s has NULL lib pointer while being in library %s!\n", id->name, curlib->name);
+ continue;
+ }
+ if (id->lib != curlib) {
+ is_valid = false;
+ BKE_reportf(reports, RPT_ERROR,
+ "ID %s has mismatched lib pointer!\n", id->name);
+ continue;
+ }
+
+ LinkNode *name = names;
+ for (; name; name = name->next) {
+ char *str_name = (char *)name->link;
+ if (id->name[2] == str_name[0] && STREQ(str_name, id->name + 2)) {
+ break;
+ }
+ }
+
+ if (name == NULL) {
+ is_valid = false;
+ BKE_reportf(reports, RPT_ERROR,
+ "ID %s not found in library %s anymore!\n", id->name, id->lib->name);
+ continue;
+ }
+ }
+
+ BLI_linklist_free(names, free);
+ }
+
+ BLO_blendhandle_close(bh);
+ }
+
+ blo_join_main(&mainlist);
+
+ BLI_assert(BLI_listbase_is_single(&mainlist));
+ BLI_assert(mainlist.first == (void *)bmain);
+
+ BKE_main_unlock(bmain);
+
+ return is_valid;
+}
diff --git a/source/blender/blenloader/intern/readblenentry.c b/source/blender/blenloader/intern/readblenentry.c
index be893177b3b..73109413271 100644
--- a/source/blender/blenloader/intern/readblenentry.c
+++ b/source/blender/blenloader/intern/readblenentry.c
@@ -317,7 +317,9 @@ void BLO_blendhandle_close(BlendHandle *bh)
* \param reports If the return value is NULL, errors indicating the cause of the failure.
* \return The data of the file.
*/
-BlendFileData *BLO_read_from_file(const char *filepath, ReportList *reports)
+BlendFileData *BLO_read_from_file(
+ const char *filepath,
+ ReportList *reports, eBLOReadSkip skip_flags)
{
BlendFileData *bfd = NULL;
FileData *fd;
@@ -325,6 +327,7 @@ BlendFileData *BLO_read_from_file(const char *filepath, ReportList *reports)
fd = blo_openblenderfile(filepath, reports);
if (fd) {
fd->reports = reports;
+ fd->skip_flags = skip_flags;
bfd = blo_read_file_internal(fd, filepath);
blo_freefiledata(fd);
}
@@ -341,7 +344,9 @@ BlendFileData *BLO_read_from_file(const char *filepath, ReportList *reports)
* \param reports If the return value is NULL, errors indicating the cause of the failure.
* \return The data of the file.
*/
-BlendFileData *BLO_read_from_memory(const void *mem, int memsize, ReportList *reports)
+BlendFileData *BLO_read_from_memory(
+ const void *mem, int memsize,
+ ReportList *reports, eBLOReadSkip skip_flags)
{
BlendFileData *bfd = NULL;
FileData *fd;
@@ -349,6 +354,7 @@ BlendFileData *BLO_read_from_memory(const void *mem, int memsize, ReportList *re
fd = blo_openblendermemory(mem, memsize, reports);
if (fd) {
fd->reports = reports;
+ fd->skip_flags = skip_flags;
bfd = blo_read_file_internal(fd, "");
blo_freefiledata(fd);
}
@@ -362,7 +368,9 @@ BlendFileData *BLO_read_from_memory(const void *mem, int memsize, ReportList *re
* \param oldmain old main, from which we will keep libraries and other datablocks that should not have changed.
* \param filename current file, only for retrieving library data.
*/
-BlendFileData *BLO_read_from_memfile(Main *oldmain, const char *filename, MemFile *memfile, ReportList *reports)
+BlendFileData *BLO_read_from_memfile(
+ Main *oldmain, const char *filename, MemFile *memfile,
+ ReportList *reports, eBLOReadSkip skip_flags)
{
BlendFileData *bfd = NULL;
FileData *fd;
@@ -371,6 +379,7 @@ BlendFileData *BLO_read_from_memfile(Main *oldmain, const char *filename, MemFil
fd = blo_openblendermemfile(memfile, reports);
if (fd) {
fd->reports = reports;
+ fd->skip_flags = skip_flags;
BLI_strncpy(fd->relabase, filename, sizeof(fd->relabase));
/* clear ob->proxy_from pointers in old main */
diff --git a/source/blender/blenloader/intern/readfile.c b/source/blender/blenloader/intern/readfile.c
index 7ea79fc5557..7d73b3050a6 100644
--- a/source/blender/blenloader/intern/readfile.c
+++ b/source/blender/blenloader/intern/readfile.c
@@ -41,6 +41,7 @@
#include <math.h> // for fabs
#include <stdarg.h> /* for va_start/end */
#include <time.h> /* for gmtime */
+#include <ctype.h> /* for isdigit */
#include "BLI_utildefines.h"
#ifndef WIN32
@@ -80,7 +81,7 @@
#include "DNA_meshdata_types.h"
#include "DNA_nla_types.h"
#include "DNA_node_types.h"
-#include "DNA_object_fluidsim.h" // NT
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "DNA_packedFile_types.h"
#include "DNA_particle_types.h"
@@ -129,6 +130,7 @@
#include "BKE_library_idmap.h"
#include "BKE_library_query.h"
#include "BKE_idcode.h"
+#include "BKE_idprop.h"
#include "BKE_material.h"
#include "BKE_main.h" // for Main
#include "BKE_mesh.h" // for ME_ defines (patching)
@@ -218,6 +220,15 @@
/* Use GHash for restoring pointers by name */
#define USE_GHASH_RESTORE_POINTER
+/* Define this to have verbose debug prints. */
+#define USE_DEBUG_PRINT
+
+#ifdef USE_DEBUG_PRINT
+# define DEBUG_PRINTF(...) printf(__VA_ARGS__)
+#else
+# define DEBUG_PRINTF(...)
+#endif
+
/***/
typedef struct OldNew {
@@ -278,7 +289,7 @@ static OldNewMap *oldnewmap_new(void)
OldNewMap *onm= MEM_callocN(sizeof(*onm), "OldNewMap");
onm->entriessize = 1024;
- onm->entries = MEM_mallocN(sizeof(*onm->entries)*onm->entriessize, "OldNewMap.entries");
+ onm->entries = MEM_malloc_arrayN(onm->entriessize, sizeof(*onm->entries), "OldNewMap.entries");
return onm;
}
@@ -525,7 +536,7 @@ void blo_split_main(ListBase *mainlist, Main *main)
/* (Library.temp_index -> Main), lookup table */
const unsigned int lib_main_array_len = BLI_listbase_count(&main->library);
- Main **lib_main_array = MEM_mallocN(lib_main_array_len * sizeof(*lib_main_array), __func__);
+ Main **lib_main_array = MEM_malloc_arrayN(lib_main_array_len, sizeof(*lib_main_array), __func__);
int i = 0;
for (Library *lib = main->library.first; lib; lib = lib->id.next, i++) {
@@ -541,6 +552,10 @@ void blo_split_main(ListBase *mainlist, Main *main)
ListBase *lbarray[MAX_LIBARRAY];
i = set_listbasepointers(main, lbarray);
while (i--) {
+ ID *id = lbarray[i]->first;
+ if (id == NULL || GS(id->name) == ID_LI) {
+ continue; /* no ID_LI datablock should ever be linked anyway, but just in case, better be explicit. */
+ }
split_libdata(lbarray[i], lib_main_array, lib_main_array_len);
}
@@ -637,7 +652,7 @@ static Main *blo_find_main(FileData *fd, const char *filepath, const char *relab
/* Add library datablock itself to 'main' Main, since libraries are **never** linked data.
* Fixes bug where you could end with all ID_LI datablocks having the same name... */
- lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib");
+ lib = BKE_libblock_alloc(mainlist->first, ID_LI, "Lib", 0);
lib->id.us = ID_FAKE_USERS(lib); /* Important, consistency with main ID reading code from read_libblock(). */
BLI_strncpy(lib->name, filepath, sizeof(lib->name));
BLI_strncpy(lib->filepath, name1, sizeof(lib->filepath));
@@ -871,7 +886,7 @@ BHead *blo_nextbhead(FileData *fd, BHead *thisblock)
return(bhead);
}
-/* Warning! Caller's responsability to ensure given bhead **is** and ID one! */
+/* Warning! Caller's responsibility to ensure given bhead **is** and ID one! */
const char *bhead_id_name(const FileData *fd, const BHead *bhead)
{
return (const char *)POINTER_OFFSET(bhead, sizeof(*bhead) + fd->id_name_offs);
@@ -881,39 +896,42 @@ static void decode_blender_header(FileData *fd)
{
char header[SIZEOFBLENDERHEADER], num[4];
int readsize;
-
+
/* read in the header data */
readsize = fd->read(fd, header, sizeof(header));
-
- if (readsize == sizeof(header)) {
- if (STREQLEN(header, "BLENDER", 7)) {
- fd->flags |= FD_FLAGS_FILE_OK;
-
- /* what size are pointers in the file ? */
- if (header[7]=='_') {
- fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
- if (sizeof(void *) != 4) {
- fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
- }
- }
- else {
- if (sizeof(void *) != 8) {
- fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
- }
+
+ if (readsize == sizeof(header) &&
+ STREQLEN(header, "BLENDER", 7) &&
+ ELEM(header[7], '_', '-') &&
+ ELEM(header[8], 'v', 'V') &&
+ (isdigit(header[9]) && isdigit(header[10]) && isdigit(header[11])))
+ {
+ fd->flags |= FD_FLAGS_FILE_OK;
+
+ /* what size are pointers in the file ? */
+ if (header[7] == '_') {
+ fd->flags |= FD_FLAGS_FILE_POINTSIZE_IS_4;
+ if (sizeof(void *) != 4) {
+ fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
}
-
- /* is the file saved in a different endian
- * than we need ?
- */
- if (((header[8] == 'v') ? L_ENDIAN : B_ENDIAN) != ENDIAN_ORDER) {
- fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
+ }
+ else {
+ if (sizeof(void *) != 8) {
+ fd->flags |= FD_FLAGS_POINTSIZE_DIFFERS;
}
-
- /* get the version number */
- memcpy(num, header + 9, 3);
- num[3] = 0;
- fd->fileversion = atoi(num);
}
+
+ /* is the file saved in a different endian
+ * than we need ?
+ */
+ if (((header[8] == 'v') ? L_ENDIAN : B_ENDIAN) != ENDIAN_ORDER) {
+ fd->flags |= FD_FLAGS_SWITCH_ENDIAN;
+ }
+
+ /* get the version number */
+ memcpy(num, header + 9, 3);
+ num[3] = 0;
+ fd->fileversion = atoi(num);
}
}
@@ -968,7 +986,13 @@ static int *read_file_thumbnail(FileData *fd)
BLI_endian_switch_int32(&data[1]);
}
- if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(data[0], data[1])) {
+ int width = data[0];
+ int height = data[1];
+
+ if (!BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
+ break;
+ }
+ if (bhead->len < BLEN_THUMB_MEMSIZE_FILE(width, height)) {
break;
}
@@ -1407,23 +1431,28 @@ bool BLO_library_path_explode(const char *path, char *r_dir, char **r_group, cha
BlendThumbnail *BLO_thumbnail_from_file(const char *filepath)
{
FileData *fd;
- BlendThumbnail *data;
+ BlendThumbnail *data = NULL;
int *fd_data;
fd = blo_openblenderfile_minimal(filepath);
fd_data = fd ? read_file_thumbnail(fd) : NULL;
if (fd_data) {
- const size_t sz = BLEN_THUMB_MEMSIZE(fd_data[0], fd_data[1]);
- data = MEM_mallocN(sz, __func__);
+ int width = fd_data[0];
+ int height = fd_data[1];
- BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(fd_data[0], fd_data[1]) - (sizeof(*fd_data) * 2)));
- data->width = fd_data[0];
- data->height = fd_data[1];
- memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
- }
- else {
- data = NULL;
+ /* Protect against buffer overflow vulnerability. */
+ if (BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
+ const size_t sz = BLEN_THUMB_MEMSIZE(width, height);
+ data = MEM_mallocN(sz, __func__);
+
+ if (data) {
+ BLI_assert((sz - sizeof(*data)) == (BLEN_THUMB_MEMSIZE_FILE(width, height) - (sizeof(*fd_data) * 2)));
+ data->width = width;
+ data->height = height;
+ memcpy(data->rect, &fd_data[2], sz - sizeof(*data));
+ }
+ }
}
blo_freefiledata(fd);
@@ -1969,7 +1998,7 @@ static void test_pointer_array(FileData *fd, void **mat)
len = MEM_allocN_len(*mat)/fd->filesdna->pointerlen;
if (fd->filesdna->pointerlen==8 && fd->memsdna->pointerlen==4) {
- ipoin=imat= MEM_mallocN(len * 4, "newmatar");
+ ipoin=imat= MEM_malloc_arrayN(len, 4, "newmatar");
lpoin= *mat;
while (len-- > 0) {
@@ -1984,7 +2013,7 @@ static void test_pointer_array(FileData *fd, void **mat)
}
if (fd->filesdna->pointerlen==4 && fd->memsdna->pointerlen==8) {
- lpoin = lmat = MEM_mallocN(len * 8, "newmatar");
+ lpoin = lmat = MEM_malloc_arrayN(len, 8, "newmatar");
ipoin = *mat;
while (len-- > 0) {
@@ -2001,7 +2030,7 @@ static void test_pointer_array(FileData *fd, void **mat)
/* ************ READ ID Properties *************** */
static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
-static void IDP_LibLinkProperty(IDProperty *prop, int switch_endian, FileData *fd);
+static void IDP_LibLinkProperty(IDProperty *prop, FileData *fd);
static void IDP_DirectLinkIDPArray(IDProperty *prop, int switch_endian, FileData *fd)
{
@@ -2106,8 +2135,19 @@ static void IDP_DirectLinkProperty(IDProperty *prop, int switch_endian, FileData
BLI_endian_switch_int32(&prop->data.val2);
BLI_endian_switch_int64((int64_t *)&prop->data.val);
}
-
break;
+ case IDP_INT:
+ case IDP_FLOAT:
+ case IDP_ID:
+ break; /* Nothing special to do here. */
+ default:
+ /* Unknown IDP type, nuke it (we cannot handle unknown types everywhere in code,
+ * IDP are way too polymorphic to do it safely. */
+ printf("%s: found unknown IDProperty type %d, reset to Integer one !\n", __func__, prop->type);
+ /* Note: we do not attempt to free unknown prop, we have no way to know how to do that! */
+ prop->type = IDP_INT;
+ prop->subtype = 0;
+ IDP_Int(prop) = 0;
}
}
@@ -2132,10 +2172,39 @@ static void _IDP_DirectLinkGroup_OrFree(IDProperty **prop, int switch_endian, Fi
}
}
-/* stub function */
-static void IDP_LibLinkProperty(IDProperty *UNUSED(prop), int UNUSED(switch_endian), FileData *UNUSED(fd))
+static void IDP_LibLinkProperty(IDProperty *prop, FileData *fd)
{
- /* Should we do something here, prop should be ensured to be non-NULL first... */
+ if (!prop)
+ return;
+
+ switch (prop->type) {
+ case IDP_ID: /* PointerProperty */
+ {
+ void *newaddr = newlibadr_us(fd, NULL, IDP_Id(prop));
+ if (IDP_Id(prop) && !newaddr && G.debug) {
+ printf("Error while loading \"%s\". Data not found in file!\n", prop->name);
+ }
+ prop->data.pointer = newaddr;
+ break;
+ }
+ case IDP_IDPARRAY: /* CollectionProperty */
+ {
+ IDProperty *idp_array = IDP_IDPArray(prop);
+ for (int i = 0; i < prop->len; i++) {
+ IDP_LibLinkProperty(&(idp_array[i]), fd);
+ }
+ break;
+ }
+ case IDP_GROUP: /* PointerProperty */
+ {
+ for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
+ IDP_LibLinkProperty(loop, fd);
+ }
+ break;
+ }
+ default:
+ break; /* Nothing to do for other IDProps. */
+ }
}
/* ************ READ IMAGE PREVIEW *************** */
@@ -2169,6 +2238,11 @@ static void direct_link_id(FileData *fd, ID *id)
/* this case means the data was written incorrectly, it should not happen */
IDP_DirectLinkGroup_OrFree(&id->properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
}
+ id->py_instance = NULL;
+
+ /* That way datablock reading not going through main read_libblock() function are still in a clear tag state.
+ * (glowering at certain nodetree fake datablock here...). */
+ id->tag = 0;
}
/* ************ READ CurveMapping *************** */
@@ -2192,19 +2266,19 @@ static void direct_link_curvemapping(FileData *fd, CurveMapping *cumap)
/* library brush linking after fileread */
static void lib_link_brush(FileData *fd, Main *main)
{
- Brush *brush;
-
/* only link ID pointers */
- for (brush = main->brush.first; brush; brush = brush->id.next) {
+ for (Brush *brush = main->brush.first; brush; brush = brush->id.next) {
if (brush->id.tag & LIB_TAG_NEED_LINK) {
- brush->id.tag &= ~LIB_TAG_NEED_LINK;
-
+ IDP_LibLinkProperty(brush->id.properties, fd);
+
/* brush->(mask_)mtex.obj is ignored on purpose? */
brush->mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mtex.tex);
brush->mask_mtex.tex = newlibadr_us(fd, brush->id.lib, brush->mask_mtex.tex);
brush->clone.image = newlibadr(fd, brush->id.lib, brush->clone.image);
brush->toggle_brush = newlibadr(fd, brush->id.lib, brush->toggle_brush);
brush->paint_curve = newlibadr_us(fd, brush->id.lib, brush->paint_curve);
+
+ brush->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -2227,13 +2301,13 @@ static void direct_link_brush(FileData *fd, Brush *brush)
}
/* ************ READ Palette *************** */
-static void lib_link_palette(FileData *UNUSED(fd), Main *main)
+static void lib_link_palette(FileData *fd, Main *main)
{
- Palette *palette;
-
/* only link ID pointers */
- for (palette = main->palettes.first; palette; palette = palette->id.next) {
+ for (Palette *palette = main->palettes.first; palette; palette = palette->id.next) {
if (palette->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(palette->id.properties, fd);
+
palette->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -2245,13 +2319,13 @@ static void direct_link_palette(FileData *fd, Palette *palette)
link_list(fd, &palette->colors);
}
-static void lib_link_paint_curve(FileData *UNUSED(fd), Main *main)
+static void lib_link_paint_curve(FileData *fd, Main *main)
{
- PaintCurve *pc;
-
/* only link ID pointers */
- for (pc = main->paintcurves.first; pc; pc = pc->id.next) {
+ for (PaintCurve *pc = main->paintcurves.first; pc; pc = pc->id.next) {
if (pc->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(pc->id.properties, fd);
+
pc->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -2400,13 +2474,14 @@ static void lib_link_fcurves(FileData *fd, ID *id, ListBase *list)
/* NOTE: this assumes that link_list has already been called on the list */
-static void direct_link_fmodifiers(FileData *fd, ListBase *list)
+static void direct_link_fmodifiers(FileData *fd, ListBase *list, FCurve *curve)
{
FModifier *fcm;
for (fcm = list->first; fcm; fcm = fcm->next) {
/* relink general data */
fcm->data = newdataadr(fd, fcm->data);
+ fcm->curve = curve;
/* do relinking of data for specific types */
switch (fcm->type) {
@@ -2496,22 +2571,19 @@ static void direct_link_fcurves(FileData *fd, ListBase *list)
/* modifiers */
link_list(fd, &fcu->modifiers);
- direct_link_fmodifiers(fd, &fcu->modifiers);
+ direct_link_fmodifiers(fd, &fcu->modifiers, fcu);
}
}
static void lib_link_action(FileData *fd, Main *main)
{
- bAction *act;
- bActionChannel *chan;
-
- for (act = main->action.first; act; act = act->id.next) {
+ for (bAction *act = main->action.first; act; act = act->id.next) {
if (act->id.tag & LIB_TAG_NEED_LINK) {
- act->id.tag &= ~LIB_TAG_NEED_LINK;
+ IDP_LibLinkProperty(act->id.properties, fd);
// XXX deprecated - old animation system <<<
- for (chan=act->chanbase.first; chan; chan=chan->next) {
+ for (bActionChannel *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);
}
@@ -2524,6 +2596,8 @@ static void lib_link_action(FileData *fd, Main *main)
marker->camera = newlibadr(fd, act->id.lib, marker->camera);
}
}
+
+ act->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -2602,7 +2676,7 @@ static void direct_link_nladata_strips(FileData *fd, ListBase *list)
/* strip's F-Modifiers */
link_list(fd, &strip->modifiers);
- direct_link_fmodifiers(fd, &strip->modifiers);
+ direct_link_fmodifiers(fd, &strip->modifiers, NULL);
}
}
@@ -2710,26 +2784,20 @@ static void direct_link_animdata(FileData *fd, AnimData *adt)
static void lib_link_cachefiles(FileData *fd, Main *bmain)
{
- CacheFile *cache_file;
-
/* only link ID pointers */
- for (cache_file = bmain->cachefiles.first; cache_file; cache_file = cache_file->id.next) {
+ for (CacheFile *cache_file = bmain->cachefiles.first; cache_file; cache_file = cache_file->id.next) {
if (cache_file->id.tag & LIB_TAG_NEED_LINK) {
- cache_file->id.tag &= ~LIB_TAG_NEED_LINK;
- }
-
- BLI_listbase_clear(&cache_file->object_paths);
- cache_file->handle = NULL;
- cache_file->handle_mutex = NULL;
-
- if (cache_file->adt) {
+ IDP_LibLinkProperty(cache_file->id.properties, fd);
lib_link_animdata(fd, &cache_file->id, cache_file->adt);
+
+ cache_file->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
static void direct_link_cachefile(FileData *fd, CacheFile *cache_file)
{
+ BLI_listbase_clear(&cache_file->object_paths);
cache_file->handle = NULL;
cache_file->handle_mutex = NULL;
@@ -2753,19 +2821,13 @@ static void direct_link_motionpath(FileData *fd, bMotionPath *mpath)
/* ************ READ NODE TREE *************** */
-static void lib_link_node_socket(FileData *fd, ID *UNUSED(id), bNodeSocket *sock)
-{
- /* Link ID Properties -- and copy this comment EXACTLY for easy finding
- * of library blocks that implement this.*/
- IDP_LibLinkProperty(sock->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
-}
-
/* Single node tree (also used for material/scene trees), ntree is not NULL */
static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
{
bNode *node;
bNodeSocket *sock;
+ IDP_LibLinkProperty(ntree->id.properties, fd);
lib_link_animdata(fd, &ntree->id, ntree->adt);
ntree->gpd = newlibadr_us(fd, id->lib, ntree->gpd);
@@ -2773,32 +2835,35 @@ static void lib_link_ntree(FileData *fd, ID *id, bNodeTree *ntree)
for (node = ntree->nodes.first; node; node = node->next) {
/* Link ID Properties -- and copy this comment EXACTLY for easy finding
* of library blocks that implement this.*/
- IDP_LibLinkProperty(node->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ IDP_LibLinkProperty(node->prop, fd);
- node->id= newlibadr_us(fd, id->lib, node->id);
+ node->id = newlibadr_us(fd, id->lib, node->id);
- for (sock = node->inputs.first; sock; sock = sock->next)
- lib_link_node_socket(fd, id, sock);
- for (sock = node->outputs.first; sock; sock = sock->next)
- lib_link_node_socket(fd, id, sock);
+ for (sock = node->inputs.first; sock; sock = sock->next) {
+ IDP_LibLinkProperty(sock->prop, fd);
+ }
+ for (sock = node->outputs.first; sock; sock = sock->next) {
+ IDP_LibLinkProperty(sock->prop, fd);
+ }
}
- for (sock = ntree->inputs.first; sock; sock = sock->next)
- lib_link_node_socket(fd, id, sock);
- for (sock = ntree->outputs.first; sock; sock = sock->next)
- lib_link_node_socket(fd, id, sock);
+ for (sock = ntree->inputs.first; sock; sock = sock->next) {
+ IDP_LibLinkProperty(sock->prop, fd);
+ }
+ for (sock = ntree->outputs.first; sock; sock = sock->next) {
+ IDP_LibLinkProperty(sock->prop, fd);
+ }
}
/* library ntree linking after fileread */
static void lib_link_nodetree(FileData *fd, Main *main)
{
- bNodeTree *ntree;
-
/* only link ID pointers */
- for (ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
+ for (bNodeTree *ntree = main->nodetree.first; ntree; ntree = ntree->id.next) {
if (ntree->id.tag & LIB_TAG_NEED_LINK) {
- ntree->id.tag &= ~LIB_TAG_NEED_LINK;
lib_link_ntree(fd, &ntree->id, ntree);
+
+ ntree->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -3044,7 +3109,7 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
ntree->adt = newdataadr(fd, ntree->adt);
direct_link_animdata(fd, ntree->adt);
- ntree->id.tag &= ~(LIB_TAG_ID_RECALC|LIB_TAG_ID_RECALC_DATA);
+ ntree->id.recalc &= ~ID_RECALC_ALL;
link_list(fd, &ntree->nodes);
for (node = ntree->nodes.first; node; node = node->next) {
@@ -3089,7 +3154,7 @@ static void direct_link_nodetree(FileData *fd, bNodeTree *ntree)
else if (ntree->type==NTREE_COMPOSIT) {
if (ELEM(node->type, CMP_NODE_TIME, CMP_NODE_CURVE_VEC, CMP_NODE_CURVE_RGB, CMP_NODE_HUECORRECT))
direct_link_curvemapping(fd, node->storage);
- else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
+ else if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS, CMP_NODE_VIEWER, CMP_NODE_SPLITVIEWER))
((ImageUser *)node->storage)->ok = 1;
}
else if ( ntree->type==NTREE_TEXTURE) {
@@ -3291,6 +3356,8 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose)
pchan->bone = BLI_ghash_lookup(bone_hash, pchan->name);
+ IDP_LibLinkProperty(pchan->prop, fd);
+
pchan->custom = newlibadr_us(fd, arm->id.lib, pchan->custom);
if (UNLIKELY(pchan->bone == NULL)) {
rebuild = true;
@@ -3311,13 +3378,26 @@ static void lib_link_pose(FileData *fd, Main *bmain, Object *ob, bPose *pose)
}
}
+static void lib_link_bones(FileData *fd, Bone *bone)
+{
+ IDP_LibLinkProperty(bone->prop, fd);
+
+ for (Bone *curbone = bone->childbase.first; curbone; curbone = curbone->next) {
+ lib_link_bones(fd, curbone);
+ }
+}
+
static void lib_link_armature(FileData *fd, Main *main)
{
- bArmature *arm;
-
- for (arm = main->armature.first; arm; arm = arm->id.next) {
+ for (bArmature *arm = main->armature.first; arm; arm = arm->id.next) {
if (arm->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(arm->id.properties, fd);
lib_link_animdata(fd, &arm->id, arm->adt);
+
+ for (Bone *curbone = arm->bonebase.first; curbone; curbone = curbone->next) {
+ lib_link_bones(fd, curbone);
+ }
+
arm->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -3362,14 +3442,13 @@ static void direct_link_armature(FileData *fd, bArmature *arm)
static void lib_link_camera(FileData *fd, Main *main)
{
- Camera *ca;
-
- for (ca = main->camera.first; ca; ca = ca->id.next) {
+ for (Camera *ca = main->camera.first; ca; ca = ca->id.next) {
if (ca->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(ca->id.properties, fd);
lib_link_animdata(fd, &ca->id, ca->adt);
ca->ipo = newlibadr_us(fd, ca->id.lib, ca->ipo); // XXX deprecated - old animation system
-
+
ca->dof_ob = newlibadr(fd, ca->id.lib, ca->dof_ob);
ca->id.tag &= ~LIB_TAG_NEED_LINK;
@@ -3388,16 +3467,13 @@ static void direct_link_camera(FileData *fd, Camera *ca)
static void lib_link_lamp(FileData *fd, Main *main)
{
- Lamp *la;
- MTex *mtex;
- int a;
-
- for (la = main->lamp.first; la; la = la->id.next) {
+ for (Lamp *la = main->lamp.first; la; la = la->id.next) {
if (la->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(la->id.properties, fd);
lib_link_animdata(fd, &la->id, la->adt);
- for (a = 0; a < MAX_MTEX; a++) {
- mtex = la->mtex[a];
+ for (int a = 0; a < MAX_MTEX; a++) {
+ MTex *mtex = la->mtex[a];
if (mtex) {
mtex->tex = newlibadr_us(fd, la->id.lib, mtex->tex);
mtex->object = newlibadr(fd, la->id.lib, mtex->object);
@@ -3454,17 +3530,11 @@ void blo_do_versions_key_uidgen(Key *key)
static void lib_link_key(FileData *fd, Main *main)
{
- Key *key;
-
- for (key = main->key.first; key; key = key->id.next) {
- /*check if we need to generate unique ids for the shapekeys*/
- if (!key->uidgen) {
- blo_do_versions_key_uidgen(key);
- }
-
+ for (Key *key = main->key.first; key; key = key->id.next) {
BLI_assert((key->id.tag & LIB_TAG_EXTERN) == 0);
if (key->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(key->id.properties, fd);
lib_link_animdata(fd, &key->id, key->adt);
key->ipo = newlibadr_us(fd, key->id.lib, key->ipo); // XXX deprecated - old animation system
@@ -3527,15 +3597,14 @@ static void direct_link_key(FileData *fd, Key *key)
static void lib_link_mball(FileData *fd, Main *main)
{
- MetaBall *mb;
- int a;
-
- for (mb = main->mball.first; mb; mb = mb->id.next) {
+ for (MetaBall *mb = main->mball.first; mb; mb = mb->id.next) {
if (mb->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(mb->id.properties, fd);
lib_link_animdata(fd, &mb->id, mb->adt);
- for (a = 0; a < mb->totcol; a++)
+ for (int a = 0; a < mb->totcol; a++) {
mb->mat[a] = newlibadr_us(fd, mb->id.lib, mb->mat[a]);
+ }
mb->ipo = newlibadr_us(fd, mb->id.lib, mb->ipo); // XXX deprecated - old animation system
@@ -3564,18 +3633,15 @@ static void direct_link_mball(FileData *fd, MetaBall *mb)
static void lib_link_world(FileData *fd, Main *main)
{
- World *wrld;
- MTex *mtex;
- int a;
-
- for (wrld = main->world.first; wrld; wrld = wrld->id.next) {
+ for (World *wrld = main->world.first; wrld; wrld = wrld->id.next) {
if (wrld->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(wrld->id.properties, fd);
lib_link_animdata(fd, &wrld->id, wrld->adt);
wrld->ipo = newlibadr_us(fd, wrld->id.lib, wrld->ipo); // XXX deprecated - old animation system
- for (a=0; a < MAX_MTEX; a++) {
- mtex = wrld->mtex[a];
+ for (int a = 0; a < MAX_MTEX; a++) {
+ MTex *mtex = wrld->mtex[a];
if (mtex) {
mtex->tex = newlibadr_us(fd, wrld->id.lib, mtex->tex);
mtex->object = newlibadr(fd, wrld->id.lib, mtex->object);
@@ -3616,12 +3682,12 @@ static void direct_link_world(FileData *fd, World *wrld)
/* ************ READ VFONT ***************** */
-static void lib_link_vfont(FileData *UNUSED(fd), Main *main)
+static void lib_link_vfont(FileData *fd, Main *main)
{
- VFont *vf;
-
- for (vf = main->vfont.first; vf; vf = vf->id.next) {
+ for (VFont *vf = main->vfont.first; vf; vf = vf->id.next) {
if (vf->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(vf->id.properties, fd);
+
vf->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -3636,12 +3702,12 @@ static void direct_link_vfont(FileData *fd, VFont *vf)
/* ************ READ TEXT ****************** */
-static void lib_link_text(FileData *UNUSED(fd), Main *main)
+static void lib_link_text(FileData *fd, Main *main)
{
- Text *text;
-
- for (text = main->text.first; text; text = text->id.next) {
+ for (Text *text = main->text.first; text; text = text->id.next) {
if (text->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(text->id.properties, fd);
+
text->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -3650,20 +3716,16 @@ static void lib_link_text(FileData *UNUSED(fd), Main *main)
static void direct_link_text(FileData *fd, Text *text)
{
TextLine *ln;
-
+
text->name = newdataadr(fd, text->name);
-
- text->undo_pos = -1;
- text->undo_len = TXT_INIT_UNDO;
- text->undo_buf = MEM_mallocN(text->undo_len, "undo buf");
-
+
text->compiled = NULL;
-
+
#if 0
if (text->flags & TXT_ISEXT) {
BKE_text_reload(text);
- }
- /* else { */
+ }
+ /* else { */
#endif
link_list(fd, &text->lines);
@@ -3690,11 +3752,9 @@ static void direct_link_text(FileData *fd, Text *text)
static void lib_link_image(FileData *fd, Main *main)
{
- Image *ima;
-
- for (ima = main->image.first; ima; ima = ima->id.next) {
+ for (Image *ima = main->image.first; ima; ima = ima->id.next) {
if (ima->id.tag & LIB_TAG_NEED_LINK) {
- IDP_LibLinkProperty(ima->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ IDP_LibLinkProperty(ima->id.properties, fd);
ima->id.tag &= ~LIB_TAG_NEED_LINK;
}
@@ -3759,15 +3819,14 @@ static void direct_link_image(FileData *fd, Image *ima)
static void lib_link_curve(FileData *fd, Main *main)
{
- Curve *cu;
- int a;
-
- for (cu = main->curve.first; cu; cu = cu->id.next) {
+ for (Curve *cu = main->curve.first; cu; cu = cu->id.next) {
if (cu->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(cu->id.properties, fd);
lib_link_animdata(fd, &cu->id, cu->adt);
- for (a = 0; a < cu->totcol; a++)
+ for (int a = 0; a < cu->totcol; a++) {
cu->mat[a] = newlibadr_us(fd, cu->id.lib, cu->mat[a]);
+ }
cu->bevobj = newlibadr(fd, cu->id.lib, cu->bevobj);
cu->taperobj = newlibadr(fd, cu->id.lib, cu->taperobj);
@@ -3804,6 +3863,9 @@ static void direct_link_curve(FileData *fd, Curve *cu)
cu->adt= newdataadr(fd, cu->adt);
direct_link_animdata(fd, cu->adt);
+ /* Protect against integer overflow vulnerability. */
+ CLAMP(cu->len_wchar, 0, INT_MAX - 4);
+
cu->mat = newdataadr(fd, cu->mat);
test_pointer_array(fd, (void **)&cu->mat);
cu->str = newdataadr(fd, cu->str);
@@ -3816,7 +3878,7 @@ static void direct_link_curve(FileData *fd, Curve *cu)
else {
cu->nurb.first=cu->nurb.last= NULL;
- tb = MEM_callocN(MAXTEXTBOX*sizeof(TextBox), "TextBoxread");
+ tb = MEM_calloc_arrayN(MAXTEXTBOX, sizeof(TextBox), "TextBoxread");
if (cu->tb) {
memcpy(tb, cu->tb, cu->totbox*sizeof(TextBox));
MEM_freeN(cu->tb);
@@ -3852,10 +3914,9 @@ static void direct_link_curve(FileData *fd, Curve *cu)
static void lib_link_texture(FileData *fd, Main *main)
{
- Tex *tex;
-
- for (tex = main->tex.first; tex; tex = tex->id.next) {
+ for (Tex *tex = main->tex.first; tex; tex = tex->id.next) {
if (tex->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(tex->id.properties, fd);
lib_link_animdata(fd, &tex->id, tex->adt);
tex->ima = newlibadr_us(fd, tex->id.lib, tex->ima);
@@ -3931,23 +3992,16 @@ static void direct_link_texture(FileData *fd, Tex *tex)
static void lib_link_material(FileData *fd, Main *main)
{
- Material *ma;
- MTex *mtex;
- int a;
-
- for (ma = main->mat.first; ma; ma = ma->id.next) {
+ for (Material *ma = main->mat.first; ma; ma = ma->id.next) {
if (ma->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(ma->id.properties, fd);
lib_link_animdata(fd, &ma->id, ma->adt);
- /* Link ID Properties -- and copy this comment EXACTLY for easy finding
- * of library blocks that implement this.*/
- IDP_LibLinkProperty(ma->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
-
ma->ipo = newlibadr_us(fd, ma->id.lib, ma->ipo); // XXX deprecated - old animation system
ma->group = newlibadr_us(fd, ma->id.lib, ma->group);
- for (a = 0; a < MAX_MTEX; a++) {
- mtex = ma->mtex[a];
+ for (int a = 0; a < MAX_MTEX; a++) {
+ MTex *mtex = ma->mtex[a];
if (mtex) {
mtex->tex = newlibadr_us(fd, ma->id.lib, mtex->tex);
mtex->object = newlibadr(fd, ma->id.lib, mtex->object);
@@ -4078,14 +4132,11 @@ static void lib_link_partdeflect(FileData *fd, ID *id, PartDeflect *pd)
static void lib_link_particlesettings(FileData *fd, Main *main)
{
- ParticleSettings *part;
- ParticleDupliWeight *dw;
- MTex *mtex;
- int a;
-
- for (part = main->particle.first; part; part = part->id.next) {
+ for (ParticleSettings *part = main->particle.first; part; part = part->id.next) {
if (part->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(part->id.properties, fd);
lib_link_animdata(fd, &part->id, part->adt);
+
part->ipo = newlibadr_us(fd, part->id.lib, part->ipo); // XXX deprecated - old animation system
part->dup_ob = newlibadr(fd, part->id.lib, part->dup_ob);
@@ -4105,6 +4156,7 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
}
if (part->dupliweights.first && part->dup_group) {
+ ParticleDupliWeight *dw;
int index_ok = 0;
/* check for old files without indices (all indexes 0) */
if (BLI_listbase_is_single(&part->dupliweights)) {
@@ -4169,8 +4221,8 @@ static void lib_link_particlesettings(FileData *fd, Main *main)
}
}
- for (a = 0; a < MAX_MTEX; a++) {
- mtex= part->mtex[a];
+ for (int a = 0; a < MAX_MTEX; a++) {
+ MTex *mtex= part->mtex[a];
if (mtex) {
mtex->tex = newlibadr_us(fd, part->id.lib, mtex->tex);
mtex->object = newlibadr(fd, part->id.lib, mtex->object);
@@ -4205,6 +4257,9 @@ static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
part->roughcurve = newdataadr(fd, part->roughcurve);
if (part->roughcurve)
direct_link_curvemapping(fd, part->roughcurve);
+ part->twistcurve = newdataadr(fd, part->twistcurve);
+ if (part->twistcurve)
+ direct_link_curvemapping(fd, part->twistcurve);
part->effector_weights = newdataadr(fd, part->effector_weights);
if (!part->effector_weights)
@@ -4228,6 +4283,9 @@ static void direct_link_particlesettings(FileData *fd, ParticleSettings *part)
for (a = 0; a < MAX_MTEX; a++) {
part->mtex[a] = newdataadr(fd, part->mtex[a]);
}
+
+ /* Protect against integer overflow vulnerability. */
+ CLAMP(part->trail_count, 1, 100000);
}
static void lib_link_particlesystems(FileData *fd, Object *ob, ID *id, ListBase *particles)
@@ -4404,7 +4462,7 @@ static void lib_link_mesh(FileData *fd, Main *main)
/* Link ID Properties -- and copy this comment EXACTLY for easy finding
* of library blocks that implement this.*/
- IDP_LibLinkProperty(me->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ IDP_LibLinkProperty(me->id.properties, fd);
lib_link_animdata(fd, &me->id, me->adt);
/* this check added for python created meshes */
@@ -4677,10 +4735,9 @@ static void direct_link_mesh(FileData *fd, Mesh *mesh)
static void lib_link_latt(FileData *fd, Main *main)
{
- Lattice *lt;
-
- for (lt = main->latt.first; lt; lt = lt->id.next) {
+ for (Lattice *lt = main->latt.first; lt; lt = lt->id.next) {
if (lt->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(lt->id.properties, fd);
lib_link_animdata(fd, &lt->id, lt->adt);
lt->ipo = newlibadr_us(fd, lt->id.lib, lt->ipo); // XXX deprecated - old animation system
@@ -4724,17 +4781,13 @@ static void lib_link_modifiers(FileData *fd, Object *ob)
static void lib_link_object(FileData *fd, Main *main)
{
- Object *ob;
- PartEff *paf;
- bSensor *sens;
- bController *cont;
- bActuator *act;
- void *poin;
- int warn=0, a;
-
- for (ob = main->object.first; ob; ob = ob->id.next) {
+ bool warn = false;
+
+ for (Object *ob = main->object.first; ob; ob = ob->id.next) {
if (ob->id.tag & LIB_TAG_NEED_LINK) {
- IDP_LibLinkProperty(ob->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ int a;
+
+ IDP_LibLinkProperty(ob->id.properties, fd);
lib_link_animdata(fd, &ob->id, ob->adt);
// XXX deprecated - old animation system <<<
@@ -4766,17 +4819,17 @@ static void lib_link_object(FileData *fd, Main *main)
}
ob->proxy_group = newlibadr(fd, ob->id.lib, ob->proxy_group);
- poin = ob->data;
+ void *poin = ob->data;
ob->data = newlibadr_us(fd, ob->id.lib, ob->data);
- if (ob->data==NULL && poin!=NULL) {
+ if (ob->data == NULL && poin != NULL) {
if (ob->id.lib)
printf("Can't find obdata of %s lib %s\n", ob->id.name + 2, ob->id.lib->name);
else
printf("Object %s lost data.\n", ob->id.name + 2);
ob->type = OB_EMPTY;
- warn = 1;
+ warn = true;
if (ob->pose) {
/* we can't call #BKE_pose_free() here because of library linking
@@ -4822,13 +4875,13 @@ static void lib_link_object(FileData *fd, Main *main)
lib_link_nlastrips(fd, &ob->id, &ob->nlastrips);
// >>> XXX deprecated - old animation system
- for (paf = ob->effect.first; paf; paf = paf->next) {
+ for (PartEff *paf = ob->effect.first; paf; paf = paf->next) {
if (paf->type == EFF_PARTICLE) {
paf->group = newlibadr_us(fd, ob->id.lib, paf->group);
}
}
- for (sens = ob->sensors.first; sens; sens = sens->next) {
+ for (bSensor *sens = ob->sensors.first; sens; sens = sens->next) {
for (a = 0; a < sens->totlinks; a++)
sens->links[a] = newglobadr(fd, sens->links[a]);
@@ -4839,7 +4892,7 @@ static void lib_link_object(FileData *fd, Main *main)
}
}
- for (cont = ob->controllers.first; cont; cont = cont->next) {
+ for (bController *cont = ob->controllers.first; cont; cont = cont->next) {
for (a=0; a < cont->totlinks; a++)
cont->links[a] = newglobadr(fd, cont->links[a]);
@@ -4851,86 +4904,117 @@ static void lib_link_object(FileData *fd, Main *main)
cont->totslinks = 0;
}
- for (act = ob->actuators.first; act; act = act->next) {
- if (act->type == ACT_SOUND) {
- bSoundActuator *sa = act->data;
- sa->sound= newlibadr_us(fd, ob->id.lib, sa->sound);
- }
- else if (act->type == ACT_GAME) {
- /* bGameActuator *ga= act->data; */
- }
- else if (act->type == ACT_CAMERA) {
- bCameraActuator *ca = act->data;
- ca->ob= newlibadr(fd, ob->id.lib, ca->ob);
- }
- /* leave this one, it's obsolete but necessary to read for conversion */
- else if (act->type == ACT_ADD_OBJECT) {
- bAddObjectActuator *eoa = act->data;
- if (eoa) eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
- }
- else if (act->type == ACT_OBJECT) {
- bObjectActuator *oa = act->data;
- if (oa == NULL) {
- init_actuator(act);
+ for (bActuator *act = ob->actuators.first; act; act = act->next) {
+ switch (act->type) {
+ case ACT_SOUND:
+ {
+ bSoundActuator *sa = act->data;
+ sa->sound = newlibadr_us(fd, ob->id.lib, sa->sound);
+ break;
}
- else {
- oa->reference = newlibadr(fd, ob->id.lib, oa->reference);
+ case ACT_GAME:
+ /* bGameActuator *ga= act->data; */
+ break;
+ case ACT_CAMERA:
+ {
+ bCameraActuator *ca = act->data;
+ ca->ob = newlibadr(fd, ob->id.lib, ca->ob);
+ break;
}
- }
- else if (act->type == ACT_EDIT_OBJECT) {
- bEditObjectActuator *eoa = act->data;
- if (eoa == NULL) {
- init_actuator(act);
+ /* leave this one, it's obsolete but necessary to read for conversion */
+ case ACT_ADD_OBJECT:
+ {
+ bAddObjectActuator *eoa = act->data;
+ if (eoa)
+ eoa->ob = newlibadr(fd, ob->id.lib, eoa->ob);
+ break;
}
- else {
- eoa->ob= newlibadr(fd, ob->id.lib, eoa->ob);
- eoa->me= newlibadr(fd, ob->id.lib, eoa->me);
+ case ACT_OBJECT:
+ {
+ bObjectActuator *oa = act->data;
+ if (oa == NULL) {
+ init_actuator(act);
+ }
+ else {
+ oa->reference = newlibadr(fd, ob->id.lib, oa->reference);
+ }
+ break;
}
- }
- else if (act->type == ACT_SCENE) {
- bSceneActuator *sa = act->data;
- sa->camera= newlibadr(fd, ob->id.lib, sa->camera);
- sa->scene= newlibadr(fd, ob->id.lib, sa->scene);
- }
- else if (act->type == ACT_ACTION) {
- bActionActuator *aa = act->data;
- aa->act= newlibadr_us(fd, ob->id.lib, aa->act);
- }
- else if (act->type == ACT_SHAPEACTION) {
- bActionActuator *aa = act->data;
- aa->act= newlibadr_us(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);
- }
- else if (act->type == ACT_MESSAGE) {
- 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; */
- }
- else if (act->type == ACT_ARMATURE) {
- bArmatureActuator *arma= act->data;
- arma->target= newlibadr(fd, ob->id.lib, arma->target);
- arma->subtarget= newlibadr(fd, ob->id.lib, arma->subtarget);
- }
- else if (act->type == ACT_STEERING) {
- bSteeringActuator *steeringa = act->data;
- steeringa->target = newlibadr(fd, ob->id.lib, steeringa->target);
- steeringa->navmesh = newlibadr(fd, ob->id.lib, steeringa->navmesh);
- }
- else if (act->type == ACT_MOUSE) {
- /* bMouseActuator *moa= act->data; */
+ case ACT_EDIT_OBJECT:
+ {
+ bEditObjectActuator *eoa = act->data;
+ if (eoa == NULL) {
+ init_actuator(act);
+ }
+ else {
+ eoa->ob = newlibadr(fd, ob->id.lib, eoa->ob);
+ eoa->me = newlibadr(fd, ob->id.lib, eoa->me);
+ }
+ break;
+ }
+ case ACT_SCENE:
+ {
+ bSceneActuator *sa = act->data;
+ sa->camera = newlibadr(fd, ob->id.lib, sa->camera);
+ sa->scene = newlibadr(fd, ob->id.lib, sa->scene);
+ break;
+ }
+ case ACT_ACTION:
+ {
+ bActionActuator *aa = act->data;
+ aa->act = newlibadr_us(fd, ob->id.lib, aa->act);
+ break;
+ }
+ case ACT_SHAPEACTION:
+ {
+ bActionActuator *aa = act->data;
+ aa->act = newlibadr_us(fd, ob->id.lib, aa->act);
+ break;
+ }
+ case ACT_PROPERTY:
+ {
+ bPropertyActuator *pa = act->data;
+ pa->ob = newlibadr(fd, ob->id.lib, pa->ob);
+ break;
+ }
+ case ACT_MESSAGE:
+ {
+ bMessageActuator *ma = act->data;
+ ma->toObject = newlibadr(fd, ob->id.lib, ma->toObject);
+ break;
+ }
+ case ACT_2DFILTER:
+ {
+ bTwoDFilterActuator *_2dfa = act->data;
+ _2dfa->text = newlibadr(fd, ob->id.lib, _2dfa->text);
+ break;
+ }
+ case ACT_PARENT:
+ {
+ bParentActuator *parenta = act->data;
+ parenta->ob = newlibadr(fd, ob->id.lib, parenta->ob);
+ break;
+ }
+ case ACT_STATE:
+ /* bStateActuator *statea = act->data; */
+ break;
+ case ACT_ARMATURE:
+ {
+ bArmatureActuator *arma= act->data;
+ arma->target = newlibadr(fd, ob->id.lib, arma->target);
+ arma->subtarget = newlibadr(fd, ob->id.lib, arma->subtarget);
+ break;
+ }
+ case ACT_STEERING:
+ {
+ bSteeringActuator *steeringa = act->data;
+ steeringa->target = newlibadr(fd, ob->id.lib, steeringa->target);
+ steeringa->navmesh = newlibadr(fd, ob->id.lib, steeringa->navmesh);
+ break;
+ }
+ case ACT_MOUSE:
+ /* bMouseActuator *moa = act->data; */
+ break;
}
}
@@ -4996,6 +5080,7 @@ static void direct_link_pose(FileData *fd, bPose *pose)
link_list(fd, &pose->agroups);
pose->chanhash = NULL;
+ pose->chan_array = NULL;
for (pchan = pose->chanbase.first; pchan; pchan=pchan->next) {
pchan->bone = NULL;
@@ -5195,9 +5280,9 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
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->current_x = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_x");
+ collmd->current_xnew = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_xnew");
+ collmd->current_v = MEM_calloc_arrayN(collmd->numverts, sizeof(MVert), "current_v");
#endif
collmd->x = NULL;
@@ -5317,6 +5402,37 @@ static void direct_link_modifiers(FileData *fd, ListBase *lb)
MeshSeqCacheModifierData *msmcd = (MeshSeqCacheModifierData *)md;
msmcd->reader = NULL;
}
+ else if (md->type == eModifierType_SurfaceDeform) {
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+
+ smd->verts = newdataadr(fd, smd->verts);
+
+ if (smd->verts) {
+ for (int i = 0; i < smd->numverts; i++) {
+ smd->verts[i].binds = newdataadr(fd, smd->verts[i].binds);
+
+ if (smd->verts[i].binds) {
+ for (int j = 0; j < smd->verts[i].numbinds; j++) {
+ smd->verts[i].binds[j].vert_inds = newdataadr(fd, smd->verts[i].binds[j].vert_inds);
+ smd->verts[i].binds[j].vert_weights = newdataadr(fd, smd->verts[i].binds[j].vert_weights);
+
+ if (fd->flags & FD_FLAGS_SWITCH_ENDIAN) {
+ if (smd->verts[i].binds[j].vert_inds)
+ BLI_endian_switch_uint32_array(smd->verts[i].binds[j].vert_inds, smd->verts[i].binds[j].numverts);
+
+ if (smd->verts[i].binds[j].vert_weights) {
+ if (smd->verts[i].binds[j].mode == MOD_SDEF_MODE_CENTROID ||
+ smd->verts[i].binds[j].mode == MOD_SDEF_MODE_LOOPTRI)
+ BLI_endian_switch_float_array(smd->verts[i].binds[j].vert_weights, 3);
+ else
+ BLI_endian_switch_float_array(smd->verts[i].binds[j].vert_weights, smd->verts[i].binds[j].numverts);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
}
}
@@ -5631,23 +5747,16 @@ static bool scene_validate_setscene__liblink(Scene *sce, const int totscene)
static void lib_link_scene(FileData *fd, Main *main)
{
- Scene *sce;
- Base *base, *next;
- Sequence *seq;
- SceneRenderLayer *srl;
- FreestyleModuleConfig *fmc;
- FreestyleLineSet *fls;
-
#ifdef USE_SETSCENE_CHECK
bool need_check_set = false;
int totscene = 0;
#endif
- for (sce = main->scene.first; sce; sce = sce->id.next) {
+ for (Scene *sce = main->scene.first; sce; sce = sce->id.next) {
if (sce->id.tag & LIB_TAG_NEED_LINK) {
/* Link ID Properties -- and copy this comment EXACTLY for easy finding
* of library blocks that implement this.*/
- IDP_LibLinkProperty(sce->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ IDP_LibLinkProperty(sce->id.properties, fd);
lib_link_animdata(fd, &sce->id, sce->adt);
lib_link_keyingsets(fd, &sce->id, &sce->keyingsets);
@@ -5683,7 +5792,7 @@ static void lib_link_scene(FileData *fd, Main *main)
sce->toolsettings->particle.shape_object = newlibadr(fd, sce->id.lib, sce->toolsettings->particle.shape_object);
- for (base = sce->base.first; base; base = next) {
+ for (Base *next, *base = sce->base.first; base; base = next) {
next = base->next;
base->object = newlibadr_us(fd, sce->id.lib, base->object);
@@ -5697,8 +5806,11 @@ static void lib_link_scene(FileData *fd, Main *main)
}
}
+ Sequence *seq;
SEQ_BEGIN (sce->ed, seq)
{
+ IDP_LibLinkProperty(seq->prop, fd);
+
if (seq->ipo) seq->ipo = newlibadr_us(fd, sce->id.lib, seq->ipo); // XXX deprecated - old animation system
seq->scene_sound = NULL;
if (seq->scene) {
@@ -5762,13 +5874,13 @@ static void lib_link_scene(FileData *fd, Main *main)
composite_patch(sce->nodetree, sce);
}
- for (srl = sce->r.layers.first; srl; srl = srl->next) {
+ for (SceneRenderLayer *srl = sce->r.layers.first; srl; srl = srl->next) {
srl->mat_override = newlibadr_us(fd, sce->id.lib, srl->mat_override);
srl->light_override = newlibadr_us(fd, sce->id.lib, srl->light_override);
- for (fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
+ for (FreestyleModuleConfig *fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
fmc->script = newlibadr(fd, sce->id.lib, fmc->script);
}
- for (fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
+ for (FreestyleLineSet *fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
fls->linestyle = newlibadr_us(fd, sce->id.lib, fls->linestyle);
fls->group = newlibadr_us(fd, sce->id.lib, fls->group);
}
@@ -5802,7 +5914,7 @@ static void lib_link_scene(FileData *fd, Main *main)
#ifdef USE_SETSCENE_CHECK
if (need_check_set) {
- for (sce = main->scene.first; sce; sce = sce->id.next) {
+ for (Scene *sce = main->scene.first; sce; sce = sce->id.next) {
if (sce->id.tag & LIB_TAG_NEED_LINK) {
sce->id.tag &= ~LIB_TAG_NEED_LINK;
if (!scene_validate_setscene__liblink(sce, totscene)) {
@@ -5927,16 +6039,6 @@ static void direct_link_scene(FileData *fd, Scene *sce)
sce->toolsettings->particle.scene = NULL;
sce->toolsettings->particle.object = NULL;
sce->toolsettings->gp_sculpt.paintcursor = NULL;
-
- /* in rare cases this is needed, see [#33806] */
- if (sce->toolsettings->vpaint) {
- sce->toolsettings->vpaint->vpaint_prev = NULL;
- sce->toolsettings->vpaint->tot = 0;
- }
- if (sce->toolsettings->wpaint) {
- sce->toolsettings->wpaint->wpaint_prev = NULL;
- sce->toolsettings->wpaint->tot = 0;
- }
/* relink grease pencil drawing brushes */
link_list(fd, &sce->toolsettings->gp_brushes);
@@ -6020,9 +6122,13 @@ static void direct_link_scene(FileData *fd, Scene *sce)
seq->strip->transform = NULL;
}
if (seq->flag & SEQ_USE_PROXY) {
- seq->strip->proxy = newdataadr(
- fd, seq->strip->proxy);
- seq->strip->proxy->anim = NULL;
+ seq->strip->proxy = newdataadr(fd, seq->strip->proxy);
+ if (seq->strip->proxy) {
+ seq->strip->proxy->anim = NULL;
+ }
+ else {
+ BKE_sequencer_proxy_set(seq, true);
+ }
}
else {
seq->strip->proxy = NULL;
@@ -6076,17 +6182,17 @@ static void direct_link_scene(FileData *fd, Scene *sce)
}
}
}
-
+
+#ifdef DURIAN_CAMERA_SWITCH
+ /* Runtime */
+ sce->r.mode &= ~R_NO_CAMERA_SWITCH;
+#endif
+
sce->r.avicodecdata = newdataadr(fd, sce->r.avicodecdata);
if (sce->r.avicodecdata) {
sce->r.avicodecdata->lpFormat = newdataadr(fd, sce->r.avicodecdata->lpFormat);
sce->r.avicodecdata->lpParms = newdataadr(fd, sce->r.avicodecdata->lpParms);
}
-
- sce->r.qtcodecdata = newdataadr(fd, sce->r.qtcodecdata);
- 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);
IDP_DirectLinkGroup_OrFree(&sce->r.ffcodecdata.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
@@ -6097,6 +6203,11 @@ static void direct_link_scene(FileData *fd, Scene *sce)
link_list(fd, &(sce->r.layers));
link_list(fd, &(sce->r.views));
+
+ for (srl = sce->r.layers.first; srl; srl = srl->next) {
+ srl->prop = newdataadr(fd, srl->prop);
+ IDP_DirectLinkGroup_OrFree(&srl->prop, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ }
for (srl = sce->r.layers.first; srl; srl = srl->next) {
link_list(fd, &(srl->freestyleConfig.modules));
}
@@ -6194,7 +6305,8 @@ static void direct_link_windowmanager(FileData *fd, wmWindowManager *wm)
wm->defaultconf = NULL;
wm->addonconf = NULL;
wm->userconf = NULL;
-
+ wm->undo_stack = NULL;
+
BLI_listbase_clear(&wm->jobs);
BLI_listbase_clear(&wm->drags);
@@ -6212,8 +6324,10 @@ static void lib_link_windowmanager(FileData *fd, Main *main)
for (wm = main->wm.first; wm; wm = wm->id.next) {
if (wm->id.tag & LIB_TAG_NEED_LINK) {
- for (win = wm->windows.first; win; win = win->next)
+ /* Note: WM IDProperties are never written to file, hence no need to read/link them here. */
+ for (win = wm->windows.first; win; win = win->next) {
win->screen = newlibadr(fd, NULL, win->screen);
+ }
wm->id.tag &= ~LIB_TAG_NEED_LINK;
}
@@ -6225,13 +6339,12 @@ static void lib_link_windowmanager(FileData *fd, Main *main)
/* relink's grease pencil data's refs */
static void lib_link_gpencil(FileData *fd, Main *main)
{
- bGPdata *gpd;
-
- for (gpd = main->gpencil.first; gpd; gpd = gpd->id.next) {
+ for (bGPdata *gpd = main->gpencil.first; gpd; gpd = gpd->id.next) {
if (gpd->id.tag & LIB_TAG_NEED_LINK) {
- gpd->id.tag &= ~LIB_TAG_NEED_LINK;
-
+ IDP_LibLinkProperty(gpd->id.properties, fd);
lib_link_animdata(fd, &gpd->id, gpd->adt);
+
+ gpd->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -6293,12 +6406,11 @@ static void direct_link_gpencil(FileData *fd, bGPdata *gpd)
* check lib pointers in call below */
static void lib_link_screen(FileData *fd, Main *main)
{
- bScreen *sc;
- ScrArea *sa;
-
- for (sc = main->screen.first; sc; sc = sc->id.next) {
+ for (bScreen *sc = main->screen.first; sc; sc = sc->id.next) {
if (sc->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(sc->id.properties, fd);
id_us_ensure_real(&sc->id);
+
sc->scene = newlibadr(fd, sc->id.lib, sc->scene);
/* this should not happen, but apparently it does somehow. Until we figure out the cause,
@@ -6307,179 +6419,207 @@ static void lib_link_screen(FileData *fd, Main *main)
sc->scene = main->scene.first;
sc->animtimer = NULL; /* saved in rare cases */
+ sc->tool_tip = NULL;
sc->scrubbing = false;
- for (sa = sc->areabase.first; sa; sa = sa->next) {
- SpaceLink *sl;
-
+ for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
sa->full = newlibadr(fd, sc->id.lib, sa->full);
- for (sl = sa->spacedata.first; sl; sl= sl->next) {
- if (sl->spacetype == SPACE_VIEW3D) {
- View3D *v3d = (View3D*) sl;
- BGpic *bgpic = NULL;
-
- v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
- v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
-
- /* should be do_versions but not easy adding into the listbase */
- if (v3d->bgpic) {
- v3d->bgpic = newlibadr(fd, sc->id.lib, v3d->bgpic);
- BLI_addtail(&v3d->bgpicbase, bgpic);
- v3d->bgpic = NULL;
+ for (SpaceLink *sl = sa->spacedata.first; sl; sl= sl->next) {
+ switch (sl->spacetype) {
+ case SPACE_VIEW3D:
+ {
+ View3D *v3d = (View3D*) sl;
+ BGpic *bgpic = NULL;
+
+ v3d->camera= newlibadr(fd, sc->id.lib, v3d->camera);
+ v3d->ob_centre= newlibadr(fd, sc->id.lib, v3d->ob_centre);
+
+ /* should be do_versions but not easy adding into the listbase */
+ if (v3d->bgpic) {
+ v3d->bgpic = newlibadr(fd, sc->id.lib, v3d->bgpic);
+ BLI_addtail(&v3d->bgpicbase, bgpic);
+ v3d->bgpic = NULL;
+ }
+
+ for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
+ bgpic->ima = newlibadr_us(fd, sc->id.lib, bgpic->ima);
+ bgpic->clip = newlibadr_us(fd, sc->id.lib, bgpic->clip);
+ }
+ if (v3d->localvd) {
+ v3d->localvd->camera = newlibadr(fd, sc->id.lib, v3d->localvd->camera);
+ }
+ break;
}
-
- for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
- bgpic->ima = newlibadr_us(fd, sc->id.lib, bgpic->ima);
- bgpic->clip = newlibadr_us(fd, sc->id.lib, bgpic->clip);
+ case SPACE_IPO:
+ {
+ SpaceIpo *sipo = (SpaceIpo *)sl;
+ bDopeSheet *ads = sipo->ads;
+
+ if (ads) {
+ ads->source = newlibadr(fd, sc->id.lib, ads->source);
+ ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ }
+ break;
}
- if (v3d->localvd) {
- v3d->localvd->camera = newlibadr(fd, sc->id.lib, v3d->localvd->camera);
+ case SPACE_BUTS:
+ {
+ SpaceButs *sbuts = (SpaceButs *)sl;
+ sbuts->pinid = newlibadr(fd, sc->id.lib, sbuts->pinid);
+ if (sbuts->pinid == NULL) {
+ sbuts->flag &= ~SB_PIN_CONTEXT;
+ }
+ break;
}
- }
- else if (sl->spacetype == SPACE_IPO) {
- SpaceIpo *sipo = (SpaceIpo *)sl;
- bDopeSheet *ads = sipo->ads;
-
- if (ads) {
- ads->source = newlibadr(fd, sc->id.lib, ads->source);
- ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ case SPACE_FILE:
+ break;
+ case SPACE_ACTION:
+ {
+ SpaceAction *saction = (SpaceAction *)sl;
+ bDopeSheet *ads = &saction->ads;
+
+ if (ads) {
+ ads->source = newlibadr(fd, sc->id.lib, ads->source);
+ ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ }
+
+ saction->action = newlibadr(fd, sc->id.lib, saction->action);
+ break;
}
- }
- else if (sl->spacetype == SPACE_BUTS) {
- SpaceButs *sbuts = (SpaceButs *)sl;
- sbuts->pinid = newlibadr(fd, sc->id.lib, sbuts->pinid);
- if (sbuts->pinid == NULL) {
- sbuts->flag &= ~SB_PIN_CONTEXT;
+ case SPACE_IMAGE:
+ {
+ SpaceImage *sima = (SpaceImage *)sl;
+
+ sima->image = newlibadr_real_us(fd, sc->id.lib, sima->image);
+ sima->mask_info.mask = newlibadr_real_us(fd, sc->id.lib, sima->mask_info.mask);
+
+ /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
+ * so fingers crossed this works fine!
+ */
+ sima->gpd = newlibadr_us(fd, sc->id.lib, sima->gpd);
+ break;
}
- }
- else if (sl->spacetype == SPACE_FILE) {
- ;
- }
- else if (sl->spacetype == SPACE_ACTION) {
- SpaceAction *saction = (SpaceAction *)sl;
- bDopeSheet *ads = &saction->ads;
-
- if (ads) {
- ads->source = newlibadr(fd, sc->id.lib, ads->source);
- ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ case SPACE_SEQ:
+ {
+ SpaceSeq *sseq = (SpaceSeq *)sl;
+
+ /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
+ * so fingers crossed this works fine!
+ */
+ sseq->gpd = newlibadr_us(fd, sc->id.lib, sseq->gpd);
+ break;
}
-
- saction->action = newlibadr(fd, sc->id.lib, saction->action);
- }
- else if (sl->spacetype == SPACE_IMAGE) {
- SpaceImage *sima = (SpaceImage *)sl;
-
- sima->image = newlibadr_real_us(fd, sc->id.lib, sima->image);
- sima->mask_info.mask = newlibadr_real_us(fd, sc->id.lib, sima->mask_info.mask);
-
- /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
- * so fingers crossed this works fine!
- */
- sima->gpd = newlibadr_us(fd, sc->id.lib, sima->gpd);
- }
- else if (sl->spacetype == SPACE_SEQ) {
- SpaceSeq *sseq = (SpaceSeq *)sl;
-
- /* NOTE: pre-2.5, this was local data not lib data, but now we need this as lib data
- * so fingers crossed this works fine!
- */
- sseq->gpd = newlibadr_us(fd, sc->id.lib, sseq->gpd);
+ case SPACE_NLA:
+ {
+ SpaceNla *snla= (SpaceNla *)sl;
+ bDopeSheet *ads= snla->ads;
+
+ if (ads) {
+ ads->source = newlibadr(fd, sc->id.lib, ads->source);
+ ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ }
+ break;
+ }
+ case SPACE_TEXT:
+ {
+ SpaceText *st= (SpaceText *)sl;
- }
- else if (sl->spacetype == SPACE_NLA) {
- SpaceNla *snla= (SpaceNla *)sl;
- bDopeSheet *ads= snla->ads;
-
- if (ads) {
- ads->source = newlibadr(fd, sc->id.lib, ads->source);
- ads->filter_grp = newlibadr(fd, sc->id.lib, ads->filter_grp);
+ st->text= newlibadr(fd, sc->id.lib, st->text);
+ break;
}
- }
- else if (sl->spacetype == SPACE_TEXT) {
- SpaceText *st= (SpaceText *)sl;
-
- st->text= newlibadr(fd, sc->id.lib, st->text);
- }
- else if (sl->spacetype == SPACE_SCRIPT) {
- 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);
+ case SPACE_SCRIPT:
+ {
+ SpaceScript *scpt = (SpaceScript *)sl;
+ /*scpt->script = NULL; - 2.45 set to null, better re-run the script */
if (scpt->script) {
- SCRIPT_SET_NULL(scpt->script);
+ scpt->script = newlibadr(fd, sc->id.lib, scpt->script);
+ if (scpt->script) {
+ SCRIPT_SET_NULL(scpt->script);
+ }
}
+ break;
}
- }
- else if (sl->spacetype == SPACE_OUTLINER) {
- SpaceOops *so= (SpaceOops *)sl;
- so->search_tse.id = newlibadr(fd, NULL, so->search_tse.id);
-
- if (so->treestore) {
- TreeStoreElem *tselem;
- BLI_mempool_iter iter;
+ case SPACE_OUTLINER:
+ {
+ SpaceOops *so= (SpaceOops *)sl;
+ so->search_tse.id = newlibadr(fd, NULL, so->search_tse.id);
+
+ if (so->treestore) {
+ TreeStoreElem *tselem;
+ BLI_mempool_iter iter;
+
+ BLI_mempool_iternew(so->treestore, &iter);
+ while ((tselem = BLI_mempool_iterstep(&iter))) {
+ tselem->id = newlibadr(fd, NULL, tselem->id);
+ }
+ if (so->treehash) {
+ /* rebuild hash table, because it depends on ids too */
+ so->storeflag |= SO_TREESTORE_REBUILD;
+ }
+ }
+ break;
+ }
+ case SPACE_NODE:
+ {
+ SpaceNode *snode = (SpaceNode *)sl;
+ bNodeTreePath *path, *path_next;
+ bNodeTree *ntree;
+
+ /* node tree can be stored locally in id too, link this first */
+ snode->id = newlibadr(fd, sc->id.lib, snode->id);
+ snode->from = newlibadr(fd, sc->id.lib, snode->from);
+
+ ntree = snode->id ? ntreeFromID(snode->id) : NULL;
+ snode->nodetree = ntree ? ntree : newlibadr_us(fd, sc->id.lib, snode->nodetree);
+
+ for (path = snode->treepath.first; path; path = path->next) {
+ if (path == snode->treepath.first) {
+ /* first nodetree in path is same as snode->nodetree */
+ path->nodetree = snode->nodetree;
+ }
+ else
+ path->nodetree = newlibadr_us(fd, sc->id.lib, path->nodetree);
- BLI_mempool_iternew(so->treestore, &iter);
- while ((tselem = BLI_mempool_iterstep(&iter))) {
- tselem->id = newlibadr(fd, NULL, tselem->id);
+ if (!path->nodetree)
+ break;
}
- if (so->treehash) {
- /* rebuild hash table, because it depends on ids too */
- so->storeflag |= SO_TREESTORE_REBUILD;
+
+ /* remaining path entries are invalid, remove */
+ for (; path; path = path_next) {
+ path_next = path->next;
+
+ BLI_remlink(&snode->treepath, path);
+ MEM_freeN(path);
}
- }
- }
- else if (sl->spacetype == SPACE_NODE) {
- SpaceNode *snode = (SpaceNode *)sl;
- bNodeTreePath *path, *path_next;
- bNodeTree *ntree;
-
- /* node tree can be stored locally in id too, link this first */
- snode->id = newlibadr(fd, sc->id.lib, snode->id);
- snode->from = newlibadr(fd, sc->id.lib, snode->from);
-
- ntree = snode->id ? ntreeFromID(snode->id) : NULL;
- snode->nodetree = ntree ? ntree : newlibadr_us(fd, sc->id.lib, snode->nodetree);
-
- for (path = snode->treepath.first; path; path = path->next) {
- if (path == snode->treepath.first) {
- /* first nodetree in path is same as snode->nodetree */
- path->nodetree = snode->nodetree;
+
+ /* edittree is just the last in the path,
+ * set this directly since the path may have been shortened above */
+ if (snode->treepath.last) {
+ path = snode->treepath.last;
+ snode->edittree = path->nodetree;
}
- else
- path->nodetree = newlibadr_us(fd, sc->id.lib, path->nodetree);
-
- if (!path->nodetree)
- break;
+ else {
+ snode->edittree = NULL;
+ }
+ break;
}
-
- /* remaining path entries are invalid, remove */
- for (; path; path = path_next) {
- path_next = path->next;
-
- BLI_remlink(&snode->treepath, path);
- MEM_freeN(path);
+ case SPACE_CLIP:
+ {
+ SpaceClip *sclip = (SpaceClip *)sl;
+
+ sclip->clip = newlibadr_real_us(fd, sc->id.lib, sclip->clip);
+ sclip->mask_info.mask = newlibadr_real_us(fd, sc->id.lib, sclip->mask_info.mask);
+ break;
}
-
- /* edittree is just the last in the path,
- * set this directly since the path may have been shortened above */
- if (snode->treepath.last) {
- path = snode->treepath.last;
- snode->edittree = path->nodetree;
+ case SPACE_LOGIC:
+ {
+ SpaceLogic *slogic = (SpaceLogic *)sl;
+
+ slogic->gpd = newlibadr_us(fd, sc->id.lib, slogic->gpd);
+ break;
}
- else
- snode->edittree = NULL;
- }
- else if (sl->spacetype == SPACE_CLIP) {
- SpaceClip *sclip = (SpaceClip *)sl;
-
- sclip->clip = newlibadr_real_us(fd, sc->id.lib, sclip->clip);
- sclip->mask_info.mask = newlibadr_real_us(fd, sc->id.lib, sclip->mask_info.mask);
- }
- else if (sl->spacetype == SPACE_LOGIC) {
- SpaceLogic *slogic = (SpaceLogic *)sl;
-
- slogic->gpd = newlibadr_us(fd, sc->id.lib, slogic->gpd);
+ default:
+ break;
}
}
}
@@ -7200,7 +7340,7 @@ static bool direct_link_screen(FileData *fd, bScreen *sc)
sseq->scopes.sep_waveform_ibuf = NULL;
sseq->scopes.vector_ibuf = NULL;
sseq->scopes.histogram_ibuf = NULL;
-
+ sseq->compositor = NULL;
}
else if (sl->spacetype == SPACE_BUTS) {
SpaceButs *sbuts = (SpaceButs *)sl;
@@ -7289,12 +7429,20 @@ static void direct_link_library(FileData *fd, Library *lib, Main *main)
BLI_remlink(&main->library, lib);
MEM_freeN(lib);
-
-
+
+ /* Now, since Blender always expect **latest** Main pointer from fd->mainlist to be the active library
+ * Main pointer, where to add all non-library data-blocks found in file next, we have to switch that
+ * 'dupli' found Main to latest position in the list!
+ * Otherwise, you get weird disappearing linked data on a rather unconsistant basis.
+ * See also T53977 for reproducible case. */
+ BLI_remlink(fd->mainlist, newmain);
+ BLI_addtail(fd->mainlist, newmain);
+
return;
}
}
}
+
/* make sure we have full path in lib->filepath */
BLI_strncpy(lib->filepath, lib->name, sizeof(lib->name));
BLI_cleanup_path(fd->relabase, lib->filepath);
@@ -7353,13 +7501,13 @@ static void fix_relpaths_library(const char *basepath, Main *main)
static void lib_link_speaker(FileData *fd, Main *main)
{
- Speaker *spk;
-
- for (spk = main->speaker.first; spk; spk = spk->id.next) {
+ for (Speaker *spk = main->speaker.first; spk; spk = spk->id.next) {
if (spk->id.tag & LIB_TAG_NEED_LINK) {
+ IDP_LibLinkProperty(spk->id.properties, fd);
lib_link_animdata(fd, &spk->id, spk->adt);
spk->sound = newlibadr_us(fd, spk->id.lib, spk->sound);
+
spk->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
@@ -7409,14 +7557,15 @@ static void direct_link_sound(FileData *fd, bSound *sound)
static void lib_link_sound(FileData *fd, Main *main)
{
- bSound *sound;
-
- for (sound = main->sound.first; sound; sound = sound->id.next) {
+ for (bSound *sound = main->sound.first; sound; sound = sound->id.next) {
if (sound->id.tag & LIB_TAG_NEED_LINK) {
- sound->id.tag &= ~LIB_TAG_NEED_LINK;
+ IDP_LibLinkProperty(sound->id.properties, fd);
+
sound->ipo = newlibadr_us(fd, sound->id.lib, sound->ipo); // XXX deprecated - old animation system
BKE_sound_load(main, sound);
+
+ sound->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -7431,17 +7580,13 @@ static void direct_link_group(FileData *fd, Group *group)
static void lib_link_group(FileData *fd, Main *main)
{
- Group *group;
- GroupObject *go;
- bool add_us;
-
- for (group = main->group.first; group; group = group->id.next) {
+ for (Group *group = main->group.first; group; group = group->id.next) {
if (group->id.tag & LIB_TAG_NEED_LINK) {
- group->id.tag &= ~LIB_TAG_NEED_LINK;
+ IDP_LibLinkProperty(group->id.properties, fd);
- add_us = false;
+ bool add_us = false;
- for (go = group->gobject.first; go; go = go->next) {
+ for (GroupObject *go = group->gobject.first; go; go = go->next) {
go->ob = newlibadr_real_us(fd, group->id.lib, go->ob);
if (go->ob) {
go->ob->flag |= OB_FROMGROUP;
@@ -7453,6 +7598,8 @@ static void lib_link_group(FileData *fd, Main *main)
id_us_ensure_real(&group->id);
}
BKE_group_object_unlink(group, NULL, NULL, NULL); /* removes NULL entries */
+
+ group->id.tag &= ~LIB_TAG_NEED_LINK;
}
}
}
@@ -7488,7 +7635,7 @@ static void direct_link_moviePlaneTracks(FileData *fd, ListBase *plane_tracks_ba
int i;
plane_track->point_tracks = newdataadr(fd, plane_track->point_tracks);
- test_pointer_array(fd, (void**)&plane_track->point_tracks);
+ test_pointer_array(fd, (void **)&plane_track->point_tracks);
for (i = 0; i < plane_track->point_tracksnr; i++) {
plane_track->point_tracks[i] = newdataadr(fd, plane_track->point_tracks[i]);
}
@@ -7557,13 +7704,11 @@ static void lib_link_moviePlaneTracks(FileData *fd, MovieClip *clip, ListBase *t
static void lib_link_movieclip(FileData *fd, Main *main)
{
- MovieClip *clip;
-
- for (clip = main->movieclip.first; clip; clip = clip->id.next) {
+ for (MovieClip *clip = main->movieclip.first; clip; clip = clip->id.next) {
if (clip->id.tag & LIB_TAG_NEED_LINK) {
MovieTracking *tracking = &clip->tracking;
- MovieTrackingObject *object;
+ IDP_LibLinkProperty(clip->id.properties, fd);
lib_link_animdata(fd, &clip->id, clip->adt);
clip->gpd = newlibadr_us(fd, clip->id.lib, clip->gpd);
@@ -7571,7 +7716,7 @@ static void lib_link_movieclip(FileData *fd, Main *main)
lib_link_movieTracks(fd, clip, &tracking->tracks);
lib_link_moviePlaneTracks(fd, clip, &tracking->plane_tracks);
- for (object = tracking->objects.first; object; object = object->next) {
+ for (MovieTrackingObject *object = tracking->objects.first; object; object = object->next) {
lib_link_movieTracks(fd, clip, &object->tracks);
lib_link_moviePlaneTracks(fd, clip, &object->plane_tracks);
}
@@ -7648,16 +7793,12 @@ static void lib_link_mask_parent(FileData *fd, Mask *mask, MaskParent *parent)
static void lib_link_mask(FileData *fd, Main *main)
{
- Mask *mask;
-
- mask = main->mask.first;
- while (mask) {
+ for (Mask *mask = main->mask.first; mask; mask = mask->id.next) {
if (mask->id.tag & LIB_TAG_NEED_LINK) {
- MaskLayer *masklay;
-
+ IDP_LibLinkProperty(mask->id.properties, fd);
lib_link_animdata(fd, &mask->id, mask->adt);
- for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
+ for (MaskLayer *masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
MaskSpline *spline;
spline = masklay->splines.first;
@@ -7678,7 +7819,6 @@ static void lib_link_mask(FileData *fd, Main *main)
mask->id.tag &= ~LIB_TAG_NEED_LINK;
}
- mask = mask->id.next;
}
}
@@ -7686,18 +7826,13 @@ static void lib_link_mask(FileData *fd, Main *main)
static void lib_link_linestyle(FileData *fd, Main *main)
{
- FreestyleLineStyle *linestyle;
- LineStyleModifier *m;
- MTex *mtex;
- int a;
-
- linestyle = main->linestyle.first;
- while (linestyle) {
+ for (FreestyleLineStyle *linestyle = main->linestyle.first; linestyle; linestyle = linestyle->id.next) {
if (linestyle->id.tag & LIB_TAG_NEED_LINK) {
- linestyle->id.tag &= ~LIB_TAG_NEED_LINK;
+ LineStyleModifier *m;
- IDP_LibLinkProperty(linestyle->id.properties, (fd->flags & FD_FLAGS_SWITCH_ENDIAN), fd);
+ IDP_LibLinkProperty(linestyle->id.properties, fd);
lib_link_animdata(fd, &linestyle->id, linestyle->adt);
+
for (m = linestyle->color_modifiers.first; m; m = m->next) {
switch (m->type) {
case LS_MODIFIER_DISTANCE_FROM_OBJECT:
@@ -7728,8 +7863,8 @@ static void lib_link_linestyle(FileData *fd, Main *main)
break;
}
}
- for (a=0; a < MAX_MTEX; a++) {
- mtex = linestyle->mtex[a];
+ for (int a = 0; a < MAX_MTEX; a++) {
+ MTex *mtex = linestyle->mtex[a];
if (mtex) {
mtex->tex = newlibadr_us(fd, linestyle->id.lib, mtex->tex);
mtex->object = newlibadr(fd, linestyle->id.lib, mtex->object);
@@ -7739,8 +7874,9 @@ static void lib_link_linestyle(FileData *fd, Main *main)
lib_link_ntree(fd, &linestyle->id, linestyle->nodetree);
linestyle->nodetree->id.lib = linestyle->id.lib;
}
+
+ linestyle->id.tag &= ~LIB_TAG_NEED_LINK;
}
- linestyle = linestyle->id.next;
}
}
@@ -7974,7 +8110,7 @@ static const char *dataname(short id_code)
case ID_WO: return "Data from WO";
case ID_SCR: return "Data from SCR";
case ID_VF: return "Data from VF";
- case ID_TXT : return "Data from TXT";
+ case ID_TXT: return "Data from TXT";
case ID_SPK: return "Data from SPK";
case ID_SO: return "Data from SO";
case ID_NT: return "Data from NT";
@@ -8037,22 +8173,16 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
if (fd->memfile && ELEM(bhead->code, ID_LI, ID_ID)) {
const char *idname = bhead_id_name(fd, bhead);
-#ifdef PRINT_DEBUG
- printf("Checking %s...\n", idname);
-#endif
+ DEBUG_PRINTF("Checking %s...\n", idname);
if (bhead->code == ID_LI) {
Main *libmain = fd->old_mainlist->first;
/* Skip oldmain itself... */
for (libmain = libmain->next; libmain; libmain = libmain->next) {
-#ifdef PRINT_DEBUG
- printf("... against %s: ", libmain->curlib ? libmain->curlib->id.name : "<NULL>");
-#endif
+ DEBUG_PRINTF("... against %s: ", libmain->curlib ? libmain->curlib->id.name : "<NULL>");
if (libmain->curlib && STREQ(idname, libmain->curlib->id.name)) {
Main *oldmain = fd->old_mainlist->first;
-#ifdef PRINT_DEBUG
- printf("FOUND!\n");
-#endif
+ DEBUG_PRINTF("FOUND!\n");
/* In case of a library, we need to re-add its main to fd->mainlist, because if we have later
* a missing ID_ID, we need to get the correct lib it is linked to!
* Order is crucial, we cannot bulk-add it in BLO_read_from_memfile() like it used to be... */
@@ -8066,19 +8196,13 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
}
return blo_nextbhead(fd, bhead);
}
-#ifdef PRINT_DEBUG
- printf("nothing...\n");
-#endif
+ DEBUG_PRINTF("nothing...\n");
}
}
else {
-#ifdef PRINT_DEBUG
- printf("... in %s (%s): ", main->curlib ? main->curlib->id.name : "<NULL>", main->curlib ? main->curlib->name : "<NULL>");
-#endif
+ DEBUG_PRINTF("... in %s (%s): ", main->curlib ? main->curlib->id.name : "<NULL>", main->curlib ? main->curlib->name : "<NULL>");
if ((id = BKE_libblock_find_name_ex(main, GS(idname), idname + 2))) {
-#ifdef PRINT_DEBUG
- printf("FOUND!\n");
-#endif
+ DEBUG_PRINTF("FOUND!\n");
/* Even though we found our linked ID, there is no guarantee its address is still the same... */
if (id != bhead->old) {
oldnewmap_insert(fd->libmap, bhead->old, id, GS(id->name));
@@ -8090,9 +8214,7 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
}
return blo_nextbhead(fd, bhead);
}
-#ifdef PRINT_DEBUG
- printf("nothing...\n");
-#endif
+ DEBUG_PRINTF("nothing...\n");
}
}
@@ -8100,7 +8222,7 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
id = read_struct(fd, bhead, "lib block");
if (id) {
- const short idcode = (bhead->code == ID_ID) ? GS(id->name) : bhead->code;
+ const short idcode = GS(id->name);
/* do after read_struct, for dna reconstruct */
lb = which_libbase(main, idcode);
if (lb) {
@@ -8120,20 +8242,20 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
if (!id)
return blo_nextbhead(fd, bhead);
- id->tag = tag | LIB_TAG_NEED_LINK;
id->lib = main->curlib;
id->us = ID_FAKE_USERS(id);
id->icon_id = 0;
id->newid = NULL; /* Needed because .blend may have been saved with crap value here... */
+ id->recalc = 0;
/* this case cannot be direct_linked: it's just the ID part */
if (bhead->code == ID_ID) {
+ /* That way, we know which datablock needs do_versions (required currently for linking). */
+ id->tag = tag | LIB_TAG_NEED_LINK | LIB_TAG_NEW;
+
return blo_nextbhead(fd, bhead);
}
- /* That way, we know which datablock needs do_versions (required currently for linking). */
- id->tag |= LIB_TAG_NEW;
-
/* need a name for the mallocN, just for debugging and sane prints on leaks */
allocname = dataname(GS(id->name));
@@ -8142,7 +8264,11 @@ static BHead *read_libblock(FileData *fd, Main *main, BHead *bhead, const short
/* init pointers direct data */
direct_link_id(fd, id);
-
+
+ /* That way, we know which datablock needs do_versions (required currently for linking). */
+ /* Note: doing this after driect_link_id(), which resets that field. */
+ id->tag = tag | LIB_TAG_NEED_LINK | LIB_TAG_NEW;
+
switch (GS(id->name)) {
case ID_WM:
direct_link_windowmanager(fd, (wmWindowManager *)id);
@@ -8411,12 +8537,13 @@ static void lib_link_all(FileData *fd, Main *main)
lib_link_screen(fd, main);
lib_link_scene(fd, main);
lib_link_object(fd, main);
+ lib_link_mesh(fd, main);
lib_link_curve(fd, main);
lib_link_mball(fd, main);
lib_link_material(fd, main);
lib_link_texture(fd, main);
lib_link_image(fd, main);
- lib_link_ipo(fd, main); // XXX deprecated... still needs to be maintained for version patches still
+ lib_link_ipo(fd, main); /* XXX deprecated... still needs to be maintained for version patches still */
lib_link_key(fd, main);
lib_link_world(fd, main);
lib_link_lamp(fd, main);
@@ -8429,7 +8556,7 @@ static void lib_link_all(FileData *fd, Main *main)
lib_link_armature(fd, main);
lib_link_action(fd, main);
lib_link_vfont(fd, main);
- lib_link_nodetree(fd, main); /* has to be done after scene/materials, this will verify group nodes */
+ lib_link_nodetree(fd, main); /* has to be done after scene/materials, this will verify group nodes */
lib_link_brush(fd, main);
lib_link_palette(fd, main);
lib_link_paint_curve(fd, main);
@@ -8440,9 +8567,7 @@ static void lib_link_all(FileData *fd, Main *main)
lib_link_gpencil(fd, main);
lib_link_cachefiles(fd, main);
- lib_link_mesh(fd, main); /* as last: tpage images with users at zero */
-
- lib_link_library(fd, main); /* only init users */
+ lib_link_library(fd, main); /* only init users */
}
static void direct_link_keymapitem(FileData *fd, wmKeyMapItem *kmi)
@@ -8543,14 +8668,20 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
const int *data = read_file_thumbnail(fd);
if (data) {
- const size_t sz = BLEN_THUMB_MEMSIZE(data[0], data[1]);
- bfd->main->blen_thumb = MEM_mallocN(sz, __func__);
+ int width = data[0];
+ int height = data[1];
- BLI_assert((sz - sizeof(*bfd->main->blen_thumb)) ==
- (BLEN_THUMB_MEMSIZE_FILE(data[0], data[1]) - (sizeof(*data) * 2)));
- bfd->main->blen_thumb->width = data[0];
- bfd->main->blen_thumb->height = data[1];
- memcpy(bfd->main->blen_thumb->rect, &data[2], sz - sizeof(*bfd->main->blen_thumb));
+ /* Protect against buffer overflow vulnerability. */
+ if (BLEN_THUMB_SAFE_MEMSIZE(width, height)) {
+ const size_t sz = BLEN_THUMB_MEMSIZE(width, height);
+ bfd->main->blen_thumb = MEM_mallocN(sz, __func__);
+
+ BLI_assert((sz - sizeof(*bfd->main->blen_thumb)) ==
+ (BLEN_THUMB_MEMSIZE_FILE(width, height) - (sizeof(*data) * 2)));
+ bfd->main->blen_thumb->width = width;
+ bfd->main->blen_thumb->height = height;
+ memcpy(bfd->main->blen_thumb->rect, &data[2], sz - sizeof(*bfd->main->blen_thumb));
+ }
}
}
@@ -8566,7 +8697,12 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
bhead = read_global(bfd, fd, bhead);
break;
case USER:
- bhead = read_userdef(bfd, fd, bhead);
+ if (fd->skip_flags & BLO_READ_SKIP_USERDEF) {
+ bhead = blo_nextbhead(fd, bhead);
+ }
+ else {
+ bhead = read_userdef(bfd, fd, bhead);
+ }
break;
case ENDB:
bhead = NULL;
@@ -8575,15 +8711,25 @@ BlendFileData *blo_read_file_internal(FileData *fd, const char *filepath)
case ID_ID:
/* Always adds to the most recently loaded ID_LI block, see direct_link_library.
* This is part of the file format definition. */
- bhead = read_libblock(fd, mainlist.last, bhead, LIB_TAG_READ | LIB_TAG_EXTERN, NULL);
+ if (fd->skip_flags & BLO_READ_SKIP_DATA) {
+ bhead = blo_nextbhead(fd, bhead);
+ }
+ else {
+ bhead = read_libblock(fd, mainlist.last, bhead, LIB_TAG_READ | LIB_TAG_EXTERN, NULL);
+ }
break;
-
/* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
case ID_SCRN:
bhead->code = ID_SCR;
- /* deliberate pass on to default */
+ /* pass on to default */
+ ATTR_FALLTHROUGH;
default:
- bhead = read_libblock(fd, bfd->main, bhead, LIB_TAG_LOCAL, NULL);
+ if (fd->skip_flags & BLO_READ_SKIP_DATA) {
+ bhead = blo_nextbhead(fd, bhead);
+ }
+ else {
+ bhead = read_libblock(fd, bfd->main, bhead, LIB_TAG_LOCAL, NULL);
+ }
}
}
@@ -8650,7 +8796,7 @@ static void sort_bhead_old_map(FileData *fd)
fd->tot_bheadmap = tot;
if (tot == 0) return;
- bhs = fd->bheadmap = MEM_mallocN(tot * sizeof(struct BHeadSort), "BHeadSort");
+ bhs = fd->bheadmap = MEM_malloc_arrayN(tot, sizeof(struct BHeadSort), "BHeadSort");
for (bhead = blo_firstbhead(fd); bhead; bhead = blo_nextbhead(fd, bhead), bhs++) {
bhs->bhead = bhead;
@@ -8848,6 +8994,31 @@ static void expand_constraint_channels(FileData *fd, Main *mainvar, ListBase *ch
}
}
+static void expand_idprops(FileData *fd, Main *mainvar, IDProperty *prop)
+{
+ if (!prop)
+ return;
+
+ switch (prop->type) {
+ case IDP_ID:
+ expand_doit(fd, mainvar, IDP_Id(prop));
+ break;
+ case IDP_IDPARRAY:
+ {
+ IDProperty *idp_array = IDP_IDPArray(prop);
+ for (int i = 0; i < prop->len; i++) {
+ expand_idprops(fd, mainvar, &idp_array[i]);
+ }
+ break;
+ }
+ case IDP_GROUP:
+ for (IDProperty *loop = prop->data.group.first; loop; loop = loop->next) {
+ expand_idprops(fd, mainvar, loop);
+ }
+ break;
+ }
+}
+
static void expand_fmodifiers(FileData *fd, Main *mainvar, ListBase *list)
{
FModifier *fcm;
@@ -9033,6 +9204,7 @@ static void expand_key(FileData *fd, Main *mainvar, Key *key)
static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree)
{
bNode *node;
+ bNodeSocket *sock;
if (ntree->adt)
expand_animdata(fd, mainvar, ntree->adt);
@@ -9041,10 +9213,22 @@ static void expand_nodetree(FileData *fd, Main *mainvar, bNodeTree *ntree)
expand_doit(fd, mainvar, ntree->gpd);
for (node = ntree->nodes.first; node; node = node->next) {
- if (node->id && node->type != CMP_NODE_R_LAYERS)
+ if (node->id && node->type != CMP_NODE_R_LAYERS) {
expand_doit(fd, mainvar, node->id);
+ }
+
+ expand_idprops(fd, mainvar, node->prop);
+
+ for (sock = node->inputs.first; sock; sock = sock->next)
+ expand_idprops(fd, mainvar, sock->prop);
+ for (sock = node->outputs.first; sock; sock = sock->next)
+ expand_idprops(fd, mainvar, sock->prop);
}
+ for (sock = ntree->inputs.first; sock; sock = sock->next)
+ expand_idprops(fd, mainvar, sock->prop);
+ for (sock = ntree->outputs.first; sock; sock = sock->next)
+ expand_idprops(fd, mainvar, sock->prop);
}
static void expand_texture(FileData *fd, Main *mainvar, Tex *tex)
@@ -9262,17 +9446,6 @@ static void expand_constraints(FileData *fd, Main *mainvar, ListBase *lb)
}
}
-#if 0 /* Disabled as it doesn't actually do anything except recurse... */
-static void expand_bones(FileData *fd, Main *mainvar, Bone *bone)
-{
- Bone *curBone;
-
- for (curBone = bone->childbase.first; curBone; curBone=curBone->next) {
- expand_bones(fd, mainvar, curBone);
- }
-}
-#endif
-
static void expand_pose(FileData *fd, Main *mainvar, bPose *pose)
{
bPoseChannel *chan;
@@ -9282,24 +9455,28 @@ static void expand_pose(FileData *fd, Main *mainvar, bPose *pose)
for (chan = pose->chanbase.first; chan; chan = chan->next) {
expand_constraints(fd, mainvar, &chan->constraints);
+ expand_idprops(fd, mainvar, chan->prop);
expand_doit(fd, mainvar, chan->custom);
}
}
+static void expand_bones(FileData *fd, Main *mainvar, Bone *bone)
+{
+ expand_idprops(fd, mainvar, bone->prop);
+
+ for (Bone *curBone = bone->childbase.first; curBone; curBone = curBone->next) {
+ expand_bones(fd, mainvar, curBone);
+ }
+}
+
static void expand_armature(FileData *fd, Main *mainvar, bArmature *arm)
-{
+{
if (arm->adt)
expand_animdata(fd, mainvar, arm->adt);
-
-#if 0 /* Disabled as this currently only recurses down the chain doing nothing */
- {
- Bone *curBone;
-
- for (curBone = arm->bonebase.first; curBone; curBone=curBone->next) {
- expand_bones(fd, mainvar, curBone);
- }
+
+ for (Bone *curBone = arm->bonebase.first; curBone; curBone = curBone->next) {
+ expand_bones(fd, mainvar, curBone);
}
-#endif
}
static void expand_object_expandModifiers(
@@ -9527,6 +9704,8 @@ static void expand_scene(FileData *fd, Main *mainvar, Scene *sce)
SEQ_BEGIN (sce->ed, seq)
{
+ expand_idprops(fd, mainvar, seq->prop);
+
if (seq->scene) expand_doit(fd, mainvar, seq->scene);
if (seq->scene_camera) expand_doit(fd, mainvar, seq->scene_camera);
if (seq->clip) expand_doit(fd, mainvar, seq->clip);
@@ -9684,6 +9863,8 @@ void BLO_expand_main(void *fdhandle, Main *mainvar)
id = lbarray[a]->first;
while (id) {
if (id->tag & LIB_TAG_NEED_EXPAND) {
+ expand_idprops(fd, mainvar, id->properties);
+
switch (GS(id->name)) {
case ID_OB:
expand_object(fd, mainvar, (Object *)id);
@@ -9763,6 +9944,8 @@ void BLO_expand_main(void *fdhandle, Main *mainvar)
case ID_CF:
expand_cachefile(fd, mainvar, (CacheFile *)id);
break;
+ default:
+ break;
}
do_it = true;
@@ -9823,7 +10006,7 @@ static void give_base_to_objects(Main *mainvar, Scene *scene, View3D *v3d, Libra
}
if (flag & FILE_AUTOSELECT) {
/* Note that link_object_postprocess() already checks for FILE_AUTOSELECT flag,
- * but it will miss objects from non-instanciated groups... */
+ * but it will miss objects from non-instantiated groups... */
ob->flag |= SELECT;
/* do NOT make base active here! screws up GUI stuff, if you want it do it on src/ level */
}
@@ -9898,12 +10081,14 @@ static ID *create_placeholder(Main *mainvar, const short idcode, const char *idn
/* returns true if the item was found
* but it may already have already been appended/linked */
static ID *link_named_part(
- Main *mainl, FileData *fd, const short idcode, const char *name,
- const bool use_placeholders, const bool force_indirect)
+ Main *mainl, FileData *fd, const short idcode, const char *name, const int flag)
{
BHead *bhead = find_bhead_from_code_name(fd, idcode, name);
ID *id;
+ const bool use_placeholders = (flag & BLO_LIBLINK_USE_PLACEHOLDERS) != 0;
+ const bool force_indirect = (flag & BLO_LIBLINK_FORCE_INDIRECT) != 0;
+
BLI_assert(BKE_idcode_is_linkable(idcode) && BKE_idcode_is_valid(idcode));
if (bhead) {
@@ -9943,7 +10128,7 @@ static ID *link_named_part(
return id;
}
-static void link_object_postprocess(ID *id, Scene *scene, View3D *v3d, const short flag)
+static void link_object_postprocess(ID *id, Scene *scene, View3D *v3d, const int flag)
{
if (scene) {
Base *base;
@@ -10009,10 +10194,10 @@ void BLO_library_link_copypaste(Main *mainl, BlendHandle *bh)
}
static ID *link_named_part_ex(
- Main *mainl, FileData *fd, const short idcode, const char *name, const short flag,
- Scene *scene, View3D *v3d, const bool use_placeholders, const bool force_indirect)
+ Main *mainl, FileData *fd, const short idcode, const char *name, const int flag,
+ Scene *scene, View3D *v3d)
{
- ID *id = link_named_part(mainl, fd, idcode, name, use_placeholders, force_indirect);
+ ID *id = link_named_part(mainl, fd, idcode, name, flag);
if (id && (GS(id->name) == ID_OB)) { /* loose object: give a base */
link_object_postprocess(id, scene, v3d, flag);
@@ -10038,7 +10223,7 @@ static ID *link_named_part_ex(
ID *BLO_library_link_named_part(Main *mainl, BlendHandle **bh, const short idcode, const char *name)
{
FileData *fd = (FileData*)(*bh);
- return link_named_part(mainl, fd, idcode, name, false, false);
+ return link_named_part(mainl, fd, idcode, name, 0);
}
/**
@@ -10052,18 +10237,15 @@ ID *BLO_library_link_named_part(Main *mainl, BlendHandle **bh, const short idcod
* \param flag Options for linking, used for instantiating.
* \param scene The scene in which to instantiate objects/groups (if NULL, no instantiation is done).
* \param v3d The active View3D (only to define active layers for instantiated objects & groups, can be NULL).
- * \param use_placeholders If true, generate a placeholder (empty ID) if not found in current lib file.
- * \param force_indirect If true, force loaded ID to be tagged as LIB_TAG_INDIRECT (used in reload context only).
* \return the linked ID when found.
*/
ID *BLO_library_link_named_part_ex(
Main *mainl, BlendHandle **bh,
- const short idcode, const char *name, const short flag,
- Scene *scene, View3D *v3d,
- const bool use_placeholders, const bool force_indirect)
+ const short idcode, const char *name, const int flag,
+ Scene *scene, View3D *v3d)
{
FileData *fd = (FileData*)(*bh);
- return link_named_part_ex(mainl, fd, idcode, name, flag, scene, v3d, use_placeholders, force_indirect);
+ return link_named_part_ex(mainl, fd, idcode, name, flag, scene, v3d);
}
static void link_id_part(ReportList *reports, FileData *fd, Main *mainvar, ID *id, ID **r_id)
@@ -10300,6 +10482,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
Main *mainl = mainlist->first;
Main *mainptr;
ListBase *lbarray[MAX_LIBARRAY];
+ GHash *loaded_ids = BLI_ghash_str_new(__func__);
int a;
bool do_it = true;
@@ -10313,7 +10496,7 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
mainptr= mainl->next;
while (mainptr) {
if (mainvar_id_tag_any_check(mainptr, LIB_TAG_READ)) {
- // printf("found LIB_TAG_READ %s\n", mainptr->curlib->name);
+ // printf("found LIB_TAG_READ %s (%s)\n", mainptr->curlib->id.name, mainptr->curlib->name);
FileData *fd = mainptr->curlib->filedata;
@@ -10411,25 +10594,38 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
a = set_listbasepointers(mainptr, lbarray);
while (a--) {
ID *id = lbarray[a]->first;
+ ListBase pending_free_ids = {NULL};
while (id) {
ID *idn = id->next;
if (id->tag & LIB_TAG_READ) {
- ID *realid = NULL;
BLI_remlink(lbarray[a], id);
- link_id_part(basefd->reports, fd, mainptr, id, &realid);
+ /* When playing with lib renaming and such, you may end with cases where you have
+ * more than one linked ID of the same data-block from same library.
+ * This is absolutely horrible, hence we use a ghash to ensure we go back to a single
+ * linked data when loading the file... */
+ ID **realid = NULL;
+ if (!BLI_ghash_ensure_p(loaded_ids, id->name, (void ***)&realid)) {
+ link_id_part(basefd->reports, fd, mainptr, id, realid);
+ }
/* realid shall never be NULL - unless some source file/lib is broken
* (known case: some directly linked shapekey from a missing lib...). */
- /* BLI_assert(realid != NULL); */
+ /* BLI_assert(*realid != NULL); */
- change_idid_adr(mainlist, basefd, id, realid);
+ change_idid_adr(mainlist, basefd, id, *realid);
- MEM_freeN(id);
+ /* We cannot free old lib-ref placeholder ID here anymore, since we use its name
+ * as key in loaded_ids hass. */
+ BLI_addtail(&pending_free_ids, id);
}
id = idn;
}
+
+ /* Clear GHash and free all lib-ref placeholders IDs of that type now. */
+ BLI_ghash_clear(loaded_ids, NULL, NULL);
+ BLI_freelistN(&pending_free_ids);
}
BLO_expand_main(fd, mainptr);
}
@@ -10437,7 +10633,10 @@ static void read_libraries(FileData *basefd, ListBase *mainlist)
mainptr = mainptr->next;
}
}
-
+
+ BLI_ghash_free(loaded_ids, NULL, NULL);
+ loaded_ids = NULL;
+
/* test if there are unread libblocks */
/* XXX This code block is kept for 2.77, until we are sure it never gets reached anymore. Can be removed later. */
for (mainptr = mainl->next; mainptr; mainptr = mainptr->next) {
diff --git a/source/blender/blenloader/intern/readfile.h b/source/blender/blenloader/intern/readfile.h
index d97bef13a78..62ce15a640e 100644
--- a/source/blender/blenloader/intern/readfile.h
+++ b/source/blender/blenloader/intern/readfile.h
@@ -81,6 +81,8 @@ typedef struct FileData {
int id_name_offs; /* used to retrieve ID names from (bhead+1) */
int globalf, fileflags; /* for do_versions patching */
+ eBLOReadSkip skip_flags; /* skip some data-blocks */
+
struct OldNewMap *datamap;
struct OldNewMap *globmap;
struct OldNewMap *libmap;
diff --git a/source/blender/blenloader/intern/undofile.c b/source/blender/blenloader/intern/undofile.c
index c191e48a143..7133dee0e82 100644
--- a/source/blender/blenloader/intern/undofile.c
+++ b/source/blender/blenloader/intern/undofile.c
@@ -34,6 +34,15 @@
#include <string.h>
#include <stdio.h>
#include <math.h>
+#include <fcntl.h>
+#include <errno.h>
+
+/* open/close */
+#ifndef _WIN32
+# include <unistd.h>
+#else
+# include <io.h>
+#endif
#include "MEM_guardedalloc.h"
@@ -42,6 +51,12 @@
#include "BLI_blenlib.h"
#include "BLO_undofile.h"
+#include "BLO_readfile.h"
+
+#include "BKE_main.h"
+
+/* keep last */
+#include "BLI_strict_flags.h"
/* **************** support for memory-write, for undo buffers *************** */
@@ -51,8 +66,9 @@ void BLO_memfile_free(MemFile *memfile)
MemFileChunk *chunk;
while ((chunk = BLI_pophead(&memfile->chunks))) {
- if (chunk->ident == 0)
- MEM_freeN(chunk->buf);
+ if (chunk->is_identical == false) {
+ MEM_freeN((void *)chunk->buf);
+ }
MEM_freeN(chunk);
}
memfile->size = 0;
@@ -68,9 +84,9 @@ void BLO_memfile_merge(MemFile *first, MemFile *second)
sc = second->chunks.first;
while (fc || sc) {
if (fc && sc) {
- if (sc->ident) {
- sc->ident = 0;
- fc->ident = 1;
+ if (sc->is_identical) {
+ sc->is_identical = false;
+ fc->is_identical = true;
}
}
if (fc) fc = fc->next;
@@ -80,43 +96,99 @@ void BLO_memfile_merge(MemFile *first, MemFile *second)
BLO_memfile_free(first);
}
-void memfile_chunk_add(MemFile *compare, MemFile *current, const char *buf, unsigned int size)
+void memfile_chunk_add(
+ MemFile *memfile, const char *buf, unsigned int size,
+ MemFileChunk **compchunk_step)
{
- static MemFileChunk *compchunk = NULL;
- MemFileChunk *curchunk;
-
- /* this function inits when compare != NULL or when current == NULL */
- if (compare) {
- compchunk = compare->chunks.first;
- return;
- }
- if (current == NULL) {
- compchunk = NULL;
- return;
- }
-
- curchunk = MEM_mallocN(sizeof(MemFileChunk), "MemFileChunk");
+ MemFileChunk *curchunk = MEM_mallocN(sizeof(MemFileChunk), "MemFileChunk");
curchunk->size = size;
curchunk->buf = NULL;
- curchunk->ident = 0;
- BLI_addtail(&current->chunks, curchunk);
-
+ curchunk->is_identical = false;
+ BLI_addtail(&memfile->chunks, curchunk);
+
/* we compare compchunk with buf */
- if (compchunk) {
+ if (*compchunk_step != NULL) {
+ MemFileChunk *compchunk = *compchunk_step;
if (compchunk->size == curchunk->size) {
if (memcmp(compchunk->buf, buf, size) == 0) {
curchunk->buf = compchunk->buf;
- curchunk->ident = 1;
+ curchunk->is_identical = true;
}
}
- compchunk = compchunk->next;
+ *compchunk_step = compchunk->next;
}
-
+
/* not equal... */
if (curchunk->buf == NULL) {
- curchunk->buf = MEM_mallocN(size, "Chunk buffer");
- memcpy(curchunk->buf, buf, size);
- current->size += size;
+ char *buf_new = MEM_mallocN(size, "Chunk buffer");
+ memcpy(buf_new, buf, size);
+ curchunk->buf = buf_new;
+ memfile->size += size;
+ }
+}
+
+struct Main *BLO_memfile_main_get(struct MemFile *memfile, struct Main *oldmain, struct Scene **r_scene)
+{
+ struct Main *bmain_undo = NULL;
+ BlendFileData *bfd = BLO_read_from_memfile(oldmain, oldmain->name, memfile, NULL, BLO_READ_SKIP_NONE);
+
+ if (bfd) {
+ bmain_undo = bfd->main;
+ if (r_scene) {
+ *r_scene = bfd->curscene;
+ }
+
+ MEM_freeN(bfd);
}
+
+ return bmain_undo;
}
+
+/**
+ * Saves .blend using undo buffer.
+ *
+ * \return success.
+ */
+bool BLO_memfile_write_file(struct MemFile *memfile, const char *filename)
+{
+ MemFileChunk *chunk;
+ int file, oflags;
+
+ /* note: This is currently used for autosave and 'quit.blend', where _not_ following symlinks is OK,
+ * however if this is ever executed explicitly by the user, we may want to allow writing to symlinks.
+ */
+
+ oflags = O_BINARY | O_WRONLY | O_CREAT | O_TRUNC;
+#ifdef O_NOFOLLOW
+ /* use O_NOFOLLOW to avoid writing to a symlink - use 'O_EXCL' (CVE-2008-1103) */
+ oflags |= O_NOFOLLOW;
+#else
+ /* TODO(sergey): How to deal with symlinks on windows? */
+# ifndef _MSC_VER
+# warning "Symbolic links will be followed on undo save, possibly causing CVE-2008-1103"
+# endif
+#endif
+ file = BLI_open(filename, oflags, 0666);
+
+ if (file == -1) {
+ fprintf(stderr, "Unable to save '%s': %s\n",
+ filename, errno ? strerror(errno) : "Unknown error opening file");
+ return false;
+ }
+
+ for (chunk = memfile->chunks.first; chunk; chunk = chunk->next) {
+ if ((size_t)write(file, chunk->buf, chunk->size) != chunk->size) {
+ break;
+ }
+ }
+
+ close(file);
+
+ if (chunk) {
+ fprintf(stderr, "Unable to save '%s': %s\n",
+ filename, errno ? strerror(errno) : "Unknown error writing file");
+ return false;
+ }
+ return true;
+}
diff --git a/source/blender/blenloader/intern/versioning_250.c b/source/blender/blenloader/intern/versioning_250.c
index 1956a17d57b..d308bd54da3 100644
--- a/source/blender/blenloader/intern/versioning_250.c
+++ b/source/blender/blenloader/intern/versioning_250.c
@@ -52,7 +52,7 @@
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_node_types.h"
-#include "DNA_object_fluidsim.h" // NT
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "DNA_view3d_types.h"
#include "DNA_screen_types.h"
@@ -951,7 +951,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
if (ob->totcol && ob->matbits == NULL) {
int a;
- ob->matbits = MEM_callocN(sizeof(char)*ob->totcol, "ob->matbits");
+ ob->matbits = MEM_calloc_arrayN(ob->totcol, sizeof(char), "ob->matbits");
for (a = 0; a < ob->totcol; a++)
ob->matbits[a] = (ob->colbits & (1<<a)) != 0;
}
@@ -1785,7 +1785,7 @@ void blo_do_versions_250(FileData *fd, Library *lib, Main *main)
ParticleEditSettings *pset = &sce->toolsettings->particle;
int a;
- for (a = 0; a < PE_TOT_BRUSH; a++)
+ for (a = 0; a < ARRAY_SIZE(pset->brush); a++)
pset->brush[a].strength /= 100.0f;
}
diff --git a/source/blender/blenloader/intern/versioning_260.c b/source/blender/blenloader/intern/versioning_260.c
index 4a856feaa1a..b93d1aa47da 100644
--- a/source/blender/blenloader/intern/versioning_260.c
+++ b/source/blender/blenloader/intern/versioning_260.c
@@ -41,7 +41,7 @@
#include "DNA_linestyle_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "DNA_object_fluidsim.h" // NT
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "DNA_property_types.h"
#include "DNA_text_types.h"
@@ -944,7 +944,7 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main)
}
}
{
- /* Warn the user if he is using ["Text"] properties for Font objects */
+ /* Warn the user if he is using ["Text"] properties for Font objects */
Object *ob;
bProperty *prop;
@@ -1000,7 +1000,7 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main)
{
/* convert extended ascii to utf-8 for text editor */
Text *text;
- for (text = main->text.first; text; text = text->id.next)
+ for (text = main->text.first; text; text = text->id.next) {
if (!(text->flags & TXT_ISEXT)) {
TextLine *tl;
@@ -1013,6 +1013,7 @@ void blo_do_versions_260(FileData *fd, Library *UNUSED(lib), Main *main)
text->curc = 0;
}
}
+ }
}
{
/* set new dynamic paint values */
diff --git a/source/blender/blenloader/intern/versioning_270.c b/source/blender/blenloader/intern/versioning_270.c
index 7106cf60721..86e6071180e 100644
--- a/source/blender/blenloader/intern/versioning_270.c
+++ b/source/blender/blenloader/intern/versioning_270.c
@@ -45,7 +45,7 @@
#include "DNA_sequence_types.h"
#include "DNA_space_types.h"
#include "DNA_screen_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_mask_types.h"
#include "DNA_mesh_types.h"
@@ -60,7 +60,10 @@
#include "DNA_genfile.h"
#include "BKE_animsys.h"
+#include "BKE_brush.h"
#include "BKE_colortools.h"
+#include "BKE_fcurve.h"
+#include "BKE_gpencil.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_mask.h"
@@ -70,7 +73,6 @@
#include "BKE_sequencer.h"
#include "BKE_screen.h"
#include "BKE_tracking.h"
-#include "BKE_gpencil.h"
#include "BLI_math.h"
#include "BLI_listbase.h"
@@ -80,6 +82,7 @@
#include "NOD_common.h"
#include "NOD_socket.h"
+#include "NOD_composite.h"
#include "readfile.h"
@@ -248,6 +251,102 @@ static void do_version_hue_sat_node(bNodeTree *ntree, bNode *node)
node->storage = NULL;
}
+static void do_versions_compositor_render_passes_storage(bNode *node)
+{
+ int pass_index = 0;
+ const char *sockname;
+ for (bNodeSocket *sock = node->outputs.first; sock && pass_index < 31; sock = sock->next, pass_index++) {
+ if (sock->storage == NULL) {
+ NodeImageLayer *sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
+ sock->storage = sockdata;
+ BLI_strncpy(sockdata->pass_name, node_cmp_rlayers_sock_to_pass(pass_index), sizeof(sockdata->pass_name));
+
+ if (pass_index == 0) sockname = "Image";
+ else if (pass_index == 1) sockname = "Alpha";
+ else sockname = node_cmp_rlayers_sock_to_pass(pass_index);
+ BLI_strncpy(sock->name, sockname, sizeof(sock->name));
+ }
+ }
+}
+
+static void do_versions_compositor_render_passes(bNodeTree *ntree)
+{
+ for (bNode *node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == CMP_NODE_R_LAYERS) {
+ /* First we make sure existing sockets have proper names.
+ * This is important because otherwise verification will
+ * drop links from sockets which were renamed.
+ */
+ do_versions_compositor_render_passes_storage(node);
+ /* Make sure new sockets are properly created. */
+ node_verify_socket_templates(ntree, node);
+ /* Make sure all possibly created sockets have proper storage. */
+ do_versions_compositor_render_passes_storage(node);
+ }
+ }
+}
+
+
+static char *replace_bbone_easing_rnapath(char *old_path)
+{
+ char *new_path = NULL;
+
+ /* NOTE: This will break paths for any bones/custom-properties
+ * which happen be named after the bbone property id's
+ */
+ if (strstr(old_path, "bbone_in"))
+ new_path = BLI_str_replaceN(old_path, "bbone_in", "bbone_easein");
+ else if (strstr(old_path, "bbone_out"))
+ new_path = BLI_str_replaceN(old_path, "bbone_out", "bbone_easeout");
+
+ if (new_path) {
+ MEM_freeN(old_path);
+ return new_path;
+ }
+ else {
+ return old_path;
+ }
+}
+
+static void do_version_bbone_easing_fcurve_fix(ID *UNUSED(id), FCurve *fcu, void *UNUSED(user_data))
+{
+ /* F-Curve's path (for bbone_in/out) */
+ if (fcu->rna_path) {
+ fcu->rna_path = replace_bbone_easing_rnapath(fcu->rna_path);
+ }
+
+ /* Driver -> Driver Vars (for bbone_in/out) */
+ if (fcu->driver) {
+ for (DriverVar *dvar = fcu->driver->variables.first; dvar; dvar = dvar->next) {
+ DRIVER_TARGETS_LOOPER(dvar)
+ {
+ if (dtar->rna_path) {
+ dtar->rna_path = replace_bbone_easing_rnapath(dtar->rna_path);
+ }
+ }
+ DRIVER_TARGETS_LOOPER_END;
+ }
+ }
+
+ /* FModifiers -> Stepped (for frame_start/end) */
+ if (fcu->modifiers.first) {
+ for (FModifier *fcm = fcu->modifiers.first; fcm; fcm = fcm->next) {
+ if (fcm->type == FMODIFIER_TYPE_STEPPED) {
+ FMod_Stepped *data = fcm->data;
+
+ /* Modifier doesn't work if the modifier's copy of start/end frame are both 0
+ * as those were only getting written to the fcm->data copy (T52009)
+ */
+ if ((fcm->sfra == fcm->efra) && (fcm->sfra == 0)) {
+ fcm->sfra = data->start_frame;
+ fcm->efra = data->end_frame;
+ }
+ }
+ }
+ }
+}
+
+
void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
{
if (!MAIN_VERSION_ATLEAST(main, 270, 0)) {
@@ -1144,7 +1243,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
if (!MAIN_VERSION_ATLEAST(main, 277, 1)) {
for (Scene *scene = main->scene.first; scene; scene = scene->id.next) {
ParticleEditSettings *pset = &scene->toolsettings->particle;
- for (int a = 0; a < PE_TOT_BRUSH; a++) {
+ for (int a = 0; a < ARRAY_SIZE(pset->brush); a++) {
if (pset->brush[a].strength > 1.0f) {
pset->brush[a].strength *= 0.01f;
}
@@ -1200,12 +1299,19 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
SEQ_BEGIN (scene->ed, seq)
{
- if (seq->type == SEQ_TYPE_TEXT) {
- TextVars *data = seq->effectdata;
- if (data->color[3] == 0.0f) {
- copy_v4_fl(data->color, 1.0f);
- data->shadow_color[3] = 1.0f;
- }
+ if (seq->type != SEQ_TYPE_TEXT) {
+ continue;
+ }
+
+ if (seq->effectdata == NULL) {
+ struct SeqEffectHandle effect_handle = BKE_sequence_get_effect(seq);
+ effect_handle.init(seq);
+ }
+
+ TextVars *data = seq->effectdata;
+ if (data->color[3] == 0.0f) {
+ copy_v4_fl(data->color, 1.0f);
+ data->shadow_color[3] = 1.0f;
}
}
SEQ_END
@@ -1259,7 +1365,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
for (Camera *camera = main->camera.first; camera != NULL; camera = camera->id.next) {
if (camera->stereo.pole_merge_angle_from == 0.0f &&
- camera->stereo.pole_merge_angle_to == 0.0f)
+ camera->stereo.pole_merge_angle_to == 0.0f)
{
camera->stereo.pole_merge_angle_from = DEG2RADF(60.0f);
camera->stereo.pole_merge_angle_to = DEG2RADF(75.0f);
@@ -1487,7 +1593,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
if (scene->toolsettings != NULL) {
ToolSettings *ts = scene->toolsettings;
ParticleEditSettings *pset = &ts->particle;
- for (int a = 0; a < PE_TOT_BRUSH; a++) {
+ for (int a = 0; a < ARRAY_SIZE(pset->brush); a++) {
if (pset->brush[a].count == 0) {
pset->brush[a].count = 10;
}
@@ -1559,8 +1665,7 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
}
}
- /* To be added to next subversion bump! */
- {
+ if (!MAIN_VERSION_ATLEAST(main, 278, 5)) {
/* Mask primitive adding code was not initializing correctly id_type of its points' parent. */
for (Mask *mask = main->mask.first; mask; mask = mask->id.next) {
for (MaskLayer *mlayer = mask->masklayers.first; mlayer; mlayer = mlayer->next) {
@@ -1598,13 +1703,135 @@ void blo_do_versions_270(FileData *fd, Library *UNUSED(lib), Main *main)
}
} FOREACH_NODETREE_END
}
+
+ if (!DNA_struct_elem_find(fd->filesdna, "SurfaceDeformModifierData", "float", "mat[4][4]")) {
+ for (Object *ob = main->object.first; ob; ob = ob->id.next) {
+ for (ModifierData *md = ob->modifiers.first; md; md = md->next) {
+ if (md->type == eModifierType_SurfaceDeform) {
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+ unit_m4(smd->mat);
+ }
+ }
+ }
+ }
+
+ FOREACH_NODETREE(main, ntree, id) {
+ if (ntree->type == NTREE_COMPOSIT) {
+ do_versions_compositor_render_passes(ntree);
+ }
+ } FOREACH_NODETREE_END
+ }
+
+ if (!MAIN_VERSION_ATLEAST(main, 279, 0)) {
+ for (Scene *scene = main->scene.first; scene; scene = scene->id.next) {
+ if (scene->r.im_format.exr_codec == R_IMF_EXR_CODEC_DWAB) {
+ scene->r.im_format.exr_codec = R_IMF_EXR_CODEC_DWAA;
+ }
+ }
+
+ /* Fix related to VGroup modifiers creating named defgroup CD layers! See T51520. */
+ for (Mesh *me = main->mesh.first; me; me = me->id.next) {
+ CustomData_set_layer_name(&me->vdata, CD_MDEFORMVERT, 0, "");
+ }
+ }
+
+ if (!MAIN_VERSION_ATLEAST(main, 279, 3)) {
+ if (!DNA_struct_elem_find(fd->filesdna, "SmokeDomainSettings", "float", "clipping")) {
+ Object *ob;
+ ModifierData *md;
+
+ for (ob = main->object.first; ob; ob = ob->id.next) {
+ for (md = ob->modifiers.first; md; md = md->next) {
+ if (md->type == eModifierType_Smoke) {
+ SmokeModifierData *smd = (SmokeModifierData *)md;
+ if (smd->domain) {
+ smd->domain->clipping = 1e-3f;
+ }
+ }
+ }
+ }
+ }
+ }
+
+ {
+ /* Fix for invalid state of screen due to bug in older versions. */
+ for (bScreen *sc = main->screen.first; sc; sc = sc->id.next) {
+ for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
+ if (sa->full && sc->state == SCREENNORMAL) {
+ sa->full = NULL;
+ }
+ }
+ }
+
+ if (!DNA_struct_elem_find(fd->filesdna, "Brush", "float", "falloff_angle")) {
+ for (Brush *br = main->brush.first; br; br = br->id.next) {
+ br->falloff_angle = DEG2RADF(80);
+ br->flag &= ~(
+ BRUSH_FLAG_DEPRECATED_1 | BRUSH_FLAG_DEPRECATED_2 |
+ BRUSH_FLAG_DEPRECATED_3 | BRUSH_FLAG_DEPRECATED_4 |
+ BRUSH_FRONTFACE_FALLOFF);
+ }
+
+ for (Scene *scene = main->scene.first; scene; scene = scene->id.next) {
+ ToolSettings *ts = scene->toolsettings;
+ for (int i = 0; i < 2; i++) {
+ VPaint *vp = i ? ts->vpaint : ts->wpaint;
+ if (vp != NULL) {
+ /* remove all other flags */
+ vp->flag &= (VP_FLAG_VGROUP_RESTRICT);
+ }
+ }
+ }
+ }
+
+ /* Simple deform modifier no longer assumes Z axis (X for bend type).
+ * Must set previous defaults. */
+ if (!DNA_struct_elem_find(fd->filesdna, "SimpleDeformModifierData", "char", "deform_axis")) {
+ for (Object *ob = main->object.first; ob; ob = ob->id.next) {
+ for (ModifierData *md = ob->modifiers.first; md; md = md->next) {
+ if (md->type == eModifierType_SimpleDeform) {
+ SimpleDeformModifierData *smd = (SimpleDeformModifierData *)md;
+ smd->deform_axis = 2;
+ }
+ }
+ }
+ }
+
+ for (Scene *scene = main->scene.first; scene; scene = scene->id.next) {
+ int preset = scene->r.ffcodecdata.ffmpeg_preset;
+ if (preset == FFM_PRESET_NONE || preset >= FFM_PRESET_GOOD) {
+ continue;
+ }
+ if (preset <= FFM_PRESET_FAST) {
+ preset = FFM_PRESET_REALTIME;
+ }
+ else if (preset >= FFM_PRESET_SLOW) {
+ preset = FFM_PRESET_BEST;
+ }
+ else {
+ preset = FFM_PRESET_GOOD;
+ }
+ scene->r.ffcodecdata.ffmpeg_preset = preset;
+ }
+
+ if (!DNA_struct_elem_find(fd->filesdna, "ParticleInstanceModifierData", "float", "particle_amount")) {
+ for (Object *ob = main->object.first; ob; ob = ob->id.next) {
+ for (ModifierData *md = ob->modifiers.first; md; md = md->next) {
+ if (md->type == eModifierType_ParticleInstance) {
+ ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
+ pimd->space = eParticleInstanceSpace_World;
+ pimd->particle_amount = 1.0f;
+ }
+ }
+ }
+ }
}
}
void do_versions_after_linking_270(Main *main)
{
/* To be added to next subversion bump! */
- {
+ if (!MAIN_VERSION_ATLEAST(main, 279, 0)) {
FOREACH_NODETREE(main, ntree, id) {
if (ntree->type == NTREE_COMPOSIT) {
ntreeSetTypes(NULL, ntree);
@@ -1616,4 +1843,10 @@ void do_versions_after_linking_270(Main *main)
}
} FOREACH_NODETREE_END
}
+
+ if (!MAIN_VERSION_ATLEAST(main, 279, 2)) {
+ /* B-Bones (bbone_in/out -> bbone_easein/out) + Stepped FMod Frame Start/End fix */
+ /* if (!DNA_struct_elem_find(fd->filesdna, "Bone", "float", "bbone_easein")) */
+ BKE_fcurves_main_cb(main, do_version_bbone_easing_fcurve_fix, NULL);
+ }
}
diff --git a/source/blender/blenloader/intern/versioning_defaults.c b/source/blender/blenloader/intern/versioning_defaults.c
index 99d9e140481..7e05ba1f529 100644
--- a/source/blender/blenloader/intern/versioning_defaults.c
+++ b/source/blender/blenloader/intern/versioning_defaults.c
@@ -54,10 +54,13 @@ void BLO_update_defaults_userpref_blend(void)
{
/* defaults from T37518 */
- U.uiflag |= USER_ZBUF_CURSOR;
+ U.uiflag |= USER_DEPTH_CURSOR;
U.uiflag |= USER_QUIT_PROMPT;
U.uiflag |= USER_CONTINUOUS_MOUSE;
+ /* See T45301 */
+ U.uiflag |= USER_LOCK_CURSOR_ADJUST;
+
U.versions = 1;
U.savetime = 2;
@@ -68,6 +71,18 @@ void BLO_update_defaults_userpref_blend(void)
* but take care since some hardware has driver bugs here (T46962).
* Further hardware workarounds should be made in gpu_extensions.c */
U.glalphaclip = (1.0f / 255);
+
+ /* default so DPI is detected automatically */
+ U.dpi = 0;
+ U.ui_scale = 1.0f;
+
+#ifdef WITH_PYTHON_SECURITY
+ /* use alternative setting for security nuts
+ * otherwise we'd need to patch the binary blob - startup.blend.c */
+ U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
+#else
+ U.flag &= ~USER_SCRIPT_AUTOEXEC_DISABLE;
+#endif
}
/**
@@ -94,6 +109,16 @@ void BLO_update_defaults_startup_blend(Main *bmain)
sculpt->detail_size = 12;
}
+ if (ts->vpaint) {
+ VPaint *vp = ts->vpaint;
+ vp->radial_symm[0] = vp->radial_symm[1] = vp->radial_symm[2] = 1;
+ }
+
+ if (ts->wpaint) {
+ VPaint *wp = ts->wpaint;
+ wp->radial_symm[0] = wp->radial_symm[1] = wp->radial_symm[2] = 1;
+ }
+
if (ts->gp_sculpt.brush[0].size == 0) {
GP_BrushEdit_Settings *gset = &ts->gp_sculpt;
GP_EditBrush_Data *brush;
@@ -145,7 +170,7 @@ void BLO_update_defaults_startup_blend(Main *bmain)
ts->gpencil_ima_align = GP_PROJECT_VIEWSPACE;
ParticleEditSettings *pset = &ts->particle;
- for (int a = 0; a < PE_TOT_BRUSH; a++) {
+ for (int a = 0; a < ARRAY_SIZE(pset->brush); a++) {
pset->brush[a].strength = 0.5f;
pset->brush[a].count = 10;
}
@@ -217,10 +242,27 @@ void BLO_update_defaults_startup_blend(Main *bmain)
br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Fill");
if (!br) {
br = BKE_brush_add(bmain, "Fill", OB_MODE_TEXTURE_PAINT);
+ id_us_min(&br->id); /* fake user only */
br->imagepaint_tool = PAINT_TOOL_FILL;
br->ob_mode = OB_MODE_TEXTURE_PAINT;
}
+ /* Vertex/Weight Paint */
+ br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Average");
+ if (!br) {
+ br = BKE_brush_add(bmain, "Average", OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT);
+ id_us_min(&br->id); /* fake user only */
+ br->vertexpaint_tool = PAINT_BLEND_AVERAGE;
+ br->ob_mode = OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT;
+ }
+ br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Smear");
+ if (!br) {
+ br = BKE_brush_add(bmain, "Smear", OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT);
+ id_us_min(&br->id); /* fake user only */
+ br->vertexpaint_tool = PAINT_BLEND_SMEAR;
+ br->ob_mode = OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT;
+ }
+
br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Mask");
if (br) {
br->imagepaint_tool = PAINT_TOOL_MASK;
@@ -230,13 +272,13 @@ void BLO_update_defaults_startup_blend(Main *bmain)
/* remove polish brush (flatten/contrast does the same) */
br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Polish");
if (br) {
- BKE_libblock_free(bmain, br);
+ BKE_libblock_delete(bmain, br);
}
/* remove brush brush (huh?) from some modes (draw brushes do the same) */
br = (Brush *)BKE_libblock_find_name_ex(bmain, ID_BR, "Brush");
if (br) {
- BKE_libblock_free(bmain, br);
+ BKE_libblock_delete(bmain, br);
}
/* remove draw brush from texpaint (draw brushes do the same) */
diff --git a/source/blender/blenloader/intern/versioning_legacy.c b/source/blender/blenloader/intern/versioning_legacy.c
index 921c69fcaa4..eae6ca1e689 100644
--- a/source/blender/blenloader/intern/versioning_legacy.c
+++ b/source/blender/blenloader/intern/versioning_legacy.c
@@ -58,7 +58,7 @@
#include "DNA_meshdata_types.h"
#include "DNA_nla_types.h"
#include "DNA_node_types.h"
-#include "DNA_object_fluidsim.h" // NT
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "DNA_property_types.h"
#include "DNA_view3d_types.h"
@@ -113,7 +113,7 @@ static void vcol_to_fcol(Mesh *me)
if (me->totface == 0 || me->mcol == NULL)
return;
- mcoln = mcolmain = MEM_mallocN(4*sizeof(int)*me->totface, "mcoln");
+ mcoln = mcolmain = MEM_malloc_arrayN(me->totface, 4 * sizeof(int), "mcoln");
mcol = (unsigned int *)me->mcol;
mface = me->mface;
for (a = me->totface; a > 0; a--, mface++) {
@@ -2290,11 +2290,12 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
/* during 2.41 images with this name were used for viewer node output, lets fix that */
if (main->versionfile == 241) {
Image *ima;
- for (ima = main->image.first; ima; ima = ima->id.next)
+ for (ima = main->image.first; ima; ima = ima->id.next) {
if (STREQ(ima->name, "Compositor")) {
strcpy(ima->id.name + 2, "Viewer Node");
strcpy(ima->name, "Viewer Node");
}
+ }
}
}
@@ -2904,12 +2905,12 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
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] == 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;
+ sce->toolsettings->skgen_subdivisions[0] = SKGEN_SUB_CORRELATION;
+ sce->toolsettings->skgen_subdivisions[1] = SKGEN_SUB_LENGTH;
+ sce->toolsettings->skgen_subdivisions[2] = SKGEN_SUB_ANGLE;
}
}
}
@@ -3022,7 +3023,7 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
psys->pointcache = BKE_ptcache_add(&psys->ptcaches);
- part = psys->part = psys_new_settings("ParticleSettings", main);
+ part = psys->part = BKE_particlesettings_add(main, "ParticleSettings");
/* needed for proper libdata lookup */
blo_do_versions_oldnewmap_insert(fd->libmap, psys->part, psys->part, 0);
@@ -3141,7 +3142,7 @@ void blo_do_versions_pre250(FileData *fd, Library *lib, Main *main)
pset->totaddkey = 5;
pset->brushtype = PE_BRUSH_NONE;
- for (a = 0; a < PE_TOT_BRUSH; a++) {
+ for (a = 0; a < ARRAY_SIZE(pset->brush); a++) {
pset->brush[a].strength = 50;
pset->brush[a].size = 50;
pset->brush[a].step = 10;
diff --git a/source/blender/blenloader/intern/writefile.c b/source/blender/blenloader/intern/writefile.c
index 38a032f4907..549800ae02b 100644
--- a/source/blender/blenloader/intern/writefile.c
+++ b/source/blender/blenloader/intern/writefile.c
@@ -127,7 +127,7 @@
#include "DNA_material_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_packedFile_types.h"
#include "DNA_particle_types.h"
#include "DNA_property_types.h"
@@ -180,6 +180,7 @@
#include "BLO_writefile.h"
#include "BLO_readfile.h"
+#include "BLO_runtime.h"
#include "BLO_undofile.h"
#include "BLO_blend_defs.h"
@@ -196,8 +197,11 @@
#define MYWRITE_BUFFER_SIZE (MEM_SIZE_OPTIMAL(1 << 17)) /* 128kb */
#define MYWRITE_MAX_CHUNK (MEM_SIZE_OPTIMAL(1 << 15)) /* ~32kb */
+/** Use if we want to store how many bytes have been written to the file. */
+// #define USE_WRITE_DATA_LEN
-/** \name Small API to handle compression.
+/* -------------------------------------------------------------------- */
+/** \name Internal Write Wrapper's (Abstracts Compression)
* \{ */
typedef enum {
@@ -301,20 +305,41 @@ static void ww_handle_init(eWriteWrapType ww_type, WriteWrap *r_ww)
/** \} */
-
+/* -------------------------------------------------------------------- */
+/** \name Write Data Type & Functions
+ * \{ */
typedef struct {
const struct SDNA *sdna;
- unsigned char *buf;
- MemFile *compare, *current;
+ /** Use for file and memory writing (fixed size of #MYWRITE_BUFFER_SIZE). */
+ uchar *buf;
+ /** Number of bytes used in #WriteData.buf (flushed when exceeded). */
+ int buf_used_len;
+
+#ifdef USE_WRITE_DATA_LEN
+ /** Total number of bytes written. */
+ size_t write_len;
+#endif
- int tot, count;
+ /** Set on unlikely case of an error (ignores further file writing). */
bool error;
- /* Wrap writing, so we can use zlib or
+ /** #MemFile writing (used for undo). */
+ struct {
+ MemFile *current;
+ MemFile *compare;
+ /** Use to de-duplicate chunks when writing. */
+ MemFileChunk *compare_chunk;
+ } mem;
+ /** When true, write to #WriteData.current, could also call 'is_undo'. */
+ bool use_memfile;
+
+ /**
+ * Wrap writing, so we can use zlib or
* other compression types later, see: G_FILE_COMPRESS
- * Will be NULL for UNDO. */
+ * Will be NULL for UNDO.
+ */
WriteWrap *ww;
#ifdef USE_BMESH_SAVE_AS_COMPAT
@@ -346,8 +371,8 @@ static void writedata_do_write(WriteData *wd, const void *mem, int memlen)
}
/* memory based save */
- if (wd->current) {
- memfile_chunk_add(NULL, wd->current, mem, memlen);
+ if (wd->use_memfile) {
+ memfile_chunk_add(wd->mem.current, mem, memlen, &wd->mem.compare_chunk);
}
else {
if (wd->ww->write(wd->ww, mem, memlen) != memlen) {
@@ -362,7 +387,11 @@ static void writedata_free(WriteData *wd)
MEM_freeN(wd);
}
-/***/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Local Writing API 'mywrite'
+ * \{ */
/**
* Flush helps the de-duplicating memory for undo-save by logically segmenting data,
@@ -370,9 +399,9 @@ static void writedata_free(WriteData *wd)
*/
static void mywrite_flush(WriteData *wd)
{
- if (wd->count) {
- writedata_do_write(wd, wd->buf, wd->count);
- wd->count = 0;
+ if (wd->buf_used_len) {
+ writedata_do_write(wd, wd->buf, wd->buf_used_len);
+ wd->buf_used_len = 0;
}
}
@@ -380,7 +409,6 @@ static void mywrite_flush(WriteData *wd)
* Low level WRITE(2) wrapper that buffers data
* \param adr Pointer to new chunk of data
* \param len Length of new chunk of data
- * \warning Talks to other functions with global parameters
*/
static void mywrite(WriteData *wd, const void *adr, int len)
{
@@ -388,19 +416,21 @@ static void mywrite(WriteData *wd, const void *adr, int len)
return;
}
- if (adr == NULL) {
+ if (UNLIKELY(adr == NULL)) {
BLI_assert(0);
return;
}
- wd->tot += len;
+#ifdef USE_WRITE_DATA_LEN
+ wd->write_len += len;
+#endif
/* 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;
+ if (wd->buf_used_len) {
+ writedata_do_write(wd, wd->buf, wd->buf_used_len);
+ wd->buf_used_len = 0;
}
do {
@@ -414,14 +444,14 @@ static void mywrite(WriteData *wd, const void *adr, int len)
}
/* 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;
+ if (len + wd->buf_used_len > MYWRITE_BUFFER_SIZE - 1) {
+ writedata_do_write(wd, wd->buf, wd->buf_used_len);
+ wd->buf_used_len = 0;
}
/* append data at end of buffer */
- memcpy(&wd->buf[wd->count], adr, len);
- wd->count += len;
+ memcpy(&wd->buf[wd->buf_used_len], adr, len);
+ wd->buf_used_len += len;
}
/**
@@ -431,19 +461,17 @@ static void mywrite(WriteData *wd, const void *adr, int len)
* \param current The current memory file (can be NULL).
* \warning Talks to other functions with global parameters
*/
-static WriteData *bgnwrite(WriteWrap *ww, MemFile *compare, MemFile *current)
+static WriteData *mywrite_begin(WriteWrap *ww, MemFile *compare, MemFile *current)
{
WriteData *wd = writedata_new(ww);
- if (wd == NULL) {
- return NULL;
+ if (current != NULL) {
+ wd->mem.current = current;
+ wd->mem.compare = compare;
+ wd->mem.compare_chunk = compare ? compare->chunks.first : NULL;
+ wd->use_memfile = true;
}
- wd->compare = compare;
- wd->current = current;
- /* this inits comparing */
- memfile_chunk_add(compare, NULL, NULL, 0);
-
return wd;
}
@@ -453,11 +481,11 @@ static WriteData *bgnwrite(WriteWrap *ww, MemFile *compare, MemFile *current)
* \return unknown global variable otherwise
* \warning Talks to other functions with global parameters
*/
-static bool endwrite(WriteData *wd)
+static bool mywrite_end(WriteData *wd)
{
- if (wd->count) {
- writedata_do_write(wd, wd->buf, wd->count);
- wd->count = 0;
+ if (wd->buf_used_len) {
+ writedata_do_write(wd, wd->buf, wd->buf_used_len);
+ wd->buf_used_len = 0;
}
const bool err = wd->error;
@@ -466,7 +494,11 @@ static bool endwrite(WriteData *wd)
return err;
}
-/* ********** WRITE FILE ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Generic DNA File Writing
+ * \{ */
static void writestruct_at_address_nr(
WriteData *wd, int filecode, const int struct_nr, int nr,
@@ -592,8 +624,14 @@ static void writelist_id(WriteData *wd, int filecode, const char *structname, co
#define writelist(wd, filecode, struct_id, lb) \
writelist_nr(wd, filecode, SDNA_TYPE_FROM_STRUCT(struct_id), lb)
-/* *************** writing some direct data structs used in more code parts **************** */
-/*These functions are used by blender's .blend system for file saving/loading.*/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Typed DNA File Writing
+ *
+ * These functions are used by blender's .blend system for file saving/loading.
+ * \{ */
+
void IDP_WriteProperty_OnlyData(const IDProperty *prop, void *wd);
void IDP_WriteProperty(const IDProperty *prop, void *wd);
@@ -679,8 +717,10 @@ static void write_iddata(void *wd, const ID *id)
static void write_previews(WriteData *wd, const PreviewImage *prv_orig)
{
- /* Never write previews when doing memsave (i.e. undo/redo)! */
- if (prv_orig && !wd->current) {
+ /* Note we write previews also for undo steps. It takes up some memory,
+ * but not doing so would causes all previews to be re-rendered after
+ * undo which is too expensive. */
+ if (prv_orig) {
PreviewImage prv = *prv_orig;
/* don't write out large previews if not requested */
@@ -797,26 +837,22 @@ static void write_fcurves(WriteData *wd, ListBase *fcurves)
}
}
-static void write_actions(WriteData *wd, ListBase *idbase)
+static void write_action(WriteData *wd, bAction *act)
{
- for (bAction *act = idbase->first; act; act = act->id.next) {
- if (act->id.us > 0 || wd->current) {
- writestruct(wd, ID_AC, bAction, 1, act);
- write_iddata(wd, &act->id);
+ if (act->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_AC, bAction, 1, act);
+ write_iddata(wd, &act->id);
- write_fcurves(wd, &act->curves);
+ write_fcurves(wd, &act->curves);
- for (bActionGroup *grp = act->groups.first; grp; grp = grp->next) {
- writestruct(wd, DATA, bActionGroup, 1, grp);
- }
+ for (bActionGroup *grp = act->groups.first; grp; grp = grp->next) {
+ writestruct(wd, DATA, bActionGroup, 1, grp);
+ }
- for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
- writestruct(wd, DATA, TimeMarker, 1, marker);
- }
+ for (TimeMarker *marker = act->markers.first; marker; marker = marker->next) {
+ writestruct(wd, DATA, TimeMarker, 1, marker);
}
}
-
- mywrite_flush(wd);
}
static void write_keyingsets(WriteData *wd, ListBase *list)
@@ -911,7 +947,7 @@ static void write_node_socket(WriteData *wd, bNodeTree *UNUSED(ntree), bNode *no
{
#ifdef USE_NODE_COMPAT_CUSTOMNODES
/* forward compatibility code, so older blenders still open (not for undo) */
- if (wd->current == NULL) {
+ if (wd->use_memfile == false) {
sock->stack_type = 1;
if (node->type == NODE_GROUP) {
@@ -965,7 +1001,7 @@ static void write_node_socket_interface(WriteData *wd, bNodeTree *UNUSED(ntree),
}
}
/* this is only direct data, tree itself should have been written */
-static void write_nodetree(WriteData *wd, bNodeTree *ntree)
+static void write_nodetree_nolib(WriteData *wd, bNodeTree *ntree)
{
bNode *node;
bNodeSocket *sock;
@@ -1031,7 +1067,7 @@ static void write_nodetree(WriteData *wd, bNodeTree *ntree)
* Not ideal (there is no ideal solution here), but should do for now. */
NodeGlare *ndg = node->storage;
/* Not in undo case. */
- if (!wd->current) {
+ if (wd->use_memfile == false) {
switch (ndg->type) {
case 2: /* Grrrr! magic numbers :( */
ndg->angle = ndg->streaks;
@@ -1056,7 +1092,7 @@ static void write_nodetree(WriteData *wd, bNodeTree *ntree)
writestruct(wd, DATA, NodeImageMultiFileSocket, 1, sock->storage);
}
}
- if (node->type == CMP_NODE_IMAGE) {
+ if (ELEM(node->type, CMP_NODE_IMAGE, CMP_NODE_R_LAYERS)) {
/* write extra socket info */
for (sock = node->outputs.first; sock; sock = sock->next) {
writestruct(wd, DATA, NodeImageLayer, 1, sock->storage);
@@ -1145,7 +1181,7 @@ static void write_renderinfo(WriteData *wd, Main *mainvar)
}
}
-static void write_keymapitem(WriteData *wd, wmKeyMapItem *kmi)
+static void write_keymapitem(WriteData *wd, const wmKeyMapItem *kmi)
{
writestruct(wd, DATA, wmKeyMapItem, 1, kmi);
if (kmi->properties) {
@@ -1153,26 +1189,18 @@ static void write_keymapitem(WriteData *wd, wmKeyMapItem *kmi)
}
}
-static void write_userdef(WriteData *wd)
+static void write_userdef(WriteData *wd, const UserDef *userdef)
{
- bTheme *btheme;
- wmKeyMap *keymap;
- wmKeyMapItem *kmi;
- wmKeyMapDiffItem *kmdi;
- bAddon *bext;
- bPathCompare *path_cmp;
- uiStyle *style;
+ writestruct(wd, USER, UserDef, 1, userdef);
- writestruct(wd, USER, UserDef, 1, &U);
-
- for (btheme = U.themes.first; btheme; btheme = btheme->next) {
+ for (const bTheme *btheme = userdef->themes.first; btheme; btheme = btheme->next) {
writestruct(wd, DATA, bTheme, 1, btheme);
}
- for (keymap = U.user_keymaps.first; keymap; keymap = keymap->next) {
+ for (const wmKeyMap *keymap = userdef->user_keymaps.first; keymap; keymap = keymap->next) {
writestruct(wd, DATA, wmKeyMap, 1, keymap);
- for (kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
+ for (const wmKeyMapDiffItem *kmdi = keymap->diff_items.first; kmdi; kmdi = kmdi->next) {
writestruct(wd, DATA, wmKeyMapDiffItem, 1, kmdi);
if (kmdi->remove_item) {
write_keymapitem(wd, kmdi->remove_item);
@@ -1182,23 +1210,23 @@ static void write_userdef(WriteData *wd)
}
}
- for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
+ for (const wmKeyMapItem *kmi = keymap->items.first; kmi; kmi = kmi->next) {
write_keymapitem(wd, kmi);
}
}
- for (bext = U.addons.first; bext; bext = bext->next) {
+ for (const bAddon *bext = userdef->addons.first; bext; bext = bext->next) {
writestruct(wd, DATA, bAddon, 1, bext);
if (bext->prop) {
IDP_WriteProperty(bext->prop, wd);
}
}
- for (path_cmp = U.autoexec_paths.first; path_cmp; path_cmp = path_cmp->next) {
+ for (const bPathCompare *path_cmp = userdef->autoexec_paths.first; path_cmp; path_cmp = path_cmp->next) {
writestruct(wd, DATA, bPathCompare, 1, path_cmp);
}
- for (style = U.uistyles.first; style; style = style->next) {
+ for (const uiStyle *style = userdef->uistyles.first; style; style = style->next) {
writestruct(wd, DATA, uiStyle, 1, style);
}
}
@@ -1293,60 +1321,63 @@ static void write_pointcaches(WriteData *wd, ListBase *ptcaches)
}
}
}
-static void write_particlesettings(WriteData *wd, ListBase *idbase)
+
+static void write_particlesettings(WriteData *wd, ParticleSettings *part)
{
- for (ParticleSettings *part = idbase->first; part; part = part->id.next) {
- if (part->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_PA, ParticleSettings, 1, part);
- write_iddata(wd, &part->id);
-
- if (part->adt) {
- write_animdata(wd, part->adt);
- }
- writestruct(wd, DATA, PartDeflect, 1, part->pd);
- writestruct(wd, DATA, PartDeflect, 1, part->pd2);
- writestruct(wd, DATA, EffectorWeights, 1, part->effector_weights);
+ if (part->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_PA, ParticleSettings, 1, part);
+ write_iddata(wd, &part->id);
- if (part->clumpcurve) {
- write_curvemapping(wd, part->clumpcurve);
- }
- if (part->roughcurve) {
- write_curvemapping(wd, part->roughcurve);
- }
+ if (part->adt) {
+ write_animdata(wd, part->adt);
+ }
+ writestruct(wd, DATA, PartDeflect, 1, part->pd);
+ writestruct(wd, DATA, PartDeflect, 1, part->pd2);
+ writestruct(wd, DATA, EffectorWeights, 1, part->effector_weights);
- for (ParticleDupliWeight *dw = part->dupliweights.first; dw; dw = dw->next) {
- /* update indices, but only if dw->ob is set (can be NULL after loading e.g.) */
- if (dw->ob != NULL) {
- dw->index = 0;
- if (part->dup_group) { /* can be NULL if lining fails or set to None */
- for (GroupObject *go = part->dup_group->gobject.first;
- go && go->ob != dw->ob;
- go = go->next, dw->index++);
- }
+ if (part->clumpcurve) {
+ write_curvemapping(wd, part->clumpcurve);
+ }
+ if (part->roughcurve) {
+ write_curvemapping(wd, part->roughcurve);
+ }
+ if (part->twistcurve) {
+ write_curvemapping(wd, part->twistcurve);
+ }
+
+ for (ParticleDupliWeight *dw = part->dupliweights.first; dw; dw = dw->next) {
+ /* update indices, but only if dw->ob is set (can be NULL after loading e.g.) */
+ if (dw->ob != NULL) {
+ dw->index = 0;
+ if (part->dup_group) { /* can be NULL if lining fails or set to None */
+ for (GroupObject *go = part->dup_group->gobject.first;
+ go && go->ob != dw->ob;
+ go = go->next, dw->index++);
}
- writestruct(wd, DATA, ParticleDupliWeight, 1, dw);
}
+ writestruct(wd, DATA, ParticleDupliWeight, 1, dw);
+ }
- if (part->boids && part->phystype == PART_PHYS_BOIDS) {
- writestruct(wd, DATA, BoidSettings, 1, part->boids);
+ if (part->boids && part->phystype == PART_PHYS_BOIDS) {
+ writestruct(wd, DATA, BoidSettings, 1, part->boids);
- for (BoidState *state = part->boids->states.first; state; state = state->next) {
- write_boid_state(wd, state);
- }
- }
- if (part->fluid && part->phystype == PART_PHYS_FLUID) {
- writestruct(wd, DATA, SPHFluidSettings, 1, part->fluid);
+ for (BoidState *state = part->boids->states.first; state; state = state->next) {
+ write_boid_state(wd, state);
}
+ }
+ if (part->fluid && part->phystype == PART_PHYS_FLUID) {
+ writestruct(wd, DATA, SPHFluidSettings, 1, part->fluid);
+ }
- for (int a = 0; a < MAX_MTEX; a++) {
- if (part->mtex[a]) {
- writestruct(wd, DATA, MTex, 1, part->mtex[a]);
- }
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (part->mtex[a]) {
+ writestruct(wd, DATA, MTex, 1, part->mtex[a]);
}
}
}
}
+
static void write_particlesystems(WriteData *wd, ListBase *particles)
{
ParticleSystem *psys = particles->first;
@@ -1837,201 +1868,207 @@ static void write_modifiers(WriteData *wd, ListBase *modbase)
writedata(wd, DATA, sizeof(float[3]) * csmd->bind_coords_num, csmd->bind_coords);
}
}
- }
-}
+ else if (md->type == eModifierType_SurfaceDeform) {
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
-static void write_objects(WriteData *wd, ListBase *idbase)
-{
- for (Object *ob = idbase->first; ob; ob = ob->id.next) {
- if (ob->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_OB, Object, 1, ob);
- write_iddata(wd, &ob->id);
-
- if (ob->adt) {
- write_animdata(wd, ob->adt);
- }
+ writestruct(wd, DATA, SDefVert, smd->numverts, smd->verts);
- /* direct data */
- writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat);
- writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits);
- /* write_effects(wd, &ob->effect); */ /* not used anymore */
- write_properties(wd, &ob->prop);
- write_sensors(wd, &ob->sensors);
- write_controllers(wd, &ob->controllers);
- write_actuators(wd, &ob->actuators);
-
- if (ob->type == OB_ARMATURE) {
- bArmature *arm = ob->data;
- if (arm && ob->pose && arm->act_bone) {
- BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
+ if (smd->verts) {
+ for (int i = 0; i < smd->numverts; i++) {
+ writestruct(wd, DATA, SDefBind, smd->verts[i].numbinds, smd->verts[i].binds);
+
+ if (smd->verts[i].binds) {
+ for (int j = 0; j < smd->verts[i].numbinds; j++) {
+ writedata(wd, DATA, sizeof(int) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_inds);
+
+ if (smd->verts[i].binds[j].mode == MOD_SDEF_MODE_CENTROID ||
+ smd->verts[i].binds[j].mode == MOD_SDEF_MODE_LOOPTRI)
+ {
+ writedata(wd, DATA, sizeof(float) * 3, smd->verts[i].binds[j].vert_weights);
+ }
+ else {
+ writedata(wd, DATA, sizeof(float) * smd->verts[i].binds[j].numverts, smd->verts[i].binds[j].vert_weights);
+ }
+ }
+ }
}
}
+ }
+ }
+}
- write_pose(wd, ob->pose);
- write_defgroups(wd, &ob->defbase);
- write_constraints(wd, &ob->constraints);
- write_motionpath(wd, ob->mpath);
+static void write_object(WriteData *wd, Object *ob)
+{
+ if (ob->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_OB, Object, 1, ob);
+ write_iddata(wd, &ob->id);
- writestruct(wd, DATA, PartDeflect, 1, ob->pd);
- writestruct(wd, DATA, SoftBody, 1, ob->soft);
- if (ob->soft) {
- write_pointcaches(wd, &ob->soft->ptcaches);
- writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights);
- }
- writestruct(wd, DATA, BulletSoftBody, 1, ob->bsoft);
+ if (ob->adt) {
+ write_animdata(wd, ob->adt);
+ }
- if (ob->rigidbody_object) {
- /* TODO: if any extra data is added to handle duplis, will need separate function then */
- writestruct(wd, DATA, RigidBodyOb, 1, ob->rigidbody_object);
- }
- if (ob->rigidbody_constraint) {
- writestruct(wd, DATA, RigidBodyCon, 1, ob->rigidbody_constraint);
- }
+ /* direct data */
+ writedata(wd, DATA, sizeof(void *) * ob->totcol, ob->mat);
+ writedata(wd, DATA, sizeof(char) * ob->totcol, ob->matbits);
+ /* write_effects(wd, &ob->effect); */ /* not used anymore */
+ write_properties(wd, &ob->prop);
+ write_sensors(wd, &ob->sensors);
+ write_controllers(wd, &ob->controllers);
+ write_actuators(wd, &ob->actuators);
- if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
- writestruct(wd, DATA, ImageUser, 1, ob->iuser);
+ if (ob->type == OB_ARMATURE) {
+ bArmature *arm = ob->data;
+ if (arm && ob->pose && arm->act_bone) {
+ BLI_strncpy(ob->pose->proxy_act_bone, arm->act_bone->name, sizeof(ob->pose->proxy_act_bone));
}
+ }
- write_particlesystems(wd, &ob->particlesystem);
- write_modifiers(wd, &ob->modifiers);
+ write_pose(wd, ob->pose);
+ write_defgroups(wd, &ob->defbase);
+ write_constraints(wd, &ob->constraints);
+ write_motionpath(wd, ob->mpath);
- writelist(wd, DATA, LinkData, &ob->pc_ids);
- writelist(wd, DATA, LodLevel, &ob->lodlevels);
+ writestruct(wd, DATA, PartDeflect, 1, ob->pd);
+ writestruct(wd, DATA, SoftBody, 1, ob->soft);
+ if (ob->soft) {
+ write_pointcaches(wd, &ob->soft->ptcaches);
+ writestruct(wd, DATA, EffectorWeights, 1, ob->soft->effector_weights);
+ }
+ writestruct(wd, DATA, BulletSoftBody, 1, ob->bsoft);
- write_previews(wd, ob->preview);
+ if (ob->rigidbody_object) {
+ /* TODO: if any extra data is added to handle duplis, will need separate function then */
+ writestruct(wd, DATA, RigidBodyOb, 1, ob->rigidbody_object);
+ }
+ if (ob->rigidbody_constraint) {
+ writestruct(wd, DATA, RigidBodyCon, 1, ob->rigidbody_constraint);
}
- }
- mywrite_flush(wd);
+ if (ob->type == OB_EMPTY && ob->empty_drawtype == OB_EMPTY_IMAGE) {
+ writestruct(wd, DATA, ImageUser, 1, ob->iuser);
+ }
+
+ write_particlesystems(wd, &ob->particlesystem);
+ write_modifiers(wd, &ob->modifiers);
+
+ writelist(wd, DATA, LinkData, &ob->pc_ids);
+ writelist(wd, DATA, LodLevel, &ob->lodlevels);
+
+ write_previews(wd, ob->preview);
+ }
}
-static void write_vfonts(WriteData *wd, ListBase *idbase)
+static void write_vfont(WriteData *wd, VFont *vf)
{
- for (VFont *vf = idbase->first; vf; vf = vf->id.next) {
- if (vf->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_VF, VFont, 1, vf);
- write_iddata(wd, &vf->id);
+ if (vf->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_VF, VFont, 1, vf);
+ write_iddata(wd, &vf->id);
- /* direct data */
- if (vf->packedfile) {
- PackedFile *pf = vf->packedfile;
- writestruct(wd, DATA, PackedFile, 1, pf);
- writedata(wd, DATA, pf->size, pf->data);
- }
+ /* direct data */
+ if (vf->packedfile) {
+ PackedFile *pf = vf->packedfile;
+ writestruct(wd, DATA, PackedFile, 1, pf);
+ writedata(wd, DATA, pf->size, pf->data);
}
}
-
- mywrite_flush(wd);
}
-static void write_keys(WriteData *wd, ListBase *idbase)
+static void write_key(WriteData *wd, Key *key)
{
- for (Key *key = idbase->first; key; key = key->id.next) {
- if (key->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_KE, Key, 1, key);
- write_iddata(wd, &key->id);
-
- if (key->adt) {
- write_animdata(wd, key->adt);
- }
+ if (key->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_KE, Key, 1, key);
+ write_iddata(wd, &key->id);
- /* direct data */
- for (KeyBlock *kb = key->block.first; kb; kb = kb->next) {
- writestruct(wd, DATA, KeyBlock, 1, kb);
- if (kb->data) {
- writedata(wd, DATA, kb->totelem * key->elemsize, kb->data);
- }
+ if (key->adt) {
+ write_animdata(wd, key->adt);
+ }
+
+ /* direct data */
+ for (KeyBlock *kb = key->block.first; kb; kb = kb->next) {
+ writestruct(wd, DATA, KeyBlock, 1, kb);
+ if (kb->data) {
+ writedata(wd, DATA, kb->totelem * key->elemsize, kb->data);
}
}
}
-
- mywrite_flush(wd);
}
-static void write_cameras(WriteData *wd, ListBase *idbase)
+static void write_camera(WriteData *wd, Camera *cam)
{
- for (Camera *cam = idbase->first; cam; cam = cam->id.next) {
- if (cam->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_CA, Camera, 1, cam);
- write_iddata(wd, &cam->id);
-
- if (cam->adt) {
- write_animdata(wd, cam->adt);
- }
+ if (cam->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_CA, Camera, 1, cam);
+ write_iddata(wd, &cam->id);
+
+ if (cam->adt) {
+ write_animdata(wd, cam->adt);
}
}
}
-static void write_mballs(WriteData *wd, ListBase *idbase)
+static void write_mball(WriteData *wd, MetaBall *mb)
{
- for (MetaBall *mb = idbase->first; mb; mb = mb->id.next) {
- if (mb->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_MB, MetaBall, 1, mb);
- write_iddata(wd, &mb->id);
+ if (mb->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_MB, MetaBall, 1, mb);
+ write_iddata(wd, &mb->id);
- /* direct data */
- writedata(wd, DATA, sizeof(void *) * mb->totcol, mb->mat);
- if (mb->adt) {
- write_animdata(wd, mb->adt);
- }
+ /* direct data */
+ writedata(wd, DATA, sizeof(void *) * mb->totcol, mb->mat);
+ if (mb->adt) {
+ write_animdata(wd, mb->adt);
+ }
- for (MetaElem *ml = mb->elems.first; ml; ml = ml->next) {
- writestruct(wd, DATA, MetaElem, 1, ml);
- }
+ for (MetaElem *ml = mb->elems.first; ml; ml = ml->next) {
+ writestruct(wd, DATA, MetaElem, 1, ml);
}
}
}
-static void write_curves(WriteData *wd, ListBase *idbase)
+static void write_curve(WriteData *wd, Curve *cu)
{
- for (Curve *cu = idbase->first; cu; cu = cu->id.next) {
- if (cu->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_CU, Curve, 1, cu);
- write_iddata(wd, &cu->id);
+ if (cu->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_CU, Curve, 1, cu);
+ write_iddata(wd, &cu->id);
- /* direct data */
- writedata(wd, DATA, sizeof(void *) * cu->totcol, cu->mat);
- if (cu->adt) {
- write_animdata(wd, cu->adt);
- }
+ /* direct data */
+ writedata(wd, DATA, sizeof(void *) * cu->totcol, cu->mat);
+ if (cu->adt) {
+ write_animdata(wd, cu->adt);
+ }
- if (cu->vfont) {
- writedata(wd, DATA, cu->len + 1, cu->str);
- writestruct(wd, DATA, CharInfo, cu->len_wchar + 1, cu->strinfo);
- writestruct(wd, DATA, TextBox, cu->totbox, cu->tb);
+ if (cu->vfont) {
+ writedata(wd, DATA, cu->len + 1, cu->str);
+ writestruct(wd, DATA, CharInfo, cu->len_wchar + 1, cu->strinfo);
+ writestruct(wd, DATA, TextBox, cu->totbox, cu->tb);
+ }
+ else {
+ /* is also the order of reading */
+ for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
+ writestruct(wd, DATA, Nurb, 1, nu);
}
- else {
- /* is also the order of reading */
- for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
- writestruct(wd, DATA, Nurb, 1, nu);
+ for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
+ if (nu->type == CU_BEZIER) {
+ writestruct(wd, DATA, BezTriple, nu->pntsu, nu->bezt);
}
- for (Nurb *nu = cu->nurb.first; nu; nu = nu->next) {
- if (nu->type == CU_BEZIER) {
- writestruct(wd, DATA, BezTriple, nu->pntsu, nu->bezt);
+ else {
+ writestruct(wd, DATA, BPoint, nu->pntsu * nu->pntsv, nu->bp);
+ if (nu->knotsu) {
+ writedata(wd, DATA, KNOTSU(nu) * sizeof(float), nu->knotsu);
}
- else {
- writestruct(wd, DATA, BPoint, nu->pntsu * nu->pntsv, nu->bp);
- if (nu->knotsu) {
- writedata(wd, DATA, KNOTSU(nu) * sizeof(float), nu->knotsu);
- }
- if (nu->knotsv) {
- writedata(wd, DATA, KNOTSV(nu) * sizeof(float), nu->knotsv);
- }
+ if (nu->knotsv) {
+ writedata(wd, DATA, KNOTSV(nu) * sizeof(float), nu->knotsv);
}
}
}
}
}
-
- mywrite_flush(wd);
}
static void write_dverts(WriteData *wd, int count, MDeformVert *dvlist)
@@ -2096,7 +2133,7 @@ static void write_customdata(
int i;
/* write external customdata (not for undo) */
- if (data->external && !wd->current) {
+ if (data->external && (wd->use_memfile == false)) {
CustomData_external_write(data, id, CD_MASK_MESH, count, 0);
}
@@ -2148,7 +2185,7 @@ static void write_customdata(
}
}
-static void write_meshes(WriteData *wd, ListBase *idbase)
+static void write_mesh(WriteData *wd, Mesh *mesh)
{
#ifdef USE_BMESH_SAVE_AS_COMPAT
const bool save_for_old_blender = wd->use_mesh_compat; /* option to save with older mesh format */
@@ -2156,365 +2193,342 @@ static void write_meshes(WriteData *wd, ListBase *idbase)
const bool save_for_old_blender = false;
#endif
- for (Mesh *mesh = idbase->first; mesh; mesh = mesh->id.next) {
- CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
- CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
- CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
- CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
- CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
-
- if (mesh->id.us > 0 || wd->current) {
- /* write LibData */
- if (!save_for_old_blender) {
- /* write a copy of the mesh, don't modify in place because it is
- * not thread safe for threaded renders that are reading this */
- Mesh *old_mesh = mesh;
- Mesh copy_mesh = *mesh;
- mesh = &copy_mesh;
+ CustomDataLayer *vlayers = NULL, vlayers_buff[CD_TEMP_CHUNK_SIZE];
+ CustomDataLayer *elayers = NULL, elayers_buff[CD_TEMP_CHUNK_SIZE];
+ CustomDataLayer *flayers = NULL, flayers_buff[CD_TEMP_CHUNK_SIZE];
+ CustomDataLayer *llayers = NULL, llayers_buff[CD_TEMP_CHUNK_SIZE];
+ CustomDataLayer *players = NULL, players_buff[CD_TEMP_CHUNK_SIZE];
+
+ if (mesh->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ if (!save_for_old_blender) {
+ /* write a copy of the mesh, don't modify in place because it is
+ * not thread safe for threaded renders that are reading this */
+ Mesh *old_mesh = mesh;
+ Mesh copy_mesh = *mesh;
+ mesh = &copy_mesh;
#ifdef USE_BMESH_SAVE_WITHOUT_MFACE
- /* cache only - don't write */
- mesh->mface = NULL;
- mesh->totface = 0;
- memset(&mesh->fdata, 0, sizeof(mesh->fdata));
+ /* cache only - don't write */
+ mesh->mface = NULL;
+ mesh->totface = 0;
+ memset(&mesh->fdata, 0, sizeof(mesh->fdata));
#endif /* USE_BMESH_SAVE_WITHOUT_MFACE */
- /**
- * Those calls:
- * - Reduce mesh->xdata.totlayer to number of layers to write.
- * - Fill xlayers with those layers to be written.
- * Note that mesh->xdata is from now on invalid for Blender, but this is why the whole mesh is
- * a temp local copy!
- */
- CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
- CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
+ /**
+ * Those calls:
+ * - Reduce mesh->xdata.totlayer to number of layers to write.
+ * - Fill xlayers with those layers to be written.
+ * Note that mesh->xdata is from now on invalid for Blender, but this is why the whole mesh is
+ * a temp local copy!
+ */
+ CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
+ CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
#ifndef USE_BMESH_SAVE_WITHOUT_MFACE /* Do not copy org fdata in this case!!! */
- CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
+ CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
#else
- flayers = flayers_buff;
+ flayers = flayers_buff;
#endif
- CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
- CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
+ CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
+ CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
- writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
- write_iddata(wd, &mesh->id);
+ writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
+ write_iddata(wd, &mesh->id);
- /* direct data */
- if (mesh->adt) {
- write_animdata(wd, mesh->adt);
- }
+ /* direct data */
+ if (mesh->adt) {
+ write_animdata(wd, mesh->adt);
+ }
- writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
- writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
+ writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
+ writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect);
- write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
- /* fdata is really a dummy - written so slots align */
- write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
+ /* fdata is really a dummy - written so slots align */
+ write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
- /* restore pointer */
- mesh = old_mesh;
- }
- else {
+ /* restore pointer */
+ mesh = old_mesh;
+ }
+ else {
#ifdef USE_BMESH_SAVE_AS_COMPAT
- /* write a copy of the mesh, don't modify in place because it is
- * not thread safe for threaded renders that are reading this */
- Mesh *old_mesh = mesh;
- Mesh copy_mesh = *mesh;
- mesh = &copy_mesh;
-
- mesh->mpoly = NULL;
- mesh->mface = NULL;
- mesh->totface = 0;
- mesh->totpoly = 0;
- mesh->totloop = 0;
- CustomData_reset(&mesh->fdata);
- CustomData_reset(&mesh->pdata);
- CustomData_reset(&mesh->ldata);
- mesh->edit_btmesh = NULL;
-
- /* now fill in polys to mfaces */
- /* XXX This breaks writing design, by using temp allocated memory, which will likely generate
- * duplicates in stored 'old' addresses.
- * This is very bad, but do not see easy way to avoid this, aside from generating those data
- * outside of save process itself.
- * Maybe we can live with this, though?
- */
- mesh->totface = BKE_mesh_mpoly_to_mface(&mesh->fdata, &old_mesh->ldata, &old_mesh->pdata,
- mesh->totface, old_mesh->totloop, old_mesh->totpoly);
+ /* write a copy of the mesh, don't modify in place because it is
+ * not thread safe for threaded renders that are reading this */
+ Mesh *old_mesh = mesh;
+ Mesh copy_mesh = *mesh;
+ mesh = &copy_mesh;
+
+ mesh->mpoly = NULL;
+ mesh->mface = NULL;
+ mesh->totface = 0;
+ mesh->totpoly = 0;
+ mesh->totloop = 0;
+ CustomData_reset(&mesh->fdata);
+ CustomData_reset(&mesh->pdata);
+ CustomData_reset(&mesh->ldata);
+ mesh->edit_btmesh = NULL;
+
+ /* now fill in polys to mfaces */
+ /* XXX This breaks writing design, by using temp allocated memory, which will likely generate
+ * duplicates in stored 'old' addresses.
+ * This is very bad, but do not see easy way to avoid this, aside from generating those data
+ * outside of save process itself.
+ * Maybe we can live with this, though?
+ */
+ mesh->totface = BKE_mesh_mpoly_to_mface(
+ &mesh->fdata, &old_mesh->ldata, &old_mesh->pdata,
+ mesh->totface, old_mesh->totloop, old_mesh->totpoly);
- BKE_mesh_update_customdata_pointers(mesh, false);
+ BKE_mesh_update_customdata_pointers(mesh, false);
- CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
- CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
- CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
+ CustomData_file_write_prepare(&mesh->vdata, &vlayers, vlayers_buff, ARRAY_SIZE(vlayers_buff));
+ CustomData_file_write_prepare(&mesh->edata, &elayers, elayers_buff, ARRAY_SIZE(elayers_buff));
+ CustomData_file_write_prepare(&mesh->fdata, &flayers, flayers_buff, ARRAY_SIZE(flayers_buff));
#if 0
- CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
- CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
+ CustomData_file_write_prepare(&mesh->ldata, &llayers, llayers_buff, ARRAY_SIZE(llayers_buff));
+ CustomData_file_write_prepare(&mesh->pdata, &players, players_buff, ARRAY_SIZE(players_buff));
#endif
- writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
- write_iddata(wd, &mesh->id);
+ writestruct_at_address(wd, ID_ME, Mesh, 1, old_mesh, mesh);
+ write_iddata(wd, &mesh->id);
- /* direct data */
- if (mesh->adt) {
- write_animdata(wd, mesh->adt);
- }
+ /* direct data */
+ if (mesh->adt) {
+ write_animdata(wd, mesh->adt);
+ }
- writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
- /* writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect); */ /* pre-bmesh NULL's */
+ writedata(wd, DATA, sizeof(void *) * mesh->totcol, mesh->mat);
+ /* writedata(wd, DATA, sizeof(MSelect) * mesh->totselect, mesh->mselect); */ /* pre-bmesh NULL's */
- write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
- /* harmless for older blender versioins but _not_ writing these keeps file size down */
+ write_customdata(wd, &mesh->id, mesh->totvert, &mesh->vdata, vlayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totedge, &mesh->edata, elayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totface, &mesh->fdata, flayers, -1, 0);
+ /* harmless for older blender versioins but _not_ writing these keeps file size down */
#if 0
- write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
- write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totloop, &mesh->ldata, llayers, -1, 0);
+ write_customdata(wd, &mesh->id, mesh->totpoly, &mesh->pdata, players, -1, 0);
#endif
- CustomData_free(&mesh->fdata, mesh->totface);
- flayers = NULL;
+ CustomData_free(&mesh->fdata, mesh->totface);
+ flayers = NULL;
- /* restore pointer */
- mesh = old_mesh;
+ /* restore pointer */
+ mesh = old_mesh;
#endif /* USE_BMESH_SAVE_AS_COMPAT */
- }
- }
-
- if (vlayers && vlayers != vlayers_buff) {
- MEM_freeN(vlayers);
- }
- if (elayers && elayers != elayers_buff) {
- MEM_freeN(elayers);
- }
- if (flayers && flayers != flayers_buff) {
- MEM_freeN(flayers);
- }
- if (llayers && llayers != llayers_buff) {
- MEM_freeN(llayers);
- }
- if (players && players != players_buff) {
- MEM_freeN(players);
}
}
- mywrite_flush(wd);
+ if (vlayers && vlayers != vlayers_buff) {
+ MEM_freeN(vlayers);
+ }
+ if (elayers && elayers != elayers_buff) {
+ MEM_freeN(elayers);
+ }
+ if (flayers && flayers != flayers_buff) {
+ MEM_freeN(flayers);
+ }
+ if (llayers && llayers != llayers_buff) {
+ MEM_freeN(llayers);
+ }
+ if (players && players != players_buff) {
+ MEM_freeN(players);
+ }
}
-static void write_lattices(WriteData *wd, ListBase *idbase)
+static void write_lattice(WriteData *wd, Lattice *lt)
{
- for (Lattice *lt = idbase->first; lt; lt = lt->id.next) {
- if (lt->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_LT, Lattice, 1, lt);
- write_iddata(wd, &lt->id);
-
- /* write animdata */
- if (lt->adt) {
- write_animdata(wd, lt->adt);
- }
-
- /* direct data */
- writestruct(wd, DATA, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def);
+ if (lt->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_LT, Lattice, 1, lt);
+ write_iddata(wd, &lt->id);
- write_dverts(wd, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert);
+ /* write animdata */
+ if (lt->adt) {
+ write_animdata(wd, lt->adt);
}
- }
- mywrite_flush(wd);
+ /* direct data */
+ writestruct(wd, DATA, BPoint, lt->pntsu * lt->pntsv * lt->pntsw, lt->def);
+
+ write_dverts(wd, lt->pntsu * lt->pntsv * lt->pntsw, lt->dvert);
+ }
}
-static void write_images(WriteData *wd, ListBase *idbase)
+static void write_image(WriteData *wd, Image *ima)
{
- for (Image *ima = idbase->first; ima; ima = ima->id.next) {
- if (ima->id.us > 0 || wd->current) {
- ImagePackedFile *imapf;
-
- /* Some trickery to keep forward compatibility of packed images. */
- BLI_assert(ima->packedfile == NULL);
- if (ima->packedfiles.first != NULL) {
- imapf = ima->packedfiles.first;
- ima->packedfile = imapf->packedfile;
- }
-
- /* write LibData */
- writestruct(wd, ID_IM, Image, 1, ima);
- write_iddata(wd, &ima->id);
+ if (ima->id.us > 0 || wd->use_memfile) {
+ ImagePackedFile *imapf;
- for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
- writestruct(wd, DATA, ImagePackedFile, 1, imapf);
- if (imapf->packedfile) {
- PackedFile *pf = imapf->packedfile;
- writestruct(wd, DATA, PackedFile, 1, pf);
- writedata(wd, DATA, pf->size, pf->data);
- }
- }
+ /* Some trickery to keep forward compatibility of packed images. */
+ BLI_assert(ima->packedfile == NULL);
+ if (ima->packedfiles.first != NULL) {
+ imapf = ima->packedfiles.first;
+ ima->packedfile = imapf->packedfile;
+ }
- write_previews(wd, ima->preview);
+ /* write LibData */
+ writestruct(wd, ID_IM, Image, 1, ima);
+ write_iddata(wd, &ima->id);
- for (ImageView *iv = ima->views.first; iv; iv = iv->next) {
- writestruct(wd, DATA, ImageView, 1, iv);
+ for (imapf = ima->packedfiles.first; imapf; imapf = imapf->next) {
+ writestruct(wd, DATA, ImagePackedFile, 1, imapf);
+ if (imapf->packedfile) {
+ PackedFile *pf = imapf->packedfile;
+ writestruct(wd, DATA, PackedFile, 1, pf);
+ writedata(wd, DATA, pf->size, pf->data);
}
- writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format);
+ }
+
+ write_previews(wd, ima->preview);
- ima->packedfile = NULL;
+ for (ImageView *iv = ima->views.first; iv; iv = iv->next) {
+ writestruct(wd, DATA, ImageView, 1, iv);
}
- }
+ writestruct(wd, DATA, Stereo3dFormat, 1, ima->stereo3d_format);
- mywrite_flush(wd);
+ ima->packedfile = NULL;
+ }
}
-static void write_textures(WriteData *wd, ListBase *idbase)
+static void write_texture(WriteData *wd, Tex *tex)
{
- for (Tex *tex = idbase->first; tex; tex = tex->id.next) {
- if (tex->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_TE, Tex, 1, tex);
- write_iddata(wd, &tex->id);
-
- if (tex->adt) {
- write_animdata(wd, tex->adt);
- }
+ if (tex->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_TE, Tex, 1, tex);
+ write_iddata(wd, &tex->id);
- /* direct data */
- if (tex->coba) {
- writestruct(wd, DATA, ColorBand, 1, tex->coba);
- }
- if (tex->type == TEX_ENVMAP && tex->env) {
- writestruct(wd, DATA, EnvMap, 1, tex->env);
- }
- if (tex->type == TEX_POINTDENSITY && tex->pd) {
- writestruct(wd, DATA, PointDensity, 1, tex->pd);
- if (tex->pd->coba) {
- writestruct(wd, DATA, ColorBand, 1, tex->pd->coba);
- }
- if (tex->pd->falloff_curve) {
- write_curvemapping(wd, tex->pd->falloff_curve);
- }
- }
- if (tex->type == TEX_VOXELDATA) {
- writestruct(wd, DATA, VoxelData, 1, tex->vd);
- }
- if (tex->type == TEX_OCEAN && tex->ot) {
- writestruct(wd, DATA, OceanTex, 1, tex->ot);
- }
+ if (tex->adt) {
+ write_animdata(wd, tex->adt);
+ }
- /* nodetree is integral part of texture, no libdata */
- if (tex->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, tex->nodetree);
- write_nodetree(wd, tex->nodetree);
+ /* direct data */
+ if (tex->coba) {
+ writestruct(wd, DATA, ColorBand, 1, tex->coba);
+ }
+ if (tex->type == TEX_ENVMAP && tex->env) {
+ writestruct(wd, DATA, EnvMap, 1, tex->env);
+ }
+ if (tex->type == TEX_POINTDENSITY && tex->pd) {
+ writestruct(wd, DATA, PointDensity, 1, tex->pd);
+ if (tex->pd->coba) {
+ writestruct(wd, DATA, ColorBand, 1, tex->pd->coba);
}
+ if (tex->pd->falloff_curve) {
+ write_curvemapping(wd, tex->pd->falloff_curve);
+ }
+ }
+ if (tex->type == TEX_VOXELDATA) {
+ writestruct(wd, DATA, VoxelData, 1, tex->vd);
+ }
+ if (tex->type == TEX_OCEAN && tex->ot) {
+ writestruct(wd, DATA, OceanTex, 1, tex->ot);
+ }
- write_previews(wd, tex->preview);
+ /* nodetree is integral part of texture, no libdata */
+ if (tex->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, tex->nodetree);
+ write_nodetree_nolib(wd, tex->nodetree);
}
- }
- mywrite_flush(wd);
+ write_previews(wd, tex->preview);
+ }
}
-static void write_materials(WriteData *wd, ListBase *idbase)
+static void write_material(WriteData *wd, Material *ma)
{
- for (Material *ma = idbase->first; ma; ma = ma->id.next) {
- if (ma->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_MA, Material, 1, ma);
- write_iddata(wd, &ma->id);
-
- if (ma->adt) {
- write_animdata(wd, ma->adt);
- }
+ if (ma->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_MA, Material, 1, ma);
+ write_iddata(wd, &ma->id);
- for (int a = 0; a < MAX_MTEX; a++) {
- if (ma->mtex[a]) {
- writestruct(wd, DATA, MTex, 1, ma->mtex[a]);
- }
- }
+ if (ma->adt) {
+ write_animdata(wd, ma->adt);
+ }
- if (ma->ramp_col) {
- writestruct(wd, DATA, ColorBand, 1, ma->ramp_col);
- }
- if (ma->ramp_spec) {
- writestruct(wd, DATA, ColorBand, 1, ma->ramp_spec);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (ma->mtex[a]) {
+ writestruct(wd, DATA, MTex, 1, ma->mtex[a]);
}
+ }
- /* nodetree is integral part of material, no libdata */
- if (ma->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, ma->nodetree);
- write_nodetree(wd, ma->nodetree);
- }
+ if (ma->ramp_col) {
+ writestruct(wd, DATA, ColorBand, 1, ma->ramp_col);
+ }
+ if (ma->ramp_spec) {
+ writestruct(wd, DATA, ColorBand, 1, ma->ramp_spec);
+ }
- write_previews(wd, ma->preview);
+ /* nodetree is integral part of material, no libdata */
+ if (ma->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, ma->nodetree);
+ write_nodetree_nolib(wd, ma->nodetree);
}
+
+ write_previews(wd, ma->preview);
}
}
-static void write_worlds(WriteData *wd, ListBase *idbase)
+static void write_world(WriteData *wd, World *wrld)
{
- for (World *wrld = idbase->first; wrld; wrld = wrld->id.next) {
- if (wrld->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_WO, World, 1, wrld);
- write_iddata(wd, &wrld->id);
-
- if (wrld->adt) {
- write_animdata(wd, wrld->adt);
- }
+ if (wrld->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_WO, World, 1, wrld);
+ write_iddata(wd, &wrld->id);
- for (int a = 0; a < MAX_MTEX; a++) {
- if (wrld->mtex[a]) {
- writestruct(wd, DATA, MTex, 1, wrld->mtex[a]);
- }
- }
+ if (wrld->adt) {
+ write_animdata(wd, wrld->adt);
+ }
- /* nodetree is integral part of world, no libdata */
- if (wrld->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, wrld->nodetree);
- write_nodetree(wd, wrld->nodetree);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (wrld->mtex[a]) {
+ writestruct(wd, DATA, MTex, 1, wrld->mtex[a]);
}
+ }
- write_previews(wd, wrld->preview);
+ /* nodetree is integral part of world, no libdata */
+ if (wrld->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, wrld->nodetree);
+ write_nodetree_nolib(wd, wrld->nodetree);
}
+
+ write_previews(wd, wrld->preview);
}
}
-static void write_lamps(WriteData *wd, ListBase *idbase)
+static void write_lamp(WriteData *wd, Lamp *la)
{
- for (Lamp *la = idbase->first; la; la = la->id.next) {
- if (la->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_LA, Lamp, 1, la);
- write_iddata(wd, &la->id);
-
- if (la->adt) {
- write_animdata(wd, la->adt);
- }
+ if (la->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_LA, Lamp, 1, la);
+ write_iddata(wd, &la->id);
- /* direct data */
- for (int a = 0; a < MAX_MTEX; a++) {
- if (la->mtex[a]) {
- writestruct(wd, DATA, MTex, 1, la->mtex[a]);
- }
- }
+ if (la->adt) {
+ write_animdata(wd, la->adt);
+ }
- if (la->curfalloff) {
- write_curvemapping(wd, la->curfalloff);
+ /* direct data */
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (la->mtex[a]) {
+ writestruct(wd, DATA, MTex, 1, la->mtex[a]);
}
+ }
- /* nodetree is integral part of lamps, no libdata */
- if (la->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, la->nodetree);
- write_nodetree(wd, la->nodetree);
- }
+ if (la->curfalloff) {
+ write_curvemapping(wd, la->curfalloff);
+ }
- write_previews(wd, la->preview);
+ /* nodetree is integral part of lamps, no libdata */
+ if (la->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, la->nodetree);
+ write_nodetree_nolib(wd, la->nodetree);
}
- }
- mywrite_flush(wd);
+ write_previews(wd, la->preview);
+ }
}
static void write_sequence_modifiers(WriteData *wd, ListBase *modbase)
@@ -2558,267 +2572,252 @@ static void write_paint(WriteData *wd, Paint *p)
}
}
-static void write_scenes(WriteData *wd, ListBase *scebase)
+static void write_scene(WriteData *wd, Scene *sce)
{
- for (Scene *sce = scebase->first; sce; sce = sce->id.next) {
- /* write LibData */
- writestruct(wd, ID_SCE, Scene, 1, sce);
- write_iddata(wd, &sce->id);
+ /* write LibData */
+ writestruct(wd, ID_SCE, Scene, 1, sce);
+ write_iddata(wd, &sce->id);
- if (sce->adt) {
- write_animdata(wd, sce->adt);
- }
- write_keyingsets(wd, &sce->keyingsets);
+ if (sce->adt) {
+ write_animdata(wd, sce->adt);
+ }
+ write_keyingsets(wd, &sce->keyingsets);
- /* direct data */
- for (Base *base = sce->base.first; base; base = base->next) {
- writestruct(wd, DATA, Base, 1, base);
- }
+ /* direct data */
+ for (Base *base = sce->base.first; base; base = base->next) {
+ writestruct(wd, DATA, Base, 1, base);
+ }
- ToolSettings *tos = sce->toolsettings;
- writestruct(wd, DATA, ToolSettings, 1, tos);
- if (tos->vpaint) {
- writestruct(wd, DATA, VPaint, 1, tos->vpaint);
- write_paint(wd, &tos->vpaint->paint);
- }
- if (tos->wpaint) {
- writestruct(wd, DATA, VPaint, 1, tos->wpaint);
- write_paint(wd, &tos->wpaint->paint);
- }
- if (tos->sculpt) {
- writestruct(wd, DATA, Sculpt, 1, tos->sculpt);
- write_paint(wd, &tos->sculpt->paint);
- }
- if (tos->uvsculpt) {
- writestruct(wd, DATA, UvSculpt, 1, tos->uvsculpt);
- write_paint(wd, &tos->uvsculpt->paint);
+ ToolSettings *tos = sce->toolsettings;
+ writestruct(wd, DATA, ToolSettings, 1, tos);
+ if (tos->vpaint) {
+ writestruct(wd, DATA, VPaint, 1, tos->vpaint);
+ write_paint(wd, &tos->vpaint->paint);
+ }
+ if (tos->wpaint) {
+ writestruct(wd, DATA, VPaint, 1, tos->wpaint);
+ write_paint(wd, &tos->wpaint->paint);
+ }
+ if (tos->sculpt) {
+ writestruct(wd, DATA, Sculpt, 1, tos->sculpt);
+ write_paint(wd, &tos->sculpt->paint);
+ }
+ if (tos->uvsculpt) {
+ writestruct(wd, DATA, UvSculpt, 1, tos->uvsculpt);
+ write_paint(wd, &tos->uvsculpt->paint);
+ }
+ /* write grease-pencil drawing brushes to file */
+ writelist(wd, DATA, bGPDbrush, &tos->gp_brushes);
+ for (bGPDbrush *brush = tos->gp_brushes.first; brush; brush = brush->next) {
+ if (brush->cur_sensitivity) {
+ write_curvemapping(wd, brush->cur_sensitivity);
}
- /* write grease-pencil drawing brushes to file */
- writelist(wd, DATA, bGPDbrush, &tos->gp_brushes);
- for (bGPDbrush *brush = tos->gp_brushes.first; brush; brush = brush->next) {
- if (brush->cur_sensitivity) {
- write_curvemapping(wd, brush->cur_sensitivity);
- }
- if (brush->cur_strength) {
- write_curvemapping(wd, brush->cur_strength);
- }
- if (brush->cur_jitter) {
- write_curvemapping(wd, brush->cur_jitter);
- }
+ if (brush->cur_strength) {
+ write_curvemapping(wd, brush->cur_strength);
}
- /* write grease-pencil custom ipo curve to file */
- if (tos->gp_interpolate.custom_ipo) {
- write_curvemapping(wd, tos->gp_interpolate.custom_ipo);
+ if (brush->cur_jitter) {
+ write_curvemapping(wd, brush->cur_jitter);
}
-
+ }
+ /* write grease-pencil custom ipo curve to file */
+ if (tos->gp_interpolate.custom_ipo) {
+ write_curvemapping(wd, tos->gp_interpolate.custom_ipo);
+ }
- write_paint(wd, &tos->imapaint.paint);
- Editing *ed = sce->ed;
- if (ed) {
- Sequence *seq;
+ write_paint(wd, &tos->imapaint.paint);
- writestruct(wd, DATA, Editing, 1, ed);
+ Editing *ed = sce->ed;
+ if (ed) {
+ Sequence *seq;
- /* reset write flags too */
+ writestruct(wd, DATA, Editing, 1, ed);
- SEQ_BEGIN(ed, seq)
- {
- if (seq->strip) {
- seq->strip->done = false;
- }
- writestruct(wd, DATA, Sequence, 1, seq);
- }
- SEQ_END
+ /* reset write flags too */
- SEQ_BEGIN(ed, seq)
- {
- if (seq->strip && seq->strip->done == 0) {
- /* write strip with 'done' at 0 because readfile */
-
- if (seq->effectdata) {
- switch (seq->type) {
- case SEQ_TYPE_COLOR:
- writestruct(wd, DATA, SolidColorVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_SPEED:
- writestruct(wd, DATA, SpeedControlVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_WIPE:
- writestruct(wd, DATA, WipeVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_GLOW:
- writestruct(wd, DATA, GlowVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_TRANSFORM:
- writestruct(wd, DATA, TransformVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_GAUSSIAN_BLUR:
- writestruct(wd, DATA, GaussianBlurVars, 1, seq->effectdata);
- break;
- case SEQ_TYPE_TEXT:
- writestruct(wd, DATA, TextVars, 1, seq->effectdata);
- break;
- }
- }
+ SEQ_BEGIN(ed, seq)
+ {
+ if (seq->strip) {
+ seq->strip->done = false;
+ }
+ writestruct(wd, DATA, Sequence, 1, seq);
+ }
+ SEQ_END
- writestruct(wd, DATA, Stereo3dFormat, 1, seq->stereo3d_format);
+ SEQ_BEGIN(ed, seq)
+ {
+ if (seq->strip && seq->strip->done == 0) {
+ /* write strip with 'done' at 0 because readfile */
- Strip *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->type == SEQ_TYPE_IMAGE) {
- writestruct(wd, DATA, StripElem,
- MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem),
- strip->stripdata);
- }
- else if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) {
- writestruct(wd, DATA, StripElem, 1, strip->stripdata);
+ if (seq->effectdata) {
+ switch (seq->type) {
+ case SEQ_TYPE_COLOR:
+ writestruct(wd, DATA, SolidColorVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_SPEED:
+ writestruct(wd, DATA, SpeedControlVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_WIPE:
+ writestruct(wd, DATA, WipeVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_GLOW:
+ writestruct(wd, DATA, GlowVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_TRANSFORM:
+ writestruct(wd, DATA, TransformVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_GAUSSIAN_BLUR:
+ writestruct(wd, DATA, GaussianBlurVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_TEXT:
+ writestruct(wd, DATA, TextVars, 1, seq->effectdata);
+ break;
+ case SEQ_TYPE_COLORMIX:
+ writestruct(wd, DATA, ColorMixVars, 1, seq->effectdata);
+ break;
}
-
- strip->done = true;
}
- if (seq->prop) {
- IDP_WriteProperty(seq->prop, wd);
+ writestruct(wd, DATA, Stereo3dFormat, 1, seq->stereo3d_format);
+
+ Strip *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->type == SEQ_TYPE_IMAGE) {
+ writestruct(wd, DATA, StripElem,
+ MEM_allocN_len(strip->stripdata) / sizeof(struct StripElem),
+ strip->stripdata);
+ }
+ else if (ELEM(seq->type, SEQ_TYPE_MOVIE, SEQ_TYPE_SOUND_RAM, SEQ_TYPE_SOUND_HD)) {
+ writestruct(wd, DATA, StripElem, 1, strip->stripdata);
}
- write_sequence_modifiers(wd, &seq->modifiers);
+ strip->done = true;
}
- SEQ_END
- /* new; meta stack too, even when its nasty restore code */
- for (MetaStack *ms = ed->metastack.first; ms; ms = ms->next) {
- writestruct(wd, DATA, MetaStack, 1, ms);
+ if (seq->prop) {
+ IDP_WriteProperty(seq->prop, wd);
}
+
+ write_sequence_modifiers(wd, &seq->modifiers);
}
+ SEQ_END
- if (sce->r.avicodecdata) {
- writestruct(wd, DATA, AviCodecData, 1, sce->r.avicodecdata);
- if (sce->r.avicodecdata->lpFormat) {
- writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
- }
- if (sce->r.avicodecdata->lpParms) {
- writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
- }
+ /* new; meta stack too, even when its nasty restore code */
+ for (MetaStack *ms = ed->metastack.first; ms; ms = ms->next) {
+ writestruct(wd, DATA, MetaStack, 1, ms);
}
+ }
- if (sce->r.qtcodecdata) {
- 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.avicodecdata) {
+ writestruct(wd, DATA, AviCodecData, 1, sce->r.avicodecdata);
+ if (sce->r.avicodecdata->lpFormat) {
+ writedata(wd, DATA, sce->r.avicodecdata->cbFormat, sce->r.avicodecdata->lpFormat);
}
- if (sce->r.ffcodecdata.properties) {
- IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
+ if (sce->r.avicodecdata->lpParms) {
+ writedata(wd, DATA, sce->r.avicodecdata->cbParms, sce->r.avicodecdata->lpParms);
}
+ }
+ if (sce->r.ffcodecdata.properties) {
+ IDP_WriteProperty(sce->r.ffcodecdata.properties, wd);
+ }
- /* writing dynamic list of TimeMarkers to the blend file */
- for (TimeMarker *marker = sce->markers.first; marker; marker = marker->next) {
- writestruct(wd, DATA, TimeMarker, 1, marker);
- }
+ /* writing dynamic list of TimeMarkers to the blend file */
+ for (TimeMarker *marker = sce->markers.first; marker; marker = marker->next) {
+ writestruct(wd, DATA, TimeMarker, 1, marker);
+ }
- /* writing dynamic list of TransformOrientations to the blend file */
- for (TransformOrientation *ts = sce->transform_spaces.first; ts; ts = ts->next) {
- writestruct(wd, DATA, TransformOrientation, 1, ts);
- }
+ /* writing dynamic list of TransformOrientations to the blend file */
+ for (TransformOrientation *ts = sce->transform_spaces.first; ts; ts = ts->next) {
+ writestruct(wd, DATA, TransformOrientation, 1, ts);
+ }
- for (SceneRenderLayer *srl = sce->r.layers.first; srl; srl = srl->next) {
- writestruct(wd, DATA, SceneRenderLayer, 1, srl);
- for (FreestyleModuleConfig *fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
- writestruct(wd, DATA, FreestyleModuleConfig, 1, fmc);
- }
- for (FreestyleLineSet *fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
- writestruct(wd, DATA, FreestyleLineSet, 1, fls);
- }
+ for (SceneRenderLayer *srl = sce->r.layers.first; srl; srl = srl->next) {
+ writestruct(wd, DATA, SceneRenderLayer, 1, srl);
+ if (srl->prop) {
+ IDP_WriteProperty(srl->prop, wd);
}
-
- /* writing MultiView to the blend file */
- for (SceneRenderView *srv = sce->r.views.first; srv; srv = srv->next) {
- writestruct(wd, DATA, SceneRenderView, 1, srv);
+ for (FreestyleModuleConfig *fmc = srl->freestyleConfig.modules.first; fmc; fmc = fmc->next) {
+ writestruct(wd, DATA, FreestyleModuleConfig, 1, fmc);
}
-
- if (sce->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, sce->nodetree);
- write_nodetree(wd, sce->nodetree);
+ for (FreestyleLineSet *fls = srl->freestyleConfig.linesets.first; fls; fls = fls->next) {
+ writestruct(wd, DATA, FreestyleLineSet, 1, fls);
}
+ }
- write_view_settings(wd, &sce->view_settings);
+ /* writing MultiView to the blend file */
+ for (SceneRenderView *srv = sce->r.views.first; srv; srv = srv->next) {
+ writestruct(wd, DATA, SceneRenderView, 1, srv);
+ }
- /* writing RigidBodyWorld data to the blend file */
- if (sce->rigidbody_world) {
- writestruct(wd, DATA, RigidBodyWorld, 1, sce->rigidbody_world);
- writestruct(wd, DATA, EffectorWeights, 1, sce->rigidbody_world->effector_weights);
- write_pointcaches(wd, &(sce->rigidbody_world->ptcaches));
- }
+ if (sce->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, sce->nodetree);
+ write_nodetree_nolib(wd, sce->nodetree);
+ }
- write_previews(wd, sce->preview);
- write_curvemapping_curves(wd, &sce->r.mblur_shutter_curve);
+ write_view_settings(wd, &sce->view_settings);
+
+ /* writing RigidBodyWorld data to the blend file */
+ if (sce->rigidbody_world) {
+ writestruct(wd, DATA, RigidBodyWorld, 1, sce->rigidbody_world);
+ writestruct(wd, DATA, EffectorWeights, 1, sce->rigidbody_world->effector_weights);
+ write_pointcaches(wd, &(sce->rigidbody_world->ptcaches));
}
- mywrite_flush(wd);
+ write_previews(wd, sce->preview);
+ write_curvemapping_curves(wd, &sce->r.mblur_shutter_curve);
}
-static void write_gpencils(WriteData *wd, ListBase *lb)
+static void write_gpencil(WriteData *wd, bGPdata *gpd)
{
- for (bGPdata *gpd = lb->first; gpd; gpd = gpd->id.next) {
- if (gpd->id.us > 0 || wd->current) {
- /* write gpd data block to file */
- writestruct(wd, ID_GD, bGPdata, 1, gpd);
- write_iddata(wd, &gpd->id);
-
- if (gpd->adt) {
- write_animdata(wd, gpd->adt);
- }
-
- /* write grease-pencil layers to file */
- writelist(wd, DATA, bGPDlayer, &gpd->layers);
- for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
- /* write this layer's frames to file */
- writelist(wd, DATA, bGPDframe, &gpl->frames);
- for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
- /* write strokes */
- writelist(wd, DATA, bGPDstroke, &gpf->strokes);
- for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
- writestruct(wd, DATA, bGPDspoint, gps->totpoints, gps->points);
- }
+ if (gpd->id.us > 0 || wd->use_memfile) {
+ /* write gpd data block to file */
+ writestruct(wd, ID_GD, bGPdata, 1, gpd);
+ write_iddata(wd, &gpd->id);
+
+ if (gpd->adt) {
+ write_animdata(wd, gpd->adt);
+ }
+
+ /* write grease-pencil layers to file */
+ writelist(wd, DATA, bGPDlayer, &gpd->layers);
+ for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
+ /* write this layer's frames to file */
+ writelist(wd, DATA, bGPDframe, &gpl->frames);
+ for (bGPDframe *gpf = gpl->frames.first; gpf; gpf = gpf->next) {
+ /* write strokes */
+ writelist(wd, DATA, bGPDstroke, &gpf->strokes);
+ for (bGPDstroke *gps = gpf->strokes.first; gps; gps = gps->next) {
+ writestruct(wd, DATA, bGPDspoint, gps->totpoints, gps->points);
}
}
+ }
- /* write grease-pencil palettes */
- writelist(wd, DATA, bGPDpalette, &gpd->palettes);
- for (bGPDpalette *palette = gpd->palettes.first; palette; palette = palette->next) {
- writelist(wd, DATA, bGPDpalettecolor, &palette->colors);
- }
+ /* write grease-pencil palettes */
+ writelist(wd, DATA, bGPDpalette, &gpd->palettes);
+ for (bGPDpalette *palette = gpd->palettes.first; palette; palette = palette->next) {
+ writelist(wd, DATA, bGPDpalettecolor, &palette->colors);
}
}
-
- mywrite_flush(wd);
}
-static void write_windowmanagers(WriteData *wd, ListBase *lb)
+static void write_windowmanager(WriteData *wd, wmWindowManager *wm)
{
- for (wmWindowManager *wm = lb->first; wm; wm = wm->id.next) {
- writestruct(wd, ID_WM, wmWindowManager, 1, wm);
- write_iddata(wd, &wm->id);
+ writestruct(wd, ID_WM, wmWindowManager, 1, wm);
+ write_iddata(wd, &wm->id);
- for (wmWindow *win = wm->windows.first; win; win = win->next) {
- writestruct(wd, DATA, wmWindow, 1, win);
- writestruct(wd, DATA, Stereo3dFormat, 1, win->stereo3d_format);
- }
+ for (wmWindow *win = wm->windows.first; win; win = win->next) {
+ writestruct(wd, DATA, wmWindow, 1, win);
+ writestruct(wd, DATA, Stereo3dFormat, 1, win->stereo3d_format);
}
-
- /* typically flushing wouldn't be needed however this data _always_ changes,
- * so flush here for more efficient undo. */
- mywrite_flush(wd);
}
static void write_region(WriteData *wd, ARegion *ar, int spacetype)
@@ -2865,7 +2864,7 @@ static void write_soops(WriteData *wd, SpaceOops *so)
if (ts) {
SpaceOops so_flat = *so;
- int elems = BLI_mempool_count(ts);
+ int elems = BLI_mempool_len(ts);
/* linearize mempool to array */
TreeStoreElem *data = elems ? BLI_mempool_as_arrayN(ts, "TreeStoreElem") : NULL;
@@ -2901,172 +2900,168 @@ static void write_soops(WriteData *wd, SpaceOops *so)
}
}
-static void write_screens(WriteData *wd, ListBase *scrbase)
+static void write_screen(WriteData *wd, bScreen *sc)
{
- for (bScreen *sc = scrbase->first; sc; sc = sc->id.next) {
- /* write LibData */
- /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
- writestruct(wd, ID_SCRN, bScreen, 1, sc);
- write_iddata(wd, &sc->id);
-
- /* direct data */
- for (ScrVert *sv = sc->vertbase.first; sv; sv = sv->next) {
- writestruct(wd, DATA, ScrVert, 1, sv);
- }
-
- for (ScrEdge *se = sc->edgebase.first; se; se = se->next) {
- writestruct(wd, DATA, ScrEdge, 1, se);
- }
+ /* write LibData */
+ /* in 2.50+ files, the file identifier for screens is patched, forward compatibility */
+ writestruct(wd, ID_SCRN, bScreen, 1, sc);
+ write_iddata(wd, &sc->id);
- for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
- SpaceLink *sl;
- Panel *pa;
- uiList *ui_list;
- uiPreview *ui_preview;
- PanelCategoryStack *pc_act;
- ARegion *ar;
+ /* direct data */
+ for (ScrVert *sv = sc->vertbase.first; sv; sv = sv->next) {
+ writestruct(wd, DATA, ScrVert, 1, sv);
+ }
- writestruct(wd, DATA, ScrArea, 1, sa);
+ for (ScrEdge *se = sc->edgebase.first; se; se = se->next) {
+ writestruct(wd, DATA, ScrEdge, 1, se);
+ }
- for (ar = sa->regionbase.first; ar; ar = ar->next) {
- write_region(wd, ar, sa->spacetype);
+ for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
+ SpaceLink *sl;
+ Panel *pa;
+ uiList *ui_list;
+ uiPreview *ui_preview;
+ PanelCategoryStack *pc_act;
+ ARegion *ar;
- for (pa = ar->panels.first; pa; pa = pa->next) {
- writestruct(wd, DATA, Panel, 1, pa);
- }
+ writestruct(wd, DATA, ScrArea, 1, sa);
- for (pc_act = ar->panels_category_active.first; pc_act; pc_act = pc_act->next) {
- writestruct(wd, DATA, PanelCategoryStack, 1, pc_act);
- }
+ for (ar = sa->regionbase.first; ar; ar = ar->next) {
+ write_region(wd, ar, sa->spacetype);
- for (ui_list = ar->ui_lists.first; ui_list; ui_list = ui_list->next) {
- write_uilist(wd, ui_list);
- }
-
- for (ui_preview = ar->ui_previews.first; ui_preview; ui_preview = ui_preview->next) {
- writestruct(wd, DATA, uiPreview, 1, ui_preview);
- }
+ for (pa = ar->panels.first; pa; pa = pa->next) {
+ writestruct(wd, DATA, Panel, 1, pa);
}
- for (sl = sa->spacedata.first; sl; sl = sl->next) {
- for (ar = sl->regionbase.first; ar; ar = ar->next) {
- write_region(wd, ar, sl->spacetype);
- }
-
- if (sl->spacetype == SPACE_VIEW3D) {
- View3D *v3d = (View3D *)sl;
- BGpic *bgpic;
- writestruct(wd, DATA, View3D, 1, v3d);
- for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
- writestruct(wd, DATA, BGpic, 1, bgpic);
- }
- if (v3d->localvd) {
- writestruct(wd, DATA, View3D, 1, v3d->localvd);
- }
+ for (pc_act = ar->panels_category_active.first; pc_act; pc_act = pc_act->next) {
+ writestruct(wd, DATA, PanelCategoryStack, 1, pc_act);
+ }
- if (v3d->fx_settings.ssao) {
- writestruct(wd, DATA, GPUSSAOSettings, 1, v3d->fx_settings.ssao);
- }
- if (v3d->fx_settings.dof) {
- writestruct(wd, DATA, GPUDOFSettings, 1, v3d->fx_settings.dof);
- }
- }
- else if (sl->spacetype == SPACE_IPO) {
- SpaceIpo *sipo = (SpaceIpo *)sl;
- ListBase tmpGhosts = sipo->ghostCurves;
+ for (ui_list = ar->ui_lists.first; ui_list; ui_list = ui_list->next) {
+ write_uilist(wd, ui_list);
+ }
- /* temporarily disable ghost curves when saving */
- sipo->ghostCurves.first = sipo->ghostCurves.last = NULL;
+ for (ui_preview = ar->ui_previews.first; ui_preview; ui_preview = ui_preview->next) {
+ writestruct(wd, DATA, uiPreview, 1, ui_preview);
+ }
+ }
- writestruct(wd, DATA, SpaceIpo, 1, sl);
- if (sipo->ads) {
- writestruct(wd, DATA, bDopeSheet, 1, sipo->ads);
- }
+ for (sl = sa->spacedata.first; sl; sl = sl->next) {
+ for (ar = sl->regionbase.first; ar; ar = ar->next) {
+ write_region(wd, ar, sl->spacetype);
+ }
- /* reenable ghost curves */
- sipo->ghostCurves = tmpGhosts;
+ if (sl->spacetype == SPACE_VIEW3D) {
+ View3D *v3d = (View3D *)sl;
+ BGpic *bgpic;
+ writestruct(wd, DATA, View3D, 1, v3d);
+ for (bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
+ writestruct(wd, DATA, BGpic, 1, bgpic);
}
- else if (sl->spacetype == SPACE_BUTS) {
- writestruct(wd, DATA, SpaceButs, 1, sl);
+ if (v3d->localvd) {
+ writestruct(wd, DATA, View3D, 1, v3d->localvd);
}
- else if (sl->spacetype == SPACE_FILE) {
- SpaceFile *sfile = (SpaceFile *)sl;
- writestruct(wd, DATA, SpaceFile, 1, sl);
- if (sfile->params) {
- writestruct(wd, DATA, FileSelectParams, 1, sfile->params);
- }
- }
- else if (sl->spacetype == SPACE_SEQ) {
- writestruct(wd, DATA, SpaceSeq, 1, sl);
- }
- else if (sl->spacetype == SPACE_OUTLINER) {
- SpaceOops *so = (SpaceOops *)sl;
- write_soops(wd, so);
- }
- else if (sl->spacetype == SPACE_IMAGE) {
- writestruct(wd, DATA, SpaceImage, 1, sl);
- }
- else if (sl->spacetype == SPACE_TEXT) {
- writestruct(wd, DATA, SpaceText, 1, sl);
- }
- else if (sl->spacetype == SPACE_SCRIPT) {
- SpaceScript *scr = (SpaceScript *)sl;
- scr->but_refs = NULL;
- writestruct(wd, DATA, SpaceScript, 1, sl);
+ if (v3d->fx_settings.ssao) {
+ writestruct(wd, DATA, GPUSSAOSettings, 1, v3d->fx_settings.ssao);
}
- else if (sl->spacetype == SPACE_ACTION) {
- writestruct(wd, DATA, SpaceAction, 1, sl);
+ if (v3d->fx_settings.dof) {
+ writestruct(wd, DATA, GPUDOFSettings, 1, v3d->fx_settings.dof);
}
- else if (sl->spacetype == SPACE_NLA) {
- SpaceNla *snla = (SpaceNla *)sl;
+ }
+ else if (sl->spacetype == SPACE_IPO) {
+ SpaceIpo *sipo = (SpaceIpo *)sl;
+ ListBase tmpGhosts = sipo->ghostCurves;
- writestruct(wd, DATA, SpaceNla, 1, snla);
- if (snla->ads) {
- writestruct(wd, DATA, bDopeSheet, 1, snla->ads);
- }
- }
- else if (sl->spacetype == SPACE_TIME) {
- writestruct(wd, DATA, SpaceTime, 1, sl);
- }
- else if (sl->spacetype == SPACE_NODE) {
- SpaceNode *snode = (SpaceNode *)sl;
- bNodeTreePath *path;
- writestruct(wd, DATA, SpaceNode, 1, snode);
+ /* temporarily disable ghost curves when saving */
+ sipo->ghostCurves.first = sipo->ghostCurves.last = NULL;
- for (path = snode->treepath.first; path; path = path->next) {
- writestruct(wd, DATA, bNodeTreePath, 1, path);
- }
- }
- else if (sl->spacetype == SPACE_LOGIC) {
- writestruct(wd, DATA, SpaceLogic, 1, sl);
+ writestruct(wd, DATA, SpaceIpo, 1, sl);
+ if (sipo->ads) {
+ writestruct(wd, DATA, bDopeSheet, 1, sipo->ads);
}
- else if (sl->spacetype == SPACE_CONSOLE) {
- SpaceConsole *con = (SpaceConsole *)sl;
- ConsoleLine *cl;
-
- for (cl = con->history.first; cl; cl = cl->next) {
- /* 'len_alloc' is invalid on write, set from 'len' on read */
- writestruct(wd, DATA, ConsoleLine, 1, cl);
- writedata(wd, DATA, cl->len + 1, cl->line);
- }
- writestruct(wd, DATA, SpaceConsole, 1, sl);
+ /* reenable ghost curves */
+ sipo->ghostCurves = tmpGhosts;
+ }
+ else if (sl->spacetype == SPACE_BUTS) {
+ writestruct(wd, DATA, SpaceButs, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_FILE) {
+ SpaceFile *sfile = (SpaceFile *)sl;
+
+ writestruct(wd, DATA, SpaceFile, 1, sl);
+ if (sfile->params) {
+ writestruct(wd, DATA, FileSelectParams, 1, sfile->params);
}
- else if (sl->spacetype == SPACE_USERPREF) {
- writestruct(wd, DATA, SpaceUserPref, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_SEQ) {
+ writestruct(wd, DATA, SpaceSeq, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_OUTLINER) {
+ SpaceOops *so = (SpaceOops *)sl;
+ write_soops(wd, so);
+ }
+ else if (sl->spacetype == SPACE_IMAGE) {
+ writestruct(wd, DATA, SpaceImage, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_TEXT) {
+ writestruct(wd, DATA, SpaceText, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_SCRIPT) {
+ SpaceScript *scr = (SpaceScript *)sl;
+ scr->but_refs = NULL;
+ writestruct(wd, DATA, SpaceScript, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_ACTION) {
+ writestruct(wd, DATA, SpaceAction, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_NLA) {
+ SpaceNla *snla = (SpaceNla *)sl;
+
+ writestruct(wd, DATA, SpaceNla, 1, snla);
+ if (snla->ads) {
+ writestruct(wd, DATA, bDopeSheet, 1, snla->ads);
}
- else if (sl->spacetype == SPACE_CLIP) {
- writestruct(wd, DATA, SpaceClip, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_TIME) {
+ writestruct(wd, DATA, SpaceTime, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_NODE) {
+ SpaceNode *snode = (SpaceNode *)sl;
+ bNodeTreePath *path;
+ writestruct(wd, DATA, SpaceNode, 1, snode);
+
+ for (path = snode->treepath.first; path; path = path->next) {
+ writestruct(wd, DATA, bNodeTreePath, 1, path);
}
- else if (sl->spacetype == SPACE_INFO) {
- writestruct(wd, DATA, SpaceInfo, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_LOGIC) {
+ writestruct(wd, DATA, SpaceLogic, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_CONSOLE) {
+ SpaceConsole *con = (SpaceConsole *)sl;
+ ConsoleLine *cl;
+
+ for (cl = con->history.first; cl; cl = cl->next) {
+ /* 'len_alloc' is invalid on write, set from 'len' on read */
+ writestruct(wd, DATA, ConsoleLine, 1, cl);
+ writedata(wd, DATA, cl->len + 1, cl->line);
}
+ writestruct(wd, DATA, SpaceConsole, 1, sl);
+
+ }
+ else if (sl->spacetype == SPACE_USERPREF) {
+ writestruct(wd, DATA, SpaceUserPref, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_CLIP) {
+ writestruct(wd, DATA, SpaceClip, 1, sl);
+ }
+ else if (sl->spacetype == SPACE_INFO) {
+ writestruct(wd, DATA, SpaceInfo, 1, sl);
}
}
}
-
- mywrite_flush(wd);
}
static void write_bone(WriteData *wd, Bone *bone)
@@ -3089,121 +3084,101 @@ static void write_bone(WriteData *wd, Bone *bone)
}
}
-static void write_armatures(WriteData *wd, ListBase *idbase)
+static void write_armature(WriteData *wd, bArmature *arm)
{
- for (bArmature *arm = idbase->first; arm; arm = arm->id.next) {
- if (arm->id.us > 0 || wd->current) {
- writestruct(wd, ID_AR, bArmature, 1, arm);
- write_iddata(wd, &arm->id);
+ if (arm->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_AR, bArmature, 1, arm);
+ write_iddata(wd, &arm->id);
- if (arm->adt) {
- write_animdata(wd, arm->adt);
- }
+ if (arm->adt) {
+ write_animdata(wd, arm->adt);
+ }
- /* Direct data */
- for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
- write_bone(wd, bone);
- }
+ /* Direct data */
+ for (Bone *bone = arm->bonebase.first; bone; bone = bone->next) {
+ write_bone(wd, bone);
}
}
-
- mywrite_flush(wd);
}
-static void write_texts(WriteData *wd, ListBase *idbase)
+static void write_text(WriteData *wd, Text *text)
{
- for (Text *text = idbase->first; text; text = text->id.next) {
- if ((text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) {
- text->flags &= ~TXT_ISEXT;
- }
+ if ((text->flags & TXT_ISMEM) && (text->flags & TXT_ISEXT)) {
+ text->flags &= ~TXT_ISEXT;
+ }
- /* write LibData */
- writestruct(wd, ID_TXT, Text, 1, text);
- write_iddata(wd, &text->id);
+ /* write LibData */
+ writestruct(wd, ID_TXT, Text, 1, text);
+ write_iddata(wd, &text->id);
- if (text->name) {
- writedata(wd, DATA, strlen(text->name) + 1, text->name);
- }
+ if (text->name) {
+ writedata(wd, DATA, strlen(text->name) + 1, text->name);
+ }
- if (!(text->flags & TXT_ISEXT)) {
- /* now write the text data, in two steps for optimization in the readfunction */
- for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
- writestruct(wd, DATA, TextLine, 1, tmp);
- }
+ if (!(text->flags & TXT_ISEXT)) {
+ /* now write the text data, in two steps for optimization in the readfunction */
+ for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
+ writestruct(wd, DATA, TextLine, 1, tmp);
+ }
- for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
- writedata(wd, DATA, tmp->len + 1, tmp->line);
- }
+ for (TextLine *tmp = text->lines.first; tmp; tmp = tmp->next) {
+ writedata(wd, DATA, tmp->len + 1, tmp->line);
}
}
-
- mywrite_flush(wd);
}
-static void write_speakers(WriteData *wd, ListBase *idbase)
+static void write_speaker(WriteData *wd, Speaker *spk)
{
- for (Speaker *spk = idbase->first; spk; spk = spk->id.next) {
- if (spk->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_SPK, Speaker, 1, spk);
- write_iddata(wd, &spk->id);
-
- if (spk->adt) {
- write_animdata(wd, spk->adt);
- }
+ if (spk->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_SPK, Speaker, 1, spk);
+ write_iddata(wd, &spk->id);
+
+ if (spk->adt) {
+ write_animdata(wd, spk->adt);
}
}
}
-static void write_sounds(WriteData *wd, ListBase *idbase)
+static void write_sound(WriteData *wd, bSound *sound)
{
- for (bSound *sound = idbase->first; sound; sound = sound->id.next) {
- if (sound->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_SO, bSound, 1, sound);
- write_iddata(wd, &sound->id);
-
- if (sound->packedfile) {
- PackedFile *pf = sound->packedfile;
- writestruct(wd, DATA, PackedFile, 1, pf);
- writedata(wd, DATA, pf->size, pf->data);
- }
+ if (sound->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_SO, bSound, 1, sound);
+ write_iddata(wd, &sound->id);
+
+ if (sound->packedfile) {
+ PackedFile *pf = sound->packedfile;
+ writestruct(wd, DATA, PackedFile, 1, pf);
+ writedata(wd, DATA, pf->size, pf->data);
}
}
-
- mywrite_flush(wd);
}
-static void write_groups(WriteData *wd, ListBase *idbase)
+static void write_group(WriteData *wd, Group *group)
{
- for (Group *group = idbase->first; group; group = group->id.next) {
- if (group->id.us > 0 || wd->current) {
- /* write LibData */
- writestruct(wd, ID_GR, Group, 1, group);
- write_iddata(wd, &group->id);
+ if (group->id.us > 0 || wd->use_memfile) {
+ /* write LibData */
+ writestruct(wd, ID_GR, Group, 1, group);
+ write_iddata(wd, &group->id);
- write_previews(wd, group->preview);
+ write_previews(wd, group->preview);
- for (GroupObject *go = group->gobject.first; go; go = go->next) {
- writestruct(wd, DATA, GroupObject, 1, go);
- }
+ for (GroupObject *go = group->gobject.first; go; go = go->next) {
+ writestruct(wd, DATA, GroupObject, 1, go);
}
}
-
- mywrite_flush(wd);
}
-static void write_nodetrees(WriteData *wd, ListBase *idbase)
+static void write_nodetree(WriteData *wd, bNodeTree *ntree)
{
- for (bNodeTree *ntree = idbase->first; ntree; ntree = ntree->id.next) {
- if (ntree->id.us > 0 || wd->current) {
- writestruct(wd, ID_NT, bNodeTree, 1, ntree);
- /* Note that trees directly used by other IDs (materials etc.) are not 'real' ID, they cannot
- * be linked, etc., so we write actual id data here only, for 'real' ID trees. */
- write_iddata(wd, &ntree->id);
+ if (ntree->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_NT, bNodeTree, 1, ntree);
+ /* Note that trees directly used by other IDs (materials etc.) are not 'real' ID, they cannot
+ * be linked, etc., so we write actual id data here only, for 'real' ID trees. */
+ write_iddata(wd, &ntree->id);
- write_nodetree(wd, ntree);
- }
+ write_nodetree_nolib(wd, ntree);
}
}
@@ -3277,47 +3252,41 @@ static void customnodes_free_deprecated_data(Main *mainvar)
}
#endif
-static void write_brushes(WriteData *wd, ListBase *idbase)
+static void write_brush(WriteData *wd, Brush *brush)
{
- for (Brush *brush = idbase->first; brush; brush = brush->id.next) {
- if (brush->id.us > 0 || wd->current) {
- writestruct(wd, ID_BR, Brush, 1, brush);
- write_iddata(wd, &brush->id);
+ if (brush->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_BR, Brush, 1, brush);
+ write_iddata(wd, &brush->id);
- if (brush->curve) {
- write_curvemapping(wd, brush->curve);
- }
- if (brush->gradient) {
- writestruct(wd, DATA, ColorBand, 1, brush->gradient);
- }
+ if (brush->curve) {
+ write_curvemapping(wd, brush->curve);
+ }
+ if (brush->gradient) {
+ writestruct(wd, DATA, ColorBand, 1, brush->gradient);
}
}
}
-static void write_palettes(WriteData *wd, ListBase *idbase)
+static void write_palette(WriteData *wd, Palette *palette)
{
- for (Palette *palette = idbase->first; palette; palette = palette->id.next) {
- if (palette->id.us > 0 || wd->current) {
- PaletteColor *color;
- writestruct(wd, ID_PAL, Palette, 1, palette);
- write_iddata(wd, &palette->id);
-
- for (color = palette->colors.first; color; color = color->next) {
- writestruct(wd, DATA, PaletteColor, 1, color);
- }
+ if (palette->id.us > 0 || wd->use_memfile) {
+ PaletteColor *color;
+ writestruct(wd, ID_PAL, Palette, 1, palette);
+ write_iddata(wd, &palette->id);
+
+ for (color = palette->colors.first; color; color = color->next) {
+ writestruct(wd, DATA, PaletteColor, 1, color);
}
}
}
-static void write_paintcurves(WriteData *wd, ListBase *idbase)
+static void write_paintcurve(WriteData *wd, PaintCurve *pc)
{
- for (PaintCurve *pc = idbase->first; pc; pc = pc->id.next) {
- if (pc->id.us > 0 || wd->current) {
- writestruct(wd, ID_PC, PaintCurve, 1, pc);
- write_iddata(wd, &pc->id);
+ if (pc->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_PC, PaintCurve, 1, pc);
+ write_iddata(wd, &pc->id);
- writestruct(wd, DATA, PaintCurvePoint, pc->tot_points, pc->points);
- }
+ writestruct(wd, DATA, PaintCurvePoint, pc->tot_points, pc->points);
}
}
@@ -3359,93 +3328,85 @@ static void write_movieReconstruction(WriteData *wd, MovieTrackingReconstruction
}
}
-static void write_movieclips(WriteData *wd, ListBase *idbase)
+static void write_movieclip(WriteData *wd, MovieClip *clip)
{
- for (MovieClip *clip = idbase->first; clip; clip = clip->id.next) {
- if (clip->id.us > 0 || wd->current) {
- MovieTracking *tracking = &clip->tracking;
- MovieTrackingObject *object;
+ if (clip->id.us > 0 || wd->use_memfile) {
+ MovieTracking *tracking = &clip->tracking;
+ MovieTrackingObject *object;
- writestruct(wd, ID_MC, MovieClip, 1, clip);
- write_iddata(wd, &clip->id);
+ writestruct(wd, ID_MC, MovieClip, 1, clip);
+ write_iddata(wd, &clip->id);
- if (clip->adt) {
- write_animdata(wd, clip->adt);
- }
+ if (clip->adt) {
+ write_animdata(wd, clip->adt);
+ }
- write_movieTracks(wd, &tracking->tracks);
- write_moviePlaneTracks(wd, &tracking->plane_tracks);
- write_movieReconstruction(wd, &tracking->reconstruction);
+ write_movieTracks(wd, &tracking->tracks);
+ write_moviePlaneTracks(wd, &tracking->plane_tracks);
+ write_movieReconstruction(wd, &tracking->reconstruction);
- object = tracking->objects.first;
- while (object) {
- writestruct(wd, DATA, MovieTrackingObject, 1, object);
+ object = tracking->objects.first;
+ while (object) {
+ writestruct(wd, DATA, MovieTrackingObject, 1, object);
- write_movieTracks(wd, &object->tracks);
- write_moviePlaneTracks(wd, &object->plane_tracks);
- write_movieReconstruction(wd, &object->reconstruction);
+ write_movieTracks(wd, &object->tracks);
+ write_moviePlaneTracks(wd, &object->plane_tracks);
+ write_movieReconstruction(wd, &object->reconstruction);
- object = object->next;
- }
+ object = object->next;
}
}
-
- mywrite_flush(wd);
}
-static void write_masks(WriteData *wd, ListBase *idbase)
+static void write_mask(WriteData *wd, Mask *mask)
{
- for (Mask *mask = idbase->first; mask; mask = mask->id.next) {
- if (mask->id.us > 0 || wd->current) {
- MaskLayer *masklay;
+ if (mask->id.us > 0 || wd->use_memfile) {
+ MaskLayer *masklay;
- writestruct(wd, ID_MSK, Mask, 1, mask);
- write_iddata(wd, &mask->id);
+ writestruct(wd, ID_MSK, Mask, 1, mask);
+ write_iddata(wd, &mask->id);
- if (mask->adt) {
- write_animdata(wd, mask->adt);
- }
+ if (mask->adt) {
+ write_animdata(wd, mask->adt);
+ }
- for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
- MaskSpline *spline;
- MaskLayerShape *masklay_shape;
+ for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
+ MaskSpline *spline;
+ MaskLayerShape *masklay_shape;
- writestruct(wd, DATA, MaskLayer, 1, masklay);
+ writestruct(wd, DATA, MaskLayer, 1, masklay);
- for (spline = masklay->splines.first; spline; spline = spline->next) {
- int i;
+ for (spline = masklay->splines.first; spline; spline = spline->next) {
+ int i;
- void *points_deform = spline->points_deform;
- spline->points_deform = NULL;
+ void *points_deform = spline->points_deform;
+ spline->points_deform = NULL;
- writestruct(wd, DATA, MaskSpline, 1, spline);
- writestruct(wd, DATA, MaskSplinePoint, spline->tot_point, spline->points);
+ writestruct(wd, DATA, MaskSpline, 1, spline);
+ writestruct(wd, DATA, MaskSplinePoint, spline->tot_point, spline->points);
- spline->points_deform = points_deform;
+ spline->points_deform = points_deform;
- for (i = 0; i < spline->tot_point; i++) {
- MaskSplinePoint *point = &spline->points[i];
+ for (i = 0; i < spline->tot_point; i++) {
+ MaskSplinePoint *point = &spline->points[i];
- if (point->tot_uw) {
- writestruct(wd, DATA, MaskSplinePointUW, point->tot_uw, point->uw);
- }
+ if (point->tot_uw) {
+ writestruct(wd, DATA, MaskSplinePointUW, point->tot_uw, point->uw);
}
}
+ }
- for (masklay_shape = masklay->splines_shapes.first;
- masklay_shape;
- masklay_shape = masklay_shape->next)
- {
- writestruct(wd, DATA, MaskLayerShape, 1, masklay_shape);
- writedata(wd, DATA,
- masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE,
- masklay_shape->data);
- }
+ for (masklay_shape = masklay->splines_shapes.first;
+ masklay_shape;
+ masklay_shape = masklay_shape->next)
+ {
+ writestruct(wd, DATA, MaskLayerShape, 1, masklay_shape);
+ writedata(wd, DATA,
+ masklay_shape->tot_vert * sizeof(float) * MASK_OBJECT_SHAPE_ELEM_SIZE,
+ masklay_shape->data);
}
}
}
-
- mywrite_flush(wd);
}
static void write_linestyle_color_modifiers(WriteData *wd, ListBase *modifiers)
@@ -3702,43 +3663,39 @@ static void write_linestyle_geometry_modifiers(WriteData *wd, ListBase *modifier
}
}
-static void write_linestyles(WriteData *wd, ListBase *idbase)
+static void write_linestyle(WriteData *wd, FreestyleLineStyle *linestyle)
{
- for (FreestyleLineStyle *linestyle = idbase->first; linestyle; linestyle = linestyle->id.next) {
- if (linestyle->id.us > 0 || wd->current) {
- writestruct(wd, ID_LS, FreestyleLineStyle, 1, linestyle);
- write_iddata(wd, &linestyle->id);
+ if (linestyle->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_LS, FreestyleLineStyle, 1, linestyle);
+ write_iddata(wd, &linestyle->id);
- if (linestyle->adt) {
- write_animdata(wd, linestyle->adt);
- }
+ if (linestyle->adt) {
+ write_animdata(wd, linestyle->adt);
+ }
- write_linestyle_color_modifiers(wd, &linestyle->color_modifiers);
- write_linestyle_alpha_modifiers(wd, &linestyle->alpha_modifiers);
- write_linestyle_thickness_modifiers(wd, &linestyle->thickness_modifiers);
- write_linestyle_geometry_modifiers(wd, &linestyle->geometry_modifiers);
- for (int a = 0; a < MAX_MTEX; a++) {
- if (linestyle->mtex[a]) {
- writestruct(wd, DATA, MTex, 1, linestyle->mtex[a]);
- }
- }
- if (linestyle->nodetree) {
- writestruct(wd, DATA, bNodeTree, 1, linestyle->nodetree);
- write_nodetree(wd, linestyle->nodetree);
+ write_linestyle_color_modifiers(wd, &linestyle->color_modifiers);
+ write_linestyle_alpha_modifiers(wd, &linestyle->alpha_modifiers);
+ write_linestyle_thickness_modifiers(wd, &linestyle->thickness_modifiers);
+ write_linestyle_geometry_modifiers(wd, &linestyle->geometry_modifiers);
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (linestyle->mtex[a]) {
+ writestruct(wd, DATA, MTex, 1, linestyle->mtex[a]);
}
}
+ if (linestyle->nodetree) {
+ writestruct(wd, DATA, bNodeTree, 1, linestyle->nodetree);
+ write_nodetree_nolib(wd, linestyle->nodetree);
+ }
}
}
-static void write_cachefiles(WriteData *wd, ListBase *idbase)
+static void write_cachefile(WriteData *wd, CacheFile *cache_file)
{
- for (CacheFile *cache_file = idbase->first; cache_file; cache_file = cache_file->id.next) {
- if (cache_file->id.us > 0 || wd->current) {
- writestruct(wd, ID_CF, CacheFile, 1, cache_file);
+ if (cache_file->id.us > 0 || wd->use_memfile) {
+ writestruct(wd, ID_CF, CacheFile, 1, cache_file);
- if (cache_file->adt) {
- write_animdata(wd, cache_file->adt);
- }
+ if (cache_file->adt) {
+ write_animdata(wd, cache_file->adt);
}
}
}
@@ -3781,7 +3738,7 @@ static void write_libraries(WriteData *wd, Main *main)
PackedFile *pf = main->curlib->packedfile;
writestruct(wd, DATA, PackedFile, 1, pf);
writedata(wd, DATA, pf->size, pf->data);
- if (wd->current == NULL) {
+ if (wd->use_memfile == false) {
printf("write packed .blend: %s\n", main->curlib->name);
}
}
@@ -3809,7 +3766,7 @@ static void write_libraries(WriteData *wd, Main *main)
* - for undofile, curscene needs to be saved */
static void write_global(WriteData *wd, int fileflags, Main *mainvar)
{
- const bool is_undo = (wd->current != NULL);
+ const bool is_undo = wd->use_memfile;
FileGlobal fg;
bScreen *screen;
char subvstr[8];
@@ -3862,6 +3819,12 @@ static void write_thumb(WriteData *wd, const BlendThumbnail *thumb)
}
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name File Writing (Private)
+ * \{ */
+
/* if MemFile * there's filesave to memory */
static bool write_file_handle(
Main *mainvar,
@@ -3876,7 +3839,7 @@ static bool write_file_handle(
blo_split_main(&mainlist, mainvar);
- wd = bgnwrite(ww, compare, current);
+ wd = mywrite_begin(ww, compare, current);
#ifdef USE_BMESH_SAVE_AS_COMPAT
wd->use_mesh_compat = (write_flags & G_FILE_MESH_COMPAT) != 0;
@@ -3905,45 +3868,141 @@ static bool write_file_handle(
* avoid thumbnail detecting changes because of this. */
mywrite_flush(wd);
- write_windowmanagers(wd, &mainvar->wm);
- write_screens(wd, &mainvar->screen);
- write_movieclips(wd, &mainvar->movieclip);
- write_masks(wd, &mainvar->mask);
- write_scenes(wd, &mainvar->scene);
- write_curves(wd, &mainvar->curve);
- write_mballs(wd, &mainvar->mball);
- write_images(wd, &mainvar->image);
- write_cameras(wd, &mainvar->camera);
- write_lamps(wd, &mainvar->lamp);
- write_lattices(wd, &mainvar->latt);
- write_vfonts(wd, &mainvar->vfont);
- write_keys(wd, &mainvar->key);
- write_worlds(wd, &mainvar->world);
- write_texts(wd, &mainvar->text);
- write_speakers(wd, &mainvar->speaker);
- write_sounds(wd, &mainvar->sound);
- write_groups(wd, &mainvar->group);
- write_armatures(wd, &mainvar->armature);
- write_actions(wd, &mainvar->action);
- write_objects(wd, &mainvar->object);
- write_materials(wd, &mainvar->mat);
- write_textures(wd, &mainvar->tex);
- write_meshes(wd, &mainvar->mesh);
- write_particlesettings(wd, &mainvar->particle);
- write_nodetrees(wd, &mainvar->nodetree);
- write_brushes(wd, &mainvar->brush);
- write_palettes(wd, &mainvar->palettes);
- write_paintcurves(wd, &mainvar->paintcurves);
- write_gpencils(wd, &mainvar->gpencil);
- write_linestyles(wd, &mainvar->linestyle);
- write_cachefiles(wd, &mainvar->cachefiles);
+ ListBase *lbarray[MAX_LIBARRAY];
+ int a = set_listbasepointers(mainvar, lbarray);
+ while (a--) {
+ ID *id = lbarray[a]->first;
+
+ if (id && GS(id->name) == ID_LI) {
+ continue; /* Libraries are handled separately below. */
+ }
+
+ for (; id; id = id->next) {
+ /* We should never attempt to write non-regular IDs (i.e. all kind of temp/runtime ones). */
+ BLI_assert((id->tag & (LIB_TAG_NO_MAIN | LIB_TAG_NO_USER_REFCOUNT | LIB_TAG_NOT_ALLOCATED)) == 0);
+
+ switch ((ID_Type)GS(id->name)) {
+ case ID_WM:
+ write_windowmanager(wd, (wmWindowManager *)id);
+ break;
+ case ID_SCR:
+ write_screen(wd, (bScreen *)id);
+ break;
+ case ID_MC:
+ write_movieclip(wd, (MovieClip *)id);
+ break;
+ case ID_MSK:
+ write_mask(wd, (Mask *)id);
+ break;
+ case ID_SCE:
+ write_scene(wd, (Scene *)id);
+ break;
+ case ID_CU:
+ write_curve(wd, (Curve *)id);
+ break;
+ case ID_MB:
+ write_mball(wd, (MetaBall *)id);
+ break;
+ case ID_IM:
+ write_image(wd, (Image *)id);
+ break;
+ case ID_CA:
+ write_camera(wd, (Camera *)id);
+ break;
+ case ID_LA:
+ write_lamp(wd, (Lamp *)id);
+ break;
+ case ID_LT:
+ write_lattice(wd, (Lattice *)id);
+ break;
+ case ID_VF:
+ write_vfont(wd, (VFont *)id);
+ break;
+ case ID_KE:
+ write_key(wd, (Key *)id);
+ break;
+ case ID_WO:
+ write_world(wd, (World *)id);
+ break;
+ case ID_TXT:
+ write_text(wd, (Text *)id);
+ break;
+ case ID_SPK:
+ write_speaker(wd, (Speaker *)id);
+ break;
+ case ID_SO:
+ write_sound(wd, (bSound *)id);
+ break;
+ case ID_GR:
+ write_group(wd, (Group *)id);
+ break;
+ case ID_AR:
+ write_armature(wd, (bArmature *)id);
+ break;
+ case ID_AC:
+ write_action(wd, (bAction *)id);
+ break;
+ case ID_OB:
+ write_object(wd, (Object *)id);
+ break;
+ case ID_MA:
+ write_material(wd, (Material *)id);
+ break;
+ case ID_TE:
+ write_texture(wd, (Tex *)id);
+ break;
+ case ID_ME:
+ write_mesh(wd, (Mesh *)id);
+ break;
+ case ID_PA:
+ write_particlesettings(wd, (ParticleSettings *)id);
+ break;
+ case ID_NT:
+ write_nodetree(wd, (bNodeTree *)id);
+ break;
+ case ID_BR:
+ write_brush(wd, (Brush *)id);
+ break;
+ case ID_PAL:
+ write_palette(wd, (Palette *)id);
+ break;
+ case ID_PC:
+ write_paintcurve(wd, (PaintCurve *)id);
+ break;
+ case ID_GD:
+ write_gpencil(wd, (bGPdata *)id);
+ break;
+ case ID_LS:
+ write_linestyle(wd, (FreestyleLineStyle *)id);
+ break;
+ case ID_CF:
+ write_cachefile(wd, (CacheFile *)id);
+ break;
+ case ID_LI:
+ /* Do nothing, handled below - and should never be reached. */
+ BLI_assert(0);
+ break;
+ case ID_IP:
+ /* Do nothing, deprecated. */
+ break;
+ default:
+ /* Should never be reached. */
+ BLI_assert(0);
+ break;
+ }
+ }
+
+ mywrite_flush(wd);
+ }
+
+ /* Special handling, operating over split Mains... */
write_libraries(wd, mainvar->next);
/* So changes above don't cause a 'DNA1' to be detected as changed on undo. */
mywrite_flush(wd);
if (write_flags & G_FILE_USERPREFS) {
- write_userdef(wd);
+ write_userdef(wd, &U);
}
/* Write DNA last, because (to be implemented) test for which structs are written.
@@ -3970,7 +4029,7 @@ static bool write_file_handle(
blo_join_main(&mainlist);
- return endwrite(wd);
+ return mywrite_end(wd);
}
/* do reverse file history: .blend1 -> .blend2, .blend -> .blend1 */
@@ -4015,6 +4074,12 @@ static bool do_history(const char *name, ReportList *reports)
return 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name File Writing (Public)
+ * \{ */
+
/**
* \return Success.
*/
@@ -4030,6 +4095,11 @@ bool BLO_write_file(
void *path_list_backup = NULL;
const int path_list_flag = (BKE_BPATH_TRAVERSE_SKIP_LIBRARY | BKE_BPATH_TRAVERSE_SKIP_MULTIFILE);
+ if (G.debug & G_DEBUG_IO && mainvar->lock != NULL) {
+ BKE_report(reports, RPT_INFO, "Checking sanity of current .blend file *BEFORE* save to disk.");
+ BLO_main_validate_libraries(mainvar, reports);
+ }
+
/* open temporary file, so we preserve the original in case we crash */
BLI_snprintf(tempname, sizeof(tempname), "%s@", filepath);
@@ -4114,6 +4184,11 @@ bool BLO_write_file(
return 0;
}
+ if (G.debug & G_DEBUG_IO && mainvar->lock != NULL) {
+ BKE_report(reports, RPT_INFO, "Checking sanity of current .blend file *AFTER* save to disk.");
+ BLO_main_validate_libraries(mainvar, reports);
+ }
+
return 1;
}
@@ -4128,3 +4203,5 @@ bool BLO_write_file_mem(Main *mainvar, MemFile *compare, MemFile *current, int w
return (err == 0);
}
+
+/** \} */
diff --git a/source/blender/blentranslation/CMakeLists.txt b/source/blender/blentranslation/CMakeLists.txt
index a3e85344027..320a784ea25 100644
--- a/source/blender/blentranslation/CMakeLists.txt
+++ b/source/blender/blentranslation/CMakeLists.txt
@@ -60,3 +60,7 @@ if(WIN32)
endif()
blender_add_lib(bf_blentranslation "${SRC}" "${INC}" "${INC_SYS}")
+
+if(WITH_INTERNATIONAL)
+ add_subdirectory(msgfmt)
+endif()
diff --git a/source/blender/quicktime/CMakeLists.txt b/source/blender/blentranslation/msgfmt/CMakeLists.txt
index f853c35457f..d2cb6f5a03b 100644
--- a/source/blender/quicktime/CMakeLists.txt
+++ b/source/blender/blentranslation/msgfmt/CMakeLists.txt
@@ -14,49 +14,37 @@
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
-# The Original Code is Copyright (C) 2006, Blender Foundation
+# The Original Code is Copyright (C) 2017, Blender Foundation
# All rights reserved.
#
# The Original Code is: all of this file.
#
-# Contributor(s): Jacques Beaurain.
+# Contributor(s): Bastien Montagne.
#
# ***** END GPL LICENSE BLOCK *****
-set(INC
- .
- ../avi
- ../blenkernel
- ../blenlib
- ../imbuf
- ../imbuf/intern
- ../makesdna
- ../makesrna
- ../render/extern/include
- ../windowmanager
- ../../../intern/guardedalloc
-)
+# -----------------------------------------------------------------------------
+# Build msgfmt executable
-set(INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
+blender_include_dirs(
+ ../../../../intern/guardedalloc
+ ../../blenlib
)
set(SRC
- apple/qtkit_import.m
- apple/qtkit_export.m
-
- quicktime_export.h
- quicktime_import.h
+ msgfmt.c
)
-add_definitions(-DWITH_QUICKTIME)
+add_cc_flags_custom_test(msgfmt)
+
+add_executable(msgfmt ${SRC})
-if(WITH_AUDASPACE)
- add_definitions(${AUDASPACE_DEFINITIONS})
+target_link_libraries(msgfmt bf_blenlib)
+target_link_libraries(msgfmt bf_intern_guardedalloc)
- list(APPEND INC_SYS
- ${AUDASPACE_C_INCLUDE_DIRS}
- )
+if(WIN32)
+ target_link_libraries(msgfmt bf_intern_utfconv)
endif()
-blender_add_lib(bf_quicktime "${SRC}" "${INC}" "${INC_SYS}")
+target_link_libraries(msgfmt ${ZLIB_LIBRARIES})
+target_link_libraries(msgfmt ${PLATFORM_LINKLIBS})
diff --git a/source/blender/blentranslation/msgfmt/msgfmt.c b/source/blender/blentranslation/msgfmt/msgfmt.c
new file mode 100644
index 00000000000..a155cce53a5
--- /dev/null
+++ b/source/blender/blentranslation/msgfmt/msgfmt.c
@@ -0,0 +1,468 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2017 by Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Bastien Montagne
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/*
+ * Based on C++ version by Sergey Sharybin <sergey.vfx@gmail.com>.
+ * Based on Python script msgfmt.py from Python source code tree, which was written by
+ * Martin v. Löwis <loewis@informatik.hu-berlin.de>
+ *
+ * Generate binary message catalog from textual translation description.
+ *
+ * This program converts a textual Uniforum-style message catalog (.po file) into a binary GNU catalog (.mo file).
+ * This is essentially the same function as the GNU msgfmt program, however, it is a simpler implementation.
+ *
+ * Usage: msgfmt input.po output.po
+ */
+
+#include <string.h>
+#include <stdlib.h>
+
+#include "BLI_utildefines.h"
+#include "BLI_dynstr.h"
+#include "BLI_fileops.h"
+#include "BLI_ghash.h"
+#include "BLI_linklist.h"
+#include "BLI_memarena.h"
+
+#include "MEM_guardedalloc.h"
+
+
+/* Stupid stub necessary because some BLI files includes winstuff.h, which uses G a bit... */
+#ifdef WIN32
+ typedef struct Global {
+ void *dummy;
+ } Global;
+
+ Global G;
+#endif
+
+
+/* We cannot use NULL char until ultimate step, would give nightmare to our C string processing...
+ * Using one of the UTF-8 invalid bytes (as per our BLI string_utf8.c) */
+#define NULLSEP_STR "\xff"
+#define NULLSEP_CHR '\xff'
+
+typedef enum {
+ SECTION_NONE = 0,
+ SECTION_CTX = 1,
+ SECTION_ID = 2,
+ SECTION_STR = 3,
+} eSectionType;
+
+typedef struct Message {
+ DynStr *ctxt;
+ DynStr *id;
+ DynStr *str;
+
+ bool is_fuzzy;
+} Message;
+
+static char *trim(char *str)
+{
+ const size_t len = strlen(str);
+ size_t i;
+
+ if (len == 0) {
+ return str;
+ }
+
+ for (i = 0; i < len && ELEM(str[0], ' ', '\t', '\n'); str++, i++);
+
+ char *end = &str[len - 1 - i];
+ for (i = len; i > 0 && ELEM(end[0], ' ', '\t', '\n'); end--, i--);
+ end[1] = '\0';
+
+ return str;
+}
+
+static char *unescape(char *str)
+{
+ char *curr, *next;
+ for (curr = next = str; next[0] != '\0'; curr++, next++) {
+ if (next[0] == '\\') {
+ switch (next[1]) {
+ case '\0':
+ /* Get rid of trailing escape char... */
+ curr--;
+ break;
+ case '\\':
+ *curr = '\\';
+ next++;
+ break;
+ case 'n':
+ *curr = '\n';
+ next++;
+ break;
+ case 't':
+ *curr = '\t';
+ next++;
+ break;
+ default:
+ /* Get rid of useless escape char. */
+ next++;
+ *curr = *next;
+ }
+ }
+ else if (curr != next) {
+ *curr = *next;
+ }
+ }
+ *curr = '\0';
+
+ if (str[0] == '"' && *(curr - 1) == '"') {
+ *(curr - 1) = '\0';
+ return str + 1;
+ }
+ return str;
+}
+
+static int qsort_str_cmp(const void *a, const void *b)
+{
+ return strcmp(*(const char **)a, *(const char **)b);
+}
+
+static char **get_keys_sorted(GHash *messages, const uint32_t num_keys)
+{
+ GHashIterator iter;
+
+ char **keys = MEM_mallocN(sizeof(*keys) * num_keys, __func__);
+ char **k = keys;
+
+ GHASH_ITER(iter, messages) {
+ *k = BLI_ghashIterator_getKey(&iter);
+ k++;
+ }
+
+ qsort(keys, num_keys, sizeof(*keys), qsort_str_cmp);
+
+ return keys;
+}
+
+BLI_INLINE size_t uint32_to_bytes(const int value, char *bytes)
+{
+ size_t i;
+ for (i = 0; i < sizeof(value); i++) {
+ bytes[i] = (char) ((value >> ((int)i * 8)) & 0xff);
+ }
+ return i;
+}
+
+BLI_INLINE size_t msg_to_bytes(char *msg, char *bytes, uint32_t size)
+{
+ /* Note that we also perform replacing of our NULLSEP placeholder by real NULL char... */
+ size_t i;
+ for (i = 0; i < size; i++, msg++, bytes++) {
+ *bytes = (*msg == NULLSEP_CHR) ? '\0' : *msg;
+ }
+ return i;
+}
+
+typedef struct Offset {
+ uint32_t key_offset, key_len, val_offset, val_len;
+} Offset;
+
+/* Return the generated binary output. */
+static char *generate(GHash *messages, size_t *r_output_size)
+{
+ const uint32_t num_keys = BLI_ghash_len(messages);
+
+ /* Get list of sorted keys. */
+ char **keys = get_keys_sorted(messages, num_keys);
+ char **vals = MEM_mallocN(sizeof(*vals) * num_keys, __func__);
+ uint32_t tot_keys_len = 0;
+ uint32_t tot_vals_len = 0;
+
+ Offset *offsets = MEM_mallocN(sizeof(*offsets) * num_keys, __func__);
+
+ for (int i = 0; i < num_keys; i++) {
+ Offset *off = &offsets[i];
+
+ vals[i] = BLI_ghash_lookup(messages, keys[i]);
+
+ /* For each string, we need size and file offset.
+ * Each string is NULL terminated; the NULL does not count into the size. */
+ off->key_offset = tot_keys_len;
+ off->key_len = (uint32_t)strlen(keys[i]);
+ tot_keys_len += off->key_len + 1;
+
+ off->val_offset = tot_vals_len;
+ off->val_len = (uint32_t)strlen(vals[i]);
+ tot_vals_len += off->val_len + 1;
+ }
+
+ /* The header is 7 32-bit unsigned integers. then comes the keys index table, then the values index table. */
+ const uint32_t idx_keystart = 7 * 4;
+ const uint32_t idx_valstart = idx_keystart + 8 * num_keys;
+ /* We don't use hash tables, so the keys start right after the index tables. */
+ const uint32_t keystart = idx_valstart + 8 * num_keys;
+ /* and the values start after the keys */
+ const uint32_t valstart = keystart + tot_keys_len;
+
+ /* Final buffer representing the binary MO file. */
+ *r_output_size = valstart + tot_vals_len;
+ char *output = MEM_mallocN(*r_output_size, __func__);
+ char *h = output;
+ char *ik = output + idx_keystart;
+ char *iv = output + idx_valstart;
+ char *k = output + keystart;
+ char *v = output + valstart;
+
+ h += uint32_to_bytes(0x950412de, h); /* Magic */
+ h += uint32_to_bytes(0x0, h); /* Version */
+ h += uint32_to_bytes(num_keys, h); /* Number of entries */
+ h += uint32_to_bytes(idx_keystart, h); /* Start of key index */
+ h += uint32_to_bytes(idx_valstart, h); /* Start of value index */
+ h += uint32_to_bytes(0, h); /* Size of hash table */
+ h += uint32_to_bytes(0, h); /* Offset of hash table */
+
+ BLI_assert(h == ik);
+
+ for (int i = 0; i < num_keys; i++) {
+ Offset *off = &offsets[i];
+
+ /* The index table first has the list of keys, then the list of values.
+ * Each entry has first the size of the string, then the file offset. */
+ ik += uint32_to_bytes(off->key_len, ik);
+ ik += uint32_to_bytes(off->key_offset + keystart, ik);
+ iv += uint32_to_bytes(off->val_len, iv);
+ iv += uint32_to_bytes(off->val_offset + valstart, iv);
+
+ k += msg_to_bytes(keys[i], k, off->key_len + 1);
+ v += msg_to_bytes(vals[i], v, off->val_len + 1);
+ }
+
+ BLI_assert(ik == output + idx_valstart);
+ BLI_assert(iv == output + keystart);
+ BLI_assert(k == output + valstart);
+
+ MEM_freeN(keys);
+ MEM_freeN(vals);
+ MEM_freeN(offsets);
+
+ return output;
+}
+
+/* Add a non-fuzzy translation to the dictionary. */
+static void add(GHash *messages, MemArena *memarena, const Message *msg)
+{
+ const size_t msgctxt_len = (size_t)BLI_dynstr_get_len(msg->ctxt);
+ const size_t msgid_len = (size_t)BLI_dynstr_get_len(msg->id);
+ const size_t msgstr_len = (size_t)BLI_dynstr_get_len(msg->str);
+ const size_t msgkey_len = msgid_len + ((msgctxt_len == 0) ? 0 : msgctxt_len + 1);
+
+ if (!msg->is_fuzzy && msgstr_len != 0) {
+ char *msgkey = BLI_memarena_alloc(memarena, sizeof(*msgkey) * (msgkey_len + 1));
+ char *msgstr = BLI_memarena_alloc(memarena, sizeof(*msgstr) * (msgstr_len + 1));
+
+ if (msgctxt_len != 0) {
+ BLI_dynstr_get_cstring_ex(msg->ctxt, msgkey);
+ msgkey[msgctxt_len] = '\x04'; /* Context/msgid separator */
+ BLI_dynstr_get_cstring_ex(msg->id, &msgkey[msgctxt_len + 1]);
+ }
+ else {
+ BLI_dynstr_get_cstring_ex(msg->id, msgkey);
+ }
+
+ BLI_dynstr_get_cstring_ex(msg->str, msgstr);
+
+ BLI_ghash_insert(messages, msgkey, msgstr);
+ }
+}
+
+
+static void clear(Message *msg)
+{
+ BLI_dynstr_clear(msg->ctxt);
+ BLI_dynstr_clear(msg->id);
+ BLI_dynstr_clear(msg->str);
+ msg->is_fuzzy = false;
+}
+
+static int make(const char *input_file_name, const char *output_file_name)
+{
+ GHash *messages = BLI_ghash_new(BLI_ghashutil_strhash_p_murmur, BLI_ghashutil_strcmp, __func__);
+ MemArena *msgs_memarena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
+
+ const char *msgctxt_kw = "msgctxt";
+ const char *msgid_kw = "msgid";
+ const char *msgid_plural_kw = "msgid_plural";
+ const char *msgstr_kw = "msgstr";
+ const size_t msgctxt_len = strlen(msgctxt_kw);
+ const size_t msgid_len = strlen(msgid_kw);
+ const size_t msgid_plural_len = strlen(msgid_plural_kw);
+ const size_t msgstr_len = strlen(msgstr_kw);
+
+ /* Note: For now, we assume file encoding is always utf-8. */
+
+ eSectionType section = SECTION_NONE;
+ bool is_plural = false;
+
+ Message msg = {
+ .ctxt = BLI_dynstr_new_memarena(),
+ .id = BLI_dynstr_new_memarena(),
+ .str = BLI_dynstr_new_memarena(),
+ .is_fuzzy = false,
+ };
+
+ LinkNode *input_file_lines = BLI_file_read_as_lines(input_file_name);
+ LinkNode *ifl = input_file_lines;
+
+ /* Parse the catalog. */
+ for (int lno = 1; ifl; ifl = ifl->next, lno++) {
+ char *l = ifl->link;
+ const bool is_comment = (l[0] == '#');
+ /* If we get a comment line after a msgstr, this is a new entry. */
+ if (is_comment) {
+ if (section == SECTION_STR) {
+ add(messages, msgs_memarena, &msg);
+ clear(&msg);
+ section = SECTION_NONE;
+ }
+ /* Record a fuzzy mark. */
+ if (l[1] == ',' && strstr(l, "fuzzy") != NULL) {
+ msg.is_fuzzy = true;
+ }
+ /* Skip comments */
+ continue;
+ }
+ if (strstr(l, msgctxt_kw) == l) {
+ if (section == SECTION_STR) {
+ /* New message, output previous section. */
+ add(messages, msgs_memarena, &msg);
+ }
+ if (!ELEM(section, SECTION_NONE, SECTION_STR)) {
+ printf("msgctxt not at start of new message on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ section = SECTION_CTX;
+ l = l + msgctxt_len;
+ clear(&msg);
+ }
+ else if (strstr(l, msgid_plural_kw) == l) {
+ /* This is a message with plural forms. */
+ if (section != SECTION_ID) {
+ printf("msgid_plural not preceeded by msgid on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ l = l + msgid_plural_len;
+ BLI_dynstr_append(msg.id, NULLSEP_STR); /* separator of singular and plural */
+ is_plural = true;
+ }
+ else if (strstr(l, msgid_kw) == l) {
+ if (section == SECTION_STR) {
+ add(messages, msgs_memarena, &msg);
+ }
+ if (section != SECTION_CTX) {
+ clear(&msg);
+ }
+ section = SECTION_ID;
+ l = l + msgid_len;
+ is_plural = false;
+ }
+ else if (strstr(l, msgstr_kw) == l) {
+ l = l + msgstr_len;
+ // Now we are in a msgstr section
+ section = SECTION_STR;
+ if (l[0] == '[') {
+ if (!is_plural) {
+ printf("plural without msgid_plural on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ if ((l = strchr(l, ']')) == NULL) {
+ printf("Syntax error on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ if (BLI_dynstr_get_len(msg.str) != 0) {
+ BLI_dynstr_append(msg.str, NULLSEP_STR); /* Separator of the various plural forms. */
+ }
+ }
+ else {
+ if (is_plural) {
+ printf("indexed msgstr required for plural on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ }
+ }
+ /* Skip empty lines. */
+ l = trim(l);
+ if (l[0] == '\0') {
+ if (section == SECTION_STR) {
+ add(messages, msgs_memarena, &msg);
+ clear(&msg);
+ }
+ section = SECTION_NONE;
+ continue;
+ }
+ l = unescape(l);
+ if (section == SECTION_CTX) {
+ BLI_dynstr_append(msg.ctxt, l);
+ }
+ else if (section == SECTION_ID) {
+ BLI_dynstr_append(msg.id, l);
+ }
+ else if (section == SECTION_STR) {
+ BLI_dynstr_append(msg.str, l);
+ }
+ else {
+ printf("Syntax error on %s:%d\n", input_file_name, lno);
+ return EXIT_FAILURE;
+ }
+ }
+ /* Add last entry */
+ if (section == SECTION_STR) {
+ add(messages, msgs_memarena, &msg);
+ }
+
+ BLI_dynstr_free(msg.ctxt);
+ BLI_dynstr_free(msg.id);
+ BLI_dynstr_free(msg.str);
+ BLI_file_free_lines(input_file_lines);
+
+ /* Compute output */
+ size_t output_size;
+ char *output = generate(messages, &output_size);
+
+ FILE *fp = BLI_fopen(output_file_name, "wb");
+ fwrite(output, 1, output_size, fp);
+ fclose(fp);
+
+ MEM_freeN(output);
+ BLI_ghash_free(messages, NULL, NULL);
+ BLI_memarena_free(msgs_memarena);
+
+ return EXIT_SUCCESS;
+}
+
+int main(int argc, char **argv)
+{
+ if (argc != 3) {
+ printf("Usage: %s <input.po> <output.mo>\n", argv[0]);
+ return EXIT_FAILURE;
+ }
+ const char *input_file = argv[1];
+ const char *output_file = argv[2];
+
+ return make(input_file, output_file);
+}
diff --git a/source/blender/bmesh/CMakeLists.txt b/source/blender/bmesh/CMakeLists.txt
index 30fefe37f0e..5245d24a075 100644
--- a/source/blender/bmesh/CMakeLists.txt
+++ b/source/blender/bmesh/CMakeLists.txt
@@ -30,6 +30,7 @@ set(INC
../blentranslation
../makesdna
../../../intern/guardedalloc
+ ../../../intern/atomic
../../../intern/eigen
../../../extern/rangetree
)
@@ -39,6 +40,7 @@ set(INC_SYS
)
set(SRC
+ # Naming convention for BMesh operators is: bmo_*action*_*details*.c
operators/bmo_beautify.c
operators/bmo_bevel.c
operators/bmo_bisect_plane.c
@@ -67,6 +69,7 @@ set(SRC
operators/bmo_poke.c
operators/bmo_primitive.c
operators/bmo_removedoubles.c
+ operators/bmo_rotate_edges.c
operators/bmo_similar.c
operators/bmo_smooth_laplacian.c
operators/bmo_split_edges.c
@@ -152,6 +155,8 @@ set(SRC
tools/bmesh_path_region.h
tools/bmesh_region_match.c
tools/bmesh_region_match.h
+ tools/bmesh_separate.c
+ tools/bmesh_separate.h
tools/bmesh_triangulate.c
tools/bmesh_triangulate.h
tools/bmesh_wireframe.c
diff --git a/source/blender/bmesh/bmesh.h b/source/blender/bmesh/bmesh.h
index f29d280d071..b84a3d5e559 100644
--- a/source/blender/bmesh/bmesh.h
+++ b/source/blender/bmesh/bmesh.h
@@ -192,9 +192,10 @@
*
* These conventions should be used throughout the bmesh module.
*
- * - ``BM_***()`` - High level BMesh API function for use anywhere.
- * - ``bmesh_***()`` - Low level API function.
+ * - ``bmesh_kernel_*()`` - Low level API, for primitive functions that others are built ontop of.
+ * - ``bmesh_***()`` - Low level API function.
* - ``bm_***()`` - 'static' functions, not apart of the API at all, but use prefix since they operate on BMesh data.
+ * - ``BM_***()`` - High level BMesh API function for use anywhere.
* - ``BMO_***()`` - High level operator API function for use anywhere.
* - ``bmo_***()`` - Low level / internal operator API functions.
* - ``_bm_***()`` - Functions which are called via macros only.
diff --git a/source/blender/bmesh/bmesh_class.h b/source/blender/bmesh/bmesh_class.h
index 104df625ee6..bec2c7a1f45 100644
--- a/source/blender/bmesh/bmesh_class.h
+++ b/source/blender/bmesh/bmesh_class.h
@@ -225,7 +225,7 @@ typedef struct BMesh {
/* operator api stuff (must be all NULL or all alloc'd) */
struct BLI_mempool *vtoolflagpool, *etoolflagpool, *ftoolflagpool;
- unsigned int use_toolflags : 1;
+ uint use_toolflags : 1;
int toolflag_index;
struct BMOperator *currentop;
@@ -341,9 +341,9 @@ enum {
/* spare tag, assumed dirty, use define in each function to name based on use */
// _BM_ELEM_TAG_ALT = (1 << 6), // UNUSED
/**
- * for low level internal API tagging,
- * since tools may want to tag verts and
- * not have functions clobber them */
+ * For low level internal API tagging,
+ * since tools may want to tag verts and not have functions clobber them.
+ * Leave cleared! */
BM_ELEM_INTERNAL_TAG = (1 << 7),
};
@@ -382,7 +382,7 @@ typedef bool (*BMLoopFilterFunc)(const BMLoop *, void *user_data);
(assert(offset != -1), *((float *)((char *)(ele)->head.data + (offset))))
#define BM_ELEM_CD_GET_FLOAT_AS_UCHAR(ele, offset) \
- (assert(offset != -1), (unsigned char)(BM_ELEM_CD_GET_FLOAT(ele, offset) * 255.0f))
+ (assert(offset != -1), (uchar)(BM_ELEM_CD_GET_FLOAT(ele, offset) * 255.0f))
/*forward declarations*/
diff --git a/source/blender/bmesh/bmesh_tools.h b/source/blender/bmesh/bmesh_tools.h
index 23212dd085e..a537c3b872c 100644
--- a/source/blender/bmesh/bmesh_tools.h
+++ b/source/blender/bmesh/bmesh_tools.h
@@ -43,6 +43,7 @@ extern "C" {
#include "tools/bmesh_path.h"
#include "tools/bmesh_path_region.h"
#include "tools/bmesh_region_match.h"
+#include "tools/bmesh_separate.h"
#include "tools/bmesh_triangulate.h"
#ifdef __cplusplus
diff --git a/source/blender/bmesh/intern/bmesh_callback_generic.c b/source/blender/bmesh/intern/bmesh_callback_generic.c
index 913255bfb33..e9304e8536f 100644
--- a/source/blender/bmesh/intern/bmesh_callback_generic.c
+++ b/source/blender/bmesh/intern/bmesh_callback_generic.c
@@ -32,7 +32,7 @@
bool BM_elem_cb_check_hflag_ex(BMElem *ele, void *user_data)
{
- const unsigned int hflag_pair = GET_INT_FROM_POINTER(user_data);
+ const uint hflag_pair = GET_INT_FROM_POINTER(user_data);
const char hflag_p = (hflag_pair & 0xff);
const char hflag_n = (hflag_pair >> 8);
diff --git a/source/blender/bmesh/intern/bmesh_construct.c b/source/blender/bmesh/intern/bmesh_construct.c
index e46a31cb2e9..f8ecbe1756b 100644
--- a/source/blender/bmesh/intern/bmesh_construct.c
+++ b/source/blender/bmesh/intern/bmesh_construct.c
@@ -154,7 +154,7 @@ void BM_face_copy_shared(
if (l_other && l_other != l_iter) {
BMLoop *l_src[2];
BMLoop *l_dst[2] = {l_iter, l_iter->next};
- unsigned int j;
+ uint j;
if (l_other->v == l_iter->v) {
l_src[0] = l_other;
@@ -311,7 +311,7 @@ BMFace *BM_face_create_ngon_verts(
const bool calc_winding, const bool create_edges)
{
BMEdge **edge_arr = BLI_array_alloca(edge_arr, len);
- unsigned int winding[2] = {0, 0};
+ uint winding[2] = {0, 0};
int i, i_prev = len - 1;
BMVert *v_winding[2] = {vert_arr[i_prev], vert_arr[0]};
diff --git a/source/blender/bmesh/intern/bmesh_core.c b/source/blender/bmesh/intern/bmesh_core.c
index d1178a198dc..7e35866887d 100644
--- a/source/blender/bmesh/intern/bmesh_core.c
+++ b/source/blender/bmesh/intern/bmesh_core.c
@@ -32,7 +32,7 @@
#include "BLI_array.h"
#include "BLI_alloca.h"
#include "BLI_linklist_stack.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLT_translation.h"
@@ -685,7 +685,7 @@ int bmesh_elem_check(void *element, const char htype)
err |= IS_FACE_LOOP_WRONG_RADIAL_LENGTH;
}
- if (bmesh_disk_count_ex(l_iter->v, 2) < 2) {
+ if (bmesh_disk_count_at_most(l_iter->v, 2) < 2) {
err |= IS_FACE_LOOP_WRONG_DISK_LENGTH;
}
}
@@ -1021,7 +1021,7 @@ static int UNUSED_FUNCTION(bm_loop_length)(BMLoop *l)
* \param use_loop_mdisp_flip: When set, flip the Z-depth of the mdisp,
* (use when flipping normals, disable when mirroring, eg: symmetrize).
*/
-void bmesh_loop_reverse(
+void bmesh_kernel_loop_reverse(
BMesh *bm, BMFace *f,
const int cd_loop_mdisp_offset, const bool use_loop_mdisp_flip)
{
@@ -1282,8 +1282,8 @@ BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const bool do_del)
}
/* create region face */
- f_new = BLI_array_count(edges) ?
- BM_face_create_ngon(bm, v1, v2, edges, BLI_array_count(edges), faces[0], BM_CREATE_NOP) : NULL;
+ f_new = BLI_array_len(edges) ?
+ BM_face_create_ngon(bm, v1, v2, edges, BLI_array_len(edges), faces[0], BM_CREATE_NOP) : NULL;
if (UNLIKELY(f_new == NULL)) {
/* Invalid boundary region to join faces */
goto error;
@@ -1347,11 +1347,11 @@ BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const bool do_del)
/* delete old geometry */
if (do_del) {
- for (i = 0; i < BLI_array_count(deledges); i++) {
+ for (i = 0; i < BLI_array_len(deledges); i++) {
BM_edge_kill(bm, deledges[i]);
}
- for (i = 0; i < BLI_array_count(delverts); i++) {
+ for (i = 0; i < BLI_array_len(delverts); i++) {
BM_vert_kill(bm, delverts[i]);
}
}
@@ -1438,7 +1438,7 @@ static BMFace *bm_face_create__sfme(BMesh *bm, BMFace *f_example)
*
* \return A BMFace pointer
*/
-BMFace *bmesh_sfme(
+BMFace *bmesh_kernel_split_face_make_edge(
BMesh *bm, BMFace *f, BMLoop *l_v1, BMLoop *l_v2,
BMLoop **r_l,
#ifdef USE_BMESH_HOLES
@@ -1584,7 +1584,7 @@ BMFace *bmesh_sfme(
*
* \return The newly created BMVert pointer.
*/
-BMVert *bmesh_semv(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e)
+BMVert *bmesh_kernel_split_edge_make_vert(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e)
{
BMLoop *l_next;
BMEdge *e_new;
@@ -1766,7 +1766,7 @@ BMVert *bmesh_semv(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e)
* faces with just 2 edges. It is up to the caller to decide what to do with
* these faces.
*/
-BMEdge *bmesh_jekv(
+BMEdge *bmesh_kernel_join_edge_kill_vert(
BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
const bool do_del, const bool check_edge_double,
const bool kill_degenerate_faces)
@@ -1785,7 +1785,7 @@ BMEdge *bmesh_jekv(
return NULL;
}
- if (bmesh_disk_count_ex(v_kill, 3) == 2) {
+ if (bmesh_disk_count_at_most(v_kill, 3) == 2) {
#ifndef NDEBUG
int valence1, valence2;
BMLoop *l;
@@ -1920,7 +1920,7 @@ BMEdge *bmesh_jekv(
*
* Collapse an edge, merging surrounding data.
*
- * Unlike #BM_vert_collapse_edge & #bmesh_jekv which only handle 2 valence verts,
+ * Unlike #BM_vert_collapse_edge & #bmesh_kernel_join_edge_kill_vert which only handle 2 valence verts,
* this can handle any number of connected edges/faces.
*
* <pre>
@@ -1932,7 +1932,7 @@ BMEdge *bmesh_jekv(
* +-+-+-+ +-+-+-+
* </pre>
*/
-BMVert *bmesh_jvke(
+BMVert *bmesh_kernel_join_vert_kill_edge(
BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
const bool do_del, const bool check_edge_double,
const bool kill_degenerate_faces)
@@ -2035,7 +2035,7 @@ BMVert *bmesh_jvke(
* In the example A, faces \a f1 and \a f2 are joined by a single edge,
* and the euler can safely be used.
* In example B however, \a f1 and \a f2 are joined by multiple edges and will produce an error.
- * The caller in this case should call #bmesh_jekv on the extra edges
+ * The caller in this case should call #bmesh_kernel_join_edge_kill_vert on the extra edges
* before attempting to fuse \a f1 and \a f2.
*
* \note The order of arguments decides whether or not certain per-face attributes are present
@@ -2044,7 +2044,7 @@ BMVert *bmesh_jvke(
*
* \return A BMFace pointer
*/
-BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
+BMFace *bmesh_kernel_join_face_kill_edge(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
{
BMLoop *l_iter, *l_f1 = NULL, *l_f2 = NULL;
int newlen = 0, i, f1len = 0, f2len = 0;
@@ -2090,25 +2090,33 @@ BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e)
}
/* validate no internal join */
- for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
- BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
- }
- for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
- BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
- }
+ {
+ bool is_dupe = false;
- for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
- if (l_iter != l_f1) {
- BM_elem_flag_enable(l_iter->v, BM_ELEM_INTERNAL_TAG);
+ /* TODO: skip clearing once this is ensured. */
+ for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
+ BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
}
- }
- for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
- if (l_iter != l_f2) {
- /* as soon as a duplicate is found, bail out */
- if (BM_elem_flag_test(l_iter->v, BM_ELEM_INTERNAL_TAG)) {
- return NULL;
+
+ for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
+ BM_elem_flag_set(l_iter->v, BM_ELEM_INTERNAL_TAG, l_iter != l_f1);
+ }
+ for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f2); i < f2len; i++, l_iter = l_iter->next) {
+ if (l_iter != l_f2) {
+ /* as soon as a duplicate is found, bail out */
+ if (BM_elem_flag_test(l_iter->v, BM_ELEM_INTERNAL_TAG)) {
+ is_dupe = true;
+ break;
+ }
}
}
+ /* Cleanup tags. */
+ for (i = 0, l_iter = BM_FACE_FIRST_LOOP(f1); i < f1len; i++, l_iter = l_iter->next) {
+ BM_elem_flag_disable(l_iter->v, BM_ELEM_INTERNAL_TAG);
+ }
+ if (is_dupe) {
+ return NULL;
+ }
}
/* join the two loop */
@@ -2249,7 +2257,7 @@ bool BM_vert_splice(BMesh *bm, BMVert *v_dst, BMVert *v_src)
}
-/** \name BM_vert_separate, bmesh_vert_separate and friends
+/** \name BM_vert_separate, bmesh_kernel_vert_separate and friends
* \{ */
/* BM_edge_face_count(e) >= 1 */
@@ -2269,7 +2277,7 @@ BLI_INLINE bool bm_edge_supports_separate(const BMEdge *e)
*
* \return Success
*/
-void bmesh_vert_separate(
+void bmesh_kernel_vert_separate(
BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len,
const bool copy_select)
{
@@ -2385,7 +2393,7 @@ void bmesh_vert_separate(
*
* Takes a list of edges, which have been split from their original.
*
- * Any edges which failed to split off in #bmesh_vert_separate will be merged back into the original edge.
+ * Any edges which failed to split off in #bmesh_kernel_vert_separate will be merged back into the original edge.
*
* \param edges_separate
* A list-of-lists, each list is from a single original edge (the first edge is the original),
@@ -2398,18 +2406,25 @@ void bmesh_vert_separate(
* \note this function looks like it could become slow,
* but in common cases its only going to iterate a few times.
*/
-static void bmesh_vert_separate__cleanup(BMesh *bm, LinkNode *edges_separate)
+static void bmesh_kernel_vert_separate__cleanup(BMesh *bm, LinkNode *edges_separate)
{
do {
LinkNode *n_orig = edges_separate->link;
do {
- BMEdge *e_orig = n_orig->link;
+ LinkNode *n_prev = n_orig;
LinkNode *n_step = n_orig->next;
+ BMEdge *e_orig = n_orig->link;
do {
BMEdge *e = n_step->link;
BLI_assert(e != e_orig);
- if ((e->v1 == e_orig->v1) && (e->v2 == e_orig->v2)) {
- BM_edge_splice(bm, e_orig, e);
+ if ((e->v1 == e_orig->v1) && (e->v2 == e_orig->v2) &&
+ BM_edge_splice(bm, e_orig, e))
+ {
+ /* don't visit again */
+ n_prev->next = n_step->next;
+ }
+ else {
+ n_prev = n_step;
}
} while ((n_step = n_step->next));
@@ -2418,7 +2433,7 @@ static void bmesh_vert_separate__cleanup(BMesh *bm, LinkNode *edges_separate)
}
/**
- * High level function which wraps both #bmesh_vert_separate and #bmesh_edge_separate
+ * High level function which wraps both #bmesh_kernel_vert_separate and #bmesh_kernel_edge_separate
*/
void BM_vert_separate(
BMesh *bm, BMVert *v,
@@ -2435,7 +2450,7 @@ void BM_vert_separate(
LinkNode *edges_orig = NULL;
do {
BMLoop *l_sep = e->l;
- bmesh_edge_separate(bm, e, l_sep, copy_select);
+ bmesh_kernel_edge_separate(bm, e, l_sep, copy_select);
BLI_linklist_prepend_alloca(&edges_orig, l_sep->e);
BLI_assert(e != l_sep->e);
} while (bm_edge_supports_separate(e));
@@ -2444,10 +2459,10 @@ void BM_vert_separate(
}
}
- bmesh_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
+ bmesh_kernel_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
if (edges_separate) {
- bmesh_vert_separate__cleanup(bm, edges_separate);
+ bmesh_kernel_vert_separate__cleanup(bm, edges_separate);
}
}
@@ -2472,7 +2487,7 @@ void BM_vert_separate_hflag(
LinkNode *edges_orig = NULL;
do {
BMLoop *l_sep = e->l;
- bmesh_edge_separate(bm, e, l_sep, copy_select);
+ bmesh_kernel_edge_separate(bm, e, l_sep, copy_select);
/* trick to avoid looping over separated edges */
if (edges_separate == NULL && edges_orig == NULL) {
e_first = l_sep->e;
@@ -2486,10 +2501,10 @@ void BM_vert_separate_hflag(
}
} while ((e_iter = BM_DISK_EDGE_NEXT(e_iter, v)) != e_first);
- bmesh_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
+ bmesh_kernel_vert_separate(bm, v, r_vout, r_vout_len, copy_select);
if (edges_separate) {
- bmesh_vert_separate__cleanup(bm, edges_separate);
+ bmesh_kernel_vert_separate__cleanup(bm, edges_separate);
}
}
@@ -2574,7 +2589,7 @@ bool BM_edge_splice(BMesh *bm, BMEdge *e_dst, BMEdge *e_src)
* \note Does nothing if \a l_sep is already the only loop in the
* edge radial.
*/
-void bmesh_edge_separate(
+void bmesh_kernel_edge_separate(
BMesh *bm, BMEdge *e, BMLoop *l_sep,
const bool copy_select)
{
@@ -2620,7 +2635,7 @@ void bmesh_edge_separate(
*
* \note Will be a no-op and return original vertex if only two edges at that vertex.
*/
-BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *l_sep)
+BMVert *bmesh_kernel_unglue_region_make_vert(BMesh *bm, BMLoop *l_sep)
{
BMVert *v_new = NULL;
BMVert *v_sep = l_sep->v;
@@ -2630,10 +2645,12 @@ BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *l_sep)
/* peel the face from the edge radials on both sides of the
* loop vert, disconnecting the face from its fan */
- if (!BM_edge_is_boundary(l_sep->e))
- bmesh_edge_separate(bm, l_sep->e, l_sep, false);
- if (!BM_edge_is_boundary(l_sep->prev->e))
- bmesh_edge_separate(bm, l_sep->prev->e, l_sep->prev, false);
+ if (!BM_edge_is_boundary(l_sep->e)) {
+ bmesh_kernel_edge_separate(bm, l_sep->e, l_sep, false);
+ }
+ if (!BM_edge_is_boundary(l_sep->prev->e)) {
+ bmesh_kernel_edge_separate(bm, l_sep->prev->e, l_sep->prev, false);
+ }
/* do inline, below */
#if 0
@@ -2681,21 +2698,23 @@ BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *l_sep)
}
/**
- * A version of #bmesh_urmv_loop that disconnects multiple loops at once.
+ * A version of #bmesh_kernel_unglue_region_make_vert that disconnects multiple loops at once.
* The loops must all share the same vertex, can be in any order
* and are all moved to use a single new vertex - which is returned.
*
* This function handles the details of finding fans boundaries.
*/
-BMVert *bmesh_urmv_loop_multi(
+BMVert *bmesh_kernel_unglue_region_make_vert_multi(
BMesh *bm, BMLoop **larr, int larr_len)
{
BMVert *v_sep = larr[0]->v;
BMVert *v_new;
+ int edges_len = 0;
int i;
- bool is_mixed_any = false;
-
- BLI_SMALLSTACK_DECLARE(edges, BMEdge *);
+ /* any edges not owned by 'larr' loops connected to 'v_sep'? */
+ bool is_mixed_edge_any = false;
+ /* any loops not owned by 'larr' radially connected to 'larr' loop edges? */
+ bool is_mixed_loop_any = false;
#define LOOP_VISIT _FLAG_WALK
#define EDGE_VISIT _FLAG_WALK
@@ -2713,58 +2732,74 @@ BMVert *bmesh_urmv_loop_multi(
* while doing a radial loop (where loops may be adjacent) */
BM_ELEM_API_FLAG_ENABLE(l_sep->next, LOOP_VISIT);
BM_ELEM_API_FLAG_ENABLE(l_sep->prev, LOOP_VISIT);
- }
-
- for (i = 0; i < larr_len; i++) {
- BMLoop *l_sep = larr[i];
BMLoop *loop_pair[2] = {l_sep, l_sep->prev};
- int j;
- for (j = 0; j < ARRAY_SIZE(loop_pair); j++) {
+ for (int j = 0; j < ARRAY_SIZE(loop_pair); j++) {
BMEdge *e = loop_pair[j]->e;
if (!BM_ELEM_API_FLAG_TEST(e, EDGE_VISIT)) {
- BMLoop *l_iter, *l_first;
- bool is_mixed = false;
-
BM_ELEM_API_FLAG_ENABLE(e, EDGE_VISIT);
+ edges_len += 1;
+ }
+ }
+ }
- l_iter = l_first = e->l;
+ BMEdge **edges = BLI_array_alloca(edges, edges_len);
+ STACK_DECLARE(edges);
+
+ STACK_INIT(edges, edges_len);
+
+ {
+ BMEdge *e_first, *e_iter;
+ e_iter = e_first = v_sep->e;
+ do {
+ if (BM_ELEM_API_FLAG_TEST(e_iter, EDGE_VISIT)) {
+ BMLoop *l_iter, *l_first;
+ bool is_mixed_loop = false;
+
+ l_iter = l_first = e_iter->l;
do {
if (!BM_ELEM_API_FLAG_TEST(l_iter, LOOP_VISIT)) {
- is_mixed = true;
- is_mixed_any = true;
+ is_mixed_loop = true;
break;
}
} while ((l_iter = l_iter->radial_next) != l_first);
- if (is_mixed) {
+ if (is_mixed_loop) {
/* ensure the first loop is one we don't own so we can do a quick check below
* on the edge's loop-flag to see if the edge is mixed or not. */
- e->l = l_iter;
+ e_iter->l = l_iter;
+
+ is_mixed_loop_any = true;
}
- BLI_SMALLSTACK_PUSH(edges, e);
+
+ STACK_PUSH(edges, e_iter);
}
- }
+ else {
+ /* at least one edge attached isn't connected to our loops */
+ is_mixed_edge_any = true;
+ }
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, v_sep)) != e_first);
}
- if (is_mixed_any == false) {
+ BLI_assert(edges_len == STACK_SIZE(edges));
+
+ if (is_mixed_loop_any == false && is_mixed_edge_any == false) {
/* all loops in 'larr' are the sole owners of their edges.
* nothing to split away from, this is a no-op */
v_new = v_sep;
}
else {
- BMEdge *e;
-
- BLI_assert(!BLI_SMALLSTACK_IS_EMPTY(edges));
-
v_new = BM_vert_create(bm, v_sep->co, v_sep, BM_CREATE_NOP);
- while ((e = BLI_SMALLSTACK_POP(edges))) {
+
+ for (i = 0; i < STACK_SIZE(edges); i++) {
+ BMEdge *e = edges[i];
BMLoop *l_iter, *l_first, *l_next;
BMEdge *e_new;
/* disable so copied edge isn't left dirty (loop edges are cleared last too) */
BM_ELEM_API_FLAG_DISABLE(e, EDGE_VISIT);
+ /* will always be false when (is_mixed_loop_any == false) */
if (!BM_ELEM_API_FLAG_TEST(e->l, LOOP_VISIT)) {
/* edge has some loops owned by us, some owned by other loops */
BMVert *e_new_v_pair[2];
@@ -2853,9 +2888,9 @@ static void bmesh_edge_vert_swap__recursive(BMEdge *e, BMVert *v_dst, BMVert *v_
/**
* This function assumes l_sep is apart of a larger fan which has already been
- * isolated by calling bmesh_edge_separate to segregate it radially.
+ * isolated by calling #bmesh_kernel_edge_separate to segregate it radially.
*/
-BMVert *bmesh_urmv_loop_region(BMesh *bm, BMLoop *l_sep)
+BMVert *bmesh_kernel_unglue_region_make_vert_multi_isolated(BMesh *bm, BMLoop *l_sep)
{
BMVert *v_new = BM_vert_create(bm, l_sep->v->co, l_sep->v, BM_CREATE_NOP);
/* passing either 'l_sep->e', 'l_sep->prev->e' will work */
@@ -2864,20 +2899,6 @@ BMVert *bmesh_urmv_loop_region(BMesh *bm, BMLoop *l_sep)
return v_new;
}
-
-/**
- * \brief Unglue Region Make Vert (URMV)
- *
- * Disconnects f_sep from the vertex fan at \a v_sep
- *
- * \return The newly created BMVert
- */
-BMVert *bmesh_urmv(BMesh *bm, BMFace *f_sep, BMVert *v_sep)
-{
- BMLoop *l = BM_face_vert_share_loop(f_sep, v_sep);
- return bmesh_urmv_loop(bm, l);
-}
-
/**
* Avoid calling this where possible,
* low level function so both face pointers remain intact but point to swapped data.
diff --git a/source/blender/bmesh/intern/bmesh_core.h b/source/blender/bmesh/intern/bmesh_core.h
index f72e9d7b198..fb6b66809f3 100644
--- a/source/blender/bmesh/intern/bmesh_core.h
+++ b/source/blender/bmesh/intern/bmesh_core.h
@@ -64,21 +64,16 @@ void BM_face_kill(BMesh *bm, BMFace *f);
void BM_edge_kill(BMesh *bm, BMEdge *e);
void BM_vert_kill(BMesh *bm, BMVert *v);
-void bmesh_edge_separate(
- BMesh *bm, BMEdge *e, BMLoop *l_sep,
- const bool copy_select);
bool BM_edge_splice(BMesh *bm, BMEdge *e_dst, BMEdge *e_src);
bool BM_vert_splice(BMesh *bm, BMVert *v_dst, BMVert *v_src);
bool BM_vert_splice_check_double(BMVert *v_a, BMVert *v_b);
-void bmesh_vert_separate(
- BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len,
- const bool copy_select);
-
-void bmesh_loop_reverse(
+void bmesh_kernel_loop_reverse(
BMesh *bm, BMFace *f,
const int cd_loop_mdisp_offset, const bool use_loop_mdisp_flip);
+void bmesh_face_swap_data(BMFace *f_a, BMFace *f_b);
+
BMFace *BM_faces_join(BMesh *bm, BMFace **faces, int totface, const bool do_del);
void BM_vert_separate(
BMesh *bm, BMVert *v, BMEdge **e_in, int e_in_len, const bool copy_select,
@@ -90,34 +85,43 @@ void BM_vert_separate_wire_hflag(
BMesh *bm, BMVert *v_dst, BMVert *v_src,
const char hflag);
-/* EULER API - For modifying structure */
-BMFace *bmesh_sfme(
+/**
+ * BMesh Kernel: For modifying structure.
+ *
+ * Names are on the verbose side but these are only for low-level access.
+ */
+void bmesh_kernel_vert_separate(
+ BMesh *bm, BMVert *v, BMVert ***r_vout, int *r_vout_len,
+ const bool copy_select);
+void bmesh_kernel_edge_separate(
+ BMesh *bm, BMEdge *e, BMLoop *l_sep,
+ const bool copy_select);
+
+BMFace *bmesh_kernel_split_face_make_edge(
BMesh *bm, BMFace *f,
BMLoop *l1, BMLoop *l2,
BMLoop **r_l,
#ifdef USE_BMESH_HOLES
- ListBase *holes,
+ ListBase *holes,
#endif
- BMEdge *example,
- const bool no_double
- );
+ BMEdge *example,
+ const bool no_double
+ );
-BMVert *bmesh_semv(BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e);
-BMEdge *bmesh_jekv(
+BMVert *bmesh_kernel_split_edge_make_vert(
+ BMesh *bm, BMVert *tv, BMEdge *e, BMEdge **r_e);
+BMEdge *bmesh_kernel_join_edge_kill_vert(
BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
const bool do_del, const bool check_edge_splice,
const bool kill_degenerate_faces);
-BMVert *bmesh_jvke(
+BMVert *bmesh_kernel_join_vert_kill_edge(
BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
const bool do_del, const bool check_edge_double,
const bool kill_degenerate_faces);
-BMFace *bmesh_jfke(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e);
-BMVert *bmesh_urmv(BMesh *bm, BMFace *f_sep, BMVert *v_sep);
-BMVert *bmesh_urmv_loop(BMesh *bm, BMLoop *l_sep);
-BMVert *bmesh_urmv_loop_multi(
- BMesh *bm, BMLoop **larr, int larr_len);
-BMVert *bmesh_urmv_loop_region(BMesh *bm, BMLoop *l_sep);
+BMFace *bmesh_kernel_join_face_kill_edge(BMesh *bm, BMFace *f1, BMFace *f2, BMEdge *e);
-void bmesh_face_swap_data(BMFace *f_a, BMFace *f_b);
+BMVert *bmesh_kernel_unglue_region_make_vert(BMesh *bm, BMLoop *l_sep);
+BMVert *bmesh_kernel_unglue_region_make_vert_multi(BMesh *bm, BMLoop **larr, int larr_len);
+BMVert *bmesh_kernel_unglue_region_make_vert_multi_isolated(BMesh *bm, BMLoop *l_sep);
#endif /* __BMESH_CORE_H__ */
diff --git a/source/blender/bmesh/intern/bmesh_edgeloop.c b/source/blender/bmesh/intern/bmesh_edgeloop.c
index 5e1d9c3a98d..54fe2801d0c 100644
--- a/source/blender/bmesh/intern/bmesh_edgeloop.c
+++ b/source/blender/bmesh/intern/bmesh_edgeloop.c
@@ -32,6 +32,8 @@
#include "BLI_math_vector.h"
#include "BLI_listbase.h"
#include "BLI_mempool.h"
+#include "BLI_utildefines_iter.h"
+#include "BLI_stack.h"
#include "bmesh.h"
@@ -58,7 +60,7 @@ static int bm_vert_other_tag(
{
BMIter iter;
BMEdge *e, *e_next = NULL;
- unsigned int count = 0;
+ uint count = 0;
BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
if (BM_elem_flag_test(e, BM_ELEM_INTERNAL_TAG)) {
@@ -140,18 +142,27 @@ int BM_mesh_edgeloops_find(
}
/* first flush edges to tags, and tag verts */
+ BLI_Stack *edge_stack = BLI_stack_new(sizeof(BMEdge *), __func__);
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ BLI_assert(!BM_elem_flag_test(e, BM_ELEM_INTERNAL_TAG));
if (test_fn(e, user_data)) {
BM_elem_flag_enable(e, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v1, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v2, BM_ELEM_INTERNAL_TAG);
+ BLI_stack_push(edge_stack, (void *)&e);
}
else {
BM_elem_flag_disable(e, BM_ELEM_INTERNAL_TAG);
}
}
- BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ const uint edges_len = BLI_stack_count(edge_stack);
+ BMEdge **edges = MEM_mallocN(sizeof(*edges) * edges_len, __func__);
+ BLI_stack_pop_n_reverse(edge_stack, edges, BLI_stack_count(edge_stack));
+ BLI_stack_free(edge_stack);
+
+ for (uint i = 0; i < edges_len; i += 1) {
+ e = edges[i];
if (BM_elem_flag_test(e, BM_ELEM_INTERNAL_TAG)) {
BMEdgeLoopStore *el_store = MEM_callocN(sizeof(BMEdgeLoopStore), __func__);
@@ -161,7 +172,6 @@ int BM_mesh_edgeloops_find(
el_store->len > 1)
{
BLI_addtail(r_eloops, el_store);
- BM_elem_flag_disable(e, BM_ELEM_INTERNAL_TAG);
count++;
}
else {
@@ -169,6 +179,15 @@ int BM_mesh_edgeloops_find(
}
}
}
+
+ for (uint i = 0; i < edges_len; i += 1) {
+ e = edges[i];
+ BM_elem_flag_disable(e, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(e->v1, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(e->v2, BM_ELEM_INTERNAL_TAG);
+ }
+
+ MEM_freeN(edges);
return count;
}
@@ -266,6 +285,7 @@ bool BM_mesh_edgeloops_find_path(
{
BMIter iter;
BMEdge *e;
+ bool found = false;
BLI_assert(v_src != v_dst);
@@ -273,28 +293,43 @@ bool BM_mesh_edgeloops_find_path(
BMVert *v;
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
BM_elem_index_set(v, 0);
+ BM_elem_flag_disable(v, BM_ELEM_INTERNAL_TAG);
}
}
bm->elem_index_dirty |= BM_VERT;
/* first flush edges to tags, and tag verts */
+ int edges_len;
+ BMEdge **edges;
+
if (test_fn) {
+ BLI_Stack *edge_stack = BLI_stack_new(sizeof(BMEdge *), __func__);
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (test_fn(e, user_data)) {
BM_elem_flag_enable(e, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v1, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v2, BM_ELEM_INTERNAL_TAG);
+ BLI_stack_push(edge_stack, (void *)&e);
}
else {
BM_elem_flag_disable(e, BM_ELEM_INTERNAL_TAG);
}
}
+ edges_len = BLI_stack_count(edge_stack);
+ edges = MEM_mallocN(sizeof(*edges) * edges_len, __func__);
+ BLI_stack_pop_n_reverse(edge_stack, edges, BLI_stack_count(edge_stack));
+ BLI_stack_free(edge_stack);
}
else {
- BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ int i = 0;
+ edges_len = bm->totedge;
+ edges = MEM_mallocN(sizeof(*edges) * edges_len, __func__);
+
+ BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
BM_elem_flag_enable(e, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v1, BM_ELEM_INTERNAL_TAG);
BM_elem_flag_enable(e->v2, BM_ELEM_INTERNAL_TAG);
+ edges[i] = e;
}
}
@@ -353,11 +388,19 @@ bool BM_mesh_edgeloops_find_path(
BLI_addtail(r_eloops, el_store);
- return true;
+ found = true;
}
}
- return false;
+ for (uint i = 0; i < edges_len; i += 1) {
+ e = edges[i];
+ BM_elem_flag_disable(e, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(e->v1, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(e->v2, BM_ELEM_INTERNAL_TAG);
+ }
+ MEM_freeN(edges);
+
+ return found;
}
@@ -708,21 +751,16 @@ void BM_edgeloop_expand(
}
if (el_store->len < el_store_len) {
- const int step = max_ii(1, el_store->len / (el_store->len % el_store_len));
- LinkData *node_first = el_store->verts.first;
- LinkData *node_curr = node_first;
+ LinkData *node_curr = el_store->verts.first;
- do {
- LinkData *node_curr_init = node_curr;
- LinkData *node_curr_copy;
- int i = 0;
- BLI_LISTBASE_CIRCULAR_FORWARD_BEGIN (&el_store->verts, node_curr, node_curr_init) {
- if (i++ < step) {
- break;
- }
+ int iter_prev = 0;
+ BLI_FOREACH_SPARSE_RANGE(el_store->len, (el_store_len - el_store->len), iter) {
+ while (iter_prev < iter) {
+ node_curr = node_curr->next;
+ iter_prev += 1;
}
- BLI_LISTBASE_CIRCULAR_FORWARD_END (&el_store->verts, node_curr, node_curr_init);
+ LinkData *node_curr_copy;
node_curr_copy = MEM_dupallocN(node_curr);
if (split == false) {
BLI_insertlinkafter(&el_store->verts, node_curr, node_curr_copy);
@@ -730,7 +768,8 @@ void BM_edgeloop_expand(
}
else {
if (node_curr->next || (el_store->flag & BM_EDGELOOP_IS_CLOSED)) {
- EDGE_SPLIT(node_curr_copy, node_curr->next ? node_curr->next : (LinkData *)el_store->verts.first);
+ EDGE_SPLIT(node_curr_copy,
+ node_curr->next ? node_curr->next : (LinkData *)el_store->verts.first);
BLI_insertlinkafter(&el_store->verts, node_curr, node_curr_copy);
node_curr = node_curr_copy->next;
}
@@ -742,9 +781,11 @@ void BM_edgeloop_expand(
split_swap = !split_swap;
}
el_store->len++;
- } while (el_store->len < el_store_len);
+ iter_prev += 1;
+ }
}
+#undef BKE_FOREACH_SUBSET_OF_RANGE
#undef EDGE_SPLIT
BLI_assert(el_store->len == el_store_len);
@@ -754,19 +795,29 @@ bool BM_edgeloop_overlap_check(struct BMEdgeLoopStore *el_store_a, struct BMEdge
{
LinkData *node;
+ /* A little more efficient if 'a' as smaller. */
+ if (el_store_a->len > el_store_b->len) {
+ SWAP(BMEdgeLoopStore *, el_store_a, el_store_b);
+ }
+
/* init */
for (node = el_store_a->verts.first; node; node = node->next) {
- BM_elem_flag_disable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_enable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
}
for (node = el_store_b->verts.first; node; node = node->next) {
- BM_elem_flag_enable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
}
- /* check 'a' */
+ /* Check 'a' (clear as we go). */
for (node = el_store_a->verts.first; node; node = node->next) {
- if (BM_elem_flag_test((BMVert *)node->data, BM_ELEM_INTERNAL_TAG)) {
+ if (!BM_elem_flag_test((BMVert *)node->data, BM_ELEM_INTERNAL_TAG)) {
+ /* Finish clearing 'a', leave tag clean. */
+ while ((node = node->next)) {
+ BM_elem_flag_disable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
+ }
return true;
}
+ BM_elem_flag_disable((BMVert *)node->data, BM_ELEM_INTERNAL_TAG);
}
return false;
}
diff --git a/source/blender/bmesh/intern/bmesh_interp.c b/source/blender/bmesh/intern/bmesh_interp.c
index 20ee31251e8..8a1090891f2 100644
--- a/source/blender/bmesh/intern/bmesh_interp.c
+++ b/source/blender/bmesh/intern/bmesh_interp.c
@@ -36,12 +36,13 @@
#include "DNA_meshdata_types.h"
#include "BLI_alloca.h"
+#include "BLI_linklist.h"
#include "BLI_math.h"
+#include "BLI_memarena.h"
+#include "BLI_task.h"
#include "BKE_customdata.h"
#include "BKE_multires.h"
-#include "BLI_memarena.h"
-#include "BLI_linklist.h"
#include "bmesh.h"
#include "intern/bmesh_private.h"
@@ -401,13 +402,81 @@ static void bm_loop_flip_disp(
disp[1] = (mat[0][0] * b[1] - b[0] * mat[1][0]) / d;
}
+
+typedef struct BMLoopInterpMultiresData {
+ BMLoop *l_dst;
+ BMLoop *l_src_first;
+ int cd_loop_mdisp_offset;
+
+ MDisps *md_dst;
+ const float *f_src_center;
+
+ float *axis_x, *axis_y;
+ float *v1, *v4;
+ float *e1, *e2;
+
+ int res;
+ float d;
+} BMLoopInterpMultiresData;
+
+static void loop_interp_multires_cb(
+ void *__restrict userdata,
+ const int ix,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ BMLoopInterpMultiresData *data = userdata;
+
+ BMLoop *l_first = data->l_src_first;
+ BMLoop *l_dst = data->l_dst;
+ const int cd_loop_mdisp_offset = data->cd_loop_mdisp_offset;
+
+ MDisps *md_dst = data->md_dst;
+ const float *f_src_center = data->f_src_center;
+
+ float *axis_x = data->axis_x;
+ float *axis_y = data->axis_y;
+
+ float *v1 = data->v1;
+ float *v4 = data->v4;
+ float *e1 = data->e1;
+ float *e2 = data->e2;
+
+ const int res = data->res;
+ const float d = data->d;
+
+ float x = d * ix, y;
+ int iy;
+ for (y = 0.0f, iy = 0; iy < res; y += d, iy++) {
+ BMLoop *l_iter = l_first;
+ float co1[3], co2[3], co[3];
+
+ madd_v3_v3v3fl(co1, v1, e1, y);
+ madd_v3_v3v3fl(co2, v4, e2, y);
+ interp_v3_v3v3(co, co1, co2, x);
+
+ do {
+ MDisps *md_src;
+ float src_axis_x[3], src_axis_y[3];
+ float uv[2];
+
+ md_src = BM_ELEM_CD_GET_VOID_P(l_iter, cd_loop_mdisp_offset);
+
+ if (mdisp_in_mdispquad(l_dst, l_iter, f_src_center, co, res, src_axis_x, src_axis_y, uv)) {
+ old_mdisps_bilinear(md_dst->disps[iy * res + ix], md_src->disps, res, uv[0], uv[1]);
+ bm_loop_flip_disp(src_axis_x, src_axis_y, axis_x, axis_y, md_dst->disps[iy * res + ix]);
+
+ break;
+ }
+ } while ((l_iter = l_iter->next) != l_first);
+ }
+}
+
void BM_loop_interp_multires_ex(
BMesh *UNUSED(bm), BMLoop *l_dst, const BMFace *f_src,
const float f_dst_center[3], const float f_src_center[3], const int cd_loop_mdisp_offset)
{
MDisps *md_dst;
- float d, v1[3], v2[3], v3[3], v4[3] = {0.0f, 0.0f, 0.0f}, e1[3], e2[3];
- int ix, res;
+ float v1[3], v2[3], v3[3], v4[3] = {0.0f, 0.0f, 0.0f}, e1[3], e2[3];
float axis_x[3], axis_y[3];
/* ignore 2-edged faces */
@@ -433,38 +502,18 @@ void BM_loop_interp_multires_ex(
mdisp_axis_from_quad(v1, v2, v3, v4, axis_x, axis_y);
- res = (int)sqrt(md_dst->totdisp);
- d = 1.0f / (float)(res - 1);
-#pragma omp parallel for if (res > 3)
- for (ix = 0; ix < res; ix++) {
- float x = d * ix, y;
- int iy;
- for (y = 0.0f, iy = 0; iy < res; y += d, iy++) {
- BMLoop *l_iter;
- BMLoop *l_first;
- float co1[3], co2[3], co[3];
-
- madd_v3_v3v3fl(co1, v1, e1, y);
- madd_v3_v3v3fl(co2, v4, e2, y);
- interp_v3_v3v3(co, co1, co2, x);
-
- l_iter = l_first = BM_FACE_FIRST_LOOP(f_src);
- do {
- MDisps *md_src;
- float src_axis_x[3], src_axis_y[3];
- float uv[2];
-
- md_src = BM_ELEM_CD_GET_VOID_P(l_iter, cd_loop_mdisp_offset);
-
- if (mdisp_in_mdispquad(l_dst, l_iter, f_src_center, co, res, src_axis_x, src_axis_y, uv)) {
- old_mdisps_bilinear(md_dst->disps[iy * res + ix], md_src->disps, res, uv[0], uv[1]);
- bm_loop_flip_disp(src_axis_x, src_axis_y, axis_x, axis_y, md_dst->disps[iy * res + ix]);
-
- break;
- }
- } while ((l_iter = l_iter->next) != l_first);
- }
- }
+ const int res = (int)sqrt(md_dst->totdisp);
+ BMLoopInterpMultiresData data = {
+ .l_dst = l_dst, .l_src_first = BM_FACE_FIRST_LOOP(f_src),
+ .cd_loop_mdisp_offset = cd_loop_mdisp_offset,
+ .md_dst = md_dst, .f_src_center = f_src_center,
+ .axis_x = axis_x, .axis_y = axis_y, .v1 = v1, .v4 = v4, .e1 = e1, .e2 = e2,
+ .res = res, .d = 1.0f / (float)(res - 1)
+ };
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (res > 5);
+ BLI_task_parallel_range(0, res, &data, loop_interp_multires_cb, &settings);
}
/**
@@ -957,7 +1006,7 @@ static void bm_loop_walk_add(struct LoopWalkCtx *lwc, BMLoop *l)
{
const int i = BM_elem_index_get(l);
const float w = lwc->loop_weights[i];
- BM_elem_flag_enable(l, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(l, BM_ELEM_INTERNAL_TAG);
lwc->data_array[lwc->data_len] = BM_ELEM_CD_GET_VOID_P(l, lwc->cd_layer_offset);
lwc->data_index_array[lwc->data_len] = i;
lwc->weight_array[lwc->data_len] = w;
@@ -976,7 +1025,7 @@ static void bm_loop_walk_data(struct LoopWalkCtx *lwc, BMLoop *l_walk)
int i;
BLI_assert(CustomData_data_equals(lwc->type, lwc->data_ref, BM_ELEM_CD_GET_VOID_P(l_walk, lwc->cd_layer_offset)));
- BLI_assert(BM_elem_flag_test(l_walk, BM_ELEM_INTERNAL_TAG) == false);
+ BLI_assert(BM_elem_flag_test(l_walk, BM_ELEM_INTERNAL_TAG));
bm_loop_walk_add(lwc, l_walk);
@@ -988,7 +1037,7 @@ static void bm_loop_walk_data(struct LoopWalkCtx *lwc, BMLoop *l_walk)
l_other = l_other->next;
}
BLI_assert(l_other->v == l_walk->v);
- if (!BM_elem_flag_test(l_other, BM_ELEM_INTERNAL_TAG)) {
+ if (BM_elem_flag_test(l_other, BM_ELEM_INTERNAL_TAG)) {
if (CustomData_data_equals(lwc->type, lwc->data_ref, BM_ELEM_CD_GET_VOID_P(l_other, lwc->cd_layer_offset))) {
bm_loop_walk_data(lwc, l_other);
}
@@ -1012,9 +1061,10 @@ LinkNode *BM_vert_loop_groups_data_layer_create(
lwc.loop_weights = loop_weights;
lwc.arena = arena;
+ /* Enable 'BM_ELEM_INTERNAL_TAG', leaving the flag clean on completion. */
loop_num = 0;
BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
- BM_elem_flag_disable(l, BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_enable(l, BM_ELEM_INTERNAL_TAG);
BM_elem_index_set(l, loop_num); /* set_dirty! */
loop_num++;
}
@@ -1026,7 +1076,7 @@ LinkNode *BM_vert_loop_groups_data_layer_create(
lwc.weight_array = BLI_memarena_alloc(lwc.arena, sizeof(float) * loop_num);
BM_ITER_ELEM (l, &liter, v, BM_LOOPS_OF_VERT) {
- if (!BM_elem_flag_test(l, BM_ELEM_INTERNAL_TAG)) {
+ if (BM_elem_flag_test(l, BM_ELEM_INTERNAL_TAG)) {
struct LoopGroupCD *lf = BLI_memarena_alloc(lwc.arena, sizeof(*lf));
int len_prev = lwc.data_len;
diff --git a/source/blender/bmesh/intern/bmesh_iterators.c b/source/blender/bmesh/intern/bmesh_iterators.c
index 96154f051f9..9fe28561b93 100644
--- a/source/blender/bmesh/intern/bmesh_iterators.c
+++ b/source/blender/bmesh/intern/bmesh_iterators.c
@@ -430,7 +430,7 @@ int BM_iter_mesh_count_flag(const char itype, BMesh *bm, const char hflag, const
void bmiter__elem_of_mesh_begin(struct BMIter__elem_of_mesh *iter)
{
#ifdef USE_IMMUTABLE_ASSERT
- ((BMIter *)iter)->count = BLI_mempool_count(iter->pooliter.pool);
+ ((BMIter *)iter)->count = BLI_mempool_len(iter->pooliter.pool);
#endif
BLI_mempool_iternew(iter->pooliter.pool, &iter->pooliter);
}
@@ -438,7 +438,7 @@ void bmiter__elem_of_mesh_begin(struct BMIter__elem_of_mesh *iter)
void *bmiter__elem_of_mesh_step(struct BMIter__elem_of_mesh *iter)
{
#ifdef USE_IMMUTABLE_ASSERT
- BLI_assert(((BMIter *)iter)->count <= BLI_mempool_count(iter->pooliter.pool));
+ BLI_assert(((BMIter *)iter)->count <= BLI_mempool_len(iter->pooliter.pool));
#endif
return BLI_mempool_iterstep(&iter->pooliter);
}
diff --git a/source/blender/bmesh/intern/bmesh_iterators.h b/source/blender/bmesh/intern/bmesh_iterators.h
index 0551d824131..ab066682081 100644
--- a/source/blender/bmesh/intern/bmesh_iterators.h
+++ b/source/blender/bmesh/intern/bmesh_iterators.h
@@ -211,12 +211,12 @@ void *BMO_iter_as_arrayN(
int BM_iter_mesh_bitmap_from_filter(
const char itype, BMesh *bm,
- unsigned int *bitmap,
+ uint *bitmap,
bool (*test_fn)(BMElem *, void *user_data),
void *user_data);
int BM_iter_mesh_bitmap_from_filter_tessface(
BMesh *bm,
- unsigned int *bitmap,
+ uint *bitmap,
bool (*test_fn)(BMFace *, void *user_data),
void *user_data);
diff --git a/source/blender/bmesh/intern/bmesh_iterators_inline.h b/source/blender/bmesh/intern/bmesh_iterators_inline.h
index e68440021e6..88985d639cf 100644
--- a/source/blender/bmesh/intern/bmesh_iterators_inline.h
+++ b/source/blender/bmesh/intern/bmesh_iterators_inline.h
@@ -182,4 +182,38 @@ BLI_INLINE void *BM_iter_new(BMIter *iter, BMesh *bm, const char itype, void *da
}
}
+/**
+ * \brief Parallel (threaded) iterator, only available for most basic itertypes (verts/edges/faces of mesh).
+ *
+ * Uses BLI_task_parallel_mempool to iterate over all items of underlying matching mempool.
+ *
+ * \note You have to include BLI_task.h before BMesh includes to be able to use this function!
+ */
+
+#ifdef __BLI_TASK_H__
+
+ATTR_NONNULL(1)
+BLI_INLINE void BM_iter_parallel(
+ BMesh *bm, const char itype, TaskParallelMempoolFunc func, void *userdata, const bool use_threading)
+{
+ /* inlining optimizes out this switch when called with the defined type */
+ switch ((BMIterType)itype) {
+ case BM_VERTS_OF_MESH:
+ BLI_task_parallel_mempool(bm->vpool, userdata, func, use_threading);
+ break;
+ case BM_EDGES_OF_MESH:
+ BLI_task_parallel_mempool(bm->epool, userdata, func, use_threading);
+ break;
+ case BM_FACES_OF_MESH:
+ BLI_task_parallel_mempool(bm->fpool, userdata, func, use_threading);
+ break;
+ default:
+ /* should never happen */
+ BLI_assert(0);
+ break;
+ }
+}
+
+#endif /* __BLI_TASK_H__ */
+
#endif /* __BMESH_ITERATORS_INLINE_H__ */
diff --git a/source/blender/bmesh/intern/bmesh_log.c b/source/blender/bmesh/intern/bmesh_log.c
index 2591c33fc73..5ae72851c7e 100644
--- a/source/blender/bmesh/intern/bmesh_log.c
+++ b/source/blender/bmesh/intern/bmesh_log.c
@@ -88,7 +88,7 @@ struct BMLog {
/* Mapping from unique IDs to vertices and faces
*
- * Each vertex and face in the log gets a unique unsigned integer
+ * Each vertex and face in the log gets a unique uinteger
* assigned. That ID is taken from the set managed by the
* unused_ids range tree.
*
@@ -120,7 +120,7 @@ typedef struct {
} BMLogVert;
typedef struct {
- unsigned int v_ids[3];
+ uint v_ids[3];
char hflag;
} BMLogFace;
@@ -131,14 +131,14 @@ typedef struct {
#define logkey_cmp BLI_ghashutil_intcmp
/* Get the vertex's unique ID from the log */
-static unsigned int bm_log_vert_id_get(BMLog *log, BMVert *v)
+static uint bm_log_vert_id_get(BMLog *log, BMVert *v)
{
BLI_assert(BLI_ghash_haskey(log->elem_to_id, v));
return GET_UINT_FROM_POINTER(BLI_ghash_lookup(log->elem_to_id, v));
}
/* Set the vertex's unique ID in the log */
-static void bm_log_vert_id_set(BMLog *log, BMVert *v, unsigned int id)
+static void bm_log_vert_id_set(BMLog *log, BMVert *v, uint id)
{
void *vid = SET_UINT_IN_POINTER(id);
@@ -147,7 +147,7 @@ static void bm_log_vert_id_set(BMLog *log, BMVert *v, unsigned int id)
}
/* Get a vertex from its unique ID */
-static BMVert *bm_log_vert_from_id(BMLog *log, unsigned int id)
+static BMVert *bm_log_vert_from_id(BMLog *log, uint id)
{
void *key = SET_UINT_IN_POINTER(id);
BLI_assert(BLI_ghash_haskey(log->id_to_elem, key));
@@ -155,14 +155,14 @@ static BMVert *bm_log_vert_from_id(BMLog *log, unsigned int id)
}
/* Get the face's unique ID from the log */
-static unsigned int bm_log_face_id_get(BMLog *log, BMFace *f)
+static uint bm_log_face_id_get(BMLog *log, BMFace *f)
{
BLI_assert(BLI_ghash_haskey(log->elem_to_id, f));
return GET_UINT_FROM_POINTER(BLI_ghash_lookup(log->elem_to_id, f));
}
/* Set the face's unique ID in the log */
-static void bm_log_face_id_set(BMLog *log, BMFace *f, unsigned int id)
+static void bm_log_face_id_set(BMLog *log, BMFace *f, uint id)
{
void *fid = SET_UINT_IN_POINTER(id);
@@ -171,7 +171,7 @@ static void bm_log_face_id_set(BMLog *log, BMFace *f, unsigned int id)
}
/* Get a face from its unique ID */
-static BMFace *bm_log_face_from_id(BMLog *log, unsigned int id)
+static BMFace *bm_log_face_from_id(BMLog *log, uint id)
{
void *key = SET_UINT_IN_POINTER(id);
BLI_assert(BLI_ghash_haskey(log->id_to_elem, key));
@@ -255,7 +255,7 @@ static void bm_log_verts_unmake(BMesh *bm, BMLog *log, GHash *verts)
GHASH_ITER (gh_iter, verts) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
BMLogVert *lv = BLI_ghashIterator_getValue(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
BMVert *v = bm_log_vert_from_id(log, id);
/* Ensure the log has the final values of the vertex before
@@ -271,7 +271,7 @@ static void bm_log_faces_unmake(BMesh *bm, BMLog *log, GHash *faces)
GHashIterator gh_iter;
GHASH_ITER (gh_iter, faces) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
BMFace *f = bm_log_face_from_id(log, id);
BMEdge *e_tri[3];
BMLoop *l_iter;
@@ -333,7 +333,7 @@ static void bm_log_vert_values_swap(BMesh *bm, BMLog *log, GHash *verts)
GHASH_ITER (gh_iter, verts) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
BMLogVert *lv = BLI_ghashIterator_getValue(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
BMVert *v = bm_log_vert_from_id(log, id);
float mask;
short normal[3];
@@ -355,7 +355,7 @@ static void bm_log_face_values_swap(BMLog *log, GHash *faces)
GHASH_ITER (gh_iter, faces) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
BMLogFace *lf = BLI_ghashIterator_getValue(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
BMFace *f = bm_log_face_from_id(log, id);
SWAP(char, f->head.hflag, lf->hflag);
@@ -374,13 +374,13 @@ static void bm_log_assign_ids(BMesh *bm, BMLog *log)
/* Generate vertex IDs */
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
- unsigned int id = range_tree_uint_take_any(log->unused_ids);
+ uint id = range_tree_uint_take_any(log->unused_ids);
bm_log_vert_id_set(log, v, id);
}
/* Generate face IDs */
BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
- unsigned int id = range_tree_uint_take_any(log->unused_ids);
+ uint id = range_tree_uint_take_any(log->unused_ids);
bm_log_face_id_set(log, f, id);
}
}
@@ -425,7 +425,7 @@ static void bm_log_id_ghash_retake(RangeTreeUInt *unused_ids, GHash *id_ghash)
GHASH_ITER (gh_iter, id_ghash) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
range_tree_uint_retake(unused_ids, id);
}
@@ -433,8 +433,8 @@ static void bm_log_id_ghash_retake(RangeTreeUInt *unused_ids, GHash *id_ghash)
static int uint_compare(const void *a_v, const void *b_v)
{
- const unsigned int *a = a_v;
- const unsigned int *b = b_v;
+ const uint *a = a_v;
+ const uint *b = b_v;
return (*a) < (*b);
}
@@ -446,10 +446,10 @@ static int uint_compare(const void *a_v, const void *b_v)
* 10 -> 3
* 3 -> 1
*/
-static GHash *bm_log_compress_ids_to_indices(unsigned int *ids, unsigned int totid)
+static GHash *bm_log_compress_ids_to_indices(uint *ids, uint totid)
{
GHash *map = BLI_ghash_int_new_ex(__func__, totid);
- unsigned int i;
+ uint i;
qsort(ids, totid, sizeof(*ids), uint_compare);
@@ -469,7 +469,7 @@ static void bm_log_id_ghash_release(BMLog *log, GHash *id_ghash)
GHASH_ITER (gh_iter, id_ghash) {
void *key = BLI_ghashIterator_getKey(&gh_iter);
- unsigned int id = GET_UINT_FROM_POINTER(key);
+ uint id = GET_UINT_FROM_POINTER(key);
range_tree_uint_release(log->unused_ids, id);
}
}
@@ -480,7 +480,7 @@ static void bm_log_id_ghash_release(BMLog *log, GHash *id_ghash)
BMLog *BM_log_create(BMesh *bm)
{
BMLog *log = MEM_callocN(sizeof(*log), __func__);
- const unsigned int reserve_num = (unsigned int)(bm->totvert + bm->totface);
+ const uint reserve_num = (uint)(bm->totvert + bm->totface);
log->unused_ids = range_tree_uint_alloc(0, (unsigned)-1);
log->id_to_elem = BLI_ghash_new_ex(logkey_hash, logkey_cmp, __func__, reserve_num);
@@ -593,8 +593,8 @@ int BM_log_length(const BMLog *log)
/* Apply a consistent ordering to BMesh vertices */
void BM_log_mesh_elems_reorder(BMesh *bm, BMLog *log)
{
- unsigned int *varr;
- unsigned int *farr;
+ uint *varr;
+ uint *farr;
GHash *id_to_idx;
@@ -602,7 +602,7 @@ void BM_log_mesh_elems_reorder(BMesh *bm, BMLog *log)
BMVert *v;
BMFace *f;
- unsigned int i;
+ uint i;
/* Put all vertex IDs into an array */
varr = MEM_mallocN(sizeof(int) * (size_t)bm->totvert, __func__);
@@ -617,7 +617,7 @@ void BM_log_mesh_elems_reorder(BMesh *bm, BMLog *log)
}
/* Create BMVert index remap array */
- id_to_idx = bm_log_compress_ids_to_indices(varr, (unsigned int)bm->totvert);
+ id_to_idx = bm_log_compress_ids_to_indices(varr, (uint)bm->totvert);
BM_ITER_MESH_INDEX (v, &bm_iter, bm, BM_VERTS_OF_MESH, i) {
const unsigned id = bm_log_vert_id_get(log, v);
const void *key = SET_UINT_IN_POINTER(id);
@@ -627,7 +627,7 @@ void BM_log_mesh_elems_reorder(BMesh *bm, BMLog *log)
BLI_ghash_free(id_to_idx, NULL, NULL);
/* Create BMFace index remap array */
- id_to_idx = bm_log_compress_ids_to_indices(farr, (unsigned int)bm->totface);
+ id_to_idx = bm_log_compress_ids_to_indices(farr, (uint)bm->totface);
BM_ITER_MESH_INDEX (f, &bm_iter, bm, BM_FACES_OF_MESH, i) {
const unsigned id = bm_log_face_id_get(log, f);
const void *key = SET_UINT_IN_POINTER(id);
@@ -835,7 +835,7 @@ void BM_log_vert_before_modified(BMLog *log, BMVert *v, const int cd_vert_mask_o
{
BMLogEntry *entry = log->current_entry;
BMLogVert *lv;
- unsigned int v_id = bm_log_vert_id_get(log, v);
+ uint v_id = bm_log_vert_id_get(log, v);
void *key = SET_UINT_IN_POINTER(v_id);
void **val_p;
@@ -859,7 +859,7 @@ void BM_log_vert_before_modified(BMLog *log, BMVert *v, const int cd_vert_mask_o
void BM_log_vert_added(BMLog *log, BMVert *v, const int cd_vert_mask_offset)
{
BMLogVert *lv;
- unsigned int v_id = range_tree_uint_take_any(log->unused_ids);
+ uint v_id = range_tree_uint_take_any(log->unused_ids);
void *key = SET_UINT_IN_POINTER(v_id);
bm_log_vert_id_set(log, v, v_id);
@@ -876,7 +876,7 @@ void BM_log_vert_added(BMLog *log, BMVert *v, const int cd_vert_mask_offset)
void BM_log_face_modified(BMLog *log, BMFace *f)
{
BMLogFace *lf;
- unsigned int f_id = bm_log_face_id_get(log, f);
+ uint f_id = bm_log_face_id_get(log, f);
void *key = SET_UINT_IN_POINTER(f_id);
lf = bm_log_face_alloc(log, f);
@@ -892,7 +892,7 @@ void BM_log_face_modified(BMLog *log, BMFace *f)
void BM_log_face_added(BMLog *log, BMFace *f)
{
BMLogFace *lf;
- unsigned int f_id = range_tree_uint_take_any(log->unused_ids);
+ uint f_id = range_tree_uint_take_any(log->unused_ids);
void *key = SET_UINT_IN_POINTER(f_id);
/* Only triangles are supported for now */
@@ -922,7 +922,7 @@ void BM_log_face_added(BMLog *log, BMFace *f)
void BM_log_vert_removed(BMLog *log, BMVert *v, const int cd_vert_mask_offset)
{
BMLogEntry *entry = log->current_entry;
- unsigned int v_id = bm_log_vert_id_get(log, v);
+ uint v_id = bm_log_vert_id_get(log, v);
void *key = SET_UINT_IN_POINTER(v_id);
/* if it has a key, it shouldn't be NULL */
@@ -963,7 +963,7 @@ void BM_log_vert_removed(BMLog *log, BMVert *v, const int cd_vert_mask_offset)
void BM_log_face_removed(BMLog *log, BMFace *f)
{
BMLogEntry *entry = log->current_entry;
- unsigned int f_id = bm_log_face_id_get(log, f);
+ uint f_id = bm_log_face_id_get(log, f);
void *key = SET_UINT_IN_POINTER(f_id);
/* if it has a key, it shouldn't be NULL */
@@ -990,12 +990,12 @@ void BM_log_all_added(BMesh *bm, BMLog *log)
BMFace *f;
/* avoid unnecessary resizing on initialization */
- if (BLI_ghash_size(log->current_entry->added_verts) == 0) {
- BLI_ghash_reserve(log->current_entry->added_verts, (unsigned int)bm->totvert);
+ if (BLI_ghash_len(log->current_entry->added_verts) == 0) {
+ BLI_ghash_reserve(log->current_entry->added_verts, (uint)bm->totvert);
}
- if (BLI_ghash_size(log->current_entry->added_faces) == 0) {
- BLI_ghash_reserve(log->current_entry->added_faces, (unsigned int)bm->totface);
+ if (BLI_ghash_len(log->current_entry->added_faces) == 0) {
+ BLI_ghash_reserve(log->current_entry->added_faces, (uint)bm->totface);
}
/* Log all vertices as newly created */
diff --git a/source/blender/bmesh/intern/bmesh_marking.c b/source/blender/bmesh/intern/bmesh_marking.c
index 7f2032d5f53..1b96237e262 100644
--- a/source/blender/bmesh/intern/bmesh_marking.c
+++ b/source/blender/bmesh/intern/bmesh_marking.c
@@ -57,7 +57,6 @@ static void recount_totsels(BMesh *bm)
tots[1] = &bm->totedgesel;
tots[2] = &bm->totfacesel;
-#pragma omp parallel for schedule(static) if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
for (i = 0; i < 3; i++) {
BMIter iter;
BMElem *ele;
@@ -253,44 +252,34 @@ void BM_mesh_select_mode_flush_ex(BMesh *bm, const short selectmode)
if (selectmode & SCE_SELECT_VERTEX) {
/* both loops only set edge/face flags and read off verts */
-#pragma omp parallel sections if (bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
+ BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
+ if (BM_elem_flag_test(e->v1, BM_ELEM_SELECT) &&
+ BM_elem_flag_test(e->v2, BM_ELEM_SELECT) &&
+ !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
{
- BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
- if (BM_elem_flag_test(e->v1, BM_ELEM_SELECT) &&
- BM_elem_flag_test(e->v2, BM_ELEM_SELECT) &&
- !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
- {
- BM_elem_flag_enable(e, BM_ELEM_SELECT);
- }
- else {
- BM_elem_flag_disable(e, BM_ELEM_SELECT);
- }
- }
+ BM_elem_flag_enable(e, BM_ELEM_SELECT);
}
-#pragma omp section
- {
- BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
- bool ok = true;
- if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
- l_iter = l_first = BM_FACE_FIRST_LOOP(f);
- do {
- if (!BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
- ok = false;
- break;
- }
- } while ((l_iter = l_iter->next) != l_first);
- }
- else {
+ else {
+ BM_elem_flag_disable(e, BM_ELEM_SELECT);
+ }
+ }
+ BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
+ bool ok = true;
+ if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ if (!BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
ok = false;
+ break;
}
-
- BM_elem_flag_set(f, BM_ELEM_SELECT, ok);
- }
+ } while ((l_iter = l_iter->next) != l_first);
}
+ else {
+ ok = false;
+ }
+
+ BM_elem_flag_set(f, BM_ELEM_SELECT, ok);
}
- /* end sections */
}
else if (selectmode & SCE_SELECT_EDGE) {
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
@@ -375,42 +364,31 @@ void BM_mesh_select_flush(BMesh *bm)
bool ok;
- /* we can use 2 sections here because the second loop isnt checking edge selection */
-#pragma omp parallel sections if (bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
+ BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
+ if (BM_elem_flag_test(e->v1, BM_ELEM_SELECT) &&
+ BM_elem_flag_test(e->v2, BM_ELEM_SELECT) &&
+ !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
{
- BM_ITER_MESH (e, &eiter, bm, BM_EDGES_OF_MESH) {
- if (BM_elem_flag_test(e->v1, BM_ELEM_SELECT) &&
- BM_elem_flag_test(e->v2, BM_ELEM_SELECT) &&
- !BM_elem_flag_test(e, BM_ELEM_HIDDEN))
- {
- BM_elem_flag_enable(e, BM_ELEM_SELECT);
- }
- }
+ BM_elem_flag_enable(e, BM_ELEM_SELECT);
}
-
-#pragma omp section
- {
- BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
- ok = true;
- if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
- l_iter = l_first = BM_FACE_FIRST_LOOP(f);
- do {
- if (!BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
- ok = false;
- break;
- }
- } while ((l_iter = l_iter->next) != l_first);
- }
- else {
+ }
+ BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
+ ok = true;
+ if (!BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ if (!BM_elem_flag_test(l_iter->v, BM_ELEM_SELECT)) {
ok = false;
+ break;
}
+ } while ((l_iter = l_iter->next) != l_first);
+ }
+ else {
+ ok = false;
+ }
- if (ok) {
- BM_elem_flag_enable(f, BM_ELEM_SELECT);
- }
- }
+ if (ok) {
+ BM_elem_flag_enable(f, BM_ELEM_SELECT);
}
}
@@ -1107,8 +1085,6 @@ void BM_mesh_elem_hflag_disable_test(
{
/* fast path for deselect all, avoid topology loops
* since we know all will be de-selected anyway. */
-
-#pragma omp parallel for schedule(static) if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
for (i = 0; i < 3; i++) {
BMIter iter;
BMElem *ele;
diff --git a/source/blender/bmesh/intern/bmesh_mesh.c b/source/blender/bmesh/intern/bmesh_mesh.c
index 57a6d8d2e1a..7f7f48e37bd 100644
--- a/source/blender/bmesh/intern/bmesh_mesh.c
+++ b/source/blender/bmesh/intern/bmesh_mesh.c
@@ -35,6 +35,7 @@
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_stack.h"
+#include "BLI_task.h"
#include "BLI_utildefines.h"
#include "BKE_cdderivedmesh.h"
@@ -42,6 +43,8 @@
#include "BKE_mesh.h"
#include "BKE_multires.h"
+#include "atomic_ops.h"
+
#include "intern/bmesh_private.h"
/* used as an extern, defined in bmesh.h */
@@ -112,37 +115,24 @@ void BM_mesh_elem_toolflags_ensure(BMesh *bm)
bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totedge, 512, BLI_MEMPOOL_NOP);
bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer), bm->totface, 512, BLI_MEMPOOL_NOP);
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
- {
- BLI_mempool *toolflagpool = bm->vtoolflagpool;
- BMIter iter;
- BMVert_OFlag *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
- ele->oflags = BLI_mempool_calloc(toolflagpool);
- }
- }
-#pragma omp section
- {
- BLI_mempool *toolflagpool = bm->etoolflagpool;
- BMIter iter;
- BMEdge_OFlag *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
- ele->oflags = BLI_mempool_calloc(toolflagpool);
- }
- }
-#pragma omp section
- {
- BLI_mempool *toolflagpool = bm->ftoolflagpool;
- BMIter iter;
- BMFace_OFlag *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
- ele->oflags = BLI_mempool_calloc(toolflagpool);
- }
- }
+ BMIter iter;
+ BMVert_OFlag *v_olfag;
+ BLI_mempool *toolflagpool = bm->vtoolflagpool;
+ BM_ITER_MESH (v_olfag, &iter, bm, BM_VERTS_OF_MESH) {
+ v_olfag->oflags = BLI_mempool_calloc(toolflagpool);
}
+ BMEdge_OFlag *e_olfag;
+ toolflagpool = bm->etoolflagpool;
+ BM_ITER_MESH (e_olfag, &iter, bm, BM_EDGES_OF_MESH) {
+ e_olfag->oflags = BLI_mempool_calloc(toolflagpool);
+ }
+
+ BMFace_OFlag *f_olfag;
+ toolflagpool = bm->ftoolflagpool;
+ BM_ITER_MESH (f_olfag, &iter, bm, BM_FACES_OF_MESH) {
+ f_olfag->oflags = BLI_mempool_calloc(toolflagpool);
+ }
bm->totflags = 1;
}
@@ -318,96 +308,163 @@ void BM_mesh_free(BMesh *bm)
MEM_freeN(bm);
}
+
/**
* Helpers for #BM_mesh_normals_update and #BM_verts_calc_normal_vcos
*/
-static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
+
+typedef struct BMEdgesCalcVectorsData {
+ /* Read-only data. */
+ const float (*vcos)[3];
+
+ /* Read-write data, but no need to protect it, no concurrency to fear here. */
+ float (*edgevec)[3];
+} BMEdgesCalcVectorsData;
+
+
+static void mesh_edges_calc_vectors_cb(void *userdata, MempoolIterData *mp_e)
{
- BMIter eiter;
- BMEdge *e;
- int index;
+ BMEdgesCalcVectorsData *data = userdata;
+ BMEdge *e = (BMEdge *)mp_e;
- if (vcos) {
- BM_mesh_elem_index_ensure(bm, BM_VERT);
+ if (e->l) {
+ const float *v1_co = data->vcos ? data->vcos[BM_elem_index_get(e->v1)] : e->v1->co;
+ const float *v2_co = data->vcos ? data->vcos[BM_elem_index_get(e->v2)] : e->v2->co;
+ sub_v3_v3v3(data->edgevec[BM_elem_index_get(e)], v2_co, v1_co);
+ normalize_v3(data->edgevec[BM_elem_index_get(e)]);
}
+ else {
+ /* the edge vector will not be needed when the edge has no radial */
+ }
+}
- BM_ITER_MESH_INDEX (e, &eiter, bm, BM_EDGES_OF_MESH, index) {
- BM_elem_index_set(e, index); /* set_inline */
+static void bm_mesh_edges_calc_vectors(BMesh *bm, float (*edgevec)[3], const float (*vcos)[3])
+{
+ BM_mesh_elem_index_ensure(bm, BM_EDGE | (vcos ? BM_VERT : 0));
+
+ BMEdgesCalcVectorsData data = {
+ .vcos = vcos,
+ .edgevec = edgevec
+ };
- if (e->l) {
- const float *v1_co = vcos ? vcos[BM_elem_index_get(e->v1)] : e->v1->co;
- const float *v2_co = vcos ? vcos[BM_elem_index_get(e->v2)] : e->v2->co;
- sub_v3_v3v3(edgevec[index], v2_co, v1_co);
- normalize_v3(edgevec[index]);
+ BM_iter_parallel(bm, BM_EDGES_OF_MESH, mesh_edges_calc_vectors_cb, &data, bm->totedge >= BM_OMP_LIMIT);
+}
+
+
+typedef struct BMVertsCalcNormalsData {
+ /* Read-only data. */
+ const float (*fnos)[3];
+ const float (*edgevec)[3];
+ const float (*vcos)[3];
+
+ /* Read-write data, protected by an atomic-based fake spinlock-like system... */
+ float (*vnos)[3];
+} BMVertsCalcNormalsData;
+
+static void mesh_verts_calc_normals_accum_cb(void *userdata, MempoolIterData *mp_f)
+{
+ BMVertsCalcNormalsData *data = userdata;
+ BMFace *f = (BMFace *)mp_f;
+
+ const float *f_no = data->fnos ? data->fnos[BM_elem_index_get(f)] : f->no;
+
+ BMLoop *l_first, *l_iter;
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ const float *e1diff, *e2diff;
+ float dotprod;
+ float fac;
+
+ /* calculate the dot product of the two edges that
+ * meet at the loop's vertex */
+ e1diff = data->edgevec[BM_elem_index_get(l_iter->prev->e)];
+ e2diff = data->edgevec[BM_elem_index_get(l_iter->e)];
+ dotprod = dot_v3v3(e1diff, e2diff);
+
+ /* edge vectors are calculated from e->v1 to e->v2, so
+ * adjust the dot product if one but not both loops
+ * actually runs from from e->v2 to e->v1 */
+ if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
+ dotprod = -dotprod;
}
- else {
- /* the edge vector will not be needed when the edge has no radial */
+
+ fac = saacos(-dotprod);
+
+ /* accumulate weighted face normal into the vertex's normal */
+ float *v_no = data->vnos ? data->vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
+
+ /* This block is a lockless threadsafe madd_v3_v3fl.
+ * It uses the first float of the vector as a sort of cheap spinlock,
+ * assuming FLT_MAX is a safe 'illegal' value that cannot be set here otherwise.
+ * It also assumes that collisions between threads are highly unlikely,
+ * else performances would be quite bad here. */
+ float virtual_lock = v_no[0];
+ while (true) {
+ /* This loops until following conditions are met:
+ * - v_no[0] has same value as virtual_lock (i.e. it did not change since last try).
+ * - v_no[0] was not FLT_MAX, i.e. it was not locked by another thread.
+ */
+ const float vl = atomic_cas_float(&v_no[0], virtual_lock, FLT_MAX);
+ if (vl == virtual_lock && vl != FLT_MAX) {
+ break;
+ }
+ virtual_lock = vl;
}
+ BLI_assert(v_no[0] == FLT_MAX);
+ /* Now we own that normal value, and can change it.
+ * But first scalar of the vector must not be changed yet, it's our lock! */
+ virtual_lock += f_no[0] * fac;
+ v_no[1] += f_no[1] * fac;
+ v_no[2] += f_no[2] * fac;
+ /* Second atomic operation to 'release' our lock on that vector and set its first scalar value. */
+ /* Note that we do not need to loop here, since we 'locked' v_no[0],
+ * nobody should have changed it in the mean time. */
+ virtual_lock = atomic_cas_float(&v_no[0], FLT_MAX, virtual_lock);
+ BLI_assert(virtual_lock == FLT_MAX);
+
+ } while ((l_iter = l_iter->next) != l_first);
+}
+
+static void mesh_verts_calc_normals_normalize_cb(void *userdata, MempoolIterData *mp_v)
+{
+ BMVertsCalcNormalsData *data = userdata;
+ BMVert *v = (BMVert *)mp_v;
+
+ float *v_no = data->vnos ? data->vnos[BM_elem_index_get(v)] : v->no;
+ if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
+ const float *v_co = data->vcos ? data->vcos[BM_elem_index_get(v)] : v->co;
+ normalize_v3_v3(v_no, v_co);
}
- bm->elem_index_dirty &= ~BM_EDGE;
}
static void bm_mesh_verts_calc_normals(
BMesh *bm, const float (*edgevec)[3], const float (*fnos)[3],
const float (*vcos)[3], float (*vnos)[3])
{
- BM_mesh_elem_index_ensure(bm, (vnos) ? (BM_EDGE | BM_VERT) : BM_EDGE);
+ BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE) | ((vnos || vcos) ? BM_VERT : 0));
- /* add weighted face normals to vertices */
- {
- BMIter fiter;
- BMFace *f;
- int i;
-
- BM_ITER_MESH_INDEX (f, &fiter, bm, BM_FACES_OF_MESH, i) {
- BMLoop *l_first, *l_iter;
- const float *f_no = fnos ? fnos[i] : f->no;
-
- l_iter = l_first = BM_FACE_FIRST_LOOP(f);
- do {
- const float *e1diff, *e2diff;
- float dotprod;
- float fac;
- float *v_no = vnos ? vnos[BM_elem_index_get(l_iter->v)] : l_iter->v->no;
-
- /* calculate the dot product of the two edges that
- * meet at the loop's vertex */
- e1diff = edgevec[BM_elem_index_get(l_iter->prev->e)];
- e2diff = edgevec[BM_elem_index_get(l_iter->e)];
- dotprod = dot_v3v3(e1diff, e2diff);
-
- /* edge vectors are calculated from e->v1 to e->v2, so
- * adjust the dot product if one but not both loops
- * actually runs from from e->v2 to e->v1 */
- if ((l_iter->prev->e->v1 == l_iter->prev->v) ^ (l_iter->e->v1 == l_iter->v)) {
- dotprod = -dotprod;
- }
+ BMVertsCalcNormalsData data = {
+ .fnos = fnos,
+ .edgevec = edgevec,
+ .vcos = vcos,
+ .vnos = vnos
+ };
- fac = saacos(-dotprod);
+ BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_verts_calc_normals_accum_cb, &data, bm->totface >= BM_OMP_LIMIT);
- /* accumulate weighted face normal into the vertex's normal */
- madd_v3_v3fl(v_no, f_no, fac);
- } while ((l_iter = l_iter->next) != l_first);
- }
- }
+ /* normalize the accumulated vertex normals */
+ BM_iter_parallel(bm, BM_VERTS_OF_MESH, mesh_verts_calc_normals_normalize_cb, &data, bm->totvert >= BM_OMP_LIMIT);
+}
- /* normalize the accumulated vertex normals */
- {
- BMIter viter;
- BMVert *v;
- int i;
-
- BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
- float *v_no = vnos ? vnos[i] : v->no;
- if (UNLIKELY(normalize_v3(v_no) == 0.0f)) {
- const float *v_co = vcos ? vcos[i] : v->co;
- normalize_v3_v3(v_no, v_co);
- }
- }
- }
+static void mesh_faces_calc_normals_cb(void *UNUSED(userdata), MempoolIterData *mp_f)
+{
+ BMFace *f = (BMFace *)mp_f;
+
+ BM_face_normal_update(f);
}
+
/**
* \brief BMesh Compute Normals
*
@@ -417,43 +474,27 @@ void BM_mesh_normals_update(BMesh *bm)
{
float (*edgevec)[3] = MEM_mallocN(sizeof(*edgevec) * bm->totedge, __func__);
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
- {
- /* calculate all face normals */
- BMIter fiter;
- BMFace *f;
- int i;
-
- BM_ITER_MESH_INDEX (f, &fiter, bm, BM_FACES_OF_MESH, i) {
- BM_elem_index_set(f, i); /* set_inline */
- BM_face_normal_update(f);
- }
- bm->elem_index_dirty &= ~BM_FACE;
- }
-#pragma omp section
- {
- /* Zero out vertex normals */
- BMIter viter;
- BMVert *v;
- int i;
-
- BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
- BM_elem_index_set(v, i); /* set_inline */
- zero_v3(v->no);
- }
- bm->elem_index_dirty &= ~BM_VERT;
- }
-#pragma omp section
- {
- /* Compute normalized direction vectors for each edge.
- * Directions will be used for calculating the weights of the face normals on the vertex normals.
- */
- bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
- }
+ /* Parallel mempool iteration does not allow to generate indices inline anymore... */
+ BM_mesh_elem_index_ensure(bm, (BM_EDGE | BM_FACE));
+
+ /* calculate all face normals */
+ BM_iter_parallel(bm, BM_FACES_OF_MESH, mesh_faces_calc_normals_cb, NULL, bm->totface >= BM_OMP_LIMIT);
+
+ /* Zero out vertex normals */
+ BMIter viter;
+ BMVert *v;
+ int i;
+
+ BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
+ BM_elem_index_set(v, i); /* set_inline */
+ zero_v3(v->no);
}
- /* end omp */
+ bm->elem_index_dirty &= ~BM_VERT;
+
+ /* Compute normalized direction vectors for each edge.
+ * Directions will be used for calculating the weights of the face normals on the vertex normals.
+ */
+ bm_mesh_edges_calc_vectors(bm, edgevec, NULL);
/* Add weighted face normals to vertices, and normalize vert normals. */
bm_mesh_verts_calc_normals(bm, (const float(*)[3])edgevec, NULL, NULL, NULL);
@@ -480,37 +521,28 @@ void BM_verts_calc_normal_vcos(BMesh *bm, const float (*fnos)[3], const float (*
}
/**
- * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normals_vnos
+ * Helpers for #BM_mesh_loop_normals_update and #BM_loops_calc_normal_vcos
*/
static void bm_mesh_edges_sharp_tag(
- BMesh *bm, const float (*vnos)[3], const float (*fnos)[3], float split_angle,
- float (*r_lnos)[3])
+ BMesh *bm,
+ const float (*vnos)[3], const float (*fnos)[3], float (*r_lnos)[3],
+ const float split_angle, const bool do_sharp_edges_tag)
{
- BMIter eiter, viter;
- BMVert *v;
+ BMIter eiter;
BMEdge *e;
int i;
const bool check_angle = (split_angle < (float)M_PI);
-
- if (check_angle) {
- split_angle = cosf(split_angle);
- }
+ const float split_angle_cos = check_angle ? cosf(split_angle) : -1.0f;
{
- char htype = BM_LOOP;
+ char htype = BM_VERT | BM_LOOP;
if (fnos) {
htype |= BM_FACE;
}
BM_mesh_elem_index_ensure(bm, htype);
}
- /* Clear all vertices' tags (means they are all smooth for now). */
- BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
- BM_elem_index_set(v, i); /* set_inline */
- BM_elem_flag_disable(v, BM_ELEM_TAG);
- }
-
/* This first loop checks which edges are actually smooth, and pre-populate lnos with vnos (as if they were
* all smooth).
*/
@@ -526,7 +558,7 @@ static void bm_mesh_edges_sharp_tag(
if (check_angle) {
const float *no_a = fnos ? fnos[BM_elem_index_get(l_a->f)] : l_a->f->no;
const float *no_b = fnos ? fnos[BM_elem_index_get(l_b->f)] : l_b->f->no;
- is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle);
+ is_angle_smooth = (dot_v3v3(no_a, no_b) >= split_angle_cos);
}
/* We only tag edges that are *really* smooth:
@@ -536,35 +568,70 @@ static void bm_mesh_edges_sharp_tag(
* and both its faces have compatible (non-flipped) normals,
* i.e. both loops on the same edge do not share the same vertex.
*/
- if (is_angle_smooth &&
- BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
+ if (BM_elem_flag_test(e, BM_ELEM_SMOOTH) &&
BM_elem_flag_test(l_a->f, BM_ELEM_SMOOTH) &&
BM_elem_flag_test(l_b->f, BM_ELEM_SMOOTH) &&
l_a->v != l_b->v)
{
- const float *no;
- BM_elem_flag_enable(e, BM_ELEM_TAG);
-
- /* linked vertices might be fully smooth, copy their normals to loop ones. */
- no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
- copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
- no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
- copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
+ if (is_angle_smooth) {
+ const float *no;
+ BM_elem_flag_enable(e, BM_ELEM_TAG);
+
+ /* linked vertices might be fully smooth, copy their normals to loop ones. */
+ if (r_lnos) {
+ no = vnos ? vnos[BM_elem_index_get(l_a->v)] : l_a->v->no;
+ copy_v3_v3(r_lnos[BM_elem_index_get(l_a)], no);
+ no = vnos ? vnos[BM_elem_index_get(l_b->v)] : l_b->v->no;
+ copy_v3_v3(r_lnos[BM_elem_index_get(l_b)], no);
+ }
+ }
+ else if (do_sharp_edges_tag) {
+ /* Note that we do not care about the other sharp-edge cases (sharp poly, non-manifold edge, etc.),
+ * only tag edge as sharp when it is due to angle threashold. */
+ BM_elem_flag_disable(e, BM_ELEM_SMOOTH);
+ }
}
- else {
- /* Sharp edge, tag its verts as such. */
- BM_elem_flag_enable(e->v1, BM_ELEM_TAG);
- BM_elem_flag_enable(e->v2, BM_ELEM_TAG);
+ }
+ }
+
+ bm->elem_index_dirty &= ~BM_EDGE;
+}
+
+/**
+ * Check whether given loop is part of an unknown-so-far cyclic smooth fan, or not.
+ * Needed because cyclic smooth fans have no obvious 'entry point', and yet we need to walk them once, and only once.
+ */
+bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr)
+{
+ BMLoop *lfan_pivot_next = l_curr;
+ BMEdge *e_next = l_curr->e;
+
+ BLI_assert(!BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG));
+ BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
+
+ while (true) {
+ /* Much simpler than in sibling code with basic Mesh data! */
+ lfan_pivot_next = BM_vert_step_fan_loop(lfan_pivot_next, &e_next);
+
+ if (!lfan_pivot_next || !BM_elem_flag_test(e_next, BM_ELEM_TAG)) {
+ /* Sharp loop/edge, so not a cyclic smooth fan... */
+ return false;
+ }
+ /* Smooth loop/edge... */
+ else if (BM_elem_flag_test(lfan_pivot_next, BM_ELEM_TAG)) {
+ if (lfan_pivot_next == l_curr) {
+ /* We walked around a whole cyclic smooth fan without finding any already-processed loop, means we can
+ * use initial l_curr/l_prev edge as start for this smooth fan. */
+ return true;
}
+ /* ... already checked in some previous looping, we can abort. */
+ return false;
}
else {
- /* Sharp edge, tag its verts as such. */
- BM_elem_flag_enable(e->v1, BM_ELEM_TAG);
- BM_elem_flag_enable(e->v2, BM_ELEM_TAG);
+ /* ... we can skip it in future, and keep checking the smooth fan. */
+ BM_elem_flag_enable(lfan_pivot_next, BM_ELEM_TAG);
}
}
-
- bm->elem_index_dirty &= ~(BM_EDGE | BM_VERT);
}
/* BMesh version of BKE_mesh_normals_loop_split() in mesh_evaluate.c
@@ -587,13 +654,11 @@ static void bm_mesh_loops_calc_normals(
BLI_Stack *edge_vectors = NULL;
{
- char htype = BM_LOOP;
+ char htype = 0;
if (vcos) {
htype |= BM_VERT;
}
- if (fnos) {
- htype |= BM_FACE;
- }
+ /* Face/Loop indices are set inline below. */
BM_mesh_elem_index_ensure(bm, htype);
}
@@ -602,10 +667,25 @@ static void bm_mesh_loops_calc_normals(
r_lnors_spacearr = &_lnors_spacearr;
}
if (r_lnors_spacearr) {
- BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop);
+ BKE_lnor_spacearr_init(r_lnors_spacearr, bm->totloop, MLNOR_SPACEARR_BMLOOP_PTR);
edge_vectors = BLI_stack_new(sizeof(float[3]), __func__);
}
+ /* Clear all loops' tags (means none are to be skipped for now). */
+ int index_face, index_loop = 0;
+ BM_ITER_MESH_INDEX (f_curr, &fiter, bm, BM_FACES_OF_MESH, index_face) {
+ BMLoop *l_curr, *l_first;
+
+ BM_elem_index_set(f_curr, index_face); /* set_inline */
+
+ l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
+ do {
+ BM_elem_index_set(l_curr, index_loop++); /* set_inline */
+ BM_elem_flag_disable(l_curr, BM_ELEM_TAG);
+ } while ((l_curr = l_curr->next) != l_first);
+ }
+ bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP);
+
/* We now know edges that can be smoothed (they are tagged), and edges that will be hard (they aren't).
* Now, time to generate the normals.
*/
@@ -614,16 +694,16 @@ static void bm_mesh_loops_calc_normals(
l_curr = l_first = BM_FACE_FIRST_LOOP(f_curr);
do {
+ /* A smooth edge, we have to check for cyclic smooth fan case.
+ * If we find a new, never-processed cyclic smooth fan, we can do it now using that loop/edge as
+ * 'entry point', otherwise we can skip it. */
+ /* Note: In theory, we could make bm_mesh_loop_check_cyclic_smooth_fan() store mlfan_pivot's in a stack,
+ * to avoid having to fan again around the vert during actual computation of clnor & clnorspace.
+ * However, this would complicate the code, add more memory usage, and BM_vert_step_fan_loop()
+ * is quite cheap in term of CPU cycles, so really think it's not worth it. */
if (BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
- (!r_lnors_spacearr || BM_elem_flag_test(l_curr->v, BM_ELEM_TAG)))
+ (BM_elem_flag_test(l_curr, BM_ELEM_TAG) || !BM_loop_check_cyclic_smooth_fan(l_curr)))
{
- /* A smooth edge, and we are not generating lnors_spacearr, or the related vertex is sharp.
- * We skip it because it is either:
- * - in the middle of a 'smooth fan' already computed (or that will be as soon as we hit
- * one of its ends, i.e. one of its two sharp edges), or...
- * - the related vertex is a "full smooth" one, in which case pre-populated normals from vertex
- * are just fine!
- */
}
else if (!BM_elem_flag_test(l_curr->e, BM_ELEM_TAG) &&
!BM_elem_flag_test(l_curr->prev->e, BM_ELEM_TAG))
@@ -656,7 +736,7 @@ static void bm_mesh_loops_calc_normals(
BKE_lnor_space_define(lnor_space, r_lnos[l_curr_index], vec_curr, vec_prev, NULL);
/* We know there is only one loop in this space, no need to create a linklist in this case... */
- BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, false);
+ BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, l_curr_index, l_curr, true);
if (has_clnors) {
short (*clnor)[2] = clnors_data ? &clnors_data[l_curr_index] :
@@ -744,7 +824,7 @@ static void bm_mesh_loops_calc_normals(
}
{
- /* Code similar to accumulate_vertex_normals_poly. */
+ /* Code similar to accumulate_vertex_normals_poly_v3. */
/* Calculate angle between the two poly edges incident on this vertex. */
const BMFace *f = lfan_pivot->f;
const float fac = saacos(dot_v3v3(vec_next, vec_curr));
@@ -775,7 +855,7 @@ static void bm_mesh_loops_calc_normals(
if (r_lnors_spacearr) {
/* Assign current lnor space to current 'vertex' loop. */
- BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, true);
+ BKE_lnor_space_add_loop(r_lnors_spacearr, lnor_space, lfan_pivot_index, lfan_pivot, false);
if (e_next != e_org) {
/* We store here all edges-normalized vectors processed. */
BLI_stack_push(edge_vectors, vec_next);
@@ -936,7 +1016,7 @@ void BM_loops_calc_normal_vcos(
if (use_split_normals) {
/* Tag smooth edges and set lnos from vnos when they might be completely smooth...
* When using custom loop normals, disable the angle feature! */
- bm_mesh_edges_sharp_tag(bm, vnos, fnos, has_clnors ? (float)M_PI : split_angle, r_lnos);
+ bm_mesh_edges_sharp_tag(bm, vnos, fnos, r_lnos, has_clnors ? (float)M_PI : split_angle, false);
/* Finish computing lnos by accumulating face normals in each fan of faces defined by sharp edges. */
bm_mesh_loops_calc_normals(bm, vcos, fnos, r_lnos, r_lnors_spacearr, clnors_data, cd_loop_clnors_offset);
@@ -947,6 +1027,20 @@ void BM_loops_calc_normal_vcos(
}
}
+/** Define sharp edges as needed to mimic 'autosmooth' from angle threshold.
+ *
+ * Used when defining an empty custom loop normals data layer, to keep same shading as with autosmooth!
+ */
+void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle)
+{
+ if (split_angle >= (float)M_PI) {
+ /* Nothing to do! */
+ return;
+ }
+
+ bm_mesh_edges_sharp_tag(bm, NULL, NULL, NULL, split_angle, true);
+}
+
static void UNUSED_FUNCTION(bm_mdisps_space_set)(Object *ob, BMesh *bm, int from, int to)
{
/* switch multires data out of tangent space */
@@ -1073,94 +1167,78 @@ void BM_mesh_elem_index_ensure(BMesh *bm, const char htype)
BM_ELEM_INDEX_VALIDATE(bm, "Should Never Fail!", __func__);
#endif
- if (htype_needed == 0) {
+ if (0 && htype_needed == 0) {
goto finally;
}
- /* skip if we only need to operate on one element */
-#pragma omp parallel sections if ((!ELEM(htype_needed, BM_VERT, BM_EDGE, BM_FACE, BM_LOOP, BM_FACE | BM_LOOP)) && \
- (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT))
- {
-#pragma omp section
+ if (htype & BM_VERT) {
+ if (bm->elem_index_dirty & BM_VERT) {
+ BMIter iter;
+ BMElem *ele;
- {
- if (htype & BM_VERT) {
- if (bm->elem_index_dirty & BM_VERT) {
- BMIter iter;
- BMElem *ele;
-
- int index;
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
- BM_elem_index_set(ele, index); /* set_ok */
- }
- BLI_assert(index == bm->totvert);
- }
- else {
- // printf("%s: skipping vert index calc!\n", __func__);
- }
+ int index;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, index) {
+ BM_elem_index_set(ele, index); /* set_ok */
}
+ BLI_assert(index == bm->totvert);
+ }
+ else {
+ // printf("%s: skipping vert index calc!\n", __func__);
}
+ }
-#pragma omp section
- {
- if (htype & BM_EDGE) {
- if (bm->elem_index_dirty & BM_EDGE) {
- BMIter iter;
- BMElem *ele;
-
- int index;
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
- BM_elem_index_set(ele, index); /* set_ok */
- }
- BLI_assert(index == bm->totedge);
- }
- else {
- // printf("%s: skipping edge index calc!\n", __func__);
- }
+ if (htype & BM_EDGE) {
+ if (bm->elem_index_dirty & BM_EDGE) {
+ BMIter iter;
+ BMElem *ele;
+
+ int index;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, index) {
+ BM_elem_index_set(ele, index); /* set_ok */
}
+ BLI_assert(index == bm->totedge);
}
+ else {
+ // printf("%s: skipping edge index calc!\n", __func__);
+ }
+ }
-#pragma omp section
- {
- if (htype & (BM_FACE | BM_LOOP)) {
- if (bm->elem_index_dirty & (BM_FACE | BM_LOOP)) {
- BMIter iter;
- BMElem *ele;
-
- const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
- const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
+ if (htype & (BM_FACE | BM_LOOP)) {
+ if (bm->elem_index_dirty & (BM_FACE | BM_LOOP)) {
+ BMIter iter;
+ BMElem *ele;
- int index;
- int index_loop = 0;
+ const bool update_face = (htype & BM_FACE) && (bm->elem_index_dirty & BM_FACE);
+ const bool update_loop = (htype & BM_LOOP) && (bm->elem_index_dirty & BM_LOOP);
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
- if (update_face) {
- BM_elem_index_set(ele, index); /* set_ok */
- }
+ int index;
+ int index_loop = 0;
- if (update_loop) {
- BMLoop *l_iter, *l_first;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, index) {
+ if (update_face) {
+ BM_elem_index_set(ele, index); /* set_ok */
+ }
- l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
- do {
- BM_elem_index_set(l_iter, index_loop++); /* set_ok */
- } while ((l_iter = l_iter->next) != l_first);
- }
- }
+ if (update_loop) {
+ BMLoop *l_iter, *l_first;
- BLI_assert(index == bm->totface);
- if (update_loop) {
- BLI_assert(index_loop == bm->totloop);
- }
- }
- else {
- // printf("%s: skipping face/loop index calc!\n", __func__);
+ l_iter = l_first = BM_FACE_FIRST_LOOP((BMFace *)ele);
+ do {
+ BM_elem_index_set(l_iter, index_loop++); /* set_ok */
+ } while ((l_iter = l_iter->next) != l_first);
}
}
+
+ BLI_assert(index == bm->totface);
+ if (update_loop) {
+ BLI_assert(index_loop == bm->totloop);
+ }
+ }
+ else {
+ // printf("%s: skipping face/loop index calc!\n", __func__);
}
}
-
finally:
bm->elem_index_dirty &= ~htype;
}
@@ -1332,28 +1410,16 @@ void BM_mesh_elem_table_ensure(BMesh *bm, const char htype)
}
}
- /* skip if we only need to operate on one element */
-#pragma omp parallel sections if ((!ELEM(htype_needed, BM_VERT, BM_EDGE, BM_FACE)) && \
- (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT))
- {
-#pragma omp section
- {
- if (htype_needed & BM_VERT) {
- BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
- }
- }
-#pragma omp section
- {
- if (htype_needed & BM_EDGE) {
- BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
- }
- }
-#pragma omp section
- {
- if (htype_needed & BM_FACE) {
- BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
- }
- }
+ if (htype_needed & BM_VERT) {
+ BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)bm->vtable, bm->totvert);
+ }
+
+ if (htype_needed & BM_EDGE) {
+ BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)bm->etable, bm->totedge);
+ }
+
+ if (htype_needed & BM_FACE) {
+ BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)bm->ftable, bm->totface);
}
finally:
@@ -1481,23 +1547,6 @@ int BM_mesh_elem_count(BMesh *bm, const char htype)
}
}
-/**
- * Special case: Python uses custom-data layers to hold PyObject references.
- * These have to be kept in-place, else the PyObject's we point to, wont point back to us.
- *
- * \note ``ele_src`` Is a duplicate, so we don't need to worry about getting in a feedback loop.
- *
- * \note If there are other customdata layers which need this functionality, it should be generalized.
- * However #BM_mesh_remap is currently the only place where this is done.
- */
-static void bm_mesh_remap_cd_update(
- BMHeader *ele_dst, BMHeader *ele_src,
- const int cd_elem_pyptr)
-{
- void **pyptr_dst_p = BM_ELEM_CD_GET_VOID_P(((BMElem *)ele_dst), cd_elem_pyptr);
- void **pyptr_src_p = BM_ELEM_CD_GET_VOID_P(((BMElem *)ele_src), cd_elem_pyptr);
- *pyptr_dst_p = *pyptr_src_p;
-}
/**
* Remaps the vertices, edges and/or faces of the bmesh as indicated by vert/edge/face_idx arrays
@@ -1513,9 +1562,9 @@ static void bm_mesh_remap_cd_update(
*/
void BM_mesh_remap(
BMesh *bm,
- const unsigned int *vert_idx,
- const unsigned int *edge_idx,
- const unsigned int *face_idx)
+ const uint *vert_idx,
+ const uint *edge_idx,
+ const uint *face_idx)
{
/* Mapping old to new pointers. */
GHash *vptr_map = NULL, *eptr_map = NULL, *fptr_map = NULL;
@@ -1538,7 +1587,9 @@ void BM_mesh_remap(
if (vert_idx) {
BMVert **verts_pool, *verts_copy, **vep;
int i, totvert = bm->totvert;
- const unsigned int *new_idx;
+ const uint *new_idx;
+ /* Special case: Python uses custom - data layers to hold PyObject references.
+ * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_vert_pyptr = CustomData_get_offset(&bm->vdata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
@@ -1547,9 +1598,14 @@ void BM_mesh_remap(
/* Make a copy of all vertices. */
verts_pool = bm->vtable;
verts_copy = MEM_mallocN(sizeof(BMVert) * totvert, "BM_mesh_remap verts copy");
+ void **pyptrs = (cd_vert_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totvert, __func__) : NULL;
for (i = totvert, ve = verts_copy + totvert - 1, vep = verts_pool + totvert - 1; i--; ve--, vep--) {
*ve = **vep;
/* printf("*vep: %p, verts_pool[%d]: %p\n", *vep, i, verts_pool[i]);*/
+ if (cd_vert_pyptr != -1) {
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ve), cd_vert_pyptr);
+ pyptrs[i] = *pyptr;
+ }
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
@@ -1562,20 +1618,26 @@ void BM_mesh_remap(
/* printf("mapping vert from %d to %d (%p/%p to %p)\n", i, *new_idx, *vep, verts_pool[i], new_vep);*/
BLI_ghash_insert(vptr_map, *vep, new_vep);
if (cd_vert_pyptr != -1) {
- bm_mesh_remap_cd_update(&(*vep)->head, &new_vep->head, cd_vert_pyptr);
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_vep), cd_vert_pyptr);
+ *pyptr = pyptrs[*new_idx];
}
}
bm->elem_index_dirty |= BM_VERT;
bm->elem_table_dirty |= BM_VERT;
MEM_freeN(verts_copy);
+ if (pyptrs) {
+ MEM_freeN(pyptrs);
+ }
}
/* Remap Edges */
if (edge_idx) {
BMEdge **edges_pool, *edges_copy, **edp;
int i, totedge = bm->totedge;
- const unsigned int *new_idx;
+ const uint *new_idx;
+ /* Special case: Python uses custom - data layers to hold PyObject references.
+ * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_edge_pyptr = CustomData_get_offset(&bm->edata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
@@ -1584,8 +1646,13 @@ void BM_mesh_remap(
/* Make a copy of all vertices. */
edges_pool = bm->etable;
edges_copy = MEM_mallocN(sizeof(BMEdge) * totedge, "BM_mesh_remap edges copy");
+ void **pyptrs = (cd_edge_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totedge, __func__) : NULL;
for (i = totedge, ed = edges_copy + totedge - 1, edp = edges_pool + totedge - 1; i--; ed--, edp--) {
*ed = **edp;
+ if (cd_edge_pyptr != -1) {
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)ed), cd_edge_pyptr);
+ pyptrs[i] = *pyptr;
+ }
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
@@ -1598,20 +1665,26 @@ void BM_mesh_remap(
BLI_ghash_insert(eptr_map, *edp, new_edp);
/* printf("mapping edge from %d to %d (%p/%p to %p)\n", i, *new_idx, *edp, edges_pool[i], new_edp);*/
if (cd_edge_pyptr != -1) {
- bm_mesh_remap_cd_update(&(*edp)->head, &new_edp->head, cd_edge_pyptr);
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_edp), cd_edge_pyptr);
+ *pyptr = pyptrs[*new_idx];
}
}
bm->elem_index_dirty |= BM_EDGE;
bm->elem_table_dirty |= BM_EDGE;
MEM_freeN(edges_copy);
+ if (pyptrs) {
+ MEM_freeN(pyptrs);
+ }
}
/* Remap Faces */
if (face_idx) {
BMFace **faces_pool, *faces_copy, **fap;
int i, totface = bm->totface;
- const unsigned int *new_idx;
+ const uint *new_idx;
+ /* Special case: Python uses custom - data layers to hold PyObject references.
+ * These have to be kept in - place, else the PyObject's we point to, wont point back to us. */
const int cd_poly_pyptr = CustomData_get_offset(&bm->pdata, CD_BM_ELEM_PYPTR);
/* Init the old-to-new vert pointers mapping */
@@ -1620,8 +1693,13 @@ void BM_mesh_remap(
/* Make a copy of all vertices. */
faces_pool = bm->ftable;
faces_copy = MEM_mallocN(sizeof(BMFace) * totface, "BM_mesh_remap faces copy");
+ void **pyptrs = (cd_poly_pyptr != -1) ? MEM_mallocN(sizeof(void *) * totface, __func__) : NULL;
for (i = totface, fa = faces_copy + totface - 1, fap = faces_pool + totface - 1; i--; fa--, fap--) {
*fa = **fap;
+ if (cd_poly_pyptr != -1) {
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)fa), cd_poly_pyptr);
+ pyptrs[i] = *pyptr;
+ }
}
/* Copy back verts to their new place, and update old2new pointers mapping. */
@@ -1633,7 +1711,8 @@ void BM_mesh_remap(
*new_fap = *fa;
BLI_ghash_insert(fptr_map, *fap, new_fap);
if (cd_poly_pyptr != -1) {
- bm_mesh_remap_cd_update(&(*fap)->head, &new_fap->head, cd_poly_pyptr);
+ void **pyptr = BM_ELEM_CD_GET_VOID_P(((BMElem *)new_fap), cd_poly_pyptr);
+ *pyptr = pyptrs[*new_idx];
}
}
@@ -1641,6 +1720,9 @@ void BM_mesh_remap(
bm->elem_table_dirty |= BM_FACE;
MEM_freeN(faces_copy);
+ if (pyptrs) {
+ MEM_freeN(pyptrs);
+ }
}
/* And now, fix all vertices/edges/faces/loops pointers! */
@@ -2008,4 +2090,4 @@ void BM_mesh_toolflags_set(BMesh *bm, bool use_toolflags)
vpool_dst, epool_dst, NULL, fpool_dst);
bm->use_toolflags = use_toolflags;
-} \ No newline at end of file
+}
diff --git a/source/blender/bmesh/intern/bmesh_mesh.h b/source/blender/bmesh/intern/bmesh_mesh.h
index 6a9540c3b60..d449aac04f5 100644
--- a/source/blender/bmesh/intern/bmesh_mesh.h
+++ b/source/blender/bmesh/intern/bmesh_mesh.h
@@ -34,7 +34,7 @@ void BM_mesh_elem_toolflags_ensure(BMesh *bm);
void BM_mesh_elem_toolflags_clear(BMesh *bm);
struct BMeshCreateParams {
- unsigned int use_toolflags : 1;
+ uint use_toolflags : 1;
};
BMesh *BM_mesh_create(
@@ -52,6 +52,11 @@ void BM_loops_calc_normal_vcos(
const bool use_split_normals, const float split_angle, float (*r_lnos)[3],
struct MLoopNorSpaceArray *r_lnors_spacearr, short (*clnors_data)[2], const int cd_loop_clnors_offset);
+bool BM_loop_check_cyclic_smooth_fan(BMLoop *l_curr);
+
+
+void BM_edges_sharp_from_angle_set(BMesh *bm, const float split_angle);
+
void bmesh_edit_begin(BMesh *bm, const BMOpTypeFlag type_flag);
void bmesh_edit_end(BMesh *bm, const BMOpTypeFlag type_flag);
@@ -88,9 +93,9 @@ int BM_mesh_elem_count(BMesh *bm, const char htype);
void BM_mesh_remap(
BMesh *bm,
- const unsigned int *vert_idx,
- const unsigned int *edge_idx,
- const unsigned int *face_idx);
+ const uint *vert_idx,
+ const uint *edge_idx,
+ const uint *face_idx);
void BM_mesh_rebuild(
BMesh *bm, const struct BMeshCreateParams *params,
@@ -114,7 +119,7 @@ extern const BMAllocTemplate bm_mesh_chunksize_default;
(dm)->getNumEdges(dm), \
(dm)->getNumLoops(dm), \
(dm)->getNumPolys(dm), \
- }
+}
#define _VA_BMALLOC_TEMPLATE_FROM_DM_2(dm_a, dm_b) { \
(CHECK_TYPE_INLINE(dm_a, DerivedMesh *), \
CHECK_TYPE_INLINE(dm_b, DerivedMesh *), \
@@ -122,7 +127,7 @@ extern const BMAllocTemplate bm_mesh_chunksize_default;
(dm_a)->getNumEdges(dm_a) + (dm_b)->getNumEdges(dm_b), \
(dm_a)->getNumLoops(dm_a) + (dm_b)->getNumLoops(dm_b), \
(dm_a)->getNumPolys(dm_a) + (dm_b)->getNumPolys(dm_b), \
- }
+}
#define BMALLOC_TEMPLATE_FROM_DM(...) VA_NARGS_CALL_OVERLOAD(_VA_BMALLOC_TEMPLATE_FROM_DM_, __VA_ARGS__)
diff --git a/source/blender/bmesh/intern/bmesh_mesh_conv.c b/source/blender/bmesh/intern/bmesh_mesh_conv.c
index 59ce91a3e70..474b4656a68 100644
--- a/source/blender/bmesh/intern/bmesh_mesh_conv.c
+++ b/source/blender/bmesh/intern/bmesh_mesh_conv.c
@@ -219,6 +219,11 @@ static BMFace *bm_face_create_from_mpoly(
/**
* \brief Mesh -> BMesh
+ * \param bm: The mesh to write into, while this is typically a newly created BMesh,
+ * merging into existing data is supported.
+ * Note the custom-data layout isn't used.
+ * If more comprehensive merging is needed we should move this into a separate function
+ * since this should be kept fast for edit-mode switching and storing undo steps.
*
* \warning This function doesn't calculate face normals.
*/
@@ -226,6 +231,9 @@ void BM_mesh_bm_from_me(
BMesh *bm, Mesh *me,
const struct BMeshFromMeshParams *params)
{
+ const bool is_new =
+ !(bm->totvert ||
+ (bm->vdata.totlayer || bm->edata.totlayer || bm->pdata.totlayer || bm->ldata.totlayer));
MVert *mvert;
MEdge *medge;
MLoop *mloop;
@@ -233,19 +241,12 @@ void BM_mesh_bm_from_me(
KeyBlock *actkey, *block;
BMVert *v, **vtable = NULL;
BMEdge *e, **etable = NULL;
- BMFace *f;
+ BMFace *f, **ftable = NULL;
float (*keyco)[3] = NULL;
- int totuv, totloops, i, j;
-
- /* free custom data */
- /* this isnt needed in most cases but do just incase */
- CustomData_free(&bm->vdata, bm->totvert);
- CustomData_free(&bm->edata, bm->totedge);
- CustomData_free(&bm->ldata, bm->totloop);
- CustomData_free(&bm->pdata, bm->totface);
+ int totuv, totloops, i;
if (!me || !me->totvert) {
- if (me) { /*no verts? still copy customdata layout*/
+ if (me && is_new) { /*no verts? still copy customdata layout*/
CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_ASSIGN, 0);
CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_ASSIGN, 0);
CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_ASSIGN, 0);
@@ -259,19 +260,27 @@ void BM_mesh_bm_from_me(
return; /* sanity check */
}
- vtable = MEM_mallocN(sizeof(void **) * me->totvert, "mesh to bmesh vtable");
+ if (is_new) {
+ CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
+ CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
- CustomData_copy(&me->vdata, &bm->vdata, CD_MASK_BMESH, CD_CALLOC, 0);
- CustomData_copy(&me->edata, &bm->edata, CD_MASK_BMESH, CD_CALLOC, 0);
- CustomData_copy(&me->ldata, &bm->ldata, CD_MASK_BMESH, CD_CALLOC, 0);
- CustomData_copy(&me->pdata, &bm->pdata, CD_MASK_BMESH, CD_CALLOC, 0);
+ /* make sure uv layer names are consisten */
+ totuv = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ for (i = 0; i < totuv; i++) {
+ int li = CustomData_get_layer_index_n(&bm->pdata, CD_MTEXPOLY, i);
+ CustomData_set_layer_name(&bm->ldata, CD_MLOOPUV, i, bm->pdata.layers[li].name);
+ }
+ }
- /* make sure uv layer names are consisten */
- totuv = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
- for (i = 0; i < totuv; i++) {
- int li = CustomData_get_layer_index_n(&bm->pdata, CD_MTEXPOLY, i);
- CustomData_set_layer_name(&bm->ldata, CD_MLOOPUV, i, bm->pdata.layers[li].name);
+ /* -------------------------------------------------------------------- */
+ /* Shape Key */
+ int tot_shape_keys = me->key ? BLI_listbase_count(&me->key->block) : 0;
+ if (is_new == false) {
+ tot_shape_keys = min_ii(tot_shape_keys, CustomData_number_of_layers(&bm->vdata, CD_SHAPEKEY));
}
+ const float (**shape_key_table)[3] = tot_shape_keys ? BLI_array_alloca(shape_key_table, tot_shape_keys) : NULL;
if ((params->active_shapekey != 0) && (me->key != NULL)) {
actkey = BLI_findlink(&me->key->block, params->active_shapekey - 1);
@@ -280,63 +289,68 @@ void BM_mesh_bm_from_me(
actkey = NULL;
}
- const int tot_shape_keys = me->key ? BLI_listbase_count(&me->key->block) : 0;
- const float (**shape_key_table)[3] = tot_shape_keys ? BLI_array_alloca(shape_key_table, tot_shape_keys) : NULL;
-
- if (tot_shape_keys || params->add_key_index) {
- CustomData_add_layer(&bm->vdata, CD_SHAPE_KEYINDEX, CD_ASSIGN, NULL, 0);
+ if (is_new) {
+ if (tot_shape_keys || params->add_key_index) {
+ CustomData_add_layer(&bm->vdata, CD_SHAPE_KEYINDEX, CD_ASSIGN, NULL, 0);
+ }
}
if (tot_shape_keys) {
- /* check if we need to generate unique ids for the shapekeys.
- * this also exists in the file reading code, but is here for
- * a sanity check */
- if (!me->key->uidgen) {
- fprintf(stderr,
- "%s had to generate shape key uid's in a situation we shouldn't need to! "
- "(bmesh internal error)\n",
- __func__);
-
- me->key->uidgen = 1;
- for (block = me->key->block.first; block; block = block->next) {
- block->uid = me->key->uidgen++;
+ if (is_new) {
+ /* check if we need to generate unique ids for the shapekeys.
+ * this also exists in the file reading code, but is here for
+ * a sanity check */
+ if (!me->key->uidgen) {
+ fprintf(stderr,
+ "%s had to generate shape key uid's in a situation we shouldn't need to! "
+ "(bmesh internal error)\n",
+ __func__);
+
+ me->key->uidgen = 1;
+ for (block = me->key->block.first; block; block = block->next) {
+ block->uid = me->key->uidgen++;
+ }
}
}
if (actkey && actkey->totelem == me->totvert) {
- keyco = actkey->data;
- bm->shapenr = params->active_shapekey;
+ keyco = params->use_shapekey ? actkey->data : NULL;
+ if (is_new) {
+ bm->shapenr = params->active_shapekey;
+ }
}
- for (i = 0, block = me->key->block.first; block; block = block->next, i++) {
- CustomData_add_layer_named(&bm->vdata, CD_SHAPEKEY,
- CD_ASSIGN, NULL, 0, block->name);
-
- j = CustomData_get_layer_index_n(&bm->vdata, CD_SHAPEKEY, i);
- bm->vdata.layers[j].uid = block->uid;
-
+ for (i = 0, block = me->key->block.first; i < tot_shape_keys; block = block->next, i++) {
+ if (is_new) {
+ CustomData_add_layer_named(&bm->vdata, CD_SHAPEKEY,
+ CD_ASSIGN, NULL, 0, block->name);
+ int j = CustomData_get_layer_index_n(&bm->vdata, CD_SHAPEKEY, i);
+ bm->vdata.layers[j].uid = block->uid;
+ }
shape_key_table[i] = (const float (*)[3])block->data;
}
}
- CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
- CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
- CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
- CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
+ if (is_new) {
+ CustomData_bmesh_init_pool(&bm->vdata, me->totvert, BM_VERT);
+ CustomData_bmesh_init_pool(&bm->edata, me->totedge, BM_EDGE);
+ CustomData_bmesh_init_pool(&bm->ldata, me->totloop, BM_LOOP);
+ CustomData_bmesh_init_pool(&bm->pdata, me->totpoly, BM_FACE);
- BM_mesh_cd_flag_apply(bm, me->cd_flag);
+ BM_mesh_cd_flag_apply(bm, me->cd_flag);
+ }
const int cd_vert_bweight_offset = CustomData_get_offset(&bm->vdata, CD_BWEIGHT);
const int cd_edge_bweight_offset = CustomData_get_offset(&bm->edata, CD_BWEIGHT);
const int cd_edge_crease_offset = CustomData_get_offset(&bm->edata, CD_CREASE);
const int cd_shape_key_offset = me->key ? CustomData_get_offset(&bm->vdata, CD_SHAPEKEY) : -1;
- const int cd_shape_keyindex_offset = (tot_shape_keys || params->add_key_index) ?
+ const int cd_shape_keyindex_offset = is_new && (tot_shape_keys || params->add_key_index) ?
CustomData_get_offset(&bm->vdata, CD_SHAPE_KEYINDEX) : -1;
+ vtable = MEM_mallocN(sizeof(BMVert **) * me->totvert, __func__);
+
for (i = 0, mvert = me->mvert; i < me->totvert; i++, mvert++) {
- v = vtable[i] = BM_vert_create(
- bm, keyco && params->use_shapekey ? keyco[i] : mvert->co, NULL,
- BM_CREATE_SKIP_CD);
+ v = vtable[i] = BM_vert_create(bm, keyco ? keyco[i] : mvert->co, NULL, BM_CREATE_SKIP_CD);
BM_elem_index_set(v, i); /* set_ok */
/* transfer flag */
@@ -360,20 +374,16 @@ void BM_mesh_bm_from_me(
/* set shapekey data */
if (tot_shape_keys) {
float (*co_dst)[3] = BM_ELEM_CD_GET_VOID_P(v, cd_shape_key_offset);
- for (j = 0; j < tot_shape_keys; j++, co_dst++) {
+ for (int j = 0; j < tot_shape_keys; j++, co_dst++) {
copy_v3_v3(*co_dst, shape_key_table[j][i]);
}
}
}
-
- bm->elem_index_dirty &= ~BM_VERT; /* added in order, clear dirty flag */
-
- if (!me->totedge) {
- MEM_freeN(vtable);
- return;
+ if (is_new) {
+ bm->elem_index_dirty &= ~BM_VERT; /* added in order, clear dirty flag */
}
- etable = MEM_mallocN(sizeof(void **) * me->totedge, "mesh to bmesh etable");
+ etable = MEM_mallocN(sizeof(BMEdge **) * me->totedge, __func__);
medge = me->medge;
for (i = 0; i < me->totedge; i++, medge++) {
@@ -395,8 +405,14 @@ void BM_mesh_bm_from_me(
if (cd_edge_crease_offset != -1) BM_ELEM_CD_SET_FLOAT(e, cd_edge_crease_offset, (float)medge->crease / 255.0f);
}
+ if (is_new) {
+ bm->elem_index_dirty &= ~BM_EDGE; /* added in order, clear dirty flag */
+ }
- bm->elem_index_dirty &= ~BM_EDGE; /* added in order, clear dirty flag */
+ /* only needed for selection. */
+ if (me->mselect && me->totselect != 0) {
+ ftable = MEM_mallocN(sizeof(BMFace **) * me->totpoly, __func__);
+ }
mloop = me->mloop;
mp = me->mpoly;
@@ -406,6 +422,9 @@ void BM_mesh_bm_from_me(
f = bm_face_create_from_mpoly(mp, mloop + mp->loopstart,
bm, vtable, etable);
+ if (ftable != NULL) {
+ ftable[i] = f;
+ }
if (UNLIKELY(f == NULL)) {
printf("%s: Warning! Bad face in mesh"
@@ -428,7 +447,7 @@ void BM_mesh_bm_from_me(
f->mat_nr = mp->mat_nr;
if (i == me->act_face) bm->act_face = f;
- j = mp->loopstart;
+ int j = mp->loopstart;
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
/* don't use 'j' since we may have skipped some faces, hence some loops. */
@@ -445,54 +464,49 @@ void BM_mesh_bm_from_me(
BM_face_normal_update(f);
}
}
+ if (is_new) {
+ bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP); /* added in order, clear dirty flag */
+ }
- bm->elem_index_dirty &= ~(BM_FACE | BM_LOOP); /* added in order, clear dirty flag */
+ /* -------------------------------------------------------------------- */
+ /* MSelect clears the array elements (avoid adding multiple times).
+ *
+ * Take care to keep this last and not use (v/e/ftable) after this.
+ */
if (me->mselect && me->totselect != 0) {
-
- BMVert **vert_array = MEM_mallocN(sizeof(BMVert *) * bm->totvert, "VSelConv");
- BMEdge **edge_array = MEM_mallocN(sizeof(BMEdge *) * bm->totedge, "ESelConv");
- BMFace **face_array = MEM_mallocN(sizeof(BMFace *) * bm->totface, "FSelConv");
MSelect *msel;
-
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
- { BM_iter_as_array(bm, BM_VERTS_OF_MESH, NULL, (void **)vert_array, bm->totvert); }
-#pragma omp section
- { BM_iter_as_array(bm, BM_EDGES_OF_MESH, NULL, (void **)edge_array, bm->totedge); }
-#pragma omp section
- { BM_iter_as_array(bm, BM_FACES_OF_MESH, NULL, (void **)face_array, bm->totface); }
- }
-
for (i = 0, msel = me->mselect; i < me->totselect; i++, msel++) {
+ BMElem **ele_p;
switch (msel->type) {
case ME_VSEL:
- BM_select_history_store(bm, (BMElem *)vert_array[msel->index]);
+ ele_p = (BMElem **)&vtable[msel->index];
break;
case ME_ESEL:
- BM_select_history_store(bm, (BMElem *)edge_array[msel->index]);
+ ele_p = (BMElem **)&etable[msel->index];
break;
case ME_FSEL:
- BM_select_history_store(bm, (BMElem *)face_array[msel->index]);
+ ele_p = (BMElem **)&ftable[msel->index];
break;
+ default:
+ continue;
}
- }
- MEM_freeN(vert_array);
- MEM_freeN(edge_array);
- MEM_freeN(face_array);
+ if (*ele_p != NULL) {
+ BM_select_history_store_notest(bm, *ele_p);
+ *ele_p = NULL;
+ }
+ }
}
else {
- me->totselect = 0;
- if (me->mselect) {
- MEM_freeN(me->mselect);
- me->mselect = NULL;
- }
+ BM_select_history_clear(bm);
}
MEM_freeN(vtable);
MEM_freeN(etable);
+ if (ftable) {
+ MEM_freeN(ftable);
+ }
}
@@ -737,7 +751,7 @@ void BM_mesh_bm_to_me(
}
/* patch hook indices and vertex parents */
- if (ototvert > 0) {
+ if (params->calc_object_remap && (ototvert > 0)) {
Object *ob;
ModifierData *md;
BMVert **vertMap = NULL;
@@ -794,11 +808,7 @@ void BM_mesh_bm_to_me(
if (vertMap) MEM_freeN(vertMap);
}
- if (params->calc_tessface) {
- BKE_mesh_tessface_calc(me);
- }
-
- BKE_mesh_update_customdata_pointers(me, params->calc_tessface);
+ BKE_mesh_update_customdata_pointers(me, false);
{
BMEditSelection *selected;
diff --git a/source/blender/bmesh/intern/bmesh_mesh_conv.h b/source/blender/bmesh/intern/bmesh_mesh_conv.h
index 7cbfe2d9210..6e9d62349ea 100644
--- a/source/blender/bmesh/intern/bmesh_mesh_conv.h
+++ b/source/blender/bmesh/intern/bmesh_mesh_conv.h
@@ -41,11 +41,11 @@ char BM_mesh_cd_flag_from_bmesh(BMesh *bm);
struct BMeshFromMeshParams {
- unsigned int calc_face_normal : 1;
+ uint calc_face_normal : 1;
/* add a vertex CD_SHAPE_KEYINDEX layer */
- unsigned int add_key_index : 1;
+ uint add_key_index : 1;
/* set vertex coordinates from the shapekey */
- unsigned int use_shapekey : 1;
+ uint use_shapekey : 1;
/* define the active shape key (index + 1) */
int active_shapekey;
};
@@ -55,7 +55,8 @@ void BM_mesh_bm_from_me(
ATTR_NONNULL(1, 3);
struct BMeshToMeshParams {
- unsigned int calc_tessface : 1;
+ /** Update object hook indices & vertex parents. */
+ uint calc_object_remap : 1;
int64_t cd_mask_extra;
};
void BM_mesh_bm_to_me(
diff --git a/source/blender/bmesh/intern/bmesh_mesh_validate.c b/source/blender/bmesh/intern/bmesh_mesh_validate.c
index 7c9ebc800a3..3a6a3543bc8 100644
--- a/source/blender/bmesh/intern/bmesh_mesh_validate.c
+++ b/source/blender/bmesh/intern/bmesh_mesh_validate.c
@@ -41,7 +41,7 @@
/* macro which inserts the function name */
-#if defined __GNUC__ || defined __sun
+#if defined __GNUC__
# define ERRMSG(format, args...) { fprintf(stderr, "%s: " format ", " AT "\n", __func__, ##args); errtot++; } (void)0
#else
# define ERRMSG(format, ...) { fprintf(stderr, "%s: " format ", " AT "\n", __func__, __VA_ARGS__); errtot++; } (void)0
diff --git a/source/blender/bmesh/intern/bmesh_mods.c b/source/blender/bmesh/intern/bmesh_mods.c
index 500da6b8788..4290f94bba1 100644
--- a/source/blender/bmesh/intern/bmesh_mods.c
+++ b/source/blender/bmesh/intern/bmesh_mods.c
@@ -65,7 +65,7 @@
bool BM_vert_dissolve(BMesh *bm, BMVert *v)
{
/* logic for 3 or more is identical */
- const int len = BM_vert_edge_count_ex(v, 3);
+ const int len = BM_vert_edge_count_at_most(v, 3);
if (len == 1) {
BM_vert_kill(bm, v); /* will kill edges too */
@@ -234,7 +234,7 @@ BMFace *BM_faces_join_pair(BMesh *bm, BMLoop *l_a, BMLoop *l_b, const bool do_de
if (l_a->v == l_b->v) {
const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
- bmesh_loop_reverse(bm, l_b->f, cd_loop_mdisp_offset, true);
+ bmesh_kernel_loop_reverse(bm, l_b->f, cd_loop_mdisp_offset, true);
}
BMFace *faces[2] = {l_a->f, l_b->f};
@@ -288,9 +288,9 @@ BMFace *BM_face_split(
}
#ifdef USE_BMESH_HOLES
- f_new = bmesh_sfme(bm, f, l_a, l_b, r_l, NULL, example, no_double);
+ f_new = bmesh_kernel_split_face_make_edge(bm, f, l_a, l_b, r_l, NULL, example, no_double);
#else
- f_new = bmesh_sfme(bm, f, l_a, l_b, r_l, example, no_double);
+ f_new = bmesh_kernel_split_face_make_edge(bm, f, l_a, l_b, r_l, example, no_double);
#endif
if (f_new) {
@@ -370,19 +370,19 @@ BMFace *BM_face_split_n(
f_tmp = BM_face_copy(bm, bm, f, true, true);
#ifdef USE_BMESH_HOLES
- f_new = bmesh_sfme(bm, f, l_a, l_b, &l_new, NULL, example, false);
+ f_new = bmesh_kernel_split_face_make_edge(bm, f, l_a, l_b, &l_new, NULL, example, false);
#else
- f_new = bmesh_sfme(bm, f, l_a, l_b, &l_new, example, false);
+ f_new = bmesh_kernel_split_face_make_edge(bm, f, l_a, l_b, &l_new, example, false);
#endif
- /* bmesh_sfme returns in 'l_new' a Loop for f_new going from 'v_a' to 'v_b'.
+ /* bmesh_kernel_split_face_make_edge returns in 'l_new' a Loop for f_new going from 'v_a' to 'v_b'.
* The radial_next is for 'f' and goes from 'v_b' to 'v_a' */
if (f_new) {
e = l_new->e;
for (i = 0; i < n; i++) {
- v_new = bmesh_semv(bm, v_b, e, &e_new);
+ v_new = bmesh_kernel_split_edge_make_vert(bm, v_b, e, &e_new);
BLI_assert(v_new != NULL);
- /* bmesh_semv returns in 'e_new' the edge going from 'v_new' to 'v_b' */
+ /* bmesh_kernel_split_edge_make_vert returns in 'e_new' the edge going from 'v_new' to 'v_b' */
copy_v3_v3(v_new->co, cos[i]);
/* interpolate the loop data for the loops with (v == v_new), using orig face */
@@ -482,8 +482,8 @@ BMEdge *BM_vert_collapse_faces(
BLI_array_append(faces, f);
}
- if (BLI_array_count(faces) >= 2) {
- BMFace *f2 = BM_faces_join(bm, faces, BLI_array_count(faces), true);
+ if (BLI_array_len(faces) >= 2) {
+ BMFace *f2 = BM_faces_join(bm, faces, BLI_array_len(faces), true);
if (f2) {
BMLoop *l_a, *l_b;
@@ -499,7 +499,7 @@ BMEdge *BM_vert_collapse_faces(
}
}
- BLI_assert(BLI_array_count(faces) < 8);
+ BLI_assert(BLI_array_len(faces) < 8);
BLI_array_free(faces);
}
@@ -507,7 +507,7 @@ BMEdge *BM_vert_collapse_faces(
/* single face or no faces */
/* same as BM_vert_collapse_edge() however we already
* have vars to perform this operation so don't call. */
- e_new = bmesh_jekv(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
+ e_new = bmesh_kernel_join_edge_kill_vert(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
/* e_new = BM_edge_exists(tv, tv2); */ /* same as return above */
}
@@ -542,7 +542,7 @@ BMEdge *BM_vert_collapse_edge(
BMVert *tv2 = BM_edge_other_vert(e2, v_kill);
if (tv2) {
/* only action, other calls here only get the edge to return */
- e_new = bmesh_jekv(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
+ e_new = bmesh_kernel_join_edge_kill_vert(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
}
}
}
@@ -564,7 +564,7 @@ BMVert *BM_edge_collapse(
BMesh *bm, BMEdge *e_kill, BMVert *v_kill,
const bool do_del, const bool kill_degenerate_faces)
{
- return bmesh_jvke(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
+ return bmesh_kernel_join_vert_kill_edge(bm, e_kill, v_kill, do_del, true, kill_degenerate_faces);
}
/**
@@ -608,7 +608,7 @@ BMVert *BM_edge_split(BMesh *bm, BMEdge *e, BMVert *v, BMEdge **r_e, float fac)
} while (l != e->l);
/* flag existing faces so we can differentiate oldfaces from new faces */
- for (i = 0; i < BLI_array_count(oldfaces); i++) {
+ for (i = 0; i < BLI_array_len(oldfaces); i++) {
BM_ELEM_API_FLAG_ENABLE(oldfaces[i], _FLAG_OVERLAP);
oldfaces[i] = BM_face_copy(bm, bm, oldfaces[i], true, true);
BM_ELEM_API_FLAG_DISABLE(oldfaces[i], _FLAG_OVERLAP);
@@ -616,7 +616,7 @@ BMVert *BM_edge_split(BMesh *bm, BMEdge *e, BMVert *v, BMEdge **r_e, float fac)
}
v_other = BM_edge_other_vert(e, v);
- v_new = bmesh_semv(bm, v, e, &e_new);
+ v_new = bmesh_kernel_split_edge_make_vert(bm, v, e, &e_new);
if (r_e != NULL) {
*r_e = e_new;
}
@@ -639,7 +639,7 @@ BMVert *BM_edge_split(BMesh *bm, BMEdge *e, BMVert *v, BMEdge **r_e, float fac)
int i, j;
/* interpolate new/changed loop data from copied old faces */
- for (i = 0; i < BLI_array_count(oldfaces); i++) {
+ for (i = 0; i < BLI_array_len(oldfaces); i++) {
float f_center_old[3];
BM_face_calc_center_mean(oldfaces[i], f_center_old);
@@ -671,7 +671,7 @@ BMVert *BM_edge_split(BMesh *bm, BMEdge *e, BMVert *v, BMEdge **r_e, float fac)
}
/* destroy the old faces */
- for (i = 0; i < BLI_array_count(oldfaces); i++) {
+ for (i = 0; i < BLI_array_len(oldfaces); i++) {
BM_face_verts_kill(bm, oldfaces[i]);
}
@@ -1090,23 +1090,18 @@ BMEdge *BM_edge_rotate(BMesh *bm, BMEdge *e, const bool ccw, const short check_f
/**
* \brief Rip a single face from a vertex fan
*/
-BMVert *BM_face_vert_separate(BMesh *bm, BMFace *sf, BMVert *sv)
+BMVert *BM_face_loop_separate(BMesh *bm, BMLoop *l_sep)
{
- return bmesh_urmv(bm, sf, sv);
+ return bmesh_kernel_unglue_region_make_vert(bm, l_sep);
}
-/**
- * \brief Rip a single face from a vertex fan
- *
- * \note same as #BM_face_vert_separate but faster (avoids a loop lookup)
- */
-BMVert *BM_face_loop_separate(BMesh *bm, BMLoop *sl)
+BMVert *BM_face_loop_separate_multi_isolated(BMesh *bm, BMLoop *l_sep)
{
- return bmesh_urmv_loop(bm, sl);
+ return bmesh_kernel_unglue_region_make_vert_multi_isolated(bm, l_sep);
}
-BMVert *BM_face_loop_separate_multi(
- BMesh *bm, BMLoop **larr, int larr_len)
+BMVert *BM_face_loop_separate_multi(BMesh *bm, BMLoop **larr, int larr_len)
{
- return bmesh_urmv_loop_multi(bm, larr, larr_len);
+ return bmesh_kernel_unglue_region_make_vert_multi(bm, larr, larr_len);
}
+
diff --git a/source/blender/bmesh/intern/bmesh_mods.h b/source/blender/bmesh/intern/bmesh_mods.h
index 5e95e9a2cc7..330a714418d 100644
--- a/source/blender/bmesh/intern/bmesh_mods.h
+++ b/source/blender/bmesh/intern/bmesh_mods.h
@@ -86,9 +86,8 @@ enum {
};
-BMVert *BM_face_vert_separate(BMesh *bm, BMFace *sf, BMVert *sv);
-BMVert *BM_face_loop_separate(BMesh *bm, BMLoop *sl);
-BMVert *BM_face_loop_separate_multi(
- BMesh *bm, BMLoop **larr, int larr_len);
+BMVert *BM_face_loop_separate(BMesh *bm, BMLoop *l_sep);
+BMVert *BM_face_loop_separate_multi_isolated(BMesh *bm, BMLoop *l_sep);
+BMVert *BM_face_loop_separate_multi(BMesh *bm, BMLoop **larr, int larr_len);
#endif /* __BMESH_MODS_H__ */
diff --git a/source/blender/bmesh/intern/bmesh_opdefines.c b/source/blender/bmesh/intern/bmesh_opdefines.c
index 0d0fdda2c4c..b5e6fe168e5 100644
--- a/source/blender/bmesh/intern/bmesh_opdefines.c
+++ b/source/blender/bmesh/intern/bmesh_opdefines.c
@@ -112,7 +112,7 @@ static BMOpDefine bmo_smooth_vert_def = {
{"use_axis_x", BMO_OP_SLOT_BOOL}, /* smooth vertices along X axis */
{"use_axis_y", BMO_OP_SLOT_BOOL}, /* smooth vertices along Y axis */
{"use_axis_z", BMO_OP_SLOT_BOOL}, /* smooth vertices along Z axis */
- {{'\0'}},
+ {{'\0'}},
},
{{{'\0'}}}, /* no output */
bmo_smooth_vert_exec,
@@ -120,7 +120,7 @@ static BMOpDefine bmo_smooth_vert_def = {
};
/*
- * Vertext Smooth Laplacian.
+ * Vertex Smooth Laplacian.
*
* Smooths vertices by using Laplacian smoothing propose by.
* Desbrun, et al. Implicit Fairing of Irregular Meshes using Diffusion and Curvature Flow.
@@ -135,7 +135,7 @@ static BMOpDefine bmo_smooth_laplacian_vert_def = {
{"use_y", BMO_OP_SLOT_BOOL}, /* Smooth object along Y axis */
{"use_z", BMO_OP_SLOT_BOOL}, /* Smooth object along Z axis */
{"preserve_volume", BMO_OP_SLOT_BOOL}, /* Apply volume preservation after smooth */
- {{'\0'}},
+ {{'\0'}},
},
{{{'\0'}}}, /* no output */
bmo_smooth_laplacian_vert_exec,
@@ -839,11 +839,10 @@ static BMOpDefine bmo_bmesh_to_mesh_def = {
"bmesh_to_mesh",
/* slots_in */
{
- /* pointer to a mesh structure to fill in */
+ /* pointer to a mesh structure to fill in */
{"mesh", BMO_OP_SLOT_PTR, {(int)BMO_OP_SLOT_SUBTYPE_PTR_MESH}},
/* pointer to an object structure */
{"object", BMO_OP_SLOT_PTR, {(int)BMO_OP_SLOT_SUBTYPE_PTR_OBJECT}},
- {"skip_tessface", BMO_OP_SLOT_BOOL}, /* don't calculate mfaces */
{{'\0'}},
},
{{{'\0'}}}, /* no output */
@@ -861,7 +860,7 @@ static BMOpDefine bmo_mesh_to_bmesh_def = {
"mesh_to_bmesh",
/* slots_in */
{
- /* pointer to a Mesh structure */
+ /* pointer to a Mesh structure */
{"mesh", BMO_OP_SLOT_PTR, {(int)BMO_OP_SLOT_SUBTYPE_PTR_MESH}},
/* pointer to an Object structure */
{"object", BMO_OP_SLOT_PTR, {(int)BMO_OP_SLOT_SUBTYPE_PTR_OBJECT}},
@@ -1037,7 +1036,7 @@ static BMOpDefine bmo_extrude_face_region_def = {
/* slots_in */
{{"geom", BMO_OP_SLOT_ELEMENT_BUF, {BM_VERT | BM_EDGE | BM_FACE}}, /* edges and faces */
{"edges_exclude", BMO_OP_SLOT_MAPPING, {(int)BMO_OP_SLOT_SUBTYPE_MAP_EMPTY}},
- {"use_keep_orig", BMO_OP_SLOT_BOOL}, /* keep original geometry */
+ {"use_keep_orig", BMO_OP_SLOT_BOOL}, /* keep original geometry (requires ``geom`` to include edges). */
{"use_select_history", BMO_OP_SLOT_BOOL}, /* pass to duplicate */
{{'\0'}},
},
@@ -1284,7 +1283,7 @@ static BMOpDefine bmo_bisect_plane_def = {
{"clear_inner", BMO_OP_SLOT_BOOL}, /* when enabled. remove all geometry on the negative side of the plane */
{{'\0'}},
},
- {{"geom_cut.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_VERT | BM_EDGE}}, /* output new geometry from the cut */
+ {{"geom_cut.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_VERT | BM_EDGE}}, /* output geometry aligned with the plane (new and existing) */
{"geom.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_VERT | BM_EDGE | BM_FACE}}, /* input and output geometry (result of cut) */
{{'\0'}}},
bmo_bisect_plane_exec,
@@ -1338,7 +1337,7 @@ static BMOpDefine bmo_duplicate_def = {
{"face_map.out", BMO_OP_SLOT_MAPPING, {(int)BMO_OP_SLOT_SUBTYPE_MAP_ELEM}},
{"boundary_map.out", BMO_OP_SLOT_MAPPING, {(int)BMO_OP_SLOT_SUBTYPE_MAP_ELEM}},
{"isovert_map.out", BMO_OP_SLOT_MAPPING, {(int)BMO_OP_SLOT_SUBTYPE_MAP_ELEM}},
- {{'\0'}},
+ {{'\0'}},
},
bmo_duplicate_exec,
(BMO_OPTYPE_FLAG_NORMALS_CALC |
@@ -1684,7 +1683,7 @@ static BMOpDefine bmo_create_circle_def = {
{{"cap_ends", BMO_OP_SLOT_BOOL}, /* whether or not to fill in the ends with faces */
{"cap_tris", BMO_OP_SLOT_BOOL}, /* fill ends with triangles instead of ngons */
{"segments", BMO_OP_SLOT_INT},
- {"diameter", BMO_OP_SLOT_FLT}, /* diameter of one end */
+ {"radius", BMO_OP_SLOT_FLT}, /* Radius of the circle. */
{"matrix", BMO_OP_SLOT_MAT}, /* matrix to multiply the new geometry with */
{"calc_uvs", BMO_OP_SLOT_BOOL}, /* calculate default UVs */
{{'\0'}},
@@ -1741,6 +1740,8 @@ static BMOpDefine bmo_bevel_def = {
},
/* slots_out */
{{"faces.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_FACE}}, /* output faces */
+ {"edges.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_EDGE}}, /* output edges */
+ {"verts.out", BMO_OP_SLOT_ELEMENT_BUF, {BM_VERT}}, /* output verts */
{{'\0'}},
},
@@ -1912,7 +1913,6 @@ static BMOpDefine bmo_wireframe_def = {
{"use_even_offset", BMO_OP_SLOT_BOOL},
{"use_crease", BMO_OP_SLOT_BOOL},
{"crease_weight", BMO_OP_SLOT_FLT},
- {"thickness", BMO_OP_SLOT_FLT},
{"use_relative_offset", BMO_OP_SLOT_BOOL},
{"material_offset", BMO_OP_SLOT_INT},
{{'\0'}},
diff --git a/source/blender/bmesh/intern/bmesh_operators.c b/source/blender/bmesh/intern/bmesh_operators.c
index 706a7f74ed2..f814767a200 100644
--- a/source/blender/bmesh/intern/bmesh_operators.c
+++ b/source/blender/bmesh/intern/bmesh_operators.c
@@ -128,7 +128,7 @@ void BMO_pop(BMesh *bm)
static void bmo_op_slots_init(const BMOSlotType *slot_types, BMOpSlot *slot_args)
{
BMOpSlot *slot;
- unsigned int i;
+ uint i;
for (i = 0; slot_types[i].type; i++) {
slot = &slot_args[i];
slot->slot_name = slot_types[i].name;
@@ -149,7 +149,7 @@ static void bmo_op_slots_init(const BMOSlotType *slot_types, BMOpSlot *slot_args
static void bmo_op_slots_free(const BMOSlotType *slot_types, BMOpSlot *slot_args)
{
BMOpSlot *slot;
- unsigned int i;
+ uint i;
for (i = 0; slot_types[i].type; i++) {
slot = &slot_args[i];
switch (slot->slot_type) {
@@ -311,9 +311,9 @@ void _bmo_slot_copy(
}
else {
/* check types */
- const unsigned int tot = slot_src->len;
- unsigned int i;
- unsigned int out = 0;
+ const uint tot = slot_src->len;
+ uint i;
+ uint out = 0;
BMElem **ele_src = (BMElem **)slot_src->data.buf;
for (i = 0; i < tot; i++, ele_src++) {
if ((*ele_src)->head.htype & dst_elem_flag) {
@@ -333,8 +333,8 @@ void _bmo_slot_copy(
}
else {
/* only copy compatible elements */
- const unsigned int tot = slot_src->len;
- unsigned int i;
+ const uint tot = slot_src->len;
+ uint i;
BMElem **ele_src = (BMElem **)slot_src->data.buf;
BMElem **ele_dst = (BMElem **)slot_dst->data.buf;
for (i = 0; i < tot; i++, ele_src++) {
@@ -550,37 +550,30 @@ static int bmo_mesh_flag_count(
{
int count_vert = 0, count_edge = 0, count_face = 0;
-#pragma omp parallel sections if ((bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT) && \
- (ELEM(htype, BM_VERT, BM_EDGE, BM_FACE) == 0))
- {
-#pragma omp section
- if (htype & BM_VERT) {
- BMIter iter;
- BMVert *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
- if (BMO_vert_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
- count_vert++;
- }
+ if (htype & BM_VERT) {
+ BMIter iter;
+ BMVert *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
+ if (BMO_vert_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
+ count_vert++;
}
}
-#pragma omp section
- if (htype & BM_EDGE) {
- BMIter iter;
- BMEdge *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
- if (BMO_edge_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
- count_edge++;
- }
+ }
+ if (htype & BM_EDGE) {
+ BMIter iter;
+ BMEdge *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
+ if (BMO_edge_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
+ count_edge++;
}
}
-#pragma omp section
- if (htype & BM_FACE) {
- BMIter iter;
- BMFace *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
- if (BMO_face_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
- count_face++;
- }
+ }
+ if (htype & BM_FACE) {
+ BMIter iter;
+ BMFace *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
+ if (BMO_face_flag_test_bool(bm, ele, oflag) == test_for_enabled) {
+ count_face++;
}
}
}
@@ -601,33 +594,25 @@ int BMO_mesh_disabled_flag_count(BMesh *bm, const char htype, const short oflag)
void BMO_mesh_flag_disable_all(BMesh *bm, BMOperator *UNUSED(op), const char htype, const short oflag)
{
-
-#pragma omp parallel sections if ((bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT) && \
- (ELEM(htype, BM_VERT, BM_EDGE, BM_FACE) == 0))
- {
-#pragma omp section
- if (htype & BM_VERT) {
- BMIter iter;
- BMVert *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
- BMO_vert_flag_disable(bm, ele, oflag);
- }
+ if (htype & BM_VERT) {
+ BMIter iter;
+ BMVert *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_VERTS_OF_MESH) {
+ BMO_vert_flag_disable(bm, ele, oflag);
}
-#pragma omp section
- if (htype & BM_EDGE) {
- BMIter iter;
- BMEdge *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
- BMO_edge_flag_disable(bm, ele, oflag);
- }
+ }
+ if (htype & BM_EDGE) {
+ BMIter iter;
+ BMEdge *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_EDGES_OF_MESH) {
+ BMO_edge_flag_disable(bm, ele, oflag);
}
-#pragma omp section
- if (htype & BM_FACE) {
- BMIter iter;
- BMFace *ele;
- BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
- BMO_face_flag_disable(bm, ele, oflag);
- }
+ }
+ if (htype & BM_FACE) {
+ BMIter iter;
+ BMFace *ele;
+ BM_ITER_MESH (ele, &iter, bm, BM_FACES_OF_MESH) {
+ BMO_face_flag_disable(bm, ele, oflag);
}
}
}
@@ -688,7 +673,7 @@ int BMO_slot_map_count(BMOpSlot slot_args[BMO_OP_MAX_SLOTS], const char *slot_na
{
BMOpSlot *slot = BMO_slot_get(slot_args, slot_name);
BLI_assert(slot->slot_type == BMO_OP_SLOT_MAPPING);
- return BLI_ghash_size(slot->data.ghash);
+ return BLI_ghash_len(slot->data.ghash);
}
/* inserts a key/value mapping into a mapping slot. note that it copies the
@@ -1236,57 +1221,38 @@ static void bmo_flag_layer_alloc(BMesh *bm)
bm->etoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer) * bm->totflags, bm->totedge, 512, BLI_MEMPOOL_NOP);
bm->ftoolflagpool = BLI_mempool_create(sizeof(BMFlagLayer) * bm->totflags, bm->totface, 512, BLI_MEMPOOL_NOP);
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
- {
- BMIter iter;
- BMVert_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->vtoolflagpool;
-
- /* now go through and memcpy all the flags. Loops don't get a flag layer at this time.. */
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_calloc(newpool);
- memcpy(ele->oflags, oldflags, old_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
-#pragma omp section
- {
- BMIter iter;
- BMEdge_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->etoolflagpool;
-
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_calloc(newpool);
- memcpy(ele->oflags, oldflags, old_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
-#pragma omp section
- {
- BMIter iter;
- BMFace_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->ftoolflagpool;
-
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_calloc(newpool);
- memcpy(ele->oflags, oldflags, old_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
+ /* now go through and memcpy all the flags. Loops don't get a flag layer at this time.. */
+ BMIter iter;
+ int i;
+
+ BMVert_OFlag *v_oflag;
+ BLI_mempool *newpool = bm->vtoolflagpool;
+ BM_ITER_MESH_INDEX (v_oflag, &iter, bm, BM_VERTS_OF_MESH, i) {
+ void *oldflags = v_oflag->oflags;
+ v_oflag->oflags = BLI_mempool_calloc(newpool);
+ memcpy(v_oflag->oflags, oldflags, old_totflags_size);
+ BM_elem_index_set(&v_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)v_oflag);
+ }
+
+ BMEdge_OFlag *e_oflag;
+ newpool = bm->etoolflagpool;
+ BM_ITER_MESH_INDEX (e_oflag, &iter, bm, BM_EDGES_OF_MESH, i) {
+ void *oldflags = e_oflag->oflags;
+ e_oflag->oflags = BLI_mempool_calloc(newpool);
+ memcpy(e_oflag->oflags, oldflags, old_totflags_size);
+ BM_elem_index_set(&e_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)e_oflag);
+ }
+
+ BMFace_OFlag *f_oflag;
+ newpool = bm->ftoolflagpool;
+ BM_ITER_MESH_INDEX (f_oflag, &iter, bm, BM_FACES_OF_MESH, i) {
+ void *oldflags = f_oflag->oflags;
+ f_oflag->oflags = BLI_mempool_calloc(newpool);
+ memcpy(f_oflag->oflags, oldflags, old_totflags_size);
+ BM_elem_index_set(&f_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)f_oflag);
}
BLI_mempool_destroy(voldpool);
@@ -1315,57 +1281,38 @@ static void bmo_flag_layer_free(BMesh *bm)
bm->etoolflagpool = BLI_mempool_create(new_totflags_size, bm->totedge, 512, BLI_MEMPOOL_NOP);
bm->ftoolflagpool = BLI_mempool_create(new_totflags_size, bm->totface, 512, BLI_MEMPOOL_NOP);
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
- {
-#pragma omp section
- {
- BMIter iter;
- BMVert_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->vtoolflagpool;
-
- /* now go through and memcpy all the flag */
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_alloc(newpool);
- memcpy(ele->oflags, oldflags, new_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
-#pragma omp section
- {
- BMIter iter;
- BMEdge_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->etoolflagpool;
-
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_alloc(newpool);
- memcpy(ele->oflags, oldflags, new_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
-#pragma omp section
- {
- BMIter iter;
- BMFace_OFlag *ele;
- int i;
-
- BLI_mempool *newpool = bm->ftoolflagpool;
-
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
- void *oldflags = ele->oflags;
- ele->oflags = BLI_mempool_alloc(newpool);
- memcpy(ele->oflags, oldflags, new_totflags_size);
- BM_elem_index_set(&ele->base, i); /* set_inline */
- BM_ELEM_API_FLAG_CLEAR((BMElemF *)ele);
- }
- }
+ /* now go through and memcpy all the flag */
+ BMIter iter;
+ int i;
+
+ BMVert_OFlag *v_oflag;
+ BLI_mempool *newpool = bm->vtoolflagpool;
+ BM_ITER_MESH_INDEX (v_oflag, &iter, bm, BM_VERTS_OF_MESH, i) {
+ void *oldflags = v_oflag->oflags;
+ v_oflag->oflags = BLI_mempool_alloc(newpool);
+ memcpy(v_oflag->oflags, oldflags, new_totflags_size);
+ BM_elem_index_set(&v_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)v_oflag);
+ }
+
+ BMEdge_OFlag *e_oflag;
+ newpool = bm->etoolflagpool;
+ BM_ITER_MESH_INDEX (e_oflag, &iter, bm, BM_EDGES_OF_MESH, i) {
+ void *oldflags = e_oflag->oflags;
+ e_oflag->oflags = BLI_mempool_alloc(newpool);
+ memcpy(e_oflag->oflags, oldflags, new_totflags_size);
+ BM_elem_index_set(&e_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)e_oflag);
+ }
+
+ BMFace_OFlag *f_oflag;
+ newpool = bm->ftoolflagpool;
+ BM_ITER_MESH_INDEX (f_oflag, &iter, bm, BM_FACES_OF_MESH, i) {
+ void *oldflags = f_oflag->oflags;
+ f_oflag->oflags = BLI_mempool_alloc(newpool);
+ memcpy(f_oflag->oflags, oldflags, new_totflags_size);
+ BM_elem_index_set(&f_oflag->base, i); /* set_inline */
+ BM_ELEM_API_FLAG_CLEAR((BMElemF *)f_oflag);
}
BLI_mempool_destroy(voldpool);
@@ -1383,38 +1330,32 @@ static void bmo_flag_layer_clear(BMesh *bm)
const int totflags_offset = bm->totflags - 1;
-#pragma omp parallel sections if (bm->totvert + bm->totedge + bm->totface >= BM_OMP_LIMIT)
+ /* now go through and memcpy all the flag */
{
- /* now go through and memcpy all the flag */
-#pragma omp section
- {
- BMIter iter;
- BMVert_OFlag *ele;
- int i;
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
- ele->oflags[totflags_offset] = zero_flag;
- BM_elem_index_set(&ele->base, i); /* set_inline */
- }
+ BMIter iter;
+ BMVert_OFlag *ele;
+ int i;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_VERTS_OF_MESH, i) {
+ ele->oflags[totflags_offset] = zero_flag;
+ BM_elem_index_set(&ele->base, i); /* set_inline */
}
-#pragma omp section
- {
- BMIter iter;
- BMEdge_OFlag *ele;
- int i;
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
- ele->oflags[totflags_offset] = zero_flag;
- BM_elem_index_set(&ele->base, i); /* set_inline */
- }
+ }
+ {
+ BMIter iter;
+ BMEdge_OFlag *ele;
+ int i;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_EDGES_OF_MESH, i) {
+ ele->oflags[totflags_offset] = zero_flag;
+ BM_elem_index_set(&ele->base, i); /* set_inline */
}
-#pragma omp section
- {
- BMIter iter;
- BMFace_OFlag *ele;
- int i;
- BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
- ele->oflags[totflags_offset] = zero_flag;
- BM_elem_index_set(&ele->base, i); /* set_inline */
- }
+ }
+ {
+ BMIter iter;
+ BMFace_OFlag *ele;
+ int i;
+ BM_ITER_MESH_INDEX (ele, &iter, bm, BM_FACES_OF_MESH, i) {
+ ele->oflags[totflags_offset] = zero_flag;
+ BM_elem_index_set(&ele->base, i); /* set_inline */
}
}
@@ -1639,8 +1580,8 @@ static int bmo_name_to_slotcode_check(BMOpSlot slot_args[BMO_OP_MAX_SLOTS], cons
int BMO_opcode_from_opname(const char *opname)
{
- const unsigned int tot = bmo_opdefines_total;
- unsigned int i;
+ const uint tot = bmo_opdefines_total;
+ uint i;
for (i = 0; i < tot; i++) {
if (STREQ(bmo_opdefines[i]->opname, opname)) {
return i;
diff --git a/source/blender/bmesh/intern/bmesh_operators.h b/source/blender/bmesh/intern/bmesh_operators.h
index 0a4fb1d56a4..b670f31ad9f 100644
--- a/source/blender/bmesh/intern/bmesh_operators.h
+++ b/source/blender/bmesh/intern/bmesh_operators.h
@@ -141,12 +141,19 @@ void BM_mesh_esubdivide(
const short use_only_quads,
const int seed);
-void BM_mesh_calc_uvs_grid(BMesh *bm, const unsigned int x_segments, const unsigned int y_segments, const short oflag);
-void BM_mesh_calc_uvs_sphere(BMesh *bm, const short oflag);
-void BM_mesh_calc_uvs_circle(BMesh *bm, float mat[4][4], const float radius, const short oflag);
+void BM_mesh_calc_uvs_grid(
+ BMesh *bm, const uint x_segments, const uint y_segments,
+ const short oflag, const int cd_loop_uv_offset);
+void BM_mesh_calc_uvs_sphere(
+ BMesh *bm,
+ const short oflag, const int cd_loop_uv_offset);
+void BM_mesh_calc_uvs_circle(
+ BMesh *bm, float mat[4][4], const float radius,
+ const short oflag, const int cd_loop_uv_offset);
void BM_mesh_calc_uvs_cone(
BMesh *bm, float mat[4][4],
- const float radius_top, const float radius_bottom, const int segments, const bool cap_ends, const short oflag);
+ const float radius_top, const float radius_bottom, const int segments, const bool cap_ends,
+ const short oflag, const int cd_loop_uv_offset);
void BM_mesh_calc_uvs_cube(BMesh *bm, const short oflag);
#include "intern/bmesh_operator_api_inline.h"
diff --git a/source/blender/bmesh/intern/bmesh_polygon.c b/source/blender/bmesh/intern/bmesh_polygon.c
index 6acd790fc0c..bcb940f8b96 100644
--- a/source/blender/bmesh/intern/bmesh_polygon.c
+++ b/source/blender/bmesh/intern/bmesh_polygon.c
@@ -36,9 +36,11 @@
#include "BLI_alloca.h"
#include "BLI_math.h"
#include "BLI_memarena.h"
-#include "BLI_polyfill2d.h"
-#include "BLI_polyfill2d_beautify.h"
+#include "BLI_polyfill_2d.h"
+#include "BLI_polyfill_2d_beautify.h"
#include "BLI_linklist.h"
+#include "BLI_edgehash.h"
+#include "BLI_heap.h"
#include "bmesh.h"
#include "bmesh_tools.h"
@@ -132,7 +134,7 @@ static void bm_face_calc_poly_center_mean_vertex_cos(
*/
void BM_face_calc_tessellation(
const BMFace *f, const bool use_fixed_quad,
- BMLoop **r_loops, unsigned int (*r_index)[3])
+ BMLoop **r_loops, uint (*r_index)[3])
{
BMLoop *l_first = BM_FACE_FIRST_LOOP(f);
BMLoop *l_iter;
@@ -176,7 +178,7 @@ void BM_face_calc_tessellation(
} while ((l_iter = l_iter->next) != l_first);
/* complete the loop */
- BLI_polyfill_calc((const float (*)[2])projverts, f->len, -1, r_index);
+ BLI_polyfill_calc(projverts, f->len, -1, r_index);
}
}
@@ -196,7 +198,7 @@ void BM_face_calc_point_in_face(const BMFace *f, float r_co[3])
* but without this we can't be sure the point is inside a concave face. */
const int tottri = f->len - 2;
BMLoop **loops = BLI_array_alloca(loops, f->len);
- unsigned int (*index)[3] = BLI_array_alloca(index, tottri);
+ uint (*index)[3] = BLI_array_alloca(index, tottri);
int j;
int j_best = 0; /* use as fallback when unset */
float area_best = -1.0f;
@@ -508,6 +510,18 @@ void BM_face_calc_tangent_auto(const BMFace *f, float r_tangent[3])
}
/**
+ * expands bounds (min/max must be initialized).
+ */
+void BM_face_calc_bounds_expand(const BMFace *f, float min[3], float max[3])
+{
+ const BMLoop *l_iter, *l_first;
+ l_iter = l_first = BM_FACE_FIRST_LOOP(f);
+ do {
+ minmax_v3v3_v3(min, max, l_iter->v->co);
+ } while ((l_iter = l_iter->next) != l_first);
+}
+
+/**
* computes center of face in 3d. uses center of bounding box.
*/
void BM_face_calc_center_bounds(const BMFace *f, float r_cent[3])
@@ -575,11 +589,11 @@ void BM_face_calc_center_mean_weighted(const BMFace *f, float r_cent[3])
* Rotates a polygon so that it's
* normal is pointing towards the mesh Z axis
*/
-void poly_rotate_plane(const float normal[3], float (*verts)[3], const unsigned int nverts)
+void poly_rotate_plane(const float normal[3], float (*verts)[3], const uint nverts)
{
float mat[3][3];
float co[3];
- unsigned int i;
+ uint i;
co[2] = 0.0f;
@@ -844,7 +858,7 @@ void BM_face_normal_flip_ex(
BMesh *bm, BMFace *f,
const int cd_loop_mdisp_offset, const bool use_loop_mdisp_flip)
{
- bmesh_loop_reverse(bm, f, cd_loop_mdisp_offset, use_loop_mdisp_flip);
+ bmesh_kernel_loop_reverse(bm, f, cd_loop_mdisp_offset, use_loop_mdisp_flip);
negate_v3(f->no);
}
@@ -883,7 +897,7 @@ bool BM_face_point_inside_test(const BMFace *f, const float co[3])
mul_v2_m3v3(projverts[i], axis_mat, l_iter->v->co);
}
- return isect_point_poly_v2(co_2d, (const float (*)[2])projverts, f->len, false);
+ return isect_point_poly_v2(co_2d, projverts, f->len, false);
}
/**
@@ -923,7 +937,7 @@ void BM_face_triangulate(
MemArena *pf_arena,
/* use for MOD_TRIANGULATE_NGON_BEAUTY only! */
- struct Heap *pf_heap, struct EdgeHash *pf_ehash)
+ struct Heap *pf_heap)
{
const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
const bool use_beauty = (ngon_method == MOD_TRIANGULATE_NGON_BEAUTY);
@@ -941,7 +955,7 @@ void BM_face_triangulate(
{
BMLoop **loops = BLI_array_alloca(loops, f->len);
- unsigned int (*tris)[3] = BLI_array_alloca(tris, f->len);
+ uint (*tris)[3] = BLI_array_alloca(tris, f->len);
const int totfilltri = f->len - 2;
const int last_tri = f->len - 3;
int i;
@@ -1033,13 +1047,13 @@ void BM_face_triangulate(
mul_v2_m3v3(projverts[i], axis_mat, l_iter->v->co);
}
- BLI_polyfill_calc_arena((const float (*)[2])projverts, f->len, 1, tris,
+ BLI_polyfill_calc_arena(projverts, f->len, 1, tris,
pf_arena);
if (use_beauty) {
BLI_polyfill_beautify(
- (const float (*)[2])projverts, f->len, tris,
- pf_arena, pf_heap, pf_ehash);
+ projverts, f->len, tris,
+ pf_arena, pf_heap);
}
BLI_memarena_clear(pf_arena);
@@ -1169,7 +1183,7 @@ void BM_face_splits_check_legal(BMesh *bm, BMFace *f, BMLoop *(*loops)[2], int l
}
/* first test for completely convex face */
- if (is_poly_convex_v2((const float (*)[2])projverts, f->len)) {
+ if (is_poly_convex_v2(projverts, f->len)) {
return;
}
@@ -1412,6 +1426,17 @@ void BM_mesh_calc_tessellation(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptri
(l_ptr_a[2] = l_ptr_b[1] = l = l->next);
( l_ptr_b[2] = l->next);
#endif
+
+ if (UNLIKELY(is_quad_flip_v3_first_third_fast(
+ l_ptr_a[0]->v->co,
+ l_ptr_a[1]->v->co,
+ l_ptr_a[2]->v->co,
+ l_ptr_b[2]->v->co)))
+ {
+ /* flip out of degenerate 0-2 state. */
+ l_ptr_a[2] = l_ptr_b[2];
+ l_ptr_b[0] = l_ptr_a[1];
+ }
}
#endif /* USE_TESSFACE_SPEEDUP */
@@ -1425,7 +1450,7 @@ void BM_mesh_calc_tessellation(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptri
float axis_mat[3][3];
float (*projverts)[2];
- unsigned int (*tris)[3];
+ uint (*tris)[3];
const int totfilltri = efa->len - 2;
@@ -1447,11 +1472,11 @@ void BM_mesh_calc_tessellation(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptri
j++;
} while ((l_iter = l_iter->next) != l_first);
- BLI_polyfill_calc_arena((const float (*)[2])projverts, efa->len, 1, tris, arena);
+ BLI_polyfill_calc_arena(projverts, efa->len, 1, tris, arena);
for (j = 0; j < totfilltri; j++) {
BMLoop **l_ptr = looptris[i++];
- unsigned int *tri = tris[j];
+ uint *tri = tris[j];
l_ptr[0] = l_arr[tri[0]];
l_ptr[1] = l_arr[tri[1]];
@@ -1474,3 +1499,144 @@ void BM_mesh_calc_tessellation(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptri
#undef USE_TESSFACE_SPEEDUP
}
+
+
+/**
+ * A version of #BM_mesh_calc_tessellation that avoids degenerate triangles.
+ */
+void BM_mesh_calc_tessellation_beauty(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptris_tot)
+{
+ /* this assumes all faces can be scan-filled, which isn't always true,
+ * worst case we over alloc a little which is acceptable */
+#ifndef NDEBUG
+ const int looptris_tot = poly_to_tri_count(bm->totface, bm->totloop);
+#endif
+
+ BMIter iter;
+ BMFace *efa;
+ int i = 0;
+
+ MemArena *pf_arena = NULL;
+
+ /* use_beauty */
+ Heap *pf_heap = NULL;
+
+ BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
+ /* don't consider two-edged faces */
+ if (UNLIKELY(efa->len < 3)) {
+ /* do nothing */
+ }
+ else if (efa->len == 3) {
+ BMLoop *l;
+ BMLoop **l_ptr = looptris[i++];
+ l_ptr[0] = l = BM_FACE_FIRST_LOOP(efa);
+ l_ptr[1] = l = l->next;
+ l_ptr[2] = l->next;
+ }
+ else if (efa->len == 4) {
+ BMLoop *l_v1 = BM_FACE_FIRST_LOOP(efa);
+ BMLoop *l_v2 = l_v1->next;
+ BMLoop *l_v3 = l_v2->next;
+ BMLoop *l_v4 = l_v1->prev;
+
+ /* #BM_verts_calc_rotate_beauty performs excessive checks we don't need!
+ * It's meant for rotating edges, it also calculates a new normal.
+ *
+ * Use #BLI_polyfill_beautify_quad_rotate_calc since we have the normal.
+ */
+#if 0
+ const bool split_13 = (BM_verts_calc_rotate_beauty(
+ l_v1->v, l_v2->v, l_v3->v, l_v4->v, 0, 0) < 0.0f);
+#else
+ float axis_mat[3][3], v_quad[4][2];
+ axis_dominant_v3_to_m3(axis_mat, efa->no);
+ mul_v2_m3v3(v_quad[0], axis_mat, l_v1->v->co);
+ mul_v2_m3v3(v_quad[1], axis_mat, l_v2->v->co);
+ mul_v2_m3v3(v_quad[2], axis_mat, l_v3->v->co);
+ mul_v2_m3v3(v_quad[3], axis_mat, l_v4->v->co);
+
+ const bool split_13 = BLI_polyfill_beautify_quad_rotate_calc(
+ v_quad[0], v_quad[1], v_quad[2], v_quad[3]) < 0.0f;
+#endif
+
+ BMLoop **l_ptr_a = looptris[i++];
+ BMLoop **l_ptr_b = looptris[i++];
+ if (split_13) {
+ l_ptr_a[0] = l_v1;
+ l_ptr_a[1] = l_v2;
+ l_ptr_a[2] = l_v3;
+
+ l_ptr_b[0] = l_v1;
+ l_ptr_b[1] = l_v3;
+ l_ptr_b[2] = l_v4;
+ }
+ else {
+ l_ptr_a[0] = l_v1;
+ l_ptr_a[1] = l_v2;
+ l_ptr_a[2] = l_v4;
+
+ l_ptr_b[0] = l_v2;
+ l_ptr_b[1] = l_v3;
+ l_ptr_b[2] = l_v4;
+ }
+ }
+ else {
+ int j;
+
+ BMLoop *l_iter;
+ BMLoop *l_first;
+ BMLoop **l_arr;
+
+ float axis_mat[3][3];
+ float (*projverts)[2];
+ unsigned int (*tris)[3];
+
+ const int totfilltri = efa->len - 2;
+
+ if (UNLIKELY(pf_arena == NULL)) {
+ pf_arena = BLI_memarena_new(BLI_MEMARENA_STD_BUFSIZE, __func__);
+ pf_heap = BLI_heap_new_ex(BLI_POLYFILL_ALLOC_NGON_RESERVE);
+ }
+
+ tris = BLI_memarena_alloc(pf_arena, sizeof(*tris) * totfilltri);
+ l_arr = BLI_memarena_alloc(pf_arena, sizeof(*l_arr) * efa->len);
+ projverts = BLI_memarena_alloc(pf_arena, sizeof(*projverts) * efa->len);
+
+ axis_dominant_v3_to_m3_negate(axis_mat, efa->no);
+
+ j = 0;
+ l_iter = l_first = BM_FACE_FIRST_LOOP(efa);
+ do {
+ l_arr[j] = l_iter;
+ mul_v2_m3v3(projverts[j], axis_mat, l_iter->v->co);
+ j++;
+ } while ((l_iter = l_iter->next) != l_first);
+
+ BLI_polyfill_calc_arena(projverts, efa->len, 1, tris, pf_arena);
+
+ BLI_polyfill_beautify(projverts, efa->len, tris, pf_arena, pf_heap);
+
+ for (j = 0; j < totfilltri; j++) {
+ BMLoop **l_ptr = looptris[i++];
+ unsigned int *tri = tris[j];
+
+ l_ptr[0] = l_arr[tri[0]];
+ l_ptr[1] = l_arr[tri[1]];
+ l_ptr[2] = l_arr[tri[2]];
+ }
+
+ BLI_memarena_clear(pf_arena);
+ }
+ }
+
+ if (pf_arena) {
+ BLI_memarena_free(pf_arena);
+
+ BLI_heap_free(pf_heap, NULL);
+ }
+
+ *r_looptris_tot = i;
+
+ BLI_assert(i <= looptris_tot);
+
+}
diff --git a/source/blender/bmesh/intern/bmesh_polygon.h b/source/blender/bmesh/intern/bmesh_polygon.h
index 1e50a504875..a40da2bfbfa 100644
--- a/source/blender/bmesh/intern/bmesh_polygon.h
+++ b/source/blender/bmesh/intern/bmesh_polygon.h
@@ -27,16 +27,16 @@
* \ingroup bmesh
*/
-struct EdgeHash;
struct Heap;
#include "BLI_compiler_attrs.h"
void BM_mesh_calc_tessellation(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptris_tot);
+void BM_mesh_calc_tessellation_beauty(BMesh *bm, BMLoop *(*looptris)[3], int *r_looptris_tot);
void BM_face_calc_tessellation(
const BMFace *f, const bool use_fixed_quad,
- BMLoop **r_loops, unsigned int (*r_index)[3]);
+ BMLoop **r_loops, uint (*r_index)[3]);
void BM_face_calc_point_in_face(const BMFace *f, float r_co[3]);
float BM_face_calc_normal(const BMFace *f, float r_no[3]) ATTR_NONNULL();
float BM_face_calc_normal_vcos(
@@ -57,6 +57,8 @@ void BM_face_calc_center_mean_vcos(
float const (*vertexCos)[3]) ATTR_NONNULL();
void BM_face_calc_center_mean_weighted(const BMFace *f, float center[3]) ATTR_NONNULL();
+void BM_face_calc_bounds_expand(const BMFace *f, float min[3], float max[3]);
+
void BM_face_normal_update(BMFace *f) ATTR_NONNULL();
void BM_edge_normals_update(BMEdge *e) ATTR_NONNULL();
@@ -82,7 +84,7 @@ void BM_face_triangulate(
const int quad_method, const int ngon_method,
const bool use_tag,
struct MemArena *pf_arena,
- struct Heap *pf_heap, struct EdgeHash *pf_ehash
+ struct Heap *pf_heap
) ATTR_NONNULL(1, 2);
void BM_face_splits_check_legal(BMesh *bm, BMFace *f, BMLoop *(*loops)[2], int len) ATTR_NONNULL();
diff --git a/source/blender/bmesh/intern/bmesh_polygon_edgenet.c b/source/blender/bmesh/intern/bmesh_polygon_edgenet.c
index 6ce7c100b0d..85dfd3f58e2 100644
--- a/source/blender/bmesh/intern/bmesh_polygon_edgenet.c
+++ b/source/blender/bmesh/intern/bmesh_polygon_edgenet.c
@@ -32,7 +32,7 @@
#include "BLI_memarena.h"
#include "BLI_array.h"
#include "BLI_alloca.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_linklist_stack.h"
#include "BLI_sort.h"
#include "BLI_sort_utils.h"
@@ -62,15 +62,16 @@
#define EDGE_NET _FLAG_WALK
/* tag verts we've visit */
#define VERT_VISIT _FLAG_WALK
+#define VERT_IN_QUEUE _FLAG_WALK_ALT
struct VertOrder {
float angle;
BMVert *v;
};
-static unsigned int bm_edge_flagged_radial_count(BMEdge *e)
+static uint bm_edge_flagged_radial_count(BMEdge *e)
{
- unsigned int count = 0;
+ uint count = 0;
BMLoop *l;
if ((l = e->l)) {
@@ -133,7 +134,7 @@ static bool bm_face_split_edgenet_find_loop_pair(
e = e_first = v_init->e;
do {
if (BM_ELEM_API_FLAG_TEST(e, EDGE_NET)) {
- const unsigned int count = bm_edge_flagged_radial_count(e);
+ const uint count = bm_edge_flagged_radial_count(e);
if (count == 1) {
BLI_SMALLSTACK_PUSH(edges_boundary, e);
edges_boundary_len++;
@@ -238,7 +239,7 @@ static bool bm_face_split_edgenet_find_loop_pair_exists(
e = e_first = v_init->e;
do {
if (BM_ELEM_API_FLAG_TEST(e, EDGE_NET)) {
- const unsigned int count = bm_edge_flagged_radial_count(e);
+ const uint count = bm_edge_flagged_radial_count(e);
if (count == 1) {
edges_boundary_len++;
}
@@ -274,7 +275,7 @@ static bool bm_face_split_edgenet_find_loop_pair_exists(
static bool bm_face_split_edgenet_find_loop_walk(
BMVert *v_init, const float face_normal[3],
/* cache to avoid realloc every time */
- struct VertOrder *edge_order, const unsigned int edge_order_len,
+ struct VertOrder *edge_order, const uint edge_order_len,
BMEdge *e_pair[2])
{
/* fast-path for the common case (avoid push-pop).
@@ -381,7 +382,7 @@ walk_nofork:
/* sort by angle if needed */
if (STACK_SIZE(edge_order) > 1) {
- unsigned int j;
+ uint j;
BMVert *v_prev = BM_edge_other_vert(v->e, v);
for (j = 0; j < STACK_SIZE(edge_order); j++) {
@@ -420,7 +421,7 @@ finally:
static bool bm_face_split_edgenet_find_loop(
BMVert *v_init, const float face_normal[3], float face_normal_matrix[3][3],
/* cache to avoid realloc every time */
- struct VertOrder *edge_order, const unsigned int edge_order_len,
+ struct VertOrder *edge_order, const uint edge_order_len,
BMVert **r_face_verts, int *r_face_verts_len)
{
BMEdge *e_pair[2];
@@ -434,7 +435,7 @@ static bool bm_face_split_edgenet_find_loop(
(bm_edge_flagged_radial_count(e_pair[1]) == 1));
if (bm_face_split_edgenet_find_loop_walk(v_init, face_normal, edge_order, edge_order_len, e_pair)) {
- unsigned int i = 0;
+ uint i = 0;
r_face_verts[i++] = v_init;
v = BM_edge_other_vert(e_pair[1], v_init);
@@ -474,7 +475,7 @@ bool BM_face_split_edgenet(
int i;
struct VertOrder *edge_order;
- const unsigned int edge_order_len = edge_net_len + 2;
+ const uint edge_order_len = edge_net_len + 2;
BMVert *v;
@@ -512,13 +513,21 @@ bool BM_face_split_edgenet(
} while ((l_iter = l_iter->next) != l_first);
#endif
+ /* Note: 'VERT_IN_QUEUE' is often not needed at all,
+ * however in rare cases verts are added multiple times to the queue,
+ * that on it's own is harmless but in _very_ rare cases,
+ * the queue will overflow its maximum size,
+ * so we better be strict about this! see: T51539 */
for (i = 0; i < edge_net_len; i++) {
BM_ELEM_API_FLAG_ENABLE(edge_net[i], EDGE_NET);
+ BM_ELEM_API_FLAG_DISABLE(edge_net[i]->v1, VERT_IN_QUEUE);
+ BM_ELEM_API_FLAG_DISABLE(edge_net[i]->v2, VERT_IN_QUEUE);
}
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
BM_ELEM_API_FLAG_ENABLE(l_iter->e, EDGE_NET);
+ BM_ELEM_API_FLAG_DISABLE(l_iter->v, VERT_IN_QUEUE);
} while ((l_iter = l_iter->next) != l_first);
float face_normal_matrix[3][3];
@@ -527,8 +536,10 @@ bool BM_face_split_edgenet(
/* any vert can be used to begin with */
STACK_PUSH(vert_queue, l_first->v);
+ BM_ELEM_API_FLAG_ENABLE(l_first->v, VERT_IN_QUEUE);
while ((v = STACK_POP(vert_queue))) {
+ BM_ELEM_API_FLAG_DISABLE(v, VERT_IN_QUEUE);
if (bm_face_split_edgenet_find_loop(
v, f->no, face_normal_matrix,
edge_order, edge_order_len, face_verts, &face_verts_len))
@@ -558,8 +569,12 @@ bool BM_face_split_edgenet(
* (verts between boundary and manifold edges) */
l_iter = l_first = BM_FACE_FIRST_LOOP(f_new);
do {
- if (bm_face_split_edgenet_find_loop_pair_exists(l_iter->v)) {
+ /* Avoid adding to queue multiple times (not common but happens). */
+ if (!BM_ELEM_API_FLAG_TEST(l_iter->v, VERT_IN_QUEUE) &&
+ bm_face_split_edgenet_find_loop_pair_exists(l_iter->v))
+ {
STACK_PUSH(vert_queue, l_iter->v);
+ BM_ELEM_API_FLAG_ENABLE(l_iter->v, VERT_IN_QUEUE);
}
} while ((l_iter = l_iter->next) != l_first);
}
@@ -650,7 +665,7 @@ bool BM_face_split_edgenet(
BM_ELEM_API_FLAG_DISABLE(l_iter->v, VERT_VISIT);
} while ((l_iter = l_iter->next) != l_first);
- if (BLI_array_count(face_arr)) {
+ if (BLI_array_len(face_arr)) {
bmesh_face_swap_data(f, face_arr[0]);
BM_face_kill(bm, face_arr[0]);
face_arr[0] = f;
@@ -659,13 +674,13 @@ bool BM_face_split_edgenet(
BM_ELEM_API_FLAG_DISABLE(f, FACE_NET);
}
- for (i = 0; i < BLI_array_count(face_arr); i++) {
+ for (i = 0; i < BLI_array_len(face_arr); i++) {
BM_ELEM_API_FLAG_DISABLE(face_arr[i], FACE_NET);
}
if (r_face_arr) {
*r_face_arr = face_arr;
- *r_face_arr_len = BLI_array_count(face_arr);
+ *r_face_arr_len = BLI_array_len(face_arr);
}
else {
if (face_arr) {
@@ -710,10 +725,30 @@ BLI_INLINE bool edge_isect_verts_point_2d(
const BMEdge *e, const BMVert *v_a, const BMVert *v_b,
float r_isect[2])
{
- return ((isect_seg_seg_v2_point(v_a->co, v_b->co, e->v1->co, e->v2->co, r_isect) == 1) &&
+ /* This bias seems like it could be too large,
+ * mostly its not needed, see T52329 for example where it is. */
+ const float endpoint_bias = 1e-4f;
+ return ((isect_seg_seg_v2_point_ex(v_a->co, v_b->co, e->v1->co, e->v2->co, endpoint_bias, r_isect) == 1) &&
((e->v1 != v_a) && (e->v2 != v_a) && (e->v1 != v_b) && (e->v2 != v_b)));
}
+BLI_INLINE int axis_pt_cmp(const float pt_a[2], const float pt_b[2])
+{
+ if (pt_a[0] < pt_b[0]) {
+ return -1;
+ }
+ if (pt_a[0] > pt_b[0]) {
+ return 1;
+ }
+ if (pt_a[1] < pt_b[1]) {
+ return -1;
+ }
+ if (pt_a[1] > pt_b[1]) {
+ return 1;
+ }
+ return 0;
+}
+
/**
* Represents isolated edge-links,
* each island owns contiguous slices of the vert array.
@@ -721,20 +756,21 @@ BLI_INLINE bool edge_isect_verts_point_2d(
*/
struct EdgeGroupIsland {
LinkNode edge_links; /* keep first */
- unsigned int vert_len, edge_len;
+ uint vert_len, edge_len;
/* Set the following vars once we have >1 groups */
/* when when an edge in a previous group connects to this one,
* so theres no need to create one pointing back. */
- unsigned int has_prev_edge : 1;
+ uint has_prev_edge : 1;
/* verts in the group which has the lowest & highest values,
* the lower vertex is connected to the first edge */
struct {
BMVert *min, *max;
/* used for sorting only */
- float min_axis;
+ float min_axis[2];
+ float max_axis[2];
} vert_span;
};
@@ -743,12 +779,11 @@ static int group_min_cmp_fn(const void *p1, const void *p2)
const struct EdgeGroupIsland *g1 = *(struct EdgeGroupIsland **)p1;
const struct EdgeGroupIsland *g2 = *(struct EdgeGroupIsland **)p2;
/* min->co[SORT_AXIS] hasn't been applied yet */
- const float f1 = g1->vert_span.min_axis;
- const float f2 = g2->vert_span.min_axis;
-
- if (f1 < f2) return -1;
- if (f1 > f2) return 1;
- else return 0;
+ int test = axis_pt_cmp(g1->vert_span.min_axis, g2->vert_span.min_axis);
+ if (UNLIKELY(test == 0)) {
+ test = axis_pt_cmp(g1->vert_span.max_axis, g2->vert_span.max_axis);
+ }
+ return test;
}
struct Edges_VertVert_BVHTreeTest {
@@ -758,7 +793,7 @@ struct Edges_VertVert_BVHTreeTest {
BMVert *v_origin;
BMVert *v_other;
- const unsigned int *vert_range;
+ const uint *vert_range;
};
struct Edges_VertRay_BVHTreeTest {
@@ -766,7 +801,7 @@ struct Edges_VertRay_BVHTreeTest {
BMVert *v_origin;
- const unsigned int *vert_range;
+ const uint *vert_range;
};
static void bvhtree_test_edges_isect_2d_vert_cb(
@@ -825,18 +860,18 @@ static void bvhtree_test_edges_isect_2d_ray_cb(
/**
* Store values for:
* - #bm_face_split_edgenet_find_connection
- * - #test_edges_isect_2d
+ * - #test_edges_isect_2d_vert
* ... which don't change each call.
*/
struct EdgeGroup_FindConnection_Args {
BVHTree *bvhtree;
BMEdge **edge_arr;
- unsigned int edge_arr_len;
+ uint edge_arr_len;
BMEdge **edge_arr_new;
- unsigned int edge_arr_new_len;
+ uint edge_arr_new_len;
- const unsigned int *vert_range;
+ const uint *vert_range;
};
static BMEdge *test_edges_isect_2d_vert(
@@ -869,7 +904,7 @@ static BMEdge *test_edges_isect_2d_vert(
/* check existing connections (no spatial optimization here since we're continually adding). */
if (LIKELY(index == -1)) {
float t_best = 1.0f;
- for (unsigned int i = 0; i < args->edge_arr_new_len; i++) {
+ for (uint i = 0; i < args->edge_arr_new_len; i++) {
float co_isect[2];
if (UNLIKELY(edge_isect_verts_point_2d(args->edge_arr_new[i], v_origin, v_other, co_isect))) {
const float t_test = line_point_factor_v2(co_isect, v_origin->co, v_other->co);
@@ -914,7 +949,7 @@ static BMEdge *test_edges_isect_2d_ray(
/* check existing connections (no spatial optimization here since we're continually adding). */
if (LIKELY(index != -1)) {
- for (unsigned int i = 0; i < args->edge_arr_new_len; i++) {
+ for (uint i = 0; i < args->edge_arr_new_len; i++) {
BMEdge *e = args->edge_arr_new[i];
float dist_new;
if (isect_ray_seg_v2(v_origin->co, dir, e->v1->co, e->v2->co, &dist_new, NULL)) {
@@ -978,8 +1013,8 @@ static int bm_face_split_edgenet_find_connection(
for (int j = 0; j < 2; j++) {
BMVert *v_iter = v_pair[j];
if (BM_elem_flag_test(v_iter, VERT_IS_VALID)) {
- if (direction_sign ? (v_iter->co[SORT_AXIS] >= v_origin->co[SORT_AXIS]) :
- (v_iter->co[SORT_AXIS] <= v_origin->co[SORT_AXIS]))
+ if (direction_sign ? (v_iter->co[SORT_AXIS] > v_origin->co[SORT_AXIS]) :
+ (v_iter->co[SORT_AXIS] < v_origin->co[SORT_AXIS]))
{
BLI_SMALLSTACK_PUSH(vert_search, v_iter);
BLI_SMALLSTACK_PUSH(vert_blacklist, v_iter);
@@ -1031,7 +1066,7 @@ static BMVert *bm_face_split_edgenet_partial_connect(BMesh *bm, BMVert *v_delimi
/* initial check - see if we have 3+ flagged edges attached to 'v_delimit'
* if not, we can early exit */
LinkNode *e_delimit_list = NULL;
- unsigned int e_delimit_list_len = 0;
+ uint e_delimit_list_len = 0;
#define EDGE_NOT_IN_STACK BM_ELEM_INTERNAL_TAG
#define VERT_NOT_IN_STACK BM_ELEM_INTERNAL_TAG
@@ -1169,10 +1204,10 @@ static bool bm_vert_partial_connect_check_overlap(
*/
bool BM_face_split_edgenet_connect_islands(
BMesh *bm,
- BMFace *f, BMEdge **edge_net_init, const unsigned int edge_net_init_len,
+ BMFace *f, BMEdge **edge_net_init, const uint edge_net_init_len,
bool use_partial_connect,
MemArena *mem_arena,
- BMEdge ***r_edge_net_new, unsigned int *r_edge_net_new_len)
+ BMEdge ***r_edge_net_new, uint *r_edge_net_new_len)
{
/* -------------------------------------------------------------------- */
/* This function has 2 main parts.
@@ -1186,7 +1221,7 @@ bool BM_face_split_edgenet_connect_islands(
* (avoid thrashing the area when the initial check isn't so intensive on the stack).
*/
- const unsigned int edge_arr_len = (unsigned int)edge_net_init_len + (unsigned int)f->len;
+ const uint edge_arr_len = (uint)edge_net_init_len + (uint)f->len;
BMEdge **edge_arr = BLI_array_alloca(edge_arr, edge_arr_len);
bool ok = false;
@@ -1197,16 +1232,18 @@ bool BM_face_split_edgenet_connect_islands(
#define VERT_NOT_IN_STACK BM_ELEM_INTERNAL_TAG
{
- unsigned int i = edge_net_init_len;
+ uint i = edge_net_init_len;
BMLoop *l_iter, *l_first;
l_iter = l_first = BM_FACE_FIRST_LOOP(f);
do {
+ BLI_assert(!BM_elem_flag_test(l_iter->v, VERT_NOT_IN_STACK));
+ BLI_assert(!BM_elem_flag_test(l_iter->e, EDGE_NOT_IN_STACK));
edge_arr[i++] = l_iter->e;
} while ((l_iter = l_iter->next) != l_first);
BLI_assert(i == edge_arr_len);
}
- for (unsigned int i = 0; i < edge_arr_len; i++) {
+ for (uint i = 0; i < edge_arr_len; i++) {
BM_elem_flag_enable(edge_arr[i], EDGE_NOT_IN_STACK);
BM_elem_flag_enable(edge_arr[i]->v1, VERT_NOT_IN_STACK);
BM_elem_flag_enable(edge_arr[i]->v2, VERT_NOT_IN_STACK);
@@ -1224,12 +1261,12 @@ bool BM_face_split_edgenet_connect_islands(
struct {
struct TempVertPair *list;
- unsigned int len;
+ uint len;
int *remap; /* temp -> orig mapping */
} temp_vert_pairs = {NULL};
if (use_partial_connect) {
- for (unsigned int i = 0; i < edge_net_init_len; i++) {
+ for (uint i = 0; i < edge_net_init_len; i++) {
for (unsigned j = 0; j < 2; j++) {
BMVert *v_delimit = (&edge_arr[i]->v1)[j];
BMVert *v_other;
@@ -1254,19 +1291,19 @@ bool BM_face_split_edgenet_connect_islands(
- unsigned int group_arr_len = 0;
+ uint group_arr_len = 0;
LinkNode *group_head = NULL;
{
/* scan 'edge_arr' backwards so the outer face boundary is handled first
* (since its likely to be the largest) */
- unsigned int edge_index = (edge_arr_len - 1);
- unsigned int edge_in_group_tot = 0;
+ uint edge_index = (edge_arr_len - 1);
+ uint edge_in_group_tot = 0;
BLI_SMALLSTACK_DECLARE(vstack, BMVert *);
while (true) {
LinkNode *edge_links = NULL;
- unsigned int unique_verts_in_group = 0, unique_edges_in_group = 0;
+ uint unique_verts_in_group = 0, unique_edges_in_group = 0;
/* list of groups */
BLI_assert(BM_elem_flag_test(edge_arr[edge_index]->v1, VERT_NOT_IN_STACK));
@@ -1333,7 +1370,7 @@ bool BM_face_split_edgenet_connect_islands(
#define VERT_IN_ARRAY BM_ELEM_INTERNAL_TAG
struct EdgeGroupIsland **group_arr = BLI_memarena_alloc(mem_arena, sizeof(*group_arr) * group_arr_len);
- unsigned int vert_arr_len = 0;
+ uint vert_arr_len = 0;
/* sort groups by lowest value vertex */
{
/* fill 'groups_arr' in reverse order so the boundary face is first */
@@ -1345,8 +1382,8 @@ bool BM_face_split_edgenet_connect_islands(
/* init with *any* different verts */
g->vert_span.min = ((BMEdge *)edge_links->link)->v1;
g->vert_span.max = ((BMEdge *)edge_links->link)->v2;
- float min_axis = FLT_MAX;
- float max_axis = -FLT_MAX;
+ float min_axis[2] = {FLT_MAX, FLT_MAX};
+ float max_axis[2] = {-FLT_MAX, -FLT_MAX};
do {
BMEdge *e = edge_links->link;
@@ -1357,24 +1394,29 @@ bool BM_face_split_edgenet_connect_islands(
BLI_assert(v_iter->head.htype == BM_VERT);
/* ideally we could use 'v_iter->co[SORT_AXIS]' here,
* but we need to sort the groups before setting the vertex array order */
+ const float axis_value[2] = {
#if SORT_AXIS == 0
- const float axis_value = dot_m3_v3_row_x(axis_mat, v_iter->co);
+ dot_m3_v3_row_x(axis_mat, v_iter->co),
+ dot_m3_v3_row_y(axis_mat, v_iter->co),
#else
- const float axis_value = dot_m3_v3_row_y(axis_mat, v_iter->co);
+ dot_m3_v3_row_y(axis_mat, v_iter->co),
+ dot_m3_v3_row_x(axis_mat, v_iter->co),
#endif
+ };
- if (axis_value < min_axis) {
+ if (axis_pt_cmp(axis_value, min_axis) == -1) {
g->vert_span.min = v_iter;
- min_axis = axis_value;
+ copy_v2_v2(min_axis, axis_value);
}
- if (axis_value > max_axis ) {
+ if (axis_pt_cmp(axis_value, max_axis) == 1) {
g->vert_span.max = v_iter;
- max_axis = axis_value;
+ copy_v2_v2(max_axis, axis_value);
}
}
} while ((edge_links = edge_links->next));
- g->vert_span.min_axis = min_axis;
+ copy_v2_v2(g->vert_span.min_axis, min_axis);
+ copy_v2_v2(g->vert_span.max_axis, max_axis);
g->has_prev_edge = false;
@@ -1389,7 +1431,7 @@ bool BM_face_split_edgenet_connect_islands(
/* we don't know how many unique verts there are connecting the edges, so over-alloc */
BMVert **vert_arr = BLI_memarena_alloc(mem_arena, sizeof(*vert_arr) * vert_arr_len);
/* map vertex -> group index */
- unsigned int *verts_group_table = BLI_memarena_alloc(mem_arena, sizeof(*verts_group_table) * vert_arr_len);
+ uint *verts_group_table = BLI_memarena_alloc(mem_arena, sizeof(*verts_group_table) * vert_arr_len);
float (*vert_coords_backup)[3] = BLI_memarena_alloc(mem_arena, sizeof(*vert_coords_backup) * vert_arr_len);
@@ -1398,7 +1440,7 @@ bool BM_face_split_edgenet_connect_islands(
const float f_co_ref[3] = {UNPACK3(BM_FACE_FIRST_LOOP(f)->v->co)};
int v_index = 0; /* global vert index */
- for (unsigned int g_index = 0; g_index < group_arr_len; g_index++) {
+ for (uint g_index = 0; g_index < group_arr_len; g_index++) {
LinkNode *edge_links = group_arr[g_index]->edge_links.link;
do {
BMEdge *e = edge_links->link;
@@ -1434,9 +1476,11 @@ bool BM_face_split_edgenet_connect_islands(
bm->elem_index_dirty |= BM_VERT;
- /* Now create bvh tree*/
- BVHTree *bvhtree = BLI_bvhtree_new(edge_arr_len, 0.0f, 8, 8);
- for (unsigned int i = 0; i < edge_arr_len; i++) {
+ /* Now create bvh tree
+ *
+ * Note that a large epsilon is used because meshes with dimensions of around 100+ need it. see T52329. */
+ BVHTree *bvhtree = BLI_bvhtree_new(edge_arr_len, 1e-4f, 8, 8);
+ for (uint i = 0; i < edge_arr_len; i++) {
const float e_cos[2][3] = {
{UNPACK2(edge_arr[i]->v1->co), 0.0f},
{UNPACK2(edge_arr[i]->v2->co), 0.0f},
@@ -1465,15 +1509,15 @@ bool BM_face_split_edgenet_connect_islands(
/* Create connections between groups */
/* may be an over-alloc, but not by much */
- unsigned int edge_net_new_len = (unsigned int)edge_net_init_len + ((group_arr_len - 1) * 2);
+ uint edge_net_new_len = (uint)edge_net_init_len + ((group_arr_len - 1) * 2);
BMEdge **edge_net_new = BLI_memarena_alloc(mem_arena, sizeof(*edge_net_new) * edge_net_new_len);
memcpy(edge_net_new, edge_net_init, sizeof(*edge_net_new) * (size_t)edge_net_init_len);
{
- unsigned int edge_net_new_index = edge_net_init_len;
+ uint edge_net_new_index = edge_net_init_len;
/* start-end of the verts in the current group */
- unsigned int vert_range[2];
+ uint vert_range[2];
vert_range[0] = 0;
vert_range[1] = group_arr[0]->vert_len;
@@ -1492,7 +1536,7 @@ bool BM_face_split_edgenet_connect_islands(
.vert_range = vert_range,
};
- for (unsigned int g_index = 1; g_index < group_arr_len; g_index++) {
+ for (uint g_index = 1; g_index < group_arr_len; g_index++) {
struct EdgeGroupIsland *g = group_arr[g_index];
/* the range of verts this group uses in 'verts_arr' (not uncluding the last index) */
@@ -1551,7 +1595,7 @@ bool BM_face_split_edgenet_connect_islands(
}
/* tell the 'next' group it doesn't need to create its own back-link */
- unsigned int g_index_other = verts_group_table[index_other];
+ uint g_index_other = verts_group_table[index_other];
group_arr[g_index_other]->has_prev_edge = true;
}
}
@@ -1567,7 +1611,7 @@ bool BM_face_split_edgenet_connect_islands(
*r_edge_net_new_len = edge_net_new_len;
ok = true;
- for (unsigned int i = 0; i < vert_arr_len; i++) {
+ for (uint i = 0; i < vert_arr_len; i++) {
copy_v3_v3(vert_arr[i]->co, vert_coords_backup[i]);
}
@@ -1600,7 +1644,7 @@ finally:
/* Remove edges which have become doubles since splicing vertices together,
* its less trouble then detecting future-doubles on edge-creation. */
- for (unsigned int i = edge_net_init_len; i < edge_net_new_len; i++) {
+ for (uint i = edge_net_init_len; i < edge_net_new_len; i++) {
while (BM_edge_find_double(edge_net_new[i])) {
BM_edge_kill(bm, edge_net_new[i]);
edge_net_new_len--;
@@ -1616,7 +1660,7 @@ finally:
#endif
- for (unsigned int i = 0; i < edge_arr_len; i++) {
+ for (uint i = 0; i < edge_arr_len; i++) {
BM_elem_flag_disable(edge_arr[i], EDGE_NOT_IN_STACK);
BM_elem_flag_disable(edge_arr[i]->v1, VERT_NOT_IN_STACK);
BM_elem_flag_disable(edge_arr[i]->v2, VERT_NOT_IN_STACK);
diff --git a/source/blender/bmesh/intern/bmesh_polygon_edgenet.h b/source/blender/bmesh/intern/bmesh_polygon_edgenet.h
index 72ae7695f0f..bf5cea59e30 100644
--- a/source/blender/bmesh/intern/bmesh_polygon_edgenet.h
+++ b/source/blender/bmesh/intern/bmesh_polygon_edgenet.h
@@ -32,10 +32,10 @@ bool BM_face_split_edgenet(
bool BM_face_split_edgenet_connect_islands(
BMesh *bm,
- BMFace *f, BMEdge **edge_net_init, const unsigned int edge_net_init_len,
+ BMFace *f, BMEdge **edge_net_init, const uint edge_net_init_len,
bool use_partial_connect,
struct MemArena *arena,
- BMEdge ***r_edge_net_new, unsigned int *r_edge_net_new_len)
+ BMEdge ***r_edge_net_new, uint *r_edge_net_new_len)
ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1, 2, 3, 6, 7, 8);
#endif /* __BMESH_POLYGON_EDGENET_H__ */
diff --git a/source/blender/bmesh/intern/bmesh_private.h b/source/blender/bmesh/intern/bmesh_private.h
index d8d297c9298..daee22ffe76 100644
--- a/source/blender/bmesh/intern/bmesh_private.h
+++ b/source/blender/bmesh/intern/bmesh_private.h
@@ -44,17 +44,18 @@
# define BM_CHECK_ELEMENT(el) (void)(el)
#else
int bmesh_elem_check(void *element, const char htype);
-# define BM_CHECK_ELEMENT(el) \
+# define BM_CHECK_ELEMENT(el) { \
if (bmesh_elem_check(el, ((BMHeader *)el)->htype)) { \
printf("check_element failure, with code %i on line %i in file\n" \
" \"%s\"\n\n", \
bmesh_elem_check(el, ((BMHeader *)el)->htype), \
__LINE__, __FILE__); \
- } (void)0
+ } \
+} ((void)0)
#endif
int bmesh_radial_length(const BMLoop *l);
-int bmesh_disk_count_ex(const BMVert *v, const int count_max);
+int bmesh_disk_count_at_most(const BMVert *v, const int count_max);
int bmesh_disk_count(const BMVert *v);
/**
@@ -73,7 +74,7 @@ enum {
};
#define BM_ELEM_API_FLAG_ENABLE(element, f) { ((element)->head.api_flag |= (f)); } (void)0
-#define BM_ELEM_API_FLAG_DISABLE(element, f) { ((element)->head.api_flag &= (unsigned char)~(f)); } (void)0
+#define BM_ELEM_API_FLAG_DISABLE(element, f) { ((element)->head.api_flag &= (uchar)~(f)); } (void)0
#define BM_ELEM_API_FLAG_TEST(element, f) ((element)->head.api_flag & (f))
#define BM_ELEM_API_FLAG_CLEAR(element) { ((element)->head.api_flag = 0); } (void)0
diff --git a/source/blender/bmesh/intern/bmesh_queries.c b/source/blender/bmesh/intern/bmesh_queries.c
index 7ca5640578a..ab2f017d103 100644
--- a/source/blender/bmesh/intern/bmesh_queries.c
+++ b/source/blender/bmesh/intern/bmesh_queries.c
@@ -36,7 +36,7 @@
#include "BLI_math.h"
#include "BLI_alloca.h"
#include "BLI_linklist.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BKE_customdata.h"
@@ -754,6 +754,22 @@ bool BM_vert_is_edge_pair(const BMVert *v)
}
/**
+ * Fast alternative to ``(BM_vert_edge_count(v) == 2)``
+ * that checks both edges connect to the same faces.
+ */
+bool BM_vert_is_edge_pair_manifold(const BMVert *v)
+{
+ const BMEdge *e = v->e;
+ if (e) {
+ BMEdge *e_other = BM_DISK_EDGE_NEXT(e, v);
+ if (((e_other != e) && (BM_DISK_EDGE_NEXT(e_other, v) == e))) {
+ return BM_edge_is_manifold(e) && BM_edge_is_manifold(e_other);
+ }
+ }
+ return false;
+}
+
+/**
* Access a verts 2 connected edges.
*
* \return true when only 2 verts are found.
@@ -783,9 +799,9 @@ int BM_vert_edge_count(const BMVert *v)
return bmesh_disk_count(v);
}
-int BM_vert_edge_count_ex(const BMVert *v, const int count_max)
+int BM_vert_edge_count_at_most(const BMVert *v, const int count_max)
{
- return bmesh_disk_count_ex(v, count_max);
+ return bmesh_disk_count_at_most(v, count_max);
}
int BM_vert_edge_count_nonwire(const BMVert *v)
@@ -819,7 +835,7 @@ int BM_edge_face_count(const BMEdge *e)
return count;
}
-int BM_edge_face_count_ex(const BMEdge *e, const int count_max)
+int BM_edge_face_count_at_most(const BMEdge *e, const int count_max)
{
int count = 0;
@@ -847,9 +863,9 @@ int BM_vert_face_count(const BMVert *v)
return bmesh_disk_facevert_count(v);
}
-int BM_vert_face_count_ex(const BMVert *v, int count_max)
+int BM_vert_face_count_at_most(const BMVert *v, int count_max)
{
- return bmesh_disk_facevert_count_ex(v, count_max);
+ return bmesh_disk_facevert_count_at_most(v, count_max);
}
/**
@@ -1028,7 +1044,7 @@ static int bm_loop_region_count__clear(BMLoop *l)
/**
* The number of loops connected to this loop (not including disconnected regions).
*/
-int BM_loop_region_loops_count_ex(BMLoop *l, int *r_loop_total)
+int BM_loop_region_loops_count_at_most(BMLoop *l, int *r_loop_total)
{
const int count = bm_loop_region_count__recursive(l->e, l->v);
const int count_total = bm_loop_region_count__clear(l);
@@ -1043,7 +1059,7 @@ int BM_loop_region_loops_count_ex(BMLoop *l, int *r_loop_total)
int BM_loop_region_loops_count(BMLoop *l)
{
- return BM_loop_region_loops_count_ex(l, NULL);
+ return BM_loop_region_loops_count_at_most(l, NULL);
}
/**
@@ -1055,7 +1071,7 @@ bool BM_vert_is_manifold_region(const BMVert *v)
BMLoop *l_first = BM_vert_find_first_loop((BMVert *)v);
if (l_first) {
int count, count_total;
- count = BM_loop_region_loops_count_ex(l_first, &count_total);
+ count = BM_loop_region_loops_count_at_most(l_first, &count_total);
return (count == count_total);
}
return true;
@@ -1510,21 +1526,69 @@ float BM_loop_calc_face_angle(const BMLoop *l)
*
* Calculate the normal at this loop corner or fallback to the face normal on straight lines.
*
+ * \param l: The loop to calculate the normal at.
+ * \param epsilon_sq: Value to avoid numeric errors (1e-5f works well).
+ * \param r_normal: Resulting normal.
+ */
+float BM_loop_calc_face_normal_safe_ex(const BMLoop *l, const float epsilon_sq, float r_normal[3])
+{
+ /* Note: we cannot use result of normal_tri_v3 here to detect colinear vectors (vertex on a straight line)
+ * from zero value, because it does not normalize both vectors before making crossproduct.
+ * Instead of adding two costly normalize computations, just check ourselves for colinear case. */
+ /* Note: FEPSILON might need some finer tweaking at some point? Seems to be working OK for now though. */
+ float v1[3], v2[3], v_tmp[3];
+ sub_v3_v3v3(v1, l->prev->v->co, l->v->co);
+ sub_v3_v3v3(v2, l->next->v->co, l->v->co);
+
+ const float fac =
+ ((v2[0] == 0.0f) ?
+ ((v2[1] == 0.0f) ?
+ ((v2[2] == 0.0f) ? 0.0f : v1[2] / v2[2]) : v1[1] / v2[1]) : v1[0] / v2[0]);
+
+ mul_v3_v3fl(v_tmp, v2, fac);
+ sub_v3_v3(v_tmp, v1);
+ if (fac != 0.0f && !is_zero_v3(v1) && len_squared_v3(v_tmp) > epsilon_sq) {
+ /* Not co-linear, we can compute crossproduct and normalize it into normal. */
+ cross_v3_v3v3(r_normal, v1, v2);
+ return normalize_v3(r_normal);
+ }
+ else {
+ copy_v3_v3(r_normal, l->f->no);
+ return 0.0f;
+ }
+}
+
+/**
+ * #BM_loop_calc_face_normal_safe_ex with pre-defined sane epsilon.
+ *
+ * Since this doesn't scale baed on triangle size, fixed value works well.
+ */
+float BM_loop_calc_face_normal_safe(const BMLoop *l, float r_normal[3])
+{
+ return BM_loop_calc_face_normal_safe_ex(l, 1e-5f, r_normal);
+}
+
+/**
+ * \brief BM_loop_calc_face_normal
+ *
+ * Calculate the normal at this loop corner or fallback to the face normal on straight lines.
+ *
* \param l The loop to calculate the normal at
* \param r_normal Resulting normal
+ * \return The length of the cross product (double the area).
*/
-void BM_loop_calc_face_normal(const BMLoop *l, float r_normal[3])
+float BM_loop_calc_face_normal(const BMLoop *l, float r_normal[3])
{
- if (normal_tri_v3(r_normal,
- l->prev->v->co,
- l->v->co,
- l->next->v->co) != 0.0f)
- {
- /* pass */
- }
- else {
+ float v1[3], v2[3];
+ sub_v3_v3v3(v1, l->prev->v->co, l->v->co);
+ sub_v3_v3v3(v2, l->next->v->co, l->v->co);
+
+ cross_v3_v3v3(r_normal, v1, v2);
+ const float len = normalize_v3(r_normal);
+ if (UNLIKELY(len == 0.0f)) {
copy_v3_v3(r_normal, l->f->no);
}
+ return len;
}
/**
@@ -1680,6 +1744,7 @@ float BM_vert_calc_edge_angle_ex(const BMVert *v, const float fallback)
if ((e1 = v->e) &&
(e2 = bmesh_disk_edge_next(e1, v)) &&
+ (e1 != e2) &&
/* make sure we come full circle and only have 2 connected edges */
(e1 == bmesh_disk_edge_next(e2, v)))
{
@@ -2044,7 +2109,8 @@ bool BM_face_exists_multi(BMVert **varr, BMEdge **earr, int len)
if (tot_tag == 0) {
/* no faces use only boundary verts, quit early */
- return false;
+ ok = false;
+ goto finally;
}
/* 2) loop over non-boundary edges that use boundary verts,
@@ -2079,6 +2145,12 @@ bool BM_face_exists_multi(BMVert **varr, BMEdge **earr, int len)
}
}
+finally:
+ /* Cleanup */
+ for (i = 0; i < len; i++) {
+ BM_elem_flag_disable(varr[i], BM_ELEM_INTERNAL_TAG);
+ BM_elem_flag_disable(earr[i], BM_ELEM_INTERNAL_TAG);
+ }
return ok;
}
@@ -2326,7 +2398,7 @@ static void bm_mesh_calc_volume_face(const BMFace *f, float *r_vol)
{
const int tottri = f->len - 2;
BMLoop **loops = BLI_array_alloca(loops, f->len);
- unsigned int (*index)[3] = BLI_array_alloca(index, tottri);
+ uint (*index)[3] = BLI_array_alloca(index, tottri);
int j;
BM_face_calc_tessellation(f, false, loops, index);
@@ -2395,8 +2467,8 @@ int BM_mesh_calc_face_groups(
int group_curr = 0;
- unsigned int tot_faces = 0;
- unsigned int tot_touch = 0;
+ uint tot_faces = 0;
+ uint tot_touch = 0;
BMFace **stack;
STACK_DECLARE(stack);
@@ -2553,8 +2625,8 @@ int BM_mesh_calc_edge_groups(
int group_curr = 0;
- unsigned int tot_edges = 0;
- unsigned int tot_touch = 0;
+ uint tot_edges = 0;
+ uint tot_touch = 0;
BMEdge **stack;
STACK_DECLARE(stack);
diff --git a/source/blender/bmesh/intern/bmesh_queries.h b/source/blender/bmesh/intern/bmesh_queries.h
index 903fdc59cb8..e602c63da94 100644
--- a/source/blender/bmesh/intern/bmesh_queries.h
+++ b/source/blender/bmesh/intern/bmesh_queries.h
@@ -70,21 +70,22 @@ BMFace *BM_edge_pair_share_face_by_len(
const bool allow_adjacent) ATTR_NONNULL();
int BM_vert_edge_count_nonwire(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-#define BM_vert_edge_count_is_equal(v, n) (BM_vert_edge_count_ex(v, (n) + 1) == n)
-#define BM_vert_edge_count_is_over(v, n) (BM_vert_edge_count_ex(v, (n) + 1) == (n) + 1)
-int BM_vert_edge_count_ex(const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+#define BM_vert_edge_count_is_equal(v, n) (BM_vert_edge_count_at_most(v, (n) + 1) == n)
+#define BM_vert_edge_count_is_over(v, n) (BM_vert_edge_count_at_most(v, (n) + 1) == (n) + 1)
+int BM_vert_edge_count_at_most(const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
int BM_vert_edge_count(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-#define BM_edge_face_count_is_equal(e, n) (BM_edge_face_count_ex(e, (n) + 1) == n)
-#define BM_edge_face_count_is_over(e, n) (BM_edge_face_count_ex(e, (n) + 1) == (n) + 1)
-int BM_edge_face_count_ex(const BMEdge *e, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+#define BM_edge_face_count_is_equal(e, n) (BM_edge_face_count_at_most(e, (n) + 1) == n)
+#define BM_edge_face_count_is_over(e, n) (BM_edge_face_count_at_most(e, (n) + 1) == (n) + 1)
+int BM_edge_face_count_at_most(const BMEdge *e, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
int BM_edge_face_count(const BMEdge *e) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-#define BM_vert_face_count_is_equal(v, n) (BM_vert_face_count_ex(v, (n) + 1) == n)
-#define BM_vert_face_count_is_over(v, n) (BM_vert_face_count_ex(v, (n) + 1) == (n) + 1)
-int BM_vert_face_count_ex(const BMVert *v, int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+#define BM_vert_face_count_is_equal(v, n) (BM_vert_face_count_at_most(v, (n) + 1) == n)
+#define BM_vert_face_count_is_over(v, n) (BM_vert_face_count_at_most(v, (n) + 1) == (n) + 1)
+int BM_vert_face_count_at_most(const BMVert *v, int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
int BM_vert_face_count(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BMEdge *BM_vert_other_disk_edge(BMVert *v, BMEdge *e) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool BM_vert_is_edge_pair(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+bool BM_vert_is_edge_pair_manifold(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool BM_vert_edge_pair(BMVert *v, BMEdge **r_e_a, BMEdge **r_e_b);
bool BM_vert_face_check(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool BM_vert_is_wire(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
@@ -102,7 +103,7 @@ bool BM_edge_is_contiguous_loop_cd(
const int cd_loop_type, const int cd_loop_offset)
ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-int BM_loop_region_loops_count_ex(BMLoop *l, int *r_loop_total) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
+int BM_loop_region_loops_count_at_most(BMLoop *l, int *r_loop_total) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
int BM_loop_region_loops_count(BMLoop *l) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1);
bool BM_loop_is_convex(const BMLoop *l) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BLI_INLINE bool BM_loop_is_adjacent(const BMLoop *l_a, const BMLoop *l_b) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
@@ -113,7 +114,9 @@ BMLoop *BM_loop_find_prev_nodouble(BMLoop *l, BMLoop *l_stop, const float eps_sq
BMLoop *BM_loop_find_next_nodouble(BMLoop *l, BMLoop *l_stop, const float eps_sq);
float BM_loop_calc_face_angle(const BMLoop *l) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-void BM_loop_calc_face_normal(const BMLoop *l, float r_normal[3]) ATTR_NONNULL();
+float BM_loop_calc_face_normal(const BMLoop *l, float r_normal[3]) ATTR_NONNULL();
+float BM_loop_calc_face_normal_safe(const BMLoop *l, float r_normal[3]) ATTR_NONNULL();
+float BM_loop_calc_face_normal_safe_ex(const BMLoop *l, const float epsilon, float r_normal[3]) ATTR_NONNULL();
void BM_loop_calc_face_direction(const BMLoop *l, float r_normal[3]);
void BM_loop_calc_face_tangent(const BMLoop *l, float r_tangent[3]);
diff --git a/source/blender/bmesh/intern/bmesh_structure.c b/source/blender/bmesh/intern/bmesh_structure.c
index 8e484841568..8aa9502c0f7 100644
--- a/source/blender/bmesh/intern/bmesh_structure.c
+++ b/source/blender/bmesh/intern/bmesh_structure.c
@@ -244,7 +244,7 @@ int bmesh_disk_count(const BMVert *v)
return count;
}
-int bmesh_disk_count_ex(const BMVert *v, const int count_max)
+int bmesh_disk_count_at_most(const BMVert *v, const int count_max)
{
int count = 0;
if (v->e) {
@@ -267,7 +267,7 @@ bool bmesh_disk_validate(int len, BMEdge *e, BMVert *v)
if (!BM_vert_in_edge(e, v)) {
return false;
}
- if (len == 0 || bmesh_disk_count_ex(v, len + 1) != len) {
+ if (len == 0 || bmesh_disk_count_at_most(v, len + 1) != len) {
return false;
}
@@ -307,7 +307,7 @@ int bmesh_disk_facevert_count(const BMVert *v)
return count;
}
-int bmesh_disk_facevert_count_ex(const BMVert *v, const int count_max)
+int bmesh_disk_facevert_count_at_most(const BMVert *v, const int count_max)
{
/* is there an edge on this vert at all */
int count = 0;
@@ -318,7 +318,7 @@ int bmesh_disk_facevert_count_ex(const BMVert *v, const int count_max)
e_first = e_iter = v->e;
do {
if (e_iter->l) {
- count += bmesh_radial_facevert_count_ex(e_iter->l, v, count_max - count);
+ count += bmesh_radial_facevert_count_at_most(e_iter->l, v, count_max - count);
if (count == count_max) {
break;
}
@@ -560,7 +560,7 @@ int bmesh_radial_facevert_count(const BMLoop *l, const BMVert *v)
return count;
}
-int bmesh_radial_facevert_count_ex(const BMLoop *l, const BMVert *v, const int count_max)
+int bmesh_radial_facevert_count_at_most(const BMLoop *l, const BMVert *v, const int count_max)
{
const BMLoop *l_iter;
int count = 0;
diff --git a/source/blender/bmesh/intern/bmesh_structure.h b/source/blender/bmesh/intern/bmesh_structure.h
index 0efb25da37c..974b276f8b3 100644
--- a/source/blender/bmesh/intern/bmesh_structure.h
+++ b/source/blender/bmesh/intern/bmesh_structure.h
@@ -49,7 +49,7 @@ BLI_INLINE BMEdge *bmesh_disk_edge_next_safe(const BMEdge *e, const BMVert *v) A
BLI_INLINE BMEdge *bmesh_disk_edge_prev_safe(const BMEdge *e, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BLI_INLINE BMEdge *bmesh_disk_edge_next(const BMEdge *e, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BLI_INLINE BMEdge *bmesh_disk_edge_prev(const BMEdge *e, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
-int bmesh_disk_facevert_count_ex(const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int bmesh_disk_facevert_count_at_most(const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
int bmesh_disk_facevert_count(const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BMEdge *bmesh_disk_faceedge_find_first(const BMEdge *e, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BMLoop *bmesh_disk_faceloop_find_first(const BMEdge *e, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
@@ -63,7 +63,7 @@ void bmesh_radial_loop_unlink(BMLoop *l) ATTR_NONNULL();
* bmesh_radial_loop_next(BMLoop *l) / prev.
* just use member access l->radial_next, l->radial_prev now */
-int bmesh_radial_facevert_count_ex(const BMLoop *l, const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
+int bmesh_radial_facevert_count_at_most(const BMLoop *l, const BMVert *v, const int count_max) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
int bmesh_radial_facevert_count(const BMLoop *l, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
bool bmesh_radial_facevert_check(const BMLoop *l, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
BMLoop *bmesh_radial_faceloop_find_first(const BMLoop *l, const BMVert *v) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL();
diff --git a/source/blender/bmesh/operators/bmo_bevel.c b/source/blender/bmesh/operators/bmo_bevel.c
index d5afb39d7b7..2ae87b64286 100644
--- a/source/blender/bmesh/operators/bmo_bevel.c
+++ b/source/blender/bmesh/operators/bmo_bevel.c
@@ -66,5 +66,7 @@ void bmo_bevel_exec(BMesh *bm, BMOperator *op)
BM_mesh_bevel(bm, offset, offset_type, seg, profile, vonly, false, clamp_overlap, NULL, -1, material, loop_slide);
BMO_slot_buffer_from_enabled_hflag(bm, op, op->slots_out, "faces.out", BM_FACE, BM_ELEM_TAG);
+ BMO_slot_buffer_from_enabled_hflag(bm, op, op->slots_out, "edges.out", BM_EDGE, BM_ELEM_TAG);
+ BMO_slot_buffer_from_enabled_hflag(bm, op, op->slots_out, "verts.out", BM_VERT, BM_ELEM_TAG);
}
}
diff --git a/source/blender/bmesh/operators/bmo_bisect_plane.c b/source/blender/bmesh/operators/bmo_bisect_plane.c
index bed1ea5cb94..ed232e81b82 100644
--- a/source/blender/bmesh/operators/bmo_bisect_plane.c
+++ b/source/blender/bmesh/operators/bmo_bisect_plane.c
@@ -29,7 +29,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_math.h"
#include "bmesh.h"
@@ -38,7 +38,8 @@
#include "intern/bmesh_operators_private.h" /* own include */
#define ELE_NEW 1
-#define ELE_INPUT 2
+#define ELE_CUT 2
+#define ELE_INPUT 4
void bmo_bisect_plane_exec(BMesh *bm, BMOperator *op)
{
@@ -69,7 +70,7 @@ void bmo_bisect_plane_exec(BMesh *bm, BMOperator *op)
BM_mesh_bisect_plane(bm, plane, use_snap_center, true,
- ELE_NEW, dist);
+ ELE_CUT, ELE_NEW, dist);
if (clear_outer || clear_inner) {
@@ -108,5 +109,5 @@ void bmo_bisect_plane_exec(BMesh *bm, BMOperator *op)
}
BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom.out", BM_ALL_NOLOOP, ELE_NEW | ELE_INPUT);
- BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom_cut.out", BM_VERT | BM_EDGE, ELE_NEW);
+ BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "geom_cut.out", BM_VERT | BM_EDGE, ELE_CUT);
}
diff --git a/source/blender/bmesh/operators/bmo_connect.c b/source/blender/bmesh/operators/bmo_connect.c
index 5c9cd8dc3fa..0b5f1bb9ca1 100644
--- a/source/blender/bmesh/operators/bmo_connect.c
+++ b/source/blender/bmesh/operators/bmo_connect.c
@@ -27,7 +27,7 @@
*/
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_alloca.h"
#include "BLI_linklist_stack.h"
@@ -55,7 +55,7 @@ static int bm_face_connect_verts(BMesh *bm, BMFace *f, const bool check_degenera
BMLoop *l_tag_prev = NULL, *l_tag_first = NULL;
BMLoop *l_iter, *l_first;
- unsigned int i;
+ uint i;
STACK_INIT(loops_split, pair_split_max);
STACK_INIT(verts_pair, pair_split_max);
diff --git a/source/blender/bmesh/operators/bmo_connect_concave.c b/source/blender/bmesh/operators/bmo_connect_concave.c
index 9bb67ed9341..d1811ac6a83 100644
--- a/source/blender/bmesh/operators/bmo_connect_concave.c
+++ b/source/blender/bmesh/operators/bmo_connect_concave.c
@@ -39,9 +39,8 @@
#include "BLI_alloca.h"
#include "BLI_memarena.h"
#include "BLI_heap.h"
-#include "BLI_polyfill2d.h"
-#include "BLI_polyfill2d_beautify.h"
-#include "BLI_edgehash.h"
+#include "BLI_polyfill_2d.h"
+#include "BLI_polyfill_2d_beautify.h"
#include "BLI_linklist.h"
#include "bmesh.h"
@@ -77,7 +76,7 @@ static bool bm_face_split_by_concave(
BMesh *bm, BMFace *f_base, const float eps,
MemArena *pf_arena,
- struct Heap *pf_heap, struct EdgeHash *pf_ehash)
+ struct Heap *pf_heap)
{
const int f_base_len = f_base->len;
int faces_array_tot = f_base_len - 3;
@@ -99,7 +98,7 @@ static bool bm_face_split_by_concave(
&faces_double,
quad_method, ngon_method, false,
pf_arena,
- pf_heap, pf_ehash);
+ pf_heap);
BLI_assert(edges_array_tot <= f_base_len - 3);
@@ -161,7 +160,6 @@ static bool bm_face_split_by_concave(
}
BLI_heap_clear(pf_heap, NULL);
- BLI_edgehash_clear_ex(pf_ehash, NULL, BLI_POLYFILL_ALLOC_NGON_RESERVE);
while (faces_double) {
LinkNode *next = faces_double->next;
@@ -201,17 +199,15 @@ void bmo_connect_verts_concave_exec(BMesh *bm, BMOperator *op)
MemArena *pf_arena;
Heap *pf_heap;
- EdgeHash *pf_ehash;
pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
pf_heap = BLI_heap_new_ex(BLI_POLYFILL_ALLOC_NGON_RESERVE);
- pf_ehash = BLI_edgehash_new_ex(__func__, BLI_POLYFILL_ALLOC_NGON_RESERVE);
BMO_ITER (f, &siter, op->slots_in, "faces", BM_FACE) {
if (f->len > 3 && bm_face_convex_tag_verts(f)) {
if (bm_face_split_by_concave(
bm, f, FLT_EPSILON,
- pf_arena, pf_heap, pf_ehash))
+ pf_arena, pf_heap))
{
changed = true;
}
@@ -225,5 +221,4 @@ void bmo_connect_verts_concave_exec(BMesh *bm, BMOperator *op)
BLI_memarena_free(pf_arena);
BLI_heap_free(pf_heap, NULL);
- BLI_edgehash_free(pf_ehash, NULL);
}
diff --git a/source/blender/bmesh/operators/bmo_connect_nonplanar.c b/source/blender/bmesh/operators/bmo_connect_nonplanar.c
index b8acc9d09b8..67590fe8ef9 100644
--- a/source/blender/bmesh/operators/bmo_connect_nonplanar.c
+++ b/source/blender/bmesh/operators/bmo_connect_nonplanar.c
@@ -67,8 +67,8 @@ static bool bm_face_split_find(BMesh *bm, BMFace *f, BMLoop *l_pair[2], float *r
{
BMLoop *l_iter, *l_first;
BMLoop **l_arr = BLI_array_alloca(l_arr, f->len);
- const unsigned int f_len = f->len;
- unsigned int i_a, i_b;
+ const uint f_len = f->len;
+ uint i_a, i_b;
bool found = false;
/* angle finding */
diff --git a/source/blender/bmesh/operators/bmo_connect_pair.c b/source/blender/bmesh/operators/bmo_connect_pair.c
index a73c86fd122..b9e5cd927c3 100644
--- a/source/blender/bmesh/operators/bmo_connect_pair.c
+++ b/source/blender/bmesh/operators/bmo_connect_pair.c
@@ -72,14 +72,15 @@
BMO_vert_flag_test(pc->bm_bmoflag, v, VERT_EXCLUDE) == 0)
#if 0
-#define ELE_TOUCH_TEST(e) \
- (CHECK_TYPE_ANY(e, BMVert *, BMEdge *, BMElem *, BMElemF *), \
- BMO_elem_flag_test(pc->bm_bmoflag, (BMElemF *)e, ELE_TOUCHED))
+#define ELE_TOUCH_TEST(e) ( \
+ CHECK_TYPE_ANY(e, BMVert *, BMEdge *, BMElem *, BMElemF *), \
+ BMO_elem_flag_test(pc->bm_bmoflag, (BMElemF *)e, ELE_TOUCHED) \
+)
#endif
-#define ELE_TOUCH_MARK(e) \
- { CHECK_TYPE_ANY(e, BMVert *, BMEdge *, BMElem *, BMElemF *); \
- BMO_elem_flag_enable(pc->bm_bmoflag, (BMElemF *)e, ELE_TOUCHED); } ((void)0)
-
+#define ELE_TOUCH_MARK(e) { \
+ CHECK_TYPE_ANY(e, BMVert *, BMEdge *, BMElem *, BMElemF *); \
+ BMO_elem_flag_enable(pc->bm_bmoflag, (BMElemF *)e, ELE_TOUCHED); \
+} ((void)0)
#define ELE_TOUCH_TEST_VERT(v) BMO_vert_flag_test(pc->bm_bmoflag, v, ELE_TOUCHED)
// #define ELE_TOUCH_MARK_VERT(v) BMO_vert_flag_enable(pc->bm_bmoflag, (BMElemF *)v, ELE_TOUCHED)
@@ -530,8 +531,8 @@ static void bm_vert_pair_to_matrix(BMVert *v_pair[2], float r_unit_mat[3][3])
float basis_nor_b[3];
/* align normal to direction */
- project_plane_v3_v3v3(basis_nor_a, v_pair[0]->no, basis_dir);
- project_plane_v3_v3v3(basis_nor_b, v_pair[1]->no, basis_dir);
+ project_plane_normalized_v3_v3v3(basis_nor_a, v_pair[0]->no, basis_dir);
+ project_plane_normalized_v3_v3v3(basis_nor_b, v_pair[1]->no, basis_dir);
/* don't normalize before combining so as normals approach the direction, they have less effect (T46784). */
@@ -569,7 +570,7 @@ static void bm_vert_pair_to_matrix(BMVert *v_pair[2], float r_unit_mat[3][3])
float angle_cos_test;
/* project basis dir onto the normal to find its closest angle */
- project_plane_v3_v3v3(basis_dir_proj, basis_dir, l->f->no);
+ project_plane_normalized_v3_v3v3(basis_dir_proj, basis_dir, l->f->no);
if (normalize_v3(basis_dir_proj) > eps) {
angle_cos_test = dot_v3v3(basis_dir_proj, basis_dir);
@@ -586,7 +587,7 @@ static void bm_vert_pair_to_matrix(BMVert *v_pair[2], float r_unit_mat[3][3])
* note: we could add the directions,
* but this more often gives 45d rotated matrix, so just use the best one. */
copy_v3_v3(basis_nor, axis_pair[axis_pair[0].angle_cos < axis_pair[1].angle_cos].nor);
- project_plane_v3_v3v3(basis_nor, basis_nor, basis_dir);
+ project_plane_normalized_v3_v3v3(basis_nor, basis_nor, basis_dir);
cross_v3_v3v3(basis_tmp, basis_dir, basis_nor);
@@ -661,11 +662,11 @@ void bmo_connect_vert_pair_exec(BMesh *bm, BMOperator *op)
while (!BLI_heap_is_empty(pc.states)) {
#ifdef DEBUG_PRINT
- printf("\n%s: stepping %u\n", __func__, BLI_heap_size(pc.states));
+ printf("\n%s: stepping %u\n", __func__, BLI_heap_len(pc.states));
#endif
while (!BLI_heap_is_empty(pc.states)) {
- PathLinkState *state = BLI_heap_popmin(pc.states);
+ PathLinkState *state = BLI_heap_pop_min(pc.states);
/* either we insert this into 'pc.states' or its freed */
bool continue_search;
diff --git a/source/blender/bmesh/operators/bmo_create.c b/source/blender/bmesh/operators/bmo_create.c
index a980baf8626..fa08d009d40 100644
--- a/source/blender/bmesh/operators/bmo_create.c
+++ b/source/blender/bmesh/operators/bmo_create.c
@@ -74,13 +74,13 @@ void bmo_contextual_create_exec(BMesh *bm, BMOperator *op)
BMVert *verts[2];
BMEdge *e;
- BMO_iter_as_array(op->slots_in, "geom", BM_VERT, (void **)verts, 2);
-
- /* create edge */
- e = BM_edge_create(bm, verts[0], verts[1], NULL, BM_CREATE_NO_DOUBLE);
- BMO_edge_flag_enable(bm, e, ELE_OUT);
- tote += 1;
- BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "edges.out", BM_EDGE, ELE_OUT);
+ if (BMO_iter_as_array(op->slots_in, "geom", BM_VERT, (void **)verts, 2) == 2) {
+ /* create edge */
+ e = BM_edge_create(bm, verts[0], verts[1], NULL, BM_CREATE_NO_DOUBLE);
+ BMO_edge_flag_enable(bm, e, ELE_OUT);
+ tote += 1;
+ BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "edges.out", BM_EDGE, ELE_OUT);
+ }
return;
}
@@ -283,13 +283,13 @@ void bmo_contextual_create_exec(BMesh *bm, BMOperator *op)
*/
if (totv > 2) {
/* TODO, some of these vertes may be connected by edges,
- * this connectivity could be used rather then treating
+ * this connectivity could be used rather than treating
* them as a bunch of isolated verts. */
BMVert **vert_arr = MEM_mallocN(sizeof(BMVert *) * totv, __func__);
BMFace *f;
- BMO_iter_as_array(op->slots_in, "geom", BM_VERT, (void **)vert_arr, totv);
+ totv = BMO_iter_as_array(op->slots_in, "geom", BM_VERT, (void **)vert_arr, totv);
BM_verts_sort_radial_plane(vert_arr, totv);
diff --git a/source/blender/bmesh/operators/bmo_dissolve.c b/source/blender/bmesh/operators/bmo_dissolve.c
index 6e3a8a1473d..816d2e8d009 100644
--- a/source/blender/bmesh/operators/bmo_dissolve.c
+++ b/source/blender/bmesh/operators/bmo_dissolve.c
@@ -166,7 +166,7 @@ void bmo_dissolve_faces_exec(BMesh *bm, BMOperator *op)
continue;
}
- BLI_array_empty(faces);
+ BLI_array_clear(faces);
faces = NULL; /* forces different allocatio */
BMW_init(&regwalker, bm, BMW_ISLAND_MANIFOLD,
@@ -179,7 +179,7 @@ void bmo_dissolve_faces_exec(BMesh *bm, BMOperator *op)
}
BMW_end(&regwalker);
- for (i = 0; i < BLI_array_count(faces); i++) {
+ for (i = 0; i < BLI_array_len(faces); i++) {
f_iter = faces[i];
BMO_face_flag_disable(bm, f_iter, FACE_TAG);
BMO_face_flag_enable(bm, f_iter, FACE_ORIG);
@@ -198,7 +198,7 @@ void bmo_dissolve_faces_exec(BMesh *bm, BMOperator *op)
/* track how many faces we should end up with */
int totface_target = bm->totface;
- for (i = 0; i < BLI_array_count(regions); i++) {
+ for (i = 0; i < BLI_array_len(regions); i++) {
BMFace *f_new;
int tot = 0;
@@ -259,7 +259,7 @@ void bmo_dissolve_faces_exec(BMesh *bm, BMOperator *op)
cleanup:
/* free/cleanup */
- for (i = 0; i < BLI_array_count(regions); i++) {
+ for (i = 0; i < BLI_array_len(regions); i++) {
if (regions[i]) MEM_freeN(regions[i]);
}
@@ -309,7 +309,7 @@ void bmo_dissolve_edges_exec(BMesh *bm, BMOperator *op)
BMO_ITER (e, &eiter, op->slots_in, "edges", BM_EDGE) {
BMFace *f_pair[2];
if (BM_edge_face_pair(e, &f_pair[0], &f_pair[1])) {
- unsigned int j;
+ uint j;
for (j = 0; j < 2; j++) {
BMLoop *l_first, *l_iter;
l_iter = l_first = BM_FACE_FIRST_LOOP(f_pair[j]);
diff --git a/source/blender/bmesh/operators/bmo_dupe.c b/source/blender/bmesh/operators/bmo_dupe.c
index 56639a097b6..394faabbd25 100644
--- a/source/blender/bmesh/operators/bmo_dupe.c
+++ b/source/blender/bmesh/operators/bmo_dupe.c
@@ -83,7 +83,7 @@ static BMEdge *bmo_edge_copy(
{
BMEdge *e_dst;
BMVert *e_dst_v1, *e_dst_v2;
- unsigned int rlen;
+ uint rlen;
/* see if any of the neighboring faces are
* not being duplicated. in that case,
@@ -378,6 +378,10 @@ void BMO_dupe_from_flag(BMesh *bm, int htype, const char hflag)
* BMOP_DUPE_VOUTPUT: Buffer containing pointers to the split mesh vertices
* BMOP_DUPE_EOUTPUT: Buffer containing pointers to the split mesh edges
* BMOP_DUPE_FOUTPUT: Buffer containing pointers to the split mesh faces
+ *
+ * \note Lower level uses of this operator may want to use #BM_mesh_separate_faces
+ * Since it's faster for the 'use_only_faces' case.
+ *
*/
void bmo_split_exec(BMesh *bm, BMOperator *op)
{
@@ -385,12 +389,10 @@ void bmo_split_exec(BMesh *bm, BMOperator *op)
BMOperator *splitop = op;
BMOperator dupeop;
- BMOperator delop;
const bool use_only_faces = BMO_slot_bool_get(op->slots_in, "use_only_faces");
/* initialize our sub-operator */
BMO_op_init(bm, &dupeop, op->flag, "duplicate");
- BMO_op_init(bm, &delop, op->flag, "delete");
BMO_slot_copy(splitop, slots_in, "geom",
&dupeop, slots_in, "geom");
@@ -433,24 +435,13 @@ void bmo_split_exec(BMesh *bm, BMOperator *op)
}
/* connect outputs of dupe to delete, exluding keep geometry */
- BMO_slot_int_set(delop.slots_in, "context", DEL_FACES);
- BMO_slot_buffer_from_enabled_flag(bm, &delop, delop.slots_in, "geom", BM_ALL_NOLOOP, SPLIT_INPUT);
-
- BMO_op_exec(bm, &delop);
+ BMO_mesh_delete_oflag_context(bm, SPLIT_INPUT, DEL_FACES);
/* now we make our outputs by copying the dupe output */
BMO_slot_copy(&dupeop, slots_out, "geom.out",
splitop, slots_out, "geom.out");
- BMO_slot_copy(&dupeop, slots_out, "boundary_map.out",
- splitop, slots_out, "boundary_map.out");
-
- BMO_slot_copy(&dupeop, slots_out, "isovert_map.out",
- splitop, slots_out, "isovert_map.out");
-
-
/* cleanup */
- BMO_op_finish(bm, &delop);
BMO_op_finish(bm, &dupeop);
#undef SPLIT_INPUT
diff --git a/source/blender/bmesh/operators/bmo_edgenet.c b/source/blender/bmesh/operators/bmo_edgenet.c
index 64b092da5c8..931ac684b07 100644
--- a/source/blender/bmesh/operators/bmo_edgenet.c
+++ b/source/blender/bmesh/operators/bmo_edgenet.c
@@ -179,22 +179,22 @@ void bmo_edgenet_prepare_exec(BMesh *bm, BMOperator *op)
if (!count) {
edges1 = edges;
- BLI_array_count_set(edges1, BLI_array_count(edges));
+ BLI_array_len_set(edges1, BLI_array_len(edges));
}
else {
edges2 = edges;
- BLI_array_count_set(edges2, BLI_array_count(edges));
+ BLI_array_len_set(edges2, BLI_array_len(edges));
}
- BLI_array_empty(edges);
+ BLI_array_clear(edges);
count++;
}
- if (edges1 && BLI_array_count(edges1) > 2 &&
- BM_edge_share_vert_check(edges1[0], edges1[BLI_array_count(edges1) - 1]))
+ if (edges1 && BLI_array_len(edges1) > 2 &&
+ BM_edge_share_vert_check(edges1[0], edges1[BLI_array_len(edges1) - 1]))
{
- if (edges2 && BLI_array_count(edges2) > 2 &&
- BM_edge_share_vert_check(edges2[0], edges2[BLI_array_count(edges2) - 1]))
+ if (edges2 && BLI_array_len(edges2) > 2 &&
+ BM_edge_share_vert_check(edges2[0], edges2[BLI_array_len(edges2) - 1]))
{
BLI_array_free(edges1);
BLI_array_free(edges2);
@@ -206,8 +206,8 @@ void bmo_edgenet_prepare_exec(BMesh *bm, BMOperator *op)
}
}
- if (edges2 && BLI_array_count(edges2) > 2 &&
- BM_edge_share_vert_check(edges2[0], edges2[BLI_array_count(edges2) - 1]))
+ if (edges2 && BLI_array_len(edges2) > 2 &&
+ BM_edge_share_vert_check(edges2[0], edges2[BLI_array_len(edges2) - 1]))
{
edges2 = NULL;
}
@@ -218,23 +218,23 @@ void bmo_edgenet_prepare_exec(BMesh *bm, BMOperator *op)
float dvec1[3];
float dvec2[3];
- if (BLI_array_count(edges1) == 1) {
+ if (BLI_array_len(edges1) == 1) {
v1 = edges1[0]->v1;
v2 = edges1[0]->v2;
}
else {
v1 = BM_vert_in_edge(edges1[1], edges1[0]->v1) ? edges1[0]->v2 : edges1[0]->v1;
- i = BLI_array_count(edges1) - 1;
+ i = BLI_array_len(edges1) - 1;
v2 = BM_vert_in_edge(edges1[i - 1], edges1[i]->v1) ? edges1[i]->v2 : edges1[i]->v1;
}
- if (BLI_array_count(edges2) == 1) {
+ if (BLI_array_len(edges2) == 1) {
v3 = edges2[0]->v1;
v4 = edges2[0]->v2;
}
else {
v3 = BM_vert_in_edge(edges2[1], edges2[0]->v1) ? edges2[0]->v2 : edges2[0]->v1;
- i = BLI_array_count(edges2) - 1;
+ i = BLI_array_len(edges2) - 1;
v4 = BM_vert_in_edge(edges2[i - 1], edges2[i]->v1) ? edges2[i]->v2 : edges2[i]->v1;
}
@@ -265,9 +265,9 @@ void bmo_edgenet_prepare_exec(BMesh *bm, BMOperator *op)
else if (edges1) {
BMVert *v1, *v2;
- if (BLI_array_count(edges1) > 1) {
+ if (BLI_array_len(edges1) > 1) {
v1 = BM_vert_in_edge(edges1[1], edges1[0]->v1) ? edges1[0]->v2 : edges1[0]->v1;
- i = BLI_array_count(edges1) - 1;
+ i = BLI_array_len(edges1) - 1;
v2 = BM_vert_in_edge(edges1[i - 1], edges1[i]->v1) ? edges1[i]->v2 : edges1[i]->v1;
e = BM_edge_create(bm, v1, v2, NULL, BM_CREATE_NO_DOUBLE);
BMO_edge_flag_enable(bm, e, ELE_NEW);
diff --git a/source/blender/bmesh/operators/bmo_fill_attribute.c b/source/blender/bmesh/operators/bmo_fill_attribute.c
index 233ed746ed4..dcf2570dff4 100644
--- a/source/blender/bmesh/operators/bmo_fill_attribute.c
+++ b/source/blender/bmesh/operators/bmo_fill_attribute.c
@@ -91,7 +91,7 @@ static void bm_face_copy_shared_all(
/**
* Flood fill attributes.
*/
-static unsigned int bmesh_face_attribute_fill(
+static uint bmesh_face_attribute_fill(
BMesh *bm,
const bool use_normals, const bool use_data)
{
@@ -102,7 +102,7 @@ static unsigned int bmesh_face_attribute_fill(
BMIter iter;
BMLoop *l;
- unsigned int face_tot = 0;
+ uint face_tot = 0;
BLI_LINKSTACK_INIT(loop_queue_prev);
diff --git a/source/blender/bmesh/operators/bmo_fill_grid.c b/source/blender/bmesh/operators/bmo_fill_grid.c
index 04ae915b707..dc4ebf50754 100644
--- a/source/blender/bmesh/operators/bmo_fill_grid.c
+++ b/source/blender/bmesh/operators/bmo_fill_grid.c
@@ -187,15 +187,15 @@ static void bm_loop_interp_from_grid_boundary_2(BMesh *bm, BMLoop *l, BMLoop *l_
* Avoids calling #barycentric_weights_v2_quad often by caching weights into an array.
*/
static void barycentric_weights_v2_grid_cache(
- const unsigned int xtot, const unsigned int ytot,
+ const uint xtot, const uint ytot,
float (*weight_table)[4])
{
float x_step = 1.0f / (float)(xtot - 1);
float y_step = 1.0f / (float)(ytot - 1);
- unsigned int i = 0;
+ uint i = 0;
float xy_fl[2];
- unsigned int x, y;
+ uint x, y;
for (y = 0; y < ytot; y++) {
xy_fl[1] = y_step * (float)y;
for (x = 0; x < xtot; x++) {
@@ -219,13 +219,13 @@ static void barycentric_weights_v2_grid_cache(
* \param v_grid 2d array of verts, all boundary verts must be set, we fill in the middle.
*/
static void bm_grid_fill_array(
- BMesh *bm, BMVert **v_grid, const unsigned int xtot, unsigned const int ytot,
+ BMesh *bm, BMVert **v_grid, const uint xtot, unsigned const int ytot,
const short mat_nr, const bool use_smooth,
const bool use_flip, const bool use_interp_simple)
{
const bool use_vert_interp = CustomData_has_interp(&bm->vdata);
const bool use_loop_interp = CustomData_has_interp(&bm->ldata);
- unsigned int x, y;
+ uint x, y;
/* for use_loop_interp */
BMLoop *((*larr_x_a)[2]), *((*larr_x_b)[2]), *((*larr_y_a)[2]), *((*larr_y_b)[2]);
@@ -393,7 +393,7 @@ static void bm_grid_fill_array(
BMLoop *l_quad[4];
BMLoop *l_bound[4];
BMLoop *l_tmp;
- unsigned int x_side, y_side, i;
+ uint x_side, y_side, i;
char interp_from;
@@ -496,12 +496,12 @@ static void bm_grid_fill(
{
#define USE_FLIP_DETECT
- const unsigned int xtot = (unsigned int)BM_edgeloop_length_get(estore_a);
- const unsigned int ytot = (unsigned int)BM_edgeloop_length_get(estore_rail_a);
+ const uint xtot = (uint)BM_edgeloop_length_get(estore_a);
+ const uint ytot = (uint)BM_edgeloop_length_get(estore_rail_a);
//BMVert *v;
- unsigned int i;
+ uint i;
#ifdef DEBUG
- unsigned int x, y;
+ uint x, y;
#endif
LinkData *el;
bool use_flip = false;
diff --git a/source/blender/bmesh/operators/bmo_fill_holes.c b/source/blender/bmesh/operators/bmo_fill_holes.c
index eadfbdb1aa8..869994a98b9 100644
--- a/source/blender/bmesh/operators/bmo_fill_holes.c
+++ b/source/blender/bmesh/operators/bmo_fill_holes.c
@@ -36,7 +36,7 @@
void bmo_holes_fill_exec(BMesh *bm, BMOperator *op)
{
BMOperator op_attr;
- const unsigned int sides = BMO_slot_int_get(op->slots_in, "sides");
+ const uint sides = BMO_slot_int_get(op->slots_in, "sides");
BM_mesh_elem_hflag_disable_all(bm, BM_EDGE | BM_FACE, BM_ELEM_TAG, false);
diff --git a/source/blender/bmesh/operators/bmo_hull.c b/source/blender/bmesh/operators/bmo_hull.c
index 81ec2860cf7..d52cb00e172 100644
--- a/source/blender/bmesh/operators/bmo_hull.c
+++ b/source/blender/bmesh/operators/bmo_hull.c
@@ -521,7 +521,7 @@ static void hull_from_bullet(
int j;
/* Get face vertex indices */
- BLI_array_empty(fvi);
+ BLI_array_clear(fvi);
BLI_array_grow_items(fvi, len);
plConvexHullGetFaceVertices(hull, i, fvi);
diff --git a/source/blender/bmesh/operators/bmo_inset.c b/source/blender/bmesh/operators/bmo_inset.c
index e2ff09669d7..a64c6d74a93 100644
--- a/source/blender/bmesh/operators/bmo_inset.c
+++ b/source/blender/bmesh/operators/bmo_inset.c
@@ -275,7 +275,7 @@ static void bmo_face_inset_individual(
BMLoop *l_iter, *l_first;
BMLoop *l_other;
- unsigned int i;
+ uint i;
float e_length_prev;
l_first = BM_FACE_FIRST_LOOP(f);
@@ -663,7 +663,7 @@ void bmo_inset_region_exec(BMesh *bm, BMOperator *op)
/* run the separate arg */
if (!BM_edge_is_boundary(es->e_old)) {
- bmesh_edge_separate(bm, es->e_old, es->l, false);
+ bmesh_kernel_edge_separate(bm, es->e_old, es->l, false);
}
/* calc edge-split info */
@@ -742,7 +742,7 @@ void bmo_inset_region_exec(BMesh *bm, BMOperator *op)
/* disable touching twice, this _will_ happen if the flags not disabled */
BM_elem_flag_disable(v, BM_ELEM_TAG);
- bmesh_vert_separate(bm, v, &vout, &r_vout_len, false);
+ bmesh_kernel_vert_separate(bm, v, &vout, &r_vout_len, false);
v = NULL; /* don't use again */
/* in some cases the edge doesn't split off */
diff --git a/source/blender/bmesh/operators/bmo_join_triangles.c b/source/blender/bmesh/operators/bmo_join_triangles.c
index 655fb346976..b1053e6d8c2 100644
--- a/source/blender/bmesh/operators/bmo_join_triangles.c
+++ b/source/blender/bmesh/operators/bmo_join_triangles.c
@@ -132,11 +132,11 @@ struct DelimitData_CD {
};
struct DelimitData {
- unsigned int do_seam : 1;
- unsigned int do_sharp : 1;
- unsigned int do_mat : 1;
- unsigned int do_angle_face : 1;
- unsigned int do_angle_shape : 1;
+ uint do_seam : 1;
+ uint do_sharp : 1;
+ uint do_mat : 1;
+ uint do_angle_face : 1;
+ uint do_angle_shape : 1;
float angle_face;
float angle_face__cos;
@@ -270,9 +270,9 @@ void bmo_join_triangles_exec(BMesh *bm, BMOperator *op)
BMFace *f;
BMEdge *e;
/* data: edge-to-join, sort_value: error weight */
- struct SortPointerByFloat *jedges;
+ struct SortPtrByFloat *jedges;
unsigned i, totedge;
- unsigned int totedge_tag = 0;
+ uint totedge_tag = 0;
struct DelimitData delimit_data = {0};
diff --git a/source/blender/bmesh/operators/bmo_mesh_conv.c b/source/blender/bmesh/operators/bmo_mesh_conv.c
index 0eb9bf90ca8..7311ed5ce64 100644
--- a/source/blender/bmesh/operators/bmo_mesh_conv.c
+++ b/source/blender/bmesh/operators/bmo_mesh_conv.c
@@ -62,15 +62,18 @@ void bmo_object_load_bmesh_exec(BMesh *bm, BMOperator *op)
Mesh *me = ob->data;
BMO_op_callf(bm, op->flag,
- "bmesh_to_mesh mesh=%p object=%p skip_tessface=%b",
- me, ob, true);
+ "bmesh_to_mesh mesh=%p object=%p",
+ me, ob);
}
void bmo_bmesh_to_mesh_exec(BMesh *bm, BMOperator *op)
{
Mesh *me = BMO_slot_ptr_get(op->slots_in, "mesh");
/* Object *ob = BMO_slot_ptr_get(op, "object"); */
- const bool dotess = !BMO_slot_bool_get(op->slots_in, "skip_tessface");
- BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){ .calc_tessface = dotess, }));
+ BM_mesh_bm_to_me(
+ bm, me,
+ (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
}
diff --git a/source/blender/bmesh/operators/bmo_offset_edgeloops.c b/source/blender/bmesh/operators/bmo_offset_edgeloops.c
index 7a6f779b34f..d54efc27124 100644
--- a/source/blender/bmesh/operators/bmo_offset_edgeloops.c
+++ b/source/blender/bmesh/operators/bmo_offset_edgeloops.c
@@ -33,7 +33,7 @@
#include "BLI_math.h"
#include "BLI_alloca.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BKE_customdata.h"
@@ -242,6 +242,7 @@ void bmo_offset_edgeloops_exec(BMesh *bm, BMOperator *op)
#if 0
else if (BM_elem_index_get(l->prev->v) == -1) {
if (BM_elem_index_get(l->next->next->v) == -1) {
+ /* pass */
}
}
#endif
@@ -270,7 +271,7 @@ void bmo_offset_edgeloops_exec(BMesh *bm, BMOperator *op)
v_other = BM_edge_other_vert(e, v);
if (BM_elem_index_get(v_other) == -1) {
if (BM_vert_is_edge_pair(v_other)) {
- /* defer bmesh_jekv to avoid looping over data we're removing */
+ /* defer bmesh_kernel_join_edge_kill_vert to avoid looping over data we're removing */
v_other->e = e;
STACK_PUSH(varr, v_other);
}
@@ -278,7 +279,7 @@ void bmo_offset_edgeloops_exec(BMesh *bm, BMOperator *op)
}
while ((v = STACK_POP(varr))) {
- bmesh_jekv(bm, v->e, v, true, false, false);
+ bmesh_kernel_join_edge_kill_vert(bm, v->e, v, true, false, false);
}
}
}
diff --git a/source/blender/bmesh/operators/bmo_primitive.c b/source/blender/bmesh/operators/bmo_primitive.c
index 723e0b168e0..95d61763902 100644
--- a/source/blender/bmesh/operators/bmo_primitive.c
+++ b/source/blender/bmesh/operators/bmo_primitive.c
@@ -760,11 +760,13 @@ void bmo_create_grid_exec(BMesh *bm, BMOperator *op)
BMOpSlot *slot_verts_out = BMO_slot_get(op->slots_out, "verts.out");
const float dia = BMO_slot_float_get(op->slots_in, "size");
- const unsigned int xtot = max_ii(2, BMO_slot_int_get(op->slots_in, "x_segments"));
- const unsigned int ytot = max_ii(2, BMO_slot_int_get(op->slots_in, "y_segments"));
+ const uint xtot = max_ii(2, BMO_slot_int_get(op->slots_in, "x_segments"));
+ const uint ytot = max_ii(2, BMO_slot_int_get(op->slots_in, "y_segments"));
const float xtot_inv2 = 2.0f / (xtot - 1);
const float ytot_inv2 = 2.0f / (ytot - 1);
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
BMVert **varr;
BMVert *vquad[4];
@@ -772,7 +774,7 @@ void bmo_create_grid_exec(BMesh *bm, BMOperator *op)
float mat[4][4];
float vec[3], tvec[3];
- unsigned int x, y, i;
+ uint x, y, i;
BMO_slot_mat4_get(op->slots_in, "matrix", mat);
@@ -814,7 +816,7 @@ void bmo_create_grid_exec(BMesh *bm, BMOperator *op)
#undef XY
if (calc_uvs) {
- BM_mesh_calc_uvs_grid(bm, xtot, ytot, FACE_MARK);
+ BM_mesh_calc_uvs_grid(bm, xtot, ytot, FACE_MARK, cd_loop_uv_offset);
}
}
@@ -826,7 +828,9 @@ void bmo_create_grid_exec(BMesh *bm, BMOperator *op)
* \param y_segments The y-resolution of the grid
* \param oflag The flag to check faces with.
*/
-void BM_mesh_calc_uvs_grid(BMesh *bm, const unsigned int x_segments, const unsigned int y_segments, const short oflag)
+void BM_mesh_calc_uvs_grid(
+ BMesh *bm, const uint x_segments, const uint y_segments,
+ const short oflag, const int cd_loop_uv_offset)
{
BMFace *f;
BMLoop *l;
@@ -835,9 +839,7 @@ void BM_mesh_calc_uvs_grid(BMesh *bm, const unsigned int x_segments, const unsig
const float dx = 1.0f / (float)(x_segments - 1);
const float dy = 1.0f / (float)(y_segments - 1);
float x = 0.0f;
- float y = 0.0f;
-
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ float y = dy;
int loop_index;
@@ -852,16 +854,16 @@ void BM_mesh_calc_uvs_grid(BMesh *bm, const unsigned int x_segments, const unsig
switch (loop_index) {
case 0:
- x += dx;
+ y -= dy;
break;
case 1:
- y += dy;
+ x += dx;
break;
case 2:
- x -= dx;
+ y += dy;
break;
case 3:
- y -= dy;
+ x -= dx;
break;
default:
break;
@@ -884,7 +886,9 @@ void bmo_create_uvsphere_exec(BMesh *bm, BMOperator *op)
const float dia = BMO_slot_float_get(op->slots_in, "diameter");
const int seg = BMO_slot_int_get(op->slots_in, "u_segments");
const int tot = BMO_slot_int_get(op->slots_in, "v_segments");
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
BMOperator bmop, prevop;
BMVert *eve, *preveve;
@@ -982,7 +986,7 @@ void bmo_create_uvsphere_exec(BMesh *bm, BMOperator *op)
}
}
- BM_mesh_calc_uvs_sphere(bm, FACE_MARK);
+ BM_mesh_calc_uvs_sphere(bm, FACE_MARK, cd_loop_uv_offset);
}
/* and now do imat */
@@ -1000,7 +1004,9 @@ void bmo_create_icosphere_exec(BMesh *bm, BMOperator *op)
const float dia = BMO_slot_float_get(op->slots_in, "diameter");
const float dia_div = dia / 200.0f;
const int subdiv = BMO_slot_int_get(op->slots_in, "subdivisions");
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
BMVert *eva[12];
BMVert *v;
@@ -1026,7 +1032,6 @@ void bmo_create_icosphere_exec(BMesh *bm, BMOperator *op)
}
int uvi = 0;
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
for (a = 0; a < 20; a++) {
BMFace *f;
BMVert *v1, *v2, *v3;
@@ -1157,13 +1162,13 @@ static void bm_mesh_calc_uvs_sphere_face(BMFace *f, const int cd_loop_uv_offset)
* \param bm The BMesh to operate on
* \param oflag The flag to check faces with.
*/
-void BM_mesh_calc_uvs_sphere(BMesh *bm, const short oflag)
+void BM_mesh_calc_uvs_sphere(
+ BMesh *bm,
+ const short oflag, const int cd_loop_uv_offset)
{
BMFace *f;
BMIter iter;
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
-
BLI_assert(cd_loop_uv_offset != -1); /* caller is responsible for giving us UVs */
BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
@@ -1206,7 +1211,9 @@ void bmo_create_monkey_exec(BMesh *bm, BMOperator *op)
int i;
BMO_slot_mat4_get(op->slots_in, "matrix", mat);
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
for (i = 0; i < monkeynv; i++) {
float v[3];
@@ -1234,7 +1241,6 @@ void bmo_create_monkey_exec(BMesh *bm, BMOperator *op)
}
int uvi = 0;
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
for (i = 0; i < monkeynf; i++) {
BMFace *f_new_a = BM_face_create_quad_tri(bm,
tv[monkeyf[i][0] + i - monkeyo],
@@ -1279,11 +1285,13 @@ void bmo_create_monkey_exec(BMesh *bm, BMOperator *op)
void bmo_create_circle_exec(BMesh *bm, BMOperator *op)
{
- const float dia = BMO_slot_float_get(op->slots_in, "diameter");
+ const float radius = BMO_slot_float_get(op->slots_in, "radius");
const int segs = BMO_slot_int_get(op->slots_in, "segments");
const bool cap_ends = BMO_slot_bool_get(op->slots_in, "cap_ends");
const bool cap_tris = BMO_slot_bool_get(op->slots_in, "cap_tris");
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
BMVert *v1, *lastv1 = NULL, *cent1, *firstv1 = NULL;
float vec[3], mat[4][4], phi, phid;
@@ -1307,8 +1315,8 @@ void bmo_create_circle_exec(BMesh *bm, BMOperator *op)
for (a = 0; a < segs; a++, phi += phid) {
/* Going this way ends up with normal(s) upward */
- vec[0] = -dia * sinf(phi);
- vec[1] = dia * cosf(phi);
+ vec[0] = -radius * sinf(phi);
+ vec[1] = radius * cosf(phi);
vec[2] = 0.0f;
mul_m4_v3(mat, vec);
v1 = BM_vert_create(bm, vec, NULL, BM_CREATE_NOP);
@@ -1343,7 +1351,7 @@ void bmo_create_circle_exec(BMesh *bm, BMOperator *op)
BMO_face_flag_enable(bm, f, FACE_NEW);
if (calc_uvs) {
- BM_mesh_calc_uvs_circle(bm, mat, dia, FACE_NEW);
+ BM_mesh_calc_uvs_circle(bm, mat, radius, FACE_NEW, cd_loop_uv_offset);
}
}
@@ -1362,14 +1370,14 @@ void bmo_create_circle_exec(BMesh *bm, BMOperator *op)
* \param radius The size of the circle.
* \param oflag The flag to check faces with.
*/
-void BM_mesh_calc_uvs_circle(BMesh *bm, float mat[4][4], const float radius, const short oflag)
+void BM_mesh_calc_uvs_circle(
+ BMesh *bm, float mat[4][4], const float radius,
+ const short oflag, const int cd_loop_uv_offset)
{
BMFace *f;
BMLoop *l;
BMIter fiter, liter;
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
-
const float uv_scale = 0.5f / radius;
const float uv_center = 0.5f;
@@ -1409,7 +1417,9 @@ void bmo_create_cone_exec(BMesh *bm, BMOperator *op)
int segs = BMO_slot_int_get(op->slots_in, "segments");
const bool cap_ends = BMO_slot_bool_get(op->slots_in, "cap_ends");
const bool cap_tris = BMO_slot_bool_get(op->slots_in, "cap_tris");
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
int a;
if (!segs)
@@ -1506,7 +1516,7 @@ void bmo_create_cone_exec(BMesh *bm, BMOperator *op)
}
if (calc_uvs) {
- BM_mesh_calc_uvs_cone(bm, mat, dia2, dia1, segs, cap_ends, FACE_MARK);
+ BM_mesh_calc_uvs_cone(bm, mat, dia2, dia1, segs, cap_ends, FACE_MARK, cd_loop_uv_offset);
}
if (!cap_tris) {
@@ -1530,12 +1540,12 @@ void bmo_create_cone_exec(BMesh *bm, BMOperator *op)
*/
void BM_mesh_calc_uvs_cone(
BMesh *bm, float mat[4][4],
- const float radius_top, const float radius_bottom, const int segments, const bool cap_ends, const short oflag)
+ const float radius_top, const float radius_bottom, const int segments, const bool cap_ends,
+ const short oflag, const int cd_loop_uv_offset)
{
BMFace *f;
BMLoop *l;
BMIter fiter, liter;
- const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
const float uv_width = 1.0f / (float)segments;
const float uv_height = cap_ends ? 0.5f : 1.0f;
@@ -1566,7 +1576,7 @@ void BM_mesh_calc_uvs_cone(
BLI_assert(cd_loop_uv_offset != -1); /* caller is responsible for ensuring the mesh has UVs */
- x = 0.0f;
+ x = 1.0f;
y = 1.0f - uv_height;
BM_ITER_MESH (f, &fiter, bm, BM_FACES_OF_MESH) {
@@ -1580,7 +1590,7 @@ void BM_mesh_calc_uvs_cone(
switch (loop_index) {
case 0:
- x += uv_width;
+ /* Continue in the last position */
break;
case 1:
y += uv_height;
@@ -1598,8 +1608,6 @@ void BM_mesh_calc_uvs_cone(
luv->uv[0] = x;
luv->uv[1] = y;
}
-
- x += uv_width;
}
else {
/* top or bottom face - so unwrap it by transforming back to a circle and using the X/Y coords */
@@ -1629,8 +1637,10 @@ void bmo_create_cube_exec(BMesh *bm, BMOperator *op)
BMVert *verts[8];
float mat[4][4];
float off = BMO_slot_float_get(op->slots_in, "size") / 2.0f;
- const bool calc_uvs = BMO_slot_bool_get(op->slots_in, "calc_uvs");
- int i, x, y, z;
+
+ const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
+ const bool calc_uvs = (cd_loop_uv_offset != -1) && BMO_slot_bool_get(op->slots_in, "calc_uvs");
+
/* rotation order set to match 'BM_mesh_calc_uvs_cube' */
const char faces[6][4] = {
{0, 1, 3, 2},
@@ -1644,11 +1654,11 @@ void bmo_create_cube_exec(BMesh *bm, BMOperator *op)
BMO_slot_mat4_get(op->slots_in, "matrix", mat);
if (!off) off = 0.5f;
- i = 0;
+ int i = 0;
- for (x = -1; x < 2; x += 2) {
- for (y = -1; y < 2; y += 2) {
- for (z = -1; z < 2; z += 2) {
+ for (int x = -1; x < 2; x += 2) {
+ for (int y = -1; y < 2; y += 2) {
+ for (int z = -1; z < 2; z += 2) {
float vec[3] = {(float)x * off, (float)y * off, (float)z * off};
mul_m4_v3(mat, vec);
verts[i] = BM_vert_create(bm, vec, NULL, BM_CREATE_NOP);
diff --git a/source/blender/bmesh/operators/bmo_removedoubles.c b/source/blender/bmesh/operators/bmo_removedoubles.c
index 0ad8247e539..e85751531ae 100644
--- a/source/blender/bmesh/operators/bmo_removedoubles.c
+++ b/source/blender/bmesh/operators/bmo_removedoubles.c
@@ -30,7 +30,8 @@
#include "BLI_math.h"
#include "BLI_alloca.h"
-#include "BLI_stackdefines.h"
+#include "BLI_kdtree.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_stack.h"
#include "BKE_customdata.h"
@@ -153,7 +154,7 @@ static BMFace *remdoubles_createface(BMesh *bm, BMFace *f, BMOpSlot *slot_target
finally:
{
- unsigned int i;
+ uint i;
for (i = 0; i < STACK_SIZE(verts); i++) {
BMO_vert_flag_disable(bm, verts[i], VERT_IN_FACE);
}
@@ -165,7 +166,7 @@ finally:
BLI_assert(f_new != f);
if (f_new) {
- unsigned int i = 0;
+ uint i = 0;
BMLoop *l_iter, *l_first;
l_iter = l_first = BM_FACE_FIRST_LOOP(f_new);
do {
@@ -277,22 +278,7 @@ void bmo_weld_verts_exec(BMesh *bm, BMOperator *op)
BMO_mesh_delete_oflag_context(bm, ELE_DEL, DEL_ONLYTAGGED);
}
-static int vergaverco(const void *e1, const void *e2)
-{
- const BMVert *v1 = *(const void **)e1, *v2 = *(const void **)e2;
- float x1 = v1->co[0] + v1->co[1] + v1->co[2];
- float x2 = v2->co[0] + v2->co[1] + v2->co[2];
-
- if (x1 > x2) return 1;
- else if (x1 < x2) return -1;
- else return 0;
-}
-
-// #define VERT_TESTED 1 // UNUSED
-#define VERT_DOUBLE 2
-#define VERT_TARGET 4
#define VERT_KEEP 8
-// #define VERT_MARK 16 // UNUSED
#define VERT_IN 32
#define EDGE_MARK 1
@@ -440,20 +426,24 @@ void bmo_collapse_exec(BMesh *bm, BMOperator *op)
edge_stack = BLI_stack_new(sizeof(BMEdge *), __func__);
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
- float min[3], max[3], center[3];
+ float center[3];
+ int count = 0;
BMVert *v_tar;
+ zero_v3(center);
+
if (!BMO_edge_flag_test(bm, e, EDGE_MARK))
continue;
BLI_assert(BLI_stack_is_empty(edge_stack));
- INIT_MINMAX(min, max);
for (e = BMW_begin(&walker, e->v1); e; e = BMW_step(&walker)) {
BLI_stack_push(edge_stack, &e);
- minmax_v3v3_v3(min, max, e->v1->co);
- minmax_v3v3_v3(min, max, e->v2->co);
+ add_v3_v3(center, e->v1->co);
+ add_v3_v3(center, e->v2->co);
+
+ count += 2;
/* prevent adding to slot_targetmap multiple times */
BM_elem_flag_disable(e->v1, BM_ELEM_TAG);
@@ -461,15 +451,14 @@ void bmo_collapse_exec(BMesh *bm, BMOperator *op)
}
if (!BLI_stack_is_empty(edge_stack)) {
-
- mid_v3_v3v3(center, min, max);
+ mul_v3_fl(center, 1.0f / count);
/* snap edges to a point. for initial testing purposes anyway */
e = *(BMEdge **)BLI_stack_peek(edge_stack);
v_tar = e->v1;
while (!BLI_stack_is_empty(edge_stack)) {
- unsigned int j;
+ uint j;
BLI_stack_pop(edge_stack, &e);
for (j = 0; j < 2; j++) {
@@ -581,77 +570,62 @@ static void bmesh_find_doubles_common(
BMesh *bm, BMOperator *op,
BMOperator *optarget, BMOpSlot *optarget_slot)
{
- BMVert **verts;
- int verts_len;
+ const BMOpSlot *slot_verts = BMO_slot_get(op->slots_in, "verts");
+ BMVert * const *verts = (BMVert **)slot_verts->data.buf;
+ const int verts_len = slot_verts->len;
- int i, j, keepvert = 0;
+ bool has_keep_vert = false;
+ bool found_duplicates = false;
const float dist = BMO_slot_float_get(op->slots_in, "dist");
- const float dist_sq = dist * dist;
- const float dist3 = ((float)M_SQRT3 + 0.00005f) * dist; /* Just above sqrt(3) */
/* Test whether keep_verts arg exists and is non-empty */
if (BMO_slot_exists(op->slots_in, "keep_verts")) {
BMOIter oiter;
- keepvert = BMO_iter_new(&oiter, op->slots_in, "keep_verts", BM_VERT) != NULL;
+ has_keep_vert = BMO_iter_new(&oiter, op->slots_in, "keep_verts", BM_VERT) != NULL;
}
- /* get the verts as an array we can sort */
- verts = BMO_slot_as_arrayN(op->slots_in, "verts", &verts_len);
-
- /* sort by vertex coordinates added together */
- qsort(verts, verts_len, sizeof(BMVert *), vergaverco);
-
/* Flag keep_verts */
- if (keepvert) {
+ if (has_keep_vert) {
BMO_slot_buffer_flag_enable(bm, op->slots_in, "keep_verts", BM_VERT, VERT_KEEP);
}
- for (i = 0; i < verts_len; i++) {
- BMVert *v_check = verts[i];
-
- if (BMO_vert_flag_test(bm, v_check, VERT_DOUBLE | VERT_TARGET)) {
- continue;
+ int *duplicates = MEM_mallocN(sizeof(int) * verts_len, __func__);
+ {
+ KDTree *tree = BLI_kdtree_new(verts_len);
+ for (int i = 0; i < verts_len; i++) {
+ BLI_kdtree_insert(tree, i, verts[i]->co);
+ if (has_keep_vert && BMO_vert_flag_test(bm, verts[i], VERT_KEEP)) {
+ duplicates[i] = i;
+ }
+ else {
+ duplicates[i] = -1;
+ }
}
- for (j = i + 1; j < verts_len; j++) {
- BMVert *v_other = verts[j];
-
- /* a match has already been found, (we could check which is best, for now don't) */
- if (BMO_vert_flag_test(bm, v_other, VERT_DOUBLE | VERT_TARGET)) {
- continue;
- }
+ BLI_kdtree_balance(tree);
+ found_duplicates = BLI_kdtree_calc_duplicates_fast(tree, dist, false, duplicates) != 0;
+ BLI_kdtree_free(tree);
+ }
- /* Compare sort values of the verts using 3x tolerance (allowing for the tolerance
- * on each of the three axes). This avoids the more expensive length comparison
- * for most vertex pairs. */
- if ((v_other->co[0] + v_other->co[1] + v_other->co[2]) -
- (v_check->co[0] + v_check->co[1] + v_check->co[2]) > dist3)
- {
- break;
+ if (found_duplicates) {
+ for (int i = 0; i < verts_len; i++) {
+ BMVert *v_check = verts[i];
+ if (duplicates[i] == -1) {
+ /* nop (others can use as target) */
}
-
- if (keepvert) {
- if (BMO_vert_flag_test(bm, v_other, VERT_KEEP) == BMO_vert_flag_test(bm, v_check, VERT_KEEP))
- continue;
+ else if (duplicates[i] == i) {
+ /* keep (others can use as target) */
}
-
- if (compare_len_squared_v3v3(v_check->co, v_other->co, dist_sq)) {
-
- /* If one vert is marked as keep, make sure it will be the target */
- if (BMO_vert_flag_test(bm, v_other, VERT_KEEP)) {
- SWAP(BMVert *, v_check, v_other);
- }
-
- BMO_vert_flag_enable(bm, v_other, VERT_DOUBLE);
- BMO_vert_flag_enable(bm, v_check, VERT_TARGET);
-
- BMO_slot_map_elem_insert(optarget, optarget_slot, v_other, v_check);
+ else {
+ BMVert *v_other = verts[duplicates[i]];
+ BLI_assert(ELEM(duplicates[duplicates[i]], -1, duplicates[i]));
+ BMO_slot_map_elem_insert(optarget, optarget_slot, v_check, v_other);
}
}
}
- MEM_freeN(verts);
+ MEM_freeN(duplicates);
}
void bmo_remove_doubles_exec(BMesh *bm, BMOperator *op)
diff --git a/source/blender/bmesh/operators/bmo_rotate_edges.c b/source/blender/bmesh/operators/bmo_rotate_edges.c
new file mode 100644
index 00000000000..75e31c68dae
--- /dev/null
+++ b/source/blender/bmesh/operators/bmo_rotate_edges.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/operators/bmo_rotate_edges.c
+ * \ingroup bmesh
+ *
+ * Rotate edges topology that share two faces.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+#include "BLI_heap.h"
+
+#include "bmesh.h"
+
+#include "intern/bmesh_operators_private.h" /* own include */
+
+#define EDGE_OUT 1
+#define FACE_MARK 1
+
+/**
+ * Rotate edges where every edge has it's own faces (we can rotate in any order).
+ */
+static void bm_rotate_edges_simple(
+ BMesh *bm, BMOperator *op,
+ const short check_flag, const bool use_ccw)
+{
+ BMOIter siter;
+ BMEdge *e;
+
+ BMO_ITER (e, &siter, op->slots_in, "edges", BM_EDGE) {
+ /**
+ * this ends up being called twice, could add option to not to call check in
+ * #BM_edge_rotate to get some extra speed */
+ if (BM_edge_rotate_check(e)) {
+ BMEdge *e_rotate = BM_edge_rotate(bm, e, use_ccw, check_flag);
+ if (e_rotate != NULL) {
+ BMO_edge_flag_enable(bm, e_rotate, EDGE_OUT);
+ }
+ }
+ }
+}
+
+
+/**
+ * Edge length is just a way of ordering that's independent of order in the edges argument,
+ * we could use some other method since ideally all edges will be rotated,
+ * this just happens to be simple to calculate.
+ */
+static float bm_edge_calc_rotate_cost(const BMEdge *e)
+{
+ return -BM_edge_calc_length_squared(e);
+}
+
+/**
+ * Check if this edge is a boundary: Are more than one of the connected faces edges rotating too?
+ */
+static float bm_edge_rotate_is_boundary(const BMEdge *e)
+{
+ /* Number of adjacent shared faces. */
+ int count = 0;
+ BMLoop *l_radial_iter = e->l;
+ do {
+ /* Skip this edge. */
+ BMLoop *l_iter = l_radial_iter->next;
+ do {
+ BMEdge *e_iter = l_iter->e;
+ const int e_iter_index = BM_elem_index_get(e_iter);
+ if ((e_iter_index != -1)) {
+ if (count == 1) {
+ return false;
+ }
+ count += 1;
+ break;
+ }
+ } while ((l_iter = l_iter->next) != l_radial_iter);
+ } while ((l_radial_iter = l_radial_iter->radial_next) != e->l);
+ return true;
+}
+
+/**
+ * Rotate edges where edges share faces,
+ * edges which could not rotate need to be re-considered after neighbors are rotated.
+ */
+static void bm_rotate_edges_shared(
+ BMesh *bm, BMOperator *op,
+ short check_flag, const bool use_ccw, const int edges_len)
+{
+ Heap *heap = BLI_heap_new_ex(edges_len);
+ HeapNode **eheap_table = MEM_mallocN(sizeof(*eheap_table) * edges_len, __func__);
+ int edges_len_rotate = 0;
+
+ {
+ BMIter iter;
+ BMEdge *e;
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ BM_elem_index_set(e, -1); /* set_dirty! */
+ }
+ bm->elem_index_dirty |= BM_EDGE;
+ }
+
+ {
+ BMOIter siter;
+ BMEdge *e;
+ uint i;
+ BMO_ITER_INDEX (e, &siter, op->slots_in, "edges", BM_EDGE, i) {
+ BM_elem_index_set(e, BM_edge_is_manifold(e) ? i : -1); /* set_dirty! */
+ eheap_table[i] = NULL;
+ }
+ }
+
+ /* First operate on boundary edges, this is often all that's needed,
+ * regions that have no boundaries are handles after. */
+ enum {
+ PASS_TYPE_BOUNDARY = 0,
+ PASS_TYPE_ALL = 1,
+ PASS_TYPE_DONE = 2,
+ };
+ uint pass_type = PASS_TYPE_BOUNDARY;
+
+
+ while ((pass_type != PASS_TYPE_DONE) && (edges_len_rotate != edges_len)) {
+ BLI_assert(BLI_heap_is_empty(heap));
+ {
+ BMOIter siter;
+ BMEdge *e;
+ uint i;
+ BMO_ITER_INDEX (e, &siter, op->slots_in, "edges", BM_EDGE, i) {
+ BLI_assert(eheap_table[i] == NULL);
+
+ bool ok = (BM_elem_index_get(e) != -1) && BM_edge_rotate_check(e);
+
+ if (ok) {
+ if (pass_type == PASS_TYPE_BOUNDARY) {
+ ok = bm_edge_rotate_is_boundary(e);
+ }
+ }
+
+ if (ok) {
+ float cost = bm_edge_calc_rotate_cost(e);
+ if (pass_type == PASS_TYPE_BOUNDARY) {
+ /* Trick to ensure once started, non boundaries are handled before other boundary edges.
+ * This means the first longest boundary defines the starting point which is rotated
+ * until all its connected edges are exhausted and the next boundary is popped off the heap.
+ *
+ * Without this we may rotate from different starting points and meet in the middle
+ * with obviously uneven topology.
+ *
+ * Move from negative to positive value, inverting so large values are still handled first.
+ */
+ cost = cost != 0.0f ? -1.0f / cost : FLT_MAX;
+ }
+ eheap_table[i] = BLI_heap_insert(heap, cost, e);
+ }
+ }
+ }
+
+ if (BLI_heap_is_empty(heap)) {
+ pass_type += 1;
+ continue;
+ }
+
+ const int edges_len_rotate_prev = edges_len_rotate;
+ while (!BLI_heap_is_empty(heap)) {
+ BMEdge *e_best = BLI_heap_pop_min(heap);
+ eheap_table[BM_elem_index_get(e_best)] = NULL;
+
+ /* No problem if this fails, re-evaluate if faces connected to this edge are touched. */
+ if (BM_edge_rotate_check(e_best)) {
+ BMEdge *e_rotate = BM_edge_rotate(bm, e_best, use_ccw, check_flag);
+ if (e_rotate != NULL) {
+ BMO_edge_flag_enable(bm, e_rotate, EDGE_OUT);
+
+ /* invalidate so we don't try touch this again. */
+ BM_elem_index_set(e_rotate, -1); /* set_dirty! */
+
+ edges_len_rotate += 1;
+
+ /* Note: we could validate all edges which have not been rotated
+ * (not just previously degenerate edges).
+ * However there is no real need - they can be left until they're popped off the queue. */
+
+ /* We don't know the exact topology after rotating the edge,
+ * so loop over all faces attached to the new edge, typically this will only be two faces. */
+ BMLoop *l_radial_iter = e_rotate->l;
+ do {
+ /* Skip this edge. */
+ BMLoop *l_iter = l_radial_iter->next;
+ do {
+ BMEdge *e_iter = l_iter->e;
+ const int e_iter_index = BM_elem_index_get(e_iter);
+ if ((e_iter_index != -1) && (eheap_table[e_iter_index] == NULL)) {
+ if (BM_edge_rotate_check(e_iter)) {
+ /* Previously degenerate, now valid. */
+ float cost = bm_edge_calc_rotate_cost(e_iter);
+ eheap_table[e_iter_index] = BLI_heap_insert(heap, cost, e_iter);
+ }
+ }
+ } while ((l_iter = l_iter->next) != l_radial_iter);
+ } while ((l_radial_iter = l_radial_iter->radial_next) != e_rotate->l);
+ }
+ }
+ }
+
+ /* If no actions were taken, move onto the next pass. */
+ if (edges_len_rotate == edges_len_rotate_prev) {
+ pass_type += 1;
+ continue;
+ }
+ }
+
+ BLI_heap_free(heap, NULL);
+ MEM_freeN(eheap_table);
+}
+
+void bmo_rotate_edges_exec(BMesh *bm, BMOperator *op)
+{
+ BMOIter siter;
+ BMEdge *e;
+ const int edges_len = BMO_slot_buffer_count(op->slots_in, "edges");
+ const bool use_ccw = BMO_slot_bool_get(op->slots_in, "use_ccw");
+ const bool is_single = (edges_len == 1);
+ short check_flag = is_single ?
+ BM_EDGEROT_CHECK_EXISTS :
+ BM_EDGEROT_CHECK_EXISTS | BM_EDGEROT_CHECK_DEGENERATE;
+
+ bool is_simple = true;
+ if (is_single == false) {
+ BMO_ITER (e, &siter, op->slots_in, "edges", BM_EDGE) {
+ BMFace *f_pair[2];
+ if (BM_edge_face_pair(e, &f_pair[0], &f_pair[1])) {
+ for (uint i = 0; i < ARRAY_SIZE(f_pair); i += 1) {
+ if (BMO_face_flag_test(bm, f_pair[i], FACE_MARK)) {
+ is_simple = false;
+ break;
+ }
+ BMO_face_flag_enable(bm, f_pair[i], FACE_MARK);
+ }
+ if (is_simple == false) {
+ break;
+ }
+ }
+ }
+ }
+
+ if (is_simple) {
+ bm_rotate_edges_simple(bm, op, use_ccw, check_flag);
+ }
+ else {
+ bm_rotate_edges_shared(bm, op, check_flag, use_ccw, edges_len);
+ }
+
+ BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "edges.out", BM_EDGE, EDGE_OUT);
+}
diff --git a/source/blender/bmesh/operators/bmo_smooth_laplacian.c b/source/blender/bmesh/operators/bmo_smooth_laplacian.c
index 1a83bafc074..2a7b85ac8fd 100644
--- a/source/blender/bmesh/operators/bmo_smooth_laplacian.c
+++ b/source/blender/bmesh/operators/bmo_smooth_laplacian.c
@@ -172,7 +172,7 @@ static void init_laplacian_matrix(LaplacianSystem *sys)
float w1, w2, w3, w4;
int i, j;
bool has_4_vert;
- unsigned int idv1, idv2, idv3, idv4, idv[4];
+ uint idv1, idv2, idv3, idv4, idv[4];
BMEdge *e;
BMFace *f;
BMIter eiter;
@@ -289,7 +289,7 @@ static void fill_laplacian_matrix(LaplacianSystem *sys)
float w2, w3, w4;
int i, j;
bool has_4_vert;
- unsigned int idv1, idv2, idv3, idv4, idv[4];
+ uint idv1, idv2, idv3, idv4, idv[4];
BMEdge *e;
BMFace *f;
@@ -420,7 +420,7 @@ static void validate_solution(LaplacianSystem *sys, int usex, int usey, int usez
float leni, lene;
float vini, vend;
float *vi1, *vi2, ve1[3], ve2[3];
- unsigned int idv1, idv2;
+ uint idv1, idv2;
BMOIter siter;
BMVert *v;
BMEdge *e;
diff --git a/source/blender/bmesh/operators/bmo_split_edges.c b/source/blender/bmesh/operators/bmo_split_edges.c
index eb7946caff0..f67a9e38fcc 100644
--- a/source/blender/bmesh/operators/bmo_split_edges.c
+++ b/source/blender/bmesh/operators/bmo_split_edges.c
@@ -50,5 +50,5 @@ void bmo_split_edges_exec(BMesh *bm, BMOperator *op)
/* this is where everything happens */
BM_mesh_edgesplit(bm, use_verts, true, false);
- BMO_slot_buffer_from_enabled_hflag(bm, op, op->slots_out, "edges.out", BM_EDGE, BM_ELEM_INTERNAL_TAG);
+ BMO_slot_buffer_from_enabled_hflag(bm, op, op->slots_out, "edges.out", BM_EDGE, BM_ELEM_TAG);
}
diff --git a/source/blender/bmesh/operators/bmo_subdivide.c b/source/blender/bmesh/operators/bmo_subdivide.c
index 894129b4a33..8f998797a16 100644
--- a/source/blender/bmesh/operators/bmo_subdivide.c
+++ b/source/blender/bmesh/operators/bmo_subdivide.c
@@ -1011,8 +1011,8 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
/* figure out which pattern to use */
- BLI_array_empty(edges);
- BLI_array_empty(verts);
+ BLI_array_clear(edges);
+ BLI_array_clear(verts);
BLI_array_grow_items(edges, face->len);
BLI_array_grow_items(verts, face->len);
@@ -1140,7 +1140,7 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
face = fd->face;
/* figure out which pattern to use */
- BLI_array_empty(verts);
+ BLI_array_clear(verts);
pat = fd->pat;
@@ -1148,8 +1148,8 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
int vlen;
/* ok, no pattern. we still may be able to do something */
- BLI_array_empty(loops);
- BLI_array_empty(loops_split);
+ BLI_array_clear(loops);
+ BLI_array_clear(loops_split);
/* for case of two edges, connecting them shouldn't be too hard */
BLI_array_grow_items(loops, face->len);
@@ -1157,7 +1157,7 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
loops[a] = l;
}
- vlen = BLI_array_count(loops);
+ vlen = BLI_array_len(loops);
/* find the boundary of one of the split edges */
for (a = 1; a < vlen; a++) {
@@ -1236,9 +1236,9 @@ void bmo_subdivide_edges_exec(BMesh *bm, BMOperator *op)
* - concave corner of an ngon.
* - 2 edges being used in 2+ ngons.
*/
-// BM_face_splits_check_legal(bm, face, loops_split, BLI_array_count(loops_split));
+// BM_face_splits_check_legal(bm, face, loops_split, BLI_array_len(loops_split));
- for (j = 0; j < BLI_array_count(loops_split); j++) {
+ for (j = 0; j < BLI_array_len(loops_split); j++) {
if (loops_split[j][0]) {
BMFace *f_new;
BLI_assert(BM_edge_exists(loops_split[j][0]->v, loops_split[j][1]->v) == NULL);
diff --git a/source/blender/bmesh/operators/bmo_subdivide_edgering.c b/source/blender/bmesh/operators/bmo_subdivide_edgering.c
index ce031e1c230..e6881f6d8b1 100644
--- a/source/blender/bmesh/operators/bmo_subdivide_edgering.c
+++ b/source/blender/bmesh/operators/bmo_subdivide_edgering.c
@@ -40,7 +40,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_alloca.h"
#include "BLI_math.h"
#include "BLI_listbase.h"
@@ -66,7 +66,7 @@
/* Specialized Utility Funcs */
#ifndef NDEBUG
-static unsigned int bm_verts_tag_count(BMesh *bm)
+static uint bm_verts_tag_count(BMesh *bm)
{
int count = 0;
BMIter iter;
@@ -269,7 +269,7 @@ static GSet *bm_edgering_pair_calc(BMesh *bm, ListBase *eloops_rim)
BLI_ghash_free(vert_eloop_gh, NULL, NULL);
- if (BLI_gset_size(eloop_pair_gs) == 0) {
+ if (BLI_gset_len(eloop_pair_gs) == 0) {
BLI_gset_free(eloop_pair_gs, NULL);
eloop_pair_gs = NULL;
}
@@ -390,9 +390,9 @@ static void bm_vert_calc_surface_tangent(BMesh *bm, BMVert *v, float r_no[3])
* Tag faces connected to an edge loop as FACE_SHARED
* if all vertices are VERT_SHARED.
*/
-static void bm_faces_share_tag_flush(BMesh *bm, BMEdge **e_arr, const unsigned int e_arr_len)
+static void bm_faces_share_tag_flush(BMesh *bm, BMEdge **e_arr, const uint e_arr_len)
{
- unsigned int i;
+ uint i;
for (i = 0; i < e_arr_len; i++) {
BMEdge *e = e_arr[i];
@@ -412,9 +412,9 @@ static void bm_faces_share_tag_flush(BMesh *bm, BMEdge **e_arr, const unsigned i
/**
* Un-Tag faces connected to an edge loop, clearing FACE_SHARED
*/
-static void bm_faces_share_tag_clear(BMesh *bm, BMEdge **e_arr_iter, const unsigned int e_arr_len_iter)
+static void bm_faces_share_tag_clear(BMesh *bm, BMEdge **e_arr_iter, const uint e_arr_len_iter)
{
- unsigned int i;
+ uint i;
for (i = 0; i < e_arr_len_iter; i++) {
BMEdge *e = e_arr_iter[i];
@@ -454,16 +454,16 @@ static LoopPairStore *bm_edgering_pair_store_create(
LoopPairStore *lpair = MEM_mallocN(sizeof(*lpair), __func__);
if (interp_mode == SUBD_RING_INTERP_SURF) {
- const unsigned int len_a = BM_edgeloop_length_get(el_store_a);
- const unsigned int len_b = BM_edgeloop_length_get(el_store_b);
- const unsigned int e_arr_a_len = len_a - (BM_edgeloop_is_closed(el_store_a) ? 0 : 1);
- const unsigned int e_arr_b_len = len_b - (BM_edgeloop_is_closed(el_store_b) ? 0 : 1);
+ const uint len_a = BM_edgeloop_length_get(el_store_a);
+ const uint len_b = BM_edgeloop_length_get(el_store_b);
+ const uint e_arr_a_len = len_a - (BM_edgeloop_is_closed(el_store_a) ? 0 : 1);
+ const uint e_arr_b_len = len_b - (BM_edgeloop_is_closed(el_store_b) ? 0 : 1);
BMEdge **e_arr_a = BLI_array_alloca(e_arr_a, e_arr_a_len);
BMEdge **e_arr_b = BLI_array_alloca(e_arr_b, e_arr_b_len);
- unsigned int i;
+ uint i;
struct BMEdgeLoopStore *el_store_pair[2] = {el_store_a, el_store_b};
- unsigned int side_index;
+ uint side_index;
float (*nors_pair[2])[3];
GHash *nors_gh_pair[2];
@@ -768,8 +768,8 @@ static void bm_edgering_pair_interpolate(
bm_vert_calc_surface_tangent(bm, v_b, no_b);
#else
{
- const unsigned int index_a = GET_UINT_FROM_POINTER(BLI_ghash_lookup(lpair->nors_gh_a, v_a));
- const unsigned int index_b = GET_UINT_FROM_POINTER(BLI_ghash_lookup(lpair->nors_gh_b, v_b));
+ const uint index_a = GET_UINT_FROM_POINTER(BLI_ghash_lookup(lpair->nors_gh_a, v_a));
+ const uint index_b = GET_UINT_FROM_POINTER(BLI_ghash_lookup(lpair->nors_gh_b, v_b));
BLI_assert(BLI_ghash_haskey(lpair->nors_gh_a, v_a));
BLI_assert(BLI_ghash_haskey(lpair->nors_gh_b, v_b));
@@ -1193,7 +1193,7 @@ void bmo_subdivide_edgering_exec(BMesh *bm, BMOperator *op)
goto cleanup;
}
- lpair_arr = BLI_array_alloca(lpair_arr, BLI_gset_size(eloop_pairs_gs));
+ lpair_arr = BLI_array_alloca(lpair_arr, BLI_gset_len(eloop_pairs_gs));
/* first cache pairs */
GSET_ITER_INDEX (gs_iter, eloop_pairs_gs, i) {
diff --git a/source/blender/bmesh/operators/bmo_triangulate.c b/source/blender/bmesh/operators/bmo_triangulate.c
index 6bd3174d27a..2cdc2646649 100644
--- a/source/blender/bmesh/operators/bmo_triangulate.c
+++ b/source/blender/bmesh/operators/bmo_triangulate.c
@@ -77,7 +77,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
GHash *sf_vert_map;
float normal[3];
const int scanfill_flag = BLI_SCANFILL_CALC_HOLES | BLI_SCANFILL_CALC_POLYS | BLI_SCANFILL_CALC_LOOSE;
- unsigned int nors_tot;
+ uint nors_tot;
bool calc_winding = false;
sf_vert_map = BLI_ghash_ptr_new_ex(__func__, BMO_slot_buffer_count(op->slots_in, "edges"));
@@ -89,7 +89,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
BMO_ITER (e, &siter, op->slots_in, "edges", BM_EDGE) {
ScanFillVert *sf_verts[2];
BMVert **e_verts = &e->v1;
- unsigned int i;
+ uint i;
BMO_edge_flag_enable(bm, e, EDGE_MARK);
@@ -106,7 +106,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
/* sf_edge = */ BLI_scanfill_edge_add(&sf_ctx, UNPACK2(sf_verts));
/* sf_edge->tmp.p = e; */ /* UNUSED */
}
- nors_tot = BLI_ghash_size(sf_vert_map);
+ nors_tot = BLI_ghash_len(sf_vert_map);
BLI_ghash_free(sf_vert_map, NULL, NULL);
@@ -115,7 +115,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
* Since we don't know winding, just accumulate */
ScanFillVert *sf_vert;
struct SortNormal *nors;
- unsigned int i;
+ uint i;
bool is_degenerate = true;
nors = MEM_mallocN(sizeof(*nors) * nors_tot, __func__);
@@ -124,7 +124,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
BMVert *v = sf_vert->tmp.p;
BMIter eiter;
BMEdge *e_pair[2];
- unsigned int e_index = 0;
+ uint e_index = 0;
nors[i].value = -1.0f;
@@ -199,7 +199,7 @@ void bmo_triangle_fill_exec(BMesh *bm, BMOperator *op)
int winding_votes = 0;
for (sf_tri = sf_ctx.fillfacebase.first; sf_tri; sf_tri = sf_tri->next) {
BMVert *v_tri[3] = {sf_tri->v1->tmp.p, sf_tri->v2->tmp.p, sf_tri->v3->tmp.p};
- unsigned int i, i_prev;
+ uint i, i_prev;
for (i = 0, i_prev = 2; i < 3; i_prev = i++) {
e = BM_edge_exists(v_tri[i], v_tri[i_prev]);
diff --git a/source/blender/bmesh/operators/bmo_utils.c b/source/blender/bmesh/operators/bmo_utils.c
index aa1e4bc7523..e9ee1e6e552 100644
--- a/source/blender/bmesh/operators/bmo_utils.c
+++ b/source/blender/bmesh/operators/bmo_utils.c
@@ -121,60 +121,6 @@ void bmo_reverse_faces_exec(BMesh *bm, BMOperator *op)
}
}
-void bmo_rotate_edges_exec(BMesh *bm, BMOperator *op)
-{
- BMOIter siter;
- BMEdge *e, *e2;
- const bool use_ccw = BMO_slot_bool_get(op->slots_in, "use_ccw");
- const bool is_single = BMO_slot_buffer_count(op->slots_in, "edges") == 1;
- short check_flag = is_single ?
- BM_EDGEROT_CHECK_EXISTS :
- BM_EDGEROT_CHECK_EXISTS | BM_EDGEROT_CHECK_DEGENERATE;
-
-#define EDGE_OUT 1
-#define FACE_TAINT 1
-
- BMO_ITER (e, &siter, op->slots_in, "edges", BM_EDGE) {
- /**
- * this ends up being called twice, could add option to not to call check in
- * #BM_edge_rotate to get some extra speed */
- if (BM_edge_rotate_check(e)) {
- BMFace *fa, *fb;
- if (BM_edge_face_pair(e, &fa, &fb)) {
-
- /* check we're untouched */
- if (BMO_face_flag_test(bm, fa, FACE_TAINT) == false &&
- BMO_face_flag_test(bm, fb, FACE_TAINT) == false)
- {
-
- /* don't touch again (faces will be freed so run before rotating the edge) */
- BMO_face_flag_enable(bm, fa, FACE_TAINT);
- BMO_face_flag_enable(bm, fb, FACE_TAINT);
-
- if (!(e2 = BM_edge_rotate(bm, e, use_ccw, check_flag))) {
-
- BMO_face_flag_disable(bm, fa, FACE_TAINT);
- BMO_face_flag_disable(bm, fb, FACE_TAINT);
-#if 0
- BMO_error_raise(bm, op, BMERR_INVALID_SELECTION, "Could not rotate edge");
- return;
-#endif
-
- continue;
- }
-
- BMO_edge_flag_enable(bm, e2, EDGE_OUT);
- }
- }
- }
- }
-
- BMO_slot_buffer_from_enabled_flag(bm, op, op->slots_out, "edges.out", BM_EDGE, EDGE_OUT);
-
-#undef EDGE_OUT
-#undef FACE_TAINT
-
-}
#define SEL_FLAG 1
#define SEL_ORIG 2
diff --git a/source/blender/bmesh/tools/bmesh_beautify.c b/source/blender/bmesh/tools/bmesh_beautify.c
index 3e3a6547b75..d3972363bb4 100644
--- a/source/blender/bmesh/tools/bmesh_beautify.c
+++ b/source/blender/bmesh/tools/bmesh_beautify.c
@@ -37,7 +37,7 @@
#include "BLI_math.h"
#include "BLI_heap.h"
-#include "BLI_polyfill2d_beautify.h"
+#include "BLI_polyfill_2d_beautify.h"
#include "MEM_guardedalloc.h"
@@ -62,7 +62,7 @@ typedef struct EdRotState {
#if 0
/* use BLI_ghashutil_inthash_v4 direct */
-static unsigned int erot_gsetutil_hash(const void *ptr)
+static uint erot_gsetutil_hash(const void *ptr)
{
const EdRotState *e_state = (const EdRotState *)ptr;
return BLI_ghashutil_inthash_v4(&e_state->v1);
@@ -150,7 +150,7 @@ static float bm_edge_calc_rotate_beauty__area(
(ELEM(v4, v1, v2, v3) == false));
add_v3_v3v3(no, no_a, no_b);
- if (UNLIKELY((no_scale = normalize_v3(no)) <= FLT_EPSILON)) {
+ if (UNLIKELY((no_scale = normalize_v3(no)) == 0.0f)) {
break;
}
@@ -182,7 +182,12 @@ static float bm_edge_calc_rotate_beauty__area(
}
}
- return BLI_polyfill_beautify_quad_rotate_calc(v1_xy, v2_xy, v3_xy, v4_xy);
+ /**
+ * Important to lock degenerate here,
+ * since the triangle pars will be projected into different 2D spaces.
+ * Allowing to rotate out of a degenerate state can flip the faces (when performed iteratively).
+ */
+ return BLI_polyfill_beautify_quad_rotate_calc_ex(v1_xy, v2_xy, v3_xy, v4_xy, true);
} while (false);
return FLT_MAX;
@@ -368,7 +373,7 @@ void BM_mesh_beautify_fill(
TIMEIT_START(beautify_fill);
#endif
- eheap = BLI_heap_new_ex((unsigned int)edge_array_len);
+ eheap = BLI_heap_new_ex((uint)edge_array_len);
eheap_table = MEM_mallocN(sizeof(HeapNode *) * (size_t)edge_array_len, __func__);
/* build heap */
@@ -387,7 +392,7 @@ void BM_mesh_beautify_fill(
bm->elem_index_dirty |= BM_EDGE;
while (BLI_heap_is_empty(eheap) == false) {
- BMEdge *e = BLI_heap_popmin(eheap);
+ BMEdge *e = BLI_heap_pop_min(eheap);
i = BM_elem_index_get(e);
eheap_table[i] = NULL;
diff --git a/source/blender/bmesh/tools/bmesh_bevel.c b/source/blender/bmesh/tools/bmesh_bevel.c
index 05169a2a976..457e74ce1aa 100644
--- a/source/blender/bmesh/tools/bmesh_bevel.c
+++ b/source/blender/bmesh/tools/bmesh_bevel.c
@@ -44,6 +44,8 @@
#include "BKE_customdata.h"
#include "BKE_deform.h"
+#include "eigen_capi.h"
+
#include "bmesh.h"
#include "bmesh_bevel.h" /* own include */
@@ -58,6 +60,7 @@
#define BEVEL_SMALL_ANG DEG2RADF(10.0f)
#define BEVEL_MAX_ADJUST_PCT 10.0f
#define BEVEL_MAX_AUTO_ADJUST_PCT 300.0f
+#define BEVEL_MATCH_SPEC_WEIGHT 0.2
/* happens far too often, uncomment for development */
// #define BEVEL_ASSERT_PROJECT
@@ -117,7 +120,7 @@ typedef struct Profile {
float *prof_co; /* seg+1 profile coordinates (triples of floats) */
float *prof_co_2; /* like prof_co, but for seg power of 2 >= seg */
} Profile;
-#define PRO_SQUARE_R 4.0f
+#define PRO_SQUARE_R 1e4f
#define PRO_CIRCLE_R 2.0f
#define PRO_LINE_R 1.0f
#define PRO_SQUARE_IN_R 0.0f
@@ -126,8 +129,10 @@ typedef struct Profile {
* get even spacing on superellipse for current BevelParams seg
* and pro_super_r. */
typedef struct ProfileSpacing {
- float *uvals; /* seg+1 u values */
- float *uvals_2; /* seg_2+1 u values, seg_2 = power of 2 >= seg */
+ double *xvals; /* seg+1 x values */
+ double *xvals_2; /* seg_2+1 x values, seg_2 = power of 2 >= seg */
+ double *yvals; /* seg+1 y values */
+ double *yvals_2; /* seg_2+1 y values, seg_2 = power of 2 >= seg */
int seg_2; /* the seg_2 value */
} ProfileSpacing;
@@ -137,10 +142,14 @@ typedef struct BoundVert {
NewVert nv;
EdgeHalf *efirst; /* first of edges attached here: in CCW order */
EdgeHalf *elast;
+ EdgeHalf *eon; /* the "edge between" that this is on, in offset_on_edge_between case */
EdgeHalf *ebev; /* beveled edge whose left side is attached here, if any */
int index; /* used for vmesh indexing */
+ float sinratio; /* when eon set, ratio of sines of angles to eon edge */
+ struct BoundVert *adjchain; /* adjustment chain or cycle link pointer */
Profile profile; /* edge profile between this and next BoundVert */
bool any_seam; /* are any of the edges attached here seams? */
+ bool visited; /* used during delta adjust pass */
// int _pad;
} BoundVert;
@@ -190,6 +199,7 @@ typedef struct BevelParams {
bool use_weights; /* bevel amount affected by weights on edges or verts */
bool loop_slide; /* should bevel prefer to slide along edges rather than keep widths spec? */
bool limit_offset; /* should offsets be limited by collisions? */
+ bool offset_adjust; /* should offsets be adjusted to try to get even widths? */
const struct MDeformVert *dvert; /* vertex group array, maybe set if vertex_only */
int vertex_group; /* vertex group index, maybe set if vertex_only */
int mat_nr; /* if >= 0, material number for bevel; else material comes from adjacent faces */
@@ -205,6 +215,39 @@ static int bev_debug_flags = 0;
#define DEBUG_OLD_PROJ_TO_PERP_PLANE (bev_debug_flags & 2)
#define DEBUG_OLD_FLAT_MID (bev_debug_flags & 4)
+
+/* this flag values will get set on geom we want to return in 'out' slots for edges and verts */
+#define EDGE_OUT 4
+#define VERT_OUT 8
+
+/* If we're called from the modifier, tool flags aren't available, but don't need output geometry */
+static void flag_out_edge(BMesh *bm, BMEdge *bme)
+{
+ if (bm->use_toolflags)
+ BMO_edge_flag_enable(bm, bme, EDGE_OUT);
+}
+
+static void flag_out_vert(BMesh *bm, BMVert *bmv)
+{
+ if (bm->use_toolflags)
+ BMO_vert_flag_enable(bm, bmv, VERT_OUT);
+}
+
+static void disable_flag_out_edge(BMesh *bm, BMEdge *bme)
+{
+ if (bm->use_toolflags)
+ BMO_edge_flag_disable(bm, bme, EDGE_OUT);
+}
+
+/* Are d1 and d2 parallel or nearly so? */
+static bool nearly_parallel(const float d1[3], const float d2[3])
+{
+ float ang;
+
+ ang = angle_v3v3(d1, d2);
+ return (fabsf(ang) < BEVEL_EPSILON_ANG) || (fabsf(ang - (float)M_PI) < BEVEL_EPSILON_ANG);
+}
+
/* Make a new BoundVert of the given kind, insert it at the end of the circular linked
* list with entry point bv->boundstart, and return it. */
static BoundVert *add_new_bound_vert(MemArena *mem_arena, VMesh *vm, const float co[3])
@@ -226,6 +269,9 @@ static BoundVert *add_new_bound_vert(MemArena *mem_arena, VMesh *vm, const float
vm->boundstart->prev = ans;
}
ans->profile.super_r = PRO_LINE_R;
+ ans->adjchain = NULL;
+ ans->sinratio = 1.0f;
+ ans->visited = false;
vm->count++;
return ans;
}
@@ -253,6 +299,7 @@ static void create_mesh_bmvert(BMesh *bm, VMesh *vm, int i, int j, int k, BMVert
NewVert *nv = mesh_vert(vm, i, j, k);
nv->v = BM_vert_create(bm, nv->co, eg, BM_CREATE_NOP);
BM_elem_flag_disable(nv->v, BM_ELEM_TAG);
+ flag_out_vert(bm, nv->v);
}
static void copy_mesh_vert(
@@ -307,52 +354,6 @@ static EdgeHalf *find_other_end_edge_half(BevelParams *bp, EdgeHalf *e, BevVert
return NULL;
}
-static bool other_edge_half_visited(BevelParams *bp, EdgeHalf *e)
-{
- BevVert *bvo;
-
- bvo = find_bevvert(bp, e->is_rev ? e->e->v1 : e->e->v2);
- if (bvo)
- return bvo->visited;
- else
- return false;
-}
-
-static bool edge_half_offset_changed(EdgeHalf *e)
-{
- return e->offset_l != e->offset_l_spec ||
- e->offset_r != e->offset_r_spec;
-}
-
-static float adjusted_rel_change(float val, float spec)
-{
- float relchg;
-
- relchg = 0.0f;
- if (val != spec) {
- if (spec == 0)
- relchg = 1000.0f; /* arbitrary large value */
- else
- relchg = fabsf((val - spec) / spec);
- }
- return relchg;
-}
-
-static float max_edge_half_offset_rel_change(BevVert *bv)
-{
- int i;
- float max_rel_change;
- EdgeHalf *e;
-
- max_rel_change = 0.0f;
- for (i = 0; i < bv->edgecount; i++) {
- e = &bv->edges[i];
- max_rel_change = max_ff(max_rel_change, adjusted_rel_change(e->offset_l, e->offset_l_spec));
- max_rel_change = max_ff(max_rel_change, adjusted_rel_change(e->offset_r, e->offset_r_spec));
- }
- return max_rel_change;
-}
-
/* Return the next EdgeHalf after from_e that is beveled.
* If from_e is NULL, find the first beveled edge. */
static EdgeHalf *next_bev(BevVert *bv, EdgeHalf *from_e)
@@ -495,9 +496,12 @@ static BMFace *bev_create_ngon(
}
/* not essential for bevels own internal logic,
- * this is done so the operator can select newly created faces */
+ * this is done so the operator can select newly created geometry */
if (f) {
BM_elem_flag_enable(f, BM_ELEM_TAG);
+ BM_ITER_ELEM(bme, &iter, f, BM_EDGES_OF_FACE) {
+ flag_out_edge(bm, bme);
+ }
}
if (mat_nr >= 0)
@@ -680,14 +684,18 @@ static void slide_dist(EdgeHalf *e, BMVert *v, float d, float slideco[3])
/* Is co not on the edge e? if not, return the closer end of e in ret_closer_v */
static bool is_outside_edge(EdgeHalf *e, const float co[3], BMVert **ret_closer_v)
{
- float d_squared;
-
- d_squared = dist_squared_to_line_segment_v3(co, e->e->v1->co, e->e->v2->co);
- if (d_squared > BEVEL_EPSILON_BIG * BEVEL_EPSILON_BIG) {
- if (len_squared_v3v3(co, e->e->v1->co) > len_squared_v3v3(co, e->e->v2->co))
- *ret_closer_v = e->e->v2;
- else
- *ret_closer_v = e->e->v1;
+ float h[3], u[3], lambda, lenu, *l1 = e->e->v1->co;
+
+ sub_v3_v3v3(u, e->e->v2->co, l1);
+ sub_v3_v3v3(h, co, l1);
+ lenu = normalize_v3(u);
+ lambda = dot_v3v3(u, h);
+ if (lambda <= -BEVEL_EPSILON_BIG * lenu) {
+ *ret_closer_v = e->e->v1;
+ return true;
+ }
+ else if (lambda >= (1.0f + BEVEL_EPSILON_BIG) * lenu) {
+ *ret_closer_v = e->e->v2;
return true;
}
else {
@@ -776,10 +784,6 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
copy_v3_v3(off1a, v->co);
d = max_ff(e1->offset_r, e2->offset_l);
madd_v3_v3fl(off1a, norm_perp1, d);
- if (e1->offset_r != d)
- e1->offset_r = d;
- else if (e2->offset_l != d)
- e2->offset_l = d;
copy_v3_v3(meetco, off1a);
}
else if (fabsf(ang - (float)M_PI) < BEVEL_EPSILON_ANG) {
@@ -788,10 +792,6 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
* common line, at offset distance from v. */
d = max_ff(e1->offset_r, e2->offset_l);
slide_dist(e2, v, d, meetco);
- if (e1->offset_r != d)
- e1->offset_r = d;
- else if (e2->offset_l != d)
- e2->offset_l = d;
}
else {
/* Get normal to plane where meet point should be,
@@ -829,7 +829,6 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
negate_v3(norm_v2);
}
-
/* get vectors perp to each edge, perp to norm_v, and pointing into face */
cross_v3_v3v3(norm_perp1, dir1, norm_v1);
cross_v3_v3v3(norm_perp2, dir2, norm_v2);
@@ -849,9 +848,6 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
if (isect_kind == 0) {
/* lines are collinear: we already tested for this, but this used a different epsilon */
copy_v3_v3(meetco, off1a); /* just to do something */
- d = dist_to_line_v3(meetco, v->co, BM_edge_other_vert(e2->e, v)->co);
- if (fabsf(d - e2->offset_l) > BEVEL_EPSILON)
- e2->offset_l = d;
}
else {
/* The lines intersect, but is it at a reasonable place?
@@ -861,11 +857,9 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
* or if the offset amount is > the edge length*/
if (e1->offset_r == 0.0f && is_outside_edge(e1, meetco, &closer_v)) {
copy_v3_v3(meetco, closer_v->co);
- e2->offset_l = len_v3v3(meetco, v->co);
}
if (e2->offset_l == 0.0f && is_outside_edge(e2, meetco, &closer_v)) {
copy_v3_v3(meetco, closer_v->co);
- e1->offset_r = len_v3v3(meetco, v->co);
}
if (edges_between && e1->offset_r > 0.0f && e2->offset_l > 0.0f) {
/* Try to drop meetco to a face between e1 and e2 */
@@ -884,8 +878,6 @@ static void offset_meet(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, BMFace *f, bool e
break;
}
}
- e1->offset_r = dist_to_line_v3(meetco, v->co, BM_edge_other_vert(e1->e, v)->co);
- e2->offset_l = dist_to_line_v3(meetco, v->co, BM_edge_other_vert(e2->e, v)->co);
}
}
}
@@ -916,8 +908,12 @@ static bool offset_meet_edge(EdgeHalf *e1, EdgeHalf *e2, BMVert *v, float meetc
return false;
}
cross_v3_v3v3(fno, dir1, dir2);
- if (dot_v3v3(fno, v->no) < 0.0f)
+ if (dot_v3v3(fno, v->no) < 0.0f) {
ang = 2.0f * (float)M_PI - ang; /* angle is reflex */
+ if (r_angle)
+ *r_angle = ang;
+ return false;
+ }
if (r_angle)
*r_angle = ang;
@@ -948,40 +944,27 @@ static bool good_offset_on_edge_between(EdgeHalf *e1, EdgeHalf *e2, EdgeHalf *em
/* Calculate the best place for a meeting point for the offsets from edges e1 and e2
* on the in-between edge emid. Viewed from the vertex normal side, the CCW
* order of these edges is e1, emid, e2.
- * The offsets probably do not meet at a common point on emid, so need to pick
- * one that causes the least problems. If the other end of one of e1 or e2 has been visited
- * already, prefer to keep the offset the same on this end.
- * Otherwise, pick a point between the two intersection points on emid that minimizes
- * the sum of squares of errors from desired offset. */
-static void offset_on_edge_between(
- BevelParams *bp, EdgeHalf *e1, EdgeHalf *e2, EdgeHalf *emid,
- BMVert *v, float meetco[3])
+ * Return true if we placed meetco as compromise between where two edges met.
+ * If we did, put ration of sines of angles in *r_sinratio too */
+static bool offset_on_edge_between(
+ EdgeHalf *e1, EdgeHalf *e2, EdgeHalf *emid,
+ BMVert *v, float meetco[3], float *r_sinratio)
{
- float d, ang1, ang2, sina1, sina2, lambda;
+ float ang1, ang2;
float meet1[3], meet2[3];
- bool visited1, visited2, ok1, ok2;
+ bool ok1, ok2;
+ bool retval = false;
BLI_assert(e1->is_bev && e2->is_bev && !emid->is_bev);
- visited1 = other_edge_half_visited(bp, e1);
- visited2 = other_edge_half_visited(bp, e2);
-
ok1 = offset_meet_edge(e1, emid, v, meet1, &ang1);
ok2 = offset_meet_edge(emid, e2, v, meet2, &ang2);
if (ok1 && ok2) {
- if (visited1 && !visited2) {
- copy_v3_v3(meetco, meet1);
- }
- else if (!visited1 && visited2) {
- copy_v3_v3(meetco, meet2);
- }
- else {
- /* find best compromise meet point */
- sina1 = sinf(ang1);
- sina2 = sinf(ang2);
- lambda = sina2 * sina2 / (sina1 * sina1 + sina2 * sina2);
- interp_v3_v3v3(meetco, meet1, meet2, lambda);
- }
+ mid_v3_v3v3(meetco, meet1, meet2);
+ if (r_sinratio)
+ /* ang1 should not be 0, but be paranoid */
+ *r_sinratio = (ang1 == 0.0f) ? 1.0f : sinf(ang2) / sinf(ang1);
+ retval = true;
}
else if (ok1 && !ok2) {
copy_v3_v3(meetco, meet1);
@@ -995,13 +978,7 @@ static void offset_on_edge_between(
slide_dist(emid, v, e1->offset_r, meetco);
}
- /* offsets may have changed now */
- d = dist_to_line_v3(meetco, v->co, BM_edge_other_vert(e1->e, v)->co);
- if (fabsf(d - e1->offset_r) > BEVEL_EPSILON)
- e1->offset_r = d;
- d = dist_to_line_v3(meetco, v->co, BM_edge_other_vert(e2->e, v)->co);
- if (fabsf(d - e2->offset_l) > BEVEL_EPSILON)
- e2->offset_l = d;
+ return retval;
}
/* Offset by e->offset in plane with normal plane_no, on left if left==true,
@@ -1055,7 +1032,7 @@ static void set_profile_params(BevelParams *bp, BevVert *bv, BoundVert *bndv)
{
EdgeHalf *e;
Profile *pro;
- float co1[3], co2[3], co3[3], d1[3], d2[3], l;
+ float co1[3], co2[3], co3[3], d1[3], d2[3];
bool do_linear_interp;
copy_v3_v3(co1, bndv->nv.co);
@@ -1093,8 +1070,8 @@ static void set_profile_params(BevelParams *bp, BevVert *bv, BoundVert *bndv)
normalize_v3(d1);
normalize_v3(d2);
cross_v3_v3v3(pro->plane_no, d1, d2);
- l = normalize_v3(pro->plane_no);
- if (l <= BEVEL_EPSILON_BIG) {
+ normalize_v3(pro->plane_no);
+ if (nearly_parallel(d1, d2)) {
/* co1 - midco -co2 are collinear.
* Should be case that beveled edge is coplanar with two boundary verts.
* We want to move the profile to that common plane, if possible.
@@ -1126,17 +1103,24 @@ static void set_profile_params(BevelParams *bp, BevVert *bv, BoundVert *bndv)
sub_v3_v3v3(d4, e->next->e->v1->co, e->next->e->v2->co);
normalize_v3(d3);
normalize_v3(d4);
- add_v3_v3v3(co3, co1, d3);
- add_v3_v3v3(co4, co2, d4);
- isect_kind = isect_line_line_v3(co1, co3, co2, co4, meetco, isect2);
- if (isect_kind != 0) {
- copy_v3_v3(pro->midco, meetco);
- }
- else {
+ if (nearly_parallel(d3, d4)) {
/* offset lines are collinear - want linear interpolation */
mid_v3_v3v3(pro->midco, co1, co2);
do_linear_interp = true;
}
+ else {
+ add_v3_v3v3(co3, co1, d3);
+ add_v3_v3v3(co4, co2, d4);
+ isect_kind = isect_line_line_v3(co1, co3, co2, co4, meetco, isect2);
+ if (isect_kind != 0) {
+ copy_v3_v3(pro->midco, meetco);
+ }
+ else {
+ /* offset lines don't intersect - want linear interpolation */
+ mid_v3_v3v3(pro->midco, co1, co2);
+ do_linear_interp = true;
+ }
+ }
}
}
copy_v3_v3(pro->cob, co2);
@@ -1145,8 +1129,8 @@ static void set_profile_params(BevelParams *bp, BevVert *bv, BoundVert *bndv)
sub_v3_v3v3(d2, pro->midco, co2);
normalize_v3(d2);
cross_v3_v3v3(pro->plane_no, d1, d2);
- l = normalize_v3(pro->plane_no);
- if (l <= BEVEL_EPSILON_BIG) {
+ normalize_v3(pro->plane_no);
+ if (nearly_parallel(d1, d2)) {
/* whole profile is collinear with edge: just interpolate */
do_linear_interp = true;
}
@@ -1336,56 +1320,21 @@ static void make_unit_cube_map(
r_mat[3][3] = 1.0f;
}
-/* Get the coordinate on the superellipse (exponent r),
- * at parameter value u. u goes from u to 2 as the
- * superellipse moves on the quadrant (0,1) to (1,0). */
-static void superellipse_co(float u, float r, float r_co[2])
+/* Get the coordinate on the superellipse (x^r + y^r = 1),
+ * at parameter value x (or, if !rbig, mirrored (y=x)-line).
+ * rbig should be true if r > 1.0 and false if <= 1.0.
+ * Assume r > 0.0 */
+static double superellipse_co(double x, float r, bool rbig)
{
- float t;
-
- if (u <= 0.0f) {
- r_co[0] = 0.0f;
- r_co[1] = 1.0f;
- }
- else if (u >= 2.0f) {
- r_co[0] = 1.0f;
- r_co[1] = 0.0f;
- }
- else if (r == PRO_LINE_R) {
- t = u / 2.0f;
- r_co[0] = t;
- r_co[1] = 1.0f - t;
-
- }
- else if (r == PRO_SQUARE_IN_R) {
- if (u < 1.0f) {
- r_co[0] = 0.0f;
- r_co[1] = 1.0f - u;
- }
- else {
- r_co[0] = u - 1.0f;
- r_co[1] = 0.0f;
- }
- }
- else if (r == PRO_SQUARE_R) {
- if (u < 1.0f) {
- r_co[0] = u;
- r_co[1] = 1.0f;
- }
- else {
- r_co[0] = 1.0f;
- r_co[1] = 2.0f - u;
- }
-
+ BLI_assert(r > 0.0f);
+
+ /* If r<1, mirror the superellipse function by (y=x)-line to get a numerically stable range
+ * Possible because of symmetry, later mirror back. */
+ if (rbig) {
+ return pow((1.0 - pow(x, r)), (1.0 / r));
}
else {
- t = u * (float)M_PI / 4.0f; /* angle from y axis */
- r_co[0] = sinf(t);
- r_co[1] = cosf(t);
- if (r != PRO_SQUARE_R) {
- r_co[0] = pow(r_co[0], 2.0f / r);
- r_co[1] = pow(r_co[1], 2.0f / r);
- }
+ return 1.0 - pow((1.0 - pow(1.0 - x, r)), (1.0 / r));
}
}
@@ -1431,7 +1380,7 @@ static void get_profile_point(BevelParams *bp, const Profile *pro, int i, int n,
static void calculate_profile(BevelParams *bp, BoundVert *bndv)
{
int i, k, ns;
- const float *uvals;
+ const double *xvals, *yvals;
float co[3], co2[3], p[3], m[4][4];
float *prof_co, *prof_co_k;
float r;
@@ -1457,17 +1406,19 @@ static void calculate_profile(BevelParams *bp, BoundVert *bndv)
for (i = 0; i < 2; i++) {
if (i == 0) {
ns = bp->seg;
- uvals = bp->pro_spacing.uvals;
+ xvals = bp->pro_spacing.xvals;
+ yvals = bp->pro_spacing.yvals;
prof_co = pro->prof_co;
}
else {
if (!need_2)
break; /* shares coords with pro->prof_co */
ns = bp->pro_spacing.seg_2;
- uvals = bp->pro_spacing.uvals_2;
+ xvals = bp->pro_spacing.xvals_2;
+ yvals = bp->pro_spacing.yvals_2;
prof_co = pro->prof_co_2;
}
- BLI_assert((r == PRO_LINE_R || uvals != NULL) && prof_co != NULL);
+ BLI_assert((r == PRO_LINE_R || (xvals != NULL && yvals != NULL)) && prof_co != NULL);
for (k = 0; k <= ns; k++) {
if (k == 0)
copy_v3_v3(co, pro->coa);
@@ -1475,7 +1426,8 @@ static void calculate_profile(BevelParams *bp, BoundVert *bndv)
copy_v3_v3(co, pro->cob);
else {
if (map_ok) {
- superellipse_co(uvals[k], r, p);
+ p[0] = xvals[k];
+ p[1] = yvals[k];
p[2] = 0.0f;
mul_v3_m4v3(co, m, p);
}
@@ -1671,7 +1623,7 @@ static void build_boundary_vertex_only(BevelParams *bp, BevVert *bv, bool constr
* Special case of build_boundary when a single edge is beveled.
* The 'width adjust' part of build_boundary has been done already,
* and \a efirst is the first beveled edge at vertex \a bv.
-*/
+ */
static void build_boundary_terminal_edge(BevelParams *bp, BevVert *bv, EdgeHalf *efirst, bool construct)
{
MemArena *mem_arena = bp->mem_arena;
@@ -1785,6 +1737,7 @@ static void build_boundary_terminal_edge(BevelParams *bp, BevVert *bv, EdgeHalf
}
}
+#if 0
/* Return a value that is v if v is within BEVEL_MAX_ADJUST_PCT of the spec (assumed positive),
* else clamp to make it at most that far away from spec */
static float clamp_adjust(float v, float spec)
@@ -1798,6 +1751,7 @@ static float clamp_adjust(float v, float spec)
else
return v;
}
+#endif
/* Make a circular list of BoundVerts for bv, each of which has the coordinates
* of a vertex on the boundary of the beveled vertex bv->v.
@@ -1814,11 +1768,10 @@ static float clamp_adjust(float v, float spec)
static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
{
MemArena *mem_arena = bp->mem_arena;
- EdgeHalf *efirst, *e, *e2, *e3, *enip, *eip, *eother;
+ EdgeHalf *efirst, *e, *e2, *e3, *enip, *eip, *eon;
BoundVert *v;
- BevVert *bvother;
VMesh *vm;
- float co[3];
+ float co[3], r;
int nip, nnip;
/* Current bevel does nothing if only one edge into a vertex */
@@ -1832,30 +1785,9 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
vm = bv->vmesh;
- /* Find a beveled edge to be efirst. Then for each edge, try matching widths to other end. */
+ /* Find a beveled edge to be efirst */
e = efirst = next_bev(bv, NULL);
BLI_assert(e->is_bev);
- do {
- eother = find_other_end_edge_half(bp, e, &bvother);
- if (eother && bvother->visited && bp->offset_type != BEVEL_AMT_PERCENT) {
- /* try to keep bevel even by matching other end offsets */
- /* sometimes, adjustment can accumulate errors so use the bp->limit_offset to
- * let user limit the adjustment to within a reasonable range around spec */
- if (bp->limit_offset) {
- e->offset_l = clamp_adjust(eother->offset_r, e->offset_l_spec);
- e->offset_r = clamp_adjust(eother->offset_l, e->offset_r_spec);
- }
- else {
- e->offset_l = eother->offset_r;
- e->offset_r = eother->offset_l;
- }
- }
- else {
- /* reset to user spec */
- e->offset_l = e->offset_l_spec;
- e->offset_r = e->offset_r_spec;
- }
- } while ((e = e->next) != efirst);
if (bv->selcount == 1) {
/* special case: only one beveled edge in */
@@ -1869,6 +1801,7 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
e = efirst;
do {
BLI_assert(e->is_bev);
+ eon = NULL;
/* Make the BoundVert for the right side of e; other side will be made
* when the beveled edge to the left of e is handled.
* Analyze edges until next beveled edge.
@@ -1892,7 +1825,8 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
}
else if (nnip > 0) {
if (bp->loop_slide && nnip == 1 && good_offset_on_edge_between(e, e2, enip, bv->v)) {
- offset_on_edge_between(bp, e, e2, enip, bv->v, co);
+ if (offset_on_edge_between(e, e2, enip, bv->v, co, &r))
+ eon = enip;
}
else {
offset_meet(e, e2, bv->v, NULL, true, co);
@@ -1901,7 +1835,8 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
else {
/* nip > 0 and nnip == 0 */
if (bp->loop_slide && nip == 1 && good_offset_on_edge_between(e, e2, eip, bv->v)) {
- offset_on_edge_between(bp, e, e2, eip, bv->v, co);
+ if (offset_on_edge_between(e, e2, eip, bv->v, co, &r))
+ eon = eip;
}
else {
offset_meet(e, e2, bv->v, e->fnext, true, co);
@@ -1912,6 +1847,9 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
v->efirst = e;
v->elast = e2;
v->ebev = e2;
+ v->eon = eon;
+ if (eon)
+ v->sinratio = r;
e->rightv = v;
e2->leftv = v;
for (e3 = e->next; e3 != e2; e3 = e3->next) {
@@ -1941,98 +1879,393 @@ static void build_boundary(BevelParams *bp, BevVert *bv, bool construct)
}
}
-/* Do a global pass to try to make offsets as even as possible.
- * Consider this graph:
- * nodes = BevVerts
- * edges = { (u,v) } where u and v are nodes such that u and v
- * are connected by a mesh edge that has at least one end
- * whose offset does not match the user spec.
- *
- * Do a breadth-first search on this graph, starting from nodes
- * that have any_adjust=true, and changing all
- * not-already-changed offsets on EdgeHalfs to match the
- * corresponding ones that changed on the other end.
- * The graph is dynamic in the sense that having an offset that
- * doesn't meet the user spec can be added as the search proceeds.
- * We want this search to be deterministic (not dependent
- * on order of processing through hash table), so as to avoid
- * flicker to to different decisions made if search is different
- * while dragging the offset number in the UI. So look for the
- * lower vertex number when there is a choice of where to start.
- *
- * Note that this might not process all BevVerts, only the ones
- * that need adjustment.
- */
-static void adjust_offsets(BevelParams *bp)
+#ifdef DEBUG_ADJUST
+static void print_adjust_stats(BoundVert *vstart)
{
- BevVert *bv, *searchbv, *bvother;
- int i, searchi;
- GHashIterator giter;
- EdgeHalf *e, *efirst, *eother;
- GSQueue *q;
- float max_rel_adj;
+ BoundVert *v;
+ EdgeHalf *eleft, *eright;
+ double even_residual2, spec_residual2;
+ double max_even_r, max_even_r_pct;
+ double max_spec_r, max_spec_r_pct;
+ double delta, delta_pct;
+
+ printf("\nSolution analysis\n");
+ even_residual2 = 0.0;
+ spec_residual2 = 0.0;
+ max_even_r = 0.0;
+ max_even_r_pct = 0.0;
+ max_spec_r = 0.0;
+ max_spec_r_pct = 0.0;
+ printf("width matching\n");
+ v = vstart;
+ do {
+ if (v->adjchain != NULL) {
+ eright = v->efirst;
+ eleft = v->adjchain->elast;
+ delta = fabs(eright->offset_r - eleft->offset_l);
+ delta_pct = 100.0 * delta / eright->offset_r_spec;
+ printf("e%d r(%f) vs l(%f): abs(delta)=%f, delta_pct=%f\n",
+ BM_elem_index_get(eright->e), eright->offset_r, eleft->offset_l, delta, delta_pct);
+ even_residual2 += delta * delta;
+ if (delta > max_even_r)
+ max_even_r = delta;
+ if (delta_pct > max_even_r_pct)
+ max_even_r_pct = delta_pct;
+ }
+ v = v->adjchain;
+ } while (v && v != vstart);
+
+ printf("spec matching\n");
+ v = vstart;
+ do {
+ if (v->adjchain != NULL) {
+ eright = v->efirst;
+ eleft = v->adjchain->elast;
+ delta = eright->offset_r - eright->offset_r_spec;
+ delta_pct = 100.0 * delta / eright->offset_r_spec;
+ printf("e%d r(%f) vs r spec(%f): delta=%f, delta_pct=%f\n",
+ BM_elem_index_get(eright->e), eright->offset_r, eright->offset_r_spec, delta, delta_pct);
+ spec_residual2 += delta * delta;
+ delta = fabs(delta);
+ delta_pct = fabs(delta_pct);
+ if (delta > max_spec_r)
+ max_spec_r = delta;
+ if (delta_pct > max_spec_r_pct)
+ max_spec_r_pct = delta_pct;
+
+ delta = eleft->offset_l - eleft->offset_l_spec;
+ delta_pct = 100.0 * delta / eright->offset_l_spec;
+ printf("e%d l(%f) vs l spec(%f): delta=%f, delta_pct=%f\n",
+ BM_elem_index_get(eright->e), eleft->offset_l, eleft->offset_l_spec, delta, delta_pct);
+ spec_residual2 += delta * delta;
+ delta = fabs(delta);
+ delta_pct = fabs(delta_pct);
+ if (delta > max_spec_r)
+ max_spec_r = delta;
+ if (delta_pct > max_spec_r_pct)
+ max_spec_r_pct = delta_pct;
+ }
+ v = v->adjchain;
+ } while (v && v != vstart);
+
+ printf("Analysis Result:\n");
+ printf("even residual2 = %f, spec residual2 = %f\n", even_residual2, spec_residual2);
+ printf("max even delta = %f, max as percent of spec = %f\n", max_even_r, max_even_r_pct);
+ printf("max spec delta = %f, max as percent of spec = %f\n", max_spec_r, max_spec_r_pct);
+}
+#endif
- BLI_assert(!bp->vertex_only);
- GHASH_ITER(giter, bp->vert_hash) {
- bv = BLI_ghashIterator_getValue(&giter);
- bv->visited = false;
+#ifdef FAST_ADJUST_CODE
+/* This code uses a direct solution to the adjustment problem for chains and certain cycles.
+ * It is a two-step approach: first solve for the exact solution of the 'match widths' constraints
+ * using the one degree of freedom that allows for expressing all other widths in terms of that.
+ * And then minimize the spec-matching constraints using the derivative of the least squares
+ * residual in terms of that one degree of freedom.
+ * Unfortunately, the results are in some cases worse than the general least squares solution
+ * for the combined (with weights) problem, so this code is not used.
+ * But keep it here for a while in case peformance issues demand that it be used sometimes. */
+static bool adjust_the_cycle_or_chain_fast(BoundVert *vstart, int np, bool iscycle)
+{
+ BoundVert *v;
+ EdgeHalf *eleft, *eright;
+ float *g;
+ float *g_prod;
+ float gprod, gprod_sum, spec_sum, p;
+ int i;
+
+ g = MEM_mallocN(np * sizeof(float), "beveladjust");
+ g_prod = MEM_mallocN(np * sizeof(float), "beveladjust");
+
+ v = vstart;
+ spec_sum = 0.0f;
+ i = 0;
+ do {
+ g[i] = v->sinratio;
+ if (iscycle || v->adjchain != NULL) {
+ spec_sum += v->efirst->offset_r;
+ }
+ else {
+ spec_sum += v->elast->offset_l;
+ }
+ i++;
+ v = v->adjchain;
+ } while (v && v != vstart);
+
+ gprod = 1.00f;
+ gprod_sum = 1.0f;
+ for (i = np - 1; i > 0; i--) {
+ gprod *= g[i];
+ g_prod[i] = gprod;
+ gprod_sum += gprod;
+ }
+ g_prod[0] = 1.0f;
+ if (iscycle) {
+ gprod *= g[0];
+ if (fabs(gprod - 1.0f) > BEVEL_EPSILON) {
+ /* fast cycle calc only works if total product is 1 */
+ MEM_freeN(g);
+ MEM_freeN(g_prod);
+ return false;
+ }
}
+ if (gprod_sum == 0.0f) {
+ MEM_freeN(g);
+ MEM_freeN(g_prod);
+ return false;
+ }
+ p = spec_sum / gprod_sum;
- q = BLI_gsqueue_new(sizeof(BevVert *));
- /* the following loop terminates because at least one node is visited each time */
- for (;;) {
- /* look for root of a connected component in search graph */
- searchbv = NULL;
- searchi = -1;
- GHASH_ITER(giter, bp->vert_hash) {
- bv = BLI_ghashIterator_getValue(&giter);
- if (!bv->visited && max_edge_half_offset_rel_change(bv) > 0.0f) {
- i = BM_elem_index_get(bv->v);
- if (!searchbv || i < searchi) {
- searchbv = bv;
- searchi = i;
- }
+ /* apply the new offsets */
+ v = vstart;
+ i = 0;
+ do {
+ if (iscycle || v->adjchain != NULL) {
+ eright = v->efirst;
+ eleft = v->elast;
+ eright->offset_r = g_prod[(i + 1) % np] * p;
+ if (iscycle || v != vstart) {
+ eleft->offset_l = v->sinratio * eright->offset_r;
}
}
- if (searchbv == NULL)
- break;
+ else {
+ /* not a cycle, and last of chain */
+ eleft = v->elast;
+ eleft->offset_l = p;
+ }
+ i++;
+ v = v->adjchain;
+ } while (v && v != vstart);
- BLI_gsqueue_push(q, &searchbv);
- while (!BLI_gsqueue_is_empty(q)) {
- BLI_gsqueue_pop(q, &bv);
- /* If do this check, don't have to check for already-on-queue before push, below */
- if (bv->visited)
- continue;
- bv->visited = true;
- build_boundary(bp, bv, false);
-
- e = efirst = &bv->edges[0];
- do {
- eother = find_other_end_edge_half(bp, e, &bvother);
- if (eother && !bvother->visited && edge_half_offset_changed(e)) {
- BLI_gsqueue_push(q, &bvother);
+ MEM_freeN(g);
+ MEM_freeN(g_prod);
+ return true;
+}
+#endif
+
+/* Adjust the offsets for a single cycle or chain.
+ * For chains and some cycles, a fast solution exists.
+ * Otherwise, we set up and solve a linear least squares problem
+ * that tries to minimize the squared differences of lengths
+ * at each end of an edge, and (with smaller weight) the
+ * squared differences of the offsets from their specs.
+ */
+static void adjust_the_cycle_or_chain(BoundVert *vstart, bool iscycle)
+{
+ BoundVert *v;
+ EdgeHalf *eleft, *eright, *enextleft;
+ LinearSolver *solver;
+ double weight, val;
+ int i, np, nrows, row;
+
+ np = 0;
+#ifdef DEBUG_ADJUST
+ printf("\nadjust the %s (with eigen)\n", iscycle ? "cycle" : "chain");
+#endif
+ v = vstart;
+ do {
+#ifdef DEBUG_ADJUST
+ eleft = v->elast;
+ eright = v->efirst;
+ printf(" (left=e%d, right=e%d)", BM_elem_index_get(eleft->e), BM_elem_index_get(eright->e));
+#endif
+ np++;
+ v = v->adjchain;
+ } while (v && v != vstart);
+#ifdef DEBUG_ADJUST
+ printf(" -> %d parms\n", np);
+#endif
+
+#ifdef FAST_ADJUST_CODE
+ if (adjust_the_cycle_or_chain_fast(vstart, np, iscycle))
+ return;
+#endif
+
+ nrows = iscycle ? 3 * np : 3 * np - 3;
+
+ solver = EIG_linear_least_squares_solver_new(nrows, np, 1);
+
+ v = vstart;
+ i = 0;
+ weight = BEVEL_MATCH_SPEC_WEIGHT; /* sqrt of factor to weight down importance of spec match */
+ do {
+ /* except at end of chain, v's indep variable is offset_r of v->efirst */
+ if (iscycle || i < np - 1) {
+ eright = v->efirst;
+ eleft = v->elast;
+ enextleft = v->adjchain->elast;
+#ifdef DEBUG_ADJUST
+ printf("p%d: e%d->offset_r = %f\n", i, BM_elem_index_get(eright->e), eright->offset_r);
+ if (iscycle || v != vstart)
+ printf(" dependent: e%d->offset_l = %f * p%d\n", BM_elem_index_get(eleft->e), v->sinratio, i);
+#endif
+
+ /* residue i: width difference between eright and eleft of next */
+ EIG_linear_solver_matrix_add(solver, i, i, 1.0);
+ EIG_linear_solver_right_hand_side_add(solver, 0, i, 0.0);
+ if (iscycle) {
+ EIG_linear_solver_matrix_add(solver, i > 0 ? i - 1 : np - 1, i, -v->sinratio);
+ }
+ else {
+ if (i > 0) {
+ EIG_linear_solver_matrix_add(solver, i - 1, i, -v->sinratio);
}
- } while ((e = e->next) != efirst);
+ }
+
+ /* residue np + 2*i (if cycle) else np - 1 + 2*i:
+ * right offset for parm i matches its spec; weighted */
+ row = iscycle ? np + 2 * i : np - 1 + 2 * i;
+ EIG_linear_solver_matrix_add(solver, row, i, weight);
+ EIG_linear_solver_right_hand_side_add(solver, 0, row, weight * eright->offset_r);
+#ifdef DEBUG_ADJUST
+ printf("b[%d]=%f * %f, for e%d->offset_r\n", row, weight, eright->offset_r, BM_elem_index_get(eright->e));
+#endif
+
+ /* residue np + 2*i + 1 (if cycle) else np - 1 + 2*i + 1:
+ * left offset for parm i matches its spec; weighted */
+ row = row + 1;
+ EIG_linear_solver_matrix_add(solver, row, (i == np - 1) ? 0 : i + 1, weight * v->adjchain->sinratio);
+ EIG_linear_solver_right_hand_side_add(solver, 0, row, weight * enextleft->offset_l);
+#ifdef DEBUG_ADJUST
+ printf("b[%d]=%f * %f, for e%d->offset_l\n", row, weight, enextleft->offset_l,
+ BM_elem_index_get(enextleft->e));
+#endif
}
- }
- BLI_gsqueue_free(q);
+ else {
+ /* not a cycle, and last of chain */
+ eleft = v->elast;
+#ifdef DEBUG_ADJUST
+ printf("p%d: e%d->offset_l = %f\n", i, BM_elem_index_get(eleft->e), eleft->offset_l);
+#endif
+ /* second part of residue i for last i */
+ EIG_linear_solver_matrix_add(solver, i - 1, i, -1.0);
+ }
+ i++;
+ v = v->adjchain;
+ } while (v && v != vstart);
+ EIG_linear_solver_solve(solver);
+#ifdef DEBUG_ADJUST
+ /* Note: this print only works after solve, but by that time b has been cleared */
+ EIG_linear_solver_print_matrix(solver);
+ printf("\nSolution:\n");
+ for (i = 0; i < np; i++)
+ printf("p%d = %f\n", i, EIG_linear_solver_variable_get(solver, 0, i));
+#endif
- /* Should we auto-limit the error accumulation? Typically, spirals can lead to 100x relative adjustments,
- * and somewhat hacky mechanism of using bp->limit_offset to indicate "clamp the adjustments" is not
- * obvious to users, who almost certainaly want clamping in this situation.
- * The reason not to clamp always is that some models work better without it (e.g., Bent_test in regression
- * suite, where relative adjust maximum is about .6). */
- if (!bp->limit_offset) {
- max_rel_adj = 0.0f;
- GHASH_ITER(giter, bp->vert_hash) {
- bv = BLI_ghashIterator_getValue(&giter);
- max_rel_adj = max_ff(max_rel_adj, max_edge_half_offset_rel_change(bv));
+ /* Use the solution to set new widths */
+ v = vstart;
+ i = 0;
+ do {
+ val = EIG_linear_solver_variable_get(solver, 0, i);
+ if (iscycle || i < np - 1) {
+ eright = v->efirst;
+ eleft = v->elast;
+ eright->offset_r = (float)val;
+#ifdef DEBUG_ADJUST
+ printf("e%d->offset_r = %f\n", BM_elem_index_get(eright->e), eright->offset_r);
+#endif
+ if (iscycle || v != vstart) {
+ eleft->offset_l = (float)(v->sinratio * val);
+#ifdef DEBUG_ADJUST
+ printf("e%d->offset_l = %f\n", BM_elem_index_get(eleft->e), eleft->offset_l);
+#endif
+ }
}
- if (max_rel_adj > BEVEL_MAX_AUTO_ADJUST_PCT / 100.0f) {
- bp->limit_offset = true;
- adjust_offsets(bp);
- bp->limit_offset = false;
+ else {
+ /* not a cycle, and last of chain */
+ eleft = v->elast;
+ eleft->offset_l = (float)val;
+#ifdef DEBUG_ADJUST
+ printf("e%d->offset_l = %f\n", BM_elem_index_get(eleft->e), eleft->offset_l);
+#endif
}
+ i++;
+ v = v->adjchain;
+ } while (v && v != vstart);
+
+#ifdef DEBUG_ADJUST
+ print_adjust_stats(vstart);
+ EIG_linear_solver_print_matrix(solver);
+#endif
+
+ EIG_linear_solver_delete(solver);
+}
+
+/* Adjust the offsets to try to make them, as much as possible,
+ * have even-width bevels with offsets that match their specs.
+ * The problem that we can try to amelieroate is that when loop slide
+ * is active, the meet point will probably not be the one that makes
+ * both sides have their specified width. And because both ends may be
+ * on loop slide edges, the widths at each end could be different.
+ *
+ * It turns out that the dependent offsets either form chains or
+ * cycles, and we can process each of those separatey.
+ */
+static void adjust_offsets(BevelParams *bp)
+{
+ BevVert *bv, *bvcur;
+ BoundVert *v, *vanchor, *vchainstart, *vnext;
+ EdgeHalf *enext;
+ GHashIterator giter;
+ bool iscycle;
+
+ /* find and process chains and cycles of unvisited BoundVerts that have eon set */
+ GHASH_ITER(giter, bp->vert_hash) {
+ bv = bvcur = BLI_ghashIterator_getValue(&giter);
+ vanchor = bv->vmesh->boundstart;
+ do {
+ if (vanchor->visited || !vanchor->eon)
+ continue;
+
+ /* Find one of (1) a cycle that starts and ends at v
+ * where each v has v->eon set and had not been visited before;
+ * or (2) a chain of v's where the start and end of the chain do not have
+ * v->eon set but all else do.
+ * It is OK for the first and last elements to
+ * have been visited before, but not any of the inner ones.
+ * We chain the v's together through v->adjchain, and are following
+ * them in left->right direction, meaning that the left side of one edge
+ * pairs with the right side of the next edge in the cycle or chain. */
+
+ /* first follow paired edges in left->right direction */
+ v = vchainstart = vanchor;
+ iscycle = false;
+ while (v->eon && !v->visited && !iscycle) {
+ enext = find_other_end_edge_half(bp, v->efirst, &bvcur);
+ BLI_assert(enext != NULL);
+ vnext = enext->leftv;
+ v->adjchain = vnext;
+ v->visited = true;
+ if (vnext->visited) {
+ if (vnext != vchainstart) {
+ break;
+ }
+ adjust_the_cycle_or_chain(vchainstart, true);
+ iscycle = true;
+ }
+ v = vnext;
+ }
+ if (!iscycle) {
+ /* right->left direction, changing vchainstart at each step */
+ v = vchainstart;
+ bvcur = bv;
+ do {
+ enext = find_other_end_edge_half(bp, v->elast, &bvcur);
+ BLI_assert(enext != NULL);
+ vnext = enext->rightv;
+ vnext->adjchain = v;
+ vchainstart = vnext;
+ v->visited = true;
+ v = vnext;
+ } while (!v->visited && v->eon);
+ adjust_the_cycle_or_chain(vchainstart, false);
+ }
+ } while ((vanchor = vanchor->next) != bv->vmesh->boundstart);
+ }
+
+ /* Rebuild boundaries with new width specs */
+ GHASH_ITER(giter, bp->vert_hash) {
+ bv = BLI_ghashIterator_getValue(&giter);
+ build_boundary(bp, bv, false);
}
}
@@ -2295,7 +2528,7 @@ static int interp_range(const float *frac, int n, const float f, float *r_rest)
/* Interpolate given vmesh to make one with target nseg border vertices on the profiles */
static VMesh *interp_vmesh(BevelParams *bp, VMesh *vm0, int nseg)
{
- int n, ns0, nseg2, odd, i, j, k, j0, k0, k0prev;
+ int n, ns0, nseg2, odd, i, j, k, j0, k0, k0prev, j0inc, k0inc;
float *prev_frac, *frac, *new_frac, *prev_new_frac;
float f, restj, restk, restkprev;
float quad[4][3], co[3], center[3];
@@ -2339,10 +2572,12 @@ static VMesh *interp_vmesh(BevelParams *bp, VMesh *vm0, int nseg)
copy_v3_v3(co, mesh_vert_canon(vm0, i, j0, k0)->co);
}
else {
+ j0inc = (restj < BEVEL_EPSILON || j0 == ns0) ? 0 : 1;
+ k0inc = (restk < BEVEL_EPSILON || k0 == ns0) ? 0 : 1;
copy_v3_v3(quad[0], mesh_vert_canon(vm0, i, j0, k0)->co);
- copy_v3_v3(quad[1], mesh_vert_canon(vm0, i, j0, k0 + 1)->co);
- copy_v3_v3(quad[2], mesh_vert_canon(vm0, i, j0 + 1, k0 + 1)->co);
- copy_v3_v3(quad[3], mesh_vert_canon(vm0, i, j0 + 1, k0)->co);
+ copy_v3_v3(quad[1], mesh_vert_canon(vm0, i, j0, k0 + k0inc)->co);
+ copy_v3_v3(quad[2], mesh_vert_canon(vm0, i, j0 + j0inc, k0 + k0inc)->co);
+ copy_v3_v3(quad[3], mesh_vert_canon(vm0, i, j0 + j0inc, k0)->co);
interp_bilinear_quad_v3(quad, restk, restj, co);
}
copy_v3_v3(mesh_vert(vm1, i, j, k)->co, co);
@@ -2532,9 +2767,8 @@ static VMesh *cubic_subdiv(BevelParams *bp, VMesh *vm0)
return vm1;
}
-/* Special case for cube corner, when r is PRO_SQUARE_R,
- * meaning straight sides */
-static VMesh *make_cube_corner_straight(MemArena *mem_arena, int nseg)
+/* Special case for cube corner, when r is PRO_SQUARE_R, meaning straight sides */
+static VMesh *make_cube_corner_square(MemArena *mem_arena, int nseg)
{
VMesh *vm;
float co[3];
@@ -2564,6 +2798,46 @@ static VMesh *make_cube_corner_straight(MemArena *mem_arena, int nseg)
return vm;
}
+/* Special case for cube corner, when r is PRO_SQUARE_IN_R, meaning inward
+ * straight sides.
+ * We mostly don't want a VMesh at all for this case -- just a three-way weld
+ * with a triangle in the middle for odd nseg */
+static VMesh *make_cube_corner_square_in(MemArena *mem_arena, int nseg)
+{
+ VMesh *vm;
+ float co[3];
+ float b;
+ int i, k, ns2, odd;
+
+ ns2 = nseg / 2;
+ odd = nseg % 2;
+ vm = new_adj_vmesh(mem_arena, 3, nseg, NULL);
+ vm->count = 0; // reset, so following loop will end up with correct count
+ for (i = 0; i < 3; i++) {
+ zero_v3(co);
+ co[i] = 1.0f;
+ add_new_bound_vert(mem_arena, vm, co);
+ }
+ if (odd)
+ b = 2.0f / (2.0f * (float)ns2 + (float)M_SQRT2);
+ else
+ b = 2.0f / (float)nseg;
+ for (i = 0; i < 3; i++) {
+ for (k = 0; k <= ns2; k++) {
+ co[i] = 1.0f - (float)k * b;
+ co[(i + 1) % 3] = 0.0f;
+ co[(i + 2) % 3] = 0.0f;
+ copy_v3_v3(mesh_vert(vm, i, 0, k)->co, co);
+ co[(i + 1) % 3] = 1.0f - (float)k * b;
+ co[(i + 2) % 3] = 0.0f;
+ co[i] = 0.0f;
+ copy_v3_v3(mesh_vert(vm, i, 0, nseg - k)->co, co);
+ }
+ }
+ return vm;
+}
+
+
/* Make a VMesh with nseg segments that covers the unit radius sphere octant
* with center at (0,0,0).
* This has BoundVerts at (1,0,0), (0,1,0) and (0,0,1), with quarter circle arcs
@@ -2580,7 +2854,9 @@ static VMesh *make_cube_corner_adj_vmesh(BevelParams *bp)
float co[3], coc[3];
if (r == PRO_SQUARE_R)
- return make_cube_corner_straight(mem_arena, nseg);
+ return make_cube_corner_square(mem_arena, nseg);
+ else if (r == PRO_SQUARE_IN_R)
+ return make_cube_corner_square_in(mem_arena, nseg);
/* initial mesh has 3 sides, 2 segments */
vm0 = new_adj_vmesh(mem_arena, 3, 2, NULL);
@@ -2638,6 +2914,7 @@ static VMesh *make_cube_corner_adj_vmesh(BevelParams *bp)
}
}
}
+
return vm1;
}
@@ -2895,6 +3172,254 @@ static float snap_face_dist_squared(float *co, BMFace *f, BMEdge **r_snap_e, flo
return beste_d2;
}
+static void build_center_ngon(BMesh *bm, BevVert *bv, int mat_nr)
+{
+ VMesh *vm = bv->vmesh;
+ BoundVert *v;
+ int i, ns2;
+ BMFace *frep;
+ BMEdge *frep_e1, *frep_e2, *frep_e;
+ BMVert **vv = NULL;
+ BMFace **vf = NULL;
+ BMEdge **ve = NULL;
+ BLI_array_staticdeclare(vv, BM_DEFAULT_NGON_STACK_SIZE);
+ BLI_array_staticdeclare(vf, BM_DEFAULT_NGON_STACK_SIZE);
+ BLI_array_staticdeclare(ve, BM_DEFAULT_NGON_STACK_SIZE);
+
+ ns2 = vm->seg / 2;
+ if (bv->any_seam) {
+ frep = boundvert_rep_face(vm->boundstart, NULL);
+ get_incident_edges(frep, bv->v, &frep_e1, &frep_e2);
+ }
+ else {
+ frep = NULL;
+ frep_e1 = frep_e2 = NULL;
+ }
+ v = vm->boundstart;
+ do {
+ i = v->index;
+ BLI_array_append(vv, mesh_vert(vm, i, ns2, ns2)->v);
+ if (frep) {
+ BLI_array_append(vf, frep);
+ frep_e = find_closer_edge(mesh_vert(vm, i, ns2, ns2)->v->co, frep_e1, frep_e2);
+ BLI_array_append(ve, v == vm->boundstart ? NULL : frep_e);
+ }
+ else {
+ BLI_array_append(vf, boundvert_rep_face(v, NULL));
+ BLI_array_append(ve, NULL);
+ }
+ } while ((v = v->next) != vm->boundstart);
+ bev_create_ngon(bm, vv, BLI_array_len(vv), vf, frep, ve, mat_nr, true);
+
+ BLI_array_free(vv);
+ BLI_array_free(vf);
+ BLI_array_free(ve);
+}
+
+/* Special case of bevel_build_rings when tri-corner and profile is 0.
+ * There is no corner mesh except, if nseg odd, for a center poly.
+ * Boundary verts merge with previous ones according to pattern:
+ * (i, 0, k) merged with (i+1, 0, ns-k) for k <= ns/2 */
+static void build_square_in_vmesh(BevelParams *bp, BMesh *bm, BevVert *bv, VMesh *vm1)
+{
+ int n, ns, ns2, odd, i, k;
+ VMesh *vm;
+
+ vm = bv->vmesh;
+ n = vm->count;
+ ns = vm->seg;
+ ns2 = ns / 2;
+ odd = ns % 2;
+
+ for (i = 0; i < n; i++) {
+ for (k = 1; k < ns; k++) {
+ copy_v3_v3(mesh_vert(vm, i, 0, k)->co, mesh_vert(vm1, i, 0, k)->co);
+ if (i > 0 && k <= ns2) {
+ mesh_vert(vm, i, 0, k)->v = mesh_vert(vm, i - 1, 0, ns - k)->v;
+ }
+ else if (i == n - 1 && k > ns2) {
+ mesh_vert(vm, i, 0, k)->v = mesh_vert(vm, 0, 0, ns - k)->v;
+ }
+ else {
+ create_mesh_bmvert(bm, vm, i, 0, k, bv->v);
+ }
+ }
+ }
+ if (odd) {
+ for (i = 0; i < n; i++) {
+ mesh_vert(vm, i, ns2, ns2)->v = mesh_vert(vm, i, 0, ns2)->v;
+ }
+ build_center_ngon(bm, bv, bp->mat_nr);
+ }
+}
+
+/* copy whichever of a and b is closer to v into r */
+static void closer_v3_v3v3v3(float r[3], float a[3], float b[3], float v[3])
+{
+ if (len_squared_v3v3(a, v) <= len_squared_v3v3(b, v))
+ copy_v3_v3(r, a);
+ else
+ copy_v3_v3(r, b);
+}
+
+/* Special case of VMesh when profile == 1 and there are 3 or more beveled edges.
+ * We want the effect of parallel offset lines (n/2 of them) on each side of the center, for even n.
+ * Wherever they intersect with each other between two successive beveled edges, those intersections
+ * are part of the vmesh rings.
+ * We have to move the boundary edges too -- the usual method is to make one profile plane between
+ * successive BoundVerts, but for the effect we want here, there will be two planes, one on each side
+ * of the original edge.
+ */
+static VMesh *square_out_adj_vmesh(BevelParams *bp, BevVert *bv)
+{
+ int n, ns, ns2, odd, i, j, k, ikind, im1, clstride;
+ float bndco[3], dir1[3], dir2[3], co1[3], co2[3], meet1[3], meet2[3], v1co[3], v2co[3];
+ float *on_edge_cur, *on_edge_prev, *p;
+ float ns2inv, finalfrac, ang;
+ BoundVert *bndv;
+ EdgeHalf *e1, *e2;
+ VMesh *vm;
+ float *centerline;
+
+ n = bv->vmesh->count;
+ ns = bv->vmesh->seg;
+ ns2 = ns / 2;
+ odd = ns % 2;
+ ns2inv = 1.0f / (float) ns2;
+ vm = new_adj_vmesh(bp->mem_arena, n, ns, bv->vmesh->boundstart);
+ clstride = 3 * (ns2 + 1);
+ centerline = MEM_mallocN(clstride * n * sizeof(float), "bevel");
+
+ /* find on_edge, place on bndv[i]'s elast where offset line would meet,
+ * averaging with position where next sector's offset line would meet */
+ bndv = vm->boundstart;
+ for (i = 0; i < n; i++) {
+ copy_v3_v3(bndco, bndv->nv.co);
+ e1 = bndv->efirst;
+ e2 = bndv->elast;
+ sub_v3_v3v3(dir1, e1->e->v1->co, e1->e->v2->co);
+ sub_v3_v3v3(dir2, e2->e->v1->co, e2->e->v2->co);
+ add_v3_v3v3(co1, bndco, dir1);
+ add_v3_v3v3(co2, bndco, dir2);
+ /* intersect e1 with line through bndv parallel to e2 to get v1co */
+ ikind = isect_line_line_v3(e1->e->v1->co, e1->e->v2->co, bndco, co2, meet1, meet2);
+
+ if (ikind == 0) {
+ /* Placeholder: this should get eliminated by min dist test with adjacent edge */
+ mid_v3_v3v3(v1co, e1->e->v1->co, e1->e->v2->co);
+ }
+ else {
+ /* if the lines are skew (ikind == 2), want meet1 which is on e1 */
+ copy_v3_v3(v1co, meet1);
+ }
+ /* intersect e2 with line through bndv parallel to e1 to get v2co */
+ ikind = isect_line_line_v3(e2->e->v1->co, e2->e->v2->co, bndco, co1, meet1, meet2);
+ if (ikind == 0) {
+ mid_v3_v3v3(v2co, e2->e->v1->co, e2->e->v2->co);
+ }
+ else {
+ copy_v3_v3(v2co, meet1);
+ }
+
+ /* want on_edge[i] to be min dist to bv->v of v2co and the v1co of next iteration */
+ on_edge_cur = centerline + clstride * i;
+ on_edge_prev = centerline + clstride * ((i == 0) ? n - 1 : i - 1);
+ if (i == 0) {
+ copy_v3_v3(on_edge_cur, v2co);
+ copy_v3_v3(on_edge_prev, v1co);
+ }
+ else if (i == n - 1) {
+ closer_v3_v3v3v3(on_edge_cur, on_edge_cur, v2co, bv->v->co);
+ closer_v3_v3v3v3(on_edge_prev, on_edge_prev, v1co, bv->v->co);
+ }
+ else {
+ copy_v3_v3(on_edge_cur, v2co);
+ closer_v3_v3v3v3(on_edge_prev, on_edge_prev, v1co, bv->v->co);
+ }
+ bndv = bndv->next;
+ }
+
+ /* fill in rest of centerlines by interpolation */
+ copy_v3_v3(co2, bv->v->co);
+ bndv = vm->boundstart;
+ for (i = 0; i < n; i++) {
+ if (odd) {
+ ang = 0.5f * angle_v3v3v3(bndv->nv.co, co1, bndv->next->nv.co);
+ if (ang > BEVEL_SMALL_ANG) {
+ /* finalfrac is length along arms of isoceles triangle with top angle 2*ang
+ * such that the base of the triangle is 1.
+ * This is used in interpolation along centerline in odd case.
+ * To avoid too big a drop from bv, cap finalfrac a 0.8 arbitrarily */
+ finalfrac = 0.5f / sin(ang);
+ if (finalfrac > 0.8f)
+ finalfrac = 0.8f;
+ }
+ else {
+ finalfrac = 0.8f;
+ }
+ ns2inv = 1.0f / (ns2 + finalfrac);
+ }
+
+ p = centerline + clstride * i;
+ copy_v3_v3(co1, p);
+ p += 3;
+ for (j = 1; j <= ns2; j++) {
+ interp_v3_v3v3(p, co1, co2, j * ns2inv);
+ p += 3;
+ }
+ bndv = bndv->next;
+ }
+
+ /* coords of edges and mid or near-mid line */
+ bndv = vm->boundstart;
+ for (i = 0; i < n; i++) {
+ copy_v3_v3(co1, bndv->nv.co);
+ copy_v3_v3(co2, centerline + clstride * (i == 0 ? n - 1 : i - 1));
+ for (j = 0; j < ns2 + odd; j++) {
+ interp_v3_v3v3(mesh_vert(vm, i, j, 0)->co, co1, co2, j * ns2inv);
+ }
+ copy_v3_v3(co2, centerline + clstride * i);
+ for (k = 1; k <= ns2; k++) {
+ interp_v3_v3v3(mesh_vert(vm, i, 0, k)->co, co1, co2, k * ns2inv);
+ }
+ bndv = bndv->next;
+ }
+ if (!odd)
+ copy_v3_v3(mesh_vert(vm, 0, ns2, ns2)->co, bv->v->co);
+ vmesh_copy_equiv_verts(vm);
+
+ /* fill in interior points by interpolation from edges to centerlines */
+ bndv = vm->boundstart;
+ for (i = 0; i < n; i++) {
+ im1 = (i == 0) ? n - 1 : i - 1;
+ for (j = 1; j < ns2 + odd; j++) {
+ for (k = 1; k <= ns2; k++) {
+ ikind = isect_line_line_v3(
+ mesh_vert(vm, i, 0, k)->co, centerline + clstride * im1 + 3 * k,
+ mesh_vert(vm, i, j, 0)->co, centerline + clstride * i + 3 * j,
+ meet1, meet2);
+ if (ikind == 0) {
+ /* how can this happen? fall back on interpolation in one direction if it does */
+ interp_v3_v3v3(mesh_vert(vm, i, j, k)->co,
+ mesh_vert(vm, i, 0, k)->co, centerline + clstride * im1 + 3 * k, j * ns2inv);
+ }
+ else if (ikind == 1) {
+ copy_v3_v3(mesh_vert(vm, i, j, k)->co, meet1);
+ }
+ else {
+ mid_v3_v3v3(mesh_vert(vm, i, j, k)->co, meet1, meet2);
+ }
+ }
+ }
+ bndv = bndv->next;
+ }
+
+ vmesh_copy_equiv_verts(vm);
+
+ MEM_freeN(centerline);
+ return vm;
+}
+
/*
* Given that the boundary is built and the boundary BMVerts have been made,
* calculate the positions of the interior mesh points for the M_ADJ pattern,
@@ -2917,14 +3442,27 @@ static void bevel_build_rings(BevelParams *bp, BMesh *bm, BevVert *bv)
odd = ns % 2;
BLI_assert(n >= 3 && ns > 1);
+
vpipe = pipe_test(bv);
- if (vpipe)
+ if (bp->pro_super_r == PRO_SQUARE_R && bv->selcount >= 3 && !odd) {
+ vm1 = square_out_adj_vmesh(bp, bv);
+ }
+ else if (vpipe) {
vm1 = pipe_adj_vmesh(bp, bv, vpipe);
- else if (tri_corner_test(bp, bv))
+ }
+ else if (tri_corner_test(bp, bv)) {
vm1 = tri_corner_adj_vmesh(bp, bv);
- else
+ /* the PRO_SQUARE_IN_R profile has boundary edges that merge
+ * and no internal ring polys except possibly center ngon */
+ if (bp->pro_super_r == PRO_SQUARE_IN_R) {
+ build_square_in_vmesh(bp, bm, bv, vm1);
+ return;
+ }
+ }
+ else {
vm1 = adj_vmesh(bp, bv);
+ }
/* copy final vmesh into bv->vmesh, make BMVerts and BMFaces */
vm = bv->vmesh;
@@ -3037,48 +3575,13 @@ static void bevel_build_rings(BevelParams *bp, BMesh *bm, BevVert *bv)
/* center ngon */
if (odd) {
- BMFace *frep;
- BMEdge *frep_e1, *frep_e2, *frep_e;
- BMVert **vv = NULL;
- BMFace **vf = NULL;
- BMEdge **ve = NULL;
- BLI_array_staticdeclare(vv, BM_DEFAULT_NGON_STACK_SIZE);
- BLI_array_staticdeclare(vf, BM_DEFAULT_NGON_STACK_SIZE);
- BLI_array_staticdeclare(ve, BM_DEFAULT_NGON_STACK_SIZE);
-
- if (bv->any_seam) {
- frep = boundvert_rep_face(vm->boundstart, NULL);
- get_incident_edges(frep, bv->v, &frep_e1, &frep_e2);
- }
- else {
- frep = NULL;
- frep_e1 = frep_e2 = NULL;
- }
- v = vm->boundstart;
- do {
- i = v->index;
- BLI_array_append(vv, mesh_vert(vm, i, ns2, ns2)->v);
- if (frep) {
- BLI_array_append(vf, frep);
- frep_e = find_closer_edge(mesh_vert(vm, i, ns2, ns2)->v->co, frep_e1, frep_e2);
- BLI_array_append(ve, v == vm->boundstart ? NULL : frep_e);
- }
- else {
- BLI_array_append(vf, boundvert_rep_face(v, NULL));
- BLI_array_append(ve, NULL);
- }
- } while ((v = v->next) != vm->boundstart);
- bev_create_ngon(bm, vv, BLI_array_count(vv), vf, frep, ve, mat_nr, true);
-
- BLI_array_free(vv);
- BLI_array_free(vf);
- BLI_array_free(ve);
+ build_center_ngon(bm, bv, mat_nr);
}
}
/* If we make a poly out of verts around bv, snapping to rep frep, will uv poly have zero area?
* The uv poly is made by snapping all outside-of-frep vertices to the closest edge in frep.
- * Assume that this funciton is called when the only inside-of-frep vertex is vm->boundstart.
+ * Assume that this function is called when the only inside-of-frep vertex is vm->boundstart.
* The poly will have zero area if the distance of that first vertex to some edge e is zero, and all
* the other vertices snap to e or snap to an edge at a point that is essentially on e too. */
static bool is_bad_uv_poly(BevVert *bv, BMFace *frep)
@@ -3191,6 +3694,7 @@ static void bevel_build_trifan(BevelParams *bp, BMesh *bm, BevVert *bv)
BMFace *f_new;
BLI_assert(v_fan == l_fan->v);
f_new = BM_face_split(bm, f, l_fan, l_fan->next->next, &l_new, NULL, false);
+ flag_out_edge(bm, l_new->e);
if (f_new->len > f->len) {
f = f_new;
@@ -3237,6 +3741,7 @@ static void bevel_build_quadstrip(BevelParams *bp, BMesh *bm, BevVert *bv)
else {
BM_face_split(bm, f, l_a, l_b, &l_new, NULL, false);
f = l_new->f;
+ flag_out_edge(bm, l_new->e);
/* walk around the new face to get the next verts to split */
l_a = l_new->prev;
@@ -3256,7 +3761,7 @@ static void bevel_vert_two_edges(BevelParams *bp, BMesh *bm, BevVert *bv)
{
VMesh *vm = bv->vmesh;
BMVert *v1, *v2;
- BMEdge *e_eg;
+ BMEdge *e_eg, *bme;
Profile *pro;
float co[3];
BoundVert *bndv;
@@ -3298,7 +3803,9 @@ static void bevel_vert_two_edges(BevelParams *bp, BMesh *bm, BevVert *bv)
v1 = mesh_vert(vm, 0, 0, k)->v;
v2 = mesh_vert(vm, 0, 0, k + 1)->v;
BLI_assert(v1 != NULL && v2 != NULL);
- BM_edge_create(bm, v1, v2, e_eg, BM_CREATE_NO_DOUBLE);
+ bme = BM_edge_create(bm, v1, v2, e_eg, BM_CREATE_NO_DOUBLE);
+ if (bme)
+ flag_out_edge(bm, bme);
}
}
}
@@ -3453,7 +3960,7 @@ static int bevel_edge_order_extend(BMesh *bm, BevVert *bv, int i)
BLI_array_append(sucs, bme2);
}
}
- nsucs = BLI_array_count(sucs);
+ nsucs = BLI_array_len(sucs);
bestj = j = i;
for (sucindex = 0; sucindex < nsucs; sucindex++) {
@@ -3466,7 +3973,7 @@ static int bevel_edge_order_extend(BMesh *bm, BevVert *bv, int i)
tryj = bevel_edge_order_extend(bm, bv, j + 1);
if (tryj > bestj || (tryj == bestj && edges_face_connected_at_vert(bv->edges[tryj].e, bv->edges[0].e))) {
bestj = tryj;
- BLI_array_empty(save_path);
+ BLI_array_clear(save_path);
for (k = j + 1; k <= bestj; k++) {
BLI_array_append(save_path, bv->edges[k].e);
}
@@ -3879,7 +4386,7 @@ static BevVert *bevel_vert_construct(BMesh *bm, BevelParams *bp, BMVert *v)
/* Face f has at least one beveled vertex. Rebuild f */
static bool bev_rebuild_polygon(BMesh *bm, BevelParams *bp, BMFace *f)
{
- BMIter liter;
+ BMIter liter, eiter, fiter;
BMLoop *l, *lprev;
BevVert *bv;
BoundVert *v, *vstart, *vend;
@@ -3887,10 +4394,10 @@ static bool bev_rebuild_polygon(BMesh *bm, BevelParams *bp, BMFace *f)
VMesh *vm;
int i, k, n;
bool do_rebuild = false;
- bool go_ccw, corner3special;
+ bool go_ccw, corner3special, keep;
BMVert *bmv;
BMEdge *bme, *bme_new, *bme_prev;
- BMFace *f_new;
+ BMFace *f_new, *f_other;
BMVert **vv = NULL;
BMVert **vv_fix = NULL;
BMEdge **ee = NULL;
@@ -3993,15 +4500,15 @@ static bool bev_rebuild_polygon(BMesh *bm, BevelParams *bp, BMFace *f)
}
}
if (do_rebuild) {
- n = BLI_array_count(vv);
+ n = BLI_array_len(vv);
f_new = bev_create_ngon(bm, vv, n, NULL, f, NULL, -1, true);
- for (k = 0; k < BLI_array_count(vv_fix); k++) {
+ for (k = 0; k < BLI_array_len(vv_fix); k++) {
bev_merge_uvs(bm, vv_fix[k]);
}
/* copy attributes from old edges */
- BLI_assert(n == BLI_array_count(ee));
+ BLI_assert(n == BLI_array_len(ee));
bme_prev = ee[n - 1];
for (k = 0; k < n; k++) {
bme_new = BM_edge_exists(vv[k], vv[(k + 1) % n]);
@@ -4028,9 +4535,21 @@ static bool bev_rebuild_polygon(BMesh *bm, BevelParams *bp, BMFace *f)
}
}
- /* don't select newly created boundary faces... */
+ /* don't select newly or return created boundary faces... */
if (f_new) {
BM_elem_flag_disable(f_new, BM_ELEM_TAG);
+ /* Also don't want new edges that aren't part of a new bevel face */
+ BM_ITER_ELEM(bme, &eiter, f_new, BM_EDGES_OF_FACE) {
+ keep = false;
+ BM_ITER_ELEM(f_other, &fiter, bme, BM_FACES_OF_EDGE) {
+ if (BM_elem_flag_test(f_other, BM_ELEM_TAG)) {
+ keep = true;
+ break;
+ }
+ }
+ if (!keep)
+ disable_flag_out_edge(bm, bme);
+ }
}
}
@@ -4112,8 +4631,9 @@ static void bevel_reattach_wires(BMesh *bm, BevelParams *bp, BMVert *v)
}
}
} while ((bndv = bndv->next) != bv->vmesh->boundstart);
- if (vclosest)
+ if (vclosest) {
BM_edge_create(bm, vclosest, votherclosest, e, BM_CREATE_NO_DOUBLE);
+ }
}
}
@@ -4323,203 +4843,501 @@ static void bevel_build_edge_polygons(BMesh *bm, BevelParams *bp, BMEdge *bme)
}
}
-/* Returns the square of the length of the chord from parameter u0 to parameter u1
- * of superellipse_co. */
-static float superellipse_chord_length_squared(float u0, float u1, float r)
-{
- float a[2], b[2];
- BLI_assert(u0 >= 0.0f && u1 >= u0 && u1 <= 2.0f);
- superellipse_co(u0, r, a);
- superellipse_co(u1, r, b);
- return len_squared_v2v2(a, b);
+/* Find xnew > x0 so that distance((x0,y0), (xnew, ynew)) = dtarget.
+ * False position Illinois method used because the function is somewhat linear
+ * -> linear interpolation converges fast.
+ * Assumes that the gradient is always between 1 and -1 for
+ * x in [x0, x0+dtarget] */
+static double find_superellipse_chord_endpoint(double x0, double dtarget, float r, bool rbig)
+{
+ double xmin, xmax, ymin, ymax, dmaxerr, dminerr, dnewerr, xnew, ynew;
+ double y0 = superellipse_co(x0, r, rbig);
+ const double tol = 1e-13; // accumulates for many segments so use low value
+ const int maxiter = 10;
+ bool lastupdated_upper;
+
+ /* For gradient between -1 and 1, xnew can only be in
+ * [x0 + sqrt(2)/2*dtarget, x0 + dtarget]. */
+ xmin = x0 + M_SQRT2 / 2.0 * dtarget;
+ if (xmin > 1.0)
+ xmin = 1.0;
+ xmax = x0 + dtarget;
+ if (xmax > 1.0)
+ xmax = 1.0;
+ ymin = superellipse_co(xmin, r, rbig);
+ ymax = superellipse_co(xmax, r, rbig);
+
+ /* Note: using distance**2 (no sqrt needed) does not converge that well. */
+ dmaxerr = sqrt(pow((xmax - x0), 2) + pow((ymax - y0), 2)) - dtarget;
+ dminerr = sqrt(pow((xmin - x0), 2) + pow((ymin - y0), 2)) - dtarget;
+
+ xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
+ lastupdated_upper = true;
+
+ for (int iter = 0; iter < maxiter; iter++) {
+ ynew = superellipse_co(xnew, r, rbig);
+ dnewerr = sqrt(pow((xnew - x0), 2) + pow((ynew - y0), 2)) - dtarget;
+ if (fabs(dnewerr) < tol) {
+ break;
+ }
+ if (dnewerr < 0) {
+ xmin = xnew;
+ ymin = ynew;
+ dminerr = dnewerr;
+ if (!lastupdated_upper) {
+ xnew = (dmaxerr / 2 * xmin - dminerr * xmax) / (dmaxerr / 2 - dminerr);
+ }
+ else {
+ xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
+ }
+ lastupdated_upper = false;
+ }
+ else {
+ xmax = xnew;
+ ymax = ynew;
+ dmaxerr = dnewerr;
+ if (lastupdated_upper) {
+ xnew = (dmaxerr * xmin - dminerr / 2 * xmax) / (dmaxerr - dminerr / 2);
+ }
+ else {
+ xnew = xmax - dmaxerr * (xmax - xmin) / (dmaxerr - dminerr);
+ }
+ lastupdated_upper = true;
+ }
+ }
+ return xnew;
}
-/* Find parameter u >= u0 to make chord of squared length d2goal,
- * from u0 to u on superellipse with parameter r.
- * If it cannot be found, return -1.0f. */
-static float find_superellipse_chord_u(float u0, float d2goal, float r)
+ /* This search procedure to find equidistant points (x,y) in the first
+ * superellipse quadrant works for every superellipse exponent but is more
+ * expensive than known solutions for special cases.
+ * Call the point on superellipse that intersects x=y line mx.
+ * For r>=1 use only the range x in [0,mx] and mirror the rest along x=y line,
+ * for r<1 use only x in [mx,1]. Points are initially spaced and iteratively
+ * repositioned to have the same distance. */
+
+static void find_even_superellipse_chords_general(int seg, float r, double *xvals, double *yvals)
{
- float ulow, uhigh, u, d2, d2max;
- const float dtol = 1e-4f;
- const float utol = 1e-6f;
- const float umax = 2.0f;
-
- if (d2goal == 0.0f)
- return u0;
- d2max = superellipse_chord_length_squared(u0, umax, r);
- if (fabsf(d2goal - d2max) <= dtol)
- return umax;
- if (d2goal - d2max > dtol)
- return -1.0f;
-
- /* binary search for good u value */
- ulow = u0;
- uhigh = umax;
- do {
- u = 0.5f * (ulow + uhigh);
- d2 = superellipse_chord_length_squared(u0, u, r);
- if (fabsf(d2goal - d2) <= dtol)
+ const int smoothitermax = 10;
+ const double error_tol = 1e-7;
+ int i;
+ int imax = (seg + 1) / 2 - 1; /* ceiling division - 1 */
+
+ double d, dmin, dmax;
+ double davg;
+ double mx;
+ double sum;
+ double temp;
+
+ bool precision_reached;
+ bool seg_odd = seg % 2;
+ bool rbig;
+
+ if (r > 1.0f) {
+ rbig = true;
+ mx = pow(0.5, 1.0 / r);
+ }
+ else {
+ rbig = false;
+ mx = 1 - pow(0.5, 1.0 / r);
+ }
+
+ /* Initial positions, linear spacing along x axis. */
+ for (i = 0; i <= imax; i++) {
+ xvals[i] = i * mx / seg * 2;
+ yvals[i] = superellipse_co(xvals[i], r, rbig);
+ }
+ yvals[0] = 1;
+
+ /* Smooth distance loop */
+ for (int iter = 0; iter < smoothitermax; iter++) {
+ sum = 0.0;
+ dmin = 2.0;
+ dmax = 0.0;
+ /* Update distances between neighbor points. Store the highest and
+ * lowest to see if the maximum error to average distance (which isn't
+ * known yet) is below required precision. */
+ for (i = 0; i < imax; i++) {
+ d = sqrt(pow((xvals[i + 1] - xvals[i]), 2) + pow((yvals[i + 1] - yvals[i]), 2));
+ sum += d;
+ if (d > dmax) {
+ dmax = d;
+ }
+ if (d < dmin) {
+ dmin = d;
+ }
+ }
+ /* For last distance, weight with 1/2 if seg_odd. */
+ if (seg_odd) {
+ sum += M_SQRT2 / 2 * (yvals[imax] - xvals[imax]);
+ davg = sum / (imax + 0.5);
+ }
+ else {
+ sum += sqrt(pow((xvals[imax] - mx), 2) + pow((yvals[imax] - mx), 2));
+ davg = sum / (imax + 1.0);
+ }
+ /* Max error in tolerance? -> Quit. */
+ if (dmax - davg > error_tol) {
+ precision_reached = false;
+ }
+ if (dmin - davg < error_tol) {
+ precision_reached = false;
+ }
+ if (precision_reached) {
break;
- if (d2 < d2goal)
- ulow = u;
- else
- uhigh = u;
- } while (fabsf(uhigh - ulow) > utol);
- return u;
+ }
+
+
+ /* Update new coordinates. */
+ for (i = 1; i <= imax; i++) {
+ xvals[i] = find_superellipse_chord_endpoint(xvals[i - 1], davg, r, rbig);
+ yvals[i] = superellipse_co(xvals[i], r, rbig);
+ }
+ }
+
+ /* Fill remaining. */
+ if (!seg_odd) {
+ xvals[imax + 1] = mx;
+ yvals[imax + 1] = mx;
+ }
+ for (i = imax + 1; i <= seg; i++) {
+ yvals[i] = xvals[seg - i];
+ xvals[i] = yvals[seg - i];
+ }
+
+ if (!rbig) {
+ for (i = 0; i <= seg; i++) {
+ temp = xvals[i];
+ xvals[i] = 1.0 - yvals[i];
+ yvals[i] = 1.0 - temp;
+ }
+ }
}
-/* Find parameters u0, u1, ..., un that divide the quarter-arc superellipse
- * with parameter r into n even chords.
- * There is no closed form way of doing this except for a few special
- * values of r, so this uses binary search to find a chord length that works.
- * Return the u's in *r_params, which should point to an array of size n+1. */
-static void find_even_superellipse_params(int n, float r, float *r_params)
+ /* Find equidistant points (x0,y0), (x1,y1)... (xn,yn) on the superellipse
+ * function in the first quadrant. For special profiles (linear, arc,
+ * rectangle) the point can be calculated easily, for any other profile a more
+ * expensive search procedure must be used because there is no known closed
+ * form for equidistant parametrization
+ * xvals and yvals should be size n+1 */
+
+static void find_even_superellipse_chords(int n, float r, double *xvals, double *yvals)
{
- float d2low, d2high, d2 = 0.0f, d2final, u;
- int i, j, n2;
- const int maxiters = 40;
- const float d2tol = 1e-6f;
- const float umax = 2.0f;
-
- if (r == PRO_CIRCLE_R || r == PRO_LINE_R ||
- ((n % 2 == 0) && (r == PRO_SQUARE_IN_R || r == PRO_SQUARE_R)))
- {
- /* even parameter spacing works for these cases */
- for (i = 0; i <= n; i++)
- r_params[i] = i * 2.0f / (float) n;
+ int i, n2;
+ double temp;
+ bool seg_odd = n % 2;
+
+ n2 = n / 2;
+
+ /* Special cases. */
+ if (r == PRO_LINE_R) {
+ /* Linear spacing */
+ for (i = 0; i <= n; i++) {
+ xvals[i] = (double) i / n;
+ yvals[i] = 1.0 - (double) i / n;
+ }
return;
}
- if (r == PRO_SQUARE_IN_R || r == PRO_SQUARE_R) {
- /* n is odd, so get one corner-cut chord.
- * Solve u == sqrt(2*(1-n2*u)^2) where n2 = floor(n/2) */
- n2 = n / 2;
- u = (2.0f * n2 - (float)M_SQRT2) / (2.0f * n2 * n2 - 1.0f);
- for (i = 0; i < n; i++)
- r_params[i] = i * u;
- r_params[n] = umax;
- }
- d2low = 2.0f / (n * n); /* (sqrt(2)/n)**2 */
- d2high = 2 * d2low; /* (2/n)**2 */
- for (i = 0; i < maxiters && fabsf(d2high - d2low) > d2tol; i++) {
- d2 = 0.5f * (d2low + d2high);
-
- /* find where we are after n-1 chords of squared length d2 */
- u = 0.0f;
- for (j = 0; j < n - 1; j++) {
- u = find_superellipse_chord_u(u, d2, r);
- if (u == -1.0f)
- break; /* d2 is too big to go n-1 chords */
- }
- if (u == -1.0f) {
- d2high = d2;
- continue;
+ if (r == PRO_CIRCLE_R) {
+ temp = (M_PI / 2) / n;
+ /* Angle spacing. */
+ for (i = 0; i <= n; i++) {
+ xvals[i] = sin(i * temp);
+ yvals[i] = cos(i * temp);
}
- d2final = superellipse_chord_length_squared(u, umax, r);
- if (fabsf(d2final - d2) <= d2tol)
- break;
- if (d2final < d2)
- d2high = d2;
- else
- d2low = d2;
+ return;
}
- u = 0.0f;
- for (i = 0; i < n; i++) {
- r_params[i] = u;
- u = find_superellipse_chord_u(u, d2, r);
+ if (r == PRO_SQUARE_IN_R) {
+ /* n is even, distribute first and second half linear. */
+ if (!seg_odd) {
+ for (i = 0; i <= n2; i++) {
+ xvals[i] = 0.0;
+ yvals[i] = 1.0 - (double) i / n2;
+ xvals[n - i] = yvals[i];
+ yvals[n - i] = xvals[i];
+ }
+ }
+ /* n is odd, so get one corner-cut chord. */
+ else {
+ temp = 1.0 / (n2 + M_SQRT2 / 2.0);
+ for (i = 0; i <= n2; i++) {
+ xvals[i] = 0.0;
+ yvals[i] = 1.0 - (double) i * temp;
+ xvals[n -i ] = yvals[i];
+ yvals[n - i] = xvals[i];
+ }
+ }
+ return;
}
- r_params[n] = umax;
+ if (r == PRO_SQUARE_R) {
+ /* n is even, distribute first and second half linear. */
+ if (!seg_odd) {
+ for (i = 0; i <= n2; i++) {
+ xvals[i] = (double) i / n2;
+ yvals[i] = 1.0;
+ xvals[n - i] = yvals[i];
+ yvals[n - i] = xvals[i];
+ }
+ }
+ /* n is odd, so get one corner-cut chord. */
+ else {
+ temp = 1.0 / (n2 + M_SQRT2 / 2);
+ for (i = 0; i <= n2; i++) {
+ xvals[i] = (double) i * temp;
+ yvals[i] = 1.0;
+ xvals[n - i] = yvals[i];
+ yvals[n - i] = xvals[i];
+ }
+ }
+ return;
+ }
+ /* For general case use the more expensive search algorithm. */
+ find_even_superellipse_chords_general(n, r, xvals, yvals);
}
+
/* The superellipse used for multisegment profiles does not
* have a closed-form way to generate evenly spaced points
* along an arc. We use an expensive search procedure to find
* the parameter values that lead to bp->seg even chords.
* We also want spacing for a number of segments that is
- * a power of 2 >= bp->seg (but at least 4). */
+ * a power of 2 >= bp->seg (but at least 4).
+ * Use doubles because otherwise we cannot come close to float
+ * precision for final results. */
static void set_profile_spacing(BevelParams *bp)
{
int seg, seg_2;
seg = bp->seg;
if (seg > 1) {
- bp->pro_spacing.uvals = (float *)BLI_memarena_alloc(bp->mem_arena, (seg + 1) * sizeof(float));
- find_even_superellipse_params(seg, bp->pro_super_r, bp->pro_spacing.uvals);
+ bp->pro_spacing.xvals = (double *)BLI_memarena_alloc(bp->mem_arena, (seg + 1) * sizeof(double));
+ bp->pro_spacing.yvals = (double *)BLI_memarena_alloc(bp->mem_arena, (seg + 1) * sizeof(double));
+ find_even_superellipse_chords(seg, bp->pro_super_r, bp->pro_spacing.xvals, bp->pro_spacing.yvals);
seg_2 = power_of_2_max_i(bp->seg);
if (seg_2 == 2)
seg_2 = 4;
bp->pro_spacing.seg_2 = seg_2;
if (seg_2 == seg) {
- bp->pro_spacing.uvals_2 = bp->pro_spacing.uvals;
+ bp->pro_spacing.xvals_2 = bp->pro_spacing.xvals;
+ bp->pro_spacing.yvals_2 = bp->pro_spacing.yvals;
}
else {
- bp->pro_spacing.uvals_2 = (float *)BLI_memarena_alloc(bp->mem_arena, (seg_2 + 1) * sizeof(float));
- find_even_superellipse_params(seg_2, bp->pro_super_r, bp->pro_spacing.uvals_2);
+ bp->pro_spacing.xvals_2 = (double *)BLI_memarena_alloc(bp->mem_arena, (seg_2 + 1) * sizeof(double));
+ bp->pro_spacing.yvals_2 = (double *)BLI_memarena_alloc(bp->mem_arena, (seg_2 + 1) * sizeof(double));
+ find_even_superellipse_chords(seg_2, bp->pro_super_r, bp->pro_spacing.xvals_2, bp->pro_spacing.yvals_2);
}
}
else {
- bp->pro_spacing.uvals = NULL;
- bp->pro_spacing.uvals_2 = NULL;
+ bp->pro_spacing.xvals = NULL;
+ bp->pro_spacing.yvals = NULL;
+ bp->pro_spacing.xvals_2 = NULL;
+ bp->pro_spacing.yvals_2 = NULL;
bp->pro_spacing.seg_2 = 0;
}
}
/*
- * Calculate and return an offset that is the lesser of the current
+ * Assume we have a situation like:
+ *
+ * a d
+ * \ /
+ * A \ / C
+ * \ th1 th2/
+ * b---------c
+ * B
+ *
+ * where edges are A, B, and C,
+ * following a face around vertices a, b, c, d;
+ * th1 is angle abc and th2 is angle bcd;
+ * and the argument EdgeHalf eb is B, going from b to c.
+ * In general case, edge offset specs for A, B, C have
+ * the form ka*t, kb*t, kc*t where ka, kb, kc are some factors
+ * (may be 0) and t is the current bp->offset.
+ * We want to calculate t at which the clone of B parallel
+ * to it collapses. This can be calculated using trig.
+ * Another case of geometry collision that can happen is
+ * When B slides along A because A is unbeveled.
+ * Then it might collide with a. Similarly for B sliding along C.
+ */
+static float geometry_collide_offset(BevelParams *bp, EdgeHalf *eb)
+{
+ EdgeHalf *ea, *ec, *ebother;
+ BevVert *bvc;
+ BMLoop *lb;
+ BMVert *va, *vb, *vc, *vd;
+ float ka, kb, kc, g, h, t, den, no_collide_offset, th1, th2, sin1, sin2, tan1, tan2, limit;
+
+ limit = no_collide_offset = bp->offset + 1e6;
+ if (bp->offset == 0.0f)
+ return no_collide_offset;
+ kb = eb->offset_l_spec;
+ ea = eb->next; /* note: this is in direction b --> a */
+ ka = ea->offset_r_spec;
+ if (eb->is_rev) {
+ vc = eb->e->v1;
+ vb = eb->e->v2;
+ }
+ else {
+ vb = eb->e->v1;
+ vc = eb->e->v2;
+ }
+ va = ea->is_rev ? ea->e->v1 : ea->e->v2;
+ bvc = NULL;
+ ebother = find_other_end_edge_half(bp, eb, &bvc);
+ if (ebother != NULL) {
+ ec = ebother->prev; /* note: this is in direction c --> d*/
+ vc = bvc->v;
+ kc = ec->offset_l_spec;
+ vd = ec->is_rev ? ec->e->v1 : ec->e->v2;
+ }
+ else {
+ /* No bevvert for w, so C can't be beveled */
+ kc = 0.0f;
+ ec = NULL;
+ /* Find an edge from c that has same face */
+ lb = BM_face_edge_share_loop(eb->fnext, eb->e);
+ if (!lb) {
+ return no_collide_offset;
+ }
+ if (lb->next->v == vc)
+ vd = lb->next->next->v;
+ else if (lb->v == vc)
+ vd = lb->prev->v;
+ else {
+ return no_collide_offset;
+ }
+ }
+ if (ea->e == eb->e || (ec && ec->e == eb->e))
+ return no_collide_offset;
+ ka = ka / bp->offset;
+ kb = kb / bp->offset;
+ kc = kc / bp->offset;
+ th1 = angle_v3v3v3(va->co, vb->co, vc->co);
+ th2 = angle_v3v3v3(vb->co, vc->co, vd->co);
+
+ /* First calculate offset at which edge B collapses, which happens
+ * when advancing clones of A, B, C all meet at a point.
+ * This only happens if at least two of those three edges have non-zero k's */
+ sin1 = sinf(th1);
+ sin2 = sinf(th2);
+ if ((ka > 0.0f) + (kb > 0.0f) + (kc > 0.0f) >= 2) {
+ tan1 = tanf(th1);
+ tan2 = tanf(th2);
+ g = tan1 * tan2;
+ h = sin1 * sin2;
+ den = g * (ka * sin2 + kc * sin1) + kb * h * (tan1 + tan2);
+ if (den != 0.0f) {
+ t = BM_edge_calc_length(eb->e);
+ t *= g * h / den;
+ if (t >= 0.0f)
+ limit = t;
+ }
+ }
+
+ /* Now check edge slide cases */
+ if (kb > 0.0f && ka == 0.0f /*&& bvb->selcount == 1 && bvb->edgecount > 2*/) {
+ t = BM_edge_calc_length(ea->e);
+ t *= sin1 / kb;
+ if (t >= 0.0f && t < limit)
+ limit = t;
+ }
+ if (kb > 0.0f && kc == 0.0f /* && bvc && ec && bvc->selcount == 1 && bvc->edgecount > 2 */) {
+ t = BM_edge_calc_length(ec->e);
+ t *= sin2 / kb;
+ if (t >= 0.0f && t < limit)
+ limit = t;
+ }
+ return limit;
+}
+
+/*
+ * We have an edge A between vertices a and b,
+ * where EdgeHalf ea is the half of A that starts at a.
+ * For vertex-only bevels, the new vertices slide from a at a rate ka*t
+ * and from b at a rate kb*t.
+ * We want to calculate the t at which the two meet.
+ */
+static float vertex_collide_offset(BevelParams *bp, EdgeHalf *ea)
+{
+ float limit, ka, kb, no_collide_offset, la, kab;
+ EdgeHalf *eb;
+
+ limit = no_collide_offset = bp->offset + 1e6;
+ if (bp->offset == 0.0f)
+ return no_collide_offset;
+ ka = ea->offset_l_spec / bp->offset;
+ eb = find_other_end_edge_half(bp, ea, NULL);
+ kb = eb ? eb->offset_l_spec / bp->offset : 0.0f;
+ kab = ka + kb;
+ la = BM_edge_calc_length(ea->e);
+ if (kab <= 0.0f)
+ return no_collide_offset;
+ limit = la / kab;
+ return limit;
+}
+
+/*
+ * Calculate an offset that is the lesser of the current
* bp.offset and the maximum possible offset before geometry
* collisions happen.
- * Currently this is a quick and dirty estimate of the max
- * possible: half the minimum edge length of any vertex involved
- * in a bevel. This is usually conservative.
- * The correct calculation is quite complicated.
- * TODO: implement this correctly.
+ * If the offset changes as a result of this, adjust the
+ * current edge offset specs to reflect this clamping,
+ * and store the new offset in bp.offset.
*/
-static float bevel_limit_offset(BMesh *bm, BevelParams *bp)
+static void bevel_limit_offset(BevelParams *bp)
{
- BMVert *v;
- BMEdge *e;
- BMIter v_iter, e_iter;
- float limited_offset, half_elen;
- bool vbeveled;
+ BevVert *bv;
+ EdgeHalf *eh;
+ GHashIterator giter;
+ float limited_offset, offset_factor, collision_offset;
+ int i;
limited_offset = bp->offset;
- if (bp->offset_type == BEVEL_AMT_PERCENT) {
- if (limited_offset > 50.0f)
- limited_offset = 50.0f;
- return limited_offset;
- }
- BM_ITER_MESH (v, &v_iter, bm, BM_VERTS_OF_MESH) {
- if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
+ GHASH_ITER(giter, bp->vert_hash) {
+ bv = BLI_ghashIterator_getValue(&giter);
+ for (i = 0; i < bv->edgecount; i++) {
+ eh = &bv->edges[i];
if (bp->vertex_only) {
- vbeveled = true;
+ collision_offset = vertex_collide_offset(bp, eh);
+ if (collision_offset < limited_offset)
+ limited_offset = collision_offset;
}
else {
- vbeveled = false;
- BM_ITER_ELEM (e, &e_iter, v, BM_EDGES_OF_VERT) {
- if (BM_elem_flag_test(BM_edge_other_vert(e, v), BM_ELEM_TAG)) {
- vbeveled = true;
- break;
- }
- }
+ collision_offset = geometry_collide_offset(bp, eh);
+ if (collision_offset < limited_offset)
+ limited_offset = collision_offset;
}
- if (vbeveled) {
- BM_ITER_ELEM (e, &e_iter, v, BM_EDGES_OF_VERT) {
- half_elen = 0.5f * BM_edge_calc_length(e);
- if (half_elen < limited_offset)
- limited_offset = half_elen;
- }
+ }
+ }
+
+ if (limited_offset < bp->offset) {
+ /* All current offset specs have some number times bp->offset,
+ * so we can just multiply them all by the reduction factor
+ * of the offset to have the effect of recalculating the specs
+ * with the new limited_offset.
+ */
+ offset_factor = limited_offset / bp->offset;
+ GHASH_ITER(giter, bp->vert_hash) {
+ bv = BLI_ghashIterator_getValue(&giter);
+ for (i = 0; i < bv->edgecount; i++) {
+ eh = &bv->edges[i];
+ eh->offset_l_spec *= offset_factor;
+ eh->offset_r_spec *= offset_factor;
+ eh->offset_l *= offset_factor;
+ eh->offset_r *= offset_factor;
}
}
+ bp->offset = limited_offset;
}
- return limited_offset;
}
/**
* - Currently only bevels BM_ELEM_TAG'd verts and edges.
*
- * - Newly created faces are BM_ELEM_TAG'd too,
- * the caller needs to ensure this is cleared before calling
- * if its going to use this face tag.
+ * - Newly created faces, edges, and verts are BM_ELEM_TAG'd too,
+ * the caller needs to ensure these are cleared before calling
+ * if its going to use this tag.
*
* - If limit_offset is set, adjusts offset down if necessary
* to avoid geometry collisions.
@@ -4538,21 +5356,24 @@ void BM_mesh_bevel(
BMEdge *e;
BevVert *bv;
BevelParams bp = {NULL};
+ GHashIterator giter;
bp.offset = offset;
bp.offset_type = offset_type;
bp.seg = segments;
- bp.pro_super_r = 4.0f * profile; /* convert to superellipse exponent */
+ bp.pro_super_r = -log(2.0) / log(sqrt(profile)); /* convert to superellipse exponent */
bp.vertex_only = vertex_only;
bp.use_weights = use_weights;
bp.loop_slide = loop_slide;
bp.limit_offset = limit_offset;
+ bp.offset_adjust = true;
bp.dvert = dvert;
bp.vertex_group = vertex_group;
bp.mat_nr = mat;
- if (bp.pro_super_r < 0.60f)
- bp.pro_super_r = 0.60f; /* TODO: implement 0 case properly */
+ if (profile >= 0.999f) { /* r ~ 692, so PRO_SQUARE_R is 1e4 */
+ bp.pro_super_r = PRO_SQUARE_R;
+ }
if (bp.offset > 0) {
/* primary alloc */
@@ -4561,24 +5382,33 @@ void BM_mesh_bevel(
BLI_memarena_use_calloc(bp.mem_arena);
set_profile_spacing(&bp);
- if (limit_offset)
- bp.offset = bevel_limit_offset(bm, &bp);
-
/* Analyze input vertices, sorting edges and assigning initial new vertex positions */
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
bv = bevel_vert_construct(bm, &bp, v);
- if (bv)
+ if (!limit_offset && bv)
build_boundary(&bp, bv, true);
}
}
+ /* Perhaps clamp offset to avoid geometry colliisions */
+ if (limit_offset) {
+ bevel_limit_offset(&bp);
+
+ /* Assign initial new vertex positions */
+ GHASH_ITER(giter, bp.vert_hash) {
+ bv = BLI_ghashIterator_getValue(&giter);
+ build_boundary(&bp, bv, true);
+ }
+ }
+
/* Perhaps do a pass to try to even out widths */
- if (!bp.vertex_only) {
+ if (!bp.vertex_only && bp.offset_adjust) {
adjust_offsets(&bp);
}
/* Build the meshes around vertices, now that positions are final */
+ /* Note: could use GHASH_ITER over bp.vert_hash when backward compatibility no longer matters */
BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
bv = find_bevvert(&bp, v);
@@ -4611,6 +5441,20 @@ void BM_mesh_bevel(
}
}
+ /* When called from operator (as opposed to modifier), bm->use_toolflags
+ * will be set, and we to transfer the oflags to BM_ELEM_TAGs */
+ if (bm->use_toolflags) {
+ BM_ITER_MESH (v, &iter, bm, BM_VERTS_OF_MESH) {
+ if (BMO_vert_flag_test(bm, v, VERT_OUT))
+ BM_elem_flag_enable(v, BM_ELEM_TAG);
+ }
+ BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
+ if (BMO_edge_flag_test(bm, e, EDGE_OUT)) {
+ BM_elem_flag_enable(e, BM_ELEM_TAG);
+ }
+ }
+ }
+
/* primary free */
BLI_ghash_free(bp.vert_hash, NULL, NULL);
BLI_memarena_free(bp.mem_arena);
diff --git a/source/blender/bmesh/tools/bmesh_bisect_plane.c b/source/blender/bmesh/tools/bmesh_bisect_plane.c
index 51b92a3c45e..f3927a3ff67 100644
--- a/source/blender/bmesh/tools/bmesh_bisect_plane.c
+++ b/source/blender/bmesh/tools/bmesh_bisect_plane.c
@@ -38,7 +38,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_alloca.h"
#include "BLI_linklist.h"
#include "BLI_linklist_stack.h"
@@ -74,7 +74,7 @@ static short plane_point_test_v3(const float plane[4], const float co[3], const
#define BM_VERT_DIST(v) ((v)->no[0]) /* Distance from the plane. */
#define BM_VERT_SORTVAL(v) ((v)->no[1]) /* Temp value for sorting. */
#define BM_VERT_LOOPINDEX(v) /* The verts index within a face (temp var) */ \
- (*((unsigned int *)(&(v)->no[2])))
+ (*((uint *)(&(v)->no[2])))
/**
* Hide flag access
@@ -110,10 +110,10 @@ static int bm_vert_sortval_cb(const void *v_a_v, const void *v_b_v)
}
-static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], const short oflag_center)
+static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], const short oflag_center, const short oflag_new)
{
/* unlikely more than 2 verts are needed */
- const unsigned int f_len_orig = (unsigned int)f->len;
+ const uint f_len_orig = (uint)f->len;
BMVert **vert_split_arr = BLI_array_alloca(vert_split_arr, f_len_orig);
STACK_DECLARE(vert_split_arr);
BMLoop *l_iter, *l_first;
@@ -154,10 +154,11 @@ static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], con
/* common case, just cut the face once */
BM_face_split(bm, f, l_a, l_b, &l_new, NULL, true);
if (l_new) {
- if (oflag_center) {
- BMO_edge_flag_enable(bm, l_new->e, oflag_center);
- BMO_face_flag_enable(bm, l_new->f, oflag_center);
- BMO_face_flag_enable(bm, f, oflag_center);
+ if (oflag_center | oflag_new) {
+ BMO_edge_flag_enable(bm, l_new->e, oflag_center | oflag_new);
+ }
+ if (oflag_new) {
+ BMO_face_flag_enable(bm, l_new->f, oflag_new);
}
}
}
@@ -170,7 +171,7 @@ static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], con
STACK_DECLARE(face_split_arr);
float sort_dir[3];
- unsigned int i;
+ uint i;
/* ---- */
@@ -245,7 +246,7 @@ static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], con
if (is_inside) {
BMLoop *l_a, *l_b;
bool found = false;
- unsigned int j;
+ uint j;
for (j = 0; j < STACK_SIZE(face_split_arr); j++) {
/* would be nice to avoid loop lookup here,
@@ -269,10 +270,11 @@ static void bm_face_bisect_verts(BMesh *bm, BMFace *f, const float plane[4], con
f_tmp = BM_face_split(bm, face_split_arr[j], l_a, l_b, &l_new, NULL, true);
if (l_new) {
- if (oflag_center) {
- BMO_edge_flag_enable(bm, l_new->e, oflag_center);
- BMO_face_flag_enable(bm, l_new->f, oflag_center);
- BMO_face_flag_enable(bm, face_split_arr[j], oflag_center);
+ if (oflag_center | oflag_new) {
+ BMO_edge_flag_enable(bm, l_new->e, oflag_center | oflag_new);
+ }
+ if (oflag_new) {
+ BMO_face_flag_enable(bm, l_new->f, oflag_new);
}
}
@@ -307,10 +309,10 @@ finally:
void BM_mesh_bisect_plane(
BMesh *bm, const float plane[4],
const bool use_snap_center, const bool use_tag,
- const short oflag_center, const float eps)
+ const short oflag_center, const short oflag_new, const float eps)
{
- unsigned int einput_len;
- unsigned int i;
+ uint einput_len;
+ uint i;
BMEdge **edges_arr = MEM_mallocN(sizeof(*edges_arr) * (size_t)bm->totedge, __func__);
BLI_LINKSTACK_DECLARE(face_stack, BMFace *);
@@ -343,7 +345,7 @@ void BM_mesh_bisect_plane(
}
else {
BMEdge *e;
- einput_len = (unsigned int)bm->totedge;
+ einput_len = (uint)bm->totedge;
BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
edge_is_cut_enable(e);
edges_arr[i] = e;
@@ -390,7 +392,7 @@ void BM_mesh_bisect_plane(
const float dist[2] = {BM_VERT_DIST(e->v1), BM_VERT_DIST(e->v2)};
if (side[0] && side[1] && (side[0] != side[1])) {
- const float e_fac = fabsf(dist[0]) / fabsf(dist[0] - dist[1]);
+ const float e_fac = dist[0] / (dist[0] - dist[1]);
BMVert *v_new;
if (e->l) {
@@ -404,10 +406,17 @@ void BM_mesh_bisect_plane(
} while ((l_iter = l_iter->radial_next) != l_first);
}
- v_new = BM_edge_split(bm, e, e->v1, NULL, e_fac);
+ {
+ BMEdge *e_new;
+ v_new = BM_edge_split(bm, e, e->v1, &e_new, e_fac);
+ if (oflag_new) {
+ BMO_edge_flag_enable(bm, e_new, oflag_new);
+ }
+ }
+
vert_is_center_enable(v_new);
- if (oflag_center) {
- BMO_vert_flag_enable(bm, v_new, oflag_center);
+ if (oflag_new | oflag_center) {
+ BMO_vert_flag_enable(bm, v_new, oflag_new | oflag_center);
}
BM_VERT_DIR(v_new) = 0;
@@ -416,7 +425,7 @@ void BM_mesh_bisect_plane(
else if (side[0] == 0 || side[1] == 0) {
/* check if either edge verts are aligned,
* if so - tag and push all faces that use it into the stack */
- unsigned int j;
+ uint j;
BM_ITER_ELEM_INDEX (v, &iter, e, BM_VERTS_OF_EDGE, j) {
if (side[j] == 0) {
if (vert_is_center_test(v) == 0) {
@@ -448,7 +457,7 @@ void BM_mesh_bisect_plane(
MEM_freeN(edges_arr);
while ((f = BLI_LINKSTACK_POP(face_stack))) {
- bm_face_bisect_verts(bm, f, plane, oflag_center);
+ bm_face_bisect_verts(bm, f, plane, oflag_center, oflag_new);
}
/* now we have all faces to split in the stack */
diff --git a/source/blender/bmesh/tools/bmesh_bisect_plane.h b/source/blender/bmesh/tools/bmesh_bisect_plane.h
index 7f3a97c4c79..fb99a1c8214 100644
--- a/source/blender/bmesh/tools/bmesh_bisect_plane.h
+++ b/source/blender/bmesh/tools/bmesh_bisect_plane.h
@@ -30,6 +30,6 @@
void BM_mesh_bisect_plane(
BMesh *bm, const float plane[4],
const bool use_snap_center, const bool use_tag,
- const short oflag_center, const float eps);
+ const short oflag_center, const short oflag_new, const float eps);
#endif /* __BMESH_BISECT_PLANE_H__ */
diff --git a/source/blender/bmesh/tools/bmesh_decimate_collapse.c b/source/blender/bmesh/tools/bmesh_decimate_collapse.c
index 372d341f223..c1b2bc2625b 100644
--- a/source/blender/bmesh/tools/bmesh_decimate_collapse.c
+++ b/source/blender/bmesh/tools/bmesh_decimate_collapse.c
@@ -38,9 +38,9 @@
#include "BLI_alloca.h"
#include "BLI_memarena.h"
#include "BLI_edgehash.h"
-#include "BLI_polyfill2d.h"
-#include "BLI_polyfill2d_beautify.h"
-#include "BLI_stackdefines.h"
+#include "BLI_polyfill_2d.h"
+#include "BLI_polyfill_2d_beautify.h"
+#include "BLI_utildefines_stack.h"
#include "BKE_customdata.h"
@@ -180,7 +180,7 @@ static bool bm_edge_collapse_is_degenerate_flip(BMEdge *e, const float optimize_
{
BMIter liter;
BMLoop *l;
- unsigned int i;
+ uint i;
for (i = 0; i < 2; i++) {
/* loop over both verts */
@@ -256,10 +256,6 @@ static void bm_decim_build_edge_cost_single(
{
float cost;
- if (eheap_table[BM_elem_index_get(e)]) {
- BLI_heap_remove(eheap, eheap_table[BM_elem_index_get(e)]);
- }
-
if (UNLIKELY(vweights &&
((vweights[BM_elem_index_get(e->v1)] == 0.0f) ||
(vweights[BM_elem_index_get(e->v2)] == 0.0f))))
@@ -341,10 +337,13 @@ static void bm_decim_build_edge_cost_single(
}
}
- eheap_table[BM_elem_index_get(e)] = BLI_heap_insert(eheap, cost, e);
+ BLI_heap_insert_or_update(eheap, &eheap_table[BM_elem_index_get(e)], cost, e);
return;
clear:
+ if (eheap_table[BM_elem_index_get(e)]) {
+ BLI_heap_remove(eheap, eheap_table[BM_elem_index_get(e)]);
+ }
eheap_table[BM_elem_index_get(e)] = NULL;
}
@@ -367,7 +366,7 @@ static void bm_decim_build_edge_cost(
{
BMIter iter;
BMEdge *e;
- unsigned int i;
+ uint i;
BM_ITER_MESH_INDEX (e, &iter, bm, BM_EDGES_OF_MESH, i) {
eheap_table[i] = NULL; /* keep sanity check happy */
@@ -418,12 +417,12 @@ static bool bm_edge_symmetry_check_cb(void *user_data, int index, const float UN
return false;
}
-static int *bm_edge_symmetry_map(BMesh *bm, unsigned int symmetry_axis, float limit)
+static int *bm_edge_symmetry_map(BMesh *bm, uint symmetry_axis, float limit)
{
struct KD_Symmetry_Data sym_data;
BMIter iter;
BMEdge *e, **etable;
- unsigned int i;
+ uint i;
int *edge_symmetry_map;
const float limit_sq = SQUARE(limit);
KDTree *tree;
@@ -497,7 +496,7 @@ static bool bm_face_triangulate(
MemArena *pf_arena,
/* use for MOD_TRIANGULATE_NGON_BEAUTY only! */
- struct Heap *pf_heap, struct EdgeHash *pf_ehash)
+ struct Heap *pf_heap)
{
const int f_base_len = f_base->len;
int faces_array_tot = f_base_len - 3;
@@ -516,8 +515,7 @@ static bool bm_face_triangulate(
edges_array, &edges_array_tot,
r_faces_double,
quad_method, ngon_method, false,
- pf_arena,
- pf_heap, pf_ehash);
+ pf_arena, pf_heap);
for (int i = 0; i < edges_array_tot; i++) {
BMLoop *l_iter, *l_first;
@@ -567,19 +565,16 @@ static bool bm_decim_triangulate_begin(BMesh *bm, int *r_edges_tri_tot)
{
MemArena *pf_arena;
Heap *pf_heap;
- EdgeHash *pf_ehash;
LinkNode *faces_double = NULL;
if (has_ngon) {
pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
pf_heap = BLI_heap_new_ex(BLI_POLYFILL_ALLOC_NGON_RESERVE);
- pf_ehash = BLI_edgehash_new_ex(__func__, BLI_POLYFILL_ALLOC_NGON_RESERVE);
}
else {
pf_arena = NULL;
pf_heap = NULL;
- pf_ehash = NULL;
}
/* adding new faces as we loop over faces
@@ -591,8 +586,7 @@ static bool bm_decim_triangulate_begin(BMesh *bm, int *r_edges_tri_tot)
bm, f, &faces_double,
r_edges_tri_tot,
- pf_arena,
- pf_heap, pf_ehash);
+ pf_arena, pf_heap);
}
}
@@ -606,7 +600,6 @@ static bool bm_decim_triangulate_begin(BMesh *bm, int *r_edges_tri_tot)
if (has_ngon) {
BLI_memarena_free(pf_arena);
BLI_heap_free(pf_heap, NULL);
- BLI_edgehash_free(pf_ehash, NULL);
}
BLI_assert((bm->elem_index_dirty & BM_VERT) == 0);
@@ -1364,7 +1357,7 @@ void BM_mesh_decimate_collapse(
(BLI_heap_node_value(BLI_heap_top(eheap)) != COST_INVALID))
{
// const float value = BLI_heap_node_value(BLI_heap_top(eheap));
- BMEdge *e = BLI_heap_popmin(eheap);
+ BMEdge *e = BLI_heap_pop_min(eheap);
float optimize_co[3];
BLI_assert(BM_elem_index_get(e) < tot_edge_orig); /* handy to detect corruptions elsewhere */
@@ -1395,7 +1388,7 @@ void BM_mesh_decimate_collapse(
* - edges sharing a vertex are ignored, so the pivot vertex isnt moved to one side.
*/
- BMEdge *e = BLI_heap_popmin(eheap);
+ BMEdge *e = BLI_heap_pop_min(eheap);
const int e_index = BM_elem_index_get(e);
const int e_index_mirr = edge_symmetry_map[e_index];
BMEdge *e_mirr = NULL;
diff --git a/source/blender/bmesh/tools/bmesh_decimate_dissolve.c b/source/blender/bmesh/tools/bmesh_decimate_dissolve.c
index e2c36299ddf..72722eab4e6 100644
--- a/source/blender/bmesh/tools/bmesh_decimate_dissolve.c
+++ b/source/blender/bmesh/tools/bmesh_decimate_dissolve.c
@@ -342,8 +342,7 @@ void BM_mesh_decimate_dissolve_ex(
const int j = BM_elem_index_get(l_iter->e);
if (j != -1 && eheap_table[j]) {
const float cost = bm_edge_calc_dissolve_error(l_iter->e, delimit, &delimit_data);
- BLI_heap_remove(eheap, eheap_table[j]);
- eheap_table[j] = BLI_heap_insert(eheap, cost, l_iter->e);
+ BLI_heap_node_value_update(eheap, eheap_table[j], cost);
}
} while ((l_iter = l_iter->next) != l_first);
}
@@ -353,8 +352,7 @@ void BM_mesh_decimate_dissolve_ex(
}
if (UNLIKELY(f_new == NULL)) {
- BLI_heap_remove(eheap, enode_top);
- eheap_table[i] = BLI_heap_insert(eheap, COST_INVALID, e);
+ BLI_heap_node_value_update(eheap, enode_top, COST_INVALID);
}
}
@@ -475,8 +473,7 @@ void BM_mesh_decimate_dissolve_ex(
const int j = BM_elem_index_get(v_iter);
if (j != -1 && vheap_table[j]) {
const float cost = bm_vert_edge_face_angle(v_iter);
- BLI_heap_remove(vheap, vheap_table[j]);
- vheap_table[j] = BLI_heap_insert(vheap, cost, v_iter);
+ BLI_heap_node_value_update(vheap, vheap_table[j], cost);
}
}
@@ -497,8 +494,7 @@ void BM_mesh_decimate_dissolve_ex(
(BLI_heap_node_value(vheap_table[j]) == COST_INVALID))
{
const float cost = bm_vert_edge_face_angle(l_cycle_iter->v);
- BLI_heap_remove(vheap, vheap_table[j]);
- vheap_table[j] = BLI_heap_insert(vheap, cost, l_cycle_iter->v);
+ BLI_heap_node_value_update(vheap, vheap_table[j], cost);
}
} while ((l_cycle_iter = l_cycle_iter->next) != l_cycle_first);
@@ -510,8 +506,7 @@ void BM_mesh_decimate_dissolve_ex(
}
if (UNLIKELY(e_new == NULL)) {
- BLI_heap_remove(vheap, vnode_top);
- vheap_table[i] = BLI_heap_insert(vheap, COST_INVALID, v);
+ BLI_heap_node_value_update(vheap, vnode_top, COST_INVALID);
}
}
diff --git a/source/blender/bmesh/tools/bmesh_decimate_unsubdivide.c b/source/blender/bmesh/tools/bmesh_decimate_unsubdivide.c
index 92300ae66a2..f0ac6c673c9 100644
--- a/source/blender/bmesh/tools/bmesh_decimate_unsubdivide.c
+++ b/source/blender/bmesh/tools/bmesh_decimate_unsubdivide.c
@@ -43,10 +43,10 @@ static bool bm_vert_dissolve_fan_test(BMVert *v)
BMVert *varr[4];
- unsigned int tot_edge = 0;
- unsigned int tot_edge_boundary = 0;
- unsigned int tot_edge_manifold = 0;
- unsigned int tot_edge_wire = 0;
+ uint tot_edge = 0;
+ uint tot_edge_boundary = 0;
+ uint tot_edge_manifold = 0;
+ uint tot_edge_wire = 0;
BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
if (BM_edge_is_boundary(e)) {
@@ -97,11 +97,11 @@ static bool bm_vert_dissolve_fan(BMesh *bm, BMVert *v)
BMIter iter;
BMEdge *e;
- unsigned int tot_loop = 0;
- unsigned int tot_edge = 0;
- unsigned int tot_edge_boundary = 0;
- unsigned int tot_edge_manifold = 0;
- unsigned int tot_edge_wire = 0;
+ uint tot_loop = 0;
+ uint tot_edge = 0;
+ uint tot_edge_boundary = 0;
+ uint tot_edge_manifold = 0;
+ uint tot_edge_wire = 0;
BM_ITER_ELEM (e, &iter, v, BM_EDGES_OF_VERT) {
if (BM_edge_is_boundary(e)) {
@@ -143,7 +143,7 @@ static bool bm_vert_dissolve_fan(BMesh *bm, BMVert *v)
if (tot_loop) {
BMLoop *f_loop[4];
- unsigned int i;
+ uint i;
/* ensure there are exactly tot_loop loops */
BLI_assert(BM_iter_at_index(bm, BM_LOOPS_OF_VERT, v, tot_loop) == NULL);
@@ -192,8 +192,8 @@ void BM_mesh_decimate_unsubdivide_ex(BMesh *bm, const int iterations, const bool
BMIter iter;
- const unsigned int offset = 0;
- const unsigned int nth = 2;
+ const uint offset = 0;
+ const uint nth = 2;
int iter_step;
@@ -229,8 +229,8 @@ void BM_mesh_decimate_unsubdivide_ex(BMesh *bm, const int iterations, const bool
#ifdef USE_WALKER
BMWalker walker;
#else
- unsigned int depth = 1;
- unsigned int i;
+ uint depth = 1;
+ uint i;
#endif
BMVert *v_first = NULL;
diff --git a/source/blender/bmesh/tools/bmesh_edgenet.c b/source/blender/bmesh/tools/bmesh_edgenet.c
index 2a1946df7ae..df9d07036af 100644
--- a/source/blender/bmesh/tools/bmesh_edgenet.c
+++ b/source/blender/bmesh/tools/bmesh_edgenet.c
@@ -100,13 +100,13 @@ static BMEdge *bm_edgenet_edge_get_next(
*
* This function returns half a loop, the caller needs to run twice to get both sides.
*/
-static unsigned int bm_edgenet_path_from_pass(
+static uint bm_edgenet_path_from_pass(
BMVert *v, LinkNode **v_ls,
VertNetInfo *vnet_info, BLI_mempool *path_pool)
{
VertNetInfo *vn = &vnet_info[BM_elem_index_get(v)];
const int pass = vn->pass;
- unsigned int v_ls_tot = 0;
+ uint v_ls_tot = 0;
do {
BLI_linklist_prepend_pool(v_ls, v, path_pool);
@@ -127,10 +127,10 @@ static bool bm_edgenet_path_check_overlap(
VertNetInfo *vnet_info)
{
/* vert order doesn't matter */
- unsigned int v_ls_tot = 0;
+ uint v_ls_tot = 0;
LinkNode *v_ls = NULL;
BMVert *v_pair[2] = {v1, v2};
- unsigned int i;
+ uint i;
for (i = 0; i < 2; i++) {
BMVert *v = v_pair[i];
@@ -162,7 +162,7 @@ static bool bm_edgenet_path_check_overlap(
* Create a face from the path.
*/
static BMFace *bm_edgenet_face_from_path(
- BMesh *bm, LinkNode *path, const unsigned int path_len)
+ BMesh *bm, LinkNode *path, const uint path_len)
{
BMFace *f;
LinkNode *v_lnk;
@@ -205,8 +205,8 @@ static BMEdge *bm_edgenet_path_step(
BMEdge *e;
BMIter iter;
- unsigned int tot;
- unsigned int v_ls_tot;
+ uint tot;
+ uint v_ls_tot;
begin:
@@ -277,8 +277,8 @@ begin:
* \return A linked list of verts.
*/
static LinkNode *bm_edgenet_path_calc(
- BMEdge *e, const int pass_nr, const unsigned int path_cost_max,
- unsigned int *r_path_len, unsigned int *r_path_cost,
+ BMEdge *e, const int pass_nr, const uint path_cost_max,
+ uint *r_path_len, uint *r_path_cost,
VertNetInfo *vnet_info, BLI_mempool *path_pool)
{
VertNetInfo *vn_1, *vn_2;
@@ -288,7 +288,7 @@ static LinkNode *bm_edgenet_path_calc(
LinkNode *v_ls_prev = NULL;
LinkNode *v_ls_next = NULL;
- unsigned int path_cost_accum = 0;
+ uint path_cost_accum = 0;
BLI_assert(bm_edge_step_ok(e));
@@ -331,11 +331,11 @@ static LinkNode *bm_edgenet_path_calc(
if (e_found) {
LinkNode *path = NULL;
- unsigned int path_len;
+ uint path_len;
BLI_linklist_free_pool(v_ls_next, NULL, path_pool);
BLI_linklist_free_pool(v_ls_prev, NULL, path_pool);
- // BLI_assert(BLI_mempool_count(path_pool) == 0);
+ // BLI_assert(BLI_mempool_len(path_pool) == 0);
path_len = bm_edgenet_path_from_pass(e_found->v1, &path, vnet_info, path_pool);
BLI_linklist_reverse(&path);
@@ -376,12 +376,12 @@ static LinkNode *bm_edgenet_path_calc(
* _don't_ have a better option.
*/
static LinkNode *bm_edgenet_path_calc_best(
- BMEdge *e, int *pass_nr, unsigned int path_cost_max,
- unsigned int *r_path_len, unsigned int *r_path_cost,
+ BMEdge *e, int *pass_nr, uint path_cost_max,
+ uint *r_path_len, uint *r_path_cost,
VertNetInfo *vnet_info, BLI_mempool *path_pool)
{
LinkNode *path;
- unsigned int path_cost;
+ uint path_cost;
path = bm_edgenet_path_calc(e, *pass_nr, path_cost_max,
r_path_len, &path_cost,
@@ -399,8 +399,8 @@ static LinkNode *bm_edgenet_path_calc_best(
/* Check every edge to see if any can give a better path.
* This avoids very strange/long paths from being created. */
- const unsigned int path_len = *r_path_len;
- unsigned int i, i_prev;
+ const uint path_len = *r_path_len;
+ uint i, i_prev;
BMVert **vert_arr = BLI_array_alloca(vert_arr, path_len);
LinkNode *v_lnk;
@@ -413,8 +413,8 @@ static LinkNode *bm_edgenet_path_calc_best(
BMEdge *e_other = BM_edge_exists(vert_arr[i], vert_arr[i_prev]);
if (e_other != e) {
LinkNode *path_test;
- unsigned int path_len_test;
- unsigned int path_cost_test;
+ uint path_len_test;
+ uint path_cost_test;
path_test = bm_edgenet_path_calc(e_other, *pass_nr, path_cost,
&path_len_test, &path_cost_test,
@@ -471,8 +471,8 @@ void BM_mesh_edgenet(
while (true) {
LinkNode *path = NULL;
- unsigned int path_len;
- unsigned int path_cost;
+ uint path_len;
+ uint path_cost;
e = bm_edgenet_edge_get_next(bm, &edge_queue, edge_queue_pool);
if (e == NULL) {
@@ -505,7 +505,7 @@ void BM_mesh_edgenet(
}
BLI_linklist_free_pool(path, NULL, path_pool);
- BLI_assert(BLI_mempool_count(path_pool) == 0);
+ BLI_assert(BLI_mempool_len(path_pool) == 0);
}
bm->elem_index_dirty |= BM_FACE | BM_LOOP;
diff --git a/source/blender/bmesh/tools/bmesh_edgesplit.c b/source/blender/bmesh/tools/bmesh_edgesplit.c
index a59a5c43c82..3a844a0b8d9 100644
--- a/source/blender/bmesh/tools/bmesh_edgesplit.c
+++ b/source/blender/bmesh/tools/bmesh_edgesplit.c
@@ -96,7 +96,7 @@ void BM_mesh_edgesplit(
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
- unsigned int i;
+ uint i;
for (i = 0; i < 2; i++) {
BMVert *v = ((&e->v1)[i]);
if (BM_elem_flag_test(v, BM_ELEM_TAG)) {
diff --git a/source/blender/bmesh/tools/bmesh_intersect.c b/source/blender/bmesh/tools/bmesh_intersect.c
index 58234ddf3bd..acadb663810 100644
--- a/source/blender/bmesh/tools/bmesh_intersect.c
+++ b/source/blender/bmesh/tools/bmesh_intersect.c
@@ -44,7 +44,7 @@
#include "BLI_sort_utils.h"
#include "BLI_linklist_stack.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#ifndef NDEBUG
# include "BLI_array_utils.h"
#endif
@@ -152,7 +152,7 @@ struct ISectState {
*/
struct LinkBase {
LinkNode *list;
- unsigned int list_len;
+ uint list_len;
};
static bool ghash_insert_link(
@@ -193,7 +193,7 @@ struct vert_sort_t {
static void edge_verts_sort(const float co[3], struct LinkBase *v_ls_base)
{
/* not optimal but list will be typically < 5 */
- unsigned int i;
+ uint i;
struct vert_sort_t *vert_sort = BLI_array_alloca(vert_sort, v_ls_base->list_len);
LinkNode *node;
@@ -246,8 +246,8 @@ static void face_edges_split(
bool use_island_connect,
MemArena *mem_arena_edgenet)
{
- unsigned int i;
- unsigned int edge_arr_len = e_ls_base->list_len;
+ uint i;
+ uint edge_arr_len = e_ls_base->list_len;
BMEdge **edge_arr = BLI_array_alloca(edge_arr, edge_arr_len);
LinkNode *node;
BLI_assert(f->head.htype == BM_FACE);
@@ -263,7 +263,7 @@ static void face_edges_split(
#ifdef USE_NET_ISLAND_CONNECT
if (use_island_connect) {
- unsigned int edge_arr_holes_len;
+ uint edge_arr_holes_len;
BMEdge **edge_arr_holes;
if (BM_face_split_edgenet_connect_islands(
bm, f,
@@ -305,14 +305,14 @@ static enum ISectType intersect_line_tri(
const struct ISectEpsilon *e)
{
float p_dir[3];
- unsigned int i_t0;
+ uint i_t0;
float fac;
sub_v3_v3v3(p_dir, p0, p1);
normalize_v3(p_dir);
for (i_t0 = 0; i_t0 < 3; i_t0++) {
- const unsigned int i_t1 = (i_t0 + 1) % 3;
+ const uint i_t1 = (i_t0 + 1) % 3;
float te_dir[3];
sub_v3_v3v3(te_dir, t_cos[i_t0], t_cos[i_t1]);
@@ -375,7 +375,7 @@ static BMVert *bm_isect_edge_tri(
{
BMesh *bm = s->bm;
int k_arr[IX_TOT][4];
- unsigned int i;
+ uint i;
const int ti[3] = {UNPACK3_EX(BM_elem_index_get, t, )};
float ix[3];
@@ -470,7 +470,7 @@ static BMVert *bm_isect_edge_tri(
}
if ((*r_side >= IX_EDGE_TRI_EDGE0) && (*r_side <= IX_EDGE_TRI_EDGE2)) {
- i = (unsigned int)(*r_side - IX_EDGE_TRI_EDGE0);
+ i = (uint)(*r_side - IX_EDGE_TRI_EDGE0);
e = BM_edge_exists(t[i], t[(i + 1) % 3]);
if (e) {
edge_verts_add(s, e, iv, false);
@@ -537,7 +537,7 @@ static void bm_isect_tri_tri(
const float *f_b_cos[3] = {UNPACK3_EX(, fv_b, ->co)};
float f_a_nor[3];
float f_b_nor[3];
- unsigned int i;
+ uint i;
/* should be enough but may need to bump */
@@ -578,9 +578,9 @@ static void bm_isect_tri_tri(
/* first check in any verts are touching
* (any case where we wont create new verts)
*/
- unsigned int i_a;
+ uint i_a;
for (i_a = 0; i_a < 3; i_a++) {
- unsigned int i_b;
+ uint i_b;
for (i_b = 0; i_b < 3; i_b++) {
if (len_squared_v3v3(fv_a[i_a]->co, fv_b[i_b]->co) <= s->epsilon.eps2x_sq) {
#ifdef USE_DUMP
@@ -603,12 +603,12 @@ static void bm_isect_tri_tri(
/* vert-edge
* --------- */
{
- unsigned int i_a;
+ uint i_a;
for (i_a = 0; i_a < 3; i_a++) {
if (BM_ELEM_API_FLAG_TEST(fv_a[i_a], VERT_VISIT_A) == 0) {
- unsigned int i_b_e0;
+ uint i_b_e0;
for (i_b_e0 = 0; i_b_e0 < 3; i_b_e0++) {
- unsigned int i_b_e1 = (i_b_e0 + 1) % 3;
+ uint i_b_e1 = (i_b_e0 + 1) % 3;
if (BM_ELEM_API_FLAG_TEST(fv_b[i_b_e0], VERT_VISIT_B) ||
BM_ELEM_API_FLAG_TEST(fv_b[i_b_e1], VERT_VISIT_B))
@@ -644,12 +644,12 @@ static void bm_isect_tri_tri(
}
{
- unsigned int i_b;
+ uint i_b;
for (i_b = 0; i_b < 3; i_b++) {
if (BM_ELEM_API_FLAG_TEST(fv_b[i_b], VERT_VISIT_B) == 0) {
- unsigned int i_a_e0;
+ uint i_a_e0;
for (i_a_e0 = 0; i_a_e0 < 3; i_a_e0++) {
- unsigned int i_a_e1 = (i_a_e0 + 1) % 3;
+ uint i_a_e1 = (i_a_e0 + 1) % 3;
if (BM_ELEM_API_FLAG_TEST(fv_a[i_a_e0], VERT_VISIT_A) ||
BM_ELEM_API_FLAG_TEST(fv_a[i_a_e1], VERT_VISIT_A))
@@ -689,7 +689,7 @@ static void bm_isect_tri_tri(
{
float t_scale[3][3];
- unsigned int i_a;
+ uint i_a;
copy_v3_v3(t_scale[0], fv_b[0]->co);
copy_v3_v3(t_scale[1], fv_b[1]->co);
@@ -717,7 +717,7 @@ static void bm_isect_tri_tri(
{
float t_scale[3][3];
- unsigned int i_b;
+ uint i_b;
copy_v3_v3(t_scale[0], fv_a[0]->co);
copy_v3_v3(t_scale[1], fv_a[1]->co);
@@ -757,8 +757,8 @@ static void bm_isect_tri_tri(
/* edge-tri & edge-edge
* -------------------- */
{
- for (unsigned int i_a_e0 = 0; i_a_e0 < 3; i_a_e0++) {
- unsigned int i_a_e1 = (i_a_e0 + 1) % 3;
+ for (uint i_a_e0 = 0; i_a_e0 < 3; i_a_e0++) {
+ uint i_a_e1 = (i_a_e0 + 1) % 3;
enum ISectType side;
BMVert *iv;
@@ -778,8 +778,8 @@ static void bm_isect_tri_tri(
}
}
- for (unsigned int i_b_e0 = 0; i_b_e0 < 3; i_b_e0++) {
- unsigned int i_b_e1 = (i_b_e0 + 1) % 3;
+ for (uint i_b_e0 = 0; i_b_e0 < 3; i_b_e0++) {
+ uint i_b_e1 = (i_b_e0 + 1) % 3;
enum ISectType side;
BMVert *iv;
@@ -956,7 +956,7 @@ static int isect_bvhtree_point_v3(
const float *depth_arr = z_buffer.data;
float depth_last = depth_arr[0];
- for (unsigned int i = 1; i < z_buffer.count; i++) {
+ for (uint i = 1; i < z_buffer.count; i++) {
if (depth_arr[i] - depth_last > eps) {
depth_last = depth_arr[i];
num_isect++;
@@ -986,7 +986,7 @@ bool BM_mesh_intersect(
struct BMLoop *(*looptris)[3], const int looptris_tot,
int (*test_fn)(BMFace *f, void *user_data), void *user_data,
const bool use_self, const bool use_separate, const bool use_dissolve, const bool use_island_connect,
- const int boolean_mode,
+ const bool use_edge_tag, const int boolean_mode,
const float eps)
{
struct ISectState s;
@@ -1000,7 +1000,7 @@ bool BM_mesh_intersect(
#ifdef USE_BVH
BVHTree *tree_a, *tree_b;
- unsigned int tree_overlap_tot;
+ uint tree_overlap_tot;
BVHTreeOverlap *overlap;
#else
int i_a, i_b;
@@ -1117,7 +1117,7 @@ bool BM_mesh_intersect(
overlap = BLI_bvhtree_overlap(tree_b, tree_a, &tree_overlap_tot, NULL, NULL);
if (overlap) {
- unsigned int i;
+ uint i;
for (i = 0; i < tree_overlap_tot; i++) {
#ifdef USE_DUMP
@@ -1275,8 +1275,8 @@ bool BM_mesh_intersect(
}
}
- splice_ls = MEM_mallocN(BLI_gset_size(s.wire_edges) * sizeof(*splice_ls), __func__);
- STACK_INIT(splice_ls, BLI_gset_size(s.wire_edges));
+ splice_ls = MEM_mallocN(BLI_gset_len(s.wire_edges) * sizeof(*splice_ls), __func__);
+ STACK_INIT(splice_ls, BLI_gset_len(s.wire_edges));
for (node = s.vert_dissolve; node; node = node->next) {
BMEdge *e_pair[2];
@@ -1390,7 +1390,7 @@ bool BM_mesh_intersect(
GHASH_ITER (gh_iter, s.face_edges) {
struct LinkBase *e_ls_base = BLI_ghashIterator_getValue(&gh_iter);
LinkNode **node_prev_p;
- unsigned int i;
+ uint i;
node_prev_p = &e_ls_base->list;
for (i = 0, node = e_ls_base->list; node; i++, node = node->next) {
@@ -1455,7 +1455,7 @@ bool BM_mesh_intersect(
}
{
- unsigned int i;
+ uint i;
for (i = 0; i < STACK_SIZE(splice_ls); i++) {
if (!BLI_gset_haskey(verts_invalid, splice_ls[i][0]) &&
!BLI_gset_haskey(verts_invalid, splice_ls[i][1]))
@@ -1526,7 +1526,7 @@ bool BM_mesh_intersect(
BM_mesh_edgesplit(bm, false, true, false);
}
- else if (boolean_mode != BMESH_ISECT_BOOLEAN_NONE) {
+ else if (boolean_mode != BMESH_ISECT_BOOLEAN_NONE || use_edge_tag) {
GSetIterator gs_iter;
/* no need to clear for boolean */
@@ -1610,7 +1610,7 @@ bool BM_mesh_intersect(
#ifdef USE_BOOLEAN_RAYCAST_DRAW
{
- unsigned int colors[4] = {0x00000000, 0xffffffff, 0xff000000, 0x0000ff};
+ uint colors[4] = {0x00000000, 0xffffffff, 0xff000000, 0x0000ff};
float co_other[3] = {UNPACK3(co)};
co_other[0] += 1000.0f;
bl_debug_color_set(colors[(hits & 1) == 1]);
@@ -1690,7 +1690,7 @@ bool BM_mesh_intersect(
}
}
- has_edit_isect = (BLI_ghash_size(s.face_edges) != 0);
+ has_edit_isect = (BLI_ghash_len(s.face_edges) != 0);
/* cleanup */
BLI_ghash_free(s.edgetri_cache, NULL, NULL);
diff --git a/source/blender/bmesh/tools/bmesh_intersect.h b/source/blender/bmesh/tools/bmesh_intersect.h
index d0cc41654eb..51926a01710 100644
--- a/source/blender/bmesh/tools/bmesh_intersect.h
+++ b/source/blender/bmesh/tools/bmesh_intersect.h
@@ -30,7 +30,7 @@ bool BM_mesh_intersect(
struct BMLoop *(*looptris)[3], const int looptris_tot,
int (*test_fn)(BMFace *f, void *user_data), void *user_data,
const bool use_self, const bool use_separate, const bool use_dissolve, const bool use_island_connect,
- const int boolean_mode,
+ const bool use_edge_tag, const int boolean_mode,
const float eps);
enum {
diff --git a/source/blender/bmesh/tools/bmesh_path.c b/source/blender/bmesh/tools/bmesh_path.c
index 30b083cacda..cc5ac6dd8ce 100644
--- a/source/blender/bmesh/tools/bmesh_path.c
+++ b/source/blender/bmesh/tools/bmesh_path.c
@@ -38,24 +38,34 @@
/* -------------------------------------------------------------------- */
/* Generic Helpers */
-static float step_cost_3_v3(const float v1[3], const float v2[3], const float v3[3])
+/**
+ * Use skip options when we want to start measuring from a boundary.
+ */
+static float step_cost_3_v3_ex(
+ const float v1[3], const float v2[3], const float v3[3],
+ bool skip_12, bool skip_23)
{
- float cost, d1[3], d2[3];
-
+ float d1[3], d2[3];
/* The cost is based on the simple sum of the length of the two edgees... */
sub_v3_v3v3(d1, v2, v1);
sub_v3_v3v3(d2, v3, v2);
- cost = normalize_v3(d1) + normalize_v3(d2);
+ const float cost_12 = normalize_v3(d1);
+ const float cost_23 = normalize_v3(d2);
+ const float cost = ((skip_12 ? 0.0f : cost_12) +
+ (skip_23 ? 0.0f : cost_23));
/* but is biased to give higher values to sharp turns, so that it will take
* paths with fewer "turns" when selecting between equal-weighted paths between
* the two edges */
- cost = cost * (1.0f + 0.5f * (2.0f - sqrtf(fabsf(dot_v3v3(d1, d2)))));
-
- return cost;
+ return cost * (1.0f + 0.5f * (2.0f - sqrtf(fabsf(dot_v3v3(d1, d2)))));
}
+static float step_cost_3_v3(
+ const float v1[3], const float v2[3], const float v3[3])
+{
+ return step_cost_3_v3_ex(v1, v2, v3, false, false);
+}
/* -------------------------------------------------------------------- */
@@ -164,7 +174,7 @@ LinkNode *BM_mesh_calc_path_vert(
cost[BM_elem_index_get(v_src)] = 0.0f;
while (!BLI_heap_is_empty(heap)) {
- v = BLI_heap_popmin(heap);
+ v = BLI_heap_pop_min(heap);
if (v == v_dst)
break;
@@ -336,7 +346,7 @@ LinkNode *BM_mesh_calc_path_edge(
cost[BM_elem_index_get(e_src)] = 0.0f;
while (!BLI_heap_is_empty(heap)) {
- e = BLI_heap_popmin(heap);
+ e = BLI_heap_pop_min(heap);
if (e == e_dst)
break;
@@ -364,7 +374,7 @@ LinkNode *BM_mesh_calc_path_edge(
/* -------------------------------------------------------------------- */
/* BM_mesh_calc_path_face */
-static float facetag_cut_cost_edge(BMFace *f_a, BMFace *f_b, BMEdge *e)
+static float facetag_cut_cost_edge(BMFace *f_a, BMFace *f_b, BMEdge *e, const void * const f_endpoints[2])
{
float f_a_cent[3];
float f_b_cent[3];
@@ -392,10 +402,12 @@ static float facetag_cut_cost_edge(BMFace *f_a, BMFace *f_b, BMEdge *e)
}
#endif
- return step_cost_3_v3(f_a_cent, e_cent, f_b_cent);
+ return step_cost_3_v3_ex(
+ f_a_cent, e_cent, f_b_cent,
+ (f_a == f_endpoints[0]), (f_b == f_endpoints[1]));
}
-static float facetag_cut_cost_vert(BMFace *f_a, BMFace *f_b, BMVert *v)
+static float facetag_cut_cost_vert(BMFace *f_a, BMFace *f_b, BMVert *v, const void * const f_endpoints[2])
{
float f_a_cent[3];
float f_b_cent[3];
@@ -403,12 +415,14 @@ static float facetag_cut_cost_vert(BMFace *f_a, BMFace *f_b, BMVert *v)
BM_face_calc_center_mean_weighted(f_a, f_a_cent);
BM_face_calc_center_mean_weighted(f_b, f_b_cent);
- return step_cost_3_v3(f_a_cent, v->co, f_b_cent);
+ return step_cost_3_v3_ex(
+ f_a_cent, v->co, f_b_cent,
+ (f_a == f_endpoints[0]), (f_b == f_endpoints[1]));
}
static void facetag_add_adjacent(
Heap *heap, BMFace *f_a, BMFace **faces_prev, float *cost,
- const struct BMCalcPathParams *params)
+ const void * const f_endpoints[2], const struct BMCalcPathParams *params)
{
const int f_a_index = BM_elem_index_get(f_a);
@@ -427,7 +441,7 @@ static void facetag_add_adjacent(
/* we know 'f_b' is not visited, check it out! */
const int f_b_index = BM_elem_index_get(f_b);
const float cost_cut = params->use_topology_distance ?
- 1.0f : facetag_cut_cost_edge(f_a, f_b, l_iter->e);
+ 1.0f : facetag_cut_cost_edge(f_a, f_b, l_iter->e, f_endpoints);
const float cost_new = cost[f_a_index] + cost_cut;
if (cost[f_b_index] > cost_new) {
@@ -454,7 +468,7 @@ static void facetag_add_adjacent(
/* we know 'f_b' is not visited, check it out! */
const int f_b_index = BM_elem_index_get(f_b);
const float cost_cut = params->use_topology_distance ?
- 1.0f : facetag_cut_cost_vert(f_a, f_b, l_a->v);
+ 1.0f : facetag_cut_cost_vert(f_a, f_b, l_a->v, f_endpoints);
const float cost_new = cost[f_a_index] + cost_cut;
if (cost[f_b_index] > cost_new) {
@@ -482,6 +496,9 @@ LinkNode *BM_mesh_calc_path_face(
BMFace **faces_prev;
int i, totface;
+ /* Start measuring face path at the face edges, ignoring their centers. */
+ const void * const f_endpoints[2] = {f_src, f_dst};
+
/* note, would pass BM_EDGE except we are looping over all faces anyway */
// BM_mesh_elem_index_ensure(bm, BM_VERT /* | BM_EDGE */); // NOT NEEDED FOR FACETAG
@@ -515,14 +532,14 @@ LinkNode *BM_mesh_calc_path_face(
cost[BM_elem_index_get(f_src)] = 0.0f;
while (!BLI_heap_is_empty(heap)) {
- f = BLI_heap_popmin(heap);
+ f = BLI_heap_pop_min(heap);
if (f == f_dst)
break;
if (!BM_elem_flag_test(f, BM_ELEM_TAG)) {
BM_elem_flag_enable(f, BM_ELEM_TAG);
- facetag_add_adjacent(heap, f, faces_prev, cost, params);
+ facetag_add_adjacent(heap, f, faces_prev, cost, f_endpoints, params);
}
}
diff --git a/source/blender/bmesh/tools/bmesh_path.h b/source/blender/bmesh/tools/bmesh_path.h
index b6de5e0e4e0..fbdd2296121 100644
--- a/source/blender/bmesh/tools/bmesh_path.h
+++ b/source/blender/bmesh/tools/bmesh_path.h
@@ -28,8 +28,8 @@
*/
struct BMCalcPathParams {
- unsigned int use_topology_distance : 1;
- unsigned int use_step_face : 1;
+ uint use_topology_distance : 1;
+ uint use_step_face : 1;
};
struct LinkNode *BM_mesh_calc_path_vert(
diff --git a/source/blender/bmesh/tools/bmesh_path_region.c b/source/blender/bmesh/tools/bmesh_path_region.c
index aad1f9c5a49..d23ea537d82 100644
--- a/source/blender/bmesh/tools/bmesh_path_region.c
+++ b/source/blender/bmesh/tools/bmesh_path_region.c
@@ -29,22 +29,32 @@
#include "BLI_math.h"
#include "BLI_linklist.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_alloca.h"
#include "bmesh.h"
#include "bmesh_path_region.h" /* own include */
-/* Special handling of vertices with 2 edges
- * (act as if the edge-chain is a single edge). */
+/**
+ * Special handling of vertices with 2 edges
+ * (act as if the edge-chain is a single edge).
+ *
+ * \note Regarding manifold edge stepping: #BM_vert_is_edge_pair_manifold usage.
+ * Logic to skip a chain of vertices is not applied at boundaries because it gives
+ * strange behavior from a user perspective especially with boundary quads, see: T52701
+ *
+ * Restrict walking over a vertex chain to cases where the edges share the same faces.
+ * This is more typical of what a user would consider a vertex chain.
+ */
#define USE_EDGE_CHAIN
#ifdef USE_EDGE_CHAIN
/**
- * Takes a vertex with 2 edge users and fills in the vertices at each end-point,
- * or nothing if if the edges loop back to its self.
+ * Takes a vertex with 2 edge users and assigns the vertices at each end-point,
+ *
+ * \return Success when \a v_end_pair values are set or false if the edges loop back on themselves.
*/
static bool bm_vert_pair_ends(BMVert *v_pivot, BMVert *v_end_pair[2])
{
@@ -53,7 +63,7 @@ static bool bm_vert_pair_ends(BMVert *v_pivot, BMVert *v_end_pair[2])
do {
BMEdge *e_chain = e;
BMVert *v_other = BM_edge_other_vert(e_chain, v_pivot);
- while (BM_vert_is_edge_pair(v_other)) {
+ while (BM_vert_is_edge_pair_manifold(v_other)) {
BMEdge *e_chain_next = BM_DISK_EDGE_NEXT(e_chain, v_other);
BLI_assert(BM_DISK_EDGE_NEXT(e_chain_next, v_other) == e_chain);
v_other = BM_edge_other_vert(e_chain_next, v_other);
@@ -88,7 +98,7 @@ static bool bm_vert_region_test_chain(BMVert *v, int * const depths[2], const in
if (bm_vert_region_test(v, depths, pass)) {
return true;
}
- else if (BM_vert_is_edge_pair(v) &&
+ else if (BM_vert_is_edge_pair_manifold(v) &&
bm_vert_pair_ends(v, v_end_pair) &&
bm_vert_region_test(v_end_pair[0], depths, pass) &&
bm_vert_region_test(v_end_pair[1], depths, pass))
@@ -206,7 +216,7 @@ static LinkNode *mesh_calc_path_region_elem(
for (int i = 0; i < ele_verts_len[side]; i++) {
BMVert *v = ele_verts[side][i];
BMVert *v_end_pair[2];
- if (BM_vert_is_edge_pair(v) && bm_vert_pair_ends(v, v_end_pair)) {
+ if (BM_vert_is_edge_pair_manifold(v) && bm_vert_pair_ends(v, v_end_pair)) {
for (int j = 0; j < 2; j++) {
const int v_end_index = BM_elem_index_get(v_end_pair[j]);
if (depths[side][v_end_index] == -1) {
@@ -239,7 +249,7 @@ static LinkNode *mesh_calc_path_region_elem(
/* Walk along the chain, fill in values until we reach a vertex with 3+ edges. */
{
BMEdge *e_chain = e;
- while (BM_vert_is_edge_pair(v_b) &&
+ while (BM_vert_is_edge_pair_manifold(v_b) &&
((depths[side][v_b_index] == -1)))
{
depths[side][v_b_index] = pass;
@@ -256,7 +266,7 @@ static LinkNode *mesh_calc_path_region_elem(
/* Add the other vertex to the stack, to be traversed in the next pass. */
if (depths[side][v_b_index] == -1) {
#ifdef USE_EDGE_CHAIN
- BLI_assert(!BM_vert_is_edge_pair(v_b));
+ BLI_assert(!BM_vert_is_edge_pair_manifold(v_b));
#endif
BLI_assert(pass == depths[side][BM_elem_index_get(v_a)] + 1);
depths[side][v_b_index] = pass;
diff --git a/source/blender/bmesh/tools/bmesh_region_match.c b/source/blender/bmesh/tools/bmesh_region_match.c
index a6860a6614a..e83ba73ad01 100644
--- a/source/blender/bmesh/tools/bmesh_region_match.c
+++ b/source/blender/bmesh/tools/bmesh_region_match.c
@@ -114,7 +114,7 @@ typedef struct UUIDWalk {
GHash *faces_from_uuid; /* UUID -> UUIDFaceStepItem */
UUID_Int *rehash_store;
- unsigned int rehash_store_len;
+ uint rehash_store_len;
} cache;
} UUIDWalk;
@@ -136,7 +136,7 @@ typedef struct UUIDFaceStepItem {
uintptr_t uuid;
LinkNode *list;
- unsigned int list_len;
+ uint list_len;
} UUIDFaceStepItem;
BLI_INLINE bool bm_uuidwalk_face_test(
@@ -178,10 +178,10 @@ BLI_INLINE bool bm_uuidwalk_face_lookup(
}
}
-static unsigned int ghashutil_bmelem_indexhash(const void *key)
+static uint ghashutil_bmelem_indexhash(const void *key)
{
const BMElem *ele = key;
- return (unsigned int)BM_elem_index_get(ele);
+ return (uint)BM_elem_index_get(ele);
}
static bool ghashutil_bmelem_indexcmp(const void *a, const void *b)
@@ -192,14 +192,14 @@ static bool ghashutil_bmelem_indexcmp(const void *a, const void *b)
static GHash *ghash_bmelem_new_ex(
const char *info,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
return BLI_ghash_new_ex(ghashutil_bmelem_indexhash, ghashutil_bmelem_indexcmp, info, nentries_reserve);
}
static GSet *gset_bmelem_new_ex(
const char *info,
- const unsigned int nentries_reserve)
+ const uint nentries_reserve)
{
return BLI_gset_new_ex(ghashutil_bmelem_indexhash, ghashutil_bmelem_indexcmp, info, nentries_reserve);
}
@@ -218,8 +218,8 @@ static GSet *gset_bmelem_new(const char *info)
static void bm_uuidwalk_init(
UUIDWalk *uuidwalk,
- const unsigned int faces_src_region_len,
- const unsigned int verts_src_region_len)
+ const uint faces_src_region_len,
+ const uint verts_src_region_len)
{
BLI_listbase_clear(&uuidwalk->faces_step);
@@ -307,7 +307,7 @@ static UUID_Int bm_uuidwalk_calc_vert_uuid(
/* vert -> other */
{
- unsigned int tot = 0;
+ uint tot = 0;
BMIter eiter;
BMEdge *e;
BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
@@ -323,7 +323,7 @@ static UUID_Int bm_uuidwalk_calc_vert_uuid(
/* faces */
{
- unsigned int tot = 0;
+ uint tot = 0;
BMIter iter;
BMFace *f;
@@ -357,7 +357,7 @@ static UUID_Int bm_uuidwalk_calc_face_uuid(
UUID_Int uuid;
- uuid = uuidwalk->pass * (unsigned int)f->len * PRIME_FACE_LARGE;
+ uuid = uuidwalk->pass * (uint)f->len * PRIME_FACE_LARGE;
/* face-verts */
{
@@ -399,7 +399,7 @@ static UUID_Int bm_uuidwalk_calc_face_uuid(
}
static void bm_uuidwalk_rehash_reserve(
- UUIDWalk *uuidwalk, unsigned int rehash_store_len_new)
+ UUIDWalk *uuidwalk, uint rehash_store_len_new)
{
if (UNLIKELY(rehash_store_len_new > uuidwalk->cache.rehash_store_len)) {
/* avoid re-allocs */
@@ -419,10 +419,10 @@ static void bm_uuidwalk_rehash(
{
GHashIterator gh_iter;
UUID_Int *uuid_store;
- unsigned int i;
+ uint i;
- unsigned int rehash_store_len_new = MAX2(BLI_ghash_size(uuidwalk->verts_uuid),
- BLI_ghash_size(uuidwalk->faces_uuid));
+ uint rehash_store_len_new = MAX2(BLI_ghash_len(uuidwalk->verts_uuid),
+ BLI_ghash_len(uuidwalk->faces_uuid));
bm_uuidwalk_rehash_reserve(uuidwalk, rehash_store_len_new);
uuid_store = uuidwalk->cache.rehash_store;
@@ -454,12 +454,12 @@ static void bm_uuidwalk_rehash(
static void bm_uuidwalk_rehash_facelinks(
UUIDWalk *uuidwalk,
- LinkNode *faces, const unsigned int faces_len,
+ LinkNode *faces, const uint faces_len,
const bool is_init)
{
UUID_Int *uuid_store;
LinkNode *f_link;
- unsigned int i;
+ uint i;
bm_uuidwalk_rehash_reserve(uuidwalk, faces_len);
uuid_store = uuidwalk->cache.rehash_store;
@@ -502,7 +502,7 @@ static bool bm_vert_is_uuid_connect(
}
static void bm_uuidwalk_pass_add(
- UUIDWalk *uuidwalk, LinkNode *faces_pass, const unsigned int faces_pass_len)
+ UUIDWalk *uuidwalk, LinkNode *faces_pass, const uint faces_pass_len)
{
GHashIterator gh_iter;
GHash *verts_uuid_pass;
@@ -511,7 +511,7 @@ static void bm_uuidwalk_pass_add(
UUIDFaceStep *fstep;
- BLI_assert(faces_pass_len == (unsigned int)BLI_linklist_count(faces_pass));
+ BLI_assert(faces_pass_len == (uint)BLI_linklist_count(faces_pass));
/* rehash faces now all their verts have been added */
bm_uuidwalk_rehash_facelinks(uuidwalk, faces_pass, faces_pass_len, true);
@@ -520,8 +520,8 @@ static void bm_uuidwalk_pass_add(
verts_uuid_pass = uuidwalk->cache.verts_uuid;
faces_step_next = uuidwalk->cache.faces_step;
- BLI_assert(BLI_ghash_size(verts_uuid_pass) == 0);
- BLI_assert(BLI_gset_size(faces_step_next) == 0);
+ BLI_assert(BLI_ghash_len(verts_uuid_pass) == 0);
+ BLI_assert(BLI_gset_len(faces_step_next) == 0);
/* Add the face_step data from connected faces, creating new passes */
fstep = BLI_mempool_alloc(uuidwalk->step_pool);
@@ -588,13 +588,13 @@ static int bm_face_len_cmp(const void *v1, const void *v2)
else return 0;
}
-static unsigned int bm_uuidwalk_init_from_edge(
+static uint bm_uuidwalk_init_from_edge(
UUIDWalk *uuidwalk, BMEdge *e)
{
BMLoop *l_iter = e->l;
- unsigned int f_arr_len = (unsigned int)BM_edge_face_count(e);
+ uint f_arr_len = (uint)BM_edge_face_count(e);
BMFace **f_arr = BLI_array_alloca(f_arr, f_arr_len);
- unsigned int fstep_num = 0, i = 0;
+ uint fstep_num = 0, i = 0;
do {
BMFace *f = l_iter->f;
@@ -619,7 +619,7 @@ static unsigned int bm_uuidwalk_init_from_edge(
* elsewhere using LinkNode's makes more sense */
for (i = 0; i < f_arr_len; ) {
LinkNode *faces_pass = NULL;
- const unsigned int i_init = i;
+ const uint i_init = i;
const int f_len = f_arr[i]->len;
do {
@@ -659,7 +659,7 @@ static bool bm_uuidwalk_facestep_begin(
LinkNode *f_link, *f_link_next, **f_link_prev_p;
bool ok = false;
- BLI_assert(BLI_ghash_size(uuidwalk->cache.faces_from_uuid) == 0);
+ BLI_assert(BLI_ghash_len(uuidwalk->cache.faces_from_uuid) == 0);
BLI_assert(BLI_listbase_is_empty(&fstep->items));
f_link_prev_p = &fstep->faces;
@@ -750,9 +750,9 @@ static BMFace **bm_mesh_region_match_pair(
UUIDWalk *w_src, UUIDWalk *w_dst,
#endif
BMEdge *e_src, BMEdge *e_dst,
- const unsigned int faces_src_region_len,
- const unsigned int verts_src_region_len,
- unsigned int *r_faces_result_len)
+ const uint faces_src_region_len,
+ const uint verts_src_region_len,
+ uint *r_faces_result_len)
{
#ifndef USE_WALKER_REUSE
UUIDWalk w_src_, w_dst_;
@@ -864,7 +864,7 @@ static BMFace **bm_mesh_region_match_pair(
break;
}
- found = (BLI_ghash_size(w_dst->faces_uuid) == faces_src_region_len);
+ found = (BLI_ghash_len(w_dst->faces_uuid) == faces_src_region_len);
if (found) {
break;
}
@@ -877,8 +877,8 @@ static BMFace **bm_mesh_region_match_pair(
if (found) {
GHashIterator gh_iter;
- const unsigned int faces_result_len = BLI_ghash_size(w_dst->faces_uuid);
- unsigned int i;
+ const uint faces_result_len = BLI_ghash_len(w_dst->faces_uuid);
+ uint i;
faces_result = MEM_mallocN(sizeof(*faces_result) * (faces_result_len + 1), __func__);
GHASH_ITER_INDEX (gh_iter, w_dst->faces_uuid, i) {
@@ -909,12 +909,12 @@ finally:
* Tag as visited, avoid re-use.
*/
static void bm_face_array_visit(
- BMFace **faces, const unsigned int faces_len,
- unsigned int *r_verts_len,
+ BMFace **faces, const uint faces_len,
+ uint *r_verts_len,
bool visit_faces)
{
- unsigned int verts_len = 0;
- unsigned int i;
+ uint verts_len = 0;
+ uint i;
for (i = 0; i < faces_len; i++) {
BMFace *f = faces[i];
BMLoop *l_iter, *l_first;
@@ -1081,9 +1081,9 @@ static SUID_Int bm_face_region_vert_pass_id(GHash *gh, BMVert *v)
* This is only called once on the source region (no need to be highly optimized).
*/
static BMEdge *bm_face_region_pivot_edge_find(
- BMFace **faces_region, unsigned int faces_region_len,
- unsigned int verts_region_len,
- unsigned int *r_depth)
+ BMFace **faces_region, uint faces_region_len,
+ uint verts_region_len,
+ uint *r_depth)
{
/* note, keep deterministic where possible (geometry order independent)
* this function assumed all visit faces & edges are tagged */
@@ -1092,7 +1092,7 @@ static BMEdge *bm_face_region_pivot_edge_find(
BLI_LINKSTACK_DECLARE(vert_queue_next, BMVert *);
GHash *gh = BLI_ghash_ptr_new(__func__);
- unsigned int i;
+ uint i;
BMEdge *e_pivot = NULL;
/* pick any non-boundary edge (not ideal) */
@@ -1101,7 +1101,7 @@ static BMEdge *bm_face_region_pivot_edge_find(
SUID_Int pass = 0;
/* total verts in 'gs' we have visited - aka - not v_init_none */
- unsigned int vert_queue_used = 0;
+ uint vert_queue_used = 0;
BLI_LINKSTACK_INIT(vert_queue_prev);
BLI_LINKSTACK_INIT(vert_queue_next);
@@ -1115,7 +1115,7 @@ static BMEdge *bm_face_region_pivot_edge_find(
do {
BMEdge *e = l_iter->e;
if (bm_edge_is_region_boundary(e)) {
- unsigned int j;
+ uint j;
for (j = 0; j < 2; j++) {
void **val_p;
if (!BLI_ghash_ensure_p(gh, (&e->v1)[j], &val_p)) {
@@ -1251,7 +1251,7 @@ static BMEdge *bm_face_region_pivot_edge_find(
pass = 0;
}
- *r_depth = (unsigned int)pass;
+ *r_depth = (uint)pass;
return e_pivot;
}
@@ -1286,7 +1286,7 @@ static UUIDFashMatch bm_vert_fasthash_single(BMVert *v)
e_num += 1;
do {
f_num += 1;
- l_num += (unsigned int)l_iter->f->len;
+ l_num += (uint)l_iter->f->len;
} while ((l_iter = l_iter->radial_next) != e->l);
}
}
@@ -1301,16 +1301,16 @@ static UUIDFashMatch bm_vert_fasthash_single(BMVert *v)
}
static UUIDFashMatch *bm_vert_fasthash_create(
- BMesh *bm, const unsigned int depth)
+ BMesh *bm, const uint depth)
{
UUIDFashMatch *id_prev;
UUIDFashMatch *id_curr;
- unsigned int pass, i;
+ uint pass, i;
BMVert *v;
BMIter iter;
- id_prev = MEM_mallocN(sizeof(*id_prev) * (unsigned int)bm->totvert, __func__);
- id_curr = MEM_mallocN(sizeof(*id_curr) * (unsigned int)bm->totvert, __func__);
+ id_prev = MEM_mallocN(sizeof(*id_prev) * (uint)bm->totvert, __func__);
+ id_curr = MEM_mallocN(sizeof(*id_curr) * (uint)bm->totvert, __func__);
BM_ITER_MESH_INDEX (v, &iter, bm, BM_VERTS_OF_MESH, i) {
id_prev[i] = bm_vert_fasthash_single(v);
@@ -1319,7 +1319,7 @@ static UUIDFashMatch *bm_vert_fasthash_create(
for (pass = 0; pass < depth; pass++) {
BMEdge *e;
- memcpy(id_curr, id_prev, sizeof(*id_prev) * (unsigned int)bm->totvert);
+ memcpy(id_curr, id_prev, sizeof(*id_prev) * (uint)bm->totvert);
BM_ITER_MESH (e, &iter, bm, BM_EDGES_OF_MESH) {
if (BM_edge_is_wire(e) == false) {
@@ -1379,16 +1379,16 @@ static void bm_vert_fasthash_destroy(
*/
int BM_mesh_region_match(
BMesh *bm,
- BMFace **faces_region, unsigned int faces_region_len,
+ BMFace **faces_region, uint faces_region_len,
ListBase *r_face_regions)
{
BMEdge *e_src;
BMEdge *e_dst;
BMIter iter;
- unsigned int verts_region_len = 0;
- unsigned int faces_result_len = 0;
+ uint verts_region_len = 0;
+ uint faces_result_len = 0;
/* number of steps from e_src to a boundary vert */
- unsigned int depth;
+ uint depth;
#ifdef USE_WALKER_REUSE
@@ -1457,7 +1457,7 @@ int BM_mesh_region_match(
BM_ITER_MESH (e_dst, &iter, bm, BM_EDGES_OF_MESH) {
BMFace **faces_result;
- unsigned int faces_result_len_out;
+ uint faces_result_len_out;
if (BM_elem_flag_test(e_dst, BM_ELEM_TAG) || BM_edge_is_wire(e_dst)) {
continue;
diff --git a/source/blender/bmesh/tools/bmesh_region_match.h b/source/blender/bmesh/tools/bmesh_region_match.h
index edf8369b070..8ef138629b8 100644
--- a/source/blender/bmesh/tools/bmesh_region_match.h
+++ b/source/blender/bmesh/tools/bmesh_region_match.h
@@ -27,7 +27,7 @@
int BM_mesh_region_match(
BMesh *bm,
- BMFace **faces_region, unsigned int faces_region_len,
+ BMFace **faces_region, uint faces_region_len,
ListBase *r_face_regions);
#endif /* __BMESH_REGION_MATCH_H__ */
diff --git a/source/blender/bmesh/tools/bmesh_separate.c b/source/blender/bmesh/tools/bmesh_separate.c
new file mode 100644
index 00000000000..b3d0c339885
--- /dev/null
+++ b/source/blender/bmesh/tools/bmesh_separate.c
@@ -0,0 +1,133 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/bmesh/tools/bmesh_separate.c
+ * \ingroup bmesh
+ *
+ * BMesh separate, disconnects a set of faces from all others,
+ * so they don't share any vertices/edges with other faces.
+ */
+
+#include <limits.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_buffer.h"
+
+#include "bmesh.h"
+#include "intern/bmesh_private.h"
+#include "bmesh_separate.h" /* own include */
+
+/**
+ * Split all faces that match `filter_fn`.
+ * \note
+ */
+void BM_mesh_separate_faces(
+ BMesh *bm,
+ BMFaceFilterFunc filter_fn, void *user_data)
+{
+ BMFace **faces_array_all = MEM_mallocN(bm->totface * sizeof(BMFace *), __func__);
+ /*
+ * - Create an array of faces based on 'filter_fn'.
+ * First part of array for match, for non-match.
+ *
+ * - Enable all vertex tags, then clear all tagged vertices from 'faces_b'.
+ *
+ * - Loop over 'faces_a', checking each vertex,
+ * splitting out any which aren't tagged (and therefor shared), disabling tags as we go.
+ */
+
+ BMFace *f;
+ BMIter iter;
+
+ uint faces_a_len = 0;
+ uint faces_b_len = 0;
+ {
+ int i_a = 0;
+ int i_b = bm->totface;
+ BM_ITER_MESH (f, &iter, bm, BM_FACES_OF_MESH) {
+ faces_array_all[filter_fn(f, user_data) ? i_a++ : --i_b] = f;
+ }
+ faces_a_len = i_a;
+ faces_b_len = bm->totface - i_a;
+ }
+
+ BMFace **faces_a = faces_array_all;
+ BMFace **faces_b = faces_array_all + faces_a_len;
+
+ /* Enable for all */
+ BM_mesh_elem_hflag_enable_all(bm, BM_VERT, BM_ELEM_TAG, false);
+
+ /* Disable vert tag on faces_b */
+ for (uint i = 0; i < faces_b_len; i++) {
+ BMLoop *l_iter, *l_first;
+ l_iter = l_first = BM_FACE_FIRST_LOOP(faces_b[i]);
+ do {
+ BM_elem_flag_disable(l_iter->v, BM_ELEM_TAG);
+ } while ((l_iter = l_iter->next) != l_first);
+ }
+
+
+ BLI_buffer_declare_static(BMLoop **, loop_split, 0, 128);
+
+ /* Check shared verts ('faces_a' tag and disable) */
+ for (uint i = 0; i < faces_a_len; i++) {
+ BMLoop *l_iter, *l_first;
+ l_iter = l_first = BM_FACE_FIRST_LOOP(faces_a[i]);
+ do {
+ if (!BM_elem_flag_test(l_iter->v, BM_ELEM_TAG)) {
+ BMVert *v = l_iter->v;
+ /* Enable, since we may visit this vertex again on other faces */
+ BM_elem_flag_enable(v, BM_ELEM_TAG);
+
+ /* We know the vertex is shared, collect all vertices and split them off. */
+
+ /* Fill 'loop_split' */
+ {
+ BMEdge *e_first, *e_iter;
+ e_iter = e_first = l_iter->e;
+ do {
+ if (e_iter->l != NULL) {
+ BMLoop *l_radial_first, *l_radial_iter;
+ l_radial_first = l_radial_iter = e_iter->l;
+ do {
+ if (l_radial_iter->v == v) {
+ if (filter_fn(l_radial_iter->f, user_data)) {
+ BLI_buffer_append(&loop_split, BMLoop *, l_radial_iter);
+ }
+ }
+ } while ((l_radial_iter = l_radial_iter->radial_next) != l_radial_first);
+ }
+ } while ((e_iter = bmesh_disk_edge_next(e_iter, v)) != e_first);
+ }
+
+ /* Perform the split */
+ BM_face_loop_separate_multi(bm, loop_split.data, loop_split.count);
+
+ BLI_buffer_clear(&loop_split);
+ }
+ } while ((l_iter = l_iter->next) != l_first);
+ }
+
+ BLI_buffer_free(&loop_split);
+
+ MEM_freeN(faces_array_all);
+}
diff --git a/source/blender/bmesh/tools/bmesh_separate.h b/source/blender/bmesh/tools/bmesh_separate.h
new file mode 100644
index 00000000000..91b2b71c872
--- /dev/null
+++ b/source/blender/bmesh/tools/bmesh_separate.h
@@ -0,0 +1,32 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#ifndef __BMESH_SEPARATE_H__
+#define __BMESH_SEPARATE_H__
+
+/** \file blender/bmesh/tools/bmesh_separate.h
+ * \ingroup bmesh
+ */
+
+void BM_mesh_separate_faces(
+ BMesh *bm,
+ BMFaceFilterFunc filter_fn, void *user_data);
+
+#endif /* __BMESH_SEPARATE_H__ */
diff --git a/source/blender/bmesh/tools/bmesh_triangulate.c b/source/blender/bmesh/tools/bmesh_triangulate.c
index ce1bc46d5e8..a3a3355d20f 100644
--- a/source/blender/bmesh/tools/bmesh_triangulate.c
+++ b/source/blender/bmesh/tools/bmesh_triangulate.c
@@ -35,12 +35,11 @@
#include "BLI_alloca.h"
#include "BLI_memarena.h"
#include "BLI_heap.h"
-#include "BLI_edgehash.h"
#include "BLI_linklist.h"
/* only for defines */
-#include "BLI_polyfill2d.h"
-#include "BLI_polyfill2d_beautify.h"
+#include "BLI_polyfill_2d.h"
+#include "BLI_polyfill_2d_beautify.h"
#include "bmesh.h"
@@ -57,7 +56,7 @@ static void bm_face_triangulate_mapping(
MemArena *pf_arena,
/* use for MOD_TRIANGULATE_NGON_BEAUTY only! */
- struct Heap *pf_heap, struct EdgeHash *pf_ehash)
+ struct Heap *pf_heap)
{
int faces_array_tot = face->len - 3;
BMFace **faces_array = BLI_array_alloca(faces_array, faces_array_tot);
@@ -71,7 +70,7 @@ static void bm_face_triangulate_mapping(
&faces_double,
quad_method, ngon_method, use_tag,
pf_arena,
- pf_heap, pf_ehash);
+ pf_heap);
if (faces_array_tot) {
int i;
@@ -98,17 +97,14 @@ void BM_mesh_triangulate(
BMFace *face;
MemArena *pf_arena;
Heap *pf_heap;
- EdgeHash *pf_ehash;
pf_arena = BLI_memarena_new(BLI_POLYFILL_ARENA_SIZE, __func__);
if (ngon_method == MOD_TRIANGULATE_NGON_BEAUTY) {
pf_heap = BLI_heap_new_ex(BLI_POLYFILL_ALLOC_NGON_RESERVE);
- pf_ehash = BLI_edgehash_new_ex(__func__, BLI_POLYFILL_ALLOC_NGON_RESERVE);
}
else {
pf_heap = NULL;
- pf_ehash = NULL;
}
if (slot_facemap_out) {
@@ -120,8 +116,7 @@ void BM_mesh_triangulate(
bm, face,
quad_method, ngon_method, tag_only,
op, slot_facemap_out, slot_facemap_double_out,
- pf_arena,
- pf_heap, pf_ehash);
+ pf_arena, pf_heap);
}
}
}
@@ -138,8 +133,7 @@ void BM_mesh_triangulate(
NULL, NULL,
&faces_double,
quad_method, ngon_method, tag_only,
- pf_arena,
- pf_heap, pf_ehash);
+ pf_arena, pf_heap);
}
}
}
@@ -156,6 +150,5 @@ void BM_mesh_triangulate(
if (ngon_method == MOD_TRIANGULATE_NGON_BEAUTY) {
BLI_heap_free(pf_heap, NULL);
- BLI_edgehash_free(pf_ehash, NULL);
}
}
diff --git a/source/blender/collada/AnimationExporter.cpp b/source/blender/collada/AnimationExporter.cpp
index 3bff20e846b..a59665f897f 100644
--- a/source/blender/collada/AnimationExporter.cpp
+++ b/source/blender/collada/AnimationExporter.cpp
@@ -49,40 +49,265 @@ bool AnimationExporter::exportAnimations(Scene *sce)
return has_animations;
}
-// called for each exported object
+bool AnimationExporter::is_flat_line(std::vector<float> &values, int channel_count)
+{
+ for (int i = 0; i < values.size(); i += channel_count) {
+ for (int j = 0; j < channel_count; j++) {
+ if (!bc_in_range(values[j], values[i+j], 0.000001))
+ return false;
+ }
+ }
+ return true;
+}
+/*
+ * This function creates a complete LINEAR Collada <Animation> Entry with all needed
+ * <source>, <sampler>, and <channel> entries.
+ * This is is used for creating sampled Transformation Animations for either:
+ *
+ * 1-axis animation:
+ * times contains the time points in seconds from within the timeline
+ * values contains the data (list of single floats)
+ * channel_count = 1
+ * axis_name = ['X' | 'Y' | 'Z']
+ * is_rot indicates if the animation is a rotation
+ *
+ * 3-axis animation:
+ * times contains the time points in seconds from within the timeline
+ * values contains the data (list of floats where each 3 entries are one vector)
+ * channel_count = 3
+ * axis_name = "" (actually not used)
+ * is_rot = false (see xxx below)
+ *
+ * xxx: I tried to create a 3 axis rotation animation
+ * like for translation or scale. But i could not
+ * figure out how to setup the channel for this case.
+ * So for now rotations are exported as 3 separate 1-axis collada animations
+ * See export_sampled_animation() further down.
+ */
+void AnimationExporter::create_sampled_animation(int channel_count,
+ std::vector<float> &times,
+ std::vector<float> &values,
+ std::string ob_name,
+ std::string label,
+ std::string axis_name,
+ bool is_rot)
+{
+ char anim_id[200];
+
+ if (is_flat_line(values, channel_count))
+ return;
+
+ BLI_snprintf(anim_id, sizeof(anim_id), "%s_%s_%s", (char *)translate_id(ob_name).c_str(), label.c_str(), axis_name.c_str());
+
+ openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);
+
+ /* create input source */
+ std::string input_id = create_source_from_vector(COLLADASW::InputSemantic::INPUT, times, false, anim_id, "");
+
+ /* create output source */
+ std::string output_id;
+ if (channel_count == 1)
+ output_id = create_source_from_array(COLLADASW::InputSemantic::OUTPUT, &values[0], values.size(), is_rot, anim_id, axis_name.c_str());
+ else if (channel_count == 3)
+ output_id = create_xyz_source(&values[0], times.size(), anim_id);
+ else if (channel_count == 16)
+ output_id = create_4x4_source(times, values, anim_id);
+
+ std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
+ COLLADASW::LibraryAnimations::Sampler sampler(sw, sampler_id);
+ std::string empty;
+ sampler.addInput(COLLADASW::InputSemantic::INPUT, COLLADABU::URI(empty, input_id));
+ sampler.addInput(COLLADASW::InputSemantic::OUTPUT, COLLADABU::URI(empty, output_id));
+
+ /* TODO create in/out tangents source (LINEAR) */
+ std::string interpolation_id = fake_interpolation_source(times.size(), anim_id, "");
+
+ /* Create Sampler */
+ sampler.addInput(COLLADASW::InputSemantic::INTERPOLATION, COLLADABU::URI(empty, interpolation_id));
+ addSampler(sampler);
+
+ /* Create channel */
+ std::string target = translate_id(ob_name) + "/" + label + axis_name + ((is_rot) ? ".ANGLE" : "");
+ addChannel(COLLADABU::URI(empty, sampler_id), target);
+
+ closeAnimation();
+
+}
+
+/*
+ * Export all animation FCurves of an Object.
+ *
+ * Note: This uses the keyframes as sample points,
+ * and exports "baked keyframes" while keeping the tangent infromation
+ * of the FCurves intact. This works for simple cases, but breaks
+ * especially when negative scales are involved in the animation.
+ *
+ * If it is necessary to conserve the Animation precisely then
+ * use export_sampled_animation_set() instead.
+ */
+void AnimationExporter::export_keyframed_animation_set(Object *ob)
+{
+ FCurve *fcu = (FCurve *)ob->adt->action->curves.first;
+ if (!fcu) {
+ return; /* object has no animation */
+ }
+
+ if (this->export_settings->export_transformation_type == BC_TRANSFORMATION_TYPE_MATRIX) {
+
+ std::vector<float> ctimes;
+ find_keyframes(ob, ctimes);
+ if (ctimes.size() > 0)
+ export_sampled_matrix_animation(ob, ctimes);
+ }
+ else {
+ char *transformName;
+ while (fcu) {
+ //for armature animations as objects
+ if (ob->type == OB_ARMATURE)
+ transformName = fcu->rna_path;
+ else
+ transformName = extract_transform_name(fcu->rna_path);
+
+ if (
+ STREQ(transformName, "location") ||
+ STREQ(transformName, "scale") ||
+ (STREQ(transformName, "rotation_euler") && ob->rotmode == ROT_MODE_EUL) ||
+ STREQ(transformName, "rotation_quaternion"))
+ {
+ create_keyframed_animation(ob, fcu, transformName, false);
+ }
+ fcu = fcu->next;
+ }
+ }
+}
+
+/*
+ * Export the sampled animation of an Object.
+ *
+ * Note: This steps over all animation frames (step size is given in export_settings.sample_size)
+ * and then evaluates the transformation,
+ * and exports "baked samples" This works always, however currently the interpolation type is set
+ * to LINEAR for now. (maybe later this can be changed to BEZIER)
+ *
+ * Note: If it is necessary to keep the FCurves intact, then use export_keyframed_animation_set() instead.
+ * However be aware that exporting keyframed animation may modify the animation slightly.
+ * Also keyframed animation exports tend to break when negative scales are involved.
+ */
+void AnimationExporter::export_sampled_animation_set(Object *ob)
+{
+ std::vector<float>ctimes;
+ find_sampleframes(ob, ctimes);
+ if (ctimes.size() > 0) {
+ if (this->export_settings->export_transformation_type == BC_TRANSFORMATION_TYPE_MATRIX)
+ export_sampled_matrix_animation(ob, ctimes);
+ else
+ export_sampled_transrotloc_animation(ob, ctimes);
+ }
+}
+
+void AnimationExporter::export_sampled_matrix_animation(Object *ob, std::vector<float> &ctimes)
+{
+ UnitConverter converter;
+
+ std::vector<float> values;
+
+ for (std::vector<float>::iterator ctime = ctimes.begin(); ctime != ctimes.end(); ++ctime) {
+ float fmat[4][4];
+
+ bc_update_scene(scene, *ctime);
+ BKE_object_matrix_local_get(ob, fmat);
+ if (this->export_settings->limit_precision)
+ bc_sanitize_mat(fmat, 6);
+
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ values.push_back(fmat[i][j]);
+ }
+
+ std::string ob_name = id_name(ob);
+
+ create_sampled_animation(16, ctimes, values, ob_name, "transform", "", false);
+}
+
+void AnimationExporter::export_sampled_transrotloc_animation(Object *ob, std::vector<float> &ctimes)
+{
+ static int LOC = 0;
+ static int EULX = 1;
+ static int EULY = 2;
+ static int EULZ = 3;
+ static int SCALE = 4;
+
+ std::vector<float> baked_curves[5];
+
+ for (std::vector<float>::iterator ctime = ctimes.begin(); ctime != ctimes.end(); ++ctime ) {
+ float fmat[4][4];
+ float floc[3];
+ float fquat[4];
+ float fsize[3];
+ float feul[3];
+
+ bc_update_scene(scene, *ctime);
+ BKE_object_matrix_local_get(ob, fmat);
+ mat4_decompose(floc, fquat, fsize, fmat);
+ quat_to_eul(feul, fquat);
+
+ baked_curves[LOC].push_back(floc[0]);
+ baked_curves[LOC].push_back(floc[1]);
+ baked_curves[LOC].push_back(floc[2]);
+
+ baked_curves[EULX].push_back(feul[0]);
+ baked_curves[EULY].push_back(feul[1]);
+ baked_curves[EULZ].push_back(feul[2]);
+
+ baked_curves[SCALE].push_back(fsize[0]);
+ baked_curves[SCALE].push_back(fsize[1]);
+ baked_curves[SCALE].push_back(fsize[2]);
+
+ }
+
+ std::string ob_name = id_name(ob);
+
+ create_sampled_animation(3, ctimes, baked_curves[SCALE], ob_name, "scale", "", false);
+ create_sampled_animation(3, ctimes, baked_curves[LOC], ob_name, "location", "", false);
+
+ /* Not sure how to export rotation as a 3channel animation,
+ * so separate into 3 single animations for now:
+ */
+
+ create_sampled_animation(1, ctimes, baked_curves[EULX], ob_name, "rotation", "X", true);
+ create_sampled_animation(1, ctimes, baked_curves[EULY], ob_name, "rotation", "Y", true);
+ create_sampled_animation(1, ctimes, baked_curves[EULZ], ob_name, "rotation", "Z", true);
+
+ fprintf(stdout, "Animation Export: Baked %d frames for %s (sampling rate: %d)\n",
+ (int)baked_curves[0].size(),
+ ob->id.name,
+ this->export_settings->sampling_rate);
+}
+
+/* called for each exported object */
void AnimationExporter::operator()(Object *ob)
{
- FCurve *fcu;
char *transformName;
+
/* bool isMatAnim = false; */ /* UNUSED */
//Export transform animations
if (ob->adt && ob->adt->action) {
- fcu = (FCurve *)ob->adt->action->curves.first;
- //transform matrix export for bones are temporarily disabled here.
if (ob->type == OB_ARMATURE) {
+ /* Export skeletal animation (if any)*/
bArmature *arm = (bArmature *)ob->data;
for (Bone *bone = (Bone *)arm->bonebase.first; bone; bone = bone->next)
write_bone_animation_matrix(ob, bone);
}
- while (fcu) {
- //for armature animations as objects
- if (ob->type == OB_ARMATURE)
- transformName = fcu->rna_path;
- else
- transformName = extract_transform_name(fcu->rna_path);
-
- if ((STREQ(transformName, "location") || STREQ(transformName, "scale")) ||
- (STREQ(transformName, "rotation_euler") && ob->rotmode == ROT_MODE_EUL) ||
- (STREQ(transformName, "rotation_quaternion")))
- {
- dae_animation(ob, fcu, transformName, false);
- }
- fcu = fcu->next;
+ /* Armatures can have object animation and skeletal animation*/
+ if (this->export_settings->sampling_rate < 1) {
+ export_keyframed_animation_set(ob);
+ }
+ else {
+ export_sampled_animation_set(ob);
}
-
}
export_object_constraint_animation(ob);
@@ -92,14 +317,14 @@ void AnimationExporter::operator()(Object *ob)
//Export Lamp parameter animations
if ( (ob->type == OB_LAMP) && ((Lamp *)ob->data)->adt && ((Lamp *)ob->data)->adt->action) {
- fcu = (FCurve *)(((Lamp *)ob->data)->adt->action->curves.first);
+ FCurve *fcu = (FCurve *)(((Lamp *)ob->data)->adt->action->curves.first);
while (fcu) {
transformName = extract_transform_name(fcu->rna_path);
if ((STREQ(transformName, "color")) || (STREQ(transformName, "spot_size")) ||
(STREQ(transformName, "spot_blend")) || (STREQ(transformName, "distance")))
{
- dae_animation(ob, fcu, transformName, true);
+ create_keyframed_animation(ob, fcu, transformName, true);
}
fcu = fcu->next;
}
@@ -107,7 +332,7 @@ void AnimationExporter::operator()(Object *ob)
//Export Camera parameter animations
if ( (ob->type == OB_CAMERA) && ((Camera *)ob->data)->adt && ((Camera *)ob->data)->adt->action) {
- fcu = (FCurve *)(((Camera *)ob->data)->adt->action->curves.first);
+ FCurve *fcu = (FCurve *)(((Camera *)ob->data)->adt->action->curves.first);
while (fcu) {
transformName = extract_transform_name(fcu->rna_path);
@@ -116,7 +341,7 @@ void AnimationExporter::operator()(Object *ob)
(STREQ(transformName, "clip_end")) ||
(STREQ(transformName, "clip_start")))
{
- dae_animation(ob, fcu, transformName, true);
+ create_keyframed_animation(ob, fcu, transformName, true);
}
fcu = fcu->next;
}
@@ -128,7 +353,7 @@ void AnimationExporter::operator()(Object *ob)
if (!ma) continue;
if (ma->adt && ma->adt->action) {
/* isMatAnim = true; */
- fcu = (FCurve *)ma->adt->action->curves.first;
+ FCurve *fcu = (FCurve *)ma->adt->action->curves.first;
while (fcu) {
transformName = extract_transform_name(fcu->rna_path);
@@ -136,7 +361,7 @@ void AnimationExporter::operator()(Object *ob)
(STREQ(transformName, "diffuse_color")) || (STREQ(transformName, "alpha")) ||
(STREQ(transformName, "ior")))
{
- dae_animation(ob, fcu, transformName, true, ma);
+ create_keyframed_animation(ob, fcu, transformName, true, ma);
}
fcu = fcu->next;
}
@@ -167,7 +392,7 @@ void AnimationExporter::export_morph_animation(Object *ob)
while (fcu) {
transformName = extract_transform_name(fcu->rna_path);
- dae_animation(ob, fcu, transformName, true);
+ create_keyframed_animation(ob, fcu, transformName, true);
fcu = fcu->next;
}
@@ -200,7 +425,7 @@ void AnimationExporter::make_anim_frames_from_targets(Object *ob, std::vector<fl
obtar = ct->tar;
if (obtar)
- find_frames(obtar, frames);
+ find_keyframes(obtar, frames);
}
if (cti->flush_constraint_targets)
@@ -265,8 +490,8 @@ std::string AnimationExporter::getAnimationPathId(const FCurve *fcu)
return translate_id(rna_path);
}
-//convert f-curves to animation curves and write
-void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformName, bool is_param, Material *ma)
+/* convert f-curves to animation curves and write */
+void AnimationExporter::create_keyframed_animation(Object *ob, FCurve *fcu, char *transformName, bool is_param, Material *ma)
{
const char *axis_name = NULL;
char anim_id[200];
@@ -274,6 +499,8 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
bool has_tangents = false;
bool quatRotation = false;
+ Object *obj = NULL;
+
if (STREQ(transformName, "rotation_quaternion") ) {
fprintf(stderr, "quaternion rotation curves are not supported. rotation curve will not be exported\n");
quatRotation = true;
@@ -291,15 +518,26 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
axis_name = axis_names[fcu->array_index];
}
- //axis names for transforms
- else if (STREQ(transformName, "location") ||
- STREQ(transformName, "scale") ||
- STREQ(transformName, "rotation_euler") ||
- STREQ(transformName, "rotation_quaternion"))
+ /*
+ * Note: Handle transformation animations separately (to apply matrix inverse to fcurves)
+ * We will use the object to evaluate the animation on all keyframes and calculate the
+ * resulting object matrix. We need this to incorporate the
+ * effects of the parent inverse matrix (when it contains a rotation component)
+ *
+ * TODO: try to combine exported fcurves into 3 channel animations like done
+ * in export_sampled_animation(). For now each channel is exported as separate <Animation>.
+ */
+
+ else if (
+ STREQ(transformName, "scale") ||
+ STREQ(transformName, "location") ||
+ STREQ(transformName, "rotation_euler"))
{
const char *axis_names[] = {"X", "Y", "Z"};
- if (fcu->array_index < 3)
+ if (fcu->array_index < 3) {
axis_name = axis_names[fcu->array_index];
+ obj = ob;
+ }
}
else {
/* no axis name. single parameter */
@@ -308,16 +546,16 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
std::string ob_name = std::string("null");
- //Create anim Id
+ /* Create anim Id */
if (ob->type == OB_ARMATURE) {
ob_name = getObjectBoneName(ob, fcu);
BLI_snprintf(
- anim_id,
- sizeof(anim_id),
- "%s_%s.%s",
- (char *)translate_id(ob_name).c_str(),
- (char *)translate_id(transformName).c_str(),
- axis_name);
+ anim_id,
+ sizeof(anim_id),
+ "%s_%s.%s",
+ (char *)translate_id(ob_name).c_str(),
+ (char *)translate_id(transformName).c_str(),
+ axis_name);
}
else {
if (ma)
@@ -326,12 +564,12 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
ob_name = id_name(ob);
BLI_snprintf(
- anim_id,
- sizeof(anim_id),
- "%s_%s_%s",
- (char *)translate_id(ob_name).c_str(),
- (char *)getAnimationPathId(fcu).c_str(),
- axis_name);
+ anim_id,
+ sizeof(anim_id),
+ "%s_%s_%s",
+ (char *)translate_id(ob_name).c_str(),
+ (char *)getAnimationPathId(fcu).c_str(),
+ axis_name);
}
openAnimation(anim_id, COLLADABU::Utils::EMPTY_STRING);
@@ -357,7 +595,7 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
output_id = create_lens_source_from_fcurve((Camera *) ob->data, COLLADASW::InputSemantic::OUTPUT, fcu, anim_id);
}
else {
- output_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUTPUT, fcu, anim_id, axis_name);
+ output_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUTPUT, fcu, anim_id, axis_name, obj);
}
// create interpolations source
@@ -369,10 +607,10 @@ void AnimationExporter::dae_animation(Object *ob, FCurve *fcu, char *transformNa
if (has_tangents) {
// create in_tangent source
- intangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::IN_TANGENT, fcu, anim_id, axis_name);
+ intangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::IN_TANGENT, fcu, anim_id, axis_name, obj);
// create out_tangent source
- outtangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUT_TANGENT, fcu, anim_id, axis_name);
+ outtangent_id = create_source_from_fcurve(COLLADASW::InputSemantic::OUT_TANGENT, fcu, anim_id, axis_name, obj);
}
std::string sampler_id = std::string(anim_id) + SAMPLER_ID_SUFFIX;
@@ -475,8 +713,11 @@ void AnimationExporter::sample_and_write_bone_animation_matrix(Object *ob_arm, B
if (!pchan)
return;
- //every inserted keyframe of bones.
- find_frames(ob_arm, fra);
+
+ if (this->export_settings->sampling_rate < 1)
+ find_keyframes(ob_arm, fra);
+ else
+ find_sampleframes(ob_arm, fra);
if (flag & ARM_RESTPOS) {
arm->flag &= ~ARM_RESTPOS;
@@ -530,7 +771,7 @@ void AnimationExporter::dae_baked_animation(std::vector<float> &fra, Object *ob_
addSampler(sampler);
- std::string target = translate_id(bone_name) + "/transform";
+ std::string target = get_joint_id(ob_arm, bone) + "/transform";
addChannel(COLLADABU::URI(empty, sampler_id), target);
closeAnimation();
@@ -755,14 +996,60 @@ void AnimationExporter::get_source_values(BezTriple *bezt, COLLADASW::InputSeman
}
}
+// old function to keep compatibility for calls where offset and object are not needed
std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name)
{
- std::string source_id = anim_id + get_semantic_suffix(semantic);
+ return create_source_from_fcurve(semantic, fcu, anim_id, axis_name, NULL);
+}
- //bool is_angle = STREQ(fcu->rna_path, "rotation");
- bool is_angle = false;
+void AnimationExporter::evaluate_anim_with_constraints(Object *ob, float ctime)
+{
+ BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL);
+ ListBase *conlist = get_active_constraints(ob);
+ bConstraint *con;
+ for (con = (bConstraint *)conlist->first; con; con = con->next) {
+ ListBase targets = { NULL, NULL };
+
+ const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
+
+ if (cti && cti->get_constraint_targets) {
+ bConstraintTarget *ct;
+ Object *obtar;
+ cti->get_constraint_targets(con, &targets);
+ for (ct = (bConstraintTarget *)targets.first; ct; ct = ct->next) {
+ obtar = ct->tar;
+
+ if (obtar) {
+ BKE_animsys_evaluate_animdata(scene, &obtar->id, obtar->adt, ctime, ADT_RECALC_ANIM);
+ BKE_object_where_is_calc_time(scene, obtar, ctime);
+ }
+ }
+
+ if (cti->flush_constraint_targets)
+ cti->flush_constraint_targets(con, &targets, 1);
+ }
+ }
+ BKE_object_where_is_calc_time(scene, ob, ctime);
+}
+
+/*
+ * ob is needed to aply parent inverse information to fcurve.
+ * TODO: Here we have to step over all keyframes for each object and for each fcurve.
+ * Instead of processing each fcurve one by one,
+ * step over the animation from keyframe to keyframe,
+ * then create adjusted fcurves (and entries) for all affected objects.
+ * Then we would need to step through the scene only once.
+ */
+std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name, Object *ob)
+{
+ std::string source_id = anim_id + get_semantic_suffix(semantic);
- if (strstr(fcu->rna_path, "rotation") || strstr(fcu->rna_path,"spot_size")) is_angle = true;
+ bool is_angle = (strstr(fcu->rna_path, "rotation") || strstr(fcu->rna_path, "spot_size"));
+ bool is_euler = strstr(fcu->rna_path, "rotation_euler");
+ bool is_translation = strstr(fcu->rna_path, "location");
+ bool is_scale = strstr(fcu->rna_path, "scale");
+ bool is_tangent = false;
+ int offset_index = 0;
COLLADASW::FloatSourceF source(mSW);
source.setId(source_id);
@@ -773,27 +1060,76 @@ std::string AnimationExporter::create_source_from_fcurve(COLLADASW::InputSemanti
case COLLADASW::InputSemantic::INPUT:
case COLLADASW::InputSemantic::OUTPUT:
source.setAccessorStride(1);
+ offset_index = 0;
break;
case COLLADASW::InputSemantic::IN_TANGENT:
case COLLADASW::InputSemantic::OUT_TANGENT:
source.setAccessorStride(2);
+ offset_index = 1;
+ is_tangent = true;
break;
default:
break;
}
-
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
add_source_parameters(param, semantic, is_angle, axis_name, false);
source.prepareToAppendValues();
- for (unsigned int i = 0; i < fcu->totvert; i++) {
+ for (unsigned int frame_index = 0; frame_index < fcu->totvert; frame_index++) {
+ float fixed_val = 0;
+ if (ob) {
+ float fmat[4][4];
+ float frame = fcu->bezt[frame_index].vec[1][0];
+ float ctime = BKE_scene_frame_get_from_ctime(scene, frame);
+
+ evaluate_anim_with_constraints(ob, ctime); // set object transforms to fcurve's i'th keyframe
+
+ BKE_object_matrix_local_get(ob, fmat);
+ float floc[3];
+ float fquat[4];
+ float fsize[3];
+ mat4_decompose(floc, fquat, fsize, fmat);
+
+ if (is_euler) {
+ float eul[3];
+ quat_to_eul(eul, fquat);
+ fixed_val = RAD2DEGF(eul[fcu->array_index]);
+ }
+ else if (is_translation) {
+ fixed_val = floc[fcu->array_index];
+ }
+ else if (is_scale) {
+ fixed_val = fsize[fcu->array_index];
+ }
+ }
+
float values[3]; // be careful!
+ float offset = 0;
int length = 0;
- get_source_values(&fcu->bezt[i], semantic, is_angle, values, &length);
- for (int j = 0; j < length; j++)
- source.appendValues(values[j]);
+ get_source_values(&fcu->bezt[frame_index], semantic, is_angle, values, &length);
+ if (is_tangent) {
+ float bases[3];
+ int len = 0;
+ get_source_values(&fcu->bezt[frame_index], COLLADASW::InputSemantic::OUTPUT, is_angle, bases, &len);
+ offset = values[offset_index] - bases[0];
+ }
+
+ for (int j = 0; j < length; j++) {
+ float val;
+ if (j == offset_index) {
+ if (ob) {
+ val = fixed_val + offset;
+ }
+ else {
+ val = values[j] + offset;
+ }
+ } else {
+ val = values[j];
+ }
+ source.appendValues(val);
+ }
}
source.finish();
@@ -837,9 +1173,9 @@ std::string AnimationExporter::create_lens_source_from_fcurve(Camera *cam, COLLA
return source_id;
}
-
-
-//Currently called only to get OUTPUT source values ( if rotation and hence the axis is also specified )
+/*
+ * only to get OUTPUT source values ( if rotation and hence the axis is also specified )
+ */
std::string AnimationExporter::create_source_from_array(COLLADASW::InputSemantic::Semantics semantic, float *v, int tot, bool is_rot, const std::string& anim_id, const char *axis_name)
{
std::string source_id = anim_id + get_semantic_suffix(semantic);
@@ -869,7 +1205,10 @@ std::string AnimationExporter::create_source_from_array(COLLADASW::InputSemantic
return source_id;
}
-// only used for sources with INPUT semantic
+
+/*
+ * only used for sources with INPUT semantic
+ */
std::string AnimationExporter::create_source_from_vector(COLLADASW::InputSemantic::Semantics semantic, std::vector<float> &fra, bool is_rot, const std::string& anim_id, const char *axis_name)
{
std::string source_id = anim_id + get_semantic_suffix(semantic);
@@ -900,9 +1239,47 @@ std::string AnimationExporter::create_source_from_vector(COLLADASW::InputSemanti
return source_id;
}
+std::string AnimationExporter::create_4x4_source(std::vector<float> &ctimes, std::vector<float> &values , const std::string &anim_id)
+{
+ COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT;
+ std::string source_id = anim_id + get_semantic_suffix(semantic);
+
+ COLLADASW::Float4x4Source source(mSW);
+ source.setId(source_id);
+ source.setArrayId(source_id + ARRAY_ID_SUFFIX);
+ source.setAccessorCount(ctimes.size());
+ source.setAccessorStride(16);
+
+ COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
+ add_source_parameters(param, semantic, false, NULL, true);
+
+ source.prepareToAppendValues();
+
+ std::vector<float>::iterator it;
+
+ for (it = values.begin(); it != values.end(); it+=16) {
+ float mat[4][4];
+
+ bc_copy_m4_farray(mat, &*it);
+
+ UnitConverter converter;
+ double outmat[4][4];
+ converter.mat4_to_dae_double(outmat, mat);
+
+ if (this->export_settings->limit_precision)
+ bc_sanitize_mat(outmat, 6);
+
+ source.appendValues(outmat);
+ }
+
+ source.finish();
+ return source_id;
+}
std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Object *ob, Bone *bone, const std::string &anim_id)
{
+ bool is_bone_animation = ob->type == OB_ARMATURE && bone;
+
COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT;
std::string source_id = anim_id + get_semantic_suffix(semantic);
@@ -920,7 +1297,7 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
bPoseChannel *parchan = NULL;
bPoseChannel *pchan = NULL;
- if (ob->type == OB_ARMATURE && bone) {
+ if (is_bone_animation) {
bPose *pose = ob->pose;
pchan = BKE_pose_channel_find_name(pose, bone->name);
if (!pchan)
@@ -935,13 +1312,11 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
int j = 0;
for (it = frames.begin(); it != frames.end(); it++) {
float mat[4][4], ipar[4][4];
+ float frame = *it;
- float ctime = BKE_scene_frame_get_from_ctime(scene, *it);
- CFRA = BKE_scene_frame_get_from_ctime(scene, *it);
- //BKE_scene_update_for_newframe(G.main->eval_ctx, G.main,scene,scene->lay);
- BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL);
-
- if (bone) {
+ float ctime = BKE_scene_frame_get_from_ctime(scene, frame);
+ bc_update_scene(scene, ctime);
+ if (is_bone_animation) {
if (pchan->flag & POSE_CHAIN) {
enable_fcurves(ob->adt->action, NULL);
BKE_animsys_evaluate_animdata(scene, &ob->id, ob->adt, ctime, ADT_RECALC_ALL);
@@ -959,9 +1334,10 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
else
copy_m4_m4(mat, pchan->pose_mat);
- // OPEN_SIM_COMPATIBILITY
- // AFAIK animation to second life is via BVH, but no
- // reason to not have the collada-animation be correct
+ /* OPEN_SIM_COMPATIBILITY
+ * AFAIK animation to second life is via BVH, but no
+ * reason to not have the collada-animation be correct
+ */
if (export_settings->open_sim) {
float temp[4][4];
copy_m4_m4(temp, bone->arm_mat);
@@ -980,7 +1356,7 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
}
else {
- calc_ob_mat_at_time(ob, ctime, mat);
+ copy_m4_m4(mat, ob->obmat);
}
UnitConverter converter;
@@ -988,6 +1364,9 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
double outmat[4][4];
converter.mat4_to_dae_double(outmat, mat);
+ if (this->export_settings->limit_precision)
+ bc_sanitize_mat(outmat, 6);
+
source.appendValues(outmat);
j++;
@@ -1005,7 +1384,9 @@ std::string AnimationExporter::create_4x4_source(std::vector<float> &frames, Obj
}
-// only used for sources with OUTPUT semantic ( locations and scale)
+/*
+ * only used for sources with OUTPUT semantic ( locations and scale)
+ */
std::string AnimationExporter::create_xyz_source(float *v, int tot, const std::string& anim_id)
{
COLLADASW::InputSemantic::Semantics semantic = COLLADASW::InputSemantic::OUTPUT;
@@ -1189,8 +1570,10 @@ std::string AnimationExporter::get_camera_param_sid(char *rna_path, int tm_type,
return std::string("");
}
-// Assign sid of the animated parameter or transform
-// for rotation, axis name is always appended and the value of append_axis is ignored
+/*
+ * Assign sid of the animated parameter or transform for rotation,
+ * axis name is always appended and the value of append_axis is ignored
+ */
std::string AnimationExporter::get_transform_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis)
{
std::string tm_name;
@@ -1274,29 +1657,10 @@ char *AnimationExporter::extract_transform_name(char *rna_path)
return dot ? (dot + 1) : rna_path;
}
-//find keyframes of all the objects animations
-void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra)
-{
- if (ob->adt && ob->adt->action) {
- FCurve *fcu = (FCurve *)ob->adt->action->curves.first;
-
- for (; fcu; fcu = fcu->next) {
- for (unsigned int i = 0; i < fcu->totvert; i++) {
- float f = fcu->bezt[i].vec[1][0];
- if (std::find(fra.begin(), fra.end(), f) == fra.end())
- fra.push_back(f);
- }
- }
-
- // keep the keys in ascending order
- std::sort(fra.begin(), fra.end());
- }
-}
-
-
-
-// enable fcurves driving a specific bone, disable all the rest
-// if bone_name = NULL enable all fcurves
+/*
+ * enable fcurves driving a specific bone, disable all the rest
+ * if bone_name = NULL enable all fcurves
+ */
void AnimationExporter::enable_fcurves(bAction *act, char *bone_name)
{
FCurve *fcu;
@@ -1361,14 +1725,53 @@ bool AnimationExporter::hasAnimations(Scene *sce)
void AnimationExporter::find_rotation_frames(Object *ob, std::vector<float> &fra, const char *prefix, int rotmode)
{
if (rotmode > 0)
- find_frames(ob, fra, prefix, "rotation_euler");
+ find_keyframes(ob, fra, prefix, "rotation_euler");
else if (rotmode == ROT_MODE_QUAT)
- find_frames(ob, fra, prefix, "rotation_quaternion");
+ find_keyframes(ob, fra, prefix, "rotation_quaternion");
/*else if (rotmode == ROT_MODE_AXISANGLE)
;*/
}
-void AnimationExporter::find_frames(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name)
+/* Take care to always have the first frame and the last frame in the animation
+ * regardless of the sampling_rate setting
+ */
+void AnimationExporter::find_sampleframes(Object *ob, std::vector<float> &fra)
+{
+ int frame = scene->r.sfra;
+ do {
+ float ctime = BKE_scene_frame_get_from_ctime(scene, frame);
+ fra.push_back(ctime);
+ if (frame == scene->r.efra)
+ break;
+ frame += this->export_settings->sampling_rate;
+ if (frame > scene->r.efra)
+ frame = scene->r.efra; // make sure the last frame is always exported
+
+ } while (true);
+}
+
+/*
+ * find keyframes of all the objects animations
+ */
+void AnimationExporter::find_keyframes(Object *ob, std::vector<float> &fra)
+{
+ if (ob->adt && ob->adt->action) {
+ FCurve *fcu = (FCurve *)ob->adt->action->curves.first;
+
+ for (; fcu; fcu = fcu->next) {
+ for (unsigned int i = 0; i < fcu->totvert; i++) {
+ float f = fcu->bezt[i].vec[1][0];
+ if (std::find(fra.begin(), fra.end(), f) == fra.end())
+ fra.push_back(f);
+ }
+ }
+
+ // keep the keys in ascending order
+ std::sort(fra.begin(), fra.end());
+ }
+}
+
+void AnimationExporter::find_keyframes(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name)
{
if (ob->adt && ob->adt->action) {
FCurve *fcu = (FCurve *)ob->adt->action->curves.first;
@@ -1426,10 +1829,10 @@ void AnimationExporter::sample_and_write_bone_animation(Object *ob_arm, Bone *bo
find_rotation_frames(ob_arm, fra, prefix, pchan->rotmode);
break;
case 1:
- find_frames(ob_arm, fra, prefix, "scale");
+ find_keyframes(ob_arm, fra, prefix, "scale");
break;
case 2:
- find_frames(ob_arm, fra, prefix, "location");
+ find_keyframes(ob_arm, fra, prefix, "location");
break;
default:
return;
@@ -1523,46 +1926,21 @@ void AnimationExporter::sample_animation(float *v, std::vector<float> &frames, i
bool AnimationExporter::validateConstraints(bConstraint *con)
{
- bool valid = true;
const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
/* these we can skip completely (invalid constraints...) */
- if (cti == NULL) valid = false;
- if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF)) valid = false;
- /* these constraints can't be evaluated anyway */
- if (cti->evaluate_constraint == NULL) valid = false;
- /* influence == 0 should be ignored */
- if (con->enforce == 0.0f) valid = false;
+ if (cti == NULL)
+ return false;
+ if (con->flag & (CONSTRAINT_DISABLE | CONSTRAINT_OFF))
+ return false;
- return valid;
-}
-
-void AnimationExporter::calc_ob_mat_at_time(Object *ob, float ctime , float mat[][4])
-{
- ListBase *conlist = get_active_constraints(ob);
- bConstraint *con;
- for (con = (bConstraint *)conlist->first; con; con = con->next) {
- ListBase targets = {NULL, NULL};
-
- const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
-
- if (cti && cti->get_constraint_targets) {
- bConstraintTarget *ct;
- Object *obtar;
- cti->get_constraint_targets(con, &targets);
- for (ct = (bConstraintTarget *)targets.first; ct; ct = ct->next) {
- obtar = ct->tar;
+ /* these constraints can't be evaluated anyway */
+ if (cti->evaluate_constraint == NULL)
+ return false;
- if (obtar) {
- BKE_animsys_evaluate_animdata(scene, &obtar->id, obtar->adt, ctime, ADT_RECALC_ANIM);
- BKE_object_where_is_calc_time(scene, obtar, ctime);
- }
- }
+ /* influence == 0 should be ignored */
+ if (con->enforce == 0.0f)
+ return false;
- if (cti->flush_constraint_targets)
- cti->flush_constraint_targets(con, &targets, 1);
- }
- }
- BKE_object_where_is_calc_time(scene, ob, ctime);
- copy_m4_m4(mat, ob->obmat);
+ /* validation passed */
+ return true;
}
-
diff --git a/source/blender/collada/AnimationExporter.h b/source/blender/collada/AnimationExporter.h
index 4736361ad13..a739b2b6cbe 100644
--- a/source/blender/collada/AnimationExporter.h
+++ b/source/blender/collada/AnimationExporter.h
@@ -90,9 +90,11 @@ private:
public:
AnimationExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings):
- COLLADASW::LibraryAnimations(sw), export_settings(export_settings)
- { this->sw = sw; }
-
+ COLLADASW::LibraryAnimations(sw),
+ export_settings(export_settings)
+ {
+ this->sw = sw;
+ }
bool exportAnimations(Scene *sce);
@@ -102,7 +104,6 @@ public:
protected:
const ExportSettings *export_settings;
- void dae_animation(Object *ob, FCurve *fcu, char *transformName, bool is_param, Material *ma = NULL);
void export_object_constraint_animation(Object *ob);
@@ -143,7 +144,18 @@ protected:
float* get_eul_source_for_quat(Object *ob );
+ bool is_flat_line(std::vector<float> &values, int channel_count);
+ void export_keyframed_animation_set(Object *ob);
+ void create_keyframed_animation(Object *ob, FCurve *fcu, char *transformName, bool is_param, Material *ma = NULL);
+ void export_sampled_animation_set(Object *ob);
+ void export_sampled_transrotloc_animation(Object *ob, std::vector<float> &ctimes);
+ void export_sampled_matrix_animation(Object *ob, std::vector<float> &ctimes);
+ void create_sampled_animation(int channel_count, std::vector<float> &times, std::vector<float> &values, std::string, std::string label, std::string axis_name, bool is_rot);
+
+ void evaluate_anim_with_constraints(Object *ob, float ctime);
+
std::string create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name);
+ std::string create_source_from_fcurve(COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id, const char *axis_name, Object *ob);
std::string create_lens_source_from_fcurve(Camera *cam, COLLADASW::InputSemantic::Semantics semantic, FCurve *fcu, const std::string& anim_id);
@@ -152,7 +164,7 @@ protected:
std::string create_source_from_vector(COLLADASW::InputSemantic::Semantics semantic, std::vector<float> &fra, bool is_rot, const std::string& anim_id, const char *axis_name);
std::string create_xyz_source(float *v, int tot, const std::string& anim_id);
-
+ std::string create_4x4_source(std::vector<float> &times, std::vector<float> &values, const std::string& anim_id);
std::string create_4x4_source(std::vector<float> &frames, Object * ob_arm, Bone *bone, const std::string& anim_id);
std::string create_interpolation_source(FCurve *fcu, const std::string& anim_id, const char *axis_name, bool *has_tangents);
@@ -164,8 +176,10 @@ protected:
std::string get_light_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis);
std::string get_camera_param_sid(char *rna_path, int tm_type, const char *axis_name, bool append_axis);
- void find_frames(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name);
- void find_frames(Object *ob, std::vector<float> &fra);
+ void find_keyframes(Object *ob, std::vector<float> &fra, const char *prefix, const char *tm_name);
+ void find_keyframes(Object *ob, std::vector<float> &fra);
+ void find_sampleframes(Object *ob, std::vector<float> &fra);
+
void make_anim_frames_from_targets(Object *ob, std::vector<float> &frames );
@@ -186,6 +200,5 @@ protected:
bool validateConstraints(bConstraint *con);
- void calc_ob_mat_at_time(Object *ob, float ctime , float mat[][4]);
};
diff --git a/source/blender/collada/AnimationImporter.cpp b/source/blender/collada/AnimationImporter.cpp
index 3801c9300df..75017ce32b4 100644
--- a/source/blender/collada/AnimationImporter.cpp
+++ b/source/blender/collada/AnimationImporter.cpp
@@ -70,17 +70,18 @@ FCurve *AnimationImporter::create_fcurve(int array_index, const char *rna_path)
fcu->array_index = array_index;
return fcu;
}
-
-void AnimationImporter::create_bezt(FCurve *fcu, float frame, float output)
+
+void AnimationImporter::add_bezt(FCurve *fcu, float frame, float value, eBezTriple_Interpolation ipo)
{
+ //float fps = (float)FPS;
BezTriple bez;
memset(&bez, 0, sizeof(BezTriple));
bez.vec[1][0] = frame;
- bez.vec[1][1] = output;
- bez.ipo = U.ipo_new; /* use default interpolation mode here... */
+ bez.vec[1][1] = value;
+ bez.ipo = ipo; /* use default interpolation mode here... */
bez.f1 = bez.f2 = bez.f3 = SELECT;
bez.h1 = bez.h2 = HD_AUTO;
- insert_bezt_fcurve(fcu, &bez, 0);
+ insert_bezt_fcurve(fcu, &bez, INSERTKEY_NOFLAGS);
calchandles_fcurve(fcu);
}
@@ -108,7 +109,7 @@ void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
fcu->flag = (FCURVE_VISIBLE | FCURVE_AUTO_HANDLES | FCURVE_SELECTED);
// fcu->rna_path = BLI_strdupn(path, strlen(path));
fcu->array_index = 0;
- fcu->totvert = curve->getKeyCount();
+ //fcu->totvert = curve->getKeyCount();
// create beztriple for each key
for (unsigned int j = 0; j < curve->getKeyCount(); j++) {
@@ -147,7 +148,7 @@ void AnimationImporter::animation_to_fcurves(COLLADAFW::AnimationCurve *curve)
// bez.ipo = U.ipo_new; /* use default interpolation mode here... */
bez.f1 = bez.f2 = bez.f3 = SELECT;
- insert_bezt_fcurve(fcu, &bez, 0);
+ insert_bezt_fcurve(fcu, &bez, INSERTKEY_NOFLAGS);
}
calchandles_fcurve(fcu);
@@ -401,7 +402,7 @@ virtual void AnimationImporter::change_eul_to_quat(Object *ob, bAction *act)
eul_to_quat(quat, eul);
for (int k = 0; k < 4; k++)
- create_bezt(quatcu[k], frame, quat[k]);
+ create_bezt(quatcu[k], frame, quat[k], U.ipo_new);
}
}
@@ -565,14 +566,16 @@ void AnimationImporter:: Assign_transform_animations(COLLADAFW::Transformation *
}
case COLLADAFW::Transformation::MATRIX:
- /*{
- COLLADAFW::Matrix *mat = (COLLADAFW::Matrix*)transform;
- COLLADABU::Math::Matrix4 mat4 = mat->getMatrix();
- switch (binding->animationClass) {
- case COLLADAFW::AnimationList::TRANSFORM:
-
- }
- }*/
+#if 0
+ {
+ COLLADAFW::Matrix *mat = (COLLADAFW::Matrix*)transform;
+ COLLADABU::Math::Matrix4 mat4 = mat->getMatrix();
+ switch (binding->animationClass) {
+ case COLLADAFW::AnimationList::TRANSFORM:
+
+ }
+ }
+#endif
unused_fcurve(curves);
break;
case COLLADAFW::Transformation::SKEW:
@@ -591,6 +594,12 @@ void AnimationImporter:: Assign_color_animations(const COLLADAFW::UniqueId& list
BLI_strncpy(rna_path, anim_type, sizeof(rna_path));
const COLLADAFW::AnimationList *animlist = animlist_map[listid];
+ if (animlist == NULL)
+ {
+ fprintf(stderr, "Collada: No animlist found for ID: %s of type %s\n", listid.toAscii().c_str(), anim_type);
+ return;
+ }
+
const COLLADAFW::AnimationList::AnimationBindings& bindings = animlist->getAnimationBindings();
//all the curves belonging to the current binding
std::vector<FCurve *> animcurves;
@@ -668,6 +677,13 @@ void AnimationImporter:: Assign_float_animations(const COLLADAFW::UniqueId& list
}
+float AnimationImporter::convert_to_focal_length(float in_xfov, int fov_type, float aspect, float sensorx)
+{
+ // NOTE: Needs more testing (As we curretnly have no official test data for this)
+ float xfov = (fov_type == CAMERA_YFOV) ? (2.0f * atanf(aspect * tanf(DEG2RADF(in_xfov) * 0.5f))) : DEG2RADF(in_xfov);
+ return fov_to_focallength(xfov, sensorx);
+}
+
/*
* Lens animations must be stored in COLLADA by using FOV,
* while blender internally uses focal length.
@@ -697,13 +713,9 @@ void AnimationImporter::Assign_lens_animations(const COLLADAFW::UniqueId& listid
FCurve *fcu = *iter;
for (unsigned int i = 0; i < fcu->totvert; i++) {
-
- double input_fov = fcu->bezt[i].vec[1][1];
-
- // NOTE: Needs more testing (As we curretnly have no official test data for this)
- double xfov = (fov_type == CAMERA_YFOV) ? (2.0f * atanf(aspect * tanf(DEG2RADF(input_fov) * 0.5f))) : DEG2RADF(input_fov);
-
- fcu->bezt[i].vec[1][1] = fov_to_focallength(xfov, cam->sensor_x);
+ fcu->bezt[i].vec[0][1] = convert_to_focal_length(fcu->bezt[i].vec[0][1], fov_type, aspect, cam->sensor_x);
+ fcu->bezt[i].vec[1][1] = convert_to_focal_length(fcu->bezt[i].vec[1][1], fov_type, aspect, cam->sensor_x);
+ fcu->bezt[i].vec[2][1] = convert_to_focal_length(fcu->bezt[i].vec[2][1], fov_type, aspect, cam->sensor_x);
}
BLI_addtail(AnimCurves, fcu);
@@ -764,7 +776,6 @@ void AnimationImporter::apply_matrix_curves(Object *ob, std::vector<FCurve *>& a
axis = i - 7;
}
-
if (is_joint)
BLI_snprintf(rna_path, sizeof(rna_path), "%s.%s", joint_path, tm_str);
else
@@ -780,6 +791,9 @@ void AnimationImporter::apply_matrix_curves(Object *ob, std::vector<FCurve *>& a
std::vector<float>::iterator it;
+ //float qref[4];
+ //unit_qt(qref);
+
// sample values at each frame
for (it = frames.begin(); it != frames.end(); it++) {
float fra = *it;
@@ -814,14 +828,7 @@ void AnimationImporter::apply_matrix_curves(Object *ob, std::vector<FCurve *>& a
}
float rot[4], loc[3], scale[3];
-
- mat4_to_quat(rot, mat);
- /*for ( int i = 0 ; i < 4 ; i ++ )
- {
- rot[i] = RAD2DEGF(rot[i]);
- }*/
- copy_v3_v3(loc, mat[3]);
- mat4_to_size(scale, mat);
+ mat4_decompose(loc, rot, scale, mat);
// add keys
for (int i = 0; i < totcu; i++) {
@@ -890,11 +897,22 @@ static const double get_aspect_ratio(const COLLADAFW::Camera *camera)
return aspect;
}
+static ListBase &get_animation_curves(Material *ma)
+{
+ bAction *act;
+ if (!ma->adt || !ma->adt->action)
+ act = verify_adt_action((ID *)&ma->id, 1);
+ else
+ act = ma->adt->action;
+
+ return act->curves;
+}
void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
std::map<COLLADAFW::UniqueId, COLLADAFW::Node *>& root_map,
std::multimap<COLLADAFW::UniqueId, Object *>& object_map,
- std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map)
+ std::map<COLLADAFW::UniqueId, const COLLADAFW::Object *> FW_object_map,
+ std::map<COLLADAFW::UniqueId, Material*> uid_material_map)
{
bool is_joint = node->getType() == COLLADAFW::Node::JOINT;
COLLADAFW::UniqueId uid = node->getUniqueId();
@@ -1072,11 +1090,6 @@ void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
}
}
if (animType->material != 0) {
- Material *ma = give_current_material(ob, 1);
- if (!ma->adt || !ma->adt->action) act = verify_adt_action((ID *)&ma->id, 1);
- else act = ma->adt->action;
-
- ListBase *AnimCurves = &(act->curves);
const COLLADAFW::InstanceGeometryPointerArray& nodeGeoms = node->getInstanceGeometries();
for (unsigned int i = 0; i < nodeGeoms.getCount(); i++) {
@@ -1085,30 +1098,36 @@ void AnimationImporter::translate_Animations(COLLADAFW::Node *node,
const COLLADAFW::UniqueId & matuid = matBinds[j].getReferencedMaterial();
const COLLADAFW::Effect *ef = (COLLADAFW::Effect *) (FW_object_map[matuid]);
if (ef != NULL) { /* can be NULL [#28909] */
- const COLLADAFW::CommonEffectPointerArray& commonEffects = ef->getCommonEffects();
+ Material *ma = uid_material_map[matuid];
+ if (!ma) {
+ fprintf(stderr, "Collada: Node %s refers to undefined material\n", node->getName().c_str());
+ continue;
+ }
+ ListBase &AnimCurves = get_animation_curves(ma);
+ const COLLADAFW::CommonEffectPointerArray& commonEffects = ef->getCommonEffects();
COLLADAFW::EffectCommon *efc = commonEffects[0];
if ((animType->material & MATERIAL_SHININESS) != 0) {
const COLLADAFW::FloatOrParam *shin = &(efc->getShininess());
- const COLLADAFW::UniqueId& listid = shin->getAnimationList();
- Assign_float_animations(listid, AnimCurves, "specular_hardness");
+ const COLLADAFW::UniqueId& listid = shin->getAnimationList();
+ Assign_float_animations(listid, &AnimCurves, "specular_hardness");
}
if ((animType->material & MATERIAL_IOR) != 0) {
const COLLADAFW::FloatOrParam *ior = &(efc->getIndexOfRefraction());
- const COLLADAFW::UniqueId& listid = ior->getAnimationList();
- Assign_float_animations(listid, AnimCurves, "raytrace_transparency.ior");
+ const COLLADAFW::UniqueId& listid = ior->getAnimationList();
+ Assign_float_animations(listid, &AnimCurves, "raytrace_transparency.ior");
}
if ((animType->material & MATERIAL_SPEC_COLOR) != 0) {
const COLLADAFW::ColorOrTexture *cot = &(efc->getSpecular());
- const COLLADAFW::UniqueId& listid = cot->getColor().getAnimationList();
- Assign_color_animations(listid, AnimCurves, "specular_color");
+ const COLLADAFW::UniqueId& listid = cot->getColor().getAnimationList();
+ Assign_color_animations(listid, &AnimCurves, "specular_color");
}
if ((animType->material & MATERIAL_DIFF_COLOR) != 0) {
const COLLADAFW::ColorOrTexture *cot = &(efc->getDiffuse());
- const COLLADAFW::UniqueId& listid = cot->getColor().getAnimationList();
- Assign_color_animations(listid, AnimCurves, "diffuse_color");
+ const COLLADAFW::UniqueId& listid = cot->getColor().getAnimationList();
+ Assign_color_animations(listid, &AnimCurves, "diffuse_color");
}
}
}
@@ -1189,6 +1208,9 @@ void AnimationImporter::add_bone_animation_sampled(Object *ob, std::vector<FCurv
std::sort(frames.begin(), frames.end());
+ float qref[4];
+ unit_qt(qref);
+
std::vector<float>::iterator it;
// sample values at each frame
@@ -1222,7 +1244,9 @@ void AnimationImporter::add_bone_animation_sampled(Object *ob, std::vector<FCurv
float rot[4], loc[3], scale[3];
- mat4_to_quat(rot, mat);
+ bc_rotate_from_reference_quat(rot, qref, mat);
+ copy_qt_qt(qref, rot);
+
copy_v3_v3(loc, mat[3]);
mat4_to_size(scale, mat);
@@ -1560,7 +1584,8 @@ Object *AnimationImporter::translate_animation_OLD(COLLADAFW::Node *node,
copy_m4_m4(mat, matfra);
}
- float val[4], rot[4], loc[3], scale[3];
+ float val[4] = {};
+ float rot[4], loc[3], scale[3];
switch (tm_type) {
case COLLADAFW::Transformation::ROTATE:
@@ -1728,7 +1753,8 @@ bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float
if (type != COLLADAFW::Transformation::ROTATE &&
type != COLLADAFW::Transformation::SCALE &&
type != COLLADAFW::Transformation::TRANSLATE &&
- type != COLLADAFW::Transformation::MATRIX) {
+ type != COLLADAFW::Transformation::MATRIX)
+ {
fprintf(stderr, "animation of transformation %d is not supported yet\n", type);
return false;
}
@@ -1832,23 +1858,18 @@ bool AnimationImporter::evaluate_animation(COLLADAFW::Transformation *tm, float
}
COLLADABU::Math::Matrix4 matrix;
- int i = 0, j = 0;
+ int mi = 0, mj = 0;
for (std::vector<FCurve *>::iterator it = curves.begin(); it != curves.end(); it++) {
- matrix.setElement(i, j, evaluate_fcurve(*it, fra));
- j++;
- if (j == 4) {
- i++;
- j = 0;
+ matrix.setElement(mi, mj, evaluate_fcurve(*it, fra));
+ mj++;
+ if (mj == 4) {
+ mi++;
+ mj = 0;
}
fcurve_is_used(*it);
}
-
- COLLADAFW::Matrix tm(matrix);
- dae_matrix_to_mat4(&tm, mat);
-
- std::vector<FCurve *>::iterator it;
-
+ unit_converter->dae_matrix_to_mat4_(mat, matrix);
return true;
}
}
@@ -1934,7 +1955,7 @@ Object *AnimationImporter::get_joint_object(COLLADAFW::Node *root, COLLADAFW::No
mul_m4_m4m4(mat, ipar, temp);
}
- TransformBase::decompose(mat, job->loc, NULL, job->quat, job->size);
+ bc_decompose(mat, job->loc, NULL, job->quat, job->size);
if (par_job) {
job->parent = par_job;
@@ -2011,19 +2032,6 @@ void AnimationImporter::add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurv
action_groups_add_channel(act, grp, fcu);
}
-void AnimationImporter::add_bezt(FCurve *fcu, float fra, float value)
-{
- //float fps = (float)FPS;
- BezTriple bez;
- memset(&bez, 0, sizeof(BezTriple));
- bez.vec[1][0] = fra;
- bez.vec[1][1] = value;
- bez.ipo = BEZT_IPO_LIN; /* use default interpolation mode here... */
- bez.f1 = bez.f2 = bez.f3 = SELECT;
- bez.h1 = bez.h2 = HD_AUTO;
- insert_bezt_fcurve(fcu, &bez, 0);
- calchandles_fcurve(fcu);
-}
void AnimationImporter::set_import_from_version(std::string import_from_version)
{
diff --git a/source/blender/collada/AnimationImporter.h b/source/blender/collada/AnimationImporter.h
index 15dee8ff5f4..e25116cac9f 100644
--- a/source/blender/collada/AnimationImporter.h
+++ b/source/blender/collada/AnimationImporter.h
@@ -78,7 +78,7 @@ private:
FCurve *create_fcurve(int array_index, const char *rna_path);
- void create_bezt(FCurve *fcu, float frame, float output);
+ void add_bezt(FCurve *fcu, float frame, float value, eBezTriple_Interpolation ipo=BEZT_IPO_LIN);
// create one or several fcurves depending on the number of parameters being animated
void animation_to_fcurves(COLLADAFW::AnimationCurve *curve);
@@ -156,7 +156,8 @@ public:
void translate_Animations(COLLADAFW::Node * Node,
std::map<COLLADAFW::UniqueId, COLLADAFW::Node*>& root_map,
std::multimap<COLLADAFW::UniqueId, Object*>& object_map,
- std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map);
+ std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map,
+ std::map<COLLADAFW::UniqueId, Material*> uid_material_map);
AnimMix* get_animation_type( const COLLADAFW::Node * node, std::map<COLLADAFW::UniqueId, const COLLADAFW::Object*> FW_object_map );
@@ -202,6 +203,8 @@ public:
// gives a world-space mat, end's mat not included
bool calc_joint_parent_mat_rest(float mat[4][4], float par[4][4], COLLADAFW::Node *node, COLLADAFW::Node *end);
+ float convert_to_focal_length(float in_xfov, int fov_type, float aspect, float sensorx);
+
#ifdef ARMATURE_TEST
Object *get_joint_object(COLLADAFW::Node *root, COLLADAFW::Node *node, Object *par_job);
#endif
@@ -214,8 +217,6 @@ public:
void add_bone_fcurve(Object *ob, COLLADAFW::Node *node, FCurve *fcu);
- void add_bezt(FCurve *fcu, float fra, float value);
-
void extra_data_importer(std::string elementName);
};
diff --git a/source/blender/collada/ArmatureExporter.cpp b/source/blender/collada/ArmatureExporter.cpp
index 9c26ba83b44..92ec8b470a8 100644
--- a/source/blender/collada/ArmatureExporter.cpp
+++ b/source/blender/collada/ArmatureExporter.cpp
@@ -89,7 +89,7 @@ void ArmatureExporter::add_armature_bones(Object *ob_arm, Scene *sce,
void ArmatureExporter::write_bone_URLs(COLLADASW::InstanceController &ins, Object *ob_arm, Bone *bone)
{
if (bc_is_root_bone(bone, this->export_settings->deform_bones_only))
- ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
+ ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(ob_arm, bone)));
else {
for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
write_bone_URLs(ins, ob_arm, child);
@@ -116,7 +116,10 @@ bool ArmatureExporter::add_instance_controller(Object *ob)
write_bone_URLs(ins, ob_arm, bone);
}
- InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob, this->export_settings->active_uv_only);
+ InstanceWriter::add_material_bindings(ins.getBindMaterial(),
+ ob,
+ this->export_settings->active_uv_only,
+ this->export_settings->export_texture_type);
ins.add();
return true;
@@ -156,20 +159,15 @@ void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<O
}
#endif
-std::string ArmatureExporter::get_joint_sid(Bone *bone, Object *ob_arm)
-{
- return get_joint_id(bone, ob_arm);
-}
-
// parent_mat is armature-space
void ArmatureExporter::add_bone_node(Bone *bone, Object *ob_arm, Scene *sce,
SceneExporter *se,
std::list<Object *>& child_objects)
{
if (!(this->export_settings->deform_bones_only && bone->flag & BONE_NO_DEFORM)) {
- std::string node_id = get_joint_id(bone, ob_arm);
+ std::string node_id = get_joint_id(ob_arm, bone);
std::string node_name = std::string(bone->name);
- std::string node_sid = get_joint_sid(bone, ob_arm);
+ std::string node_sid = get_joint_sid(bone);
COLLADASW::Node node(mSW);
@@ -261,47 +259,59 @@ void ArmatureExporter::add_bone_transform(Object *ob_arm, Bone *bone, COLLADASW:
//bPoseChannel *pchan = BKE_pose_channel_find_name(ob_arm->pose, bone->name);
float mat[4][4];
+ float bone_rest_mat[4][4]; /* derived from bone->arm_mat */
+ float parent_rest_mat[4][4]; /* derived from bone->parent->arm_mat */
- if (bone->parent) {
- // get bone-space matrix from parent pose
- /*bPoseChannel *parchan = BKE_pose_channel_find_name(ob_arm->pose, bone->parent->name);
- float invpar[4][4];
- invert_m4_m4(invpar, parchan->pose_mat);
- mul_m4_m4m4(mat, invpar, pchan->pose_mat);*/
-
- float invpar[4][4];
- invert_m4_m4(invpar, bone->parent->arm_mat);
- mul_m4_m4m4(mat, invpar, bone->arm_mat);
+ bool has_restmat = bc_get_property_matrix(bone, "rest_mat", mat);
- }
- else {
+ if (!has_restmat) {
+
+ /* Have no restpose matrix stored, try old style <= Blender 2.78 */
- //copy_m4_m4(mat, pchan->pose_mat);
- //pose mat is object space
- //New change: export bone->arm_mat
- copy_m4_m4(mat, bone->arm_mat);
- }
+ bc_create_restpose_mat(this->export_settings, bone, bone_rest_mat, bone->arm_mat, true);
- // OPEN_SIM_COMPATIBILITY
- if (export_settings->open_sim) {
- // Remove rotations vs armature from transform
- // parent_rest_rot * mat * irest_rot
- float temp[4][4];
- copy_m4_m4(temp, bone->arm_mat);
- temp[3][0] = temp[3][1] = temp[3][2] = 0.0f;
- invert_m4(temp);
+ if (bone->parent) {
+ // get bone-space matrix from parent pose
+ /*bPoseChannel *parchan = BKE_pose_channel_find_name(ob_arm->pose, bone->parent->name);
+ float invpar[4][4];
+ invert_m4_m4(invpar, parchan->pose_mat);
+ mul_m4_m4m4(mat, invpar, pchan->pose_mat);*/
+ float invpar[4][4];
+ bc_create_restpose_mat(this->export_settings, bone->parent, parent_rest_mat, bone->parent->arm_mat, true);
- mul_m4_m4m4(mat, mat, temp);
+ invert_m4_m4(invpar, parent_rest_mat);
+ mul_m4_m4m4(mat, invpar, bone_rest_mat);
- if (bone->parent) {
- copy_m4_m4(temp, bone->parent->arm_mat);
+ }
+ else {
+ copy_m4_m4(mat, bone_rest_mat);
+ }
+
+ // OPEN_SIM_COMPATIBILITY
+ if (export_settings->open_sim) {
+ // Remove rotations vs armature from transform
+ // parent_rest_rot * mat * irest_rot
+ float temp[4][4];
+ copy_m4_m4(temp, bone_rest_mat);
temp[3][0] = temp[3][1] = temp[3][2] = 0.0f;
+ invert_m4(temp);
+
+ mul_m4_m4m4(mat, mat, temp);
- mul_m4_m4m4(mat, temp, mat);
+ if (bone->parent) {
+ copy_m4_m4(temp, parent_rest_mat);
+ temp[3][0] = temp[3][1] = temp[3][2] = 0.0f;
+
+ mul_m4_m4m4(mat, temp, mat);
+ }
}
}
+ if (this->export_settings->limit_precision)
+ bc_sanitize_mat(mat, 6);
+
TransformWriter::add_node_transform(node, mat, NULL);
+
}
std::string ArmatureExporter::get_controller_id(Object *ob_arm, Object *ob)
diff --git a/source/blender/collada/ArmatureExporter.h b/source/blender/collada/ArmatureExporter.h
index 883a6aca847..d271b505aa9 100644
--- a/source/blender/collada/ArmatureExporter.h
+++ b/source/blender/collada/ArmatureExporter.h
@@ -83,8 +83,6 @@ private:
void find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce);
#endif
- std::string get_joint_sid(Bone *bone, Object *ob_arm);
-
// Scene, SceneExporter and the list of child_objects
// are required for writing bone parented objects
void add_bone_node(Bone *bone, Object *ob_arm, Scene *sce, SceneExporter *se,
diff --git a/source/blender/collada/ArmatureImporter.cpp b/source/blender/collada/ArmatureImporter.cpp
index 17334ca326c..c32a2a7034e 100644
--- a/source/blender/collada/ArmatureImporter.cpp
+++ b/source/blender/collada/ArmatureImporter.cpp
@@ -32,6 +32,7 @@
#include "COLLADAFWUniqueId.h"
+extern "C" {
#include "BKE_action.h"
#include "BKE_depsgraph.h"
#include "BKE_object.h"
@@ -39,7 +40,9 @@
#include "BLI_string.h"
#include "BLI_listbase.h"
#include "ED_armature.h"
+}
+#include "collada_utils.h"
#include "ArmatureImporter.h"
// use node name, or fall back to original id if not present (name is optional)
@@ -91,6 +94,7 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
{
float mat[4][4];
float joint_inv_bind_mat[4][4];
+ float joint_bind_mat[4][4];
int chain_length = 0;
//Checking if bone is already made.
@@ -98,7 +102,7 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
it = std::find(finished_joints.begin(), finished_joints.end(), node);
if (it != finished_joints.end()) return chain_length;
- EditBone *bone = ED_armature_edit_bone_add(arm, (char *)bc_get_joint_name(node));
+ EditBone *bone = ED_armature_ebone_add(arm, bc_get_joint_name(node));
totbone++;
/*
@@ -106,7 +110,7 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
*/
std::map<COLLADAFW::UniqueId, SkinInfo>::iterator skin_it;
- bool bone_is_not_skinned = true;
+ bool bone_is_skinned = false;
for (skin_it = skin_by_data_uid.begin(); skin_it != skin_by_data_uid.end(); skin_it++) {
SkinInfo *b = &skin_it->second;
@@ -114,7 +118,7 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
// get original world-space matrix
invert_m4_m4(mat, joint_inv_bind_mat);
-
+ copy_m4_m4(joint_bind_mat, mat);
// And make local to armature
Object *ob_arm = skin->BKE_armature_from_object();
if (ob_arm) {
@@ -123,24 +127,14 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
mul_m4_m4m4(mat, invmat, mat);
}
- bone_is_not_skinned = false;
+ bone_is_skinned = true;
break;
}
}
// create a bone even if there's no joint data for it (i.e. it has no influence)
- if (bone_is_not_skinned) {
- float obmat[4][4];
- // bone-space
- get_node_mat(obmat, node, NULL, NULL);
-
- // get world-space
- if (parent) {
- mul_m4_m4m4(mat, parent_mat, obmat);
- }
- else {
- copy_m4_m4(mat, obmat);
- }
+ if (!bone_is_skinned) {
+ get_node_mat(mat, node, NULL, NULL, parent_mat);
}
if (parent) bone->parent = parent;
@@ -156,10 +150,11 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
int use_connect = be.get_use_connect();
switch (use_connect) {
- case 1: bone->flag |= BONE_CONNECTED;
- break;
- case 0: bone->flag &= ~BONE_CONNECTED;
- case -1: break; // not defined
+ case 1: bone->flag |= BONE_CONNECTED;
+ break;
+ case -1:/* Connect type not specified */
+ case 0: bone->flag &= ~BONE_CONNECTED;
+ break;
}
if (be.has_roll()) {
@@ -172,6 +167,15 @@ int ArmatureImporter::create_bone(SkinInfo *skin, COLLADAFW::Node *node, EditBon
bone->roll = angle;
}
copy_v3_v3(bone->head, mat[3]);
+
+ if (bone_is_skinned)
+ {
+ float rest_mat[4][4];
+ get_node_mat(rest_mat, node, NULL, NULL, NULL);
+ bc_set_IDPropertyMatrix(bone, "bind_mat", joint_bind_mat);
+ bc_set_IDPropertyMatrix(bone, "rest_mat", rest_mat);
+ }
+
add_v3_v3v3(bone->tail, bone->head, tail); //tail must be non zero
/* find smallest bone length in armature (used later for leaf bone length) */
@@ -273,28 +277,27 @@ void ArmatureImporter::fix_parent_connect(bArmature *armature, Bone *bone)
}
-
void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone, int clip)
{
BoneExtensionMap &extended_bones = bone_extension_manager.getExtensionMap(armature);
BoneExtended *dominant_child = NULL;
int maxlen = 0;
- Bone *child;
if (parentbone == NULL)
return;
- child = (Bone *)parentbone->childbase.first;
+ Bone *child = (Bone *)parentbone->childbase.first;
if (child && (import_settings->find_chains || child->next==NULL)) {
for (; child; child = child->next) {
BoneExtended *be = extended_bones[child->name];
if (be != NULL) {
- if (be->get_chain_length() <= clip) {
- if (be->get_chain_length() > maxlen) {
+ int chain_len = be->get_chain_length();
+ if (chain_len <= clip) {
+ if (chain_len > maxlen) {
dominant_child = be;
- maxlen = be->get_chain_length();
+ maxlen = chain_len;
}
- else if (be->get_chain_length() == maxlen) {
+ else if (chain_len == maxlen) {
dominant_child = NULL;
}
}
@@ -308,7 +311,6 @@ void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone
EditBone *pebone = bc_get_edit_bone(armature, parentbone->name);
EditBone *cebone = bc_get_edit_bone(armature, dominant_child->get_name());
if (pebone && !(cebone->flag & BONE_CONNECTED)) {
-
float vec[3];
sub_v3_v3v3(vec, cebone->head, pebone->head);
@@ -321,19 +323,21 @@ void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone
if (len_squared_v3(vec) > MINIMUM_BONE_LENGTH)
{
- pebone->tail[0] = cebone->head[0];
- pebone->tail[1] = cebone->head[1];
- pebone->tail[2] = cebone->head[2];
-
+ copy_v3_v3(pebone->tail, cebone->head);
+ pbe->set_tail(pebone->tail); /* to make fix_leafbone happy ...*/
if (pbe && pbe->get_chain_length() >= this->import_settings->min_chain_length) {
+
+ BoneExtended *cbe = extended_bones[cebone->name];
+ cbe->set_use_connect(true);
+
cebone->flag |= BONE_CONNECTED;
- printf("Connecting chain: parent %s --> %s (child)\n", pebone->name, cebone->name);
pbe->set_leaf_bone(false);
+ printf("Connect Bone chain: parent (%s --> %s) child)\n", pebone->name, cebone->name);
}
}
}
- for (Bone *child = (Bone *)parentbone->childbase.first; child; child = child->next) {
- ArmatureImporter::connect_bone_chains(armature, child, UNLIMITED_CHAIN_MAX);
+ for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
+ ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
}
}
else if (maxlen>1 && maxlen > this->import_settings->min_chain_length) {
@@ -343,8 +347,8 @@ void ArmatureImporter::connect_bone_chains(bArmature *armature, Bone *parentbone
else {
/* can't connect this Bone. Proceed with children ... */
if (pbe) pbe->set_leaf_bone(true);
- for (Bone *child = (Bone *)parentbone->childbase.first; child; child = child->next) {
- ArmatureImporter::connect_bone_chains(armature, child, UNLIMITED_CHAIN_MAX);
+ for (Bone *ch = (Bone *)parentbone->childbase.first; ch; ch = ch->next) {
+ ArmatureImporter::connect_bone_chains(armature, ch, UNLIMITED_CHAIN_MAX);
}
}
@@ -630,8 +634,8 @@ Object *ArmatureImporter::create_armature_bones(SkinInfo& skin)
}
void ArmatureImporter::set_pose(Object *ob_arm, COLLADAFW::Node *root_node, const char *parentname, float parent_mat[4][4])
-{
- char *bone_name = (char *) bc_get_joint_name(root_node);
+{
+ const char *bone_name = bc_get_joint_name(root_node);
float mat[4][4];
float obmat[4][4];
diff --git a/source/blender/collada/ControllerExporter.cpp b/source/blender/collada/ControllerExporter.cpp
index 06e151c363b..14e8e0323a8 100644
--- a/source/blender/collada/ControllerExporter.cpp
+++ b/source/blender/collada/ControllerExporter.cpp
@@ -71,7 +71,7 @@ bool ControllerExporter::is_skinned_mesh(Object *ob)
void ControllerExporter::write_bone_URLs(COLLADASW::InstanceController &ins, Object *ob_arm, Bone *bone)
{
if (bc_is_root_bone(bone, this->export_settings->deform_bones_only))
- ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(bone, ob_arm)));
+ ins.addSkeleton(COLLADABU::URI(COLLADABU::Utils::EMPTY_STRING, get_joint_id(ob_arm, bone)));
else {
for (Bone *child = (Bone *)bone->childbase.first; child; child = child->next) {
write_bone_URLs(ins, ob_arm, child);
@@ -98,7 +98,10 @@ bool ControllerExporter::add_instance_controller(Object *ob)
write_bone_URLs(ins, ob_arm, bone);
}
- InstanceWriter::add_material_bindings(ins.getBindMaterial(), ob, this->export_settings->active_uv_only);
+ InstanceWriter::add_material_bindings(ins.getBindMaterial(),
+ ob,
+ this->export_settings->active_uv_only,
+ this->export_settings->export_texture_type);
ins.add();
return true;
@@ -157,11 +160,6 @@ void ArmatureExporter::find_objects_using_armature(Object *ob_arm, std::vector<O
}
#endif
-std::string ControllerExporter::get_joint_sid(Bone *bone, Object *ob_arm)
-{
- return get_joint_id(bone, ob_arm);
-}
-
std::string ControllerExporter::get_controller_id(Object *ob_arm, Object *ob)
{
return translate_id(id_name(ob_arm)) + "_" + translate_id(id_name(ob)) + SKIN_CONTROLLER_ID_SUFFIX;
@@ -284,7 +282,7 @@ void ControllerExporter::export_skin_controller(Object *ob, Object *ob_arm)
}
if (oob_counter > 0) {
- fprintf(stderr, "Ignored %d Vertex weights which use index to non existing VGroup %lu.\n",
+ fprintf(stderr, "Ignored %d Vertex weights which use index to non existing VGroup %zu.\n",
oob_counter, joint_index_by_def_index.size());
}
}
@@ -460,7 +458,7 @@ std::string ControllerExporter::add_joints_source(Object *ob_arm, ListBase *defb
for (def = (bDeformGroup *)defbase->first; def; def = def->next) {
Bone *bone = get_bone_from_defgroup(ob_arm, def);
if (bone)
- source.appendValues(get_joint_sid(bone, ob_arm));
+ source.appendValues(get_joint_sid(bone));
}
source.finish();
@@ -468,81 +466,6 @@ std::string ControllerExporter::add_joints_source(Object *ob_arm, ListBase *defb
return source_id;
}
-static float get_property(Bone *bone, const char *key, float def)
-{
- float result = def;
- if (bone->prop) {
- IDProperty *property = IDP_GetPropertyFromGroup(bone->prop, key);
- if (property) {
- switch (property->type) {
- case IDP_INT:
- result = (float)(IDP_Int(property));
- break;
- case IDP_FLOAT:
- result = (float)(IDP_Float(property));
- break;
- case IDP_DOUBLE:
- result = (float)(IDP_Double(property));
- break;
- default:
- result = def;
- }
- }
- }
- return result;
-}
-
-/**
- * This function creates an arbitrary rest pose matrix from
- * data provided as custom properties. This is a workaround
- * for support of maya's restpose matrix which can be arbitrary
- * in opposition to Blender where the Rest pose Matrix is always
- * the Identity matrix.
- *
- * The custom properties are:
- *
- * restpose_scale_x
- * restpose_scale_y
- * restpose_scale_z
- *
- * restpose_rot_x
- * restpose_rot_y
- * restpose_rot_z
- *
- * restpose_loc_x
- * restpose_loc_y
- * restpose_loc_z
- *
- * The matrix is only setup if the scale AND the rot properties are defined.
- * The presence of the loc properties is optional.
- *
- * This feature has been implemented to support Second Life "Fitted Mesh"
- * TODO: Check if an arbitrary rest pose matrix makes sense within Blender.
- * Eventually leverage the custom property data into an "official"
- * Edit_bone Property
- */
-static void create_restpose_mat(Bone *bone, float mat[4][4])
-{
- float loc[3] = {
- get_property(bone, "restpose_loc_x", 0.0),
- get_property(bone, "restpose_loc_y", 0.0),
- get_property(bone, "restpose_loc_z", 0.0)
- };
-
- float rot[3] = {
- DEG2RADF(get_property(bone, "restpose_rot_x", 0.0)),
- DEG2RADF(get_property(bone, "restpose_rot_y", 0.0)),
- DEG2RADF(get_property(bone, "restpose_rot_z", 0.0))
- };
-
- float scale[3] = {
- get_property(bone, "restpose_scale_x", 1.0),
- get_property(bone, "restpose_scale_y", 1.0),
- get_property(bone, "restpose_scale_z", 1.0)
- };
-
- loc_eulO_size_to_mat4(mat, loc, rot, scale, 6);
-}
std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm, ListBase *defbase, const std::string& controller_id)
{
@@ -585,30 +508,36 @@ std::string ControllerExporter::add_inv_bind_mats_source(Object *ob_arm, ListBas
float world[4][4];
float inv_bind_mat[4][4];
+ float bind_mat[4][4]; /* derived from bone->arm_mat */
+
+ bool has_bindmat = bc_get_property_matrix(pchan->bone, "bind_mat", bind_mat);
- // SL/OPEN_SIM COMPATIBILITY
- if (export_settings->open_sim) {
- // Only translations, no rotation vs armature
- float temp[4][4];
- unit_m4(temp);
- copy_v3_v3(temp[3], pchan->bone->arm_mat[3]);
- mul_m4_m4m4(world, ob_arm->obmat, temp);
-
- // Add Maya restpose matrix (if defined as properties)
- float restpose_mat[4][4];
- create_restpose_mat(pchan->bone, restpose_mat);
- mul_m4_m4m4(world, world, restpose_mat);
+ if (!has_bindmat) {
- }
- else {
- // make world-space matrix, arm_mat is armature-space
- mul_m4_m4m4(world, ob_arm->obmat, pchan->bone->arm_mat);
+ /* Have no bind matrix stored, try old style <= Blender 2.78 */
+
+ bc_create_restpose_mat(this->export_settings, pchan->bone, bind_mat, pchan->bone->arm_mat, true);
+
+ // SL/OPEN_SIM COMPATIBILITY
+ if (export_settings->open_sim) {
+
+ float loc[3];
+ float rot[3] = { 0, 0, 0 };
+ float scale[3];
+ bc_decompose(bind_mat, loc, NULL, NULL, scale);
+
+ // Only translations, no rotation vs armature
+ loc_eulO_size_to_mat4(bind_mat, loc, rot, scale, 6);
+ }
}
+ // make world-space matrix (bind_mat is armature-space)
+ mul_m4_m4m4(world, ob_arm->obmat, bind_mat);
invert_m4_m4(mat, world);
converter.mat4_to_dae(inv_bind_mat, mat);
-
+ if (this->export_settings->limit_precision)
+ bc_sanitize_mat(inv_bind_mat, 6);
source.appendValues(inv_bind_mat);
}
}
diff --git a/source/blender/collada/ControllerExporter.h b/source/blender/collada/ControllerExporter.h
index 0be51187f6f..80b858ca6dd 100644
--- a/source/blender/collada/ControllerExporter.h
+++ b/source/blender/collada/ControllerExporter.h
@@ -84,8 +84,6 @@ private:
void find_objects_using_armature(Object *ob_arm, std::vector<Object *>& objects, Scene *sce);
#endif
- std::string get_joint_sid(Bone *bone, Object *ob_arm);
-
std::string get_controller_id(Object *ob_arm, Object *ob);
std::string get_controller_id(Key *key, Object *ob);
diff --git a/source/blender/collada/DocumentExporter.cpp b/source/blender/collada/DocumentExporter.cpp
index bd32e989ae3..d4eb6b477db 100644
--- a/source/blender/collada/DocumentExporter.cpp
+++ b/source/blender/collada/DocumentExporter.cpp
@@ -138,7 +138,8 @@ extern bool bc_has_object_type(LinkNode *export_set, short obtype);
char *bc_CustomData_get_layer_name(const struct CustomData *data, int type, int n)
{
int layer_index = CustomData_get_layer_index(data, type);
- if (layer_index < 0) return NULL;
+ if (layer_index < 0)
+ return NULL;
return data->layers[layer_index + n].name;
}
@@ -147,9 +148,10 @@ char *bc_CustomData_get_active_layer_name(const CustomData *data, int type)
{
/* get the layer index of the active layer of type */
int layer_index = CustomData_get_active_layer_index(data, type);
- if (layer_index < 0) return NULL;
+ if (layer_index < 1)
+ return NULL;
- return data->layers[layer_index].name;
+ return bc_CustomData_get_layer_name(data, type, layer_index-1);
}
DocumentExporter::DocumentExporter(const ExportSettings *export_settings) : export_settings(export_settings) {
@@ -179,7 +181,7 @@ static COLLADABU::NativeString make_temp_filepath(const char *name, const char *
// COLLADA allows this through multiple <channel>s in <animation>.
// For this to work, we need to know objects that use a certain action.
-int DocumentExporter::exportCurrentScene(Scene *sce)
+int DocumentExporter::exportCurrentScene(const EvaluationContext *eval_ctx, Scene *sce)
{
PointerRNA sceneptr, unit_settings;
PropertyRNA *system; /* unused , *scale; */
@@ -288,10 +290,6 @@ int DocumentExporter::exportCurrentScene(Scene *sce)
ge.exportGeom(sce);
}
- // <library_animations>
- AnimationExporter ae(writer, this->export_settings);
- bool has_animations = ae.exportAnimations(sce);
-
// <library_controllers>
ArmatureExporter arm_exporter(writer, this->export_settings);
ControllerExporter controller_exporter(writer, this->export_settings);
@@ -304,18 +302,11 @@ int DocumentExporter::exportCurrentScene(Scene *sce)
SceneExporter se(writer, &arm_exporter, this->export_settings);
- if (has_animations && this->export_settings->export_transformation_type == BC_TRANSFORMATION_TYPE_MATRIX) {
- // channels adressing <matrix> objects is not (yet) supported
- // So we force usage of <location>, <translation> and <scale>
- fprintf(stdout,
- "For animated Ojects we must use decomposed <matrix> elements,\n" \
- "Forcing usage of TransLocRot transformation type.");
- se.setExportTransformationType(BC_TRANSFORMATION_TYPE_TRANSROTLOC);
- }
- else {
- se.setExportTransformationType(this->export_settings->export_transformation_type);
+ if (this->export_settings->include_animations) {
+ // <library_animations>
+ AnimationExporter ae(writer, this->export_settings);
+ ae.exportAnimations(sce);
}
-
se.exportScene(sce);
// <scene>
diff --git a/source/blender/collada/DocumentExporter.h b/source/blender/collada/DocumentExporter.h
index 6e3c1ecd7cd..60e5deb0e31 100644
--- a/source/blender/collada/DocumentExporter.h
+++ b/source/blender/collada/DocumentExporter.h
@@ -27,10 +27,11 @@
#ifndef __DOCUMENTEXPORTER_H__
#define __DOCUMENTEXPORTER_H__
-#include "ExportSettings.h"
+#include "collada.h"
extern "C" {
#include "DNA_customdata_types.h"
+#include "BKE_depsgraph.h"
}
struct Scene;
@@ -39,7 +40,7 @@ class DocumentExporter
{
public:
DocumentExporter(const ExportSettings *export_settings);
- int exportCurrentScene(Scene *sce);
+ int exportCurrentScene(const EvaluationContext *eval_ctx, Scene *sce);
void exportScenes(const char *filename);
private:
const ExportSettings *export_settings;
diff --git a/source/blender/collada/DocumentImporter.cpp b/source/blender/collada/DocumentImporter.cpp
index 226f319cefd..ce0d296843b 100644
--- a/source/blender/collada/DocumentImporter.cpp
+++ b/source/blender/collada/DocumentImporter.cpp
@@ -190,8 +190,8 @@ void DocumentImporter::finish()
std::vector<Object *> *objects_to_scale = new std::vector<Object *>();
/** TODO Break up and put into 2-pass parsing of DAE */
- std::vector<const COLLADAFW::VisualScene *>::iterator it;
- for (it = vscenes.begin(); it != vscenes.end(); it++) {
+ std::vector<const COLLADAFW::VisualScene *>::iterator sit;
+ for (sit = vscenes.begin(); sit != vscenes.end(); sit++) {
PointerRNA sceneptr, unit_settings;
PropertyRNA *system, *scale;
@@ -222,7 +222,7 @@ void DocumentImporter::finish()
}
// Write nodes to scene
- const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
+ const COLLADAFW::NodePointerArray& roots = (*sit)->getRootNodes();
for (unsigned int i = 0; i < roots.getCount(); i++) {
std::vector<Object *> *objects_done = write_node(roots[i], NULL, sce, NULL, false);
objects_to_scale->insert(objects_to_scale->end(), objects_done->begin(), objects_done->end());
@@ -247,8 +247,8 @@ void DocumentImporter::finish()
armature_importer.fix_animation();
#endif
- for (std::vector<const COLLADAFW::VisualScene *>::iterator it = vscenes.begin(); it != vscenes.end(); it++) {
- const COLLADAFW::NodePointerArray& roots = (*it)->getRootNodes();
+ for (std::vector<const COLLADAFW::VisualScene *>::iterator vsit = vscenes.begin(); vsit != vscenes.end(); vsit++) {
+ const COLLADAFW::NodePointerArray& roots = (*vsit)->getRootNodes();
for (unsigned int i = 0; i < roots.getCount(); i++) {
translate_anim_recursive(roots[i], NULL, NULL);
@@ -256,13 +256,12 @@ void DocumentImporter::finish()
}
if (libnode_ob.size()) {
- Scene *sce = CTX_data_scene(mContext);
fprintf(stderr, "got %d library nodes to free\n", (int)libnode_ob.size());
// free all library_nodes
- std::vector<Object *>::iterator it;
- for (it = libnode_ob.begin(); it != libnode_ob.end(); it++) {
- Object *ob = *it;
+ std::vector<Object *>::iterator lit;
+ for (lit = libnode_ob.begin(); lit != libnode_ob.end(); lit++) {
+ Object *ob = *lit;
Base *base = BKE_scene_base_find(sce, ob);
if (base) {
@@ -321,7 +320,7 @@ void DocumentImporter::translate_anim_recursive(COLLADAFW::Node *node, COLLADAFW
translate_anim_recursive(node, node, parob);
}
else {
- anim_importer.translate_Animations(node, root_map, object_map, FW_object_map);
+ anim_importer.translate_Animations(node, root_map, object_map, FW_object_map, uid_material_map);
COLLADAFW::NodePointerArray &children = node->getChildNodes();
for (i = 0; i < children.getCount(); i++) {
translate_anim_recursive(children[i], node, NULL);
@@ -388,9 +387,7 @@ Object *DocumentImporter::create_camera_object(COLLADAFW::InstanceCamera *camera
Camera *cam = uid_camera_map[cam_uid];
Camera *old_cam = (Camera *)ob->data;
ob->data = cam;
- id_us_min(&old_cam->id);
- if (old_cam->id.us == 0)
- BKE_libblock_free(G.main, old_cam);
+ BKE_libblock_free_us(G.main, old_cam);
return ob;
}
@@ -406,9 +403,7 @@ Object *DocumentImporter::create_lamp_object(COLLADAFW::InstanceLight *lamp, Sce
Lamp *la = uid_lamp_map[lamp_uid];
Lamp *old_lamp = (Lamp *)ob->data;
ob->data = la;
- id_us_min(&old_lamp->id);
- if (old_lamp->id.us == 0)
- BKE_libblock_free(G.main, old_lamp);
+ BKE_libblock_free_us(G.main, old_lamp);
return ob;
}
@@ -479,9 +474,9 @@ void DocumentImporter::create_constraints(ExtraTags *et, Object *ob)
{
if (et && et->isProfile("blender")) {
std::string name;
- short* type = 0;
- et->setData("type", type);
- BKE_constraint_add_for_object(ob, "Test_con", *type);
+ short type = 0;
+ et->setData("type", &type);
+ BKE_constraint_add_for_object(ob, "Test_con", type);
}
}
@@ -512,9 +507,9 @@ std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLA
std::vector<Object *> *root_objects = new std::vector<Object *>();
fprintf(stderr,
- "Writing node id='%s', name='%s'\n",
- id.c_str(),
- name.c_str());
+ "Writing node id='%s', name='%s'\n",
+ id.c_str(),
+ name.c_str());
if (is_joint) {
if (parent_node == NULL && !is_library_node) {
@@ -592,8 +587,8 @@ std::vector<Object *> *DocumentImporter::write_node(COLLADAFW::Node *node, COLLA
++lamp_done;
}
while (controller_done < controller.getCount()) {
- COLLADAFW::InstanceGeometry *geom = (COLLADAFW::InstanceGeometry *)controller[controller_done];
- ob = mesh_importer.create_mesh_object(node, geom, true, uid_material_map, material_texture_mapping_map);
+ COLLADAFW::InstanceGeometry *geometry = (COLLADAFW::InstanceGeometry *)controller[controller_done];
+ ob = mesh_importer.create_mesh_object(node, geometry, true, uid_material_map, material_texture_mapping_map);
if (ob == NULL) {
report_unknown_reference(*node, "instance_controller");
}
diff --git a/source/blender/collada/EffectExporter.cpp b/source/blender/collada/EffectExporter.cpp
index 76b51148509..a4764cab67e 100644
--- a/source/blender/collada/EffectExporter.cpp
+++ b/source/blender/collada/EffectExporter.cpp
@@ -27,7 +27,6 @@
#include <map>
-#include <set>
#include "COLLADASWEffectProfile.h"
#include "COLLADAFWColorOrTexture.h"
@@ -49,21 +48,10 @@ extern "C" {
#include "BKE_material.h"
}
-// OB_MESH is assumed
-static std::string getActiveUVLayerName(Object *ob)
-{
- Mesh *me = (Mesh *)ob->data;
-
- int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
- if (num_layers)
- return std::string(bc_CustomData_get_active_layer_name(&me->fdata, CD_MTFACE));
-
- return "";
-}
-
EffectsExporter::EffectsExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryEffects(sw), export_settings(export_settings) {
}
+
bool EffectsExporter::hasEffects(Scene *sce)
{
Base *base = (Base *)sce->base.first;
@@ -86,13 +74,50 @@ bool EffectsExporter::hasEffects(Scene *sce)
void EffectsExporter::exportEffects(Scene *sce)
{
- if (hasEffects(sce)) {
- this->scene = sce;
- openLibrary();
- MaterialFunctor mf;
- mf.forEachMaterialInExportSet<EffectsExporter>(sce, *this, this->export_settings->export_set);
+ this->scene = sce;
+
+ if (this->export_settings->export_texture_type == BC_TEXTURE_TYPE_MAT) {
+ if (hasEffects(sce)) {
+ MaterialFunctor mf;
+ openLibrary();
+ mf.forEachMaterialInExportSet<EffectsExporter>(sce, *this, this->export_settings->export_set);
+ closeLibrary();
+ }
+ }
+ else {
+ std::set<Object *> uv_textured_obs = bc_getUVTexturedObjects(sce, !this->export_settings->active_uv_only);
+ std::set<Image *> uv_images = bc_getUVImages(sce, !this->export_settings->active_uv_only);
+ if (uv_images.size() > 0) {
+ openLibrary();
+ std::set<Image *>::iterator uv_images_iter;
+ for (uv_images_iter = uv_images.begin();
+ uv_images_iter != uv_images.end();
+ uv_images_iter++)
+ {
- closeLibrary();
+ Image *ima = *uv_images_iter;
+ std::string key(id_name(ima));
+ key = translate_id(key);
+ COLLADASW::Sampler sampler(COLLADASW::Sampler::SAMPLER_TYPE_2D,
+ key + COLLADASW::Sampler::SAMPLER_SID_SUFFIX,
+ key + COLLADASW::Sampler::SURFACE_SID_SUFFIX);
+ sampler.setImageId(key);
+
+ openEffect(key + "-effect");
+ COLLADASW::EffectProfile ep(mSW);
+ ep.setProfileType(COLLADASW::EffectProfile::COMMON);
+ ep.setShaderType(COLLADASW::EffectProfile::PHONG);
+ ep.setDiffuse(createTexture(ima, key, &sampler), false, "diffuse");
+ COLLADASW::ColorOrTexture cot = getcol(0, 0, 0, 1.0f);
+ ep.setSpecular(cot, false, "specular");
+ ep.openProfile();
+ ep.addProfileElements();
+ ep.addExtraTechniques(mSW);
+ ep.closeProfile();
+ closeEffect();
+ }
+ closeLibrary();
+ }
}
}
@@ -124,12 +149,13 @@ void EffectsExporter::writePhong(COLLADASW::EffectProfile &ep, Material *ma)
ep.setSpecular(cot, false, "specular");
}
-void EffectsExporter::writeTextures(COLLADASW::EffectProfile &ep,
- std::string &key,
- COLLADASW::Sampler *sampler,
- MTex *t, Image *ima,
- std::string &uvname ) {
-
+void EffectsExporter::writeTextures(
+ COLLADASW::EffectProfile &ep,
+ std::string &key,
+ COLLADASW::Sampler *sampler,
+ MTex *t, Image *ima,
+ std::string &uvname )
+{
// Image not set for texture
if (!ima) return;
@@ -176,8 +202,7 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
{
// create a list of indices to textures of type TEX_IMAGE
std::vector<int> tex_indices;
- if (this->export_settings->include_material_textures)
- createTextureIndices(ma, tex_indices);
+ createTextureIndices(ma, tex_indices);
openEffect(translate_id(id_name(ma)) + "-effect");
@@ -311,61 +336,9 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
}
}
- int active_uv_layer = -1;
- std::set<Image *> uv_textures;
- if (ob->type == OB_MESH && ob->totcol && this->export_settings->include_uv_textures) {
- bool active_uv_only = this->export_settings->active_uv_only;
- Mesh *me = (Mesh *) ob->data;
- active_uv_layer = CustomData_get_active_layer_index(&me->pdata, CD_MTEXPOLY);
-
- BKE_mesh_tessface_ensure(me);
- for (int i = 0; i < me->pdata.totlayer; i++) {
- if (!active_uv_only || active_uv_layer == i)
- {
- if (me->pdata.layers[i].type == CD_MTEXPOLY) {
- MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
- MPoly *mpoly = me->mpoly;
- for (int j = 0; j < me->totpoly; j++, mpoly++, txface++) {
-
- Material *mat = give_current_material(ob, mpoly->mat_nr + 1);
- if (mat != ma)
- continue;
-
- Image *ima = txface->tpage;
- if (ima == NULL)
- continue;
-
-
- bool not_in_list = uv_textures.find(ima)==uv_textures.end();
- if (not_in_list) {
- std::string name = id_name(ima);
- std::string key(name);
- key = translate_id(key);
-
- // create only one <sampler>/<surface> pair for each unique image
- if (im_samp_map.find(key) == im_samp_map.end()) {
- //<newparam> <sampler> <source>
- COLLADASW::Sampler sampler(COLLADASW::Sampler::SAMPLER_TYPE_2D,
- key + COLLADASW::Sampler::SAMPLER_SID_SUFFIX,
- key + COLLADASW::Sampler::SURFACE_SID_SUFFIX);
- sampler.setImageId(key);
- samplers[a] = sampler;
- samp_surf[b] = &samplers[a];
- im_samp_map[key] = b;
- b++;
- a++;
- uv_textures.insert(ima);
- }
- }
- }
- }
- }
- }
- }
-
// used as fallback when MTex->uvname is "" (this is pretty common)
// it is indeed the correct value to use in that case
- std::string active_uv(getActiveUVLayerName(ob));
+ std::string active_uv(bc_get_active_uvlayer_name(ob));
// write textures
// XXX very slow
@@ -385,19 +358,6 @@ void EffectsExporter::operator()(Material *ma, Object *ob)
writeTextures(ep, key, sampler, t, ima, uvname);
}
- std::set<Image *>::iterator uv_t_iter;
- int idx;
- for (idx = 0, uv_t_iter = uv_textures.begin(); uv_t_iter != uv_textures.end(); uv_t_iter++, idx++ ) {
- if (active_uv_layer>-1 && idx==active_uv_layer) {
- Image *ima = *uv_t_iter;
- std::string key(id_name(ima));
- key = translate_id(key);
- int i = im_samp_map[key];
- COLLADASW::Sampler *sampler = (COLLADASW::Sampler *)samp_surf[i];
- ep.setDiffuse(createTexture(ima, active_uv, sampler), false, "diffuse");
- }
- }
-
// performs the actual writing
ep.addProfileElements();
bool twoSided = false;
diff --git a/source/blender/collada/EffectExporter.h b/source/blender/collada/EffectExporter.h
index d20cbfdfe0b..7d45a085777 100644
--- a/source/blender/collada/EffectExporter.h
+++ b/source/blender/collada/EffectExporter.h
@@ -48,7 +48,6 @@ class EffectsExporter: COLLADASW::LibraryEffects
public:
EffectsExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings);
void exportEffects(Scene *sce);
-
void operator()(Material *ma, Object *ob);
COLLADASW::ColorOrTexture createTexture(Image *ima,
diff --git a/source/blender/collada/ErrorHandler.cpp b/source/blender/collada/ErrorHandler.cpp
index 98aa85f8a9b..7e18328f000 100644
--- a/source/blender/collada/ErrorHandler.cpp
+++ b/source/blender/collada/ErrorHandler.cpp
@@ -49,7 +49,10 @@ ErrorHandler::~ErrorHandler()
//--------------------------------------------------------------------
bool ErrorHandler::handleError(const COLLADASaxFWL::IError *error)
{
- bool isError = true;
+ /* This method must return true when Collada should continue.
+ See https://github.com/KhronosGroup/OpenCOLLADA/issues/442
+ */
+ bool isWarning = false;
if (error->getErrorClass() == COLLADASaxFWL::IError::ERROR_SAXPARSER) {
COLLADASaxFWL::SaxParserError *saxParserError = (COLLADASaxFWL::SaxParserError *) error;
@@ -58,14 +61,14 @@ bool ErrorHandler::handleError(const COLLADASaxFWL::IError *error)
// Workaround to avoid wrong error
if (parserError.getErrorType() == GeneratedSaxParser::ParserError::ERROR_VALIDATION_MIN_OCCURS_UNMATCHED) {
if (STREQ(parserError.getElement(), "effect")) {
- isError = false;
+ isWarning = true;
}
}
if (parserError.getErrorType() == GeneratedSaxParser::ParserError::ERROR_VALIDATION_SEQUENCE_PREVIOUS_SIBLING_NOT_PRESENT) {
if (!(STREQ(parserError.getElement(), "extra") &&
STREQ(parserError.getAdditionalText().c_str(), "sibling: fx_profile_abstract")))
{
- isError = false;
+ isWarning = true;
}
}
@@ -81,17 +84,12 @@ bool ErrorHandler::handleError(const COLLADASaxFWL::IError *error)
* Accept non critical errors as warnings (i.e. texture not found)
* This makes the importer more graceful, so it now imports what makes sense.
*/
- if (saxFWLError->getSeverity() == COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL) {
- isError = false;
- }
-
+ isWarning = (saxFWLError->getSeverity() == COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL);
std::cout << "Sax FWL Error: " << saxFWLError->getErrorMessage() << std::endl;
}
else {
std::cout << "opencollada error: " << error->getFullErrorMessage() << std::endl;
}
- mError |= isError;
-
- return false; // let OpenCollada decide when to abort
+ return isWarning;
}
diff --git a/source/blender/collada/ExportSettings.h b/source/blender/collada/ExportSettings.h
index 9451cac9dae..fa6751bef60 100644
--- a/source/blender/collada/ExportSettings.h
+++ b/source/blender/collada/ExportSettings.h
@@ -27,11 +27,28 @@
#ifndef __EXPORTSETTINGS_H__
#define __EXPORTSETTINGS_H__
-#include "collada.h"
-#include "collada.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "BLI_linklist.h"
+
+typedef enum BC_export_mesh_type {
+ BC_MESH_TYPE_VIEW,
+ BC_MESH_TYPE_RENDER
+} BC_export_mesh_type;
+
+typedef enum BC_export_transformation_type {
+ BC_TRANSFORMATION_TYPE_MATRIX,
+ BC_TRANSFORMATION_TYPE_TRANSROTLOC
+} BC_export_transformation_type;
-struct ExportSettings {
-public:
+typedef enum BC_export_texture_type {
+ BC_TEXTURE_TYPE_MAT,
+ BC_TEXTURE_TYPE_UV
+} BC_export_texture_type;
+
+typedef struct ExportSettings {
bool apply_modifiers;
BC_export_mesh_type export_mesh_type;
@@ -40,10 +57,11 @@ public:
bool include_armatures;
bool include_shapekeys;
bool deform_bones_only;
+ bool include_animations;
+ int sampling_rate;
bool active_uv_only;
- bool include_uv_textures;
- bool include_material_textures;
+ BC_export_texture_type export_texture_type;
bool use_texture_copies;
bool triangulate;
@@ -51,10 +69,17 @@ public:
bool use_blender_profile;
bool sort_by_name;
BC_export_transformation_type export_transformation_type;
+
bool open_sim;
+ bool limit_precision;
+ bool keep_bind_info;
char *filepath;
LinkNode *export_set;
-};
+} ExportSettings;
+
+#ifdef __cplusplus
+}
+#endif
#endif
diff --git a/source/blender/collada/GeometryExporter.cpp b/source/blender/collada/GeometryExporter.cpp
index 7c7c57f3305..8406426a366 100644
--- a/source/blender/collada/GeometryExporter.cpp
+++ b/source/blender/collada/GeometryExporter.cpp
@@ -52,6 +52,7 @@ extern "C" {
#include "collada_internal.h"
#include "collada_utils.h"
+
// TODO: optimize UV sets by making indexed list with duplicates removed
GeometryExporter::GeometryExporter(COLLADASW::StreamWriter *sw, const ExportSettings *export_settings) : COLLADASW::LibraryGeometries(sw), export_settings(export_settings)
{
@@ -134,13 +135,22 @@ void GeometryExporter::operator()(Object *ob)
// Only create Polylists if number of faces > 0
if (me->totface > 0) {
// XXX slow
- if (ob->totcol) {
- for (int a = 0; a < ob->totcol; a++) {
- createPolylist(a, has_uvs, has_color, ob, me, geom_id, norind);
+ std::set<Image *> uv_images = bc_getUVImages(ob, !this->export_settings->active_uv_only);
+ if (this->export_settings->export_texture_type == BC_TEXTURE_TYPE_MAT || uv_images.size() == 0) {
+ if (ob->totcol) {
+ for (int a = 0; a < ob->totcol; a++) {
+ createPolylist(a, has_uvs, has_color, ob, me, geom_id, norind);
+ }
+ }
+ else {
+ int i = 0;
+ createPolylist(i, has_uvs, has_color, ob, me, geom_id, norind);
}
}
else {
- createPolylist(0, has_uvs, has_color, ob, me, geom_id, norind);
+ bool all_uv_layers = !this->export_settings->active_uv_only;
+ std::set<Image *> uv_image_set = bc_getUVImages(ob, all_uv_layers);
+ createPolylists(uv_image_set, has_uvs, has_color, ob, me, geom_id, norind);
}
}
@@ -220,13 +230,15 @@ void GeometryExporter::export_key_mesh(Object *ob, Mesh *me, KeyBlock *kb)
//createLooseEdgeList(ob, me, geom_id, norind);
// XXX slow
- if (ob->totcol) {
+ if (ob->totcol && this->export_settings->export_texture_type == BC_TEXTURE_TYPE_MAT) {
for (int a = 0; a < ob->totcol; a++) {
createPolylist(a, has_uvs, has_color, ob, me, geom_id, norind);
}
}
else {
- createPolylist(0, has_uvs, has_color, ob, me, geom_id, norind);
+ bool all_uv_layers = !this->export_settings->active_uv_only;
+ std::set<Image *> uv_images = bc_getUVImages(ob, all_uv_layers);
+ createPolylists(uv_images, has_uvs, has_color, ob, me, geom_id, norind);
}
closeMesh();
@@ -295,7 +307,44 @@ std::string GeometryExporter::makeVertexColorSourceId(std::string& geom_id, char
return result;
}
-// powerful because it handles both cases when there is material and when there's not
+static void prepareToAppendValues(bool is_triangulated, COLLADASW::PrimitivesBase *facelist, std::vector<unsigned long> &vcount_list)
+{
+ // performs the actual writing
+ if (is_triangulated) {
+ ((COLLADASW::Triangles *)facelist)->prepareToAppendValues();
+ }
+ else {
+ // sets <vcount>
+ facelist->setVCountList(vcount_list);
+ ((COLLADASW::Polylist *)facelist)-> prepareToAppendValues();
+ }
+}
+
+static void finishList(bool is_triangulated, COLLADASW::PrimitivesBase *facelist)
+{
+ if (is_triangulated) {
+ ((COLLADASW::Triangles *)facelist)->finish();
+ }
+ else {
+ ((COLLADASW::Polylist *)facelist)->finish();
+ }
+}
+
+COLLADASW::PrimitivesBase *getFacelist(bool is_triangulated, COLLADASW::StreamWriter *mSW)
+{
+ COLLADASW::PrimitivesBase *facelist;
+
+ if (is_triangulated)
+ {
+ facelist = new COLLADASW::Triangles(mSW);
+ }
+ else {
+ facelist = new COLLADASW::Polylist(mSW);
+ }
+ return facelist;
+}
+
+// Export meshes with Materials
void GeometryExporter::createPolylist(short material_index,
bool has_uvs,
bool has_color,
@@ -313,7 +362,7 @@ void GeometryExporter::createPolylist(short material_index,
int i;
int faces_in_polylist = 0;
std::vector<unsigned long> vcount_list;
-
+ bool is_triangulated = true;
// count faces with this material
for (i = 0; i < totpolys; i++) {
MPoly *p = &mpolys[i];
@@ -321,6 +370,9 @@ void GeometryExporter::createPolylist(short material_index,
if (p->mat_nr == material_index) {
faces_in_polylist++;
vcount_list.push_back(p->totloop);
+ if (p->totloop != 3) {
+ is_triangulated = false;
+ }
}
}
@@ -331,20 +383,21 @@ void GeometryExporter::createPolylist(short material_index,
}
Material *ma = ob->totcol ? give_current_material(ob, material_index + 1) : NULL;
- COLLADASW::Polylist polylist(mSW);
+ COLLADASW::PrimitivesBase *facelist = getFacelist(is_triangulated, mSW);
+
// sets count attribute in <polylist>
- polylist.setCount(faces_in_polylist);
+ facelist->setCount(faces_in_polylist);
// sets material name
if (ma) {
std::string material_id = get_material_id(ma);
std::ostringstream ostr;
ostr << translate_id(material_id);
- polylist.setMaterial(ostr.str());
+ facelist->setMaterial(ostr.str());
}
-
- COLLADASW::InputList &til = polylist.getInputList();
+
+ COLLADASW::InputList &til = facelist->getInputList();
// creates <input> in <polylist> for vertices
COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
@@ -360,13 +413,21 @@ void GeometryExporter::createPolylist(short material_index,
int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE)-1;
for (i = 0; i < num_layers; i++) {
if (!this->export_settings->active_uv_only || i == active_uv_index) {
-
- // char *name = CustomData_get_layer_name(&me->fdata, CD_MTFACE, i);
+
+ std::string uv_name(bc_get_uvlayer_name(me, i));
+ std::string effective_id = geom_id; // (uv_name == "") ? geom_id : uv_name;
+ std::string layer_id = makeTexcoordSourceId(
+ effective_id,
+ i, this->export_settings->active_uv_only);
+
+ /* Note: the third parameter denotes the offset of TEXCOORD in polylist elements
+ For now this is always 2 (This may change sometime/maybe)
+ */
COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD,
- makeUrl(makeTexcoordSourceId(geom_id, i, this->export_settings->active_uv_only)),
- 2, // this is only until we have optimized UV sets
- (this->export_settings->active_uv_only) ? 0 : i // only_active_uv exported -> we have only one set
- );
+ makeUrl(layer_id),
+ 2, // this is only until we have optimized UV sets
+ (this->export_settings->active_uv_only) ? 0 : i // only_active_uv exported -> we have only one set
+ );
til.push_back(input3);
}
}
@@ -387,12 +448,10 @@ void GeometryExporter::createPolylist(short material_index,
}
}
- // sets <vcount>
- polylist.setVCountList(vcount_list);
// performs the actual writing
- polylist.prepareToAppendValues();
-
+ prepareToAppendValues(is_triangulated, facelist, vcount_list);
+
// <p>
int texindex = 0;
for (i = 0; i < totpolys; i++) {
@@ -404,22 +463,203 @@ void GeometryExporter::createPolylist(short material_index,
BCPolygonNormalsIndices normal_indices = norind[i];
for (int j = 0; j < loop_count; j++) {
- polylist.appendValues(l[j].v);
- polylist.appendValues(normal_indices[j]);
+ facelist->appendValues(l[j].v);
+ facelist->appendValues(normal_indices[j]);
if (has_uvs)
- polylist.appendValues(texindex + j);
+ facelist->appendValues(texindex + j);
if (has_color)
- polylist.appendValues(texindex + j);
+ facelist->appendValues(texindex + j);
}
}
texindex += loop_count;
}
-
- polylist.finish();
+
+ finishList(is_triangulated, facelist);
+ delete facelist;
}
+void GeometryExporter::createPolylists(std::set<Image *> uv_images,
+ bool has_uvs,
+ bool has_color,
+ Object *ob,
+ Mesh *me,
+ std::string& geom_id,
+ std::vector<BCPolygonNormalsIndices>& norind)
+{
+ std::set<Image *>::iterator uv_images_iter;
+ for (uv_images_iter = uv_images.begin();
+ uv_images_iter != uv_images.end();
+ uv_images_iter++)
+ {
+
+ Image *ima = *uv_images_iter;
+ std::string imageid(id_name(ima));
+ createPolylist(imageid, has_uvs,
+ has_color,
+ ob,
+ me,
+ geom_id,
+ norind);
+ }
+
+ /* We msut add an additional collector for the case when
+ * some parts of the object are not textured at all.
+ * The next call creates a polylist for all untextured polygons
+ */
+
+ createPolylist("", has_uvs,
+ has_color,
+ ob,
+ me,
+ geom_id,
+ norind);
+
+}
+
+/* ===========================================================================
+ * Export Meshes with UV Textures (export as materials, see also in
+ * effectExporter and MaterialExporter)
+ *
+ * If imageid is the empty string, then collect only untextured polygons
+ * =========================================================================== */
+void GeometryExporter::createPolylist(std::string imageid,
+ bool has_uvs,
+ bool has_color,
+ Object *ob,
+ Mesh *me,
+ std::string& geom_id,
+ std::vector<BCPolygonNormalsIndices>& norind)
+{
+
+ MPoly *mpolys = me->mpoly;
+ MLoop *mloops = me->mloop;
+ MTexPoly *mtpolys = me->mtpoly;
+
+ int totpolys = me->totpoly;
+
+ // <vcount>
+ int i;
+ int faces_in_polylist = 0;
+ std::vector<unsigned long> vcount_list;
+ bool is_triangulated = true;
+ // count faces with this material
+ for (i = 0; i < totpolys; i++) {
+ MTexPoly *tp = &mtpolys[i];
+ MPoly *p = &mpolys[i];
+
+ std::string tpageid = (mtpolys && tp->tpage) ? id_name(tp->tpage) : "";
+ if (tpageid == imageid) {
+ faces_in_polylist++;
+ vcount_list.push_back(p->totloop);
+ if (p->totloop != 3) {
+ is_triangulated = false;
+ }
+ }
+ }
+
+ // no faces using this imageid
+ if (faces_in_polylist == 0) {
+ if (imageid != "")
+ fprintf(stderr, "%s: Image %s is not used.\n", id_name(ob).c_str(), imageid.c_str());
+ return;
+ }
+
+ COLLADASW::PrimitivesBase *facelist = getFacelist(is_triangulated, mSW);
+
+ // sets count attribute in <polylist>
+ facelist->setCount(faces_in_polylist);
+
+ if (imageid != "") {
+ // sets material name
+ std::string material_id = get_material_id_from_id(imageid);
+ std::ostringstream ostr;
+ ostr << translate_id(material_id);
+ facelist->setMaterial(ostr.str());
+ }
+ COLLADASW::InputList &til = facelist->getInputList();
+
+ // creates <input> in <polylist> for vertices
+ COLLADASW::Input input1(COLLADASW::InputSemantic::VERTEX, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::VERTEX), 0);
+
+ // creates <input> in <polylist> for normals
+ COLLADASW::Input input2(COLLADASW::InputSemantic::NORMAL, getUrlBySemantics(geom_id, COLLADASW::InputSemantic::NORMAL), 1);
+
+ til.push_back(input1);
+ til.push_back(input2);
+
+ // if mesh has uv coords writes <input> for TEXCOORD
+ int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
+ int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE) - 1;
+ for (i = 0; i < num_layers; i++) {
+ if (!this->export_settings->active_uv_only || i == active_uv_index) {
+
+ std::string uv_name(bc_get_uvlayer_name(me, i));
+ std::string effective_id = geom_id; // (uv_name == "") ? geom_id : uv_name;
+ std::string layer_id = makeTexcoordSourceId(
+ effective_id,
+ i, this->export_settings->active_uv_only);
+
+ /* Note: the third parameter denotes the offset of TEXCOORD in polylist elements
+ For now this is always 2 (This may change sometime/maybe)
+ */
+ COLLADASW::Input input3(COLLADASW::InputSemantic::TEXCOORD,
+ makeUrl(layer_id),
+ 2, // this is only until we have optimized UV sets
+ (this->export_settings->active_uv_only) ? 0 : i // only_active_uv exported -> we have only one set
+ );
+ til.push_back(input3);
+ }
+ }
+
+ int totlayer_mcol = CustomData_number_of_layers(&me->ldata, CD_MLOOPCOL);
+ if (totlayer_mcol > 0) {
+ int map_index = 0;
+
+ for (int a = 0; a < totlayer_mcol; a++) {
+ char *layer_name = bc_CustomData_get_layer_name(&me->ldata, CD_MLOOPCOL, a);
+ COLLADASW::Input input4(COLLADASW::InputSemantic::COLOR,
+ makeUrl(makeVertexColorSourceId(geom_id, layer_name)),
+ (has_uvs) ? 3 : 2, // all color layers have same index order
+ map_index // set number equals color map index
+ );
+ til.push_back(input4);
+ map_index++;
+ }
+ }
+
+ // performs the actual writing
+ prepareToAppendValues(is_triangulated, facelist, vcount_list);
+
+ // <p>
+ int texindex = 0;
+ for (i = 0; i < totpolys; i++) {
+ MTexPoly *tp = &mtpolys[i];
+ MPoly *p = &mpolys[i];
+ int loop_count = p->totloop;
+ std::string tpageid = (mtpolys && tp->tpage) ? id_name(tp->tpage) : "";
+ if (tpageid == imageid) {
+ MLoop *l = &mloops[p->loopstart];
+ BCPolygonNormalsIndices normal_indices = norind[i];
+
+ for (int j = 0; j < loop_count; j++) {
+ facelist->appendValues(l[j].v);
+ facelist->appendValues(normal_indices[j]);
+ if (has_uvs)
+ facelist->appendValues(texindex + j);
+
+ if (has_color)
+ facelist->appendValues(texindex + j);
+ }
+ }
+
+ texindex += loop_count;
+ }
+
+ finishList(is_triangulated, facelist);
+ delete facelist;
+}
// creates <source> for positions
void GeometryExporter::createVertsSource(std::string geom_id, Mesh *me)
@@ -479,12 +719,13 @@ void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me)
source.setArrayId(layer_id + ARRAY_ID_SUFFIX);
source.setAccessorCount(me->totloop);
- source.setAccessorStride(3);
+ source.setAccessorStride(4);
COLLADASW::SourceBase::ParameterNameList &param = source.getParameterNameList();
param.push_back("R");
param.push_back("G");
param.push_back("B");
+ param.push_back("A");
source.prepareToAppendValues();
@@ -496,7 +737,8 @@ void GeometryExporter::createVertexColorSource(std::string geom_id, Mesh *me)
source.appendValues(
mlc->r / 255.0f,
mlc->g / 255.0f,
- mlc->b / 255.0f
+ mlc->b / 255.0f,
+ mlc->a / 255.0f
);
}
}
@@ -537,7 +779,13 @@ void GeometryExporter::createTexcoordsSource(std::string geom_id, Mesh *me)
MLoopUV *mloops = (MLoopUV *)CustomData_get_layer_n(&me->ldata, CD_MLOOPUV, a);
COLLADASW::FloatSourceF source(mSW);
- std::string layer_id = makeTexcoordSourceId(geom_id, a, this->export_settings->active_uv_only);
+ std::string active_uv_name(bc_get_active_uvlayer_name(me));
+ std::string effective_id = geom_id; // (active_uv_name == "") ? geom_id : active_uv_name;
+ std::string layer_id = makeTexcoordSourceId(
+ effective_id,
+ a,
+ this->export_settings->active_uv_only );
+
source.setId(layer_id);
source.setArrayId(layer_id + ARRAY_ID_SUFFIX);
diff --git a/source/blender/collada/GeometryExporter.h b/source/blender/collada/GeometryExporter.h
index 69d1067e6f4..890304f4568 100644
--- a/source/blender/collada/GeometryExporter.h
+++ b/source/blender/collada/GeometryExporter.h
@@ -85,15 +85,33 @@ public:
Mesh *me,
std::string& geom_id);
- // powerful because it handles both cases when there is material and when there's not
+ // Create polylists for meshes with Materials
void createPolylist(short material_index,
- bool has_uvs,
- bool has_color,
- Object *ob,
- Mesh *me,
- std::string& geom_id,
- std::vector<BCPolygonNormalsIndices>& norind);
-
+ bool has_uvs,
+ bool has_color,
+ Object *ob,
+ Mesh *me,
+ std::string& geom_id,
+ std::vector<BCPolygonNormalsIndices>& norind);
+
+ // Create polylists for meshes with UV Textures
+ void createPolylists(std::set<Image *> uv_images,
+ bool has_uvs,
+ bool has_color,
+ Object *ob,
+ Mesh *me,
+ std::string& geom_id,
+ std::vector<BCPolygonNormalsIndices>& norind);
+
+ // Create polylists for meshes with UV Textures
+ void createPolylist(std::string imageid,
+ bool has_uvs,
+ bool has_color,
+ Object *ob,
+ Mesh *me,
+ std::string& geom_id,
+ std::vector<BCPolygonNormalsIndices>& norind);
+
// creates <source> for positions
void createVertsSource(std::string geom_id, Mesh *me);
diff --git a/source/blender/collada/ImageExporter.cpp b/source/blender/collada/ImageExporter.cpp
index aac41e2e93c..99547551a12 100644
--- a/source/blender/collada/ImageExporter.cpp
+++ b/source/blender/collada/ImageExporter.cpp
@@ -55,9 +55,9 @@ ImagesExporter::ImagesExporter(COLLADASW::StreamWriter *sw, const ExportSettings
void ImagesExporter::export_UV_Image(Image *image, bool use_copies)
{
- std::string name(id_name(image));
- std::string translated_name(translate_id(name));
- bool not_yet_exported = find(mImages.begin(), mImages.end(), translated_name) == mImages.end();
+ std::string id(id_name(image));
+ std::string translated_id(translate_id(id));
+ bool not_yet_exported = find(mImages.begin(), mImages.end(), translated_id) == mImages.end();
if (not_yet_exported) {
@@ -88,7 +88,7 @@ void ImagesExporter::export_UV_Image(Image *image, bool use_copies)
// make absolute destination path
- BLI_strncpy(export_file, name.c_str(), sizeof(export_file));
+ BLI_strncpy(export_file, id.c_str(), sizeof(export_file));
BKE_image_path_ensure_ext_from_imformat(export_file, &imageFormat);
BLI_join_dirfile(export_path, sizeof(export_path), export_dir, export_file);
@@ -143,10 +143,11 @@ void ImagesExporter::export_UV_Image(Image *image, bool use_copies)
}
}
- COLLADASW::Image img(COLLADABU::URI(COLLADABU::URI::nativePathToUri(export_path)), translated_name, translated_name); /* set name also to mNameNC. This helps other viewers import files exported from Blender better */
+ /* set name also to mNameNC. This helps other viewers import files exported from Blender better */
+ COLLADASW::Image img(COLLADABU::URI(COLLADABU::URI::nativePathToUri(export_path)), translated_id, translated_id);
img.add(mSW);
fprintf(stdout, "Collada export: Added image: %s\n", export_file);
- mImages.push_back(translated_name);
+ mImages.push_back(translated_id);
BKE_image_release_ibuf(image, imbuf, NULL);
}
@@ -161,7 +162,7 @@ void ImagesExporter::export_UV_Images()
for (node = this->export_settings->export_set; node; node = node->next) {
Object *ob = (Object *)node->link;
- if (ob->type == OB_MESH && ob->totcol) {
+ if (ob->type == OB_MESH) {
Mesh *me = (Mesh *) ob->data;
BKE_mesh_tessface_ensure(me);
int active_uv_layer = CustomData_get_active_layer_index(&me->pdata, CD_MTEXPOLY);
@@ -189,15 +190,21 @@ void ImagesExporter::export_UV_Images()
}
}
-
+/* ============================================================
+ * Check if there are any images to be exported
+ * Returns true as soon as an object is detected that
+ * either has an UV Texture assigned, or has a material
+ * assigned that uses an Image Texture.
+ * ============================================================
+ */
bool ImagesExporter::hasImages(Scene *sce)
{
LinkNode *node;
for (node = this->export_settings->export_set; node; node = node->next) {
Object *ob = (Object *)node->link;
- int a;
- for (a = 0; a < ob->totcol; a++) {
+
+ for (int a = 0; a < ob->totcol; a++) {
Material *ma = give_current_material(ob, a + 1);
// no material, but check all of the slots
@@ -232,11 +239,10 @@ void ImagesExporter::exportImages(Scene *sce)
openLibrary();
MaterialFunctor mf;
- if (this->export_settings->include_material_textures) {
+ if (this->export_settings->export_texture_type == BC_TEXTURE_TYPE_MAT) {
mf.forEachMaterialInExportSet<ImagesExporter>(sce, *this, this->export_settings->export_set);
}
-
- if (this->export_settings->include_uv_textures) {
+ else {
export_UV_Images();
}
diff --git a/source/blender/collada/ImportSettings.h b/source/blender/collada/ImportSettings.h
index 2c52d73e756..fb4277b048f 100644
--- a/source/blender/collada/ImportSettings.h
+++ b/source/blender/collada/ImportSettings.h
@@ -27,16 +27,14 @@
#ifndef __IMPORTSETTINGS_H__
#define __IMPORTSETTINGS_H__
-#include "collada.h"
-
-struct ImportSettings {
-public:
+typedef struct ImportSettings {
bool import_units;
bool find_chains;
bool auto_connect;
bool fix_orientation;
int min_chain_length;
char *filepath;
-};
+ bool keep_bind_info;
+} ImportSettings;
#endif
diff --git a/source/blender/collada/InstanceWriter.cpp b/source/blender/collada/InstanceWriter.cpp
index 71371d280df..4d846693e50 100644
--- a/source/blender/collada/InstanceWriter.cpp
+++ b/source/blender/collada/InstanceWriter.cpp
@@ -32,43 +32,77 @@
#include "COLLADASWInstanceMaterial.h"
extern "C" {
- #include "BKE_customdata.h"
- #include "BKE_material.h"
- #include "DNA_mesh_types.h"
+#include "BKE_customdata.h"
+#include "BKE_material.h"
+#include "DNA_mesh_types.h"
}
#include "InstanceWriter.h"
#include "collada_internal.h"
#include "collada_utils.h"
-void InstanceWriter::add_material_bindings(COLLADASW::BindMaterial& bind_material, Object *ob, bool active_uv_only)
+void InstanceWriter::add_material_bindings(COLLADASW::BindMaterial& bind_material, Object *ob, bool active_uv_only, BC_export_texture_type export_texture_type)
{
- for (int a = 0; a < ob->totcol; a++) {
- Material *ma = give_current_material(ob, a + 1);
-
- COLLADASW::InstanceMaterialList& iml = bind_material.getInstanceMaterialList();
+ bool all_uv_layers = !active_uv_only;
+ COLLADASW::InstanceMaterialList& iml = bind_material.getInstanceMaterialList();
- if (ma) {
- std::string matid(get_material_id(ma));
- matid = translate_id(matid);
+ if (export_texture_type == BC_TEXTURE_TYPE_UV)
+ {
+ std::set<Image *> uv_images = bc_getUVImages(ob, all_uv_layers);
+ std::set<Image *>::iterator uv_images_iter;
+ for (uv_images_iter = uv_images.begin();
+ uv_images_iter != uv_images.end();
+ uv_images_iter++)
+ {
+ Image *ima = *uv_images_iter;
+ std::string matid(id_name(ima));
+ matid = get_material_id_from_id(matid);
std::ostringstream ostr;
ostr << matid;
COLLADASW::InstanceMaterial im(ostr.str(), COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, matid));
-
+
// create <bind_vertex_input> for each uv map
Mesh *me = (Mesh *)ob->data;
int totlayer = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
-
+
int map_index = 0;
- int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE) -1;
+ int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE) - 1;
for (int b = 0; b < totlayer; b++) {
if (!active_uv_only || b == active_uv_index) {
char *name = bc_CustomData_get_layer_name(&me->fdata, CD_MTFACE, b);
im.push_back(COLLADASW::BindVertexInput(name, "TEXCOORD", map_index++));
}
}
-
+
iml.push_back(im);
}
}
+
+ else {
+ for (int a = 0; a < ob->totcol; a++) {
+ Material *ma = give_current_material(ob, a + 1);
+ if (ma) {
+ std::string matid(get_material_id(ma));
+ matid = translate_id(matid);
+ std::ostringstream ostr;
+ ostr << matid;
+ COLLADASW::InstanceMaterial im(ostr.str(), COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, matid));
+
+ // create <bind_vertex_input> for each uv map
+ Mesh *me = (Mesh *)ob->data;
+ int totlayer = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
+
+ int map_index = 0;
+ int active_uv_index = CustomData_get_active_layer_index(&me->fdata, CD_MTFACE) - 1;
+ for (int b = 0; b < totlayer; b++) {
+ if (!active_uv_only || b == active_uv_index) {
+ char *name = bc_CustomData_get_layer_name(&me->fdata, CD_MTFACE, b);
+ im.push_back(COLLADASW::BindVertexInput(name, "TEXCOORD", map_index++));
+ }
+ }
+
+ iml.push_back(im);
+ }
+ }
+ }
}
diff --git a/source/blender/collada/InstanceWriter.h b/source/blender/collada/InstanceWriter.h
index 49ddf091b1c..a46027325a2 100644
--- a/source/blender/collada/InstanceWriter.h
+++ b/source/blender/collada/InstanceWriter.h
@@ -31,11 +31,12 @@
#include "COLLADASWBindMaterial.h"
#include "DNA_object_types.h"
+#include "collada.h"
class InstanceWriter
{
protected:
- void add_material_bindings(COLLADASW::BindMaterial& bind_material, Object *ob, bool active_uv_only);
+ void add_material_bindings(COLLADASW::BindMaterial& bind_material, Object *ob, bool active_uv_only, BC_export_texture_type export_texture_type);
};
#endif
diff --git a/source/blender/collada/MaterialExporter.cpp b/source/blender/collada/MaterialExporter.cpp
index 4aece997f72..0c0395f2a21 100644
--- a/source/blender/collada/MaterialExporter.cpp
+++ b/source/blender/collada/MaterialExporter.cpp
@@ -38,14 +38,40 @@ MaterialsExporter::MaterialsExporter(COLLADASW::StreamWriter *sw, const ExportSe
void MaterialsExporter::exportMaterials(Scene *sce)
{
- if (hasMaterials(sce)) {
- openLibrary();
+ if (this->export_settings->export_texture_type == BC_TEXTURE_TYPE_MAT)
+ {
+ if (hasMaterials(sce)) {
+ openLibrary();
- MaterialFunctor mf;
- mf.forEachMaterialInExportSet<MaterialsExporter>(sce, *this, this->export_settings->export_set);
+ MaterialFunctor mf;
+ mf.forEachMaterialInExportSet<MaterialsExporter>(sce, *this, this->export_settings->export_set);
- closeLibrary();
+ closeLibrary();
+ }
}
+
+ else {
+ std::set<Image *> uv_images = bc_getUVImages(sce, !this->export_settings->active_uv_only);
+ if (uv_images.size() > 0) {
+ openLibrary();
+ std::set<Image *>::iterator uv_images_iter;
+ for (uv_images_iter = uv_images.begin();
+ uv_images_iter != uv_images.end();
+ uv_images_iter++)
+ {
+
+ Image *ima = *uv_images_iter;
+ std::string matid(id_name(ima));
+
+ openMaterial(get_material_id_from_id(matid), translate_id(matid));
+ std::string efid = translate_id(matid) + "-effect";
+ addInstanceEffect(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, efid));
+ closeMaterial();
+ }
+ closeLibrary();
+ }
+ }
+
}
bool MaterialsExporter::hasMaterials(Scene *sce)
diff --git a/source/blender/collada/MeshImporter.cpp b/source/blender/collada/MeshImporter.cpp
index 8f3bf88af65..9848bf3b50b 100644
--- a/source/blender/collada/MeshImporter.cpp
+++ b/source/blender/collada/MeshImporter.cpp
@@ -27,7 +27,7 @@
#include <algorithm>
-#if !defined(WIN32) || defined(FREE_WINDOWS)
+#if !defined(WIN32)
#include <iostream>
#endif
@@ -552,7 +552,7 @@ void MeshImporter::mesh_add_edges(Mesh *mesh, int len)
{
CustomData edata;
MEdge *medge;
- int i, totedge;
+ int totedge;
if (len == 0)
return;
@@ -572,7 +572,7 @@ void MeshImporter::mesh_add_edges(Mesh *mesh, int len)
/* set default flags */
medge = &mesh->medge[mesh->totedge];
- for (i = 0; i < len; i++, medge++)
+ for (int i = 0; i < len; i++, medge++)
medge->flag = ME_EDGEDRAW | ME_EDGERENDER | SELECT;
mesh->totedge = totedge;
@@ -606,12 +606,12 @@ void MeshImporter::read_lines(COLLADAFW::Mesh *mesh, Mesh *me)
unsigned int edge_count = mp->getFaceCount();
unsigned int *indices = mp->getPositionIndices().getData();
- for (int i = 0; i < edge_count; i++, med++) {
+ for (int j = 0; j < edge_count; j++, med++) {
med->bweight = 0;
med->crease = 0;
med->flag |= ME_LOOSEEDGE;
- med->v1 = indices[2 * i];
- med->v2 = indices[2 * i + 1];
+ med->v1 = indices[2 * j];
+ med->v2 = indices[2 * j + 1];
}
}
}
@@ -703,8 +703,9 @@ void MeshImporter::read_polys(COLLADAFW::Mesh *collada_mesh, Mesh *me)
}
if (collada_meshtype == COLLADAFW::MeshPrimitive::POLYLIST ||
- collada_meshtype == COLLADAFW::MeshPrimitive::POLYGONS ||
- collada_meshtype == COLLADAFW::MeshPrimitive::TRIANGLES) {
+ collada_meshtype == COLLADAFW::MeshPrimitive::POLYGONS ||
+ collada_meshtype == COLLADAFW::MeshPrimitive::TRIANGLES)
+ {
COLLADAFW::Polygons *mpvc = (COLLADAFW::Polygons *)mp;
unsigned int start_index = 0;
@@ -1092,7 +1093,8 @@ MTFace *MeshImporter::assign_material_to_geom(COLLADAFW::MaterialBinding cmateri
// set texture face
if (color_texture &&
strlen((color_texture)->uvname) &&
- !STREQ(layername, color_texture->uvname)) {
+ !STREQ(layername, color_texture->uvname))
+ {
texture_face = (MTFace *)CustomData_get_layer_named(&me->fdata, CD_MTFACE,
color_texture->uvname);
strcpy(layername, color_texture->uvname);
@@ -1173,8 +1175,9 @@ Object *MeshImporter::create_mesh_object(COLLADAFW::Node *node, COLLADAFW::Insta
BKE_mesh_assign_object(ob, new_mesh);
BKE_mesh_calc_normals(new_mesh);
- if (old_mesh->id.us == 0) BKE_libblock_free(G.main, old_mesh);
-
+ id_us_plus(&old_mesh->id); /* Because BKE_mesh_assign_object would have already decreased it... */
+ BKE_libblock_free_us(G.main, old_mesh);
+
char layername[100];
layername[0] = '\0';
MTFace *texture_face = NULL;
diff --git a/source/blender/collada/SceneExporter.cpp b/source/blender/collada/SceneExporter.cpp
index 30cd6ddf197..5a0badf8d3a 100644
--- a/source/blender/collada/SceneExporter.cpp
+++ b/source/blender/collada/SceneExporter.cpp
@@ -38,11 +38,6 @@ SceneExporter::SceneExporter(COLLADASW::StreamWriter *sw, ArmatureExporter *arm,
{
}
-void SceneExporter::setExportTransformationType(BC_export_transformation_type transformation_type)
-{
- this->transformation_type = transformation_type;
-}
-
void SceneExporter::exportScene(Scene *sce)
{
// <library_visual_scenes> <visual_scene>
@@ -138,7 +133,7 @@ void SceneExporter::writeNodes(Object *ob, Scene *sce)
// for skinned mesh we write obmat in <bind_shape_matrix>
TransformWriter::add_node_transform_identity(colladaNode);
else {
- TransformWriter::add_node_transform_ob(colladaNode, ob, this->transformation_type);
+ TransformWriter::add_node_transform_ob(colladaNode, ob, this->export_settings->export_transformation_type);
}
// <instance_geometry>
@@ -151,7 +146,10 @@ void SceneExporter::writeNodes(Object *ob, Scene *sce)
COLLADASW::InstanceGeometry instGeom(mSW);
instGeom.setUrl(COLLADASW::URI(COLLADABU::Utils::EMPTY_STRING, get_geometry_id(ob, this->export_settings->use_object_instantiation)));
instGeom.setName(translate_id(id_name(ob)));
- InstanceWriter::add_material_bindings(instGeom.getBindMaterial(), ob, this->export_settings->active_uv_only);
+ InstanceWriter::add_material_bindings(instGeom.getBindMaterial(),
+ ob,
+ this->export_settings->active_uv_only,
+ this->export_settings->export_texture_type);
instGeom.add();
}
diff --git a/source/blender/collada/SceneExporter.h b/source/blender/collada/SceneExporter.h
index c7c15dba2cb..b896b9abd8d 100644
--- a/source/blender/collada/SceneExporter.h
+++ b/source/blender/collada/SceneExporter.h
@@ -97,11 +97,8 @@ class SceneExporter: COLLADASW::LibraryVisualScenes, protected TransformWriter,
public:
SceneExporter(COLLADASW::StreamWriter *sw, ArmatureExporter *arm, const ExportSettings *export_settings);
void exportScene(Scene *sce);
- void setExportTransformationType(BC_export_transformation_type transformation_type);
private:
- BC_export_transformation_type transformation_type;
- // required for writeNodes() for bone-parented objects
friend class ArmatureExporter;
void exportHierarchy(Scene *sce);
void writeNodes(Object *ob, Scene *sce);
diff --git a/source/blender/collada/SkinInfo.cpp b/source/blender/collada/SkinInfo.cpp
index 71875d6274a..c48c060dc95 100644
--- a/source/blender/collada/SkinInfo.cpp
+++ b/source/blender/collada/SkinInfo.cpp
@@ -27,7 +27,7 @@
#include <algorithm>
-#if !defined(WIN32) || defined(FREE_WINDOWS)
+#if !defined(WIN32)
#include <stdint.h>
#endif
diff --git a/source/blender/collada/TransformReader.cpp b/source/blender/collada/TransformReader.cpp
index f8f31304d28..7f742be7e30 100644
--- a/source/blender/collada/TransformReader.cpp
+++ b/source/blender/collada/TransformReader.cpp
@@ -34,7 +34,21 @@ TransformReader::TransformReader(UnitConverter *conv) : unit_converter(conv)
/* pass */
}
-void TransformReader::get_node_mat(float mat[4][4], COLLADAFW::Node *node, std::map<COLLADAFW::UniqueId, Animation> *animation_map, Object *ob)
+void TransformReader::get_node_mat(
+ float mat[4][4],
+ COLLADAFW::Node *node,
+ std::map<COLLADAFW::UniqueId, Animation> *animation_map,
+ Object *ob)
+{
+ get_node_mat(mat, node, animation_map, ob, NULL);
+}
+
+void TransformReader::get_node_mat(
+ float mat[4][4],
+ COLLADAFW::Node *node,
+ std::map<COLLADAFW::UniqueId, Animation> *animation_map,
+ Object *ob,
+ float parent_mat[4][4])
{
float cur[4][4];
float copy[4][4];
@@ -52,6 +66,9 @@ void TransformReader::get_node_mat(float mat[4][4], COLLADAFW::Node *node, std::
// then this is considered as redundant information.
// So if we find a Matrix we use that and return.
dae_matrix_to_mat4(tm, mat);
+ if (parent_mat) {
+ mul_m4_m4m4(mat, parent_mat, mat);
+ }
return;
case COLLADAFW::Transformation::TRANSLATE:
dae_translate_to_mat4(tm, cur);
@@ -80,6 +97,10 @@ void TransformReader::get_node_mat(float mat[4][4], COLLADAFW::Node *node, std::
(*animation_map)[anim_list_id] = anim;
}
}
+
+ if (parent_mat) {
+ mul_m4_m4m4(mat, parent_mat, mat);
+ }
}
void TransformReader::dae_rotate_to_mat4(COLLADAFW::Transformation *tm, float m[4][4])
diff --git a/source/blender/collada/TransformReader.h b/source/blender/collada/TransformReader.h
index ab974b9ba85..08bb17ccac1 100644
--- a/source/blender/collada/TransformReader.h
+++ b/source/blender/collada/TransformReader.h
@@ -43,7 +43,7 @@
//struct Object;
-class TransformReader : public TransformBase
+class TransformReader
{
protected:
@@ -59,7 +59,8 @@ public:
TransformReader(UnitConverter *conv);
void get_node_mat(float mat[4][4], COLLADAFW::Node *node, std::map<COLLADAFW::UniqueId, Animation> *animation_map, Object *ob);
-
+ void get_node_mat(float mat[4][4], COLLADAFW::Node *node, std::map<COLLADAFW::UniqueId, Animation> *animation_map, Object *ob, float parent_mat[4][4]);
+
void dae_rotate_to_mat4(COLLADAFW::Transformation *tm, float m[4][4]);
void dae_translate_to_mat4(COLLADAFW::Transformation *tm, float m[4][4]);
void dae_scale_to_mat4(COLLADAFW::Transformation *tm, float m[4][4]);
diff --git a/source/blender/collada/TransformWriter.cpp b/source/blender/collada/TransformWriter.cpp
index 908111ebae6..b7eeff3b074 100644
--- a/source/blender/collada/TransformWriter.cpp
+++ b/source/blender/collada/TransformWriter.cpp
@@ -27,11 +27,10 @@
#include "BKE_object.h"
+#include "BLI_math.h"
#include "TransformWriter.h"
-#include "BLI_math.h"
-
void TransformWriter::add_node_transform(COLLADASW::Node& node, float mat[4][4], float parent_mat[4][4])
{
float loc[3], rot[3], scale[3];
@@ -51,7 +50,7 @@ void TransformWriter::add_node_transform(COLLADASW::Node& node, float mat[4][4],
converter->mat4_to_dae_double(dmat, local);
delete converter;
- TransformBase::decompose(local, loc, rot, NULL, scale);
+ bc_decompose(local, loc, rot, NULL, scale);
if (node.getType() == COLLADASW::Node::JOINT) {
// XXX Why are joints handled differently ?
@@ -116,7 +115,7 @@ void TransformWriter::add_node_transform_ob(COLLADASW::Node& node, Object *ob, B
case BC_TRANSFORMATION_TYPE_TRANSROTLOC:
{
float loc[3], rot[3], scale[3];
- TransformBase::decompose(f_obmat, loc, rot, NULL, scale);
+ bc_decompose(f_obmat, loc, rot, NULL, scale);
add_transform(node, loc, rot, scale);
break;
}
diff --git a/source/blender/collada/TransformWriter.h b/source/blender/collada/TransformWriter.h
index 7f69a4b9c95..5bb13d4aac9 100644
--- a/source/blender/collada/TransformWriter.h
+++ b/source/blender/collada/TransformWriter.h
@@ -33,9 +33,10 @@
#include "DNA_object_types.h"
#include "collada_internal.h"
+#include "collada_utils.h"
#include "collada.h"
-class TransformWriter : protected TransformBase
+class TransformWriter
{
protected:
void add_node_transform(COLLADASW::Node& node, float mat[4][4], float parent_mat[4][4]);
diff --git a/source/blender/collada/collada.cpp b/source/blender/collada/collada.cpp
index fe8b1d2320a..3794b6aefac 100644
--- a/source/blender/collada/collada.cpp
+++ b/source/blender/collada/collada.cpp
@@ -42,88 +42,27 @@ extern "C"
#include "BLI_fileops.h"
#include "BLI_linklist.h"
-int collada_import(bContext *C,
- const char *filepath,
- int import_units,
- int find_chains,
- int auto_connect,
- int fix_orientation,
- int min_chain_length)
+int collada_import(bContext *C, ImportSettings *import_settings)
{
-
- ImportSettings import_settings;
- import_settings.filepath = (char *)filepath;
- import_settings.import_units = import_units != 0;
- import_settings.auto_connect = auto_connect != 0;
- import_settings.find_chains = find_chains != 0;
- import_settings.fix_orientation = fix_orientation != 0;
- import_settings.min_chain_length = min_chain_length;
-
- DocumentImporter imp(C, &import_settings);
- if (imp.import()) return 1;
-
- return 0;
+ DocumentImporter imp(C, import_settings);
+ return (imp.import())? 1:0;
}
-int collada_export(Scene *sce,
- const char *filepath,
-
- int apply_modifiers,
- BC_export_mesh_type export_mesh_type,
-
- int selected,
- int include_children,
- int include_armatures,
- int include_shapekeys,
- int deform_bones_only,
-
- int active_uv_only,
- int include_uv_textures,
- int include_material_textures,
- int use_texture_copies,
-
- int triangulate,
- int use_object_instantiation,
- int use_blender_profile,
- int sort_by_name,
- BC_export_transformation_type export_transformation_type,
- int open_sim)
+int collada_export(EvaluationContext *eval_ctx,
+ Scene *sce,
+ ExportSettings *export_settings)
{
- ExportSettings export_settings;
-
- export_settings.filepath = (char *)filepath;
-
- export_settings.apply_modifiers = apply_modifiers != 0;
- export_settings.export_mesh_type = export_mesh_type;
- export_settings.selected = selected != 0;
- export_settings.include_children = include_children != 0;
- export_settings.include_armatures = include_armatures != 0;
- export_settings.include_shapekeys = include_shapekeys != 0;
- export_settings.deform_bones_only = deform_bones_only != 0;
-
- export_settings.active_uv_only = active_uv_only != 0;
- export_settings.include_uv_textures = include_uv_textures != 0;
- export_settings.include_material_textures= include_material_textures != 0;
- export_settings.use_texture_copies = use_texture_copies != 0;
-
- export_settings.triangulate = triangulate != 0;
- export_settings.use_object_instantiation = use_object_instantiation != 0;
- export_settings.use_blender_profile = use_blender_profile != 0;
- export_settings.sort_by_name = sort_by_name != 0;
- export_settings.export_transformation_type = export_transformation_type;
- export_settings.open_sim = open_sim != 0;
-
int includeFilter = OB_REL_NONE;
- if (export_settings.include_armatures) includeFilter |= OB_REL_MOD_ARMATURE;
- if (export_settings.include_children) includeFilter |= OB_REL_CHILDREN_RECURSIVE;
+ if (export_settings->include_armatures) includeFilter |= OB_REL_MOD_ARMATURE;
+ if (export_settings->include_children) includeFilter |= OB_REL_CHILDREN_RECURSIVE;
- eObjectSet objectSet = (export_settings.selected) ? OB_SET_SELECTED : OB_SET_ALL;
- export_settings.export_set = BKE_object_relational_superset(sce, objectSet, (eObRelationTypes)includeFilter);
- int export_count = BLI_linklist_count(export_settings.export_set);
+ eObjectSet objectSet = (export_settings->selected) ? OB_SET_SELECTED : OB_SET_ALL;
+ export_settings->export_set = BKE_object_relational_superset(sce, objectSet, (eObRelationTypes)includeFilter);
+ int export_count = BLI_linklist_count(export_settings->export_set);
if (export_count == 0) {
- if (export_settings.selected) {
+ if (export_settings->selected) {
fprintf(stderr, "Collada: Found no objects to export.\nPlease ensure that all objects which shall be exported are also visible in the 3D Viewport.\n");
}
else {
@@ -131,14 +70,14 @@ int collada_export(Scene *sce,
}
}
else {
- if (export_settings.sort_by_name)
- bc_bubble_sort_by_Object_name(export_settings.export_set);
+ if (export_settings->sort_by_name)
+ bc_bubble_sort_by_Object_name(export_settings->export_set);
}
- DocumentExporter exporter(&export_settings);
- int status = exporter.exportCurrentScene(sce);
+ DocumentExporter exporter(export_settings);
+ int status = exporter.exportCurrentScene(eval_ctx, sce);
- BLI_linklist_free(export_settings.export_set, NULL);
+ BLI_linklist_free(export_settings->export_set, NULL);
return (status) ? -1:export_count;
}
diff --git a/source/blender/collada/collada.h b/source/blender/collada/collada.h
index a4416608584..312f11d4ba9 100644
--- a/source/blender/collada/collada.h
+++ b/source/blender/collada/collada.h
@@ -28,24 +28,21 @@
#define __COLLADA_H__
#include <stdlib.h>
+
+#include "ImportSettings.h"
+#include "ExportSettings.h"
+
#ifdef __cplusplus
extern "C" {
#endif
+#include "BKE_depsgraph.h"
#include "BLI_linklist.h"
#include "BLI_path_util.h"
#include "RNA_types.h"
-typedef enum BC_export_mesh_type {
- BC_MESH_TYPE_VIEW,
- BC_MESH_TYPE_RENDER
-} BC_export_mesh_type;
-
-typedef enum BC_export_transformation_type {
- BC_TRANSFORMATION_TYPE_MATRIX,
- BC_TRANSFORMATION_TYPE_TRANSROTLOC
-} BC_export_transformation_type;
+struct EvaluationContext;
struct bContext;
struct Scene;
@@ -53,37 +50,11 @@ struct Scene;
* both return 1 on success, 0 on error
*/
int collada_import(struct bContext *C,
- const char *filepath,
- int import_units,
- int find_chains,
- int auto_connect,
- int fix_orientation,
- int min_chain_length);
-
-int collada_export(struct Scene *sce,
- const char *filepath,
- int apply_modifiers,
- BC_export_mesh_type export_mesh_type,
-
- int selected,
- int include_children,
- int include_armatures,
- int include_shapekeys,
- int deform_bones_only,
-
- int active_uv_only,
- int include_uv_textures,
- int include_material_textures,
- int use_texture_copies,
-
- int triangulate,
- int use_object_instantiation,
- int use_blender_profile,
- int sort_by_name,
- BC_export_transformation_type export_transformation_type,
- int open_sim);
-
+ ImportSettings *import_settings);
+int collada_export(struct EvaluationContext *eval_ctx,
+ struct Scene *sce,
+ ExportSettings *export_settings);
#ifdef __cplusplus
}
diff --git a/source/blender/collada/collada_internal.cpp b/source/blender/collada/collada_internal.cpp
index e1a13559b08..f2cc56777d8 100644
--- a/source/blender/collada/collada_internal.cpp
+++ b/source/blender/collada/collada_internal.cpp
@@ -162,18 +162,6 @@ void UnitConverter::calculate_scale(Scene &sce)
size_to_mat4(scale_mat4, rescale);
}
-void TransformBase::decompose(float mat[4][4], float *loc, float eul[3], float quat[4], float *size)
-{
- mat4_to_size(size, mat);
- if (eul) {
- mat4_to_eul(eul, mat);
- }
- if (quat) {
- mat4_to_quat(quat, mat);
- }
- copy_v3_v3(loc, mat[3]);
-}
-
/**
* Translation map.
* Used to translate every COLLADA id to a valid id, no matter what "wrong" letters may be
@@ -339,9 +327,14 @@ std::string get_light_id(Object *ob)
return translate_id(id_name(ob)) + "-light";
}
-std::string get_joint_id(Bone *bone, Object *ob_arm)
+std::string get_joint_id(Object *ob, Bone *bone)
{
- return translate_id(/*id_name(ob_arm) + "_" +*/ bone->name);
+ return translate_id(id_name(ob) + "_" + bone->name);
+}
+
+std::string get_joint_sid(Bone *bone)
+{
+ return translate_id(bone->name);
}
std::string get_camera_id(Object *ob)
@@ -351,7 +344,13 @@ std::string get_camera_id(Object *ob)
std::string get_material_id(Material *mat)
{
- return translate_id(id_name(mat)) + "-material";
+ std::string id = id_name(mat);
+ return get_material_id_from_id(id);
+}
+
+std::string get_material_id_from_id(std::string id)
+{
+ return translate_id(id) + "-material";
}
std::string get_morph_id(Object *ob)
diff --git a/source/blender/collada/collada_internal.h b/source/blender/collada/collada_internal.h
index 4aa637a6876..fc848100b79 100644
--- a/source/blender/collada/collada_internal.h
+++ b/source/blender/collada/collada_internal.h
@@ -85,12 +85,6 @@ public:
};
-class TransformBase
-{
-public:
- void decompose(float mat[4][4], float *loc, float eul[3], float quat[4], float *size);
-};
-
extern void clear_global_id_map();
/** Look at documentation of translate_map */
extern std::string translate_id(const std::string &id);
@@ -103,11 +97,13 @@ extern std::string get_geometry_id(Object *ob, bool use_instantiation);
extern std::string get_light_id(Object *ob);
-extern std::string get_joint_id(Bone *bone, Object *ob_arm);
+extern std::string get_joint_id(Object *ob, Bone *bone);
+extern std::string get_joint_sid(Bone *bone);
extern std::string get_camera_id(Object *ob);
extern std::string get_material_id(Material *mat);
+extern std::string get_material_id_from_id(std::string id);
extern std::string get_morph_id(Object *ob);
diff --git a/source/blender/collada/collada_utils.cpp b/source/blender/collada/collada_utils.cpp
index 2efa8b21d81..8c4ddd67d07 100644
--- a/source/blender/collada/collada_utils.cpp
+++ b/source/blender/collada/collada_utils.cpp
@@ -32,7 +32,7 @@
#include "COLLADAFWMeshPrimitive.h"
#include "COLLADAFWMeshVertexData.h"
-#include "collada_utils.h"
+#include <set>
extern "C" {
#include "DNA_modifier_types.h"
@@ -53,6 +53,7 @@ extern "C" {
#include "BKE_mesh.h"
#include "BKE_scene.h"
#include "BKE_DerivedMesh.h"
+#include "BKE_main.h"
#include "ED_armature.h"
@@ -63,6 +64,9 @@ extern "C" {
#include "bmesh_tools.h"
}
+#include "collada_utils.h"
+#include "ExportSettings.h"
+
float bc_get_float_value(const COLLADAFW::FloatOrDoubleArray& array, unsigned int index)
{
if (index >= array.getValuesCount())
@@ -129,6 +133,25 @@ int bc_set_parent(Object *ob, Object *par, bContext *C, bool is_parent_space)
return true;
}
+Main *bc_get_main()
+{
+ return G.main;
+}
+
+EvaluationContext *bc_get_evaluation_context()
+{
+ Main *bmain = G.main;
+ return bmain->eval_ctx;
+}
+
+void bc_update_scene(Scene *scene, float ctime)
+{
+ BKE_scene_frame_set(scene, ctime);
+ Main *bmain = bc_get_main();
+ EvaluationContext *ev_context = bc_get_evaluation_context();
+ BKE_scene_update_for_newframe(ev_context, bmain, scene, scene->lay);
+}
+
Object *bc_add_object(Scene *scene, int type, const char *name)
{
Object *ob = BKE_object_add_only_object(G.main, type, name);
@@ -352,6 +375,57 @@ void bc_match_scale(std::vector<Object *> *objects_done,
}
}
+/*
+ Convenience function to get only the needed components of a matrix
+*/
+void bc_decompose(float mat[4][4], float *loc, float eul[3], float quat[4], float *size)
+{
+ if (size) {
+ mat4_to_size(size, mat);
+ }
+
+ if (eul) {
+ mat4_to_eul(eul, mat);
+ }
+
+ if (quat) {
+ mat4_to_quat(quat, mat);
+ }
+
+ if (loc) {
+ copy_v3_v3(loc, mat[3]);
+ }
+}
+
+/*
+* Create rotation_quaternion from a delta rotation and a reference quat
+*
+* Input:
+* mat_from: The rotation matrix before rotation
+* mat_to : The rotation matrix after rotation
+* qref : the quat corresponding to mat_from
+*
+* Output:
+* rot : the calculated result (quaternion)
+*
+*/
+void bc_rotate_from_reference_quat(float quat_to[4], float quat_from[4], float mat_to[4][4])
+{
+ float qd[4];
+ float matd[4][4];
+ float mati[4][4];
+ float mat_from[4][4];
+ quat_to_mat4(mat_from, quat_from);
+
+ // Calculate the difference matrix matd between mat_from and mat_to
+ invert_m4_m4(mati, mat_from);
+ mul_m4_m4m4(matd, mati, mat_to);
+
+ mat4_to_quat(qd, matd);
+
+ mul_qt_qtqt(quat_to, qd, quat_from); // rot is the final rotation corresponding to mat_to
+}
+
void bc_triangulate_mesh(Mesh *me)
{
bool use_beauty = false;
@@ -612,3 +686,384 @@ int BoneExtended::get_use_connect()
{
return this->use_connect;
}
+
+/**
+* Stores a 4*4 matrix as a custom bone property array of size 16
+*/
+void bc_set_IDPropertyMatrix(EditBone *ebone, const char *key, float mat[4][4])
+{
+ IDProperty *idgroup = (IDProperty *)ebone->prop;
+ if (idgroup == NULL)
+ {
+ IDPropertyTemplate val = { 0 };
+ idgroup = IDP_New(IDP_GROUP, &val, "RNA_EditBone ID properties");
+ ebone->prop = idgroup;
+ }
+
+ IDPropertyTemplate val = { 0 };
+ val.array.len = 16;
+ val.array.type = IDP_FLOAT;
+
+ IDProperty *data = IDP_New(IDP_ARRAY, &val, key);
+ float *array = (float *)IDP_Array(data);
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ array[4 * i + j] = mat[i][j];
+
+ IDP_AddToGroup(idgroup, data);
+}
+
+#if 0
+/**
+* Stores a Float value as a custom bone property
+*
+* Note: This function is currently not needed. Keep for future usage
+*/
+static void bc_set_IDProperty(EditBone *ebone, const char *key, float value)
+{
+ if (ebone->prop == NULL)
+ {
+ IDPropertyTemplate val = { 0 };
+ ebone->prop = IDP_New(IDP_GROUP, &val, "RNA_EditBone ID properties");
+ }
+
+ IDProperty *pgroup = (IDProperty *)ebone->prop;
+ IDPropertyTemplate val = { 0 };
+ IDProperty *prop = IDP_New(IDP_FLOAT, &val, key);
+ IDP_Float(prop) = value;
+ IDP_AddToGroup(pgroup, prop);
+
+}
+#endif
+
+/*
+* Get a custom property when it exists.
+* This function is also used to check if a property exists.
+*/
+IDProperty *bc_get_IDProperty(Bone *bone, std::string key)
+{
+ return (bone->prop == NULL) ? NULL : IDP_GetPropertyFromGroup(bone->prop, key.c_str());
+}
+
+/**
+* Read a custom bone property and convert to float
+* Return def if the property does not exist.
+*/
+float bc_get_property(Bone *bone, std::string key, float def)
+{
+ float result = def;
+ IDProperty *property = bc_get_IDProperty(bone, key);
+ if (property) {
+ switch (property->type) {
+ case IDP_INT:
+ result = (float)(IDP_Int(property));
+ break;
+ case IDP_FLOAT:
+ result = (float)(IDP_Float(property));
+ break;
+ case IDP_DOUBLE:
+ result = (float)(IDP_Double(property));
+ break;
+ default:
+ result = def;
+ }
+ }
+ return result;
+}
+
+/**
+* Read a custom bone property and convert to matrix
+* Return true if conversion was succesfull
+*
+* Return false if:
+* - the property does not exist
+* - is not an array of size 16
+*/
+bool bc_get_property_matrix(Bone *bone, std::string key, float mat[4][4])
+{
+ IDProperty *property = bc_get_IDProperty(bone, key);
+ if (property && property->type == IDP_ARRAY && property->len == 16) {
+ float *array = (float *)IDP_Array(property);
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ mat[i][j] = array[4 * i + j];
+ return true;
+ }
+ return false;
+}
+
+/**
+* get a vector that is stored in 3 custom properties (used in Blender <= 2.78)
+*/
+void bc_get_property_vector(Bone *bone, std::string key, float val[3], const float def[3])
+{
+ val[0] = bc_get_property(bone, key + "_x", def[0]);
+ val[1] = bc_get_property(bone, key + "_y", def[1]);
+ val[2] = bc_get_property(bone, key + "_z", def[2]);
+}
+
+/**
+* Check if vector exist stored in 3 custom properties (used in Blender <= 2.78)
+*/
+static bool has_custom_props(Bone *bone, bool enabled, std::string key)
+{
+ if (!enabled)
+ return false;
+
+ return (bc_get_IDProperty(bone, key + "_x")
+ || bc_get_IDProperty(bone, key + "_y")
+ || bc_get_IDProperty(bone, key + "_z"));
+
+}
+
+/**
+* Check if custom information about bind matrix exists and modify the from_mat
+* accordingly.
+*
+* Note: This is old style for Blender <= 2.78 only kept for compatibility
+*/
+void bc_create_restpose_mat(const ExportSettings *export_settings, Bone *bone, float to_mat[4][4], float from_mat[4][4], bool use_local_space)
+{
+ float loc[3];
+ float rot[3];
+ float scale[3];
+ static const float V0[3] = { 0, 0, 0 };
+
+ if (!has_custom_props(bone, export_settings->keep_bind_info, "restpose_loc") &&
+ !has_custom_props(bone, export_settings->keep_bind_info, "restpose_rot") &&
+ !has_custom_props(bone, export_settings->keep_bind_info, "restpose_scale"))
+ {
+ /* No need */
+ copy_m4_m4(to_mat, from_mat);
+ return;
+ }
+
+ bc_decompose(from_mat, loc, rot, NULL, scale);
+ loc_eulO_size_to_mat4(to_mat, loc, rot, scale, 6);
+
+ if (export_settings->keep_bind_info) {
+ bc_get_property_vector(bone, "restpose_loc", loc, loc);
+
+ if (use_local_space && bone->parent) {
+ Bone *b = bone;
+ while (b->parent) {
+ b = b->parent;
+ float ploc[3];
+ bc_get_property_vector(b, "restpose_loc", ploc, V0);
+ loc[0] += ploc[0];
+ loc[1] += ploc[1];
+ loc[2] += ploc[2];
+ }
+ }
+ }
+
+ if (export_settings->keep_bind_info) {
+ if (bc_get_IDProperty(bone, "restpose_rot_x"))
+ rot[0] = DEG2RADF(bc_get_property(bone, "restpose_rot_x", 0));
+ if (bc_get_IDProperty(bone, "restpose_rot_y"))
+ rot[1] = DEG2RADF(bc_get_property(bone, "restpose_rot_y", 0));
+ if (bc_get_IDProperty(bone, "restpose_rot_z"))
+ rot[2] = DEG2RADF(bc_get_property(bone, "restpose_rot_z", 0));
+ }
+
+ if (export_settings->keep_bind_info) {
+ bc_get_property_vector(bone, "restpose_scale", scale, scale);
+ }
+
+ loc_eulO_size_to_mat4(to_mat, loc, rot, scale, 6);
+
+}
+
+/*
+ Make 4*4 matrices better readable
+*/
+void bc_sanitize_mat(float mat[4][4], int precision)
+{
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ mat[i][j] = double_round(mat[i][j], precision);
+}
+
+void bc_sanitize_mat(double mat[4][4], int precision)
+{
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ mat[i][j] = double_round(mat[i][j], precision);
+}
+
+void bc_copy_m4_farray(float r[4][4], float *a)
+{
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ r[i][j] = *a++;
+}
+
+void bc_copy_farray_m4(float *r, float a[4][4])
+{
+ for (int i = 0; i < 4; i++)
+ for (int j = 0; j < 4; j++)
+ *r++ = a[i][j];
+
+}
+
+/*
+* Returns name of Active UV Layer or empty String if no active UV Layer defined.
+* Assuming the Object is of type MESH
+*/
+std::string bc_get_active_uvlayer_name(Object *ob)
+{
+ Mesh *me = (Mesh *)ob->data;
+ return bc_get_active_uvlayer_name(me);
+}
+
+/*
+ * Returns name of Active UV Layer or empty String if no active UV Layer defined
+ */
+std::string bc_get_active_uvlayer_name(Mesh *me)
+{
+ int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
+ if (num_layers) {
+ char *layer_name = bc_CustomData_get_active_layer_name(&me->fdata, CD_MTFACE);
+ if (layer_name) {
+ return std::string(layer_name);
+ }
+ }
+ return "";
+}
+
+/*
+ * Returns UV Layer name or empty string if layer index is out of range
+ */
+std::string bc_get_uvlayer_name(Mesh *me, int layer)
+{
+ int num_layers = CustomData_number_of_layers(&me->fdata, CD_MTFACE);
+ if (num_layers && layer < num_layers) {
+ char *layer_name = bc_CustomData_get_layer_name(&me->fdata, CD_MTFACE, layer);
+ if (layer_name) {
+ return std::string(layer_name);
+ }
+ }
+ return "";
+}
+
+/**********************************************************************
+*
+* Return the list of Mesh objects with assigned UVtextures and Images
+* Note: We need to create artificaial materials for each of them
+*
+***********************************************************************/
+std::set<Object *> bc_getUVTexturedObjects(Scene *sce, bool all_uv_layers)
+{
+ std::set <Object *> UVObjects;
+ Base *base = (Base *)sce->base.first;
+
+ while (base) {
+ Object *ob = base->object;
+ bool has_uvimage = false;
+ if (ob->type == OB_MESH) {
+ Mesh *me = (Mesh *)ob->data;
+ int active_uv_layer = CustomData_get_active_layer_index(&me->pdata, CD_MTEXPOLY);
+
+ for (int i = 0; i < me->pdata.totlayer && !has_uvimage; i++) {
+ if (all_uv_layers || active_uv_layer == i)
+ {
+ if (me->pdata.layers[i].type == CD_MTEXPOLY) {
+ MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
+ MPoly *mpoly = me->mpoly;
+ for (int j = 0; j < me->totpoly; j++, mpoly++, txface++) {
+
+ Image *ima = txface->tpage;
+ if (ima != NULL) {
+ has_uvimage = true;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ if (has_uvimage) {
+ UVObjects.insert(ob);
+ }
+ }
+ base = base->next;
+ }
+ return UVObjects;
+}
+
+/**********************************************************************
+*
+* Return the list of UV Texture images from all exported Mesh Items
+* Note: We need to create one artificial material for each Image.
+*
+***********************************************************************/
+std::set<Image *> bc_getUVImages(Scene *sce, bool all_uv_layers)
+{
+ std::set <Image *> UVImages;
+ Base *base = (Base *)sce->base.first;
+
+ while (base) {
+ Object *ob = base->object;
+ bool has_uvimage = false;
+ if (ob->type == OB_MESH) {
+ Mesh *me = (Mesh *)ob->data;
+ int active_uv_layer = CustomData_get_active_layer_index(&me->pdata, CD_MTEXPOLY);
+
+ for (int i = 0; i < me->pdata.totlayer && !has_uvimage; i++) {
+ if (all_uv_layers || active_uv_layer == i)
+ {
+ if (me->pdata.layers[i].type == CD_MTEXPOLY) {
+ MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
+ MPoly *mpoly = me->mpoly;
+ for (int j = 0; j < me->totpoly; j++, mpoly++, txface++) {
+
+ Image *ima = txface->tpage;
+ if (ima != NULL) {
+ if (UVImages.find(ima) == UVImages.end())
+ UVImages.insert(ima);
+ }
+ }
+ }
+ }
+ }
+ }
+ base = base->next;
+ }
+ return UVImages;
+}
+
+/**********************************************************************
+*
+* Return the list of UV Texture images for the given Object
+* Note: We need to create one artificial material for each Image.
+*
+***********************************************************************/
+std::set<Image *> bc_getUVImages(Object *ob, bool all_uv_layers)
+{
+ std::set <Image *> UVImages;
+
+ bool has_uvimage = false;
+ if (ob->type == OB_MESH) {
+ Mesh *me = (Mesh *)ob->data;
+ int active_uv_layer = CustomData_get_active_layer_index(&me->pdata, CD_MTEXPOLY);
+
+ for (int i = 0; i < me->pdata.totlayer && !has_uvimage; i++) {
+ if (all_uv_layers || active_uv_layer == i)
+ {
+ if (me->pdata.layers[i].type == CD_MTEXPOLY) {
+ MTexPoly *txface = (MTexPoly *)me->pdata.layers[i].data;
+ MPoly *mpoly = me->mpoly;
+ for (int j = 0; j < me->totpoly; j++, mpoly++, txface++) {
+
+ Image *ima = txface->tpage;
+ if (ima != NULL) {
+ if (UVImages.find(ima) == UVImages.end())
+ UVImages.insert(ima);
+ }
+ }
+ }
+ }
+ }
+ }
+ return UVImages;
+}
diff --git a/source/blender/collada/collada_utils.h b/source/blender/collada/collada_utils.h
index 7fdbef3b6cb..0069b4d4871 100644
--- a/source/blender/collada/collada_utils.h
+++ b/source/blender/collada/collada_utils.h
@@ -34,6 +34,7 @@
#include <vector>
#include <map>
+#include <set>
#include <algorithm>
extern "C" {
@@ -53,13 +54,19 @@ extern "C" {
#include "BKE_object.h"
#include "BKE_DerivedMesh.h"
#include "BKE_scene.h"
+#include "BKE_idprop.h"
}
+#include "ImportSettings.h"
#include "ExportSettings.h"
#include "collada_internal.h"
typedef std::map<COLLADAFW::TextureMapId, std::vector<MTex *> > TexIndexTextureArrayMap;
+extern Main *bc_get_main();
+extern EvaluationContext *bc_get_evaluation_context();
+extern void bc_update_scene(Scene *scene, float ctime);
+
extern float bc_get_float_value(const COLLADAFW::FloatOrDoubleArray& array, unsigned int index);
extern int bc_test_parent_loop(Object *par, Object *ob);
extern int bc_set_parent(Object *ob, Object *par, bContext *C, bool is_parent_space = true);
@@ -88,12 +95,42 @@ extern std::string bc_url_encode(std::string data);
extern void bc_match_scale(Object *ob, UnitConverter &bc_unit, bool scale_to_scene);
extern void bc_match_scale(std::vector<Object *> *objects_done, UnitConverter &unit_converter, bool scale_to_scene);
+extern void bc_decompose(float mat[4][4], float *loc, float eul[3], float quat[4], float *size);
+extern void bc_rotate_from_reference_quat(float quat_to[4], float quat_from[4], float mat_to[4][4]);
+
extern void bc_triangulate_mesh(Mesh *me);
extern bool bc_is_leaf_bone(Bone *bone);
extern EditBone *bc_get_edit_bone(bArmature * armature, char *name);
extern int bc_set_layer(int bitfield, int layer, bool enable);
extern int bc_set_layer(int bitfield, int layer);
+inline bool bc_in_range(float a, float b, float range) {
+ return fabsf(a - b) < range;
+}
+void bc_copy_m4_farray(float r[4][4], float *a);
+void bc_copy_farray_m4(float *r, float a[4][4]);
+
+extern void bc_sanitize_mat(float mat[4][4], int precision);
+extern void bc_sanitize_mat(double mat[4][4], int precision);
+
+extern IDProperty *bc_get_IDProperty(Bone *bone, std::string key);
+extern void bc_set_IDProperty(EditBone *ebone, const char *key, float value);
+extern void bc_set_IDPropertyMatrix(EditBone *ebone, const char *key, float mat[4][4]);
+
+extern float bc_get_property(Bone *bone, std::string key, float def);
+extern void bc_get_property_vector(Bone *bone, std::string key, float val[3], const float def[3]);
+extern bool bc_get_property_matrix(Bone *bone, std::string key, float mat[4][4]);
+
+extern void bc_create_restpose_mat(const ExportSettings *export_settings, Bone *bone, float to_mat[4][4], float world[4][4], bool use_local_space);
+
+extern std::string bc_get_active_uvlayer_name(Object *ob);
+extern std::string bc_get_active_uvlayer_name(Mesh *me);
+extern std::string bc_get_uvlayer_name(Mesh *me, int layer);
+
+extern std::set<Image *> bc_getUVImages(Scene *sce, bool all_uv_layers);
+extern std::set<Image *> bc_getUVImages(Object *ob, bool all_uv_layers);
+extern std::set<Object *> bc_getUVTexturedObjects(Scene *sce, bool all_uv_layers);
+
class BCPolygonNormalsIndices
{
std::vector<unsigned int> normal_indices;
diff --git a/source/blender/compositor/CMakeLists.txt b/source/blender/compositor/CMakeLists.txt
index 3180e7e4154..3e1dd83112a 100644
--- a/source/blender/compositor/CMakeLists.txt
+++ b/source/blender/compositor/CMakeLists.txt
@@ -551,8 +551,4 @@ if(WITH_INTERNATIONAL)
add_definitions(-DWITH_INTERNATIONAL)
endif()
-if(WITH_CYCLES AND WITH_CYCLES_DEBUG)
- add_definitions(-DWITH_CYCLES_DEBUG)
-endif()
-
blender_add_lib(bf_compositor "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/compositor/COM_compositor.h b/source/blender/compositor/COM_compositor.h
index a5d7704a708..3b24f9c69a2 100644
--- a/source/blender/compositor/COM_compositor.h
+++ b/source/blender/compositor/COM_compositor.h
@@ -331,19 +331,6 @@ void COM_deinitialize(void);
*/
// void COM_clearCaches(void); // NOT YET WRITTEN
-/**
- * @brief Return a list of highlighted bnodes pointers.
- * @return
- */
-void COM_startReadHighlights(void);
-
-/**
- * @brief check if a bnode is highlighted
- * @param bnode
- * @return
- */
-int COM_isHighlightedbNode(bNode *bnode);
-
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/compositor/intern/COM_Debug.cpp b/source/blender/compositor/intern/COM_Debug.cpp
index a7b464cde29..68439ff8469 100644
--- a/source/blender/compositor/intern/COM_Debug.cpp
+++ b/source/blender/compositor/intern/COM_Debug.cpp
@@ -28,9 +28,11 @@
#include <vector>
extern "C" {
+#include "BLI_sys_types.h"
#include "BLI_fileops.h"
#include "BLI_path_util.h"
#include "BLI_string.h"
+
#include "DNA_node_types.h"
#include "BKE_appdir.h"
#include "BKE_node.h"
@@ -174,7 +176,7 @@ int DebugInfo::graphviz_operation(const ExecutionSystem *system, const NodeOpera
len += snprintf(str + len, maxlen > len ? maxlen - len : 0, "%s\\n(%s)", m_op_names[operation].c_str(), typeid(*operation).name());
- len += snprintf(str + len, maxlen > len ? maxlen - len : 0, " (%d,%d)", operation->getWidth(), operation->getHeight());
+ len += snprintf(str + len, maxlen > len ? maxlen - len : 0, " (%u,%u)", operation->getWidth(), operation->getHeight());
int totoutputs = operation->getNumberOfOutputSockets();
if (totoutputs != 0) {
diff --git a/source/blender/compositor/intern/COM_ExecutionGroup.h b/source/blender/compositor/intern/COM_ExecutionGroup.h
index 99365cdd4a8..d3b11accd96 100644
--- a/source/blender/compositor/intern/COM_ExecutionGroup.h
+++ b/source/blender/compositor/intern/COM_ExecutionGroup.h
@@ -64,7 +64,7 @@ typedef enum ChunkExecutionState {
*/
class ExecutionGroup {
public:
- typedef std::vector<NodeOperation*> Operations;
+ typedef std::vector<NodeOperation*> Operations;
private:
// fields
diff --git a/source/blender/compositor/intern/COM_WorkScheduler.cpp b/source/blender/compositor/intern/COM_WorkScheduler.cpp
index 39147f3ab84..e2dc289eb1c 100644
--- a/source/blender/compositor/intern/COM_WorkScheduler.cpp
+++ b/source/blender/compositor/intern/COM_WorkScheduler.cpp
@@ -75,82 +75,6 @@ static bool g_openclInitialized = false;
#endif
#endif
-#define MAX_HIGHLIGHT 8
-static bool g_highlightInitialized = false;
-extern "C" {
-static int g_highlightIndex;
-static void **g_highlightedNodes;
-static void **g_highlightedNodesRead;
-
-/* XXX highlighting disabled for now
- * This requires pointers back to DNA data (bNodeTree/bNode) in operations, which is bad!
- * Instead IF we want to keep this feature it should use a weak reference such as bNodeInstanceKey
- */
-#if 0
-#if COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE
-#define HIGHLIGHT(wp) \
-{ \
- ExecutionGroup *group = wp->getExecutionGroup(); \
- if (group->isComplex()) { \
- NodeOperation *operation = group->getOutputOperation(); \
- if (operation->isWriteBufferOperation()) { \
- WriteBufferOperation *writeOperation = (WriteBufferOperation *)operation; \
- NodeOperation *complexOperation = writeOperation->getInput(); \
- bNode *node = complexOperation->getbNode(); \
- if (node) { \
- if (node->original) { \
- node = node->original; \
- } \
- if (g_highlightInitialized && g_highlightedNodes) { \
- if (g_highlightIndex < MAX_HIGHLIGHT) { \
- g_highlightedNodes[g_highlightIndex++] = node; \
- } \
- } \
- } \
- } \
- } \
-}
-#endif /* COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE */
-#else
-# if COM_CURRENT_THREADING_MODEL != COM_TM_NOTHREAD
-#define HIGHLIGHT(wp) {}
-# endif
-#endif
-
-void COM_startReadHighlights()
-{
- if (!g_highlightInitialized) {
- return;
- }
-
- if (g_highlightedNodesRead) {
- MEM_freeN(g_highlightedNodesRead);
- }
-
- g_highlightedNodesRead = g_highlightedNodes;
- g_highlightedNodes = (void **)MEM_callocN(sizeof(void *) * MAX_HIGHLIGHT, __func__);
- g_highlightIndex = 0;
-}
-
-int COM_isHighlightedbNode(bNode *bnode)
-{
- if (!g_highlightInitialized) {
- return false;
- }
-
- if (!g_highlightedNodesRead) {
- return false;
- }
-
- for (int i = 0; i < MAX_HIGHLIGHT; i++) {
- void *p = g_highlightedNodesRead[i];
- if (!p) return false;
- if (p == bnode) return true;
- }
- return false;
-}
-} // end extern "C"
-
#if COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE
void *WorkScheduler::thread_execute_cpu(void *data)
{
@@ -158,7 +82,6 @@ void *WorkScheduler::thread_execute_cpu(void *data)
WorkPackage *work;
BLI_thread_local_set(g_thread_device, device);
while ((work = (WorkPackage *)BLI_thread_queue_pop(g_cpuqueue))) {
- HIGHLIGHT(work);
device->execute(work);
delete work;
}
@@ -172,7 +95,6 @@ void *WorkScheduler::thread_execute_gpu(void *data)
WorkPackage *work;
while ((work = (WorkPackage *)BLI_thread_queue_pop(g_gpuqueue))) {
- HIGHLIGHT(work);
device->execute(work);
delete work;
}
@@ -209,18 +131,18 @@ void WorkScheduler::start(CompositorContext &context)
#if COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE
unsigned int index;
g_cpuqueue = BLI_thread_queue_init();
- BLI_init_threads(&g_cputhreads, thread_execute_cpu, g_cpudevices.size());
+ BLI_threadpool_init(&g_cputhreads, thread_execute_cpu, g_cpudevices.size());
for (index = 0; index < g_cpudevices.size(); index++) {
Device *device = g_cpudevices[index];
- BLI_insert_thread(&g_cputhreads, device);
+ BLI_threadpool_insert(&g_cputhreads, device);
}
#ifdef COM_OPENCL_ENABLED
if (context.getHasActiveOpenCLDevices()) {
g_gpuqueue = BLI_thread_queue_init();
- BLI_init_threads(&g_gputhreads, thread_execute_gpu, g_gpudevices.size());
+ BLI_threadpool_init(&g_gputhreads, thread_execute_gpu, g_gpudevices.size());
for (index = 0; index < g_gpudevices.size(); index++) {
Device *device = g_gpudevices[index];
- BLI_insert_thread(&g_gputhreads, device);
+ BLI_threadpool_insert(&g_gputhreads, device);
}
g_openclActive = true;
}
@@ -250,13 +172,13 @@ void WorkScheduler::stop()
{
#if COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE
BLI_thread_queue_nowait(g_cpuqueue);
- BLI_end_threads(&g_cputhreads);
+ BLI_threadpool_end(&g_cputhreads);
BLI_thread_queue_free(g_cpuqueue);
g_cpuqueue = NULL;
#ifdef COM_OPENCL_ENABLED
if (g_openclActive) {
BLI_thread_queue_nowait(g_gpuqueue);
- BLI_end_threads(&g_gputhreads);
+ BLI_threadpool_end(&g_gputhreads);
BLI_thread_queue_free(g_gpuqueue);
g_gpuqueue = NULL;
}
@@ -289,19 +211,6 @@ static void CL_CALLBACK clContextError(const char *errinfo,
void WorkScheduler::initialize(bool use_opencl, int num_cpu_threads)
{
- /* initialize highlighting */
- if (!g_highlightInitialized) {
- if (g_highlightedNodesRead) MEM_freeN(g_highlightedNodesRead);
- if (g_highlightedNodes) MEM_freeN(g_highlightedNodes);
-
- g_highlightedNodesRead = NULL;
- g_highlightedNodes = NULL;
-
- COM_startReadHighlights();
-
- g_highlightInitialized = true;
- }
-
#if COM_CURRENT_THREADING_MODEL == COM_TM_QUEUE
/* deinitialize if number of threads doesn't match */
if (g_cpudevices.size() != num_cpu_threads) {
@@ -439,20 +348,6 @@ void WorkScheduler::deinitialize()
}
#endif
#endif
-
- /* deinitialize highlighting */
- if (g_highlightInitialized) {
- g_highlightInitialized = false;
- if (g_highlightedNodes) {
- MEM_freeN(g_highlightedNodes);
- g_highlightedNodes = NULL;
- }
-
- if (g_highlightedNodesRead) {
- MEM_freeN(g_highlightedNodesRead);
- g_highlightedNodesRead = NULL;
- }
- }
}
int WorkScheduler::current_thread_id()
diff --git a/source/blender/compositor/intern/COM_compositor.cpp b/source/blender/compositor/intern/COM_compositor.cpp
index e3dfd69d8ec..40db5efda27 100644
--- a/source/blender/compositor/intern/COM_compositor.cpp
+++ b/source/blender/compositor/intern/COM_compositor.cpp
@@ -64,9 +64,21 @@ void COM_execute(RenderData *rd, Scene *scene, bNodeTree *editingtree, int rende
/* Make sure node tree has previews.
* Don't create previews in advance, this is done when adding preview operations.
* Reserved preview size is determined by render output for now.
+ *
+ * We fit the aspect into COM_PREVIEW_SIZE x COM_PREVIEW_SIZE image to avoid
+ * insane preview resolution, which might even overflow preview dimensions.
*/
- float aspect = rd->xsch > 0 ? (float)rd->ysch / (float)rd->xsch : 1.0f;
- BKE_node_preview_init_tree(editingtree, COM_PREVIEW_SIZE, (int)(COM_PREVIEW_SIZE * aspect), false);
+ const float aspect = rd->xsch > 0 ? (float)rd->ysch / (float)rd->xsch : 1.0f;
+ int preview_width, preview_height;
+ if (aspect < 1.0f) {
+ preview_width = COM_PREVIEW_SIZE;
+ preview_height = (int)(COM_PREVIEW_SIZE * aspect);
+ }
+ else {
+ preview_width = (int)(COM_PREVIEW_SIZE / aspect);
+ preview_height = COM_PREVIEW_SIZE;
+ }
+ BKE_node_preview_init_tree(editingtree, preview_width, preview_height, false);
/* initialize workscheduler, will check if already done. TODO deinitialize somewhere */
bool use_opencl = (editingtree->flag & NTREE_COM_OPENCL) != 0;
diff --git a/source/blender/compositor/nodes/COM_BrightnessNode.cpp b/source/blender/compositor/nodes/COM_BrightnessNode.cpp
index 053f286c66e..6729571fac0 100644
--- a/source/blender/compositor/nodes/COM_BrightnessNode.cpp
+++ b/source/blender/compositor/nodes/COM_BrightnessNode.cpp
@@ -31,7 +31,9 @@ BrightnessNode::BrightnessNode(bNode *editorNode) : Node(editorNode)
void BrightnessNode::convertToOperations(NodeConverter &converter, const CompositorContext &/*context*/) const
{
+ bNode *bnode = this->getbNode();
BrightnessOperation *operation = new BrightnessOperation();
+ operation->setUsePremultiply((bnode->custom1 & 1) != 0);
converter.addOperation(operation);
converter.mapInputSocket(getInputSocket(0), operation->getInputSocket(0));
diff --git a/source/blender/compositor/nodes/COM_CompositorNode.cpp b/source/blender/compositor/nodes/COM_CompositorNode.cpp
index 9e8b40d8af4..4754f23a167 100644
--- a/source/blender/compositor/nodes/COM_CompositorNode.cpp
+++ b/source/blender/compositor/nodes/COM_CompositorNode.cpp
@@ -41,6 +41,7 @@ void CompositorNode::convertToOperations(NodeConverter &converter, const Composi
NodeInput *depthSocket = this->getInputSocket(2);
CompositorOperation *compositorOperation = new CompositorOperation();
+ compositorOperation->setScene(context.getScene());
compositorOperation->setSceneName(context.getScene()->id.name);
compositorOperation->setRenderData(context.getRenderData());
compositorOperation->setViewName(context.getViewName());
diff --git a/source/blender/compositor/nodes/COM_ImageNode.cpp b/source/blender/compositor/nodes/COM_ImageNode.cpp
index facd422c217..1399749fc8d 100644
--- a/source/blender/compositor/nodes/COM_ImageNode.cpp
+++ b/source/blender/compositor/nodes/COM_ImageNode.cpp
@@ -95,20 +95,17 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo
NodeOperation *operation = NULL;
socket = this->getOutputSocket(index);
bNodeSocket *bnodeSocket = socket->getbNodeSocket();
- RenderPass *rpass = (RenderPass *)BLI_findstring(&rl->passes, bnodeSocket->identifier, offsetof(RenderPass, internal_name));
+ NodeImageLayer *storage = (NodeImageLayer *)bnodeSocket->storage;
+ RenderPass *rpass = (RenderPass *)BLI_findstring(&rl->passes, storage->pass_name, offsetof(RenderPass, name));
int view = 0;
- /* Passes in the file can differ from passes stored in sockets (#36755).
- * Look up the correct file pass using the socket identifier instead.
- */
-#if 0
- NodeImageLayer *storage = (NodeImageLayer *)bnodeSocket->storage;*/
- int passindex = storage->pass_index;*/
- RenderPass *rpass = (RenderPass *)BLI_findlink(&rl->passes, passindex);
-#endif
+ if (STREQ(storage->pass_name, RE_PASSNAME_COMBINED) && STREQ(bnodeSocket->name, "Alpha")) {
+ /* Alpha output is already handled with the associated combined output. */
+ continue;
+ }
/* returns the image view to use for the current active view */
- if (BLI_listbase_count_ex(&image->rr->views, 2) > 1) {
+ if (BLI_listbase_count_at_most(&image->rr->views, 2) > 1) {
const int view_image = imageuser->view;
const bool is_allview = (view_image == 0); /* if view selected == All (0) */
@@ -147,17 +144,25 @@ void ImageNode::convertToOperations(NodeConverter &converter, const CompositorCo
if (index == 0 && operation) {
converter.addPreview(operation->getOutputSocket());
}
- if (rpass->passtype == SCE_PASS_COMBINED) {
- BLI_assert(operation != NULL);
- BLI_assert(index < numberOfOutputs - 1);
- NodeOutput *outputSocket = this->getOutputSocket(index + 1);
- SeparateChannelOperation *separate_operation;
- separate_operation = new SeparateChannelOperation();
- separate_operation->setChannel(3);
- converter.addOperation(separate_operation);
- converter.addLink(operation->getOutputSocket(), separate_operation->getInputSocket(0));
- converter.mapOutputSocket(outputSocket, separate_operation->getOutputSocket());
- index++;
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED)) {
+ for (int alphaIndex = 0; alphaIndex < numberOfOutputs; alphaIndex++) {
+ NodeOutput *alphaSocket = this->getOutputSocket(alphaIndex);
+ bNodeSocket *bnodeAlphaSocket = alphaSocket->getbNodeSocket();
+ if (!STREQ(bnodeAlphaSocket->name, "Alpha")) {
+ continue;
+ }
+ NodeImageLayer *alphaStorage = (NodeImageLayer *)bnodeSocket->storage;
+ if (!STREQ(alphaStorage->pass_name, RE_PASSNAME_COMBINED)) {
+ continue;
+ }
+ SeparateChannelOperation *separate_operation;
+ separate_operation = new SeparateChannelOperation();
+ separate_operation->setChannel(3);
+ converter.addOperation(separate_operation);
+ converter.addLink(operation->getOutputSocket(), separate_operation->getInputSocket(0));
+ converter.mapOutputSocket(alphaSocket, separate_operation->getOutputSocket());
+ break;
+ }
}
}
diff --git a/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp b/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp
index 382296a7f3a..de6ad3df030 100644
--- a/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp
+++ b/source/blender/compositor/nodes/COM_LuminanceMatteNode.cpp
@@ -37,14 +37,11 @@ void LuminanceMatteNode::convertToOperations(NodeConverter &converter, const Com
NodeOutput *outputSocketImage = this->getOutputSocket(0);
NodeOutput *outputSocketMatte = this->getOutputSocket(1);
- ConvertRGBToYUVOperation *rgbToYUV = new ConvertRGBToYUVOperation();
LuminanceMatteOperation *operationSet = new LuminanceMatteOperation();
operationSet->setSettings((NodeChroma *)editorsnode->storage);
- converter.addOperation(rgbToYUV);
converter.addOperation(operationSet);
- converter.mapInputSocket(inputSocket, rgbToYUV->getInputSocket(0));
- converter.addLink(rgbToYUV->getOutputSocket(), operationSet->getInputSocket(0));
+ converter.mapInputSocket(inputSocket, operationSet->getInputSocket(0));
converter.mapOutputSocket(outputSocketMatte, operationSet->getOutputSocket(0));
SetAlphaOperation *operation = new SetAlphaOperation();
diff --git a/source/blender/compositor/nodes/COM_RenderLayersNode.cpp b/source/blender/compositor/nodes/COM_RenderLayersNode.cpp
index 842edcf35c9..2286db81860 100644
--- a/source/blender/compositor/nodes/COM_RenderLayersNode.cpp
+++ b/source/blender/compositor/nodes/COM_RenderLayersNode.cpp
@@ -15,8 +15,8 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
- * Contributor:
- * Jeroen Bakker
+ * Contributor:
+ * Jeroen Bakker
* Monique Dewanchand
*/
@@ -25,78 +25,164 @@
#include "COM_TranslateOperation.h"
#include "COM_RotateOperation.h"
#include "COM_ScaleOperation.h"
+#include "COM_SetColorOperation.h"
#include "COM_SetValueOperation.h"
-
-#ifdef WITH_CYCLES_DEBUG
-# include "RE_pipeline.h"
-#endif
+#include "COM_SetVectorOperation.h"
RenderLayersNode::RenderLayersNode(bNode *editorNode) : Node(editorNode)
{
/* pass */
}
-void RenderLayersNode::testSocketLink(NodeConverter &converter, const CompositorContext &context,
- int outputSocketNumber, RenderLayersBaseProg *operation) const
+void RenderLayersNode::testSocketLink(NodeConverter &converter,
+ const CompositorContext &context,
+ NodeOutput *output,
+ RenderLayersProg *operation,
+ Scene *scene,
+ int layerId,
+ bool is_preview) const
{
- NodeOutput *outputSocket = this->getOutputSocket(outputSocketNumber);
- Scene *scene = (Scene *)this->getbNode()->id;
- short layerId = this->getbNode()->custom1;
-
operation->setScene(scene);
operation->setLayerId(layerId);
operation->setRenderData(context.getRenderData());
operation->setViewName(context.getViewName());
- converter.mapOutputSocket(outputSocket, operation->getOutputSocket());
+ converter.mapOutputSocket(output, operation->getOutputSocket());
converter.addOperation(operation);
-
- if (outputSocketNumber == 0) /* only for image socket */
+
+ if (is_preview) /* only for image socket */
converter.addPreview(operation->getOutputSocket());
}
-void RenderLayersNode::convertToOperations(NodeConverter &converter, const CompositorContext &context) const
+void RenderLayersNode::testRenderLink(NodeConverter &converter,
+ const CompositorContext &context,
+ Render *re) const
+{
+ Scene *scene = (Scene *)this->getbNode()->id;
+ const short layerId = this->getbNode()->custom1;
+ RenderResult *rr = RE_AcquireResultRead(re);
+ if (rr == NULL) {
+ missingRenderLink(converter);
+ return;
+ }
+ SceneRenderLayer *srl = (SceneRenderLayer *)BLI_findlink(&scene->r.layers, layerId);
+ if (srl == NULL) {
+ missingRenderLink(converter);
+ return;
+ }
+ RenderLayer *rl = RE_GetRenderLayer(rr, srl->name);
+ if (rl == NULL) {
+ missingRenderLink(converter);
+ return;
+ }
+ const int num_outputs = this->getNumberOfOutputSockets();
+ for (int i = 0; i < num_outputs; i++) {
+ NodeOutput *output = this->getOutputSocket(i);
+ NodeImageLayer *storage = (NodeImageLayer*) output->getbNodeSocket()->storage;
+ RenderPass *rpass = (RenderPass*) BLI_findstring(
+ &rl->passes,
+ storage->pass_name,
+ offsetof(RenderPass, name));
+ if (rpass == NULL) {
+ missingSocketLink(converter, output);
+ continue;
+ }
+ RenderLayersProg *operation;
+ bool is_preview;
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED) &&
+ STREQ(output->getbNodeSocket()->name, "Alpha"))
+ {
+ operation = new RenderLayersAlphaProg(rpass->name,
+ COM_DT_VALUE,
+ rpass->channels);
+ is_preview = false;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
+ operation = new RenderLayersDepthProg(rpass->name,
+ COM_DT_VALUE,
+ rpass->channels);
+ is_preview = false;
+ }
+ else {
+ DataType type;
+ switch (rpass->channels) {
+ case 4: type = COM_DT_COLOR; break;
+ case 3: type = COM_DT_VECTOR; break;
+ case 1: type = COM_DT_VALUE; break;
+ default:
+ BLI_assert(!"Unexpected number of channels for pass");
+ type = COM_DT_VALUE;
+ break;
+ }
+ operation = new RenderLayersProg(rpass->name,
+ type,
+ rpass->channels);
+ is_preview = STREQ(output->getbNodeSocket()->name, "Image");
+ }
+ testSocketLink(converter,
+ context,
+ output,
+ operation,
+ scene,
+ layerId,
+ is_preview);
+ }
+}
+
+void RenderLayersNode::missingSocketLink(NodeConverter &converter,
+ NodeOutput *output) const
{
- testSocketLink(converter, context, 0, new RenderLayersColorProg());
- testSocketLink(converter, context, 1, new RenderLayersAlphaProg());
- testSocketLink(converter, context, 2, new RenderLayersDepthProg());
- testSocketLink(converter, context, 3, new RenderLayersNormalOperation());
- testSocketLink(converter, context, 4, new RenderLayersUVOperation());
- testSocketLink(converter, context, 5, new RenderLayersSpeedOperation());
- testSocketLink(converter, context, 6, new RenderLayersColorOperation());
- testSocketLink(converter, context, 7, new RenderLayersDiffuseOperation());
- testSocketLink(converter, context, 8, new RenderLayersSpecularOperation());
- testSocketLink(converter, context, 9, new RenderLayersShadowOperation());
- testSocketLink(converter, context, 10, new RenderLayersAOOperation());
- testSocketLink(converter, context, 11, new RenderLayersReflectionOperation());
- testSocketLink(converter, context, 12, new RenderLayersRefractionOperation());
- testSocketLink(converter, context, 13, new RenderLayersIndirectOperation());
- testSocketLink(converter, context, 14, new RenderLayersObjectIndexOperation());
- testSocketLink(converter, context, 15, new RenderLayersMaterialIndexOperation());
- testSocketLink(converter, context, 16, new RenderLayersMistOperation());
- testSocketLink(converter, context, 17, new RenderLayersEmitOperation());
- testSocketLink(converter, context, 18, new RenderLayersEnvironmentOperation());
-
- // cycles passes
- testSocketLink(converter, context, 19, new RenderLayersCyclesOperation(SCE_PASS_DIFFUSE_DIRECT));
- testSocketLink(converter, context, 20, new RenderLayersCyclesOperation(SCE_PASS_DIFFUSE_INDIRECT));
- testSocketLink(converter, context, 21, new RenderLayersCyclesOperation(SCE_PASS_DIFFUSE_COLOR));
- testSocketLink(converter, context, 22, new RenderLayersCyclesOperation(SCE_PASS_GLOSSY_DIRECT));
- testSocketLink(converter, context, 23, new RenderLayersCyclesOperation(SCE_PASS_GLOSSY_INDIRECT));
- testSocketLink(converter, context, 24, new RenderLayersCyclesOperation(SCE_PASS_GLOSSY_COLOR));
- testSocketLink(converter, context, 25, new RenderLayersCyclesOperation(SCE_PASS_TRANSM_DIRECT));
- testSocketLink(converter, context, 26, new RenderLayersCyclesOperation(SCE_PASS_TRANSM_INDIRECT));
- testSocketLink(converter, context, 27, new RenderLayersCyclesOperation(SCE_PASS_TRANSM_COLOR));
- testSocketLink(converter, context, 28, new RenderLayersCyclesOperation(SCE_PASS_SUBSURFACE_DIRECT));
- testSocketLink(converter, context, 29, new RenderLayersCyclesOperation(SCE_PASS_SUBSURFACE_INDIRECT));
- testSocketLink(converter, context, 30, new RenderLayersCyclesOperation(SCE_PASS_SUBSURFACE_COLOR));
+ NodeOperation *operation;
+ switch (output->getDataType()) {
+ case COM_DT_COLOR:
+ {
+ const float color[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ SetColorOperation *color_operation = new SetColorOperation();
+ color_operation->setChannels(color);
+ operation = color_operation;
+ break;
+ }
+ case COM_DT_VECTOR:
+ {
+ const float vector[3] = {0.0f, 0.0f, 0.0f};
+ SetVectorOperation *vector_operation = new SetVectorOperation();
+ vector_operation->setVector(vector);
+ operation = vector_operation;
+ break;
+ }
+ case COM_DT_VALUE:
+ {
+ SetValueOperation *value_operation = new SetValueOperation();
+ value_operation->setValue(0.0f);
+ operation = value_operation;
+ break;
+ }
+ }
+
+ converter.mapOutputSocket(output, operation->getOutputSocket());
+ converter.addOperation(operation);
+}
+
+void RenderLayersNode::missingRenderLink(NodeConverter &converter) const
+{
+ const int num_outputs = this->getNumberOfOutputSockets();
+ for (int i = 0; i < num_outputs; i++) {
+ NodeOutput *output = this->getOutputSocket(i);
+ missingSocketLink(converter, output);
+ }
+}
+
+void RenderLayersNode::convertToOperations(NodeConverter &converter,
+ const CompositorContext &context) const
+{
+ Scene *scene = (Scene *)this->getbNode()->id;
+ Render *re = (scene) ? RE_GetSceneRender(scene) : NULL;
-#ifdef WITH_CYCLES_DEBUG
- {
- Scene *scene = (Scene *)this->getbNode()->id;
- Render *re = RE_GetRender(scene->id.name);
- int debug_pass_type = ((re != NULL) ? RE_debug_pass_type_get(re) : scene->r.debug_pass_type);
- testSocketLink(converter, context, 31, new RenderLayersCyclesDebugOperation(SCE_PASS_DEBUG, debug_pass_type));
+ if (re != NULL) {
+ testRenderLink(converter, context, re);
+ RE_ReleaseResult(re);
+ }
+ else {
+ missingRenderLink(converter);
}
-#endif
}
diff --git a/source/blender/compositor/nodes/COM_RenderLayersNode.h b/source/blender/compositor/nodes/COM_RenderLayersNode.h
index 5863cbb390c..5c6c5e17d1f 100644
--- a/source/blender/compositor/nodes/COM_RenderLayersNode.h
+++ b/source/blender/compositor/nodes/COM_RenderLayersNode.h
@@ -24,6 +24,8 @@
#include "DNA_node_types.h"
#include "COM_RenderLayersProg.h"
+struct Render;
+
/**
* @brief RenderLayersNode
* @ingroup Node
@@ -31,7 +33,21 @@
class RenderLayersNode : public Node {
public:
RenderLayersNode(bNode *editorNode);
- void convertToOperations(NodeConverter &converter, const CompositorContext &context) const;
+ void convertToOperations(NodeConverter &converter,
+ const CompositorContext &context) const;
private:
- void testSocketLink(NodeConverter &converter, const CompositorContext &context, int outputSocketNumber, RenderLayersBaseProg *operation) const;
+ void testSocketLink(NodeConverter &converter,
+ const CompositorContext &context,
+ NodeOutput *output,
+ RenderLayersProg *operation,
+ Scene *scene,
+ int layerId,
+ bool is_preview) const;
+ void testRenderLink(NodeConverter &converter,
+ const CompositorContext &context,
+ Render *re) const;
+
+ void missingSocketLink(NodeConverter &converter,
+ NodeOutput *output) const;
+ void missingRenderLink(NodeConverter &converter) const;
};
diff --git a/source/blender/compositor/nodes/COM_ScaleNode.cpp b/source/blender/compositor/nodes/COM_ScaleNode.cpp
index 61eea9227dc..ef4128a78b4 100644
--- a/source/blender/compositor/nodes/COM_ScaleNode.cpp
+++ b/source/blender/compositor/nodes/COM_ScaleNode.cpp
@@ -52,6 +52,9 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo
converter.mapInputSocket(inputXSocket, operation->getInputSocket(1));
converter.mapInputSocket(inputYSocket, operation->getInputSocket(2));
converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0));
+
+ operation->setVariableSize(inputXSocket->isLinked() ||
+ inputYSocket->isLinked());
break;
}
case CMP_SCALE_SCENEPERCENT:
@@ -67,6 +70,10 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo
converter.addLink(scaleFactorOperation->getOutputSocket(), operation->getInputSocket(1));
converter.addLink(scaleFactorOperation->getOutputSocket(), operation->getInputSocket(2));
converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0));
+
+ operation->setVariableSize(inputXSocket->isLinked() ||
+ inputYSocket->isLinked());
+
break;
}
case CMP_SCALE_RENDERPERCENT:
@@ -81,9 +88,13 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo
operation->setNewHeight(rd->ysch * rd->size / 100.0f);
operation->getInputSocket(0)->setResizeMode(COM_SC_NO_RESIZE);
converter.addOperation(operation);
-
+
converter.mapInputSocket(inputSocket, operation->getInputSocket(0));
converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0));
+
+ operation->setVariableSize(inputXSocket->isLinked() ||
+ inputYSocket->isLinked());
+
break;
}
case CMP_SCALE_ABSOLUTE:
@@ -91,11 +102,15 @@ void ScaleNode::convertToOperations(NodeConverter &converter, const CompositorCo
/* TODO: what is the use of this one.... perhaps some issues when the ui was updated... */
ScaleAbsoluteOperation *operation = new ScaleAbsoluteOperation();
converter.addOperation(operation);
-
+
converter.mapInputSocket(inputSocket, operation->getInputSocket(0));
converter.mapInputSocket(inputXSocket, operation->getInputSocket(1));
converter.mapInputSocket(inputYSocket, operation->getInputSocket(2));
converter.mapOutputSocket(outputSocket, operation->getOutputSocket(0));
+
+ operation->setVariableSize(inputXSocket->isLinked() ||
+ inputYSocket->isLinked());
+
break;
}
}
diff --git a/source/blender/compositor/operations/COM_BrightnessOperation.cpp b/source/blender/compositor/operations/COM_BrightnessOperation.cpp
index 33e35c3fe3b..c7ba86b66bc 100644
--- a/source/blender/compositor/operations/COM_BrightnessOperation.cpp
+++ b/source/blender/compositor/operations/COM_BrightnessOperation.cpp
@@ -29,7 +29,14 @@ BrightnessOperation::BrightnessOperation() : NodeOperation()
this->addInputSocket(COM_DT_VALUE);
this->addOutputSocket(COM_DT_COLOR);
this->m_inputProgram = NULL;
+ this->m_use_premultiply = false;
}
+
+void BrightnessOperation::setUsePremultiply(bool use_premultiply)
+{
+ this->m_use_premultiply = use_premultiply;
+}
+
void BrightnessOperation::initExecution()
{
this->m_inputProgram = this->getInputSocketReader(0);
@@ -64,11 +71,16 @@ void BrightnessOperation::executePixelSampled(float output[4], float x, float y,
delta *= -1;
b = a * (brightness + delta);
}
-
+ if (this->m_use_premultiply) {
+ premul_to_straight_v4(inputValue);
+ }
output[0] = a * inputValue[0] + b;
output[1] = a * inputValue[1] + b;
output[2] = a * inputValue[2] + b;
output[3] = inputValue[3];
+ if (this->m_use_premultiply) {
+ straight_to_premul_v4(output);
+ }
}
void BrightnessOperation::deinitExecution()
diff --git a/source/blender/compositor/operations/COM_BrightnessOperation.h b/source/blender/compositor/operations/COM_BrightnessOperation.h
index 22086ae11e8..ff492f2b102 100644
--- a/source/blender/compositor/operations/COM_BrightnessOperation.h
+++ b/source/blender/compositor/operations/COM_BrightnessOperation.h
@@ -34,6 +34,8 @@ private:
SocketReader *m_inputBrightnessProgram;
SocketReader *m_inputContrastProgram;
+ bool m_use_premultiply;
+
public:
BrightnessOperation();
@@ -52,5 +54,6 @@ public:
*/
void deinitExecution();
+ void setUsePremultiply(bool use_premultiply);
};
#endif
diff --git a/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp b/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp
index d26dcd17750..ecbc7a9a93d 100644
--- a/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp
+++ b/source/blender/compositor/operations/COM_CalculateMeanOperation.cpp
@@ -121,7 +121,7 @@ void CalculateMeanOperation::calculateMean(MemoryBuffer *tile)
case 5:
{
float yuv[3];
- rgb_to_yuv(buffer[offset], buffer[offset + 1], buffer[offset + 2], &yuv[0], &yuv[1], &yuv[2]);
+ rgb_to_yuv(buffer[offset], buffer[offset + 1], buffer[offset + 2], &yuv[0], &yuv[1], &yuv[2], BLI_YUV_ITU_BT709);
sum += yuv[0];
break;
}
diff --git a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp
index 6b238e53d7b..56b402f2b3b 100644
--- a/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp
+++ b/source/blender/compositor/operations/COM_CalculateStandardDeviationOperation.cpp
@@ -87,7 +87,7 @@ void *CalculateStandardDeviationOperation::initializeTileData(rcti *rect)
case 5: /* luminance */
{
float yuv[3];
- rgb_to_yuv(buffer[offset], buffer[offset + 1], buffer[offset + 2], &yuv[0], &yuv[1], &yuv[2]);
+ rgb_to_yuv(buffer[offset], buffer[offset + 1], buffer[offset + 2], &yuv[0], &yuv[1], &yuv[2], BLI_YUV_ITU_BT709);
sum += (yuv[0] - mean) * (yuv[0] - mean);
break;
}
diff --git a/source/blender/compositor/operations/COM_ColorRampOperation.cpp b/source/blender/compositor/operations/COM_ColorRampOperation.cpp
index 84d36034ec6..c67f906b374 100644
--- a/source/blender/compositor/operations/COM_ColorRampOperation.cpp
+++ b/source/blender/compositor/operations/COM_ColorRampOperation.cpp
@@ -25,7 +25,7 @@
#ifdef __cplusplus
extern "C" {
#endif
-# include "BKE_texture.h"
+# include "BKE_colorband.h"
#ifdef __cplusplus
}
#endif
@@ -48,7 +48,7 @@ void ColorRampOperation::executePixelSampled(float output[4], float x, float y,
float values[4];
this->m_inputProgram->readSampled(values, x, y, sampler);
- do_colorband(this->m_colorBand, values[0], output);
+ BKE_colorband_evaluate(this->m_colorBand, values[0], output);
}
void ColorRampOperation::deinitExecution()
diff --git a/source/blender/compositor/operations/COM_CompositorOperation.cpp b/source/blender/compositor/operations/COM_CompositorOperation.cpp
index 76f74c144f6..241ae20ce33 100644
--- a/source/blender/compositor/operations/COM_CompositorOperation.cpp
+++ b/source/blender/compositor/operations/COM_CompositorOperation.cpp
@@ -51,6 +51,7 @@ CompositorOperation::CompositorOperation() : NodeOperation()
this->m_useAlphaInput = false;
this->m_active = false;
+ this->m_scene = NULL;
this->m_sceneName[0] = '\0';
this->m_viewName = NULL;
}
@@ -78,7 +79,7 @@ void CompositorOperation::deinitExecution()
return;
if (!isBreaked()) {
- Render *re = RE_GetRender(this->m_sceneName);
+ Render *re = RE_GetSceneRender(this->m_scene);
RenderResult *rr = RE_AcquireResultWrite(re);
if (rr) {
@@ -107,9 +108,9 @@ void CompositorOperation::deinitExecution()
re = NULL;
}
- BLI_lock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_lock(LOCK_DRAW_IMAGE);
BKE_image_signal(BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result"), NULL, IMA_SIGNAL_FREE);
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
}
else {
if (this->m_outputBuffer) {
@@ -151,31 +152,31 @@ void CompositorOperation::executeRegion(rcti *rect, unsigned int /*tileNumber*/)
const RenderData *rd = this->m_rd;
if (rd->mode & R_BORDER && rd->mode & R_CROP) {
- /*!
- When using cropped render result, need to re-position area of interest,
- so it'll natch bounds of render border within frame. By default, canvas
- will be centered between full frame and cropped frame, so we use such
- scheme to map cropped coordinates to full-frame coordinates
-
- ^ Y
- | Width
- +------------------------------------------------+
- | |
- | |
- | Centered canvas, we map coordinate from it |
- | +------------------+ |
- | | | | H
- | | | | e
- | +------------------+ . Center | | i
- | | | | | | g
- | | | | | | h
- | |....dx.... +------|-----------+ | t
- | | . dy | |
- | +------------------+ |
- | Render border, we map coordinates to it |
- | | X
- +------------------------------------------------+---->
- Full frame
+ /**
+ * When using cropped render result, need to re-position area of interest,
+ * so it'll natch bounds of render border within frame. By default, canvas
+ * will be centered between full frame and cropped frame, so we use such
+ * scheme to map cropped coordinates to full-frame coordinates
+ *
+ * ^ Y
+ * | Width
+ * +------------------------------------------------+
+ * | |
+ * | |
+ * | Centered canvas, we map coordinate from it |
+ * | +------------------+ |
+ * | | | | H
+ * | | | | e
+ * | +------------------+ . Center | | i
+ * | | | | | | g
+ * | | | | | | h
+ * | |....dx.... +------|-----------+ | t
+ * | | . dy | |
+ * | +------------------+ |
+ * | Render border, we map coordinates to it |
+ * | | X
+ * +------------------------------------------------+---->
+ * Full frame
*/
int full_width = rd->xsch * rd->size / 100;
@@ -217,7 +218,7 @@ void CompositorOperation::determineResolution(unsigned int resolution[2], unsign
// check actual render resolution with cropping it may differ with cropped border.rendering
// FIX for: [31777] Border Crop gives black (easy)
- Render *re = RE_GetRender(this->m_sceneName);
+ Render *re = RE_GetSceneRender(this->m_scene);
if (re) {
RenderResult *rr = RE_AcquireResultRead(re);
if (rr) {
diff --git a/source/blender/compositor/operations/COM_CompositorOperation.h b/source/blender/compositor/operations/COM_CompositorOperation.h
index e81ba520695..269a065a793 100644
--- a/source/blender/compositor/operations/COM_CompositorOperation.h
+++ b/source/blender/compositor/operations/COM_CompositorOperation.h
@@ -26,11 +26,14 @@
#include "BLI_rect.h"
#include "BLI_string.h"
+struct Scene;
+
/**
* @brief Compositor output operation
*/
class CompositorOperation : public NodeOperation {
private:
+ const struct Scene *m_scene;
/**
* @brief Scene name, used for getting the render output, includes 'SC' prefix.
*/
@@ -84,6 +87,7 @@ public:
CompositorOperation();
const bool isActiveCompositorOutput() const { return this->m_active; }
void executeRegion(rcti *rect, unsigned int tileNumber);
+ void setScene(const struct Scene *scene) { m_scene = scene; }
void setSceneName(const char *sceneName) { BLI_strncpy(this->m_sceneName, sceneName, sizeof(this->m_sceneName)); }
void setViewName(const char *viewName) { this->m_viewName = viewName; }
void setRenderData(const RenderData *rd) { this->m_rd = rd; }
diff --git a/source/blender/compositor/operations/COM_ConvertOperation.cpp b/source/blender/compositor/operations/COM_ConvertOperation.cpp
index 8b8e8408208..327015c1139 100644
--- a/source/blender/compositor/operations/COM_ConvertOperation.cpp
+++ b/source/blender/compositor/operations/COM_ConvertOperation.cpp
@@ -241,7 +241,7 @@ void ConvertRGBToYUVOperation::executePixelSampled(float output[4], float x, flo
{
float inputColor[4];
this->m_inputOperation->readSampled(inputColor, x, y, sampler);
- rgb_to_yuv(inputColor[0], inputColor[1], inputColor[2], &output[0], &output[1], &output[2]);
+ rgb_to_yuv(inputColor[0], inputColor[1], inputColor[2], &output[0], &output[1], &output[2], BLI_YUV_ITU_BT709);
output[3] = inputColor[3];
}
@@ -258,7 +258,7 @@ void ConvertYUVToRGBOperation::executePixelSampled(float output[4], float x, flo
{
float inputColor[4];
this->m_inputOperation->readSampled(inputColor, x, y, sampler);
- yuv_to_rgb(inputColor[0], inputColor[1], inputColor[2], &output[0], &output[1], &output[2]);
+ yuv_to_rgb(inputColor[0], inputColor[1], inputColor[2], &output[0], &output[1], &output[2], BLI_YUV_ITU_BT709);
output[3] = inputColor[3];
}
diff --git a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp
index e1ada9a8c39..5f78067220a 100644
--- a/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp
+++ b/source/blender/compositor/operations/COM_ConvolutionEdgeFilterOperation.cpp
@@ -94,4 +94,10 @@ void ConvolutionEdgeFilterOperation::executePixel(float output[4], int x, int y,
output[2] = output[2] * value[0] + in2[2] * mval;
output[3] = in2[3];
+
+ /* Make sure we don't return negative color. */
+ output[0] = max(output[0], 0.0f);
+ output[1] = max(output[1], 0.0f);
+ output[2] = max(output[2], 0.0f);
+ output[3] = max(output[3], 0.0f);
}
diff --git a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp
index 68ec2be5ebd..6ac1ff9a1eb 100644
--- a/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp
+++ b/source/blender/compositor/operations/COM_ConvolutionFilterOperation.cpp
@@ -107,6 +107,12 @@ void ConvolutionFilterOperation::executePixel(float output[4], int x, int y, voi
output[1] = output[1] * value[0] + in2[1] * mval;
output[2] = output[2] * value[0] + in2[2] * mval;
output[3] = output[3] * value[0] + in2[3] * mval;
+
+ /* Make sure we don't return negative color. */
+ output[0] = max(output[0], 0.0f);
+ output[1] = max(output[1], 0.0f);
+ output[2] = max(output[2], 0.0f);
+ output[3] = max(output[3], 0.0f);
}
bool ConvolutionFilterOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output)
diff --git a/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp b/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp
index 325ef83a529..aa58c0571cf 100644
--- a/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp
+++ b/source/blender/compositor/operations/COM_DifferenceMatteOperation.cpp
@@ -65,11 +65,11 @@ void DifferenceMatteOperation::executePixelSampled(float output[4], float x, flo
difference = difference / 3.0f;
/* make 100% transparent */
- if (difference < tolerance) {
+ if (difference <= tolerance) {
output[0] = 0.0f;
}
/*in the falloff region, make partially transparent */
- else if (difference < falloff + tolerance) {
+ else if (difference <= falloff + tolerance) {
difference = difference - tolerance;
alpha = difference / falloff;
/*only change if more transparent than before */
diff --git a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
index 29ed4334412..4d05ece7ef0 100644
--- a/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianXBlurOperation.cpp
@@ -85,7 +85,7 @@ void GaussianXBlurOperation::updateGauss()
void GaussianXBlurOperation::executePixel(float output[4], int x, int y, void *data)
{
- float color_accum[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ float ATTR_ALIGN(16) color_accum[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float multiplier_accum = 0.0f;
MemoryBuffer *inputBuffer = (MemoryBuffer *)data;
float *buffer = inputBuffer->getBuffer();
diff --git a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
index 4b55333c08c..3203914b5a7 100644
--- a/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_GaussianYBlurOperation.cpp
@@ -84,7 +84,7 @@ void GaussianYBlurOperation::updateGauss()
void GaussianYBlurOperation::executePixel(float output[4], int x, int y, void *data)
{
- float color_accum[4] = {0.0f, 0.0f, 0.0f, 0.0f};
+ float ATTR_ALIGN(16) color_accum[4] = {0.0f, 0.0f, 0.0f, 0.0f};
float multiplier_accum = 0.0f;
MemoryBuffer *inputBuffer = (MemoryBuffer *)data;
float *buffer = inputBuffer->getBuffer();
diff --git a/source/blender/compositor/operations/COM_GlareSimpleStarOperation.cpp b/source/blender/compositor/operations/COM_GlareSimpleStarOperation.cpp
index 57aa3a1bac2..94f407dad86 100644
--- a/source/blender/compositor/operations/COM_GlareSimpleStarOperation.cpp
+++ b/source/blender/compositor/operations/COM_GlareSimpleStarOperation.cpp
@@ -65,10 +65,10 @@ void GlareSimpleStarOperation::generateGlare(float *data, MemoryBuffer *inputTil
}
}
// // B
- for (y = tbuf1->getHeight() - 1 && (!breaked); y >= 0; y--) {
+ for (y = this->getHeight() - 1; y >= 0 && (!breaked); y--) {
ym = y - i;
yp = y + i;
- for (x = tbuf1->getWidth() - 1; x >= 0; x--) {
+ for (x = this->getWidth() - 1; x >= 0; x--) {
xm = x - i;
xp = x + i;
tbuf1->read(c, x, y);
diff --git a/source/blender/compositor/operations/COM_KeyingOperation.cpp b/source/blender/compositor/operations/COM_KeyingOperation.cpp
index e2566d2f4f0..fa0ef70fca6 100644
--- a/source/blender/compositor/operations/COM_KeyingOperation.cpp
+++ b/source/blender/compositor/operations/COM_KeyingOperation.cpp
@@ -67,15 +67,16 @@ void KeyingOperation::deinitExecution()
void KeyingOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
{
- float pixelColor[4];
- float screenColor[4];
+ float pixel_color[4];
+ float screen_color[4];
- this->m_pixelReader->readSampled(pixelColor, x, y, sampler);
- this->m_screenReader->readSampled(screenColor, x, y, sampler);
+ this->m_pixelReader->readSampled(pixel_color, x, y, sampler);
+ this->m_screenReader->readSampled(screen_color, x, y, sampler);
- const int primary_channel = max_axis_v3(screenColor);
+ const int primary_channel = max_axis_v3(screen_color);
+ const float min_pixel_color = min_fff(pixel_color[0], pixel_color[1], pixel_color[2]);
- if (pixelColor[primary_channel] > 1.0f) {
+ if (min_pixel_color > 1.0f) {
/* overexposure doesn't happen on screen itself and usually happens
* on light sources in the shot, this need to be checked separately
* because saturation and falloff calculation is based on the fact
@@ -84,8 +85,8 @@ void KeyingOperation::executePixelSampled(float output[4], float x, float y, Pix
output[0] = 1.0f;
}
else {
- float saturation = get_pixel_saturation(pixelColor, this->m_screenBalance, primary_channel);
- float screen_saturation = get_pixel_saturation(screenColor, this->m_screenBalance, primary_channel);
+ float saturation = get_pixel_saturation(pixel_color, this->m_screenBalance, primary_channel);
+ float screen_saturation = get_pixel_saturation(screen_color, this->m_screenBalance, primary_channel);
if (saturation < 0) {
/* means main channel of pixel is different from screen,
diff --git a/source/blender/compositor/operations/COM_KeyingScreenOperation.h b/source/blender/compositor/operations/COM_KeyingScreenOperation.h
index b1a5c0c39c7..45195b1e98d 100644
--- a/source/blender/compositor/operations/COM_KeyingScreenOperation.h
+++ b/source/blender/compositor/operations/COM_KeyingScreenOperation.h
@@ -35,7 +35,7 @@
#include "BLI_string.h"
extern "C" {
-# include "BLI_voronoi.h"
+# include "BLI_voronoi_2d.h"
}
/**
diff --git a/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp b/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp
index 3be5447db3b..1401ab56fbd 100644
--- a/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp
+++ b/source/blender/compositor/operations/COM_LuminanceMatteOperation.cpp
@@ -22,6 +22,10 @@
#include "COM_LuminanceMatteOperation.h"
#include "BLI_math.h"
+extern "C" {
+#include "IMB_colormanagement.h"
+}
+
LuminanceMatteOperation::LuminanceMatteOperation() : NodeOperation()
{
addInputSocket(COM_DT_COLOR);
@@ -43,41 +47,34 @@ void LuminanceMatteOperation::deinitExecution()
void LuminanceMatteOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
{
float inColor[4];
+ this->m_inputImageProgram->readSampled(inColor, x, y, sampler);
const float high = this->m_settings->t1;
const float low = this->m_settings->t2;
+ const float luminance = IMB_colormanagement_get_luminance(inColor);
float alpha;
-
- this->m_inputImageProgram->readSampled(inColor, x, y, sampler);
/* one line thread-friend algorithm:
- * output[0] = max(inputValue[3], min(high, max(low, ((inColor[0] - low) / (high - low))));
+ * output[0] = min(inputValue[3], min(1.0f, max(0.0f, ((luminance - low) / (high - low))));
*/
/* test range */
- if (inColor[0] > high) {
+ if (luminance > high) {
alpha = 1.0f;
}
- else if (inColor[0] < low) {
+ else if (luminance < low) {
alpha = 0.0f;
}
else { /*blend */
- alpha = (inColor[0] - low) / (high - low);
+ alpha = (luminance - low) / (high - low);
}
-
/* store matte(alpha) value in [0] to go with
* COM_SetAlphaOperation and the Value output
*/
/* don't make something that was more transparent less transparent */
- if (alpha < inColor[3]) {
- output[0] = alpha;
- }
- else {
- /* leave now it was before */
- output[0] = inColor[3];
- }
+ output[0] = min_ff(alpha, inColor[3]);
}
diff --git a/source/blender/compositor/operations/COM_MapRangeOperation.cpp b/source/blender/compositor/operations/COM_MapRangeOperation.cpp
index 7a89ba91b4c..7a38d066122 100644
--- a/source/blender/compositor/operations/COM_MapRangeOperation.cpp
+++ b/source/blender/compositor/operations/COM_MapRangeOperation.cpp
@@ -65,6 +65,11 @@ void MapRangeOperation::executePixelSampled(float output[4], float x, float y, P
dest_min = inputs[3];
dest_max = inputs[4];
+ if (fabsf(source_max - source_min) < 1e-6f) {
+ output[0] = 0.0f;
+ return;
+ }
+
if (value >= -BLENDER_ZMAX && value <= BLENDER_ZMAX) {
value = (value - source_min) / (source_max - source_min);
value = dest_min + value * (dest_max - dest_min);
diff --git a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp
index 41f7da7c49f..5d682352d46 100644
--- a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp
+++ b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.cpp
@@ -28,55 +28,61 @@ extern "C" {
MovieClipAttributeOperation::MovieClipAttributeOperation() : NodeOperation()
{
this->addOutputSocket(COM_DT_VALUE);
- this->m_valueSet = false;
this->m_framenumber = 0;
this->m_attribute = MCA_X;
this->m_invert = false;
}
-void MovieClipAttributeOperation::executePixelSampled(float output[4],
- float /*x*/, float /*y*/,
- PixelSampler /*sampler*/)
+void MovieClipAttributeOperation::initExecution()
{
- /* TODO(sergey): This code isn't really thread-safe. */
- if (!this->m_valueSet) {
- float loc[2], scale, angle;
- loc[0] = 0.0f;
- loc[1] = 0.0f;
- scale = 1.0f;
- angle = 0.0f;
- if (this->m_clip) {
- int clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(this->m_clip, this->m_framenumber);
- BKE_tracking_stabilization_data_get(this->m_clip, clip_framenr, getWidth(), getHeight(), loc, &scale, &angle);
- }
- switch (this->m_attribute) {
- case MCA_SCALE:
- this->m_value = scale;
- break;
- case MCA_ANGLE:
- this->m_value = angle;
- break;
- case MCA_X:
- this->m_value = loc[0];
- break;
- case MCA_Y:
- this->m_value = loc[1];
- break;
+ if (this->m_clip == NULL) {
+ return;
+ }
+ float loc[2], scale, angle;
+ loc[0] = 0.0f;
+ loc[1] = 0.0f;
+ scale = 1.0f;
+ angle = 0.0f;
+ int clip_framenr = BKE_movieclip_remap_scene_to_clip_frame(
+ this->m_clip, this->m_framenumber);
+ BKE_tracking_stabilization_data_get(this->m_clip,
+ clip_framenr,
+ getWidth(), getHeight(),
+ loc, &scale, &angle);
+ switch (this->m_attribute) {
+ case MCA_SCALE:
+ this->m_value = scale;
+ break;
+ case MCA_ANGLE:
+ this->m_value = angle;
+ break;
+ case MCA_X:
+ this->m_value = loc[0];
+ break;
+ case MCA_Y:
+ this->m_value = loc[1];
+ break;
+ }
+ if (this->m_invert) {
+ if (this->m_attribute != MCA_SCALE) {
+ this->m_value = -this->m_value;
}
- if (this->m_invert) {
- if (this->m_attribute != MCA_SCALE) {
- this->m_value = -this->m_value;
- }
- else {
- this->m_value = 1.0f / this->m_value;
- }
+ else {
+ this->m_value = 1.0f / this->m_value;
}
- this->m_valueSet = true;
}
+}
+
+void MovieClipAttributeOperation::executePixelSampled(float output[4],
+ float /*x*/, float /*y*/,
+ PixelSampler /*sampler*/)
+{
output[0] = this->m_value;
}
-void MovieClipAttributeOperation::determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2])
+void MovieClipAttributeOperation::determineResolution(
+ unsigned int resolution[2],
+ unsigned int preferredResolution[2])
{
resolution[0] = preferredResolution[0];
resolution[1] = preferredResolution[1];
diff --git a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h
index 731b9debaf0..659f54c1ca2 100644
--- a/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h
+++ b/source/blender/compositor/operations/COM_MovieClipAttributeOperation.h
@@ -39,16 +39,18 @@ class MovieClipAttributeOperation : public NodeOperation {
private:
MovieClip *m_clip;
float m_value;
- bool m_valueSet;
int m_framenumber;
bool m_invert;
MovieClipAttribute m_attribute;
+
public:
/**
* Default constructor
*/
MovieClipAttributeOperation();
-
+
+ void initExecution();
+
/**
* the inner loop of this program
*/
diff --git a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp
index fb8730c9fa0..d6affa6eee9 100644
--- a/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp
+++ b/source/blender/compositor/operations/COM_PlaneCornerPinOperation.cpp
@@ -29,8 +29,6 @@
#include "BLI_math_color.h"
extern "C" {
-# include "BLI_jitter.h"
-
# include "BKE_node.h"
}
diff --git a/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.cpp b/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.cpp
index 1145abd076a..75a85ad7e33 100644
--- a/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.cpp
+++ b/source/blender/compositor/operations/COM_PlaneDistortCommonOperation.cpp
@@ -28,7 +28,7 @@ extern "C" {
#include "BLI_listbase.h"
#include "BLI_math.h"
#include "BLI_math_color.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BKE_movieclip.h"
#include "BKE_node.h"
diff --git a/source/blender/compositor/operations/COM_PlaneTrackOperation.cpp b/source/blender/compositor/operations/COM_PlaneTrackOperation.cpp
index a56aa0cbaa6..070b7562b2d 100644
--- a/source/blender/compositor/operations/COM_PlaneTrackOperation.cpp
+++ b/source/blender/compositor/operations/COM_PlaneTrackOperation.cpp
@@ -29,8 +29,6 @@
#include "BLI_math_color.h"
extern "C" {
-# include "BLI_jitter.h"
-
# include "BKE_movieclip.h"
# include "BKE_node.h"
# include "BKE_tracking.h"
diff --git a/source/blender/compositor/operations/COM_RenderLayersProg.cpp b/source/blender/compositor/operations/COM_RenderLayersProg.cpp
index 099208ce600..d1c654ddb6c 100644
--- a/source/blender/compositor/operations/COM_RenderLayersProg.cpp
+++ b/source/blender/compositor/operations/COM_RenderLayersProg.cpp
@@ -34,20 +34,21 @@ extern "C" {
/* ******** Render Layers Base Prog ******** */
-RenderLayersBaseProg::RenderLayersBaseProg(int renderpass, int elementsize) : NodeOperation()
+RenderLayersProg::RenderLayersProg(const char *passName, DataType type, int elementsize) : NodeOperation(), m_passName(passName)
{
- this->m_renderpass = renderpass;
this->setScene(NULL);
this->m_inputBuffer = NULL;
this->m_elementsize = elementsize;
this->m_rd = NULL;
+
+ this->addOutputSocket(type);
}
-void RenderLayersBaseProg::initExecution()
+void RenderLayersProg::initExecution()
{
Scene *scene = this->getScene();
- Render *re = (scene) ? RE_GetRender(scene->id.name) : NULL;
+ Render *re = (scene) ? RE_GetSceneRender(scene) : NULL;
RenderResult *rr = NULL;
if (re)
@@ -59,10 +60,7 @@ void RenderLayersBaseProg::initExecution()
RenderLayer *rl = RE_GetRenderLayer(rr, srl->name);
if (rl) {
- this->m_inputBuffer = RE_RenderLayerGetPass(rl, this->m_renderpass, this->m_viewName);
- if (this->m_inputBuffer == NULL && this->m_renderpass == SCE_PASS_COMBINED) {
- this->m_inputBuffer = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, this->m_viewName);
- }
+ this->m_inputBuffer = RE_RenderLayerGetPass(rl, this->m_passName.c_str(), this->m_viewName);
}
}
}
@@ -72,7 +70,7 @@ void RenderLayersBaseProg::initExecution()
}
}
-void RenderLayersBaseProg::doInterpolation(float output[4], float x, float y, PixelSampler sampler)
+void RenderLayersProg::doInterpolation(float output[4], float x, float y, PixelSampler sampler)
{
unsigned int offset;
int width = this->getWidth(), height = this->getHeight();
@@ -111,7 +109,7 @@ void RenderLayersBaseProg::doInterpolation(float output[4], float x, float y, Pi
}
}
-void RenderLayersBaseProg::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
+void RenderLayersProg::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
{
#if 0
const RenderData *rd = this->m_rd;
@@ -173,15 +171,15 @@ void RenderLayersBaseProg::executePixelSampled(float output[4], float x, float y
}
}
-void RenderLayersBaseProg::deinitExecution()
+void RenderLayersProg::deinitExecution()
{
this->m_inputBuffer = NULL;
}
-void RenderLayersBaseProg::determineResolution(unsigned int resolution[2], unsigned int /*preferredResolution*/[2])
+void RenderLayersProg::determineResolution(unsigned int resolution[2], unsigned int /*preferredResolution*/[2])
{
Scene *sce = this->getScene();
- Render *re = (sce) ? RE_GetRender(sce->id.name) : NULL;
+ Render *re = (sce) ? RE_GetSceneRender(sce) : NULL;
RenderResult *rr = NULL;
resolution[0] = 0;
@@ -207,13 +205,6 @@ void RenderLayersBaseProg::determineResolution(unsigned int resolution[2], unsig
}
/* ******** Render Layers AO Operation ******** */
-
-RenderLayersAOOperation::RenderLayersAOOperation() : RenderLayersBaseProg(SCE_PASS_AO, 3)
-{
- this->addOutputSocket(COM_DT_COLOR);
-}
-
-
void RenderLayersAOOperation::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
{
float *inputBuffer = this->getInputBuffer();
@@ -227,12 +218,6 @@ void RenderLayersAOOperation::executePixelSampled(float output[4], float x, floa
}
/* ******** Render Layers Alpha Operation ******** */
-
-RenderLayersAlphaProg::RenderLayersAlphaProg() : RenderLayersBaseProg(SCE_PASS_COMBINED, 4)
-{
- this->addOutputSocket(COM_DT_VALUE);
-}
-
void RenderLayersAlphaProg::executePixelSampled(float output[4], float x, float y, PixelSampler sampler)
{
float *inputBuffer = this->getInputBuffer();
@@ -247,27 +232,7 @@ void RenderLayersAlphaProg::executePixelSampled(float output[4], float x, float
}
}
-/* ******** Render Layers Color Operation ******** */
-
-RenderLayersColorOperation::RenderLayersColorOperation() : RenderLayersBaseProg(SCE_PASS_RGBA, 4)
-{
- this->addOutputSocket(COM_DT_COLOR);
-}
-
-/* ******** Render Layers Cycles Operation ******** */
-
-RenderLayersCyclesOperation::RenderLayersCyclesOperation(int pass) : RenderLayersBaseProg(pass, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
/* ******** Render Layers Depth Operation ******** */
-
-RenderLayersDepthProg::RenderLayersDepthProg() : RenderLayersBaseProg(SCE_PASS_Z, 1)
-{
- this->addOutputSocket(COM_DT_VALUE);
-}
-
void RenderLayersDepthProg::executePixelSampled(float output[4], float x, float y, PixelSampler /*sampler*/)
{
int ix = x;
@@ -282,134 +247,3 @@ void RenderLayersDepthProg::executePixelSampled(float output[4], float x, float
output[0] = inputBuffer[offset];
}
}
-
-/* ******** Render Layers Diffuse Operation ******** */
-
-RenderLayersDiffuseOperation::RenderLayersDiffuseOperation() : RenderLayersBaseProg(SCE_PASS_DIFFUSE, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Emit Operation ******** */
-
-RenderLayersEmitOperation::RenderLayersEmitOperation() : RenderLayersBaseProg(SCE_PASS_EMIT, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Environment Operation ******** */
-
-RenderLayersEnvironmentOperation::RenderLayersEnvironmentOperation() : RenderLayersBaseProg(SCE_PASS_ENVIRONMENT, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Image Operation ******** */
-
-RenderLayersColorProg::RenderLayersColorProg() : RenderLayersBaseProg(SCE_PASS_COMBINED, 4)
-{
- this->addOutputSocket(COM_DT_COLOR);
-}
-
-/* ******** Render Layers Indirect Operation ******** */
-
-RenderLayersIndirectOperation::RenderLayersIndirectOperation() : RenderLayersBaseProg(SCE_PASS_INDIRECT, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Material Index Operation ******** */
-
-RenderLayersMaterialIndexOperation::RenderLayersMaterialIndexOperation() : RenderLayersBaseProg(SCE_PASS_INDEXMA, 1)
-{
- this->addOutputSocket(COM_DT_VALUE);
-}
-
-/* ******** Render Layers Mist Operation ******** */
-
-RenderLayersMistOperation::RenderLayersMistOperation() : RenderLayersBaseProg(SCE_PASS_MIST, 1)
-{
- this->addOutputSocket(COM_DT_VALUE);
-}
-
-/* ******** Render Layers Normal Operation ******** */
-
-RenderLayersNormalOperation::RenderLayersNormalOperation() : RenderLayersBaseProg(SCE_PASS_NORMAL, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Object Index Operation ******** */
-
-RenderLayersObjectIndexOperation::RenderLayersObjectIndexOperation() : RenderLayersBaseProg(SCE_PASS_INDEXOB, 1)
-{
- this->addOutputSocket(COM_DT_VALUE);
-}
-
-/* ******** Render Layers Reflection Operation ******** */
-
-RenderLayersReflectionOperation::RenderLayersReflectionOperation() : RenderLayersBaseProg(SCE_PASS_REFLECT, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Refraction Operation ******** */
-
-RenderLayersRefractionOperation::RenderLayersRefractionOperation() : RenderLayersBaseProg(SCE_PASS_REFRACT, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Shadow Operation ******** */
-
-RenderLayersShadowOperation::RenderLayersShadowOperation() : RenderLayersBaseProg(SCE_PASS_SHADOW, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Specular Operation ******** */
-
-RenderLayersSpecularOperation::RenderLayersSpecularOperation() : RenderLayersBaseProg(SCE_PASS_SPEC, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Render Layers Speed Operation ******** */
-
-RenderLayersSpeedOperation::RenderLayersSpeedOperation() : RenderLayersBaseProg(SCE_PASS_VECTOR, 4)
-{
- this->addOutputSocket(COM_DT_COLOR);
-}
-
-/* ******** Render Layers UV Operation ******** */
-
-RenderLayersUVOperation::RenderLayersUVOperation() : RenderLayersBaseProg(SCE_PASS_UV, 3)
-{
- this->addOutputSocket(COM_DT_VECTOR);
-}
-
-/* ******** Debug Render Layers Cycles Operation ******** */
-
-#ifdef WITH_CYCLES_DEBUG
-
-RenderLayersCyclesDebugOperation::RenderLayersCyclesDebugOperation(
- int pass,
- int debug_pass_type)
- : RenderLayersBaseProg(pass, RE_debug_pass_num_channels_get(debug_pass_type))
-{
- switch (m_elementsize) {
- case 1:
- this->addOutputSocket(COM_DT_VALUE);
- break;
- case 3:
- this->addOutputSocket(COM_DT_VECTOR);
- break;
- case 4:
- this->addOutputSocket(COM_DT_COLOR);
- break;
- default:
- BLI_assert(!"Unkown debug pass type element size.");
- }
-}
-
-#endif
diff --git a/source/blender/compositor/operations/COM_RenderLayersProg.h b/source/blender/compositor/operations/COM_RenderLayersProg.h
index 89eb2a6954d..7cfead7e98c 100644
--- a/source/blender/compositor/operations/COM_RenderLayersProg.h
+++ b/source/blender/compositor/operations/COM_RenderLayersProg.h
@@ -30,8 +30,6 @@
#include "BKE_image.h"
extern "C" {
# include "RE_pipeline.h"
-# include "RE_shader_ext.h"
-# include "RE_render_ext.h"
# include "MEM_guardedalloc.h"
}
@@ -40,13 +38,13 @@ extern "C" {
*
* @todo: rename to operation.
*/
-class RenderLayersBaseProg : public NodeOperation {
+class RenderLayersProg : public NodeOperation {
protected:
/**
* Reference to the scene object.
*/
Scene *m_scene;
-
+
/**
* layerId of the layer where this operation needs to get its data from
*/
@@ -61,12 +59,12 @@ protected:
* cached instance to the float buffer inside the layer
*/
float *m_inputBuffer;
-
+
/**
* renderpass where this operation needs to get its data from
*/
- int m_renderpass;
-
+ std::string m_passName;
+
int m_elementsize;
/**
@@ -75,15 +73,10 @@ protected:
const RenderData *m_rd;
/**
- * Constructor
- */
- RenderLayersBaseProg(int renderpass, int elementsize);
-
- /**
* Determine the output resolution. The resolution is retrieved from the Renderer
*/
void determineResolution(unsigned int resolution[2], unsigned int preferredResolution[2]);
-
+
/**
* retrieve the reference to the float buffer of the renderer.
*/
@@ -92,6 +85,10 @@ protected:
void doInterpolation(float output[4], float x, float y, PixelSampler sampler);
public:
/**
+ * Constructor
+ */
+ RenderLayersProg(const char *passName, DataType type, int elementsize);
+ /**
* setter for the scene field. Will be called from
* @see RenderLayerNode to set the actual scene where
* the data will be retrieved from.
@@ -108,116 +105,25 @@ public:
void executePixelSampled(float output[4], float x, float y, PixelSampler sampler);
};
-class RenderLayersAOOperation : public RenderLayersBaseProg {
+class RenderLayersAOOperation : public RenderLayersProg {
public:
- RenderLayersAOOperation();
+ RenderLayersAOOperation(const char *passName, DataType type, int elementsize)
+ : RenderLayersProg(passName, type, elementsize) {}
void executePixelSampled(float output[4], float x, float y, PixelSampler sampler);
};
-class RenderLayersAlphaProg : public RenderLayersBaseProg {
+class RenderLayersAlphaProg : public RenderLayersProg {
public:
- RenderLayersAlphaProg();
+ RenderLayersAlphaProg(const char *passName, DataType type, int elementsize)
+ : RenderLayersProg(passName, type, elementsize) {}
void executePixelSampled(float output[4], float x, float y, PixelSampler sampler);
};
-class RenderLayersColorOperation : public RenderLayersBaseProg {
-public:
- RenderLayersColorOperation();
-};
-
-class RenderLayersCyclesOperation : public RenderLayersBaseProg {
+class RenderLayersDepthProg : public RenderLayersProg {
public:
- RenderLayersCyclesOperation(int pass);
-};
-
-class RenderLayersDepthProg : public RenderLayersBaseProg {
-public:
- RenderLayersDepthProg();
+ RenderLayersDepthProg(const char *passName, DataType type, int elementsize)
+ : RenderLayersProg(passName, type, elementsize) {}
void executePixelSampled(float output[4], float x, float y, PixelSampler sampler);
};
-class RenderLayersDiffuseOperation : public RenderLayersBaseProg {
-public:
- RenderLayersDiffuseOperation();
-};
-
-class RenderLayersEmitOperation : public RenderLayersBaseProg {
-public:
- RenderLayersEmitOperation();
-};
-
-class RenderLayersEnvironmentOperation : public RenderLayersBaseProg {
-public:
- RenderLayersEnvironmentOperation();
-};
-
-/// @todo rename to image operation
-class RenderLayersColorProg : public RenderLayersBaseProg {
-public:
- RenderLayersColorProg();
-};
-
-class RenderLayersIndirectOperation : public RenderLayersBaseProg {
-public:
- RenderLayersIndirectOperation();
-};
-
-class RenderLayersMaterialIndexOperation : public RenderLayersBaseProg {
-public:
- RenderLayersMaterialIndexOperation();
-};
-
-class RenderLayersMistOperation : public RenderLayersBaseProg {
-public:
- RenderLayersMistOperation();
-};
-
-class RenderLayersNormalOperation : public RenderLayersBaseProg {
-public:
- RenderLayersNormalOperation();
-};
-
-class RenderLayersObjectIndexOperation : public RenderLayersBaseProg {
-public:
- RenderLayersObjectIndexOperation();
-};
-
-class RenderLayersReflectionOperation : public RenderLayersBaseProg {
-public:
- RenderLayersReflectionOperation();
-};
-
-class RenderLayersRefractionOperation : public RenderLayersBaseProg {
-public:
- RenderLayersRefractionOperation();
-};
-
-class RenderLayersShadowOperation : public RenderLayersBaseProg {
-public:
- RenderLayersShadowOperation();
-};
-
-class RenderLayersSpecularOperation : public RenderLayersBaseProg {
-public:
- RenderLayersSpecularOperation();
-};
-
-class RenderLayersSpeedOperation : public RenderLayersBaseProg {
-public:
- RenderLayersSpeedOperation();
-};
-
-class RenderLayersUVOperation : public RenderLayersBaseProg {
-public:
- RenderLayersUVOperation();
-};
-
-#ifdef WITH_CYCLES_DEBUG
-class RenderLayersCyclesDebugOperation : public RenderLayersBaseProg {
-public:
- RenderLayersCyclesDebugOperation(int pass,
- int debug_pass_type);
-};
-#endif
-
#endif
diff --git a/source/blender/compositor/operations/COM_ScaleOperation.cpp b/source/blender/compositor/operations/COM_ScaleOperation.cpp
index 117ae743ee7..b498b359144 100644
--- a/source/blender/compositor/operations/COM_ScaleOperation.cpp
+++ b/source/blender/compositor/operations/COM_ScaleOperation.cpp
@@ -36,6 +36,7 @@ BaseScaleOperation::BaseScaleOperation()
#else
m_sampler = -1;
#endif
+ m_variable_size = false;
}
ScaleOperation::ScaleOperation() : BaseScaleOperation()
@@ -87,20 +88,27 @@ void ScaleOperation::executePixelSampled(float output[4], float x, float y, Pixe
bool ScaleOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output)
{
rcti newInput;
- float scaleX[4];
- float scaleY[4];
-
- this->m_inputXOperation->readSampled(scaleX, 0, 0, COM_PS_NEAREST);
- this->m_inputYOperation->readSampled(scaleY, 0, 0, COM_PS_NEAREST);
+ if (!m_variable_size) {
+ float scaleX[4];
+ float scaleY[4];
- const float scx = scaleX[0];
- const float scy = scaleY[0];
+ this->m_inputXOperation->readSampled(scaleX, 0, 0, COM_PS_NEAREST);
+ this->m_inputYOperation->readSampled(scaleY, 0, 0, COM_PS_NEAREST);
- newInput.xmax = this->m_centerX + (input->xmax - this->m_centerX) / scx;
- newInput.xmin = this->m_centerX + (input->xmin - this->m_centerX) / scx;
- newInput.ymax = this->m_centerY + (input->ymax - this->m_centerY) / scy;
- newInput.ymin = this->m_centerY + (input->ymin - this->m_centerY) / scy;
+ const float scx = scaleX[0];
+ const float scy = scaleY[0];
+ newInput.xmax = this->m_centerX + (input->xmax - this->m_centerX) / scx;
+ newInput.xmin = this->m_centerX + (input->xmin - this->m_centerX) / scx;
+ newInput.ymax = this->m_centerY + (input->ymax - this->m_centerY) / scy;
+ newInput.ymin = this->m_centerY + (input->ymin - this->m_centerY) / scy;
+ }
+ else {
+ newInput.xmax = this->getWidth();
+ newInput.xmin = 0;
+ newInput.ymax = this->getHeight();
+ newInput.ymin = 0;
+ }
return BaseScaleOperation::determineDependingAreaOfInterest(&newInput, readOperation, output);
}
@@ -162,24 +170,32 @@ void ScaleAbsoluteOperation::executePixelSampled(float output[4], float x, float
bool ScaleAbsoluteOperation::determineDependingAreaOfInterest(rcti *input, ReadBufferOperation *readOperation, rcti *output)
{
rcti newInput;
- float scaleX[4];
- float scaleY[4];
-
- this->m_inputXOperation->readSampled(scaleX, 0, 0, COM_PS_NEAREST);
- this->m_inputYOperation->readSampled(scaleY, 0, 0, COM_PS_NEAREST);
-
- const float scx = scaleX[0];
- const float scy = scaleY[0];
- const float width = this->getWidth();
- const float height = this->getHeight();
- //div
- float relateveXScale = scx / width;
- float relateveYScale = scy / height;
-
- newInput.xmax = this->m_centerX + (input->xmax - this->m_centerX) / relateveXScale;
- newInput.xmin = this->m_centerX + (input->xmin - this->m_centerX) / relateveXScale;
- newInput.ymax = this->m_centerY + (input->ymax - this->m_centerY) / relateveYScale;
- newInput.ymin = this->m_centerY + (input->ymin - this->m_centerY) / relateveYScale;
+ if (!m_variable_size) {
+ float scaleX[4];
+ float scaleY[4];
+
+ this->m_inputXOperation->readSampled(scaleX, 0, 0, COM_PS_NEAREST);
+ this->m_inputYOperation->readSampled(scaleY, 0, 0, COM_PS_NEAREST);
+
+ const float scx = scaleX[0];
+ const float scy = scaleY[0];
+ const float width = this->getWidth();
+ const float height = this->getHeight();
+ //div
+ float relateveXScale = scx / width;
+ float relateveYScale = scy / height;
+
+ newInput.xmax = this->m_centerX + (input->xmax - this->m_centerX) / relateveXScale;
+ newInput.xmin = this->m_centerX + (input->xmin - this->m_centerX) / relateveXScale;
+ newInput.ymax = this->m_centerY + (input->ymax - this->m_centerY) / relateveYScale;
+ newInput.ymin = this->m_centerY + (input->ymin - this->m_centerY) / relateveYScale;
+ }
+ else {
+ newInput.xmax = this->getWidth();
+ newInput.xmin = 0;
+ newInput.ymax = this->getHeight();
+ newInput.ymin = 0;
+ }
return BaseScaleOperation::determineDependingAreaOfInterest(&newInput, readOperation, output);
}
@@ -271,9 +287,9 @@ bool ScaleFixedSizeOperation::determineDependingAreaOfInterest(rcti *input, Read
{
rcti newInput;
- newInput.xmax = (input->xmax - m_offsetX) * this->m_relX;
+ newInput.xmax = (input->xmax - m_offsetX) * this->m_relX + 1;
newInput.xmin = (input->xmin - m_offsetX) * this->m_relX;
- newInput.ymax = (input->ymax - m_offsetY) * this->m_relY;
+ newInput.ymax = (input->ymax - m_offsetY) * this->m_relY + 1;
newInput.ymin = (input->ymin - m_offsetY) * this->m_relY;
return BaseScaleOperation::determineDependingAreaOfInterest(&newInput, readOperation, output);
diff --git a/source/blender/compositor/operations/COM_ScaleOperation.h b/source/blender/compositor/operations/COM_ScaleOperation.h
index 706a5898027..17cd31f9710 100644
--- a/source/blender/compositor/operations/COM_ScaleOperation.h
+++ b/source/blender/compositor/operations/COM_ScaleOperation.h
@@ -28,6 +28,7 @@
class BaseScaleOperation : public NodeOperation {
public:
void setSampler(PixelSampler sampler) { this->m_sampler = (int) sampler; }
+ void setVariableSize(bool variable_size) { m_variable_size = variable_size; };
protected:
BaseScaleOperation();
@@ -35,6 +36,7 @@ protected:
PixelSampler getEffectiveSampler(PixelSampler sampler) { return (m_sampler == -1) ? sampler : (PixelSampler) m_sampler; }
int m_sampler;
+ bool m_variable_size;
};
class ScaleOperation : public BaseScaleOperation {
diff --git a/source/blender/compositor/operations/COM_TextureOperation.cpp b/source/blender/compositor/operations/COM_TextureOperation.cpp
index 6bfd8ae3888..d0c72935b16 100644
--- a/source/blender/compositor/operations/COM_TextureOperation.cpp
+++ b/source/blender/compositor/operations/COM_TextureOperation.cpp
@@ -41,6 +41,7 @@ TextureBaseOperation::TextureBaseOperation() : NodeOperation()
this->m_rd = NULL;
this->m_pool = NULL;
this->m_sceneColorManage = false;
+ setComplex(true);
}
TextureOperation::TextureOperation() : TextureBaseOperation()
{
@@ -155,31 +156,3 @@ void TextureBaseOperation::executePixelSampled(float output[4], float x, float y
output[0] = output[1] = output[2] = output[3];
}
}
-
-MemoryBuffer *TextureBaseOperation::createMemoryBuffer(rcti * /*rect2*/)
-{
- int height = getHeight();
- int width = getWidth();
- DataType datatype = this->getOutputSocket()->getDataType();
- int add = 4;
- if (datatype == COM_DT_VALUE) {
- add = 1;
- }
-
- rcti rect;
- rect.xmin = 0;
- rect.ymin = 0;
- rect.xmax = width;
- rect.ymax = height;
- MemoryBuffer *result = new MemoryBuffer(datatype, &rect);
-
- float *data = result->getBuffer();
-
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++, data += add) {
- this->executePixelSampled(data, x, y, COM_PS_NEAREST);
- }
- }
-
- return result;
-}
diff --git a/source/blender/compositor/operations/COM_TextureOperation.h b/source/blender/compositor/operations/COM_TextureOperation.h
index 4cc203b54a2..59ff58a7289 100644
--- a/source/blender/compositor/operations/COM_TextureOperation.h
+++ b/source/blender/compositor/operations/COM_TextureOperation.h
@@ -59,8 +59,6 @@ protected:
* Constructor
*/
TextureBaseOperation();
-
- MemoryBuffer *createMemoryBuffer(rcti *rect2);
public:
void executePixelSampled(float output[4], float x, float y, PixelSampler sampler);
diff --git a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
index 1ec52571be8..9ff0bf9ce12 100644
--- a/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_VariableSizeBokehBlurOperation.cpp
@@ -286,9 +286,9 @@ void InverseSearchRadiusOperation::initExecution()
this->m_inputRadius = this->getInputSocketReader(0);
}
-voi *InverseSearchRadiusOperation::initializeTileData(rcti *rect)
+void *InverseSearchRadiusOperation::initializeTileData(rcti *rect)
{
- MemoryBuffer * data = new MemoryBuffer(NULL, rect);
+ MemoryBuffer * data = new MemoryBuffer(COM_DT_COLOR, rect);
float *buffer = data->getBuffer();
int x, y;
int width = this->m_inputRadius->getWidth();
@@ -343,7 +343,7 @@ voi *InverseSearchRadiusOperation::initializeTileData(rcti *rect)
void InverseSearchRadiusOperation::executePixelChunk(float output[4], int x, int y, void *data)
{
MemoryBuffer *buffer = (MemoryBuffer *)data;
- buffer->readNoCheck(color, x, y);
+ buffer->readNoCheck(output, x, y);
}
void InverseSearchRadiusOperation::deinitializeTileData(rcti *rect, void *data)
diff --git a/source/blender/compositor/operations/COM_VectorBlurOperation.cpp b/source/blender/compositor/operations/COM_VectorBlurOperation.cpp
index 36f06e92436..9c04e74a7da 100644
--- a/source/blender/compositor/operations/COM_VectorBlurOperation.cpp
+++ b/source/blender/compositor/operations/COM_VectorBlurOperation.cpp
@@ -20,16 +20,30 @@
* Monique Dewanchand
*/
-#include "COM_VectorBlurOperation.h"
-#include "BLI_math.h"
-
+#include <string.h>
#include "MEM_guardedalloc.h"
-
-// use the implementation of blender internal renderer to calculate the vector blur.
+#include "BLI_math.h"
extern "C" {
-# include "RE_pipeline.h"
+#include "BLI_jitter_2d.h"
}
+#include "COM_VectorBlurOperation.h"
+
+/* Defined */
+#define PASS_VECTOR_MAX 10000.0f
+
+/* Forward declarations */
+struct ZSpan;
+struct DrawBufPixel;
+void zbuf_accumulate_vecblur(
+ NodeBlurData *nbd, int xsize, int ysize, float *newrect,
+ const float *imgrect, float *vecbufrect, const float *zbufrect);
+void zbuf_alloc_span(ZSpan *zspan, int rectx, int recty, float clipcrop);
+void zbuf_free_span(ZSpan *zspan);
+void antialias_tagbuf(int xsize, int ysize, char *rectmove);
+
+
+/* VectorBlurOperation */
VectorBlurOperation::VectorBlurOperation() : NodeOperation()
{
this->addInputSocket(COM_DT_COLOR);
@@ -51,12 +65,12 @@ void VectorBlurOperation::initExecution()
this->m_inputSpeedProgram = getInputSocketReader(2);
this->m_cachedInstance = NULL;
QualityStepHelper::initExecution(COM_QH_INCREASE);
-
+
}
void VectorBlurOperation::executePixel(float output[4], int x, int y, void *data)
{
- float *buffer = (float *) data;
+ float *buffer = (float *)data;
int index = (y * this->getWidth() + x) * COM_NUM_CHANNELS_COLOR;
copy_v4_v4(output, &buffer[index]);
}
@@ -77,7 +91,7 @@ void *VectorBlurOperation::initializeTileData(rcti *rect)
if (this->m_cachedInstance) {
return this->m_cachedInstance;
}
-
+
lockMutex();
if (this->m_cachedInstance == NULL) {
MemoryBuffer *tile = (MemoryBuffer *)this->m_inputImageProgram->initializeTileData(rect);
@@ -114,6 +128,690 @@ void VectorBlurOperation::generateVectorBlur(float *data, MemoryBuffer *inputIma
blurdata.minspeed = this->m_settings->minspeed;
blurdata.curved = this->m_settings->curved;
blurdata.fac = this->m_settings->fac;
- RE_zbuf_accumulate_vecblur(&blurdata, this->getWidth(), this->getHeight(), data, inputImage->getBuffer(), inputSpeed->getBuffer(), inputZ->getBuffer());
+ zbuf_accumulate_vecblur(&blurdata, this->getWidth(), this->getHeight(), data, inputImage->getBuffer(), inputSpeed->getBuffer(), inputZ->getBuffer());
return;
}
+
+/* ****************** Spans ******************************* */
+/* span fill in method, is also used to localize data for zbuffering */
+typedef struct ZSpan {
+ /* range for clipping */
+ int rectx, recty;
+
+ /* actual filled in range */
+ int miny1, maxy1, miny2, maxy2;
+ /* vertex pointers detect min/max range in */
+ const float *minp1, *maxp1, *minp2, *maxp2;
+ float *span1, *span2;
+
+ /* transform from hoco to zbuf co */
+ float zmulx, zmuly, zofsx, zofsy;
+
+ int *rectz;
+ DrawBufPixel *rectdraw;
+ float clipcrop;
+
+} ZSpan;
+
+/* each zbuffer has coordinates transformed to local rect coordinates, so we can simply clip */
+void zbuf_alloc_span(ZSpan *zspan, int rectx, int recty, float clipcrop)
+{
+ memset(zspan, 0, sizeof(ZSpan));
+
+ zspan->rectx = rectx;
+ zspan->recty = recty;
+
+ zspan->span1 = (float *)MEM_mallocN(recty * sizeof(float), "zspan");
+ zspan->span2 = (float *)MEM_mallocN(recty * sizeof(float), "zspan");
+
+ zspan->clipcrop = clipcrop;
+}
+
+void zbuf_free_span(ZSpan *zspan)
+{
+ if (zspan) {
+ if (zspan->span1) MEM_freeN(zspan->span1);
+ if (zspan->span2) MEM_freeN(zspan->span2);
+ zspan->span1 = zspan->span2 = NULL;
+ }
+}
+
+/* reset range for clipping */
+static void zbuf_init_span(ZSpan *zspan)
+{
+ zspan->miny1 = zspan->miny2 = zspan->recty + 1;
+ zspan->maxy1 = zspan->maxy2 = -1;
+ zspan->minp1 = zspan->maxp1 = zspan->minp2 = zspan->maxp2 = NULL;
+}
+
+static void zbuf_add_to_span(ZSpan *zspan, const float v1[2], const float v2[2])
+{
+ const float *minv, *maxv;
+ float *span;
+ float xx1, dx0, xs0;
+ int y, my0, my2;
+
+ if (v1[1] < v2[1]) {
+ minv = v1; maxv = v2;
+ }
+ else {
+ minv = v2; maxv = v1;
+ }
+
+ my0 = ceil(minv[1]);
+ my2 = floor(maxv[1]);
+
+ if (my2 < 0 || my0 >= zspan->recty) return;
+
+ /* clip top */
+ if (my2 >= zspan->recty) my2 = zspan->recty - 1;
+ /* clip bottom */
+ if (my0 < 0) my0 = 0;
+
+ if (my0 > my2) return;
+ /* if (my0>my2) should still fill in, that way we get spans that skip nicely */
+
+ xx1 = maxv[1] - minv[1];
+ if (xx1 > FLT_EPSILON) {
+ dx0 = (minv[0] - maxv[0]) / xx1;
+ xs0 = dx0 * (minv[1] - my2) + minv[0];
+ }
+ else {
+ dx0 = 0.0f;
+ xs0 = min_ff(minv[0], maxv[0]);
+ }
+
+ /* empty span */
+ if (zspan->maxp1 == NULL) {
+ span = zspan->span1;
+ }
+ else { /* does it complete left span? */
+ if (maxv == zspan->minp1 || minv == zspan->maxp1) {
+ span = zspan->span1;
+ }
+ else {
+ span = zspan->span2;
+ }
+ }
+
+ if (span == zspan->span1) {
+// printf("left span my0 %d my2 %d\n", my0, my2);
+ if (zspan->minp1 == NULL || zspan->minp1[1] > minv[1]) {
+ zspan->minp1 = minv;
+ }
+ if (zspan->maxp1 == NULL || zspan->maxp1[1] < maxv[1]) {
+ zspan->maxp1 = maxv;
+ }
+ if (my0 < zspan->miny1) zspan->miny1 = my0;
+ if (my2 > zspan->maxy1) zspan->maxy1 = my2;
+ }
+ else {
+// printf("right span my0 %d my2 %d\n", my0, my2);
+ if (zspan->minp2 == NULL || zspan->minp2[1] > minv[1]) {
+ zspan->minp2 = minv;
+ }
+ if (zspan->maxp2 == NULL || zspan->maxp2[1] < maxv[1]) {
+ zspan->maxp2 = maxv;
+ }
+ if (my0 < zspan->miny2) zspan->miny2 = my0;
+ if (my2 > zspan->maxy2) zspan->maxy2 = my2;
+ }
+
+ for (y = my2; y >= my0; y--, xs0 += dx0) {
+ /* xs0 is the xcoord! */
+ span[y] = xs0;
+ }
+}
+
+/* ******************** VECBLUR ACCUM BUF ************************* */
+
+typedef struct DrawBufPixel {
+ const float *colpoin;
+ float alpha;
+} DrawBufPixel;
+
+
+static void zbuf_fill_in_rgba(ZSpan *zspan, DrawBufPixel *col, float *v1, float *v2, float *v3, float *v4)
+{
+ DrawBufPixel *rectpofs, *rp;
+ double zxd, zyd, zy0, zverg;
+ float x0, y0, z0;
+ float x1, y1, z1, x2, y2, z2, xx1;
+ const float *span1, *span2;
+ float *rectzofs, *rz;
+ int x, y;
+ int sn1, sn2, rectx, my0, my2;
+
+ /* init */
+ zbuf_init_span(zspan);
+
+ /* set spans */
+ zbuf_add_to_span(zspan, v1, v2);
+ zbuf_add_to_span(zspan, v2, v3);
+ zbuf_add_to_span(zspan, v3, v4);
+ zbuf_add_to_span(zspan, v4, v1);
+
+ /* clipped */
+ if (zspan->minp2 == NULL || zspan->maxp2 == NULL) return;
+
+ my0 = max_ii(zspan->miny1, zspan->miny2);
+ my2 = min_ii(zspan->maxy1, zspan->maxy2);
+
+ // printf("my %d %d\n", my0, my2);
+ if (my2 < my0) return;
+
+ /* ZBUF DX DY, in floats still */
+ x1 = v1[0] - v2[0];
+ x2 = v2[0] - v3[0];
+ y1 = v1[1] - v2[1];
+ y2 = v2[1] - v3[1];
+ z1 = v1[2] - v2[2];
+ z2 = v2[2] - v3[2];
+ x0 = y1 * z2 - z1 * y2;
+ y0 = z1 * x2 - x1 * z2;
+ z0 = x1 * y2 - y1 * x2;
+
+ if (z0 == 0.0f) return;
+
+ xx1 = (x0 * v1[0] + y0 * v1[1]) / z0 + v1[2];
+
+ zxd = -(double)x0 / (double)z0;
+ zyd = -(double)y0 / (double)z0;
+ zy0 = ((double)my2) * zyd + (double)xx1;
+
+ /* start-offset in rect */
+ rectx = zspan->rectx;
+ rectzofs = (float *)(zspan->rectz + rectx * my2);
+ rectpofs = ((DrawBufPixel *)zspan->rectdraw) + rectx * my2;
+
+ /* correct span */
+ sn1 = (my0 + my2) / 2;
+ if (zspan->span1[sn1] < zspan->span2[sn1]) {
+ span1 = zspan->span1 + my2;
+ span2 = zspan->span2 + my2;
+ }
+ else {
+ span1 = zspan->span2 + my2;
+ span2 = zspan->span1 + my2;
+ }
+
+ for (y = my2; y >= my0; y--, span1--, span2--) {
+
+ sn1 = floor(*span1);
+ sn2 = floor(*span2);
+ sn1++;
+
+ if (sn2 >= rectx) sn2 = rectx - 1;
+ if (sn1 < 0) sn1 = 0;
+
+ if (sn2 >= sn1) {
+ zverg = (double)sn1 * zxd + zy0;
+ rz = rectzofs + sn1;
+ rp = rectpofs + sn1;
+ x = sn2 - sn1;
+
+ while (x >= 0) {
+ if (zverg < (double)*rz) {
+ *rz = zverg;
+ *rp = *col;
+ }
+ zverg += zxd;
+ rz++;
+ rp++;
+ x--;
+ }
+ }
+
+ zy0 -= zyd;
+ rectzofs -= rectx;
+ rectpofs -= rectx;
+ }
+}
+
+/* char value==255 is filled in, rest should be zero */
+/* returns alpha values, but sets alpha to 1 for zero alpha pixels that have an alpha value as neighbor */
+void antialias_tagbuf(int xsize, int ysize, char *rectmove)
+{
+ char *row1, *row2, *row3;
+ char prev, next;
+ int a, x, y, step;
+
+ /* 1: tag pixels to be candidate for AA */
+ for (y = 2; y < ysize; y++) {
+ /* setup rows */
+ row1 = rectmove + (y - 2) * xsize;
+ row2 = row1 + xsize;
+ row3 = row2 + xsize;
+ for (x = 2; x < xsize; x++, row1++, row2++, row3++) {
+ if (row2[1]) {
+ if (row2[0] == 0 || row2[2] == 0 || row1[1] == 0 || row3[1] == 0)
+ row2[1] = 128;
+ }
+ }
+ }
+
+ /* 2: evaluate horizontal scanlines and calculate alphas */
+ row1 = rectmove;
+ for (y = 0; y < ysize; y++) {
+ row1++;
+ for (x = 1; x < xsize; x++, row1++) {
+ if (row1[0] == 128 && row1[1] == 128) {
+ /* find previous color and next color and amount of steps to blend */
+ prev = row1[-1];
+ step = 1;
+ while (x + step < xsize && row1[step] == 128)
+ step++;
+
+ if (x + step != xsize) {
+ /* now we can blend values */
+ next = row1[step];
+
+ /* note, prev value can be next value, but we do this loop to clear 128 then */
+ for (a = 0; a < step; a++) {
+ int fac, mfac;
+
+ fac = ((a + 1) << 8) / (step + 1);
+ mfac = 255 - fac;
+
+ row1[a] = (prev * mfac + next * fac) >> 8;
+ }
+ }
+ }
+ }
+ }
+
+ /* 3: evaluate vertical scanlines and calculate alphas */
+ /* use for reading a copy of the original tagged buffer */
+ for (x = 0; x < xsize; x++) {
+ row1 = rectmove + x + xsize;
+
+ for (y = 1; y < ysize; y++, row1 += xsize) {
+ if (row1[0] == 128 && row1[xsize] == 128) {
+ /* find previous color and next color and amount of steps to blend */
+ prev = row1[-xsize];
+ step = 1;
+ while (y + step < ysize && row1[step * xsize] == 128)
+ step++;
+
+ if (y + step != ysize) {
+ /* now we can blend values */
+ next = row1[step * xsize];
+ /* note, prev value can be next value, but we do this loop to clear 128 then */
+ for (a = 0; a < step; a++) {
+ int fac, mfac;
+
+ fac = ((a + 1) << 8) / (step + 1);
+ mfac = 255 - fac;
+
+ row1[a * xsize] = (prev * mfac + next * fac) >> 8;
+ }
+ }
+ }
+ }
+ }
+
+ /* last: pixels with 0 we fill in zbuffer, with 1 we skip for mask */
+ for (y = 2; y < ysize; y++) {
+ /* setup rows */
+ row1 = rectmove + (y - 2) * xsize;
+ row2 = row1 + xsize;
+ row3 = row2 + xsize;
+ for (x = 2; x < xsize; x++, row1++, row2++, row3++) {
+ if (row2[1] == 0) {
+ if (row2[0] > 1 || row2[2] > 1 || row1[1] > 1 || row3[1] > 1)
+ row2[1] = 1;
+ }
+ }
+ }
+}
+
+/* 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 - 0.5*p1 - 0.5*p3 */
+ p2[0] = -0.5f * p1[0] - 0.5f * p3[0];
+ p2[1] = -0.5f * p1[1] - 0.5f * 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 zbuf_accumulate_vecblur(
+ NodeBlurData *nbd, int xsize, int ysize, float *newrect,
+ const float *imgrect, float *vecbufrect, const float *zbufrect)
+{
+ ZSpan zspan;
+ DrawBufPixel *rectdraw, *dr;
+ static float jit[256][2];
+ float v1[3], v2[3], v3[3], v4[3], fx, fy;
+ const float *dimg, *dz, *ro;
+ float *rectvz, *dvz, *dvec1, *dvec2, *dz1, *dz2, *rectz;
+ float *minvecbufrect = NULL, *rectweight, *rw, *rectmax, *rm;
+ float maxspeedsq = (float)nbd->maxspeed * nbd->maxspeed;
+ int y, x, step, maxspeed = nbd->maxspeed, samples = nbd->samples;
+ int tsktsk = 0;
+ static int firsttime = 1;
+ char *rectmove, *dm;
+
+ zbuf_alloc_span(&zspan, xsize, ysize, 1.0f);
+ zspan.zmulx = ((float)xsize) / 2.0f;
+ zspan.zmuly = ((float)ysize) / 2.0f;
+ zspan.zofsx = 0.0f;
+ zspan.zofsy = 0.0f;
+
+ /* the buffers */
+ rectz = (float *)MEM_mapallocN(sizeof(float) * xsize * ysize, "zbuf accum");
+ zspan.rectz = (int *)rectz;
+
+ rectmove = (char *)MEM_mapallocN(xsize * ysize, "rectmove");
+ rectdraw = (DrawBufPixel *)MEM_mapallocN(sizeof(DrawBufPixel) * xsize * ysize, "rect draw");
+ zspan.rectdraw = rectdraw;
+
+ rectweight = (float *)MEM_mapallocN(sizeof(float) * xsize * ysize, "rect weight");
+ rectmax = (float *)MEM_mapallocN(sizeof(float) * xsize * ysize, "rect max");
+
+ /* debug... check if PASS_VECTOR_MAX still is in buffers */
+ dvec1 = vecbufrect;
+ for (x = 4 * xsize * ysize; x > 0; x--, dvec1++) {
+ if (dvec1[0] == PASS_VECTOR_MAX) {
+ dvec1[0] = 0.0f;
+ tsktsk = 1;
+ }
+ }
+ if (tsktsk) printf("Found uninitialized speed in vector buffer... fixed.\n");
+
+ /* min speed? then copy speedbuffer to recalculate speed vectors */
+ if (nbd->minspeed) {
+ float minspeed = (float)nbd->minspeed;
+ float minspeedsq = minspeed * minspeed;
+
+ minvecbufrect = (float *)MEM_mapallocN(4 * sizeof(float) * xsize * ysize, "minspeed buf");
+
+ dvec1 = vecbufrect;
+ dvec2 = minvecbufrect;
+ for (x = 2 * xsize * ysize; x > 0; x--, dvec1 += 2, dvec2 += 2) {
+ if (dvec1[0] == 0.0f && dvec1[1] == 0.0f) {
+ dvec2[0] = dvec1[0];
+ dvec2[1] = dvec1[1];
+ }
+ else {
+ float speedsq = dvec1[0] * dvec1[0] + dvec1[1] * dvec1[1];
+ if (speedsq <= minspeedsq) {
+ dvec2[0] = 0.0f;
+ dvec2[1] = 0.0f;
+ }
+ else {
+ speedsq = 1.0f - minspeed / sqrtf(speedsq);
+ dvec2[0] = speedsq * dvec1[0];
+ dvec2[1] = speedsq * dvec1[1];
+ }
+ }
+ }
+ SWAP(float *, minvecbufrect, vecbufrect);
+ }
+
+ /* make vertex buffer with averaged speed and zvalues */
+ rectvz = (float *)MEM_mapallocN(4 * sizeof(float) * (xsize + 1) * (ysize + 1), "vertices");
+ dvz = rectvz;
+ for (y = 0; y <= ysize; y++) {
+
+ if (y == 0)
+ dvec1 = vecbufrect + 4 * y * xsize;
+ else
+ dvec1 = vecbufrect + 4 * (y - 1) * xsize;
+
+ if (y == ysize)
+ dvec2 = vecbufrect + 4 * (y - 1) * xsize;
+ else
+ dvec2 = vecbufrect + 4 * y * xsize;
+
+ for (x = 0; x <= xsize; x++) {
+
+ /* two vectors, so a step loop */
+ for (step = 0; step < 2; step++, dvec1 += 2, dvec2 += 2, dvz += 2) {
+ /* average on minimal speed */
+ int div = 0;
+
+ if (x != 0) {
+ if (dvec1[-4] != 0.0f || dvec1[-3] != 0.0f) {
+ dvz[0] = dvec1[-4];
+ dvz[1] = dvec1[-3];
+ div++;
+ }
+ if (dvec2[-4] != 0.0f || dvec2[-3] != 0.0f) {
+ if (div == 0) {
+ dvz[0] = dvec2[-4];
+ dvz[1] = dvec2[-3];
+ div++;
+ }
+ else if ( (ABS(dvec2[-4]) + ABS(dvec2[-3])) < (ABS(dvz[0]) + ABS(dvz[1])) ) {
+ dvz[0] = dvec2[-4];
+ dvz[1] = dvec2[-3];
+ }
+ }
+ }
+
+ if (x != xsize) {
+ if (dvec1[0] != 0.0f || dvec1[1] != 0.0f) {
+ if (div == 0) {
+ dvz[0] = dvec1[0];
+ dvz[1] = dvec1[1];
+ div++;
+ }
+ else if ( (ABS(dvec1[0]) + ABS(dvec1[1])) < (ABS(dvz[0]) + ABS(dvz[1])) ) {
+ dvz[0] = dvec1[0];
+ dvz[1] = dvec1[1];
+ }
+ }
+ if (dvec2[0] != 0.0f || dvec2[1] != 0.0f) {
+ if (div == 0) {
+ dvz[0] = dvec2[0];
+ dvz[1] = dvec2[1];
+ }
+ else if ( (ABS(dvec2[0]) + ABS(dvec2[1])) < (ABS(dvz[0]) + ABS(dvz[1])) ) {
+ dvz[0] = dvec2[0];
+ dvz[1] = dvec2[1];
+ }
+ }
+ }
+ if (maxspeed) {
+ float speedsq = dvz[0] * dvz[0] + dvz[1] * dvz[1];
+ if (speedsq > maxspeedsq) {
+ speedsq = (float)maxspeed / sqrtf(speedsq);
+ dvz[0] *= speedsq;
+ dvz[1] *= speedsq;
+ }
+ }
+ }
+ }
+ }
+
+ /* set border speeds to keep border speeds on border */
+ dz1 = rectvz;
+ 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 + 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;
+ dz2[2] = 0.0f;
+ }
+
+ /* tag moving pixels, only these faces we draw */
+ 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))
+ *dm = 255;
+ }
+
+ antialias_tagbuf(xsize, ysize, rectmove);
+
+ /* has to become static, the init-jit calls a random-seed, screwing up texture noise node */
+ if (firsttime) {
+ firsttime = 0;
+ BLI_jitter_init(jit, 256);
+ }
+
+ memset(newrect, 0, sizeof(float) * xsize * ysize * 4);
+
+ /* accumulate */
+ samples /= 2;
+ for (step = 1; step <= samples; step++) {
+ float speedfac = 0.5f * nbd->fac * (float)step / (float)(samples + 1);
+ 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)
+ for (x = xsize * ysize - 1; x >= 0; x--) rectz[x] = 10e16;
+ else
+ for (x = xsize * ysize - 1; x >= 0; x--) {
+ if (rectmove[x] == 0)
+ rectz[x] = zbufrect[x];
+ else
+ rectz[x] = 10e16;
+ }
+
+ /* clear drawing buffer */
+ for (x = xsize * ysize - 1; x >= 0; x--) rectdraw[x].colpoin = NULL;
+
+ dimg = imgrect;
+ dm = rectmove;
+ dz = zbufrect;
+ dz1 = rectvz;
+ dz2 = rectvz + 4 * (xsize + 1);
+
+ if (side) {
+ if (nbd->curved == 0) {
+ dz1 += 2;
+ dz2 += 2;
+ }
+ speedfac = -speedfac;
+ }
+
+ 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 */
+ 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 {
+ ARRAY_SET_ITEMS(v1, speedfac * dz1[0] + jfx, speedfac * dz1[1] + jfy, *dz);
+ ARRAY_SET_ITEMS(v2, speedfac * dz1[4] + jfx + 1.0f, speedfac * dz1[5] + jfy, *dz);
+ ARRAY_SET_ITEMS(v3, speedfac * dz2[4] + jfx + 1.0f, speedfac * dz2[5] + jfy + 1.0f, *dz);
+ ARRAY_SET_ITEMS(v4, speedfac * dz2[0] + jfx, speedfac * dz2[1] + jfy + 1.0f, *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 += 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 */
+ 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;
+
+ 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);
+}
diff --git a/source/blender/compositor/operations/COM_ViewerOperation.cpp b/source/blender/compositor/operations/COM_ViewerOperation.cpp
index aa47d3427d0..42fe24120dc 100644
--- a/source/blender/compositor/operations/COM_ViewerOperation.cpp
+++ b/source/blender/compositor/operations/COM_ViewerOperation.cpp
@@ -135,14 +135,14 @@ void ViewerOperation::initImage()
BKE_image_verify_viewer_views(this->m_rd, ima, this->m_imageUser);
}
- BLI_lock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_lock(LOCK_DRAW_IMAGE);
/* local changes to the original ImageUser */
iuser.multi_index = BKE_scene_multiview_view_id_get(this->m_rd, this->m_viewName);
ibuf = BKE_image_acquire_ibuf(ima, &iuser, &lock);
if (!ibuf) {
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
return;
}
if (ibuf->x != (int)getWidth() || ibuf->y != (int)getHeight()) {
@@ -176,7 +176,7 @@ void ViewerOperation::initImage()
BKE_image_release_ibuf(this->m_image, this->m_ibuf, lock);
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
}
void ViewerOperation::updateImage(rcti *rect)
diff --git a/source/blender/datatoc/datatoc.c b/source/blender/datatoc/datatoc.c
index 4e49a9a7694..ffccca98f99 100644
--- a/source/blender/datatoc/datatoc.c
+++ b/source/blender/datatoc/datatoc.c
@@ -91,6 +91,11 @@ int main(int argc, char **argv)
}
fprintf(fpout, "/* DataToC output of file <%s> */\n\n", argv[1]);
+
+ /* Quiet 'missing-variable-declarations' warning. */
+ fprintf(fpout, "extern int datatoc_%s_size;\n", argv[1]);
+ fprintf(fpout, "extern char datatoc_%s[];\n\n", argv[1]);
+
fprintf(fpout, "int datatoc_%s_size = %d;\n", argv[1], (int)size);
fprintf(fpout, "char datatoc_%s[] = {\n", argv[1]);
while (size--) {
diff --git a/source/blender/depsgraph/CMakeLists.txt b/source/blender/depsgraph/CMakeLists.txt
index e635256cda6..50c0910ef02 100644
--- a/source/blender/depsgraph/CMakeLists.txt
+++ b/source/blender/depsgraph/CMakeLists.txt
@@ -42,6 +42,7 @@ set(INC_SYS
set(SRC
intern/builder/deg_builder.cc
intern/builder/deg_builder_cycle.cc
+ intern/builder/deg_builder_map.cc
intern/builder/deg_builder_nodes.cc
intern/builder/deg_builder_nodes_rig.cc
intern/builder/deg_builder_nodes_scene.cc
@@ -51,18 +52,22 @@ set(SRC
intern/builder/deg_builder_relations_rig.cc
intern/builder/deg_builder_relations_scene.cc
intern/builder/deg_builder_transitive.cc
- intern/debug/deg_debug_graphviz.cc
+ intern/debug/deg_debug_relations_graphviz.cc
+ intern/debug/deg_debug_stats_gnuplot.cc
intern/eval/deg_eval.cc
- intern/eval/deg_eval_debug.cc
intern/eval/deg_eval_flush.cc
+ intern/eval/deg_eval_stats.cc
intern/nodes/deg_node.cc
intern/nodes/deg_node_component.cc
+ intern/nodes/deg_node_id.cc
intern/nodes/deg_node_operation.cc
+ intern/nodes/deg_node_time.cc
intern/depsgraph.cc
intern/depsgraph_build.cc
intern/depsgraph_debug.cc
intern/depsgraph_eval.cc
intern/depsgraph_query.cc
+ intern/depsgraph_query_foreach.cc
intern/depsgraph_tag.cc
intern/depsgraph_type_defines.cc
@@ -73,22 +78,26 @@ set(SRC
intern/builder/deg_builder.h
intern/builder/deg_builder_cycle.h
+ intern/builder/deg_builder_map.h
intern/builder/deg_builder_nodes.h
intern/builder/deg_builder_pchanmap.h
intern/builder/deg_builder_relations.h
+ intern/builder/deg_builder_relations_impl.h
intern/builder/deg_builder_transitive.h
intern/eval/deg_eval.h
- intern/eval/deg_eval_debug.h
intern/eval/deg_eval_flush.h
+ intern/eval/deg_eval_stats.h
intern/nodes/deg_node.h
intern/nodes/deg_node_component.h
+ intern/nodes/deg_node_id.h
intern/nodes/deg_node_operation.h
+ intern/nodes/deg_node_time.h
intern/depsgraph.h
intern/depsgraph_intern.h
intern/depsgraph_types.h
+ util/deg_util_foreach.h
util/deg_util_function.h
- util/deg_util_hash.h
)
if(WITH_CXX11)
diff --git a/source/blender/depsgraph/DEG_depsgraph.h b/source/blender/depsgraph/DEG_depsgraph.h
index 945a4785b9c..72e90f49748 100644
--- a/source/blender/depsgraph/DEG_depsgraph.h
+++ b/source/blender/depsgraph/DEG_depsgraph.h
@@ -111,8 +111,6 @@ void DEG_on_visible_update(struct Main *bmain, const bool do_time);
void DEG_graph_id_tag_update(struct Main *bmain,
Depsgraph *graph,
struct ID *id);
-void DEG_graph_data_tag_update(Depsgraph *graph, const struct PointerRNA *ptr);
-void DEG_graph_property_tag_update(Depsgraph *graph, const struct PointerRNA *ptr, const struct PropertyRNA *prop);
/* Tag given ID for an update in all the dependency graphs. */
void DEG_id_tag_update(struct ID *id, short flag);
@@ -120,10 +118,9 @@ void DEG_id_tag_update_ex(struct Main *bmain,
struct ID *id,
short flag);
-/* Tag given ID type for update.
- *
- * Used by all sort of render engines to quickly check if
- * IDs of a given type need to be checked for update.
+/* Mark a particular datablock type as having changing. This does
+ * not cause any updates but is used by external render engines to detect if for
+ * example a datablock was removed.
*/
void DEG_id_type_tag(struct Main *bmain, short idtype);
@@ -134,6 +131,9 @@ void DEG_ids_clear_recalc(struct Main *bmain);
/* Flush updates for all IDs */
void DEG_ids_flush_tagged(struct Main *bmain);
+/* Flush updates for IDs in a single scene. */
+void DEG_scene_flush_update(struct Main *bmain, struct Scene *scene);
+
/* Check if something was changed in the database and inform
* editors about this.
*/
@@ -208,6 +208,32 @@ void DEG_editors_set_update_cb(DEG_EditorUpdateIDCb id_func,
void DEG_editors_update_pre(struct Main *bmain, struct Scene *scene, bool time);
+/* Evaluation Debug ------------------------------ */
+
+void DEG_debug_print_eval(const char* function_name,
+ const char* object_name,
+ const void* object_address);
+
+void DEG_debug_print_eval_subdata(const char *function_name,
+ const char *object_name,
+ const void *object_address,
+ const char *subdata_comment,
+ const char *subdata_name,
+ const void *subdata_address);
+
+void DEG_debug_print_eval_subdata_index(const char *function_name,
+ const char *object_name,
+ const void *object_address,
+ const char *subdata_comment,
+ const char *subdata_name,
+ const void *subdata_address,
+ const int subdata_index);
+
+void DEG_debug_print_eval_time(const char* function_name,
+ const char* object_name,
+ const void* object_address,
+ float time);
+
#ifdef __cplusplus
} /* extern "C" */
#endif
diff --git a/source/blender/depsgraph/DEG_depsgraph_build.h b/source/blender/depsgraph/DEG_depsgraph_build.h
index fdc86540171..b268822f659 100644
--- a/source/blender/depsgraph/DEG_depsgraph_build.h
+++ b/source/blender/depsgraph/DEG_depsgraph_build.h
@@ -44,6 +44,8 @@ struct Main;
struct Scene;
struct Group;
struct EffectorWeights;
+struct ModifierData;
+struct Object;
#ifdef __cplusplus
extern "C" {
@@ -139,12 +141,12 @@ void DEG_add_scene_relation(struct DepsNodeHandle *node,
struct Scene *scene,
eDepsSceneComponentType component,
const char *description);
-void DEG_add_object_relation(struct DepsNodeHandle *node, struct
- Object *ob,
+void DEG_add_object_relation(struct DepsNodeHandle *node,
+ struct Object *object,
eDepsObjectComponentType component,
const char *description);
void DEG_add_bone_relation(struct DepsNodeHandle *handle,
- struct Object *ob,
+ struct Object *object,
const char *bone_name,
eDepsObjectComponentType component,
const char *description);
@@ -153,7 +155,8 @@ void DEG_add_object_cache_relation(struct DepsNodeHandle *handle,
eDepsObjectComponentType component,
const char *description);
-/* TODO(sergey): Remove once all geometry update is granular. */
+
+struct Depsgraph *DEG_get_graph_from_handle(struct DepsNodeHandle *handle);
void DEG_add_special_eval_flag(struct Depsgraph *graph, struct ID *id, short flag);
/* Utility functions for physics modifiers */
@@ -161,7 +164,7 @@ typedef bool (*DEG_CollobjFilterFunction)(struct Object *obj, struct ModifierDat
void DEG_add_collision_relations(struct DepsNodeHandle *handle,
struct Scene *scene,
- Object *ob,
+ struct Object *object,
struct Group *group,
int layer,
unsigned int modifier_type,
@@ -170,7 +173,7 @@ void DEG_add_collision_relations(struct DepsNodeHandle *handle,
const char *name);
void DEG_add_forcefield_relations(struct DepsNodeHandle *handle,
struct Scene *scene,
- Object *ob,
+ struct Object *object,
struct EffectorWeights *eff,
bool add_absorption,
int skip_forcefield,
diff --git a/source/blender/depsgraph/DEG_depsgraph_debug.h b/source/blender/depsgraph/DEG_depsgraph_debug.h
index 0d19b8e1e97..bc93fcc94cb 100644
--- a/source/blender/depsgraph/DEG_depsgraph_debug.h
+++ b/source/blender/depsgraph/DEG_depsgraph_debug.h
@@ -39,45 +39,11 @@
extern "C" {
#endif
-struct GHash;
-struct ID;
-
struct Depsgraph;
-/* ************************************************ */
-/* Statistics */
-
-typedef struct DepsgraphStatsTimes {
- float duration_last;
-} DepsgraphStatsTimes;
-
-typedef struct DepsgraphStatsComponent {
- struct DepsgraphStatsComponent *next, *prev;
-
- char name[64];
- DepsgraphStatsTimes times;
-} DepsgraphStatsComponent;
-
-typedef struct DepsgraphStatsID {
- struct ID *id;
-
- DepsgraphStatsTimes times;
- ListBase components;
-} DepsgraphStatsID;
-
-typedef struct DepsgraphStats {
- struct GHash *id_stats;
-} DepsgraphStats;
-
-struct DepsgraphStats *DEG_stats(void);
-
-void DEG_stats_verify(void);
-
-struct DepsgraphStatsID *DEG_stats_id(struct ID *id);
-
/* ------------------------------------------------ */
-void DEG_stats_simple(const struct Depsgraph *graph,
+void DEG_stats_simple(const struct Depsgraph *graph,
size_t *r_outer,
size_t *r_operations,
size_t *r_relations);
@@ -85,7 +51,14 @@ void DEG_stats_simple(const struct Depsgraph *graph,
/* ************************************************ */
/* Diagram-Based Graph Debugging */
-void DEG_debug_graphviz(const struct Depsgraph *graph, FILE *stream, const char *label, bool show_eval);
+void DEG_debug_relations_graphviz(const struct Depsgraph *graph,
+ FILE *stream,
+ const char *label);
+
+void DEG_debug_stats_gnuplot(const struct Depsgraph *graph,
+ FILE *stream,
+ const char *label,
+ const char *output_filename);
/* ************************************************ */
diff --git a/source/blender/depsgraph/DEG_depsgraph_query.h b/source/blender/depsgraph/DEG_depsgraph_query.h
index ccd204a2083..f8cfb407831 100644
--- a/source/blender/depsgraph/DEG_depsgraph_query.h
+++ b/source/blender/depsgraph/DEG_depsgraph_query.h
@@ -47,6 +47,18 @@ bool DEG_id_type_tagged(struct Main *bmain, short idtype);
/* Get additional evaluation flags for the given ID. */
short DEG_get_eval_flags_for_id(struct Depsgraph *graph, struct ID *id);
+/* ************************ DEG traversal ********************* */
+
+typedef void (*DEGForeachIDCallback)(ID *id, void *user_data);
+
+/* NOTE: Modifies runtime flags in depsgraph nodes, so can not be used in
+ * parallel. Keep an eye on that!
+ */
+void DEG_foreach_dependent_ID(const Depsgraph *depsgraph,
+ const ID *id,
+ DEGForeachIDCallback callback, void *user_data);
+
+
#ifdef __cplusplus
} /* extern "C" */
#endif
diff --git a/source/blender/depsgraph/intern/builder/deg_builder.cc b/source/blender/depsgraph/intern/builder/deg_builder.cc
index cb2f057a090..5713297d658 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder.cc
@@ -30,20 +30,19 @@
#include "intern/builder/deg_builder.h"
-// TODO(sergey): Use own wrapper over STD.
-#include <stack>
-
#include "DNA_anim_types.h"
#include "DNA_object_types.h"
#include "DNA_ID.h"
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
+#include "BLI_stack.h"
#include "intern/depsgraph.h"
#include "intern/depsgraph_types.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "util/deg_util_foreach.h"
@@ -52,14 +51,6 @@
namespace DEG {
-string deg_fcurve_id_name(const FCurve *fcu)
-{
- char index_buf[32];
- // TODO(sergey): Use int-to-string utility or so.
- BLI_snprintf(index_buf, sizeof(index_buf), "[%d]", fcu->array_index);
- return string(fcu->rna_path) + index_buf;
-}
-
static bool check_object_needs_evaluation(Object *object)
{
if (object->recalc & OB_RECALC_ALL) {
@@ -77,86 +68,90 @@ static bool check_object_needs_evaluation(Object *object)
return false;
}
-void deg_graph_build_finalize(Depsgraph *graph)
+void deg_graph_build_flush_layers(Depsgraph *graph)
{
- /* STEP 1: Make sure new invisible dependencies are ready for use.
- *
- * TODO(sergey): This might do a bit of extra tagging, but it's kinda nice
- * to do it ahead of a time and don't spend time on flushing updates on
- * every frame change.
- */
- GHASH_FOREACH_BEGIN(IDDepsNode *, id_node, graph->id_hash)
- {
- if (id_node->layers == 0) {
- ID *id = id_node->id;
- if (GS(id->name) == ID_OB) {
- Object *object = (Object *)id;
- if (check_object_needs_evaluation(object)) {
- id_node->tag_update(graph);
- }
- }
- }
- }
- GHASH_FOREACH_END();
- /* STEP 2: Flush visibility layers from children to parent. */
- std::stack<OperationDepsNode *> stack;
+ BLI_Stack *stack = BLI_stack_new(sizeof(OperationDepsNode *),
+ "DEG flush layers stack");
foreach (OperationDepsNode *node, graph->operations) {
IDDepsNode *id_node = node->owner->owner;
node->done = 0;
node->num_links_pending = 0;
foreach (DepsRelation *rel, node->outlinks) {
- if ((rel->from->type == DEPSNODE_TYPE_OPERATION) &&
+ if ((rel->from->type == DEG_NODE_TYPE_OPERATION) &&
(rel->flag & DEPSREL_FLAG_CYCLIC) == 0)
{
++node->num_links_pending;
}
}
if (node->num_links_pending == 0) {
- stack.push(node);
+ BLI_stack_push(stack, &node);
node->done = 1;
}
node->owner->layers = id_node->layers;
id_node->id->tag |= LIB_TAG_DOIT;
}
- while (!stack.empty()) {
- OperationDepsNode *node = stack.top();
- stack.pop();
+ while (!BLI_stack_is_empty(stack)) {
+ OperationDepsNode *node;
+ BLI_stack_pop(stack, &node);
/* Flush layers to parents. */
foreach (DepsRelation *rel, node->inlinks) {
- if (rel->from->type == DEPSNODE_TYPE_OPERATION) {
+ if (rel->from->type == DEG_NODE_TYPE_OPERATION) {
OperationDepsNode *from = (OperationDepsNode *)rel->from;
from->owner->layers |= node->owner->layers;
}
}
/* Schedule parent nodes. */
foreach (DepsRelation *rel, node->inlinks) {
- if (rel->from->type == DEPSNODE_TYPE_OPERATION) {
+ if (rel->from->type == DEG_NODE_TYPE_OPERATION) {
OperationDepsNode *from = (OperationDepsNode *)rel->from;
if ((rel->flag & DEPSREL_FLAG_CYCLIC) == 0) {
BLI_assert(from->num_links_pending > 0);
--from->num_links_pending;
}
if (from->num_links_pending == 0 && from->done == 0) {
- stack.push(from);
+ BLI_stack_push(stack, &from);
from->done = 1;
}
}
}
}
+ BLI_stack_free(stack);
+}
+
+void deg_graph_build_finalize(Depsgraph *graph)
+{
+ /* STEP 1: Make sure new invisible dependencies are ready for use.
+ *
+ * TODO(sergey): This might do a bit of extra tagging, but it's kinda nice
+ * to do it ahead of a time and don't spend time on flushing updates on
+ * every frame change.
+ */
+ foreach (IDDepsNode *id_node, graph->id_nodes) {
+ if (id_node->layers == 0) {
+ ID *id = id_node->id;
+ if (GS(id->name) == ID_OB) {
+ Object *object = (Object *)id;
+ if (check_object_needs_evaluation(object)) {
+ id_node->tag_update(graph);
+ }
+ }
+ }
+ }
+ /* STEP 2: Flush visibility layers from children to parent. */
+ deg_graph_build_flush_layers(graph);
/* STEP 3: Re-tag IDs for update if it was tagged before the relations
* update tag.
*/
- GHASH_FOREACH_BEGIN(IDDepsNode *, id_node, graph->id_hash)
- {
+ foreach (IDDepsNode *id_node, graph->id_nodes) {
GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp, id_node->components)
{
id_node->layers |= comp->layers;
}
GHASH_FOREACH_END();
- if ((id_node->layers & graph->layers) != 0) {
+ if ((id_node->layers & graph->layers) != 0 || graph->layers == 0) {
ID *id = id_node->id;
- if ((id->tag & LIB_TAG_ID_RECALC_ALL) &&
+ if ((id->recalc & ID_RECALC_ALL) &&
(id->tag & LIB_TAG_DOIT))
{
id_node->tag_update(graph);
@@ -172,7 +167,6 @@ void deg_graph_build_finalize(Depsgraph *graph)
}
id_node->finalize_build();
}
- GHASH_FOREACH_END();
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder.h b/source/blender/depsgraph/intern/builder/deg_builder.h
index bdc030e3810..b8ea8c8e599 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder.h
+++ b/source/blender/depsgraph/intern/builder/deg_builder.h
@@ -38,9 +38,7 @@ namespace DEG {
struct Depsgraph;
-/* Get unique identifier for FCurves and Drivers */
-string deg_fcurve_id_name(const FCurve *fcu);
-
void deg_graph_build_finalize(struct Depsgraph *graph);
+void deg_graph_build_flush_layers(struct Depsgraph *graph);
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc b/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc
index 9b37aaa12ff..026aa309b02 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_cycle.cc
@@ -32,11 +32,9 @@
// TOO(sergey): Use some wrappers over those?
#include <cstdio>
#include <cstdlib>
-#include <stack>
-extern "C" {
#include "BLI_utildefines.h"
-}
+#include "BLI_stack.h"
#include "util/deg_util_foreach.h"
@@ -48,61 +46,128 @@ extern "C" {
namespace DEG {
+namespace {
+
+typedef enum eCyclicCheckVisitedState {
+ /* Not is not visited at all during traversal. */
+ NODE_NOT_VISITED = 0,
+ /* Node has been visited during traversal and not in current stack. */
+ NODE_VISITED = 1,
+ /* Node has been visited during traversal and is in current stack. */
+ NODE_IN_STACK = 2,
+} eCyclicCheckVisitedState;
+
struct StackEntry {
OperationDepsNode *node;
StackEntry *from;
DepsRelation *via_relation;
};
-void deg_graph_detect_cycles(Depsgraph *graph)
+struct CyclesSolverState {
+ CyclesSolverState(Depsgraph *graph)
+ : graph(graph),
+ traversal_stack(BLI_stack_new(sizeof(StackEntry),
+ "DEG detect cycles stack")),
+ num_cycles(0) {
+ }
+ ~CyclesSolverState() {
+ BLI_stack_free(traversal_stack);
+ if (num_cycles != 0) {
+ printf("Detected %d dependency cycles\n", num_cycles);
+ }
+ }
+ Depsgraph *graph;
+ BLI_Stack *traversal_stack;
+ int num_cycles;
+};
+
+BLI_INLINE void set_node_visited_state(DepsNode *node,
+ eCyclicCheckVisitedState state)
+{
+ node->done = (node->done & ~0x3) | (int)state;
+}
+
+BLI_INLINE eCyclicCheckVisitedState get_node_visited_state(DepsNode *node)
+{
+ return (eCyclicCheckVisitedState)(node->done & 0x3);
+}
+
+BLI_INLINE void set_node_num_visited_children(DepsNode *node, int num_children)
+{
+ node->done = (node->done & 0x3) | (num_children << 2);
+}
+
+BLI_INLINE int get_node_num_visited_children(DepsNode *node)
+{
+ return node->done >> 2;
+}
+
+void schedule_node_to_stack(CyclesSolverState *state, OperationDepsNode *node)
{
- enum {
- /* Not is not visited at all during traversal. */
- NODE_NOT_VISITED = 0,
- /* Node has been visited during traversal and not in current stack. */
- NODE_VISITED = 1,
- /* Node has been visited during traversal and is in current stack. */
- NODE_IN_STACK = 2,
- };
-
- std::stack<StackEntry> traversal_stack;
- foreach (OperationDepsNode *node, graph->operations) {
+ StackEntry entry;
+ entry.node = node;
+ entry.from = NULL;
+ entry.via_relation = NULL;
+ BLI_stack_push(state->traversal_stack, &entry);
+ set_node_visited_state(node, NODE_IN_STACK);
+}
+
+/* Schedule leaf nodes (node without input links) for traversal. */
+void schedule_leaf_nodes(CyclesSolverState *state)
+{
+ foreach (OperationDepsNode *node, state->graph->operations) {
bool has_inlinks = false;
foreach (DepsRelation *rel, node->inlinks) {
- if (rel->from->type == DEPSNODE_TYPE_OPERATION) {
+ if (rel->from->type == DEG_NODE_TYPE_OPERATION) {
has_inlinks = true;
}
}
+ node->done = 0;
if (has_inlinks == false) {
- StackEntry entry;
- entry.node = node;
- entry.from = NULL;
- entry.via_relation = NULL;
- traversal_stack.push(entry);
- node->tag = NODE_IN_STACK;
+ schedule_node_to_stack(state, node);
}
else {
- node->tag = NODE_NOT_VISITED;
+ set_node_visited_state(node, NODE_NOT_VISITED);
+ }
+ }
+}
+
+/* Schedule node which was not checked yet for being belong to
+ * any of dependency cycle.
+ */
+bool schedule_non_checked_node(CyclesSolverState *state)
+{
+ foreach (OperationDepsNode *node, state->graph->operations) {
+ if (get_node_visited_state(node) == NODE_NOT_VISITED) {
+ schedule_node_to_stack(state, node);
+ return true;
}
- node->done = 0;
}
+ return false;
+}
- while (!traversal_stack.empty()) {
- StackEntry& entry = traversal_stack.top();
- OperationDepsNode *node = entry.node;
+/* Solve cycles with all nodes which are scheduled for traversal. */
+void solve_cycles(CyclesSolverState *state)
+{
+ BLI_Stack *traversal_stack = state->traversal_stack;
+ while (!BLI_stack_is_empty(traversal_stack)) {
+ StackEntry *entry = (StackEntry *)BLI_stack_peek(traversal_stack);
+ OperationDepsNode *node = entry->node;
bool all_child_traversed = true;
- for (int i = node->done; i < node->outlinks.size(); ++i) {
+ const int num_visited = get_node_num_visited_children(node);
+ for (int i = num_visited; i < node->outlinks.size(); ++i) {
DepsRelation *rel = node->outlinks[i];
- if (rel->to->type == DEPSNODE_TYPE_OPERATION) {
+ if (rel->to->type == DEG_NODE_TYPE_OPERATION) {
OperationDepsNode *to = (OperationDepsNode *)rel->to;
- if (to->tag == NODE_IN_STACK) {
+ eCyclicCheckVisitedState to_state = get_node_visited_state(to);
+ if (to_state == NODE_IN_STACK) {
printf("Dependency cycle detected:\n");
printf(" '%s' depends on '%s' through '%s'\n",
to->full_identifier().c_str(),
node->full_identifier().c_str(),
rel->name);
- StackEntry *current = &entry;
+ StackEntry *current = entry;
while (current->node != to) {
BLI_assert(current != NULL);
printf(" '%s' depends on '%s' through '%s'\n",
@@ -113,25 +178,44 @@ void deg_graph_detect_cycles(Depsgraph *graph)
}
/* TODO(sergey): So called russian roulette cycle solver. */
rel->flag |= DEPSREL_FLAG_CYCLIC;
+ ++state->num_cycles;
}
- else if (to->tag == NODE_NOT_VISITED) {
+ else if (to_state == NODE_NOT_VISITED) {
StackEntry new_entry;
new_entry.node = to;
- new_entry.from = &entry;
+ new_entry.from = entry;
new_entry.via_relation = rel;
- traversal_stack.push(new_entry);
- to->tag = NODE_IN_STACK;
+ BLI_stack_push(traversal_stack, &new_entry);
+ set_node_visited_state(node, NODE_IN_STACK);
all_child_traversed = false;
- node->done = i;
+ set_node_num_visited_children(node, i);
break;
}
}
}
if (all_child_traversed) {
- node->tag = NODE_VISITED;
- traversal_stack.pop();
+ set_node_visited_state(node, NODE_VISITED);
+ BLI_stack_discard(traversal_stack);
}
}
}
+} // namespace
+
+void deg_graph_detect_cycles(Depsgraph *graph)
+{
+ CyclesSolverState state(graph);
+ /* First we solve cycles which are reachable from leaf nodes. */
+ schedule_leaf_nodes(&state);
+ solve_cycles(&state);
+ /* We are not done yet. It is possible to have closed loop cycle,
+ * for example A -> B -> C -> A. These nodes were not scheduled
+ * yet (since they all have inlinks), and were not traversed since
+ * nobody else points to them.
+ */
+ while (schedule_non_checked_node(&state)) {
+ solve_cycles(&state);
+ }
+}
+
} // namespace DEG
diff --git a/source/blender/modifiers/intern/MOD_boolean_util.h b/source/blender/depsgraph/intern/builder/deg_builder_map.cc
index 00d7c37b266..67cb04d1b98 100644
--- a/source/blender/modifiers/intern/MOD_boolean_util.h
+++ b/source/blender/depsgraph/intern/builder/deg_builder_map.cc
@@ -15,32 +15,50 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
- * The Original Code is Copyright (C) Blender Foundation.
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
* All rights reserved.
*
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
*
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/modifiers/intern/MOD_boolean_util.h
- * \ingroup modifiers
+/** \file blender/depsgraph/intern/builder/deg_builder_map.cc
+ * \ingroup depsgraph
*/
+#include "intern/builder/deg_builder_map.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+
+namespace DEG {
+
+BuilderMap::BuilderMap() {
+ set = BLI_gset_ptr_new("deg builder gset");
+}
+
-#ifndef __MOD_BOOLEAN_UTIL_H__
-#define __MOD_BOOLEAN_UTIL_H__
+BuilderMap::~BuilderMap() {
+ BLI_gset_free(set, NULL);
+}
-struct Object;
-struct DerivedMesh;
+bool BuilderMap::checkIsBuilt(ID *id) {
+ return BLI_gset_haskey(set, id);
+}
-/* Performs a boolean between two mesh objects, it is assumed that both objects
- * are in fact mesh object. On success returns a DerivedMesh. On failure
- * returns NULL and reports an error. */
+void BuilderMap::tagBuild(ID *id) {
+ BLI_gset_insert(set, id);
+}
-struct DerivedMesh *NewBooleanDerivedMesh(struct DerivedMesh *dm, struct Object *ob,
- struct DerivedMesh *dm_select, struct Object *ob_select, int int_op_type);
+bool BuilderMap::checkIsBuiltAndTag(ID *id) {
+ void **key_p;
+ if (!BLI_gset_ensure_p_ex(set, id, &key_p)) {
+ *key_p = id;
+ return false;
+ }
+ return true;
+}
-#endif /* MOD_BOOLEAN_UTILS */
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_map.h b/source/blender/depsgraph/intern/builder/deg_builder_map.h
new file mode 100644
index 00000000000..5ad22a9aa77
--- /dev/null
+++ b/source/blender/depsgraph/intern/builder/deg_builder_map.h
@@ -0,0 +1,69 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2018 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/builder/deg_builder_map.h
+ * \ingroup depsgraph
+ */
+
+#pragma once
+
+struct GSet;
+struct ID;
+
+namespace DEG {
+
+class BuilderMap {
+public:
+ BuilderMap();
+ ~BuilderMap();
+
+ /* Check whether given ID is already handled by builder (or if it's being
+ * handled).
+ */
+ bool checkIsBuilt(ID *id);
+
+ /* Tag given ID as handled/built. */
+ void tagBuild(ID *id);
+
+ /* Combination of previous two functions, returns truth if ID was already
+ * handled, or tags is handled otherwise and return false.
+ */
+ bool checkIsBuiltAndTag(ID *id);
+
+ template<typename T> bool checkIsBuilt(T *datablock) {
+ return checkIsBuilt(&datablock->id);
+ }
+ template<typename T> void tagBuild(T *datablock) {
+ tagBuild(&datablock->id);
+ }
+ template<typename T> bool checkIsBuiltAndTag(T *datablock) {
+ return checkIsBuiltAndTag(&datablock->id);
+ }
+
+ GSet *set;
+};
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc
index 6b7fb5246ca..3a4ca7515a3 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes.cc
@@ -37,11 +37,11 @@
#include "MEM_guardedalloc.h"
-extern "C" {
#include "BLI_blenlib.h"
#include "BLI_string.h"
#include "BLI_utildefines.h"
+extern "C" {
#include "DNA_action_types.h"
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
@@ -81,78 +81,48 @@ extern "C" {
#include "BKE_lattice.h"
#include "BKE_library.h"
#include "BKE_main.h"
+#include "BKE_mask.h"
#include "BKE_material.h"
#include "BKE_mesh.h"
#include "BKE_mball.h"
#include "BKE_modifier.h"
+#include "BKE_movieclip.h"
#include "BKE_node.h"
#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_rigidbody.h"
#include "BKE_sound.h"
-#include "BKE_texture.h"
#include "BKE_tracking.h"
#include "BKE_world.h"
-#include "DEG_depsgraph.h"
-#include "DEG_depsgraph_build.h"
-
#include "RNA_access.h"
#include "RNA_types.h"
} /* extern "C" */
+#include "DEG_depsgraph.h"
+#include "DEG_depsgraph_build.h"
+
#include "intern/builder/deg_builder.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_types.h"
#include "intern/depsgraph_intern.h"
+
#include "util/deg_util_foreach.h"
namespace DEG {
-namespace {
-
-struct BuilderWalkUserData {
- DepsgraphNodeBuilder *builder;
- Scene *scene;
-};
-
-static void modifier_walk(void *user_data,
- struct Object * /*ob*/,
- struct Object **obpoin,
- int /*cb_flag*/)
-{
- BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
- if (*obpoin) {
- data->builder->build_object(data->scene, NULL, *obpoin);
- }
-}
-
-void constraint_walk(bConstraint * /*con*/,
- ID **idpoin,
- bool /*is_reference*/,
- void *user_data)
-{
- BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
- if (*idpoin) {
- ID *id = *idpoin;
- if (GS(id->name) == ID_OB) {
- data->builder->build_object(data->scene, NULL, (Object *)id);
- }
- }
-}
-
-} /* namespace */
-
/* ************ */
/* Node Builder */
/* **** General purpose functions **** */
-DepsgraphNodeBuilder::DepsgraphNodeBuilder(Main *bmain, Depsgraph *graph) :
- m_bmain(bmain),
- m_graph(graph)
+DepsgraphNodeBuilder::DepsgraphNodeBuilder(Main *bmain, Depsgraph *graph)
+ : bmain_(bmain),
+ graph_(graph),
+ scene_(NULL)
{
}
@@ -160,55 +130,14 @@ DepsgraphNodeBuilder::~DepsgraphNodeBuilder()
{
}
-RootDepsNode *DepsgraphNodeBuilder::add_root_node()
-{
- return m_graph->add_root_node();
-}
-
IDDepsNode *DepsgraphNodeBuilder::add_id_node(ID *id)
{
- return m_graph->add_id_node(id, id->name);
+ return graph_->add_id_node(id, id->name);
}
-TimeSourceDepsNode *DepsgraphNodeBuilder::add_time_source(ID *id)
+TimeSourceDepsNode *DepsgraphNodeBuilder::add_time_source()
{
- /* determine which node to attach timesource to */
- if (id) {
-#if 0 /* XXX TODO */
- /* get ID node */
- IDDepsNode id_node = m_graph->find_id_node(id);
-
- /* depends on what this is... */
- switch (GS(id->name)) {
- case ID_SCE: /* Scene - Usually sequencer strip causing time remapping... */
- {
- // TODO...
- }
- break;
-
- case ID_GR: /* Group */
- {
- // TODO...
- }
- break;
-
- // XXX: time source...
-
- default: /* Unhandled */
- printf("%s(): Unhandled ID - %s \n", __func__, id->name);
- break;
- }
-#endif
- }
- else {
- /* root-node */
- RootDepsNode *root_node = m_graph->root_node;
- if (root_node) {
- return root_node->add_time_source("Time Source");
- }
- }
-
- return NULL;
+ return graph_->add_time_source();
}
ComponentDepsNode *DepsgraphNodeBuilder::add_component_node(
@@ -224,18 +153,17 @@ ComponentDepsNode *DepsgraphNodeBuilder::add_component_node(
OperationDepsNode *DepsgraphNodeBuilder::add_operation_node(
ComponentDepsNode *comp_node,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name,
int name_tag)
{
- OperationDepsNode *op_node = comp_node->has_operation(opcode,
- name,
- name_tag);
+ OperationDepsNode *op_node = comp_node->find_operation(opcode,
+ name,
+ name_tag);
if (op_node == NULL) {
- op_node = comp_node->add_operation(optype, op, opcode, name, name_tag);
- m_graph->operations.push_back(op_node);
+ op_node = comp_node->add_operation(op, opcode, name, name_tag);
+ graph_->operations.push_back(op_node);
}
else {
fprintf(stderr,
@@ -252,21 +180,19 @@ OperationDepsNode *DepsgraphNodeBuilder::add_operation_node(
ID *id,
eDepsNode_Type comp_type,
const char *comp_name,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name,
int name_tag)
{
ComponentDepsNode *comp_node = add_component_node(id, comp_type, comp_name);
- return add_operation_node(comp_node, optype, op, opcode, name, name_tag);
+ return add_operation_node(comp_node, op, opcode, name, name_tag);
}
OperationDepsNode *DepsgraphNodeBuilder::add_operation_node(
ID *id,
eDepsNode_Type comp_type,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name,
int name_tag)
@@ -274,13 +200,28 @@ OperationDepsNode *DepsgraphNodeBuilder::add_operation_node(
return add_operation_node(id,
comp_type,
"",
- optype,
op,
opcode,
name,
name_tag);
}
+OperationDepsNode *DepsgraphNodeBuilder::ensure_operation_node(
+ ID *id,
+ eDepsNode_Type comp_type,
+ const DepsEvalOperationCb& op,
+ eDepsOperation_Code opcode,
+ const char *name,
+ int name_tag)
+{
+ OperationDepsNode *operation =
+ find_operation_node(id, comp_type, opcode, name, name_tag);
+ if (operation != NULL) {
+ return operation;
+ }
+ return add_operation_node(id, comp_type, op, opcode, name, name_tag);
+}
+
bool DepsgraphNodeBuilder::has_operation_node(ID *id,
eDepsNode_Type comp_type,
const char *comp_name,
@@ -305,7 +246,7 @@ OperationDepsNode *DepsgraphNodeBuilder::find_operation_node(
int name_tag)
{
ComponentDepsNode *comp_node = add_component_node(id, comp_type, comp_name);
- return comp_node->has_operation(opcode, name, name_tag);
+ return comp_node->find_operation(opcode, name, name_tag);
}
OperationDepsNode *DepsgraphNodeBuilder::find_operation_node(
@@ -320,79 +261,66 @@ OperationDepsNode *DepsgraphNodeBuilder::find_operation_node(
/* **** Build functions for entity nodes **** */
-void DepsgraphNodeBuilder::begin_build(Main *bmain) {
- /* LIB_TAG_DOIT is used to indicate whether node for given ID was already
- * created or not. This flag is being set in add_id_node(), so functions
- * shouldn't bother with setting it, they only might query this flag when
- * needed.
- */
- BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
- /* XXX nested node trees are not included in tag-clearing above,
- * so we need to do this manually.
- */
- FOREACH_NODETREE(bmain, nodetree, id) {
- if (id != (ID *)nodetree) {
- nodetree->id.tag &= ~LIB_TAG_DOIT;
- }
- } FOREACH_NODETREE_END
+void DepsgraphNodeBuilder::begin_build() {
}
-void DepsgraphNodeBuilder::build_group(Scene *scene,
- Base *base,
- Group *group)
-{
- ID *group_id = &group->id;
- if (group_id->tag & LIB_TAG_DOIT) {
+void DepsgraphNodeBuilder::build_id(ID* id) {
+ if (id == NULL) {
return;
}
- group_id->tag |= LIB_TAG_DOIT;
-
- LINKLIST_FOREACH (GroupObject *, go, &group->gobject) {
- build_object(scene, base, go->ob);
+ switch (GS(id->name)) {
+ case ID_SCE:
+ build_scene((Scene *)id);
+ break;
+ case ID_GR:
+ build_group(NULL, (Group *)id);
+ break;
+ case ID_OB:
+ build_object(NULL, (Object *)id);
+ break;
+ case ID_NT:
+ build_nodetree((bNodeTree *)id);
+ break;
+ case ID_MA:
+ build_material((Material *)id);
+ break;
+ case ID_TE:
+ build_texture((Tex *)id);
+ break;
+ case ID_IM:
+ build_image((Image *)id);
+ break;
+ case ID_WO:
+ build_world((World *)id);
+ break;
+ case ID_MSK:
+ build_mask((Mask *)id);
+ break;
+ case ID_MC:
+ build_movieclip((MovieClip *)id);
+ break;
+ default:
+ /* fprintf(stderr, "Unhandled ID %s\n", id->name); */
+ break;
}
}
-SubgraphDepsNode *DepsgraphNodeBuilder::build_subgraph(Group *group)
+void DepsgraphNodeBuilder::build_group(Base *base, Group *group)
{
- /* sanity checks */
- if (!group)
- return NULL;
-
- /* create new subgraph's data */
- Depsgraph *subgraph = reinterpret_cast<Depsgraph *>(DEG_graph_new());
-
- DepsgraphNodeBuilder subgraph_builder(m_bmain, subgraph);
-
- /* add group objects */
- LINKLIST_FOREACH (GroupObject *, go, &group->gobject) {
- /*Object *ob = go->ob;*/
-
- /* Each "group object" is effectively a separate instance of the
- * underlying object data. When the group is evaluated, the transform
- * results and/or some other attributes end up getting overridden by
- * the group.
- */
+ if (built_map_.checkIsBuiltAndTag(group)) {
+ return;
+ }
+ LISTBASE_FOREACH (GroupObject *, go, &group->gobject) {
+ build_object(base, go->ob);
}
-
- /* Create a node for representing subgraph. */
- SubgraphDepsNode *subgraph_node = m_graph->add_subgraph_node(&group->id);
- subgraph_node->graph = subgraph;
-
- /* Make a copy of the data this node will need? */
- /* XXX: do we do this now, or later? */
- /* TODO: need API function which queries graph's ID's hash, and duplicates
- * those blocks thoroughly with all outside links removed.
- */
-
- return subgraph_node;
}
-void DepsgraphNodeBuilder::build_object(Scene *scene, Base *base, Object *ob)
+void DepsgraphNodeBuilder::build_object(Base *base, Object *object)
{
- const bool has_object = (ob->id.tag & LIB_TAG_DOIT);
+ const bool has_object = built_map_.checkIsBuiltAndTag(object);
IDDepsNode *id_node = (has_object)
- ? m_graph->find_id_node(&ob->id)
- : add_id_node(&ob->id);
+ ? graph_->find_id_node(&object->id)
+ : add_id_node(&object->id);
/* Update node layers.
* Do it for both new and existing ID nodes. This is so because several
* bases might be sharing same object.
@@ -400,123 +328,139 @@ void DepsgraphNodeBuilder::build_object(Scene *scene, Base *base, Object *ob)
if (base != NULL) {
id_node->layers |= base->lay;
}
- if (ob == scene->camera) {
- /* Camera should always be updated, it used directly by viewport. */
+ if (object->type == OB_CAMERA) {
+ /* Camera should always be updated, it used directly by viewport.
+ *
+ * TODO(sergey): Make it only for active scene camera.
+ */
id_node->layers |= (unsigned int)(-1);
}
/* Skip rest of components if the ID node was already there. */
if (has_object) {
return;
}
- ob->id.tag |= LIB_TAG_DOIT;
- ob->customdata_mask = 0;
-
- /* Standard components. */
- build_object_transform(scene, ob);
-
- if (ob->parent != NULL) {
- build_object(scene, NULL, ob->parent);
+ object->customdata_mask = 0;
+ /* Transform. */
+ build_object_transform(object);
+ /* Parent. */
+ if (object->parent != NULL) {
+ build_object(NULL, object->parent);
}
- if (ob->modifiers.first != NULL) {
+ /* Modifiers. */
+ if (object->modifiers.first != NULL) {
BuilderWalkUserData data;
data.builder = this;
- data.scene = scene;
- modifiers_foreachObjectLink(ob, modifier_walk, &data);
+ modifiers_foreachIDLink(object, modifier_walk, &data);
}
- if (ob->constraints.first != NULL) {
+ /* Constraints. */
+ if (object->constraints.first != NULL) {
BuilderWalkUserData data;
data.builder = this;
- data.scene = scene;
- modifiers_foreachObjectLink(ob, modifier_walk, &data);
- BKE_constraints_id_loop(&ob->constraints, constraint_walk, &data);
+ BKE_constraints_id_loop(&object->constraints, constraint_walk, &data);
}
-
/* Object data. */
- if (ob->data) {
- /* type-specific data... */
- switch (ob->type) {
- case OB_MESH: /* Geometry */
- case OB_CURVE:
- case OB_FONT:
- case OB_SURF:
- case OB_MBALL:
- case OB_LATTICE:
- build_obdata_geom(scene, ob);
- /* TODO(sergey): Only for until we support granular
- * update of curves.
- */
- if (ob->type == OB_FONT) {
- Curve *curve = (Curve *)ob->data;
- if (curve->textoncurve) {
- id_node->eval_flags |= DAG_EVAL_NEED_CURVE_PATH;
- }
- }
- break;
-
- case OB_ARMATURE: /* Pose */
- if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from != NULL) {
- build_proxy_rig(ob);
- }
- else {
- build_rig(scene, ob);
- }
- break;
-
- case OB_LAMP: /* Lamp */
- build_lamp(ob);
- break;
-
- case OB_CAMERA: /* Camera */
- build_camera(ob);
- break;
-
- default:
- {
- ID *obdata = (ID *)ob->data;
- if ((obdata->tag & LIB_TAG_DOIT) == 0) {
- build_animdata(obdata);
- }
- break;
- }
- }
- }
-
+ build_object_data(object);
/* Build animation data,
*
* Do it now because it's possible object data will affect
* on object's level animation, for example in case of rebuilding
* pose for proxy.
*/
- build_animdata(&ob->id);
-
- /* particle systems */
- if (ob->particlesystem.first) {
- build_particles(scene, ob);
+ OperationDepsNode *op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ op_node->set_as_exit();
+ build_animdata(&object->id);
+ /* Particle systems. */
+ if (object->particlesystem.first != NULL) {
+ build_particles(object);
+ }
+ /* Grease pencil. */
+ if (object->gpd != NULL) {
+ build_gpencil(object->gpd);
+ }
+ /* Object that this is a proxy for. */
+ if (object->proxy) {
+ object->proxy->proxy_from = object;
+ build_object(base, object->proxy);
}
+ /* Object dupligroup. */
+ if (object->dup_group != NULL) {
+ build_group(base, object->dup_group);
+ }
+}
- /* grease pencil */
- if (ob->gpd) {
- build_gpencil(ob->gpd);
+void DepsgraphNodeBuilder::build_object_data(Object *object)
+{
+ if (object->data == NULL) {
+ return;
+ }
+ IDDepsNode *id_node = graph_->find_id_node(&object->id);
+ /* type-specific data... */
+ switch (object->type) {
+ case OB_MESH: /* Geometry */
+ case OB_CURVE:
+ case OB_FONT:
+ case OB_SURF:
+ case OB_MBALL:
+ case OB_LATTICE:
+ build_obdata_geom(object);
+ /* TODO(sergey): Only for until we support granular
+ * update of curves.
+ */
+ if (object->type == OB_FONT) {
+ Curve *curve = (Curve *)object->data;
+ if (curve->textoncurve) {
+ id_node->eval_flags |= DAG_EVAL_NEED_CURVE_PATH;
+ }
+ }
+ break;
+ case OB_ARMATURE:
+ if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
+ build_proxy_rig(object);
+ }
+ else {
+ build_rig(object);
+ }
+ break;
+ case OB_LAMP:
+ build_lamp(object);
+ break;
+ case OB_CAMERA:
+ build_camera(object);
+ break;
+ default:
+ {
+ ID *obdata = (ID *)object->data;
+ if (built_map_.checkIsBuilt(obdata) == 0) {
+ build_animdata(obdata);
+ }
+ break;
+ }
}
}
-void DepsgraphNodeBuilder::build_object_transform(Scene *scene, Object *ob)
+void DepsgraphNodeBuilder::build_object_transform(Object *object)
{
+ OperationDepsNode *op_node;
+
/* local transforms (from transform channels - loc/rot/scale + deltas) */
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_INIT, function_bind(BKE_object_eval_local_transform, _1, scene, ob),
- DEG_OPCODE_TRANSFORM_LOCAL);
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_object_eval_local_transform, _1, object),
+ DEG_OPCODE_TRANSFORM_LOCAL);
+ op_node->set_as_entry();
/* object parent */
- if (ob->parent) {
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_EXEC, function_bind(BKE_object_eval_parent, _1, scene, ob),
+ if (object->parent) {
+ add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_object_eval_parent, _1, scene_, object),
DEG_OPCODE_TRANSFORM_PARENT);
}
/* object constraints */
- if (ob->constraints.first) {
- build_object_constraints(scene, ob);
+ if (object->constraints.first) {
+ build_object_constraints(object);
}
/* Temporary uber-update node, which does everything.
@@ -526,14 +470,15 @@ void DepsgraphNodeBuilder::build_object_transform(Scene *scene, Object *ob)
*
* TODO(sergey): Get rid of this node.
*/
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_EXEC, function_bind(BKE_object_eval_uber_transform, _1, scene, ob),
- DEG_OPCODE_OBJECT_UBEREVAL);
+ add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_object_eval_uber_transform, _1, object),
+ DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
/* object transform is done */
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_POST, function_bind(BKE_object_eval_done, _1, ob),
- DEG_OPCODE_TRANSFORM_FINAL);
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_object_eval_done, _1, object),
+ DEG_OPCODE_TRANSFORM_FINAL);
+ op_node->set_as_exit();
}
/**
@@ -553,11 +498,11 @@ void DepsgraphNodeBuilder::build_object_transform(Scene *scene, Object *ob)
*
* -- Aligorith, August 2013
*/
-void DepsgraphNodeBuilder::build_object_constraints(Scene *scene, Object *ob)
+void DepsgraphNodeBuilder::build_object_constraints(Object *object)
{
/* create node for constraint stack */
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_EXEC, function_bind(BKE_object_eval_constraints, _1, scene, ob),
+ add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_object_eval_constraints, _1, scene_, object),
DEG_OPCODE_TRANSFORM_CONSTRAINTS);
}
@@ -579,8 +524,8 @@ void DepsgraphNodeBuilder::build_animdata(ID *id)
/* actions and NLA - as a single unit for now, as it gets complicated to schedule otherwise */
if ((adt->action) || (adt->nla_tracks.first)) {
/* create the node */
- add_operation_node(id, DEPSNODE_TYPE_ANIMATION,
- DEPSOP_TYPE_EXEC, function_bind(BKE_animsys_eval_animdata, _1, id),
+ add_operation_node(id, DEG_NODE_TYPE_ANIMATION,
+ function_bind(BKE_animsys_eval_animdata, _1, id),
DEG_OPCODE_ANIMATION, id->name);
// TODO: for each channel affected, we might also want to add some support for running RNA update callbacks on them
@@ -588,7 +533,7 @@ void DepsgraphNodeBuilder::build_animdata(ID *id)
}
/* drivers */
- LINKLIST_FOREACH (FCurve *, fcu, &adt->drivers) {
+ LISTBASE_FOREACH (FCurve *, fcu, &adt->drivers) {
/* create driver */
build_driver(id, fcu);
}
@@ -600,58 +545,72 @@ void DepsgraphNodeBuilder::build_animdata(ID *id)
* \param id: ID-Block that driver is attached to
* \param fcu: Driver-FCurve
*/
-OperationDepsNode *DepsgraphNodeBuilder::build_driver(ID *id, FCurve *fcu)
+void DepsgraphNodeBuilder::build_driver(ID *id, FCurve *fcurve)
{
- ChannelDriver *driver = fcu->driver;
-
/* Create data node for this driver */
- /* TODO(sergey): Avoid creating same operation multiple times,
- * in the future we need to avoid lookup of the operation as well
- * and use some tagging magic instead.
- */
- OperationDepsNode *driver_op = find_operation_node(id,
- DEPSNODE_TYPE_PARAMETERS,
- DEG_OPCODE_DRIVER,
- fcu->rna_path,
- fcu->array_index);
-
- if (driver_op == NULL) {
- driver_op = add_operation_node(id,
- DEPSNODE_TYPE_PARAMETERS,
- DEPSOP_TYPE_EXEC,
- function_bind(BKE_animsys_eval_driver, _1, id, fcu),
- DEG_OPCODE_DRIVER,
- fcu->rna_path,
- fcu->array_index);
- }
+ ensure_operation_node(id,
+ DEG_NODE_TYPE_PARAMETERS,
+ function_bind(BKE_animsys_eval_driver, _1, id, fcurve),
+ DEG_OPCODE_DRIVER,
+ fcurve->rna_path ? fcurve->rna_path : "",
+ fcurve->array_index);
+ build_driver_variables(id, fcurve);
+}
- /* tag "scripted expression" drivers as needing Python (due to GIL issues, etc.) */
- if (driver->type == DRIVER_TYPE_PYTHON) {
- driver_op->flag |= DEPSOP_FLAG_USES_PYTHON;
+void DepsgraphNodeBuilder::build_driver_variables(ID * id, FCurve *fcurve)
+{
+ build_driver_id_property(id, fcurve->rna_path);
+ LISTBASE_FOREACH (DriverVar *, dvar, &fcurve->driver->variables) {
+ DRIVER_TARGETS_USED_LOOPER(dvar)
+ {
+ build_id(dtar->id);
+ build_driver_id_property(dtar->id, dtar->rna_path);
+ }
+ DRIVER_TARGETS_LOOPER_END
}
+}
- /* return driver node created */
- return driver_op;
+void DepsgraphNodeBuilder::build_driver_id_property(ID *id,
+ const char *rna_path)
+{
+ if (id == NULL || rna_path == NULL) {
+ return;
+ }
+ PointerRNA id_ptr, ptr;
+ PropertyRNA *prop;
+ RNA_id_pointer_create(id, &id_ptr);
+ if (!RNA_path_resolve_full(&id_ptr, rna_path, &ptr, &prop, NULL)) {
+ return;
+ }
+ if (prop == NULL) {
+ return;
+ }
+ if (!RNA_property_is_idprop(prop)) {
+ return;
+ }
+ const char *prop_identifier = RNA_property_identifier((PropertyRNA *)prop);
+ ensure_operation_node(id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_ID_PROPERTY,
+ prop_identifier);
}
/* Recursively build graph for world */
void DepsgraphNodeBuilder::build_world(World *world)
{
- ID *world_id = &world->id;
- if (world_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(world)) {
return;
}
-
- /* world itself */
- add_id_node(world_id); /* world shading/params? */
-
+ ID *world_id = &world->id;
build_animdata(world_id);
-
- /* TODO: other settings? */
-
+ /* world itself */
+ add_operation_node(world_id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
/* textures */
build_texture_stack(world->mtex);
-
/* world's nodetree */
if (world->nodetree) {
build_nodetree(world->nodetree);
@@ -682,14 +641,14 @@ void DepsgraphNodeBuilder::build_rigidbody(Scene *scene)
/* XXX: is this the right component, or do we want to use another one instead? */
/* init/rebuild operation */
- /*OperationDepsNode *init_node =*/ add_operation_node(&scene->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_REBUILD, function_bind(BKE_rigidbody_rebuild_sim, _1, scene),
+ /*OperationDepsNode *init_node =*/ add_operation_node(&scene->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_rigidbody_rebuild_sim, _1, scene),
DEG_OPCODE_RIGIDBODY_REBUILD);
/* do-sim operation */
// XXX: what happens if we need to split into several groups?
- OperationDepsNode *sim_node = add_operation_node(&scene->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_SIM, function_bind(BKE_rigidbody_eval_simulation, _1, scene),
+ OperationDepsNode *sim_node = add_operation_node(&scene->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_rigidbody_eval_simulation, _1, scene),
DEG_OPCODE_RIGIDBODY_SIM);
/* XXX: For now, the sim node is the only one that really matters here. If any other
@@ -701,22 +660,22 @@ void DepsgraphNodeBuilder::build_rigidbody(Scene *scene)
/* objects - simulation participants */
if (rbw->group) {
- LINKLIST_FOREACH (GroupObject *, go, &rbw->group->gobject) {
- Object *ob = go->ob;
+ LISTBASE_FOREACH (GroupObject *, go, &rbw->group->gobject) {
+ Object *object = go->ob;
- if (!ob || (ob->type != OB_MESH))
+ if (!object || (object->type != OB_MESH))
continue;
/* 2) create operation for flushing results */
/* object's transform component - where the rigidbody operation lives */
- add_operation_node(&ob->id, DEPSNODE_TYPE_TRANSFORM,
- DEPSOP_TYPE_EXEC, function_bind(BKE_rigidbody_object_sync_transforms, _1, scene, ob),
- DEG_OPCODE_TRANSFORM_RIGIDBODY);
+ add_operation_node(&object->id, DEG_NODE_TYPE_TRANSFORM,
+ function_bind(BKE_rigidbody_object_sync_transforms, _1, scene, object),
+ DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
}
}
}
-void DepsgraphNodeBuilder::build_particles(Scene *scene, Object *ob)
+void DepsgraphNodeBuilder::build_particles(Object *object)
{
/**
* Particle Systems Nodes
@@ -732,60 +691,73 @@ void DepsgraphNodeBuilder::build_particles(Scene *scene, Object *ob)
* blackbox evaluation step for one particle system referenced by
* the particle systems stack. All dependencies link to this operation.
*/
-
- /* component for all particle systems */
- ComponentDepsNode *psys_comp = add_component_node(&ob->id, DEPSNODE_TYPE_EVAL_PARTICLES);
-
- /* particle systems */
- LINKLIST_FOREACH (ParticleSystem *, psys, &ob->particlesystem) {
+ /* Component for all particle systems. */
+ ComponentDepsNode *psys_comp =
+ add_component_node(&object->id, DEG_NODE_TYPE_EVAL_PARTICLES);
+ add_operation_node(psys_comp,
+ function_bind(BKE_particle_system_eval_init,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL_INIT);
+ /* Build all particle systems. */
+ LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
ParticleSettings *part = psys->part;
-
- /* particle settings */
+ /* Particle settings. */
// XXX: what if this is used more than once!
build_animdata(&part->id);
-
- /* this particle system */
+ /* This particle system evaluation. */
// TODO: for now, this will just be a placeholder "ubereval" node
add_operation_node(psys_comp,
- DEPSOP_TYPE_EXEC, function_bind(BKE_particle_system_eval,
- _1,
- scene,
- ob,
- psys),
- DEG_OPCODE_PSYS_EVAL,
+ NULL,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
psys->name);
+ /* Visualization of particle system. */
+ switch (part->ren_as) {
+ case PART_DRAW_OB:
+ if (part->dup_ob != NULL) {
+ build_object(NULL, part->dup_ob);
+ }
+ break;
+ case PART_DRAW_GR:
+ if (part->dup_group != NULL) {
+ build_group(NULL, part->dup_group);
+ }
+ break;
+ }
}
/* pointcache */
// TODO...
}
+void DepsgraphNodeBuilder::build_cloth(Object *object)
+{
+ add_operation_node(&object->id,
+ DEG_NODE_TYPE_CACHE,
+ function_bind(BKE_object_eval_cloth,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_GEOMETRY_CLOTH_MODIFIER);
+}
+
/* Shapekeys */
void DepsgraphNodeBuilder::build_shapekeys(Key *key)
{
build_animdata(&key->id);
-
- add_operation_node(&key->id, DEPSNODE_TYPE_GEOMETRY, DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER, "Shapekey Eval");
+ add_operation_node(&key->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ NULL,
+ DEG_OPCODE_GEOMETRY_SHAPEKEY);
}
/* ObData Geometry Evaluation */
// XXX: what happens if the datablock is shared!
-void DepsgraphNodeBuilder::build_obdata_geom(Scene *scene, Object *ob)
+void DepsgraphNodeBuilder::build_obdata_geom(Object *object)
{
- ID *obdata = (ID *)ob->data;
-
- /* TODO(sergey): This way using this object's properties as driver target
- * works fine.
- *
- * Does this depend on other nodes?
- */
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_PARAMETERS,
- DEPSOP_TYPE_POST,
- NULL,
- DEG_OPCODE_PLACEHOLDER,
- "Parameters Eval");
+ ID *obdata = (ID *)object->data;
+ OperationDepsNode *op_node;
/* Temporary uber-update node, which does everything.
* It is for the being we're porting old dependencies into the new system.
@@ -794,61 +766,50 @@ void DepsgraphNodeBuilder::build_obdata_geom(Scene *scene, Object *ob)
*
* TODO(sergey): Get rid of this node.
*/
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_POST,
- function_bind(BKE_object_eval_uber_data, _1, scene, ob),
- DEG_OPCODE_GEOMETRY_UBEREVAL);
-
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_INIT,
- NULL,
- DEG_OPCODE_PLACEHOLDER,
- "Eval Init");
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ function_bind(BKE_object_eval_uber_data,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_GEOMETRY_UBEREVAL);
+ op_node->set_as_exit();
+
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ NULL,
+ DEG_OPCODE_PLACEHOLDER,
+ "Eval Init");
+ op_node->set_as_entry();
// TODO: "Done" operation
- /* Modifiers */
- LINKLIST_FOREACH (ModifierData *, md, &ob->modifiers) {
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_EXEC,
- function_bind(BKE_object_eval_modifier,
- _1,
- scene,
- ob,
- md),
- DEG_OPCODE_GEOMETRY_MODIFIER,
- md->name);
+ /* Cloth modifier. */
+ LISTBASE_FOREACH (ModifierData *, md, &object->modifiers) {
+ if (md->type == eModifierType_Cloth) {
+ build_cloth(object);
+ }
}
/* materials */
- if (ob->totcol != 0) {
- for (int a = 1; a <= ob->totcol; a++) {
- Material *ma = give_current_material(ob, a);
- if (ma != NULL) {
- build_material(ma);
- }
+ for (int a = 1; a <= object->totcol; a++) {
+ Material *ma = give_current_material(object, a);
+ if (ma != NULL) {
+ build_material(ma);
}
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_SHADING,
- DEPSOP_TYPE_EXEC,
- NULL,
- DEG_OPCODE_PLACEHOLDER, "Material Update");
}
/* geometry collision */
- if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
+ if (ELEM(object->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
// add geometry collider relations
}
- if (obdata->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(obdata)) {
return;
}
/* ShapeKeys */
- Key *key = BKE_key_from_object(ob);
+ Key *key = BKE_key_from_object(object);
if (key) {
build_shapekeys(key);
}
@@ -858,39 +819,46 @@ void DepsgraphNodeBuilder::build_obdata_geom(Scene *scene, Object *ob)
/* Nodes for result of obdata's evaluation, and geometry
* evaluation on object.
*/
- switch (ob->type) {
+ switch (object->type) {
case OB_MESH:
{
- //Mesh *me = (Mesh *)ob->data;
+ //Mesh *me = (Mesh *)object->data;
/* evaluation operations */
- add_operation_node(obdata,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_INIT,
- function_bind(BKE_mesh_eval_geometry,
- _1,
- (Mesh *)obdata),
- DEG_OPCODE_PLACEHOLDER,
- "Geometry Eval");
+ op_node = add_operation_node(obdata,
+ DEG_NODE_TYPE_GEOMETRY,
+ function_bind(BKE_mesh_eval_geometry,
+ _1,
+ (Mesh *)obdata),
+ DEG_OPCODE_PLACEHOLDER,
+ "Geometry Eval");
+ op_node->set_as_entry();
break;
}
case OB_MBALL:
{
- Object *mom = BKE_mball_basis_find(scene, ob);
-
- /* Motherball - mom depends on children! */
- if (mom == ob) {
+ Object *mom = BKE_mball_basis_find(scene_, object);
+ /* NOTE: Only the motherball gets evaluated, it's children are
+ * having empty placeholders for the correct relations being built.
+ */
+ if (mom == object) {
/* metaball evaluation operations */
- /* NOTE: only the motherball gets evaluated! */
- add_operation_node(obdata,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_INIT,
- function_bind(BKE_mball_eval_geometry,
- _1,
- (MetaBall *)obdata),
- DEG_OPCODE_PLACEHOLDER,
- "Geometry Eval");
+ op_node = add_operation_node(obdata,
+ DEG_NODE_TYPE_GEOMETRY,
+ function_bind(BKE_mball_eval_geometry,
+ _1,
+ (MetaBall *)obdata),
+ DEG_OPCODE_PLACEHOLDER,
+ "Geometry Eval");
+ }
+ else {
+ op_node = add_operation_node(obdata,
+ DEG_NODE_TYPE_GEOMETRY,
+ NULL,
+ DEG_OPCODE_PLACEHOLDER,
+ "Geometry Eval");
+ op_node->set_as_entry();
}
break;
}
@@ -901,39 +869,27 @@ void DepsgraphNodeBuilder::build_obdata_geom(Scene *scene, Object *ob)
{
/* Curve/nurms evaluation operations. */
/* - calculate curve geometry (including path) */
- add_operation_node(obdata,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_INIT,
- function_bind(BKE_curve_eval_geometry,
- _1,
- (Curve *)obdata),
- DEG_OPCODE_PLACEHOLDER,
- "Geometry Eval");
-
- /* Calculate curve path - this is used by constraints, etc. */
- if (ELEM(ob->type, OB_CURVE, OB_FONT)) {
- add_operation_node(obdata,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_EXEC,
- function_bind(BKE_curve_eval_path,
- _1,
- (Curve *)obdata),
- DEG_OPCODE_GEOMETRY_PATH,
- "Path");
- }
+ op_node = add_operation_node(obdata,
+ DEG_NODE_TYPE_GEOMETRY,
+ function_bind(BKE_curve_eval_geometry,
+ _1,
+ (Curve *)obdata),
+ DEG_OPCODE_PLACEHOLDER,
+ "Geometry Eval");
+ op_node->set_as_entry();
/* Make sure objects used for bevel.taper are in the graph.
* NOTE: This objects might be not linked to the scene.
*/
Curve *cu = (Curve *)obdata;
if (cu->bevobj != NULL) {
- build_object(scene, NULL, cu->bevobj);
+ build_object(NULL, cu->bevobj);
}
if (cu->taperobj != NULL) {
- build_object(scene, NULL, cu->taperobj);
+ build_object(NULL, cu->taperobj);
}
- if (ob->type == OB_FONT && cu->textoncurve != NULL) {
- build_object(scene, NULL, cu->textoncurve);
+ if (object->type == OB_FONT && cu->textoncurve != NULL) {
+ build_object(NULL, cu->textoncurve);
}
break;
}
@@ -941,112 +897,119 @@ void DepsgraphNodeBuilder::build_obdata_geom(Scene *scene, Object *ob)
case OB_LATTICE:
{
/* Lattice evaluation operations. */
- add_operation_node(obdata,
- DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_INIT,
- function_bind(BKE_lattice_eval_geometry,
- _1,
- (Lattice *)obdata),
- DEG_OPCODE_PLACEHOLDER,
- "Geometry Eval");
+ op_node = add_operation_node(obdata,
+ DEG_NODE_TYPE_GEOMETRY,
+ function_bind(BKE_lattice_eval_geometry,
+ _1,
+ (Lattice *)obdata),
+ DEG_OPCODE_PLACEHOLDER,
+ "Geometry Eval");
+ op_node->set_as_entry();
break;
}
}
- add_operation_node(obdata, DEPSNODE_TYPE_GEOMETRY,
- DEPSOP_TYPE_POST, NULL,
- DEG_OPCODE_PLACEHOLDER, "Eval Done");
+ op_node = add_operation_node(obdata, DEG_NODE_TYPE_GEOMETRY, NULL,
+ DEG_OPCODE_PLACEHOLDER, "Eval Done");
+ op_node->set_as_exit();
/* Parameters for driver sources. */
- add_operation_node(obdata, DEPSNODE_TYPE_PARAMETERS, DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER, "Parameters Eval");
+ add_operation_node(obdata,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
}
/* Cameras */
-void DepsgraphNodeBuilder::build_camera(Object *ob)
+void DepsgraphNodeBuilder::build_camera(Object *object)
{
/* TODO: Link scene-camera links in somehow... */
- Camera *cam = (Camera *)ob->data;
- ID *camera_id = &cam->id;
- if (camera_id->tag & LIB_TAG_DOIT) {
+ Camera *camera = (Camera *)object->data;
+ if (built_map_.checkIsBuiltAndTag(camera)) {
return;
}
-
- build_animdata(&cam->id);
-
- add_operation_node(camera_id, DEPSNODE_TYPE_PARAMETERS, DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER, "Parameters Eval");
-
- if (cam->dof_ob != NULL) {
+ build_animdata(&camera->id);
+ add_operation_node(&camera->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ if (camera->dof_ob != NULL) {
/* TODO(sergey): For now parametrs are on object level. */
- add_operation_node(&ob->id, DEPSNODE_TYPE_PARAMETERS,
- DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER,
- "Camera DOF");
+ add_operation_node(&object->id, DEG_NODE_TYPE_PARAMETERS, NULL,
+ DEG_OPCODE_PLACEHOLDER, "Camera DOF");
}
}
/* Lamps */
-void DepsgraphNodeBuilder::build_lamp(Object *ob)
+void DepsgraphNodeBuilder::build_lamp(Object *object)
{
- Lamp *la = (Lamp *)ob->data;
- ID *lamp_id = &la->id;
- if (lamp_id->tag & LIB_TAG_DOIT) {
+ Lamp *lamp = (Lamp *)object->data;
+ if (built_map_.checkIsBuiltAndTag(lamp)) {
return;
}
-
- build_animdata(&la->id);
-
- /* node for obdata */
- add_component_node(lamp_id, DEPSNODE_TYPE_PARAMETERS);
-
+ build_animdata(&lamp->id);
/* TODO(sergey): Is it really how we're supposed to work with drivers? */
- add_operation_node(lamp_id, DEPSNODE_TYPE_PARAMETERS, DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER, "Parameters Eval");
-
+ add_operation_node(&lamp->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
/* lamp's nodetree */
- if (la->nodetree) {
- build_nodetree(la->nodetree);
- }
-
+ build_nodetree(lamp->nodetree);
/* textures */
- build_texture_stack(la->mtex);
+ build_texture_stack(lamp->mtex);
}
void DepsgraphNodeBuilder::build_nodetree(bNodeTree *ntree)
{
- if (!ntree)
+ if (ntree == NULL) {
+ return;
+ }
+ if (built_map_.checkIsBuiltAndTag(ntree)) {
return;
+ }
/* nodetree itself */
- ID *ntree_id = &ntree->id;
-
- build_animdata(ntree_id);
-
+ OperationDepsNode *op_node;
+ build_animdata(&ntree->id);
/* Parameters for drivers. */
- add_operation_node(ntree_id, DEPSNODE_TYPE_PARAMETERS, DEPSOP_TYPE_POST, NULL,
- DEG_OPCODE_PLACEHOLDER, "Parameters Eval");
-
+ op_node = add_operation_node(&ntree->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ op_node->set_as_exit();
/* nodetree's nodes... */
- LINKLIST_FOREACH (bNode *, bnode, &ntree->nodes) {
+ LISTBASE_FOREACH (bNode *, bnode, &ntree->nodes) {
ID *id = bnode->id;
- if (id != NULL) {
- short id_type = GS(id->name);
- if (id_type == ID_MA) {
- build_material((Material *)id);
- }
- else if (id_type == ID_TE) {
- build_texture((Tex *)id);
- }
- else if (id_type == ID_IM) {
- build_image((Image *)id);
- }
- else if (bnode->type == NODE_GROUP) {
- bNodeTree *group_ntree = (bNodeTree *)id;
- if ((group_ntree->id.tag & LIB_TAG_DOIT) == 0) {
- build_nodetree(group_ntree);
- }
- }
+ if (id == NULL) {
+ continue;
+ }
+ ID_Type id_type = GS(id->name);
+ if (id_type == ID_MA) {
+ build_material((Material *)id);
+ }
+ else if (id_type == ID_TE) {
+ build_texture((Tex *)id);
+ }
+ else if (id_type == ID_IM) {
+ build_image((Image *)id);
+ }
+ else if (id_type == ID_OB) {
+ build_object(NULL, (Object *)id);
+ }
+ else if (id_type == ID_SCE) {
+ /* Scenes are used by compositor trees, and handled by render
+ * pipeline. No need to build dependencies for them here.
+ */
+ }
+ else if (id_type == ID_TXT) {
+ /* Ignore script nodes. */
+ }
+ else if (bnode->type == NODE_GROUP) {
+ bNodeTree *group_ntree = (bNodeTree *)id;
+ build_nodetree(group_ntree);
+ }
+ else {
+ BLI_assert(!"Unknown ID type used for node");
}
}
@@ -1054,28 +1017,20 @@ void DepsgraphNodeBuilder::build_nodetree(bNodeTree *ntree)
}
/* Recursively build graph for material */
-void DepsgraphNodeBuilder::build_material(Material *ma)
+void DepsgraphNodeBuilder::build_material(Material *material)
{
- ID *ma_id = &ma->id;
- if (ma_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(material)) {
return;
}
-
- /* material itself */
- add_id_node(ma_id);
-
- add_operation_node(ma_id, DEPSNODE_TYPE_SHADING,
- DEPSOP_TYPE_EXEC, NULL,
+ add_operation_node(&material->id, DEG_NODE_TYPE_SHADING, NULL,
DEG_OPCODE_PLACEHOLDER, "Material Update");
/* material animation */
- build_animdata(ma_id);
-
+ build_animdata(&material->id);
/* textures */
- build_texture_stack(ma->mtex);
-
+ build_texture_stack(material->mtex);
/* material's nodetree */
- build_nodetree(ma->nodetree);
+ build_nodetree(material->nodetree);
}
/* Texture-stack attached to some shading datablock */
@@ -1092,37 +1047,35 @@ void DepsgraphNodeBuilder::build_texture_stack(MTex **texture_stack)
}
/* Recursively build graph for texture */
-void DepsgraphNodeBuilder::build_texture(Tex *tex)
+void DepsgraphNodeBuilder::build_texture(Tex *texture)
{
- ID *tex_id = &tex->id;
- if (tex_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(texture)) {
return;
}
- tex_id->tag |= LIB_TAG_DOIT;
/* Texture itself. */
- build_animdata(tex_id);
+ build_animdata(&texture->id);
/* Texture's nodetree. */
- build_nodetree(tex->nodetree);
+ build_nodetree(texture->nodetree);
/* Special cases for different IDs which texture uses. */
- if (tex->type == TEX_IMAGE) {
- if (tex->ima != NULL) {
- build_image(tex->ima);
+ if (texture->type == TEX_IMAGE) {
+ if (texture->ima != NULL) {
+ build_image(texture->ima);
}
}
+ /* Placeholder so we can add relations and tag ID node for update. */
+ add_operation_node(&texture->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PLACEHOLDER);
}
void DepsgraphNodeBuilder::build_image(Image *image) {
- ID *image_id = &image->id;
- if (image_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(image)) {
return;
}
- image_id->tag |= LIB_TAG_DOIT;
- /* Image ID node itself. */
- add_id_node(image_id);
/* Placeholder so we can add relations and tag ID node for update. */
- add_operation_node(image_id,
- DEPSNODE_TYPE_PARAMETERS,
- DEPSOP_TYPE_EXEC,
+ add_operation_node(&image->id,
+ DEG_NODE_TYPE_PARAMETERS,
NULL,
DEG_OPCODE_PLACEHOLDER,
"Image Eval");
@@ -1133,10 +1086,10 @@ void DepsgraphNodeBuilder::build_compositor(Scene *scene)
/* For now, just a plain wrapper? */
// TODO: create compositing component?
// XXX: component type undefined!
- //graph->get_node(&scene->id, NULL, DEPSNODE_TYPE_COMPOSITING, NULL);
+ //graph->get_node(&scene->id, NULL, DEG_NODE_TYPE_COMPOSITING, NULL);
/* for now, nodetrees are just parameters; compositing occurs in internals of renderer... */
- add_component_node(&scene->id, DEPSNODE_TYPE_PARAMETERS);
+ add_component_node(&scene->id, DEG_NODE_TYPE_PARAMETERS);
build_nodetree(scene->nodetree);
}
@@ -1144,12 +1097,12 @@ void DepsgraphNodeBuilder::build_gpencil(bGPdata *gpd)
{
ID *gpd_id = &gpd->id;
- /* gpencil itself */
- // XXX: what about multiple users of same datablock? This should only get added once
- add_id_node(gpd_id);
+ /* TODO(sergey): what about multiple users of same datablock? This should
+ * only get added once.
+ */
- /* The main reason Grease Pencil is included here is because the animation (and drivers)
- * need to be hosted somewhere...
+ /* The main reason Grease Pencil is included here is because the animation
+ * (and drivers) need to be hosted somewhere.
*/
build_animdata(gpd_id);
}
@@ -1157,27 +1110,85 @@ void DepsgraphNodeBuilder::build_gpencil(bGPdata *gpd)
void DepsgraphNodeBuilder::build_cachefile(CacheFile *cache_file)
{
ID *cache_file_id = &cache_file->id;
-
- add_component_node(cache_file_id, DEPSNODE_TYPE_CACHE);
- add_operation_node(cache_file_id, DEPSNODE_TYPE_CACHE,
- DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_PLACEHOLDER, "Cache File Update");
-
- add_id_node(cache_file_id);
+ /* Animation, */
build_animdata(cache_file_id);
+ /* Cache evaluation itself. */
+ add_operation_node(cache_file_id, DEG_NODE_TYPE_CACHE, NULL,
+ DEG_OPCODE_PLACEHOLDER, "Cache File Update");
}
void DepsgraphNodeBuilder::build_mask(Mask *mask)
{
ID *mask_id = &mask->id;
- add_id_node(mask_id);
+ /* F-Curve based animation. */
build_animdata(mask_id);
+ /* Animation based on mask's shapes. */
+ add_operation_node(mask_id,
+ DEG_NODE_TYPE_ANIMATION,
+ function_bind(BKE_mask_eval_animation, _1, mask),
+ DEG_OPCODE_MASK_ANIMATION);
+ /* Final mask evaluation. */
+ add_operation_node(mask_id,
+ DEG_NODE_TYPE_PARAMETERS,
+ function_bind(BKE_mask_eval_update, _1, mask),
+ DEG_OPCODE_MASK_EVAL);
}
void DepsgraphNodeBuilder::build_movieclip(MovieClip *clip) {
ID *clip_id = &clip->id;
- add_id_node(clip_id);
+ /* Animation. */
build_animdata(clip_id);
+ /* Movie clip evaluation. */
+ add_operation_node(clip_id,
+ DEG_NODE_TYPE_PARAMETERS,
+ function_bind(BKE_movieclip_eval_update, _1, clip),
+ DEG_OPCODE_MOVIECLIP_EVAL);
+}
+
+/* **** ID traversal callbacks functions **** */
+
+void DepsgraphNodeBuilder::modifier_walk(void *user_data,
+ struct Object * /*object*/,
+ struct ID **idpoin,
+ int /*cb_flag*/)
+{
+ BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
+ ID *id = *idpoin;
+ if (id == NULL) {
+ return;
+ }
+ switch (GS(id->name)) {
+ case ID_OB:
+ data->builder->build_object(NULL, (Object *)id);
+ break;
+ case ID_TE:
+ data->builder->build_texture((Tex *)id);
+ break;
+ default:
+ /* pass */
+ break;
+ }
}
+void DepsgraphNodeBuilder::constraint_walk(bConstraint * /*con*/,
+ ID **idpoin,
+ bool /*is_reference*/,
+ void *user_data)
+{
+ BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
+ ID *id = *idpoin;
+ if (id == NULL) {
+ return;
+ }
+ switch (GS(id->name)) {
+ case ID_OB:
+ data->builder->build_object(NULL, (Object *)id);
+ break;
+ default:
+ /* pass */
+ break;
+ }
+}
+
+
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes.h b/source/blender/depsgraph/intern/builder/deg_builder_nodes.h
index c5035f35f6e..f2154e58703 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_nodes.h
+++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes.h
@@ -30,6 +30,7 @@
#pragma once
+#include "intern/builder/deg_builder_map.h"
#include "intern/depsgraph_types.h"
struct Base;
@@ -61,8 +62,6 @@ namespace DEG {
struct Depsgraph;
struct DepsNode;
-struct RootDepsNode;
-struct SubgraphDepsNode;
struct IDDepsNode;
struct TimeSourceDepsNode;
struct ComponentDepsNode;
@@ -72,38 +71,41 @@ struct DepsgraphNodeBuilder {
DepsgraphNodeBuilder(Main *bmain, Depsgraph *graph);
~DepsgraphNodeBuilder();
- void begin_build(Main *bmain);
+ void begin_build();
- RootDepsNode *add_root_node();
IDDepsNode *add_id_node(ID *id);
- TimeSourceDepsNode *add_time_source(ID *id);
+ TimeSourceDepsNode *add_time_source();
ComponentDepsNode *add_component_node(ID *id,
eDepsNode_Type comp_type,
const char *comp_name = "");
OperationDepsNode *add_operation_node(ComponentDepsNode *comp_node,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name = "",
int name_tag = -1);
OperationDepsNode *add_operation_node(ID *id,
eDepsNode_Type comp_type,
const char *comp_name,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name = "",
int name_tag = -1);
OperationDepsNode *add_operation_node(ID *id,
eDepsNode_Type comp_type,
- eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name = "",
int name_tag = -1);
+ OperationDepsNode *ensure_operation_node(ID *id,
+ eDepsNode_Type comp_type,
+ const DepsEvalOperationCb& op,
+ eDepsOperation_Code opcode,
+ const char *name = "",
+ int name_tag = -1);
+
bool has_operation_node(ID *id,
eDepsNode_Type comp_type,
const char *comp_name,
@@ -124,31 +126,33 @@ struct DepsgraphNodeBuilder {
const char *name = "",
int name_tag = -1);
- void build_scene(Main *bmain, Scene *scene);
- SubgraphDepsNode *build_subgraph(Group *group);
- void build_group(Scene *scene, Base *base, Group *group);
- void build_object(Scene *scene, Base *base, Object *ob);
- void build_object_transform(Scene *scene, Object *ob);
- void build_object_constraints(Scene *scene, Object *ob);
- void build_pose_constraints(Object *ob, bPoseChannel *pchan);
+ void build_id(ID* id);
+ void build_scene(Scene *scene);
+ void build_group(Base *base, Group *group);
+ void build_object(Base *base, Object *object);
+ void build_object_data(Object *object);
+ void build_object_transform(Object *object);
+ void build_object_constraints(Object *object);
+ void build_pose_constraints(Object *object, bPoseChannel *pchan, int pchan_index);
void build_rigidbody(Scene *scene);
- void build_particles(Scene *scene, Object *ob);
+ void build_particles(Object *object);
+ void build_cloth(Object *object);
void build_animdata(ID *id);
- OperationDepsNode *build_driver(ID *id, FCurve *fcurve);
- void build_ik_pose(Scene *scene,
- Object *ob,
+ void build_driver(ID *id, FCurve *fcurve);
+ void build_driver_variables(ID *id, FCurve *fcurve);
+ void build_driver_id_property(ID *id, const char *rna_path);
+ void build_ik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con);
- void build_splineik_pose(Scene *scene,
- Object *ob,
+ void build_splineik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con);
- void build_rig(Scene *scene, Object *ob);
- void build_proxy_rig(Object *ob);
+ void build_rig(Object *object);
+ void build_proxy_rig(Object *object);
void build_shapekeys(Key *key);
- void build_obdata_geom(Scene *scene, Object *ob);
- void build_camera(Object *ob);
- void build_lamp(Object *ob);
+ void build_obdata_geom(Object *object);
+ void build_camera(Object *object);
+ void build_lamp(Object *object);
void build_nodetree(bNodeTree *ntree);
void build_material(Material *ma);
void build_texture(Tex *tex);
@@ -162,8 +166,28 @@ struct DepsgraphNodeBuilder {
void build_movieclip(MovieClip *clip);
protected:
- Main *m_bmain;
- Depsgraph *m_graph;
+ struct BuilderWalkUserData {
+ DepsgraphNodeBuilder *builder;
+ };
+
+ static void modifier_walk(void *user_data,
+ struct Object *object,
+ struct ID **idpoin,
+ int cb_flag);
+
+ static void constraint_walk(bConstraint *constraint,
+ ID **idpoin,
+ bool is_reference,
+ void *user_data);
+
+ /* State which never changes, same for the whole builder time. */
+ Main *bmain_;
+ Depsgraph *graph_;
+
+ /* State which demotes currently built entities. */
+ Scene *scene_;
+
+ BuilderMap built_map_;
};
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes_rig.cc b/source/blender/depsgraph/intern/builder/deg_builder_nodes_rig.cc
index f2437ce1fac..9cfe83e0087 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_nodes_rig.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes_rig.cc
@@ -37,11 +37,11 @@
#include "MEM_guardedalloc.h"
-extern "C" {
+#include "BLI_utildefines.h"
#include "BLI_blenlib.h"
#include "BLI_string.h"
-#include "BLI_utildefines.h"
+extern "C" {
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
#include "DNA_constraint_types.h"
@@ -49,10 +49,11 @@ extern "C" {
#include "BKE_action.h"
#include "BKE_armature.h"
+#include "BKE_constraint.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
#include "intern/builder/deg_builder.h"
#include "intern/nodes/deg_node.h"
@@ -64,36 +65,59 @@ extern "C" {
namespace DEG {
-void DepsgraphNodeBuilder::build_pose_constraints(Object *ob, bPoseChannel *pchan)
+void DepsgraphNodeBuilder::build_pose_constraints(Object *object,
+ bPoseChannel *pchan,
+ int pchan_index)
{
- /* create node for constraint stack */
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_EXEC, function_bind(BKE_pose_constraints_evaluate, _1, ob, pchan),
+ /* Pull indirect dependencies via constraints. */
+ BuilderWalkUserData data;
+ data.builder = this;
+ BKE_constraints_id_loop(&pchan->constraints, constraint_walk, &data);
+ /* Create node for constraint stack. */
+ add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ function_bind(BKE_pose_constraints_evaluate,
+ _1,
+ scene_,
+ object,
+ pchan_index),
DEG_OPCODE_BONE_CONSTRAINTS);
}
/* IK Solver Eval Steps */
-void DepsgraphNodeBuilder::build_ik_pose(Scene *scene, Object *ob, bPoseChannel *pchan, bConstraint *con)
+void DepsgraphNodeBuilder::build_ik_pose(Object *object,
+ bPoseChannel *pchan,
+ bConstraint *con)
{
bKinematicConstraint *data = (bKinematicConstraint *)con->data;
/* Find the chain's root. */
bPoseChannel *rootchan = BKE_armature_ik_solver_find_root(pchan, data);
+ if (rootchan == NULL) {
+ return;
+ }
- if (has_operation_node(&ob->id, DEPSNODE_TYPE_EVAL_POSE, rootchan->name,
+ if (has_operation_node(&object->id, DEG_NODE_TYPE_EVAL_POSE, rootchan->name,
DEG_OPCODE_POSE_IK_SOLVER))
{
return;
}
+ int rootchan_index = BLI_findindex(&object->pose->chanbase, rootchan);
+ BLI_assert(rootchan_index != -1);
/* Operation node for evaluating/running IK Solver. */
- add_operation_node(&ob->id, DEPSNODE_TYPE_EVAL_POSE, rootchan->name,
- DEPSOP_TYPE_SIM, function_bind(BKE_pose_iktree_evaluate, _1, scene, ob, rootchan),
+ add_operation_node(&object->id, DEG_NODE_TYPE_EVAL_POSE, rootchan->name,
+ function_bind(BKE_pose_iktree_evaluate,
+ _1,
+ scene_,
+ object,
+ rootchan_index),
DEG_OPCODE_POSE_IK_SOLVER);
}
/* Spline IK Eval Steps */
-void DepsgraphNodeBuilder::build_splineik_pose(Scene *scene, Object *ob, bPoseChannel *pchan, bConstraint *con)
+void DepsgraphNodeBuilder::build_splineik_pose(Object *object,
+ bPoseChannel *pchan,
+ bConstraint *con)
{
bSplineIKConstraint *data = (bSplineIKConstraint *)con->data;
@@ -103,15 +127,22 @@ void DepsgraphNodeBuilder::build_splineik_pose(Scene *scene, Object *ob, bPoseCh
/* Operation node for evaluating/running Spline IK Solver.
* Store the "root bone" of this chain in the solver, so it knows where to start.
*/
- add_operation_node(&ob->id, DEPSNODE_TYPE_EVAL_POSE, rootchan->name,
- DEPSOP_TYPE_SIM, function_bind(BKE_pose_splineik_evaluate, _1, scene, ob, rootchan),
+ int rootchan_index = BLI_findindex(&object->pose->chanbase, rootchan);
+ BLI_assert(rootchan_index != -1);
+ add_operation_node(&object->id, DEG_NODE_TYPE_EVAL_POSE, rootchan->name,
+ function_bind(BKE_pose_splineik_evaluate,
+ _1,
+ scene_,
+ object,
+ rootchan_index),
DEG_OPCODE_POSE_SPLINE_IK_SOLVER);
}
/* Pose/Armature Bones Graph */
-void DepsgraphNodeBuilder::build_rig(Scene *scene, Object *ob)
+void DepsgraphNodeBuilder::build_rig(Object *object)
{
- bArmature *arm = (bArmature *)ob->data;
+ bArmature *arm = (bArmature *)object->data;
+ OperationDepsNode *op_node;
/* animation and/or drivers linking posebones to base-armature used to define them
* NOTE: AnimData here is really used to control animated deform properties,
@@ -119,35 +150,33 @@ void DepsgraphNodeBuilder::build_rig(Scene *scene, Object *ob)
* Eventually, we need some type of proxy/isolation mechanism in-between here
* to ensure that we can use same rig multiple times in same scene...
*/
- if ((arm->id.tag & LIB_TAG_DOIT) == 0) {
+ if (!built_map_.checkIsBuilt(arm)) {
build_animdata(&arm->id);
-
/* Make sure pose is up-to-date with armature updates. */
add_operation_node(&arm->id,
- DEPSNODE_TYPE_PARAMETERS,
- DEPSOP_TYPE_EXEC,
+ DEG_NODE_TYPE_PARAMETERS,
NULL,
DEG_OPCODE_PLACEHOLDER,
"Armature Eval");
}
/* Rebuild pose if not up to date. */
- if (ob->pose == NULL || (ob->pose->flag & POSE_RECALC)) {
- BKE_pose_rebuild_ex(ob, arm, false);
+ if (object->pose == NULL || (object->pose->flag & POSE_RECALC)) {
+ BKE_pose_rebuild_ex(object, arm, false);
/* XXX: Without this animation gets lost in certain circumstances
* after loading file. Need to investigate further since it does
* not happen with simple scenes..
*/
- if (ob->adt) {
- ob->adt->recalc |= ADT_RECALC_ANIM;
+ if (object->adt) {
+ object->adt->recalc |= ADT_RECALC_ANIM;
}
}
/* speed optimization for animation lookups */
- if (ob->pose) {
- BKE_pose_channels_hash_make(ob->pose);
- if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
- BKE_pose_update_constraint_flags(ob->pose);
+ if (object->pose) {
+ BKE_pose_channels_hash_make(object->pose);
+ if (object->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
+ BKE_pose_update_constraint_flags(object->pose);
}
}
@@ -174,102 +203,150 @@ void DepsgraphNodeBuilder::build_rig(Scene *scene, Object *ob)
*/
/* pose eval context */
- add_operation_node(&ob->id, DEPSNODE_TYPE_EVAL_POSE,
- DEPSOP_TYPE_INIT, function_bind(BKE_pose_eval_init, _1, scene, ob, ob->pose), DEG_OPCODE_POSE_INIT);
-
- add_operation_node(&ob->id, DEPSNODE_TYPE_EVAL_POSE,
- DEPSOP_TYPE_POST, function_bind(BKE_pose_eval_flush, _1, scene, ob, ob->pose), DEG_OPCODE_POSE_DONE);
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ function_bind(BKE_pose_eval_init,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_POSE_INIT);
+ op_node->set_as_entry();
+
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ function_bind(BKE_pose_eval_init_ik,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_POSE_INIT_IK);
+
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ function_bind(BKE_pose_eval_flush,
+ _1,
+ scene_,
+ object),
+ DEG_OPCODE_POSE_DONE);
+ op_node->set_as_exit();
/* bones */
- LINKLIST_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
- /* node for bone eval */
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_INIT, NULL, // XXX: BKE_pose_eval_bone_local
- DEG_OPCODE_BONE_LOCAL);
-
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_EXEC, function_bind(BKE_pose_eval_bone, _1, scene, ob, pchan), // XXX: BKE_pose_eval_bone_pose
+ int pchan_index = 0;
+ LISTBASE_FOREACH (bPoseChannel *, pchan, &object->pose->chanbase) {
+ /* Node for bone evaluation. */
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name, NULL,
+ DEG_OPCODE_BONE_LOCAL);
+ op_node->set_as_entry();
+
+ add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ function_bind(BKE_pose_eval_bone, _1, scene_, object, pchan_index),
DEG_OPCODE_BONE_POSE_PARENT);
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_OUT, NULL, /* NOTE: dedicated noop for easier relationship construction */
+ add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ NULL, /* NOTE: dedicated noop for easier relationship construction */
DEG_OPCODE_BONE_READY);
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_POST, function_bind(BKE_pose_bone_done, _1, pchan),
- DEG_OPCODE_BONE_DONE);
-
- /* constraints */
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ function_bind(BKE_pose_bone_done,
+ _1,
+ object,
+ pchan_index),
+ DEG_OPCODE_BONE_DONE);
+ op_node->set_as_exit();
+ /* Custom properties. */
+ if (pchan->prop != NULL) {
+ add_operation_node(&object->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL,
+ pchan->name);
+ }
+ /* Constraints. */
if (pchan->constraints.first != NULL) {
- build_pose_constraints(ob, pchan);
+ build_pose_constraints(object, pchan, pchan_index);
}
-
/**
- * IK Solvers...
+ * IK Solvers.
*
* - These require separate processing steps are pose-level
* to be executed between chains of bones (i.e. once the
* base transforms of a bunch of bones is done)
*
* Unsolved Issues:
- * - Care is needed to ensure that multi-headed trees work out the same as in ik-tree building
+ * - Care is needed to ensure that multi-headed trees work out the same
+ * as in ik-tree building.
* - Animated chain-lengths are a problem...
*/
- LINKLIST_FOREACH (bConstraint *, con, &pchan->constraints) {
+ LISTBASE_FOREACH (bConstraint *, con, &pchan->constraints) {
switch (con->type) {
case CONSTRAINT_TYPE_KINEMATIC:
- build_ik_pose(scene, ob, pchan, con);
+ build_ik_pose(object, pchan, con);
break;
case CONSTRAINT_TYPE_SPLINEIK:
- build_splineik_pose(scene, ob, pchan, con);
+ build_splineik_pose(object, pchan, con);
break;
default:
break;
}
}
+
+ /* Custom shape. */
+ if (pchan->custom != NULL) {
+ build_object(NULL, pchan->custom);
+ }
+
+ pchan_index++;
}
}
-void DepsgraphNodeBuilder::build_proxy_rig(Object *ob)
+void DepsgraphNodeBuilder::build_proxy_rig(Object *object)
{
- ID *obdata = (ID *)ob->data;
- build_animdata(obdata);
+ bArmature *arm = (bArmature *)object->data;
+ OperationDepsNode *op_node;
- BLI_assert(ob->pose != NULL);
+ build_animdata(&arm->id);
+
+ BLI_assert(object->pose != NULL);
/* speed optimization for animation lookups */
- BKE_pose_channels_hash_make(ob->pose);
- if (ob->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
- BKE_pose_update_constraint_flags(ob->pose);
+ BKE_pose_channels_hash_make(object->pose);
+ if (object->pose->flag & POSE_CONSTRAINTS_NEED_UPDATE_FLAGS) {
+ BKE_pose_update_constraint_flags(object->pose);
}
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_EVAL_POSE,
- DEPSOP_TYPE_INIT,
- function_bind(BKE_pose_eval_proxy_copy, _1, ob),
- DEG_OPCODE_POSE_INIT);
+ op_node = add_operation_node(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ function_bind(BKE_pose_eval_proxy_copy, _1, object),
+ DEG_OPCODE_POSE_INIT);
+ op_node->set_as_entry();
- LINKLIST_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_INIT, NULL,
- DEG_OPCODE_BONE_LOCAL);
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_EXEC, NULL,
- DEG_OPCODE_BONE_READY);
+ LISTBASE_FOREACH (bPoseChannel *, pchan, &object->pose->chanbase) {
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ NULL, DEG_OPCODE_BONE_LOCAL);
+ op_node->set_as_entry();
+
+ add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ NULL, DEG_OPCODE_BONE_READY);
- add_operation_node(&ob->id, DEPSNODE_TYPE_BONE, pchan->name,
- DEPSOP_TYPE_POST, NULL,
- DEG_OPCODE_BONE_DONE);
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_BONE, pchan->name,
+ NULL, DEG_OPCODE_BONE_DONE);
+ op_node->set_as_exit();
+
+ /* Custom properties. */
+ if (pchan->prop != NULL) {
+ add_operation_node(&object->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PARAMETERS_EVAL,
+ pchan->name);
+ }
}
- add_operation_node(&ob->id,
- DEPSNODE_TYPE_EVAL_POSE,
- DEPSOP_TYPE_POST,
- NULL,
- DEG_OPCODE_POSE_DONE);
+ op_node = add_operation_node(&object->id, DEG_NODE_TYPE_EVAL_POSE,
+ NULL, DEG_OPCODE_POSE_DONE);
+ op_node->set_as_exit();
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_nodes_scene.cc b/source/blender/depsgraph/intern/builder/deg_builder_nodes_scene.cc
index 99e61692231..4bb15350f3a 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_nodes_scene.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_nodes_scene.cc
@@ -37,21 +37,21 @@
#include "MEM_guardedalloc.h"
-extern "C" {
+#include "BLI_utildefines.h"
#include "BLI_blenlib.h"
#include "BLI_string.h"
-#include "BLI_utildefines.h"
+extern "C" {
#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "BKE_main.h"
#include "BKE_node.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
#include "intern/builder/deg_builder.h"
#include "intern/nodes/deg_node.h"
@@ -63,83 +63,63 @@ extern "C" {
namespace DEG {
-void DepsgraphNodeBuilder::build_scene(Main *bmain, Scene *scene)
+void DepsgraphNodeBuilder::build_scene(Scene *scene)
{
- /* scene ID block */
+ /* Scene ID block. */
add_id_node(&scene->id);
-
/* timesource */
- add_time_source(NULL);
-
+ add_time_source();
/* build subgraph for set, and link this in... */
// XXX: depending on how this goes, that scene itself could probably store its
// own little partial depsgraph?
- if (scene->set) {
- build_scene(bmain, scene->set);
+ if (scene->set != NULL) {
+ build_scene(scene->set);
}
-
+ /* Setup currently building context. */
+ scene_ = scene;
/* scene objects */
- LINKLIST_FOREACH (Base *, base, &scene->base) {
- Object *ob = base->object;
-
- /* object itself */
- build_object(scene, base, ob);
-
- /* object that this is a proxy for */
- // XXX: the way that proxies work needs to be completely reviewed!
- if (ob->proxy) {
- ob->proxy->proxy_from = ob;
- build_object(scene, base, ob->proxy);
- }
-
- /* Object dupligroup. */
- if (ob->dup_group) {
- build_group(scene, base, ob->dup_group);
- }
+ LISTBASE_FOREACH (Base *, base, &scene->base) {
+ Object *object = base->object;
+ build_object(base, object);
}
-
- /* rigidbody */
- if (scene->rigidbody_world) {
+ /* Rigidbody. */
+ if (scene->rigidbody_world != NULL) {
build_rigidbody(scene);
}
-
- /* scene's animation and drivers */
- if (scene->adt) {
+ /* Scene's animation and drivers. */
+ if (scene->adt != NULL) {
build_animdata(&scene->id);
}
-
- /* world */
- if (scene->world) {
+ /* World. */
+ if (scene->world != NULL) {
build_world(scene->world);
}
-
- /* compo nodes */
- if (scene->nodetree) {
+ /* Compositor nodes. */
+ if (scene->nodetree != NULL) {
build_compositor(scene);
}
-
- /* sequencer */
- // XXX...
-
- /* grease pencil */
- if (scene->gpd) {
+ /* Grease pencil. */
+ if (scene->gpd != NULL) {
build_gpencil(scene->gpd);
}
-
/* Cache file. */
- LINKLIST_FOREACH (CacheFile *, cachefile, &bmain->cachefiles) {
+ LISTBASE_FOREACH (CacheFile *, cachefile, &bmain_->cachefiles) {
build_cachefile(cachefile);
}
-
/* Masks. */
- LINKLIST_FOREACH (Mask *, mask, &bmain->mask) {
+ LISTBASE_FOREACH (Mask *, mask, &bmain_->mask) {
build_mask(mask);
}
-
/* Movie clips. */
- LINKLIST_FOREACH (MovieClip *, clip, &bmain->movieclip) {
+ LISTBASE_FOREACH (MovieClip *, clip, &bmain_->movieclip) {
build_movieclip(clip);
}
+ /* Parameters evaluation for scene relations mainly. */
+ add_operation_node(&scene->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ NULL,
+ DEG_OPCODE_PLACEHOLDER,
+ "Scene Eval");
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_pchanmap.cc b/source/blender/depsgraph/intern/builder/deg_builder_pchanmap.cc
index f870a33fb68..59eb7ed8cf1 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_pchanmap.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_pchanmap.cc
@@ -33,10 +33,8 @@
#include <stdio.h>
#include <string.h>
-extern "C" {
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
-}
namespace DEG {
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations.cc b/source/blender/depsgraph/intern/builder/deg_builder_relations.cc
index 94cff521edc..066c9868876 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_relations.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations.cc
@@ -38,10 +38,10 @@
#include "MEM_guardedalloc.h"
-extern "C" {
-#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLI_blenlib.h"
+extern "C" {
#include "DNA_action_types.h"
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
@@ -66,7 +66,7 @@ extern "C" {
#include "DNA_scene_types.h"
#include "DNA_texture_types.h"
#include "DNA_world_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "BKE_action.h"
#include "BKE_armature.h"
@@ -88,23 +88,24 @@ extern "C" {
#include "BKE_particle.h"
#include "BKE_rigidbody.h"
#include "BKE_sound.h"
-#include "BKE_texture.h"
#include "BKE_tracking.h"
#include "BKE_world.h"
-#include "DEG_depsgraph.h"
-#include "DEG_depsgraph_build.h"
-
#include "RNA_access.h"
#include "RNA_types.h"
} /* extern "C" */
+#include "DEG_depsgraph.h"
+#include "DEG_depsgraph_build.h"
+
#include "intern/builder/deg_builder.h"
#include "intern/builder/deg_builder_pchanmap.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
+#include "intern/nodes/deg_node_time.h"
#include "intern/depsgraph_intern.h"
#include "intern/depsgraph_types.h"
@@ -142,35 +143,42 @@ static bool python_driver_depends_on_time(ChannelDriver *driver)
return false;
}
-/* **** General purpose functions **** */
-
-RNAPathKey::RNAPathKey(ID *id, const char *path) :
- id(id)
+static bool particle_system_depends_on_time(ParticleSystem *psys)
{
- /* create ID pointer for root of path lookup */
- PointerRNA id_ptr;
- RNA_id_pointer_create(id, &id_ptr);
- /* try to resolve path... */
- int index;
- if (!RNA_path_resolve_full(&id_ptr, path, &this->ptr, &this->prop, &index)) {
- this->ptr = PointerRNA_NULL;
- this->prop = NULL;
+ ParticleSettings *part = psys->part;
+ /* Non-hair particles we always consider dependent on time. */
+ if (part->type != PART_HAIR) {
+ return true;
}
+ /* Dynamics always depends on time. */
+ if (psys->flag & PSYS_HAIR_DYNAMICS) {
+ return true;
+ }
+ /* TODO(sergey): Check what else makes hair dependent on time. */
+ return false;
}
-DepsgraphRelationBuilder::DepsgraphRelationBuilder(Depsgraph *graph) :
- m_graph(graph)
+static bool object_particles_depends_on_time(Object *object)
{
+ LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
+ if (particle_system_depends_on_time(psys)) {
+ return true;
+ }
+ }
+ return false;
}
-RootDepsNode *DepsgraphRelationBuilder::find_node(const RootKey &key) const
+/* **** General purpose functions **** */
+
+DepsgraphRelationBuilder::DepsgraphRelationBuilder(Main *bmain,
+ Depsgraph *graph)
+ : bmain_(bmain),
+ graph_(graph),
+ scene_(NULL)
{
- (void)key;
- BLI_assert(!"Doesn't seem to be correct");
- return m_graph->root_node;
}
-TimeSourceDepsNode *DepsgraphRelationBuilder::find_node(
+TimeSourceDepsNode *DepsgraphRelationBuilder::get_node(
const TimeSourceKey &key) const
{
if (key.id) {
@@ -178,14 +186,14 @@ TimeSourceDepsNode *DepsgraphRelationBuilder::find_node(
return NULL;
}
else {
- return m_graph->root_node->time_source;
+ return graph_->time_source;
}
}
-ComponentDepsNode *DepsgraphRelationBuilder::find_node(
+ComponentDepsNode *DepsgraphRelationBuilder::get_node(
const ComponentKey &key) const
{
- IDDepsNode *id_node = m_graph->find_id_node(key.id);
+ IDDepsNode *id_node = graph_->find_id_node(key.id);
if (!id_node) {
fprintf(stderr, "find_node component: Could not find ID %s\n",
(key.id != NULL) ? key.id->name : "<null>");
@@ -196,41 +204,26 @@ ComponentDepsNode *DepsgraphRelationBuilder::find_node(
return node;
}
-OperationDepsNode *DepsgraphRelationBuilder::find_node(
+OperationDepsNode *DepsgraphRelationBuilder::get_node(
const OperationKey &key) const
{
- IDDepsNode *id_node = m_graph->find_id_node(key.id);
- if (!id_node) {
- fprintf(stderr, "find_node operation: Could not find ID\n");
- return NULL;
- }
-
- ComponentDepsNode *comp_node = id_node->find_component(key.component_type,
- key.component_name);
- if (!comp_node) {
- fprintf(stderr, "find_node operation: Could not find component\n");
- return NULL;
- }
-
- OperationDepsNode *op_node = comp_node->find_operation(key.opcode,
- key.name,
- key.name_tag);
- if (!op_node) {
+ OperationDepsNode *op_node = find_node(key);
+ if (op_node == NULL) {
fprintf(stderr, "find_node_operation: Failed for (%s, '%s')\n",
DEG_OPNAMES[key.opcode], key.name);
}
return op_node;
}
-DepsNode *DepsgraphRelationBuilder::find_node(const RNAPathKey &key) const
+DepsNode *DepsgraphRelationBuilder::get_node(const RNAPathKey &key) const
{
- return m_graph->find_node_from_pointer(&key.ptr, key.prop);
+ return graph_->find_node_from_pointer(&key.ptr, key.prop);
}
-OperationDepsNode *DepsgraphRelationBuilder::has_node(
+OperationDepsNode *DepsgraphRelationBuilder::find_node(
const OperationKey &key) const
{
- IDDepsNode *id_node = m_graph->find_id_node(key.id);
+ IDDepsNode *id_node = graph_->find_id_node(key.id);
if (!id_node) {
return NULL;
}
@@ -239,97 +232,137 @@ OperationDepsNode *DepsgraphRelationBuilder::has_node(
if (!comp_node) {
return NULL;
}
- return comp_node->has_operation(key.opcode, key.name, key.name_tag);
+ return comp_node->find_operation(key.opcode, key.name, key.name_tag);
+}
+
+bool DepsgraphRelationBuilder::has_node(const OperationKey &key) const
+{
+ return find_node(key) != NULL;
}
-void DepsgraphRelationBuilder::add_time_relation(TimeSourceDepsNode *timesrc,
- DepsNode *node_to,
- const char *description)
+DepsRelation *DepsgraphRelationBuilder::add_time_relation(
+ TimeSourceDepsNode *timesrc,
+ DepsNode *node_to,
+ const char *description,
+ bool check_unique)
{
if (timesrc && node_to) {
- m_graph->add_new_relation(timesrc, node_to, DEPSREL_TYPE_TIME, description);
+ return graph_->add_new_relation(timesrc, node_to, description, check_unique);
}
else {
- DEG_DEBUG_PRINTF("add_time_relation(%p = %s, %p = %s, %s) Failed\n",
+ DEG_DEBUG_PRINTF(BUILD, "add_time_relation(%p = %s, %p = %s, %s) Failed\n",
timesrc, (timesrc) ? timesrc->identifier().c_str() : "<None>",
node_to, (node_to) ? node_to->identifier().c_str() : "<None>",
description);
}
+ return NULL;
}
-void DepsgraphRelationBuilder::add_operation_relation(
+DepsRelation *DepsgraphRelationBuilder::add_operation_relation(
OperationDepsNode *node_from,
OperationDepsNode *node_to,
- eDepsRelation_Type type,
- const char *description)
+ const char *description,
+ bool check_unique)
{
if (node_from && node_to) {
- m_graph->add_new_relation(node_from, node_to, type, description);
+ return graph_->add_new_relation(node_from,
+ node_to,
+ description,
+ check_unique);
}
else {
- DEG_DEBUG_PRINTF("add_operation_relation(%p = %s, %p = %s, %d, %s) Failed\n",
+ DEG_DEBUG_PRINTF(BUILD, "add_operation_relation(%p = %s, %p = %s, %s) Failed\n",
node_from, (node_from) ? node_from->identifier().c_str() : "<None>",
node_to, (node_to) ? node_to->identifier().c_str() : "<None>",
- type, description);
+ description);
}
+ return NULL;
}
-void DepsgraphRelationBuilder::add_collision_relations(const OperationKey &key, Scene *scene, Object *ob, Group *group, int layer, bool dupli, const char *name)
+void DepsgraphRelationBuilder::add_collision_relations(
+ const OperationKey &key,
+ Scene *scene,
+ Object *object,
+ Group *group,
+ int layer,
+ bool dupli,
+ const char *name)
{
unsigned int numcollobj;
- Object **collobjs = get_collisionobjects_ext(scene, ob, group, layer, &numcollobj, eModifierType_Collision, dupli);
-
- for (unsigned int i = 0; i < numcollobj; i++)
- {
+ Object **collobjs = get_collisionobjects_ext(
+ scene,
+ object,
+ group,
+ layer,
+ &numcollobj,
+ eModifierType_Collision,
+ dupli);
+ for (unsigned int i = 0; i < numcollobj; i++) {
Object *ob1 = collobjs[i];
- ComponentKey trf_key(&ob1->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(trf_key, key, DEPSREL_TYPE_STANDARD, name);
+ ComponentKey trf_key(&ob1->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(trf_key, key, name);
- ComponentKey coll_key(&ob1->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(coll_key, key, DEPSREL_TYPE_STANDARD, name);
+ ComponentKey coll_key(&ob1->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(coll_key, key, name);
}
-
- if (collobjs)
+ if (collobjs != NULL) {
MEM_freeN(collobjs);
+ }
}
-void DepsgraphRelationBuilder::add_forcefield_relations(const OperationKey &key, Scene *scene, Object *ob, ParticleSystem *psys, EffectorWeights *eff, bool add_absorption, const char *name)
+void DepsgraphRelationBuilder::add_forcefield_relations(
+ const OperationKey &key,
+ Scene *scene,
+ Object *object,
+ ParticleSystem *psys,
+ EffectorWeights *eff,
+ bool add_absorption,
+ const char *name)
{
- ListBase *effectors = pdInitEffectors(scene, ob, psys, eff, false);
-
- if (effectors) {
- for (EffectorCache *eff = (EffectorCache *)effectors->first; eff; eff = eff->next) {
- if (eff->ob != ob) {
- ComponentKey eff_key(&eff->ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(eff_key, key, DEPSREL_TYPE_STANDARD, name);
+ ListBase *effectors = pdInitEffectors(scene, object, psys, eff, false);
+ if (effectors != NULL) {
+ LISTBASE_FOREACH(EffectorCache *, eff, effectors) {
+ if (eff->ob != object) {
+ ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(eff_key, key, name);
}
+ if (eff->psys != NULL) {
+ if (eff->ob != object) {
+ ComponentKey eff_key(&eff->ob->id, DEG_NODE_TYPE_EVAL_PARTICLES);
+ add_relation(eff_key, key, name);
- if (eff->psys) {
- if (eff->ob != ob) {
- ComponentKey eff_key(&eff->ob->id, DEPSNODE_TYPE_EVAL_PARTICLES);
- add_relation(eff_key, key, DEPSREL_TYPE_STANDARD, name);
-
- /* TODO: remove this when/if EVAL_PARTICLES is sufficient for up to date particles */
- ComponentKey mod_key(&eff->ob->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(mod_key, key, DEPSREL_TYPE_STANDARD, name);
+ /* TODO: remove this when/if EVAL_PARTICLES is sufficient
+ * for up to date particles.
+ */
+ ComponentKey mod_key(&eff->ob->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(mod_key, key, name);
}
else if (eff->psys != psys) {
- OperationKey eff_key(&eff->ob->id, DEPSNODE_TYPE_EVAL_PARTICLES, DEG_OPCODE_PSYS_EVAL, eff->psys->name);
- add_relation(eff_key, key, DEPSREL_TYPE_STANDARD, name);
+ OperationKey eff_key(&eff->ob->id,
+ DEG_NODE_TYPE_EVAL_PARTICLES,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
+ eff->psys->name);
+ add_relation(eff_key, key, name);
}
}
-
if (eff->pd->forcefield == PFIELD_SMOKEFLOW && eff->pd->f_source) {
- ComponentKey trf_key(&eff->pd->f_source->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(trf_key, key, DEPSREL_TYPE_STANDARD, "Smoke Force Domain");
+ ComponentKey trf_key(&eff->pd->f_source->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(trf_key, key, "Smoke Force Domain");
- ComponentKey eff_key(&eff->pd->f_source->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(eff_key, key, DEPSREL_TYPE_STANDARD, "Smoke Force Domain");
+ ComponentKey eff_key(&eff->pd->f_source->id,
+ DEG_NODE_TYPE_GEOMETRY);
+ add_relation(eff_key, key, "Smoke Force Domain");
}
-
if (add_absorption && (eff->pd->flag & PFIELD_VISIBILITY)) {
- add_collision_relations(key, scene, ob, NULL, eff->ob->lay, true, "Force Absorption");
+ add_collision_relations(key,
+ scene,
+ object,
+ NULL,
+ eff->ob->lay,
+ true,
+ "Force Absorption");
}
}
}
@@ -337,199 +370,205 @@ void DepsgraphRelationBuilder::add_forcefield_relations(const OperationKey &key,
pdEndEffectors(&effectors);
}
+Depsgraph *DepsgraphRelationBuilder::getGraph()
+{
+ return graph_;
+}
+
/* **** Functions to build relations between entities **** */
-void DepsgraphRelationBuilder::begin_build(Main *bmain)
+void DepsgraphRelationBuilder::begin_build()
{
- /* LIB_TAG_DOIT is used to indicate whether node for given ID was already
- * created or not.
- */
- BKE_main_id_tag_all(bmain, LIB_TAG_DOIT, false);
- /* XXX nested node trees are notr included in tag-clearing above,
- * so we need to do this manually.
- */
- FOREACH_NODETREE(bmain, nodetree, id) {
- if (id != (ID *)nodetree) {
- nodetree->id.tag &= ~LIB_TAG_DOIT;
- }
- } FOREACH_NODETREE_END
}
-void DepsgraphRelationBuilder::build_group(Main *bmain,
- Scene *scene,
- Object *object,
- Group *group)
+void DepsgraphRelationBuilder::build_group(Object *object, Group *group)
{
- ID *group_id = &group->id;
- bool group_done = (group_id->tag & LIB_TAG_DOIT) != 0;
- OperationKey object_local_transform_key(&object->id,
- DEPSNODE_TYPE_TRANSFORM,
+ const bool group_done = built_map_.checkIsBuiltAndTag(group);
+ OperationKey object_local_transform_key(object != NULL ? &object->id : NULL,
+ DEG_NODE_TYPE_TRANSFORM,
DEG_OPCODE_TRANSFORM_LOCAL);
- LINKLIST_FOREACH (GroupObject *, go, &group->gobject) {
+ LISTBASE_FOREACH (GroupObject *, go, &group->gobject) {
if (!group_done) {
- build_object(bmain, scene, go->ob);
+ build_object(go->ob);
+ }
+ if (object != NULL) {
+ ComponentKey dupli_transform_key(&go->ob->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(dupli_transform_key, object_local_transform_key, "Dupligroup");
}
- ComponentKey dupli_transform_key(&go->ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(dupli_transform_key,
- object_local_transform_key,
- DEPSREL_TYPE_TRANSFORM,
- "Dupligroup");
}
- group_id->tag |= LIB_TAG_DOIT;
}
-void DepsgraphRelationBuilder::build_object(Main *bmain, Scene *scene, Object *ob)
+void DepsgraphRelationBuilder::build_object(Object *object)
{
- if (ob->id.tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(object)) {
return;
}
- ob->id.tag |= LIB_TAG_DOIT;
-
/* Object Transforms */
- eDepsOperation_Code base_op = (ob->parent) ? DEG_OPCODE_TRANSFORM_PARENT : DEG_OPCODE_TRANSFORM_LOCAL;
- OperationKey base_op_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, base_op);
-
- OperationKey local_transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_LOCAL);
- OperationKey parent_transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_PARENT);
- OperationKey final_transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_FINAL);
-
- OperationKey ob_ubereval_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_OBJECT_UBEREVAL);
-
- /* parenting */
- if (ob->parent) {
- /* parent relationship */
- build_object_parent(ob);
-
- /* local -> parent */
- add_relation(local_transform_key, parent_transform_key, DEPSREL_TYPE_COMPONENT_ORDER, "[ObLocal -> ObParent]");
- }
-
- /* object constraints */
- if (ob->constraints.first) {
- OperationKey constraint_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_CONSTRAINTS);
-
- /* constraint relations */
- // TODO: provide base op
- // XXX: this is broken
- build_constraints(scene, &ob->id, DEPSNODE_TYPE_TRANSFORM, "", &ob->constraints, NULL);
-
+ eDepsOperation_Code base_op = (object->parent) ? DEG_OPCODE_TRANSFORM_PARENT
+ : DEG_OPCODE_TRANSFORM_LOCAL;
+ OperationKey base_op_key(&object->id, DEG_NODE_TYPE_TRANSFORM, base_op);
+ OperationKey local_transform_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_LOCAL);
+ OperationKey parent_transform_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_PARENT);
+ OperationKey final_transform_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_FINAL);
+ OperationKey ob_ubereval_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
+ /* Parenting. */
+ if (object->parent != NULL) {
+ /* Make sure parent object's relations are built. */
+ build_object(object->parent);
+ /* Parent relationship. */
+ build_object_parent(object);
+ /* Local -> parent. */
+ add_relation(local_transform_key,
+ parent_transform_key,
+ "ObLocal -> ObParent");
+ }
+ /* Modifiers. */
+ if (object->modifiers.first != NULL) {
+ BuilderWalkUserData data;
+ data.builder = this;
+ modifiers_foreachIDLink(object, modifier_walk, &data);
+ }
+ /* Constraints. */
+ if (object->constraints.first != NULL) {
+ BuilderWalkUserData data;
+ data.builder = this;
+ BKE_constraints_id_loop(&object->constraints, constraint_walk, &data);
+ }
+ /* Object constraints. */
+ if (object->constraints.first != NULL) {
+ OperationKey constraint_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_CONSTRAINTS);
+ /* Constraint relations. */
+ build_constraints(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ "",
+ &object->constraints,
+ NULL);
/* operation order */
- add_relation(base_op_key, constraint_key, DEPSREL_TYPE_COMPONENT_ORDER, "[ObBase-> Constraint Stack]");
- add_relation(constraint_key, final_transform_key, DEPSREL_TYPE_COMPONENT_ORDER, "[ObConstraints -> Done]");
-
+ add_relation(base_op_key, constraint_key, "ObBase-> Constraint Stack");
+ add_relation(constraint_key, final_transform_key, "ObConstraints -> Done");
// XXX
- add_relation(constraint_key, ob_ubereval_key, DEPSREL_TYPE_COMPONENT_ORDER, "Temp Ubereval");
- add_relation(ob_ubereval_key, final_transform_key, DEPSREL_TYPE_COMPONENT_ORDER, "Temp Ubereval");
+ add_relation(constraint_key, ob_ubereval_key, "Temp Ubereval");
+ add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
}
else {
/* NOTE: Keep an eye here, we skip some relations here to "streamline"
* dependencies and avoid transitive relations which causes overhead.
* But once we get rid of uber eval node this will need reconsideration.
*/
- if (ob->rigidbody_object == NULL) {
+ if (object->rigidbody_object == NULL) {
/* Rigid body will hook up another node inbetween, so skip
* relation here to avoid transitive relation.
*/
- add_relation(base_op_key,
- ob_ubereval_key,
- DEPSREL_TYPE_COMPONENT_ORDER,
- "Temp Ubereval");
+ add_relation(base_op_key, ob_ubereval_key, "Temp Ubereval");
}
- add_relation(ob_ubereval_key,
- final_transform_key,
- DEPSREL_TYPE_COMPONENT_ORDER,
- "Temp Ubereval");
+ add_relation(ob_ubereval_key, final_transform_key, "Temp Ubereval");
+ }
+ /* Animation data */
+ build_animdata(&object->id);
+ /* Object data. */
+ build_object_data(object);
+ /* Particle systems. */
+ if (object->particlesystem.first != NULL) {
+ build_particles(object);
+ }
+ /* Grease pencil. */
+ if (object->gpd != NULL) {
+ build_gpencil(object->gpd);
+ }
+ /* Object that this is a proxy for. */
+ if (object->proxy != NULL) {
+ object->proxy->proxy_from = object;
+ build_object(object->proxy);
+ /* TODO(sergey): This is an inverted relation, matches old depsgraph
+ * behavior and need to be investigated if it still need to be inverted.
+ */
+ ComponentKey ob_pose_key(&object->id, DEG_NODE_TYPE_EVAL_POSE);
+ ComponentKey proxy_pose_key(&object->proxy->id, DEG_NODE_TYPE_EVAL_POSE);
+ add_relation(ob_pose_key, proxy_pose_key, "Proxy");
}
-
-
- /* AnimData */
- build_animdata(&ob->id);
-
- // XXX: This should be hooked up by the build_animdata code
- if (needs_animdata_node(&ob->id)) {
- ComponentKey adt_key(&ob->id, DEPSNODE_TYPE_ANIMATION);
- add_relation(adt_key, local_transform_key, DEPSREL_TYPE_OPERATION, "Object Animation");
+ /* Object dupligroup. */
+ if (object->dup_group != NULL) {
+ build_group(object, object->dup_group);
}
+}
-
- /* object data */
- if (ob->data) {
- ID *obdata_id = (ID *)ob->data;
-
- /* ob data animation */
- build_animdata(obdata_id);
-
- /* type-specific data... */
- switch (ob->type) {
- case OB_MESH: /* Geometry */
- case OB_CURVE:
- case OB_FONT:
- case OB_SURF:
- case OB_MBALL:
- case OB_LATTICE:
- {
- build_obdata_geom(bmain, scene, ob);
- break;
- }
-
- case OB_ARMATURE: /* Pose */
- if (ID_IS_LINKED_DATABLOCK(ob) && ob->proxy_from != NULL) {
- build_proxy_rig(ob);
- }
- else {
- build_rig(scene, ob);
- }
- break;
-
- case OB_LAMP: /* Lamp */
- build_lamp(ob);
- break;
-
- case OB_CAMERA: /* Camera */
- build_camera(ob);
- break;
- }
-
- Key *key = BKE_key_from_object(ob);
- if (key != NULL) {
- ComponentKey geometry_key((ID *)ob->data, DEPSNODE_TYPE_GEOMETRY);
- ComponentKey key_key(&key->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(key_key, geometry_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Shapekeys");
- }
+void DepsgraphRelationBuilder::build_object_data(Object *object)
+{
+ if (object->data == NULL) {
+ return;
}
-
- /* particle systems */
- if (ob->particlesystem.first) {
- build_particles(scene, ob);
+ ID *obdata_id = (ID *)object->data;
+ /* Object data animation. */
+ build_animdata(obdata_id);
+ /* type-specific data. */
+ switch (object->type) {
+ case OB_MESH:
+ case OB_CURVE:
+ case OB_FONT:
+ case OB_SURF:
+ case OB_MBALL:
+ case OB_LATTICE:
+ {
+ build_obdata_geom(object);
+ break;
+ }
+ case OB_ARMATURE:
+ if (ID_IS_LINKED(object) && object->proxy_from != NULL) {
+ build_proxy_rig(object);
+ }
+ else {
+ build_rig(object);
+ }
+ break;
+ case OB_LAMP:
+ build_lamp(object);
+ break;
+ case OB_CAMERA:
+ build_camera(object);
+ break;
}
-
- /* grease pencil */
- if (ob->gpd) {
- build_gpencil(ob->gpd);
+ Key *key = BKE_key_from_object(object);
+ if (key != NULL) {
+ ComponentKey geometry_key((ID *)object->data, DEG_NODE_TYPE_GEOMETRY);
+ ComponentKey key_key(&key->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(key_key, geometry_key, "Shapekeys");
}
}
-void DepsgraphRelationBuilder::build_object_parent(Object *ob)
+void DepsgraphRelationBuilder::build_object_parent(Object *object)
{
- /* XXX: for now, need to use the component key (not just direct to the parent op), or else the matrix doesn't get reset */
- // XXX: @sergey - it would be good if we got that backwards flushing working when tagging for updates
- //OperationKey ob_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_PARENT);
- ComponentKey ob_key(&ob->id, DEPSNODE_TYPE_TRANSFORM);
+ /* XXX: for now, need to use the component key (not just direct to the parent op),
+ * or else the matrix doesn't get reset/
+ */
+ // XXX: @sergey - it would be good if we got that backwards flushing working
+ // when tagging for updates.
+ //OperationKey ob_key(&object->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_PARENT);
+ ComponentKey ob_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
/* type-specific links */
- switch (ob->partype) {
+ switch (object->partype) {
case PARSKEL: /* Armature Deform (Virtual Modifier) */
{
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_STANDARD, "Armature Deform Parent");
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(parent_key, ob_key, "Armature Deform Parent");
break;
}
case PARVERT1: /* Vertex Parent */
case PARVERT3:
{
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Vertex Parent");
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(parent_key, ob_key, "Vertex Parent");
/* XXX not sure what this is for or how you could be done properly - lukas */
OperationDepsNode *parent_node = find_operation_node(parent_key);
@@ -537,179 +576,210 @@ void DepsgraphRelationBuilder::build_object_parent(Object *ob)
parent_node->customdata_mask |= CD_MASK_ORIGINDEX;
}
- ComponentKey transform_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(transform_key, ob_key, DEPSREL_TYPE_TRANSFORM, "Vertex Parent TFM");
+ ComponentKey transform_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(transform_key, ob_key, "Vertex Parent TFM");
break;
}
case PARBONE: /* Bone Parent */
{
- ComponentKey parent_bone_key(&ob->parent->id,
- DEPSNODE_TYPE_BONE,
- ob->parsubstr);
- OperationKey parent_transform_key(&ob->parent->id,
- DEPSNODE_TYPE_TRANSFORM,
+ ComponentKey parent_bone_key(&object->parent->id,
+ DEG_NODE_TYPE_BONE,
+ object->parsubstr);
+ OperationKey parent_transform_key(&object->parent->id,
+ DEG_NODE_TYPE_TRANSFORM,
DEG_OPCODE_TRANSFORM_FINAL);
- add_relation(parent_bone_key,
- ob_key,
- DEPSREL_TYPE_TRANSFORM,
- "Bone Parent");
- add_relation(parent_transform_key,
- ob_key,
- DEPSREL_TYPE_TRANSFORM,
- "Armature Parent");
+ add_relation(parent_bone_key, ob_key, "Bone Parent");
+ add_relation(parent_transform_key, ob_key, "Armature Parent");
break;
}
default:
{
- if (ob->parent->type == OB_LATTICE) {
+ if (object->parent->type == OB_LATTICE) {
/* Lattice Deform Parent - Virtual Modifier */
// XXX: no virtual modifiers should be left!
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- ComponentKey geom_key(&ob->parent->id, DEPSNODE_TYPE_GEOMETRY);
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ ComponentKey geom_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_STANDARD, "Lattice Deform Parent");
- add_relation(geom_key, ob_key, DEPSREL_TYPE_STANDARD, "Lattice Deform Parent Geom");
+ add_relation(parent_key, ob_key, "Lattice Deform Parent");
+ add_relation(geom_key, ob_key, "Lattice Deform Parent Geom");
}
- else if (ob->parent->type == OB_CURVE) {
- Curve *cu = (Curve *)ob->parent->data;
+ else if (object->parent->type == OB_CURVE) {
+ Curve *cu = (Curve *)object->parent->data;
if (cu->flag & CU_PATH) {
/* Follow Path */
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_TRANSFORM, "Curve Follow Parent");
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(parent_key, ob_key, "Curve Follow Parent");
- ComponentKey transform_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(transform_key, ob_key, DEPSREL_TYPE_TRANSFORM, "Curve Follow TFM");
+ ComponentKey transform_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(transform_key, ob_key, "Curve Follow TFM");
}
else {
/* Standard Parent */
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_TRANSFORM, "Curve Parent");
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(parent_key, ob_key, "Curve Parent");
}
}
else {
/* Standard Parent */
- ComponentKey parent_key(&ob->parent->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(parent_key, ob_key, DEPSREL_TYPE_TRANSFORM, "Parent");
+ ComponentKey parent_key(&object->parent->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(parent_key, ob_key, "Parent");
}
break;
}
}
/* exception case: parent is duplivert */
- if ((ob->type == OB_MBALL) && (ob->parent->transflag & OB_DUPLIVERTS)) {
+ if ((object->type == OB_MBALL) && (object->parent->transflag & OB_DUPLIVERTS)) {
//dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_OB, "Duplivert");
}
}
-void DepsgraphRelationBuilder::build_constraints(Scene *scene, ID *id, eDepsNode_Type component_type, const char *component_subdata,
- ListBase *constraints, RootPChanMap *root_map)
+void DepsgraphRelationBuilder::build_constraints(ID *id,
+ eDepsNode_Type component_type,
+ const char *component_subdata,
+ ListBase *constraints,
+ RootPChanMap *root_map)
{
- OperationKey constraint_op_key(id, component_type, component_subdata,
- (component_type == DEPSNODE_TYPE_BONE) ? DEG_OPCODE_BONE_CONSTRAINTS : DEG_OPCODE_TRANSFORM_CONSTRAINTS);
-
- /* add dependencies for each constraint in turn */
+ OperationKey constraint_op_key(
+ id,
+ component_type,
+ component_subdata,
+ (component_type == DEG_NODE_TYPE_BONE)
+ ? DEG_OPCODE_BONE_CONSTRAINTS
+ : DEG_OPCODE_TRANSFORM_CONSTRAINTS);
+ /* Add dependencies for each constraint in turn. */
for (bConstraint *con = (bConstraint *)constraints->first; con; con = con->next) {
const bConstraintTypeInfo *cti = BKE_constraint_typeinfo_get(con);
-
- /* invalid constraint type... */
- if (cti == NULL)
+ /* Invalid constraint type. */
+ if (cti == NULL) {
continue;
-
- /* special case for camera tracking -- it doesn't use targets to define relations */
- // TODO: we can now represent dependencies in a much richer manner, so review how this is done...
- if (ELEM(cti->type, CONSTRAINT_TYPE_FOLLOWTRACK, CONSTRAINT_TYPE_CAMERASOLVER, CONSTRAINT_TYPE_OBJECTSOLVER)) {
+ }
+ /* Special case for camera tracking -- it doesn't use targets to
+ * define relations.
+ */
+ /* TODO: we can now represent dependencies in a much richer manner,
+ * so review how this is done.
+ */
+ if (ELEM(cti->type,
+ CONSTRAINT_TYPE_FOLLOWTRACK,
+ CONSTRAINT_TYPE_CAMERASOLVER,
+ CONSTRAINT_TYPE_OBJECTSOLVER))
+ {
bool depends_on_camera = false;
-
if (cti->type == CONSTRAINT_TYPE_FOLLOWTRACK) {
bFollowTrackConstraint *data = (bFollowTrackConstraint *)con->data;
-
- if (((data->clip) || (data->flag & FOLLOWTRACK_ACTIVECLIP)) && data->track[0])
+ if (((data->clip) ||
+ (data->flag & FOLLOWTRACK_ACTIVECLIP)) && data->track[0])
+ {
depends_on_camera = true;
-
+ }
if (data->depth_ob) {
- // DAG_RL_DATA_OB | DAG_RL_OB_OB
- ComponentKey depth_key(&data->depth_ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(depth_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ ComponentKey depth_transform_key(&data->depth_ob->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ ComponentKey depth_geometry_key(&data->depth_ob->id,
+ DEG_NODE_TYPE_GEOMETRY);
+ add_relation(depth_transform_key, constraint_op_key, cti->name);
+ add_relation(depth_geometry_key, constraint_op_key, cti->name);
}
}
else if (cti->type == CONSTRAINT_TYPE_OBJECTSOLVER) {
depends_on_camera = true;
}
-
- if (depends_on_camera && scene->camera) {
- // DAG_RL_DATA_OB | DAG_RL_OB_OB
- ComponentKey camera_key(&scene->camera->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(camera_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ if (depends_on_camera && scene_->camera != NULL) {
+ ComponentKey camera_key(&scene_->camera->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(camera_key, constraint_op_key, cti->name);
}
-
- /* TODO(sergey): This is more a TimeSource -> MovieClip -> Constraint dependency chain. */
+ /* TODO(sergey): This is more a TimeSource -> MovieClip ->
+ * Constraint dependency chain.
+ */
TimeSourceKey time_src_key;
- add_relation(time_src_key, constraint_op_key, DEPSREL_TYPE_TIME, "[TimeSrc -> Animation]");
+ add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
}
else if (cti->type == CONSTRAINT_TYPE_TRANSFORM_CACHE) {
- /* TODO(kevin): This is more a TimeSource -> CacheFile -> Constraint dependency chain. */
+ /* TODO(kevin): This is more a TimeSource -> CacheFile -> Constraint
+ * dependency chain.
+ */
TimeSourceKey time_src_key;
- add_relation(time_src_key, constraint_op_key, DEPSREL_TYPE_TIME, "[TimeSrc -> Animation]");
-
+ add_relation(time_src_key, constraint_op_key, "TimeSrc -> Animation");
bTransformCacheConstraint *data = (bTransformCacheConstraint *)con->data;
-
if (data->cache_file) {
- ComponentKey cache_key(&data->cache_file->id, DEPSNODE_TYPE_CACHE);
- add_relation(cache_key, constraint_op_key, DEPSREL_TYPE_CACHE, cti->name);
+ ComponentKey cache_key(&data->cache_file->id, DEG_NODE_TYPE_CACHE);
+ add_relation(cache_key, constraint_op_key, cti->name);
}
}
else if (cti->get_constraint_targets) {
ListBase targets = {NULL, NULL};
cti->get_constraint_targets(con, &targets);
-
- LINKLIST_FOREACH (bConstraintTarget *, ct, &targets) {
+ LISTBASE_FOREACH (bConstraintTarget *, ct, &targets) {
if (ct->tar == NULL) {
continue;
}
-
- if (ELEM(con->type, CONSTRAINT_TYPE_KINEMATIC, CONSTRAINT_TYPE_SPLINEIK)) {
- /* ignore IK constraints - these are handled separately (on pose level) */
+ if (ELEM(con->type,
+ CONSTRAINT_TYPE_KINEMATIC,
+ CONSTRAINT_TYPE_SPLINEIK))
+ {
+ /* Ignore IK constraints - these are handled separately
+ * (on pose level).
+ */
}
- else if (ELEM(con->type, CONSTRAINT_TYPE_FOLLOWPATH, CONSTRAINT_TYPE_CLAMPTO)) {
- /* these constraints require path geometry data... */
- ComponentKey target_key(&ct->tar->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_GEOMETRY_EVAL, cti->name); // XXX: type = geom_transform
- // TODO: path dependency
+ else if (ELEM(con->type,
+ CONSTRAINT_TYPE_FOLLOWPATH,
+ CONSTRAINT_TYPE_CLAMPTO))
+ {
+ /* These constraints require path geometry data. */
+ ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(target_key, constraint_op_key, cti->name);
+ ComponentKey target_transform_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(target_transform_key, constraint_op_key, cti->name);
}
else if ((ct->tar->type == OB_ARMATURE) && (ct->subtarget[0])) {
/* bone */
if (&ct->tar->id == id) {
/* same armature */
eDepsOperation_Code target_key_opcode;
-
- /* Using "done" here breaks in-chain deps, while using "ready" here breaks most production rigs instead...
- * So, we do a compromise here, and only do this when an IK chain conflict may occur
+ /* Using "done" here breaks in-chain deps, while using
+ * "ready" here breaks most production rigs instead.
+ * So, we do a compromise here, and only do this when an
+ * IK chain conflict may occur.
*/
- if (root_map->has_common_root(component_subdata, ct->subtarget)) {
+ if (root_map->has_common_root(component_subdata,
+ ct->subtarget))
+ {
target_key_opcode = DEG_OPCODE_BONE_READY;
}
else {
target_key_opcode = DEG_OPCODE_BONE_DONE;
}
-
- OperationKey target_key(&ct->tar->id, DEPSNODE_TYPE_BONE, ct->subtarget, target_key_opcode);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ OperationKey target_key(&ct->tar->id,
+ DEG_NODE_TYPE_BONE,
+ ct->subtarget,
+ target_key_opcode);
+ add_relation(target_key, constraint_op_key, cti->name);
}
else {
- /* different armature - we can safely use the result of that */
- OperationKey target_key(&ct->tar->id, DEPSNODE_TYPE_BONE, ct->subtarget, DEG_OPCODE_BONE_DONE);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ /* Different armature - we can safely use the result
+ * of that.
+ */
+ OperationKey target_key(&ct->tar->id,
+ DEG_NODE_TYPE_BONE,
+ ct->subtarget,
+ DEG_OPCODE_BONE_DONE);
+ add_relation(target_key, constraint_op_key, cti->name);
}
}
- else if (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) && (ct->subtarget[0])) {
- /* vertex group */
- /* NOTE: for now, we don't need to represent vertex groups separately... */
- ComponentKey target_key(&ct->tar->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_GEOMETRY_EVAL, cti->name);
-
+ else if (ELEM(ct->tar->type, OB_MESH, OB_LATTICE) &&
+ (ct->subtarget[0]))
+ {
+ /* Vertex group. */
+ /* NOTE: for now, we don't need to represent vertex groups
+ * separately.
+ */
+ ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(target_key, constraint_op_key, cti->name);
if (ct->tar->type == OB_MESH) {
OperationDepsNode *node2 = find_operation_node(target_key);
if (node2 != NULL) {
@@ -719,39 +789,50 @@ void DepsgraphRelationBuilder::build_constraints(Scene *scene, ID *id, eDepsNode
}
else if (con->type == CONSTRAINT_TYPE_SHRINKWRAP) {
/* Constraints which requires the target object surface. */
- ComponentKey target_key(&ct->tar->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
-
- /* NOTE: obdata eval now doesn't necessarily depend on the object's transform... */
- ComponentKey target_transform_key(&ct->tar->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(target_transform_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ ComponentKey target_key(&ct->tar->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(target_key, constraint_op_key, cti->name);
+ /* NOTE: obdata eval now doesn't necessarily depend on the
+ * object's transform.
+ */
+ ComponentKey target_transform_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(target_transform_key, constraint_op_key, cti->name);
}
else {
- /* standard object relation */
+ /* Standard object relation. */
// TODO: loc vs rot vs scale?
if (&ct->tar->id == id) {
/* Constraint targetting own object:
- * - This case is fine IFF we're dealing with a bone constraint pointing to
- * its own armature. In that case, it's just transform -> bone.
- * - If however it is a real self targetting case, just make it depend on the
- * previous constraint (or the pre-constraint state)...
+ * - This case is fine IFF we're dealing with a bone
+ * constraint pointing to its own armature. In that
+ * case, it's just transform -> bone.
+ * - If however it is a real self targetting case, just
+ * make it depend on the previous constraint (or the
+ * pre-constraint state).
*/
- if ((ct->tar->type == OB_ARMATURE) && (component_type == DEPSNODE_TYPE_BONE)) {
- OperationKey target_key(&ct->tar->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_FINAL);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ if ((ct->tar->type == OB_ARMATURE) &&
+ (component_type == DEG_NODE_TYPE_BONE))
+ {
+ OperationKey target_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_FINAL);
+ add_relation(target_key, constraint_op_key, cti->name);
}
else {
- OperationKey target_key(&ct->tar->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_LOCAL);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ OperationKey target_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_LOCAL);
+ add_relation(target_key, constraint_op_key, cti->name);
}
}
else {
- /* normal object dependency */
- OperationKey target_key(&ct->tar->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_FINAL);
- add_relation(target_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ /* Normal object dependency. */
+ OperationKey target_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_FINAL);
+ add_relation(target_key, constraint_op_key, cti->name);
}
}
-
/* Constraints which needs world's matrix for transform.
* TODO(sergey): More constraints here?
*/
@@ -762,44 +843,130 @@ void DepsgraphRelationBuilder::build_constraints(Scene *scene, ID *id, eDepsNode
CONSTRAINT_TYPE_TRANSLIKE))
{
/* TODO(sergey): Add used space check. */
- ComponentKey target_transform_key(&ct->tar->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(target_transform_key, constraint_op_key, DEPSREL_TYPE_TRANSFORM, cti->name);
+ ComponentKey target_transform_key(&ct->tar->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(target_transform_key, constraint_op_key, cti->name);
}
-
}
-
- if (cti->flush_constraint_targets)
+ if (cti->flush_constraint_targets) {
cti->flush_constraint_targets(con, &targets, 1);
+ }
}
}
}
void DepsgraphRelationBuilder::build_animdata(ID *id)
{
- AnimData *adt = BKE_animdata_from_id(id);
+ /* Animation curves and NLA. */
+ build_animdata_curves(id);
+ /* Drivers. */
+ build_animdata_drivers(id);
+}
- if (adt == NULL)
+void DepsgraphRelationBuilder::build_animdata_curves(ID *id)
+{
+ AnimData *adt = BKE_animdata_from_id(id);
+ if (adt == NULL) {
return;
+ }
+ if (adt->action == NULL && adt->nla_tracks.first == NULL) {
+ return;
+ }
+ /* Wire up dependency to time source. */
+ ComponentKey adt_key(id, DEG_NODE_TYPE_ANIMATION);
+ TimeSourceKey time_src_key;
+ add_relation(time_src_key, adt_key, "TimeSrc -> Animation");
+ /* Get source operations. */
+ DepsNode *node_from = get_node(adt_key);
+ BLI_assert(node_from != NULL);
+ if (node_from == NULL) {
+ return;
+ }
+ OperationDepsNode *operation_from = node_from->get_exit_operation();
+ BLI_assert(operation_from != NULL);
+ /* Build relations from animation operation to properties it changes. */
+ if (adt->action != NULL) {
+ build_animdata_curves_targets(id, adt_key,
+ operation_from,
+ &adt->action->curves);
+ }
+ LISTBASE_FOREACH(NlaTrack *, nlt, &adt->nla_tracks) {
+ build_animdata_nlastrip_targets(id, adt_key,
+ operation_from,
+ &nlt->strips);
+ }
+}
- ComponentKey adt_key(id, DEPSNODE_TYPE_ANIMATION);
-
- /* animation */
- if (adt->action || adt->nla_tracks.first) {
- /* wire up dependency to time source */
- TimeSourceKey time_src_key;
- add_relation(time_src_key, adt_key, DEPSREL_TYPE_TIME, "[TimeSrc -> Animation]");
-
- // XXX: Hook up specific update callbacks for special properties which may need it...
+void DepsgraphRelationBuilder::build_animdata_curves_targets(
+ ID *id, ComponentKey &adt_key,
+ OperationDepsNode *operation_from,
+ ListBase *curves)
+{
+ /* Iterate over all curves and build relations. */
+ PointerRNA id_ptr;
+ RNA_id_pointer_create(id, &id_ptr);
+ LISTBASE_FOREACH(FCurve *, fcu, curves) {
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index;
+ if (!RNA_path_resolve_full(&id_ptr, fcu->rna_path,
+ &ptr, &prop, &index))
+ {
+ continue;
+ }
+ DepsNode *node_to = graph_->find_node_from_pointer(&ptr, prop);
+ if (node_to == NULL) {
+ continue;
+ }
+ OperationDepsNode *operation_to = node_to->get_entry_operation();
+ /* NOTE: Special case for bones, avoid relation from animation to
+ * each of the bones. Bone evaluation could only start from pose
+ * init anyway.
+ */
+ if (operation_to->opcode == DEG_OPCODE_BONE_LOCAL) {
+ OperationKey pose_init_key(id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ DEG_OPCODE_POSE_INIT);
+ add_relation(adt_key, pose_init_key, "Animation -> Prop", true);
+ continue;
+ }
+ graph_->add_new_relation(operation_from, operation_to,
+ "Animation -> Prop",
+ true);
+ }
+}
- // XXX: animdata "hierarchy" - top-level overrides need to go after lower-down
+void DepsgraphRelationBuilder::build_animdata_nlastrip_targets(
+ ID *id, ComponentKey &adt_key,
+ OperationDepsNode *operation_from,
+ ListBase *strips)
+{
+ LISTBASE_FOREACH(NlaStrip *, strip, strips) {
+ if (strip->act != NULL) {
+ build_animdata_curves_targets(id, adt_key,
+ operation_from,
+ &strip->act->curves);
+ }
+ else if (strip->strips.first != NULL) {
+ build_animdata_nlastrip_targets(id, adt_key,
+ operation_from,
+ &strip->strips);
+ }
}
+}
- /* drivers */
- LINKLIST_FOREACH (FCurve *, fcu, &adt->drivers) {
+void DepsgraphRelationBuilder::build_animdata_drivers(ID *id)
+{
+ AnimData *adt = BKE_animdata_from_id(id);
+ if (adt == NULL) {
+ return;
+ }
+ ComponentKey adt_key(id, DEG_NODE_TYPE_ANIMATION);
+ LISTBASE_FOREACH (FCurve *, fcu, &adt->drivers) {
OperationKey driver_key(id,
- DEPSNODE_TYPE_PARAMETERS,
+ DEG_NODE_TYPE_PARAMETERS,
DEG_OPCODE_DRIVER,
- fcu->rna_path,
+ fcu->rna_path ? fcu->rna_path : "",
fcu->array_index);
/* create the driver's relations to targets */
@@ -819,9 +986,10 @@ void DepsgraphRelationBuilder::build_animdata(ID *id)
*/
if (fcu->array_index > 0) {
FCurve *fcu_prev = NULL;
- LINKLIST_FOREACH (FCurve *, fcu_candidate, &adt->drivers) {
+ LISTBASE_FOREACH (FCurve *, fcu_candidate, &adt->drivers) {
/* Writing to different RNA paths is */
- if (!STREQ(fcu_candidate->rna_path, fcu->rna_path)) {
+ const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
+ if (!STREQ(fcu_candidate->rna_path, rna_path)) {
continue;
}
/* We only do relation from previous fcurve to previous one. */
@@ -837,26 +1005,22 @@ void DepsgraphRelationBuilder::build_animdata(ID *id)
}
if (fcu_prev != NULL) {
OperationKey prev_driver_key(id,
- DEPSNODE_TYPE_PARAMETERS,
+ DEG_NODE_TYPE_PARAMETERS,
DEG_OPCODE_DRIVER,
- fcu_prev->rna_path,
+ fcu_prev->rna_path ? fcu_prev->rna_path : "",
fcu_prev->array_index);
OperationKey driver_key(id,
- DEPSNODE_TYPE_PARAMETERS,
+ DEG_NODE_TYPE_PARAMETERS,
DEG_OPCODE_DRIVER,
- fcu->rna_path,
+ fcu->rna_path ? fcu->rna_path : "",
fcu->array_index);
- add_relation(prev_driver_key,
- driver_key,
- DEPSREL_TYPE_OPERATION,
- "[Driver Order]");
+ add_relation(prev_driver_key, driver_key, "Driver Order");
}
}
/* prevent driver from occurring before own animation... */
if (adt->action || adt->nla_tracks.first) {
- add_relation(adt_key, driver_key, DEPSREL_TYPE_OPERATION,
- "[AnimData Before Drivers]");
+ add_relation(adt_key, driver_key, "AnimData Before Drivers");
}
}
}
@@ -865,249 +1029,224 @@ void DepsgraphRelationBuilder::build_driver(ID *id, FCurve *fcu)
{
ChannelDriver *driver = fcu->driver;
OperationKey driver_key(id,
- DEPSNODE_TYPE_PARAMETERS,
+ DEG_NODE_TYPE_PARAMETERS,
DEG_OPCODE_DRIVER,
- fcu->rna_path,
+ fcu->rna_path ? fcu->rna_path : "",
fcu->array_index);
- bPoseChannel *pchan = NULL;
-
- /* create dependency between driver and data affected by it */
- /* - direct property relationship... */
- //RNAPathKey affected_key(id, fcu->rna_path);
- //add_relation(driver_key, affected_key, DEPSREL_TYPE_DRIVER, "[Driver -> Data] DepsRel");
-
- /* driver -> data components (for interleaved evaluation - bones/constraints/modifiers) */
- // XXX: this probably should probably be moved out into a separate function
- if (strstr(fcu->rna_path, "pose.bones[") != NULL) {
- /* interleaved drivers during bone eval */
- // TODO: ideally, if this is for a constraint, it goes to said constraint
- Object *ob = (Object *)id;
- char *bone_name;
-
- bone_name = BLI_str_quoted_substrN(fcu->rna_path, "pose.bones[");
- pchan = BKE_pose_channel_find_name(ob->pose, bone_name);
-
- if (bone_name) {
- MEM_freeN(bone_name);
- bone_name = NULL;
- }
-
- if (pchan) {
- OperationKey bone_key(id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_LOCAL);
- add_relation(driver_key, bone_key, DEPSREL_TYPE_DRIVER, "[Driver -> Bone]");
- }
- else {
- fprintf(stderr,
- "Couldn't find bone name for driver path - '%s'\n",
- fcu->rna_path);
- }
+ /* Driver -> data components (for interleaved evaluation
+ * bones/constraints/modifiers).
+ */
+ build_driver_data(id, fcu);
+ /* Loop over variables to get the target relationships. */
+ build_driver_variables(id, fcu);
+ /* It's quite tricky to detect if the driver actually depends on time or
+ * not, so for now we'll be quite conservative here about optimization and
+ * consider all python drivers to be depending on time.
+ */
+ if ((driver->type == DRIVER_TYPE_PYTHON) &&
+ python_driver_depends_on_time(driver))
+ {
+ TimeSourceKey time_src_key;
+ add_relation(time_src_key, driver_key, "TimeSrc -> Driver");
}
- else if (GS(id->name) == ID_AR && strstr(fcu->rna_path, "bones[")) {
- /* drivers on armature-level bone settings (i.e. bbone stuff),
- * which will affect the evaluation of corresponding pose bones
- */
- IDDepsNode *arm_node = m_graph->find_id_node(id);
- char *bone_name = BLI_str_quoted_substrN(fcu->rna_path, "bones[");
+}
+void DepsgraphRelationBuilder::build_driver_data(ID *id, FCurve *fcu)
+{
+ OperationKey driver_key(id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_DRIVER,
+ fcu->rna_path ? fcu->rna_path : "",
+ fcu->array_index);
+ const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
+ const RNAPathKey self_key(id, rna_path);
+ if (GS(id->name) == ID_AR && strstr(rna_path, "bones[")) {
+ /* Drivers on armature-level bone settings (i.e. bbone stuff),
+ * which will affect the evaluation of corresponding pose bones.
+ */
+ IDDepsNode *arm_node = graph_->find_id_node(id);
+ char *bone_name = BLI_str_quoted_substrN(rna_path, "bones[");
if (arm_node && bone_name) {
- /* find objects which use this, and make their eval callbacks depend on this */
+ /* Find objects which use this, and make their eval callbacks
+ * depend on this.
+ */
foreach (DepsRelation *rel, arm_node->outlinks) {
IDDepsNode *to_node = (IDDepsNode *)rel->to;
-
- /* we only care about objects with pose data which use this... */
+ /* We only care about objects with pose data which use this. */
if (GS(to_node->id->name) == ID_OB) {
- Object *ob = (Object *)to_node->id;
- bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, bone_name); // NOTE: ob->pose may be NULL
-
- if (pchan) {
- OperationKey bone_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_LOCAL);
- add_relation(driver_key, bone_key, DEPSREL_TYPE_DRIVER, "[Arm Bone -> Driver -> Bone]");
+ Object *object = (Object *)to_node->id;
+ /* NOTE: object->pose may be NULL. */
+ bPoseChannel *pchan = BKE_pose_channel_find_name(
+ object->pose, bone_name);
+ if (pchan != NULL) {
+ OperationKey bone_key(&object->id,
+ DEG_NODE_TYPE_BONE,
+ pchan->name,
+ DEG_OPCODE_BONE_LOCAL);
+ add_relation(driver_key,
+ bone_key,
+ "Arm Bone -> Driver -> Bone");
}
}
}
-
- /* free temp data */
+ /* Free temp data. */
MEM_freeN(bone_name);
bone_name = NULL;
}
else {
fprintf(stderr,
"Couldn't find armature bone name for driver path - '%s'\n",
- fcu->rna_path);
- }
- }
- else if (GS(id->name) == ID_OB && strstr(fcu->rna_path, "modifiers[")) {
- /* modifier driver - connect directly to the modifier */
- char *modifier_name = BLI_str_quoted_substrN(fcu->rna_path, "modifiers[");
- if (modifier_name) {
- OperationKey modifier_key(id,
- DEPSNODE_TYPE_GEOMETRY,
- DEG_OPCODE_GEOMETRY_MODIFIER,
- modifier_name);
- if (has_node(modifier_key)) {
- add_relation(driver_key, modifier_key, DEPSREL_TYPE_DRIVER, "[Driver -> Modifier]");
- }
- else {
- printf("Unexisting driver RNA path: %s\n", fcu->rna_path);
- }
-
- MEM_freeN(modifier_name);
+ rna_path);
}
}
- else if (GS(id->name) == ID_KE && strstr(fcu->rna_path, "key_blocks[")) {
- /* shape key driver - hook into the base geometry operation */
- // XXX: double check where this points
- Key *shape_key = (Key *)id;
-
- ComponentKey geometry_key(shape_key->from, DEPSNODE_TYPE_GEOMETRY);
- add_relation(driver_key, geometry_key, DEPSREL_TYPE_DRIVER, "[Driver -> ShapeKey Geom]");
- }
- else if (strstr(fcu->rna_path, "key_blocks[")) {
- ComponentKey geometry_key(id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(driver_key, geometry_key, DEPSREL_TYPE_DRIVER, "[Driver -> ShapeKey Geom]");
- }
else {
- if (GS(id->name) == ID_OB) {
- /* assume that driver affects a transform... */
- OperationKey local_transform_key(id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_LOCAL);
- add_relation(driver_key, local_transform_key, DEPSREL_TYPE_OPERATION, "[Driver -> Transform]");
+ RNAPathKey target_key(id, rna_path);
+ if (RNA_pointer_is_null(&target_key.ptr)) {
+ /* TODO(sergey): This would only mean that driver is broken.
+ * so we can't create relation anyway. However, we need to avoid
+ * adding drivers which are known to be buggy to a dependency
+ * graph, in order to save computational power.
+ */
}
- else if (GS(id->name) == ID_KE) {
- ComponentKey geometry_key(id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(driver_key, geometry_key, DEPSREL_TYPE_GEOMETRY_EVAL, "[Driver -> Shapekey Geometry]");
+ else {
+ if (target_key.prop != NULL &&
+ RNA_property_is_idprop(target_key.prop))
+ {
+ OperationKey parameters_key(id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ add_relation(target_key,
+ parameters_key,
+ "Driver Target -> Properties");
+ }
+ add_relation(driver_key, target_key, "Driver -> Target");
}
}
+}
- /* ensure that affected prop's update callbacks will be triggered once done */
- // TODO: implement this once the functionality to add these links exists in RNA
- // XXX: the data itself could also set this, if it were to be truly initialised later?
+void DepsgraphRelationBuilder::build_driver_variables(ID *id, FCurve *fcu)
+{
+ ChannelDriver *driver = fcu->driver;
+ OperationKey driver_key(id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_DRIVER,
+ fcu->rna_path ? fcu->rna_path : "",
+ fcu->array_index);
+ const char *rna_path = fcu->rna_path ? fcu->rna_path : "";
+ const RNAPathKey self_key(id, rna_path);
- /* loop over variables to get the target relationships */
- LINKLIST_FOREACH (DriverVar *, dvar, &driver->variables) {
- /* only used targets */
+ LISTBASE_FOREACH (DriverVar *, dvar, &driver->variables) {
+ /* Only used targets. */
DRIVER_TARGETS_USED_LOOPER(dvar)
{
- if (dtar->id == NULL)
+ if (dtar->id == NULL) {
continue;
-
- /* special handling for directly-named bones */
- if ((dtar->flag & DTAR_FLAG_STRUCT_REF) && (dtar->pchan_name[0])) {
- Object *ob = (Object *)dtar->id;
- bPoseChannel *target_pchan = BKE_pose_channel_find_name(ob->pose, dtar->pchan_name);
- if (target_pchan != NULL) {
- /* get node associated with bone */
- // XXX: watch the space!
- /* Some cases can't use final bone transform, for example:
- * - Driving the bone with itself (addressed here)
- * - Relations inside an IK chain (TODO?)
- */
- if (dtar->id == id &&
- pchan != NULL &&
- STREQ(pchan->name, target_pchan->name))
- {
- continue;
- }
- OperationKey target_key(dtar->id, DEPSNODE_TYPE_BONE, target_pchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(target_key, driver_key, DEPSREL_TYPE_DRIVER_TARGET, "[Bone Target -> Driver]");
+ }
+ /* Special handling for directly-named bones. */
+ if ((dtar->flag & DTAR_FLAG_STRUCT_REF) &&
+ (((Object *)dtar->id)->type == OB_ARMATURE) &&
+ (dtar->pchan_name[0]))
+ {
+ Object *object = (Object *)dtar->id;
+ bPoseChannel *target_pchan =
+ BKE_pose_channel_find_name(object->pose,
+ dtar->pchan_name);
+ if (target_pchan == NULL) {
+ continue;
+ }
+ OperationKey variable_key(dtar->id,
+ DEG_NODE_TYPE_BONE,
+ target_pchan->name,
+ DEG_OPCODE_BONE_DONE);
+ if (is_same_bone_dependency(variable_key, self_key)) {
+ continue;
}
+ add_relation(variable_key, driver_key, "Bone Target -> Driver");
}
else if (dtar->flag & DTAR_FLAG_STRUCT_REF) {
- /* get node associated with the object's transforms */
- OperationKey target_key(dtar->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_FINAL);
- add_relation(target_key, driver_key, DEPSREL_TYPE_DRIVER_TARGET, "[Target -> Driver]");
+ /* Get node associated with the object's transforms. */
+ if (dtar->id == id) {
+ /* Ignore input dependency if we're driving properties of
+ * the same ID, otherwise we'll be ending up in a cyclic
+ * dependency here.
+ */
+ continue;
+ }
+ OperationKey target_key(dtar->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_FINAL);
+ add_relation(target_key, driver_key, "Target -> Driver");
}
- else if (dtar->rna_path && strstr(dtar->rna_path, "pose.bones[")) {
- /* workaround for ensuring that local bone transforms don't end up
- * having to wait for pose eval to finish (to prevent cycles)
- */
- Object *ob = (Object *)dtar->id;
- char *bone_name = BLI_str_quoted_substrN(dtar->rna_path, "pose.bones[");
- bPoseChannel *target_pchan = BKE_pose_channel_find_name(ob->pose, bone_name);
- if (bone_name) {
- MEM_freeN(bone_name);
- bone_name = NULL;
+ else if (dtar->rna_path) {
+ RNAPathKey variable_key(dtar->id, dtar->rna_path);
+ if (RNA_pointer_is_null(&variable_key.ptr)) {
+ continue;
}
- if (target_pchan) {
- if (dtar->id == id &&
- pchan != NULL &&
- STREQ(pchan->name, target_pchan->name))
- {
- continue;
- }
- OperationKey bone_key(dtar->id, DEPSNODE_TYPE_BONE, target_pchan->name, DEG_OPCODE_BONE_LOCAL);
- add_relation(bone_key, driver_key, DEPSREL_TYPE_DRIVER, "[RNA Bone -> Driver]");
+ if (is_same_bone_dependency(variable_key, self_key) ||
+ is_same_nodetree_node_dependency(variable_key, self_key) ||
+ is_same_shapekey_dependency(variable_key, self_key))
+ {
+ continue;
}
+ add_relation(variable_key, driver_key, "RNA Target -> Driver");
}
else {
if (dtar->id == id) {
- /* Ignore input dependency if we're driving properties of the same ID,
- * otherwise we'll be ending up in a cyclic dependency here.
+ /* Ignore input dependency if we're driving properties of
+ * the same ID, otherwise we'll be ending up in a cyclic
+ * dependency here.
*/
continue;
}
- /* resolve path to get node */
- RNAPathKey target_key(dtar->id, dtar->rna_path ? dtar->rna_path : "");
- add_relation(target_key, driver_key, DEPSREL_TYPE_DRIVER_TARGET, "[RNA Target -> Driver]");
+ /* Resolve path to get node. */
+ RNAPathKey target_key(dtar->id,
+ dtar->rna_path ? dtar->rna_path : "");
+ add_relation(target_key, driver_key, "RNA Target -> Driver");
}
}
DRIVER_TARGETS_LOOPER_END
}
-
- /* It's quite tricky to detect if the driver actually depends on time or not,
- * so for now we'll be quite conservative here about optimization and consider
- * all python drivers to be depending on time.
- */
- if ((driver->type == DRIVER_TYPE_PYTHON) &&
- python_driver_depends_on_time(driver))
- {
- TimeSourceKey time_src_key;
- add_relation(time_src_key, driver_key, DEPSREL_TYPE_TIME, "[TimeSrc -> Driver]");
- }
}
void DepsgraphRelationBuilder::build_world(World *world)
{
- ID *world_id = &world->id;
- if (world_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(world)) {
return;
}
- world_id->tag |= LIB_TAG_DOIT;
-
- build_animdata(world_id);
-
+ build_animdata(&world->id);
/* TODO: other settings? */
-
/* textures */
build_texture_stack(world->mtex);
-
/* world's nodetree */
- build_nodetree(world->nodetree);
+ if (world->nodetree != NULL) {
+ build_nodetree(world->nodetree);
+ ComponentKey ntree_key(&world->nodetree->id, DEG_NODE_TYPE_PARAMETERS);
+ ComponentKey world_key(&world->id, DEG_NODE_TYPE_PARAMETERS);
+ add_relation(ntree_key, world_key, "NTree->World Parameters");
+ }
}
void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
{
RigidBodyWorld *rbw = scene->rigidbody_world;
- OperationKey init_key(&scene->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_REBUILD);
- OperationKey sim_key(&scene->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_SIM);
+ OperationKey init_key(&scene->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_REBUILD);
+ OperationKey sim_key(&scene->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_SIM);
/* rel between the two sim-nodes */
- add_relation(init_key, sim_key, DEPSREL_TYPE_OPERATION, "Rigidbody [Init -> SimStep]");
+ add_relation(init_key, sim_key, "Rigidbody [Init -> SimStep]");
/* set up dependencies between these operations and other builtin nodes --------------- */
/* time dependency */
TimeSourceKey time_src_key;
- add_relation(time_src_key,
- init_key,
- DEPSREL_TYPE_TIME,
- "TimeSrc -> Rigidbody Reset/Rebuild (Optional)");
+ add_relation(time_src_key, init_key, "TimeSrc -> Rigidbody Reset/Rebuild (Optional)");
/* objects - simulation participants */
if (rbw->group) {
- LINKLIST_FOREACH (GroupObject *, go, &rbw->group->gobject) {
- Object *ob = go->ob;
- if (ob == NULL || ob->type != OB_MESH) {
+ LISTBASE_FOREACH (GroupObject *, go, &rbw->group->gobject) {
+ Object *object = go->ob;
+ if (object == NULL || object->type != OB_MESH) {
continue;
}
@@ -1119,12 +1258,12 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
* XXX: there's probably a difference between passive and active
* - passive don't change, so may need to know full transform...
*/
- OperationKey rbo_key(&ob->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_RIGIDBODY);
+ OperationKey rbo_key(&object->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
- eDepsOperation_Code trans_opcode = ob->parent ? DEG_OPCODE_TRANSFORM_PARENT : DEG_OPCODE_TRANSFORM_LOCAL;
- OperationKey trans_op(&ob->id, DEPSNODE_TYPE_TRANSFORM, trans_opcode);
+ eDepsOperation_Code trans_opcode = object->parent ? DEG_OPCODE_TRANSFORM_PARENT : DEG_OPCODE_TRANSFORM_LOCAL;
+ OperationKey trans_op(&object->id, DEG_NODE_TYPE_TRANSFORM, trans_opcode);
- add_relation(sim_key, rbo_key, DEPSREL_TYPE_COMPONENT_ORDER, "Rigidbody Sim Eval -> RBO Sync");
+ add_relation(sim_key, rbo_key, "Rigidbody Sim Eval -> RBO Sync");
/* if constraints exist, those depend on the result of the rigidbody sim
* - This allows constraints to modify the result of the sim (i.e. clamping)
@@ -1134,14 +1273,11 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
* - Later, it might be good to include a constraint in the stack allowing us
* to control whether rigidbody eval gets interleaved into the constraint stack
*/
- if (ob->constraints.first) {
- OperationKey constraint_key(&ob->id,
- DEPSNODE_TYPE_TRANSFORM,
+ if (object->constraints.first) {
+ OperationKey constraint_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
DEG_OPCODE_TRANSFORM_CONSTRAINTS);
- add_relation(rbo_key,
- constraint_key,
- DEPSREL_TYPE_COMPONENT_ORDER,
- "RBO Sync -> Ob Constraints");
+ add_relation(rbo_key, constraint_key, "RBO Sync -> Ob Constraints");
}
else {
/* Final object transform depends on rigidbody.
@@ -1149,150 +1285,140 @@ void DepsgraphRelationBuilder::build_rigidbody(Scene *scene)
* NOTE: Currently we consider final here an ubereval node.
* If it is gone we'll need to reconsider relation here.
*/
- OperationKey uber_key(&ob->id,
- DEPSNODE_TYPE_TRANSFORM,
- DEG_OPCODE_OBJECT_UBEREVAL);
- add_relation(rbo_key,
- uber_key,
- DEPSREL_TYPE_COMPONENT_ORDER,
- "RBO Sync -> Uber (Temp)");
+ OperationKey uber_key(&object->id,
+ DEG_NODE_TYPE_TRANSFORM,
+ DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL);
+ add_relation(rbo_key, uber_key, "RBO Sync -> Uber (Temp)");
}
/* Needed to get correct base values. */
- add_relation(trans_op,
- sim_key,
- DEPSREL_TYPE_OPERATION,
- "Base Ob Transform -> Rigidbody Sim Eval");
+ add_relation(trans_op, sim_key, "Base Ob Transform -> Rigidbody Sim Eval");
}
}
/* constraints */
if (rbw->constraints) {
- LINKLIST_FOREACH (GroupObject *, go, &rbw->constraints->gobject) {
- Object *ob = go->ob;
- if (ob == NULL || !ob->rigidbody_constraint) {
+ LISTBASE_FOREACH (GroupObject *, go, &rbw->constraints->gobject) {
+ Object *object = go->ob;
+ if (object == NULL || !object->rigidbody_constraint) {
continue;
}
- RigidBodyCon *rbc = ob->rigidbody_constraint;
+ RigidBodyCon *rbc = object->rigidbody_constraint;
/* final result of the constraint object's transform controls how the
* constraint affects the physics sim for these objects
*/
- ComponentKey trans_key(&ob->id, DEPSNODE_TYPE_TRANSFORM);
- OperationKey ob1_key(&rbc->ob1->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_RIGIDBODY);
- OperationKey ob2_key(&rbc->ob2->id, DEPSNODE_TYPE_TRANSFORM, DEG_OPCODE_TRANSFORM_RIGIDBODY);
+ ComponentKey trans_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
+ OperationKey ob1_key(&rbc->ob1->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
+ OperationKey ob2_key(&rbc->ob2->id, DEG_NODE_TYPE_TRANSFORM, DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY);
/* - constrained-objects sync depends on the constraint-holder */
- add_relation(trans_key, ob1_key, DEPSREL_TYPE_TRANSFORM, "RigidBodyConstraint -> RBC.Object_1");
- add_relation(trans_key, ob2_key, DEPSREL_TYPE_TRANSFORM, "RigidBodyConstraint -> RBC.Object_2");
+ add_relation(trans_key, ob1_key, "RigidBodyConstraint -> RBC.Object_1");
+ add_relation(trans_key, ob2_key, "RigidBodyConstraint -> RBC.Object_2");
/* - ensure that sim depends on this constraint's transform */
- add_relation(trans_key, sim_key, DEPSREL_TYPE_TRANSFORM, "RigidBodyConstraint Transform -> RB Simulation");
+ add_relation(trans_key, sim_key, "RigidBodyConstraint Transform -> RB Simulation");
}
}
}
-void DepsgraphRelationBuilder::build_particles(Scene *scene, Object *ob)
+void DepsgraphRelationBuilder::build_particles(Object *object)
{
TimeSourceKey time_src_key;
- OperationKey obdata_ubereval_key(&ob->id,
- DEPSNODE_TYPE_GEOMETRY,
+ OperationKey obdata_ubereval_key(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
DEG_OPCODE_GEOMETRY_UBEREVAL);
+ OperationKey eval_init_key(&object->id,
+ DEG_NODE_TYPE_EVAL_PARTICLES,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL_INIT);
- /* particle systems */
- LINKLIST_FOREACH (ParticleSystem *, psys, &ob->particlesystem) {
+ /* Particle systems. */
+ LISTBASE_FOREACH (ParticleSystem *, psys, &object->particlesystem) {
ParticleSettings *part = psys->part;
-
- /* particle settings */
+ /* Animation of particle settings, */
build_animdata(&part->id);
-
- /* this particle system */
- OperationKey psys_key(&ob->id, DEPSNODE_TYPE_EVAL_PARTICLES, DEG_OPCODE_PSYS_EVAL, psys->name);
-
- /* XXX: if particle system is later re-enabled, we must do full rebuild? */
- if (!psys_check_enabled(ob, psys, G.is_rendering))
- continue;
-
- /* TODO(sergey): Are all particle systems depends on time?
- * Hair without dynamics i.e.
- */
- add_relation(time_src_key, psys_key,
- DEPSREL_TYPE_TIME,
- "TimeSrc -> PSys");
-
+ /* This particle system. */
+ OperationKey psys_key(&object->id,
+ DEG_NODE_TYPE_EVAL_PARTICLES,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
+ psys->name);
+ add_relation(eval_init_key, psys_key, "Init -> PSys");
/* TODO(sergey): Currently particle update is just a placeholder,
* hook it to the ubereval node so particle system is getting updated
* on playback.
*/
- add_relation(psys_key,
- obdata_ubereval_key,
- DEPSREL_TYPE_OPERATION,
- "PSys -> UberEval");
-
-#if 0
- if (ELEM(part->phystype, PART_PHYS_KEYED, PART_PHYS_BOIDS)) {
- LINKLIST_FOREACH (ParticleTarget *, pt, &psys->targets) {
- if (pt->ob && BLI_findlink(&pt->ob->particlesystem, pt->psys - 1)) {
- node2 = dag_get_node(dag, pt->ob);
- dag_add_relation(dag, node2, node, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Particle Targets");
- }
- }
- }
-
- if (part->ren_as == PART_DRAW_OB && part->dup_ob) {
- node2 = dag_get_node(dag, part->dup_ob);
- /* note that this relation actually runs in the wrong direction, the problem
- * is that dupli system all have this (due to parenting), and the render
- * engine instancing assumes particular ordering of objects in list */
- dag_add_relation(dag, node, node2, DAG_RL_OB_OB, "Particle Object Visualization");
- if (part->dup_ob->type == OB_MBALL)
- dag_add_relation(dag, node, node2, DAG_RL_DATA_DATA, "Particle Object Visualization");
- }
-
- if (part->ren_as == PART_DRAW_GR && part->dup_group) {
- LINKLIST_FOREACH (GroupObject *, go, &part->dup_group->gobject) {
- node2 = dag_get_node(dag, go->ob);
- dag_add_relation(dag, node2, node, DAG_RL_OB_OB, "Particle Group Visualization");
- }
- }
-#endif
-
- /* collisions */
+ add_relation(psys_key, obdata_ubereval_key, "PSys -> UberEval");
+ /* Collisions */
if (part->type != PART_HAIR) {
- add_collision_relations(psys_key, scene, ob, part->collision_group, ob->lay, true, "Particle Collision");
+ add_collision_relations(psys_key,
+ scene_,
+ object,
+ part->collision_group,
+ object->lay,
+ true,
+ "Particle Collision");
}
- else if ((psys->flag & PSYS_HAIR_DYNAMICS) && psys->clmd && psys->clmd->coll_parms) {
- add_collision_relations(psys_key, scene, ob, psys->clmd->coll_parms->group, ob->lay | scene->lay, true, "Hair Collision");
+ else if ((psys->flag & PSYS_HAIR_DYNAMICS) &&
+ psys->clmd && psys->clmd->coll_parms)
+ {
+ add_collision_relations(psys_key,
+ scene_,
+ object,
+ psys->clmd->coll_parms->group,
+ object->lay | scene_->lay,
+ true,
+ "Hair Collision");
}
-
- /* effectors */
- add_forcefield_relations(psys_key, scene, ob, psys, part->effector_weights, part->type == PART_HAIR, "Particle Field");
-
- /* boids */
+ /* Effectors. */
+ add_forcefield_relations(psys_key,
+ scene_,
+ object,
+ psys,
+ part->effector_weights,
+ part->type == PART_HAIR,
+ "Particle Field");
+ /* Boids. */
if (part->boids) {
- LINKLIST_FOREACH (BoidState *, state, &part->boids->states) {
- LINKLIST_FOREACH (BoidRule *, rule, &state->rules) {
+ LISTBASE_FOREACH (BoidState *, state, &part->boids->states) {
+ LISTBASE_FOREACH (BoidRule *, rule, &state->rules) {
Object *ruleob = NULL;
- if (rule->type == eBoidRuleType_Avoid)
+ if (rule->type == eBoidRuleType_Avoid) {
ruleob = ((BoidRuleGoalAvoid *)rule)->ob;
- else if (rule->type == eBoidRuleType_FollowLeader)
+ }
+ else if (rule->type == eBoidRuleType_FollowLeader) {
ruleob = ((BoidRuleFollowLeader *)rule)->ob;
-
+ }
if (ruleob) {
- ComponentKey ruleob_key(&ruleob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(ruleob_key, psys_key, DEPSREL_TYPE_TRANSFORM, "Boid Rule");
+ ComponentKey ruleob_key(&ruleob->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(ruleob_key, psys_key, "Boid Rule");
}
}
}
}
- if (part->ren_as == PART_DRAW_OB && part->dup_ob) {
- ComponentKey dup_ob_key(&part->dup_ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(dup_ob_key,
- psys_key,
- DEPSREL_TYPE_TRANSFORM,
- "Particle Object Visualization");
+ switch (part->ren_as) {
+ case PART_DRAW_OB:
+ if (part->dup_ob != NULL) {
+ /* Make sure object's relations are all built. */
+ build_object(part->dup_ob);
+ /* Build relation for the particle visualization. */
+ build_particles_visualization_object(object,
+ psys,
+ part->dup_ob);
+ }
+ break;
+ case PART_DRAW_GR:
+ if (part->dup_group != NULL) {
+ build_group(NULL, part->dup_group);
+ LISTBASE_FOREACH (GroupObject *, go, &part->dup_group->gobject) {
+ build_particles_visualization_object(object,
+ psys,
+ go->ob);
+ }
+ }
+ break;
}
}
@@ -1302,20 +1428,52 @@ void DepsgraphRelationBuilder::build_particles(Scene *scene, Object *ob)
* TODO(sergey): This relation should be altered once real granular update
* is implemented.
*/
- ComponentKey transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(transform_key,
- obdata_ubereval_key,
- DEPSREL_TYPE_GEOMETRY_EVAL,
- "Partcile Eval");
+ ComponentKey transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(transform_key, obdata_ubereval_key, "Partcile Eval");
/* pointcache */
// TODO...
}
+void DepsgraphRelationBuilder::build_particles_visualization_object(
+ Object *object,
+ ParticleSystem *psys,
+ Object *draw_object)
+{
+ OperationKey psys_key(&object->id,
+ DEG_NODE_TYPE_EVAL_PARTICLES,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
+ psys->name);
+ OperationKey obdata_ubereval_key(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ DEG_OPCODE_GEOMETRY_UBEREVAL);
+ ComponentKey dup_ob_key(&draw_object->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(dup_ob_key, psys_key, "Particle Object Visualization");
+ if (draw_object->type == OB_MBALL) {
+ ComponentKey dup_geometry_key(&draw_object->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(obdata_ubereval_key,
+ dup_geometry_key,
+ "Particle MBall Visualization");
+ }
+}
+
+void DepsgraphRelationBuilder::build_cloth(Object *object,
+ ModifierData * /*md*/)
+{
+ OperationKey cache_key(&object->id,
+ DEG_NODE_TYPE_CACHE,
+ DEG_OPCODE_GEOMETRY_CLOTH_MODIFIER);
+ /* Cache component affects on modifier. */
+ OperationKey modifier_key(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ DEG_OPCODE_GEOMETRY_UBEREVAL);
+ add_relation(cache_key, modifier_key, "Cloth Cache -> Cloth");
+}
+
/* Shapekeys */
void DepsgraphRelationBuilder::build_shapekeys(ID *obdata, Key *key)
{
- ComponentKey obdata_key(obdata, DEPSNODE_TYPE_GEOMETRY);
+ ComponentKey obdata_key(obdata, DEG_NODE_TYPE_GEOMETRY);
/* attach animdata to geometry */
build_animdata(&key->id);
@@ -1323,8 +1481,8 @@ void DepsgraphRelationBuilder::build_shapekeys(ID *obdata, Key *key)
if (key->adt) {
// TODO: this should really be handled in build_animdata, since many of these cases will need it
if (key->adt->action || key->adt->nla_tracks.first) {
- ComponentKey adt_key(&key->id, DEPSNODE_TYPE_ANIMATION);
- add_relation(adt_key, obdata_key, DEPSREL_TYPE_OPERATION, "Animation");
+ ComponentKey adt_key(&key->id, DEG_NODE_TYPE_ANIMATION);
+ add_relation(adt_key, obdata_key, "Animation");
}
/* NOTE: individual shapekey drivers are handled above already */
@@ -1332,8 +1490,8 @@ void DepsgraphRelationBuilder::build_shapekeys(ID *obdata, Key *key)
/* attach to geometry */
// XXX: aren't shapekeys now done as a pseudo-modifier on object?
- //ComponentKey key_key(&key->id, DEPSNODE_TYPE_GEOMETRY); // FIXME: this doesn't exist
- //add_relation(key_key, obdata_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Shapekeys");
+ //ComponentKey key_key(&key->id, DEG_NODE_TYPE_GEOMETRY); // FIXME: this doesn't exist
+ //add_relation(key_key, obdata_key, "Shapekeys");
}
/**
@@ -1356,86 +1514,58 @@ void DepsgraphRelationBuilder::build_shapekeys(ID *obdata, Key *key)
* re-evaluation of the individual instances of this geometry.
*/
// TODO: Materials and lighting should probably get their own component, instead of being lumped under geometry?
-void DepsgraphRelationBuilder::build_obdata_geom(Main *bmain, Scene *scene, Object *ob)
+void DepsgraphRelationBuilder::build_obdata_geom(Object *object)
{
- ID *obdata = (ID *)ob->data;
+ ID *obdata = (ID *)object->data;
/* Init operation of object-level geometry evaluation. */
- OperationKey geom_init_key(&ob->id, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Eval Init");
+ OperationKey geom_init_key(&object->id, DEG_NODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Eval Init");
/* get nodes for result of obdata's evaluation, and geometry evaluation on object */
- ComponentKey obdata_geom_key(obdata, DEPSNODE_TYPE_GEOMETRY);
- ComponentKey geom_key(&ob->id, DEPSNODE_TYPE_GEOMETRY);
+ ComponentKey obdata_geom_key(obdata, DEG_NODE_TYPE_GEOMETRY);
+ ComponentKey geom_key(&object->id, DEG_NODE_TYPE_GEOMETRY);
/* link components to each other */
- add_relation(obdata_geom_key, geom_key, DEPSREL_TYPE_DATABLOCK, "Object Geometry Base Data");
+ add_relation(obdata_geom_key, geom_key, "Object Geometry Base Data");
/* Modifiers */
- if (ob->modifiers.first) {
- OperationKey prev_mod_key;
-
- LINKLIST_FOREACH (ModifierData *, md, &ob->modifiers) {
+ if (object->modifiers.first != NULL) {
+ OperationKey obdata_ubereval_key(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ DEG_OPCODE_GEOMETRY_UBEREVAL);
+ ModifierUpdateDepsgraphContext ctx = {};
+ ctx.scene = scene_;
+ ctx.object = object;
+
+ LISTBASE_FOREACH (ModifierData *, md, &object->modifiers) {
const ModifierTypeInfo *mti = modifierType_getInfo((ModifierType)md->type);
- OperationKey mod_key(&ob->id, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_GEOMETRY_MODIFIER, md->name);
-
- if (md->prev) {
- /* Stack relation: modifier depends on previous modifier in the stack */
- add_relation(prev_mod_key, mod_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Modifier Stack");
- }
- else {
- /* Stack relation: first modifier depends on the geometry. */
- add_relation(geom_init_key, mod_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Modifier Stack");
- }
-
if (mti->updateDepsgraph) {
- DepsNodeHandle handle = create_node_handle(mod_key);
- mti->updateDepsgraph(
- md,
- bmain,
- scene,
- ob,
- reinterpret_cast< ::DepsNodeHandle* >(&handle));
+ DepsNodeHandle handle = create_node_handle(obdata_ubereval_key);
+ ctx.node = reinterpret_cast< ::DepsNodeHandle* >(&handle);
+ mti->updateDepsgraph(md, &ctx);
}
-
- if (BKE_object_modifier_use_time(ob, md)) {
+ if (BKE_object_modifier_use_time(object, md)) {
TimeSourceKey time_src_key;
- add_relation(time_src_key, mod_key, DEPSREL_TYPE_TIME, "Time Source");
-
- /* Hacky fix for T45633 (Animated modifiers aren't updated)
- *
- * This check works because BKE_object_modifier_use_time() tests
- * for either the modifier needing time, or that it is animated.
- */
- /* XXX: Remove this hack when these links are added as part of build_animdata() instead */
- if (modifier_dependsOnTime(md) == false && needs_animdata_node(&ob->id)) {
- ComponentKey animation_key(&ob->id, DEPSNODE_TYPE_ANIMATION);
- add_relation(animation_key, mod_key, DEPSREL_TYPE_OPERATION, "Modifier Animation");
- }
+ add_relation(time_src_key, obdata_ubereval_key, "Time Source");
+ }
+ if (md->type == eModifierType_Cloth) {
+ build_cloth(object, md);
}
-
- prev_mod_key = mod_key;
}
}
/* materials */
- if (ob->totcol != 0) {
- ComponentKey object_shading_key(&ob->id, DEPSNODE_TYPE_SHADING);
- for (int a = 1; a <= ob->totcol; a++) {
- Material *ma = give_current_material(ob, a);
+ if (object->totcol) {
+ for (int a = 1; a <= object->totcol; a++) {
+ Material *ma = give_current_material(object, a);
if (ma != NULL) {
build_material(ma);
- ComponentKey material_shading_key(&ma->id,
- DEPSNODE_TYPE_SHADING);
- add_relation(material_shading_key,
- object_shading_key,
- DEPSREL_TYPE_UPDATE,
- "Object Shading");
}
}
}
/* geometry collision */
- if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
+ if (ELEM(object->type, OB_MESH, OB_CURVE, OB_LATTICE)) {
// add geometry collider relations
}
@@ -1443,45 +1573,57 @@ void DepsgraphRelationBuilder::build_obdata_geom(Main *bmain, Scene *scene, Obje
*
* TODO(sergey): Get rid of this node.
*/
- if (ob->type != OB_ARMATURE) {
+ if (object->type != OB_ARMATURE) {
/* Armatures does no longer require uber node. */
- OperationKey obdata_ubereval_key(&ob->id, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_GEOMETRY_UBEREVAL);
- if (ob->modifiers.last) {
- ModifierData *md = (ModifierData *)ob->modifiers.last;
- OperationKey mod_key(&ob->id, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_GEOMETRY_MODIFIER, md->name);
- add_relation(mod_key, obdata_ubereval_key, DEPSREL_TYPE_OPERATION, "Object Geometry UberEval");
- }
- else {
- add_relation(geom_init_key, obdata_ubereval_key, DEPSREL_TYPE_OPERATION, "Object Geometry UberEval");
- }
+ OperationKey obdata_ubereval_key(&object->id, DEG_NODE_TYPE_GEOMETRY, DEG_OPCODE_GEOMETRY_UBEREVAL);
+ add_relation(geom_init_key, obdata_ubereval_key, "Object Geometry UberEval");
}
- if (obdata->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(obdata)) {
return;
}
- obdata->tag |= LIB_TAG_DOIT;
/* Link object data evaluation node to exit operation. */
- OperationKey obdata_geom_eval_key(obdata, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Geometry Eval");
- OperationKey obdata_geom_done_key(obdata, DEPSNODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Eval Done");
- add_relation(obdata_geom_eval_key, obdata_geom_done_key, DEPSREL_TYPE_DATABLOCK, "ObData Geom Eval Done");
+ OperationKey obdata_geom_eval_key(obdata, DEG_NODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Geometry Eval");
+ OperationKey obdata_geom_done_key(obdata, DEG_NODE_TYPE_GEOMETRY, DEG_OPCODE_PLACEHOLDER, "Eval Done");
+ add_relation(obdata_geom_eval_key, obdata_geom_done_key, "ObData Geom Eval Done");
/* type-specific node/links */
- switch (ob->type) {
+ switch (object->type) {
case OB_MESH:
+ /* NOTE: This is compatibility code to support particle systems
+ *
+ * for viewport being properly rendered in final render mode.
+ * This relation is similar to what dag_object_time_update_flags()
+ * was doing for mesh objects with particle system.
+ *
+ * Ideally we need to get rid of this relation.
+ */
+ if (object_particles_depends_on_time(object)) {
+ TimeSourceKey time_key;
+ OperationKey obdata_ubereval_key(&object->id,
+ DEG_NODE_TYPE_GEOMETRY,
+ DEG_OPCODE_GEOMETRY_UBEREVAL);
+ add_relation(time_key, obdata_ubereval_key, "Legacy particle time");
+ }
break;
case OB_MBALL:
{
- Object *mom = BKE_mball_basis_find(scene, ob);
-
+ Object *mom = BKE_mball_basis_find(scene_, object);
+ ComponentKey mom_geom_key(&mom->id, DEG_NODE_TYPE_GEOMETRY);
/* motherball - mom depends on children! */
- if (mom != ob) {
- /* non-motherball -> cannot be directly evaluated! */
- ComponentKey mom_key(&mom->id, DEPSNODE_TYPE_GEOMETRY);
- ComponentKey transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(geom_key, mom_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Metaball Motherball");
- add_relation(transform_key, mom_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Metaball Motherball");
+ if (mom == object) {
+ ComponentKey mom_transform_key(&mom->id,
+ DEG_NODE_TYPE_TRANSFORM);
+ add_relation(mom_transform_key,
+ mom_geom_key,
+ "Metaball Motherball Transform -> Geometry");
+ }
+ else {
+ ComponentKey transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(geom_key, mom_geom_key, "Metaball Motherball");
+ add_relation(transform_key, mom_geom_key, "Metaball Motherball");
}
break;
}
@@ -1494,20 +1636,20 @@ void DepsgraphRelationBuilder::build_obdata_geom(Main *bmain, Scene *scene, Obje
/* curve's dependencies */
// XXX: these needs geom data, but where is geom stored?
if (cu->bevobj) {
- ComponentKey bevob_key(&cu->bevobj->id, DEPSNODE_TYPE_GEOMETRY);
- build_object(bmain, scene, cu->bevobj);
- add_relation(bevob_key, geom_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Curve Bevel");
+ ComponentKey bevob_key(&cu->bevobj->id, DEG_NODE_TYPE_GEOMETRY);
+ build_object(cu->bevobj);
+ add_relation(bevob_key, geom_key, "Curve Bevel");
}
if (cu->taperobj) {
- ComponentKey taperob_key(&cu->taperobj->id, DEPSNODE_TYPE_GEOMETRY);
- build_object(bmain, scene, cu->taperobj);
- add_relation(taperob_key, geom_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Curve Taper");
+ ComponentKey taperob_key(&cu->taperobj->id, DEG_NODE_TYPE_GEOMETRY);
+ build_object(cu->taperobj);
+ add_relation(taperob_key, geom_key, "Curve Taper");
}
- if (ob->type == OB_FONT) {
+ if (object->type == OB_FONT) {
if (cu->textoncurve) {
- ComponentKey textoncurve_key(&cu->textoncurve->id, DEPSNODE_TYPE_GEOMETRY);
- build_object(bmain, scene, cu->textoncurve);
- add_relation(textoncurve_key, geom_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Text on Curve");
+ ComponentKey textoncurve_key(&cu->textoncurve->id, DEG_NODE_TYPE_GEOMETRY);
+ build_object(cu->textoncurve);
+ add_relation(textoncurve_key, geom_key, "Text on Curve");
}
}
break;
@@ -1525,180 +1667,140 @@ void DepsgraphRelationBuilder::build_obdata_geom(Main *bmain, Scene *scene, Obje
}
/* ShapeKeys */
- Key *key = BKE_key_from_object(ob);
+ Key *key = BKE_key_from_object(object);
if (key) {
build_shapekeys(obdata, key);
}
-
- if (needs_animdata_node(obdata)) {
- ComponentKey animation_key(obdata, DEPSNODE_TYPE_ANIMATION);
- ComponentKey parameters_key(obdata, DEPSNODE_TYPE_PARAMETERS);
- add_relation(animation_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "Geom Parameters");
- /* Evaluation usually depends on animation.
- * TODO(sergey): Need to re-hook it after granular update is implemented..
- */
- add_relation(animation_key, obdata_geom_eval_key, DEPSREL_TYPE_GEOMETRY_EVAL, "Animation");
- }
}
/* Cameras */
// TODO: Link scene-camera links in somehow...
-void DepsgraphRelationBuilder::build_camera(Object *ob)
+void DepsgraphRelationBuilder::build_camera(Object *object)
{
- Camera *cam = (Camera *)ob->data;
- ID *camera_id = &cam->id;
- if (camera_id->tag & LIB_TAG_DOIT) {
+ Camera *camera = (Camera *)object->data;
+ if (built_map_.checkIsBuiltAndTag(camera)) {
return;
}
- camera_id->tag |= LIB_TAG_DOIT;
-
- ComponentKey parameters_key(camera_id, DEPSNODE_TYPE_PARAMETERS);
-
- if (needs_animdata_node(camera_id)) {
- ComponentKey animation_key(camera_id, DEPSNODE_TYPE_ANIMATION);
- add_relation(animation_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "Camera Parameters");
- }
-
/* DOF */
- if (cam->dof_ob) {
- ComponentKey ob_param_key(&ob->id, DEPSNODE_TYPE_PARAMETERS);
- ComponentKey dof_ob_key(&cam->dof_ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(dof_ob_key, ob_param_key, DEPSREL_TYPE_TRANSFORM, "Camera DOF");
+ if (camera->dof_ob) {
+ ComponentKey ob_param_key(&object->id, DEG_NODE_TYPE_PARAMETERS);
+ ComponentKey dof_ob_key(&camera->dof_ob->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(dof_ob_key, ob_param_key, "Camera DOF");
}
}
/* Lamps */
-void DepsgraphRelationBuilder::build_lamp(Object *ob)
+void DepsgraphRelationBuilder::build_lamp(Object *object)
{
- Lamp *la = (Lamp *)ob->data;
- ID *lamp_id = &la->id;
- if (lamp_id->tag & LIB_TAG_DOIT) {
+ Lamp *lamp = (Lamp *)object->data;
+ if (built_map_.checkIsBuiltAndTag(lamp)) {
return;
}
- lamp_id->tag |= LIB_TAG_DOIT;
-
- ComponentKey parameters_key(lamp_id, DEPSNODE_TYPE_PARAMETERS);
-
- if (needs_animdata_node(lamp_id)) {
- ComponentKey animation_key(lamp_id, DEPSNODE_TYPE_ANIMATION);
- add_relation(animation_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "Lamp Parameters");
- }
-
/* lamp's nodetree */
- if (la->nodetree) {
- build_nodetree(la->nodetree);
- ComponentKey nodetree_key(&la->nodetree->id, DEPSNODE_TYPE_PARAMETERS);
- add_relation(nodetree_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "NTree->Lamp Parameters");
+ if (lamp->nodetree != NULL) {
+ build_nodetree(lamp->nodetree);
+ ComponentKey parameters_key(&lamp->id, DEG_NODE_TYPE_PARAMETERS);
+ ComponentKey nodetree_key(&lamp->nodetree->id, DEG_NODE_TYPE_PARAMETERS);
+ add_relation(nodetree_key, parameters_key, "NTree->Lamp Parameters");
}
-
/* textures */
- build_texture_stack(la->mtex);
+ build_texture_stack(lamp->mtex);
}
void DepsgraphRelationBuilder::build_nodetree(bNodeTree *ntree)
{
- if (!ntree)
+ if (ntree == NULL) {
return;
-
- ID *ntree_id = &ntree->id;
-
- build_animdata(ntree_id);
-
- OperationKey parameters_key(ntree_id,
- DEPSNODE_TYPE_PARAMETERS,
- DEG_OPCODE_PLACEHOLDER,
- "Parameters Eval");
-
+ }
+ if (built_map_.checkIsBuiltAndTag(ntree)) {
+ return;
+ }
+ build_animdata(&ntree->id);
+ OperationKey parameters_key(&ntree->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL);
/* nodetree's nodes... */
- LINKLIST_FOREACH (bNode *, bnode, &ntree->nodes) {
- if (bnode->id) {
- if (GS(bnode->id->name) == ID_MA) {
- build_material((Material *)bnode->id);
- }
- else if (bnode->type == ID_TE) {
- build_texture((Tex *)bnode->id);
- }
- else if (bnode->type == NODE_GROUP) {
- bNodeTree *group_ntree = (bNodeTree *)bnode->id;
- if ((group_ntree->id.tag & LIB_TAG_DOIT) == 0) {
- build_nodetree(group_ntree);
- group_ntree->id.tag |= LIB_TAG_DOIT;
- }
- OperationKey group_parameters_key(&group_ntree->id,
- DEPSNODE_TYPE_PARAMETERS,
- DEG_OPCODE_PLACEHOLDER,
- "Parameters Eval");
- add_relation(group_parameters_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "Group Node");
- }
+ LISTBASE_FOREACH (bNode *, bnode, &ntree->nodes) {
+ ID *id = bnode->id;
+ if (id == NULL) {
+ continue;
+ }
+ ID_Type id_type = GS(id->name);
+ if (id_type == ID_MA) {
+ build_material((Material *)bnode->id);
+ }
+ else if (id_type == ID_TE) {
+ build_texture((Tex *)bnode->id);
+ }
+ else if (id_type == ID_IM) {
+ /* nothing for now. */
+ }
+ else if (id_type == ID_OB) {
+ build_object((Object *)id);
+ }
+ else if (id_type == ID_SCE) {
+ /* Scenes are used by compositor trees, and handled by render
+ * pipeline. No need to build dependencies for them here.
+ */
+ }
+ else if (id_type == ID_TXT) {
+ /* Ignore script nodes. */
+ }
+ else if (bnode->type == NODE_GROUP) {
+ bNodeTree *group_ntree = (bNodeTree *)id;
+ build_nodetree(group_ntree);
+ OperationKey group_parameters_key(&group_ntree->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ add_relation(group_parameters_key, parameters_key, "Group Node");
+ }
+ else {
+ BLI_assert(!"Unknown ID type used for node");
}
- }
-
- if (needs_animdata_node(ntree_id)) {
- ComponentKey animation_key(ntree_id, DEPSNODE_TYPE_ANIMATION);
- add_relation(animation_key, parameters_key,
- DEPSREL_TYPE_COMPONENT_ORDER, "NTree Parameters");
}
}
/* Recursively build graph for material */
-void DepsgraphRelationBuilder::build_material(Material *ma)
+void DepsgraphRelationBuilder::build_material(Material *material)
{
- ID *ma_id = &ma->id;
- if (ma_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(material)) {
return;
}
- ma_id->tag |= LIB_TAG_DOIT;
-
/* animation */
- build_animdata(ma_id);
-
+ build_animdata(&material->id);
/* textures */
- build_texture_stack(ma->mtex);
-
+ build_texture_stack(material->mtex);
/* material's nodetree */
- if (ma->nodetree != NULL) {
- build_nodetree(ma->nodetree);
- OperationKey ntree_key(&ma->nodetree->id,
- DEPSNODE_TYPE_PARAMETERS,
- DEG_OPCODE_PLACEHOLDER,
- "Parameters Eval");
- OperationKey material_key(&ma->id,
- DEPSNODE_TYPE_SHADING,
+ if (material->nodetree != NULL) {
+ build_nodetree(material->nodetree);
+ OperationKey ntree_key(&material->nodetree->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL);
+ OperationKey material_key(&material->id,
+ DEG_NODE_TYPE_SHADING,
DEG_OPCODE_PLACEHOLDER,
"Material Update");
- add_relation(ntree_key, material_key,
- DEPSREL_TYPE_UPDATE, "Material's NTree");
+ add_relation(ntree_key, material_key, "Material's NTree");
}
}
/* Recursively build graph for texture */
-void DepsgraphRelationBuilder::build_texture(Tex *tex)
+void DepsgraphRelationBuilder::build_texture(Tex *texture)
{
- ID *tex_id = &tex->id;
- if (tex_id->tag & LIB_TAG_DOIT) {
+ if (built_map_.checkIsBuiltAndTag(texture)) {
return;
}
- tex_id->tag |= LIB_TAG_DOIT;
-
/* texture itself */
- build_animdata(tex_id);
-
+ build_animdata(&texture->id);
/* texture's nodetree */
- build_nodetree(tex->nodetree);
+ build_nodetree(texture->nodetree);
}
/* Texture-stack attached to some shading datablock */
void DepsgraphRelationBuilder::build_texture_stack(MTex **texture_stack)
{
- int i;
-
/* for now assume that all texture-stacks have same number of max items */
- for (i = 0; i < MAX_MTEX; i++) {
+ for (int i = 0; i < MAX_MTEX; i++) {
MTex *mtex = texture_stack[i];
if (mtex && mtex->tex)
build_texture(mtex->tex);
@@ -1719,24 +1821,26 @@ void DepsgraphRelationBuilder::build_gpencil(bGPdata *gpd)
// TODO: parent object (when that feature is implemented)
}
-bool DepsgraphRelationBuilder::needs_animdata_node(ID *id)
+void DepsgraphRelationBuilder::build_cachefile(CacheFile *cache_file)
{
- AnimData *adt = BKE_animdata_from_id(id);
- if (adt != NULL) {
- return (adt->action != NULL) || (adt->nla_tracks.first != NULL);
- }
- return false;
-}
-
-void DepsgraphRelationBuilder::build_cachefile(CacheFile *cache_file) {
/* Animation. */
build_animdata(&cache_file->id);
}
void DepsgraphRelationBuilder::build_mask(Mask *mask)
{
- /* Animation. */
- build_animdata(&mask->id);
+ ID *mask_id = &mask->id;
+ /* F-Curve animation. */
+ build_animdata(mask_id);
+ /* Own mask animation. */
+ OperationKey mask_animation_key(mask_id,
+ DEG_NODE_TYPE_ANIMATION,
+ DEG_OPCODE_MASK_ANIMATION);
+ TimeSourceKey time_src_key;
+ add_relation(time_src_key, mask_animation_key, "TimeSrc -> Mask Animation");
+ /* Final mask evaluation. */
+ ComponentKey parameters_key(mask_id, DEG_NODE_TYPE_PARAMETERS);
+ add_relation(mask_animation_key, parameters_key, "Mask Animation -> Mask Eval");
}
void DepsgraphRelationBuilder::build_movieclip(MovieClip *clip)
@@ -1745,4 +1849,43 @@ void DepsgraphRelationBuilder::build_movieclip(MovieClip *clip)
build_animdata(&clip->id);
}
+/* **** ID traversal callbacks functions **** */
+
+void DepsgraphRelationBuilder::modifier_walk(void *user_data,
+ struct Object * /*object*/,
+ struct ID **idpoin,
+ int /*cb_flag*/)
+{
+ BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
+ ID *id = *idpoin;
+ if (id == NULL) {
+ return;
+ }
+ switch (GS(id->name)) {
+ case ID_OB:
+ data->builder->build_object((Object *)id);
+ break;
+ case ID_TE:
+ data->builder->build_texture((Tex *)id);
+ break;
+ default:
+ /* pass */
+ break;
+ }
+}
+
+void DepsgraphRelationBuilder::constraint_walk(bConstraint * /*con*/,
+ ID **idpoin,
+ bool /*is_reference*/,
+ void *user_data)
+{
+ BuilderWalkUserData *data = (BuilderWalkUserData *)user_data;
+ if (*idpoin) {
+ ID *id = *idpoin;
+ if (GS(id->name) == ID_OB) {
+ data->builder->build_object((Object *)id);
+ }
+ }
+}
+
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations.h b/source/blender/depsgraph/intern/builder/deg_builder_relations.h
index 054e4103290..4a8e91f18db 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_relations.h
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations.h
@@ -31,6 +31,7 @@
#pragma once
#include <cstdio>
+#include <cstring>
#include "intern/depsgraph_types.h"
@@ -42,7 +43,9 @@
#include "BLI_utildefines.h"
#include "BLI_string.h"
+#include "intern/builder/deg_builder_map.h"
#include "intern/nodes/deg_node.h"
+#include "intern/nodes/deg_node_component.h"
#include "intern/nodes/deg_node_operation.h"
struct Base;
@@ -58,16 +61,17 @@ struct Main;
struct Mask;
struct Material;
struct MTex;
+struct ModifierData;
struct MovieClip;
struct bNodeTree;
struct Object;
struct bPoseChannel;
struct bConstraint;
+struct ParticleSystem;
struct Scene;
struct Tex;
struct World;
struct EffectorWeights;
-struct ParticleSystem;
struct PropertyRNA;
@@ -76,18 +80,14 @@ namespace DEG {
struct Depsgraph;
struct DepsNode;
struct DepsNodeHandle;
+struct DepsRelation;
struct RootDepsNode;
-struct SubgraphDepsNode;
struct IDDepsNode;
struct TimeSourceDepsNode;
struct ComponentDepsNode;
struct OperationDepsNode;
struct RootPChanMap;
-struct RootKey {
- RootKey();
-};
-
struct TimeSourceKey
{
TimeSourceKey();
@@ -169,56 +169,73 @@ struct RNAPathKey
struct DepsgraphRelationBuilder
{
- DepsgraphRelationBuilder(Depsgraph *graph);
+ DepsgraphRelationBuilder(Main *bmain, Depsgraph *graph);
- void begin_build(Main *bmain);
+ void begin_build();
template <typename KeyFrom, typename KeyTo>
- void add_relation(const KeyFrom& key_from,
- const KeyTo& key_to,
- eDepsRelation_Type type,
- const char *description);
+ DepsRelation *add_relation(const KeyFrom& key_from,
+ const KeyTo& key_to,
+ const char *description,
+ bool check_unique = false);
template <typename KeyTo>
- void add_relation(const TimeSourceKey& key_from,
- const KeyTo& key_to,
- eDepsRelation_Type type,
- const char *description);
+ DepsRelation *add_relation(const TimeSourceKey& key_from,
+ const KeyTo& key_to,
+ const char *description,
+ bool check_unique = false);
template <typename KeyType>
- void add_node_handle_relation(const KeyType& key_from,
- const DepsNodeHandle *handle,
- eDepsRelation_Type type,
- const char *description);
-
- void build_scene(Main *bmain, Scene *scene);
- void build_group(Main *bmain, Scene *scene, Object *object, Group *group);
- void build_object(Main *bmain, Scene *scene, Object *ob);
- void build_object_parent(Object *ob);
- void build_constraints(Scene *scene, ID *id,
+ DepsRelation *add_node_handle_relation(const KeyType& key_from,
+ const DepsNodeHandle *handle,
+ const char *description,
+ bool check_unique = false);
+
+ void build_scene(Scene *scene);
+ void build_group(Object *object, Group *group);
+ void build_object(Object *object);
+ void build_object_data(Object *object);
+ void build_object_parent(Object *object);
+ void build_constraints(ID *id,
eDepsNode_Type component_type,
const char *component_subdata,
ListBase *constraints,
RootPChanMap *root_map);
void build_animdata(ID *id);
+ void build_animdata_curves(ID *id);
+ void build_animdata_curves_targets(ID *id,
+ ComponentKey &adt_key,
+ OperationDepsNode *operation_from,
+ ListBase *curves);
+ void build_animdata_nlastrip_targets(ID *id,
+ ComponentKey &adt_key,
+ OperationDepsNode *operation_from,
+ ListBase *strips);
+ void build_animdata_drivers(ID *id);
void build_driver(ID *id, FCurve *fcurve);
+ void build_driver_data(ID *id, FCurve *fcurve);
+ void build_driver_variables(ID *id, FCurve *fcurve);
void build_world(World *world);
void build_rigidbody(Scene *scene);
- void build_particles(Scene *scene, Object *ob);
- void build_ik_pose(Object *ob,
+ void build_particles(Object *object);
+ void build_particles_visualization_object(Object *object,
+ ParticleSystem *psys,
+ Object *draw_object);
+ void build_cloth(Object *object, ModifierData *md);
+ void build_ik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con,
RootPChanMap *root_map);
- void build_splineik_pose(Object *ob,
+ void build_splineik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con,
RootPChanMap *root_map);
- void build_rig(Scene *scene, Object *ob);
- void build_proxy_rig(Object *ob);
+ void build_rig(Object *object);
+ void build_proxy_rig(Object *object);
void build_shapekeys(ID *obdata, Key *key);
- void build_obdata_geom(Main *bmain, Scene *scene, Object *ob);
- void build_camera(Object *ob);
- void build_lamp(Object *ob);
+ void build_obdata_geom(Object *object);
+ void build_camera(Object *object);
+ void build_lamp(Object *object);
void build_nodetree(bNodeTree *ntree);
void build_material(Material *ma);
void build_texture(Tex *tex);
@@ -229,44 +246,106 @@ struct DepsgraphRelationBuilder
void build_mask(Mask *mask);
void build_movieclip(MovieClip *clip);
- void add_collision_relations(const OperationKey &key, Scene *scene, Object *ob, Group *group, int layer, bool dupli, const char *name);
- void add_forcefield_relations(const OperationKey &key, Scene *scene, Object *ob, ParticleSystem *psys, EffectorWeights *eff, bool add_absorption, const char *name);
+ void add_collision_relations(const OperationKey &key,
+ Scene *scene,
+ Object *object,
+ Group *group,
+ int layer,
+ bool dupli,
+ const char *name);
+ void add_forcefield_relations(const OperationKey &key,
+ Scene *scene,
+ Object *object,
+ ParticleSystem *psys,
+ EffectorWeights *eff,
+ bool add_absorption,
+ const char *name);
template <typename KeyType>
OperationDepsNode *find_operation_node(const KeyType &key);
+ Depsgraph *getGraph();
+
protected:
- RootDepsNode *find_node(const RootKey &key) const;
- TimeSourceDepsNode *find_node(const TimeSourceKey &key) const;
- ComponentDepsNode *find_node(const ComponentKey &key) const;
+ TimeSourceDepsNode *get_node(const TimeSourceKey &key) const;
+ ComponentDepsNode *get_node(const ComponentKey &key) const;
+ OperationDepsNode *get_node(const OperationKey &key) const;
+ DepsNode *get_node(const RNAPathKey &key) const;
+
OperationDepsNode *find_node(const OperationKey &key) const;
- DepsNode *find_node(const RNAPathKey &key) const;
- OperationDepsNode *has_node(const OperationKey &key) const;
+ bool has_node(const OperationKey &key) const;
- void add_time_relation(TimeSourceDepsNode *timesrc,
- DepsNode *node_to,
- const char *description);
- void add_operation_relation(OperationDepsNode *node_from,
- OperationDepsNode *node_to,
- eDepsRelation_Type type,
- const char *description);
+ DepsRelation *add_time_relation(TimeSourceDepsNode *timesrc,
+ DepsNode *node_to,
+ const char *description,
+ bool check_unique = false);
+ DepsRelation *add_operation_relation(OperationDepsNode *node_from,
+ OperationDepsNode *node_to,
+ const char *description,
+ bool check_unique = false);
template <typename KeyType>
DepsNodeHandle create_node_handle(const KeyType& key,
const char *default_name = "");
- bool needs_animdata_node(ID *id);
+ /* TODO(sergey): All those is_same* functions are to be generalized. */
+
+ /* Check whether two keys correponds to the same bone from same armature.
+ *
+ * This is used by drivers relations builder to avoid possible fake
+ * dependency cycle when one bone property drives another property of the
+ * same bone.
+ */
+ template <typename KeyFrom, typename KeyTo>
+ bool is_same_bone_dependency(const KeyFrom& key_from, const KeyTo& key_to);
+
+ /* Similar to above, but used to check whether driver is using node from
+ * the same node tree as a driver variable.
+ */
+ template <typename KeyFrom, typename KeyTo>
+ bool is_same_nodetree_node_dependency(const KeyFrom& key_from,
+ const KeyTo& key_to);
+
+ /* Similar to above, but used to check whether driver is using key from
+ * the same key datablock as a driver variable.
+ */
+ template <typename KeyFrom, typename KeyTo>
+ bool is_same_shapekey_dependency(const KeyFrom& key_from,
+ const KeyTo& key_to);
private:
- Depsgraph *m_graph;
+ struct BuilderWalkUserData {
+ DepsgraphRelationBuilder *builder;
+ };
+
+ static void modifier_walk(void *user_data,
+ struct Object *object,
+ struct ID **idpoin,
+ int cb_flag);
+
+ static void constraint_walk(bConstraint *con,
+ ID **idpoin,
+ bool is_reference,
+ void *user_data);
+
+ /* State which never changes, same for the whole builder time. */
+ Main *bmain_;
+ Depsgraph *graph_;
+
+ /* State which demotes currently built entities. */
+ Scene *scene_;
+
+ BuilderMap built_map_;
};
struct DepsNodeHandle
{
- DepsNodeHandle(DepsgraphRelationBuilder *builder, OperationDepsNode *node, const char *default_name = "") :
- builder(builder),
- node(node),
- default_name(default_name)
+ DepsNodeHandle(DepsgraphRelationBuilder *builder,
+ OperationDepsNode *node,
+ const char *default_name = "")
+ : builder(builder),
+ node(node),
+ default_name(default_name)
{
BLI_assert(node != NULL);
}
@@ -276,100 +355,7 @@ struct DepsNodeHandle
const char *default_name;
};
-/* Utilities for Builders ----------------------------------------------------- */
-
-template <typename KeyType>
-OperationDepsNode *DepsgraphRelationBuilder::find_operation_node(const KeyType& key)
-{
- DepsNode *node = find_node(key);
- return node != NULL ? node->get_exit_operation() : NULL;
-}
-
-template <typename KeyFrom, typename KeyTo>
-void DepsgraphRelationBuilder::add_relation(const KeyFrom &key_from,
- const KeyTo &key_to,
- eDepsRelation_Type type,
- const char *description)
-{
- DepsNode *node_from = find_node(key_from);
- DepsNode *node_to = find_node(key_to);
- OperationDepsNode *op_from = node_from ? node_from->get_exit_operation() : NULL;
- OperationDepsNode *op_to = node_to ? node_to->get_entry_operation() : NULL;
- if (op_from && op_to) {
- add_operation_relation(op_from, op_to, type, description);
- }
- else {
- if (!op_from) {
- /* XXX TODO handle as error or report if needed */
- node_from = find_node(key_from);
- fprintf(stderr, "add_relation(%d, %s) - Could not find op_from (%s)\n",
- type, description, key_from.identifier().c_str());
- }
- else {
- fprintf(stderr, "add_relation(%d, %s) - Failed, but op_from (%s) was ok\n",
- type, description, key_from.identifier().c_str());
- }
- if (!op_to) {
- /* XXX TODO handle as error or report if needed */
- fprintf(stderr, "add_relation(%d, %s) - Could not find op_to (%s)\n",
- type, description, key_to.identifier().c_str());
- }
- else {
- fprintf(stderr, "add_relation(%d, %s) - Failed, but op_to (%s) was ok\n",
- type, description, key_to.identifier().c_str());
- }
- }
-}
-
-template <typename KeyTo>
-void DepsgraphRelationBuilder::add_relation(const TimeSourceKey &key_from,
- const KeyTo &key_to,
- eDepsRelation_Type type,
- const char *description)
-{
- (void)type; /* Ignored in release builds. */
- BLI_assert(type == DEPSREL_TYPE_TIME);
- TimeSourceDepsNode *time_from = find_node(key_from);
- DepsNode *node_to = find_node(key_to);
- OperationDepsNode *op_to = node_to ? node_to->get_entry_operation() : NULL;
- if (time_from && op_to) {
- add_time_relation(time_from, op_to, description);
- }
- else {
- }
-}
-
-template <typename KeyType>
-void DepsgraphRelationBuilder::add_node_handle_relation(
- const KeyType &key_from,
- const DepsNodeHandle *handle,
- eDepsRelation_Type type,
- const char *description)
-{
- DepsNode *node_from = find_node(key_from);
- OperationDepsNode *op_from = node_from ? node_from->get_exit_operation() : NULL;
- OperationDepsNode *op_to = handle->node->get_entry_operation();
- if (op_from && op_to) {
- add_operation_relation(op_from, op_to, type, description);
- }
- else {
- if (!op_from) {
- fprintf(stderr, "add_node_handle_relation(%d, %s) - Could not find op_from (%s)\n",
- type, description, key_from.identifier().c_str());
- }
- if (!op_to) {
- fprintf(stderr, "add_node_handle_relation(%d, %s) - Could not find op_to (%s)\n",
- type, description, key_from.identifier().c_str());
- }
- }
-}
+} // namespace DEG
-template <typename KeyType>
-DepsNodeHandle DepsgraphRelationBuilder::create_node_handle(
- const KeyType &key,
- const char *default_name)
-{
- return DepsNodeHandle(this, find_node(key), default_name);
-}
-} // namespace DEG
+#include "intern/builder/deg_builder_relations_impl.h"
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations_impl.h b/source/blender/depsgraph/intern/builder/deg_builder_relations_impl.h
new file mode 100644
index 00000000000..570227601db
--- /dev/null
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations_impl.h
@@ -0,0 +1,230 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2013 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Lukas Toenne
+ * Contributor(s): Sergey SHarybin
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/builder/deg_builder_relations_impl.h
+ * \ingroup depsgraph
+ */
+
+#pragma once
+
+#include "intern/nodes/deg_node_id.h"
+
+extern "C" {
+#include "DNA_ID.h"
+}
+
+namespace DEG {
+
+template <typename KeyType>
+OperationDepsNode *DepsgraphRelationBuilder::find_operation_node(const KeyType& key)
+{
+ DepsNode *node = get_node(key);
+ return node != NULL ? node->get_exit_operation() : NULL;
+}
+
+template <typename KeyFrom, typename KeyTo>
+DepsRelation *DepsgraphRelationBuilder::add_relation(const KeyFrom &key_from,
+ const KeyTo &key_to,
+ const char *description,
+ bool check_unique)
+{
+ DepsNode *node_from = get_node(key_from);
+ DepsNode *node_to = get_node(key_to);
+ OperationDepsNode *op_from = node_from ? node_from->get_exit_operation() : NULL;
+ OperationDepsNode *op_to = node_to ? node_to->get_entry_operation() : NULL;
+ if (op_from && op_to) {
+ return add_operation_relation(op_from, op_to, description, check_unique);
+ }
+ else {
+ if (!op_from) {
+ /* XXX TODO handle as error or report if needed */
+ fprintf(stderr, "add_relation(%s) - Could not find op_from (%s)\n",
+ description, key_from.identifier().c_str());
+ }
+ else {
+ fprintf(stderr, "add_relation(%s) - Failed, but op_from (%s) was ok\n",
+ description, key_from.identifier().c_str());
+ }
+ if (!op_to) {
+ /* XXX TODO handle as error or report if needed */
+ fprintf(stderr, "add_relation(%s) - Could not find op_to (%s)\n",
+ description, key_to.identifier().c_str());
+ }
+ else {
+ fprintf(stderr, "add_relation(%s) - Failed, but op_to (%s) was ok\n",
+ description, key_to.identifier().c_str());
+ }
+ }
+ return NULL;
+}
+
+template <typename KeyTo>
+DepsRelation *DepsgraphRelationBuilder::add_relation(
+ const TimeSourceKey &key_from,
+ const KeyTo &key_to,
+ const char *description,
+ bool check_unique)
+{
+ TimeSourceDepsNode *time_from = get_node(key_from);
+ DepsNode *node_to = get_node(key_to);
+ OperationDepsNode *op_to = node_to ? node_to->get_entry_operation() : NULL;
+ if (time_from != NULL && op_to != NULL) {
+ return add_time_relation(time_from, op_to, description, check_unique);
+ }
+ return NULL;
+}
+
+template <typename KeyType>
+DepsRelation *DepsgraphRelationBuilder::add_node_handle_relation(
+ const KeyType &key_from,
+ const DepsNodeHandle *handle,
+ const char *description,
+ bool check_unique)
+{
+ DepsNode *node_from = get_node(key_from);
+ OperationDepsNode *op_from = node_from ? node_from->get_exit_operation() : NULL;
+ OperationDepsNode *op_to = handle->node->get_entry_operation();
+ if (op_from != NULL && op_to != NULL) {
+ return add_operation_relation(op_from, op_to, description, check_unique);
+ }
+ else {
+ if (!op_from) {
+ fprintf(stderr, "add_node_handle_relation(%s) - Could not find op_from (%s)\n",
+ description, key_from.identifier().c_str());
+ }
+ if (!op_to) {
+ fprintf(stderr, "add_node_handle_relation(%s) - Could not find op_to (%s)\n",
+ description, key_from.identifier().c_str());
+ }
+ }
+ return NULL;
+}
+
+template <typename KeyType>
+DepsNodeHandle DepsgraphRelationBuilder::create_node_handle(
+ const KeyType &key,
+ const char *default_name)
+{
+ return DepsNodeHandle(this, get_node(key), default_name);
+}
+
+/* Rig compatibility: we check if bone is using local transform as a variable
+ * for driver on itself and ignore those relations to avoid "false-positive"
+ * dependency cycles.
+ */
+template <typename KeyFrom, typename KeyTo>
+bool DepsgraphRelationBuilder::is_same_bone_dependency(const KeyFrom& key_from,
+ const KeyTo& key_to)
+{
+ /* Get operations for requested keys. */
+ DepsNode *node_from = get_node(key_from);
+ DepsNode *node_to = get_node(key_to);
+ if (node_from == NULL || node_to == NULL) {
+ return false;
+ }
+ OperationDepsNode *op_from = node_from->get_exit_operation();
+ OperationDepsNode *op_to = node_to->get_entry_operation();
+ if (op_from == NULL || op_to == NULL) {
+ return false;
+ }
+ /* Different armatures, bone can't be the same. */
+ if (op_from->owner->owner != op_to->owner->owner) {
+ return false;
+ }
+ /* We are only interested in relations like BONE_DONE -> BONE_LOCAL... */
+ if (!(op_from->opcode == DEG_OPCODE_BONE_DONE &&
+ op_to->opcode == DEG_OPCODE_BONE_LOCAL))
+ {
+ return false;
+ }
+ /* ... BUT, we also need to check if it's same bone. */
+ if (!STREQ(op_from->owner->name, op_to->owner->name)) {
+ return false;
+ }
+ return true;
+}
+
+template <typename KeyFrom, typename KeyTo>
+bool DepsgraphRelationBuilder::is_same_nodetree_node_dependency(
+ const KeyFrom& key_from,
+ const KeyTo& key_to)
+{
+ /* Get operations for requested keys. */
+ DepsNode *node_from = get_node(key_from);
+ DepsNode *node_to = get_node(key_to);
+ if (node_from == NULL || node_to == NULL) {
+ return false;
+ }
+ OperationDepsNode *op_from = node_from->get_exit_operation();
+ OperationDepsNode *op_to = node_to->get_entry_operation();
+ if (op_from == NULL || op_to == NULL) {
+ return false;
+ }
+ /* Check if this is actually a node tree. */
+ if (GS(op_from->owner->owner->id->name) != ID_NT) {
+ return false;
+ }
+ /* Different node trees. */
+ if (op_from->owner->owner != op_to->owner->owner) {
+ return false;
+ }
+ /* We are only interested in relations like BONE_DONE -> BONE_LOCAL... */
+ if (!(op_from->opcode == DEG_OPCODE_PARAMETERS_EVAL &&
+ op_to->opcode == DEG_OPCODE_PARAMETERS_EVAL))
+ {
+ return false;
+ }
+ return true;
+}
+
+template <typename KeyFrom, typename KeyTo>
+bool DepsgraphRelationBuilder::is_same_shapekey_dependency(
+ const KeyFrom& key_from,
+ const KeyTo& key_to)
+{
+ /* Get operations for requested keys. */
+ DepsNode *node_from = get_node(key_from);
+ DepsNode *node_to = get_node(key_to);
+ if (node_from == NULL || node_to == NULL) {
+ return false;
+ }
+ OperationDepsNode *op_from = node_from->get_exit_operation();
+ OperationDepsNode *op_to = node_to->get_entry_operation();
+ if (op_from == NULL || op_to == NULL) {
+ return false;
+ }
+ /* Check if this is actually a shape key datablock. */
+ if (GS(op_from->owner->owner->id->name) != ID_KE) {
+ return false;
+ }
+ /* Different key data blocks. */
+ if (op_from->owner->owner != op_to->owner->owner) {
+ return false;
+ }
+ return true;
+}
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations_keys.cc b/source/blender/depsgraph/intern/builder/deg_builder_relations_keys.cc
index feae8bca303..4b8e4faae3f 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_relations_keys.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations_keys.cc
@@ -35,13 +35,6 @@
namespace DEG {
/////////////////////////////////////////
-// Root.
-
-RootKey::RootKey()
-{
-}
-
-/////////////////////////////////////////
// Time source.
TimeSourceKey::TimeSourceKey()
@@ -64,7 +57,7 @@ string TimeSourceKey::identifier() const
ComponentKey::ComponentKey()
: id(NULL),
- type(DEPSNODE_TYPE_UNDEFINED),
+ type(DEG_NODE_TYPE_UNDEFINED),
name("")
{
}
@@ -90,7 +83,7 @@ string ComponentKey::identifier() const
OperationKey::OperationKey()
: id(NULL),
- component_type(DEPSNODE_TYPE_UNDEFINED),
+ component_type(DEG_NODE_TYPE_UNDEFINED),
component_name(""),
opcode(DEG_OPCODE_OPERATION),
name(""),
@@ -200,6 +193,20 @@ RNAPathKey::RNAPathKey(ID *id, const PointerRNA &ptr, PropertyRNA *prop)
{
}
+RNAPathKey::RNAPathKey(ID *id, const char *path)
+ : id(id)
+{
+ /* create ID pointer for root of path lookup */
+ PointerRNA id_ptr;
+ RNA_id_pointer_create(id, &id_ptr);
+ /* try to resolve path... */
+ int index;
+ if (!RNA_path_resolve_full(&id_ptr, path, &this->ptr, &this->prop, &index)) {
+ this->ptr = PointerRNA_NULL;
+ this->prop = NULL;
+ }
+}
+
string RNAPathKey::identifier() const
{
const char *id_name = (id) ? id->name : "<No ID>";
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations_rig.cc b/source/blender/depsgraph/intern/builder/deg_builder_relations_rig.cc
index 2b4c000f483..2eee1671795 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_relations_rig.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations_rig.cc
@@ -38,10 +38,10 @@
#include "MEM_guardedalloc.h"
-extern "C" {
-#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLI_blenlib.h"
+extern "C" {
#include "DNA_action_types.h"
#include "DNA_anim_types.h"
#include "DNA_armature_types.h"
@@ -51,10 +51,11 @@ extern "C" {
#include "BKE_action.h"
#include "BKE_armature.h"
+#include "BKE_constraint.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
#include "intern/builder/deg_builder.h"
#include "intern/builder/deg_builder_pchanmap.h"
@@ -71,7 +72,7 @@ extern "C" {
namespace DEG {
/* IK Solver Eval Steps */
-void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
+void DepsgraphRelationBuilder::build_ik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con,
RootPChanMap *root_map)
@@ -83,7 +84,18 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
* - see notes on direction of rel below...
*/
bPoseChannel *rootchan = BKE_armature_ik_solver_find_root(pchan, data);
- OperationKey solver_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, rootchan->name, DEG_OPCODE_POSE_IK_SOLVER);
+ if (rootchan == NULL) {
+ return;
+ }
+ OperationKey pchan_local_key(&object->id, DEG_NODE_TYPE_BONE,
+ pchan->name, DEG_OPCODE_BONE_LOCAL);
+ OperationKey init_ik_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_INIT_IK);
+ OperationKey solver_key(&object->id, DEG_NODE_TYPE_EVAL_POSE,
+ rootchan->name,
+ DEG_OPCODE_POSE_IK_SOLVER);
+
+ add_relation(pchan_local_key, init_ik_key, "IK Constraint -> Init IK Tree");
+ add_relation(init_ik_key, solver_key, "Init IK -> IK Solver");
/* IK target */
// XXX: this should get handled as part of the constraint code
@@ -96,25 +108,25 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
* testing IK solver.
*/
// FIXME: geometry targets...
- ComponentKey pose_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE);
+ ComponentKey pose_key(&object->id, DEG_NODE_TYPE_EVAL_POSE);
if ((data->tar->type == OB_ARMATURE) && (data->subtarget[0])) {
/* TODO(sergey): This is only for until granular update stores intermediate result. */
- if (data->tar != ob) {
+ if (data->tar != object) {
/* different armature - can just read the results */
- ComponentKey target_key(&data->tar->id, DEPSNODE_TYPE_BONE, data->subtarget);
- add_relation(target_key, pose_key, DEPSREL_TYPE_TRANSFORM, con->name);
+ ComponentKey target_key(&data->tar->id, DEG_NODE_TYPE_BONE, data->subtarget);
+ add_relation(target_key, pose_key, con->name);
}
else {
/* same armature - we'll use the ready state only, just in case this bone is in the chain we're solving */
- OperationKey target_key(&data->tar->id, DEPSNODE_TYPE_BONE, data->subtarget, DEG_OPCODE_BONE_DONE);
- add_relation(target_key, solver_key, DEPSREL_TYPE_TRANSFORM, con->name);
+ OperationKey target_key(&data->tar->id, DEG_NODE_TYPE_BONE, data->subtarget, DEG_OPCODE_BONE_DONE);
+ add_relation(target_key, solver_key, con->name);
}
}
else if (ELEM(data->tar->type, OB_MESH, OB_LATTICE) && (data->subtarget[0])) {
/* vertex group target */
/* NOTE: for now, we don't need to represent vertex groups separately... */
- ComponentKey target_key(&data->tar->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(target_key, solver_key, DEPSREL_TYPE_GEOMETRY_EVAL, con->name);
+ ComponentKey target_key(&data->tar->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(target_key, solver_key, con->name);
if (data->tar->type == OB_MESH) {
OperationDepsNode *node2 = find_operation_node(target_key);
@@ -125,11 +137,11 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
}
else {
/* Standard Object Target */
- ComponentKey target_key(&data->tar->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(target_key, pose_key, DEPSREL_TYPE_TRANSFORM, con->name);
+ ComponentKey target_key(&data->tar->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(target_key, pose_key, con->name);
}
- if ((data->tar == ob) && (data->subtarget[0])) {
+ if ((data->tar == object) && (data->subtarget[0])) {
/* Prevent target's constraints from linking to anything from same
* chain that it controls.
*/
@@ -142,14 +154,14 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
if (data->poletar != NULL) {
if ((data->poletar->type == OB_ARMATURE) && (data->polesubtarget[0])) {
// XXX: same armature issues - ready vs done?
- ComponentKey target_key(&data->poletar->id, DEPSNODE_TYPE_BONE, data->polesubtarget);
- add_relation(target_key, solver_key, DEPSREL_TYPE_TRANSFORM, con->name);
+ ComponentKey target_key(&data->poletar->id, DEG_NODE_TYPE_BONE, data->polesubtarget);
+ add_relation(target_key, solver_key, con->name);
}
else if (ELEM(data->poletar->type, OB_MESH, OB_LATTICE) && (data->polesubtarget[0])) {
/* vertex group target */
/* NOTE: for now, we don't need to represent vertex groups separately... */
- ComponentKey target_key(&data->poletar->id, DEPSNODE_TYPE_GEOMETRY);
- add_relation(target_key, solver_key, DEPSREL_TYPE_GEOMETRY_EVAL, con->name);
+ ComponentKey target_key(&data->poletar->id, DEG_NODE_TYPE_GEOMETRY);
+ add_relation(target_key, solver_key, con->name);
if (data->poletar->type == OB_MESH) {
OperationDepsNode *node2 = find_operation_node(target_key);
@@ -159,30 +171,25 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
}
}
else {
- ComponentKey target_key(&data->poletar->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(target_key, solver_key, DEPSREL_TYPE_TRANSFORM, con->name);
+ ComponentKey target_key(&data->poletar->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(target_key, solver_key, con->name);
}
}
- DEG_DEBUG_PRINTF("\nStarting IK Build: pchan = %s, target = (%s, %s), segcount = %d\n",
+ DEG_DEBUG_PRINTF(BUILD, "\nStarting IK Build: pchan = %s, target = (%s, %s), segcount = %d\n",
pchan->name, data->tar->id.name, data->subtarget, data->rootbone);
bPoseChannel *parchan = pchan;
/* exclude tip from chain? */
if (!(data->flag & CONSTRAINT_IK_TIP)) {
- OperationKey tip_transforms_key(&ob->id, DEPSNODE_TYPE_BONE,
- parchan->name, DEG_OPCODE_BONE_LOCAL);
- add_relation(solver_key, tip_transforms_key,
- DEPSREL_TYPE_TRANSFORM, "IK Solver Result");
parchan = pchan->parent;
}
root_map->add_bone(parchan->name, rootchan->name);
- OperationKey parchan_transforms_key(&ob->id, DEPSNODE_TYPE_BONE,
+ OperationKey parchan_transforms_key(&object->id, DEG_NODE_TYPE_BONE,
parchan->name, DEG_OPCODE_BONE_READY);
- add_relation(parchan_transforms_key, solver_key,
- DEPSREL_TYPE_TRANSFORM, "IK Solver Owner");
+ add_relation(parchan_transforms_key, solver_key, "IK Solver Owner");
/* Walk to the chain's root */
//size_t segcount = 0;
@@ -196,15 +203,15 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
* grab the result with IK solver results...
*/
if (parchan != pchan) {
- OperationKey parent_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_READY);
- add_relation(parent_key, solver_key, DEPSREL_TYPE_TRANSFORM, "IK Chain Parent");
+ OperationKey parent_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_READY);
+ add_relation(parent_key, solver_key, "IK Chain Parent");
- OperationKey done_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(solver_key, done_key, DEPSREL_TYPE_TRANSFORM, "IK Chain Result");
+ OperationKey done_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
+ add_relation(solver_key, done_key, "IK Chain Result");
}
else {
- OperationKey final_transforms_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(solver_key, final_transforms_key, DEPSREL_TYPE_TRANSFORM, "IK Solver Result");
+ OperationKey final_transforms_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
+ add_relation(solver_key, final_transforms_key, "IK Solver Result");
}
parchan->flag |= POSE_DONE;
@@ -212,33 +219,33 @@ void DepsgraphRelationBuilder::build_ik_pose(Object *ob,
root_map->add_bone(parchan->name, rootchan->name);
/* continue up chain, until we reach target number of items... */
- DEG_DEBUG_PRINTF(" %d = %s\n", segcount, parchan->name);
+ DEG_DEBUG_PRINTF(BUILD, " %d = %s\n", segcount, parchan->name);
segcount++;
if ((segcount == data->rootbone) || (segcount > 255)) break; /* 255 is weak */
parchan = parchan->parent;
}
- OperationKey flush_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
- add_relation(solver_key, flush_key, DEPSREL_TYPE_OPERATION, "PoseEval Result-Bone Link");
+ OperationKey flush_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
+ add_relation(solver_key, flush_key, "PoseEval Result-Bone Link");
}
/* Spline IK Eval Steps */
-void DepsgraphRelationBuilder::build_splineik_pose(Object *ob,
+void DepsgraphRelationBuilder::build_splineik_pose(Object *object,
bPoseChannel *pchan,
bConstraint *con,
RootPChanMap *root_map)
{
bSplineIKConstraint *data = (bSplineIKConstraint *)con->data;
bPoseChannel *rootchan = BKE_armature_splineik_solver_find_root(pchan, data);
- OperationKey transforms_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_READY);
- OperationKey solver_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, rootchan->name, DEG_OPCODE_POSE_SPLINE_IK_SOLVER);
+ OperationKey transforms_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_READY);
+ OperationKey solver_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, rootchan->name, DEG_OPCODE_POSE_SPLINE_IK_SOLVER);
/* attach owner to IK Solver too
* - assume that owner is always part of chain
* - see notes on direction of rel below...
*/
- add_relation(transforms_key, solver_key, DEPSREL_TYPE_TRANSFORM, "Spline IK Solver Owner");
+ add_relation(transforms_key, solver_key, "Spline IK Solver Owner");
/* attach path dependency to solver */
if (data->tar) {
@@ -247,14 +254,14 @@ void DepsgraphRelationBuilder::build_splineik_pose(Object *ob,
* See IK pose for a bit more information.
*/
// TODO: the bigggest point here is that we need the curve PATH and not just the general geometry...
- ComponentKey target_key(&data->tar->id, DEPSNODE_TYPE_GEOMETRY);
- ComponentKey pose_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE);
- add_relation(target_key, pose_key, DEPSREL_TYPE_TRANSFORM, "[Curve.Path -> Spline IK] DepsRel");
+ ComponentKey target_key(&data->tar->id, DEG_NODE_TYPE_GEOMETRY);
+ ComponentKey pose_key(&object->id, DEG_NODE_TYPE_EVAL_POSE);
+ add_relation(target_key, pose_key, "Curve.Path -> Spline IK");
}
pchan->flag |= POSE_DONE;
- OperationKey final_transforms_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(solver_key, final_transforms_key, DEPSREL_TYPE_TRANSFORM, "Spline IK Result");
+ OperationKey final_transforms_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_DONE);
+ add_relation(solver_key, final_transforms_key, "Spline IK Result");
root_map->add_bone(pchan->name, rootchan->name);
@@ -270,16 +277,16 @@ void DepsgraphRelationBuilder::build_splineik_pose(Object *ob,
* grab the result with IK solver results...
*/
if (parchan != pchan) {
- OperationKey parent_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_READY);
- add_relation(parent_key, solver_key, DEPSREL_TYPE_TRANSFORM, "Spline IK Solver Update");
+ OperationKey parent_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_READY);
+ add_relation(parent_key, solver_key, "Spline IK Solver Update");
- OperationKey done_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(solver_key, done_key, DEPSREL_TYPE_TRANSFORM, "IK Chain Result");
+ OperationKey done_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
+ add_relation(solver_key, done_key, "IK Chain Result");
}
parchan->flag |= POSE_DONE;
- OperationKey final_transforms_key(&ob->id, DEPSNODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(solver_key, final_transforms_key, DEPSREL_TYPE_TRANSFORM, "Spline IK Solver Result");
+ OperationKey final_transforms_key(&object->id, DEG_NODE_TYPE_BONE, parchan->name, DEG_OPCODE_BONE_DONE);
+ add_relation(solver_key, final_transforms_key, "Spline IK Solver Result");
root_map->add_bone(parchan->name, rootchan->name);
@@ -288,35 +295,32 @@ void DepsgraphRelationBuilder::build_splineik_pose(Object *ob,
if ((segcount == data->chainlen) || (segcount > 255)) break; /* 255 is weak */
}
- OperationKey flush_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
- add_relation(solver_key, flush_key, DEPSREL_TYPE_OPERATION, "PoseEval Result-Bone Link");
+ OperationKey flush_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
+ add_relation(solver_key, flush_key, "PoseEval Result-Bone Link");
}
/* Pose/Armature Bones Graph */
-void DepsgraphRelationBuilder::build_rig(Scene *scene, Object *ob)
+void DepsgraphRelationBuilder::build_rig(Object *object)
{
/* Armature-Data */
- bArmature *arm = (bArmature *)ob->data;
+ bArmature *arm = (bArmature *)object->data;
// TODO: selection status?
/* attach links between pose operations */
- OperationKey init_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_INIT);
- OperationKey flush_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
+ OperationKey init_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_INIT);
+ OperationKey init_ik_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_INIT_IK);
+ OperationKey flush_key(&object->id, DEG_NODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
- add_relation(init_key, flush_key, DEPSREL_TYPE_COMPONENT_ORDER, "[Pose Init -> Pose Cleanup]");
+ add_relation(init_key, init_ik_key, "Pose Init -> Pose Init IK");
+ add_relation(init_ik_key, flush_key, "Pose Init IK -> Pose Cleanup");
/* Make sure pose is up-to-date with armature updates. */
OperationKey armature_key(&arm->id,
- DEPSNODE_TYPE_PARAMETERS,
+ DEG_NODE_TYPE_PARAMETERS,
DEG_OPCODE_PLACEHOLDER,
"Armature Eval");
- add_relation(armature_key, init_key, DEPSREL_TYPE_COMPONENT_ORDER, "Data dependency");
-
- if (needs_animdata_node(&ob->id)) {
- ComponentKey animation_key(&ob->id, DEPSNODE_TYPE_ANIMATION);
- add_relation(animation_key, init_key, DEPSREL_TYPE_OPERATION, "Rig Animation");
- }
+ add_relation(armature_key, init_key, "Data dependency");
/* IK Solvers...
* - These require separate processing steps are pose-level
@@ -335,16 +339,16 @@ void DepsgraphRelationBuilder::build_rig(Scene *scene, Object *ob)
*/
RootPChanMap root_map;
bool pose_depends_on_local_transform = false;
- LINKLIST_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
- LINKLIST_FOREACH (bConstraint *, con, &pchan->constraints) {
+ LISTBASE_FOREACH (bPoseChannel *, pchan, &object->pose->chanbase) {
+ LISTBASE_FOREACH (bConstraint *, con, &pchan->constraints) {
switch (con->type) {
case CONSTRAINT_TYPE_KINEMATIC:
- build_ik_pose(ob, pchan, con, &root_map);
+ build_ik_pose(object, pchan, con, &root_map);
pose_depends_on_local_transform = true;
break;
case CONSTRAINT_TYPE_SPLINEIK:
- build_splineik_pose(ob, pchan, con, &root_map);
+ build_splineik_pose(object, pchan, con, &root_map);
pose_depends_on_local_transform = true;
break;
@@ -370,26 +374,25 @@ void DepsgraphRelationBuilder::build_rig(Scene *scene, Object *ob)
/* TODO(sergey): Once partial updates are possible use relation between
* object transform and solver itself in it's build function.
*/
- ComponentKey pose_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE);
- ComponentKey local_transform_key(&ob->id, DEPSNODE_TYPE_TRANSFORM);
- add_relation(local_transform_key, pose_key, DEPSREL_TYPE_TRANSFORM, "Local Transforms");
+ ComponentKey pose_key(&object->id, DEG_NODE_TYPE_EVAL_POSE);
+ ComponentKey local_transform_key(&object->id, DEG_NODE_TYPE_TRANSFORM);
+ add_relation(local_transform_key, pose_key, "Local Transforms");
}
-
/* links between operations for each bone */
- LINKLIST_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
- OperationKey bone_local_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_LOCAL);
- OperationKey bone_pose_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_POSE_PARENT);
- OperationKey bone_ready_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_READY);
- OperationKey bone_done_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_DONE);
+ LISTBASE_FOREACH (bPoseChannel *, pchan, &object->pose->chanbase) {
+ OperationKey bone_local_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_LOCAL);
+ OperationKey bone_pose_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_POSE_PARENT);
+ OperationKey bone_ready_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_READY);
+ OperationKey bone_done_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_DONE);
pchan->flag &= ~POSE_DONE;
/* pose init to bone local */
- add_relation(init_key, bone_local_key, DEPSREL_TYPE_OPERATION, "PoseEval Source-Bone Link");
+ add_relation(init_key, bone_local_key, "PoseEval Source-Bone Link");
/* local to pose parenting operation */
- add_relation(bone_local_key, bone_pose_key, DEPSREL_TYPE_OPERATION, "Bone Local - PoseSpace Link");
+ add_relation(bone_local_key, bone_pose_key, "Bone Local - PoseSpace Link");
/* parent relation */
if (pchan->parent != NULL) {
@@ -403,26 +406,31 @@ void DepsgraphRelationBuilder::build_rig(Scene *scene, Object *ob)
parent_key_opcode = DEG_OPCODE_BONE_DONE;
}
- OperationKey parent_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->parent->name, parent_key_opcode);
- add_relation(parent_key, bone_pose_key, DEPSREL_TYPE_TRANSFORM, "[Parent Bone -> Child Bone]");
+ OperationKey parent_key(&object->id, DEG_NODE_TYPE_BONE, pchan->parent->name, parent_key_opcode);
+ add_relation(parent_key, bone_pose_key, "Parent Bone -> Child Bone");
}
/* constraints */
if (pchan->constraints.first != NULL) {
+ /* Build relations for indirectly linked objects. */
+ BuilderWalkUserData data;
+ data.builder = this;
+ BKE_constraints_id_loop(&pchan->constraints, constraint_walk, &data);
+
/* constraints stack and constraint dependencies */
- build_constraints(scene, &ob->id, DEPSNODE_TYPE_BONE, pchan->name, &pchan->constraints, &root_map);
+ build_constraints(&object->id, DEG_NODE_TYPE_BONE, pchan->name, &pchan->constraints, &root_map);
/* pose -> constraints */
- OperationKey constraints_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_CONSTRAINTS);
- add_relation(bone_pose_key, constraints_key, DEPSREL_TYPE_OPERATION, "Constraints Stack");
+ OperationKey constraints_key(&object->id, DEG_NODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_CONSTRAINTS);
+ add_relation(bone_pose_key, constraints_key, "Constraints Stack");
/* constraints -> ready */
// TODO: when constraint stack is exploded, this step should occur before the first IK solver
- add_relation(constraints_key, bone_ready_key, DEPSREL_TYPE_OPERATION, "Constraints -> Ready");
+ add_relation(constraints_key, bone_ready_key, "Constraints -> Ready");
}
else {
/* pose -> ready */
- add_relation(bone_pose_key, bone_ready_key, DEPSREL_TYPE_OPERATION, "Pose -> Ready");
+ add_relation(bone_pose_key, bone_ready_key, "Pose -> Ready");
}
/* bone ready -> done
@@ -430,25 +438,57 @@ void DepsgraphRelationBuilder::build_rig(Scene *scene, Object *ob)
* For IK chains however, an additional rel is created from IK to done,
* with transitive reduction removing this one...
*/
- add_relation(bone_ready_key, bone_done_key, DEPSREL_TYPE_OPERATION, "Ready -> Done");
+ add_relation(bone_ready_key, bone_done_key, "Ready -> Done");
/* assume that all bones must be done for the pose to be ready (for deformers) */
- add_relation(bone_done_key, flush_key, DEPSREL_TYPE_OPERATION, "PoseEval Result-Bone Link");
+ add_relation(bone_done_key, flush_key, "PoseEval Result-Bone Link");
+
+ /* Custom shape. */
+ if (pchan->custom != NULL) {
+ build_object(pchan->custom);
+ }
}
}
-void DepsgraphRelationBuilder::build_proxy_rig(Object *ob)
+void DepsgraphRelationBuilder::build_proxy_rig(Object *object)
{
- OperationKey pose_init_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_INIT);
- OperationKey pose_done_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE, DEG_OPCODE_POSE_DONE);
- LINKLIST_FOREACH (bPoseChannel *, pchan, &ob->pose->chanbase) {
- OperationKey bone_local_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_LOCAL);
- OperationKey bone_ready_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_READY);
- OperationKey bone_done_key(&ob->id, DEPSNODE_TYPE_BONE, pchan->name, DEG_OPCODE_BONE_DONE);
- add_relation(pose_init_key, bone_local_key, DEPSREL_TYPE_OPERATION, "Pose Init -> Bone Local");
- add_relation(bone_local_key, bone_ready_key, DEPSREL_TYPE_OPERATION, "Local -> Ready");
- add_relation(bone_ready_key, bone_done_key, DEPSREL_TYPE_OPERATION, "Ready -> Done");
- add_relation(bone_done_key, pose_done_key, DEPSREL_TYPE_OPERATION, "Bone Done -> Pose Done");
+ Object *proxy_from = object->proxy_from;
+ OperationKey pose_init_key(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ DEG_OPCODE_POSE_INIT);
+ OperationKey pose_done_key(&object->id,
+ DEG_NODE_TYPE_EVAL_POSE,
+ DEG_OPCODE_POSE_DONE);
+ LISTBASE_FOREACH (bPoseChannel *, pchan, &object->pose->chanbase) {
+ OperationKey bone_local_key(&object->id,
+ DEG_NODE_TYPE_BONE, pchan->name,
+ DEG_OPCODE_BONE_LOCAL);
+ OperationKey bone_ready_key(&object->id,
+ DEG_NODE_TYPE_BONE,
+ pchan->name,
+ DEG_OPCODE_BONE_READY);
+ OperationKey bone_done_key(&object->id,
+ DEG_NODE_TYPE_BONE,
+ pchan->name,
+ DEG_OPCODE_BONE_DONE);
+ add_relation(pose_init_key, bone_local_key, "Pose Init -> Bone Local");
+ add_relation(bone_local_key, bone_ready_key, "Local -> Ready");
+ add_relation(bone_ready_key, bone_done_key, "Ready -> Done");
+ add_relation(bone_done_key, pose_done_key, "Bone Done -> Pose Done");
+
+ if (pchan->prop != NULL) {
+ OperationKey bone_parameters(&object->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL,
+ pchan->name);
+ OperationKey from_bone_parameters(&proxy_from->id,
+ DEG_NODE_TYPE_PARAMETERS,
+ DEG_OPCODE_PARAMETERS_EVAL,
+ pchan->name);
+ add_relation(from_bone_parameters,
+ bone_parameters,
+ "Proxy Bone Parameters");
+ }
}
}
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_relations_scene.cc b/source/blender/depsgraph/intern/builder/deg_builder_relations_scene.cc
index 8a3476cff45..c51addbd206 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_relations_scene.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_relations_scene.cc
@@ -38,26 +38,27 @@
#include "MEM_guardedalloc.h"
-extern "C" {
-#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLI_blenlib.h"
+extern "C" {
#include "DNA_node_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "BKE_main.h"
#include "BKE_node.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
#include "intern/builder/deg_builder.h"
#include "intern/builder/deg_builder_pchanmap.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_intern.h"
@@ -67,74 +68,48 @@ extern "C" {
namespace DEG {
-void DepsgraphRelationBuilder::build_scene(Main *bmain, Scene *scene)
+void DepsgraphRelationBuilder::build_scene(Scene *scene)
{
- if (scene->set) {
- build_scene(bmain, scene->set);
+ if (scene->set != NULL) {
+ build_scene(scene->set);
}
-
- /* scene objects */
- LINKLIST_FOREACH (Base *, base, &scene->base) {
- Object *ob = base->object;
-
- /* object itself */
- build_object(bmain, scene, ob);
-
- /* object that this is a proxy for */
- if (ob->proxy) {
- ob->proxy->proxy_from = ob;
- build_object(bmain, scene, ob->proxy);
- /* TODO(sergey): This is an inverted relation, matches old depsgraph
- * behavior and need to be investigated if it still need to be inverted.
- */
- ComponentKey ob_pose_key(&ob->id, DEPSNODE_TYPE_EVAL_POSE);
- ComponentKey proxy_pose_key(&ob->proxy->id, DEPSNODE_TYPE_EVAL_POSE);
- add_relation(ob_pose_key, proxy_pose_key, DEPSREL_TYPE_TRANSFORM, "Proxy");
- }
-
- /* Object dupligroup. */
- if (ob->dup_group) {
- build_group(bmain, scene, ob, ob->dup_group);
- }
+ /* Setup currently building context. */
+ scene_ = scene;
+ /* Scene objects. */
+ LISTBASE_FOREACH (Base *, base, &scene->base) {
+ Object *object = base->object;
+ build_object(object);
}
-
- /* rigidbody */
- if (scene->rigidbody_world) {
+ /* Rigidbody. */
+ if (scene->rigidbody_world != NULL) {
build_rigidbody(scene);
}
-
- /* scene's animation and drivers */
- if (scene->adt) {
+ /* Scene's animation and drivers. */
+ if (scene->adt != NULL) {
build_animdata(&scene->id);
}
-
- /* world */
- if (scene->world) {
+ /* World. */
+ if (scene->world != NULL) {
build_world(scene->world);
}
-
- /* compo nodes */
- if (scene->nodetree) {
+ /* Compositor nodes. */
+ if (scene->nodetree != NULL) {
build_compositor(scene);
}
-
- /* grease pencil */
- if (scene->gpd) {
+ /* Grease pencil. */
+ if (scene->gpd != NULL) {
build_gpencil(scene->gpd);
}
-
/* Masks. */
- LINKLIST_FOREACH (Mask *, mask, &bmain->mask) {
+ LISTBASE_FOREACH (Mask *, mask, &bmain_->mask) {
build_mask(mask);
}
-
/* Movie clips. */
- LINKLIST_FOREACH (MovieClip *, clip, &bmain->movieclip) {
+ LISTBASE_FOREACH (MovieClip *, clip, &bmain_->movieclip) {
build_movieclip(clip);
}
-
- for (Depsgraph::OperationNodes::const_iterator it_op = m_graph->operations.begin();
- it_op != m_graph->operations.end();
+ for (Depsgraph::OperationNodes::const_iterator it_op = graph_->operations.begin();
+ it_op != graph_->operations.end();
++it_op)
{
OperationDepsNode *node = *it_op;
diff --git a/source/blender/depsgraph/intern/builder/deg_builder_transitive.cc b/source/blender/depsgraph/intern/builder/deg_builder_transitive.cc
index da71db09f3d..12760cad73c 100644
--- a/source/blender/depsgraph/intern/builder/deg_builder_transitive.cc
+++ b/source/blender/depsgraph/intern/builder/deg_builder_transitive.cc
@@ -30,15 +30,14 @@
#include "intern/builder/deg_builder_transitive.h"
-extern "C" {
#include "MEM_guardedalloc.h"
-}
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph.h"
+#include "intern/depsgraph_intern.h"
#include "util/deg_util_foreach.h"
@@ -81,13 +80,13 @@ static void deg_graph_tag_paths_recursive(DepsNode *node)
void deg_graph_transitive_reduction(Depsgraph *graph)
{
+ int num_removed_relations = 0;
foreach (OperationDepsNode *target, graph->operations) {
/* Clear tags. */
foreach (OperationDepsNode *node, graph->operations) {
node->done = 0;
}
-
- /* mark nodes from which we can reach the target
+ /* Mark nodes from which we can reach the target
* start with children, so the target node and direct children are not
* flagged.
*/
@@ -95,27 +94,30 @@ void deg_graph_transitive_reduction(Depsgraph *graph)
foreach (DepsRelation *rel, target->inlinks) {
deg_graph_tag_paths_recursive(rel->from);
}
-
/* Remove redundant paths to the target. */
for (DepsNode::Relations::const_iterator it_rel = target->inlinks.begin();
it_rel != target->inlinks.end();
)
{
DepsRelation *rel = *it_rel;
- /* Increment in advance, so we can safely remove the relation. */
- ++it_rel;
-
- if (rel->from->type == DEPSNODE_TYPE_TIMESOURCE) {
+ if (rel->from->type == DEG_NODE_TYPE_TIMESOURCE) {
/* HACK: time source nodes don't get "done" flag set/cleared. */
/* TODO: there will be other types in future, so iterators above
* need modifying.
*/
+ ++it_rel;
}
else if (rel->from->done & OP_REACHABLE) {
+ rel->unlink();
OBJECT_GUARDED_DELETE(rel, DepsRelation);
+ ++num_removed_relations;
+ }
+ else {
+ ++it_rel;
}
}
}
+ DEG_DEBUG_PRINTF(BUILD, "Removed %d relations\n", num_removed_relations);
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/debug/deg_debug_graphviz.cc b/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc
index 0d56ce71c7d..80772f9595f 100644
--- a/source/blender/depsgraph/intern/debug/deg_debug_graphviz.cc
+++ b/source/blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc
@@ -24,7 +24,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/depsgraph/intern/debug/deg_debug_graphviz.cc
+/** \file blender/depsgraph/intern/debug/deg_debug_relations_graphviz.cc
* \ingroup depsgraph
*
* Implementation of tools for debugging the depsgraph
@@ -35,12 +35,15 @@
extern "C" {
#include "DNA_listBase.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_debug.h"
-} /* extern "C" */
#include "intern/depsgraph_intern.h"
+#include "intern/nodes/deg_node_id.h"
+#include "intern/nodes/deg_node_time.h"
+
#include "util/deg_util_foreach.h"
/* ****************** */
@@ -77,20 +80,18 @@ static const char *deg_debug_colors_light[] = {
#ifdef COLOR_SCHEME_NODE_TYPE
static const int deg_debug_node_type_color_map[][2] = {
- {DEPSNODE_TYPE_ROOT, 0},
- {DEPSNODE_TYPE_TIMESOURCE, 1},
- {DEPSNODE_TYPE_ID_REF, 2},
- {DEPSNODE_TYPE_SUBGRAPH, 3},
+ {DEG_NODE_TYPE_TIMESOURCE, 0},
+ {DEG_NODE_TYPE_ID_REF, 2},
/* Outer Types */
- {DEPSNODE_TYPE_PARAMETERS, 4},
- {DEPSNODE_TYPE_PROXY, 5},
- {DEPSNODE_TYPE_ANIMATION, 6},
- {DEPSNODE_TYPE_TRANSFORM, 7},
- {DEPSNODE_TYPE_GEOMETRY, 8},
- {DEPSNODE_TYPE_SEQUENCER, 9},
- {DEPSNODE_TYPE_SHADING, 10},
- {DEPSNODE_TYPE_CACHE, 11},
+ {DEG_NODE_TYPE_PARAMETERS, 2},
+ {DEG_NODE_TYPE_PROXY, 3},
+ {DEG_NODE_TYPE_ANIMATION, 4},
+ {DEG_NODE_TYPE_TRANSFORM, 5},
+ {DEG_NODE_TYPE_GEOMETRY, 6},
+ {DEG_NODE_TYPE_SEQUENCER, 7},
+ {DEG_NODE_TYPE_SHADING, 8},
+ {DEG_NODE_TYPE_CACHE, 9},
{-1, 0}
};
#endif
@@ -100,9 +101,9 @@ static int deg_debug_node_color_index(const DepsNode *node)
#ifdef COLOR_SCHEME_NODE_CLASS
/* Some special types. */
switch (node->type) {
- case DEPSNODE_TYPE_ID_REF:
+ case DEG_NODE_TYPE_ID_REF:
return 5;
- case DEPSNODE_TYPE_OPERATION:
+ case DEG_NODE_TYPE_OPERATION:
{
OperationDepsNode *op_node = (OperationDepsNode *)node;
if (op_node->is_noop())
@@ -114,10 +115,10 @@ static int deg_debug_node_color_index(const DepsNode *node)
break;
}
/* Do others based on class. */
- switch (node->tclass) {
- case DEPSNODE_CLASS_OPERATION:
+ switch (node->get_class()) {
+ case DEG_NODE_CLASS_OPERATION:
return 4;
- case DEPSNODE_CLASS_COMPONENT:
+ case DEG_NODE_CLASS_COMPONENT:
return 1;
default:
return 9;
@@ -138,7 +139,6 @@ static int deg_debug_node_color_index(const DepsNode *node)
struct DebugContext {
FILE *file;
bool show_tags;
- bool show_eval_priority;
};
static void deg_debug_fprintf(const DebugContext &ctx, const char *fmt, ...) ATTR_PRINTF_FORMAT(2, 3);
@@ -179,7 +179,7 @@ static void deg_debug_graphviz_legend(const DebugContext &ctx)
#ifdef COLOR_SCHEME_NODE_TYPE
const int (*pair)[2];
for (pair = deg_debug_node_type_color_map; (*pair)[0] >= 0; ++pair) {
- DepsNodeFactory *nti = DEG_get_node_factory((eDepsNode_Type)(*pair)[0]);
+ DepsNodeFactory *nti = deg_type_get_factory((eDepsNode_Type)(*pair)[0]);
deg_debug_graphviz_legend_color(ctx,
nti->tname().c_str(),
deg_debug_colors_light[(*pair)[1] % deg_debug_max_colors]);
@@ -201,7 +201,7 @@ static void deg_debug_graphviz_node_color(const DebugContext &ctx,
const char *color_update = "dodgerblue3";
const char *color = color_default;
if (ctx.show_tags) {
- if (node->tclass == DEPSNODE_CLASS_OPERATION) {
+ if (node->get_class() == DEG_NODE_CLASS_OPERATION) {
OperationDepsNode *op_node = (OperationDepsNode *)node;
if (op_node->flag & DEPSOP_FLAG_DIRECTLY_MODIFIED) {
color = color_modified;
@@ -222,7 +222,7 @@ static void deg_debug_graphviz_node_penwidth(const DebugContext &ctx,
float penwidth_update = 4.0f;
float penwidth = penwidth_default;
if (ctx.show_tags) {
- if (node->tclass == DEPSNODE_CLASS_OPERATION) {
+ if (node->get_class() == DEG_NODE_CLASS_OPERATION) {
OperationDepsNode *op_node = (OperationDepsNode *)node;
if (op_node->flag & DEPSOP_FLAG_DIRECTLY_MODIFIED) {
penwidth = penwidth_modified;
@@ -256,25 +256,37 @@ static void deg_debug_graphviz_relation_color(const DebugContext &ctx,
deg_debug_fprintf(ctx, "%s", color);
}
+static void deg_debug_graphviz_relation_style(const DebugContext &ctx,
+ const DepsRelation *rel)
+{
+ const char *style_default = "solid";
+ const char *style_no_flush = "dashed";
+ const char *style = style_default;
+ if (rel->flag & DEPSREL_FLAG_NO_FLUSH) {
+ style = style_no_flush;
+ }
+ deg_debug_fprintf(ctx, "%s", style);
+}
+
static void deg_debug_graphviz_node_style(const DebugContext &ctx, const DepsNode *node)
{
const char *base_style = "filled"; /* default style */
if (ctx.show_tags) {
- if (node->tclass == DEPSNODE_CLASS_OPERATION) {
+ if (node->get_class() == DEG_NODE_CLASS_OPERATION) {
OperationDepsNode *op_node = (OperationDepsNode *)node;
if (op_node->flag & (DEPSOP_FLAG_DIRECTLY_MODIFIED | DEPSOP_FLAG_NEEDS_UPDATE)) {
base_style = "striped";
}
}
}
- switch (node->tclass) {
- case DEPSNODE_CLASS_GENERIC:
+ switch (node->get_class()) {
+ case DEG_NODE_CLASS_GENERIC:
deg_debug_fprintf(ctx, "\"%s\"", base_style);
break;
- case DEPSNODE_CLASS_COMPONENT:
+ case DEG_NODE_CLASS_COMPONENT:
deg_debug_fprintf(ctx, "\"%s\"", base_style);
break;
- case DEPSNODE_CLASS_OPERATION:
+ case DEG_NODE_CLASS_OPERATION:
deg_debug_fprintf(ctx, "\"%s,rounded\"", base_style);
break;
}
@@ -285,28 +297,17 @@ static void deg_debug_graphviz_node_single(const DebugContext &ctx,
{
const char *shape = "box";
string name = node->identifier();
- float priority = -1.0f;
- if (node->type == DEPSNODE_TYPE_ID_REF) {
+ if (node->type == DEG_NODE_TYPE_ID_REF) {
IDDepsNode *id_node = (IDDepsNode *)node;
char buf[256];
BLI_snprintf(buf, sizeof(buf), " (Layers: %u)", id_node->layers);
name += buf;
}
- if (ctx.show_eval_priority && node->tclass == DEPSNODE_CLASS_OPERATION) {
- priority = ((OperationDepsNode *)node)->eval_priority;
- }
deg_debug_fprintf(ctx, "// %s\n", name.c_str());
deg_debug_fprintf(ctx, "\"node_%p\"", node);
deg_debug_fprintf(ctx, "[");
// deg_debug_fprintf(ctx, "label=<<B>%s</B>>", name);
- if (priority >= 0.0f) {
- deg_debug_fprintf(ctx, "label=<%s<BR/>(<I>%.2f</I>)>",
- name.c_str(),
- priority);
- }
- else {
- deg_debug_fprintf(ctx, "label=<%s>", name.c_str());
- }
+ deg_debug_fprintf(ctx, "label=<%s>", name.c_str());
deg_debug_fprintf(ctx, ",fontname=\"%s\"", deg_debug_graphviz_fontname);
deg_debug_fprintf(ctx, ",fontsize=%f", deg_debug_graphviz_node_label_size);
deg_debug_fprintf(ctx, ",shape=%s", shape);
@@ -322,7 +323,7 @@ static void deg_debug_graphviz_node_cluster_begin(const DebugContext &ctx,
const DepsNode *node)
{
string name = node->identifier();
- if (node->type == DEPSNODE_TYPE_ID_REF) {
+ if (node->type == DEG_NODE_TYPE_ID_REF) {
IDDepsNode *id_node = (IDDepsNode *)node;
char buf[256];
BLI_snprintf(buf, sizeof(buf), " (Layers: %u)", id_node->layers);
@@ -363,10 +364,10 @@ static void deg_debug_graphviz_node(const DebugContext &ctx,
const DepsNode *node)
{
switch (node->type) {
- case DEPSNODE_TYPE_ID_REF:
+ case DEG_NODE_TYPE_ID_REF:
{
const IDDepsNode *id_node = (const IDDepsNode *)node;
- if (BLI_ghash_size(id_node->components) == 0) {
+ if (BLI_ghash_len(id_node->components) == 0) {
deg_debug_graphviz_node_single(ctx, node);
}
else {
@@ -380,30 +381,17 @@ static void deg_debug_graphviz_node(const DebugContext &ctx,
}
break;
}
- case DEPSNODE_TYPE_SUBGRAPH:
- {
- SubgraphDepsNode *sub_node = (SubgraphDepsNode *)node;
- if (sub_node->graph) {
- deg_debug_graphviz_node_cluster_begin(ctx, node);
- deg_debug_graphviz_graph_nodes(ctx, sub_node->graph);
- deg_debug_graphviz_node_cluster_end(ctx);
- }
- else {
- deg_debug_graphviz_node_single(ctx, node);
- }
- break;
- }
- case DEPSNODE_TYPE_PARAMETERS:
- case DEPSNODE_TYPE_ANIMATION:
- case DEPSNODE_TYPE_TRANSFORM:
- case DEPSNODE_TYPE_PROXY:
- case DEPSNODE_TYPE_GEOMETRY:
- case DEPSNODE_TYPE_SEQUENCER:
- case DEPSNODE_TYPE_EVAL_POSE:
- case DEPSNODE_TYPE_BONE:
- case DEPSNODE_TYPE_SHADING:
- case DEPSNODE_TYPE_CACHE:
- case DEPSNODE_TYPE_EVAL_PARTICLES:
+ case DEG_NODE_TYPE_PARAMETERS:
+ case DEG_NODE_TYPE_ANIMATION:
+ case DEG_NODE_TYPE_TRANSFORM:
+ case DEG_NODE_TYPE_PROXY:
+ case DEG_NODE_TYPE_GEOMETRY:
+ case DEG_NODE_TYPE_SEQUENCER:
+ case DEG_NODE_TYPE_EVAL_POSE:
+ case DEG_NODE_TYPE_BONE:
+ case DEG_NODE_TYPE_SHADING:
+ case DEG_NODE_TYPE_CACHE:
+ case DEG_NODE_TYPE_EVAL_PARTICLES:
{
ComponentDepsNode *comp_node = (ComponentDepsNode *)node;
if (!comp_node->operations.empty()) {
@@ -427,24 +415,19 @@ static void deg_debug_graphviz_node(const DebugContext &ctx,
static bool deg_debug_graphviz_is_cluster(const DepsNode *node)
{
switch (node->type) {
- case DEPSNODE_TYPE_ID_REF:
+ case DEG_NODE_TYPE_ID_REF:
{
const IDDepsNode *id_node = (const IDDepsNode *)node;
- return BLI_ghash_size(id_node->components) > 0;
- }
- case DEPSNODE_TYPE_SUBGRAPH:
- {
- SubgraphDepsNode *sub_node = (SubgraphDepsNode *)node;
- return sub_node->graph != NULL;
+ return BLI_ghash_len(id_node->components) > 0;
}
- case DEPSNODE_TYPE_PARAMETERS:
- case DEPSNODE_TYPE_ANIMATION:
- case DEPSNODE_TYPE_TRANSFORM:
- case DEPSNODE_TYPE_PROXY:
- case DEPSNODE_TYPE_GEOMETRY:
- case DEPSNODE_TYPE_SEQUENCER:
- case DEPSNODE_TYPE_EVAL_POSE:
- case DEPSNODE_TYPE_BONE:
+ case DEG_NODE_TYPE_PARAMETERS:
+ case DEG_NODE_TYPE_ANIMATION:
+ case DEG_NODE_TYPE_TRANSFORM:
+ case DEG_NODE_TYPE_PROXY:
+ case DEG_NODE_TYPE_GEOMETRY:
+ case DEG_NODE_TYPE_SEQUENCER:
+ case DEG_NODE_TYPE_EVAL_POSE:
+ case DEG_NODE_TYPE_BONE:
{
ComponentDepsNode *comp_node = (ComponentDepsNode *)node;
return !comp_node->operations.empty();
@@ -457,15 +440,15 @@ static bool deg_debug_graphviz_is_cluster(const DepsNode *node)
static bool deg_debug_graphviz_is_owner(const DepsNode *node,
const DepsNode *other)
{
- switch (node->tclass) {
- case DEPSNODE_CLASS_COMPONENT:
+ switch (node->get_class()) {
+ case DEG_NODE_CLASS_COMPONENT:
{
ComponentDepsNode *comp_node = (ComponentDepsNode *)node;
if (comp_node->owner == other)
return true;
break;
}
- case DEPSNODE_CLASS_OPERATION:
+ case DEG_NODE_CLASS_OPERATION:
{
OperationDepsNode *op_node = (OperationDepsNode *)node;
if (op_node->owner == other)
@@ -497,16 +480,24 @@ static void deg_debug_graphviz_node_relations(const DebugContext &ctx,
deg_debug_fprintf(ctx, "[");
/* Note: without label an id seem necessary to avoid bugs in graphviz/dot */
deg_debug_fprintf(ctx, "id=\"%s\"", rel->name);
- deg_debug_fprintf(ctx, ",color="); deg_debug_graphviz_relation_color(ctx, rel);
+ // deg_debug_fprintf(ctx, "label=\"%s\"", rel->name);
+ deg_debug_fprintf(ctx, ",color=");
+ deg_debug_graphviz_relation_color(ctx, rel);
+ deg_debug_fprintf(ctx, ",style=");
+ deg_debug_graphviz_relation_style(ctx, rel);
deg_debug_fprintf(ctx, ",penwidth=\"%f\"", penwidth);
/* NOTE: edge from node to own cluster is not possible and gives graphviz
* warning, avoid this here by just linking directly to the invisible
* placeholder node
*/
- if (deg_debug_graphviz_is_cluster(tail) && !deg_debug_graphviz_is_owner(head, tail)) {
+ if (deg_debug_graphviz_is_cluster(tail) &&
+ !deg_debug_graphviz_is_owner(head, tail))
+ {
deg_debug_fprintf(ctx, ",ltail=\"cluster_%p\"", tail);
}
- if (deg_debug_graphviz_is_cluster(head) && !deg_debug_graphviz_is_owner(tail, head)) {
+ if (deg_debug_graphviz_is_cluster(head) &&
+ !deg_debug_graphviz_is_owner(tail, head))
+ {
deg_debug_fprintf(ctx, ",lhead=\"cluster_%p\"", head);
}
deg_debug_fprintf(ctx, "];" NL);
@@ -517,15 +508,10 @@ static void deg_debug_graphviz_node_relations(const DebugContext &ctx,
static void deg_debug_graphviz_graph_nodes(const DebugContext &ctx,
const Depsgraph *graph)
{
- if (graph->root_node) {
- deg_debug_graphviz_node(ctx, graph->root_node);
- }
- GHASH_FOREACH_BEGIN (DepsNode *, node, graph->id_hash)
- {
+ foreach (DepsNode *node, graph->id_nodes) {
deg_debug_graphviz_node(ctx, node);
}
- GHASH_FOREACH_END();
- TimeSourceDepsNode *time_source = graph->find_time_source(NULL);
+ TimeSourceDepsNode *time_source = graph->find_time_source();
if (time_source != NULL) {
deg_debug_graphviz_node(ctx, time_source);
}
@@ -534,8 +520,7 @@ static void deg_debug_graphviz_graph_nodes(const DebugContext &ctx,
static void deg_debug_graphviz_graph_relations(const DebugContext &ctx,
const Depsgraph *graph)
{
- GHASH_FOREACH_BEGIN(IDDepsNode *, id_node, graph->id_hash)
- {
+ foreach (IDDepsNode *id_node, graph->id_nodes) {
GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components)
{
foreach (OperationDepsNode *op_node, comp_node->operations) {
@@ -544,9 +529,8 @@ static void deg_debug_graphviz_graph_relations(const DebugContext &ctx,
}
GHASH_FOREACH_END();
}
- GHASH_FOREACH_END();
- TimeSourceDepsNode *time_source = graph->find_time_source(NULL);
+ TimeSourceDepsNode *time_source = graph->find_time_source();
if (time_source != NULL) {
deg_debug_graphviz_node_relations(ctx, time_source);
}
@@ -554,7 +538,9 @@ static void deg_debug_graphviz_graph_relations(const DebugContext &ctx,
} // namespace DEG
-void DEG_debug_graphviz(const Depsgraph *graph, FILE *f, const char *label, bool show_eval)
+void DEG_debug_relations_graphviz(const Depsgraph *graph,
+ FILE *f,
+ const char *label)
{
if (!graph) {
return;
@@ -564,8 +550,6 @@ void DEG_debug_graphviz(const Depsgraph *graph, FILE *f, const char *label, bool
DEG::DebugContext ctx;
ctx.file = f;
- ctx.show_tags = show_eval;
- ctx.show_eval_priority = show_eval;
DEG::deg_debug_fprintf(ctx, "digraph depgraph {" NL);
DEG::deg_debug_fprintf(ctx, "rankdir=LR;" NL);
diff --git a/source/blender/depsgraph/intern/debug/deg_debug_stats_gnuplot.cc b/source/blender/depsgraph/intern/debug/deg_debug_stats_gnuplot.cc
new file mode 100644
index 00000000000..e92c7730482
--- /dev/null
+++ b/source/blender/depsgraph/intern/debug/deg_debug_stats_gnuplot.cc
@@ -0,0 +1,157 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2017 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/debug/deg_debug_stats_gnuplot.cc
+ * \ingroup depsgraph
+ */
+
+#include "DEG_depsgraph_debug.h"
+
+#include <algorithm>
+#include <cstdarg>
+
+#include "BLI_compiler_attrs.h"
+#include "BLI_math_base.h"
+
+#include "intern/depsgraph.h"
+#include "intern/nodes/deg_node_id.h"
+
+#include "util/deg_util_foreach.h"
+
+extern "C" {
+#include "DNA_ID.h"
+} /* extern "C" */
+
+#define NL "\r\n"
+
+namespace DEG {
+namespace {
+
+struct DebugContext {
+ FILE *file;
+ const Depsgraph *graph;
+ const char *label;
+ const char *output_filename;
+};
+
+struct StatsEntry {
+ const IDDepsNode *id_node;
+ double time;
+};
+
+/* TODO(sergey): De-duplicate with graphviz relation debugger. */
+static void deg_debug_fprintf(const DebugContext &ctx,
+ const char *fmt,
+ ...) ATTR_PRINTF_FORMAT(2, 3);
+static void deg_debug_fprintf(const DebugContext &ctx, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args, fmt);
+ vfprintf(ctx.file, fmt, args);
+ va_end(args);
+}
+
+BLI_INLINE double get_node_time(const DebugContext& /*ctx*/,
+ const DepsNode *node)
+{
+ // TODO(sergey): Figure out a nice way to define which exact time
+ // we want to show.
+ return node->stats.current_time;
+}
+
+bool stat_entry_comparator(const StatsEntry& a, const StatsEntry& b)
+{
+ return a.time < b.time;
+}
+
+void write_stats_data(const DebugContext& ctx)
+{
+ // Fill in array of all stats which are to be displayed.
+ vector<StatsEntry> stats;
+ stats.reserve(ctx.graph->id_nodes.size());
+ foreach (const IDDepsNode *id_node, ctx.graph->id_nodes) {
+ const double time = get_node_time(ctx, id_node);
+ if (time == 0.0) {
+ continue;
+ }
+ StatsEntry entry;
+ entry.id_node = id_node;
+ entry.time = time;
+ stats.push_back(entry);
+ }
+ // Sort the data.
+ std::sort(stats.begin(), stats.end(), stat_entry_comparator);
+ // We limit number of entries, otherwise things become unreadable.
+ stats.resize(min_ii(stats.size(), 32));
+ // Print data to the file stream.
+ deg_debug_fprintf(ctx, "$data << EOD" NL);
+ foreach (const StatsEntry& entry, stats) {
+ deg_debug_fprintf(ctx, "\"%s\",%f" NL,
+ entry.id_node->id->name + 2,
+ entry.time);
+ }
+ deg_debug_fprintf(ctx, "EOD" NL);
+}
+
+void deg_debug_stats_gnuplot(const DebugContext& ctx)
+{
+ // Data itself.
+ write_stats_data(ctx);
+ // Optional label.
+ if (ctx.label && ctx.label[0]) {
+ deg_debug_fprintf(ctx, "set title \"%s\"" NL, ctx.label);
+ }
+ // Rest of the commands.
+ // TODO(sergey): Need to decide on the resolution somehow.
+ deg_debug_fprintf(ctx, "set terminal pngcairo size 1920,1080" NL);
+ deg_debug_fprintf(ctx, "set output \"%s\"" NL, ctx.output_filename);
+ deg_debug_fprintf(ctx, "set grid" NL);
+ deg_debug_fprintf(ctx, "set datafile separator ','" NL);
+ deg_debug_fprintf(ctx, "set style fill solid" NL);
+ deg_debug_fprintf(ctx, "plot \"$data\" using " \
+ "($2*0.5):0:($2*0.5):(0.2):yticlabels(1) "
+ "with boxxyerrorbars t '' lt rgb \"#406090\"" NL);
+
+}
+
+} // namespace
+} // namespace DEG
+
+void DEG_debug_stats_gnuplot(const Depsgraph *depsgraph,
+ FILE *f,
+ const char *label,
+ const char *output_filename)
+{
+ if (depsgraph == NULL) {
+ return;
+ }
+ DEG::DebugContext ctx;
+ ctx.file = f;
+ ctx.graph = (DEG::Depsgraph *)depsgraph;
+ ctx.label = label;
+ ctx.output_filename = output_filename;
+ DEG::deg_debug_stats_gnuplot(ctx);
+}
diff --git a/source/blender/depsgraph/intern/depsgraph.cc b/source/blender/depsgraph/intern/depsgraph.cc
index 5604044e123..34fb20ee2ba 100644
--- a/source/blender/depsgraph/intern/depsgraph.cc
+++ b/source/blender/depsgraph/intern/depsgraph.cc
@@ -35,6 +35,8 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
+#include "BLI_console.h"
+#include "BLI_hash.h"
#include "BLI_ghash.h"
#include "BLI_listbase.h"
@@ -51,13 +53,16 @@ extern "C" {
#include "RNA_access.h"
}
+#include <algorithm>
#include <cstring>
#include "DEG_depsgraph.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
+#include "intern/nodes/deg_node_time.h"
#include "intern/depsgraph_intern.h"
#include "util/deg_util_foreach.h"
@@ -68,102 +73,98 @@ static DEG_EditorUpdateIDCb deg_editor_update_id_cb = NULL;
static DEG_EditorUpdateSceneCb deg_editor_update_scene_cb = NULL;
static DEG_EditorUpdateScenePreCb deg_editor_update_scene_pre_cb = NULL;
+/* TODO(sergey): Find a better place for this. */
+template <typename T>
+static void remove_from_vector(vector<T> *vector, const T& value)
+{
+ vector->erase(std::remove(vector->begin(), vector->end(), value),
+ vector->end());
+}
+
Depsgraph::Depsgraph()
- : root_node(NULL),
+ : time_source(NULL),
need_update(false),
layers(0)
{
BLI_spin_init(&lock);
id_hash = BLI_ghash_ptr_new("Depsgraph id hash");
- subgraphs = BLI_gset_ptr_new("Depsgraph subgraphs");
entry_tags = BLI_gset_ptr_new("Depsgraph entry_tags");
}
Depsgraph::~Depsgraph()
{
- /* Free root node - it won't have been freed yet... */
clear_id_nodes();
- clear_subgraph_nodes();
BLI_ghash_free(id_hash, NULL, NULL);
- BLI_gset_free(subgraphs, NULL);
BLI_gset_free(entry_tags, NULL);
- if (this->root_node != NULL) {
- OBJECT_GUARDED_DELETE(this->root_node, RootDepsNode);
+ if (time_source != NULL) {
+ OBJECT_GUARDED_DELETE(time_source, TimeSourceDepsNode);
}
BLI_spin_end(&lock);
}
/* Query Conditions from RNA ----------------------- */
-static bool pointer_to_id_node_criteria(const PointerRNA *ptr,
- const PropertyRNA *prop,
- ID **id)
+static bool pointer_to_component_node_criteria(
+ const PointerRNA *ptr,
+ const PropertyRNA *prop,
+ ID **id,
+ eDepsNode_Type *type,
+ const char **subdata,
+ eDepsOperation_Code *operation_code,
+ const char **operation_name,
+ int *operation_name_tag)
{
- if (!ptr->type)
+ if (ptr->type == NULL) {
return false;
-
- if (!prop) {
- if (RNA_struct_is_ID(ptr->type)) {
- *id = (ID *)ptr->data;
- return true;
- }
}
-
- return false;
-}
-
-static bool pointer_to_component_node_criteria(const PointerRNA *ptr,
- const PropertyRNA *prop,
- ID **id,
- eDepsNode_Type *type,
- const char **subdata)
-{
- if (!ptr->type)
- return false;
-
/* Set default values for returns. */
- *id = (ID *)ptr->id.data; /* For obvious reasons... */
- *subdata = ""; /* Default to no subdata (e.g. bone) name
- * lookup in most cases. */
-
- /* Handling of commonly known scenarios... */
+ *id = (ID *)ptr->id.data;
+ *subdata = "";
+ *operation_code = DEG_OPCODE_OPERATION;
+ *operation_name = "";
+ *operation_name_tag = -1;
+ /* Handling of commonly known scenarios. */
if (ptr->type == &RNA_PoseBone) {
bPoseChannel *pchan = (bPoseChannel *)ptr->data;
-
- /* Bone - generally, we just want the bone component... */
- *type = DEPSNODE_TYPE_BONE;
- *subdata = pchan->name;
-
+ if (prop != NULL && RNA_property_is_idprop(prop)) {
+ *type = DEG_NODE_TYPE_PARAMETERS;
+ *subdata = "";
+ *operation_code = DEG_OPCODE_PARAMETERS_EVAL;
+ *operation_name = pchan->name;
+ }
+ else {
+ /* Bone - generally, we just want the bone component. */
+ *type = DEG_NODE_TYPE_BONE;
+ *subdata = pchan->name;
+ }
return true;
}
else if (ptr->type == &RNA_Bone) {
Bone *bone = (Bone *)ptr->data;
-
/* armature-level bone, but it ends up going to bone component anyway */
- // TODO: the ID in thise case will end up being bArmature, not Object as needed!
- *type = DEPSNODE_TYPE_BONE;
+ // NOTE: the ID in thise case will end up being bArmature.
+ *type = DEG_NODE_TYPE_BONE;
*subdata = bone->name;
- //*id = ...
-
return true;
}
else if (RNA_struct_is_a(ptr->type, &RNA_Constraint)) {
- Object *ob = (Object *)ptr->id.data;
+ Object *object = (Object *)ptr->id.data;
bConstraint *con = (bConstraint *)ptr->data;
-
- /* object or bone? */
- if (BLI_findindex(&ob->constraints, con) != -1) {
- /* object transform */
- // XXX: for now, we can't address the specific constraint or the constraint stack...
- *type = DEPSNODE_TYPE_TRANSFORM;
+ /* Check whether is object or bone constraint. */
+ /* NOTE: Currently none of the area can address transform of an object
+ * at a given constraint, but for rigging one might use constraint
+ * influence to be used to drive some corrective shape keys or so.
+ */
+ if (BLI_findindex(&object->constraints, con) != -1) {
+ *type = DEG_NODE_TYPE_TRANSFORM;
+ *operation_code = DEG_OPCODE_TRANSFORM_LOCAL;
return true;
}
- else if (ob->pose) {
- bPoseChannel *pchan;
- for (pchan = (bPoseChannel *)ob->pose->chanbase.first; pchan; pchan = pchan->next) {
+ else if (object->pose != NULL) {
+ LISTBASE_FOREACH(bPoseChannel *, pchan, &object->pose->chanbase) {
if (BLI_findindex(&pchan->constraints, con) != -1) {
- /* bone transforms */
- *type = DEPSNODE_TYPE_BONE;
+ *type = DEG_NODE_TYPE_BONE;
+ *operation_code = DEG_OPCODE_BONE_LOCAL;
*subdata = pchan->name;
return true;
}
@@ -171,23 +172,12 @@ static bool pointer_to_component_node_criteria(const PointerRNA *ptr,
}
}
else if (RNA_struct_is_a(ptr->type, &RNA_Modifier)) {
- //ModifierData *md = (ModifierData *)ptr->data;
-
- /* Modifier */
- /* NOTE: subdata is not the same as "operation name",
- * so although we have unique ops for modifiers,
- * we can't lump them together
- */
- *type = DEPSNODE_TYPE_BONE;
- //*subdata = md->name;
-
+ *type = DEG_NODE_TYPE_GEOMETRY;
return true;
}
else if (ptr->type == &RNA_Object) {
- //Object *ob = (Object *)ptr->data;
-
/* Transforms props? */
- if (prop) {
+ if (prop != NULL) {
const char *prop_identifier = RNA_property_identifier((PropertyRNA *)prop);
/* TODO(sergey): How to optimize this? */
if (strstr(prop_identifier, "location") ||
@@ -195,41 +185,56 @@ static bool pointer_to_component_node_criteria(const PointerRNA *ptr,
strstr(prop_identifier, "scale") ||
strstr(prop_identifier, "matrix_"))
{
- *type = DEPSNODE_TYPE_TRANSFORM;
+ *type = DEG_NODE_TYPE_TRANSFORM;
return true;
}
else if (strstr(prop_identifier, "data")) {
/* We access object.data, most likely a geometry.
* Might be a bone tho..
*/
- *type = DEPSNODE_TYPE_GEOMETRY;
+ *type = DEG_NODE_TYPE_GEOMETRY;
return true;
}
}
}
else if (ptr->type == &RNA_ShapeKey) {
- Key *key = (Key *)ptr->id.data;
-
- /* ShapeKeys are currently handled as geometry on the geometry that owns it */
- *id = key->from; // XXX
- *type = DEPSNODE_TYPE_PARAMETERS;
-
+ *id = (ID *)ptr->id.data;
+ *type = DEG_NODE_TYPE_GEOMETRY;
+ return true;
+ }
+ else if (ptr->type == &RNA_Key) {
+ *id = (ID *)ptr->id.data;
+ *type = DEG_NODE_TYPE_GEOMETRY;
return true;
}
else if (RNA_struct_is_a(ptr->type, &RNA_Sequence)) {
Sequence *seq = (Sequence *)ptr->data;
/* Sequencer strip */
- *type = DEPSNODE_TYPE_SEQUENCER;
+ *type = DEG_NODE_TYPE_SEQUENCER;
*subdata = seq->name; // xxx?
return true;
}
-
- if (prop) {
- /* All unknown data effectively falls under "parameter evaluation" */
- *type = DEPSNODE_TYPE_PARAMETERS;
+ else if (ptr->type == &RNA_Curve) {
+ *id = (ID *)ptr->id.data;
+ *type = DEG_NODE_TYPE_GEOMETRY;
+ return true;
+ }
+ if (prop != NULL) {
+ /* All unknown data effectively falls under "parameter evaluation". */
+ if (RNA_property_is_idprop(prop)) {
+ *type = DEG_NODE_TYPE_PARAMETERS;
+ *operation_code = DEG_OPCODE_ID_PROPERTY;
+ *operation_name = RNA_property_identifier((PropertyRNA *)prop);
+ *operation_name_tag = -1;
+ }
+ else {
+ *type = DEG_NODE_TYPE_PARAMETERS;
+ *operation_code = DEG_OPCODE_PARAMETERS_EVAL;
+ *operation_name = "";
+ *operation_name_tag = -1;
+ }
return true;
}
-
return false;
}
@@ -238,20 +243,32 @@ DepsNode *Depsgraph::find_node_from_pointer(const PointerRNA *ptr,
const PropertyRNA *prop) const
{
ID *id;
- eDepsNode_Type type;
- const char *name;
-
- /* Get querying conditions. */
- if (pointer_to_id_node_criteria(ptr, prop, &id)) {
- return find_id_node(id);
- }
- else if (pointer_to_component_node_criteria(ptr, prop, &id, &type, &name)) {
+ eDepsNode_Type node_type;
+ const char *component_name, *operation_name;
+ eDepsOperation_Code operation_code;
+ int operation_name_tag;
+
+ if (pointer_to_component_node_criteria(
+ ptr, prop,
+ &id, &node_type, &component_name,
+ &operation_code, &operation_name, &operation_name_tag))
+ {
IDDepsNode *id_node = find_id_node(id);
- if (id_node != NULL) {
- return id_node->find_component(type, name);
+ if (id_node == NULL) {
+ return NULL;
}
+ ComponentDepsNode *comp_node =
+ id_node->find_component(node_type, component_name);
+ if (comp_node == NULL) {
+ return NULL;
+ }
+ if (operation_code == DEG_OPCODE_OPERATION) {
+ return comp_node;
+ }
+ return comp_node->find_operation(operation_code,
+ operation_name,
+ operation_name_tag);
}
-
return NULL;
}
@@ -263,72 +280,18 @@ static void id_node_deleter(void *value)
OBJECT_GUARDED_DELETE(id_node, IDDepsNode);
}
-RootDepsNode *Depsgraph::add_root_node()
-{
- if (!root_node) {
- DepsNodeFactory *factory = deg_get_node_factory(DEPSNODE_TYPE_ROOT);
- root_node = (RootDepsNode *)factory->create_node(NULL, "", "Root (Scene)");
- }
- return root_node;
-}
-
-TimeSourceDepsNode *Depsgraph::find_time_source(const ID *id) const
+TimeSourceDepsNode *Depsgraph::add_time_source()
{
- /* Search for one attached to a particular ID? */
- if (id) {
- /* Check if it was added as a component
- * (as may be done for subgraphs needing timeoffset).
- */
- IDDepsNode *id_node = find_id_node(id);
- if (id_node) {
- // XXX: review this
-// return id_node->find_component(DEPSNODE_TYPE_TIMESOURCE);
- }
- BLI_assert(!"Not implemented yet");
- }
- else {
- /* Use "official" timesource. */
- return root_node->time_source;
+ if (time_source == NULL) {
+ DepsNodeFactory *factory = deg_type_get_factory(DEG_NODE_TYPE_TIMESOURCE);
+ time_source = (TimeSourceDepsNode *)factory->create_node(NULL, "", "Time Source");
}
- return NULL;
-}
-
-SubgraphDepsNode *Depsgraph::add_subgraph_node(const ID *id)
-{
- DepsNodeFactory *factory = deg_get_node_factory(DEPSNODE_TYPE_SUBGRAPH);
- SubgraphDepsNode *subgraph_node =
- (SubgraphDepsNode *)factory->create_node(id, "", id->name + 2);
-
- /* Add to subnodes list. */
- BLI_gset_insert(subgraphs, subgraph_node);
-
- /* if there's an ID associated, add to ID-nodes lookup too */
- if (id) {
-#if 0
- /* XXX subgraph node is NOT a true IDDepsNode - what is this supposed to do? */
- // TODO: what to do if subgraph's ID has already been added?
- BLI_assert(!graph->find_id_node(id));
- graph->id_hash[id] = this;
-#endif
- }
-
- return subgraph_node;
-}
-
-void Depsgraph::remove_subgraph_node(SubgraphDepsNode *subgraph_node)
-{
- BLI_gset_remove(subgraphs, subgraph_node, NULL);
- OBJECT_GUARDED_DELETE(subgraph_node, SubgraphDepsNode);
+ return time_source;
}
-void Depsgraph::clear_subgraph_nodes()
+TimeSourceDepsNode *Depsgraph::find_time_source() const
{
- GSET_FOREACH_BEGIN(SubgraphDepsNode *, subgraph_node, subgraphs)
- {
- OBJECT_GUARDED_DELETE(subgraph_node, SubgraphDepsNode);
- }
- GSET_FOREACH_END();
- BLI_gset_clear(subgraphs, NULL);
+ return time_source;
}
IDDepsNode *Depsgraph::find_id_node(const ID *id) const
@@ -340,45 +303,43 @@ IDDepsNode *Depsgraph::add_id_node(ID *id, const char *name)
{
IDDepsNode *id_node = find_id_node(id);
if (!id_node) {
- DepsNodeFactory *factory = deg_get_node_factory(DEPSNODE_TYPE_ID_REF);
+ DepsNodeFactory *factory = deg_type_get_factory(DEG_NODE_TYPE_ID_REF);
id_node = (IDDepsNode *)factory->create_node(id, "", name);
- id->tag |= LIB_TAG_DOIT;
/* register */
BLI_ghash_insert(id_hash, id, id_node);
+ id_nodes.push_back(id_node);
}
return id_node;
}
-void Depsgraph::remove_id_node(const ID *id)
-{
- IDDepsNode *id_node = find_id_node(id);
- if (id_node) {
- /* unregister */
- BLI_ghash_remove(id_hash, id, NULL, NULL);
- OBJECT_GUARDED_DELETE(id_node, IDDepsNode);
- }
-}
-
void Depsgraph::clear_id_nodes()
{
BLI_ghash_clear(id_hash, NULL, id_node_deleter);
+ id_nodes.clear();
}
/* Add new relationship between two nodes. */
DepsRelation *Depsgraph::add_new_relation(OperationDepsNode *from,
OperationDepsNode *to,
- eDepsRelation_Type type,
- const char *description)
+ const char *description,
+ bool check_unique)
{
+ DepsRelation *rel = NULL;
+ if (check_unique) {
+ rel = check_nodes_connected(from, to, description);
+ }
+ if (rel != NULL) {
+ return rel;
+ }
/* Create new relation, and add it to the graph. */
- DepsRelation *rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, type, description);
+ rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, description);
/* TODO(sergey): Find a better place for this. */
#ifdef WITH_OPENSUBDIV
ComponentDepsNode *comp_node = from->owner;
- if (comp_node->type == DEPSNODE_TYPE_GEOMETRY) {
+ if (comp_node->type == DEG_NODE_TYPE_GEOMETRY) {
IDDepsNode *id_to = to->owner->owner;
IDDepsNode *id_from = from->owner->owner;
- if (id_to != id_from && (id_to->id->tag & LIB_TAG_ID_RECALC_ALL)) {
+ if (id_to != id_from && (id_to->id->recalc & ID_RECALC_ALL)) {
if ((id_from->eval_flags & DAG_EVAL_NEED_CPU) == 0) {
id_from->tag_update(this);
id_from->eval_flags |= DAG_EVAL_NEED_CPU;
@@ -391,45 +352,49 @@ DepsRelation *Depsgraph::add_new_relation(OperationDepsNode *from,
/* Add new relation between two nodes */
DepsRelation *Depsgraph::add_new_relation(DepsNode *from, DepsNode *to,
- eDepsRelation_Type type,
- const char *description)
+ const char *description,
+ bool check_unique)
{
+ DepsRelation *rel = NULL;
+ if (check_unique) {
+ rel = check_nodes_connected(from, to, description);
+ }
+ if (rel != NULL) {
+ return rel;
+ }
/* Create new relation, and add it to the graph. */
- DepsRelation *rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, type, description);
+ rel = OBJECT_GUARDED_NEW(DepsRelation, from, to, description);
return rel;
}
+DepsRelation *Depsgraph::check_nodes_connected(const DepsNode *from,
+ const DepsNode *to,
+ const char *description)
+{
+ foreach (DepsRelation *rel, from->outlinks) {
+ BLI_assert(rel->from == from);
+ if (rel->to != to) {
+ continue;
+ }
+ if (description != NULL && !STREQ(rel->name, description)) {
+ continue;
+ }
+ return rel;
+ }
+ return NULL;
+}
+
/* ************************ */
/* Relationships Management */
DepsRelation::DepsRelation(DepsNode *from,
DepsNode *to,
- eDepsRelation_Type type,
const char *description)
: from(from),
to(to),
name(description),
- type(type),
flag(0)
{
-#ifndef NDEBUG
-/*
- for (OperationDepsNode::Relations::const_iterator it = from->outlinks.begin();
- it != from->outlinks.end();
- ++it)
- {
- DepsRelation *rel = *it;
- if (rel->from == from &&
- rel->to == to &&
- rel->type == type &&
- rel->name == description)
- {
- BLI_assert(!"Duplicated relation, should not happen!");
- }
- }
-*/
-#endif
-
/* Hook it up to the nodes which use it.
*
* NOTE: We register relation in the nodes which this link connects to here
@@ -451,7 +416,15 @@ DepsRelation::DepsRelation(DepsNode *from,
DepsRelation::~DepsRelation()
{
/* Sanity check. */
- BLI_assert(this->from && this->to);
+ BLI_assert(from != NULL && to != NULL);
+}
+
+void DepsRelation::unlink()
+{
+ /* Sanity check. */
+ BLI_assert(from != NULL && to != NULL);
+ remove_from_vector(&from->outlinks, this);
+ remove_from_vector(&to->inlinks, this);
}
/* Low level tagging -------------------------------------- */
@@ -472,11 +445,9 @@ void Depsgraph::add_entry_tag(OperationDepsNode *node)
void Depsgraph::clear_all_nodes()
{
clear_id_nodes();
- clear_subgraph_nodes();
- BLI_ghash_clear(id_hash, NULL, NULL);
- if (this->root_node) {
- OBJECT_GUARDED_DELETE(this->root_node, RootDepsNode);
- root_node = NULL;
+ if (time_source != NULL) {
+ OBJECT_GUARDED_DELETE(time_source, TimeSourceDepsNode);
+ time_source = NULL;
}
}
@@ -494,6 +465,31 @@ void deg_editors_scene_update(Main *bmain, Scene *scene, bool updated)
}
}
+bool deg_terminal_do_color(void)
+{
+ return (G.debug & G_DEBUG_DEPSGRAPH_PRETTY) != 0;
+}
+
+string deg_color_for_pointer(const void *pointer)
+{
+ if (!deg_terminal_do_color()) {
+ return "";
+ }
+ int r, g, b;
+ BLI_hash_pointer_to_color(pointer, &r, &g, &b);
+ char buffer[64];
+ BLI_snprintf(buffer, sizeof(buffer), TRUECOLOR_ANSI_COLOR_FORMAT, r, g, b);
+ return string(buffer);
+}
+
+string deg_color_end(void)
+{
+ if (!deg_terminal_do_color()) {
+ return "";
+ }
+ return string(TRUECOLOR_ANSI_COLOR_FINISH);
+}
+
} // namespace DEG
/* **************** */
@@ -530,3 +526,93 @@ void DEG_editors_update_pre(Main *bmain, Scene *scene, bool time)
DEG::deg_editor_update_scene_pre_cb(bmain, scene, time);
}
}
+
+/* Evaluation and debug */
+
+void DEG_debug_print_eval(const char *function_name,
+ const char *object_name,
+ const void *object_address)
+{
+ if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
+ return;
+ }
+ fprintf(stdout,
+ "%s on %s %s(%p)%s\n",
+ function_name,
+ object_name,
+ DEG::deg_color_for_pointer(object_address).c_str(),
+ object_address,
+ DEG::deg_color_end().c_str());
+ fflush(stdout);
+}
+
+void DEG_debug_print_eval_subdata(const char *function_name,
+ const char *object_name,
+ const void *object_address,
+ const char *subdata_comment,
+ const char *subdata_name,
+ const void *subdata_address)
+{
+ if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
+ return;
+ }
+ fprintf(stdout,
+ "%s on %s %s(%p)%s %s %s %s(%p)%s\n",
+ function_name,
+ object_name,
+ DEG::deg_color_for_pointer(object_address).c_str(),
+ object_address,
+ DEG::deg_color_end().c_str(),
+ subdata_comment,
+ subdata_name,
+ DEG::deg_color_for_pointer(subdata_address).c_str(),
+ subdata_address,
+ DEG::deg_color_end().c_str());
+ fflush(stdout);
+}
+
+void DEG_debug_print_eval_subdata_index(const char *function_name,
+ const char *object_name,
+ const void *object_address,
+ const char *subdata_comment,
+ const char *subdata_name,
+ const void *subdata_address,
+ const int subdata_index)
+{
+ if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
+ return;
+ }
+ fprintf(stdout,
+ "%s on %s %s(%p)^%s %s %s[%d] %s(%p)%s\n",
+ function_name,
+ object_name,
+ DEG::deg_color_for_pointer(object_address).c_str(),
+ object_address,
+ DEG::deg_color_end().c_str(),
+ subdata_comment,
+ subdata_name,
+ subdata_index,
+ DEG::deg_color_for_pointer(subdata_address).c_str(),
+ subdata_address,
+ DEG::deg_color_end().c_str());
+ fflush(stdout);
+}
+
+void DEG_debug_print_eval_time(const char *function_name,
+ const char *object_name,
+ const void *object_address,
+ float time)
+{
+ if ((G.debug & G_DEBUG_DEPSGRAPH_EVAL) == 0) {
+ return;
+ }
+ fprintf(stdout,
+ "%s on %s %s(%p)%s at time %f\n",
+ function_name,
+ object_name,
+ DEG::deg_color_for_pointer(object_address).c_str(),
+ object_address,
+ DEG::deg_color_end().c_str(),
+ time);
+ fflush(stdout);
+}
diff --git a/source/blender/depsgraph/intern/depsgraph.h b/source/blender/depsgraph/intern/depsgraph.h
index e668facd645..dda4da7bc13 100644
--- a/source/blender/depsgraph/intern/depsgraph.h
+++ b/source/blender/depsgraph/intern/depsgraph.h
@@ -49,10 +49,8 @@ struct PropertyRNA;
namespace DEG {
struct DepsNode;
-struct RootDepsNode;
struct TimeSourceDepsNode;
struct IDDepsNode;
-struct SubgraphDepsNode;
struct ComponentDepsNode;
struct OperationDepsNode;
@@ -61,13 +59,12 @@ struct OperationDepsNode;
/* Settings/Tags on Relationship */
typedef enum eDepsRelation_Flag {
- /* "touched" tag is used when filtering, to know which to collect */
- DEPSREL_FLAG_TEMP_TAG = (1 << 0),
-
/* "cyclic" link - when detecting cycles, this relationship was the one
- * which triggers a cyclic relationship to exist in the graph
+ * which triggers a cyclic relationship to exist in the graph.
*/
- DEPSREL_FLAG_CYCLIC = (1 << 1),
+ DEPSREL_FLAG_CYCLIC = (1 << 0),
+ /* Update flush will not go through this relation. */
+ DEPSREL_FLAG_NO_FLUSH = (1 << 1),
} eDepsRelation_Flag;
/* B depends on A (A -> B) */
@@ -79,15 +76,15 @@ struct DepsRelation {
/* relationship attributes */
const char *name; /* label for debugging */
- eDepsRelation_Type type; /* type */
int flag; /* (eDepsRelation_Flag) */
DepsRelation(DepsNode *from,
DepsNode *to,
- eDepsRelation_Type type,
const char *description);
~DepsRelation();
+
+ void unlink();
};
/* ********* */
@@ -95,7 +92,9 @@ struct DepsRelation {
/* Dependency Graph object */
struct Depsgraph {
+ // TODO(sergey): Go away from C++ container and use some native BLI.
typedef vector<OperationDepsNode *> OperationNodes;
+ typedef vector<IDDepsNode *> IDDepsNodes;
Depsgraph();
~Depsgraph();
@@ -111,29 +110,31 @@ struct Depsgraph {
*/
DepsNode *find_node_from_pointer(const PointerRNA *ptr, const PropertyRNA *prop) const;
- RootDepsNode *add_root_node();
-
- TimeSourceDepsNode *find_time_source(const ID *id = NULL) const;
-
- SubgraphDepsNode *add_subgraph_node(const ID *id);
- void remove_subgraph_node(SubgraphDepsNode *subgraph_node);
- void clear_subgraph_nodes();
+ TimeSourceDepsNode *add_time_source();
+ TimeSourceDepsNode *find_time_source() const;
IDDepsNode *find_id_node(const ID *id) const;
IDDepsNode *add_id_node(ID *id, const char *name = "");
- void remove_id_node(const ID *id);
void clear_id_nodes();
/* Add new relationship between two nodes. */
DepsRelation *add_new_relation(OperationDepsNode *from,
OperationDepsNode *to,
- eDepsRelation_Type type,
- const char *description);
+ const char *description,
+ bool check_unique = false);
DepsRelation *add_new_relation(DepsNode *from,
DepsNode *to,
- eDepsRelation_Type type,
- const char *description);
+ const char *description,
+ bool check_unique = false);
+
+ /* Check whether two nodes are connected by relation with given
+ * description. Description might be NULL to check ANY relation between
+ * given nodes.
+ */
+ DepsRelation *check_nodes_connected(const DepsNode *from,
+ const DepsNode *to,
+ const char *description);
/* Tag a specific node as needing updates. */
void add_entry_tag(OperationDepsNode *node);
@@ -143,15 +144,19 @@ struct Depsgraph {
/* Core Graph Functionality ........... */
- /* <ID : IDDepsNode> mapping from ID blocks to nodes representing these blocks
- * (for quick lookups). */
+ /* <ID : IDDepsNode> mapping from ID blocks to nodes representing these
+ * blocks, used for quick lookups.
+ */
GHash *id_hash;
- /* "root" node - the one where all evaluation enters from. */
- RootDepsNode *root_node;
+ /* Ordered list of ID nodes, order matches ID allocation order.
+ * Used for faster iteration, especially for areas which are critical to
+ * keep exact order of iteration.
+ */
+ IDDepsNodes id_nodes;
- /* Subgraphs referenced in tree. */
- GSet *subgraphs;
+ /* Top-level time source node. */
+ TimeSourceDepsNode *time_source;
/* Indicates whether relations needs to be updated. */
bool need_update;
diff --git a/source/blender/depsgraph/intern/depsgraph_build.cc b/source/blender/depsgraph/intern/depsgraph_build.cc
index 3a69469053c..1b270e71d64 100644
--- a/source/blender/depsgraph/intern/depsgraph_build.cc
+++ b/source/blender/depsgraph/intern/depsgraph_build.cc
@@ -32,33 +32,28 @@
#include "MEM_guardedalloc.h"
-// #define DEBUG_TIME
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+
+#include "PIL_time.h"
+#include "PIL_time_utildefines.h"
extern "C" {
#include "DNA_cachefile_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
-#include "DNA_object_force.h"
-
-#include "BLI_utildefines.h"
-#include "BLI_ghash.h"
-
-#ifdef DEBUG_TIME
-# include "PIL_time.h"
-# include "PIL_time_utildefines.h"
-#endif
+#include "DNA_object_force_types.h"
#include "BKE_main.h"
#include "BKE_collision.h"
#include "BKE_effect.h"
#include "BKE_modifier.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_debug.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
-
#include "builder/deg_builder.h"
#include "builder/deg_builder_cycle.h"
#include "builder/deg_builder_nodes.h"
@@ -67,6 +62,7 @@ extern "C" {
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_types.h"
@@ -81,29 +77,29 @@ static DEG::eDepsNode_Type deg_build_scene_component_type(
eDepsSceneComponentType component)
{
switch (component) {
- case DEG_SCENE_COMP_PARAMETERS: return DEG::DEPSNODE_TYPE_PARAMETERS;
- case DEG_SCENE_COMP_ANIMATION: return DEG::DEPSNODE_TYPE_ANIMATION;
- case DEG_SCENE_COMP_SEQUENCER: return DEG::DEPSNODE_TYPE_SEQUENCER;
+ case DEG_SCENE_COMP_PARAMETERS: return DEG::DEG_NODE_TYPE_PARAMETERS;
+ case DEG_SCENE_COMP_ANIMATION: return DEG::DEG_NODE_TYPE_ANIMATION;
+ case DEG_SCENE_COMP_SEQUENCER: return DEG::DEG_NODE_TYPE_SEQUENCER;
}
- return DEG::DEPSNODE_TYPE_UNDEFINED;
+ return DEG::DEG_NODE_TYPE_UNDEFINED;
}
static DEG::eDepsNode_Type deg_build_object_component_type(
eDepsObjectComponentType component)
{
switch (component) {
- case DEG_OB_COMP_PARAMETERS: return DEG::DEPSNODE_TYPE_PARAMETERS;
- case DEG_OB_COMP_PROXY: return DEG::DEPSNODE_TYPE_PROXY;
- case DEG_OB_COMP_ANIMATION: return DEG::DEPSNODE_TYPE_ANIMATION;
- case DEG_OB_COMP_TRANSFORM: return DEG::DEPSNODE_TYPE_TRANSFORM;
- case DEG_OB_COMP_GEOMETRY: return DEG::DEPSNODE_TYPE_GEOMETRY;
- case DEG_OB_COMP_EVAL_POSE: return DEG::DEPSNODE_TYPE_EVAL_POSE;
- case DEG_OB_COMP_BONE: return DEG::DEPSNODE_TYPE_BONE;
- case DEG_OB_COMP_EVAL_PARTICLES: return DEG::DEPSNODE_TYPE_EVAL_PARTICLES;
- case DEG_OB_COMP_SHADING: return DEG::DEPSNODE_TYPE_SHADING;
- case DEG_OB_COMP_CACHE: return DEG::DEPSNODE_TYPE_CACHE;
+ case DEG_OB_COMP_PARAMETERS: return DEG::DEG_NODE_TYPE_PARAMETERS;
+ case DEG_OB_COMP_PROXY: return DEG::DEG_NODE_TYPE_PROXY;
+ case DEG_OB_COMP_ANIMATION: return DEG::DEG_NODE_TYPE_ANIMATION;
+ case DEG_OB_COMP_TRANSFORM: return DEG::DEG_NODE_TYPE_TRANSFORM;
+ case DEG_OB_COMP_GEOMETRY: return DEG::DEG_NODE_TYPE_GEOMETRY;
+ case DEG_OB_COMP_EVAL_POSE: return DEG::DEG_NODE_TYPE_EVAL_POSE;
+ case DEG_OB_COMP_BONE: return DEG::DEG_NODE_TYPE_BONE;
+ case DEG_OB_COMP_EVAL_PARTICLES: return DEG::DEG_NODE_TYPE_EVAL_PARTICLES;
+ case DEG_OB_COMP_SHADING: return DEG::DEG_NODE_TYPE_SHADING;
+ case DEG_OB_COMP_CACHE: return DEG::DEG_NODE_TYPE_CACHE;
}
- return DEG::DEPSNODE_TYPE_UNDEFINED;
+ return DEG::DEG_NODE_TYPE_UNDEFINED;
}
static DEG::DepsNodeHandle *get_handle(DepsNodeHandle *handle)
@@ -121,21 +117,19 @@ void DEG_add_scene_relation(DepsNodeHandle *handle,
DEG::DepsNodeHandle *deg_handle = get_handle(handle);
deg_handle->builder->add_node_handle_relation(comp_key,
deg_handle,
- DEG::DEPSREL_TYPE_GEOMETRY_EVAL,
description);
}
void DEG_add_object_relation(DepsNodeHandle *handle,
- Object *ob,
+ Object *object,
eDepsObjectComponentType component,
const char *description)
{
DEG::eDepsNode_Type type = deg_build_object_component_type(component);
- DEG::ComponentKey comp_key(&ob->id, type);
+ DEG::ComponentKey comp_key(&object->id, type);
DEG::DepsNodeHandle *deg_handle = get_handle(handle);
deg_handle->builder->add_node_handle_relation(comp_key,
deg_handle,
- DEG::DEPSREL_TYPE_GEOMETRY_EVAL,
description);
}
@@ -149,28 +143,33 @@ void DEG_add_object_cache_relation(DepsNodeHandle *handle,
DEG::DepsNodeHandle *deg_handle = get_handle(handle);
deg_handle->builder->add_node_handle_relation(comp_key,
deg_handle,
- DEG::DEPSREL_TYPE_CACHE,
description);
}
void DEG_add_bone_relation(DepsNodeHandle *handle,
- Object *ob,
+ Object *object,
const char *bone_name,
eDepsObjectComponentType component,
const char *description)
{
DEG::eDepsNode_Type type = deg_build_object_component_type(component);
- DEG::ComponentKey comp_key(&ob->id, type, bone_name);
+ DEG::ComponentKey comp_key(&object->id, type, bone_name);
DEG::DepsNodeHandle *deg_handle = get_handle(handle);
/* XXX: "Geometry Eval" might not always be true, but this only gets called
* from modifier building now.
*/
deg_handle->builder->add_node_handle_relation(comp_key,
deg_handle,
- DEG::DEPSREL_TYPE_GEOMETRY_EVAL,
description);
}
+struct Depsgraph *DEG_get_graph_from_handle(struct DepsNodeHandle *handle)
+{
+ DEG::DepsNodeHandle *deg_handle = get_handle(handle);
+ DEG::DepsgraphRelationBuilder *relation_builder = deg_handle->builder;
+ return reinterpret_cast<Depsgraph *>(relation_builder->getGraph());
+}
+
void DEG_add_special_eval_flag(Depsgraph *graph, ID *id, short flag)
{
DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(graph);
@@ -197,39 +196,24 @@ void DEG_add_special_eval_flag(Depsgraph *graph, ID *id, short flag)
*/
void DEG_graph_build_from_scene(Depsgraph *graph, Main *bmain, Scene *scene)
{
-#ifdef DEBUG_TIME
- TIMEIT_START(DEG_graph_build_from_scene);
-#endif
+ double start_time;
+ if (G.debug & G_DEBUG_DEPSGRAPH_BUILD) {
+ start_time = PIL_check_seconds_timer();
+ }
DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(graph);
/* 1) Generate all the nodes in the graph first */
DEG::DepsgraphNodeBuilder node_builder(bmain, deg_graph);
- /* create root node for scene first
- * - this way it should be the first in the graph,
- * reflecting its role as the entrypoint
- */
- node_builder.begin_build(bmain);
- node_builder.add_root_node();
- node_builder.build_scene(bmain, scene);
+ node_builder.begin_build();
+ node_builder.build_scene(scene);
/* 2) Hook up relationships between operations - to determine evaluation
* order.
*/
- DEG::DepsgraphRelationBuilder relation_builder(deg_graph);
- /* Hook scene up to the root node as entrypoint to graph. */
- /* XXX what does this relation actually mean?
- * it doesnt add any operations anyway and is not clear what part of the
- * scene is to be connected.
- */
- relation_builder.begin_build(bmain);
-#if 0
- relation_builder.add_relation(RootKey(),
- IDKey(scene),
- DEPSREL_TYPE_ROOT_TO_ACTIVE,
- "Root to Active Scene");
-#endif
- relation_builder.build_scene(bmain, scene);
+ DEG::DepsgraphRelationBuilder relation_builder(bmain, deg_graph);
+ relation_builder.begin_build();
+ relation_builder.build_scene(scene);
/* Detect and solve cycles. */
DEG::deg_graph_detect_cycles(deg_graph);
@@ -253,9 +237,10 @@ void DEG_graph_build_from_scene(Depsgraph *graph, Main *bmain, Scene *scene)
}
#endif
-#ifdef DEBUG_TIME
- TIMEIT_END(DEG_graph_build_from_scene);
-#endif
+ if (G.debug & G_DEBUG_DEPSGRAPH_BUILD) {
+ printf("Depsgraph built in %f seconds.\n",
+ PIL_check_seconds_timer() - start_time);
+ }
}
/* Tag graph relations for update. */
@@ -328,7 +313,7 @@ void DEG_scene_graph_free(Scene *scene)
void DEG_add_collision_relations(DepsNodeHandle *handle,
Scene *scene,
- Object *ob,
+ Object *object,
Group *group,
int layer,
unsigned int modifier_type,
@@ -337,7 +322,7 @@ void DEG_add_collision_relations(DepsNodeHandle *handle,
const char *name)
{
unsigned int numcollobj;
- Object **collobjs = get_collisionobjects_ext(scene, ob, group, layer, &numcollobj, modifier_type, dupli);
+ Object **collobjs = get_collisionobjects_ext(scene, object, group, layer, &numcollobj, modifier_type, dupli);
for (unsigned int i = 0; i < numcollobj; i++) {
Object *ob1 = collobjs[i];
@@ -354,53 +339,48 @@ void DEG_add_collision_relations(DepsNodeHandle *handle,
void DEG_add_forcefield_relations(DepsNodeHandle *handle,
Scene *scene,
- Object *ob,
+ Object *object,
EffectorWeights *effector_weights,
bool add_absorption,
int skip_forcefield,
const char *name)
{
- ListBase *effectors = pdInitEffectors(scene, ob, NULL, effector_weights, false);
-
- if (effectors) {
- for (EffectorCache *eff = (EffectorCache*)effectors->first; eff; eff = eff->next) {
- if (eff->ob != ob && eff->pd->forcefield != skip_forcefield) {
- DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_TRANSFORM, name);
-
- if (eff->psys) {
- DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_EVAL_PARTICLES, name);
-
- /* TODO: remove this when/if EVAL_PARTICLES is sufficient
- * for up to date particles.
- */
- DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_GEOMETRY, name);
- }
-
- if (eff->pd->forcefield == PFIELD_SMOKEFLOW && eff->pd->f_source) {
- DEG_add_object_relation(handle,
- eff->pd->f_source,
- DEG_OB_COMP_TRANSFORM,
- "Smoke Force Domain");
- DEG_add_object_relation(handle,
- eff->pd->f_source,
- DEG_OB_COMP_GEOMETRY,
- "Smoke Force Domain");
- }
-
- if (add_absorption && (eff->pd->flag & PFIELD_VISIBILITY)) {
- DEG_add_collision_relations(handle,
- scene,
- ob,
- NULL,
- eff->ob->lay,
- eModifierType_Collision,
- NULL,
- true,
- "Force Absorption");
- }
+ ListBase *effectors = pdInitEffectors(scene, object, NULL, effector_weights, false);
+ if (effectors == NULL) {
+ return;
+ }
+ for (EffectorCache *eff = (EffectorCache*)effectors->first; eff; eff = eff->next) {
+ if (eff->ob != object && eff->pd->forcefield != skip_forcefield) {
+ DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_TRANSFORM, name);
+ if (eff->psys) {
+ DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_EVAL_PARTICLES, name);
+ /* TODO: remove this when/if EVAL_PARTICLES is sufficient
+ * for up to date particles.
+ */
+ DEG_add_object_relation(handle, eff->ob, DEG_OB_COMP_GEOMETRY, name);
+ }
+ if (eff->pd->forcefield == PFIELD_SMOKEFLOW && eff->pd->f_source) {
+ DEG_add_object_relation(handle,
+ eff->pd->f_source,
+ DEG_OB_COMP_TRANSFORM,
+ "Smoke Force Domain");
+ DEG_add_object_relation(handle,
+ eff->pd->f_source,
+ DEG_OB_COMP_GEOMETRY,
+ "Smoke Force Domain");
+ }
+ if (add_absorption && (eff->pd->flag & PFIELD_VISIBILITY)) {
+ DEG_add_collision_relations(handle,
+ scene,
+ object,
+ NULL,
+ eff->ob->lay,
+ eModifierType_Collision,
+ NULL,
+ true,
+ "Force Absorption");
}
}
}
-
pdEndEffectors(&effectors);
}
diff --git a/source/blender/depsgraph/intern/depsgraph_debug.cc b/source/blender/depsgraph/intern/depsgraph_debug.cc
index d3b48930779..b7bf63e0cb0 100644
--- a/source/blender/depsgraph/intern/depsgraph_debug.cc
+++ b/source/blender/depsgraph/intern/depsgraph_debug.cc
@@ -35,35 +35,17 @@
extern "C" {
#include "DNA_scene_types.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
#include "DEG_depsgraph_debug.h"
#include "DEG_depsgraph_build.h"
-} /* extern "C" */
-#include "intern/eval/deg_eval_debug.h"
#include "intern/depsgraph_intern.h"
-#include "util/deg_util_foreach.h"
-
-/* ************************************************ */
-
-DepsgraphStats *DEG_stats(void)
-{
- return DEG::DepsgraphDebug::stats;
-}
+#include "intern/nodes/deg_node_id.h"
+#include "intern/nodes/deg_node_time.h"
-void DEG_stats_verify()
-{
- DEG::DepsgraphDebug::verify_stats();
-}
-
-DepsgraphStatsID *DEG_stats_id(ID *id)
-{
- if (!DEG::DepsgraphDebug::stats) {
- return NULL;
- }
- return DEG::DepsgraphDebug::get_id_stats(id, false);
-}
+#include "util/deg_util_foreach.h"
bool DEG_debug_compare(const struct Depsgraph *graph1,
const struct Depsgraph *graph2)
@@ -165,7 +147,7 @@ bool DEG_debug_consistency_check(Depsgraph *graph)
return false;
}
foreach (DEG::DepsRelation *rel, node->outlinks) {
- if (rel->to->type == DEG::DEPSNODE_TYPE_OPERATION) {
+ if (rel->to->type == DEG::DEG_NODE_TYPE_OPERATION) {
DEG::OperationDepsNode *to = (DEG::OperationDepsNode *)rel->to;
BLI_assert(to->num_links_pending < to->inlinks.size());
++to->num_links_pending;
@@ -177,7 +159,7 @@ bool DEG_debug_consistency_check(Depsgraph *graph)
foreach (DEG::OperationDepsNode *node, deg_graph->operations) {
int num_links_pending = 0;
foreach (DEG::DepsRelation *rel, node->inlinks) {
- if (rel->from->type == DEG::DEPSNODE_TYPE_OPERATION) {
+ if (rel->from->type == DEG::DEG_NODE_TYPE_OPERATION) {
++num_links_pending;
}
}
@@ -218,8 +200,7 @@ void DEG_stats_simple(const Depsgraph *graph, size_t *r_outer,
size_t tot_outer = 0;
size_t tot_rels = 0;
- GHASH_FOREACH_BEGIN(DEG::IDDepsNode *, id_node, deg_graph->id_hash)
- {
+ foreach (DEG::IDDepsNode *id_node, deg_graph->id_nodes) {
tot_outer++;
GHASH_FOREACH_BEGIN(DEG::ComponentDepsNode *, comp_node, id_node->components)
{
@@ -230,9 +211,8 @@ void DEG_stats_simple(const Depsgraph *graph, size_t *r_outer,
}
GHASH_FOREACH_END();
}
- GHASH_FOREACH_END();
- DEG::TimeSourceDepsNode *time_source = deg_graph->find_time_source(NULL);
+ DEG::TimeSourceDepsNode *time_source = deg_graph->find_time_source();
if (time_source != NULL) {
tot_rels += time_source->inlinks.size();
}
diff --git a/source/blender/depsgraph/intern/depsgraph_eval.cc b/source/blender/depsgraph/intern/depsgraph_eval.cc
index c41f28b07e8..a6bdcdca19d 100644
--- a/source/blender/depsgraph/intern/depsgraph_eval.cc
+++ b/source/blender/depsgraph/intern/depsgraph_eval.cc
@@ -32,23 +32,24 @@
#include "MEM_guardedalloc.h"
-extern "C" {
-#include "DNA_scene_types.h"
-
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
+extern "C" {
+#include "DNA_scene_types.h"
+
#include "BKE_depsgraph.h"
#include "BKE_scene.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
-} /* extern "C" */
#include "intern/eval/deg_eval.h"
#include "intern/eval/deg_eval_flush.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_operation.h"
+#include "intern/nodes/deg_node_time.h"
#include "intern/depsgraph.h"
@@ -56,9 +57,6 @@ extern "C" {
static bool use_legacy_depsgraph = true;
#endif
-/* Unfinished and unused, and takes quite some pre-processing time. */
-#undef USE_EVAL_PRIORITY
-
bool DEG_depsgraph_use_legacy(void)
{
#ifdef DISABLE_NEW_DEPSGRAPH
@@ -157,5 +155,5 @@ void DEG_evaluate_on_framechange(EvaluationContext *eval_ctx,
bool DEG_needs_eval(Depsgraph *graph)
{
DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(graph);
- return BLI_gset_size(deg_graph->entry_tags) != 0;
+ return BLI_gset_len(deg_graph->entry_tags) != 0;
}
diff --git a/source/blender/depsgraph/intern/depsgraph_intern.h b/source/blender/depsgraph/intern/depsgraph_intern.h
index 2d8e7dc841c..89432e17f87 100644
--- a/source/blender/depsgraph/intern/depsgraph_intern.h
+++ b/source/blender/depsgraph/intern/depsgraph_intern.h
@@ -59,8 +59,8 @@ namespace DEG {
/* Typeinfo Struct (nti) */
struct DepsNodeFactory {
virtual eDepsNode_Type type() const = 0;
- virtual eDepsNode_Class tclass() const = 0;
virtual const char *tname() const = 0;
+ virtual int id_recalc_tag() const = 0;
virtual DepsNode *create_node(const ID *id,
const char *subdata,
@@ -70,8 +70,8 @@ struct DepsNodeFactory {
template <class NodeType>
struct DepsNodeFactoryImpl : public DepsNodeFactory {
eDepsNode_Type type() const { return NodeType::typeinfo.type; }
- eDepsNode_Class tclass() const { return NodeType::typeinfo.tclass; }
const char *tname() const { return NodeType::typeinfo.tname; }
+ int id_recalc_tag() const { return NodeType::typeinfo.id_recalc_tag; }
DepsNode *create_node(const ID *id, const char *subdata, const char *name) const
{
@@ -79,7 +79,6 @@ struct DepsNodeFactoryImpl : public DepsNodeFactory {
/* populate base node settings */
node->type = type();
- node->tclass = tclass();
if (name[0] != '\0') {
/* set name if provided ... */
@@ -102,10 +101,7 @@ struct DepsNodeFactoryImpl : public DepsNodeFactory {
void deg_register_node_typeinfo(DepsNodeFactory *factory);
/* Get typeinfo for specified type */
-DepsNodeFactory *deg_get_node_factory(const eDepsNode_Type type);
-
-/* Get typeinfo for provided node */
-DepsNodeFactory *deg_node_get_factory(const DepsNode *node);
+DepsNodeFactory *deg_type_get_factory(const eDepsNode_Type type);
/* Editors Integration -------------------------------------------------- */
@@ -113,11 +109,15 @@ void deg_editors_id_update(struct Main *bmain, struct ID *id);
void deg_editors_scene_update(struct Main *bmain, struct Scene *scene, bool updated);
-#define DEG_DEBUG_PRINTF(...) \
+#define DEG_DEBUG_PRINTF(type, ...) \
do { \
- if (G.debug & G_DEBUG_DEPSGRAPH) { \
+ if (G.debug & G_DEBUG_DEPSGRAPH_ ## type) { \
fprintf(stderr, __VA_ARGS__); \
} \
} while (0)
+bool deg_terminal_do_color(void);
+string deg_color_for_pointer(const void *pointer);
+string deg_color_end(void);
+
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/depsgraph_query.cc b/source/blender/depsgraph/intern/depsgraph_query.cc
index 7f2f6a65f5e..9b1961baa48 100644
--- a/source/blender/depsgraph/intern/depsgraph_query.cc
+++ b/source/blender/depsgraph/intern/depsgraph_query.cc
@@ -35,11 +35,12 @@
extern "C" {
#include "BKE_idcode.h"
#include "BKE_main.h"
+} /* extern "C" */
#include "DEG_depsgraph_query.h"
-} /* extern "C" */
#include "intern/depsgraph_intern.h"
+#include "intern/nodes/deg_node_id.h"
bool DEG_id_type_tagged(Main *bmain, short idtype)
{
diff --git a/source/blender/depsgraph/intern/depsgraph_query_foreach.cc b/source/blender/depsgraph/intern/depsgraph_query_foreach.cc
new file mode 100644
index 00000000000..65d8f58b851
--- /dev/null
+++ b/source/blender/depsgraph/intern/depsgraph_query_foreach.cc
@@ -0,0 +1,148 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2017 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/depsgraph_query_foreach.cc
+ * \ingroup depsgraph
+ *
+ * Implementation of Querying and Filtering API's
+ */
+
+// TODO(sergey): Use some sort of wrapper.
+#include <deque>
+
+#include "MEM_guardedalloc.h"
+
+extern "C" {
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+} /* extern "C" */
+
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "DEG_depsgraph.h"
+#include "DEG_depsgraph_query.h"
+
+#include "intern/depsgraph_intern.h"
+
+#include "intern/nodes/deg_node.h"
+#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
+#include "intern/nodes/deg_node_operation.h"
+
+#include "util/deg_util_foreach.h"
+
+/* ************************ DEG TRAVERSAL ********************* */
+
+namespace DEG {
+
+typedef std::deque<OperationDepsNode *> TraversalQueue;
+
+static void deg_foreach_clear_flags(const Depsgraph *graph)
+{
+ foreach (OperationDepsNode *op_node, graph->operations) {
+ op_node->scheduled = false;
+ }
+ foreach (IDDepsNode *id_node, graph->id_nodes) {
+ id_node->done = false;
+ }
+}
+
+static void deg_foreach_dependent_ID(const Depsgraph *graph,
+ const ID *id,
+ DEGForeachIDCallback callback,
+ void *user_data)
+{
+ /* Start with getting ID node from the graph. */
+ IDDepsNode *id_node = graph->find_id_node(id);
+ if (id_node == NULL) {
+ /* TODO(sergey): Shall we inform or assert here about attempt to start
+ * iterating over non-existing ID?
+ */
+ return;
+ }
+ /* Make sure all runtime flags are ready and clear. */
+ deg_foreach_clear_flags(graph);
+ /* Start with scheduling all operations from ID node. */
+ TraversalQueue queue;
+ GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components)
+ {
+ foreach (OperationDepsNode *op_node, comp_node->operations) {
+ queue.push_back(op_node);
+ op_node->scheduled = true;
+ }
+ }
+ GHASH_FOREACH_END();
+ id_node->done = true;
+ /* Process the queue. */
+ while (!queue.empty()) {
+ /* get next operation node to process. */
+ OperationDepsNode *op_node = queue.front();
+ queue.pop_front();
+ for (;;) {
+ /* Check whether we need to inform callee about corresponding ID node. */
+ ComponentDepsNode *comp_node = op_node->owner;
+ IDDepsNode *id_node = comp_node->owner;
+ if (!id_node->done) {
+ /* TODO(sergey): Is it orig or CoW? */
+ callback(id_node->id, user_data);
+ id_node->done = true;
+ }
+ /* Schedule outgoing operation nodes. */
+ if (op_node->outlinks.size() == 1) {
+ OperationDepsNode *to_node = (OperationDepsNode *)op_node->outlinks[0]->to;
+ if (to_node->scheduled == false) {
+ to_node->scheduled = true;
+ op_node = to_node;
+ }
+ else {
+ break;
+ }
+ }
+ else {
+ foreach (DepsRelation *rel, op_node->outlinks) {
+ OperationDepsNode *to_node = (OperationDepsNode *)rel->to;
+ if (to_node->scheduled == false) {
+ queue.push_front(to_node);
+ to_node->scheduled = true;
+ }
+ }
+ break;
+ }
+ }
+ }
+}
+
+} // namespace DEG
+
+void DEG_foreach_dependent_ID(const Depsgraph *depsgraph,
+ const ID *id,
+ DEGForeachIDCallback callback, void *user_data)
+{
+ DEG::deg_foreach_dependent_ID((const DEG::Depsgraph *)depsgraph,
+ id,
+ callback, user_data);
+}
diff --git a/source/blender/depsgraph/intern/depsgraph_tag.cc b/source/blender/depsgraph/intern/depsgraph_tag.cc
index e8ed03666a6..948e4fc1f1b 100644
--- a/source/blender/depsgraph/intern/depsgraph_tag.cc
+++ b/source/blender/depsgraph/intern/depsgraph_tag.cc
@@ -34,15 +34,16 @@
#include <cstring> /* required for memset */
#include <queue>
-extern "C" {
#include "BLI_utildefines.h"
+#include "BLI_task.h"
+#include "BLI_listbase.h"
+extern "C" {
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_screen_types.h"
#include "DNA_windowmanager_types.h"
-#include "BLI_task.h"
#include "BKE_idcode.h"
#include "BKE_library.h"
@@ -52,14 +53,15 @@ extern "C" {
#define new new_
#include "BKE_screen.h"
#undef new
+} /* extern "C" */
#include "DEG_depsgraph.h"
-} /* extern "C" */
+#include "intern/builder/deg_builder.h"
#include "intern/eval/deg_eval_flush.h"
-
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_intern.h"
@@ -82,13 +84,13 @@ namespace {
void lib_id_recalc_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC;
+ id->recalc |= ID_RECALC;
DEG_id_type_tag(bmain, GS(id->name));
}
void lib_id_recalc_data_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC_DATA;
+ id->recalc |= ID_RECALC_DATA;
DEG_id_type_tag(bmain, GS(id->name));
}
@@ -108,7 +110,7 @@ void lib_id_recalc_tag_flag(Main *bmain, ID *id, int flag)
* nodes for update after relations update and after layer
* visibility changes.
*/
- short idtype = GS(id->name);
+ ID_Type idtype = GS(id->name);
if (idtype == ID_OB) {
Object *object = (Object *)id;
object->recalc |= (flag & OB_RECALC_ALL);
@@ -166,36 +168,6 @@ void DEG_graph_id_tag_update(Main *bmain, Depsgraph *graph, ID *id)
}
}
-/* Tag nodes related to a specific piece of data */
-void DEG_graph_data_tag_update(Depsgraph *graph, const PointerRNA *ptr)
-{
- DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(graph);
- DEG::DepsNode *node = deg_graph->find_node_from_pointer(ptr, NULL);
- if (node != NULL) {
- node->tag_update(deg_graph);
- }
- else {
- printf("Missing node in %s\n", __func__);
- BLI_assert(!"Shouldn't happens since it'll miss crucial update.");
- }
-}
-
-/* Tag nodes related to a specific property. */
-void DEG_graph_property_tag_update(Depsgraph *graph,
- const PointerRNA *ptr,
- const PropertyRNA *prop)
-{
- DEG::Depsgraph *deg_graph = reinterpret_cast<DEG::Depsgraph *>(graph);
- DEG::DepsNode *node = deg_graph->find_node_from_pointer(ptr, prop);
- if (node != NULL) {
- node->tag_update(deg_graph);
- }
- else {
- printf("Missing node in %s\n", __func__);
- BLI_assert(!"Shouldn't happens since it'll miss crucial update.");
- }
-}
-
/* Tag given ID for an update in all the dependency graphs. */
void DEG_id_tag_update(ID *id, short flag)
{
@@ -208,7 +180,7 @@ void DEG_id_tag_update_ex(Main *bmain, ID *id, short flag)
/* Ideally should not happen, but old depsgraph allowed this. */
return;
}
- DEG_DEBUG_PRINTF("%s: id=%s flag=%d\n", __func__, id->name, flag);
+ DEG_DEBUG_PRINTF(TAG, "%s: id=%s flag=%d\n", __func__, id->name, flag);
lib_id_recalc_tag_flag(bmain, id, flag);
for (Scene *scene = (Scene *)bmain->scene.first;
scene != NULL;
@@ -250,7 +222,7 @@ void DEG_id_tag_update_ex(Main *bmain, ID *id, short flag)
#endif
}
-/* Tag given ID type for update. */
+/* Mark a particular datablock type as having changing. */
void DEG_id_type_tag(Main *bmain, short idtype)
{
if (idtype == ID_NT) {
@@ -276,15 +248,20 @@ void DEG_ids_flush_tagged(Main *bmain)
scene != NULL;
scene = (Scene *)scene->id.next)
{
- /* TODO(sergey): Only visible scenes? */
- if (scene->depsgraph != NULL) {
- DEG::deg_graph_flush_updates(
- bmain,
- reinterpret_cast<DEG::Depsgraph *>(scene->depsgraph));
- }
+ DEG_scene_flush_update(bmain, scene);
}
}
+void DEG_scene_flush_update(Main *bmain, Scene *scene)
+{
+ if (scene->depsgraph == NULL) {
+ return;
+ }
+ DEG::deg_graph_flush_updates(
+ bmain,
+ reinterpret_cast<DEG::Depsgraph *>(scene->depsgraph));
+}
+
/* Update dependency graph when visible scenes/layers changes. */
void DEG_graph_on_visible_update(Main *bmain, Scene *scene)
{
@@ -316,10 +293,9 @@ void DEG_graph_on_visible_update(Main *bmain, Scene *scene)
* This is mainly needed on file load only, after that updates of invisible objects
* will be stored in the pending list.
*/
- GHASH_FOREACH_BEGIN(DEG::IDDepsNode *, id_node, graph->id_hash)
- {
+ foreach (DEG::IDDepsNode *id_node, graph->id_nodes) {
ID *id = id_node->id;
- if ((id->tag & LIB_TAG_ID_RECALC_ALL) != 0 ||
+ if ((id->recalc & ID_RECALC_ALL) != 0 ||
(id_node->layers & scene->lay_updated) == 0)
{
id_node->tag_update(graph);
@@ -331,21 +307,51 @@ void DEG_graph_on_visible_update(Main *bmain, Scene *scene)
*/
if (GS(id->name) == ID_OB) {
Object *object = (Object *)id;
- if ((id->tag & LIB_TAG_ID_RECALC_ALL) == 0 &&
+ if ((id->recalc & ID_RECALC_ALL) == 0 &&
(object->recalc & OB_RECALC_ALL) != 0)
{
id_node->tag_update(graph);
DEG::ComponentDepsNode *anim_comp =
- id_node->find_component(DEG::DEPSNODE_TYPE_ANIMATION);
+ id_node->find_component(DEG::DEG_NODE_TYPE_ANIMATION);
if (anim_comp != NULL && object->recalc & OB_RECALC_TIME) {
anim_comp->tag_update(graph);
}
}
}
}
- GHASH_FOREACH_END();
}
scene->lay_updated |= graph->layers;
+ /* If graph is tagged for update, we don't need to bother with updates here,
+ * nodes will be re-created.
+ */
+ if (graph->need_update) {
+ return;
+ }
+ /* Special trick to get local view to work. */
+ LISTBASE_FOREACH (Base *, base, &scene->base) {
+ Object *object = base->object;
+ DEG::IDDepsNode *id_node = graph->find_id_node(&object->id);
+ id_node->layers = 0;
+ }
+ LISTBASE_FOREACH (Base *, base, &scene->base) {
+ Object *object = base->object;
+ DEG::IDDepsNode *id_node = graph->find_id_node(&object->id);
+ id_node->layers |= base->lay;
+ if (object == scene->camera || object->type == OB_CAMERA) {
+ /* Camera should always be updated, it used directly by viewport. */
+ id_node->layers |= (unsigned int)(-1);
+ }
+ }
+ DEG::deg_graph_build_flush_layers(graph);
+ LISTBASE_FOREACH (Base *, base, &scene->base) {
+ Object *object = base->object;
+ DEG::IDDepsNode *id_node = graph->find_id_node(&object->id);
+ GHASH_FOREACH_BEGIN(DEG::ComponentDepsNode *, comp, id_node->components)
+ {
+ id_node->layers |= comp->layers;
+ }
+ GHASH_FOREACH_END();
+ }
}
void DEG_on_visible_update(Main *bmain, const bool UNUSED(do_time))
@@ -402,12 +408,12 @@ void DEG_ids_clear_recalc(Main *bmain)
if (id && bmain->id_tag_update[BKE_idcode_to_index(GS(id->name))]) {
for (; id; id = (ID *)id->next) {
- id->tag &= ~(LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA);
+ id->recalc &= ~ID_RECALC_ALL;
/* Some ID's contain semi-datablock nodetree */
ntree = ntreeFromID(id);
if (ntree != NULL) {
- ntree->id.tag &= ~(LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA);
+ ntree->id.recalc &= ~ID_RECALC_ALL;
}
}
}
diff --git a/source/blender/depsgraph/intern/depsgraph_type_defines.cc b/source/blender/depsgraph/intern/depsgraph_type_defines.cc
index 39c189629f2..41c72d11eac 100644
--- a/source/blender/depsgraph/intern/depsgraph_type_defines.cc
+++ b/source/blender/depsgraph/intern/depsgraph_type_defines.cc
@@ -32,12 +32,11 @@
#include <cstdlib> // for BLI_assert()
-extern "C" {
+
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
#include "DEG_depsgraph.h"
-} /* extern "C" */
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
@@ -52,14 +51,7 @@ namespace DEG {
/* Global type registry */
-/**
- * \note For now, this is a hashtable not array, since the core node types
- * currently do not have contiguous ID values. Using a hash here gives us
- * more flexibility, albeit using more memory and also sacrificing a little
- * speed. Later on, when things stabilise we may turn this back to an array
- * since there are only just a few node types that an array would cope fine...
- */
-static GHash *_depsnode_typeinfo_registry = NULL;
+static DepsNodeFactory *depsnode_typeinfo_registry[NUM_DEG_NODE_TYPES] = {NULL};
/* Registration ------------------------------------------- */
@@ -67,25 +59,16 @@ static GHash *_depsnode_typeinfo_registry = NULL;
void deg_register_node_typeinfo(DepsNodeFactory *factory)
{
BLI_assert(factory != NULL);
- BLI_ghash_insert(_depsnode_typeinfo_registry, SET_INT_IN_POINTER(factory->type()), factory);
+ depsnode_typeinfo_registry[factory->type()] = factory;
}
/* Getters ------------------------------------------------- */
/* Get typeinfo for specified type */
-DepsNodeFactory *deg_get_node_factory(const eDepsNode_Type type)
+DepsNodeFactory *deg_type_get_factory(const eDepsNode_Type type)
{
/* look up type - at worst, it doesn't exist in table yet, and we fail */
- return (DepsNodeFactory *)BLI_ghash_lookup(_depsnode_typeinfo_registry, SET_INT_IN_POINTER(type));
-}
-
-/* Get typeinfo for provided node */
-DepsNodeFactory *deg_node_get_factory(const DepsNode *node)
-{
- if (node != NULL) {
- return NULL;
- }
- return deg_get_node_factory(node->type);
+ return depsnode_typeinfo_registry[type];
}
/* Stringified opcodes ------------------------------------- */
@@ -96,39 +79,50 @@ static const char *stringify_opcode(eDepsOperation_Code opcode)
{
switch (opcode) {
#define STRINGIFY_OPCODE(name) case DEG_OPCODE_##name: return #name
+ /* Generic Operations. */
STRINGIFY_OPCODE(OPERATION);
+ STRINGIFY_OPCODE(ID_PROPERTY);
+ STRINGIFY_OPCODE(PARAMETERS_EVAL);
STRINGIFY_OPCODE(PLACEHOLDER);
- STRINGIFY_OPCODE(NOOP);
+ /* Animation, Drivers, etc. */
STRINGIFY_OPCODE(ANIMATION);
STRINGIFY_OPCODE(DRIVER);
- //STRINGIFY_OPCODE(PROXY);
+ /* Transform. */
STRINGIFY_OPCODE(TRANSFORM_LOCAL);
STRINGIFY_OPCODE(TRANSFORM_PARENT);
STRINGIFY_OPCODE(TRANSFORM_CONSTRAINTS);
- //STRINGIFY_OPCODE(TRANSFORM_CONSTRAINTS_INIT);
- //STRINGIFY_OPCODE(TRANSFORM_CONSTRAINT);
- //STRINGIFY_OPCODE(TRANSFORM_CONSTRAINTS_DONE);
+ STRINGIFY_OPCODE(TRANSFORM_FINAL);
+ STRINGIFY_OPCODE(TRANSFORM_OBJECT_UBEREVAL);
+ /* Rigid body. */
STRINGIFY_OPCODE(RIGIDBODY_REBUILD);
STRINGIFY_OPCODE(RIGIDBODY_SIM);
- STRINGIFY_OPCODE(TRANSFORM_RIGIDBODY);
- STRINGIFY_OPCODE(TRANSFORM_FINAL);
- STRINGIFY_OPCODE(OBJECT_UBEREVAL);
+ STRINGIFY_OPCODE(RIGIDBODY_TRANSFORM_COPY);
+ /* Geometry. */
STRINGIFY_OPCODE(GEOMETRY_UBEREVAL);
- STRINGIFY_OPCODE(GEOMETRY_MODIFIER);
- STRINGIFY_OPCODE(GEOMETRY_PATH);
+ STRINGIFY_OPCODE(GEOMETRY_CLOTH_MODIFIER);
+ STRINGIFY_OPCODE(GEOMETRY_SHAPEKEY);
+ /* Pose. */
STRINGIFY_OPCODE(POSE_INIT);
+ STRINGIFY_OPCODE(POSE_INIT_IK);
STRINGIFY_OPCODE(POSE_DONE);
STRINGIFY_OPCODE(POSE_IK_SOLVER);
STRINGIFY_OPCODE(POSE_SPLINE_IK_SOLVER);
+ /* Bone. */
STRINGIFY_OPCODE(BONE_LOCAL);
STRINGIFY_OPCODE(BONE_POSE_PARENT);
STRINGIFY_OPCODE(BONE_CONSTRAINTS);
- //STRINGIFY_OPCODE(BONE_CONSTRAINTS_INIT);
- //STRINGIFY_OPCODE(BONE_CONSTRAINT);
- //STRINGIFY_OPCODE(BONE_CONSTRAINTS_DONE);
STRINGIFY_OPCODE(BONE_READY);
STRINGIFY_OPCODE(BONE_DONE);
- STRINGIFY_OPCODE(PSYS_EVAL);
+ /* Particles. */
+ STRINGIFY_OPCODE(PARTICLE_SYSTEM_EVAL_INIT);
+ STRINGIFY_OPCODE(PARTICLE_SYSTEM_EVAL);
+ /* Masks. */
+ STRINGIFY_OPCODE(MASK_ANIMATION);
+ STRINGIFY_OPCODE(MASK_EVAL);
+ /* Shading. */
+ STRINGIFY_OPCODE(SHADING);
+ /* Movie clip. */
+ STRINGIFY_OPCODE(MOVIECLIP_EVAL);
case DEG_NUM_OPCODES: return "SpecialCase";
#undef STRINGIFY_OPCODE
@@ -157,9 +151,6 @@ const char *DepsOperationStringifier::operator[](eDepsOperation_Code opcode)
/* Register all node types */
void DEG_register_node_types(void)
{
- /* initialise registry */
- DEG::_depsnode_typeinfo_registry = BLI_ghash_int_new("Depsgraph Node Type Registry");
-
/* register node types */
DEG::deg_register_base_depsnodes();
DEG::deg_register_component_depsnodes();
@@ -169,5 +160,4 @@ void DEG_register_node_types(void)
/* Free registry on exit */
void DEG_free_node_types(void)
{
- BLI_ghash_free(DEG::_depsnode_typeinfo_registry, NULL, NULL);
}
diff --git a/source/blender/depsgraph/intern/depsgraph_types.h b/source/blender/depsgraph/intern/depsgraph_types.h
index effd34a0eb9..0e48be6b1e2 100644
--- a/source/blender/depsgraph/intern/depsgraph_types.h
+++ b/source/blender/depsgraph/intern/depsgraph_types.h
@@ -43,9 +43,7 @@
*/
#include <string>
#include <vector>
-
-using std::string;
-using std::vector;
+#include <algorithm>
struct bAction;
struct ChannelDriver;
@@ -56,6 +54,9 @@ struct FCurve;
namespace DEG {
+using std::string;
+using std::vector;
+
/* Evaluation Operation for atomic operation */
// XXX: move this to another header that can be exposed?
typedef function<void(struct EvaluationContext *)> DepsEvalOperationCb;
@@ -67,163 +68,131 @@ typedef enum eDepsNode_Class {
/* Types generally unassociated with user-visible entities,
* but needed for graph functioning.
*/
- DEPSNODE_CLASS_GENERIC = 0,
+ DEG_NODE_CLASS_GENERIC = 0,
/* [Outer Node] An "aspect" of evaluating/updating an ID-Block, requiring
* certain types of evaluation behavior.
*/
- DEPSNODE_CLASS_COMPONENT = 1,
+ DEG_NODE_CLASS_COMPONENT = 1,
/* [Inner Node] A glorified function-pointer/callback for scheduling up
* evaluation operations for components, subject to relationship
* requirements.
*/
- DEPSNODE_CLASS_OPERATION = 2,
+ DEG_NODE_CLASS_OPERATION = 2,
} eDepsNode_Class;
/* Types of Nodes */
typedef enum eDepsNode_Type {
/* Fallback type for invalid return value */
- DEPSNODE_TYPE_UNDEFINED = -1,
+ DEG_NODE_TYPE_UNDEFINED = 0,
/* Inner Node (Operation) */
- DEPSNODE_TYPE_OPERATION = 0,
+ DEG_NODE_TYPE_OPERATION,
/* **** Generic Types **** */
- /* "Current Scene" - basically whatever kicks off the evaluation process. */
- DEPSNODE_TYPE_ROOT = 1,
/* Time-Source */
- DEPSNODE_TYPE_TIMESOURCE = 2,
+ DEG_NODE_TYPE_TIMESOURCE,
/* ID-Block reference - used as landmarks/collection point for components,
* but not usually part of main graph.
*/
- DEPSNODE_TYPE_ID_REF = 3,
- /* Isolated sub-graph - used for keeping instanced data separate from
- * instances using them.
- */
- DEPSNODE_TYPE_SUBGRAPH = 4,
+ DEG_NODE_TYPE_ID_REF,
/* **** Outer Types **** */
/* Parameters Component - Default when nothing else fits
* (i.e. just SDNA property setting).
*/
- DEPSNODE_TYPE_PARAMETERS = 11,
- /* Generic "Proxy-Inherit" Component
- * XXX: Also for instancing of subgraphs?
- */
- DEPSNODE_TYPE_PROXY = 12,
- /* Animation Component
- *
- * XXX: merge in with parameters?
- */
- DEPSNODE_TYPE_ANIMATION = 13,
+ DEG_NODE_TYPE_PARAMETERS,
+ /* Generic "Proxy-Inherit" Component. */
+ DEG_NODE_TYPE_PROXY,
+ /* Animation Component */
+ DEG_NODE_TYPE_ANIMATION,
/* Transform Component (Parenting/Constraints) */
- DEPSNODE_TYPE_TRANSFORM = 14,
+ DEG_NODE_TYPE_TRANSFORM,
/* Geometry Component (DerivedMesh/Displist) */
- DEPSNODE_TYPE_GEOMETRY = 15,
+ DEG_NODE_TYPE_GEOMETRY,
/* Sequencer Component (Scene Only) */
- DEPSNODE_TYPE_SEQUENCER = 16,
+ DEG_NODE_TYPE_SEQUENCER,
/* **** Evaluation-Related Outer Types (with Subdata) **** */
/* Pose Component - Owner/Container of Bones Eval */
- DEPSNODE_TYPE_EVAL_POSE = 21,
+ DEG_NODE_TYPE_EVAL_POSE,
/* Bone Component - Child/Subcomponent of Pose */
- DEPSNODE_TYPE_BONE = 22,
+ DEG_NODE_TYPE_BONE,
/* Particle Systems Component */
- DEPSNODE_TYPE_EVAL_PARTICLES = 23,
+ DEG_NODE_TYPE_EVAL_PARTICLES,
/* Material Shading Component */
- DEPSNODE_TYPE_SHADING = 24,
+ DEG_NODE_TYPE_SHADING,
/* Cache Component */
- DEPSNODE_TYPE_CACHE = 25,
+ DEG_NODE_TYPE_CACHE,
+
+ /* Total number of meaningful node types. */
+ NUM_DEG_NODE_TYPES,
} eDepsNode_Type;
/* Identifiers for common operations (as an enum). */
typedef enum eDepsOperation_Code {
- /* Generic Operations ------------------------------ */
+ /* Generic Operations. ------------------------------ */
/* Placeholder for operations which don't need special mention */
DEG_OPCODE_OPERATION = 0,
+ /* Generic parameters evaluation. */
+ DEG_OPCODE_ID_PROPERTY,
+ DEG_OPCODE_PARAMETERS_EVAL,
+
// XXX: Placeholder while porting depsgraph code
DEG_OPCODE_PLACEHOLDER,
- DEG_OPCODE_NOOP,
-
/* Animation, Drivers, etc. ------------------------ */
-
/* NLA + Action */
DEG_OPCODE_ANIMATION,
-
/* Driver */
DEG_OPCODE_DRIVER,
- /* Proxy Inherit? */
- //DEG_OPCODE_PROXY,
-
- /* Transform --------------------------------------- */
-
+ /* Transform. -------------------------------------- */
/* Transform entry point - local transforms only */
DEG_OPCODE_TRANSFORM_LOCAL,
-
/* Parenting */
DEG_OPCODE_TRANSFORM_PARENT,
-
/* Constraints */
DEG_OPCODE_TRANSFORM_CONSTRAINTS,
- //DEG_OPCODE_TRANSFORM_CONSTRAINTS_INIT,
- //DEG_OPCODE_TRANSFORM_CONSTRAINT,
- //DEG_OPCODE_TRANSFORM_CONSTRAINTS_DONE,
+ /* Transform exit point */
+ DEG_OPCODE_TRANSFORM_FINAL,
+ /* Handle object-level updates, mainly proxies hacks and recalc flags. */
+ DEG_OPCODE_TRANSFORM_OBJECT_UBEREVAL,
- /* Rigidbody Sim - Perform Sim */
+ /* Rigid body. -------------------------------------- */
+ /* Perform Simulation */
DEG_OPCODE_RIGIDBODY_REBUILD,
DEG_OPCODE_RIGIDBODY_SIM,
+ /* Copy results to object */
+ DEG_OPCODE_RIGIDBODY_TRANSFORM_COPY,
- /* Rigidbody Sim - Copy Results to Object */
- DEG_OPCODE_TRANSFORM_RIGIDBODY,
-
- /* Transform exitpoint */
- DEG_OPCODE_TRANSFORM_FINAL,
-
- /* XXX: ubereval is for temporary porting purposes only */
- DEG_OPCODE_OBJECT_UBEREVAL,
-
- /* Geometry ---------------------------------------- */
-
- /* XXX: Placeholder - UberEval */
+ /* Geometry. ---------------------------------------- */
+ /* Evaluate the whole geometry, including modifiers. */
DEG_OPCODE_GEOMETRY_UBEREVAL,
+ DEG_OPCODE_GEOMETRY_CLOTH_MODIFIER,
+ DEG_OPCODE_GEOMETRY_SHAPEKEY,
- /* Modifier */
- DEG_OPCODE_GEOMETRY_MODIFIER,
-
- /* Curve Objects - Path Calculation (used for path-following tools, */
- DEG_OPCODE_GEOMETRY_PATH,
-
- /* Pose -------------------------------------------- */
-
- /* Init IK Trees, etc. */
+ /* Pose. -------------------------------------------- */
+ /* Init pose, clear flags, etc. */
DEG_OPCODE_POSE_INIT,
-
+ /* Initialize IK solver related pose stuff. */
+ DEG_OPCODE_POSE_INIT_IK,
/* Free IK Trees + Compute Deform Matrices */
DEG_OPCODE_POSE_DONE,
-
/* IK/Spline Solvers */
DEG_OPCODE_POSE_IK_SOLVER,
DEG_OPCODE_POSE_SPLINE_IK_SOLVER,
- /* Bone -------------------------------------------- */
-
- /* Bone local transforms - Entrypoint */
+ /* Bone. -------------------------------------------- */
+ /* Bone local transforms - entry point */
DEG_OPCODE_BONE_LOCAL,
-
/* Pose-space conversion (includes parent + restpose, */
DEG_OPCODE_BONE_POSE_PARENT,
-
/* Constraints */
DEG_OPCODE_BONE_CONSTRAINTS,
- //DEG_OPCODE_BONE_CONSTRAINTS_INIT,
- //DEG_OPCODE_BONE_CONSTRAINT,
- //DEG_OPCODE_BONE_CONSTRAINTS_DONE,
-
/* Bone transforms are ready
*
* - "READY" This (internal, noop is used to signal that all pre-IK
@@ -238,10 +207,20 @@ typedef enum eDepsOperation_Code {
DEG_OPCODE_BONE_READY,
DEG_OPCODE_BONE_DONE,
- /* Particles --------------------------------------- */
+ /* Particles. --------------------------------------- */
+ /* Particle System evaluation. */
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL_INIT,
+ DEG_OPCODE_PARTICLE_SYSTEM_EVAL,
- /* XXX: placeholder - Particle System eval */
- DEG_OPCODE_PSYS_EVAL,
+ /* Shading. ------------------------------------------- */
+ DEG_OPCODE_SHADING,
+
+ /* Masks. ------------------------------------------ */
+ DEG_OPCODE_MASK_ANIMATION,
+ DEG_OPCODE_MASK_EVAL,
+
+ /* Movie clips. ------------------------------------ */
+ DEG_OPCODE_MOVIECLIP_EVAL,
DEG_NUM_OPCODES,
} eDepsOperation_Code;
@@ -258,83 +237,4 @@ protected:
/* String defines for these opcodes, defined in depsgraph_type_defines.cpp */
extern DepsOperationStringifier DEG_OPNAMES;
-/* Type of operation */
-typedef enum eDepsOperation_Type {
- /* **** Primary operation types **** */
-
- /* Initialise evaluation data */
- DEPSOP_TYPE_INIT = 0,
- /* Standard evaluation step */
- DEPSOP_TYPE_EXEC = 1,
- /* Cleanup evaluation data + flush results */
- DEPSOP_TYPE_POST = 2,
-
- /* **** Additional operation types **** */
- /* Indicator for outputting a temporary result that other components
- * can use. // XXX?
- */
- DEPSOP_TYPE_OUT = 3,
- /* Indicator for things like IK Solvers and Rigidbody Sim steps which
- * modify final results of separate entities at once.
- */
- DEPSOP_TYPE_SIM = 4,
- /* Rebuild internal evaluation data - used for Rigidbody Reset and
- * Armature Rebuild-On-Load.
- */
- DEPSOP_TYPE_REBUILD = 5,
-} eDepsOperation_Type;
-
-/* Types of relationships between nodes
- *
- * This is used to provide additional hints to use when filtering
- * the graph, so that we can go without doing more extensive
- * data-level checks...
- */
-typedef enum eDepsRelation_Type {
- /* relationship type unknown/irrelevant */
- DEPSREL_TYPE_STANDARD = 0,
-
- /* root -> active scene or entity (screen, image, etc.) */
- DEPSREL_TYPE_ROOT_TO_ACTIVE,
-
- /* general datablock dependency */
- DEPSREL_TYPE_DATABLOCK,
-
- /* time dependency */
- DEPSREL_TYPE_TIME,
-
- /* component depends on results of another */
- DEPSREL_TYPE_COMPONENT_ORDER,
-
- /* relationship is just used to enforce ordering of operations
- * (e.g. "init()" callback done before "exec() and "cleanup()")
- */
- DEPSREL_TYPE_OPERATION,
-
- /* relationship results from a property driver affecting property */
- DEPSREL_TYPE_DRIVER,
-
- /* relationship is something driver depends on */
- DEPSREL_TYPE_DRIVER_TARGET,
-
- /* relationship is used for transform stack
- * (e.g. parenting, user transforms, constraints)
- */
- DEPSREL_TYPE_TRANSFORM,
-
- /* relationship is used for geometry evaluation
- * (e.g. metaball "motherball" or modifiers)
- */
- DEPSREL_TYPE_GEOMETRY_EVAL,
-
- /* relationship is used to trigger a post-change validity updates */
- DEPSREL_TYPE_UPDATE,
-
- /* relationship is used to trigger editor/screen updates */
- DEPSREL_TYPE_UPDATE_UI,
-
- /* cache dependency */
- DEPSREL_TYPE_CACHE,
-} eDepsRelation_Type;
-
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/eval/deg_eval.cc b/source/blender/depsgraph/intern/eval/deg_eval.cc
index 3a042535d26..fc71b5ccb7b 100644
--- a/source/blender/depsgraph/intern/eval/deg_eval.cc
+++ b/source/blender/depsgraph/intern/eval/deg_eval.cc
@@ -34,35 +34,30 @@
#include "PIL_time.h"
-extern "C" {
#include "BLI_utildefines.h"
#include "BLI_task.h"
#include "BLI_ghash.h"
+extern "C" {
#include "BKE_depsgraph.h"
#include "BKE_global.h"
+} /* extern "C" */
#include "DEG_depsgraph.h"
-} /* extern "C" */
#include "atomic_ops.h"
-#include "intern/eval/deg_eval_debug.h"
#include "intern/eval/deg_eval_flush.h"
+#include "intern/eval/deg_eval_stats.h"
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
+#include "intern/nodes/deg_node_time.h"
#include "intern/depsgraph.h"
#include "intern/depsgraph_intern.h"
-#include "util/deg_util_foreach.h"
-
-/* Unfinished and unused, and takes quite some pre-processing time. */
-#undef USE_EVAL_PRIORITY
-/* Use integrated debugger to keep track how much each of the nodes was
- * evaluating.
- */
-#undef USE_DEBUGGER
+#include "util/deg_util_foreach.h"
namespace DEG {
@@ -80,120 +75,31 @@ struct DepsgraphEvalState {
EvaluationContext *eval_ctx;
Depsgraph *graph;
unsigned int layers;
+ bool do_stats;
};
static void deg_task_run_func(TaskPool *pool,
void *taskdata,
int thread_id)
{
- DepsgraphEvalState *state =
- reinterpret_cast<DepsgraphEvalState *>(BLI_task_pool_userdata(pool));
- OperationDepsNode *node = reinterpret_cast<OperationDepsNode *>(taskdata);
-
+ void *userdata_v = BLI_task_pool_userdata(pool);
+ DepsgraphEvalState *state = (DepsgraphEvalState *)userdata_v;
+ OperationDepsNode *node = (OperationDepsNode *)taskdata;
+ /* Sanity checks. */
BLI_assert(!node->is_noop() && "NOOP nodes should not actually be scheduled");
-
- /* Should only be the case for NOOPs, which never get to this point. */
- BLI_assert(node->evaluate);
-
- while (true) {
- /* Get context. */
- /* TODO: Who initialises this? "Init" operations aren't able to
- * initialise it!!!
- */
- /* TODO(sergey): We don't use component contexts at this moment. */
- /* ComponentDepsNode *comp = node->owner; */
- BLI_assert(node->owner != NULL);
-
- /* Since we're not leaving the thread for until the graph branches it is
- * possible to have NO-OP on the way. for which evaluate() will be NULL.
- * but that's all fine, we'll just scheduler it's children.
- */
- if (node->evaluate) {
- /* Take note of current time. */
-#ifdef USE_DEBUGGER
- double start_time = PIL_check_seconds_timer();
- DepsgraphDebug::task_started(state->graph, node);
-#endif
-
- /* Perform operation. */
- node->evaluate(state->eval_ctx);
-
- /* Note how long this took. */
-#ifdef USE_DEBUGGER
- double end_time = PIL_check_seconds_timer();
- DepsgraphDebug::task_completed(state->graph,
- node,
- end_time - start_time);
-#endif
- }
-
- /* If there's only one outgoing link we try to immediately switch to
- * that node evaluation, without leaving the thread.
- *
- * It's only doable if the child don't have extra relations or all they
- * are satisfied.
- *
- * TODO(sergey): Checks here can be de-duplicated with the ones from
- * schedule_node(), however, how to do it nicely?
- */
- if (node->outlinks.size() == 1) {
- DepsRelation *rel = node->outlinks[0];
- OperationDepsNode *child = (OperationDepsNode *)rel->to;
- BLI_assert(child->type == DEPSNODE_TYPE_OPERATION);
- if (!child->scheduled) {
- unsigned int id_layers = child->owner->owner->layers;
- if (!((child->flag & DEPSOP_FLAG_NEEDS_UPDATE) != 0 &&
- (id_layers & state->layers) != 0))
- {
- /* Node does not need an update, so can;t continue with the
- * chain and need to switch to another one by leaving the
- * thread.
- */
- break;
- }
- if ((rel->flag & DEPSREL_FLAG_CYCLIC) == 0) {
- BLI_assert(child->num_links_pending > 0);
- atomic_sub_and_fetch_uint32(&child->num_links_pending, 1);
- }
- if (child->num_links_pending == 0) {
- bool is_scheduled = atomic_fetch_and_or_uint8(
- (uint8_t *)&child->scheduled, (uint8_t)true);
- if (!is_scheduled) {
- /* Node was not scheduled, switch to it! */
- node = child;
- }
- else {
- /* Someone else scheduled the node, leaving us
- * unemployed in this thread, we're leaving.
- */
- break;
- }
- }
- else {
- /* There are other dependencies on the child, can't do
- * anything in the current thread.
- */
- break;
- }
- }
- else {
- /* Happens when having cyclic dependencies.
- *
- * Nothing to do here, single child was already scheduled, we
- * can leave the thread now.
- */
- break;
- }
- }
- else {
- /* TODO(sergey): It's possible to use one of the outgoing relations
- * as a chain which we'll try to keep alive, but it's a bit more
- * involved change.
- */
- schedule_children(pool, state->graph, node, state->layers, thread_id);
- break;
- }
+ /* Perform operation. */
+ if (state->do_stats) {
+ const double start_time = PIL_check_seconds_timer();
+ node->evaluate(state->eval_ctx);
+ node->stats.current_time += PIL_check_seconds_timer() - start_time;
+ }
+ else {
+ node->evaluate(state->eval_ctx);
}
+ /* Schedule children. */
+ BLI_task_pool_delayed_push_begin(pool, thread_id);
+ schedule_children(pool, state->graph, node, state->layers, thread_id);
+ BLI_task_pool_delayed_push_end(pool, thread_id);
}
typedef struct CalculatePengindData {
@@ -201,7 +107,10 @@ typedef struct CalculatePengindData {
unsigned int layers;
} CalculatePengindData;
-static void calculate_pending_func(void *data_v, int i)
+static void calculate_pending_func(
+ void *__restrict data_v,
+ const int i,
+ const ParallelRangeTLS *__restrict /*tls*/)
{
CalculatePengindData *data = (CalculatePengindData *)data_v;
Depsgraph *graph = data->graph;
@@ -217,7 +126,7 @@ static void calculate_pending_func(void *data_v, int i)
(node->flag & DEPSOP_FLAG_NEEDS_UPDATE) != 0)
{
foreach (DepsRelation *rel, node->inlinks) {
- if (rel->from->type == DEPSNODE_TYPE_OPERATION &&
+ if (rel->from->type == DEG_NODE_TYPE_OPERATION &&
(rel->flag & DEPSREL_FLAG_CYCLIC) == 0)
{
OperationDepsNode *from = (OperationDepsNode *)rel->from;
@@ -235,43 +144,31 @@ static void calculate_pending_func(void *data_v, int i)
static void calculate_pending_parents(Depsgraph *graph, unsigned int layers)
{
const int num_operations = graph->operations.size();
- const bool do_threads = num_operations > 256;
CalculatePengindData data;
data.graph = graph;
data.layers = layers;
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1024;
BLI_task_parallel_range(0,
num_operations,
&data,
calculate_pending_func,
- do_threads);
+ &settings);
}
-#ifdef USE_EVAL_PRIORITY
-static void calculate_eval_priority(OperationDepsNode *node)
+static void initialize_execution(DepsgraphEvalState *state, Depsgraph *graph)
{
- if (node->done) {
- return;
- }
- node->done = 1;
-
- if (node->flag & DEPSOP_FLAG_NEEDS_UPDATE) {
- /* XXX standard cost of a node, could be estimated somewhat later on */
- const float cost = 1.0f;
- /* NOOP nodes have no cost */
- node->eval_priority = node->is_noop() ? cost : 0.0f;
-
- foreach (DepsRelation *rel, node->outlinks) {
- OperationDepsNode *to = (OperationDepsNode *)rel->to;
- BLI_assert(to->type == DEPSNODE_TYPE_OPERATION);
- calculate_eval_priority(to);
- node->eval_priority += to->eval_priority;
+ const bool do_stats = state->do_stats;
+ calculate_pending_parents(graph, state->layers);
+ /* Clear tags and other things which needs to be clear. */
+ foreach (OperationDepsNode *node, graph->operations) {
+ node->done = 0;
+ if (do_stats) {
+ node->stats.reset_current();
}
}
- else {
- node->eval_priority = 0.0f;
- }
}
-#endif
/* Schedule a node if it needs evaluation.
* dec_parents: Decrement pending parents count, true when child nodes are
@@ -330,7 +227,7 @@ static void schedule_children(TaskPool *pool,
{
foreach (DepsRelation *rel, node->outlinks) {
OperationDepsNode *child = (OperationDepsNode *)rel->to;
- BLI_assert(child->type == DEPSNODE_TYPE_OPERATION);
+ BLI_assert(child->type == DEG_NODE_TYPE_OPERATION);
if (child->scheduled) {
/* Happens when having cyclic dependencies. */
continue;
@@ -355,61 +252,59 @@ void deg_evaluate_on_refresh(EvaluationContext *eval_ctx,
Depsgraph *graph,
const unsigned int layers)
{
- /* Generate base evaluation context, upon which all the others are derived. */
- // TODO: this needs both main and scene access...
-
+ /* Set time for the current graph evaluation context. */
+ TimeSourceDepsNode *time_src = graph->find_time_source();
+ eval_ctx->ctime = time_src->cfra;
/* Nothing to update, early out. */
- if (BLI_gset_size(graph->entry_tags) == 0) {
+ if (BLI_gset_len(graph->entry_tags) == 0) {
return;
}
-
- DEG_DEBUG_PRINTF("%s: layers:%u, graph->layers:%u\n",
+ DEG_DEBUG_PRINTF(EVAL, "%s: layers:%u, graph->layers:%u\n",
__func__,
layers,
graph->layers);
-
- /* Set time for the current graph evaluation context. */
- TimeSourceDepsNode *time_src = graph->find_time_source();
- eval_ctx->ctime = time_src->cfra;
-
- /* XXX could use a separate pool for each eval context */
+ const bool do_time_debug = ((G.debug & G_DEBUG_DEPSGRAPH_TIME) != 0);
+ const double start_time = do_time_debug ? PIL_check_seconds_timer() : 0;
+ /* Set up evaluation context for depsgraph itself. */
DepsgraphEvalState state;
state.eval_ctx = eval_ctx;
state.graph = graph;
state.layers = layers;
-
- TaskScheduler *task_scheduler = BLI_task_scheduler_get();
- TaskPool *task_pool = BLI_task_pool_create(task_scheduler, &state);
-
+ state.do_stats = do_time_debug;
+ /* Set up task scheduler and pull for threaded evaluation. */
+ TaskScheduler *task_scheduler;
+ bool need_free_scheduler;
if (G.debug & G_DEBUG_DEPSGRAPH_NO_THREADS) {
- BLI_pool_set_num_threads(task_pool, 1);
+ task_scheduler = BLI_task_scheduler_create(1);
+ need_free_scheduler = true;
}
-
- calculate_pending_parents(graph, layers);
-
- /* Clear tags. */
- foreach (OperationDepsNode *node, graph->operations) {
- node->done = 0;
- }
-
- /* Calculate priority for operation nodes. */
-#ifdef USE_EVAL_PRIORITY
- foreach (OperationDepsNode *node, graph->operations) {
- calculate_eval_priority(node);
+ else {
+ task_scheduler = BLI_task_scheduler_get();
+ need_free_scheduler = false;
}
-#endif
-
- DepsgraphDebug::eval_begin(eval_ctx);
-
+ TaskPool *task_pool = BLI_task_pool_create_suspended(task_scheduler, &state);
+ /* Prepare all nodes for evaluation. */
+ initialize_execution(&state, graph);
+ /* Do actual evaluation now. */
schedule_graph(task_pool, graph, layers);
-
BLI_task_pool_work_and_wait(task_pool);
BLI_task_pool_free(task_pool);
-
- DepsgraphDebug::eval_end(eval_ctx);
-
+ /* Finalize statistics gathering. This is because we only gather single
+ * operation timing here, without aggregating anything to avoid any extra
+ * synchronization.
+ */
+ if (state.do_stats) {
+ deg_eval_stats_aggregate(graph);
+ }
/* Clear any uncleared tags - just in case. */
deg_graph_clear_tags(graph);
+ if (need_free_scheduler) {
+ BLI_task_scheduler_free(task_scheduler);
+ }
+ if (do_time_debug) {
+ printf("Depsgraph updated in %f seconds.\n",
+ PIL_check_seconds_timer() - start_time);
+ }
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/eval/deg_eval_debug.cc b/source/blender/depsgraph/intern/eval/deg_eval_debug.cc
deleted file mode 100644
index 060544a4407..00000000000
--- a/source/blender/depsgraph/intern/eval/deg_eval_debug.cc
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2014 Blender Foundation.
- * All rights reserved.
- *
- * Original Author: Lukas Toenne
- * Contributor(s): None Yet
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/depsgraph/intern/eval/deg_eval_debug.cc
- * \ingroup depsgraph
- *
- * Implementation of tools for debugging the depsgraph
- */
-
-#include "intern/eval/deg_eval_debug.h"
-
-#include <cstring> /* required for STREQ later on. */
-
-extern "C" {
-#include "BLI_listbase.h"
-#include "BLI_ghash.h"
-
-#include "DEG_depsgraph_debug.h"
-
-#include "WM_api.h"
-#include "WM_types.h"
-} /* extern "C" */
-
-#include "intern/nodes/deg_node.h"
-#include "intern/nodes/deg_node_component.h"
-#include "intern/nodes/deg_node_operation.h"
-#include "intern/depsgraph_intern.h"
-
-namespace DEG {
-
-DepsgraphStats *DepsgraphDebug::stats = NULL;
-
-static string get_component_name(eDepsNode_Type type, const char *name = "")
-{
- DepsNodeFactory *factory = deg_get_node_factory(type);
- if (name[0] != '\0') {
- return string(factory->tname());
- }
- else {
- return string(factory->tname()) + " | " + name;
- }
-}
-
-static void times_clear(DepsgraphStatsTimes &times)
-{
- times.duration_last = 0.0f;
-}
-
-static void times_add(DepsgraphStatsTimes &times, float time)
-{
- times.duration_last += time;
-}
-
-void DepsgraphDebug::eval_begin(const EvaluationContext *UNUSED(eval_ctx))
-{
- /* TODO(sergey): Stats are currently globally disabled. */
- /* verify_stats(); */
- reset_stats();
-}
-
-void DepsgraphDebug::eval_end(const EvaluationContext *UNUSED(eval_ctx))
-{
- WM_main_add_notifier(NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
-}
-
-void DepsgraphDebug::eval_step(const EvaluationContext *UNUSED(eval_ctx),
- const char *message)
-{
-#ifdef DEG_DEBUG_BUILD
- if (deg_debug_eval_cb)
- deg_debug_eval_cb(deg_debug_eval_userdata, message);
-#else
- (void)message; /* Ignored. */
-#endif
-}
-
-void DepsgraphDebug::task_started(Depsgraph *graph,
- const OperationDepsNode *node)
-{
- if (stats) {
- BLI_spin_lock(&graph->lock);
-
- ComponentDepsNode *comp = node->owner;
- ID *id = comp->owner->id;
-
- DepsgraphStatsID *id_stats = get_id_stats(id, true);
- times_clear(id_stats->times);
-
- /* XXX TODO use something like: if (id->flag & ID_DEG_DETAILS) {...} */
- if (0) {
- /* XXX component name usage needs cleanup! currently mixes identifier
- * and description strings!
- */
- DepsgraphStatsComponent *comp_stats =
- get_component_stats(id, get_component_name(comp->type,
- comp->name).c_str(),
- true);
- times_clear(comp_stats->times);
- }
-
- BLI_spin_unlock(&graph->lock);
- }
-}
-
-void DepsgraphDebug::task_completed(Depsgraph *graph,
- const OperationDepsNode *node,
- double time)
-{
- if (stats) {
- BLI_spin_lock(&graph->lock);
-
- ComponentDepsNode *comp = node->owner;
- ID *id = comp->owner->id;
-
- DepsgraphStatsID *id_stats = get_id_stats(id, true);
- times_add(id_stats->times, time);
-
- /* XXX TODO use something like: if (id->flag & ID_DEG_DETAILS) {...} */
- if (0) {
- /* XXX component name usage needs cleanup! currently mixes identifier
- * and description strings!
- */
- DepsgraphStatsComponent *comp_stats =
- get_component_stats(id,
- get_component_name(comp->type,
- comp->name).c_str(),
- true);
- times_add(comp_stats->times, time);
- }
-
- BLI_spin_unlock(&graph->lock);
- }
-}
-
-/* ********** */
-/* Statistics */
-
-
-/* GHash callback */
-static void deg_id_stats_free(void *val)
-{
- DepsgraphStatsID *id_stats = (DepsgraphStatsID *)val;
-
- if (id_stats) {
- BLI_freelistN(&id_stats->components);
- MEM_freeN(id_stats);
- }
-}
-
-void DepsgraphDebug::stats_init()
-{
- if (!stats) {
- stats = (DepsgraphStats *)MEM_callocN(sizeof(DepsgraphStats),
- "Depsgraph Stats");
- stats->id_stats = BLI_ghash_new(BLI_ghashutil_ptrhash,
- BLI_ghashutil_ptrcmp,
- "Depsgraph ID Stats Hash");
- }
-}
-
-void DepsgraphDebug::stats_free()
-{
- if (stats) {
- BLI_ghash_free(stats->id_stats, NULL, deg_id_stats_free);
- MEM_freeN(stats);
- stats = NULL;
- }
-}
-
-void DepsgraphDebug::verify_stats()
-{
- stats_init();
-}
-
-void DepsgraphDebug::reset_stats()
-{
- if (!stats) {
- return;
- }
-
- /* XXX this doesn't work, will immediately clear all info,
- * since most depsgraph updates have none or very few updates to handle.
- *
- * Could consider clearing only zero-user ID blocks here
- */
-// BLI_ghash_clear(stats->id_stats, NULL, deg_id_stats_free);
-}
-
-DepsgraphStatsID *DepsgraphDebug::get_id_stats(ID *id, bool create)
-{
- DepsgraphStatsID *id_stats = (DepsgraphStatsID *)BLI_ghash_lookup(stats->id_stats, id);
-
- if (!id_stats && create) {
- id_stats = (DepsgraphStatsID *)MEM_callocN(sizeof(DepsgraphStatsID),
- "Depsgraph ID Stats");
- id_stats->id = id;
-
- BLI_ghash_insert(stats->id_stats, id, id_stats);
- }
-
- return id_stats;
-}
-
-DepsgraphStatsComponent *DepsgraphDebug::get_component_stats(
- DepsgraphStatsID *id_stats,
- const char *name,
- bool create)
-{
- DepsgraphStatsComponent *comp_stats;
- for (comp_stats = (DepsgraphStatsComponent *)id_stats->components.first;
- comp_stats != NULL;
- comp_stats = comp_stats->next)
- {
- if (STREQ(comp_stats->name, name)) {
- break;
- }
- }
- if (!comp_stats && create) {
- comp_stats = (DepsgraphStatsComponent *)MEM_callocN(sizeof(DepsgraphStatsComponent),
- "Depsgraph Component Stats");
- BLI_strncpy(comp_stats->name, name, sizeof(comp_stats->name));
- BLI_addtail(&id_stats->components, comp_stats);
- }
- return comp_stats;
-}
-
-} // namespace DEG
diff --git a/source/blender/depsgraph/intern/eval/deg_eval_debug.h b/source/blender/depsgraph/intern/eval/deg_eval_debug.h
deleted file mode 100644
index 0bbe88cc9ca..00000000000
--- a/source/blender/depsgraph/intern/eval/deg_eval_debug.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2013 Blender Foundation.
- * All rights reserved.
- *
- * Original Author: Joshua Leung
- * Contributor(s): None Yet
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/depsgraph/intern/eval/deg_eval_debug.h
- * \ingroup depsgraph
- */
-
-#pragma once
-
-#include "intern/depsgraph_types.h"
-
-struct ID;
-struct EvaluationContext;
-
-struct DepsgraphStats;
-struct DepsgraphStatsID;
-struct DepsgraphStatsComponent;
-
-namespace DEG {
-
-struct Depsgraph;
-struct DepsgraphSettings;
-struct OperationDepsNode;
-
-struct DepsgraphDebug {
- static DepsgraphStats *stats;
-
- static void stats_init();
- static void stats_free();
-
- static void verify_stats();
- static void reset_stats();
-
- static void eval_begin(const EvaluationContext *eval_ctx);
- static void eval_end(const EvaluationContext *eval_ctx);
- static void eval_step(const EvaluationContext *eval_ctx,
- const char *message);
-
- static void task_started(Depsgraph *graph, const OperationDepsNode *node);
- static void task_completed(Depsgraph *graph,
- const OperationDepsNode *node,
- double time);
-
- static DepsgraphStatsID *get_id_stats(ID *id, bool create);
- static DepsgraphStatsComponent *get_component_stats(DepsgraphStatsID *id_stats,
- const char *name,
- bool create);
- static DepsgraphStatsComponent *get_component_stats(ID *id,
- const char *name,
- bool create)
- {
- return get_component_stats(get_id_stats(id, create), name, create);
- }
-};
-
-} // namespace DEG
diff --git a/source/blender/depsgraph/intern/eval/deg_eval_flush.cc b/source/blender/depsgraph/intern/eval/deg_eval_flush.cc
index 7c6c25bef0d..e7764cf5a27 100644
--- a/source/blender/depsgraph/intern/eval/deg_eval_flush.cc
+++ b/source/blender/depsgraph/intern/eval/deg_eval_flush.cc
@@ -35,18 +35,19 @@
// TODO(sergey): Use some sort of wrapper.
#include <deque>
-extern "C" {
-#include "DNA_object_types.h"
-
#include "BLI_utildefines.h"
#include "BLI_task.h"
#include "BLI_ghash.h"
-#include "DEG_depsgraph.h"
+extern "C" {
+#include "DNA_object_types.h"
} /* extern "C" */
+#include "DEG_depsgraph.h"
+
#include "intern/nodes/deg_node.h"
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_intern.h"
@@ -54,158 +55,253 @@ extern "C" {
namespace DEG {
+enum {
+ ID_STATE_NONE = 0,
+ ID_STATE_MODIFIED = 1,
+};
+
+enum {
+ COMPONENT_STATE_NONE = 0,
+ COMPONENT_STATE_SCHEDULED = 1,
+ COMPONENT_STATE_DONE = 2,
+};
+
+typedef std::deque<OperationDepsNode *> FlushQueue;
+
namespace {
// TODO(sergey): De-duplicate with depsgraph_tag,cc
void lib_id_recalc_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC;
+ id->recalc |= ID_RECALC;
DEG_id_type_tag(bmain, GS(id->name));
}
void lib_id_recalc_data_tag(Main *bmain, ID *id)
{
- id->tag |= LIB_TAG_ID_RECALC_DATA;
+ id->recalc |= ID_RECALC_DATA;
DEG_id_type_tag(bmain, GS(id->name));
}
-} /* namespace */
-
-typedef std::deque<OperationDepsNode *> FlushQueue;
-
-static void flush_init_func(void *data_v, int i)
+void flush_init_operation_node_func(
+ void *__restrict data_v,
+ const int i,
+ const ParallelRangeTLS *__restrict /*tls*/)
{
- /* ID node's done flag is used to avoid multiple editors update
- * for the same ID.
- */
Depsgraph *graph = (Depsgraph *)data_v;
OperationDepsNode *node = graph->operations[i];
- ComponentDepsNode *comp_node = node->owner;
- IDDepsNode *id_node = comp_node->owner;
- id_node->done = 0;
- comp_node->done = 0;
node->scheduled = false;
}
-/* Flush updates from tagged nodes outwards until all affected nodes
- * are tagged.
- */
-void deg_graph_flush_updates(Main *bmain, Depsgraph *graph)
+void flush_init_id_node_func(
+ void *__restrict data_v,
+ const int i,
+ const ParallelRangeTLS *__restrict /*tls*/)
{
- /* Sanity check. */
- if (graph == NULL) {
- return;
- }
+ Depsgraph *graph = (Depsgraph *)data_v;
+ IDDepsNode *id_node = graph->id_nodes[i];
+ id_node->done = ID_STATE_NONE;
+ GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components)
+ comp_node->done = COMPONENT_STATE_NONE;
+ GHASH_FOREACH_END();
+}
- /* Nothing to update, early out. */
- if (BLI_gset_size(graph->entry_tags) == 0) {
- return;
+BLI_INLINE void flush_prepare(Depsgraph *graph)
+{
+ {
+ const int num_operations = graph->operations.size();
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1024;
+ BLI_task_parallel_range(0, num_operations,
+ graph,
+ flush_init_operation_node_func,
+ &settings);
}
+ {
+ const int num_id_nodes = graph->id_nodes.size();
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1024;
+ BLI_task_parallel_range(0, num_id_nodes,
+ graph,
+ flush_init_id_node_func,
+ &settings);
+ }
+}
- /* TODO(sergey): With a bit of flag magic we can get rid of this
- * extra loop.
- */
- const int num_operations = graph->operations.size();
- const bool do_threads = num_operations > 256;
- BLI_task_parallel_range(0,
- num_operations,
- graph,
- flush_init_func,
- do_threads);
-
- FlushQueue queue;
- /* Starting from the tagged "entry" nodes, flush outwards... */
- /* NOTE: Also need to ensure that for each of these, there is a path back to
- * root, or else they won't be done.
- * NOTE: Count how many nodes we need to handle - entry nodes may be
- * component nodes which don't count for this purpose!
- */
- GSET_FOREACH_BEGIN(OperationDepsNode *, node, graph->entry_tags)
+BLI_INLINE void flush_schedule_entrypoints(Depsgraph *graph, FlushQueue *queue)
+{
+ GSET_FOREACH_BEGIN(OperationDepsNode *, op_node, graph->entry_tags)
{
- queue.push_back(node);
- node->scheduled = true;
+ queue->push_back(op_node);
+ op_node->scheduled = true;
}
GSET_FOREACH_END();
+}
- int num_flushed_objects = 0;
- while (!queue.empty()) {
- OperationDepsNode *node = queue.front();
- queue.pop_front();
-
- for (;;) {
- node->flag |= DEPSOP_FLAG_NEEDS_UPDATE;
-
- ComponentDepsNode *comp_node = node->owner;
- IDDepsNode *id_node = comp_node->owner;
-
- ID *id = id_node->id;
- if(id_node->done == 0) {
- deg_editors_id_update(bmain, id);
- lib_id_recalc_tag(bmain, id);
- /* TODO(sergey): For until we've got proper data nodes in the graph. */
- lib_id_recalc_data_tag(bmain, id);
- }
+BLI_INLINE void flush_handle_id_node(IDDepsNode *id_node)
+{
+ id_node->done = ID_STATE_MODIFIED;
+}
- if(comp_node->done == 0) {
- Object *object = NULL;
- if (GS(id->name) == ID_OB) {
- object = (Object *)id;
- if(id_node->done == 0) {
- ++num_flushed_objects;
- }
- }
- foreach (OperationDepsNode *op, comp_node->operations) {
- op->flag |= DEPSOP_FLAG_NEEDS_UPDATE;
- }
- if (object != NULL) {
- /* This code is used to preserve those areas which does
- * direct object update,
- *
- * Plus it ensures visibility changes and relations and
- * layers visibility update has proper flags to work with.
- */
- if (comp_node->type == DEPSNODE_TYPE_ANIMATION) {
- object->recalc |= OB_RECALC_TIME;
- }
- else if (comp_node->type == DEPSNODE_TYPE_TRANSFORM) {
- object->recalc |= OB_RECALC_OB;
- }
- else {
- object->recalc |= OB_RECALC_DATA;
- }
- }
- }
+/* TODO(sergey): We can reduce number of arguments here. */
+BLI_INLINE void flush_handle_component_node(Depsgraph * /*graph*/,
+ IDDepsNode *id_node,
+ ComponentDepsNode *comp_node,
+ FlushQueue *queue)
+{
+ /* We only handle component once. */
+ if (comp_node->done == COMPONENT_STATE_DONE) {
+ return;
+ }
+ comp_node->done = COMPONENT_STATE_DONE;
+ /* Tag all required operations in component for update. */
+ foreach (OperationDepsNode *op, comp_node->operations) {
+ op->flag |= DEPSOP_FLAG_NEEDS_UPDATE;
+ }
+ if (GS(id_node->id->name) == ID_OB) {
+ Object *object = (Object *)id_node->id;
+ /* This code is used to preserve those areas which does
+ * direct object update,
+ *
+ * Plus it ensures visibility changes and relations and
+ * layers visibility update has proper flags to work with.
+ */
+ switch (comp_node->type) {
+ case DEG_NODE_TYPE_UNDEFINED:
+ case DEG_NODE_TYPE_OPERATION:
+ case DEG_NODE_TYPE_TIMESOURCE:
+ case DEG_NODE_TYPE_ID_REF:
+ case DEG_NODE_TYPE_SEQUENCER:
+ case NUM_DEG_NODE_TYPES:
+ /* Ignore, does not translate to object component. */
+ BLI_assert(!"This should never happen!");
+ break;
+ case DEG_NODE_TYPE_ANIMATION:
+ object->recalc |= OB_RECALC_TIME;
+ break;
+ case DEG_NODE_TYPE_TRANSFORM:
+ object->recalc |= OB_RECALC_OB;
+ break;
+ case DEG_NODE_TYPE_GEOMETRY:
+ case DEG_NODE_TYPE_EVAL_POSE:
+ case DEG_NODE_TYPE_BONE:
+ case DEG_NODE_TYPE_EVAL_PARTICLES:
+ case DEG_NODE_TYPE_SHADING:
+ case DEG_NODE_TYPE_CACHE:
+ case DEG_NODE_TYPE_PROXY:
+ object->recalc |= OB_RECALC_DATA;
+ break;
+ case DEG_NODE_TYPE_PARAMETERS:
+ break;
+ }
+ }
+ /* When some target changes bone, we might need to re-run the
+ * whole IK solver, otherwise result might be unpredictable.
+ */
+ if (comp_node->type == DEG_NODE_TYPE_BONE) {
+ ComponentDepsNode *pose_comp =
+ id_node->find_component(DEG_NODE_TYPE_EVAL_POSE);
+ BLI_assert(pose_comp != NULL);
+ if (pose_comp->done == COMPONENT_STATE_NONE) {
+ queue->push_front(pose_comp->get_entry_operation());
+ pose_comp->done = COMPONENT_STATE_SCHEDULED;
+ }
+ }
+}
- id_node->done = 1;
- comp_node->done = 1;
-
- /* Flush to nodes along links... */
- if (node->outlinks.size() == 1) {
- OperationDepsNode *to_node = (OperationDepsNode *)node->outlinks[0]->to;
- if (to_node->scheduled == false) {
- to_node->scheduled = true;
- node = to_node;
- }
- else {
- break;
- }
+/* Schedule children of the given operation node for traversal.
+ *
+ * One of the children will by-pass the queue and will be returned as a function
+ * return value, so it can start being handled right away, without building too
+ * much of a queue.
+ */
+BLI_INLINE OperationDepsNode *flush_schedule_children(
+ OperationDepsNode *op_node,
+ FlushQueue *queue)
+{
+ OperationDepsNode *result = NULL;
+ foreach (DepsRelation *rel, op_node->outlinks) {
+ if (rel->flag & DEPSREL_FLAG_NO_FLUSH) {
+ continue;
+ }
+ OperationDepsNode *to_node = (OperationDepsNode *)rel->to;
+ if (to_node->scheduled == false) {
+ if (result != NULL) {
+ queue->push_front(to_node);
}
else {
- foreach (DepsRelation *rel, node->outlinks) {
- OperationDepsNode *to_node = (OperationDepsNode *)rel->to;
- if (to_node->scheduled == false) {
- queue.push_front(to_node);
- to_node->scheduled = true;
- }
- }
- break;
+ result = to_node;
}
+ to_node->scheduled = true;
}
}
- DEG_DEBUG_PRINTF("Update flushed to %d objects\n", num_flushed_objects);
+ return result;
}
-static void graph_clear_func(void *data_v, int i)
+BLI_INLINE void flush_editors_id_update(Main *bmain,
+ Depsgraph *graph)
+{
+ foreach (IDDepsNode *id_node, graph->id_nodes) {
+ if (id_node->done != ID_STATE_MODIFIED) {
+ continue;
+ }
+ /* TODO(sergey): Do we need to pass original or evaluated ID here? */
+ ID *id = id_node->id;
+ deg_editors_id_update(bmain, id);
+ lib_id_recalc_tag(bmain, id);
+ /* TODO(sergey): For until we've got proper data nodes in the graph. */
+ lib_id_recalc_data_tag(bmain, id);
+ }
+}
+
+} // namespace
+
+/* Flush updates from tagged nodes outwards until all affected nodes
+ * are tagged.
+ */
+void deg_graph_flush_updates(Main *bmain, Depsgraph *graph)
+{
+ /* Sanity checks. */
+ BLI_assert(bmain != NULL);
+ BLI_assert(graph != NULL);
+ /* Nothing to update, early out. */
+ if (BLI_gset_len(graph->entry_tags) == 0) {
+ return;
+ }
+ /* Reset all flags, get ready for the flush. */
+ flush_prepare(graph);
+ /* Starting from the tagged "entry" nodes, flush outwards. */
+ FlushQueue queue;
+ flush_schedule_entrypoints(graph, &queue);
+ /* Do actual flush. */
+ while (!queue.empty()) {
+ OperationDepsNode *op_node = queue.front();
+ queue.pop_front();
+ while (op_node != NULL) {
+ /* Tag operation as required for update. */
+ op_node->flag |= DEPSOP_FLAG_NEEDS_UPDATE;
+ /* Inform corresponding ID and component nodes about the change. */
+ ComponentDepsNode *comp_node = op_node->owner;
+ IDDepsNode *id_node = comp_node->owner;
+ flush_handle_id_node(id_node);
+ flush_handle_component_node(graph,
+ id_node,
+ comp_node,
+ &queue);
+ /* Flush to nodes along links. */
+ op_node = flush_schedule_children(op_node, &queue);
+ }
+ }
+ /* Inform editors about all changes. */
+ flush_editors_id_update(bmain, graph);
+}
+
+static void graph_clear_func(
+ void *__restrict data_v,
+ const int i,
+ const ParallelRangeTLS *__restrict /*tls*/)
{
Depsgraph *graph = (Depsgraph *)data_v;
OperationDepsNode *node = graph->operations[i];
@@ -218,8 +314,13 @@ void deg_graph_clear_tags(Depsgraph *graph)
{
/* Go over all operation nodes, clearing tags. */
const int num_operations = graph->operations.size();
- const bool do_threads = num_operations > 256;
- BLI_task_parallel_range(0, num_operations, graph, graph_clear_func, do_threads);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 1024;
+ BLI_task_parallel_range(0, num_operations,
+ graph,
+ graph_clear_func,
+ &settings);
/* Clear any entry tags which haven't been flushed. */
BLI_gset_clear(graph->entry_tags, NULL);
}
diff --git a/source/blender/depsgraph/intern/eval/deg_eval_stats.cc b/source/blender/depsgraph/intern/eval/deg_eval_stats.cc
new file mode 100644
index 00000000000..52ce744cc0a
--- /dev/null
+++ b/source/blender/depsgraph/intern/eval/deg_eval_stats.cc
@@ -0,0 +1,70 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2017 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/eval/deg_eval_stats.cc
+ * \ingroup depsgraph
+ */
+
+#include "intern/eval/deg_eval_stats.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+
+#include "intern/depsgraph.h"
+
+#include "intern/nodes/deg_node.h"
+#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
+#include "intern/nodes/deg_node_operation.h"
+
+#include "util/deg_util_foreach.h"
+
+namespace DEG {
+
+void deg_eval_stats_aggregate(Depsgraph *graph)
+{
+ /* Reset current evaluation stats for ID and component nodes.
+ * Those are not filled in by the evaluation engine.
+ */
+ foreach (DepsNode *node, graph->id_nodes) {
+ IDDepsNode *id_node = (IDDepsNode *)node;
+ GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, id_node->components)
+ {
+ comp_node->stats.reset_current();
+ }
+ GHASH_FOREACH_END();
+ id_node->stats.reset_current();
+ }
+ /* Now accumulate operation timings to components and IDs. */
+ foreach (OperationDepsNode *op_node, graph->operations) {
+ ComponentDepsNode *comp_node = op_node->owner;
+ IDDepsNode *id_node = comp_node->owner;
+ id_node->stats.current_time += op_node->stats.current_time;
+ comp_node->stats.current_time += op_node->stats.current_time;
+ }
+}
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/util/deg_util_hash.h b/source/blender/depsgraph/intern/eval/deg_eval_stats.h
index e490be1a7a1..8a7272ac89c 100644
--- a/source/blender/depsgraph/util/deg_util_hash.h
+++ b/source/blender/depsgraph/intern/eval/deg_eval_stats.h
@@ -15,27 +15,26 @@
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
- * The Original Code is Copyright (C) 2014 Blender Foundation.
+ * The Original Code is Copyright (C) 2017 Blender Foundation.
* All rights reserved.
*
- * Original Author: Brecht van Lommel
- * Contributor(s): Lukas Toenne
+ * Original Author: Sergey Sharybin
+ * Contributor(s): None Yet
*
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/depsgraph/util/deg_util_hash.h
+/** \file blender/depsgraph/intern/eval/deg_eval_stats.h
* \ingroup depsgraph
*/
#pragma once
-#include "BLI_utildefines.h"
+namespace DEG {
-#include "BLI_ghash.h"
+struct Depsgraph;
-/* XXX this might require 2 different variants for sizeof(size_t) (32 vs 64 bit) */
-BLI_INLINE size_t hash_combine(size_t hash_a, size_t hash_b)
-{
- return hash_a ^ (hash_b + 0x9e3779b9 + (hash_a << 6) + (hash_a >> 2));
-}
+/* Aggregate operation timings to overall component and ID nodes timing. */
+void deg_eval_stats_aggregate(Depsgraph *graph);
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node.cc b/source/blender/depsgraph/intern/nodes/deg_node.cc
index 57b25c10670..d72ca384044 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node.cc
+++ b/source/blender/depsgraph/intern/nodes/deg_node.cc
@@ -31,45 +31,55 @@
#include "intern/nodes/deg_node.h"
#include <stdio.h>
-#include <cstring> /* required for STREQ later on. */
#include "BLI_utildefines.h"
-#include "BLI_ghash.h"
-
-extern "C" {
-#include "DNA_ID.h"
-#include "DNA_anim_types.h"
-
-#include "BKE_animsys.h"
-
-#include "DEG_depsgraph.h"
-}
#include "intern/nodes/deg_node_component.h"
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
+#include "intern/nodes/deg_node_time.h"
#include "intern/depsgraph_intern.h"
+
#include "util/deg_util_foreach.h"
-#include "util/deg_util_hash.h"
namespace DEG {
-/* *************** */
-/* Node Management */
+/*******************************************************************************
+ * Type information.
+ */
+
+DepsNode::TypeInfo::TypeInfo(eDepsNode_Type type,
+ const char *tname,
+ int id_recalc_tag)
+ : type(type),
+ tname(tname),
+ id_recalc_tag(id_recalc_tag)
+{
+}
+
+/*******************************************************************************
+ * Evaluation statistics.
+ */
+
+DepsNode::Stats::Stats()
+{
+ reset();
+}
-/* Add ------------------------------------------------ */
+void DepsNode::Stats::reset()
+{
+ current_time = 0.0;
+}
-DepsNode::TypeInfo::TypeInfo(eDepsNode_Type type, const char *tname)
+void DepsNode::Stats::reset_current()
{
- this->type = type;
- if (type == DEPSNODE_TYPE_OPERATION)
- this->tclass = DEPSNODE_CLASS_OPERATION;
- else if (type < DEPSNODE_TYPE_PARAMETERS)
- this->tclass = DEPSNODE_CLASS_GENERIC;
- else
- this->tclass = DEPSNODE_CLASS_COMPONENT;
- this->tname = tname;
+ current_time = 0.0;
}
+/*******************************************************************************
+ * Node itself.
+ */
+
DepsNode::DepsNode()
{
name = "";
@@ -97,236 +107,32 @@ string DepsNode::identifier() const
return string(typebuf) + " : " + name;
}
-/* ************* */
-/* Generic Nodes */
-
-/* Time Source Node ============================================== */
-
-void TimeSourceDepsNode::tag_update(Depsgraph *graph)
-{
- foreach (DepsRelation *rel, outlinks) {
- DepsNode *node = rel->to;
- node->tag_update(graph);
- }
-}
-
-
-/* Root Node ============================================== */
-
-RootDepsNode::RootDepsNode() : scene(NULL), time_source(NULL)
-{
-}
-
-RootDepsNode::~RootDepsNode()
-{
- OBJECT_GUARDED_DELETE(time_source, TimeSourceDepsNode);
-}
-
-TimeSourceDepsNode *RootDepsNode::add_time_source(const char *name)
-{
- if (!time_source) {
- DepsNodeFactory *factory = deg_get_node_factory(DEPSNODE_TYPE_TIMESOURCE);
- time_source = (TimeSourceDepsNode *)factory->create_node(NULL, "", name);
- /*time_source->owner = this;*/ // XXX
- }
- return time_source;
-}
-
-DEG_DEPSNODE_DEFINE(RootDepsNode, DEPSNODE_TYPE_ROOT, "Root DepsNode");
-static DepsNodeFactoryImpl<RootDepsNode> DNTI_ROOT;
-
-/* Time Source Node ======================================= */
-
-DEG_DEPSNODE_DEFINE(TimeSourceDepsNode, DEPSNODE_TYPE_TIMESOURCE, "Time Source");
-static DepsNodeFactoryImpl<TimeSourceDepsNode> DNTI_TIMESOURCE;
-
-/* ID Node ================================================ */
-
-IDDepsNode::ComponentIDKey::ComponentIDKey(eDepsNode_Type type,
- const char *name)
- : type(type), name(name)
-{
-}
-
-bool IDDepsNode::ComponentIDKey::operator== (const ComponentIDKey &other) const
-{
- return type == other.type &&
- STREQ(name, other.name);
-}
-
-static unsigned int id_deps_node_hash_key(const void *key_v)
-{
- const IDDepsNode::ComponentIDKey *key =
- reinterpret_cast<const IDDepsNode::ComponentIDKey *>(key_v);
- return hash_combine(BLI_ghashutil_uinthash(key->type),
- BLI_ghashutil_strhash_p(key->name));
-}
-
-static bool id_deps_node_hash_key_cmp(const void *a, const void *b)
-{
- const IDDepsNode::ComponentIDKey *key_a =
- reinterpret_cast<const IDDepsNode::ComponentIDKey *>(a);
- const IDDepsNode::ComponentIDKey *key_b =
- reinterpret_cast<const IDDepsNode::ComponentIDKey *>(b);
- return !(*key_a == *key_b);
-}
-
-static void id_deps_node_hash_key_free(void *key_v)
-{
- typedef IDDepsNode::ComponentIDKey ComponentIDKey;
- ComponentIDKey *key = reinterpret_cast<ComponentIDKey *>(key_v);
- OBJECT_GUARDED_DELETE(key, ComponentIDKey);
-}
-
-static void id_deps_node_hash_value_free(void *value_v)
-{
- ComponentDepsNode *comp_node = reinterpret_cast<ComponentDepsNode *>(value_v);
- OBJECT_GUARDED_DELETE(comp_node, ComponentDepsNode);
-}
-
-/* Initialize 'id' node - from pointer data given. */
-void IDDepsNode::init(const ID *id, const char *UNUSED(subdata))
-{
- /* Store ID-pointer. */
- BLI_assert(id != NULL);
- this->id = (ID *)id;
- this->layers = (1 << 20) - 1;
- this->eval_flags = 0;
-
- /* For object we initialize layers to layer from base. */
- if (GS(id->name) == ID_OB) {
- this->layers = 0;
+eDepsNode_Class DepsNode::get_class() const {
+ if (type == DEG_NODE_TYPE_OPERATION) {
+ return DEG_NODE_CLASS_OPERATION;
}
-
- components = BLI_ghash_new(id_deps_node_hash_key,
- id_deps_node_hash_key_cmp,
- "Depsgraph id components hash");
-
- /* NOTE: components themselves are created if/when needed.
- * This prevents problems with components getting added
- * twice if an ID-Ref needs to be created to house it...
- */
-}
-
-/* Free 'id' node. */
-IDDepsNode::~IDDepsNode()
-{
- clear_components();
- BLI_ghash_free(components, id_deps_node_hash_key_free, NULL);
-}
-
-ComponentDepsNode *IDDepsNode::find_component(eDepsNode_Type type,
- const char *name) const
-{
- ComponentIDKey key(type, name);
- return reinterpret_cast<ComponentDepsNode *>(BLI_ghash_lookup(components, &key));
-}
-
-ComponentDepsNode *IDDepsNode::add_component(eDepsNode_Type type,
- const char *name)
-{
- ComponentDepsNode *comp_node = find_component(type, name);
- if (!comp_node) {
- DepsNodeFactory *factory = deg_get_node_factory(type);
- comp_node = (ComponentDepsNode *)factory->create_node(this->id, "", name);
-
- /* Register. */
- ComponentIDKey *key = OBJECT_GUARDED_NEW(ComponentIDKey, type, name);
- BLI_ghash_insert(components, key, comp_node);
- comp_node->owner = this;
+ else if (type < DEG_NODE_TYPE_PARAMETERS) {
+ return DEG_NODE_CLASS_GENERIC;
}
- return comp_node;
-}
-
-void IDDepsNode::remove_component(eDepsNode_Type type, const char *name)
-{
- ComponentDepsNode *comp_node = find_component(type, name);
- if (comp_node) {
- /* Unregister. */
- ComponentIDKey key(type, name);
- BLI_ghash_remove(components,
- &key,
- id_deps_node_hash_key_free,
- id_deps_node_hash_value_free);
+ else {
+ return DEG_NODE_CLASS_COMPONENT;
}
}
-void IDDepsNode::clear_components()
-{
- BLI_ghash_clear(components,
- id_deps_node_hash_key_free,
- id_deps_node_hash_value_free);
-}
-
-void IDDepsNode::tag_update(Depsgraph *graph)
-{
- GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, components)
- {
- /* TODO(sergey): What about drievrs? */
- bool do_component_tag = comp_node->type != DEPSNODE_TYPE_ANIMATION;
- if (comp_node->type == DEPSNODE_TYPE_ANIMATION) {
- AnimData *adt = BKE_animdata_from_id(id);
- /* Animation data might be null if relations are tagged for update. */
- if (adt != NULL && (adt->recalc & ADT_RECALC_ANIM)) {
- do_component_tag = true;
- }
- }
- if (do_component_tag) {
- comp_node->tag_update(graph);
- }
- }
- GHASH_FOREACH_END();
-}
-
-void IDDepsNode::finalize_build()
-{
- GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, components)
- {
- comp_node->finalize_build();
- }
- GHASH_FOREACH_END();
-}
+/*******************************************************************************
+ * Generic nodes definition.
+ */
+\
+DEG_DEPSNODE_DEFINE(TimeSourceDepsNode, DEG_NODE_TYPE_TIMESOURCE, "Time Source");
+static DepsNodeFactoryImpl<TimeSourceDepsNode> DNTI_TIMESOURCE;
-DEG_DEPSNODE_DEFINE(IDDepsNode, DEPSNODE_TYPE_ID_REF, "ID Node");
+DEG_DEPSNODE_DEFINE(IDDepsNode, DEG_NODE_TYPE_ID_REF, "ID Node");
static DepsNodeFactoryImpl<IDDepsNode> DNTI_ID_REF;
-/* Subgraph Node ========================================== */
-
-/* Initialize 'subgraph' node - from pointer data given. */
-void SubgraphDepsNode::init(const ID *id, const char *UNUSED(subdata))
-{
- /* Store ID-ref if provided. */
- this->root_id = (ID *)id;
-
- /* NOTE: graph will need to be added manually,
- * as we don't have any way of passing this down.
- */
-}
-
-/* Free 'subgraph' node */
-SubgraphDepsNode::~SubgraphDepsNode()
-{
- /* Only free if graph not shared, of if this node is the first
- * reference to it...
- */
- // XXX: prune these flags a bit...
- if ((this->flag & SUBGRAPH_FLAG_FIRSTREF) || !(this->flag & SUBGRAPH_FLAG_SHARED)) {
- /* Free the referenced graph. */
- DEG_graph_free(reinterpret_cast< ::Depsgraph* >(graph));
- graph = NULL;
- }
-}
-
-DEG_DEPSNODE_DEFINE(SubgraphDepsNode, DEPSNODE_TYPE_SUBGRAPH, "Subgraph Node");
-static DepsNodeFactoryImpl<SubgraphDepsNode> DNTI_SUBGRAPH;
-
void deg_register_base_depsnodes()
{
- deg_register_node_typeinfo(&DNTI_ROOT);
deg_register_node_typeinfo(&DNTI_TIMESOURCE);
-
deg_register_node_typeinfo(&DNTI_ID_REF);
- deg_register_node_typeinfo(&DNTI_SUBGRAPH);
}
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node.h b/source/blender/depsgraph/intern/nodes/deg_node.h
index 7c2f53840b6..603a6be7ceb 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node.h
+++ b/source/blender/depsgraph/intern/nodes/deg_node.h
@@ -51,22 +51,24 @@ struct OperationDepsNode;
struct DepsNode {
/* Helper class for static typeinfo in subclasses. */
struct TypeInfo {
- TypeInfo(eDepsNode_Type type, const char *tname);
-
+ TypeInfo(eDepsNode_Type type, const char *tname, int id_recalc_tag = 0);
eDepsNode_Type type;
- eDepsNode_Class tclass;
const char *tname;
+ int id_recalc_tag;
+ };
+ struct Stats {
+ Stats();
+ /* Reset all the counters. Including all stats needed for average
+ * evaluation time calculation.
+ */
+ void reset();
+ /* Reset counters needed for the current graph evaluation, does not
+ * touch averaging accumulators.
+ */
+ void reset_current();
+ /* Time spend on this node during current graph evaluation. */
+ double current_time;
};
-
- /* Identifier - mainly for debugging purposes. */
- const char *name;
-
- /* Structural type of node. */
- eDepsNode_Type type;
-
- /* Type of data/behaviour represented by node... */
- eDepsNode_Class tclass;
-
/* Relationships between nodes
* The reason why all depsgraph nodes are descended from this type (apart
* from basic serialization benefits - from the typeinfo) is that we can have
@@ -74,23 +76,18 @@ struct DepsNode {
*/
typedef vector<DepsRelation *> Relations;
- /* Nodes which this one depends on. */
- Relations inlinks;
-
- /* Nodes which depend on this one. */
- Relations outlinks;
-
- /* Generic tags for traversal algorithms. */
- int done;
- int tag;
+ const char *name; /* Identifier - mainly for debugging purposes. */
+ eDepsNode_Type type; /* Structural type of node. */
+ Relations inlinks; /* Nodes which this one depends on. */
+ Relations outlinks; /* Nodes which depend on this one. */
+ int done; /* Generic tags for traversal algorithms. */
+ Stats stats; /* Evaluation statistics. */
/* Methods. */
-
DepsNode();
virtual ~DepsNode();
virtual string identifier() const;
- string full_identifier() const;
virtual void init(const ID * /*id*/,
const char * /*subdata*/) {}
@@ -99,6 +96,8 @@ struct DepsNode {
virtual OperationDepsNode *get_entry_operation() { return NULL; }
virtual OperationDepsNode *get_exit_operation() { return NULL; }
+
+ virtual eDepsNode_Class get_class() const;
};
/* Macros for common static typeinfo. */
@@ -107,119 +106,6 @@ struct DepsNode {
#define DEG_DEPSNODE_DEFINE(NodeType, type_, tname_) \
const DepsNode::TypeInfo NodeType::typeinfo = DepsNode::TypeInfo(type_, tname_)
-/* Generic Nodes ======================= */
-
-struct ComponentDepsNode;
-struct IDDepsNode;
-
-/* Time Source Node. */
-struct TimeSourceDepsNode : public DepsNode {
- /* New "current time". */
- float cfra;
-
- /* time-offset relative to the "official" time source that this one has. */
- float offset;
-
- // TODO: evaluate() operation needed
-
- void tag_update(Depsgraph *graph);
-
- DEG_DEPSNODE_DECLARE;
-};
-
-/* Root Node. */
-struct RootDepsNode : public DepsNode {
- RootDepsNode();
- ~RootDepsNode();
-
- TimeSourceDepsNode *add_time_source(const char *name = "");
-
- /* scene that this corresponds to */
- Scene *scene;
-
- /* Entrypoint node for time-changed. */
- TimeSourceDepsNode *time_source;
-
- DEG_DEPSNODE_DECLARE;
-};
-
-/* ID-Block Reference */
-struct IDDepsNode : public DepsNode {
- struct ComponentIDKey {
- ComponentIDKey(eDepsNode_Type type, const char *name = "");
- bool operator==(const ComponentIDKey &other) const;
-
- eDepsNode_Type type;
- const char *name;
- };
-
- void init(const ID *id, const char *subdata);
- ~IDDepsNode();
-
- ComponentDepsNode *find_component(eDepsNode_Type type,
- const char *name = "") const;
- ComponentDepsNode *add_component(eDepsNode_Type type,
- const char *name = "");
- void remove_component(eDepsNode_Type type, const char *name = "");
- void clear_components();
-
- void tag_update(Depsgraph *graph);
-
- void finalize_build();
-
- /* ID Block referenced. */
- ID *id;
-
- /* Hash to make it faster to look up components. */
- GHash *components;
-
- /* Layers of this node with accumulated layers of it's output relations. */
- unsigned int layers;
-
- /* Additional flags needed for scene evaluation.
- * TODO(sergey): Only needed for until really granular updates
- * of all the entities.
- */
- int eval_flags;
-
- DEG_DEPSNODE_DECLARE;
-};
-
-/* Subgraph Reference. */
-struct SubgraphDepsNode : public DepsNode {
- void init(const ID *id, const char *subdata);
- ~SubgraphDepsNode();
-
- /* Instanced graph. */
- Depsgraph *graph;
-
- /* ID-block at root of subgraph (if applicable). */
- ID *root_id;
-
- /* Number of nodes which use/reference this subgraph - if just 1, it may be
- * possible to merge into main,
- */
- size_t num_users;
-
- /* (eSubgraphRef_Flag) assorted settings for subgraph node. */
- int flag;
-
- DEG_DEPSNODE_DECLARE;
-};
-
-/* Flags for subgraph node */
-typedef enum eSubgraphRef_Flag {
- /* Subgraph referenced is shared with another reference, so shouldn't
- * free on exit.
- */
- SUBGRAPH_FLAG_SHARED = (1 << 0),
-
- /* Node is first reference to subgraph, so it can be freed when we are
- * removed.
- */
- SUBGRAPH_FLAG_FIRSTREF = (1 << 1),
-} eSubgraphRef_Flag;
-
void deg_register_base_depsnodes();
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_component.cc b/source/blender/depsgraph/intern/nodes/deg_node_component.cc
index 06f91ac7fdc..755b10c3f1d 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node_component.cc
+++ b/source/blender/depsgraph/intern/nodes/deg_node_component.cc
@@ -33,18 +33,19 @@
#include <stdio.h>
#include <cstring> /* required for STREQ later on. */
-extern "C" {
#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+extern "C" {
#include "DNA_object_types.h"
#include "BKE_action.h"
} /* extern "C" */
+#include "intern/nodes/deg_node_id.h"
#include "intern/nodes/deg_node_operation.h"
#include "intern/depsgraph_intern.h"
#include "util/deg_util_foreach.h"
-#include "util/deg_util_hash.h"
namespace DEG {
@@ -87,16 +88,16 @@ bool ComponentDepsNode::OperationIDKey::operator==(
const OperationIDKey &other) const
{
return (opcode == other.opcode) &&
- (STREQ(name, other.name)) &&
- (name_tag == other.name_tag);
+ (STREQ(name, other.name)) &&
+ (name_tag == other.name_tag);
}
static unsigned int comp_node_hash_key(const void *key_v)
{
const ComponentDepsNode::OperationIDKey *key =
reinterpret_cast<const ComponentDepsNode::OperationIDKey *>(key_v);
- return hash_combine(BLI_ghashutil_uinthash(key->opcode),
- BLI_ghashutil_strhash_p(key->name));
+ return BLI_ghashutil_combine_hash(BLI_ghashutil_uinthash(key->opcode),
+ BLI_ghashutil_strhash_p(key->name));
}
static bool comp_node_hash_key_cmp(const void *a, const void *b)
@@ -165,65 +166,79 @@ string ComponentDepsNode::identifier() const
OperationDepsNode *ComponentDepsNode::find_operation(OperationIDKey key) const
{
- OperationDepsNode *node = reinterpret_cast<OperationDepsNode *>(BLI_ghash_lookup(operations_map, &key));
- if (node != NULL) {
- return node;
+ OperationDepsNode *node = NULL;
+ if (operations_map != NULL) {
+ node = (OperationDepsNode *)BLI_ghash_lookup(operations_map, &key);
}
else {
- fprintf(stderr, "%s: find_operation(%s) failed\n",
- this->identifier().c_str(), key.identifier().c_str());
- BLI_assert(!"Request for non-existing operation, should not happen");
- return NULL;
+ BLI_assert(key.name_tag == -1);
+ foreach (OperationDepsNode *op_node, operations) {
+ if (op_node->opcode == key.opcode &&
+ STREQ(op_node->name, key.name))
+ {
+ node = op_node;
+ break;
+ }
+ }
}
+ return node;
}
OperationDepsNode *ComponentDepsNode::find_operation(eDepsOperation_Code opcode,
- const char *name,
- int name_tag) const
+ const char *name,
+ int name_tag) const
{
OperationIDKey key(opcode, name, name_tag);
return find_operation(key);
}
-OperationDepsNode *ComponentDepsNode::has_operation(OperationIDKey key) const
+OperationDepsNode *ComponentDepsNode::get_operation(OperationIDKey key) const
{
- return reinterpret_cast<OperationDepsNode *>(BLI_ghash_lookup(operations_map, &key));
+ OperationDepsNode *node = find_operation(key);
+ if (node == NULL) {
+ fprintf(stderr, "%s: find_operation(%s) failed\n",
+ this->identifier().c_str(), key.identifier().c_str());
+ BLI_assert(!"Request for non-existing operation, should not happen");
+ return NULL;
+ }
+ return node;
}
-OperationDepsNode *ComponentDepsNode::has_operation(eDepsOperation_Code opcode,
+OperationDepsNode *ComponentDepsNode::get_operation(eDepsOperation_Code opcode,
const char *name,
int name_tag) const
{
OperationIDKey key(opcode, name, name_tag);
+ return get_operation(key);
+}
+
+bool ComponentDepsNode::has_operation(OperationIDKey key) const
+{
+ return find_operation(key) != NULL;
+}
+
+bool ComponentDepsNode::has_operation(eDepsOperation_Code opcode,
+ const char *name,
+ int name_tag) const
+{
+ OperationIDKey key(opcode, name, name_tag);
return has_operation(key);
}
-OperationDepsNode *ComponentDepsNode::add_operation(eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+OperationDepsNode *ComponentDepsNode::add_operation(const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name,
int name_tag)
{
- OperationDepsNode *op_node = has_operation(opcode, name, name_tag);
+ OperationDepsNode *op_node = find_operation(opcode, name, name_tag);
if (!op_node) {
- DepsNodeFactory *factory = deg_get_node_factory(DEPSNODE_TYPE_OPERATION);
+ DepsNodeFactory *factory = deg_type_get_factory(DEG_NODE_TYPE_OPERATION);
op_node = (OperationDepsNode *)factory->create_node(this->owner->id, "", name);
/* register opnode in this component's operation set */
OperationIDKey *key = OBJECT_GUARDED_NEW(OperationIDKey, opcode, name, name_tag);
BLI_ghash_insert(operations_map, key, op_node);
- /* set as entry/exit node of component (if appropriate) */
- if (optype == DEPSOP_TYPE_INIT) {
- BLI_assert(this->entry_operation == NULL);
- this->entry_operation = op_node;
- }
- else if (optype == DEPSOP_TYPE_POST) {
- // XXX: review whether DEPSOP_TYPE_OUT is better than DEPSOP_TYPE_POST, or maybe have both?
- BLI_assert(this->exit_operation == NULL);
- this->exit_operation = op_node;
- }
-
/* set backlink */
op_node->owner = this;
}
@@ -235,13 +250,24 @@ OperationDepsNode *ComponentDepsNode::add_operation(eDepsOperation_Type optype,
/* attach extra data */
op_node->evaluate = op;
- op_node->optype = optype;
op_node->opcode = opcode;
op_node->name = name;
return op_node;
}
+void ComponentDepsNode::set_entry_operation(OperationDepsNode *op_node)
+{
+ BLI_assert(entry_operation == NULL);
+ entry_operation = op_node;
+}
+
+void ComponentDepsNode::set_exit_operation(OperationDepsNode *op_node)
+{
+ BLI_assert(exit_operation == NULL);
+ exit_operation = op_node;
+}
+
void ComponentDepsNode::clear_operations()
{
if (operations_map != NULL) {
@@ -279,7 +305,7 @@ OperationDepsNode *ComponentDepsNode::get_entry_operation()
if (entry_operation) {
return entry_operation;
}
- else if (operations_map != NULL && BLI_ghash_size(operations_map) == 1) {
+ else if (operations_map != NULL && BLI_ghash_len(operations_map) == 1) {
OperationDepsNode *op_node = NULL;
/* TODO(sergey): This is somewhat slow. */
GHASH_FOREACH_BEGIN(OperationDepsNode *, tmp, operations_map)
@@ -302,7 +328,7 @@ OperationDepsNode *ComponentDepsNode::get_exit_operation()
if (exit_operation) {
return exit_operation;
}
- else if (operations_map != NULL && BLI_ghash_size(operations_map) == 1) {
+ else if (operations_map != NULL && BLI_ghash_len(operations_map) == 1) {
OperationDepsNode *op_node = NULL;
/* TODO(sergey): This is somewhat slow. */
GHASH_FOREACH_BEGIN(OperationDepsNode *, tmp, operations_map)
@@ -322,7 +348,7 @@ OperationDepsNode *ComponentDepsNode::get_exit_operation()
void ComponentDepsNode::finalize_build()
{
- operations.reserve(BLI_ghash_size(operations_map));
+ operations.reserve(BLI_ghash_len(operations_map));
GHASH_FOREACH_BEGIN(OperationDepsNode *, op_node, operations_map)
{
operations.push_back(op_node);
@@ -334,41 +360,6 @@ void ComponentDepsNode::finalize_build()
operations_map = NULL;
}
-/* Parameter Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(ParametersComponentDepsNode, DEPSNODE_TYPE_PARAMETERS, "Parameters Component");
-static DepsNodeFactoryImpl<ParametersComponentDepsNode> DNTI_PARAMETERS;
-
-/* Animation Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(AnimationComponentDepsNode, DEPSNODE_TYPE_ANIMATION, "Animation Component");
-static DepsNodeFactoryImpl<AnimationComponentDepsNode> DNTI_ANIMATION;
-
-/* Transform Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(TransformComponentDepsNode, DEPSNODE_TYPE_TRANSFORM, "Transform Component");
-static DepsNodeFactoryImpl<TransformComponentDepsNode> DNTI_TRANSFORM;
-
-/* Proxy Component Defines ================================ */
-
-DEG_DEPSNODE_DEFINE(ProxyComponentDepsNode, DEPSNODE_TYPE_PROXY, "Proxy Component");
-static DepsNodeFactoryImpl<ProxyComponentDepsNode> DNTI_PROXY;
-
-/* Geometry Component Defines ============================= */
-
-DEG_DEPSNODE_DEFINE(GeometryComponentDepsNode, DEPSNODE_TYPE_GEOMETRY, "Geometry Component");
-static DepsNodeFactoryImpl<GeometryComponentDepsNode> DNTI_GEOMETRY;
-
-/* Sequencer Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(SequencerComponentDepsNode, DEPSNODE_TYPE_SEQUENCER, "Sequencer Component");
-static DepsNodeFactoryImpl<SequencerComponentDepsNode> DNTI_SEQUENCER;
-
-/* Pose Component ========================================= */
-
-DEG_DEPSNODE_DEFINE(PoseComponentDepsNode, DEPSNODE_TYPE_EVAL_POSE, "Pose Eval Component");
-static DepsNodeFactoryImpl<PoseComponentDepsNode> DNTI_EVAL_POSE;
-
/* Bone Component ========================================= */
/* Initialize 'bone component' node - from pointer data given */
@@ -384,28 +375,23 @@ void BoneComponentDepsNode::init(const ID *id, const char *subdata)
//this->name = subdata;
/* bone-specific node data */
- Object *ob = (Object *)id;
- this->pchan = BKE_pose_channel_find_name(ob->pose, subdata);
+ Object *object = (Object *)id;
+ this->pchan = BKE_pose_channel_find_name(object->pose, subdata);
}
-DEG_DEPSNODE_DEFINE(BoneComponentDepsNode, DEPSNODE_TYPE_BONE, "Bone Component");
-static DepsNodeFactoryImpl<BoneComponentDepsNode> DNTI_BONE;
-
-/* Particles Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(ParticlesComponentDepsNode, DEPSNODE_TYPE_EVAL_PARTICLES, "Particles Component");
-static DepsNodeFactoryImpl<ParticlesComponentDepsNode> DNTI_EVAL_PARTICLES;
-
-/* Shading Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(ShadingComponentDepsNode, DEPSNODE_TYPE_SHADING, "Shading Component");
-static DepsNodeFactoryImpl<ShadingComponentDepsNode> DNTI_SHADING;
-
-/* Cache Component Defines ============================ */
-
-DEG_DEPSNODE_DEFINE(CacheComponentDepsNode, DEPSNODE_TYPE_CACHE, "Cache Component");
-static DepsNodeFactoryImpl<CacheComponentDepsNode> DNTI_CACHE;
-
+/* Register all components. =============================== */
+
+DEG_COMPONENT_NODE_DEFINE(Animation, ANIMATION, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Bone, BONE, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Cache, CACHE, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Geometry, GEOMETRY, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Parameters, PARAMETERS, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Particles, EVAL_PARTICLES, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Proxy, PROXY, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Pose, EVAL_POSE, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Sequencer, SEQUENCER, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Shading, SHADING, ID_RECALC_NONE);
+DEG_COMPONENT_NODE_DEFINE(Transform, TRANSFORM, ID_RECALC_NONE);
/* Node Types Register =================================== */
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_component.h b/source/blender/depsgraph/intern/nodes/deg_node_component.h
index 969771a29c9..985716deaac 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node_component.h
+++ b/source/blender/depsgraph/intern/nodes/deg_node_component.h
@@ -46,6 +46,7 @@ namespace DEG {
struct Depsgraph;
struct OperationDepsNode;
struct BoneComponentDepsNode;
+struct IDDepsNode;
/* ID Component - Base type for all components */
struct ComponentDepsNode : public DepsNode {
@@ -74,18 +75,26 @@ struct ComponentDepsNode : public DepsNode {
string identifier() const;
- /* Find an existing operation, will throw an assert() if it does not exist. */
+ /* Find an existing operation, if requested operation does not exist
+ * NULL will be returned.
+ */
OperationDepsNode *find_operation(OperationIDKey key) const;
OperationDepsNode *find_operation(eDepsOperation_Code opcode,
- const char *name,
- int name_tag) const;
+ const char *name,
+ int name_tag) const;
- /* Check operation exists and return it. */
- OperationDepsNode *has_operation(OperationIDKey key) const;
- OperationDepsNode *has_operation(eDepsOperation_Code opcode,
+ /* Find an existing operation, will throw an assert() if it does not exist. */
+ OperationDepsNode *get_operation(OperationIDKey key) const;
+ OperationDepsNode *get_operation(eDepsOperation_Code opcode,
const char *name,
int name_tag) const;
+ /* Check operation exists and return it. */
+ bool has_operation(OperationIDKey key) const;
+ bool has_operation(eDepsOperation_Code opcode,
+ const char *name,
+ int name_tag) const;
+
/**
* Create a new node for representing an operation and add this to graph
* \warning If an existing node is found, it will be modified. This helps
@@ -99,29 +108,22 @@ struct ComponentDepsNode : public DepsNode {
* \param op: The operation to perform
* \param name: Identifier for operation - used to find/locate it again
*/
- OperationDepsNode *add_operation(eDepsOperation_Type optype,
- DepsEvalOperationCb op,
+ OperationDepsNode *add_operation(const DepsEvalOperationCb& op,
eDepsOperation_Code opcode,
const char *name,
int name_tag);
+ /* Entry/exit operations management.
+ *
+ * Use those instead of direct set since this will perform sanity checks.
+ */
+ void set_entry_operation(OperationDepsNode *op_node);
+ void set_exit_operation(OperationDepsNode *op_node);
+
void clear_operations();
void tag_update(Depsgraph *graph);
- /* Evaluation Context Management .................. */
-
- /* Initialize component's evaluation context used for the specified
- * purpose.
- */
- virtual bool eval_context_init(EvaluationContext * /*eval_ctx*/) { return false; }
- /* Free data in component's evaluation context which is used for
- * the specified purpose
- *
- * NOTE: this does not free the actual context in question
- */
- virtual void eval_context_free(EvaluationContext * /*eval_ctx*/) {}
-
OperationDepsNode *get_entry_operation();
OperationDepsNode *get_exit_operation();
@@ -152,33 +154,34 @@ struct ComponentDepsNode : public DepsNode {
/* ---------------------------------------- */
-struct ParametersComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct AnimationComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct TransformComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct ProxyComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct GeometryComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct SequencerComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct PoseComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
+#define DEG_COMPONENT_NODE_DEFINE_TYPEINFO(NodeType, type_, tname_, id_recalc_tag) \
+ const DepsNode::TypeInfo NodeType::typeinfo = \
+ DepsNode::TypeInfo(type_, tname_, id_recalc_tag)
+
+#define DEG_COMPONENT_NODE_DECLARE DEG_DEPSNODE_DECLARE
+
+#define DEG_COMPONENT_NODE_DEFINE(name, NAME, id_recalc_tag) \
+ DEG_COMPONENT_NODE_DEFINE_TYPEINFO(name ## ComponentDepsNode, \
+ DEG_NODE_TYPE_ ## NAME, \
+ #name " Component", \
+ id_recalc_tag) ; \
+ static DepsNodeFactoryImpl<name ## ComponentDepsNode> DNTI_ ## NAME
+
+#define DEG_COMPONENT_NODE_DECLARE_GENERIC(name) \
+ struct name ## ComponentDepsNode : public ComponentDepsNode { \
+ DEG_COMPONENT_NODE_DECLARE; \
+ }
+
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Animation);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Cache);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Geometry);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Parameters);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Particles);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Proxy);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Pose);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Sequencer);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Shading);
+DEG_COMPONENT_NODE_DECLARE_GENERIC(Transform);
/* Bone Component */
struct BoneComponentDepsNode : public ComponentDepsNode {
@@ -186,22 +189,9 @@ struct BoneComponentDepsNode : public ComponentDepsNode {
struct bPoseChannel *pchan; /* the bone that this component represents */
- DEG_DEPSNODE_DECLARE;
+ DEG_COMPONENT_NODE_DECLARE;
};
-struct ParticlesComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct ShadingComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-struct CacheComponentDepsNode : public ComponentDepsNode {
- DEG_DEPSNODE_DECLARE;
-};
-
-
void deg_register_component_depsnodes();
} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_id.cc b/source/blender/depsgraph/intern/nodes/deg_node_id.cc
new file mode 100644
index 00000000000..478cc2863b0
--- /dev/null
+++ b/source/blender/depsgraph/intern/nodes/deg_node_id.cc
@@ -0,0 +1,179 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2013 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Joshua Leung
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/nodes/deg_node_id.cc
+ * \ingroup depsgraph
+ */
+
+#include "intern/nodes/deg_node_id.h"
+
+#include <stdio.h>
+#include <cstring> /* required for STREQ later on. */
+
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+
+extern "C" {
+#include "DNA_ID.h"
+#include "DNA_anim_types.h"
+
+#include "BKE_animsys.h"
+}
+
+#include "intern/nodes/deg_node_time.h"
+#include "intern/depsgraph_intern.h"
+
+#include "util/deg_util_foreach.h"
+
+namespace DEG {
+
+IDDepsNode::ComponentIDKey::ComponentIDKey(eDepsNode_Type type,
+ const char *name)
+ : type(type), name(name)
+{
+}
+
+bool IDDepsNode::ComponentIDKey::operator== (const ComponentIDKey &other) const
+{
+ return type == other.type &&
+ STREQ(name, other.name);
+}
+
+static unsigned int id_deps_node_hash_key(const void *key_v)
+{
+ const IDDepsNode::ComponentIDKey *key =
+ reinterpret_cast<const IDDepsNode::ComponentIDKey *>(key_v);
+ return BLI_ghashutil_combine_hash(BLI_ghashutil_uinthash(key->type),
+ BLI_ghashutil_strhash_p(key->name));
+}
+
+static bool id_deps_node_hash_key_cmp(const void *a, const void *b)
+{
+ const IDDepsNode::ComponentIDKey *key_a =
+ reinterpret_cast<const IDDepsNode::ComponentIDKey *>(a);
+ const IDDepsNode::ComponentIDKey *key_b =
+ reinterpret_cast<const IDDepsNode::ComponentIDKey *>(b);
+ return !(*key_a == *key_b);
+}
+
+static void id_deps_node_hash_key_free(void *key_v)
+{
+ typedef IDDepsNode::ComponentIDKey ComponentIDKey;
+ ComponentIDKey *key = reinterpret_cast<ComponentIDKey *>(key_v);
+ OBJECT_GUARDED_DELETE(key, ComponentIDKey);
+}
+
+static void id_deps_node_hash_value_free(void *value_v)
+{
+ ComponentDepsNode *comp_node = reinterpret_cast<ComponentDepsNode *>(value_v);
+ OBJECT_GUARDED_DELETE(comp_node, ComponentDepsNode);
+}
+
+/* Initialize 'id' node - from pointer data given. */
+void IDDepsNode::init(const ID *id, const char *UNUSED(subdata))
+{
+ /* Store ID-pointer. */
+ BLI_assert(id != NULL);
+ this->id = (ID *)id;
+ this->layers = (1 << 20) - 1;
+ this->eval_flags = 0;
+
+ /* For object we initialize layers to layer from base. */
+ if (GS(id->name) == ID_OB) {
+ this->layers = 0;
+ }
+
+ components = BLI_ghash_new(id_deps_node_hash_key,
+ id_deps_node_hash_key_cmp,
+ "Depsgraph id components hash");
+
+ /* NOTE: components themselves are created if/when needed.
+ * This prevents problems with components getting added
+ * twice if an ID-Ref needs to be created to house it...
+ */
+}
+
+/* Free 'id' node. */
+IDDepsNode::~IDDepsNode()
+{
+ BLI_ghash_free(components,
+ id_deps_node_hash_key_free,
+ id_deps_node_hash_value_free);
+}
+
+ComponentDepsNode *IDDepsNode::find_component(eDepsNode_Type type,
+ const char *name) const
+{
+ ComponentIDKey key(type, name);
+ return reinterpret_cast<ComponentDepsNode *>(BLI_ghash_lookup(components, &key));
+}
+
+ComponentDepsNode *IDDepsNode::add_component(eDepsNode_Type type,
+ const char *name)
+{
+ ComponentDepsNode *comp_node = find_component(type, name);
+ if (!comp_node) {
+ DepsNodeFactory *factory = deg_type_get_factory(type);
+ comp_node = (ComponentDepsNode *)factory->create_node(this->id, "", name);
+
+ /* Register. */
+ ComponentIDKey *key = OBJECT_GUARDED_NEW(ComponentIDKey, type, name);
+ BLI_ghash_insert(components, key, comp_node);
+ comp_node->owner = this;
+ }
+ return comp_node;
+}
+
+void IDDepsNode::tag_update(Depsgraph *graph)
+{
+ GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, components)
+ {
+ /* TODO(sergey): What about drievrs? */
+ bool do_component_tag = comp_node->type != DEG_NODE_TYPE_ANIMATION;
+ if (comp_node->type == DEG_NODE_TYPE_ANIMATION) {
+ AnimData *adt = BKE_animdata_from_id(id);
+ /* Animation data might be null if relations are tagged for update. */
+ if (adt != NULL && (adt->recalc & ADT_RECALC_ANIM)) {
+ do_component_tag = true;
+ }
+ }
+ if (do_component_tag) {
+ comp_node->tag_update(graph);
+ }
+ }
+ GHASH_FOREACH_END();
+}
+
+void IDDepsNode::finalize_build()
+{
+ GHASH_FOREACH_BEGIN(ComponentDepsNode *, comp_node, components)
+ {
+ comp_node->finalize_build();
+ }
+ GHASH_FOREACH_END();
+}
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_id.h b/source/blender/depsgraph/intern/nodes/deg_node_id.h
new file mode 100644
index 00000000000..55022916c4d
--- /dev/null
+++ b/source/blender/depsgraph/intern/nodes/deg_node_id.h
@@ -0,0 +1,79 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2013 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Joshua Leung
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file depsgraph/intern/nodes/deg_node_id.h
+ * \ingroup depsgraph
+ */
+
+#pragma once
+
+#include "intern/nodes/deg_node.h"
+
+namespace DEG {
+
+struct ComponentDepsNode;
+
+/* ID-Block Reference */
+struct IDDepsNode : public DepsNode {
+ struct ComponentIDKey {
+ ComponentIDKey(eDepsNode_Type type, const char *name = "");
+ bool operator==(const ComponentIDKey &other) const;
+
+ eDepsNode_Type type;
+ const char *name;
+ };
+
+ void init(const ID *id, const char *subdata);
+ ~IDDepsNode();
+
+ ComponentDepsNode *find_component(eDepsNode_Type type,
+ const char *name = "") const;
+ ComponentDepsNode *add_component(eDepsNode_Type type,
+ const char *name = "");
+
+ void tag_update(Depsgraph *graph);
+
+ void finalize_build();
+
+ /* ID Block referenced. */
+ ID *id;
+
+ /* Hash to make it faster to look up components. */
+ GHash *components;
+
+ /* Layers of this node with accumulated layers of it's output relations. */
+ unsigned int layers;
+
+ /* Additional flags needed for scene evaluation.
+ * TODO(sergey): Only needed for until really granular updates
+ * of all the entities.
+ */
+ int eval_flags;
+
+ DEG_DEPSNODE_DECLARE;
+};
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_operation.cc b/source/blender/depsgraph/intern/nodes/deg_node_operation.cc
index 9eed4dfe8d8..cbc0fbb4241 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node_operation.cc
+++ b/source/blender/depsgraph/intern/nodes/deg_node_operation.cc
@@ -32,13 +32,12 @@
#include "MEM_guardedalloc.h"
-extern "C" {
#include "BLI_utildefines.h"
-} /* extern "C" */
+#include "BLI_ghash.h"
#include "intern/depsgraph.h"
#include "intern/depsgraph_intern.h"
-#include "util/deg_util_hash.h"
+#include "intern/nodes/deg_node_id.h"
namespace DEG {
@@ -46,7 +45,6 @@ namespace DEG {
/* Inner Nodes */
OperationDepsNode::OperationDepsNode() :
- eval_priority(0.0f),
flag(0),
customdata_mask(0)
{
@@ -67,7 +65,7 @@ string OperationDepsNode::identifier() const
string OperationDepsNode::full_identifier() const
{
string owner_str = "";
- if (owner->type == DEPSNODE_TYPE_BONE) {
+ if (owner->type == DEG_NODE_TYPE_BONE) {
owner_str = string(owner->owner->name) + "." + owner->name;
}
else {
@@ -86,7 +84,19 @@ void OperationDepsNode::tag_update(Depsgraph *graph)
graph->add_entry_tag(this);
}
-DEG_DEPSNODE_DEFINE(OperationDepsNode, DEPSNODE_TYPE_OPERATION, "Operation");
+void OperationDepsNode::set_as_entry()
+{
+ BLI_assert(owner != NULL);
+ owner->set_entry_operation(this);
+}
+
+void OperationDepsNode::set_as_exit()
+{
+ BLI_assert(owner != NULL);
+ owner->set_exit_operation(this);
+}
+
+DEG_DEPSNODE_DEFINE(OperationDepsNode, DEG_NODE_TYPE_OPERATION, "Operation");
static DepsNodeFactoryImpl<OperationDepsNode> DNTI_OPERATION;
void deg_register_operation_depsnodes()
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_operation.h b/source/blender/depsgraph/intern/nodes/deg_node_operation.h
index 598393054db..c172f73be5f 100644
--- a/source/blender/depsgraph/intern/nodes/deg_node_operation.h
+++ b/source/blender/depsgraph/intern/nodes/deg_node_operation.h
@@ -38,27 +38,19 @@ struct Depsgraph;
namespace DEG {
+struct ComponentDepsNode;
+
/* Flags for Depsgraph Nodes */
typedef enum eDepsOperation_Flag {
/* node needs to be updated */
DEPSOP_FLAG_NEEDS_UPDATE = (1 << 0),
/* node was directly modified, causing need for update */
- /* XXX: intention is to make it easier to tell when we just need to
- * take subgraphs.
- */
DEPSOP_FLAG_DIRECTLY_MODIFIED = (1 << 1),
-
- /* Operation is evaluated using CPython; has GIL and security
- * implications...
- */
- DEPSOP_FLAG_USES_PYTHON = (1 << 2),
} eDepsOperation_Flag;
/* Atomic Operation - Base type for all operations */
struct OperationDepsNode : public DepsNode {
-
-
OperationDepsNode();
~OperationDepsNode();
@@ -72,21 +64,20 @@ struct OperationDepsNode : public DepsNode {
OperationDepsNode *get_entry_operation() { return this; }
OperationDepsNode *get_exit_operation() { return this; }
+ /* Set this operation as compoonent's entry/exit operation. */
+ void set_as_entry();
+ void set_as_exit();
+
/* Component that contains the operation. */
ComponentDepsNode *owner;
/* Callback for operation. */
DepsEvalOperationCb evaluate;
-
/* How many inlinks are we still waiting on before we can be evaluated. */
uint32_t num_links_pending;
- float eval_priority;
bool scheduled;
- /* Stage of evaluation */
- eDepsOperation_Type optype;
-
/* Identifier for the operation being performed. */
eDepsOperation_Code opcode;
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_time.cc b/source/blender/depsgraph/intern/nodes/deg_node_time.cc
new file mode 100644
index 00000000000..230488b2328
--- /dev/null
+++ b/source/blender/depsgraph/intern/nodes/deg_node_time.cc
@@ -0,0 +1,46 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2013 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Joshua Leung
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/depsgraph/intern/nodes/deg_node_time.cc
+ * \ingroup depsgraph
+ */
+
+#include "intern/nodes/deg_node_time.h"
+
+#include "intern/depsgraph_intern.h"
+#include "util/deg_util_foreach.h"
+
+namespace DEG {
+
+void TimeSourceDepsNode::tag_update(Depsgraph *graph)
+{
+ foreach (DepsRelation *rel, outlinks) {
+ DepsNode *node = rel->to;
+ node->tag_update(graph);
+ }
+}
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/intern/nodes/deg_node_time.h b/source/blender/depsgraph/intern/nodes/deg_node_time.h
new file mode 100644
index 00000000000..93f3edef9cf
--- /dev/null
+++ b/source/blender/depsgraph/intern/nodes/deg_node_time.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2013 Blender Foundation.
+ * All rights reserved.
+ *
+ * Original Author: Joshua Leung
+ * Contributor(s): None Yet
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file depsgraph/intern/nodes/deg_node_time.h
+ * \ingroup depsgraph
+ */
+
+#pragma once
+
+#include "intern/nodes/deg_node.h"
+
+namespace DEG {
+
+/* Time Source Node. */
+struct TimeSourceDepsNode : public DepsNode {
+ /* New "current time". */
+ float cfra;
+
+ /* time-offset relative to the "official" time source that this one has. */
+ float offset;
+
+ // TODO: evaluate() operation needed
+
+ void tag_update(Depsgraph *graph);
+
+ DEG_DEPSNODE_DECLARE;
+};
+
+} // namespace DEG
diff --git a/source/blender/depsgraph/util/deg_util_foreach.h b/source/blender/depsgraph/util/deg_util_foreach.h
index 87d37168d51..cb7361fc708 100644
--- a/source/blender/depsgraph/util/deg_util_foreach.h
+++ b/source/blender/depsgraph/util/deg_util_foreach.h
@@ -46,28 +46,3 @@
# define foreach(x, y) for (x; false; (void)y)
#endif
-
-#define GHASH_FOREACH_BEGIN(type, var, what) \
- do { \
- GHashIterator gh_iter##var; \
- GHASH_ITER(gh_iter##var, what) { \
- type var = reinterpret_cast<type>(BLI_ghashIterator_getValue(&gh_iter##var)); \
-
-#define GHASH_FOREACH_END() \
- } \
- } while(0)
-
-#define GSET_FOREACH_BEGIN(type, var, what) \
- do { \
- GSetIterator gh_iter##var; \
- GSET_ITER(gh_iter##var, what) { \
- type var = reinterpret_cast<type>(BLI_gsetIterator_getKey(&gh_iter##var)); \
-
-#define GSET_FOREACH_END() \
- } \
- } while(0)
-
-#define LINKLIST_FOREACH(type, var, list) \
- for (type var = (type)((list)->first); \
- var != NULL; \
- var = (type)(((Link*)(var))->next))
diff --git a/source/blender/depsgraph/util/deg_util_function.h b/source/blender/depsgraph/util/deg_util_function.h
index 1e34ae04d9a..99625e57f4b 100644
--- a/source/blender/depsgraph/util/deg_util_function.h
+++ b/source/blender/depsgraph/util/deg_util_function.h
@@ -30,7 +30,7 @@
#pragma once
-#if (__cplusplus > 199711L)
+#if (__cplusplus > 199711L) || (defined(_MSC_VER) && _MSC_VER >= 1900)
#include <functional>
diff --git a/source/blender/editors/CMakeLists.txt b/source/blender/editors/CMakeLists.txt
index 1559512d713..17a8eef1bdb 100644
--- a/source/blender/editors/CMakeLists.txt
+++ b/source/blender/editors/CMakeLists.txt
@@ -29,6 +29,7 @@ if(WITH_BLENDER)
add_subdirectory(gpencil)
add_subdirectory(interface)
add_subdirectory(io)
+ add_subdirectory(lattice)
add_subdirectory(mask)
add_subdirectory(mesh)
add_subdirectory(metaball)
@@ -58,6 +59,7 @@ if(WITH_BLENDER)
add_subdirectory(space_userpref)
add_subdirectory(space_view3d)
add_subdirectory(transform)
+ add_subdirectory(undo)
add_subdirectory(util)
add_subdirectory(uvedit)
endif()
diff --git a/source/blender/editors/animation/anim_channels_defines.c b/source/blender/editors/animation/anim_channels_defines.c
index 57302c18a88..dba060bfb29 100644
--- a/source/blender/editors/animation/anim_channels_defines.c
+++ b/source/blender/editors/animation/anim_channels_defines.c
@@ -2775,7 +2775,7 @@ static bAnimChannelType ACF_DSMCLIP =
acf_generic_indention_1, /* indent level */
acf_generic_basic_offset, /* offset */
- acf_generic_idblock_name , /* name */
+ acf_generic_idblock_name, /* name */
acf_generic_idfill_name_prop, /* name prop */
acf_dsmclip_icon, /* icon */
@@ -3856,7 +3856,8 @@ void ANIM_channel_draw(bAnimContext *ac, bAnimListElem *ale, float yminc, float
if (ac->sl) {
if ((ac->spacetype == SPACE_IPO) &&
(acf->has_setting(ac, ale, ACHANNEL_SETTING_VISIBLE) ||
- acf->has_setting(ac, ale, ACHANNEL_SETTING_ALWAYS_VISIBLE))) {
+ acf->has_setting(ac, ale, ACHANNEL_SETTING_ALWAYS_VISIBLE)))
+ {
/* for F-Curves, draw color-preview of curve behind checkbox */
if (ELEM(ale->type, ANIMTYPE_FCURVE, ANIMTYPE_NLACURVE)) {
FCurve *fcu = (FCurve *)ale->data;
@@ -4457,8 +4458,8 @@ void ANIM_channel_draw_widgets(const bContext *C, bAnimContext *ac, bAnimListEle
* a callback available (e.g. broken F-Curve rename)
*/
if (acf->name_prop(ale, &ptr, &prop)) {
- const short margin_x = 3 * iroundf(UI_DPI_FAC);
- const short channel_height = iroundf(ymaxc - yminc);
+ const short margin_x = 3 * round_fl_to_int(UI_DPI_FAC);
+ const short channel_height = round_fl_to_int(ymaxc - yminc);
const short width = ac->ar->winx - offset - (margin_x * 2);
uiBut *but;
diff --git a/source/blender/editors/animation/anim_channels_edit.c b/source/blender/editors/animation/anim_channels_edit.c
index 117b8549712..20904ed0263 100644
--- a/source/blender/editors/animation/anim_channels_edit.c
+++ b/source/blender/editors/animation/anim_channels_edit.c
@@ -34,11 +34,9 @@
#include "MEM_guardedalloc.h"
-#include "BKE_depsgraph.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BLI_listbase.h"
-#include "BKE_library.h"
#include "DNA_anim_types.h"
#include "DNA_object_types.h"
@@ -52,11 +50,13 @@
#include "BKE_animsys.h"
#include "BKE_action.h"
+#include "BKE_depsgraph.h"
#include "BKE_fcurve.h"
#include "BKE_gpencil.h"
#include "BKE_context.h"
#include "BKE_mask.h"
#include "BKE_global.h"
+#include "BKE_library.h"
#include "UI_view2d.h"
@@ -223,6 +223,33 @@ void ANIM_set_active_channel(bAnimContext *ac, void *data, eAnimCont_Types datat
ANIM_animdata_freelist(&anim_data);
}
+static void select_pchan_for_action_group(bAnimContext *ac, bActionGroup *agrp, bAnimListElem *ale)
+{
+ /* Armatures-Specific Feature:
+ * See mouse_anim_channels() -> ANIMTYPE_GROUP case for more details (T38737)
+ */
+ if ((ac->ads->filterflag & ADS_FILTER_ONLYSEL) == 0) {
+ if ((ale->id) && (GS(ale->id->name) == ID_OB)) {
+ Object *ob = (Object *)ale->id;
+ if (ob->type == OB_ARMATURE) {
+ /* Assume for now that any group with corresponding name is what we want
+ * (i.e. for an armature whose location is animated, things would break
+ * if the user were to add a bone named "Location").
+ *
+ * TODO: check the first F-Curve or so to be sure...
+ */
+ bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, agrp->name);
+ if (agrp->flag & AGRP_SELECTED) {
+ ED_pose_bone_select(ob, pchan, true);
+ }
+ else {
+ ED_pose_bone_select(ob, pchan, false);
+ }
+ }
+ }
+ }
+}
+
/* Deselect all animation channels
* - data: pointer to datatype, as contained in bAnimContext
* - datatype: the type of data that 'data' represents (eAnimCont_Types)
@@ -343,8 +370,8 @@ void ANIM_deselect_anim_channels(bAnimContext *ac, void *data, eAnimCont_Types d
case ANIMTYPE_GROUP:
{
bActionGroup *agrp = (bActionGroup *)ale->data;
-
ACHANNEL_SET_FLAG(agrp, sel, AGRP_SELECTED);
+ select_pchan_for_action_group(ac, agrp, ale);
agrp->flag &= ~AGRP_ACTIVE;
break;
}
@@ -680,7 +707,7 @@ typedef enum eRearrangeAnimChan_Mode {
} eRearrangeAnimChan_Mode;
/* defines for rearranging channels */
-static EnumPropertyItem prop_animchannel_rearrange_types[] = {
+static const EnumPropertyItem prop_animchannel_rearrange_types[] = {
{REARRANGE_ANIMCHAN_TOP, "TOP", 0, "To Top", ""},
{REARRANGE_ANIMCHAN_UP, "UP", 0, "Up", ""},
{REARRANGE_ANIMCHAN_DOWN, "DOWN", 0, "Down", ""},
@@ -1743,7 +1770,7 @@ static void ANIM_OT_channels_delete(wmOperatorType *ot)
/* ********************** Set Flags Operator *********************** */
/* defines for setting animation-channel flags */
-static EnumPropertyItem prop_animchannel_setflag_types[] = {
+static const EnumPropertyItem prop_animchannel_setflag_types[] = {
{ACHANNEL_SETFLAG_TOGGLE, "TOGGLE", 0, "Toggle", ""},
{ACHANNEL_SETFLAG_CLEAR, "DISABLE", 0, "Disable", ""},
{ACHANNEL_SETFLAG_ADD, "ENABLE", 0, "Enable", ""},
@@ -1753,7 +1780,7 @@ static EnumPropertyItem prop_animchannel_setflag_types[] = {
/* defines for set animation-channel settings */
// TODO: could add some more types, but those are really quite dependent on the mode...
-static EnumPropertyItem prop_animchannel_settings_types[] = {
+static const EnumPropertyItem prop_animchannel_settings_types[] = {
{ACHANNEL_SETTING_PROTECT, "PROTECT", 0, "Protect", ""},
{ACHANNEL_SETTING_MUTE, "MUTE", 0, "Mute", ""},
{0, NULL, 0, NULL, NULL}
@@ -2396,33 +2423,7 @@ static void borderselect_anim_channels(bAnimContext *ac, rcti *rect, short selec
case ANIMTYPE_GROUP:
{
bActionGroup *agrp = (bActionGroup *)ale->data;
-
- /* Armatures-Specific Feature:
- * See mouse_anim_channels() -> ANIMTYPE_GROUP case for more details (T38737)
- */
- if ((ac->ads->filterflag & ADS_FILTER_ONLYSEL) == 0) {
- if ((ale->id) && (GS(ale->id->name) == ID_OB)) {
- Object *ob = (Object *)ale->id;
-
- if (ob->type == OB_ARMATURE) {
- /* Assume for now that any group with corresponding name is what we want
- * (i.e. for an armature whose location is animated, things would break
- * if the user were to add a bone named "Location").
- *
- * TODO: check the first F-Curve or so to be sure...
- */
- bPoseChannel *pchan = BKE_pose_channel_find_name(ob->pose, agrp->name);
-
- if (agrp->flag & AGRP_SELECTED) {
- ED_pose_bone_select(ob, pchan, true);
- }
- else {
- ED_pose_bone_select(ob, pchan, false);
- }
- }
- }
- }
-
+ select_pchan_for_action_group(ac, agrp, ale);
/* always clear active flag after doing this */
agrp->flag &= ~AGRP_ACTIVE;
break;
@@ -2455,8 +2456,8 @@ static int animchannels_borderselect_exec(bContext *C, wmOperator *op)
bAnimContext ac;
rcti rect;
short selectmode = 0;
- int gesture_mode;
- bool extend;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* get editor data */
if (ANIM_animdata_get_context(C, &ac) == 0)
@@ -2464,17 +2465,17 @@ static int animchannels_borderselect_exec(bContext *C, wmOperator *op)
/* get settings from operator */
WM_operator_properties_border_to_rcti(op, &rect);
-
- gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- extend = RNA_boolean_get(op->ptr, "extend");
- if (!extend)
+ if (!extend) {
ANIM_deselect_anim_channels(&ac, ac.data, ac.datatype, true, ACHANNEL_SETFLAG_CLEAR);
+ }
- if (gesture_mode == GESTURE_MODAL_SELECT)
+ if (select) {
selectmode = ACHANNEL_SETFLAG_ADD;
- else
+ }
+ else {
selectmode = ACHANNEL_SETFLAG_CLEAR;
+ }
/* apply borderselect animation channels */
borderselect_anim_channels(&ac, &rect, selectmode);
@@ -2493,10 +2494,10 @@ static void ANIM_OT_channels_select_border(wmOperatorType *ot)
ot->description = "Select all animation channels within the specified region";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = animchannels_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = animedit_poll_channels_nla_tweakmode_off;
@@ -2504,7 +2505,7 @@ static void ANIM_OT_channels_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/* ******************* Rename Operator ***************************** */
@@ -2687,41 +2688,43 @@ static int mouse_anim_channels(bContext *C, bAnimContext *ac, int channel_index,
AnimData *adt = ob->adt;
/* set selection status */
- if (selectmode == SELECT_INVERT) {
- /* swap select */
- base->flag ^= SELECT;
- ob->flag = base->flag;
-
- if (adt) adt->flag ^= ADT_UI_SELECTED;
- }
- else {
- Base *b;
-
- /* deselect all */
- /* TODO: should this deselect all other types of channels too? */
- for (b = sce->base.first; b; b = b->next) {
- b->flag &= ~SELECT;
- b->object->flag = b->flag;
- if (b->object->adt) b->object->adt->flag &= ~(ADT_UI_SELECTED | ADT_UI_ACTIVE);
+ if ((ob->restrictflag & OB_RESTRICT_SELECT) == 0) {
+ if (selectmode == SELECT_INVERT) {
+ /* swap select */
+ base->flag ^= SELECT;
+ ob->flag = base->flag;
+
+ if (adt) adt->flag ^= ADT_UI_SELECTED;
}
-
- /* select object now */
- base->flag |= SELECT;
- ob->flag |= SELECT;
- if (adt) adt->flag |= ADT_UI_SELECTED;
+ else {
+ Base *b;
+
+ /* deselect all */
+ /* TODO: should this deselect all other types of channels too? */
+ for (b = sce->base.first; b; b = b->next) {
+ b->flag &= ~SELECT;
+ b->object->flag = b->flag;
+ if (b->object->adt) b->object->adt->flag &= ~(ADT_UI_SELECTED | ADT_UI_ACTIVE);
+ }
+
+ /* select object now */
+ base->flag |= SELECT;
+ ob->flag |= SELECT;
+ if (adt) adt->flag |= ADT_UI_SELECTED;
+ }
+
+ /* change active object - regardless of whether it is now selected [T37883] */
+ ED_base_object_activate(C, base); /* adds notifier */
+
+ if ((adt) && (adt->flag & ADT_UI_SELECTED))
+ adt->flag |= ADT_UI_ACTIVE;
+
+ /* ensure we exit editmode on whatever object was active before to avoid getting stuck there - T48747 */
+ if (ob != sce->obedit)
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
+
+ notifierFlags |= (ND_ANIMCHAN | NA_SELECTED);
}
-
- /* change active object - regardless of whether it is now selected [T37883] */
- ED_base_object_activate(C, base); /* adds notifier */
-
- if ((adt) && (adt->flag & ADT_UI_SELECTED))
- adt->flag |= ADT_UI_ACTIVE;
-
- /* ensure we exit editmode on whatever object was active before to avoid getting stuck there - T48747 */
- if (ob != sce->obedit)
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO);
-
- notifierFlags |= (ND_ANIMCHAN | NA_SELECTED);
break;
}
case ANIMTYPE_FILLACTD: /* Action Expander */
@@ -2809,7 +2812,7 @@ static int mouse_anim_channels(bContext *C, bAnimContext *ac, int channel_index,
/* deselect all other channels */
ANIM_deselect_anim_channels(ac, ac->data, ac->datatype, false, ACHANNEL_SETFLAG_CLEAR);
- if (pchan) ED_pose_de_selectall(ob, SEL_DESELECT, false);
+ if (pchan) ED_pose_deselect_all(ob, SEL_DESELECT, false);
/* only select channels in group and group itself */
for (fcu = agrp->channels.first; fcu && fcu->grp == agrp; fcu = fcu->next)
@@ -2819,7 +2822,7 @@ static int mouse_anim_channels(bContext *C, bAnimContext *ac, int channel_index,
else {
/* select group by itself */
ANIM_deselect_anim_channels(ac, ac->data, ac->datatype, false, ACHANNEL_SETFLAG_CLEAR);
- if (pchan) ED_pose_de_selectall(ob, SEL_DESELECT, false);
+ if (pchan) ED_pose_deselect_all(ob, SEL_DESELECT, false);
agrp->flag |= AGRP_SELECTED;
}
@@ -3082,7 +3085,7 @@ static bool select_anim_channel_keys(bAnimContext *ac, int channel_index, bool e
for (ale = anim_data.first; ale; ale = ale->next) {
FCurve *fcu_inner = (FCurve *)ale->key_data;
- if (fcu_inner) {
+ if (fcu_inner != NULL && fcu_inner->bezt != NULL) {
for (i = 0, bezt = fcu_inner->bezt; i < fcu_inner->totvert; i++, bezt++) {
bezt->f2 = bezt->f1 = bezt->f3 = 0;
}
diff --git a/source/blender/editors/animation/anim_draw.c b/source/blender/editors/animation/anim_draw.c
index 98900812bb2..a6febdb575e 100644
--- a/source/blender/editors/animation/anim_draw.c
+++ b/source/blender/editors/animation/anim_draw.c
@@ -579,6 +579,7 @@ void ANIM_center_frame(struct bContext *C, int smooth_viewtx)
break;
}
/* else drop through, keep range instead */
+ ATTR_FALLTHROUGH;
case ZOOM_FRAME_MODE_KEEP_RANGE:
default:
diff --git a/source/blender/editors/animation/anim_filter.c b/source/blender/editors/animation/anim_filter.c
index 2f73eb6b71c..aa31458aa5b 100644
--- a/source/blender/editors/animation/anim_filter.c
+++ b/source/blender/editors/animation/anim_filter.c
@@ -114,7 +114,7 @@ static void animedit_get_yscale_factor(bAnimContext *ac)
/* grab scale factor directly from action editor setting
* NOTE: This theme setting doesn't have an ID, as it cannot be accessed normally
- * since it is a float, and the theem settings methods can only handle chars.
+ * since it is a float, and the theme settings methods can only handle chars.
*/
ac->yscale_fac = btheme->tact.keyframe_scale_fac;
@@ -877,6 +877,7 @@ static bAnimListElem *make_new_animlistelem(void *data, short datatype, ID *owne
break;
}
case ANIMTYPE_FCURVE:
+ case ANIMTYPE_NLACURVE: /* practically the same as ANIMTYPE_FCURVE. Differences are applied post-creation */
{
FCurve *fcu = (FCurve *)data;
@@ -1086,13 +1087,14 @@ static bool name_matches_dopesheet_filter(bDopeSheet *ads, char *name)
/* (Display-)Name-based F-Curve filtering
* NOTE: when this function returns true, the F-Curve is to be skipped
*/
-static bool skip_fcurve_with_name(bDopeSheet *ads, FCurve *fcu, ID *owner_id)
+static bool skip_fcurve_with_name(bDopeSheet *ads, FCurve *fcu, eAnim_ChannelType channel_type, void *owner, ID *owner_id)
{
bAnimListElem ale_dummy = {NULL};
const bAnimChannelType *acf;
- /* create a dummy wrapper for the F-Curve */
- ale_dummy.type = ANIMTYPE_FCURVE;
+ /* create a dummy wrapper for the F-Curve, so we can get typeinfo for it */
+ ale_dummy.type = channel_type;
+ ale_dummy.owner = owner;
ale_dummy.id = owner_id;
ale_dummy.data = fcu;
@@ -1155,8 +1157,9 @@ static bool fcurve_has_errors(FCurve *fcu)
}
/* find the next F-Curve that is usable for inclusion */
-static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGroup *grp, int filter_mode, ID *owner_id)
+static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, eAnim_ChannelType channel_type, int filter_mode, void *owner, ID *owner_id)
{
+ bActionGroup *grp = (channel_type == ANIMTYPE_FCURVE) ? owner : NULL;
FCurve *fcu = NULL;
/* loop over F-Curves - assume that the caller of this has already checked that these should be included
@@ -1190,7 +1193,7 @@ static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGro
if (!(filter_mode & ANIMFILTER_ACTIVE) || (fcu->flag & FCURVE_ACTIVE)) {
/* name based filtering... */
if ( ((ads) && (ads->filterflag & ADS_FILTER_BY_FCU_NAME)) && (owner_id) ) {
- if (skip_fcurve_with_name(ads, fcu, owner_id))
+ if (skip_fcurve_with_name(ads, fcu, channel_type, owner, owner_id))
continue;
}
@@ -1213,7 +1216,10 @@ static FCurve *animfilter_fcurve_next(bDopeSheet *ads, FCurve *first, bActionGro
return NULL;
}
-static size_t animfilter_fcurves(ListBase *anim_data, bDopeSheet *ads, FCurve *first, bActionGroup *grp, int filter_mode, ID *owner_id)
+static size_t animfilter_fcurves(ListBase *anim_data, bDopeSheet *ads,
+ FCurve *first, eAnim_ChannelType fcurve_type,
+ int filter_mode,
+ void *owner, ID *owner_id)
{
FCurve *fcu;
size_t items = 0;
@@ -1227,8 +1233,18 @@ static size_t animfilter_fcurves(ListBase *anim_data, bDopeSheet *ads, FCurve *f
* 4) the fcu pointer is set to the F-Curve after the one we just added, so that we can keep going through
* the rest of the F-Curve list without an eternal loop. Back to step 2 :)
*/
- for (fcu = first; ( (fcu = animfilter_fcurve_next(ads, fcu, grp, filter_mode, owner_id)) ); fcu = fcu->next) {
- ANIMCHANNEL_NEW_CHANNEL(fcu, ANIMTYPE_FCURVE, owner_id);
+ for (fcu = first; ( (fcu = animfilter_fcurve_next(ads, fcu, fcurve_type, filter_mode, owner, owner_id)) ); fcu = fcu->next) {
+ if (UNLIKELY(fcurve_type == ANIMTYPE_NLACURVE)) {
+ /* NLA Control Curve - Basically the same as normal F-Curves, except we need to set some stuff differently */
+ ANIMCHANNEL_NEW_CHANNEL_FULL(fcu, ANIMTYPE_NLACURVE, owner_id, {
+ ale->owner = owner; /* strip */
+ ale->adt = NULL; /* to prevent time mapping from causing problems */
+ });
+ }
+ else {
+ /* Normal FCurve */
+ ANIMCHANNEL_NEW_CHANNEL(fcu, ANIMTYPE_FCURVE, owner_id);
+ }
}
/* return the number of items added to the list */
@@ -1279,10 +1295,10 @@ static size_t animfilter_act_group(bAnimContext *ac, ListBase *anim_data, bDopeS
/* group must be editable for its children to be editable (if we care about this) */
if (!(filter_mode & ANIMFILTER_FOREDIT) || EDITABLE_AGRP(agrp)) {
/* get first F-Curve which can be used here */
- FCurve *first_fcu = animfilter_fcurve_next(ads, agrp->channels.first, agrp, filter_mode, owner_id);
+ FCurve *first_fcu = animfilter_fcurve_next(ads, agrp->channels.first, ANIMTYPE_FCURVE, filter_mode, agrp, owner_id);
/* filter list, starting from this F-Curve */
- tmp_items += animfilter_fcurves(&tmp_data, ads, first_fcu, agrp, filter_mode, owner_id);
+ tmp_items += animfilter_fcurves(&tmp_data, ads, first_fcu, ANIMTYPE_FCURVE, filter_mode, agrp, owner_id);
}
}
}
@@ -1321,7 +1337,7 @@ static size_t animfilter_action(bAnimContext *ac, ListBase *anim_data, bDopeShee
/* don't include anything from this action if it is linked in from another file,
* and we're getting stuff for editing...
*/
- if ((filter_mode & ANIMFILTER_FOREDIT) && ID_IS_LINKED_DATABLOCK(act))
+ if ((filter_mode & ANIMFILTER_FOREDIT) && ID_IS_LINKED(act))
return 0;
/* do groups */
@@ -1338,7 +1354,7 @@ static size_t animfilter_action(bAnimContext *ac, ListBase *anim_data, bDopeShee
/* un-grouped F-Curves (only if we're not only considering those channels in the active group) */
if (!(filter_mode & ANIMFILTER_ACTGROUPED)) {
FCurve *firstfcu = (lastchan) ? (lastchan->next) : (act->curves.first);
- items += animfilter_fcurves(anim_data, ads, firstfcu, NULL, filter_mode, owner_id);
+ items += animfilter_fcurves(anim_data, ads, firstfcu, ANIMTYPE_FCURVE, filter_mode, NULL, owner_id);
}
/* return the number of items added to the list */
@@ -1460,36 +1476,8 @@ static size_t animfilter_nla_controls(ListBase *anim_data, bDopeSheet *ads, Anim
/* for now, we only go one level deep - so controls on grouped FCurves are not handled */
for (nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
for (strip = nlt->strips.first; strip; strip = strip->next) {
- ListBase strip_curves = {NULL, NULL};
- size_t strip_items = 0;
-
- /* create the raw items */
- strip_items += animfilter_fcurves(&strip_curves, ads, strip->fcurves.first, NULL, filter_mode, owner_id);
-
- /* change their types and add extra data
- * - There is no point making a separate copy of animfilter_fcurves for this now/yet,
- * unless we later get per-element control curves for other stuff too
- */
- if (strip_items) {
- bAnimListElem *ale, *ale_n = NULL;
-
- for (ale = strip_curves.first; ale; ale = ale_n) {
- ale_n = ale->next;
-
- /* change the type to being a FCurve for editing NLA strip controls */
- BLI_assert(ale->type == ANIMTYPE_FCURVE);
-
- ale->type = ANIMTYPE_NLACURVE;
- ale->owner = strip;
-
- ale->adt = NULL; /* XXX: This way, there are no problems with time mapping errors */
- }
- }
-
- /* add strip curves to the set of channels inside the group being collected */
- BLI_movelisttolist(&tmp_data, &strip_curves);
- BLI_assert(BLI_listbase_is_empty(&strip_curves));
- tmp_items += strip_items;
+ /* pass strip as the "owner", so that the name lookups (used while filtering) will resolve */
+ tmp_items += animfilter_fcurves(&tmp_data, ads, strip->fcurves.first, ANIMTYPE_NLACURVE, filter_mode, strip, owner_id);
}
}
}
@@ -1540,7 +1528,7 @@ static size_t animfilter_block_data(bAnimContext *ac, ListBase *anim_data, bDope
items += animfilter_nla(ac, anim_data, ads, adt, filter_mode, id);
},
{ /* Drivers */
- items += animfilter_fcurves(anim_data, ads, adt->drivers.first, NULL, filter_mode, id);
+ items += animfilter_fcurves(anim_data, ads, adt->drivers.first, ANIMTYPE_FCURVE, filter_mode, NULL, id);
},
{ /* NLA Control Keyframes */
items += animfilter_nla_controls(anim_data, ads, adt, filter_mode, id);
@@ -2247,6 +2235,8 @@ static void animfilter_modifier_idpoin_cb(void *afm_ptr, Object *ob, ID **idpoin
}
/* TODO: images? */
+ default:
+ break;
}
}
diff --git a/source/blender/editors/animation/anim_markers.c b/source/blender/editors/animation/anim_markers.c
index 823cde75334..031102c9f35 100644
--- a/source/blender/editors/animation/anim_markers.c
+++ b/source/blender/editors/animation/anim_markers.c
@@ -133,10 +133,13 @@ int ED_markers_post_apply_transform(ListBase *markers, Scene *scene, int mode, f
float cfra = (float)CFRA;
int changed_tot = 0;
- /* sanity check */
- if (markers == NULL)
+ /* sanity check - no markers, or locked markers */
+ if ((scene->toolsettings->lock_markers) ||
+ (markers == NULL))
+ {
return changed_tot;
-
+ }
+
/* affect selected markers - it's unlikely that we will want to affect all in this way? */
for (marker = markers->first; marker; marker = marker->next) {
if (marker->flag & SELECT) {
@@ -149,7 +152,7 @@ int ED_markers_post_apply_transform(ListBase *markers, Scene *scene, int mode, f
(side == 'L' && marker->frame < cfra) ||
(side == 'R' && marker->frame >= cfra))
{
- marker->frame += iroundf(value);
+ marker->frame += round_fl_to_int(value);
changed_tot++;
}
break;
@@ -157,7 +160,7 @@ int ED_markers_post_apply_transform(ListBase *markers, Scene *scene, int mode, f
case TFM_TIME_SCALE:
{
/* rescale the distance between the marker and the current frame */
- marker->frame = cfra + iroundf((float)(marker->frame - cfra) * value);
+ marker->frame = cfra + round_fl_to_int((float)(marker->frame - cfra) * value);
changed_tot++;
break;
}
@@ -195,7 +198,7 @@ TimeMarker *ED_markers_find_nearest_marker(ListBase *markers, float x)
int ED_markers_find_nearest_marker_time(ListBase *markers, float x)
{
TimeMarker *nearest = ED_markers_find_nearest_marker(markers, x);
- return (nearest) ? (nearest->frame) : iroundf(x);
+ return (nearest) ? (nearest->frame) : round_fl_to_int(x);
}
@@ -888,13 +891,14 @@ static int ed_marker_move_modal(bContext *C, wmOperator *op, const wmEvent *even
ed_marker_move_cancel(C, op);
return OPERATOR_CANCELLED;
}
- /* else continue; <--- see if release event should be caught for tweak-end */
+ /* else continue; <--- see if release event should be caught for tweak-end */
+ ATTR_FALLTHROUGH;
case RETKEY:
case PADENTER:
case LEFTMOUSE:
case MIDDLEMOUSE:
- if (WM_modal_tweak_exit(event, mm->event_type)) {
+ if (WM_event_is_modal_tweak_exit(event, mm->event_type)) {
ed_marker_move_exit(C, op);
WM_event_add_notifier(C, NC_SCENE | ND_MARKERS, NULL);
WM_event_add_notifier(C, NC_ANIMATION | ND_MARKERS, NULL);
@@ -1091,14 +1095,15 @@ static void select_timeline_marker_frame(ListBase *markers, int frame, bool exte
}
}
- BLI_LISTBASE_CIRCULAR_FORWARD_BEGIN (markers, marker, marker_first) {
+ LISTBASE_CIRCULAR_FORWARD_BEGIN(markers, marker, marker_first)
+ {
/* this way a not-extend select will always give 1 selected marker */
if (marker->frame == frame) {
marker->flag ^= SELECT;
break;
}
}
- BLI_LISTBASE_CIRCULAR_FORWARD_END (markers, marker, marker_first);
+ LISTBASE_CIRCULAR_FORWARD_END(markers, marker, marker_first);
}
static int ed_marker_select(bContext *C, const wmEvent *event, bool extend, bool camera)
@@ -1229,7 +1234,7 @@ static int ed_marker_border_select_exec(bContext *C, wmOperator *op)
View2D *v2d = UI_view2d_fromcontext(C);
ListBase *markers = ED_context_get_markers(C);
TimeMarker *marker;
- int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ bool select = !RNA_boolean_get(op->ptr, "deselect");
bool extend = RNA_boolean_get(op->ptr, "extend");
rctf rect;
@@ -1242,13 +1247,11 @@ static int ed_marker_border_select_exec(bContext *C, wmOperator *op)
/* XXX marker context */
for (marker = markers->first; marker; marker = marker->next) {
if (BLI_rctf_isect_x(&rect, marker->frame)) {
- switch (gesture_mode) {
- case GESTURE_MODAL_SELECT:
- marker->flag |= SELECT;
- break;
- case GESTURE_MODAL_DESELECT:
- marker->flag &= ~SELECT;
- break;
+ if (select) {
+ marker->flag |= SELECT;
+ }
+ else {
+ marker->flag &= ~SELECT;
}
}
else if (!extend) {
@@ -1264,7 +1267,7 @@ static int ed_marker_border_select_exec(bContext *C, wmOperator *op)
static int ed_marker_select_border_invoke_wrapper(bContext *C, wmOperator *op, const wmEvent *event)
{
- return ed_markers_opwrap_invoke_custom(C, op, event, WM_border_select_invoke);
+ return ed_markers_opwrap_invoke_custom(C, op, event, WM_gesture_border_invoke);
}
static void MARKER_OT_select_border(wmOperatorType *ot)
@@ -1277,8 +1280,8 @@ static void MARKER_OT_select_border(wmOperatorType *ot)
/* api callbacks */
ot->exec = ed_marker_border_select_exec;
ot->invoke = ed_marker_select_border_invoke_wrapper;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ed_markers_poll_markers_exist;
@@ -1286,7 +1289,7 @@ static void MARKER_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/* *********************** (de)select all ***************** */
diff --git a/source/blender/editors/animation/anim_ops.c b/source/blender/editors/animation/anim_ops.c
index bb73cbf03b4..f22c8c5b403 100644
--- a/source/blender/editors/animation/anim_ops.c
+++ b/source/blender/editors/animation/anim_ops.c
@@ -103,11 +103,12 @@ static void change_frame_apply(bContext *C, wmOperator *op)
}
/* set the new frame number */
- CFRA = (int)frame;
if (scene->r.flag & SCER_SHOW_SUBFRAME) {
+ CFRA = (int)frame;
SUBFRA = frame - (int)frame;
}
else {
+ CFRA = round_fl_to_int(frame);
SUBFRA = 0.0f;
}
FRAMENUMBER_MIN_CLAMP(CFRA);
@@ -134,15 +135,12 @@ static float frame_from_event(bContext *C, const wmEvent *event)
{
ARegion *region = CTX_wm_region(C);
Scene *scene = CTX_data_scene(C);
- float viewx;
float frame;
/* convert from region coordinates to View2D 'tot' space */
- viewx = UI_view2d_region_to_view_x(&region->v2d, event->mval[0]);
-
- /* round result to nearest int (frames are ints!) */
- frame = viewx;
+ frame = UI_view2d_region_to_view_x(&region->v2d, event->mval[0]);
+ /* respect preview range restrictions (if only allowed to move around within that range) */
if (scene->r.flag & SCER_LOCK_FRAME_SELECTION) {
CLAMP(frame, PSFRA, PEFRA);
}
@@ -303,8 +301,8 @@ static int previewrange_define_exec(bContext *C, wmOperator *op)
if (efra < sfra) efra = sfra;
scene->r.flag |= SCER_PRV_RANGE;
- scene->r.psfra = iroundf(sfra);
- scene->r.pefra = iroundf(efra);
+ scene->r.psfra = round_fl_to_int(sfra);
+ scene->r.pefra = round_fl_to_int(efra);
/* send notifiers */
WM_event_add_notifier(C, NC_SCENE | ND_FRAME, scene);
@@ -320,10 +318,10 @@ static void ANIM_OT_previewrange_set(wmOperatorType *ot)
ot->description = "Interactively define frame range used for playback";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = previewrange_define_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_animview_active;
diff --git a/source/blender/editors/animation/drivers.c b/source/blender/editors/animation/drivers.c
index 21c25f829b1..24eb6451c5d 100644
--- a/source/blender/editors/animation/drivers.c
+++ b/source/blender/editors/animation/drivers.c
@@ -40,6 +40,7 @@
#include "BLI_string.h"
#include "DNA_anim_types.h"
+#include "DNA_object_types.h"
#include "DNA_texture_types.h"
#include "BKE_animsys.h"
@@ -101,6 +102,7 @@ FCurve *verify_driver_fcurve(ID *id, const char rna_path[], const int array_inde
fcu = MEM_callocN(sizeof(FCurve), "FCurve");
fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED);
+ fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL;
/* store path - make copy, and store that */
fcu->rna_path = BLI_strdup(rna_path);
@@ -122,7 +124,7 @@ FCurve *verify_driver_fcurve(ID *id, const char rna_path[], const int array_inde
* Create FModifier so that old scripts won't break
* for now before 2.7 series -- (September 4, 2013)
*/
- add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
+ add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
}
else {
/* add 2 keyframes so that user has something to work with
@@ -764,7 +766,7 @@ EnumPropertyItem prop_driver_create_mapping_types[] = {
};
/* Filtering callback for driver mapping types enum */
-static EnumPropertyItem *driver_mapping_type_itemsf(bContext *C, PointerRNA *UNUSED(owner_ptr), PropertyRNA *UNUSED(owner_prop), bool *r_free)
+static const EnumPropertyItem *driver_mapping_type_itemsf(bContext *C, PointerRNA *UNUSED(owner_ptr), PropertyRNA *UNUSED(owner_prop), bool *r_free)
{
EnumPropertyItem *input = prop_driver_create_mapping_types;
EnumPropertyItem *item = NULL;
@@ -1029,6 +1031,11 @@ static int paste_driver_button_exec(bContext *C, wmOperator *op)
UI_context_update_anim_flag(C);
+ DAG_relations_tag_update(CTX_data_main(C));
+ DAG_id_tag_update(ptr.id.data, OB_RECALC_OB | OB_RECALC_DATA);
+
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME_PROP, NULL); // XXX
+
MEM_freeN(path);
}
}
diff --git a/source/blender/editors/animation/fmodifier_ui.c b/source/blender/editors/animation/fmodifier_ui.c
index 6bb73416fec..8106be79521 100644
--- a/source/blender/editors/animation/fmodifier_ui.c
+++ b/source/blender/editors/animation/fmodifier_ui.c
@@ -62,7 +62,7 @@
#include "UI_resources.h"
#include "ED_anim_api.h"
-#include "ED_util.h"
+#include "ED_undo.h"
/* ********************************************** */
/* UI STUFF */
@@ -736,7 +736,7 @@ bool ANIM_fmodifiers_copy_to_buf(ListBase *modifiers, bool active)
/* 'Paste' the F-Modifier(s) from the buffer to the specified list
* - replace: free all the existing modifiers to leave only the pasted ones
*/
-bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace)
+bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace, FCurve *curve)
{
FModifier *fcm;
bool ok = false;
@@ -745,6 +745,8 @@ bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace)
if (modifiers == NULL)
return 0;
+ bool was_cyclic = curve && BKE_fcurve_is_cyclic(curve);
+
/* if replacing the list, free the existing modifiers */
if (replace)
free_fmodifiers(modifiers);
@@ -753,6 +755,8 @@ bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace)
for (fcm = fmodifier_copypaste_buf.first; fcm; fcm = fcm->next) {
/* make a copy of it */
FModifier *fcmN = copy_fmodifier(fcm);
+
+ fcmN->curve = curve;
/* make sure the new one isn't active, otherwise the list may get several actives */
fcmN->flag &= ~FMODIFIER_FLAG_ACTIVE;
@@ -762,6 +766,10 @@ bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace)
ok = 1;
}
+ /* adding or removing the Cycles modifier requires an update to handles */
+ if (curve && BKE_fcurve_is_cyclic(curve) != was_cyclic)
+ calchandles_fcurve(curve);
+
/* did we succeed? */
return ok;
}
diff --git a/source/blender/editors/animation/keyframes_draw.c b/source/blender/editors/animation/keyframes_draw.c
index 5f675e690b9..f25dbf2381c 100644
--- a/source/blender/editors/animation/keyframes_draw.c
+++ b/source/blender/editors/animation/keyframes_draw.c
@@ -751,7 +751,7 @@ void draw_fcurve_channel(View2D *v2d, AnimData *adt, FCurve *fcu, float ypos, fl
bool locked = (fcu->flag & FCURVE_PROTECTED) ||
((fcu->grp) && (fcu->grp->flag & AGRP_PROTECTED)) ||
- ((adt && adt->action) && ID_IS_LINKED_DATABLOCK(adt->action));
+ ((adt && adt->action) && ID_IS_LINKED(adt->action));
BLI_dlrbTree_init(&keys);
BLI_dlrbTree_init(&blocks);
@@ -772,7 +772,7 @@ void draw_agroup_channel(View2D *v2d, AnimData *adt, bActionGroup *agrp, float y
DLRBT_Tree keys, blocks;
bool locked = (agrp->flag & AGRP_PROTECTED) ||
- ((adt && adt->action) && ID_IS_LINKED_DATABLOCK(adt->action));
+ ((adt && adt->action) && ID_IS_LINKED(adt->action));
BLI_dlrbTree_init(&keys);
BLI_dlrbTree_init(&blocks);
@@ -792,7 +792,7 @@ void draw_action_channel(View2D *v2d, AnimData *adt, bAction *act, float ypos, f
{
DLRBT_Tree keys, blocks;
- bool locked = (act && ID_IS_LINKED_DATABLOCK(act));
+ bool locked = (act && ID_IS_LINKED(act));
BLI_dlrbTree_init(&keys);
BLI_dlrbTree_init(&blocks);
diff --git a/source/blender/editors/animation/keyframes_edit.c b/source/blender/editors/animation/keyframes_edit.c
index 4571df0f077..0ef6aa4bd4a 100644
--- a/source/blender/editors/animation/keyframes_edit.c
+++ b/source/blender/editors/animation/keyframes_edit.c
@@ -36,7 +36,7 @@
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_math.h"
#include "DNA_anim_types.h"
@@ -452,7 +452,7 @@ void ANIM_editkeyframes_refresh(bAnimContext *ac)
ok |= KEYFRAME_OK_H2; \
} \
} (void)0
-
+
/* ------------------------ */
static short ok_bezier_frame(KeyframeEditData *ked, BezTriple *bezt)
diff --git a/source/blender/editors/animation/keyframes_general.c b/source/blender/editors/animation/keyframes_general.c
index c1e82583521..bf5d4ec0300 100644
--- a/source/blender/editors/animation/keyframes_general.c
+++ b/source/blender/editors/animation/keyframes_general.c
@@ -52,6 +52,7 @@
#include "BKE_deform.h"
#include "RNA_access.h"
+#include "RNA_enum_types.h"
#include "ED_anim_api.h"
#include "ED_keyframing.h"
@@ -447,6 +448,18 @@ void sample_fcurve(FCurve *fcu)
/* check if selected, and which end this is */
if (BEZT_ISSEL_ANY(bezt)) {
if (start) {
+ /* If next bezt is also selected, don't start sampling yet,
+ * but instead wait for that one to reconsider, to avoid
+ * changing the curve when sampling consecutive segments
+ * (T53229)
+ */
+ if (i < fcu->totvert - 1) {
+ BezTriple *next = &fcu->bezt[i + 1];
+ if (BEZT_ISSEL_ANY(next)) {
+ continue;
+ }
+ }
+
/* set end */
end = bezt;
@@ -479,8 +492,8 @@ void sample_fcurve(FCurve *fcu)
i += (range - 1);
}
- /* bezt was selected, so it now marks the start of a whole new chain to search */
- start = bezt;
+ /* the current selection island has ended, so start again from scratch */
+ start = NULL;
end = NULL;
}
else {
@@ -884,14 +897,14 @@ static void paste_animedit_keys_fcurve(FCurve *fcu, tAnimCopybufItem *aci, float
/* ------------------- */
-EnumPropertyItem rna_enum_keyframe_paste_offset_items[] = {
+const EnumPropertyItem rna_enum_keyframe_paste_offset_items[] = {
{KEYFRAME_PASTE_OFFSET_CFRA_START, "START", 0, "Frame Start", "Paste keys starting at current frame"},
{KEYFRAME_PASTE_OFFSET_CFRA_END, "END", 0, "Frame End", "Paste keys ending at current frame"},
{KEYFRAME_PASTE_OFFSET_CFRA_RELATIVE, "RELATIVE", 0, "Frame Relative", "Paste keys relative to the current frame when copying"},
{KEYFRAME_PASTE_OFFSET_NONE, "NONE", 0, "No Offset", "Paste keys from original time"},
{0, NULL, 0, NULL, NULL}};
-EnumPropertyItem rna_enum_keyframe_paste_merge_items[] = {
+const EnumPropertyItem rna_enum_keyframe_paste_merge_items[] = {
{KEYFRAME_PASTE_MERGE_MIX, "MIX", 0, "Mix", "Overlay existing with new keys"},
{KEYFRAME_PASTE_MERGE_OVER, "OVER_ALL", 0, "Overwrite All", "Replace all keys"},
{KEYFRAME_PASTE_MERGE_OVER_RANGE, "OVER_RANGE", 0, "Overwrite Range", "Overwrite keys in pasted range"},
diff --git a/source/blender/editors/animation/keyframing.c b/source/blender/editors/animation/keyframing.c
index f2a35bb1553..c2a0b6579bb 100644
--- a/source/blender/editors/animation/keyframing.c
+++ b/source/blender/editors/animation/keyframing.c
@@ -90,7 +90,7 @@
/* Get the active settings for keyframing settings from context (specifically the given scene) */
short ANIM_get_keyframing_flags(Scene *scene, short incl_mode)
{
- short flag = 0;
+ eInsertKeyFlags flag = INSERTKEY_NOFLAGS;
/* standard flags */
{
@@ -145,7 +145,7 @@ bAction *verify_adt_action(ID *id, short add)
BLI_snprintf(actname, sizeof(actname), "%sAction", id->name + 2);
/* create action */
- adt->action = add_empty_action(G.main, actname);
+ adt->action = BKE_action_add(G.main, actname);
/* set ID-type from ID-block that this is going to be assigned to
* so that users can't accidentally break actions by assigning them
@@ -186,6 +186,7 @@ FCurve *verify_fcurve(bAction *act, const char group[], PointerRNA *ptr,
fcu = MEM_callocN(sizeof(FCurve), "FCurve");
fcu->flag = (FCURVE_VISIBLE | FCURVE_SELECTED);
+ fcu->auto_smoothing = FCURVE_SMOOTH_CONT_ACCEL;
if (BLI_listbase_is_empty(&act->curves))
fcu->flag |= FCURVE_ACTIVE; /* first one added active */
@@ -301,7 +302,7 @@ void update_autoflags_fcurve(FCurve *fcu, bContext *C, ReportList *reports, Poin
* NOTE: any recalculate of the F-Curve that needs to be done will need to
* be done by the caller.
*/
-int insert_bezt_fcurve(FCurve *fcu, const BezTriple *bezt, short flag)
+int insert_bezt_fcurve(FCurve *fcu, const BezTriple *bezt, eInsertKeyFlags flag)
{
int i = 0;
@@ -388,11 +389,11 @@ int insert_bezt_fcurve(FCurve *fcu, const BezTriple *bezt, short flag)
* adding a new keyframe to a curve, when the keyframe doesn't exist anywhere else yet.
* It returns the index at which the keyframe was added.
*
- * \param keyframe_type: The type of keyframe (eBezTriple_KeyframeTypes)
+ * \param keyframe_type: The type of keyframe (eBezTriple_KeyframeType)
* \param flag: Optional flags (eInsertKeyFlags) for controlling how keys get added
* and/or whether updates get done
*/
-int insert_vert_fcurve(FCurve *fcu, float x, float y, char keyframe_type, short flag)
+int insert_vert_fcurve(FCurve *fcu, float x, float y, eBezTriple_KeyframeType keyframe_type, eInsertKeyFlags flag)
{
BezTriple beztr = {{{0}}};
unsigned int oldTot = fcu->totvert;
@@ -880,13 +881,13 @@ static float visualkey_get_value(PointerRNA *ptr, PropertyRNA *prop, int array_i
* Use this when validation of necessary animation data is not necessary, since an RNA-pointer to the necessary
* data being keyframed, and a pointer to the F-Curve to use have both been provided.
*
- * keytype is the "keyframe type" (eBezTriple_KeyframeTypes), as shown in the Dope Sheet.
+ * keytype is the "keyframe type" (eBezTriple_KeyframeType), as shown in the Dope Sheet.
*
* The flag argument is used for special settings that alter the behavior of
* the keyframe insertion. These include the 'visual' keyframing modes, quick refresh,
* and extra keyframe filtering.
*/
-bool insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *prop, FCurve *fcu, float cfra, char keytype, short flag)
+bool insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *prop, FCurve *fcu, float cfra, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag)
{
float curval = 0.0f;
@@ -1005,7 +1006,7 @@ bool insert_keyframe_direct(ReportList *reports, PointerRNA ptr, PropertyRNA *pr
*
* index of -1 keys all array indices
*/
-short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, char keytype, short flag)
+short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag)
{
PointerRNA id_ptr, ptr;
PropertyRNA *prop = NULL;
@@ -1073,10 +1074,11 @@ short insert_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
/* for Loc/Rot/Scale and also Color F-Curves, the color of the F-Curve in the Graph Editor,
* is determined by the array index for the F-Curve
*/
- if (ELEM(RNA_property_subtype(prop), PROP_TRANSLATION, PROP_XYZ, PROP_EULER, PROP_COLOR, PROP_COORDS)) {
+ PropertySubType prop_subtype = RNA_property_subtype(prop);
+ if (ELEM(prop_subtype, PROP_TRANSLATION, PROP_XYZ, PROP_EULER, PROP_COLOR, PROP_COORDS)) {
fcu->color_mode = FCURVE_COLOR_AUTO_RGB;
}
- else if (RNA_property_subtype(prop), PROP_QUATERNION) {
+ else if (ELEM(prop_subtype, PROP_QUATERNION)) {
fcu->color_mode = FCURVE_COLOR_AUTO_YRGB;
}
}
@@ -1127,7 +1129,7 @@ static bool delete_keyframe_fcurve(AnimData *adt, FCurve *fcu, float cfra)
return false;
}
-short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, short UNUSED(flag))
+short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, float cfra, eInsertKeyFlags UNUSED(flag))
{
AnimData *adt = BKE_animdata_from_id(id);
PointerRNA id_ptr, ptr;
@@ -1216,7 +1218,7 @@ short delete_keyframe(ReportList *reports, ID *id, bAction *act, const char grou
* The flag argument is used for special settings that alter the behavior of
* the keyframe deletion. These include the quick refresh options.
*/
-static short clear_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, short UNUSED(flag))
+static short clear_keyframe(ReportList *reports, ID *id, bAction *act, const char group[], const char rna_path[], int array_index, eInsertKeyFlags UNUSED(flag))
{
AnimData *adt = BKE_animdata_from_id(id);
PointerRNA id_ptr, ptr;
@@ -1354,7 +1356,7 @@ static int insert_key_exec(bContext *C, wmOperator *op)
* updated since the last switching to the edit mode will be keyframed correctly
*/
if (obedit && ANIM_keyingset_find_id(ks, (ID *)obedit->data)) {
- ED_object_toggle_modes(C, OB_MODE_EDIT);
+ ED_object_mode_toggle(C, OB_MODE_EDIT);
ob_edit_mode = true;
}
@@ -1365,7 +1367,7 @@ static int insert_key_exec(bContext *C, wmOperator *op)
/* restore the edit mode if necessary */
if (ob_edit_mode) {
- ED_object_toggle_modes(C, OB_MODE_EDIT);
+ ED_object_mode_toggle(C, OB_MODE_EDIT);
}
/* report failure or do updates? */
@@ -1765,7 +1767,8 @@ static int insert_key_button_exec(bContext *C, wmOperator *op)
short success = 0;
int index;
const bool all = RNA_boolean_get(op->ptr, "all");
- short flag = 0;
+ eInsertKeyFlags flag = INSERTKEY_NOFLAGS;
+
/* flags for inserting keyframes */
flag = ANIM_get_keyframing_flags(scene, 1);
@@ -1785,7 +1788,13 @@ static int insert_key_button_exec(bContext *C, wmOperator *op)
NlaStrip *strip = (NlaStrip *)ptr.data;
FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), index);
- success = insert_keyframe_direct(op->reports, ptr, prop, fcu, cfra, ts->keyframe_type, 0);
+ if (fcu) {
+ success = insert_keyframe_direct(op->reports, ptr, prop, fcu, cfra, ts->keyframe_type, 0);
+ }
+ else {
+ BKE_report(op->reports, RPT_ERROR,
+ "This property cannot be animated as it will not get updated correctly");
+ }
}
else if (UI_but_flag_is_set(but, UI_BUT_DRIVEN)) {
/* Driven property - Find driver */
@@ -1881,7 +1890,7 @@ static int delete_key_button_exec(bContext *C, wmOperator *op)
}
if (ptr.id.data && ptr.data && prop) {
- if (ptr.type == &RNA_NlaStrip) {
+ if (BKE_nlastrip_has_curves_for_property(&ptr, prop)) {
/* Handle special properties for NLA Strips, whose F-Curves are stored on the
* strips themselves. These are stored separately or else the properties will
* not have any effect.
@@ -1890,27 +1899,27 @@ static int delete_key_button_exec(bContext *C, wmOperator *op)
NlaStrip *strip = (NlaStrip *)ptr.data;
FCurve *fcu = list_find_fcurve(&strip->fcurves, RNA_property_identifier(prop), 0);
- BLI_assert(fcu != NULL); /* NOTE: This should be true, or else we wouldn't be able to get here */
-
- if (BKE_fcurve_is_protected(fcu)) {
- BKE_reportf(op->reports, RPT_WARNING,
- "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'",
- strip->name, BKE_idcode_to_name(GS(id->name)), id->name + 2);
- }
- else {
- /* remove the keyframe directly
- * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve,
- * and delete_keyframe() expects the FCurve to be part of an action
- */
- bool found = false;
- int i;
-
- /* try to find index of beztriple to get rid of */
- i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
- if (found) {
- /* delete the key at the index (will sanity check + do recalc afterwards) */
- delete_fcurve_key(fcu, i, 1);
- success = true;
+ if (fcu) {
+ if (BKE_fcurve_is_protected(fcu)) {
+ BKE_reportf(op->reports, RPT_WARNING,
+ "Not deleting keyframe for locked F-Curve for NLA Strip influence on %s - %s '%s'",
+ strip->name, BKE_idcode_to_name(GS(id->name)), id->name + 2);
+ }
+ else {
+ /* remove the keyframe directly
+ * NOTE: cannot use delete_keyframe_fcurve(), as that will free the curve,
+ * and delete_keyframe() expects the FCurve to be part of an action
+ */
+ bool found = false;
+ int i;
+
+ /* try to find index of beztriple to get rid of */
+ i = binarysearch_bezt_index(fcu->bezt, cfra, fcu->totvert, &found);
+ if (found) {
+ /* delete the key at the index (will sanity check + do recalc afterwards) */
+ delete_fcurve_key(fcu, i, 1);
+ success = true;
+ }
}
}
}
diff --git a/source/blender/editors/animation/keyingsets.c b/source/blender/editors/animation/keyingsets.c
index 4408ec26b3f..ad08caba799 100644
--- a/source/blender/editors/animation/keyingsets.c
+++ b/source/blender/editors/animation/keyingsets.c
@@ -726,7 +726,7 @@ KeyingSet *ANIM_get_keyingset_for_autokeying(Scene *scene, const char *tranformK
/* Menu of All Keying Sets ----------------------------- */
/* Dynamically populate an enum of Keying Sets */
-EnumPropertyItem *ANIM_keying_sets_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *ANIM_keying_sets_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Scene *scene = CTX_data_scene(C);
KeyingSet *ks;
@@ -1052,6 +1052,8 @@ int ANIM_apply_keyingset(bContext *C, ListBase *dsources, bAction *act, KeyingSe
DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
break;
}
+ default:
+ break;
}
/* send notifiers for updates (this doesn't require context to work!) */
diff --git a/source/blender/editors/armature/CMakeLists.txt b/source/blender/editors/armature/CMakeLists.txt
index b213aca478f..4c394d7836a 100644
--- a/source/blender/editors/armature/CMakeLists.txt
+++ b/source/blender/editors/armature/CMakeLists.txt
@@ -48,6 +48,7 @@ set(SRC
editarmature_generate.c
editarmature_retarget.c
editarmature_sketch.c
+ editarmature_undo.c
meshlaplacian.c
pose_edit.c
pose_lib.c
diff --git a/source/blender/editors/armature/armature_add.c b/source/blender/editors/armature/armature_add.c
index bbc81f522fa..cb072bee345 100644
--- a/source/blender/editors/armature/armature_add.c
+++ b/source/blender/editors/armature/armature_add.c
@@ -63,12 +63,12 @@
/* default bone add, returns it selected, but without tail set */
/* XXX should be used everywhere, now it mallocs bones still locally in functions */
-EditBone *ED_armature_edit_bone_add(bArmature *arm, const char *name)
+EditBone *ED_armature_ebone_add(bArmature *arm, const char *name)
{
EditBone *bone = MEM_callocN(sizeof(EditBone), "eBone");
BLI_strncpy(bone->name, name, sizeof(bone->name));
- unique_editbone_name(arm->edbo, bone->name, NULL);
+ ED_armature_ebone_unique_name(arm->edbo, bone->name, NULL);
BLI_addtail(arm->edbo, bone);
@@ -77,34 +77,35 @@ EditBone *ED_armature_edit_bone_add(bArmature *arm, const char *name)
bone->dist = 0.25f;
bone->xwidth = 0.1f;
bone->zwidth = 0.1f;
- bone->ease1 = 1.0f;
- bone->ease2 = 1.0f;
bone->rad_head = 0.10f;
bone->rad_tail = 0.05f;
bone->segments = 1;
bone->layer = arm->layer;
+ /* Bendy-Bone parameters */
bone->roll1 = 0.0f;
bone->roll2 = 0.0f;
bone->curveInX = 0.0f;
bone->curveInY = 0.0f;
bone->curveOutX = 0.0f;
bone->curveOutY = 0.0f;
+ bone->ease1 = 1.0f;
+ bone->ease2 = 1.0f;
bone->scaleIn = 1.0f;
bone->scaleOut = 1.0f;
return bone;
}
-EditBone *ED_armature_edit_bone_add_primitive(Object *obedit_arm, float length, bool view_aligned)
+EditBone *ED_armature_ebone_add_primitive(Object *obedit_arm, float length, bool view_aligned)
{
bArmature *arm = obedit_arm->data;
EditBone *bone;
- ED_armature_deselect_all(obedit_arm);
+ ED_armature_edit_deselect_all(obedit_arm);
/* Create a bone */
- bone = ED_armature_edit_bone_add(arm, "Bone");
+ bone = ED_armature_ebone_add(arm, "Bone");
arm->act_edbone = bone;
@@ -156,12 +157,12 @@ static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
to_root = 1;
}
- ED_armature_deselect_all(obedit);
+ ED_armature_edit_deselect_all(obedit);
/* we re-use code for mirror editing... */
flipbone = NULL;
if (arm->flag & ARM_MIRROR_EDIT)
- flipbone = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
for (a = 0; a < 2; a++) {
if (a == 1) {
@@ -172,7 +173,7 @@ static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
}
}
- newbone = ED_armature_edit_bone_add(arm, ebone->name);
+ newbone = ED_armature_ebone_add(arm, ebone->name);
arm->act_edbone = newbone;
if (to_root) {
@@ -204,7 +205,7 @@ static int armature_click_extrude_exec(bContext *C, wmOperator *UNUSED(op))
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -267,7 +268,7 @@ EditBone *add_points_bone(Object *obedit, float head[3], float tail[3])
{
EditBone *ebo;
- ebo = ED_armature_edit_bone_add(obedit->data, "Bone");
+ ebo = ED_armature_ebone_add(obedit->data, "Bone");
copy_v3_v3(ebo->head, head);
copy_v3_v3(ebo->tail, tail);
@@ -332,7 +333,7 @@ void postEditBoneDuplicate(struct ListBase *editbones, Object *ob)
for (EditBone *ebone_src = editbones->first; ebone_src; ebone_src = ebone_src->next) {
EditBone *ebone_dst = ebone_src->temp.ebone;
if (!ebone_dst) {
- ebone_dst = ED_armature_bone_get_mirrored(editbones, ebone_src);
+ ebone_dst = ED_armature_ebone_get_mirrored(editbones, ebone_src);
}
if (ebone_dst) {
BLI_ghash_insert(name_map, ebone_src->name, ebone_dst->name);
@@ -437,7 +438,7 @@ EditBone *duplicateEditBoneObjects(EditBone *curBone, const char *name, ListBase
BLI_strncpy(eBone->name, name, sizeof(eBone->name));
}
- unique_editbone_name(editbones, eBone->name, NULL);
+ ED_armature_ebone_unique_name(editbones, eBone->name, NULL);
BLI_addtail(editbones, eBone);
/* copy the ID property */
@@ -471,7 +472,7 @@ EditBone *duplicateEditBone(EditBone *curBone, const char *name, ListBase *editb
return duplicateEditBoneObjects(curBone, name, editbones, ob, ob);
}
-static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
+static int armature_duplicate_selected_exec(bContext *C, wmOperator *op)
{
bArmature *arm;
EditBone *ebone_iter;
@@ -483,8 +484,10 @@ static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
/* cancel if nothing selected */
if (CTX_DATA_COUNT(C, selected_bones) == 0)
return OPERATOR_CANCELLED;
-
- ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
+
+ const bool do_flip_names = RNA_boolean_get(op->ptr, "do_flip_names");
+
+ ED_armature_edit_sync_selection(arm->edbo); // XXX why is this needed?
preEditBoneDuplicate(arm->edbo);
@@ -496,7 +499,7 @@ static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
{
EditBone *ebone;
- ebone = ED_armature_bone_get_mirrored(arm->edbo, ebone_iter);
+ ebone = ED_armature_ebone_get_mirrored(arm->edbo, ebone_iter);
if (ebone) {
ebone->flag |= BONE_SELECTED;
}
@@ -511,8 +514,20 @@ static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
(ebone_iter->flag & BONE_SELECTED))
{
EditBone *ebone;
+ char new_bone_name_buff[MAXBONENAME];
+ char *new_bone_name = ebone_iter->name;
+
+ if (do_flip_names) {
+ BLI_string_flip_side_name(new_bone_name_buff, ebone_iter->name, false, sizeof(new_bone_name_buff));
+
+ /* Only use flipped name if not yet in use. Otherwise we'd get again inconsistent namings
+ * (different numbers), better keep default behavior in this case. */
+ if (ED_armature_ebone_find_name(arm->edbo, new_bone_name_buff) == NULL) {
+ new_bone_name = new_bone_name_buff;
+ }
+ }
- ebone = duplicateEditBone(ebone_iter, ebone_iter->name, arm->edbo, obedit);
+ ebone = duplicateEditBone(ebone_iter, new_bone_name, arm->edbo, obedit);
if (!ebone_first_dupe) {
ebone_first_dupe = ebone;
@@ -568,7 +583,7 @@ static int armature_duplicate_selected_exec(bContext *C, wmOperator *UNUSED(op))
postEditBoneDuplicate(arm->edbo, obedit);
- ED_armature_validate_active(arm);
+ ED_armature_edit_validate_active(arm);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -589,6 +604,10 @@ void ARMATURE_OT_duplicate(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(
+ ot->srna, "do_flip_names", false,
+ "Flip Names", "Try to flip names of the bones, if possible, instead of adding a number extension");
}
/**
@@ -611,7 +630,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
if (CTX_DATA_COUNT(C, selected_bones) == 0)
return OPERATOR_CANCELLED;
- ED_armature_sync_selection(arm->edbo); // XXX why is this needed?
+ ED_armature_edit_sync_selection(arm->edbo); // XXX why is this needed?
preEditBoneDuplicate(arm->edbo);
@@ -629,7 +648,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
ebone_iter->flag &= ~(BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
}
else {
- EditBone *ebone = ED_armature_bone_find_name(arm->edbo, name_flip);
+ EditBone *ebone = ED_armature_ebone_find_name(arm->edbo, name_flip);
if (ebone) {
if ((ebone->flag & BONE_SELECTED) == 0) {
@@ -719,7 +738,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
/* the parent may have been duplicated, if not lookup the mirror parent */
EditBone *ebone_parent =
(ebone_iter->parent->temp.ebone ?
- ebone_iter->parent->temp.ebone : ED_armature_bone_get_mirrored(arm->edbo, ebone_iter->parent));
+ ebone_iter->parent->temp.ebone : ED_armature_ebone_get_mirrored(arm->edbo, ebone_iter->parent));
if (ebone_parent == NULL) {
/* If the mirror lookup failed, (but the current bone has a parent)
@@ -740,7 +759,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
}
}
- transform_armature_mirror_update(obedit);
+ ED_armature_edit_transform_mirror_update(obedit);
/* Selected bones now have their 'temp' pointer set,
* so we don't need this anymore */
@@ -767,7 +786,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
postEditBoneDuplicate(arm->edbo, obedit);
- ED_armature_validate_active(arm);
+ ED_armature_edit_validate_active(arm);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -778,7 +797,7 @@ static int armature_symmetrize_exec(bContext *C, wmOperator *op)
void ARMATURE_OT_symmetrize(wmOperatorType *ot)
{
/* subset of 'rna_enum_symmetrize_direction_items' */
- static EnumPropertyItem arm_symmetrize_direction_items[] = {
+ static const EnumPropertyItem arm_symmetrize_direction_items[] = {
{-1, "NEGATIVE_X", 0, "-X to +X", ""},
{+1, "POSITIVE_X", 0, "+X to -X", ""},
{0, NULL, 0, NULL, NULL}
@@ -851,7 +870,7 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
/* we re-use code for mirror editing... */
flipbone = NULL;
if (arm->flag & ARM_MIRROR_EDIT) {
- flipbone = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
if (flipbone) {
forked = 0; // we extrude 2 different bones
if (flipbone->flag & (BONE_TIPSEL | BONE_ROOTSEL | BONE_SELECTED))
@@ -899,19 +918,20 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
newbone->dist = ebone->dist;
newbone->xwidth = ebone->xwidth;
newbone->zwidth = ebone->zwidth;
- newbone->ease1 = ebone->ease1;
- newbone->ease2 = ebone->ease2;
newbone->rad_head = ebone->rad_tail; // don't copy entire bone...
newbone->rad_tail = ebone->rad_tail;
newbone->segments = 1;
newbone->layer = ebone->layer;
+ /* Bendy-Bone parameters */
newbone->roll1 = ebone->roll1;
newbone->roll2 = ebone->roll2;
newbone->curveInX = ebone->curveInX;
newbone->curveInY = ebone->curveInY;
newbone->curveOutX = ebone->curveOutX;
newbone->curveOutY = ebone->curveOutY;
+ newbone->ease1 = ebone->ease1;
+ newbone->ease2 = ebone->ease2;
newbone->scaleIn = ebone->scaleIn;
newbone->scaleOut = ebone->scaleOut;
@@ -924,7 +944,7 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
else strcat(newbone->name, "_R");
}
}
- unique_editbone_name(arm->edbo, newbone->name, NULL);
+ ED_armature_ebone_unique_name(arm->edbo, newbone->name, NULL);
/* Add the new bone to the list */
BLI_addtail(arm->edbo, newbone);
@@ -942,12 +962,19 @@ static int armature_extrude_exec(bContext *C, wmOperator *op)
}
}
/* if only one bone, make this one active */
- if (totbone == 1 && first) arm->act_edbone = first;
+ if (totbone == 1 && first) {
+ arm->act_edbone = first;
+ }
+ else {
+ arm->act_edbone = newbone;
+ }
- if (totbone == 0) return OPERATOR_CANCELLED;
+ if (totbone == 0) {
+ return OPERATOR_CANCELLED;
+ }
/* Transform the endpoints */
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1000,10 +1027,10 @@ static int armature_bone_primitive_add_exec(bContext *C, wmOperator *op)
mul_m3_m3m3(totmat, obmat, viewmat);
invert_m3_m3(imat, totmat);
- ED_armature_deselect_all(obedit);
+ ED_armature_edit_deselect_all(obedit);
- /* Create a bone */
- bone = ED_armature_edit_bone_add(obedit->data, name);
+ /* Create a bone */
+ bone = ED_armature_ebone_add(obedit->data, name);
copy_v3_v3(bone->head, curs);
@@ -1091,7 +1118,7 @@ static int armature_subdivide_exec(bContext *C, wmOperator *op)
newbone->prop = NULL;
- unique_editbone_name(arm->edbo, newbone->name, NULL);
+ ED_armature_ebone_unique_name(arm->edbo, newbone->name, NULL);
/* correct parent bones */
for (tbone = arm->edbo->first; tbone; tbone = tbone->next) {
diff --git a/source/blender/editors/armature/armature_edit.c b/source/blender/editors/armature/armature_edit.c
index 47e73f9b777..4562329706f 100644
--- a/source/blender/editors/armature/armature_edit.c
+++ b/source/blender/editors/armature/armature_edit.c
@@ -66,7 +66,7 @@
/* ************************** Object Tools Exports ******************************* */
/* NOTE: these functions are exported to the Object module to be called from the tools there */
-void ED_armature_apply_transform(Object *ob, float mat[4][4])
+void ED_armature_transform_apply(Object *ob, float mat[4][4], const bool do_props)
{
bArmature *arm = ob->data;
@@ -74,14 +74,14 @@ void ED_armature_apply_transform(Object *ob, float mat[4][4])
ED_armature_to_edit(arm);
/* Transform the bones */
- ED_armature_transform_bones(arm, mat);
+ ED_armature_transform_bones(arm, mat, do_props);
/* Turn the list into an armature */
ED_armature_from_edit(arm);
ED_armature_edit_free(arm);
}
-void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4])
+void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4], const bool do_props)
{
EditBone *ebone;
float scale = mat4_to_scale(mat); /* store the scale of the matrix here to use on envelopes */
@@ -106,27 +106,29 @@ void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4])
/* apply the transformed roll back */
mat3_to_vec_roll(tmat, NULL, &ebone->roll);
- ebone->rad_head *= scale;
- ebone->rad_tail *= scale;
- ebone->dist *= scale;
-
- /* we could be smarter and scale by the matrix along the x & z axis */
- ebone->xwidth *= scale;
- ebone->zwidth *= scale;
+ if (do_props) {
+ ebone->rad_head *= scale;
+ ebone->rad_tail *= scale;
+ ebone->dist *= scale;
+
+ /* we could be smarter and scale by the matrix along the x & z axis */
+ ebone->xwidth *= scale;
+ ebone->zwidth *= scale;
+ }
}
}
-void ED_armature_transform(struct bArmature *arm, float mat[4][4])
+void ED_armature_transform(struct bArmature *arm, float mat[4][4], const bool do_props)
{
if (arm->edbo) {
- ED_armature_transform_bones(arm, mat);
+ ED_armature_transform_bones(arm, mat, do_props);
}
else {
/* Put the armature into editmode */
ED_armature_to_edit(arm);
/* Transform the bones */
- ED_armature_transform_bones(arm, mat);
+ ED_armature_transform_bones(arm, mat, do_props);
/* Go back to object mode*/
ED_armature_from_edit(arm);
@@ -203,7 +205,7 @@ void ED_armature_origin_set(Scene *scene, Object *ob, float cursor[3], int cente
/* adjust bone roll to align Z axis with vector
* vec is in local space and is normalized
*/
-float ED_rollBoneToVector(EditBone *bone, const float align_axis[3], const bool axis_only)
+float ED_armature_ebone_roll_to_vector(const EditBone *bone, const float align_axis[3], const bool axis_only)
{
float mat[3][3], nor[3];
float vec[3], align_axis_proj[3], roll = 0.0f;
@@ -220,7 +222,7 @@ float ED_rollBoneToVector(EditBone *bone, const float align_axis[3], const bool
vec_roll_to_mat3_normalized(nor, 0.0f, mat);
/* project the new_up_axis along the normal */
- project_v3_v3v3(vec, align_axis, nor);
+ project_v3_v3v3_normalized(vec, align_axis, nor);
sub_v3_v3v3(align_axis_proj, align_axis, vec);
if (axis_only) {
@@ -263,7 +265,7 @@ typedef enum eCalcRollTypes {
CALC_ROLL_CURSOR,
} eCalcRollTypes;
-static EnumPropertyItem prop_calc_roll_types[] = {
+static const EnumPropertyItem prop_calc_roll_types[] = {
{0, "", 0, N_("Positive"), ""},
{CALC_ROLL_TAN_POS_X, "POS_X", 0, "Local +X Tangent", ""},
{CALC_ROLL_TAN_POS_Z, "POS_Z", 0, "Local +Z Tangent", ""},
@@ -329,7 +331,7 @@ static int armature_calc_roll_exec(bContext *C, wmOperator *op)
sub_v3_v3v3(cursor_rel, cursor_local, ebone->head);
if (axis_flip) negate_v3(cursor_rel);
if (normalize_v3(cursor_rel) != 0.0f) {
- ebone->roll = ED_rollBoneToVector(ebone, cursor_rel, axis_only);
+ ebone->roll = ED_armature_ebone_roll_to_vector(ebone, cursor_rel, axis_only);
}
}
}
@@ -368,13 +370,13 @@ static int armature_calc_roll_exec(bContext *C, wmOperator *op)
if (axis_flip) negate_v3(vec);
if (is_edit) {
- ebone->roll = ED_rollBoneToVector(ebone, vec, axis_only);
+ ebone->roll = ED_armature_ebone_roll_to_vector(ebone, vec, axis_only);
}
/* parentless bones use cross product with child */
if (is_edit_parent) {
if (ebone->parent->parent == NULL) {
- ebone->parent->roll = ED_rollBoneToVector(ebone->parent, vec, axis_only);
+ ebone->parent->roll = ED_armature_ebone_roll_to_vector(ebone->parent, vec, axis_only);
}
}
}
@@ -418,7 +420,7 @@ static int armature_calc_roll_exec(bContext *C, wmOperator *op)
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if (EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) {
/* roll func is a callback which assumes that all is well */
- ebone->roll = ED_rollBoneToVector(ebone, vec, axis_only);
+ ebone->roll = ED_armature_ebone_roll_to_vector(ebone, vec, axis_only);
}
}
}
@@ -426,7 +428,7 @@ static int armature_calc_roll_exec(bContext *C, wmOperator *op)
if (arm->flag & ARM_MIRROR_EDIT) {
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if ((EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) == 0) {
- EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ EditBone *ebone_mirr = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
if (ebone_mirr && (EBONE_VISIBLE(arm, ebone_mirr) && EBONE_EDITABLE(ebone_mirr))) {
ebone->roll = -ebone_mirr->roll;
}
@@ -480,7 +482,7 @@ static int armature_roll_clear_exec(bContext *C, wmOperator *op)
if (arm->flag & ARM_MIRROR_EDIT) {
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if ((EBONE_VISIBLE(arm, ebone) && EBONE_EDITABLE(ebone)) == 0) {
- EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ EditBone *ebone_mirr = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
if (ebone_mirr && (EBONE_VISIBLE(arm, ebone_mirr) && EBONE_EDITABLE(ebone_mirr))) {
ebone->roll = -ebone_mirr->roll;
}
@@ -769,7 +771,7 @@ static int armature_fill_bones_exec(bContext *C, wmOperator *op)
}
if (newbone) {
- ED_armature_deselect_all(obedit);
+ ED_armature_edit_deselect_all(obedit);
arm->act_edbone = newbone;
newbone->flag |= BONE_TIPSEL;
}
@@ -881,7 +883,7 @@ static void bones_merge(Object *obedit, EditBone *start, EditBone *end, EditBone
}
newbone->flag |= (BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
}
@@ -957,7 +959,7 @@ static int armature_merge_exec(bContext *C, wmOperator *op)
}
/* updates */
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_POSE, obedit);
return OPERATOR_FINISHED;
@@ -965,7 +967,7 @@ static int armature_merge_exec(bContext *C, wmOperator *op)
void ARMATURE_OT_merge(wmOperatorType *ot)
{
- static EnumPropertyItem merge_types[] = {
+ static const EnumPropertyItem merge_types[] = {
{1, "WITHIN_CHAIN", 0, "Within Chains", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -1179,7 +1181,7 @@ static int armature_align_bones_exec(bContext *C, wmOperator *op)
* - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
* then just use actbone. Useful when doing upper arm to spine.
*/
- actmirb = ED_armature_bone_get_mirrored(arm->edbo, actbone);
+ actmirb = ED_armature_ebone_get_mirrored(arm->edbo, actbone);
if (actmirb == NULL)
actmirb = actbone;
}
@@ -1291,7 +1293,7 @@ static bool armature_delete_ebone_cb(const char *bone_name, void *arm_p)
bArmature *arm = arm_p;
EditBone *ebone;
- ebone = ED_armature_bone_find_name(arm->edbo, bone_name);
+ ebone = ED_armature_ebone_find_name(arm->edbo, bone_name);
return (ebone && (ebone->flag & BONE_SELECTED) && (arm->layer & ebone->layer));
}
@@ -1301,7 +1303,7 @@ static int armature_delete_selected_exec(bContext *C, wmOperator *UNUSED(op))
{
bArmature *arm;
EditBone *curBone, *ebone_next;
- Object *obedit = CTX_data_edit_object(C); // XXX get from context
+ Object *obedit = CTX_data_edit_object(C);
bool changed = false;
arm = obedit->data;
@@ -1318,7 +1320,7 @@ static int armature_delete_selected_exec(bContext *C, wmOperator *UNUSED(op))
if (arm->layer & curBone->layer) {
if (curBone->flag & BONE_SELECTED) {
if (curBone == arm->act_edbone) arm->act_edbone = NULL;
- ED_armature_edit_bone_remove(arm, curBone);
+ ED_armature_ebone_remove(arm, curBone);
changed = true;
}
}
@@ -1327,7 +1329,7 @@ static int armature_delete_selected_exec(bContext *C, wmOperator *UNUSED(op))
if (!changed)
return OPERATOR_CANCELLED;
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
BKE_pose_tag_recalc(CTX_data_main(C), obedit->pose);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1356,7 +1358,7 @@ static bool armature_dissolve_ebone_cb(const char *bone_name, void *arm_p)
bArmature *arm = arm_p;
EditBone *ebone;
- ebone = ED_armature_bone_find_name(arm->edbo, bone_name);
+ ebone = ED_armature_ebone_find_name(arm->edbo, bone_name);
return (ebone && (ebone->flag & BONE_DONE));
}
@@ -1456,8 +1458,9 @@ static int armature_dissolve_selected_exec(bContext *C, wmOperator *UNUSED(op))
if (ebone->flag & BONE_DONE) {
copy_v3_v3(ebone->parent->tail, ebone->tail);
ebone->parent->rad_tail = ebone->rad_tail;
+ SET_FLAG_FROM_TEST(ebone->parent->flag, ebone->flag & BONE_TIPSEL, BONE_TIPSEL);
- ED_armature_edit_bone_remove(arm, ebone);
+ ED_armature_ebone_remove_ex(arm, ebone, false);
changed = true;
}
}
@@ -1466,10 +1469,9 @@ static int armature_dissolve_selected_exec(bContext *C, wmOperator *UNUSED(op))
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if (ebone->parent &&
ebone->parent->temp.ebone &&
- (ebone->flag & BONE_CONNECTED) == 0)
+ (ebone->flag & BONE_CONNECTED))
{
- ebone->flag |= BONE_CONNECTED;
- ebone->rad_head = ebone->parent->rad_head;
+ ebone->rad_head = ebone->parent->rad_tail;
}
}
@@ -1491,7 +1493,7 @@ static int armature_dissolve_selected_exec(bContext *C, wmOperator *UNUSED(op))
return OPERATOR_CANCELLED;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1536,8 +1538,8 @@ static int armature_hide_exec(bContext *C, wmOperator *op)
}
}
}
- ED_armature_validate_active(arm);
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_validate_active(arm);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1562,24 +1564,25 @@ void ARMATURE_OT_hide(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
}
-static int armature_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int armature_reveal_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
bArmature *arm = obedit->data;
EditBone *ebone;
+ const bool select = RNA_boolean_get(op->ptr, "select");
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if (arm->layer & ebone->layer) {
if (ebone->flag & BONE_HIDDEN_A) {
if (!(ebone->flag & BONE_UNSELECTABLE)) {
- ebone->flag |= (BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL);
+ SET_FLAG_FROM_TEST(ebone->flag, select, (BONE_TIPSEL | BONE_SELECTED | BONE_ROOTSEL));
}
ebone->flag &= ~BONE_HIDDEN_A;
}
}
}
- ED_armature_validate_active(arm);
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_validate_active(arm);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1591,7 +1594,7 @@ void ARMATURE_OT_reveal(wmOperatorType *ot)
/* identifiers */
ot->name = "Reveal Bones";
ot->idname = "ARMATURE_OT_reveal";
- ot->description = "Unhide all bones that have been tagged to be hidden in Edit Mode";
+ ot->description = "Reveal all bones hidden in Edit Mode";
/* api callbacks */
ot->exec = armature_reveal_exec;
@@ -1600,4 +1603,5 @@ void ARMATURE_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
diff --git a/source/blender/editors/armature/armature_intern.h b/source/blender/editors/armature/armature_intern.h
index b39b4bd81ee..192bb8eea61 100644
--- a/source/blender/editors/armature/armature_intern.h
+++ b/source/blender/editors/armature/armature_intern.h
@@ -173,6 +173,7 @@ typedef struct tPChanFCurveLink {
float roll1, roll2; /* old bbone values (to be restored along with the transform properties) */
float curveInX, curveInY; /* (NOTE: we haven't renamed these this time, as their names are already long enough) */
float curveOutX, curveOutY;
+ float ease1, ease2;
float scaleIn, scaleOut;
struct IDProperty *oldprops; /* copy of custom properties at start of operator (to be restored before each modal step) */
@@ -247,8 +248,10 @@ void armature_select_mirrored_ex(struct bArmature *arm, const int flag);
void armature_select_mirrored(struct bArmature *arm);
void armature_tag_unselect(struct bArmature *arm);
-void *get_nearest_bone(struct bContext *C, short findunsel, int x, int y);
-void *get_bone_from_selectbuffer(struct Scene *scene, struct Base *base, unsigned int *buffer, short hits, short findunsel, bool do_nearest);
+void *get_nearest_bone(struct bContext *C, const int xy[2], bool findunsel);
+void *get_bone_from_selectbuffer(
+ struct Scene *scene, struct Base *base, const unsigned int *buffer, short hits,
+ bool findunsel, bool do_nearest);
int bone_looper(struct Object *ob, struct Bone *bone, void *data,
int (*bone_func)(struct Object *, struct Bone *, void *));
diff --git a/source/blender/editors/armature/armature_naming.c b/source/blender/editors/armature/armature_naming.c
index fa192ed6f36..d5ed1380a7e 100644
--- a/source/blender/editors/armature/armature_naming.c
+++ b/source/blender/editors/armature/armature_naming.c
@@ -73,11 +73,11 @@
static bool editbone_unique_check(void *arg, const char *name)
{
struct {ListBase *lb; void *bone; } *data = arg;
- EditBone *dupli = ED_armature_bone_find_name(data->lb, name);
+ EditBone *dupli = ED_armature_ebone_find_name(data->lb, name);
return dupli && dupli != data->bone;
}
-void unique_editbone_name(ListBase *edbo, char *name, EditBone *bone)
+void ED_armature_ebone_unique_name(ListBase *edbo, char *name, EditBone *bone)
{
struct {ListBase *lb; void *bone; } data;
data.lb = edbo;
@@ -152,10 +152,10 @@ void ED_armature_bone_rename(bArmature *arm, const char *oldnamep, const char *n
/* now check if we're in editmode, we need to find the unique name */
if (arm->edbo) {
- EditBone *eBone = ED_armature_bone_find_name(arm->edbo, oldname);
+ EditBone *eBone = ED_armature_ebone_find_name(arm->edbo, oldname);
if (eBone) {
- unique_editbone_name(arm->edbo, newname, NULL);
+ ED_armature_ebone_unique_name(arm->edbo, newname, NULL);
BLI_strncpy(eBone->name, newname, MAXBONENAME);
}
else {
@@ -311,10 +311,11 @@ typedef struct BoneFlipNameData {
* This way if we are flipping related bones (e.g., Bone.L, Bone.R) at the same time
* all the bones are safely renamed, without conflicting with each other.
*
- * \param arm Armature the bones belong to
- * \param bones ListBase of BoneConflict elems, populated via ED_armature_bones_flip_names_add
+ * \param arm: Armature the bones belong to
+ * \param bones_names: List of BoneConflict elems.
+ * \param do_strip_numbers: if set, try to get rid of dot-numbers at end of bone names.
*/
-void ED_armature_bones_flip_names(bArmature *arm, ListBase *bones_names)
+void ED_armature_bones_flip_names(bArmature *arm, ListBase *bones_names, const bool do_strip_numbers)
{
ListBase bones_names_conflicts = {NULL};
BoneFlipNameData *bfn;
@@ -326,9 +327,9 @@ void ED_armature_bones_flip_names(bArmature *arm, ListBase *bones_names)
char name_flip[MAXBONENAME];
char *name = link->data;
- /* Do not strip numbers, otherwise we'll end up with completely mismatched names in cases like
+ /* WARNING: if do_strip_numbers is set, expect completely mismatched names in cases like
* Bone.R, Bone.R.001, Bone.R.002, etc. */
- BLI_string_flip_side_name(name_flip, name, false, sizeof(name_flip));
+ BLI_string_flip_side_name(name_flip, name, do_strip_numbers, sizeof(name_flip));
ED_armature_bone_rename(arm, name, name_flip);
@@ -351,7 +352,7 @@ void ED_armature_bones_flip_names(bArmature *arm, ListBase *bones_names)
/* ************************************************** */
/* Bone Renaming - EditMode */
-static int armature_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
+static int armature_flip_names_exec(bContext *C, wmOperator *op)
{
Object *ob = CTX_data_edit_object(C);
bArmature *arm;
@@ -360,9 +361,11 @@ static int armature_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
if (ELEM(NULL, ob, ob->pose))
return OPERATOR_CANCELLED;
+ const bool do_strip_numbers = RNA_boolean_get(op->ptr, "do_strip_numbers");
+
arm = ob->data;
- ListBase bones_names= {NULL};
+ ListBase bones_names = {NULL};
CTX_DATA_BEGIN(C, EditBone *, ebone, selected_editable_bones)
{
@@ -370,7 +373,7 @@ static int armature_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
}
CTX_DATA_END;
- ED_armature_bones_flip_names(arm, &bones_names);
+ ED_armature_bones_flip_names(arm, &bones_names, do_strip_numbers);
BLI_freelistN(&bones_names);
@@ -400,6 +403,10 @@ void ARMATURE_OT_flip_names(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "do_strip_numbers", false, "Strip Numbers",
+ "Try to remove right-most dot-number from flipped names "
+ "(WARNING: may result in incoherent naming in some cases)");
}
@@ -435,7 +442,7 @@ static int armature_autoside_names_exec(bContext *C, wmOperator *op)
void ARMATURE_OT_autoside_names(wmOperatorType *ot)
{
- static EnumPropertyItem axis_items[] = {
+ static const EnumPropertyItem axis_items[] = {
{0, "XAXIS", 0, "X-Axis", "Left/Right"},
{1, "YAXIS", 0, "Y-Axis", "Front/Back"},
{2, "ZAXIS", 0, "Z-Axis", "Top/Bottom"},
diff --git a/source/blender/editors/armature/armature_relations.c b/source/blender/editors/armature/armature_relations.c
index 1c342657eec..3c272d52d1c 100644
--- a/source/blender/editors/armature/armature_relations.c
+++ b/source/blender/editors/armature/armature_relations.c
@@ -123,50 +123,40 @@ typedef struct tJoinArmature_AdtFixData {
GHash *names_map;
} tJoinArmature_AdtFixData;
-/* Callback to pass to void BKE_animdata_main_cb() for fixing driver ID's to point to the new ID */
+/* Callback to pass to BKE_animdata_main_cb() for fixing driver ID's to point to the new ID */
/* FIXME: For now, we only care about drivers here. When editing rigs, it's very rare to have animation
* on the rigs being edited already, so it should be safe to skip these.
*/
-static void joined_armature_fix_animdata_cb(ID *id, AnimData *adt, void *user_data)
+static void joined_armature_fix_animdata_cb(ID *id, FCurve *fcu, void *user_data)
{
tJoinArmature_AdtFixData *afd = (tJoinArmature_AdtFixData *)user_data;
ID *src_id = &afd->srcArm->id;
ID *dst_id = &afd->tarArm->id;
GHashIterator gh_iter;
- FCurve *fcu;
/* Fix paths - If this is the target object, it will have some "dirty" paths */
- if (id == src_id) {
- /* Fix drivers */
- for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
- /* skip driver if it doesn't affect the bones */
- if (strstr(fcu->rna_path, "pose.bones[") == NULL) {
- continue;
- }
+ if ((id == src_id) && strstr(fcu->rna_path, "pose.bones[")) {
+ GHASH_ITER(gh_iter, afd->names_map) {
+ const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
+ const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
- // FIXME: this is too crude... it just does everything!
- GHASH_ITER(gh_iter, afd->names_map) {
- const char *old_name = BLI_ghashIterator_getKey(&gh_iter);
- const char *new_name = BLI_ghashIterator_getValue(&gh_iter);
+ /* only remap if changed; this still means there will be some waste if there aren't many drivers/keys */
+ if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
+ fcu->rna_path = BKE_animsys_fix_rna_path_rename(id, fcu->rna_path, "pose.bones",
+ old_name, new_name, 0, 0, false);
- /* only remap if changed; this still means there will be some waste if there aren't many drivers/keys */
- if (!STREQ(old_name, new_name) && strstr(fcu->rna_path, old_name)) {
- fcu->rna_path = BKE_animsys_fix_rna_path_rename(id, fcu->rna_path, "pose.bones",
- old_name, new_name, 0, 0, false);
-
- /* we don't want to apply a second remapping on this driver now,
- * so stop trying names, but keep fixing drivers
- */
- break;
- }
+ /* we don't want to apply a second remapping on this driver now,
+ * so stop trying names, but keep fixing drivers
+ */
+ break;
}
}
}
/* Driver targets */
- for (fcu = adt->drivers.first; fcu; fcu = fcu->next) {
+ if (fcu->driver) {
ChannelDriver *driver = fcu->driver;
DriverVar *dvar;
@@ -319,10 +309,10 @@ int join_armature_exec(bContext *C, wmOperator *op)
/* Copy bones and posechannels from the object to the edit armature */
for (pchan = opose->chanbase.first; pchan; pchan = pchann) {
pchann = pchan->next;
- curbone = ED_armature_bone_find_name(curarm->edbo, pchan->name);
+ curbone = ED_armature_ebone_find_name(curarm->edbo, pchan->name);
/* Get new name */
- unique_editbone_name(arm->edbo, curbone->name, NULL);
+ ED_armature_ebone_unique_name(arm->edbo, curbone->name, NULL);
BLI_ghash_insert(afd.names_map, BLI_strdup(pchan->name), curbone->name);
/* Transform the bone */
@@ -370,7 +360,7 @@ int join_armature_exec(bContext *C, wmOperator *op)
}
/* Fix all the drivers (and animation data) */
- BKE_animdata_main_cb(bmain, joined_armature_fix_animdata_cb, &afd);
+ BKE_fcurves_main_cb(bmain, joined_armature_fix_animdata_cb, &afd);
BLI_ghash_free(afd.names_map, MEM_freeN, NULL);
/* Only copy over animdata now, after all the remapping has been done,
@@ -380,7 +370,7 @@ int join_armature_exec(bContext *C, wmOperator *op)
if (base->object->adt) {
if (ob->adt == NULL) {
/* no animdata, so just use a copy of the whole thing */
- ob->adt = BKE_animdata_copy(base->object->adt, false);
+ ob->adt = BKE_animdata_copy(bmain, base->object->adt, false);
}
else {
/* merge in data - we'll fix the drivers manually */
@@ -391,7 +381,7 @@ int join_armature_exec(bContext *C, wmOperator *op)
if (curarm->adt) {
if (arm->adt == NULL) {
/* no animdata, so just use a copy of the whole thing */
- arm->adt = BKE_animdata_copy(curarm->adt, false);
+ arm->adt = BKE_animdata_copy(bmain, curarm->adt, false);
}
else {
/* merge in data - we'll fix the drivers manually */
@@ -535,7 +525,7 @@ static void separate_armature_bones(Object *ob, short sel)
/* go through pose-channels, checking if a bone should be removed */
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchann) {
pchann = pchan->next;
- curbone = ED_armature_bone_find_name(arm->edbo, pchan->name);
+ curbone = ED_armature_ebone_find_name(arm->edbo, pchan->name);
/* check if bone needs to be removed */
if ( (sel && (curbone->flag & BONE_SELECTED)) ||
@@ -642,7 +632,7 @@ static int separate_armature_exec(bContext *C, wmOperator *op)
ED_armature_to_edit(obedit->data);
/* parents tips remain selected when connected children are removed. */
- ED_armature_deselect_all(obedit);
+ ED_armature_edit_deselect_all(obedit);
BKE_report(op->reports, RPT_INFO, "Separated bones");
@@ -735,7 +725,7 @@ static void bone_connect_to_new_parent(ListBase *edbo, EditBone *selbone, EditBo
}
-static EnumPropertyItem prop_editarm_make_parent_types[] = {
+static const EnumPropertyItem prop_editarm_make_parent_types[] = {
{ARM_PAR_CONNECT, "CONNECTED", 0, "Connected", ""},
{ARM_PAR_OFFSET, "OFFSET", 0, "Keep Offset", ""},
{0, NULL, 0, NULL, NULL}
@@ -762,7 +752,7 @@ static int armature_parent_set_exec(bContext *C, wmOperator *op)
* - if there's no mirrored copy of actbone (i.e. actbone = "parent.C" or "parent")
* then just use actbone. Useful when doing upper arm to spine.
*/
- actmirb = ED_armature_bone_get_mirrored(arm->edbo, actbone);
+ actmirb = ED_armature_ebone_get_mirrored(arm->edbo, actbone);
if (actmirb == NULL)
actmirb = actbone;
}
@@ -856,7 +846,7 @@ void ARMATURE_OT_parent_set(wmOperatorType *ot)
-static EnumPropertyItem prop_editarm_clear_parent_types[] = {
+static const EnumPropertyItem prop_editarm_clear_parent_types[] = {
{1, "CLEAR", 0, "Clear Parent", ""},
{2, "DISCONNECT", 0, "Disconnect Bone", ""},
{0, NULL, 0, NULL, NULL}
@@ -885,7 +875,7 @@ static int armature_parent_clear_exec(bContext *C, wmOperator *op)
}
CTX_DATA_END;
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
/* note, notifier might evolve */
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
diff --git a/source/blender/editors/armature/armature_select.c b/source/blender/editors/armature/armature_select.c
index e9946abba0b..ba856d4e964 100644
--- a/source/blender/editors/armature/armature_select.c
+++ b/source/blender/editors/armature/armature_select.c
@@ -38,7 +38,7 @@
#include "BLI_string_utils.h"
#include "BKE_context.h"
-//#include "BKE_deform.h"
+#include "BKE_action.h"
#include "BKE_report.h"
#include "BIF_gl.h"
@@ -62,7 +62,7 @@
/* **************** PoseMode & EditMode Selection Buffer Queries *************************** */
/* only for opengl selection indices */
-Bone *get_indexed_bone(Object *ob, int index)
+Bone *ED_armature_bone_find_index(Object *ob, int index)
{
bPoseChannel *pchan;
if (ob->pose == NULL) return NULL;
@@ -74,7 +74,9 @@ Bone *get_indexed_bone(Object *ob, int index)
/* See if there are any selected bones in this buffer */
/* only bones from base are checked on */
-void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits, short findunsel, bool do_nearest)
+void *get_bone_from_selectbuffer(
+ Scene *scene, Base *base, const unsigned int *buffer, short hits,
+ bool findunsel, bool do_nearest)
{
Object *obedit = scene->obedit; // XXX get from context
Bone *bone;
@@ -97,14 +99,14 @@ void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer,
if (obedit == NULL || base->object != obedit) {
/* no singular posemode, so check for correct object */
if (base->selcol == (hitresult & 0xFFFF)) {
- bone = get_indexed_bone(base->object, hitresult);
+ bone = ED_armature_bone_find_index(base->object, hitresult);
if (findunsel)
sel = (bone->flag & BONE_SELECTED);
else
sel = !(bone->flag & BONE_SELECTED);
-
- data = bone;
+
+ data = bone;
}
else {
data = NULL;
@@ -162,20 +164,20 @@ void *get_bone_from_selectbuffer(Scene *scene, Base *base, unsigned int *buffer,
/* used by posemode as well editmode */
/* only checks scene->basact! */
/* x and y are mouse coords (area space) */
-void *get_nearest_bone(bContext *C, short findunsel, int x, int y)
+void *get_nearest_bone(bContext *C, const int xy[2], bool findunsel)
{
ViewContext vc;
rcti rect;
unsigned int buffer[MAXPICKBUF];
short hits;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
// rect.xmin = ... mouseco!
- rect.xmin = rect.xmax = x;
- rect.ymin = rect.ymax = y;
+ rect.xmin = rect.xmax = xy[0];
+ rect.ymin = rect.ymax = xy[1];
- hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, true);
+ hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, VIEW3D_SELECT_PICK_NEAREST);
if (hits > 0)
return get_bone_from_selectbuffer(vc.scene, vc.scene->basact, buffer, hits, findunsel, true);
@@ -197,10 +199,7 @@ static int armature_select_linked_invoke(bContext *C, wmOperator *op, const wmEv
view3d_operator_needs_opengl(C);
- if (extend)
- bone = get_nearest_bone(C, 0, event->mval[0], event->mval[1]);
- else
- bone = get_nearest_bone(C, 1, event->mval[0], event->mval[1]);
+ bone = get_nearest_bone(C, event->mval, !extend);
if (!bone)
return OPERATOR_CANCELLED;
@@ -245,7 +244,7 @@ static int armature_select_linked_invoke(bContext *C, wmOperator *op, const wmEv
bone = NULL;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -276,10 +275,24 @@ void ARMATURE_OT_select_linked(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend selection instead of deselecting everything first");
}
+/* utility function for get_nearest_editbonepoint */
+static int selectbuffer_ret_hits_12(unsigned int *UNUSED(buffer), const int hits12)
+{
+ return hits12;
+}
+
+static int selectbuffer_ret_hits_5(unsigned int *buffer, const int hits12, const int hits5)
+{
+ const int offs = 4 * hits12;
+ memcpy(buffer, buffer + offs, 4 * hits5 * sizeof(unsigned int));
+ return hits5;
+}
+
/* does bones and points */
/* note that BONE ROOT only gets drawn for root bones (or without IK) */
-static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
- ListBase *edbo, int findunsel, int *selmask)
+static EditBone *get_nearest_editbonepoint(
+ ViewContext *vc,
+ bool findunsel, bool use_cycle, int *r_selmask)
{
bArmature *arm = (bArmature *)vc->obedit->data;
EditBone *ebone_next_act = arm->act_edbone;
@@ -289,7 +302,9 @@ static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
unsigned int buffer[MAXPICKBUF];
unsigned int hitresult, besthitresult = BONESEL_NOSEL;
int i, mindep = 5;
- short hits;
+ int hits12, hits5 = 0;
+
+ static int last_mval[2] = {-100, -100};
/* find the bone after the current active bone, so as to bump up its chances in selection.
* this way overlapping bones will cycle selection state as with objects. */
@@ -303,22 +318,59 @@ static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
ebone_next_act = NULL;
}
- rect.xmin = mval[0] - 5;
- rect.xmax = mval[0] + 5;
- rect.ymin = mval[1] - 5;
- rect.ymax = mval[1] + 5;
-
- hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, true);
- if (hits == 0) {
- rect.xmin = mval[0] - 12;
- rect.xmax = mval[0] + 12;
- rect.ymin = mval[1] - 12;
- rect.ymax = mval[1] + 12;
- hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, true);
+ bool do_nearest = false;
+
+ /* define if we use solid nearest select or not */
+ if (use_cycle) {
+ if (vc->v3d->drawtype > OB_WIRE) {
+ do_nearest = true;
+ if (len_manhattan_v2v2_int(vc->mval, last_mval) < 3) {
+ do_nearest = false;
+ }
+ }
+ copy_v2_v2_int(last_mval, vc->mval);
+ }
+ else {
+ if (vc->v3d->drawtype > OB_WIRE) {
+ do_nearest = true;
+ }
+ }
+
+ /* matching logic from 'mixed_bones_object_selectbuffer' */
+ const int select_mode = (do_nearest ? VIEW3D_SELECT_PICK_NEAREST : VIEW3D_SELECT_PICK_ALL);
+ int hits = 0;
+
+ /* we _must_ end cache before return, use 'goto cache_end' */
+ view3d_opengl_select_cache_begin();
+
+ BLI_rcti_init_pt_radius(&rect, vc->mval, 12);
+ hits12 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode);
+ if (hits12 == 1) {
+ hits = selectbuffer_ret_hits_12(buffer, hits12);
+ goto cache_end;
}
+ else if (hits12 > 0) {
+ int offs;
+
+ offs = 4 * hits12;
+ BLI_rcti_init_pt_radius(&rect, vc->mval, 5);
+ hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode);
+
+ if (hits5 == 1) {
+ hits = selectbuffer_ret_hits_5(buffer, hits12, hits5);
+ goto cache_end;
+ }
+
+ if (hits5 > 0) { hits = selectbuffer_ret_hits_5(buffer, hits12, hits5); goto cache_end; }
+ else { hits = selectbuffer_ret_hits_12(buffer, hits12); goto cache_end; }
+ }
+
+cache_end:
+ view3d_opengl_select_cache_end();
+
/* See if there are any selected bones in this group */
if (hits > 0) {
-
+
if (hits == 1) {
if (!(buffer[3] & BONESEL_NOSEL))
besthitresult = buffer[3];
@@ -329,7 +381,7 @@ static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
if (!(hitresult & BONESEL_NOSEL)) {
int dep;
- ebone = BLI_findlink(edbo, hitresult & ~BONESEL_ANY);
+ ebone = BLI_findlink(arm->edbo, hitresult & ~BONESEL_ANY);
/* clicks on bone points get advantage */
if (hitresult & (BONESEL_ROOT | BONESEL_TIP)) {
@@ -373,23 +425,23 @@ static EditBone *get_nearest_editbonepoint(ViewContext *vc, const int mval[2],
if (!(besthitresult & BONESEL_NOSEL)) {
- ebone = BLI_findlink(edbo, besthitresult & ~BONESEL_ANY);
+ ebone = BLI_findlink(arm->edbo, besthitresult & ~BONESEL_ANY);
- *selmask = 0;
+ *r_selmask = 0;
if (besthitresult & BONESEL_ROOT)
- *selmask |= BONE_ROOTSEL;
+ *r_selmask |= BONE_ROOTSEL;
if (besthitresult & BONESEL_TIP)
- *selmask |= BONE_TIPSEL;
+ *r_selmask |= BONE_TIPSEL;
if (besthitresult & BONESEL_BONE)
- *selmask |= BONE_SELECTED;
+ *r_selmask |= BONE_SELECTED;
return ebone;
}
}
- *selmask = 0;
+ *r_selmask = 0;
return NULL;
}
-void ED_armature_deselect_all(Object *obedit)
+void ED_armature_edit_deselect_all(Object *obedit)
{
bArmature *arm = obedit->data;
EditBone *ebone;
@@ -399,7 +451,7 @@ void ED_armature_deselect_all(Object *obedit)
}
}
-void ED_armature_deselect_all_visible(Object *obedit)
+void ED_armature_edit_deselect_all_visible(Object *obedit)
{
bArmature *arm = obedit->data;
EditBone *ebone;
@@ -411,7 +463,7 @@ void ED_armature_deselect_all_visible(Object *obedit)
}
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
}
/* accounts for connected parents */
@@ -426,25 +478,27 @@ static int ebone_select_flag(EditBone *ebone)
}
/* context: editmode armature in view3d */
-bool ED_armature_select_pick(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle)
+bool ED_armature_edit_select_pick(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle)
{
Object *obedit = CTX_data_edit_object(C);
- bArmature *arm = obedit->data;
ViewContext vc;
EditBone *nearBone = NULL;
int selmask;
- view3d_set_viewcontext(C, &vc);
-
+ ED_view3d_viewcontext_init(C, &vc);
+ vc.mval[0] = mval[0];
+ vc.mval[1] = mval[1];
+
if (BIF_sk_selectStroke(C, mval, extend)) {
return true;
}
-
- nearBone = get_nearest_editbonepoint(&vc, mval, arm->edbo, 1, &selmask);
+
+ nearBone = get_nearest_editbonepoint(&vc, true, true, &selmask);
if (nearBone) {
+ bArmature *arm = obedit->data;
if (!extend && !deselect && !toggle) {
- ED_armature_deselect_all(obedit);
+ ED_armature_edit_deselect_all(obedit);
}
/* by definition the non-root connected bones have no root point drawn,
@@ -515,7 +569,7 @@ bool ED_armature_select_pick(bContext *C, const int mval[2], bool extend, bool d
nearBone->flag |= selmask;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
if (nearBone) {
/* then now check for active status */
@@ -659,7 +713,7 @@ static void armature_select_more_less(Object *ob, bool more)
EditBone *ebone;
/* XXX, eventually we shouldn't need this - campbell */
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
/* count bones & store selection state */
for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
@@ -689,7 +743,7 @@ static void armature_select_more_less(Object *ob, bool more)
ebone->temp.p = NULL;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
}
static int armature_de_select_more_exec(bContext *C, wmOperator *UNUSED(op))
@@ -749,9 +803,11 @@ enum {
SIMEDBONE_PREFIX,
SIMEDBONE_SUFFIX,
SIMEDBONE_LAYER,
+ SIMEDBONE_GROUP,
+ SIMEDBONE_SHAPE,
};
-static EnumPropertyItem prop_similar_types[] = {
+static const EnumPropertyItem prop_similar_types[] = {
{SIMEDBONE_CHILDREN, "CHILDREN", 0, "Children", ""},
{SIMEDBONE_CHILDREN_IMMEDIATE, "CHILDREN_IMMEDIATE", 0, "Immediate children", ""},
{SIMEDBONE_SIBLINGS, "SIBLINGS", 0, "Siblings", ""},
@@ -760,6 +816,8 @@ static EnumPropertyItem prop_similar_types[] = {
{SIMEDBONE_PREFIX, "PREFIX", 0, "Prefix", ""},
{SIMEDBONE_SUFFIX, "SUFFIX", 0, "Suffix", ""},
{SIMEDBONE_LAYER, "LAYER", 0, "Layer", ""},
+ {SIMEDBONE_GROUP, "GROUP", 0, "Group", ""},
+ {SIMEDBONE_SHAPE, "SHAPE", 0, "Shape", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -862,7 +920,27 @@ static void select_similar_suffix(bArmature *arm, EditBone *ebone_act)
}
}
-static void is_ancestor(EditBone * bone, EditBone * ancestor)
+/** Use for matching any pose channel data. */
+static void select_similar_data_pchan(
+ bArmature *arm, Object *obj, EditBone *ebone_active,
+ const size_t bytes_size, const int offset)
+{
+ const bPoseChannel *pchan_active = BKE_pose_channel_find_name(obj->pose, ebone_active->name);
+ const char *data_active = (const char *)POINTER_OFFSET(pchan_active, offset);
+ for (EditBone *ebone = arm->edbo->first; ebone; ebone = ebone->next) {
+ if (EBONE_SELECTABLE(arm, ebone)) {
+ const bPoseChannel *pchan = BKE_pose_channel_find_name(obj->pose, ebone->name);
+ if (pchan) {
+ const char *data_test = (const char *)POINTER_OFFSET(pchan, offset);
+ if (memcmp(data_active, data_test, bytes_size) == 0) {
+ ED_armature_ebone_select_set(ebone, true);
+ }
+ }
+ }
+ }
+}
+
+static void is_ancestor(EditBone *bone, EditBone *ancestor)
{
if (bone->temp.ebone == ancestor || bone->temp.ebone == NULL)
return;
@@ -929,6 +1007,9 @@ static int armature_select_similar_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
+#define STRUCT_SIZE_AND_OFFSET(_struct, _member) \
+ sizeof(((_struct *)NULL)->_member), offsetof(_struct, _member)
+
switch (type) {
case SIMEDBONE_CHILDREN:
select_similar_children(arm, ebone_act);
@@ -954,8 +1035,20 @@ static int armature_select_similar_exec(bContext *C, wmOperator *op)
case SIMEDBONE_LAYER:
select_similar_layer(arm, ebone_act);
break;
+ case SIMEDBONE_GROUP:
+ select_similar_data_pchan(
+ arm, obedit, ebone_act,
+ STRUCT_SIZE_AND_OFFSET(bPoseChannel, agrp_index));
+ break;
+ case SIMEDBONE_SHAPE:
+ select_similar_data_pchan(
+ arm, obedit, ebone_act,
+ STRUCT_SIZE_AND_OFFSET(bPoseChannel, custom));
+ break;
}
+#undef STRUCT_SIZE_AND_OFFSET
+
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
return OPERATOR_FINISHED;
@@ -1055,7 +1148,7 @@ static int armature_select_hierarchy_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
@@ -1064,7 +1157,7 @@ static int armature_select_hierarchy_exec(bContext *C, wmOperator *op)
void ARMATURE_OT_select_hierarchy(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{BONE_SELECT_PARENT, "PARENT", 0, "Select Parent", ""},
{BONE_SELECT_CHILD, "CHILD", 0, "Select Child", ""},
{0, NULL, 0, NULL, NULL}
@@ -1111,7 +1204,7 @@ static int armature_select_mirror_exec(bContext *C, wmOperator *op)
EditBone *ebone_mirror;
int flag_new = extend ? EBONE_PREV_FLAG_GET(ebone) : 0;
- if ((ebone_mirror = ED_armature_bone_get_mirrored(arm->edbo, ebone)) &&
+ if ((ebone_mirror = ED_armature_ebone_get_mirrored(arm->edbo, ebone)) &&
(EBONE_VISIBLE(arm, ebone_mirror)))
{
const int flag_mirror = EBONE_PREV_FLAG_GET(ebone_mirror);
@@ -1135,7 +1228,7 @@ static int armature_select_mirror_exec(bContext *C, wmOperator *op)
arm->act_edbone = ebone_mirror_act;
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
@@ -1202,7 +1295,7 @@ static int armature_shortest_path_pick_invoke(bContext *C, wmOperator *op, const
view3d_operator_needs_opengl(C);
ebone_src = arm->act_edbone;
- ebone_dst = get_nearest_bone(C, 0, event->mval[0], event->mval[1]);
+ ebone_dst = get_nearest_bone(C, event->mval, false);
/* fallback to object selection */
if (ELEM(NULL, ebone_src, ebone_dst) || (ebone_src == ebone_dst)) {
@@ -1220,7 +1313,7 @@ static int armature_shortest_path_pick_invoke(bContext *C, wmOperator *op, const
else if (ED_armature_ebone_is_child_recursive(ebone_dst, ebone_src)) {
SWAP(EditBone *, ebone_src, ebone_dst);
}
- else if ((ebone_isect_parent = ED_armature_bone_find_shared_parent(ebone_isect_child, 2))) {
+ else if ((ebone_isect_parent = ED_armature_ebone_find_shared_parent(ebone_isect_child, 2))) {
/* pass */
}
else {
@@ -1255,7 +1348,7 @@ static int armature_shortest_path_pick_invoke(bContext *C, wmOperator *op, const
if (changed) {
arm->act_edbone = ebone_dst;
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, obedit);
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/armature/armature_skinning.c b/source/blender/editors/armature/armature_skinning.c
index e8d41f722d7..0458fc4ed1b 100644
--- a/source/blender/editors/armature/armature_skinning.c
+++ b/source/blender/editors/armature/armature_skinning.c
@@ -424,7 +424,7 @@ static void add_verts_to_dgroups(ReportList *reports, Scene *scene, Object *ob,
MEM_freeN(verts);
}
-void create_vgroups_from_armature(ReportList *reports, Scene *scene, Object *ob, Object *par,
+void ED_object_vgroup_calc_from_armature(ReportList *reports, Scene *scene, Object *ob, Object *par,
const int mode, const bool mirror)
{
/* Lets try to create some vertex groups
diff --git a/source/blender/editors/armature/armature_utils.c b/source/blender/editors/armature/armature_utils.c
index a3b439536b7..8867189baef 100644
--- a/source/blender/editors/armature/armature_utils.c
+++ b/source/blender/editors/armature/armature_utils.c
@@ -53,7 +53,7 @@
/* Validation */
/* Sync selection to parent for connected children */
-void ED_armature_sync_selection(ListBase *edbo)
+void ED_armature_edit_sync_selection(ListBase *edbo)
{
EditBone *ebo;
@@ -75,7 +75,7 @@ void ED_armature_sync_selection(ListBase *edbo)
}
}
-void ED_armature_validate_active(struct bArmature *arm)
+void ED_armature_edit_validate_active(struct bArmature *arm)
{
EditBone *ebone = arm->act_edbone;
@@ -133,7 +133,10 @@ void bone_free(bArmature *arm, EditBone *bone)
BLI_freelinkN(arm->edbo, bone);
}
-void ED_armature_edit_bone_remove(bArmature *arm, EditBone *exBone)
+/**
+ * \param clear_connected: When false caller is responsible for keeping the flag in a valid state.
+ */
+void ED_armature_ebone_remove_ex(bArmature *arm, EditBone *exBone, bool clear_connected)
{
EditBone *curBone;
@@ -141,13 +144,20 @@ void ED_armature_edit_bone_remove(bArmature *arm, EditBone *exBone)
for (curBone = arm->edbo->first; curBone; curBone = curBone->next) {
if (curBone->parent == exBone) {
curBone->parent = exBone->parent;
- curBone->flag &= ~BONE_CONNECTED;
+ if (clear_connected) {
+ curBone->flag &= ~BONE_CONNECTED;
+ }
}
}
bone_free(arm, exBone);
}
+void ED_armature_ebone_remove(bArmature *arm, EditBone *exBone)
+{
+ ED_armature_ebone_remove_ex(arm, exBone, true);
+}
+
bool ED_armature_ebone_is_child_recursive(EditBone *ebone_parent, EditBone *ebone_child)
{
for (ebone_child = ebone_child->parent; ebone_child; ebone_child = ebone_child->parent) {
@@ -164,7 +174,7 @@ bool ED_armature_ebone_is_child_recursive(EditBone *ebone_parent, EditBone *ebon
* \param ebone_child_tot Size of the ebone_child array
* \return The shared parent or NULL.
*/
-EditBone *ED_armature_bone_find_shared_parent(EditBone *ebone_child[], const unsigned int ebone_child_tot)
+EditBone *ED_armature_ebone_find_shared_parent(EditBone *ebone_child[], const unsigned int ebone_child_tot)
{
unsigned int i;
EditBone *ebone_iter;
@@ -244,7 +254,7 @@ void ED_armature_ebone_from_mat4(EditBone *ebone, float mat[4][4])
/**
* Return a pointer to the bone of the given name
*/
-EditBone *ED_armature_bone_find_name(const ListBase *edbo, const char *name)
+EditBone *ED_armature_ebone_find_name(const ListBase *edbo, const char *name)
{
return BLI_findstring(edbo, name, offsetof(EditBone, name));
}
@@ -256,7 +266,7 @@ EditBone *ED_armature_bone_find_name(const ListBase *edbo, const char *name)
/**
* \see #BKE_pose_channel_get_mirrored (pose-mode, matching function)
*/
-EditBone *ED_armature_bone_get_mirrored(const ListBase *edbo, EditBone *ebo)
+EditBone *ED_armature_ebone_get_mirrored(const ListBase *edbo, EditBone *ebo)
{
char name_flip[MAXBONENAME];
@@ -266,7 +276,7 @@ EditBone *ED_armature_bone_get_mirrored(const ListBase *edbo, EditBone *ebo)
BLI_string_flip_side_name(name_flip, ebo->name, false, sizeof(name_flip));
if (!STREQ(name_flip, ebo->name)) {
- return ED_armature_bone_find_name(edbo, name_flip);
+ return ED_armature_ebone_find_name(edbo, name_flip);
}
return NULL;
@@ -286,7 +296,7 @@ void armature_select_mirrored_ex(bArmature *arm, const int flag)
for (curBone = arm->edbo->first; curBone; curBone = curBone->next) {
if (arm->layer & curBone->layer) {
if (curBone->flag & flag) {
- ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, curBone);
+ ebone_mirr = ED_armature_ebone_get_mirrored(arm->edbo, curBone);
if (ebone_mirr)
ebone_mirr->flag |= (curBone->flag & flag);
}
@@ -315,7 +325,7 @@ void armature_tag_select_mirrored(bArmature *arm)
for (curBone = arm->edbo->first; curBone; curBone = curBone->next) {
if (arm->layer & curBone->layer) {
if (curBone->flag & (BONE_SELECTED | BONE_ROOTSEL | BONE_TIPSEL)) {
- EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, curBone);
+ EditBone *ebone_mirr = ED_armature_ebone_get_mirrored(arm->edbo, curBone);
if (ebone_mirr && (ebone_mirr->flag & BONE_SELECTED) == 0) {
ebone_mirr->flag |= BONE_DONE;
}
@@ -325,7 +335,7 @@ void armature_tag_select_mirrored(bArmature *arm)
for (curBone = arm->edbo->first; curBone; curBone = curBone->next) {
if (curBone->flag & BONE_DONE) {
- EditBone *ebone_mirr = ED_armature_bone_get_mirrored(arm->edbo, curBone);
+ EditBone *ebone_mirr = ED_armature_ebone_get_mirrored(arm->edbo, curBone);
curBone->flag |= ebone_mirr->flag & (BONE_SELECTED | BONE_ROOTSEL | BONE_TIPSEL);
}
}
@@ -348,7 +358,7 @@ void armature_tag_unselect(bArmature *arm)
/* if editbone (partial) selected, copy data */
/* context; editmode armature, with mirror editing enabled */
-void transform_armature_mirror_update(Object *obedit)
+void ED_armature_edit_transform_mirror_update(Object *obedit)
{
bArmature *arm = obedit->data;
EditBone *ebo, *eboflip;
@@ -356,7 +366,7 @@ void transform_armature_mirror_update(Object *obedit)
for (ebo = arm->edbo->first; ebo; ebo = ebo->next) {
/* no layer check, correct mirror is more important */
if (ebo->flag & (BONE_TIPSEL | BONE_ROOTSEL)) {
- eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
+ eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebo);
if (eboflip) {
/* we assume X-axis flipping for now */
@@ -426,7 +436,7 @@ EditBone *make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent, Bone
eBone = MEM_callocN(sizeof(EditBone), "make_editbone");
/* Copy relevant data from bone to eBone
- * Keep selection logic in sync with ED_armature_sync_selection.
+ * Keep selection logic in sync with ED_armature_edit_sync_selection.
*/
eBone->parent = parent;
BLI_strncpy(eBone->name, curBone->name, sizeof(eBone->name));
@@ -462,19 +472,20 @@ EditBone *make_boneList(ListBase *edbo, ListBase *bones, EditBone *parent, Bone
eBone->weight = curBone->weight;
eBone->xwidth = curBone->xwidth;
eBone->zwidth = curBone->zwidth;
- eBone->ease1 = curBone->ease1;
- eBone->ease2 = curBone->ease2;
eBone->rad_head = curBone->rad_head;
eBone->rad_tail = curBone->rad_tail;
eBone->segments = curBone->segments;
eBone->layer = curBone->layer;
+ /* Bendy-Bone parameters */
eBone->roll1 = curBone->roll1;
eBone->roll2 = curBone->roll2;
eBone->curveInX = curBone->curveInX;
eBone->curveInY = curBone->curveInY;
eBone->curveOutX = curBone->curveOutX;
eBone->curveOutY = curBone->curveOutY;
+ eBone->ease1 = curBone->ease1;
+ eBone->ease2 = curBone->ease2;
eBone->scaleIn = curBone->scaleIn;
eBone->scaleOut = curBone->scaleOut;
@@ -590,7 +601,7 @@ void ED_armature_from_edit(bArmature *arm)
if (len_sq <= SQUARE(0.000001f)) { /* FLT_EPSILON is too large? */
EditBone *fBone;
- /* Find any bones that refer to this bone */
+ /* Find any bones that refer to this bone */
for (fBone = arm->edbo->first; fBone; fBone = fBone->next) {
if (fBone->parent == eBone)
fBone->parent = eBone->parent;
@@ -626,19 +637,20 @@ void ED_armature_from_edit(bArmature *arm)
newBone->xwidth = eBone->xwidth;
newBone->zwidth = eBone->zwidth;
- newBone->ease1 = eBone->ease1;
- newBone->ease2 = eBone->ease2;
newBone->rad_head = eBone->rad_head;
newBone->rad_tail = eBone->rad_tail;
newBone->segments = eBone->segments;
newBone->layer = eBone->layer;
+ /* Bendy-Bone parameters */
newBone->roll1 = eBone->roll1;
newBone->roll2 = eBone->roll2;
newBone->curveInX = eBone->curveInX;
newBone->curveInY = eBone->curveInY;
newBone->curveOutX = eBone->curveOutX;
newBone->curveOutY = eBone->curveOutY;
+ newBone->ease1 = eBone->ease1;
+ newBone->ease2 = eBone->ease2;
newBone->scaleIn = eBone->scaleIn;
newBone->scaleOut = eBone->scaleOut;
@@ -708,11 +720,11 @@ void ED_armature_to_edit(bArmature *arm)
}
/* *************************************************************** */
-/* Undo for Armature EditMode*/
+/* Used by Undo for Armature EditMode*/
/* free's bones and their properties */
-static void ED_armature_ebone_listbase_free(ListBase *lb)
+void ED_armature_ebone_listbase_free(ListBase *lb)
{
EditBone *ebone, *ebone_next;
@@ -730,7 +742,7 @@ static void ED_armature_ebone_listbase_free(ListBase *lb)
BLI_listbase_clear(lb);
}
-static void ED_armature_ebone_listbase_copy(ListBase *lb_dst, ListBase *lb_src)
+void ED_armature_ebone_listbase_copy(ListBase *lb_dst, ListBase *lb_src)
{
EditBone *ebone_src;
EditBone *ebone_dst;
@@ -763,78 +775,6 @@ void ED_armature_ebone_listbase_temp_clear(ListBase *lb)
}
}
-typedef struct UndoArmature {
- EditBone *act_edbone;
- ListBase lb;
-} UndoArmature;
-
-static void undoBones_to_editBones(void *uarmv, void *armv, void *UNUSED(data))
-{
- UndoArmature *uarm = uarmv;
- bArmature *arm = armv;
- EditBone *ebone;
-
- ED_armature_ebone_listbase_free(arm->edbo);
- ED_armature_ebone_listbase_copy(arm->edbo, &uarm->lb);
-
- /* active bone */
- if (uarm->act_edbone) {
- ebone = uarm->act_edbone;
- arm->act_edbone = ebone->temp.ebone;
- }
- else {
- arm->act_edbone = NULL;
- }
-
- ED_armature_ebone_listbase_temp_clear(arm->edbo);
-}
-
-static void *editBones_to_undoBones(void *armv, void *UNUSED(obdata))
-{
- bArmature *arm = armv;
- UndoArmature *uarm;
- EditBone *ebone;
-
- uarm = MEM_callocN(sizeof(UndoArmature), "listbase undo");
-
- ED_armature_ebone_listbase_copy(&uarm->lb, arm->edbo);
-
- /* active bone */
- if (arm->act_edbone) {
- ebone = arm->act_edbone;
- uarm->act_edbone = ebone->temp.ebone;
- }
-
- ED_armature_ebone_listbase_temp_clear(&uarm->lb);
-
- return uarm;
-}
-
-static void free_undoBones(void *uarmv)
-{
- UndoArmature *uarm = uarmv;
-
- ED_armature_ebone_listbase_free(&uarm->lb);
-
- MEM_freeN(uarm);
-}
-
-static void *get_armature_edit(bContext *C)
-{
- Object *obedit = CTX_data_edit_object(C);
- if (obedit && obedit->type == OB_ARMATURE) {
- return obedit->data;
- }
- return NULL;
-}
-
-/* and this is all the undo system needs to know */
-void undo_push_armature(bContext *C, const char *name)
-{
- // XXX solve getdata()
- undo_editmode_push(C, name, get_armature_edit, free_undoBones, undoBones_to_editBones, editBones_to_undoBones, NULL);
-}
-
/* *************************************************************** */
/* Low level selection functions which hide connected-parent
* flag behavior which gets tricky to handle in selection operators.
diff --git a/source/blender/editors/armature/editarmature_generate.c b/source/blender/editors/armature/editarmature_generate.c
index 4eb9e3ecc79..57843265496 100644
--- a/source/blender/editors/armature/editarmature_generate.c
+++ b/source/blender/editors/armature/editarmature_generate.c
@@ -39,7 +39,7 @@ void setBoneRollFromNormal(EditBone *bone, const float no[3], float UNUSED(invma
copy_v3_v3(normal, no);
mul_m3_v3(tmat, normal);
- bone->roll = ED_rollBoneToVector(bone, normal, false);
+ bone->roll = ED_armature_ebone_roll_to_vector(bone, normal, false);
}
}
@@ -252,7 +252,7 @@ EditBone *subdivideArcBy(ToolSettings *toolsettings, bArmature *arm, ListBase *U
IT_head(iter);
- parent = ED_armature_edit_bone_add(arm, "Bone");
+ parent = ED_armature_ebone_add(arm, "Bone");
copy_v3_v3(parent->head, iter->p);
if (iter->size > FLT_EPSILON) {
@@ -265,7 +265,7 @@ EditBone *subdivideArcBy(ToolSettings *toolsettings, bArmature *arm, ListBase *U
while (index != -1) {
IT_peek(iter, index);
- child = ED_armature_edit_bone_add(arm, "Bone");
+ child = ED_armature_ebone_add(arm, "Bone");
copy_v3_v3(child->head, parent->tail);
child->parent = parent;
child->flag |= BONE_CONNECTED;
diff --git a/source/blender/editors/armature/editarmature_retarget.c b/source/blender/editors/armature/editarmature_retarget.c
index fa7bf6e7ad4..6b2893780d7 100644
--- a/source/blender/editors/armature/editarmature_retarget.c
+++ b/source/blender/editors/armature/editarmature_retarget.c
@@ -42,7 +42,7 @@
#include "BKE_context.h"
#include "ED_armature.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "BIF_retarget.h"
@@ -158,11 +158,11 @@ static float rollBoneByQuatAligned(EditBone *bone, float old_up_axis[3], float q
if (angle_normalized_v3v3(x_axis, new_up_axis) < angle_normalized_v3v3(z_axis, new_up_axis)) {
rotation_between_vecs_to_quat(qroll, new_up_axis, x_axis); /* set roll rotation quat */
- return ED_rollBoneToVector(bone, x_axis, false);
+ return ED_armature_ebone_roll_to_vector(bone, x_axis, false);
}
else {
rotation_between_vecs_to_quat(qroll, new_up_axis, z_axis); /* set roll rotation quat */
- return ED_rollBoneToVector(bone, z_axis, false);
+ return ED_armature_ebone_roll_to_vector(bone, z_axis, false);
}
}
@@ -207,7 +207,7 @@ static float rollBoneByQuatJoint(RigEdge *edge, RigEdge *previous, float qrot[4]
/* real qroll between normal and up_axis */
rotation_between_vecs_to_quat(qroll, new_up_axis, normal);
- return ED_rollBoneToVector(edge->bone, normal, false);
+ return ED_armature_ebone_roll_to_vector(edge->bone, normal, false);
}
}
@@ -218,7 +218,7 @@ float rollBoneByQuat(EditBone *bone, float old_up_axis[3], float qrot[4])
copy_v3_v3(new_up_axis, old_up_axis);
mul_qt_v3(qrot, new_up_axis);
- return ED_rollBoneToVector(bone, new_up_axis, false);
+ return ED_armature_ebone_roll_to_vector(bone, new_up_axis, false);
}
/************************************ DESTRUCTORS ******************************************************/
@@ -424,7 +424,7 @@ static void renameTemplateBone(char *name, char *template_name, ListBase *editbo
name[j] = '\0';
- unique_editbone_name(editbones, name, NULL);
+ ED_armature_ebone_unique_name(editbones, name, NULL);
}
static RigControl *cloneControl(RigGraph *rg, RigGraph *src_rg, RigControl *src_ctrl, GHash *ptr_hash, char *side_string, char *num_string)
@@ -911,6 +911,7 @@ static void RIG_reconnectControlBones(RigGraph *rg)
/* if we haven't found one yet, look in control bones */
if (ctrl->tail_mode == TL_NONE) {
+ /* pass */
}
}
}
@@ -1435,7 +1436,7 @@ static EditBone *add_editbonetolist(char *name, ListBase *list)
EditBone *bone = MEM_callocN(sizeof(EditBone), "eBone");
BLI_strncpy(bone->name, name, sizeof(bone->name));
- unique_editbone_name(list, bone->name, NULL);
+ ED_armature_ebone_unique_name(list, bone->name, NULL);
BLI_addtail(list, bone);
@@ -1444,19 +1445,20 @@ static EditBone *add_editbonetolist(char *name, ListBase *list)
bone->dist = 0.25F;
bone->xwidth = 0.1;
bone->zwidth = 0.1;
- bone->ease1 = 1.0;
- bone->ease2 = 1.0;
bone->rad_head = 0.10;
bone->rad_tail = 0.05;
bone->segments = 1;
bone->layer = 1; //arm->layer;
+ /* Bendy-Bone parameters */
bone->roll1 = 0.0f;
bone->roll2 = 0.0f;
bone->curveInX = 0.0f;
bone->curveInY = 0.0f;
bone->curveOutX = 0.0f;
bone->curveOutY = 0.0f;
+ bone->ease1 = 1.0f;
+ bone->ease2 = 1.0f;
bone->scaleIn = 1.0f;
bone->scaleOut = 1.0f;
@@ -2625,7 +2627,7 @@ void BIF_retargetArc(bContext *C, ReebArc *earc, RigGraph *template_rigg)
}
RIG_freeRigGraph((BGraph *)rigg);
- ED_armature_validate_active(armedit);
+ ED_armature_edit_validate_active(armedit);
// XXX
// allqueue(REDRAWVIEW3D, 0);
diff --git a/source/blender/editors/armature/editarmature_sketch.c b/source/blender/editors/armature/editarmature_sketch.c
index f6c04e9570a..a08898a37f6 100644
--- a/source/blender/editors/armature/editarmature_sketch.c
+++ b/source/blender/editors/armature/editarmature_sketch.c
@@ -172,7 +172,7 @@ const char *BIF_listTemplates(const bContext *UNUSED(C))
GHashIterator ghi;
const char *menu_header = IFACE_("Template %t|None %x0|");
char *p;
- const size_t template_size = (BLI_ghash_size(TEMPLATES_HASH) * 32 + 30);
+ const size_t template_size = (BLI_ghash_len(TEMPLATES_HASH) * 32 + 30);
if (TEMPLATES_MENU != NULL) {
MEM_freeN(TEMPLATES_MENU);
@@ -1334,7 +1334,7 @@ static void sk_convertStroke(bContext *C, SK_Stroke *stk)
}
if (bone == NULL) {
- bone = ED_armature_edit_bone_add(arm, "Bone");
+ bone = ED_armature_ebone_add(arm, "Bone");
copy_v3_v3(bone->head, head->p);
copy_v3_v3(bone->tail, pt->p);
@@ -1905,14 +1905,11 @@ static bool sk_selectStroke(bContext *C, SK_Sketch *sketch, const int mval[2], c
unsigned int buffer[MAXPICKBUF];
short hits;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
- rect.xmin = mval[0] - 5;
- rect.xmax = mval[0] + 5;
- rect.ymin = mval[1] - 5;
- rect.ymax = mval[1] + 5;
+ BLI_rcti_init_pt_radius(&rect, mval, 5);
- hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, true);
+ hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, VIEW3D_SELECT_PICK_NEAREST);
if (hits > 0) {
int besthitresult = -1;
diff --git a/source/blender/editors/armature/editarmature_undo.c b/source/blender/editors/armature/editarmature_undo.c
new file mode 100644
index 00000000000..f27d68d0634
--- /dev/null
+++ b/source/blender/editors/armature/editarmature_undo.c
@@ -0,0 +1,191 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation, 2002-2009 full recode.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/armature/editarmature_undo.c
+ * \ingroup edarmature
+ */
+
+#include "DNA_armature_types.h"
+#include "DNA_object_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+#include "BLI_array_utils.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+
+#include "ED_armature.h"
+#include "ED_object.h"
+#include "ED_util.h"
+
+#include "WM_types.h"
+#include "WM_api.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct UndoArmature {
+ EditBone *act_edbone;
+ ListBase lb;
+ size_t undo_size;
+} UndoArmature;
+
+static void undoarm_to_editarm(UndoArmature *uarm, bArmature *arm)
+{
+ EditBone *ebone;
+
+ ED_armature_ebone_listbase_free(arm->edbo);
+ ED_armature_ebone_listbase_copy(arm->edbo, &uarm->lb);
+
+ /* active bone */
+ if (uarm->act_edbone) {
+ ebone = uarm->act_edbone;
+ arm->act_edbone = ebone->temp.ebone;
+ }
+ else {
+ arm->act_edbone = NULL;
+ }
+
+ ED_armature_ebone_listbase_temp_clear(arm->edbo);
+}
+
+static void *undoarm_from_editarm(UndoArmature *uarm, bArmature *arm)
+{
+ BLI_assert(BLI_array_is_zeroed(uarm, 1));
+
+ /* TODO: include size of ID-properties. */
+ uarm->undo_size = 0;
+
+ ED_armature_ebone_listbase_copy(&uarm->lb, arm->edbo);
+
+ /* active bone */
+ if (arm->act_edbone) {
+ EditBone *ebone = arm->act_edbone;
+ uarm->act_edbone = ebone->temp.ebone;
+ }
+
+ ED_armature_ebone_listbase_temp_clear(&uarm->lb);
+
+ for (EditBone *ebone = uarm->lb.first; ebone; ebone = ebone->next) {
+ uarm->undo_size += sizeof(EditBone);
+ }
+
+ return uarm;
+}
+
+static void undoarm_free_data(UndoArmature *uarm)
+{
+ ED_armature_ebone_listbase_free(&uarm->lb);
+}
+
+static Object *editarm_object_from_context(bContext *C)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ if (obedit && obedit->type == OB_ARMATURE) {
+ bArmature *arm = obedit->data;
+ if (arm->edbo != NULL) {
+ return obedit;
+ }
+ }
+ return NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct ArmatureUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ UndoArmature data;
+} ArmatureUndoStep;
+
+static bool armature_undosys_poll(bContext *C)
+{
+ return editarm_object_from_context(C) != NULL;
+}
+
+static bool armature_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ ArmatureUndoStep *us = (ArmatureUndoStep *)us_p;
+ us->obedit_ref.ptr = editarm_object_from_context(C);
+ bArmature *arm = us->obedit_ref.ptr->data;
+ undoarm_from_editarm(&us->data, arm);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void armature_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_EDIT);
+ BLI_assert(armature_undosys_poll(C));
+
+ ArmatureUndoStep *us = (ArmatureUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ bArmature *arm = obedit->data;
+ undoarm_to_editarm(&us->data, arm);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
+}
+
+static void armature_undosys_step_free(UndoStep *us_p)
+{
+ ArmatureUndoStep *us = (ArmatureUndoStep *)us_p;
+ undoarm_free_data(&us->data);
+}
+
+static void armature_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ ArmatureUndoStep *us = (ArmatureUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
+}
+
+/* Export for ED_undo_sys. */
+void ED_armature_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Armature";
+ ut->poll = armature_undosys_poll;
+ ut->step_encode = armature_undosys_step_encode;
+ ut->step_decode = armature_undosys_step_decode;
+ ut->step_free = armature_undosys_step_free;
+
+ ut->step_foreach_ID_ref = armature_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(ArmatureUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/armature/meshlaplacian.c b/source/blender/editors/armature/meshlaplacian.c
index 9500fd59b8b..3c0bb4fe609 100644
--- a/source/blender/editors/armature/meshlaplacian.c
+++ b/source/blender/editors/armature/meshlaplacian.c
@@ -1633,7 +1633,7 @@ static void harmonic_coordinates_bind(Scene *UNUSED(scene), MeshDeformModifierDa
free_bvhtree_from_mesh(&mdb->bvhdata);
}
-void mesh_deform_bind(
+void ED_mesh_deform_bind_callback(
Scene *scene, MeshDeformModifierData *mmd, DerivedMesh *cagedm,
float *vertexcos, int totvert, float cagemat[4][4])
{
diff --git a/source/blender/editors/armature/meshlaplacian.h b/source/blender/editors/armature/meshlaplacian.h
index bba8c739abf..202ac8e9b70 100644
--- a/source/blender/editors/armature/meshlaplacian.h
+++ b/source/blender/editors/armature/meshlaplacian.h
@@ -67,7 +67,7 @@ void rigid_deform_end(int cancel);
/* Harmonic Coordinates */
-/* mesh_deform_bind(...) defined in ED_armature.h */
+/* ED_mesh_deform_bind_callback(...) defined in ED_armature.h */
#endif
diff --git a/source/blender/editors/armature/pose_edit.c b/source/blender/editors/armature/pose_edit.c
index 86b7271bfff..d0c467b2d2c 100644
--- a/source/blender/editors/armature/pose_edit.c
+++ b/source/blender/editors/armature/pose_edit.c
@@ -81,42 +81,55 @@ Object *ED_pose_object_from_context(bContext *C)
}
/* This function is used to process the necessary updates for */
-void ED_armature_enter_posemode(bContext *C, Base *base)
+bool ED_object_posemode_enter_ex(Object *ob)
{
- ReportList *reports = CTX_wm_reports(C);
- Object *ob = base->object;
-
- if (ID_IS_LINKED_DATABLOCK(ob)) {
- BKE_report(reports, RPT_WARNING, "Cannot pose libdata");
- return;
- }
+ BLI_assert(!ID_IS_LINKED(ob));
+ bool ok = false;
switch (ob->type) {
case OB_ARMATURE:
ob->restore_mode = ob->mode;
ob->mode |= OB_MODE_POSE;
-
- WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_POSE, NULL);
-
+ ok = true;
+
break;
default:
- return;
+ break;
}
-
- /* XXX: disabled as this would otherwise cause a nasty loop... */
- //ED_object_toggle_modes(C, ob->mode);
+
+ return ok;
+}
+bool ED_object_posemode_enter(bContext *C, Object *ob)
+{
+ ReportList *reports = CTX_wm_reports(C);
+ if (ID_IS_LINKED(ob)) {
+ BKE_report(reports, RPT_WARNING, "Cannot pose libdata");
+ return false;
+ }
+ bool ok = ED_object_posemode_enter_ex(ob);
+ if (ok) {
+ WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_POSE, NULL);
+ }
+ return ok;
}
-void ED_armature_exit_posemode(bContext *C, Base *base)
+bool ED_object_posemode_exit_ex(Object *ob)
{
- if (base) {
- Object *ob = base->object;
-
+ bool ok = false;
+ if (ob) {
ob->restore_mode = ob->mode;
ob->mode &= ~OB_MODE_POSE;
-
+ ok = true;
+ }
+ return ok;
+}
+bool ED_object_posemode_exit(bContext *C, Object *ob)
+{
+ bool ok = ED_object_posemode_exit_ex(ob);
+ if (ok) {
WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, NULL);
}
+ return ok;
}
/* if a selected or active bone is protected, throw error (oonly if warn == 1) and return 1 */
@@ -265,8 +278,8 @@ void POSE_OT_paths_calculate(wmOperatorType *ot)
static int pose_update_paths_poll(bContext *C)
{
if (ED_operator_posemode_exclusive(C)) {
- bPoseChannel *pchan = CTX_data_active_pose_bone(C);
- return (pchan && pchan->mpath);
+ Object *ob = CTX_data_active_object(C);
+ return (ob->pose->avs.path_bakeflag & MOTIONPATH_BAKE_HAS_PATHS) != 0;
}
return false;
@@ -589,7 +602,7 @@ static void pose_copy_menu(Scene *scene)
/* ********************************************** */
-static int pose_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
+static int pose_flip_names_exec(bContext *C, wmOperator *op)
{
Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
bArmature *arm;
@@ -598,6 +611,8 @@ static int pose_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
if (ELEM(NULL, ob, ob->pose))
return OPERATOR_CANCELLED;
+ const bool do_strip_numbers = RNA_boolean_get(op->ptr, "do_strip_numbers");
+
arm = ob->data;
ListBase bones_names = {NULL};
@@ -608,7 +623,7 @@ static int pose_flip_names_exec(bContext *C, wmOperator *UNUSED(op))
}
CTX_DATA_END;
- ED_armature_bones_flip_names(arm, &bones_names);
+ ED_armature_bones_flip_names(arm, &bones_names, do_strip_numbers);
BLI_freelistN(&bones_names);
@@ -634,6 +649,10 @@ void POSE_OT_flip_names(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "do_strip_numbers", false, "Strip Numbers",
+ "Try to remove right-most dot-number from flipped names "
+ "(WARNING: may result in incoherent naming in some cases)");
}
/* ------------------ */
@@ -670,7 +689,7 @@ static int pose_autoside_names_exec(bContext *C, wmOperator *op)
void POSE_OT_autoside_names(wmOperatorType *ot)
{
- static EnumPropertyItem axis_items[] = {
+ static const EnumPropertyItem axis_items[] = {
{0, "XAXIS", 0, "X-Axis", "Left/Right"},
{1, "YAXIS", 0, "Y-Axis", "Front/Back"},
{2, "ZAXIS", 0, "Z-Axis", "Top/Bottom"},
@@ -1098,16 +1117,18 @@ void POSE_OT_hide(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "");
}
-static int show_pose_bone_cb(Object *ob, Bone *bone, void *UNUSED(ptr))
+static int show_pose_bone_cb(Object *ob, Bone *bone, void *data)
{
+ const bool select = GET_INT_FROM_POINTER(data);
+
bArmature *arm = ob->data;
if (arm->layer & bone->layer) {
if (bone->flag & BONE_HIDDEN_P) {
- bone->flag &= ~BONE_HIDDEN_P;
if (!(bone->flag & BONE_UNSELECTABLE)) {
- bone->flag |= BONE_SELECTED;
+ SET_FLAG_FROM_TEST(bone->flag, select, BONE_SELECTED);
}
+ bone->flag &= ~BONE_HIDDEN_P;
}
}
@@ -1115,12 +1136,13 @@ static int show_pose_bone_cb(Object *ob, Bone *bone, void *UNUSED(ptr))
}
/* active object is armature in posemode, poll checked */
-static int pose_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int pose_reveal_exec(bContext *C, wmOperator *op)
{
Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
bArmature *arm = ob->data;
+ const bool select = RNA_boolean_get(op->ptr, "select");
- bone_looper(ob, arm->bonebase.first, NULL, show_pose_bone_cb);
+ bone_looper(ob, arm->bonebase.first, SET_INT_IN_POINTER(select), show_pose_bone_cb);
/* note, notifier might evolve */
WM_event_add_notifier(C, NC_OBJECT | ND_BONE_SELECT, ob);
@@ -1133,7 +1155,7 @@ void POSE_OT_reveal(wmOperatorType *ot)
/* identifiers */
ot->name = "Reveal Selected";
ot->idname = "POSE_OT_reveal";
- ot->description = "Unhide all bones that have been tagged to be hidden in Pose Mode";
+ ot->description = "Reveal all bones hidden in Pose Mode";
/* api callbacks */
ot->exec = pose_reveal_exec;
@@ -1141,6 +1163,8 @@ void POSE_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/* ********************************************** */
diff --git a/source/blender/editors/armature/pose_group.c b/source/blender/editors/armature/pose_group.c
index c492772b282..c9b1d8613a9 100644
--- a/source/blender/editors/armature/pose_group.c
+++ b/source/blender/editors/armature/pose_group.c
@@ -328,7 +328,7 @@ static int group_move_exec(bContext *C, wmOperator *op)
void POSE_OT_group_move(wmOperatorType *ot)
{
- static EnumPropertyItem group_slot_move[] = {
+ static const EnumPropertyItem group_slot_move[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/armature/pose_lib.c b/source/blender/editors/armature/pose_lib.c
index e3c64b523b1..d9d5fa395d6 100644
--- a/source/blender/editors/armature/pose_lib.c
+++ b/source/blender/editors/armature/pose_lib.c
@@ -184,7 +184,7 @@ static int has_poselib_pose_data_poll(bContext *C)
static int has_poselib_pose_data_for_editing_poll(bContext *C)
{
Object *ob = get_poselib_object(C);
- return (ob && ob->poselib && !ID_IS_LINKED_DATABLOCK(ob->poselib));
+ return (ob && ob->poselib && !ID_IS_LINKED(ob->poselib));
}
/* ----------------------------------- */
@@ -200,7 +200,7 @@ static bAction *poselib_init_new(Object *ob)
if (ob->poselib)
id_us_min(&ob->poselib->id);
- ob->poselib = add_empty_action(G.main, "PoseLib");
+ ob->poselib = BKE_action_add(G.main, "PoseLib");
ob->poselib->idroot = ID_OB;
return ob->poselib;
@@ -328,7 +328,7 @@ static int poselib_sanitize_exec(bContext *C, wmOperator *op)
/* add pose to poselib */
marker = MEM_callocN(sizeof(TimeMarker), "ActionMarker");
- BLI_strncpy(marker->name, "Pose", sizeof(marker->name));
+ BLI_snprintf(marker->name, sizeof(marker->name), "F%d Pose", (int)ak->cfra);
marker->frame = (int)ak->cfra;
marker->flag = -1;
@@ -386,7 +386,7 @@ static int poselib_add_poll(bContext *C)
if (ED_operator_posemode(C)) {
Object *ob = get_poselib_object(C);
if (ob) {
- if ((ob->poselib == NULL) || !ID_IS_LINKED_DATABLOCK(ob->poselib)) {
+ if ((ob->poselib == NULL) || !ID_IS_LINKED(ob->poselib)) {
return true;
}
}
@@ -410,11 +410,10 @@ static void poselib_add_menu_invoke__replacemenu(bContext *C, uiLayout *layout,
/* add each marker to this menu */
for (marker = act->markers.first; marker; marker = marker->next) {
PointerRNA props_ptr;
-
- props_ptr = uiItemFullO_ptr(layout, ot,
- marker->name, ICON_ARMATURE_DATA, NULL,
- WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
-
+ uiItemFullO_ptr(
+ layout, ot,
+ marker->name, ICON_ARMATURE_DATA, NULL,
+ WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_int_set(&props_ptr, "frame", marker->frame);
RNA_string_set(&props_ptr, "name", marker->name);
}
@@ -529,7 +528,7 @@ void POSELIB_OT_pose_add(wmOperatorType *ot)
/* ----- */
/* can be called with C == NULL */
-static EnumPropertyItem *poselib_stored_pose_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *poselib_stored_pose_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = get_poselib_object(C);
bAction *act = (ob) ? ob->poselib : NULL;
@@ -785,7 +784,7 @@ static int poselib_move_exec(bContext *C, wmOperator *op)
void POSELIB_OT_pose_move(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem pose_lib_pose_move[] = {
+ static const EnumPropertyItem pose_lib_pose_move[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -834,7 +833,6 @@ typedef struct tPoseLib_PreviewData {
bAction *act; /* poselib to use */
TimeMarker *marker; /* 'active' pose */
- int selcount; /* number of selected elements to work on */
int totcount; /* total number of elements to work on */
short state; /* state of main loop */
@@ -867,7 +865,8 @@ enum {
/* defines for tPoseLib_PreviewData->flag values */
enum {
PL_PREVIEW_FIRSTTIME = (1 << 0),
- PL_PREVIEW_SHOWORIGINAL = (1 << 1)
+ PL_PREVIEW_SHOWORIGINAL = (1 << 1),
+ PL_PREVIEW_ANY_BONE_SELECTED = (1 << 2),
};
/* ---------------------------- */
@@ -887,7 +886,20 @@ static void poselib_backup_posecopy(tPoseLib_PreviewData *pld)
{
bActionGroup *agrp;
bPoseChannel *pchan;
-
+ bool selected = false;
+
+ /* determine whether any bone is selected. */
+ LISTBASE_FOREACH (bPoseChannel *, bchan, &pld->pose->chanbase) {
+ selected = bchan->bone != NULL && bchan->bone->flag & BONE_SELECTED;
+ if (selected) {
+ pld->flag |= PL_PREVIEW_ANY_BONE_SELECTED;
+ break;
+ }
+ }
+ if (!selected) {
+ pld->flag &= ~PL_PREVIEW_ANY_BONE_SELECTED;
+ }
+
/* for each posechannel that has an actionchannel in */
for (agrp = pld->act->groups.first; agrp; agrp = agrp->next) {
/* try to find posechannel */
@@ -909,8 +921,6 @@ static void poselib_backup_posecopy(tPoseLib_PreviewData *pld)
BLI_addtail(&pld->backups, plb);
/* mark as being affected */
- if ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))
- pld->selcount++;
pld->totcount++;
}
}
@@ -971,6 +981,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
KeyframeEditData ked = {{NULL}};
KeyframeEditFunc group_ok_cb;
int frame = 1;
+ const bool any_bone_selected = pld->flag & PL_PREVIEW_ANY_BONE_SELECTED;
/* get the frame */
if (pld->marker)
@@ -983,8 +994,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
group_ok_cb = ANIM_editkeyframes_ok(BEZT_OK_FRAMERANGE);
ked.f1 = ((float)frame) - 0.5f;
ked.f2 = ((float)frame) + 0.5f;
-
-
+
/* start applying - only those channels which have a key at this point in time! */
for (agrp = act->groups.first; agrp; agrp = agrp->next) {
/* check if group has any keyframes */
@@ -996,7 +1006,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
bool ok = 0;
/* check if this bone should get any animation applied */
- if (pld->selcount == 0) {
+ if (!any_bone_selected) {
/* if no bones are selected, then any bone is ok */
ok = 1;
}
@@ -1009,7 +1019,7 @@ static void poselib_apply_pose(tPoseLib_PreviewData *pld)
ok = 1;
}
}
-
+
if (ok)
animsys_evaluate_action_group(ptr, act, agrp, NULL, (float)frame);
}
@@ -1028,14 +1038,15 @@ static void poselib_keytag_pose(bContext *C, Scene *scene, tPoseLib_PreviewData
KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_WHOLE_CHARACTER_ID);
ListBase dsources = {NULL, NULL};
bool autokey = autokeyframe_cfra_can_key(scene, &pld->ob->id);
-
+ const bool any_bone_selected = pld->flag & PL_PREVIEW_ANY_BONE_SELECTED;
+
/* start tagging/keying */
for (agrp = act->groups.first; agrp; agrp = agrp->next) {
/* only for selected bones unless there aren't any selected, in which case all are included */
pchan = BKE_pose_channel_find_name(pose, agrp->name);
if (pchan) {
- if ((pld->selcount == 0) || ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))) {
+ if (!any_bone_selected || ((pchan->bone) && (pchan->bone->flag & BONE_SELECTED))) {
if (autokey) {
/* add datasource override for the PoseChannel, to be used later */
ANIM_relative_keyingset_add_source(&dsources, &pld->ob->id, &RNA_PoseBone, pchan);
diff --git a/source/blender/editors/armature/pose_select.c b/source/blender/editors/armature/pose_select.c
index 44470c1f827..4b62fd15c04 100644
--- a/source/blender/editors/armature/pose_select.c
+++ b/source/blender/editors/armature/pose_select.c
@@ -132,8 +132,9 @@ void ED_pose_bone_select(Object *ob, bPoseChannel *pchan, bool select)
/* called from editview.c, for mode-less pose selection */
/* assumes scene obact and basact is still on old situation */
-int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, short hits,
- bool extend, bool deselect, bool toggle, bool do_nearest)
+bool ED_armature_pose_select_pick_with_buffer(
+ Scene *scene, Base *base, const unsigned int *buffer, short hits,
+ bool extend, bool deselect, bool toggle, bool do_nearest)
{
Object *ob = base->object;
Bone *nearBone;
@@ -154,7 +155,7 @@ int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, shor
* always give predictable behavior in weight paint mode - campbell */
if ((ob_act == NULL) || ((ob_act != ob) && (ob_act->mode & OB_MODE_WEIGHT_PAINT) == 0)) {
/* when we are entering into posemode via toggle-select,
- * frop another active object - always select the bone. */
+ * from another active object - always select the bone. */
if (!extend && !deselect && toggle) {
/* re-select below */
nearBone->flag &= ~BONE_SELECTED;
@@ -162,7 +163,7 @@ int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, shor
}
if (!extend && !deselect && !toggle) {
- ED_pose_de_selectall(ob, SEL_DESELECT, true);
+ ED_pose_deselect_all(ob, SEL_DESELECT, true);
nearBone->flag |= (BONE_SELECTED | BONE_TIPSEL | BONE_ROOTSEL);
arm->act_bone = nearBone;
}
@@ -216,7 +217,7 @@ int ED_do_pose_selectbuffer(Scene *scene, Base *base, unsigned int *buffer, shor
/* 'select_mode' is usual SEL_SELECT/SEL_DESELECT/SEL_TOGGLE/SEL_INVERT.
* When true, 'ignore_visibility' makes this func also affect invisible bones (hidden or on hidden layers). */
-void ED_pose_de_selectall(Object *ob, int select_mode, const bool ignore_visibility)
+void ED_pose_deselect_all(Object *ob, int select_mode, const bool ignore_visibility)
{
bArmature *arm = ob->data;
bPoseChannel *pchan;
@@ -226,7 +227,7 @@ void ED_pose_de_selectall(Object *ob, int select_mode, const bool ignore_visibil
return;
}
- /* Determine if we're selecting or deselecting */
+ /* Determine if we're selecting or deselecting */
if (select_mode == SEL_TOGGLE) {
select_mode = SEL_SELECT;
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
@@ -280,12 +281,9 @@ static int pose_select_connected_invoke(bContext *C, wmOperator *op, const wmEve
const bool extend = RNA_boolean_get(op->ptr, "extend");
view3d_operator_needs_opengl(C);
-
- if (extend)
- bone = get_nearest_bone(C, 0, event->mval[0], event->mval[1]);
- else
- bone = get_nearest_bone(C, 1, event->mval[0], event->mval[1]);
-
+
+ bone = get_nearest_bone(C, event->mval, !extend);
+
if (!bone)
return OPERATOR_CANCELLED;
@@ -593,7 +591,7 @@ static int pose_select_hierarchy_exec(bContext *C, wmOperator *op)
void POSE_OT_select_hierarchy(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{BONE_SELECT_PARENT, "PARENT", 0, "Select Parent", ""},
{BONE_SELECT_CHILD, "CHILD", 0, "Select Child", ""},
{0, NULL, 0, NULL, NULL}
@@ -842,7 +840,7 @@ static int pose_select_grouped_exec(bContext *C, wmOperator *op)
void POSE_OT_select_grouped(wmOperatorType *ot)
{
- static EnumPropertyItem prop_select_grouped_types[] = {
+ static const EnumPropertyItem prop_select_grouped_types[] = {
{POSE_SEL_SAME_LAYER, "LAYER", 0, "Layer", "Shared layers"},
{POSE_SEL_SAME_GROUP, "GROUP", 0, "Group", "Shared group"},
{POSE_SEL_SAME_KEYINGSET, "KEYINGSET", 0, "Keying Set", "All bones affected by active Keying Set"},
diff --git a/source/blender/editors/armature/pose_slide.c b/source/blender/editors/armature/pose_slide.c
index 8e8345d34c9..e5331aff12b 100644
--- a/source/blender/editors/armature/pose_slide.c
+++ b/source/blender/editors/armature/pose_slide.c
@@ -39,6 +39,7 @@
#include "DNA_scene_types.h"
#include "BKE_fcurve.h"
+#include "BKE_nla.h"
#include "BKE_context.h"
#include "BKE_object.h"
@@ -94,12 +95,19 @@ typedef struct tPoseSlideOp {
ListBase pfLinks; /* links between posechannels and f-curves */
DLRBT_Tree keys; /* binary tree for quicker searching for keyframes (when applicable) */
- int cframe; /* current frame number */
- int prevFrame; /* frame before current frame (blend-from) */
- int nextFrame; /* frame after current frame (blend-to) */
+ int cframe; /* current frame number - global time */
- int mode; /* sliding mode (ePoseSlide_Modes) */
- int flag; /* unused for now, but can later get used for storing runtime settings.... */
+ int prevFrame; /* frame before current frame (blend-from) - global time */
+ int nextFrame; /* frame after current frame (blend-to) - global time */
+
+ float prevFrameF; /* prevFrame, but in local action time (for F-Curve lookups to work) */
+ float nextFrameF; /* nextFrame, but in local action time (for F-Curve lookups to work) */
+
+ short mode; /* sliding mode (ePoseSlide_Modes) */
+ short flag; /* unused for now, but can later get used for storing runtime settings.... */
+
+ short channels; /* which transforms/channels are affected (ePoseSlide_Channels) */
+ short axislock; /* axis-limits for transforms (ePoseSlide_AxisLock) */
float percentage; /* 0-1 value for determining the influence of whatever is relevant */
@@ -113,6 +121,49 @@ typedef enum ePoseSlide_Modes {
POSESLIDE_BREAKDOWN, /* slide between the endpoint poses, finding a 'soft' spot */
} ePoseSlide_Modes;
+
+/* Transforms/Channels to Affect */
+typedef enum ePoseSlide_Channels {
+ PS_TFM_ALL = 0, /* All transforms and properties */
+
+ PS_TFM_LOC, /* Loc/Rot/Scale */
+ PS_TFM_ROT,
+ PS_TFM_SIZE,
+
+ PS_TFM_BBONE_SHAPE, /* Bendy Bones */
+
+ PS_TFM_PROPS /* Custom Properties */
+} ePoseSlide_Channels;
+
+/* Property enum for ePoseSlide_Channels */
+static const EnumPropertyItem prop_channels_types[] = {
+ {PS_TFM_ALL, "ALL", 0, "All Properties",
+ "All properties, including transforms, bendy bone shape, and custom properties"},
+ {PS_TFM_LOC, "LOC", 0, "Location", "Location only"},
+ {PS_TFM_ROT, "ROT", 0, "Rotation", "Rotation only"},
+ {PS_TFM_SIZE, "SIZE", 0, "Scale", "Scale only"},
+ {PS_TFM_BBONE_SHAPE, "BBONE", 0, "Bendy Bone", "Bendy Bone shape properties"},
+ {PS_TFM_PROPS, "CUSTOM", 0, "Custom Properties", "Custom properties"},
+ {0, NULL, 0, NULL, NULL}
+};
+
+/* Axis Locks */
+typedef enum ePoseSlide_AxisLock {
+ PS_LOCK_X = (1 << 0),
+ PS_LOCK_Y = (1 << 1),
+ PS_LOCK_Z = (1 << 2)
+} ePoseSlide_AxisLock;
+
+/* Property enum for ePoseSlide_AxisLock */
+static const EnumPropertyItem prop_axis_lock_types[] = {
+ {0, "FREE", 0, "Free", "All axes are affected"},
+ {PS_LOCK_X, "X", 0, "X", "Only X-axis transforms are affected"},
+ {PS_LOCK_Y, "Y", 0, "Y", "Only Y-axis transforms are affected"},
+ {PS_LOCK_Z, "Z", 0, "Z", "Only Z-axis transforms are affected"},
+ /* TODO: Combinations? */
+ {0, NULL, 0, NULL, NULL}
+};
+
/* ------------------------------------ */
/* operator init */
@@ -139,11 +190,19 @@ static int pose_slide_init(bContext *C, wmOperator *op, short mode)
pso->prevFrame = RNA_int_get(op->ptr, "prev_frame");
pso->nextFrame = RNA_int_get(op->ptr, "next_frame");
- /* check the settings from the context */
+ /* get the set of properties/axes that can be operated on */
+ pso->channels = RNA_enum_get(op->ptr, "channels");
+ pso->axislock = RNA_enum_get(op->ptr, "axis_lock");
+
+ /* ensure validity of the settings from the context */
if (ELEM(NULL, pso->ob, pso->arm, pso->ob->adt, pso->ob->adt->action))
return 0;
- else
- act = pso->ob->adt->action;
+
+ act = pso->ob->adt->action;
+
+ /* apply NLA mapping corrections so the frame lookups work */
+ pso->prevFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->prevFrame, NLATIME_CONVERT_UNMAP);
+ pso->nextFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->nextFrame, NLATIME_CONVERT_UNMAP);
/* for each Pose-Channel which gets affected, get the F-Curves for that channel
* and set the relevant transform flags...
@@ -209,9 +268,9 @@ static void pose_slide_apply_val(tPoseSlideOp *pso, FCurve *fcu, float *val)
/* get keyframe values for endpoint poses to blend with */
/* previous/start */
- sVal = evaluate_fcurve(fcu, (float)pso->prevFrame);
+ sVal = evaluate_fcurve(fcu, pso->prevFrameF);
/* next/end */
- eVal = evaluate_fcurve(fcu, (float)pso->nextFrame);
+ eVal = evaluate_fcurve(fcu, pso->nextFrameF);
/* if both values are equal, don't do anything */
if (IS_EQF(sVal, eVal)) {
@@ -293,10 +352,20 @@ static void pose_slide_apply_vec3(tPoseSlideOp *pso, tPChanFCurveLink *pfl, floa
/* using this path, find each matching F-Curve for the variables we're interested in */
while ( (ld = poseAnim_mapping_getNextFCurve(&pfl->fcurves, ld, path)) ) {
FCurve *fcu = (FCurve *)ld->data;
-
- /* just work on these channels one by one... there's no interaction between values */
+ const int idx = fcu->array_index;
+ const int lock = pso->axislock;
+
+ /* check if this F-Curve is ok given the current axis locks */
BLI_assert(fcu->array_index < 3);
- pose_slide_apply_val(pso, fcu, &vec[fcu->array_index]);
+
+ if ((lock == 0) ||
+ ((lock & PS_LOCK_X) && (idx == 0)) ||
+ ((lock & PS_LOCK_Y) && (idx == 1)) ||
+ ((lock & PS_LOCK_Z) && (idx == 2)))
+ {
+ /* just work on these channels one by one... there's no interaction between values */
+ pose_slide_apply_val(pso, fcu, &vec[fcu->array_index]);
+ }
}
/* free the temp path we got */
@@ -423,15 +492,15 @@ static void pose_slide_apply_quat(tPoseSlideOp *pso, tPChanFCurveLink *pfl)
float quat_prev[4], quat_next[4];
/* get 2 quats */
- quat_prev[0] = evaluate_fcurve(fcu_w, pso->prevFrame);
- quat_prev[1] = evaluate_fcurve(fcu_x, pso->prevFrame);
- quat_prev[2] = evaluate_fcurve(fcu_y, pso->prevFrame);
- quat_prev[3] = evaluate_fcurve(fcu_z, pso->prevFrame);
+ quat_prev[0] = evaluate_fcurve(fcu_w, pso->prevFrameF);
+ quat_prev[1] = evaluate_fcurve(fcu_x, pso->prevFrameF);
+ quat_prev[2] = evaluate_fcurve(fcu_y, pso->prevFrameF);
+ quat_prev[3] = evaluate_fcurve(fcu_z, pso->prevFrameF);
- quat_next[0] = evaluate_fcurve(fcu_w, pso->nextFrame);
- quat_next[1] = evaluate_fcurve(fcu_x, pso->nextFrame);
- quat_next[2] = evaluate_fcurve(fcu_y, pso->nextFrame);
- quat_next[3] = evaluate_fcurve(fcu_z, pso->nextFrame);
+ quat_next[0] = evaluate_fcurve(fcu_w, pso->nextFrameF);
+ quat_next[1] = evaluate_fcurve(fcu_x, pso->nextFrameF);
+ quat_next[2] = evaluate_fcurve(fcu_y, pso->nextFrameF);
+ quat_next[3] = evaluate_fcurve(fcu_z, pso->nextFrameF);
/* perform blending */
if (pso->mode == POSESLIDE_BREAKDOWN) {
@@ -483,6 +552,10 @@ static void pose_slide_apply(bContext *C, tPoseSlideOp *pso)
/* move out one step either side */
pso->prevFrame--;
pso->nextFrame++;
+
+ /* apply NLA mapping corrections so the frame lookups work */
+ pso->prevFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->prevFrame, NLATIME_CONVERT_UNMAP);
+ pso->nextFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->nextFrame, NLATIME_CONVERT_UNMAP);
}
/* for each link, handle each set of transforms */
@@ -494,17 +567,17 @@ static void pose_slide_apply(bContext *C, tPoseSlideOp *pso)
*/
bPoseChannel *pchan = pfl->pchan;
- if (pchan->flag & POSE_LOC) {
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_LOC) && (pchan->flag & POSE_LOC)) {
/* calculate these for the 'location' vector, and use location curves */
pose_slide_apply_vec3(pso, pfl, pchan->loc, "location");
}
- if (pchan->flag & POSE_SIZE) {
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_SIZE) && (pchan->flag & POSE_SIZE)) {
/* calculate these for the 'scale' vector, and use scale curves */
pose_slide_apply_vec3(pso, pfl, pchan->size, "scale");
}
- if (pchan->flag & POSE_ROT) {
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_ROT) && (pchan->flag & POSE_ROT)) {
/* everything depends on the rotation mode */
if (pchan->rotmode > 0) {
/* eulers - so calculate these for the 'eul' vector, and use euler_rotation curves */
@@ -519,12 +592,12 @@ static void pose_slide_apply(bContext *C, tPoseSlideOp *pso)
}
}
- if (pchan->flag & POSE_BBONE_SHAPE) {
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_BBONE_SHAPE) && (pchan->flag & POSE_BBONE_SHAPE)) {
/* bbone properties - they all start a "bbone_" prefix */
pose_slide_apply_props(pso, pfl, "bbone_");
}
- if (pfl->oldprops) {
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_PROPS) && (pfl->oldprops)) {
/* not strictly a transform, but custom properties contribute to the pose produced in many rigs
* (e.g. the facial rigs used in Sintel)
*/
@@ -553,9 +626,12 @@ static void pose_slide_reset(tPoseSlideOp *pso)
/* ------------------------------------ */
/* draw percentage indicator in header */
+// TODO: Include hints about locks here...
static void pose_slide_draw_status(tPoseSlideOp *pso)
{
char status_str[UI_MAX_DRAW_STR];
+ char limits_str[UI_MAX_DRAW_STR];
+ char axis_str[50];
char mode_str[32];
switch (pso->mode) {
@@ -575,16 +651,58 @@ static void pose_slide_draw_status(tPoseSlideOp *pso)
break;
}
+ switch (pso->axislock) {
+ case PS_LOCK_X:
+ BLI_strncpy(axis_str, "[X]/Y/Z axis only (X to clear)", sizeof(axis_str));
+ break;
+ case PS_LOCK_Y:
+ BLI_strncpy(axis_str, "X/[Y]/Z axis only (Y to clear)", sizeof(axis_str));
+ break;
+ case PS_LOCK_Z:
+ BLI_strncpy(axis_str, "X/Y/[Z] axis only (Z to clear)", sizeof(axis_str));
+ break;
+
+ default:
+ if (ELEM(pso->channels, PS_TFM_LOC, PS_TFM_ROT, PS_TFM_SIZE)) {
+ BLI_strncpy(axis_str, "X/Y/Z = Axis Constraint", sizeof(axis_str));
+ }
+ else {
+ axis_str[0] = '\0';
+ }
+ break;
+ }
+
+ switch (pso->channels) {
+ case PS_TFM_LOC:
+ BLI_snprintf(limits_str, sizeof(limits_str), "[G]/R/S/B/C - Location only (G to clear) | %s", axis_str);
+ break;
+ case PS_TFM_ROT:
+ BLI_snprintf(limits_str, sizeof(limits_str), "G/[R]/S/B/C - Rotation only (R to clear) | %s", axis_str);
+ break;
+ case PS_TFM_SIZE:
+ BLI_snprintf(limits_str, sizeof(limits_str), "G/R/[S]/B/C - Scale only (S to clear) | %s", axis_str);
+ break;
+ case PS_TFM_BBONE_SHAPE:
+ BLI_strncpy(limits_str, "G/R/S/[B]/C - Bendy Bone properties only (B to clear) | %s", sizeof(limits_str));
+ break;
+ case PS_TFM_PROPS:
+ BLI_strncpy(limits_str, "G/R/S/B/[C] - Custom Properties only (C to clear) | %s", sizeof(limits_str));
+ break;
+ default:
+ BLI_strncpy(limits_str, "G/R/S/B/C - Limit to Transform/Property Set", sizeof(limits_str));
+ break;
+ }
+
if (hasNumInput(&pso->num)) {
Scene *scene = pso->scene;
char str_offs[NUM_STR_REP_LEN];
outputNumInput(&pso->num, str_offs, &scene->unit);
- BLI_snprintf(status_str, sizeof(status_str), "%s: %s", mode_str, str_offs);
+ BLI_snprintf(status_str, sizeof(status_str), "%s: %s | %s", mode_str, str_offs, limits_str);
}
else {
- BLI_snprintf(status_str, sizeof(status_str), "%s: %d %%", mode_str, (int)(pso->percentage * 100.0f));
+ BLI_snprintf(status_str, sizeof(status_str), "%s: %d %% | %s", mode_str, (int)(pso->percentage * 100.0f), limits_str);
}
ED_area_headerprint(pso->sa, status_str);
@@ -641,6 +759,10 @@ static int pose_slide_invoke_common(bContext *C, wmOperator *op, tPoseSlideOp *p
pso->nextFrame = (ak->next) ? (ak->next->cfra) : (pso->cframe + 1);
RNA_int_set(op->ptr, "next_frame", pso->nextFrame);
}
+
+ /* apply NLA mapping corrections so the frame lookups work */
+ pso->prevFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->prevFrame, NLATIME_CONVERT_UNMAP);
+ pso->nextFrameF = BKE_nla_tweakedit_remap(pso->ob->adt, pso->nextFrame, NLATIME_CONVERT_UNMAP);
}
else {
BKE_report(op->reports, RPT_ERROR, "No keyframes to slide between");
@@ -675,11 +797,58 @@ static void pose_slide_mouse_update_percentage(tPoseSlideOp *pso, wmOperator *op
RNA_float_set(op->ptr, "percentage", pso->percentage);
}
+/* handle an event to toggle channels mode */
+static void pose_slide_toggle_channels_mode(wmOperator *op, tPoseSlideOp *pso, ePoseSlide_Channels channel)
+{
+ /* Turn channel on or off? */
+ if (pso->channels == channel) {
+ /* Already limiting to transform only, so pressing this again turns it off */
+ pso->channels = PS_TFM_ALL;
+ }
+ else {
+ /* Only this set of channels */
+ pso->channels = channel;
+ }
+ RNA_enum_set(op->ptr, "channels", pso->channels);
+
+
+ /* Reset axis limits too for good measure */
+ pso->axislock = 0;
+ RNA_enum_set(op->ptr, "axis_lock", pso->axislock);
+}
+
+/* handle an event to toggle axis locks - returns whether any change in state is needed */
+static bool pose_slide_toggle_axis_locks(wmOperator *op, tPoseSlideOp *pso, ePoseSlide_AxisLock axis)
+{
+ /* Axis can only be set when a transform is set - it doesn't make sense otherwise */
+ if (ELEM(pso->channels, PS_TFM_ALL, PS_TFM_BBONE_SHAPE, PS_TFM_PROPS)) {
+ pso->axislock = 0;
+ RNA_enum_set(op->ptr, "axis_lock", pso->axislock);
+ return false;
+ }
+
+ /* Turn on or off? */
+ if (pso->axislock == axis) {
+ /* Already limiting on this axis, so turn off */
+ pso->axislock = 0;
+ }
+ else {
+ /* Only this axis */
+ pso->axislock = axis;
+ }
+ RNA_enum_set(op->ptr, "axis_lock", pso->axislock);
+
+ /* Setting changed, so pose update is needed */
+ return true;
+}
+
/* common code for modal() */
static int pose_slide_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
tPoseSlideOp *pso = op->customdata;
wmWindow *win = CTX_wm_window(C);
+ bool do_pose_update = false;
+
const bool has_numinput = hasNumInput(&pso->num);
switch (event->type) {
@@ -718,7 +887,8 @@ static int pose_slide_modal(bContext *C, wmOperator *op, const wmEvent *event)
/* canceled! */
return OPERATOR_CANCELLED;
}
-
+
+ /* Percentage Chane... */
case MOUSEMOVE: /* calculate new position */
{
/* only handle mousemove if not doing numinput */
@@ -726,18 +896,13 @@ static int pose_slide_modal(bContext *C, wmOperator *op, const wmEvent *event)
/* update percentage based on position of mouse */
pose_slide_mouse_update_percentage(pso, op, event);
- /* update percentage indicator in header */
- pose_slide_draw_status(pso);
-
- /* reset transforms (to avoid accumulation errors) */
- pose_slide_reset(pso);
-
- /* apply... */
- pose_slide_apply(C, pso);
+ /* update pose to reflect the new values (see below) */
+ do_pose_update = true;
}
break;
}
default:
+ {
if ((event->val == KM_PRESS) && handleNumInput(C, &pso->num, event)) {
float value;
@@ -751,21 +916,94 @@ static int pose_slide_modal(bContext *C, wmOperator *op, const wmEvent *event)
CLAMP(pso->percentage, 0.0f, 1.0f);
RNA_float_set(op->ptr, "percentage", pso->percentage);
- /* update percentage indicator in header */
- pose_slide_draw_status(pso);
-
- /* reset transforms (to avoid accumulation errors) */
- pose_slide_reset(pso);
-
- /* apply... */
- pose_slide_apply(C, pso);
+ /* Update pose to reflect the new values (see below) */
+ do_pose_update = true;
break;
}
+ else if (event->val == KM_PRESS) {
+ switch (event->type) {
+ /* Transform Channel Limits */
+ /* XXX: Replace these hardcoded hotkeys with a modalmap that can be customised */
+ case GKEY: /* Location */
+ {
+ pose_slide_toggle_channels_mode(op, pso, PS_TFM_LOC);
+ do_pose_update = true;
+ break;
+ }
+ case RKEY: /* Rotation */
+ {
+ pose_slide_toggle_channels_mode(op, pso, PS_TFM_ROT);
+ do_pose_update = true;
+ break;
+ }
+ case SKEY: /* Scale */
+ {
+ pose_slide_toggle_channels_mode(op, pso, PS_TFM_SIZE);
+ do_pose_update = true;
+ break;
+ }
+ case BKEY: /* Bendy Bones */
+ {
+ pose_slide_toggle_channels_mode(op, pso, PS_TFM_BBONE_SHAPE);
+ do_pose_update = true;
+ break;
+ }
+ case CKEY: /* Custom Properties */
+ {
+ pose_slide_toggle_channels_mode(op, pso, PS_TFM_PROPS);
+ do_pose_update = true;
+ break;
+ }
+
+
+ /* Axis Locks */
+ /* XXX: Hardcoded... */
+ case XKEY:
+ {
+ if (pose_slide_toggle_axis_locks(op, pso, PS_LOCK_X)) {
+ do_pose_update = true;
+ }
+ break;
+ }
+ case YKEY:
+ {
+ if (pose_slide_toggle_axis_locks(op, pso, PS_LOCK_Y)) {
+ do_pose_update = true;
+ }
+ break;
+ }
+ case ZKEY:
+ {
+ if (pose_slide_toggle_axis_locks(op, pso, PS_LOCK_Z)) {
+ do_pose_update = true;
+ }
+ break;
+ }
+
+
+ default: /* Some other unhandled key... */
+ break;
+ }
+ }
else {
/* unhandled event - maybe it was some view manip? */
/* allow to pass through */
return OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH;
}
+ }
+ }
+
+
+ /* perform pose updates - in response to some user action (e.g. pressing a key or moving the mouse) */
+ if (do_pose_update) {
+ /* update percentage indicator in header */
+ pose_slide_draw_status(pso);
+
+ /* reset transforms (to avoid accumulation errors) */
+ pose_slide_reset(pso);
+
+ /* apply... */
+ pose_slide_apply(C, pso);
}
/* still running... */
@@ -795,11 +1033,16 @@ static int pose_slide_exec_common(bContext *C, wmOperator *op, tPoseSlideOp *pso
}
/* common code for defining RNA properties */
+/* TODO: Skip save on these? */
static void pose_slide_opdef_properties(wmOperatorType *ot)
{
+ RNA_def_float_percentage(ot->srna, "percentage", 0.5f, 0.0f, 1.0f, "Percentage", "Weighting factor for which keyframe is favored more", 0.3, 0.7);
+
RNA_def_int(ot->srna, "prev_frame", 0, MINAFRAME, MAXFRAME, "Previous Keyframe", "Frame number of keyframe immediately before the current frame", 0, 50);
RNA_def_int(ot->srna, "next_frame", 0, MINAFRAME, MAXFRAME, "Next Keyframe", "Frame number of keyframe immediately after the current frame", 0, 50);
- RNA_def_float_percentage(ot->srna, "percentage", 0.5f, 0.0f, 1.0f, "Percentage", "Weighting factor for the sliding operation", 0.3, 0.7);
+
+ RNA_def_enum(ot->srna, "channels", prop_channels_types, PS_TFM_ALL, "Channels", "Set of properties that are affected");
+ RNA_def_enum(ot->srna, "axis_lock", prop_axis_lock_types, 0, "Axis Lock", "Transform axis to restrict effects to");
}
/* ------------------------------------ */
@@ -1238,7 +1481,7 @@ static void pose_propagate_fcurve(wmOperator *op, Object *ob, FCurve *fcu,
/* stop on matching marker if there is one */
for (ce = modeData.sel_markers.first; ce; ce = ce->next) {
- if (ce->cfra == iroundf(bezt->vec[1][0]))
+ if (ce->cfra == round_fl_to_int(bezt->vec[1][0]))
break;
}
@@ -1332,7 +1575,7 @@ static int pose_propagate_exec(bContext *C, wmOperator *op)
void POSE_OT_propagate(wmOperatorType *ot)
{
- static EnumPropertyItem terminate_items[] = {
+ static const EnumPropertyItem terminate_items[] = {
{POSE_PROPAGATE_SMART_HOLDS, "WHILE_HELD", 0, "While Held",
"Propagate pose to all keyframes after current frame that don't change (Default behavior)"},
{POSE_PROPAGATE_NEXT_KEY, "NEXT_KEY", 0, "To Next Keyframe",
diff --git a/source/blender/editors/armature/pose_transform.c b/source/blender/editors/armature/pose_transform.c
index 063ba37f20d..446bab00b70 100644
--- a/source/blender/editors/armature/pose_transform.c
+++ b/source/blender/editors/armature/pose_transform.c
@@ -121,7 +121,7 @@ static int apply_armature_pose2bones_exec(bContext *C, wmOperator *op)
pose = ob->pose;
for (pchan = pose->chanbase.first; pchan; pchan = pchan->next) {
- curbone = ED_armature_bone_find_name(arm->edbo, pchan->name);
+ curbone = ED_armature_ebone_find_name(arm->edbo, pchan->name);
/* simply copy the head/tail values from pchan over to curbone */
copy_v3_v3(curbone->head, pchan->pose_head);
@@ -151,6 +151,28 @@ static int apply_armature_pose2bones_exec(bContext *C, wmOperator *op)
curbone->roll = eul[1];
}
+ /* combine pose and rest values for bendy bone settings,
+ * then clear the pchan values (so we don't get a double-up)
+ */
+ if (pchan->bone->segments > 1) {
+ curbone->curveInX += pchan->curveInX;
+ curbone->curveInY += pchan->curveInY;
+ curbone->curveOutX += pchan->curveOutX;
+ curbone->curveOutY += pchan->curveOutY;
+ curbone->roll1 += pchan->roll1;
+ curbone->roll2 += pchan->roll2;
+ curbone->ease1 += pchan->ease1;
+ curbone->ease2 += pchan->ease2;
+ curbone->scaleIn += pchan->scaleIn;
+ curbone->scaleOut += pchan->scaleOut;
+
+ pchan->curveInX = pchan->curveOutX = 0.0f;
+ pchan->curveInY = pchan->curveOutY = 0.0f;
+ pchan->roll1 = pchan->roll2 = 0.0f;
+ pchan->ease1 = pchan->ease2 = 0.0f;
+ pchan->scaleIn = pchan->scaleOut = 1.0f;
+ }
+
/* clear transform values for pchan */
zero_v3(pchan->loc);
zero_v3(pchan->eul);
@@ -355,6 +377,8 @@ static bPoseChannel *pose_bone_do_paste(Object *ob, bPoseChannel *chan, const bo
pchan->roll1 = chan->roll1;
pchan->roll2 = chan->roll2;
+ pchan->ease1 = chan->ease1;
+ pchan->ease2 = chan->ease2;
pchan->scaleIn = chan->scaleIn;
pchan->scaleOut = chan->scaleOut;
@@ -482,12 +506,15 @@ static int pose_paste_exec(bContext *C, wmOperator *op)
bPoseChannel *chan;
const bool flip = RNA_boolean_get(op->ptr, "flipped");
bool selOnly = RNA_boolean_get(op->ptr, "selected_mask");
+
/* Get KeyingSet to use. */
KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_WHOLE_CHARACTER_ID);
+
/* Sanity checks. */
if (ELEM(NULL, ob, ob->pose)) {
return OPERATOR_CANCELLED;
}
+
/* Read copy buffer .blend file. */
char str[FILE_MAX];
Main *tmp_bmain = BKE_main_new();
@@ -498,11 +525,12 @@ static int pose_paste_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
/* Make sure data from this file is usable for pose paste. */
- if (BLI_listbase_count_ex(&tmp_bmain->object, 2) != 1) {
+ if (BLI_listbase_count_at_most(&tmp_bmain->object, 2) != 1) {
BKE_report(op->reports, RPT_ERROR, "Copy buffer is not from pose mode");
BKE_main_free(tmp_bmain);
return OPERATOR_CANCELLED;
}
+
Object *object_from = tmp_bmain->object.first;
bPose *pose_from = object_from->pose;
if (pose_from == NULL) {
@@ -510,6 +538,7 @@ static int pose_paste_exec(bContext *C, wmOperator *op)
BKE_main_free(tmp_bmain);
return OPERATOR_CANCELLED;
}
+
/* If selOnly option is enabled, if user hasn't selected any bones,
* just go back to default behavior to be more in line with other
* pose tools.
@@ -519,6 +548,7 @@ static int pose_paste_exec(bContext *C, wmOperator *op)
selOnly = false;
}
}
+
/* Safely merge all of the channels in the buffer pose into any
* existing pose.
*/
@@ -533,8 +563,15 @@ static int pose_paste_exec(bContext *C, wmOperator *op)
}
}
BKE_main_free(tmp_bmain);
+
/* Update event for pose and deformation children. */
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+
+ /* Recalculate paths if any of the bones have paths... */
+ if ((ob->pose->avs.path_bakeflag & MOTIONPATH_BAKE_HAS_PATHS)) {
+ ED_pose_recalculate_paths(scene, ob);
+ }
+
/* Notifiers for updates, */
WM_event_add_notifier(C, NC_OBJECT | ND_POSE, ob);
@@ -577,6 +614,8 @@ static void pchan_clear_scale(bPoseChannel *pchan)
if ((pchan->protectflag & OB_LOCK_SCALEZ) == 0)
pchan->size[2] = 1.0f;
+ pchan->ease1 = 0.0f;
+ pchan->ease2 = 0.0f;
pchan->scaleIn = 1.0f;
pchan->scaleOut = 1.0f;
}
@@ -735,7 +774,7 @@ static int pose_clear_transform_generic_exec(bContext *C, wmOperator *op,
/* clear any unkeyed tags */
if (pchan->bone)
pchan->bone->flag &= ~BONE_UNKEYED;
-
+
/* tag for autokeying later */
autokey = 1;
}
diff --git a/source/blender/editors/armature/pose_utils.c b/source/blender/editors/armature/pose_utils.c
index b960bec3603..f80afdd169e 100644
--- a/source/blender/editors/armature/pose_utils.c
+++ b/source/blender/editors/armature/pose_utils.c
@@ -114,6 +114,8 @@ static void fcurves_to_pchan_links_get(ListBase *pfLinks, Object *ob, bAction *a
pfl->curveInY = pchan->curveInY;
pfl->curveOutX = pchan->curveOutX;
pfl->curveOutY = pchan->curveOutY;
+ pfl->ease1 = pchan->ease1;
+ pfl->ease2 = pchan->ease2;
pfl->scaleIn = pchan->scaleIn;
pfl->scaleOut = pchan->scaleOut;
@@ -219,6 +221,8 @@ void poseAnim_mapping_reset(ListBase *pfLinks)
pchan->curveInY = pfl->curveInY;
pchan->curveOutX = pfl->curveOutX;
pchan->curveOutY = pfl->curveOutY;
+ pchan->ease1 = pfl->ease1;
+ pchan->ease2 = pfl->ease2;
pchan->scaleIn = pfl->scaleIn;
pchan->scaleOut = pfl->scaleOut;
diff --git a/source/blender/editors/armature/reeb.c b/source/blender/editors/armature/reeb.c
index 661a8e1de9f..63a255806b8 100644
--- a/source/blender/editors/armature/reeb.c
+++ b/source/blender/editors/armature/reeb.c
@@ -546,7 +546,7 @@ void verifyFaces(ReebGraph *rg)
int total = 0;
ReebArc *arc = NULL;
for (arc = rg->arcs.first; arc; arc = arc->next) {
- total += BLI_ghash_size(arc->faces);
+ total += BLI_ghash_len(arc->faces);
}
#endif
@@ -1656,7 +1656,7 @@ int filterSmartReebGraph(ReebGraph *UNUSED(rg), float UNUSED(threshold))
{
GHashIterator ghi;
int merging = 0;
- int total = BLI_ghash_size(arc->faces);
+ int total = BLI_ghash_len(arc->faces);
float avg_angle = 0;
float avg_vec[3] = {0, 0, 0};
@@ -1932,7 +1932,7 @@ void REEB_exportGraph(ReebGraph *rg, int count)
add_v3_v3v3(p, arc->tail->p, arc->head->p);
mul_v3_fl(p, 0.5f);
- fprintf(f, "angle %0.3f %0.3f %0.3f %0.3f %i\n", p[0], p[1], p[2], arc->angle, BLI_ghash_size(arc->faces));
+ fprintf(f, "angle %0.3f %0.3f %0.3f %0.3f %i\n", p[0], p[1], p[2], arc->angle, BLI_ghash_len(arc->faces));
exportNode(f, "v2", arc->tail);
}
@@ -2240,9 +2240,9 @@ static void glueByMergeSort(ReebGraph *rg, ReebArc *a0, ReebArc *a1, ReebEdge *e
else {
a1 = nextArcMappedToEdge(a1, e1);
}
+ }
}
}
-}
static void mergePaths(ReebGraph *rg, ReebEdge *e0, ReebEdge *e1, ReebEdge *e2)
{
@@ -2678,7 +2678,7 @@ static void shortestPathsFromVert(EditMesh *em, EditVert *starting_vert, EdgeInd
eed->f1 = 0;
}
- while (BLI_heap_size(edge_heap) > 0) {
+ while (BLI_heap_len(edge_heap) > 0) {
float current_weight;
current_eve->f1 = 1; /* mark vertex as selected */
@@ -2695,7 +2695,7 @@ static void shortestPathsFromVert(EditMesh *em, EditVert *starting_vert, EdgeInd
/* Find next shortest edge with unselected verts */
do {
current_weight = BLI_heap_node_value(BLI_heap_top(edge_heap));
- select_eed = BLI_heap_popmin(edge_heap);
+ select_eed = BLI_heap_pop_min(edge_heap);
} while (select_eed != NULL && select_eed->v1->f1 != 0 && select_eed->v2->f1);
if (select_eed != NULL) {
diff --git a/source/blender/editors/curve/CMakeLists.txt b/source/blender/editors/curve/CMakeLists.txt
index 2f5b2ab6e87..13f12f62d95 100644
--- a/source/blender/editors/curve/CMakeLists.txt
+++ b/source/blender/editors/curve/CMakeLists.txt
@@ -42,6 +42,7 @@ set(SRC
editcurve_add.c
editcurve_paint.c
editcurve_select.c
+ editcurve_undo.c
editfont.c
editfont_undo.c
diff --git a/source/blender/editors/curve/curve_intern.h b/source/blender/editors/curve/curve_intern.h
index 856573ffab0..020d34f2767 100644
--- a/source/blender/editors/curve/curve_intern.h
+++ b/source/blender/editors/curve/curve_intern.h
@@ -35,12 +35,13 @@
/* internal exports only */
struct ListBase;
struct EditNurb;
+struct GHash;
struct Object;
struct wmOperatorType;
struct ViewContext;
/* editfont.c */
-enum { DEL_ALL, DEL_NEXT_CHAR, DEL_PREV_CHAR, DEL_SELECTION, DEL_NEXT_SEL, DEL_PREV_SEL };
+enum { DEL_NEXT_CHAR, DEL_PREV_CHAR, DEL_NEXT_WORD, DEL_PREV_WORD, DEL_SELECTION, DEL_NEXT_SEL, DEL_PREV_SEL };
enum { CASE_LOWER, CASE_UPPER };
enum { LINE_BEGIN, LINE_END, PREV_CHAR, NEXT_CHAR, PREV_WORD, NEXT_WORD,
PREV_LINE, NEXT_LINE, PREV_PAGE, NEXT_PAGE };
@@ -109,6 +110,7 @@ void CURVE_OT_radius_set(struct wmOperatorType *ot);
void CURVE_OT_spline_weight_set(struct wmOperatorType *ot);
void CURVE_OT_handle_type_set(struct wmOperatorType *ot);
void CURVE_OT_normals_make_consistent(struct wmOperatorType *ot);
+void CURVE_OT_decimate(struct wmOperatorType *ot);
void CURVE_OT_shade_smooth(struct wmOperatorType *ot);
void CURVE_OT_shade_flat(struct wmOperatorType *ot);
void CURVE_OT_tilt_clear(struct wmOperatorType *ot);
@@ -128,6 +130,10 @@ void CURVE_OT_cyclic_toggle(struct wmOperatorType *ot);
void CURVE_OT_match_texture_space(struct wmOperatorType *ot);
+/* exported for editcurve_undo.c */
+struct GHash *ED_curve_keyindex_hash_duplicate(struct GHash *keyindex);
+void ED_curve_keyindex_update_nurb(struct EditNurb *editnurb, struct Nurb *nu, struct Nurb *newnu);
+
bool ED_curve_pick_vert(
struct ViewContext *vc, short sel, const int mval[2],
struct Nurb **r_nurb, struct BezTriple **r_bezt, struct BPoint **r_bp, short *r_handle);
diff --git a/source/blender/editors/curve/curve_ops.c b/source/blender/editors/curve/curve_ops.c
index fce6425b9be..71cccdfa33d 100644
--- a/source/blender/editors/curve/curve_ops.c
+++ b/source/blender/editors/curve/curve_ops.c
@@ -94,6 +94,7 @@ void ED_operatortypes_curve(void)
WM_operatortype_append(CURVE_OT_spline_weight_set);
WM_operatortype_append(CURVE_OT_handle_type_set);
WM_operatortype_append(CURVE_OT_normals_make_consistent);
+ WM_operatortype_append(CURVE_OT_decimate);
WM_operatortype_append(CURVE_OT_shade_smooth);
WM_operatortype_append(CURVE_OT_shade_flat);
WM_operatortype_append(CURVE_OT_tilt_clear);
@@ -178,9 +179,10 @@ void ED_keymap_curve(wmKeyConfig *keyconf)
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_style_toggle", PKEY, KM_PRESS, KM_CTRL, 0)->ptr, "style", CU_CHINFO_SMALLCAPS);
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", DELKEY, KM_PRESS, 0, 0)->ptr, "type", DEL_NEXT_SEL);
+ RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", DELKEY, KM_PRESS, KM_CTRL, 0)->ptr, "type", DEL_NEXT_WORD);
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", BACKSPACEKEY, KM_PRESS, 0, 0)->ptr, "type", DEL_PREV_SEL);
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", BACKSPACEKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "type", DEL_PREV_SEL); /* same as above [#26623] */
- RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", BACKSPACEKEY, KM_PRESS, KM_CTRL, 0)->ptr, "type", DEL_ALL);
+ RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_delete", BACKSPACEKEY, KM_PRESS, KM_CTRL, 0)->ptr, "type", DEL_PREV_WORD);
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_move", HOMEKEY, KM_PRESS, 0, 0)->ptr, "type", LINE_BEGIN);
RNA_enum_set(WM_keymap_add_item(keymap, "FONT_OT_move", ENDKEY, KM_PRESS, 0, 0)->ptr, "type", LINE_END);
@@ -239,6 +241,9 @@ void ED_keymap_curve(wmKeyConfig *keyconf)
kmi = WM_keymap_add_item(keymap, "CURVE_OT_draw", ACTIONMOUSE, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "wait_for_input", false);
+ kmi = WM_keymap_add_item(keymap, "CURVE_OT_draw", TABLET_STYLUS, KM_PRESS, KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "wait_for_input", false);
+
kmi = WM_keymap_add_item(keymap, "CURVE_OT_select_all", AKEY, KM_PRESS, 0, 0);
RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE);
kmi = WM_keymap_add_item(keymap, "CURVE_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0);
diff --git a/source/blender/editors/curve/editcurve.c b/source/blender/editors/curve/editcurve.c
index 47f42ab5321..ebf2b63bb49 100644
--- a/source/blender/editors/curve/editcurve.c
+++ b/source/blender/editors/curve/editcurve.c
@@ -81,16 +81,6 @@
#include "RNA_define.h"
#include "RNA_enum_types.h"
-/* Undo stuff */
-typedef struct {
- ListBase nubase;
- int actvert;
- GHash *undoIndex;
- ListBase fcurves, drivers;
- int actnu;
- int flag;
-} UndoCurve;
-
void selectend_nurb(Object *obedit, enum eEndPoint_Types selfirst, bool doswap, bool selstatus);
static void adduplicateflagNurb(Object *obedit, ListBase *newnurb, const short flag, const bool split);
static int curve_delete_segments(Object *obedit, const bool split);
@@ -343,7 +333,7 @@ static void keyIndex_updateBP(EditNurb *editnurb, BPoint *bp,
keyIndex_updateCV(editnurb, (char *)bp, (char *)newbp, count, sizeof(BPoint));
}
-static void keyIndex_updateNurb(EditNurb *editnurb, Nurb *nu, Nurb *newnu)
+void ED_curve_keyindex_update_nurb(EditNurb *editnurb, Nurb *nu, Nurb *newnu)
{
if (nu->bezt) {
keyIndex_updateBezt(editnurb, nu->bezt, newnu->bezt, newnu->pntsu);
@@ -522,12 +512,12 @@ static void keyData_switchDirectionNurb(Curve *cu, Nurb *nu)
switch_keys_direction(cu, nu);
}
-static GHash *dupli_keyIndexHash(GHash *keyindex)
+GHash *ED_curve_keyindex_hash_duplicate(GHash *keyindex)
{
GHash *gh;
GHashIterator gh_iter;
- gh = BLI_ghash_ptr_new_ex("dupli_keyIndex gh", BLI_ghash_size(keyindex));
+ gh = BLI_ghash_ptr_new_ex("dupli_keyIndex gh", BLI_ghash_len(keyindex));
GHASH_ITER (gh_iter, keyindex) {
void *cv = BLI_ghashIterator_getKey(&gh_iter);
@@ -592,7 +582,7 @@ static void calc_keyHandles(ListBase *nurb, float *key)
if (nextp) key_to_bezt(nextfp, nextp, &next);
if (prevp) key_to_bezt(prevfp, prevp, &prev);
- BKE_nurb_handle_calc(&cur, prevp ? &prev : NULL, nextp ? &next : NULL, 0);
+ BKE_nurb_handle_calc(&cur, prevp ? &prev : NULL, nextp ? &next : NULL, 0, 0);
bezt_to_key(&cur, fp);
prevp = bezt;
@@ -1239,7 +1229,10 @@ void ED_curve_editnurb_make(Object *obedit)
if (actkey) {
// XXX strcpy(G.editModeTitleExtra, "(Key) ");
+ /* TODO(campbell): undo_system: investigate why this was needed. */
+#if 0
undo_editmode_clear();
+#endif
}
if (editnurb) {
@@ -2926,7 +2919,7 @@ void CURVE_OT_hide(wmOperatorType *ot)
/********************** reveal operator *********************/
-static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int reveal_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
ListBase *editnurb = object_editcurve_get(obedit);
@@ -2934,6 +2927,7 @@ static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
BPoint *bp;
BezTriple *bezt;
int a;
+ const bool select = RNA_boolean_get(op->ptr, "select");
for (nu = editnurb->first; nu; nu = nu->next) {
nu->hide = 0;
@@ -2942,7 +2936,7 @@ static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
a = nu->pntsu;
while (a--) {
if (bezt->hide) {
- select_beztriple(bezt, SELECT, SELECT, HIDDEN);
+ select_beztriple(bezt, select, SELECT, HIDDEN);
bezt->hide = 0;
}
bezt++;
@@ -2953,7 +2947,7 @@ static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
a = nu->pntsu * nu->pntsv;
while (a--) {
if (bp->hide) {
- select_bpoint(bp, SELECT, SELECT, HIDDEN);
+ select_bpoint(bp, select, SELECT, HIDDEN);
bp->hide = 0;
}
bp++;
@@ -2972,7 +2966,7 @@ void CURVE_OT_reveal(wmOperatorType *ot)
/* identifiers */
ot->name = "Reveal Hidden";
ot->idname = "CURVE_OT_reveal";
- ot->description = "Show again hidden control points";
+ ot->description = "Reveal hidden control points";
/* api callbacks */
ot->exec = reveal_exec;
@@ -2980,6 +2974,8 @@ void CURVE_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/********************** subdivide operator *********************/
@@ -3592,7 +3588,7 @@ static int set_spline_type_exec(bContext *C, wmOperator *op)
void CURVE_OT_spline_type_set(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{CU_POLY, "POLY", 0, "Poly", ""},
{CU_BEZIER, "BEZIER", 0, "Bezier", ""},
// {CU_CARDINAL, "CARDINAL", 0, "Cardinal", ""},
@@ -3637,7 +3633,7 @@ static int set_handle_type_exec(bContext *C, wmOperator *op)
void CURVE_OT_handle_type_set(wmOperatorType *ot)
{
/* keep in sync with graphkeys_handle_type_items */
- static EnumPropertyItem editcurve_handle_type_items[] = {
+ static const EnumPropertyItem editcurve_handle_type_items[] = {
{HD_AUTO, "AUTOMATIC", 0, "Automatic", ""},
{HD_VECT, "VECTOR", 0, "Vector", ""},
{5, "ALIGNED", 0, "Aligned", ""},
@@ -4160,7 +4156,7 @@ static int make_segment_exec(bContext *C, wmOperator *op)
*/
bp = nu->bp;
- if (bp[nu->pntsu - 1].f1 & SELECT) {
+ if (bp[nu->pntsu - 1].f1 & SELECT) {
if (nu2 == NULL) {
nu2 = nu;
}
@@ -4305,7 +4301,7 @@ bool ED_curve_editnurb_select_pick(bContext *C, const int mval[2], bool extend,
short hand;
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
location[0] = mval[0];
location[1] = mval[1];
@@ -4791,13 +4787,13 @@ static int ed_editcurve_addvert(Curve *cu, EditNurb *editnurb, const float locat
{
Nurb *nu;
- float minmax[2][3];
+ float center[3];
float temp[3];
- bool nu_has_select = false;
-
+ uint verts_len;
bool changed = false;
- INIT_MINMAX(minmax[0], minmax[1]);
+ zero_v3(center);
+ verts_len = 0;
for (nu = editnurb->nurbs.first; nu; nu = nu->next) {
int i;
@@ -4806,8 +4802,8 @@ static int ed_editcurve_addvert(Curve *cu, EditNurb *editnurb, const float locat
for (i = 0, bezt = nu->bezt; i < nu->pntsu; i++, bezt++) {
if (BEZT_ISSEL_ANY_HIDDENHANDLES(cu, bezt)) {
- minmax_v3v3_v3(UNPACK2(minmax), bezt->vec[1]);
- nu_has_select = true;
+ add_v3_v3(center, bezt->vec[1]);
+ verts_len += 1;
}
}
}
@@ -4816,18 +4812,18 @@ static int ed_editcurve_addvert(Curve *cu, EditNurb *editnurb, const float locat
for (i = 0, bp = nu->bp; i < nu->pntsu; i++, bp++) {
if (bp->f1 & SELECT) {
- minmax_v3v3_v3(UNPACK2(minmax), bp->vec);
- nu_has_select = true;
+ add_v3_v3(center, bp->vec);
+ verts_len += 1;
}
}
}
}
- if (nu_has_select && ed_editcurve_extrude(cu, editnurb)) {
- float ofs[3], center[3];
+ if (verts_len && ed_editcurve_extrude(cu, editnurb)) {
+ float ofs[3];
int i;
- mid_v3_v3v3(center, minmax[0], minmax[1]);
+ mul_v3_fl(center, 1.0f / (float)verts_len);
sub_v3_v3v3(ofs, location_init, center);
if ((cu->flag & CU_3D) == 0) {
@@ -4981,7 +4977,7 @@ static int add_vertex_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
ViewContext vc;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
if (vc.rv3d && !RNA_struct_property_is_set(op->ptr, "location")) {
Curve *cu;
@@ -5254,7 +5250,7 @@ static int toggle_cyclic_invoke(bContext *C, wmOperator *op, const wmEvent *UNUS
void CURVE_OT_cyclic_toggle(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{0, "CYCLIC_U", 0, "Cyclic U", ""},
{1, "CYCLIC_V", 0, "Cyclic V", ""},
{0, NULL, 0, NULL, NULL}
@@ -5748,13 +5744,13 @@ static int curve_delete_exec(bContext *C, wmOperator *op)
return retval;
}
-static EnumPropertyItem curve_delete_type_items[] = {
+static const EnumPropertyItem curve_delete_type_items[] = {
{CURVE_VERTEX, "VERT", 0, "Vertices", ""},
{CURVE_SEGMENT, "SEGMENT", 0, "Segments", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem *rna_curve_delete_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_curve_delete_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
@@ -5850,6 +5846,7 @@ static int curve_dissolve_exec(bContext *C, wmOperator *UNUSED(op))
BLI_assert(points_stride + dims == points + (points_len * dims));
float tan_l[3], tan_r[3], error_sq_dummy;
+ unsigned int error_index_dummy;
sub_v3_v3v3(tan_l, bezt_prev->vec[1], bezt_prev->vec[2]);
normalize_v3(tan_l);
@@ -5860,7 +5857,7 @@ static int curve_dissolve_exec(bContext *C, wmOperator *UNUSED(op))
points, points_len, NULL, dims, FLT_EPSILON,
tan_l, tan_r,
bezt_prev->vec[2], bezt_next->vec[0],
- &error_sq_dummy);
+ &error_sq_dummy, &error_index_dummy);
if (!ELEM(bezt_prev->h2, HD_FREE, HD_ALIGN)) {
bezt_prev->h2 = (bezt_prev->h2 == HD_VECT) ? HD_FREE : HD_ALIGN;
@@ -5904,6 +5901,86 @@ void CURVE_OT_dissolve_verts(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+static bool nurb_bezt_flag_any(const Nurb *nu, const char flag_test)
+{
+ BezTriple *bezt = nu->bezt;
+ int i;
+
+ for (i = nu->pntsu, bezt = nu->bezt; i--; bezt++) {
+ if (bezt->f2 & flag_test) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+static int curve_decimate_exec(bContext *C, wmOperator *op)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ Curve *cu = (Curve *)obedit->data;
+ bool all_supported = true;
+ bool changed = false;
+
+ {
+ const float error_sq_max = FLT_MAX;
+ float ratio = RNA_float_get(op->ptr, "ratio");
+
+ ListBase *editnurb = object_editcurve_get(obedit);
+ Nurb *nu;
+
+ for (nu = editnurb->first; nu; nu = nu->next) {
+ if (nu->type == CU_BEZIER) {
+ if ((nu->pntsu > 2) && nurb_bezt_flag_any(nu, SELECT)) {
+ const int error_target_len = max_ii(2, nu->pntsu * ratio);
+ if (error_target_len != nu->pntsu) {
+ BKE_curve_decimate_nurb(nu, cu->resolu, error_sq_max, error_target_len);
+ changed = true;
+ }
+ }
+ }
+ else {
+ all_supported = false;
+ }
+ }
+ }
+
+ if (all_supported == false) {
+ BKE_report(op->reports, RPT_WARNING, "Only bezier curves are supported");
+ }
+
+ if (changed) {
+ cu->actnu = cu->actvert = CU_ACT_NONE;
+ if (ED_curve_updateAnimPaths(obedit->data)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_KEYS, obedit);
+ }
+
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
+ DAG_id_tag_update(obedit->data, 0);
+ }
+
+ return OPERATOR_FINISHED;
+}
+
+void CURVE_OT_decimate(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Decimate Curve";
+ ot->description = "Simplify selected curves";
+ ot->idname = "CURVE_OT_decimate";
+
+ /* api callbacks */
+ ot->exec = curve_decimate_exec;
+ ot->poll = ED_operator_editcurve;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ RNA_def_float_factor(ot->srna, "ratio", 1.0f, 0.0f, 1.0f, "Ratio", "", 0.0f, 1.0f);
+}
+
+
/********************** shade smooth/flat operator *********************/
static int shade_smooth_exec(bContext *C, wmOperator *op)
@@ -6047,6 +6124,11 @@ int join_curve_exec(bContext *C, wmOperator *op)
cu = ob->data;
BLI_movelisttolist(&cu->nurb, &tempbase);
+ if (ob->type == OB_CURVE) {
+ /* Account for mixed 2D/3D curves when joining */
+ BKE_curve_curve_dimension_update(cu);
+ }
+
DAG_relations_tag_update(bmain); // because we removed object(s), call before editmode!
DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
@@ -6109,119 +6191,6 @@ void CURVE_OT_tilt_clear(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/****************** undo for curves ****************/
-
-static void undoCurve_to_editCurve(void *ucu, void *UNUSED(edata), void *cu_v)
-{
- Curve *cu = cu_v;
- UndoCurve *undoCurve = ucu;
- ListBase *undobase = &undoCurve->nubase;
- ListBase *editbase = BKE_curve_editNurbs_get(cu);
- Nurb *nu, *newnu;
- EditNurb *editnurb = cu->editnurb;
- AnimData *ad = BKE_animdata_from_id(&cu->id);
-
- BKE_nurbList_free(editbase);
-
- if (undoCurve->undoIndex) {
- BKE_curve_editNurb_keyIndex_free(&editnurb->keyindex);
- editnurb->keyindex = dupli_keyIndexHash(undoCurve->undoIndex);
- }
-
- if (ad) {
- if (ad->action) {
- free_fcurves(&ad->action->curves);
- copy_fcurves(&ad->action->curves, &undoCurve->fcurves);
- }
-
- free_fcurves(&ad->drivers);
- copy_fcurves(&ad->drivers, &undoCurve->drivers);
- }
-
- /* copy */
- for (nu = undobase->first; nu; nu = nu->next) {
- newnu = BKE_nurb_duplicate(nu);
-
- if (editnurb->keyindex) {
- keyIndex_updateNurb(editnurb, nu, newnu);
- }
-
- BLI_addtail(editbase, newnu);
- }
-
- cu->actvert = undoCurve->actvert;
- cu->actnu = undoCurve->actnu;
- cu->flag = undoCurve->flag;
- ED_curve_updateAnimPaths(cu);
-}
-
-static void *editCurve_to_undoCurve(void *UNUSED(edata), void *cu_v)
-{
- Curve *cu = cu_v;
- ListBase *nubase = BKE_curve_editNurbs_get(cu);
- UndoCurve *undoCurve;
- EditNurb *editnurb = cu->editnurb, tmpEditnurb;
- Nurb *nu, *newnu;
- AnimData *ad = BKE_animdata_from_id(&cu->id);
-
- undoCurve = MEM_callocN(sizeof(UndoCurve), "undoCurve");
-
- if (editnurb->keyindex) {
- undoCurve->undoIndex = dupli_keyIndexHash(editnurb->keyindex);
- tmpEditnurb.keyindex = undoCurve->undoIndex;
- }
-
- if (ad) {
- if (ad->action)
- copy_fcurves(&undoCurve->fcurves, &ad->action->curves);
-
- copy_fcurves(&undoCurve->drivers, &ad->drivers);
- }
-
- /* copy */
- for (nu = nubase->first; nu; nu = nu->next) {
- newnu = BKE_nurb_duplicate(nu);
-
- if (undoCurve->undoIndex) {
- keyIndex_updateNurb(&tmpEditnurb, nu, newnu);
- }
-
- BLI_addtail(&undoCurve->nubase, newnu);
- }
-
- undoCurve->actvert = cu->actvert;
- undoCurve->actnu = cu->actnu;
- undoCurve->flag = cu->flag;
-
- return undoCurve;
-}
-
-static void free_undoCurve(void *ucv)
-{
- UndoCurve *undoCurve = ucv;
-
- BKE_nurbList_free(&undoCurve->nubase);
-
- BKE_curve_editNurb_keyIndex_free(&undoCurve->undoIndex);
-
- free_fcurves(&undoCurve->fcurves);
- free_fcurves(&undoCurve->drivers);
-
- MEM_freeN(undoCurve);
-}
-
-static void *get_data(bContext *C)
-{
- Object *obedit = CTX_data_edit_object(C);
- return obedit;
-}
-
-/* and this is all the undo system needs to know */
-void undo_push_curve(bContext *C, const char *name)
-{
- undo_editmode_push(C, name, get_data, free_undoCurve, undoCurve_to_editCurve, editCurve_to_undoCurve, NULL);
-}
-
void ED_curve_beztcpy(EditNurb *editnurb, BezTriple *dst, BezTriple *src, int count)
{
memcpy(dst, src, count * sizeof(BezTriple));
diff --git a/source/blender/editors/curve/editcurve_add.c b/source/blender/editors/curve/editcurve_add.c
index cc8e272d4f7..b23f0f967ec 100644
--- a/source/blender/editors/curve/editcurve_add.c
+++ b/source/blender/editors/curve/editcurve_add.c
@@ -52,7 +52,7 @@
#include "ED_object.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_view3d.h"
#include "ED_curve.h"
diff --git a/source/blender/editors/curve/editcurve_paint.c b/source/blender/editors/curve/editcurve_paint.c
index 34e026a3ef4..0d7cb089c4f 100644
--- a/source/blender/editors/curve/editcurve_paint.c
+++ b/source/blender/editors/curve/editcurve_paint.c
@@ -70,102 +70,6 @@
/* Distance between start/end points to consider cyclic */
#define STROKE_CYCLIC_DIST_PX 8
-
-/* -------------------------------------------------------------------- */
-
-/** \name Depth Utilities
- * \{ */
-
-
-static float depth_read_zbuf(const ViewContext *vc, int x, int y)
-{
- ViewDepths *vd = vc->rv3d->depths;
-
- if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
- return vd->depths[y * vd->w + x];
- else
- return -1.0f;
-}
-
-static bool depth_unproject(
- const ARegion *ar, const bglMats *mats,
- const int mval[2], const double depth,
- float r_location_world[3])
-{
- double p[3];
- if (gluUnProject(
- (double)ar->winrct.xmin + mval[0] + 0.5,
- (double)ar->winrct.ymin + mval[1] + 0.5,
- depth, mats->modelview, mats->projection, (const GLint *)mats->viewport,
- &p[0], &p[1], &p[2]))
- {
- copy_v3fl_v3db(r_location_world, p);
- return true;
- }
- return false;
-}
-
-static bool depth_read_normal(
- const ViewContext *vc, const bglMats *mats, const int mval[2],
- float r_normal[3])
-{
- /* pixels surrounding */
- bool depths_valid[9] = {false};
- float coords[9][3] = {{0}};
-
- ARegion *ar = vc->ar;
- const ViewDepths *depths = vc->rv3d->depths;
-
- for (int x = 0, i = 0; x < 2; x++) {
- for (int y = 0; y < 2; y++) {
- const int mval_ofs[2] = {mval[0] + (x - 1), mval[1] + (y - 1)};
-
- const double depth = (double)depth_read_zbuf(vc, mval_ofs[0], mval_ofs[1]);
- if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
- if (depth_unproject(ar, mats, mval_ofs, depth, coords[i])) {
- depths_valid[i] = true;
- }
- }
- i++;
- }
- }
-
- const int edges[2][6][2] = {
- /* x edges */
- {{0, 1}, {1, 2},
- {3, 4}, {4, 5},
- {6, 7}, {7, 8}},
- /* y edges */
- {{0, 3}, {3, 6},
- {1, 4}, {4, 7},
- {2, 5}, {5, 8}},
- };
-
- float cross[2][3] = {{0.0f}};
-
- for (int i = 0; i < 6; i++) {
- for (int axis = 0; axis < 2; axis++) {
- if (depths_valid[edges[axis][i][0]] && depths_valid[edges[axis][i][1]]) {
- float delta[3];
- sub_v3_v3v3(delta, coords[edges[axis][i][0]], coords[edges[axis][i][1]]);
- add_v3_v3(cross[axis], delta);
- }
- }
- }
-
- cross_v3_v3v3(r_normal, cross[0], cross[1]);
-
- if (normalize_v3(r_normal) != 0.0f) {
- return true;
- }
- else {
- return false;
- }
-}
-
-/** \} */
-
-
/* -------------------------------------------------------------------- */
/** \name StrokeElem / #RNA_OperatorStrokeElement Conversion Functions
@@ -308,9 +212,9 @@ static bool stroke_elem_project(
((unsigned int)mval_i[0] < depths->w) &&
((unsigned int)mval_i[1] < depths->h))
{
- const double depth = (double)depth_read_zbuf(&cdd->vc, mval_i[0], mval_i[1]);
+ const double depth = (double)ED_view3d_depth_read_cached(&cdd->vc, mval_i);
if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
- if (depth_unproject(ar, &cdd->mats, mval_i, depth, r_location_world)) {
+ if (ED_view3d_depth_unproject(ar, &cdd->mats, mval_i, depth, r_location_world)) {
is_location_world_set = true;
if (r_normal_world) {
zero_v3(r_normal_world);
@@ -319,7 +223,7 @@ static bool stroke_elem_project(
if (surface_offset != 0.0f) {
const float offset = cdd->project.use_surface_offset_absolute ? 1.0f : radius;
float normal[3];
- if (depth_read_normal(&cdd->vc, &cdd->mats, mval_i, normal)) {
+ if (ED_view3d_depth_read_cached_normal(&cdd->vc, &cdd->mats, mval_i, normal)) {
madd_v3_v3fl(r_location_world, normal, offset * surface_offset);
if (r_normal_world) {
copy_v3_v3(r_normal_world, normal);
@@ -455,7 +359,7 @@ static void curve_draw_stroke_3d(const struct bContext *UNUSED(C), ARegion *UNUS
wmOperator *op = arg;
struct CurveDrawData *cdd = op->customdata;
- const int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
+ const int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
if (stroke_len == 0) {
return;
@@ -627,7 +531,7 @@ static void curve_draw_event_add_first(wmOperator *op, const wmEvent *event)
CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW,
CURVE_PAINT_SURFACE_PLANE_NORMAL_SURFACE))
{
- if (depth_read_normal(&cdd->vc, &cdd->mats, event->mval, normal)) {
+ if (ED_view3d_depth_read_cached_normal(&cdd->vc, &cdd->mats, event->mval, normal)) {
if (cps->surface_plane == CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW) {
float cross_a[3], cross_b[3];
cross_v3_v3v3(cross_a, rv3d->viewinv[2], normal);
@@ -677,7 +581,7 @@ static bool curve_draw_init(bContext *C, wmOperator *op, bool is_invoke)
struct CurveDrawData *cdd = MEM_callocN(sizeof(*cdd), __func__);
if (is_invoke) {
- view3d_set_viewcontext(C, &cdd->vc);
+ ED_view3d_viewcontext_init(C, &cdd->vc);
if (ELEM(NULL, cdd->vc.ar, cdd->vc.rv3d, cdd->vc.v3d, cdd->vc.win, cdd->vc.scene)) {
MEM_freeN(cdd);
BKE_report(op->reports, RPT_ERROR, "Unable to access 3D viewport");
@@ -773,7 +677,7 @@ static void curve_draw_exec_precalc(wmOperator *op)
if (!RNA_property_is_set(op->ptr, prop)) {
bool use_cyclic = false;
- if (BLI_mempool_count(cdd->stroke_elem_pool) > 2) {
+ if (BLI_mempool_len(cdd->stroke_elem_pool) > 2) {
BLI_mempool_iter iter;
const struct StrokeElem *selem, *selem_first, *selem_last;
@@ -799,7 +703,7 @@ static void curve_draw_exec_precalc(wmOperator *op)
(cps->radius_taper_end != 0.0f))
{
/* note, we could try to de-duplicate the length calculations above */
- const int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
+ const int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
BLI_mempool_iter iter;
struct StrokeElem *selem, *selem_prev;
@@ -859,14 +763,14 @@ static int curve_draw_exec(bContext *C, wmOperator *op)
Curve *cu = obedit->data;
ListBase *nurblist = object_editcurve_get(obedit);
- int stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
+ int stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
const bool is_3d = (cu->flag & CU_3D) != 0;
invert_m4_m4(obedit->imat, obedit->obmat);
- if (BLI_mempool_count(cdd->stroke_elem_pool) == 0) {
+ if (BLI_mempool_len(cdd->stroke_elem_pool) == 0) {
curve_draw_stroke_from_operator(op);
- stroke_len = BLI_mempool_count(cdd->stroke_elem_pool);
+ stroke_len = BLI_mempool_len(cdd->stroke_elem_pool);
}
ED_curve_deselect_all(cu->editnurb);
@@ -876,7 +780,7 @@ static int curve_draw_exec(bContext *C, wmOperator *op)
const float radius_range = cps->radius_max - cps->radius_min;
Nurb *nu = MEM_callocN(sizeof(Nurb), __func__);
- nu->pntsv = 1;
+ nu->pntsv = 0;
nu->resolu = cu->resolu;
nu->resolv = cu->resolv;
nu->flag |= CU_SMOOTH;
diff --git a/source/blender/editors/curve/editcurve_select.c b/source/blender/editors/curve/editcurve_select.c
index cad70443657..673faa37f2a 100644
--- a/source/blender/editors/curve/editcurve_select.c
+++ b/source/blender/editors/curve/editcurve_select.c
@@ -559,7 +559,7 @@ static int select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent
const bool select = !RNA_boolean_get(op->ptr, "deselect");
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
if (!ED_curve_pick_vert(&vc, 1, event->mval, &nu, &bezt, &bp, NULL)) {
return OPERATOR_CANCELLED;
@@ -1192,7 +1192,7 @@ enum {
SIM_CMP_LT,
};
-static EnumPropertyItem curve_prop_similar_compare_types[] = {
+static const EnumPropertyItem curve_prop_similar_compare_types[] = {
{SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
{SIM_CMP_GT, "GREATER", 0, "Greater", ""},
{SIM_CMP_LT, "LESS", 0, "Less", ""},
@@ -1207,7 +1207,7 @@ enum {
SIMCURHAND_DIRECTION,
};
-static EnumPropertyItem curve_prop_similar_types[] = {
+static const EnumPropertyItem curve_prop_similar_types[] = {
{SIMCURHAND_TYPE, "TYPE", 0, "Type", ""},
{SIMCURHAND_RADIUS, "RADIUS", 0, "Radius", ""},
{SIMCURHAND_WEIGHT, "WEIGHT", 0, "Weight", ""},
@@ -1607,7 +1607,7 @@ static void curve_select_shortest_path_surf(Nurb *nu, int vert_src, int vert_dst
int axis, sign;
int u, v;
- vert_curr = *((int *)BLI_heap_popmin(heap));
+ vert_curr = *((int *)BLI_heap_pop_min(heap));
if (vert_curr == vert_dst) {
break;
}
@@ -1677,7 +1677,7 @@ static int edcu_shortest_path_pick_invoke(bContext *C, wmOperator *op, const wmE
}
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
if (!ED_curve_pick_vert(&vc, 1, event->mval, &nu_dst, &bezt_dst, &bp_dst, NULL)) {
return OPERATOR_PASS_THROUGH;
diff --git a/source/blender/editors/curve/editcurve_undo.c b/source/blender/editors/curve/editcurve_undo.c
new file mode 100644
index 00000000000..4ced6ce506c
--- /dev/null
+++ b/source/blender/editors/curve/editcurve_undo.c
@@ -0,0 +1,256 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/curve/editcurve_undo.c
+ * \ingroup edcurve
+ */
+
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_anim_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
+#include "BLI_array_utils.h"
+
+#include "BKE_context.h"
+#include "BKE_curve.h"
+#include "BKE_fcurve.h"
+#include "BKE_library.h"
+#include "BKE_animsys.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+
+#include "ED_object.h"
+#include "ED_util.h"
+#include "ED_curve.h"
+
+#include "WM_types.h"
+#include "WM_api.h"
+
+#include "curve_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct {
+ ListBase nubase;
+ int actvert;
+ GHash *undoIndex;
+ ListBase fcurves, drivers;
+ int actnu;
+ int flag;
+
+ /* Stored in the object, needed since users may change the active key while in edit-mode. */
+ struct {
+ short shapenr;
+ } obedit;
+
+ size_t undo_size;
+} UndoCurve;
+
+static void undocurve_to_editcurve(UndoCurve *ucu, Curve *cu, short *r_shapenr)
+{
+ ListBase *undobase = &ucu->nubase;
+ ListBase *editbase = BKE_curve_editNurbs_get(cu);
+ Nurb *nu, *newnu;
+ EditNurb *editnurb = cu->editnurb;
+ AnimData *ad = BKE_animdata_from_id(&cu->id);
+
+ BKE_nurbList_free(editbase);
+
+ if (ucu->undoIndex) {
+ BKE_curve_editNurb_keyIndex_free(&editnurb->keyindex);
+ editnurb->keyindex = ED_curve_keyindex_hash_duplicate(ucu->undoIndex);
+ }
+
+ if (ad) {
+ if (ad->action) {
+ free_fcurves(&ad->action->curves);
+ copy_fcurves(&ad->action->curves, &ucu->fcurves);
+ }
+
+ free_fcurves(&ad->drivers);
+ copy_fcurves(&ad->drivers, &ucu->drivers);
+ }
+
+ /* copy */
+ for (nu = undobase->first; nu; nu = nu->next) {
+ newnu = BKE_nurb_duplicate(nu);
+
+ if (editnurb->keyindex) {
+ ED_curve_keyindex_update_nurb(editnurb, nu, newnu);
+ }
+
+ BLI_addtail(editbase, newnu);
+ }
+
+ cu->actvert = ucu->actvert;
+ cu->actnu = ucu->actnu;
+ cu->flag = ucu->flag;
+ *r_shapenr = ucu->obedit.shapenr;
+ ED_curve_updateAnimPaths(cu);
+}
+
+static void undocurve_from_editcurve(UndoCurve *ucu, Curve *cu, const short shapenr)
+{
+ BLI_assert(BLI_array_is_zeroed(ucu, 1));
+ ListBase *nubase = BKE_curve_editNurbs_get(cu);
+ EditNurb *editnurb = cu->editnurb, tmpEditnurb;
+ Nurb *nu, *newnu;
+ AnimData *ad = BKE_animdata_from_id(&cu->id);
+
+ /* TODO: include size of fcurve & undoIndex */
+ // ucu->undo_size = 0;
+
+ if (editnurb->keyindex) {
+ ucu->undoIndex = ED_curve_keyindex_hash_duplicate(editnurb->keyindex);
+ tmpEditnurb.keyindex = ucu->undoIndex;
+ }
+
+ if (ad) {
+ if (ad->action)
+ copy_fcurves(&ucu->fcurves, &ad->action->curves);
+
+ copy_fcurves(&ucu->drivers, &ad->drivers);
+ }
+
+ /* copy */
+ for (nu = nubase->first; nu; nu = nu->next) {
+ newnu = BKE_nurb_duplicate(nu);
+
+ if (ucu->undoIndex) {
+ ED_curve_keyindex_update_nurb(&tmpEditnurb, nu, newnu);
+ }
+
+ BLI_addtail(&ucu->nubase, newnu);
+
+ ucu->undo_size += (
+ (nu->bezt ? (sizeof(BezTriple) * nu->pntsu) : 0) +
+ (nu->bp ? (sizeof(BPoint) * (nu->pntsu * nu->pntsv)) : 0) +
+ (nu->knotsu ? (sizeof(float) * KNOTSU(nu)) : 0) +
+ (nu->knotsv ? (sizeof(float) * KNOTSV(nu)) : 0) +
+ sizeof(Nurb));
+ }
+
+ ucu->actvert = cu->actvert;
+ ucu->actnu = cu->actnu;
+ ucu->flag = cu->flag;
+
+ ucu->obedit.shapenr = shapenr;
+}
+
+static void undocurve_free_data(UndoCurve *uc)
+{
+ BKE_nurbList_free(&uc->nubase);
+
+ BKE_curve_editNurb_keyIndex_free(&uc->undoIndex);
+
+ free_fcurves(&uc->fcurves);
+ free_fcurves(&uc->drivers);
+}
+
+static Object *editcurve_object_from_context(bContext *C)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ if (obedit && ELEM(obedit->type, OB_CURVE, OB_SURF)) {
+ Curve *cu = obedit->data;
+ if (BKE_curve_editNurbs_get(cu) != NULL) {
+ return obedit;
+ }
+ }
+ return NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct CurveUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ UndoCurve data;
+} CurveUndoStep;
+
+static bool curve_undosys_poll(bContext *C)
+{
+ Object *obedit = editcurve_object_from_context(C);
+ return (obedit != NULL);
+}
+
+static bool curve_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ CurveUndoStep *us = (CurveUndoStep *)us_p;
+ us->obedit_ref.ptr = editcurve_object_from_context(C);
+ undocurve_from_editcurve(&us->data, us->obedit_ref.ptr->data, us->obedit_ref.ptr->shapenr);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void curve_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_EDIT);
+ BLI_assert(curve_undosys_poll(C));
+
+ CurveUndoStep *us = (CurveUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ undocurve_to_editcurve(&us->data, obedit->data, &obedit->shapenr);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
+}
+
+static void curve_undosys_step_free(UndoStep *us_p)
+{
+ CurveUndoStep *us = (CurveUndoStep *)us_p;
+ undocurve_free_data(&us->data);
+}
+
+static void curve_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ CurveUndoStep *us = (CurveUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
+}
+
+/* Export for ED_undo_sys. */
+void ED_curve_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Curve";
+ ut->poll = curve_undosys_poll;
+ ut->step_encode = curve_undosys_step_encode;
+ ut->step_decode = curve_undosys_step_decode;
+ ut->step_free = curve_undosys_step_free;
+
+ ut->step_foreach_ID_ref = curve_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(CurveUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/curve/editfont.c b/source/blender/editors/curve/editfont.c
index 57e731874b4..d651f673a7f 100644
--- a/source/blender/editors/curve/editfont.c
+++ b/source/blender/editors/curve/editfont.c
@@ -557,7 +557,7 @@ static int kill_selection(Object *obedit, int ins) /* 1 == new character */
/******************* set style operator ********************/
-static EnumPropertyItem style_items[] = {
+static const EnumPropertyItem style_items[] = {
{CU_CHINFO_BOLD, "BOLD", 0, "Bold", ""},
{CU_CHINFO_ITALIC, "ITALIC", 0, "Italic", ""},
{CU_CHINFO_UNDERLINE, "UNDERLINE", 0, "Underline", ""},
@@ -877,7 +877,7 @@ void FONT_OT_text_paste(wmOperatorType *ot)
/************************ move operator ************************/
-static EnumPropertyItem move_type_items[] = {
+static const EnumPropertyItem move_type_items[] = {
{LINE_BEGIN, "LINE_BEGIN", 0, "Line Begin", ""},
{LINE_END, "LINE_END", 0, "Line End", ""},
{PREV_CHAR, "PREVIOUS_CHARACTER", 0, "Previous Character", ""},
@@ -1169,10 +1169,11 @@ void FONT_OT_line_break(wmOperatorType *ot)
/******************* delete operator **********************/
-static EnumPropertyItem delete_type_items[] = {
- {DEL_ALL, "ALL", 0, "All", ""},
+static const EnumPropertyItem delete_type_items[] = {
{DEL_NEXT_CHAR, "NEXT_CHARACTER", 0, "Next Character", ""},
{DEL_PREV_CHAR, "PREVIOUS_CHARACTER", 0, "Previous Character", ""},
+ {DEL_NEXT_WORD, "NEXT_WORD", 0, "Next Word", ""},
+ {DEL_PREV_WORD, "PREVIOUS_WORD", 0, "Previous Word", ""},
{DEL_SELECTION, "SELECTION", 0, "Selection", ""},
{DEL_NEXT_SEL, "NEXT_OR_SELECTION", 0, "Next or Selection", ""},
{DEL_PREV_SEL, "PREVIOUS_OR_SELECTION", 0, "Previous or Selection", ""},
@@ -1183,7 +1184,9 @@ static int delete_exec(bContext *C, wmOperator *op)
Object *obedit = CTX_data_edit_object(C);
Curve *cu = obedit->data;
EditFont *ef = cu->editfont;
- int x, selstart, selend, type = RNA_enum_get(op->ptr, "type");
+ int selstart, selend, type = RNA_enum_get(op->ptr, "type");
+ int range[2] = {0, 0};
+ bool has_select = false;
if (ef->len == 0)
return OPERATOR_CANCELLED;
@@ -1191,6 +1194,7 @@ static int delete_exec(bContext *C, wmOperator *op)
if (BKE_vfont_select_get(obedit, &selstart, &selend)) {
if (type == DEL_NEXT_SEL) type = DEL_SELECTION;
else if (type == DEL_PREV_SEL) type = DEL_SELECTION;
+ has_select = true;
}
else {
if (type == DEL_NEXT_SEL) type = DEL_NEXT_CHAR;
@@ -1198,10 +1202,6 @@ static int delete_exec(bContext *C, wmOperator *op)
}
switch (type) {
- case DEL_ALL:
- ef->len = ef->pos = 0;
- ef->textbuf[0] = 0;
- break;
case DEL_SELECTION:
if (!kill_selection(obedit, 0))
return OPERATOR_CANCELLED;
@@ -1210,29 +1210,69 @@ static int delete_exec(bContext *C, wmOperator *op)
if (ef->pos <= 0)
return OPERATOR_CANCELLED;
- for (x = ef->pos; x <= ef->len; x++)
- ef->textbuf[x - 1] = ef->textbuf[x];
- for (x = ef->pos; x <= ef->len; x++)
- ef->textbufinfo[x - 1] = ef->textbufinfo[x];
+ range[0] = ef->pos - 1;
+ range[1] = ef->pos;
ef->pos--;
- ef->textbuf[--ef->len] = '\0';
break;
case DEL_NEXT_CHAR:
if (ef->pos >= ef->len)
return OPERATOR_CANCELLED;
- for (x = ef->pos; x < ef->len; x++)
- ef->textbuf[x] = ef->textbuf[x + 1];
- for (x = ef->pos; x < ef->len; x++)
- ef->textbufinfo[x] = ef->textbufinfo[x + 1];
+ range[0] = ef->pos;
+ range[1] = ef->pos + 1;
+ break;
+ case DEL_NEXT_WORD:
+ {
+ int pos = ef->pos;
+ BLI_str_cursor_step_wchar(ef->textbuf, ef->len, &pos, STRCUR_DIR_NEXT, STRCUR_JUMP_DELIM, true);
+ range[0] = ef->pos;
+ range[1] = pos;
+ break;
+ }
- ef->textbuf[--ef->len] = '\0';
+ case DEL_PREV_WORD:
+ {
+ int pos = ef->pos;
+ BLI_str_cursor_step_wchar(ef->textbuf, ef->len, &pos, STRCUR_DIR_PREV, STRCUR_JUMP_DELIM, true);
+ range[0] = pos;
+ range[1] = ef->pos;
+ ef->pos = pos;
break;
+ }
default:
return OPERATOR_CANCELLED;
}
+ if (range[0] != range[1]) {
+ BLI_assert(range[0] < range[1]);
+ int len_remove = range[1] - range[0];
+ int len_tail = ef->len - range[1];
+ if (has_select) {
+ for (int i = 0; i < 2; i++) {
+ int *sel = i ? &ef->selend : &ef->selstart;
+ if (*sel <= range[0]) {
+ /* pass */
+ }
+ else if (*sel >= range[1]) {
+ *sel -= len_remove;
+ }
+ else if (*sel < range[1]) {
+ /* pass */
+ *sel = range[0];
+ }
+ }
+ }
+
+ memmove(&ef->textbuf[range[0]], &ef->textbuf[range[1]], sizeof(*ef->textbuf) * len_tail);
+ memmove(&ef->textbufinfo[range[0]], &ef->textbufinfo[range[1]], sizeof(*ef->textbufinfo) * len_tail);
+
+ ef->len -= len_remove;
+ ef->textbuf[ef->len] = '\0';
+
+ BKE_vfont_select_clamp(obedit);
+ }
+
text_update_edited(C, obedit, FO_EDIT);
return OPERATOR_FINISHED;
@@ -1253,7 +1293,7 @@ void FONT_OT_delete(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_enum(ot->srna, "type", delete_type_items, DEL_ALL, "Type", "Which part of the text to delete");
+ RNA_def_enum(ot->srna, "type", delete_type_items, DEL_PREV_CHAR, "Type", "Which part of the text to delete");
}
/*********************** insert text operator *************************/
@@ -1550,7 +1590,7 @@ void ED_curve_editfont_free(Object *obedit)
/********************** set case operator *********************/
-static EnumPropertyItem case_items[] = {
+static const EnumPropertyItem case_items[] = {
{CASE_LOWER, "LOWER", 0, "Lower", ""},
{CASE_UPPER, "UPPER", 0, "Upper", ""},
{0, NULL, 0, NULL, NULL}};
@@ -1810,7 +1850,7 @@ bool ED_curve_editfont_select_pick(bContext *C, const int mval[2], bool extend,
const float dist = ED_view3d_select_dist_px();
float dist_sq_best = dist * dist;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
diff --git a/source/blender/editors/curve/editfont_undo.c b/source/blender/editors/curve/editfont_undo.c
index a61f863b61e..3a76d0333f9 100644
--- a/source/blender/editors/curve/editfont_undo.c
+++ b/source/blender/editors/curve/editfont_undo.c
@@ -29,6 +29,8 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
+#include "BLI_array_utils.h"
+
#include "DNA_curve_types.h"
#include "DNA_object_types.h"
@@ -36,10 +38,16 @@
#include "BKE_context.h"
#include "BKE_font.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+#include "ED_object.h"
#include "ED_curve.h"
#include "ED_util.h"
+#include "WM_types.h"
+#include "WM_api.h"
+
#define USE_ARRAY_STORE
#ifdef USE_ARRAY_STORE
@@ -50,6 +58,10 @@
# define ARRAY_CHUNK_SIZE 32
#endif
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
typedef struct UndoFont {
wchar_t *textbuf;
struct CharInfo *textbufinfo;
@@ -62,6 +74,8 @@ typedef struct UndoFont {
BArrayState *textbufinfo;
} store;
#endif
+
+ size_t undo_size;
} UndoFont;
@@ -202,23 +216,20 @@ static void uf_arraystore_free(UndoFont *uf)
BLI_array_store_at_size_clear(&uf_arraystore.bs_stride);
}
-
}
/** \} */
#endif /* USE_ARRAY_STORE */
-static void undoFont_to_editFont(void *uf_v, void *ecu, void *UNUSED(obdata))
+static void undofont_to_editfont(UndoFont *uf, Curve *cu)
{
- Curve *cu = (Curve *)ecu;
EditFont *ef = cu->editfont;
- const UndoFont *uf = uf_v;
size_t final_size;
#ifdef USE_ARRAY_STORE
- uf_arraystore_expand(uf_v);
+ uf_arraystore_expand(uf);
#endif
final_size = sizeof(wchar_t) * (uf->len + 1);
@@ -233,16 +244,17 @@ static void undoFont_to_editFont(void *uf_v, void *ecu, void *UNUSED(obdata))
ef->selstart = ef->selend = 0;
#ifdef USE_ARRAY_STORE
- uf_arraystore_expand_clear(uf_v);
+ uf_arraystore_expand_clear(uf);
#endif
}
-static void *editFont_to_undoFont(void *ecu, void *UNUSED(obdata))
+static void *undofont_from_editfont(UndoFont *uf, Curve *cu)
{
- Curve *cu = (Curve *)ecu;
+ BLI_assert(BLI_array_is_zeroed(uf, 1));
+
EditFont *ef = cu->editfont;
- UndoFont *uf = MEM_callocN(sizeof(*uf), __func__);
+ size_t mem_used_prev = MEM_get_memory_in_use();
size_t final_size;
@@ -269,13 +281,15 @@ static void *editFont_to_undoFont(void *ecu, void *UNUSED(obdata))
}
#endif
+ size_t mem_used_curr = MEM_get_memory_in_use();
+
+ uf->undo_size = mem_used_prev < mem_used_curr ? mem_used_curr - mem_used_prev : sizeof(UndoFont);
+
return uf;
}
-static void free_undoFont(void *uf_v)
+static void undofont_free_data(UndoFont *uf)
{
- UndoFont *uf = uf_v;
-
#ifdef USE_ARRAY_STORE
{
LinkData *link = BLI_findptr(&uf_arraystore.local_links, uf, offsetof(LinkData, data));
@@ -291,21 +305,91 @@ static void free_undoFont(void *uf_v)
if (uf->textbufinfo) {
MEM_freeN(uf->textbufinfo);
}
-
- MEM_freeN(uf);
}
-static void *get_undoFont(bContext *C)
+static Object *editfont_object_from_context(bContext *C)
{
Object *obedit = CTX_data_edit_object(C);
if (obedit && obedit->type == OB_FONT) {
- return obedit->data;
+ Curve *cu = obedit->data;
+ EditFont *ef = cu->editfont;
+ if (ef != NULL) {
+ return obedit;
+ }
}
return NULL;
}
-/* and this is all the undo system needs to know */
-void undo_push_font(bContext *C, const char *name)
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct FontUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ UndoFont data;
+} FontUndoStep;
+
+static bool font_undosys_poll(bContext *C)
+{
+ return editfont_object_from_context(C) != NULL;
+}
+
+static bool font_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ FontUndoStep *us = (FontUndoStep *)us_p;
+ us->obedit_ref.ptr = editfont_object_from_context(C);
+ Curve *cu = us->obedit_ref.ptr->data;
+ undofont_from_editfont(&us->data, cu);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void font_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_EDIT);
+ BLI_assert(font_undosys_poll(C));
+
+ FontUndoStep *us = (FontUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ Curve *cu = obedit->data;
+ undofont_to_editfont(&us->data, cu);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
+}
+
+static void font_undosys_step_free(UndoStep *us_p)
+{
+ FontUndoStep *us = (FontUndoStep *)us_p;
+ undofont_free_data(&us->data);
+}
+
+static void font_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
{
- undo_editmode_push(C, name, get_undoFont, free_undoFont, undoFont_to_editFont, editFont_to_undoFont, NULL);
+ FontUndoStep *us = (FontUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
}
+
+/* Export for ED_undo_sys. */
+void ED_font_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Font";
+ ut->poll = font_undosys_poll;
+ ut->step_encode = font_undosys_step_encode;
+ ut->step_decode = font_undosys_step_decode;
+ ut->step_free = font_undosys_step_free;
+
+ ut->step_foreach_ID_ref = font_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(FontUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/datafiles/CMakeLists.txt b/source/blender/editors/datafiles/CMakeLists.txt
index 2a84ca7f297..3f6de14180a 100644
--- a/source/blender/editors/datafiles/CMakeLists.txt
+++ b/source/blender/editors/datafiles/CMakeLists.txt
@@ -31,6 +31,495 @@ set(SRC
)
+# Order matches "UI_icons.h", final name will be formatted: "icons{size}_{name}.dat"
+set(ICON_NAMES
+ question
+ error
+ cancel
+ tria_right
+ tria_down
+ tria_left
+ tria_up
+ arrow_leftright
+ plus
+ disclosure_tri_down
+ disclosure_tri_right
+ radiobut_off
+ radiobut_on
+ menu_panel
+ blender
+ grip
+ dot
+ collapsemenu
+ x
+ go_left
+ plug
+ ui
+ node
+ node_sel
+ fullscreen
+ splitscreen
+ rightarrow_thin
+ bordermove
+ viewzoom
+ zoomin
+ zoomout
+ panel_close
+ copy_id
+ eyedropper
+ link_area
+ auto
+ checkbox_dehlt
+ checkbox_hlt
+ unlocked
+ locked
+ unpinned
+ pinned
+ screen_back
+ rightarrow
+ downarrow_hlt
+ dotsup
+ dotsdown
+ link
+ inlink
+ plugin
+ help
+ ghost_enabled
+ color
+ linked
+ unlinked
+ hand
+ zoom_all
+ zoom_selected
+ zoom_previous
+ zoom_in
+ zoom_out
+ render_region
+ border_rect
+ border_lasso
+ freeze
+ stylus_pressure
+ ghost_disabled
+ new
+ file_tick
+ quit
+ url
+ recover_last
+ fullscreen_enter
+ fullscreen_exit
+ lamp
+ material
+ texture
+ anim
+ world
+ scene
+ edit
+ game
+ radio
+ script
+ particles
+ physics
+ speaker
+ texture_shaded
+ view3d
+ ipo
+ oops
+ buts
+ filesel
+ image_col
+ info
+ sequence
+ text
+ imasel
+ sound
+ action
+ nla
+ scriptwin
+ time
+ nodetree
+ logic
+ console
+ preferences
+ clip
+ asset_manager
+ object_datamode
+ editmode_hlt
+ facesel_hlt
+ vpaint_hlt
+ tpaint_hlt
+ wpaint_hlt
+ sculptmode_hlt
+ pose_hlt
+ particlemode
+ lightpaint
+ scene_data
+ renderlayers
+ world_data
+ object_data
+ mesh_data
+ curve_data
+ meta_data
+ lattice_data
+ lamp_data
+ material_data
+ texture_data
+ anim_data
+ camera_data
+ particle_data
+ library_data_direct
+ group
+ armature_data
+ pose_data
+ bone_data
+ constraint
+ shapekey_data
+ constraint_bone
+ camera_stereo
+ package
+ uglypackage
+ brush_data
+ image_data
+ file
+ fcurve
+ font_data
+ render_result
+ surface_data
+ empty_data
+ settings
+ render_animation
+ render_still
+ library_data_broken
+ boids
+ strands
+ library_data_indirect
+ greasepencil
+ line_data
+ group_bone
+ group_vertex
+ group_vcol
+ group_uvs
+ rna
+ rna_add
+ outliner_ob_empty
+ outliner_ob_mesh
+ outliner_ob_curve
+ outliner_ob_lattice
+ outliner_ob_meta
+ outliner_ob_lamp
+ outliner_ob_camera
+ outliner_ob_armature
+ outliner_ob_font
+ outliner_ob_surface
+ outliner_ob_speaker
+ outliner_ob_force_field
+ outliner_ob_group_instance
+ restrict_color_off
+ restrict_color_on
+ restrict_view_off
+ restrict_view_on
+ restrict_select_off
+ restrict_select_on
+ restrict_render_off
+ restrict_render_on
+ outliner_data_empty
+ outliner_data_mesh
+ outliner_data_curve
+ outliner_data_lattice
+ outliner_data_meta
+ outliner_data_lamp
+ outliner_data_camera
+ outliner_data_armature
+ outliner_data_font
+ outliner_data_surface
+ outliner_data_speaker
+ outliner_data_pose
+ mesh_plane
+ mesh_cube
+ mesh_circle
+ mesh_uvsphere
+ mesh_icosphere
+ mesh_grid
+ mesh_monkey
+ mesh_cylinder
+ mesh_torus
+ mesh_cone
+ mesh_capsule
+ lamp_point
+ lamp_sun
+ lamp_spot
+ lamp_hemi
+ lamp_area
+ meta_empty
+ meta_plane
+ meta_cube
+ meta_ball
+ meta_ellipsoid
+ meta_capsule
+ surface_ncurve
+ surface_ncircle
+ surface_nsurface
+ surface_ncylinder
+ surface_nsphere
+ surface_ntorus
+ curve_bezcurve
+ curve_bezcircle
+ curve_ncurve
+ curve_ncircle
+ curve_path
+ color_red
+ color_green
+ color_blue
+ tria_right_bar
+ tria_down_bar
+ tria_left_bar
+ tria_up_bar
+ force_force
+ force_wind
+ force_vortex
+ force_magnetic
+ force_harmonic
+ force_charge
+ force_lennardjones
+ force_texture
+ force_curve
+ force_boid
+ force_turbulence
+ force_drag
+ force_smokeflow
+ node_insert_on
+ node_insert_off
+ modifier
+ mod_wave
+ mod_build
+ mod_decim
+ mod_mirror
+ mod_soft
+ mod_subsurf
+ hook
+ mod_physics
+ mod_particles
+ mod_boolean
+ mod_edgesplit
+ mod_array
+ mod_uvproject
+ mod_displace
+ mod_curve
+ mod_lattice
+ constraint_data
+ mod_armature
+ mod_shrinkwrap
+ mod_cast
+ mod_meshdeform
+ mod_bevel
+ mod_smooth
+ mod_simpledeform
+ mod_mask
+ mod_cloth
+ mod_explode
+ mod_fluidsim
+ mod_multires
+ mod_smoke
+ mod_solidify
+ mod_screw
+ mod_vertex_weight
+ mod_dynamicpaint
+ mod_remesh
+ mod_ocean
+ mod_warp
+ mod_skin
+ mod_triangulate
+ mod_wireframe
+ mod_data_transfer
+ mod_normaledit
+ rec
+ play
+ ff
+ rew
+ pause
+ prev_keyframe
+ next_keyframe
+ play_audio
+ play_reverse
+ preview_range
+ action_tweak
+ pmarker_act
+ pmarker_sel
+ pmarker
+ marker_hlt
+ marker
+ space2
+ space3
+ keyingset
+ key_dehlt
+ key_hlt
+ mute_ipo_off
+ mute_ipo_on
+ visible_ipo_off
+ visible_ipo_on
+ driver
+ solo_off
+ solo_on
+ frame_prev
+ frame_next
+ nla_pushdown
+ ipo_constant
+ ipo_linear
+ ipo_bezier
+ ipo_sine
+ ipo_quad
+ ipo_cubic
+ ipo_quart
+ ipo_quint
+ ipo_expo
+ ipo_circ
+ ipo_bounce
+ ipo_elastic
+ ipo_back
+ ipo_ease_in
+ ipo_ease_out
+ ipo_ease_in_out
+ normalize_fcurves
+ vertexsel
+ edgesel
+ facesel
+ loopsel
+ rotate
+ cursor
+ rotatecollection
+ rotatecenter
+ rotactive
+ align
+ smoothcurve
+ spherecurve
+ rootcurve
+ sharpcurve
+ lincurve
+ nocurve
+ rndcurve
+ prop_off
+ prop_on
+ prop_con
+ particle_point
+ particle_tip
+ particle_path
+ man_trans
+ man_rot
+ man_scale
+ manipul
+ snap_off
+ snap_on
+ snap_normal
+ snap_grid
+ snap_vertex
+ snap_edge
+ snap_face
+ snap_volume
+ snap_increment
+ sticky_uvs_loc
+ sticky_uvs_disable
+ sticky_uvs_vert
+ clipuv_dehlt
+ clipuv_hlt
+ snap_peel_object
+ grid
+ pastedown
+ copydown
+ pasteflipup
+ pasteflipdown
+ snap_surface
+ automerge_on
+ automerge_off
+ retopo
+ uv_vertexsel
+ uv_edgesel
+ uv_facesel
+ uv_islandsel
+ uv_sync_select
+ bbox
+ wire
+ solid
+ smooth
+ potato
+ ortho
+ lockview_off
+ lockview_on
+ axis_side
+ axis_front
+ axis_top
+ ndof_dom
+ ndof_turn
+ ndof_fly
+ ndof_trans
+ layer_used
+ layer_active
+ sortalpha
+ sortbyext
+ sorttime
+ sortsize
+ longdisplay
+ shortdisplay
+ ghost
+ imgdisplay
+ save_as
+ save_copy
+ bookmarks
+ fontpreview
+ filter
+ newfolder
+ open_recent
+ file_parent
+ file_refresh
+ file_folder
+ file_blend
+ file_image
+ file_movie
+ file_script
+ file_sound
+ file_font
+ file_text
+ recover_auto
+ save_prefs
+ link_blend
+ append_blend
+ import
+ export
+ external_data
+ load_factory
+ loop_back
+ loop_forwards
+ back
+ forward
+ file_hidden
+ file_backup
+ disk_drive
+ matplane
+ matsphere
+ matcube
+ monkey
+ hair
+ aliased
+ antialiased
+ mat_sphere_sky
+ wordwrap_off
+ wordwrap_on
+ syntax_off
+ syntax_on
+ linenumbers_off
+ linenumbers_on
+ scriptplugins
+ seq_sequencer
+ seq_preview
+ seq_luma_waveform
+ seq_chroma_scope
+ seq_histogram
+ seq_splitview
+ image_rgb
+ image_rgb_alpha
+ image_alpha
+ image_zdepth
+ imagefile
+)
+
data_to_c_simple(../../../../release/datafiles/bfont.pfb SRC)
data_to_c_simple(../../../../release/datafiles/bfont.ttf SRC)
data_to_c_simple(../../../../release/datafiles/bmonofont.ttf SRC)
@@ -53,12 +542,12 @@ if(WITH_BLENDER)
#../../../../release/datafiles/blender_icons16.png
#90 SRC)
- data_to_c_simple_icons(../../../../release/datafiles/blender_icons16 SRC)
+ data_to_c_simple_icons(../../../../release/datafiles/blender_icons16 "icon16_" "${ICON_NAMES}" SRC)
#data_to_c_simple(../../../../release/datafiles/blender_icons16.png SRC)
#svg_to_png(../../../../release/datafiles/blender_icons.svg
#../../../../release/datafiles/blender_icons32.png
#180 SRC)
- data_to_c_simple_icons(../../../../release/datafiles/blender_icons32 SRC)
+ data_to_c_simple_icons(../../../../release/datafiles/blender_icons32 "icon32_" "${ICON_NAMES}" SRC)
#data_to_c_simple(../../../../release/datafiles/blender_icons32.png SRC)
#svg_to_png(../../../../release/datafiles/prvicons.svg
#../../../../release/datafiles/prvicons.png
@@ -130,4 +619,6 @@ if(WITH_BLENDER)
data_to_c_simple(../../../../release/datafiles/startup.blend SRC)
endif()
+unset(ICON_NAMES)
+
blender_add_lib(bf_editor_datafiles "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/gpencil/drawgpencil.c b/source/blender/editors/gpencil/drawgpencil.c
index a542bf8fa11..b23b9a06fbb 100644
--- a/source/blender/editors/gpencil/drawgpencil.c
+++ b/source/blender/editors/gpencil/drawgpencil.c
@@ -41,7 +41,7 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
-#include "BLI_polyfill2d.h"
+#include "BLI_polyfill_2d.h"
#include "BLF_api.h"
#include "BLT_translation.h"
@@ -426,7 +426,7 @@ static void gp_triangulate_stroke_fill(bGPDstroke *gps)
/* convert to 2d and triangulate */
gp_stroke_2d_flat(gps->points, gps->totpoints, points2d, &direction);
- BLI_polyfill_calc((const float(*)[2])points2d, (unsigned int)gps->totpoints, direction, (unsigned int(*)[3])tmp_triangles);
+ BLI_polyfill_calc(points2d, (unsigned int)gps->totpoints, direction, tmp_triangles);
/* Number of triangles */
gps->tot_triangles = gps->totpoints - 2;
@@ -441,9 +441,7 @@ static void gp_triangulate_stroke_fill(bGPDstroke *gps)
for (int i = 0; i < gps->tot_triangles; i++) {
bGPDtriangle *stroke_triangle = &gps->triangles[i];
- stroke_triangle->v1 = tmp_triangles[i][0];
- stroke_triangle->v2 = tmp_triangles[i][1];
- stroke_triangle->v3 = tmp_triangles[i][2];
+ memcpy(stroke_triangle->verts, tmp_triangles[i], sizeof(uint[3]));
}
}
else {
@@ -490,53 +488,39 @@ static void gp_draw_stroke_fill(
/* Draw all triangles for filling the polygon (cache must be calculated before) */
BLI_assert(gps->tot_triangles >= 1);
glBegin(GL_TRIANGLES);
- for (i = 0, stroke_triangle = gps->triangles; i < gps->tot_triangles; i++, stroke_triangle++) {
- if (gps->flag & GP_STROKE_3DSPACE) {
- /* vertex 1 */
- pt = &gps->points[stroke_triangle->v1];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- glVertex3fv(fpt);
- /* vertex 2 */
- pt = &gps->points[stroke_triangle->v2];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- glVertex3fv(fpt);
- /* vertex 3 */
- pt = &gps->points[stroke_triangle->v3];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- glVertex3fv(fpt);
+ if (gps->flag & GP_STROKE_3DSPACE) {
+ for (i = 0, stroke_triangle = gps->triangles; i < gps->tot_triangles; i++, stroke_triangle++) {
+ for (int j = 0; j < 3; j++) {
+ pt = &gps->points[stroke_triangle->verts[j]];
+ mul_v3_m4v3(fpt, diff_mat, &pt->x);
+ glVertex3fv(fpt);
+ }
}
- else {
- float co[2];
- /* vertex 1 */
- pt = &gps->points[stroke_triangle->v1];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- gp_calc_2d_stroke_fxy(fpt, gps->flag, offsx, offsy, winx, winy, co);
- glVertex2fv(co);
- /* vertex 2 */
- pt = &gps->points[stroke_triangle->v2];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- gp_calc_2d_stroke_fxy(fpt, gps->flag, offsx, offsy, winx, winy, co);
- glVertex2fv(co);
- /* vertex 3 */
- pt = &gps->points[stroke_triangle->v3];
- mul_v3_m4v3(fpt, diff_mat, &pt->x);
- gp_calc_2d_stroke_fxy(fpt, gps->flag, offsx, offsy, winx, winy, co);
- glVertex2fv(co);
+ }
+ else {
+ for (i = 0, stroke_triangle = gps->triangles; i < gps->tot_triangles; i++, stroke_triangle++) {
+ for (int j = 0; j < 3; j++) {
+ float co[2];
+ pt = &gps->points[stroke_triangle->verts[j]];
+ mul_v3_m4v3(fpt, diff_mat, &pt->x);
+ gp_calc_2d_stroke_fxy(fpt, gps->flag, offsx, offsy, winx, winy, co);
+ glVertex2fv(co);
+ }
}
}
glEnd();
}
else {
/* As an initial implementation, we use the OpenGL filled polygon drawing
- * here since it's the easiest option to implement for this case. It does
- * come with limitations (notably for concave shapes), though it shouldn't
- * be much of an issue in most cases.
- *
- * We keep this legacy implementation around despite now having the high quality
- * fills, as this is necessary for keeping everything working nicely for files
- * created using old versions of Blender which may have depended on the artifacts
- * the old fills created.
- */
+ * here since it's the easiest option to implement for this case. It does
+ * come with limitations (notably for concave shapes), though it shouldn't
+ * be much of an issue in most cases.
+ *
+ * We keep this legacy implementation around despite now having the high quality
+ * fills, as this is necessary for keeping everything working nicely for files
+ * created using old versions of Blender which may have depended on the artifacts
+ * the old fills created.
+ */
bGPDspoint *pt;
glBegin(GL_POLYGON);
@@ -701,24 +685,25 @@ static void gp_draw_stroke_2d(bGPDspoint *points, int totpoints, short thickness
*/
{
bGPDspoint *pt1, *pt2;
- float pm[2];
+ float s0[2], s1[2]; /* segment 'center' points */
+ float pm[2]; /* normal from previous segment. */
int i;
float fpt[3];
glShadeModel(GL_FLAT);
glBegin(GL_QUADS);
-
+
+ /* get x and y coordinates from first point */
+ mul_v3_m4v3(fpt, diff_mat, &points->x);
+ gp_calc_2d_stroke_fxy(fpt, sflag, offsx, offsy, winx, winy, s0);
+
for (i = 0, pt1 = points, pt2 = points + 1; i < (totpoints - 1); i++, pt1++, pt2++) {
- float s0[2], s1[2]; /* segment 'center' points */
float t0[2], t1[2]; /* tessellated coordinates */
float m1[2], m2[2]; /* gradient and normal */
float mt[2], sc[2]; /* gradient for thickness, point for end-cap */
float pthick; /* thickness at segment point */
- /* get x and y coordinates from points */
- mul_v3_m4v3(fpt, diff_mat, &pt1->x);
- gp_calc_2d_stroke_fxy(fpt, sflag, offsx, offsy, winx, winy, s0);
-
+ /* get x and y coordinates from point2 (point1 has already been computed in previous iteration). */
mul_v3_m4v3(fpt, diff_mat, &pt2->x);
gp_calc_2d_stroke_fxy(fpt, sflag, offsx, offsy, winx, winy, s1);
@@ -846,6 +831,8 @@ static void gp_draw_stroke_2d(bGPDspoint *points, int totpoints, short thickness
glVertex2fv(t0);
}
+ /* store computed point2 coordinates as point1 ones of next segment. */
+ copy_v2_v2(s0, s1);
/* store stroke's 'natural' normal for next stroke to use */
copy_v2_v2(pm, m2);
}
@@ -1729,10 +1716,10 @@ void ED_gpencil_draw_view3d(wmWindowManager *wm, Scene *scene, View3D *v3d, AReg
rctf rectf;
ED_view3d_calc_camera_border(scene, ar, v3d, rv3d, &rectf, true); /* no shift */
- offsx = iroundf(rectf.xmin);
- offsy = iroundf(rectf.ymin);
- winx = iroundf(rectf.xmax - rectf.xmin);
- winy = iroundf(rectf.ymax - rectf.ymin);
+ offsx = round_fl_to_int(rectf.xmin);
+ offsy = round_fl_to_int(rectf.ymin);
+ winx = round_fl_to_int(rectf.xmax - rectf.xmin);
+ winy = round_fl_to_int(rectf.ymax - rectf.ymin);
}
else {
offsx = 0;
diff --git a/source/blender/editors/gpencil/editaction_gpencil.c b/source/blender/editors/gpencil/editaction_gpencil.c
index bd4856f1b93..90d44503013 100644
--- a/source/blender/editors/gpencil/editaction_gpencil.c
+++ b/source/blender/editors/gpencil/editaction_gpencil.c
@@ -252,8 +252,10 @@ bool ED_gplayer_frames_delete(bGPDlayer *gpl)
for (gpf = gpl->frames.first; gpf; gpf = gpfn) {
gpfn = gpf->next;
- if (gpf->flag & GP_FRAME_SELECT)
- changed |= BKE_gpencil_layer_delframe(gpl, gpf);
+ if (gpf->flag & GP_FRAME_SELECT) {
+ BKE_gpencil_layer_delframe(gpl, gpf);
+ changed = true;
+ }
}
return changed;
@@ -314,7 +316,7 @@ void ED_gplayer_frames_keytype_set(bGPDlayer *gpl, short type)
*/
/* globals for copy/paste data (like for other copy/paste buffers) */
-ListBase gp_anim_copybuf = {NULL, NULL};
+static ListBase gp_anim_copybuf = {NULL, NULL};
static int gp_anim_copy_firstframe = 999999999;
static int gp_anim_copy_lastframe = -999999999;
static int gp_anim_copy_cfra = 0;
diff --git a/source/blender/editors/gpencil/gpencil_brush.c b/source/blender/editors/gpencil/gpencil_brush.c
index ec5a42c23a5..5fe16226421 100644
--- a/source/blender/editors/gpencil/gpencil_brush.c
+++ b/source/blender/editors/gpencil/gpencil_brush.c
@@ -54,7 +54,6 @@
#include "DNA_object_types.h"
#include "BKE_context.h"
-#include "BKE_global.h"
#include "BKE_gpencil.h"
#include "BKE_library.h"
#include "BKE_report.h"
@@ -297,9 +296,9 @@ static bool gp_brush_strength_apply(
float inf;
/* Compute strength of effect
- * - We divide the strength by 10, so that users can set "sane" values.
- * Otherwise, good default values are in the range of 0.093
- */
+ * - We divide the strength by 10, so that users can set "sane" values.
+ * Otherwise, good default values are in the range of 0.093
+ */
inf = gp_brush_influence_calc(gso, radius, co) / 10.0f;
/* apply */
@@ -710,7 +709,7 @@ static bool gp_brush_randomize_apply(tGP_BrushEditData *gso, bGPDstroke *gps, in
}
else {
/* ERROR */
- BLI_assert("3D stroke being sculpted in non-3D view");
+ BLI_assert(!"3D stroke being sculpted in non-3D view");
}
}
else {
@@ -773,6 +772,9 @@ typedef struct tGPSB_CloneBrushData {
/* for "stamp" mode, the currently pasted brushes */
bGPDstroke **new_strokes;
+
+ /* mapping from colors referenced per stroke, to the new colours in the "pasted" strokes */
+ GHash *new_colors;
} tGPSB_CloneBrushData;
/* Initialise "clone" brush data */
@@ -816,6 +818,11 @@ static void gp_brush_clone_init(bContext *C, tGP_BrushEditData *gso)
if (1 /*gso->brush->mode == GP_EDITBRUSH_CLONE_MODE_STAMP*/) {
data->new_strokes = MEM_callocN(sizeof(bGPDstroke *) * data->totitems, "cloned strokes ptr array");
}
+
+ /* Init colormap for mapping between the pasted stroke's source colour(names)
+ * and the final colours that will be used here instead...
+ */
+ data->new_colors = gp_copybuf_validate_colormap(gso->gpd);
}
/* Free custom data used for "clone" brush */
@@ -829,6 +836,12 @@ static void gp_brush_clone_free(tGP_BrushEditData *gso)
data->new_strokes = NULL;
}
+ /* free copybuf colormap */
+ if (data->new_colors) {
+ BLI_ghash_free(data->new_colors, NULL, NULL);
+ data->new_colors = NULL;
+ }
+
/* free the customdata itself */
MEM_freeN(data);
gso->customdata = NULL;
@@ -869,6 +882,13 @@ static void gp_brush_clone_add(bContext *C, tGP_BrushEditData *gso)
new_stroke->next = new_stroke->prev = NULL;
BLI_addtail(&gpf->strokes, new_stroke);
+ /* Fix color references */
+ BLI_assert(new_stroke->colorname[0] != '\0');
+ new_stroke->palcolor = BLI_ghash_lookup(data->new_colors, new_stroke->colorname);
+
+ BLI_assert(new_stroke->palcolor != NULL);
+ BLI_strncpy(new_stroke->colorname, new_stroke->palcolor->info, sizeof(new_stroke->colorname));
+
/* Adjust all the stroke's points, so that the strokes
* get pasted relative to where the cursor is now
*/
@@ -1830,8 +1850,6 @@ static int gpsculpt_brush_modal(bContext *C, wmOperator *op, const wmEvent *even
void GPENCIL_OT_brush_paint(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
/* identifiers */
ot->name = "Stroke Sculpt";
ot->idname = "GPENCIL_OT_brush_paint";
@@ -1848,7 +1866,9 @@ void GPENCIL_OT_brush_paint(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
/* properties */
- RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input",
"Enter a mini 'sculpt-mode' if enabled, otherwise, exit after drawing a single stroke");
diff --git a/source/blender/editors/gpencil/gpencil_convert.c b/source/blender/editors/gpencil/gpencil_convert.c
index d0f68c4b8f3..7d455f214db 100644
--- a/source/blender/editors/gpencil/gpencil_convert.c
+++ b/source/blender/editors/gpencil/gpencil_convert.c
@@ -106,20 +106,20 @@ enum {
};
/* RNA enum define */
-static EnumPropertyItem prop_gpencil_convertmodes[] = {
+static const EnumPropertyItem prop_gpencil_convertmodes[] = {
{GP_STROKECONVERT_PATH, "PATH", ICON_CURVE_PATH, "Path", "Animation path"},
{GP_STROKECONVERT_CURVE, "CURVE", ICON_CURVE_BEZCURVE, "Bezier Curve", "Smooth Bezier curve"},
{GP_STROKECONVERT_POLY, "POLY", ICON_MESH_DATA, "Polygon Curve", "Bezier curve with straight-line segments (vector handles)"},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_gpencil_convert_timingmodes_restricted[] = {
+static const EnumPropertyItem prop_gpencil_convert_timingmodes_restricted[] = {
{GP_STROKECONVERT_TIMING_NONE, "NONE", 0, "No Timing", "Ignore timing"},
{GP_STROKECONVERT_TIMING_LINEAR, "LINEAR", 0, "Linear", "Simple linear timing"},
{0, NULL, 0, NULL, NULL},
};
-static EnumPropertyItem prop_gpencil_convert_timingmodes[] = {
+static const EnumPropertyItem prop_gpencil_convert_timingmodes[] = {
{GP_STROKECONVERT_TIMING_NONE, "NONE", 0, "No Timing", "Ignore timing"},
{GP_STROKECONVERT_TIMING_LINEAR, "LINEAR", 0, "Linear", "Simple linear timing"},
{GP_STROKECONVERT_TIMING_FULL, "FULL", 0, "Original", "Use the original timing, gaps included"},
@@ -128,7 +128,7 @@ static EnumPropertyItem prop_gpencil_convert_timingmodes[] = {
{0, NULL, 0, NULL, NULL},
};
-static EnumPropertyItem *rna_GPConvert_mode_items(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
+static const EnumPropertyItem *rna_GPConvert_mode_items(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
bool *UNUSED(r_free))
{
if (RNA_boolean_get(ptr, "use_timing_data")) {
diff --git a/source/blender/editors/gpencil/gpencil_data.c b/source/blender/editors/gpencil/gpencil_data.c
index 6980ad46241..9d183222c2d 100644
--- a/source/blender/editors/gpencil/gpencil_data.c
+++ b/source/blender/editors/gpencil/gpencil_data.c
@@ -53,7 +53,6 @@
#include "DNA_gpencil_types.h"
#include "BKE_context.h"
-#include "BKE_global.h"
#include "BKE_gpencil.h"
#include "BKE_library.h"
#include "BKE_object.h"
@@ -302,7 +301,7 @@ static int gp_layer_move_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_layer_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{GP_LAYER_MOVE_UP, "UP", 0, "Up", ""},
{GP_LAYER_MOVE_DOWN, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -423,18 +422,59 @@ static int gp_reveal_poll(bContext *C)
return ED_gpencil_data_get_active(C) != NULL;
}
-static int gp_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static void gp_reveal_select_frame(bContext *C, bGPDframe *frame, bool select)
+{
+ bGPDstroke *gps;
+ for (gps = frame->strokes.first; gps; gps = gps->next) {
+
+ /* only deselect strokes that are valid in this view */
+ if (ED_gpencil_stroke_can_use(C, gps)) {
+
+ /* (de)select points */
+ int i;
+ bGPDspoint *pt;
+ for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
+ SET_FLAG_FROM_TEST(pt->flag, select, GP_SPOINT_SELECT);
+ }
+
+ /* (de)select stroke */
+ SET_FLAG_FROM_TEST(gps->flag, select, GP_STROKE_SELECT);
+ }
+ }
+}
+
+static int gp_reveal_exec(bContext *C, wmOperator *op)
{
bGPdata *gpd = ED_gpencil_data_get_active(C);
bGPDlayer *gpl;
-
+ const bool select = RNA_boolean_get(op->ptr, "select");
+
/* sanity checks */
if (gpd == NULL)
return OPERATOR_CANCELLED;
- /* make all layers visible */
for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
- gpl->flag &= ~GP_LAYER_HIDE;
+
+ if (gpl->flag & GP_LAYER_HIDE) {
+ gpl->flag &= ~GP_LAYER_HIDE;
+
+ /* select or deselect if requested, only on hidden layers */
+ if (gpd->flag & GP_DATA_STROKE_EDITMODE) {
+ if (select) {
+ /* select all strokes on active frame only (same as select all operator) */
+ if (gpl->actframe) {
+ gp_reveal_select_frame(C, gpl->actframe, true);
+ }
+ }
+ else {
+ /* deselect strokes on all frames (same as deselect all operator) */
+ bGPDframe *gpf;
+ for (gpf = gpl->frames.first; gpf; gpf = gpf->next) {
+ gp_reveal_select_frame(C, gpf, false);
+ }
+ }
+ }
+ }
}
/* notifiers */
@@ -456,6 +496,9 @@ void GPENCIL_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* props */
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/* ***************** Lock/Unlock All Layers ************************ */
@@ -831,7 +874,7 @@ static int gp_stroke_arrange_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_stroke_arrange(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{GP_STROKE_MOVE_UP, "UP", 0, "Bring Forward", ""},
{GP_STROKE_MOVE_DOWN, "DOWN", 0, "Send Backward", ""},
{GP_STROKE_MOVE_TOP, "TOP", 0, "Bring to Front", ""},
@@ -1019,7 +1062,7 @@ static int gp_brush_remove_exec(bContext *C, wmOperator *op)
if (ELEM(NULL, ts, brush))
return OPERATOR_CANCELLED;
- if (BLI_listbase_count_ex(&ts->gp_brushes, 2) < 2) {
+ if (BLI_listbase_count_at_most(&ts->gp_brushes, 2) < 2) {
BKE_report(op->reports, RPT_ERROR, "Grease Pencil needs a brush, unable to delete the last one");
return OPERATOR_CANCELLED;
}
@@ -1165,7 +1208,7 @@ static int gp_brush_move_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_brush_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{GP_BRUSH_MOVE_UP, "UP", 0, "Up", ""},
{GP_BRUSH_MOVE_DOWN, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL }
@@ -1377,7 +1420,7 @@ static int gp_palette_remove_exec(bContext *C, wmOperator *op)
if (ELEM(NULL, gpd, palette))
return OPERATOR_CANCELLED;
- if (BLI_listbase_count_ex(&gpd->palettes, 2) < 2) {
+ if (BLI_listbase_count_at_most(&gpd->palettes, 2) < 2) {
BKE_report(op->reports, RPT_ERROR, "Grease Pencil needs a palette, unable to delete the last one");
return OPERATOR_CANCELLED;
}
@@ -1922,7 +1965,7 @@ static int gp_palettecolor_move_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_palettecolor_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{GP_COLOR_MOVE_UP, "UP", 0, "Up", ""},
{GP_COLOR_MOVE_DOWN, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/gpencil/gpencil_edit.c b/source/blender/editors/gpencil/gpencil_edit.c
index e118e490f25..bc54bd89958 100644
--- a/source/blender/editors/gpencil/gpencil_edit.c
+++ b/source/blender/editors/gpencil/gpencil_edit.c
@@ -38,8 +38,11 @@
#include "MEM_guardedalloc.h"
-#include "BLI_math.h"
#include "BLI_blenlib.h"
+#include "BLI_ghash.h"
+#include "BLI_math.h"
+#include "BLI_string.h"
+#include "BLI_string_utils.h"
#include "BLI_utildefines.h"
#include "BLT_translation.h"
@@ -52,7 +55,6 @@
#include "DNA_gpencil_types.h"
#include "BKE_context.h"
-#include "BKE_global.h"
#include "BKE_gpencil.h"
#include "BKE_library.h"
#include "BKE_report.h"
@@ -74,7 +76,6 @@
#include "ED_object.h"
#include "ED_screen.h"
#include "ED_view3d.h"
-#include "ED_screen.h"
#include "ED_space_api.h"
#include "gpencil_intern.h"
@@ -101,7 +102,8 @@ static int gpencil_editmode_toggle_exec(bContext *C, wmOperator *UNUSED(op))
ED_gpencil_reset_layers_parent(gpd);
}
- WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | ND_GPENCIL_EDITMODE, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | ND_GPENCIL_EDITMODE, NULL);
WM_event_add_notifier(C, NC_SCENE | ND_MODE, NULL);
return OPERATOR_FINISHED;
@@ -149,7 +151,8 @@ static int gpencil_hideselect_toggle_exec(bContext *C, wmOperator *UNUSED(op))
ts->gp_sculpt.alpha = 1.0f;
}
- WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | ND_GPENCIL_EDITMODE, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA, NULL);
+ WM_event_add_notifier(C, NC_GPENCIL | ND_GPENCIL_EDITMODE, NULL);
WM_event_add_notifier(C, NC_SCENE | ND_MODE, NULL);
return OPERATOR_FINISHED;
@@ -336,11 +339,27 @@ void GPENCIL_OT_duplicate(wmOperatorType *ot)
/* NOTE: is exposed within the editors/gpencil module so that other tools can use it too */
ListBase gp_strokes_copypastebuf = {NULL, NULL};
+/* Hash for hanging on to all the palette colors used by strokes in the buffer
+ *
+ * This is needed to prevent dangling and unsafe pointers when pasting across datablocks,
+ * or after a color used by a stroke in the buffer gets deleted (via user action or undo).
+ */
+static GHash *gp_strokes_copypastebuf_colors = NULL;
+
/* Free copy/paste buffer data */
void ED_gpencil_strokes_copybuf_free(void)
{
bGPDstroke *gps, *gpsn;
+ /* Free the palettes buffer
+ * NOTE: This is done before the strokes so that the name ptrs (keys) are still safe
+ */
+ if (gp_strokes_copypastebuf_colors) {
+ BLI_ghash_free(gp_strokes_copypastebuf_colors, NULL, MEM_freeN);
+ gp_strokes_copypastebuf_colors = NULL;
+ }
+
+ /* Free the stroke buffer */
for (gps = gp_strokes_copypastebuf.first; gps; gps = gpsn) {
gpsn = gps->next;
@@ -353,6 +372,46 @@ void ED_gpencil_strokes_copybuf_free(void)
gp_strokes_copypastebuf.first = gp_strokes_copypastebuf.last = NULL;
}
+/* Ensure that destination datablock has all the colours the pasted strokes need
+ * Helper function for copy-pasting strokes
+ */
+GHash *gp_copybuf_validate_colormap(bGPdata *gpd)
+{
+ GHash *new_colors = BLI_ghash_str_new("GPencil Paste Dst Colors");
+ GHashIterator gh_iter;
+
+ /* If there's no active palette yet (i.e. new datablock), add one */
+ bGPDpalette *palette = BKE_gpencil_palette_getactive(gpd);
+ if (palette == NULL) {
+ palette = BKE_gpencil_palette_addnew(gpd, "Pasted Palette", true);
+ }
+
+ /* For each color, figure out what to map to... */
+ GHASH_ITER(gh_iter, gp_strokes_copypastebuf_colors) {
+ bGPDpalettecolor *palcolor;
+ char *name = BLI_ghashIterator_getKey(&gh_iter);
+
+ /* Look for existing color to map to */
+ /* XXX: What to do if same name but different color? Behaviour here should depend on a property? */
+ palcolor = BKE_gpencil_palettecolor_getbyname(palette, name);
+ if (palcolor == NULL) {
+ /* Doesn't Exist - Create new matching color for this palette */
+ /* XXX: This still doesn't fix the pasting across file boundaries problem... */
+ bGPDpalettecolor *src_color = BLI_ghashIterator_getValue(&gh_iter);
+
+ palcolor = MEM_dupallocN(src_color);
+ BLI_addtail(&palette->colors, palcolor);
+
+ BLI_uniquename(&palette->colors, palcolor, DATA_("GP Color"), '.', offsetof(bGPDpalettecolor, info), sizeof(palcolor->info));
+ }
+
+ /* Store this mapping (for use later when pasting) */
+ BLI_ghash_insert(new_colors, name, palcolor);
+ }
+
+ return new_colors;
+}
+
/* --------------------- */
/* Copy selected strokes */
@@ -414,7 +473,26 @@ static int gp_strokes_copy_exec(bContext *C, wmOperator *op)
}
CTX_DATA_END;
- /* done - no updates needed */
+ /* Build up hash of colors used in these strokes, making copies of these to protect against dangling pointers */
+ if (gp_strokes_copypastebuf.first) {
+ gp_strokes_copypastebuf_colors = BLI_ghash_str_new("GPencil CopyBuf Colors");
+
+ for (bGPDstroke *gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
+ if (ED_gpencil_stroke_can_use(C, gps)) {
+ if (BLI_ghash_haskey(gp_strokes_copypastebuf_colors, gps->colorname) == false) {
+ bGPDpalettecolor *color = MEM_dupallocN(gps->palcolor);
+
+ BLI_ghash_insert(gp_strokes_copypastebuf_colors, gps->colorname, color);
+ gps->palcolor = color;
+ }
+ }
+ }
+ }
+
+ /* updates (to ensure operator buttons are refreshed, when used via hotkeys) */
+ WM_event_add_notifier(C, NC_GPENCIL | ND_DATA, NULL); // XXX?
+
+ /* done */
return OPERATOR_FINISHED;
}
@@ -459,6 +537,7 @@ static int gp_strokes_paste_exec(bContext *C, wmOperator *op)
bGPDframe *gpf;
eGP_PasteMode type = RNA_enum_get(op->ptr, "type");
+ GHash *new_colors;
/* check for various error conditions */
if (gpd == NULL) {
@@ -516,6 +595,10 @@ static int gp_strokes_paste_exec(bContext *C, wmOperator *op)
}
CTX_DATA_END;
+ /* Ensure that all the necessary colors exist */
+ new_colors = gp_copybuf_validate_colormap(gpd);
+
+ /* Copy over the strokes from the buffer (and adjust the colors) */
for (bGPDstroke *gps = gp_strokes_copypastebuf.first; gps; gps = gps->next) {
if (ED_gpencil_stroke_can_use(C, gps)) {
/* Need to verify if layer exists */
@@ -534,6 +617,7 @@ static int gp_strokes_paste_exec(bContext *C, wmOperator *op)
*/
gpf = BKE_gpencil_layer_getframe(gpl, CFRA, true);
if (gpf) {
+ /* Create new stroke */
bGPDstroke *new_stroke = MEM_dupallocN(gps);
new_stroke->tmp_layerinfo[0] = '\0';
@@ -544,10 +628,22 @@ static int gp_strokes_paste_exec(bContext *C, wmOperator *op)
new_stroke->next = new_stroke->prev = NULL;
BLI_addtail(&gpf->strokes, new_stroke);
+
+ /* Fix color references */
+ BLI_assert(new_stroke->colorname[0] != '\0');
+ new_stroke->palcolor = BLI_ghash_lookup(new_colors, new_stroke->colorname);
+
+ BLI_assert(new_stroke->palcolor != NULL);
+ BLI_strncpy(new_stroke->colorname, new_stroke->palcolor->info, sizeof(new_stroke->colorname));
+
+ /*new_stroke->flag |= GP_STROKE_RECALC_COLOR; */
}
}
}
+ /* free temp data */
+ BLI_ghash_free(new_colors, NULL, NULL);
+
/* updates */
WM_event_add_notifier(C, NC_GPENCIL | ND_DATA | NA_EDITED, NULL);
@@ -556,7 +652,7 @@ static int gp_strokes_paste_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_paste(wmOperatorType *ot)
{
- static EnumPropertyItem copy_type[] = {
+ static const EnumPropertyItem copy_type[] = {
{GP_COPY_ONLY, "COPY", 0, "Copy", ""},
{GP_COPY_MERGE, "MERGE", 0, "Merge", ""},
{0, NULL, 0, NULL, NULL}
@@ -749,10 +845,10 @@ static int gp_blank_frame_add_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_blank_frame_add(wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Add Blank Frame";
+ ot->name = "Insert Blank Frame";
ot->idname = "GPENCIL_OT_blank_frame_add";
- ot->description = "Add a new frame with nothing in it on the current frame. "
- "If there is already a frame, all existing frames are shifted one frame later";
+ ot->description = "Insert a blank frame on the current frame "
+ "(all subsequently existing frames, if any, are shifted right by one frame)";
/* callbacks */
ot->exec = gp_blank_frame_add_exec;
@@ -1221,7 +1317,7 @@ static int gp_delete_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_delete(wmOperatorType *ot)
{
- static EnumPropertyItem prop_gpencil_delete_types[] = {
+ static const EnumPropertyItem prop_gpencil_delete_types[] = {
{GP_DELETEOP_POINTS, "POINTS", 0, "Points", "Delete selected points and split strokes into segments"},
{GP_DELETEOP_STROKES, "STROKES", 0, "Strokes", "Delete selected strokes"},
{GP_DELETEOP_FRAME, "FRAME", 0, "Frame", "Delete active frame"},
@@ -1641,7 +1737,7 @@ static int gp_stroke_cyclical_set_exec(bContext *C, wmOperator *op)
*/
void GPENCIL_OT_stroke_cyclical_set(wmOperatorType *ot)
{
- static EnumPropertyItem cyclic_type[] = {
+ static const EnumPropertyItem cyclic_type[] = {
{GP_STROKE_CYCLIC_CLOSE, "CLOSE", 0, "Close all", ""},
{GP_STROKE_CYCLIC_OPEN, "OPEN", 0, "Open all", ""},
{GP_STROKE_CYCLIC_TOGGLE, "TOGGLE", 0, "Toggle", ""},
@@ -1903,7 +1999,7 @@ static int gp_stroke_join_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_stroke_join(wmOperatorType *ot)
{
- static EnumPropertyItem join_type[] = {
+ static const EnumPropertyItem join_type[] = {
{GP_STROKE_JOIN, "JOIN", 0, "Join", ""},
{GP_STROKE_JOINCOPY, "JOINCOPY", 0, "Join and Copy", ""},
{0, NULL, 0, NULL, NULL}
@@ -2089,7 +2185,7 @@ static int gp_strokes_reproject_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_reproject(wmOperatorType *ot)
{
- static EnumPropertyItem reproject_type[] = {
+ static const EnumPropertyItem reproject_type[] = {
{GP_REPROJECT_PLANAR, "PLANAR", 0, "Planar",
"Reproject the strokes to end up on the same plane, as if drawn from the current viewpoint "
"using 'Cursor' Stroke Placement"},
@@ -2127,10 +2223,10 @@ static int gp_count_subdivision_cuts(bGPDstroke *gps)
int totnewpoints = 0;
for (i = 0, pt = gps->points; i < gps->totpoints && pt; i++, pt++) {
if (pt->flag & GP_SPOINT_SELECT) {
- if (i + 1 < gps->totpoints){
+ if (i + 1 < gps->totpoints) {
if (gps->points[i + 1].flag & GP_SPOINT_SELECT) {
++totnewpoints;
- };
+ }
}
}
}
@@ -2185,7 +2281,7 @@ static int gp_stroke_subdivide_exec(bContext *C, wmOperator *op)
/* if next point is selected add a half way point */
if (pt->flag & GP_SPOINT_SELECT) {
- if (i + 1 < oldtotpoints){
+ if (i + 1 < oldtotpoints) {
if (temp_points[i + 1].flag & GP_SPOINT_SELECT) {
pt_final = &gps->points[i2];
/* Interpolate all values */
@@ -2197,7 +2293,7 @@ static int gp_stroke_subdivide_exec(bContext *C, wmOperator *op)
pt_final->time = interpf(pt->time, next->time, 0.5f);
pt_final->flag |= GP_SPOINT_SELECT;
++i2;
- };
+ }
}
}
}
diff --git a/source/blender/editors/gpencil/gpencil_intern.h b/source/blender/editors/gpencil/gpencil_intern.h
index 5c7c9b84adb..04bcea02c9b 100644
--- a/source/blender/editors/gpencil/gpencil_intern.h
+++ b/source/blender/editors/gpencil/gpencil_intern.h
@@ -40,6 +40,8 @@ struct bGPdata;
struct bGPDstroke;
struct bGPDspoint;
+struct GHash;
+
struct ARegion;
struct View2D;
struct wmOperatorType;
@@ -69,75 +71,23 @@ typedef struct GP_SpaceConversion {
float mat[4][4]; /* transform matrix on the strokes (introduced in [b770964]) */
} GP_SpaceConversion;
-
-/**
- * Check whether a given stroke segment is inside a circular brush
- *
- * \param mval The current screen-space coordinates (midpoint) of the brush
- * \param mvalo The previous screen-space coordinates (midpoint) of the brush (NOT CURRENTLY USED)
- * \param rad The radius of the brush
- *
- * \param x0, y0 The screen-space x and y coordinates of the start of the stroke segment
- * \param x1, y1 The screen-space x and y coordinates of the end of the stroke segment
- */
bool gp_stroke_inside_circle(const int mval[2], const int UNUSED(mvalo[2]),
int rad, int x0, int y0, int x1, int y1);
-
-/**
- * Init settings for stroke point space conversions
- *
- * \param[out] r_gsc The space conversion settings struct, populated with necessary params
- */
void gp_point_conversion_init(struct bContext *C, GP_SpaceConversion *r_gsc);
-/**
- * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
- *
- * \param[out] r_x The screen-space x-coordinate of the point
- * \param[out] r_y The screen-space y-coordinate of the point
- */
void gp_point_to_xy(GP_SpaceConversion *settings, struct bGPDstroke *gps, struct bGPDspoint *pt,
int *r_x, int *r_y);
-/**
- * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
- *
- * Just like gp_point_to_xy(), except the resulting coordinates are floats not ints.
- * Use this version to solve "stair-step" artifacts which may arise when roundtripping the calculations.
- *
- * \param[out] r_x The screen-space x-coordinate of the point
- * \param[out] r_y The screen-space y-coordinate of the point
- */
void gp_point_to_xy_fl(GP_SpaceConversion *gsc, bGPDstroke *gps, bGPDspoint *pt,
float *r_x, float *r_y);
-/**
- * Convert point to parent space
- *
- * \param pt Original point
- * \param diff_mat Matrix with the difference between original parent matrix
- * \param[out] r_pt Pointer to new point after apply matrix
- */
void gp_point_to_parent_space(bGPDspoint *pt, float diff_mat[4][4], bGPDspoint *r_pt);
-/**
- * Change points position relative to parent object
- */
+
void gp_apply_parent(bGPDlayer *gpl, bGPDstroke *gps);
-/**
- * Change point position relative to parent object
- */
+
void gp_apply_parent_point(bGPDlayer *gpl, bGPDspoint *pt);
-/**
- * Convert a screenspace point to a 3D Grease Pencil coordinate.
- *
- * For use with editing tools where it is easier to perform the operations in 2D,
- * and then later convert the transformed points back to 3D.
- *
- * \param screeN_co The screenspace 2D coordinates to convert to
- * \param[out] r_out The resulting 3D coordinates of the input point
- */
bool gp_point_xy_to_3d(GP_SpaceConversion *gsc, struct Scene *scene, const float screen_co[2], float r_out[3]);
/* Poll Callbacks ------------------------------------ */
@@ -155,62 +105,38 @@ int gp_brush_crt_presets_poll(bContext *C);
extern ListBase gp_strokes_copypastebuf;
+/* Build a map for converting between old colornames and destination-color-refs */
+struct GHash *gp_copybuf_validate_colormap(bGPdata *gpd);
+
/* Stroke Editing ------------------------------------ */
void gp_stroke_delete_tagged_points(bGPDframe *gpf, bGPDstroke *gps, bGPDstroke *next_stroke, int tag_flags);
-/**
- * Apply smooth to stroke point
- * \param gps Stroke to smooth
- * \param i Point index
- * \param inf Amount of smoothing to apply
- * \param affect_pressure Apply smoothing to pressure values too?
- */
bool gp_smooth_stroke(bGPDstroke *gps, int i, float inf, bool affect_pressure);
-
-/**
-* Apply smooth for strength to stroke point
-* \param gps Stroke to smooth
-* \param i Point index
-* \param inf Amount of smoothing to apply
-*/
bool gp_smooth_stroke_strength(bGPDstroke *gps, int i, float inf);
-
-/**
-* Apply smooth for thickness to stroke point (use pressure)
-* \param gps Stroke to smooth
-* \param i Point index
-* \param inf Amount of smoothing to apply
-*/
bool gp_smooth_stroke_thickness(bGPDstroke *gps, int i, float inf);
-
-/**
- * Subdivide a stroke once, by adding points at the midpoint between each pair of points
- * \param gps Stroke data
- * \param new_totpoints Total number of points (after subdividing)
- */
void gp_subdivide_stroke(bGPDstroke *gps, const int new_totpoints);
-
-/**
-* Add randomness to stroke
-* \param gps Stroke data
-* \param brush Brush data
-*/
void gp_randomize_stroke(bGPDstroke *gps, bGPDbrush *brush);
/* Layers Enums -------------------------------------- */
-struct EnumPropertyItem *ED_gpencil_layers_enum_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-struct EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const struct EnumPropertyItem *ED_gpencil_layers_enum_itemf(
+ struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop,
+ bool *r_free);
+const struct EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(
+ struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop,
+ bool *r_free);
/* Enums of GP Brushes */
-EnumPropertyItem *ED_gpencil_brushes_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
- bool *r_free);
+const EnumPropertyItem *ED_gpencil_brushes_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
+ bool *r_free);
/* Enums of GP palettes */
-EnumPropertyItem *ED_gpencil_palettes_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
- bool *r_free);
+const EnumPropertyItem *ED_gpencil_palettes_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
+ bool *r_free);
/* ***************************************************** */
/* Operator Defines */
diff --git a/source/blender/editors/gpencil/gpencil_interpolate.c b/source/blender/editors/gpencil/gpencil_interpolate.c
index 297058168a0..83e2a85db49 100644
--- a/source/blender/editors/gpencil/gpencil_interpolate.c
+++ b/source/blender/editors/gpencil/gpencil_interpolate.c
@@ -77,7 +77,6 @@
#include "ED_object.h"
#include "ED_screen.h"
#include "ED_view3d.h"
-#include "ED_screen.h"
#include "ED_space_api.h"
#include "gpencil_intern.h"
@@ -86,13 +85,14 @@
/* Core/Shared Utilities */
/* Poll callback for interpolation operators */
-static int gpencil_interpolate_poll(bContext *C)
+static int gpencil_view3d_poll(bContext *C)
{
bGPdata *gpd = CTX_data_gpencil_data(C);
bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
/* only 3D view */
- if (CTX_wm_area(C)->spacetype != SPACE_VIEW3D) {
+ ScrArea *sa = CTX_wm_area(C);
+ if (sa && sa->spacetype != SPACE_VIEW3D) {
return 0;
}
@@ -117,8 +117,8 @@ static void gp_interpolate_update_points(bGPDstroke *gps_from, bGPDstroke *gps_t
/* Interpolate all values */
interp_v3_v3v3(&pt->x, &prev->x, &next->x, factor);
- pt->pressure = interpf(prev->pressure, next->pressure, factor);
- pt->strength = interpf(prev->strength, next->strength, factor);
+ pt->pressure = interpf(prev->pressure, next->pressure, 1.0f - factor);
+ pt->strength = interpf(prev->strength, next->strength, 1.0f - factor);
CLAMP(pt->strength, GPENCIL_STRENGTH_MIN, 1.0f);
}
}
@@ -284,7 +284,9 @@ static void gp_interpolate_set_points(bContext *C, tGPDinterpolate *tgpi)
new_stroke = MEM_dupallocN(gps_from);
new_stroke->points = MEM_dupallocN(gps_from->points);
new_stroke->triangles = MEM_dupallocN(gps_from->triangles);
-
+ new_stroke->tot_triangles = 0;
+ new_stroke->flag |= GP_STROKE_RECALC_CACHES;
+
if (valid) {
/* if destination stroke is smaller, resize new_stroke to size of gps_to stroke */
if (gps_from->totpoints > gps_to->totpoints) {
@@ -302,6 +304,7 @@ static void gp_interpolate_set_points(bContext *C, tGPDinterpolate *tgpi)
new_stroke->points = MEM_recallocN(new_stroke->points, sizeof(*new_stroke->points));
new_stroke->tot_triangles = 0;
new_stroke->triangles = MEM_recallocN(new_stroke->triangles, sizeof(*new_stroke->triangles));
+ new_stroke->flag |= GP_STROKE_RECALC_CACHES;
}
/* add to strokes */
@@ -625,6 +628,7 @@ static int gpencil_interpolate_modal(bContext *C, wmOperator *op, const wmEvent
break;
}
default:
+ {
if ((event->val == KM_PRESS) && handleNumInput(C, &tgpi->num, event)) {
const float factor = tgpi->init_factor;
float value;
@@ -649,6 +653,7 @@ static int gpencil_interpolate_modal(bContext *C, wmOperator *op, const wmEvent
/* unhandled event - allow to pass through */
return OPERATOR_RUNNING_MODAL | OPERATOR_PASS_THROUGH;
}
+ }
}
/* still running... */
@@ -673,7 +678,7 @@ void GPENCIL_OT_interpolate(wmOperatorType *ot)
ot->invoke = gpencil_interpolate_invoke;
ot->modal = gpencil_interpolate_modal;
ot->cancel = gpencil_interpolate_cancel;
- ot->poll = gpencil_interpolate_poll;
+ ot->poll = gpencil_view3d_poll;
/* flags */
ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
@@ -984,7 +989,9 @@ static int gpencil_interpolate_seq_exec(bContext *C, wmOperator *op)
new_stroke = MEM_dupallocN(gps_from);
new_stroke->points = MEM_dupallocN(gps_from->points);
new_stroke->triangles = MEM_dupallocN(gps_from->triangles);
-
+ new_stroke->tot_triangles = 0;
+ new_stroke->flag |= GP_STROKE_RECALC_CACHES;
+
/* if destination stroke is smaller, resize new_stroke to size of gps_to stroke */
if (gps_from->totpoints > gps_to->totpoints) {
new_stroke->points = MEM_recallocN(new_stroke->points, sizeof(*new_stroke->points) * gps_to->totpoints);
@@ -1017,7 +1024,7 @@ void GPENCIL_OT_interpolate_sequence(wmOperatorType *ot)
/* api callbacks */
ot->exec = gpencil_interpolate_seq_exec;
- ot->poll = gpencil_interpolate_poll;
+ ot->poll = gpencil_view3d_poll;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1025,24 +1032,14 @@ void GPENCIL_OT_interpolate_sequence(wmOperatorType *ot)
/* ******************** Remove Breakdowns ************************ */
-/* Same as gpencil_interpolate_poll(),
- * except we ALSO need to have an active frame that is a breakdown
- */
static int gpencil_interpolate_reverse_poll(bContext *C)
{
- bGPdata *gpd = CTX_data_gpencil_data(C);
- bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
-
- /* only 3D view */
- if (CTX_wm_area(C)->spacetype != SPACE_VIEW3D) {
+ if (!gpencil_view3d_poll(C)) {
return 0;
}
-
- /* need data to interpolate */
- if (ELEM(NULL, gpd, gpl)) {
- return 0;
- }
-
+
+ bGPDlayer *gpl = CTX_data_active_gpencil_layer(C);
+
/* need to be on a breakdown frame */
if ((gpl->actframe == NULL) || (gpl->actframe->key_type != BEZT_KEYTYPE_BREAKDOWN)) {
CTX_wm_operator_poll_msg_set(C, "Expected current frame to be a breakdown");
diff --git a/source/blender/editors/gpencil/gpencil_ops.c b/source/blender/editors/gpencil/gpencil_ops.c
index 78e1a0dda36..3a2169798e5 100644
--- a/source/blender/editors/gpencil/gpencil_ops.c
+++ b/source/blender/editors/gpencil/gpencil_ops.c
@@ -99,8 +99,8 @@ static void ed_keymap_gpencil_general(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "GPENCIL_OT_editmode_toggle", TABKEY, KM_PRESS, 0, DKEY);
/* Pie Menu - For standard tools */
- WM_keymap_add_menu_pie(keymap, "GPENCIL_PIE_tool_palette", QKEY, KM_PRESS, 0, DKEY);
- WM_keymap_add_menu_pie(keymap, "GPENCIL_PIE_settings_palette", WKEY, KM_PRESS, 0, DKEY);
+ WM_keymap_add_menu_pie(keymap, "GPENCIL_MT_pie_tool_palette", QKEY, KM_PRESS, 0, DKEY);
+ WM_keymap_add_menu_pie(keymap, "GPENCIL_MT_pie_settings_palette", WKEY, KM_PRESS, 0, DKEY);
/* Add Blank Frame */
/* XXX: BKEY or NKEY? BKEY is easier to reach from DKEY, so we'll use that for now */
@@ -135,7 +135,7 @@ static void ed_keymap_gpencil_editing(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "GPENCIL_OT_editmode_toggle", TABKEY, KM_PRESS, 0, 0);
/* Pie Menu - For settings/tools easy access */
- WM_keymap_add_menu_pie(keymap, "GPENCIL_PIE_sculpt", EKEY, KM_PRESS, 0, DKEY);
+ WM_keymap_add_menu_pie(keymap, "GPENCIL_MT_pie_sculpt", EKEY, KM_PRESS, 0, DKEY);
/* Brush Settings */
/* NOTE: We cannot expose these in the standard keymap, as they will interfere with regular hotkeys
diff --git a/source/blender/editors/gpencil/gpencil_paint.c b/source/blender/editors/gpencil/gpencil_paint.c
index 5879306b06c..84b3ddccf77 100644
--- a/source/blender/editors/gpencil/gpencil_paint.c
+++ b/source/blender/editors/gpencil/gpencil_paint.c
@@ -46,7 +46,6 @@
#include "PIL_time.h"
-#include "BKE_main.h"
#include "BKE_paint.h"
#include "BKE_gpencil.h"
#include "BKE_context.h"
@@ -162,6 +161,8 @@ typedef struct tGPsdata {
bGPDbrush *brush; /* current drawing brush */
short straight[2]; /* 1: line horizontal, 2: line vertical, other: not defined, second element position */
int lock_axis; /* lock drawing to one axis */
+
+ short keymodifier; /* key used for invoking the operator */
} tGPsdata;
/* ------ */
@@ -484,7 +485,8 @@ static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure,
bGPdata *gpd = p->gpd;
bGPDbrush *brush = p->brush;
tGPspoint *pt;
-
+ ToolSettings *ts = p->scene->toolsettings;
+
/* check painting mode */
if (p->paintmode == GP_PAINTMODE_DRAW_STRAIGHT) {
/* straight lines only - i.e. only store start and end point in buffer */
@@ -636,7 +638,7 @@ static short gp_stroke_addpoint(tGPsdata *p, const int mval[2], float pressure,
View3D *v3d = p->sa->spacedata.first;
view3d_region_operator_needs_opengl(p->win, p->ar);
- ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
+ ED_view3d_autodist_init(p->scene, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
}
/* convert screen-coordinates to appropriate coordinates (and store them) */
@@ -756,7 +758,7 @@ static void gp_stroke_newfrombuffer(tGPsdata *p)
int i, totelem;
/* since strokes are so fine, when using their depth we need a margin otherwise they might get missed */
- int depth_margin = (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 4 : 0;
+ int depth_margin = (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 4 : 0;
/* get total number of points to allocate space for
* - drawing straight-lines only requires the endpoints
@@ -893,7 +895,7 @@ static void gp_stroke_newfrombuffer(tGPsdata *p)
copy_v2_v2_int(mval, &ptc->x);
if ((ED_view3d_autodist_depth(p->ar, mval, depth_margin, depth_arr + i) == 0) &&
- (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
+ (i && (ED_view3d_autodist_depth_seg(p->ar, mval, mval_prev, depth_margin + 1, depth_arr + i) == 0)))
{
interp_depth = true;
}
@@ -910,7 +912,7 @@ static void gp_stroke_newfrombuffer(tGPsdata *p)
depth_arr[i] = 0.9999f;
}
else {
- if (p->gpd->flag & GP_DATA_DEPTH_STROKE_ENDPOINTS) {
+ if (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE_ENDPOINTS) {
/* remove all info between the valid endpoints */
int first_valid = 0;
int last_valid = 0;
@@ -1004,9 +1006,9 @@ static void gp_stroke_newfrombuffer(tGPsdata *p)
BLI_strncpy(gps->colorname, palcolor->info, sizeof(gps->colorname));
/* add stroke to frame, usually on tail of the listbase, but if on back is enabled the stroke is added on listbase head
- * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
- * when drawing the background
- */
+ * because the drawing order is inverse and the head stroke is the first to draw. This is very useful for artist
+ * when drawing the background
+ */
if ((ts->gpencil_flags & GP_TOOL_FLAG_PAINT_ONBACK) && (p->paintmode != GP_PAINTMODE_DRAW_POLY)) {
BLI_addhead(&p->gpf->strokes, gps);
}
@@ -1794,6 +1796,7 @@ static void gp_paint_initstroke(tGPsdata *p, eGPencil_PaintModes paintmode)
/* finish off a stroke (clears buffer, but doesn't finish the paint operation) */
static void gp_paint_strokeend(tGPsdata *p)
{
+ ToolSettings *ts = p->scene->toolsettings;
/* for surface sketching, need to set the right OpenGL context stuff so that
* the conversions will project the values correctly...
*/
@@ -1802,7 +1805,7 @@ static void gp_paint_strokeend(tGPsdata *p)
/* need to restore the original projection settings before packing up */
view3d_region_operator_needs_opengl(p->win, p->ar);
- ED_view3d_autodist_init(p->scene, p->ar, v3d, (p->gpd->flag & GP_DATA_DEPTH_STROKE) ? 1 : 0);
+ ED_view3d_autodist_init(p->scene, p->ar, v3d, (ts->gpencil_v3d_align & GP_PROJECT_DEPTH_STROKE) ? 1 : 0);
}
/* check if doing eraser or not */
@@ -1938,7 +1941,7 @@ static void gpencil_draw_cancel(bContext *C, wmOperator *op)
/* ------------------------------- */
-static int gpencil_draw_init(bContext *C, wmOperator *op)
+static int gpencil_draw_init(bContext *C, wmOperator *op, const wmEvent *event)
{
tGPsdata *p;
eGPencil_PaintModes paintmode = RNA_enum_get(op->ptr, "mode");
@@ -1957,6 +1960,13 @@ static int gpencil_draw_init(bContext *C, wmOperator *op)
gpencil_draw_exit(C, op);
return 0;
}
+
+ if (event != NULL) {
+ p->keymodifier = event->keymodifier;
+ }
+ else {
+ p->keymodifier = -1;
+ }
/* everything is now setup ok */
return 1;
@@ -2198,7 +2208,7 @@ static int gpencil_draw_exec(bContext *C, wmOperator *op)
/* printf("GPencil - Starting Re-Drawing\n"); */
/* try to initialize context data needed while drawing */
- if (!gpencil_draw_init(C, op)) {
+ if (!gpencil_draw_init(C, op, NULL)) {
if (op->customdata) MEM_freeN(op->customdata);
/* printf("\tGP - no valid data\n"); */
return OPERATOR_CANCELLED;
@@ -2273,7 +2283,7 @@ static int gpencil_draw_invoke(bContext *C, wmOperator *op, const wmEvent *event
printf("GPencil - Starting Drawing\n");
/* try to initialize context data needed while drawing */
- if (!gpencil_draw_init(C, op)) {
+ if (!gpencil_draw_init(C, op, event)) {
if (op->customdata)
MEM_freeN(op->customdata);
if (G.debug & G_DEBUG)
@@ -2436,7 +2446,7 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
* is essential for ensuring that they can quickly return to that view
*/
}
- else if ((ELEM(event->type, DKEY)) && (event->val == KM_RELEASE)) {
+ else if ((ELEM(event->type, p->keymodifier)) && (event->val == KM_RELEASE)) {
/* enable continuous if release D key in mid drawing */
p->scene->toolsettings->gpencil_flags |= GP_TOOL_FLAG_PAINTSESSIONS_ON;
}
@@ -2724,7 +2734,7 @@ static int gpencil_draw_modal(bContext *C, wmOperator *op, const wmEvent *event)
/* ------------------------------- */
-static EnumPropertyItem prop_gpencil_drawmodes[] = {
+static const EnumPropertyItem prop_gpencil_drawmodes[] = {
{GP_PAINTMODE_DRAW, "DRAW", 0, "Draw Freehand", "Draw freehand stroke(s)"},
{GP_PAINTMODE_DRAW_STRAIGHT, "DRAW_STRAIGHT", 0, "Draw Straight Lines", "Draw straight line segment(s)"},
{GP_PAINTMODE_DRAW_POLY, "DRAW_POLY", 0, "Draw Poly Line", "Click to place endpoints of straight line segments (connected)"},
@@ -2734,6 +2744,8 @@ static EnumPropertyItem prop_gpencil_drawmodes[] = {
void GPENCIL_OT_draw(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
/* identifiers */
ot->name = "Grease Pencil Draw";
ot->idname = "GPENCIL_OT_draw";
@@ -2751,8 +2763,11 @@ void GPENCIL_OT_draw(wmOperatorType *ot)
/* settings for drawing */
ot->prop = RNA_def_enum(ot->srna, "mode", prop_gpencil_drawmodes, 0, "Mode", "Way to interpret mouse movements");
- RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+
+ prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
/* NOTE: wait for input is enabled by default, so that all UI code can work properly without needing users to know about this */
- RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
+ prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "Wait for first click instead of painting immediately");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
diff --git a/source/blender/editors/gpencil/gpencil_select.c b/source/blender/editors/gpencil/gpencil_select.c
index 45dbde80284..dc3483163bf 100644
--- a/source/blender/editors/gpencil/gpencil_select.c
+++ b/source/blender/editors/gpencil/gpencil_select.c
@@ -37,7 +37,7 @@
#include "BLI_blenlib.h"
#include "BLI_ghash.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_utildefines.h"
#include "BLI_math_vector.h"
@@ -371,7 +371,7 @@ static int gpencil_select_grouped_exec(bContext *C, wmOperator *op)
void GPENCIL_OT_select_grouped(wmOperatorType *ot)
{
- static EnumPropertyItem prop_select_grouped_types[] = {
+ static const EnumPropertyItem prop_select_grouped_types[] = {
{GP_SEL_SAME_LAYER, "LAYER", 0, "Layer", "Shared layers"},
{GP_SEL_SAME_COLOR, "COLOR", 0, "Color", "Shared colors"},
{0, NULL, 0, NULL, NULL}
@@ -769,8 +769,7 @@ static int gpencil_circle_select_exec(bContext *C, wmOperator *op)
const int my = RNA_int_get(op->ptr, "y");
const int radius = RNA_int_get(op->ptr, "radius");
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
+ bool select = !RNA_boolean_get(op->ptr, "deselect");
GP_SpaceConversion gsc = {NULL};
rcti rect = {0}; /* for bounding rect around circle (for quicky intersection testing) */
@@ -830,10 +829,7 @@ void GPENCIL_OT_select_circle(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
+ WM_operator_properties_gesture_circle_select(ot);
}
/* ********************************************** */
@@ -843,8 +839,7 @@ static int gpencil_border_select_exec(bContext *C, wmOperator *op)
{
ScrArea *sa = CTX_wm_area(C);
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
const bool extend = RNA_boolean_get(op->ptr, "extend");
GP_SpaceConversion gsc = {NULL};
@@ -936,10 +931,10 @@ void GPENCIL_OT_select_border(wmOperatorType *ot)
ot->idname = "GPENCIL_OT_select_border";
/* callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = gpencil_border_select_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = gpencil_select_poll;
@@ -947,7 +942,7 @@ void GPENCIL_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/* ********************************************** */
@@ -1012,7 +1007,7 @@ static int gpencil_lasso_select_exec(bContext *C, wmOperator *op)
}
/* test if in lasso boundbox + within the lasso noose */
if ((!ELEM(V2D_IS_CLIPPED, x0, y0)) && BLI_rcti_isect_pt(&rect, x0, y0) &&
- BLI_lasso_is_point_inside(mcords, mcords_tot, x0, y0, INT_MAX))
+ BLI_lasso_is_point_inside(mcords, mcords_tot, x0, y0, INT_MAX))
{
if (select) {
pt->flag |= GP_SPOINT_SELECT;
@@ -1056,9 +1051,8 @@ void GPENCIL_OT_select_lasso(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
+ /* properties */
+ WM_operator_properties_gesture_lasso_select(ot);
}
/* ********************************************** */
diff --git a/source/blender/editors/gpencil/gpencil_undo.c b/source/blender/editors/gpencil/gpencil_undo.c
index 7a9ad2b32c0..202d7630ae0 100644
--- a/source/blender/editors/gpencil/gpencil_undo.c
+++ b/source/blender/editors/gpencil/gpencil_undo.c
@@ -45,7 +45,6 @@
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_gpencil.h"
-#include "BKE_main.h"
#include "ED_gpencil.h"
diff --git a/source/blender/editors/gpencil/gpencil_utils.c b/source/blender/editors/gpencil/gpencil_utils.c
index 76e85f20c36..672c87ed6fd 100644
--- a/source/blender/editors/gpencil/gpencil_utils.c
+++ b/source/blender/editors/gpencil/gpencil_utils.c
@@ -307,7 +307,8 @@ int gp_active_palettecolor_poll(bContext *C)
/* NOTE: These include an option to create a new layer and use that... */
/* Just existing layers */
-EnumPropertyItem *ED_gpencil_layers_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *ED_gpencil_layers_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
bGPdata *gpd = CTX_data_gpencil_data(C);
bGPDlayer *gpl;
@@ -340,7 +341,8 @@ EnumPropertyItem *ED_gpencil_layers_enum_itemf(bContext *C, PointerRNA *UNUSED(p
}
/* Existing + Option to add/use new layer */
-EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
bGPdata *gpd = CTX_data_gpencil_data(C);
bGPDlayer *gpl;
@@ -391,7 +393,16 @@ EnumPropertyItem *ED_gpencil_layers_with_new_enum_itemf(bContext *C, PointerRNA
/* ******************************************************** */
/* Brush Tool Core */
-/* Check if part of stroke occurs within last segment drawn by eraser */
+/**
+ * Check whether a given stroke segment is inside a circular brush
+ *
+ * \param mval The current screen-space coordinates (midpoint) of the brush
+ * \param mvalo The previous screen-space coordinates (midpoint) of the brush (NOT CURRENTLY USED)
+ * \param rad The radius of the brush
+ *
+ * \param x0, y0 The screen-space x and y coordinates of the start of the stroke segment
+ * \param x1, y1 The screen-space x and y coordinates of the end of the stroke segment
+ */
bool gp_stroke_inside_circle(const int mval[2], const int UNUSED(mvalo[2]),
int rad, int x0, int y0, int x1, int y1)
{
@@ -502,7 +513,11 @@ bGPDpalettecolor *ED_gpencil_stroke_getcolor(bGPdata *gpd, bGPDstroke *gps)
/* ******************************************************** */
/* Space Conversion */
-/* Init handling for space-conversion function (from passed-in parameters) */
+/**
+ * Init settings for stroke point space conversions
+ *
+ * \param r_gsc: [out] The space conversion settings struct, populated with necessary params
+ */
void gp_point_conversion_init(bContext *C, GP_SpaceConversion *r_gsc)
{
ScrArea *sa = CTX_wm_area(C);
@@ -538,7 +553,13 @@ void gp_point_conversion_init(bContext *C, GP_SpaceConversion *r_gsc)
}
}
-/* convert point to parent space */
+/**
+ * Convert point to parent space
+ *
+ * \param pt Original point
+ * \param diff_mat Matrix with the difference between original parent matrix
+ * \param[out] r_pt Pointer to new point after apply matrix
+ */
void gp_point_to_parent_space(bGPDspoint *pt, float diff_mat[4][4], bGPDspoint *r_pt)
{
float fpt[3];
@@ -547,7 +568,9 @@ void gp_point_to_parent_space(bGPDspoint *pt, float diff_mat[4][4], bGPDspoint *
copy_v3_v3(&r_pt->x, fpt);
}
-/* Change position relative to parent object */
+/**
+ * Change points position relative to parent object
+ */
void gp_apply_parent(bGPDlayer *gpl, bGPDstroke *gps)
{
bGPDspoint *pt;
@@ -568,7 +591,9 @@ void gp_apply_parent(bGPDlayer *gpl, bGPDstroke *gps)
}
}
-/* Change point position relative to parent object */
+/**
+ * Change point position relative to parent object
+ */
void gp_apply_parent_point(bGPDlayer *gpl, bGPDspoint *pt)
{
/* undo matrix */
@@ -583,8 +608,13 @@ void gp_apply_parent_point(bGPDlayer *gpl, bGPDspoint *pt)
copy_v3_v3(&pt->x, fpt);
}
-/* Convert Grease Pencil points to screen-space values
- * WARNING: This assumes that the caller has already checked whether the stroke in question can be drawn
+/**
+ * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
+ *
+ * \param[out] r_x The screen-space x-coordinate of the point
+ * \param[out] r_y The screen-space y-coordinate of the point
+ *
+ * \warning This assumes that the caller has already checked whether the stroke in question can be drawn.
*/
void gp_point_to_xy(GP_SpaceConversion *gsc, bGPDstroke *gps, bGPDspoint *pt,
int *r_x, int *r_y)
@@ -628,8 +658,16 @@ void gp_point_to_xy(GP_SpaceConversion *gsc, bGPDstroke *gps, bGPDspoint *pt,
}
}
-/* Convert Grease Pencil points to screen-space values (as floats)
- * WARNING: This assumes that the caller has already checked whether the stroke in question can be drawn
+/**
+ * Convert a Grease Pencil coordinate (i.e. can be 2D or 3D) to screenspace (2D)
+ *
+ * Just like gp_point_to_xy(), except the resulting coordinates are floats not ints.
+ * Use this version to solve "stair-step" artifacts which may arise when roundtripping the calculations.
+ *
+ * \param r_x: [out] The screen-space x-coordinate of the point
+ * \param r_y: [out] The screen-space y-coordinate of the point
+ *
+ * \warning This assumes that the caller has already checked whether the stroke in question can be drawn
*/
void gp_point_to_xy_fl(GP_SpaceConversion *gsc, bGPDstroke *gps, bGPDspoint *pt,
float *r_x, float *r_y)
@@ -688,6 +726,12 @@ void gp_point_to_xy_fl(GP_SpaceConversion *gsc, bGPDstroke *gps, bGPDspoint *pt,
/**
* Project screenspace coordinates to 3D-space
*
+ * For use with editing tools where it is easier to perform the operations in 2D,
+ * and then later convert the transformed points back to 3D.
+ *
+ * \param screen_co: The screenspace 2D coordinates to convert to
+ * \param r_out: The resulting 3D coordinates of the input point
+ *
* \note We include this as a utility function, since the standard method
* involves quite a few steps, which are invariably always the same
* for all GPencil operations. So, it's nicer to just centralize these.
@@ -722,7 +766,7 @@ bool gp_point_xy_to_3d(GP_SpaceConversion *gsc, Scene *scene, const float screen
}
/**
- * Apply smooth to stroke point
+ * Apply smooth to stroke point
* \param gps Stroke to smooth
* \param i Point index
* \param inf Amount of smoothing to apply
@@ -830,8 +874,8 @@ bool gp_smooth_stroke_strength(bGPDstroke *gps, int i, float inf)
ptc = &gps->points[after];
/* the optimal value is the corresponding to the interpolation of the strength
- * at the distance of point b
- */
+ * at the distance of point b
+ */
const float fac = line_point_factor_v3(&ptb->x, &pta->x, &ptc->x);
const float optimal = (1.0f - fac) * pta->strength + fac * ptc->strength;
@@ -1056,7 +1100,7 @@ bool ED_gpencil_stroke_minmax(
}
/* Dynamic Enums of GP Brushes */
-EnumPropertyItem *ED_gpencil_brushes_enum_itemf(
+const EnumPropertyItem *ED_gpencil_brushes_enum_itemf(
bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
bool *r_free)
{
@@ -1091,7 +1135,7 @@ EnumPropertyItem *ED_gpencil_brushes_enum_itemf(
}
/* Dynamic Enums of GP Palettes */
-EnumPropertyItem *ED_gpencil_palettes_enum_itemf(
+const EnumPropertyItem *ED_gpencil_palettes_enum_itemf(
bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
bool *r_free)
{
diff --git a/source/blender/editors/include/ED_anim_api.h b/source/blender/editors/include/ED_anim_api.h
index 4a4ab832b28..ab02fd1ccc8 100644
--- a/source/blender/editors/include/ED_anim_api.h
+++ b/source/blender/editors/include/ED_anim_api.h
@@ -124,6 +124,15 @@ typedef struct bAnimListElem {
void *key_data; /* motion data - mostly F-Curves, but can be other types too */
+ /* NOTE: id here is the "IdAdtTemplate"-style datablock (e.g. Object, Material, Texture, NodeTree)
+ * from which evaluation of the RNA-paths takes place. It's used to figure out how deep
+ * channels should be nested (e.g. for Textures/NodeTrees) in the tree, and allows property
+ * lookups (e.g. for sliders and for inserting keyframes) to work. If we had instead used
+ * bAction or something similar, none of this would be possible: although it's trivial
+ * to use an IdAdtTemplate type to find the source action a channel (e.g. F-Curve) comes from
+ * (i.e. in the AnimEditors, it *must* be the active action, as only that can be edited),
+ * it's impossible to go the other way (i.e. one action may be used in multiple places).
+ */
struct ID *id; /* ID block that channel is attached to */
struct AnimData *adt; /* source of the animation data attached to ID block (for convenience) */
@@ -256,7 +265,7 @@ typedef enum eAnimFilter_Flags {
ANIMFILTER_TMP_PEEK = (1 << 30),
/* ignore ONLYSEL flag from filterflag, (internal use only!) */
- ANIMFILTER_TMP_IGNORE_ONLYSEL = (1 << 31)
+ ANIMFILTER_TMP_IGNORE_ONLYSEL = (1u << 31)
} eAnimFilter_Flags;
/* ---------- Flag Checking Macros ------------ */
@@ -563,7 +572,7 @@ bool ANIM_fmodifiers_copy_to_buf(ListBase *modifiers, bool active);
/* 'Paste' the F-Modifier(s) from the buffer to the specified list
* - replace: free all the existing modifiers to leave only the pasted ones
*/
-bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace);
+bool ANIM_fmodifiers_paste_from_buf(ListBase *modifiers, bool replace, struct FCurve *curve);
/* ************************************************* */
/* ASSORTED TOOLS */
diff --git a/source/blender/editors/include/ED_armature.h b/source/blender/editors/include/ED_armature.h
index 7ad61671b1b..567e477ec6c 100644
--- a/source/blender/editors/include/ED_armature.h
+++ b/source/blender/editors/include/ED_armature.h
@@ -49,6 +49,7 @@ struct Scene;
struct ViewContext;
struct wmKeyConfig;
struct wmOperator;
+struct UndoType;
typedef struct EditBone {
struct EditBone *next, *prev;
@@ -72,12 +73,15 @@ typedef struct EditBone {
float dist, weight;
float xwidth, length, zwidth; /* put them in order! transform uses this as scale */
- float ease1, ease2;
float rad_head, rad_tail;
+
+ /* Bendy-Bone parameters */
float roll1, roll2;
float curveOutX, curveOutY;
float curveInX, curveInY;
+ float ease1, ease2;
float scaleIn, scaleOut;
+
float oldlength; /* for envelope scaling */
short segments;
@@ -125,28 +129,31 @@ void ED_keymap_armature(struct wmKeyConfig *keyconf);
void ED_armature_from_edit(struct bArmature *arm);
void ED_armature_to_edit(struct bArmature *arm);
void ED_armature_edit_free(struct bArmature *arm);
-void ED_armature_ebone_listbase_temp_clear(struct ListBase *lb);
-void ED_armature_deselect_all(struct Object *obedit);
-void ED_armature_deselect_all_visible(struct Object *obedit);
+void ED_armature_edit_deselect_all(struct Object *obedit);
+void ED_armature_edit_deselect_all_visible(struct Object *obedit);
-int ED_do_pose_selectbuffer(struct Scene *scene, struct Base *base, unsigned int *buffer,
- short hits, bool extend, bool deselect, bool toggle, bool do_nearest);
-bool ED_armature_select_pick(struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle);
+bool ED_armature_pose_select_pick_with_buffer(
+ struct Scene *scene, struct Base *base, const unsigned int *buffer, short hits,
+ bool extend, bool deselect, bool toggle, bool do_nearest);
+bool ED_armature_edit_select_pick(
+ struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle);
int join_armature_exec(struct bContext *C, struct wmOperator *op);
-struct Bone *get_indexed_bone(struct Object *ob, int index);
-float ED_rollBoneToVector(EditBone *bone, const float new_up_axis[3], const bool axis_only);
-EditBone *ED_armature_bone_find_name(const ListBase *edbo, const char *name);
-EditBone *ED_armature_bone_get_mirrored(const struct ListBase *edbo, EditBone *ebo);
-void ED_armature_sync_selection(struct ListBase *edbo);
-void ED_armature_validate_active(struct bArmature *arm);
+struct Bone *ED_armature_bone_find_index(struct Object *ob, int index);
+float ED_armature_ebone_roll_to_vector(const EditBone *bone, const float new_up_axis[3], const bool axis_only);
+EditBone *ED_armature_ebone_find_name(const struct ListBase *edbo, const char *name);
+EditBone *ED_armature_ebone_get_mirrored(const struct ListBase *edbo, EditBone *ebo);
+void ED_armature_edit_sync_selection(struct ListBase *edbo);
+void ED_armature_edit_validate_active(struct bArmature *arm);
-EditBone *ED_armature_edit_bone_add_primitive(struct Object *obedit_arm, float length, bool view_aligned);
-EditBone *ED_armature_edit_bone_add(struct bArmature *arm, const char *name);
-void ED_armature_edit_bone_remove(struct bArmature *arm, EditBone *exBone);
+EditBone *ED_armature_ebone_add_primitive(struct Object *obedit_arm, float length, bool view_aligned);
+EditBone *ED_armature_ebone_add(struct bArmature *arm, const char *name);
+
+void ED_armature_ebone_remove_ex(struct bArmature *arm, EditBone *exBone, bool clear_connected);
+void ED_armature_ebone_remove(struct bArmature *arm, EditBone *exBone);
bool ED_armature_ebone_is_child_recursive(EditBone *ebone_parent, EditBone *ebone_child);
-EditBone *ED_armature_bone_find_shared_parent(EditBone *ebone_child[], const unsigned int ebone_child_tot);
+EditBone *ED_armature_ebone_find_shared_parent(EditBone *ebone_child[], const unsigned int ebone_child_tot);
void ED_armature_ebone_to_mat3(EditBone *ebone, float mat[3][3]);
void ED_armature_ebone_to_mat4(EditBone *ebone, float mat[4][4]);
@@ -154,26 +161,24 @@ void ED_armature_ebone_to_mat4(EditBone *ebone, float mat[4][4]);
void ED_armature_ebone_from_mat3(EditBone *ebone, float mat[3][3]);
void ED_armature_ebone_from_mat4(EditBone *ebone, float mat[4][4]);
-void transform_armature_mirror_update(struct Object *obedit);
+void ED_armature_edit_transform_mirror_update(struct Object *obedit);
void ED_armature_origin_set(struct Scene *scene, struct Object *ob, float cursor[3], int centermode, int around);
-void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4]);
-void ED_armature_apply_transform(struct Object *ob, float mat[4][4]);
-void ED_armature_transform(struct bArmature *arm, float mat[4][4]);
+void ED_armature_transform_bones(struct bArmature *arm, float mat[4][4], const bool do_props);
+void ED_armature_transform_apply(struct Object *ob, float mat[4][4], const bool do_props);
+void ED_armature_transform(struct bArmature *arm, float mat[4][4], const bool do_props);
#define ARM_GROUPS_NAME 1
#define ARM_GROUPS_ENVELOPE 2
#define ARM_GROUPS_AUTO 3
-void create_vgroups_from_armature(struct ReportList *reports, struct Scene *scene, struct Object *ob,
+void ED_object_vgroup_calc_from_armature(struct ReportList *reports, struct Scene *scene, struct Object *ob,
struct Object *par, const int mode, const bool mirror);
/* if bone is already in list, pass it as param to ignore it */
-void unique_editbone_name(struct ListBase *ebones, char *name, EditBone *bone);
+void ED_armature_ebone_unique_name(struct ListBase *ebones, char *name, EditBone *bone);
void ED_armature_bone_rename(struct bArmature *arm, const char *oldnamep, const char *newnamep);
-void ED_armature_bones_flip_names(struct bArmature *arm, struct ListBase *bones_names);
-
-void undo_push_armature(struct bContext *C, const char *name);
+void ED_armature_bones_flip_names(struct bArmature *arm, struct ListBase *bones_names, const bool do_strip_numbers);
/* low level selection functions which handle */
int ED_armature_ebone_selectflag_get(const EditBone *ebone);
@@ -182,10 +187,20 @@ void ED_armature_ebone_select_set(EditBone *ebone, bool select);
void ED_armature_ebone_selectflag_enable(EditBone *ebone, int flag);
void ED_armature_ebone_selectflag_disable(EditBone *ebone, int flag);
+/* editarmature_undo.c */
+void ED_armature_undosys_type(struct UndoType *ut);
+
+/* armature_utils.c */
+void ED_armature_ebone_listbase_temp_clear(struct ListBase *lb);
+void ED_armature_ebone_listbase_free(struct ListBase *lb);
+void ED_armature_ebone_listbase_copy(struct ListBase *lb_dst, struct ListBase *lb_src);
+
/* poseobject.c */
-void ED_armature_exit_posemode(struct bContext *C, struct Base *base);
-void ED_armature_enter_posemode(struct bContext *C, struct Base *base);
-void ED_pose_de_selectall(struct Object *ob, int select_mode, const bool ignore_visibility);
+bool ED_object_posemode_exit_ex(struct Object *ob);
+bool ED_object_posemode_exit(struct bContext *C, struct Object *ob);
+bool ED_object_posemode_enter_ex(struct Object *ob);
+bool ED_object_posemode_enter(struct bContext *C, struct Object *ob);
+void ED_pose_deselect_all(struct Object *ob, int select_mode, const bool ignore_visibility);
void ED_pose_bone_select(struct Object *ob, struct bPoseChannel *pchan, bool select);
void ED_pose_recalculate_paths(struct Scene *scene, struct Object *ob);
struct Object *ED_pose_object_from_context(struct bContext *C);
@@ -211,7 +226,7 @@ void BDR_drawSketch(const struct bContext *vc);
int BDR_drawSketchNames(struct ViewContext *vc);
/* meshlaplacian.c */
-void mesh_deform_bind(struct Scene *scene,
+void ED_mesh_deform_bind_callback(struct Scene *scene,
struct MeshDeformModifierData *mmd,
struct DerivedMesh *cagedm,
float *vertexcos, int totvert, float cagemat[4][4]);
diff --git a/source/blender/editors/include/ED_clip.h b/source/blender/editors/include/ED_clip.h
index 5f8ebd87d19..91f8b39f7b9 100644
--- a/source/blender/editors/include/ED_clip.h
+++ b/source/blender/editors/include/ED_clip.h
@@ -63,7 +63,7 @@ int ED_space_clip_get_clip_frame_number(struct SpaceClip *sc);
struct ImBuf *ED_space_clip_get_buffer(struct SpaceClip *sc);
struct ImBuf *ED_space_clip_get_stable_buffer(struct SpaceClip *sc, float loc[2], float *scale, float *angle);
-bool ED_space_clip_color_sample(struct Scene *scene, struct SpaceClip *sc, struct ARegion *ar, int mval[2], float r_col[3]);
+bool ED_space_clip_color_sample(struct SpaceClip *sc, struct ARegion *ar, int mval[2], float r_col[3]);
void ED_clip_update_frame(const struct Main *mainp, int cfra);
bool ED_clip_view_selection(const struct bContext *C, struct ARegion *ar, bool fit);
diff --git a/source/blender/editors/include/ED_curve.h b/source/blender/editors/include/ED_curve.h
index 859d45e9c86..da726cb8000 100644
--- a/source/blender/editors/include/ED_curve.h
+++ b/source/blender/editors/include/ED_curve.h
@@ -41,6 +41,7 @@ struct Curve;
struct EditNurb;
struct BezTriple;
struct BPoint;
+struct UndoType;
/* curve_ops.c */
void ED_operatortypes_curve(void);
@@ -48,8 +49,7 @@ void ED_operatormacros_curve(void);
void ED_keymap_curve(struct wmKeyConfig *keyconf);
/* editcurve.c */
-void undo_push_curve(struct bContext *C, const char *name);
-ListBase *object_editcurve_get(struct Object *ob);
+struct ListBase *object_editcurve_get(struct Object *ob);
void ED_curve_editnurb_load(struct Object *obedit);
void ED_curve_editnurb_make(struct Object *obedit);
@@ -72,6 +72,9 @@ void ED_curve_deselect_all(struct EditNurb *editnurb);
void ED_curve_select_all(struct EditNurb *editnurb);
void ED_curve_select_swap(struct EditNurb *editnurb, bool hide_handles);
+/* editcurve_undo.c */
+void ED_curve_undosys_type(struct UndoType *ut);
+
/* editfont.c */
void ED_curve_editfont_load(struct Object *obedit);
void ED_curve_editfont_make(struct Object *obedit);
@@ -89,7 +92,8 @@ bool ED_curve_active_center(struct Curve *cu, float center[3]);
bool ED_curve_editfont_select_pick(struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle);
/* editfont_undo.c */
-void undo_push_font(struct bContext *C, const char *name);
+void ED_font_undosys_type(struct UndoType *ut);
+
#if 0
/* debug only */
diff --git a/source/blender/editors/include/ED_image.h b/source/blender/editors/include/ED_image.h
index 283113f93d6..9de550a20ce 100644
--- a/source/blender/editors/include/ED_image.h
+++ b/source/blender/editors/include/ED_image.h
@@ -46,7 +46,7 @@ void ED_space_image_set(struct SpaceImage *sima, struct Scene *scene, s
struct Mask *ED_space_image_get_mask(struct SpaceImage *sima);
void ED_space_image_set_mask(struct bContext *C, struct SpaceImage *sima, struct Mask *mask);
-bool ED_space_image_color_sample(struct Scene *scene, struct SpaceImage *sima, struct ARegion *ar, int mval[2], float r_col[3]);
+bool ED_space_image_color_sample(struct SpaceImage *sima, struct ARegion *ar, int mval[2], float r_col[3]);
struct ImBuf *ED_space_image_acquire_buffer(struct SpaceImage *sima, void **r_lock);
void ED_space_image_release_buffer(struct SpaceImage *sima, struct ImBuf *ibuf, void *lock);
bool ED_space_image_has_buffer(struct SpaceImage *sima);
diff --git a/source/blender/editors/include/ED_keyframing.h b/source/blender/editors/include/ED_keyframing.h
index 07cdff687a3..4e3c92f0dc4 100644
--- a/source/blender/editors/include/ED_keyframing.h
+++ b/source/blender/editors/include/ED_keyframing.h
@@ -54,6 +54,7 @@ struct PointerRNA;
struct PropertyRNA;
struct EnumPropertyItem;
+#include "DNA_anim_types.h"
#include "RNA_types.h"
/* ************ Keyframing Management **************** */
@@ -91,14 +92,14 @@ void update_autoflags_fcurve(struct FCurve *fcu, struct bContext *C, struct Repo
* Use this when validation of necessary animation data isn't necessary as it already
* exists, and there is a beztriple that can be directly copied into the array.
*/
-int insert_bezt_fcurve(struct FCurve *fcu, const struct BezTriple *bezt, short flag);
+int insert_bezt_fcurve(struct FCurve *fcu, const struct BezTriple *bezt, eInsertKeyFlags flag);
/* Main Keyframing API call:
* Use this when validation of necessary animation data isn't necessary as it
* already exists. It will insert a keyframe using the current value being keyframed.
* Returns the index at which a keyframe was added (or -1 if failed)
*/
-int insert_vert_fcurve(struct FCurve *fcu, float x, float y, char keytype, short flag);
+int insert_vert_fcurve(struct FCurve *fcu, float x, float y, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag);
/* -------- */
@@ -106,7 +107,7 @@ int insert_vert_fcurve(struct FCurve *fcu, float x, float y, char keytype, short
* Use this to insert a keyframe using the current value being keyframed, in the
* nominated F-Curve (no creation of animation data performed). Returns success.
*/
-bool insert_keyframe_direct(struct ReportList *reports, struct PointerRNA ptr, struct PropertyRNA *prop, struct FCurve *fcu, float cfra, char keytype, short flag);
+bool insert_keyframe_direct(struct ReportList *reports, struct PointerRNA ptr, struct PropertyRNA *prop, struct FCurve *fcu, float cfra, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag);
/* -------- */
@@ -114,12 +115,12 @@ bool insert_keyframe_direct(struct ReportList *reports, struct PointerRNA ptr, s
* Use this to create any necessary animation data, and then insert a keyframe
* using the current value being keyframed, in the relevant place. Returns success.
*/
-short insert_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, char keytype, short flag);
+short insert_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, eBezTriple_KeyframeType keytype, eInsertKeyFlags flag);
/* Main Keyframing API call:
* Use this to delete keyframe on current frame for relevant channel. Will perform checks just in case.
*/
-short delete_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, short flag);
+short delete_keyframe(struct ReportList *reports, struct ID *id, struct bAction *act, const char group[], const char rna_path[], int array_index, float cfra, eInsertKeyFlags flag);
/* ************ Keying Sets ********************** */
@@ -222,7 +223,7 @@ int ANIM_scene_get_keyingset_index(struct Scene *scene, struct KeyingSet *ks);
struct KeyingSet *ANIM_get_keyingset_for_autokeying(struct Scene *scene, const char *tranformKSName);
/* Dynamically populate an enum of Keying Sets */
-struct EnumPropertyItem *ANIM_keying_sets_enum_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const struct EnumPropertyItem *ANIM_keying_sets_enum_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
/* Check if KeyingSet can be used in the current context */
bool ANIM_keyingset_context_ok_poll(struct bContext *C, struct KeyingSet *ks);
diff --git a/source/blender/editors/include/ED_lattice.h b/source/blender/editors/include/ED_lattice.h
index 30d66577770..b30929f5307 100644
--- a/source/blender/editors/include/ED_lattice.h
+++ b/source/blender/editors/include/ED_lattice.h
@@ -4,7 +4,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
@@ -18,7 +18,6 @@
* The Original Code is Copyright (C) 2008 Blender Foundation.
* All rights reserved.
*
- *
* Contributor(s): Blender Foundation
*
* ***** END GPL LICENSE BLOCK *****
@@ -31,10 +30,19 @@
#ifndef __ED_LATTICE_H__
#define __ED_LATTICE_H__
+struct wmKeyConfig;
+struct UndoType;
struct Object;
-void ED_lattice_editlatt_free(struct Object *ob);
-void ED_lattice_editlatt_make(struct Object *obedit);
-void ED_lattice_editlatt_load(struct Object *obedit);
+/* lattice_ops.c */
+void ED_operatortypes_lattice(void);
+void ED_keymap_lattice(struct wmKeyConfig *keyconf);
+
+/* editlattice_select.c */
+void ED_lattice_flags_set(struct Object *obedit, int flag);
+bool ED_lattice_select_pick(struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle);
+
+/* editlattice_undo.c */
+void ED_lattice_undosys_type(struct UndoType *ut);
#endif /* __ED_LATTICE_H__ */
diff --git a/source/blender/editors/include/ED_mball.h b/source/blender/editors/include/ED_mball.h
index 232d7d1d234..9982c87a764 100644
--- a/source/blender/editors/include/ED_mball.h
+++ b/source/blender/editors/include/ED_mball.h
@@ -34,6 +34,7 @@
struct bContext;
struct Object;
struct wmKeyConfig;
+struct UndoType;
void ED_operatortypes_metaball(void);
void ED_operatormacros_metaball(void);
@@ -47,6 +48,7 @@ void ED_mball_editmball_free(struct Object *obedit);
void ED_mball_editmball_make(struct Object *obedit);
void ED_mball_editmball_load(struct Object *obedit);
-void undo_push_mball(struct bContext *C, const char *name);
+/* editmball_undo.c */
+void ED_mball_undosys_type(struct UndoType *ut);
#endif /* __ED_MBALL_H__ */
diff --git a/source/blender/editors/include/ED_mesh.h b/source/blender/editors/include/ED_mesh.h
index de798b1fce2..349a1944a23 100644
--- a/source/blender/editors/include/ED_mesh.h
+++ b/source/blender/editors/include/ED_mesh.h
@@ -47,6 +47,7 @@ struct bDeformGroup;
struct MDeformVert;
struct Scene;
struct Mesh;
+struct MTexPoly;
struct UvVertMap;
struct UvMapVert;
struct BMEditMesh;
@@ -61,6 +62,7 @@ struct UvMapVert;
struct ToolSettings;
struct Object;
struct rcti;
+struct UndoType;
/* editmesh_utils.c */
void EDBM_verts_mirror_cache_begin_ex(struct BMEditMesh *em, const int axis,
@@ -75,12 +77,11 @@ struct BMFace *EDBM_verts_mirror_get_face(struct BMEditMesh *em, struct BMFace *
void EDBM_verts_mirror_cache_clear(struct BMEditMesh *em, struct BMVert *v);
void EDBM_verts_mirror_cache_end(struct BMEditMesh *em);
-void EDBM_mesh_ensure_valid_dm_hack(struct Scene *scene, struct BMEditMesh *em);
void EDBM_mesh_normals_update(struct BMEditMesh *em);
void EDBM_mesh_clear(struct BMEditMesh *em);
void EDBM_selectmode_to_scene(struct bContext *C);
-void EDBM_mesh_make(struct ToolSettings *ts, struct Object *ob, const bool add_key_index);
+void EDBM_mesh_make(struct Object *ob, const int select_mode, const bool add_key_index);
void EDBM_mesh_free(struct BMEditMesh *em);
void EDBM_mesh_load(struct Object *ob);
struct DerivedMesh *EDBM_mesh_deform_dm_get(struct BMEditMesh *em);
@@ -98,12 +99,10 @@ void EDBM_selectmode_flush(struct BMEditMesh *em);
void EDBM_deselect_flush(struct BMEditMesh *em);
void EDBM_select_flush(struct BMEditMesh *em);
-void undo_push_mesh(struct bContext *C, const char *name);
-
bool EDBM_vert_color_check(struct BMEditMesh *em);
void EDBM_mesh_hide(struct BMEditMesh *em, bool swap);
-void EDBM_mesh_reveal(struct BMEditMesh *em);
+void EDBM_mesh_reveal(struct BMEditMesh *em, bool select);
void EDBM_update_generic(struct BMEditMesh *em, const bool do_tessface, const bool is_destructive);
@@ -113,8 +112,10 @@ struct UvElementMap *BM_uv_element_map_create(
void BM_uv_element_map_free(struct UvElementMap *vmap);
struct UvElement *BM_uv_element_get(struct UvElementMap *map, struct BMFace *efa, struct BMLoop *l);
-bool EDBM_mtexpoly_check(struct BMEditMesh *em);
-struct MTexPoly *EDBM_mtexpoly_active_get(struct BMEditMesh *em, struct BMFace **r_act_efa, const bool sloppy, const bool selected);
+bool EDBM_uv_check(struct BMEditMesh *em);
+struct BMFace *EDBM_uv_active_face_get(
+ struct BMEditMesh *em, const bool sloppy, const bool selected,
+ struct MTexPoly **r_tf);
void BM_uv_vert_map_free(struct UvVertMap *vmap);
struct UvMapVert *BM_uv_vert_map_at_index(struct UvVertMap *vmap, unsigned int v);
@@ -128,6 +129,9 @@ void EDBM_flag_disable_all(struct BMEditMesh *em, const char hflag);
bool BMBVH_EdgeVisible(struct BMBVHTree *tree, struct BMEdge *e,
struct ARegion *ar, struct View3D *v3d, struct Object *obedit);
+/* editmesh_undo.c */
+void ED_mesh_undosys_type(struct UndoType *ut);
+
/* editmesh_select.c */
void EDBM_select_mirrored(
struct BMEditMesh *em, const int axis, const bool extend,
@@ -138,8 +142,9 @@ bool EDBM_backbuf_border_init(struct ViewContext *vc, short xmin, short ymin, sh
bool EDBM_backbuf_check(unsigned int index);
void EDBM_backbuf_free(void);
-bool EDBM_backbuf_border_mask_init(struct ViewContext *vc, const int mcords[][2], short tot,
- short xmin, short ymin, short xmax, short ymax);
+bool EDBM_backbuf_border_mask_init(
+ struct ViewContext *vc, const int mcords[][2], short tot,
+ short xmin, short ymin, short xmax, short ymax);
bool EDBM_backbuf_circle_init(struct ViewContext *vc, short xs, short ys, short rads);
struct BMVert *EDBM_vert_find_nearest_ex(
@@ -205,7 +210,7 @@ void paintface_select_linked(struct bContext *C, struct Object *ob, const int mv
bool paintface_minmax(struct Object *ob, float r_min[3], float r_max[3]);
void paintface_hide(struct Object *ob, const bool unselected);
-void paintface_reveal(struct Object *ob);
+void paintface_reveal(struct Object *ob, const bool select);
void paintvert_deselect_all_visible(struct Object *ob, int action, bool flush_flags);
void paintvert_select_ungrouped(struct Object *ob, bool extend, bool flush_flags);
@@ -219,9 +224,11 @@ typedef struct MirrTopoStore_t {
int prev_ob_mode;
} MirrTopoStore_t;
-bool ED_mesh_mirrtopo_recalc_check(struct Mesh *me, struct DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store);
-void ED_mesh_mirrtopo_init(struct Mesh *me, struct DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store,
- const bool skip_em_vert_array_init);
+bool ED_mesh_mirrtopo_recalc_check(
+ struct Mesh *me, struct DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store);
+void ED_mesh_mirrtopo_init(
+ struct Mesh *me, struct DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store,
+ const bool skip_em_vert_array_init);
void ED_mesh_mirrtopo_free(MirrTopoStore_t *mesh_topo_store);
@@ -282,6 +289,7 @@ bool ED_mesh_uv_texture_remove_active(struct Mesh *me);
bool ED_mesh_uv_texture_remove_named(struct Mesh *me, const char *name);
void ED_mesh_uv_loop_reset(struct bContext *C, struct Mesh *me);
void ED_mesh_uv_loop_reset_ex(struct Mesh *me, const int layernum);
+bool ED_mesh_color_ensure(struct Mesh *me, const char *name);
int ED_mesh_color_add(struct Mesh *me, const char *name, const bool active_set);
bool ED_mesh_color_remove_index(struct Mesh *me, const int n);
bool ED_mesh_color_remove_active(struct Mesh *me);
diff --git a/source/blender/editors/include/ED_node.h b/source/blender/editors/include/ED_node.h
index f7b9d6b4f9e..e3c382382a9 100644
--- a/source/blender/editors/include/ED_node.h
+++ b/source/blender/editors/include/ED_node.h
@@ -107,7 +107,7 @@ void ED_node_composite_job(const struct bContext *C, struct bNodeTree *nodetree,
void ED_operatormacros_node(void);
/* node_view.c */
-bool ED_space_node_color_sample(struct Scene *scene, struct SpaceNode *snode, struct ARegion *ar, int mval[2], float r_col[3]);
+bool ED_space_node_color_sample(struct SpaceNode *snode, struct ARegion *ar, int mval[2], float r_col[3]);
#endif /* __ED_NODE_H__ */
diff --git a/source/blender/editors/include/ED_object.h b/source/blender/editors/include/ED_object.h
index 04ff5692717..11dde2f5913 100644
--- a/source/blender/editors/include/ED_object.h
+++ b/source/blender/editors/include/ED_object.h
@@ -54,6 +54,8 @@ struct PointerRNA;
struct PropertyRNA;
struct EnumPropertyItem;
+#include "DNA_object_enums.h"
+
/* object_edit.c */
struct Object *ED_object_context(struct bContext *C); /* context.object */
struct Object *ED_object_active_context(struct bContext *C); /* context.object or context.active_object */
@@ -109,21 +111,43 @@ struct Base *ED_object_add_duplicate(struct Main *bmain, struct Scene *scene, st
void ED_object_parent(struct Object *ob, struct Object *parent, const int type, const char *substr);
-bool ED_object_mode_compat_set(struct bContext *C, struct Object *ob, int mode, struct ReportList *reports);
-void ED_object_toggle_modes(struct bContext *C, int mode);
-
/* bitflags for enter/exit editmode */
-#define EM_FREEDATA 1
-#define EM_FREEUNDO 2
-#define EM_WAITCURSOR 4
-#define EM_DO_UNDO 8
-#define EM_IGNORE_LAYER 16
+enum {
+ EM_FREEDATA = (1 << 0),
+ EM_WAITCURSOR = (1 << 1),
+ EM_DO_UNDO = (1 << 2),
+ EM_IGNORE_LAYER = (1 << 3),
+};
+void ED_object_editmode_exit_ex(struct bContext *C, struct Scene *scene, struct Object *obedit, int flag);
void ED_object_editmode_exit(struct bContext *C, int flag);
void ED_object_editmode_enter(struct bContext *C, int flag);
bool ED_object_editmode_load(struct Object *obedit);
bool ED_object_editmode_calc_active_center(struct Object *obedit, const bool select_only, float r_center[3]);
+
+void ED_object_vpaintmode_enter_ex(
+ struct wmWindowManager *wm,
+ struct Scene *scene, struct Object *ob);
+void ED_object_vpaintmode_enter(struct bContext *C);
+void ED_object_wpaintmode_enter_ex(
+ struct wmWindowManager *wm,
+ struct Scene *scene, struct Object *ob);
+void ED_object_wpaintmode_enter(struct bContext *C);
+
+void ED_object_vpaintmode_exit_ex(struct Object *ob);
+void ED_object_vpaintmode_exit(struct bContext *C);
+void ED_object_wpaintmode_exit_ex(struct Object *ob);
+void ED_object_wpaintmode_exit(struct bContext *C);
+
+void ED_object_sculptmode_enter_ex(
+ struct Scene *scene, struct Object *ob,
+ struct ReportList *reports);
+void ED_object_sculptmode_enter(struct bContext *C, struct ReportList *reports);
+void ED_object_sculptmode_exit_ex(
+ struct Scene *scene, struct Object *ob);
+void ED_object_sculptmode_exit(struct bContext *C);
+
void ED_object_location_from_view(struct bContext *C, float loc[3]);
void ED_object_rotation_from_view(struct bContext *C, float rot[3], const char align_axis);
void ED_object_base_init_transform(struct bContext *C, struct Base *base, const float loc[3], const float rot[3]);
@@ -169,13 +193,11 @@ void ED_object_constraint_dependency_update(struct Main *bmain, struct Object *o
void ED_object_constraint_tag_update(struct Object *ob, struct bConstraint *con);
void ED_object_constraint_dependency_tag_update(struct Main *bmain, struct Object *ob, struct bConstraint *con);
-/* object_lattice.c */
-bool ED_lattice_select_pick(struct bContext *C, const int mval[2], bool extend, bool deselect, bool toggle);
-void undo_push_lattice(struct bContext *C, const char *name);
-
-/* object_lattice.c */
-
-void ED_lattice_flags_set(struct Object *obedit, int flag);
+/* object_modes.c */
+bool ED_object_mode_compat_test(const struct Object *ob, eObjectMode mode);
+bool ED_object_mode_compat_set(struct bContext *C, struct Object *ob, eObjectMode mode, struct ReportList *reports);
+void ED_object_mode_toggle(struct bContext *C, eObjectMode mode);
+void ED_object_mode_set(struct bContext *C, eObjectMode mode);
/* object_modifier.c */
enum {
@@ -183,36 +205,40 @@ enum {
MODIFIER_APPLY_SHAPE
};
-struct ModifierData *ED_object_modifier_add(struct ReportList *reports, struct Main *bmain, struct Scene *scene,
- struct Object *ob, const char *name, int type);
+struct ModifierData *ED_object_modifier_add(
+ struct ReportList *reports, struct Main *bmain, struct Scene *scene,
+ struct Object *ob, const char *name, int type);
bool ED_object_modifier_remove(struct ReportList *reports, struct Main *bmain,
struct Object *ob, struct ModifierData *md);
void ED_object_modifier_clear(struct Main *bmain, struct Object *ob);
int ED_object_modifier_move_down(struct ReportList *reports, struct Object *ob, struct ModifierData *md);
int ED_object_modifier_move_up(struct ReportList *reports, struct Object *ob, struct ModifierData *md);
-int ED_object_modifier_convert(struct ReportList *reports, struct Main *bmain, struct Scene *scene,
- struct Object *ob, struct ModifierData *md);
+int ED_object_modifier_convert(
+ struct ReportList *reports, struct Main *bmain, struct Scene *scene,
+ struct Object *ob, struct ModifierData *md);
int ED_object_modifier_apply(struct ReportList *reports, struct Scene *scene,
struct Object *ob, struct ModifierData *md, int mode);
int ED_object_modifier_copy(struct ReportList *reports, struct Object *ob, struct ModifierData *md);
-bool ED_object_iter_other(struct Main *bmain, struct Object *orig_ob, const bool include_orig,
- bool (*callback)(struct Object *ob, void *callback_data),
- void *callback_data);
+bool ED_object_iter_other(
+ struct Main *bmain, struct Object *orig_ob, const bool include_orig,
+ bool (*callback)(struct Object *ob, void *callback_data),
+ void *callback_data);
bool ED_object_multires_update_totlevels_cb(struct Object *ob, void *totlevel_v);
/* object_select.c */
void ED_object_select_linked_by_id(struct bContext *C, struct ID *id);
-struct EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
+const struct EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
const struct bContext *C,
struct PointerRNA *ptr,
struct PropertyRNA *prop,
bool *r_free,
const unsigned int selection_mask);
-void ED_object_check_force_modifiers(struct Main *bmain, struct Scene *scene, struct Object *object);
+void ED_object_check_force_modifiers(
+ struct Main *bmain, struct Scene *scene, struct Object *object);
#ifdef __cplusplus
}
diff --git a/source/blender/editors/include/ED_paint.h b/source/blender/editors/include/ED_paint.h
index e46f4b966c0..246419d64aa 100644
--- a/source/blender/editors/include/ED_paint.h
+++ b/source/blender/editors/include/ED_paint.h
@@ -28,37 +28,32 @@
struct bContext;
struct wmKeyConfig;
struct wmOperator;
+struct ImBuf;
+struct Image;
+struct UndoStep;
+struct UndoType;
/* paint_ops.c */
void ED_operatortypes_paint(void);
void ED_operatormacros_paint(void);
void ED_keymap_paint(struct wmKeyConfig *keyconf);
-/* paint_undo.c */
-enum {
- UNDO_PAINT_IMAGE = 0,
- UNDO_PAINT_MESH = 1,
-};
-
-typedef void (*UndoRestoreCb)(struct bContext *C, struct ListBase *lb);
-typedef void (*UndoFreeCb)(struct ListBase *lb);
-typedef bool (*UndoCleanupCb)(struct bContext *C, struct ListBase *lb);
-
-int ED_undo_paint_step(struct bContext *C, int type, int step, const char *name);
-void ED_undo_paint_step_num(struct bContext *C, int type, int num);
-const char *ED_undo_paint_get_name(struct bContext *C, int type, int nr, bool *r_active);
-void ED_undo_paint_free(void);
-bool ED_undo_paint_is_valid(int type, const char *name);
-bool ED_undo_paint_empty(int type);
-void ED_undo_paint_push_begin(int type, const char *name, UndoRestoreCb restore, UndoFreeCb free, UndoCleanupCb cleanup);
-void ED_undo_paint_push_end(int type);
-
/* paint_image.c */
-/* image painting specific undo */
-void ED_image_undo_restore(struct bContext *C, struct ListBase *lb);
-void ED_image_undo_free(struct ListBase *lb);
void ED_imapaint_clear_partial_redraw(void);
void ED_imapaint_dirty_region(struct Image *ima, struct ImBuf *ibuf, int x, int y, int w, int h, bool find_old);
void ED_imapaint_bucket_fill(struct bContext *C, float color[3], struct wmOperator *op);
+/* paint_image_undo.c */
+void ED_image_undo_push_begin(const char *name);
+void ED_image_undo_push_end(void);
+void ED_image_undo_restore(struct UndoStep *us);
+
+void ED_image_undosys_type(struct UndoType *ut);
+
+/* paint_curve_undo.c */
+void ED_paintcurve_undo_push_begin(const char *name);
+void ED_paintcurve_undo_push_end(void);
+
+void ED_paintcurve_undosys_type(struct UndoType *ut);
+
#endif /* __ED_PAINT_H__ */
diff --git a/source/blender/editors/include/ED_particle.h b/source/blender/editors/include/ED_particle.h
index 6cb8c0cfb19..4f6aa1cc702 100644
--- a/source/blender/editors/include/ED_particle.h
+++ b/source/blender/editors/include/ED_particle.h
@@ -38,6 +38,7 @@ struct ParticleEditSettings;
struct rcti;
struct PTCacheEdit;
struct Scene;
+struct UndoType;
/* particle edit mode */
void PE_free_ptcache_edit(struct PTCacheEdit *edit);
@@ -61,14 +62,8 @@ int PE_circle_select(struct bContext *C, int selecting, const int mval[2], float
int PE_lasso_select(struct bContext *C, const int mcords[][2], const short moves, bool extend, bool select);
void PE_deselect_all_visible(struct PTCacheEdit *edit);
-/* undo */
-void PE_undo_push(struct Scene *scene, const char *str);
-void PE_undo_step(struct Scene *scene, int step);
-void PE_undo(struct Scene *scene);
-void PE_redo(struct Scene *scene);
-bool PE_undo_is_valid(struct Scene *scene);
-void PE_undo_number(struct Scene *scene, int nr);
-const char *PE_undo_get_name(struct Scene *scene, int nr, bool *r_active);
+/* particle_edit_undo.c */
+void ED_particle_undosys_type(struct UndoType *ut);
#endif /* __ED_PARTICLE_H__ */
diff --git a/source/blender/editors/include/ED_screen.h b/source/blender/editors/include/ED_screen.h
index ec09add56b8..af4abc60a23 100644
--- a/source/blender/editors/include/ED_screen.h
+++ b/source/blender/editors/include/ED_screen.h
@@ -47,6 +47,7 @@ struct bScreen;
struct ARegion;
struct uiBlock;
struct rcti;
+struct Main;
/* regions */
void ED_region_do_listen(struct bScreen *sc, struct ScrArea *sa, struct ARegion *ar, struct wmNotifier *note);
@@ -98,7 +99,9 @@ int ED_area_headersize(void);
/* screens */
void ED_screens_initialize(struct wmWindowManager *wm);
-void ED_screen_draw(struct wmWindow *win);
+void ED_screen_draw_edges(struct wmWindow *win);
+void ED_screen_draw_join_shape(struct ScrArea *sa1, struct ScrArea *sa2);
+void ED_screen_draw_split_preview(struct ScrArea *sa, const int dir, const float fac);
void ED_screen_refresh(struct wmWindowManager *wm, struct wmWindow *win);
void ED_screen_do_listen(struct bContext *C, struct wmNotifier *note);
bScreen *ED_screen_duplicate(struct wmWindow *win, struct bScreen *sc);
@@ -107,7 +110,7 @@ bool ED_screen_set(struct bContext *C, struct bScreen *sc);
bool ED_screen_delete(struct bContext *C, struct bScreen *sc);
void ED_screen_set_scene(struct bContext *C, struct bScreen *screen, struct Scene *scene);
bool ED_screen_delete_scene(struct bContext *C, struct Scene *scene);
-void ED_screen_set_subwinactive(struct bContext *C, struct wmEvent *event);
+void ED_screen_set_subwinactive(struct bContext *C, const struct wmEvent *event);
void ED_screen_exit(struct bContext *C, struct wmWindow *window, struct bScreen *screen);
void ED_screen_animation_timer(struct bContext *C, int redraws, int refresh, int sync, int enable);
void ED_screen_animation_timer_update(struct bScreen *screen, int redraws, int refresh);
diff --git a/source/blender/editors/include/ED_sculpt.h b/source/blender/editors/include/ED_sculpt.h
index 6daaac5bb42..7c17e7b68c3 100644
--- a/source/blender/editors/include/ED_sculpt.h
+++ b/source/blender/editors/include/ED_sculpt.h
@@ -36,6 +36,9 @@ struct Object;
struct RegionView3D;
struct ViewContext;
struct rcti;
+struct UndoStep;
+struct UndoType;
+struct ListBase;
/* sculpt.c */
void ED_operatortypes_sculpt(void);
@@ -43,4 +46,7 @@ void ED_sculpt_redraw_planes_get(float planes[4][4], struct ARegion *ar,
struct RegionView3D *rv3d, struct Object *ob);
int ED_sculpt_mask_box_select(struct bContext *C, struct ViewContext *vc, const struct rcti *rect, bool select, bool extend);
+/* sculpt_undo.c */
+void ED_sculpt_undosys_type(struct UndoType *ut);
+
#endif /* __ED_SCULPT_H__ */
diff --git a/source/blender/editors/include/ED_text.h b/source/blender/editors/include/ED_text.h
index 5df7d9cfaef..763fbe3bac5 100644
--- a/source/blender/editors/include/ED_text.h
+++ b/source/blender/editors/include/ED_text.h
@@ -30,12 +30,16 @@
#ifndef __ED_TEXT_H__
#define __ED_TEXT_H__
-struct bContext;
struct SpaceText;
struct ARegion;
+struct UndoType;
+struct TextUndoBuf;
-void ED_text_undo_step(struct bContext *C, int step);
bool ED_text_region_location_from_cursor(struct SpaceText *st, struct ARegion *ar, const int cursor_co[2], int r_pixel_co[2]);
-#endif /* __ED_TEXT_H__ */
+/* text_undo.c */
+void ED_text_undosys_type(struct UndoType *ut);
+
+struct TextUndoBuf *ED_text_undo_push_init(struct bContext *C);
+#endif /* __ED_TEXT_H__ */
diff --git a/source/blender/editors/include/ED_transform.h b/source/blender/editors/include/ED_transform.h
index ebd2a3dcb7a..9a0a7f8f1bb 100644
--- a/source/blender/editors/include/ED_transform.h
+++ b/source/blender/editors/include/ED_transform.h
@@ -148,7 +148,8 @@ int BIF_countTransformOrientation(const struct bContext *C);
#define P_CORRECT_UV (1 << 8)
#define P_NO_DEFAULTS (1 << 10)
#define P_NO_TEXSPACE (1 << 11)
-#define P_GPENCIL_EDIT (1 << 12)
+#define P_CENTER (1 << 12)
+#define P_GPENCIL_EDIT (1 << 13)
void Transform_Properties(struct wmOperatorType *ot, int flags);
@@ -159,12 +160,6 @@ void BIF_draw_manipulator(const struct bContext *C);
/* Snapping */
-typedef enum SnapSelect {
- SNAP_ALL = 0,
- SNAP_NOT_SELECTED = 1,
- SNAP_NOT_ACTIVE = 2,
-} SnapSelect;
-
#define SNAP_MIN_DISTANCE 30
bool peelObjectsTransform(
@@ -187,11 +182,7 @@ bool snapObjectsTransform(
/* return args */
float r_loc[3], float r_no[3]);
bool snapNodesTransform(
- struct TransInfo *t, const int mval[2], SnapSelect snap_select,
- /* return args */
- float r_loc[2], float *r_dist_px, char *r_node_border);
-bool snapNodesContext(
- struct bContext *C, const int mval[2], SnapSelect snap_select,
+ struct TransInfo *t, const int mval[2],
/* return args */
float r_loc[2], float *r_dist_px, char *r_node_border);
diff --git a/source/blender/editors/include/ED_transform_snap_object_context.h b/source/blender/editors/include/ED_transform_snap_object_context.h
index 6eaae49912c..156b0ab36b0 100644
--- a/source/blender/editors/include/ED_transform_snap_object_context.h
+++ b/source/blender/editors/include/ED_transform_snap_object_context.h
@@ -40,6 +40,12 @@ struct View3D;
/* ED_transform_snap_object_*** API */
+typedef enum eSnapSelect {
+ SNAP_ALL = 0,
+ SNAP_NOT_SELECTED = 1,
+ SNAP_NOT_ACTIVE = 2,
+} eSnapSelect;
+
/** used for storing multiple hits */
struct SnapObjectHitDepth {
struct SnapObjectHitDepth *next, *prev;
@@ -84,7 +90,6 @@ void ED_transform_snap_object_context_set_editmesh_callbacks(
bool ED_transform_snap_object_project_ray_ex(
struct SnapObjectContext *sctx,
- const unsigned short snap_to,
const struct SnapObjectParams *params,
const float ray_start[3], const float ray_normal[3], float *ray_depth,
/* return args */
@@ -98,7 +103,6 @@ bool ED_transform_snap_object_project_ray(
bool ED_transform_snap_object_project_ray_all(
SnapObjectContext *sctx,
- const unsigned short snap_to,
const struct SnapObjectParams *params,
const float ray_start[3], const float ray_normal[3],
float ray_depth, bool sort,
diff --git a/source/blender/editors/include/ED_undo.h b/source/blender/editors/include/ED_undo.h
new file mode 100644
index 00000000000..b3814ab5899
--- /dev/null
+++ b/source/blender/editors/include/ED_undo.h
@@ -0,0 +1,64 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file ED_undo.h
+ * \ingroup editors
+ */
+
+#ifndef __ED_UNDO_H__
+#define __ED_UNDO_H__
+
+struct bContext;
+struct wmOperator;
+struct wmOperatorType;
+struct UndoStack;
+
+/* undo.c */
+void ED_undo_push(struct bContext *C, const char *str);
+void ED_undo_push_op(struct bContext *C, struct wmOperator *op);
+void ED_undo_grouped_push(struct bContext *C, const char *str);
+void ED_undo_grouped_push_op(struct bContext *C, struct wmOperator *op);
+void ED_undo_pop_op(struct bContext *C, struct wmOperator *op);
+void ED_undo_pop(struct bContext *C);
+void ED_undo_redo(struct bContext *C);
+void ED_OT_undo(struct wmOperatorType *ot);
+void ED_OT_undo_push(struct wmOperatorType *ot);
+void ED_OT_redo(struct wmOperatorType *ot);
+void ED_OT_undo_redo(struct wmOperatorType *ot);
+void ED_OT_undo_history(struct wmOperatorType *ot);
+
+int ED_undo_operator_repeat(struct bContext *C, struct wmOperator *op);
+/* convenience since UI callbacks use this mostly*/
+void ED_undo_operator_repeat_cb(struct bContext *C, void *arg_op, void *arg_unused);
+void ED_undo_operator_repeat_cb_evt(struct bContext *C, void *arg_op, int arg_unused);
+
+bool ED_undo_is_valid(const struct bContext *C, const char *undoname);
+
+struct UndoStack *ED_undo_stack_get(void);
+
+/* undo_system_types.c */
+void ED_undosys_type_init(void);
+void ED_undosys_type_free(void);
+
+/* memfile_undo.c */
+struct MemFile *ED_undosys_stack_memfile_get_active(struct UndoStack *ustack);
+
+#endif /* __ED_UNDO_H__ */
+
diff --git a/source/blender/editors/include/ED_util.h b/source/blender/editors/include/ED_util.h
index 60c4b3593aa..2653585dacc 100644
--- a/source/blender/editors/include/ED_util.h
+++ b/source/blender/editors/include/ED_util.h
@@ -32,9 +32,10 @@
#define __ED_UTIL_H__
struct bContext;
-struct SpaceLink;
-struct wmOperator;
struct wmOperatorType;
+struct ScrArea;
+struct SpaceLink;
+struct PackedFile;
/* ed_util.c */
@@ -47,40 +48,6 @@ void ED_spacedata_id_remap(struct ScrArea *sa, struct SpaceLink *sl, struct I
void ED_OT_flush_edits(struct wmOperatorType *ot);
-/* ************** Undo ************************ */
-
-/* undo.c */
-void ED_undo_push(struct bContext *C, const char *str);
-void ED_undo_push_op(struct bContext *C, struct wmOperator *op);
-void ED_undo_grouped_push(struct bContext *C, const char *str);
-void ED_undo_grouped_push_op(struct bContext *C, struct wmOperator *op);
-void ED_undo_pop_op(struct bContext *C, struct wmOperator *op);
-void ED_undo_pop(struct bContext *C);
-void ED_undo_redo(struct bContext *C);
-void ED_OT_undo(struct wmOperatorType *ot);
-void ED_OT_undo_push(struct wmOperatorType *ot);
-void ED_OT_redo(struct wmOperatorType *ot);
-void ED_OT_undo_redo(struct wmOperatorType *ot);
-void ED_OT_undo_history(struct wmOperatorType *ot);
-
-int ED_undo_operator_repeat(struct bContext *C, struct wmOperator *op);
-/* convenience since UI callbacks use this mostly*/
-void ED_undo_operator_repeat_cb(struct bContext *C, void *arg_op, void *arg_unused);
-void ED_undo_operator_repeat_cb_evt(struct bContext *C, void *arg_op, int arg_unused);
-
-bool ED_undo_is_valid(const struct bContext *C, const char *undoname);
-
-/* undo_editmode.c */
-void undo_editmode_push(struct bContext *C, const char *name,
- void * (*getdata)(struct bContext *C),
- void (*freedata)(void *),
- void (*to_editmode)(void *, void *, void *),
- void *(*from_editmode)(void *, void *),
- int (*validate_undo)(void *, void *));
-
-
-void undo_editmode_clear(void);
-
/* ************** XXX OLD CRUFT WARNING ************* */
void apply_keyb_grid(int shift, int ctrl, float *val, float fac1, float fac2, float fac3, int invert);
diff --git a/source/blender/editors/include/ED_uvedit.h b/source/blender/editors/include/ED_uvedit.h
index a0ff29790fe..efbf3adde79 100644
--- a/source/blender/editors/include/ED_uvedit.h
+++ b/source/blender/editors/include/ED_uvedit.h
@@ -51,48 +51,63 @@ struct wmOperator;
void ED_operatortypes_uvedit(void);
void ED_keymap_uvedit(struct wmKeyConfig *keyconf);
-void ED_uvedit_assign_image(struct Main *bmain, struct Scene *scene, struct Object *obedit, struct Image *ima, struct Image *previma);
+void ED_uvedit_assign_image(
+ struct Main *bmain, struct Scene *scene, struct Object *obedit, struct Image *ima, struct Image *previma);
bool ED_uvedit_minmax(struct Scene *scene, struct Image *ima, struct Object *obedit, float min[2], float max[2]);
void ED_uvedit_select_all(struct BMesh *bm);
-bool ED_object_get_active_image(struct Object *ob, int mat_nr,
- struct Image **r_ima, struct ImageUser **r_iuser, struct bNode **r_node, struct bNodeTree **r_ntree);
+bool ED_object_get_active_image(
+ struct Object *ob, int mat_nr,
+ struct Image **r_ima, struct ImageUser **r_iuser, struct bNode **r_node, struct bNodeTree **r_ntree);
void ED_object_assign_active_image(struct Main *bmain, struct Object *ob, int mat_nr, struct Image *ima);
bool ED_uvedit_test(struct Object *obedit);
/* visibility and selection */
bool uvedit_face_visible_test(struct Scene *scene, struct Image *ima, struct BMFace *efa, struct MTexPoly *tf);
-bool uvedit_face_select_test(struct Scene *scene, struct BMFace *efa,
- const int cd_loop_uv_offset);
-bool uvedit_edge_select_test(struct Scene *scene, struct BMLoop *l,
- const int cd_loop_uv_offset);
-bool uvedit_uv_select_test(struct Scene *scene, struct BMLoop *l,
- const int cd_loop_uv_offset);
+bool uvedit_face_select_test(
+ struct Scene *scene, struct BMFace *efa,
+ const int cd_loop_uv_offset);
+bool uvedit_edge_select_test(
+ struct Scene *scene, struct BMLoop *l,
+ const int cd_loop_uv_offset);
+bool uvedit_uv_select_test(
+ struct Scene *scene, struct BMLoop *l,
+ const int cd_loop_uv_offset);
/* uv face */
-bool uvedit_face_select_set(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
- const bool do_history, const int cd_loop_uv_offset);
-bool uvedit_face_select_enable(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa,
- const bool do_history, const int cd_loop_uv_offset);
-bool uvedit_face_select_disable(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa,
- const int cd_loop_uv_offset);
+bool uvedit_face_select_set(
+ struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
+ const bool do_history, const int cd_loop_uv_offset);
+bool uvedit_face_select_enable(
+ struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa,
+ const bool do_history, const int cd_loop_uv_offset);
+bool uvedit_face_select_disable(
+ struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa,
+ const int cd_loop_uv_offset);
/* uv edge */
-void uvedit_edge_select_set(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l, const bool select,
- const bool do_history, const int cd_loop_uv_offset);
-void uvedit_edge_select_enable(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
- const bool do_history, const int cd_loop_uv_offset);
-void uvedit_edge_select_disable(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
- const int cd_loop_uv_offset);
+void uvedit_edge_select_set(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l, const bool select,
+ const bool do_history, const int cd_loop_uv_offset);
+void uvedit_edge_select_enable(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
+ const bool do_history, const int cd_loop_uv_offset);
+void uvedit_edge_select_disable(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
+ const int cd_loop_uv_offset);
/* uv vert */
-void uvedit_uv_select_set(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l, const bool select,
- const bool do_history, const int cd_loop_uv_offset);
-void uvedit_uv_select_enable(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
- const bool do_history, const int cd_loop_uv_offset);
-void uvedit_uv_select_disable(struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
- const int cd_loop_uv_offset);
-
-bool ED_uvedit_nearest_uv(struct Scene *scene, struct Object *obedit, struct Image *ima,
- const float co[2], float r_uv[2]);
+void uvedit_uv_select_set(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l, const bool select,
+ const bool do_history, const int cd_loop_uv_offset);
+void uvedit_uv_select_enable(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
+ const bool do_history, const int cd_loop_uv_offset);
+void uvedit_uv_select_disable(
+ struct BMEditMesh *em, struct Scene *scene, struct BMLoop *l,
+ const int cd_loop_uv_offset);
+
+bool ED_uvedit_nearest_uv(
+ struct Scene *scene, struct Object *obedit, struct Image *ima,
+ const float co[2], float r_uv[2]);
void ED_uvedit_get_aspect(struct Scene *scene, struct Object *ob, struct BMesh *em, float *aspx, float *aspy);
@@ -102,16 +117,22 @@ void ED_uvedit_live_unwrap_re_solve(void);
void ED_uvedit_live_unwrap_end(short cancel);
void ED_uvedit_live_unwrap(struct Scene *scene, struct Object *obedit);
-void ED_uvedit_pack_islands(struct Scene *scene, struct Object *ob, struct BMesh *bm, bool selected, bool correct_aspect, bool do_rotate);
-void ED_uvedit_unwrap_cube_project(struct Object *ob, struct BMesh *bm, float cube_size, bool use_select);
+void ED_uvedit_pack_islands(
+ struct Scene *scene, struct Object *ob, struct BMesh *bm,
+ bool selected, bool correct_aspect, bool do_rotate);
+void ED_uvedit_unwrap_cube_project(
+ struct BMesh *bm, float cube_size, bool use_select, const float center[3]);
/* single call up unwrap using scene settings, used for edge tag unwrapping */
void ED_uvedit_unwrap(struct Scene *scene, struct Object *obedit, const short sel, struct wmOperator *op);
/* uvedit_draw.c */
-void ED_image_draw_cursor(struct ARegion *ar, const float cursor[2]);
-void ED_uvedit_draw_main(struct SpaceImage *sima, struct ARegion *ar, struct Scene *scene, struct Object *obedit, struct Object *obact);
+void ED_image_draw_cursor(
+ struct ARegion *ar, const float cursor[2]);
+void ED_uvedit_draw_main(
+ struct SpaceImage *sima, struct ARegion *ar, struct Scene *scene,
+ struct Object *obedit, struct Object *obact);
/* uvedit_buttons.c */
void ED_uvedit_buttons_register(struct ARegionType *art);
diff --git a/source/blender/editors/include/ED_view3d.h b/source/blender/editors/include/ED_view3d.h
index 79176d9e9cf..2767e041627 100644
--- a/source/blender/editors/include/ED_view3d.h
+++ b/source/blender/editors/include/ED_view3d.h
@@ -47,6 +47,7 @@ struct Main;
struct MetaElem;
struct Nurb;
struct Object;
+struct RV3DMatrixStore;
struct RegionView3D;
struct Scene;
struct ScrArea;
@@ -105,7 +106,14 @@ void ED_view3d_lastview_store(struct RegionView3D *rv3d);
/* Depth buffer */
void ED_view3d_depth_update(struct ARegion *ar);
-float ED_view3d_depth_read_cached(const struct ViewContext *vc, int x, int y);
+float ED_view3d_depth_read_cached(const struct ViewContext *vc, const int mval[2]);
+bool ED_view3d_depth_read_cached_normal(
+ const ViewContext *vc, const struct bglMats *mats, const int mval[2],
+ float r_normal[3]);
+bool ED_view3d_depth_unproject(
+ const struct ARegion *ar, const struct bglMats *mats,
+ const int mval[2], const double depth,
+ float r_location_world[3]);
void ED_view3d_depth_tag_update(struct RegionView3D *rv3d);
/* Projection */
@@ -207,6 +215,8 @@ eV3DProjStatus ED_view3d_project_float_ex(const struct ARegion *ar, float perspm
eV3DProjStatus ED_view3d_project_float_global(const struct ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag);
eV3DProjStatus ED_view3d_project_float_object(const struct ARegion *ar, const float co[3], float r_co[2], const eV3DProjTest flag);
+float ED_view3d_pixel_size(const struct RegionView3D *rv3d, const float co[3]);
+
float ED_view3d_calc_zfac(const struct RegionView3D *rv3d, const float co[3], bool *r_flip);
bool ED_view3d_clip_segment(const struct RegionView3D *rv3d, float ray_start[3], float ray_end[3]);
bool ED_view3d_win_to_ray(
@@ -256,8 +266,9 @@ void ED_view3d_calc_camera_border_size(
const struct Scene *scene, const struct ARegion *ar,
const struct View3D *v3d, const struct RegionView3D *rv3d,
float r_size[2]);
-bool ED_view3d_calc_render_border(struct Scene *scene, struct View3D *v3d,
- struct ARegion *ar, struct rcti *rect);
+bool ED_view3d_calc_render_border(
+ const struct Scene *scene, const struct View3D *v3d,
+ const struct ARegion *ar, struct rcti *rect);
void ED_view3d_clipping_calc_from_boundbox(float clip[6][4], const struct BoundBox *clipbb, const bool is_flip);
void ED_view3d_clipping_calc(struct BoundBox *bb, float planes[4][4], struct bglMats *mats, const struct rcti *rect);
@@ -267,8 +278,6 @@ void ED_view3d_clipping_set(struct RegionView3D *rv3d);
void ED_view3d_clipping_enable(void);
void ED_view3d_clipping_disable(void);
-float ED_view3d_pixel_size(const struct RegionView3D *rv3d, const float co[3]);
-
float ED_view3d_radius_to_dist_persp(const float angle, const float radius);
float ED_view3d_radius_to_dist_ortho(const float lens, const float radius);
float ED_view3d_radius_to_dist(
@@ -301,11 +310,26 @@ bool ED_view3d_autodist_depth_seg(struct ARegion *ar, const int mval_sta[2], con
/* select */
#define MAXPICKELEMS 2500
#define MAXPICKBUF (4 * MAXPICKELEMS)
-short view3d_opengl_select(struct ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const struct rcti *input, bool do_nearest);
+
+typedef enum {
+ /* all elements in the region, ignore depth */
+ VIEW3D_SELECT_ALL = 0,
+ /* pick also depth sorts (only for small regions!) */
+ VIEW3D_SELECT_PICK_ALL = 1,
+ /* sorts and only returns visible objects (only for small regions!) */
+ VIEW3D_SELECT_PICK_NEAREST = 2,
+} eV3DSelectMode;
+
+void view3d_opengl_select_cache_begin(void);
+void view3d_opengl_select_cache_end(void);
+
+int view3d_opengl_select(
+ struct ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const struct rcti *input,
+ eV3DSelectMode select_mode);
/* view3d_select.c */
float ED_view3d_select_dist_px(void);
-void view3d_set_viewcontext(struct bContext *C, struct ViewContext *vc);
+void ED_view3d_viewcontext_init(struct bContext *C, struct ViewContext *vc);
void view3d_operator_needs_opengl(const struct bContext *C);
void view3d_region_operator_needs_opengl(struct wmWindow *win, struct ARegion *ar);
void view3d_opengl_read_pixels(struct ARegion *ar, int x, int y, int w, int h, int format, int type, void *data);
@@ -330,8 +354,8 @@ void ED_view3d_check_mats_rv3d(struct RegionView3D *rv3d);
#endif
int ED_view3d_scene_layer_set(int lay, const int *values, int *active);
-void *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d);
-void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, void *rv3dmat_pt);
+struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d);
+void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat);
bool ED_view3d_context_activate(struct bContext *C);
void ED_view3d_draw_offscreen_init(struct Scene *scene, struct View3D *v3d);
@@ -340,21 +364,38 @@ void ED_view3d_draw_offscreen(
float winmat[4][4], bool do_bgpic, bool do_sky, bool is_persp, const char *viewname,
struct GPUFX *fx, struct GPUFXSettings *fx_settings,
struct GPUOffScreen *ofs);
+void ED_view3d_draw_setup_view(
+ struct wmWindow *win, struct Scene *scene, struct ARegion *ar, struct View3D *v3d,
+ float viewmat[4][4], float winmat[4][4], const struct rcti *rect);
+
+enum {
+ V3D_OFSDRAW_NONE = (0),
+
+ V3D_OFSDRAW_USE_BACKGROUND = (1 << 0),
+ V3D_OFSDRAW_USE_FULL_SAMPLE = (1 << 1),
+
+ /* Only works with ED_view3d_draw_offscreen_imbuf_simple(). */
+ V3D_OFSDRAW_USE_GPENCIL = (1 << 2),
+ V3D_OFSDRAW_USE_SOLID_TEX = (1 << 2),
+ V3D_OFSDRAW_USE_CAMERA_DOF = (1 << 3),
+};
struct ImBuf *ED_view3d_draw_offscreen_imbuf(
struct Scene *scene, struct View3D *v3d, struct ARegion *ar, int sizex, int sizey,
- unsigned int flag, bool draw_background,
- int alpha_mode, int samples, bool full_samples, const char *viewname,
+ unsigned int flag, unsigned int draw_flags,
+ int alpha_mode, int samples, const char *viewname,
struct GPUFX *fx, struct GPUOffScreen *ofs, char err_out[256]);
struct ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
struct Scene *scene, struct Object *camera, int width, int height,
- unsigned int flag, int drawtype, bool use_solid_tex, bool use_gpencil, bool draw_background,
- int alpha_mode, int samples, bool full_samples, const char *viewname,
+ unsigned int flag, unsigned int draw_flags, int drawtype, int alpha_mode,
+ int samples, const char *viewname,
struct GPUFX *fx, struct GPUOffScreen *ofs, char err_out[256]);
struct Base *ED_view3d_give_base_under_cursor(struct bContext *C, const int mval[2]);
void ED_view3d_quadview_update(struct ScrArea *sa, struct ARegion *ar, bool do_clip);
-void ED_view3d_update_viewmat(struct Scene *scene, struct View3D *v3d, struct ARegion *ar, float viewmat[4][4], float winmat[4][4]);
+void ED_view3d_update_viewmat(
+ struct Scene *scene, struct View3D *v3d, struct ARegion *ar,
+ float viewmat[4][4], float winmat[4][4], const struct rcti *rect);
bool ED_view3d_quat_from_axis_view(const char view, float quat[4]);
char ED_view3d_quat_to_axis_view(const float quat[4], const float epsilon);
char ED_view3d_lock_view_from_index(int index);
@@ -365,6 +406,9 @@ uint64_t ED_view3d_datamask(const struct Scene *scene, const struct View3D *v3d)
uint64_t ED_view3d_screen_datamask(const struct bScreen *screen);
bool ED_view3d_offset_lock_check(const struct View3D *v3d, const struct RegionView3D *rv3d);
+void ED_view3d_persp_switch_from_camera(struct View3D *v3d, struct RegionView3D *rv3d, const char persp);
+bool ED_view3d_persp_ensure(struct View3D *v3d, struct ARegion *ar);
+
/* camera lock functions */
bool ED_view3d_camera_lock_check(const struct View3D *v3d, const struct RegionView3D *rv3d);
@@ -381,11 +425,11 @@ bool ED_view3d_camera_lock_autokey(
struct View3D *v3d, struct RegionView3D *rv3d,
struct bContext *C, const bool do_rotate, const bool do_translate);
-void ED_view3D_lock_clear(struct View3D *v3d);
+void ED_view3d_lock_clear(struct View3D *v3d);
-struct BGpic *ED_view3D_background_image_new(struct View3D *v3d);
-void ED_view3D_background_image_remove(struct View3D *v3d, struct BGpic *bgpic);
-void ED_view3D_background_image_clear(struct View3D *v3d);
+struct BGpic *ED_view3d_background_image_new(struct View3D *v3d);
+void ED_view3d_background_image_remove(struct View3D *v3d, struct BGpic *bgpic);
+void ED_view3d_background_image_clear(struct View3D *v3d);
#define VIEW3D_MARGIN 1.4f
#define VIEW3D_DIST_FALLBACK 1.0f
@@ -408,7 +452,7 @@ void ED_view3d_operator_properties_viewmat_get(struct wmOperator *op, int *winx,
/* render */
void ED_view3d_stop_render_preview(struct wmWindowManager *wm, struct ARegion *ar);
-void ED_view3d_shade_update(struct Main *bmain, struct Scene *scene, struct View3D *v3d, struct ScrArea *sa);
+void ED_view3d_shade_update(struct Main *bmain, struct View3D *v3d, struct ScrArea *sa);
#define V3D_IS_ZBUF(v3d) \
(((v3d)->flag & V3D_ZBUF_SELECT) && ((v3d)->drawtype > OB_WIRE))
diff --git a/source/blender/editors/include/UI_icons.h b/source/blender/editors/include/UI_icons.h
index 8420591aa3e..0c83038b7a3 100644
--- a/source/blender/editors/include/UI_icons.h
+++ b/source/blender/editors/include/UI_icons.h
@@ -313,9 +313,9 @@ DEF_ICON(OUTLINER_OB_ARMATURE)
DEF_ICON(OUTLINER_OB_FONT)
DEF_ICON(OUTLINER_OB_SURFACE)
DEF_ICON(OUTLINER_OB_SPEAKER)
+DEF_ICON(OUTLINER_OB_FORCE_FIELD)
+DEF_ICON(OUTLINER_OB_GROUP_INSTANCE)
#ifndef DEF_ICON_BLANK_SKIP
- DEF_ICON(BLANK120)
- DEF_ICON(BLANK121)
DEF_ICON(BLANK122)
DEF_ICON(BLANK123)
DEF_ICON(BLANK124)
diff --git a/source/blender/editors/include/UI_interface.h b/source/blender/editors/include/UI_interface.h
index 9fbce7dd203..d6c6f0a2eb6 100644
--- a/source/blender/editors/include/UI_interface.h
+++ b/source/blender/editors/include/UI_interface.h
@@ -136,6 +136,7 @@ enum {
/* block->flag bits 14-17 are identical to but->drawflag bits */
+#define UI_BLOCK_POPUP_HOLD (1 << 18)
#define UI_BLOCK_LIST_ITEM (1 << 19)
#define UI_BLOCK_RADIAL (1 << 20)
@@ -200,24 +201,28 @@ enum {
UI_BUT_TEXT_RIGHT = (1 << 3),
/* Prevent the button to show any tooltip. */
UI_BUT_NO_TOOLTIP = (1 << 4),
- /* button align flag, for drawing groups together (also used in uiBlock->flag!) */
+
+ /* Button align flag, for drawing groups together.
+ * Used in 'uiBlock.flag', take care! */
UI_BUT_ALIGN_TOP = (1 << 14),
UI_BUT_ALIGN_LEFT = (1 << 15),
UI_BUT_ALIGN_RIGHT = (1 << 16),
UI_BUT_ALIGN_DOWN = (1 << 17),
UI_BUT_ALIGN = (UI_BUT_ALIGN_TOP | UI_BUT_ALIGN_LEFT | UI_BUT_ALIGN_RIGHT | UI_BUT_ALIGN_DOWN),
+ /* end bits shared with 'uiBlock.flag' */
/* Warning - HACK! Needed for buttons which are not TOP/LEFT aligned, but have some top/left corner stitched to some
* other TOP/LEFT-aligned button, because of 'corrective' hack in widget_roundbox_set()... */
UI_BUT_ALIGN_STITCH_TOP = (1 << 18),
UI_BUT_ALIGN_STITCH_LEFT = (1 << 19),
UI_BUT_ALIGN_ALL = (UI_BUT_ALIGN | UI_BUT_ALIGN_STITCH_TOP | UI_BUT_ALIGN_STITCH_LEFT),
+
+ UI_BUT_BOX_ITEM = (1 << 20), /* This but is "inside" a box item (currently used to change theme colors). */
};
/* scale fixed button widths by this to account for DPI */
#define UI_DPI_FAC ((U.pixelsize * (float)U.dpi) / 72.0f)
-#define UI_DPI_WINDOW_FAC (((float)U.dpi) / 72.0f)
/* 16 to copy ICON_DEFAULT_HEIGHT */
#define UI_DPI_ICON_SIZE ((float)16 * UI_DPI_FAC)
@@ -353,6 +358,7 @@ typedef struct uiSearchItems uiSearchItems;
typedef void (*uiButHandleFunc)(struct bContext *C, void *arg1, void *arg2);
typedef void (*uiButHandleRenameFunc)(struct bContext *C, void *arg, char *origstr);
typedef void (*uiButHandleNFunc)(struct bContext *C, void *argN, void *arg2);
+typedef void (*uiButHandleHoldFunc)(struct bContext *C, struct ARegion *butregion, uiBut *but);
typedef int (*uiButCompleteFunc)(struct bContext *C, char *str, void *arg);
typedef struct ARegion *(*uiButSearchCreateFunc)(struct bContext *C, struct ARegion *butregion, uiBut *but);
typedef void (*uiButSearchFunc)(const struct bContext *C, void *arg, const char *str, uiSearchItems *items);
@@ -373,6 +379,7 @@ typedef void (*uiMenuHandleFunc)(struct bContext *C, void *arg, int event);
*/
typedef bool (*uiMenuStepFunc)(struct bContext *C, int direction, void *arg1);
+/* interface_region_menu_popup.c */
/* Popup Menus
*
* Functions used to create popup menus. For more extended menus the
@@ -394,7 +401,9 @@ void UI_popup_menu_reports(struct bContext *C, struct ReportList *reports) ATTR_
int UI_popup_menu_invoke(struct bContext *C, const char *idname, struct ReportList *reports) ATTR_NONNULL(1, 2);
void UI_popup_menu_retval_set(const uiBlock *block, const int retval, const bool enable);
+void UI_popup_menu_but_set(uiPopupMenu *pup, struct ARegion *butregion, uiBut *but);
+/* interface_region_menu_pie.c */
/* Pie menus */
typedef struct uiPieMenu uiPieMenu;
@@ -411,17 +420,19 @@ struct uiPieMenu *UI_pie_menu_begin(
const struct wmEvent *event) ATTR_NONNULL();
void UI_pie_menu_end(struct bContext *C, uiPieMenu *pie);
struct uiLayout *UI_pie_menu_layout(struct uiPieMenu *pie);
+
+/* interface_region_menu_popup.c */
+
/* Popup Blocks
*
* Functions used to create popup blocks. These are like popup menus
* but allow using all button types and creating an own layout. */
-
typedef uiBlock * (*uiBlockCreateFunc)(struct bContext *C, struct ARegion *ar, void *arg1);
typedef void (*uiBlockCancelFunc)(struct bContext *C, void *arg1);
void UI_popup_block_invoke(struct bContext *C, uiBlockCreateFunc func, void *arg);
void UI_popup_block_invoke_ex(struct bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext);
-void UI_popup_block_ex(struct bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg);
+void UI_popup_block_ex(struct bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg, struct wmOperator *op);
/* void uiPupBlockOperator(struct bContext *C, uiBlockCreateFunc func, struct wmOperator *op, int opcontext); */ /* UNUSED */
void UI_popup_block_close(struct bContext *C, struct wmWindow *win, uiBlock *block);
@@ -438,7 +449,7 @@ void UI_popup_block_close(struct bContext *C, struct wmWindow *win, uiBlock *blo
* */
uiBlock *UI_block_begin(const struct bContext *C, struct ARegion *region, const char *name, short dt);
-void UI_block_end_ex(const struct bContext *C, uiBlock *block, const int xy[2]);
+void UI_block_end_ex(const struct bContext *C, uiBlock *block, const int xy[2], int r_xy[2]);
void UI_block_end(const struct bContext *C, uiBlock *block);
void UI_block_draw(const struct bContext *C, struct uiBlock *block);
void UI_block_update_from_old(const struct bContext *C, struct uiBlock *block);
@@ -650,6 +661,15 @@ void UI_but_string_info_get(struct bContext *C, uiBut *but, ...) ATTR_SENTINEL(0
#define UI_ID_PREVIEWS (1 << 10)
#define UI_ID_FULL (UI_ID_RENAME | UI_ID_BROWSE | UI_ID_ADD_NEW | UI_ID_OPEN | UI_ID_ALONE | UI_ID_DELETE | UI_ID_LOCAL)
+/**
+ * Ways to limit what is displayed in ID-search popup.
+ * \note We may want to add LOCAL, LIBRARY ... as needed.
+ */
+enum {
+ UI_TEMPLATE_ID_FILTER_ALL = 0,
+ UI_TEMPLATE_ID_FILTER_AVAILABLE = 1,
+};
+
int UI_icon_from_id(struct ID *id);
int UI_icon_from_report_type(int type);
@@ -725,6 +745,8 @@ bool UI_textbutton_activate_but(const struct bContext *C, uiBut *but);
void UI_but_focus_on_enter_event(struct wmWindow *win, uiBut *but);
+void UI_but_func_hold_set(uiBut *but, uiButHandleHoldFunc func, void *argN);
+
/* Autocomplete
*
* Tab complete helper functions, for use in uiButCompleteFunc callbacks.
@@ -818,7 +840,6 @@ void UI_exit(void);
#define UI_LAYOUT_ALIGN_CENTER 2
#define UI_LAYOUT_ALIGN_RIGHT 3
-#define UI_ITEM_O_RETURN_PROPS (1 << 0)
#define UI_ITEM_R_EXPAND (1 << 1)
#define UI_ITEM_R_SLIDER (1 << 2)
#define UI_ITEM_R_TOGGLE (1 << 3)
@@ -827,10 +848,11 @@ void UI_exit(void);
#define UI_ITEM_R_FULL_EVENT (1 << 6)
#define UI_ITEM_R_NO_BG (1 << 7)
#define UI_ITEM_R_IMMEDIATE (1 << 8)
+#define UI_ITEM_O_DEPRESS (1 << 9)
-/* uiLayoutOperatorButs flags */
-#define UI_LAYOUT_OP_SHOW_TITLE 1
-#define UI_LAYOUT_OP_SHOW_EMPTY 2
+/* uiTemplateOperatorPropertyButs flags */
+#define UI_TEMPLATE_OP_PROPS_SHOW_TITLE 1
+#define UI_TEMPLATE_OP_PROPS_SHOW_EMPTY 2
/* used for transp checkers */
#define UI_ALPHA_CHECKER_DARK 100
@@ -865,10 +887,11 @@ void uiLayoutSetFunc(uiLayout *layout, uiMenuHandleFunc handlefunc, void *argv);
void uiLayoutSetContextPointer(uiLayout *layout, const char *name, struct PointerRNA *ptr);
void uiLayoutContextCopy(uiLayout *layout, struct bContextStore *context);
const char *uiLayoutIntrospect(uiLayout *layout); // XXX - testing
-void uiLayoutOperatorButs(const struct bContext *C, struct uiLayout *layout, struct wmOperator *op,
- bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *),
- const char label_align, const short flag);
struct MenuType *UI_but_menutype_get(uiBut *but);
+void UI_menutype_draw(struct bContext *C, struct MenuType *mt, struct uiLayout *layout);
+
+/* Only for convenience. */
+void uiLayoutSetContextFromBut(uiLayout *layout, uiBut *but);
void uiLayoutSetOperatorContext(uiLayout *layout, int opcontext);
void uiLayoutSetActive(uiLayout *layout, bool active);
@@ -904,12 +927,15 @@ uiLayout *uiLayoutRadial(uiLayout *layout);
/* templates */
void uiTemplateHeader(uiLayout *layout, struct bContext *C);
-void uiTemplateID(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
- const char *newop, const char *openop, const char *unlinkop);
-void uiTemplateIDBrowse(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
- const char *newop, const char *openop, const char *unlinkop);
-void uiTemplateIDPreview(uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
- const char *newop, const char *openop, const char *unlinkop, int rows, int cols);
+void uiTemplateID(
+ uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
+ const char *newop, const char *openop, const char *unlinkop, int filter);
+void uiTemplateIDBrowse(
+ uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
+ const char *newop, const char *openop, const char *unlinkop, int filter);
+void uiTemplateIDPreview(
+ uiLayout *layout, struct bContext *C, struct PointerRNA *ptr, const char *propname,
+ const char *newop, const char *openop, const char *unlinkop, int rows, int cols, int filter);
void uiTemplateAnyID(uiLayout *layout, struct PointerRNA *ptr, const char *propname,
const char *proptypename, const char *text);
void uiTemplatePathBuilder(uiLayout *layout, struct PointerRNA *ptr, const char *propname,
@@ -941,6 +967,9 @@ void uiTemplateImageInfo(uiLayout *layout, struct bContext *C, struct Image *ima
void uiTemplateRunningJobs(uiLayout *layout, struct bContext *C);
void UI_but_func_operator_search(uiBut *but);
void uiTemplateOperatorSearch(uiLayout *layout);
+void uiTemplateOperatorPropertyButs(const struct bContext *C, uiLayout *layout, struct wmOperator *op,
+ bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *),
+ const char label_align, const short flag);
void uiTemplateHeader3D(uiLayout *layout, struct bContext *C);
void uiTemplateEditModeSelection(uiLayout *layout, struct bContext *C);
void uiTemplateReportsBanner(uiLayout *layout, struct bContext *C);
@@ -980,8 +1009,19 @@ void uiItemIntO(uiLayout *layout, const char *name, int icon, const char *opname
void uiItemFloatO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, float value);
void uiItemStringO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value);
-PointerRNA uiItemFullO_ptr(uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon, struct IDProperty *properties, int context, int flag);
-PointerRNA uiItemFullO(uiLayout *layout, const char *idname, const char *name, int icon, struct IDProperty *properties, int context, int flag);
+void uiItemFullO_ptr(
+ uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon,
+ struct IDProperty *properties, int context, int flag,
+ PointerRNA *r_opptr);
+void uiItemFullO(
+ uiLayout *layout, const char *idname, const char *name, int icon,
+ struct IDProperty *properties, int context, int flag,
+ PointerRNA *r_opptr);
+void uiItemFullOMenuHold_ptr(
+ uiLayout *layout, struct wmOperatorType *ot, const char *name, int icon,
+ struct IDProperty *properties, int context, int flag,
+ const char *menu_id, /* extra menu arg. */
+ PointerRNA *r_opptr);
void uiItemR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, int flag, const char *name, int icon);
void uiItemFullR(uiLayout *layout, struct PointerRNA *ptr, struct PropertyRNA *prop, int index, int value, int flag, const char *name, int icon);
@@ -995,7 +1035,7 @@ void uiItemsFullEnumO(
struct IDProperty *properties, int context, int flag);
void uiItemsFullEnumO_items(
uiLayout *layout, struct wmOperatorType *ot, PointerRNA ptr, PropertyRNA *prop,
- IDProperty *properties, int context, int flag,
+ struct IDProperty *properties, int context, int flag,
const EnumPropertyItem *item_array, int totitem);
void uiItemL(uiLayout *layout, const char *name, int icon); /* label */
@@ -1005,6 +1045,7 @@ void uiItemV(uiLayout *layout, const char *name, int icon, int argval); /* value
void uiItemS(uiLayout *layout); /* separator */
void uiItemMenuF(uiLayout *layout, const char *name, int icon, uiMenuCreateFunc func, void *arg);
+void uiItemMenuEnumO_ptr(uiLayout *layout, struct bContext *C, struct wmOperatorType *ot, const char *propname, const char *name, int icon);
void uiItemMenuEnumO(uiLayout *layout, struct bContext *C, const char *opname, const char *propname, const char *name, int icon);
void uiItemMenuEnumR_prop(uiLayout *layout, struct PointerRNA *ptr, PropertyRNA *prop, const char *name, int icon);
void uiItemMenuEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *name, int icon);
@@ -1040,6 +1081,8 @@ void UI_context_active_but_prop_get_templateID(
struct bContext *C,
struct PointerRNA *r_ptr, struct PropertyRNA **r_prop);
+uiBut *UI_region_active_but_get(struct ARegion *ar);
+
/* Styled text draw */
void UI_fontstyle_set(const struct uiFontStyle *fs);
void UI_fontstyle_draw_ex(
@@ -1081,9 +1124,15 @@ void UI_butstore_register(uiButStore *bs_handle, uiBut **but_p);
bool UI_butstore_register_update(uiBlock *block, uiBut *but_dst, const uiBut *but_src);
void UI_butstore_unregister(uiButStore *bs_handle, uiBut **but_p);
+/* ui_interface_region_tooltip.c */
+struct ARegion *UI_tooltip_create_from_button(struct bContext *C, struct ARegion *butregion, uiBut *but);
+void UI_tooltip_free(struct bContext *C, struct bScreen *sc, struct ARegion *ar);
+
+/* How long before a tool-tip shows. */
+#define UI_TOOLTIP_DELAY 0.5
/* Float precision helpers */
-#define UI_PRECISION_FLOAT_MAX 7
+#define UI_PRECISION_FLOAT_MAX 6
/* For float buttons the 'step' (or a1), is scaled */
#define UI_PRECISION_FLOAT_SCALE 0.01f
diff --git a/source/blender/editors/include/UI_resources.h b/source/blender/editors/include/UI_resources.h
index f8a5f30a596..a0efd586af5 100644
--- a/source/blender/editors/include/UI_resources.h
+++ b/source/blender/editors/include/UI_resources.h
@@ -303,7 +303,6 @@ enum {
TH_EDGE_BEVEL,
TH_VERTEX_BEVEL
};
-/* XXX WARNING: previous is saved in file, so do not change order! */
/* specific defines per space should have higher define values */
diff --git a/source/blender/editors/include/UI_view2d.h b/source/blender/editors/include/UI_view2d.h
index 4caacb65f5f..f6e31e0bd22 100644
--- a/source/blender/editors/include/UI_view2d.h
+++ b/source/blender/editors/include/UI_view2d.h
@@ -169,7 +169,7 @@ void UI_view2d_view_restore(const struct bContext *C);
View2DGrid *UI_view2d_grid_calc(struct Scene *scene, struct View2D *v2d,
short xunits, short xclamp, short yunits, short yclamp, int winx, int winy);
void UI_view2d_grid_draw(struct View2D *v2d, View2DGrid *grid, int flag);
-void UI_view2d_constant_grid_draw(struct View2D *v2d);
+void UI_view2d_constant_grid_draw(struct View2D *v2d, float step);
void UI_view2d_multi_grid_draw(struct View2D *v2d, int colorid, float step, int level_size, int totlevels);
void UI_view2d_grid_size(View2DGrid *grid, float *r_dx, float *r_dy);
void UI_view2d_grid_free(View2DGrid *grid);
@@ -203,6 +203,7 @@ bool UI_view2d_view_to_region_clip(struct View2D *v2d, float x, float y, int *r
void UI_view2d_view_to_region(struct View2D *v2d, float x, float y, int *r_region_x, int *r_region_y) ATTR_NONNULL();
void UI_view2d_view_to_region_fl(struct View2D *v2d, float x, float y, float *r_region_x, float *r_region_y) ATTR_NONNULL();
+void UI_view2d_view_to_region_m4(struct View2D *v2d, float matrix[4][4]) ATTR_NONNULL();
void UI_view2d_view_to_region_rcti(struct View2D *v2d, const struct rctf *rect_src, struct rcti *rect_dst) ATTR_NONNULL();
bool UI_view2d_view_to_region_rcti_clip(struct View2D *v2d, const struct rctf *rect_src, struct rcti *rect_dst) ATTR_NONNULL();
diff --git a/source/blender/editors/interface/CMakeLists.txt b/source/blender/editors/interface/CMakeLists.txt
index c57f8d5c7a8..0adc315fd69 100644
--- a/source/blender/editors/interface/CMakeLists.txt
+++ b/source/blender/editors/interface/CMakeLists.txt
@@ -44,12 +44,23 @@ set(SRC
interface_anim.c
interface_draw.c
interface_eyedropper.c
+ interface_eyedropper_color.c
+ interface_eyedropper_colorband.c
+ interface_eyedropper_datablock.c
+ interface_eyedropper_depth.c
+ interface_eyedropper_driver.c
interface_handlers.c
interface_icons.c
interface_layout.c
interface_ops.c
interface_panel.c
interface_regions.c
+ interface_region_color_picker.c
+ interface_region_menu_pie.c
+ interface_region_menu_popup.c
+ interface_region_popup.c
+ interface_region_search.c
+ interface_region_tooltip.c
interface_style.c
interface_templates.c
interface_utils.c
@@ -58,7 +69,9 @@ set(SRC
view2d.c
view2d_ops.c
+ interface_eyedropper_intern.h
interface_intern.h
+ interface_regions_intern.h
)
if(WITH_INTERNATIONAL)
@@ -69,6 +82,10 @@ if(WITH_HEADLESS)
add_definitions(-DWITH_HEADLESS)
endif()
+if(WITH_CYCLES)
+ add_definitions(-DWITH_CYCLES)
+endif()
+
if(WITH_PYTHON)
add_definitions(-DWITH_PYTHON)
endif()
diff --git a/source/blender/editors/interface/interface.c b/source/blender/editors/interface/interface.c
index 682db20af55..5f36c5e21bf 100644
--- a/source/blender/editors/interface/interface.c
+++ b/source/blender/editors/interface/interface.c
@@ -366,10 +366,10 @@ static void ui_block_bounds_calc_centered_pie(uiBlock *block)
static void ui_block_bounds_calc_popup(
wmWindow *window, uiBlock *block,
- eBlockBoundsCalc bounds_calc, const int xy[2])
+ eBlockBoundsCalc bounds_calc, const int xy[2], int r_xy[2])
{
int width, height, oldwidth, oldheight;
- int oldbounds, xmax, ymax;
+ int oldbounds, xmax, ymax, raw_x, raw_y;
const int margin = UI_SCREEN_MARGIN;
rcti rect, rect_bounds;
int ofs_dummy[2];
@@ -407,8 +407,8 @@ static void ui_block_bounds_calc_popup(
/* offset block based on mouse position, user offset is scaled
* along in case we resized the block in ui_block_bounds_calc_text */
- rect.xmin = xy[0] + block->rect.xmin + (block->mx * width) / oldwidth;
- rect.ymin = xy[1] + block->rect.ymin + (block->my * height) / oldheight;
+ raw_x = rect.xmin = xy[0] + block->rect.xmin + (block->mx * width) / oldwidth;
+ raw_y = rect.ymin = xy[1] + block->rect.ymin + (block->my * height) / oldheight;
rect.xmax = rect.xmin + width;
rect.ymax = rect.ymin + height;
@@ -422,6 +422,13 @@ static void ui_block_bounds_calc_popup(
/* now recompute bounds and safety */
ui_block_bounds_calc(block);
+
+ /* If given, adjust input coordinates such that they would generate real final popup position.
+ * Needed to handle correctly floating panels once they have been dragged around, see T52999. */
+ if (r_xy) {
+ r_xy[0] = xy[0] + block->rect.xmin - raw_x;
+ r_xy[1] = xy[1] + block->rect.ymin - raw_y;
+ }
}
/* used for various cases */
@@ -488,6 +495,9 @@ static int ui_but_calc_float_precision(uiBut *but, double value)
else if (prec == -1) {
prec = (but->hardmax < 10.001f) ? 3 : 2;
}
+ else {
+ CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
+ }
return UI_calc_float_precision(prec, value);
}
@@ -684,7 +694,7 @@ static bool ui_but_update_from_old_block(const bContext *C, uiBlock *block, uiBu
if (oldbut->active) {
/* flags from the buttons we want to refresh, may want to add more here... */
- const int flag_copy = UI_BUT_REDALERT;
+ const int flag_copy = UI_BUT_REDALERT | UI_HAS_ICON;
found_active = true;
@@ -973,7 +983,9 @@ void ui_but_add_shortcut(uiBut *but, const char *shortcut_str, const bool do_str
}
}
-static bool ui_but_event_operator_string(const bContext *C, uiBut *but, char *buf, const size_t buf_len)
+static bool ui_but_event_operator_string(
+ const bContext *C, uiBut *but,
+ char *buf, const size_t buf_len)
{
MenuType *mt;
bool found = false;
@@ -981,7 +993,10 @@ static bool ui_but_event_operator_string(const bContext *C, uiBut *but, char *bu
if (but->optype) {
IDProperty *prop = (but->opptr) ? but->opptr->data : NULL;
- if (WM_key_event_operator_string(C, but->optype->idname, but->opcontext, prop, true, buf_len, buf)) {
+ if (WM_key_event_operator_string(
+ C, but->optype->idname, but->opcontext, prop, true,
+ buf, buf_len))
+ {
found = true;
}
}
@@ -996,8 +1011,9 @@ static bool ui_but_event_operator_string(const bContext *C, uiBut *but, char *bu
IDP_AssignString(prop_menu_name, mt->idname, sizeof(mt->idname));
- if (WM_key_event_operator_string(C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu,
- true, buf_len, buf))
+ if (WM_key_event_operator_string(
+ C, "WM_OT_call_menu", WM_OP_INVOKE_REGION_WIN, prop_menu, true,
+ buf, buf_len))
{
found = true;
}
@@ -1009,8 +1025,10 @@ static bool ui_but_event_operator_string(const bContext *C, uiBut *but, char *bu
return found;
}
-static bool ui_but_event_property_operator_string(const bContext *C, uiBut *but, char *buf, const size_t buf_len)
-{
+static bool ui_but_event_property_operator_string(
+ const bContext *C, uiBut *but,
+ char *buf, const size_t buf_len)
+{
/* context toggle operator names to check... */
const char *ctx_toggle_opnames[] = {
"WM_OT_context_toggle",
@@ -1104,8 +1122,9 @@ static bool ui_but_event_property_operator_string(const bContext *C, uiBut *but,
/* check each until one works... */
for (i = 0; (i < num_ops) && (ctx_toggle_opnames[i]); i++) {
- if (WM_key_event_operator_string(C, ctx_toggle_opnames[i], WM_OP_INVOKE_REGION_WIN, prop_path, false,
- buf_len, buf))
+ if (WM_key_event_operator_string(
+ C, ctx_toggle_opnames[i], WM_OP_INVOKE_REGION_WIN, prop_path, false,
+ buf, buf_len))
{
found = true;
break;
@@ -1165,6 +1184,8 @@ static void ui_menu_block_set_keymaps(const bContext *C, uiBlock *block)
uiBut *but;
char buf[128];
+ BLI_assert(block->flag & UI_BLOCK_LOOP);
+
/* only do it before bounding */
if (block->rect.xmin != block->rect.xmax)
return;
@@ -1179,6 +1200,9 @@ static void ui_menu_block_set_keymaps(const bContext *C, uiBlock *block)
}
else {
for (but = block->buttons.first; but; but = but->next) {
+ if (but->dt != UI_EMBOSS_PULLDOWN) {
+ continue;
+ }
if (ui_but_event_operator_string(C, but, buf, sizeof(buf))) {
ui_but_add_shortcut(but, buf, false);
@@ -1223,7 +1247,7 @@ void UI_block_update_from_old(const bContext *C, uiBlock *block)
block->oldblock = NULL;
}
-void UI_block_end_ex(const bContext *C, uiBlock *block, const int xy[2])
+void UI_block_end_ex(const bContext *C, uiBlock *block, const int xy[2], int r_xy[2])
{
wmWindow *window = CTX_wm_window(C);
Scene *scene = CTX_data_scene(C);
@@ -1291,7 +1315,7 @@ void UI_block_end_ex(const bContext *C, uiBlock *block, const int xy[2])
/* fallback */
case UI_BLOCK_BOUNDS_POPUP_MOUSE:
case UI_BLOCK_BOUNDS_POPUP_MENU:
- ui_block_bounds_calc_popup(window, block, block->bounds_type, xy);
+ ui_block_bounds_calc_popup(window, block, block->bounds_type, xy, r_xy);
break;
}
@@ -1309,7 +1333,7 @@ void UI_block_end(const bContext *C, uiBlock *block)
{
wmWindow *window = CTX_wm_window(C);
- UI_block_end_ex(C, block, &window->eventstate->x);
+ UI_block_end_ex(C, block, &window->eventstate->x, NULL);
}
/* ************** BLOCK DRAWING FUNCTION ************* */
@@ -1337,7 +1361,7 @@ static void ui_but_to_pixelrect(rcti *rect, const ARegion *ar, uiBlock *block, u
rctf rectf;
ui_block_to_window_rctf(ar, block, &rectf, (but) ? &but->rect : &block->rect);
- BLI_rcti_rctf_copy_floor(rect, &rectf);
+ BLI_rcti_rctf_copy_round(rect, &rectf);
BLI_rcti_translate(rect, -ar->winrct.xmin, -ar->winrct.ymin);
}
@@ -1932,13 +1956,14 @@ void ui_but_value_set(uiBut *but, double value)
else {
/* first do rounding */
if (but->pointype == UI_BUT_POIN_CHAR) {
- value = (char)floor(value + 0.5);
+ value = round_db_to_uchar_clamp(value);
}
else if (but->pointype == UI_BUT_POIN_SHORT) {
- value = (short)floor(value + 0.5);
+ value = round_db_to_short_clamp(value);
+ }
+ else if (but->pointype == UI_BUT_POIN_INT) {
+ value = round_db_to_int_clamp(value);
}
- else if (but->pointype == UI_BUT_POIN_INT)
- value = (int)floor(value + 0.5);
else if (but->pointype == UI_BUT_POIN_FLOAT) {
float fval = (float)value;
if (fval >= -0.00001f && fval <= 0.00001f) fval = 0.0f; /* prevent negative zero */
@@ -2146,9 +2171,14 @@ static float ui_get_but_step_unit(uiBut *but, float step_default)
/**
* \param float_precision For number buttons the precision to use or -1 to fallback to the button default.
+ * \param use_exp_float Use exponent representation of floats when out of reasonable range (outside of 1e3/1e-3).
*/
-void ui_but_string_get_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision)
+void ui_but_string_get_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision, const bool use_exp_float, bool *r_use_exp_float)
{
+ if (r_use_exp_float) {
+ *r_use_exp_float = false;
+ }
+
if (but->rnaprop && ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
PropertyType type;
const char *buf = NULL;
@@ -2216,17 +2246,38 @@ void ui_but_string_get_ex(uiBut *but, char *str, const size_t maxlen, const int
ui_get_but_string_unit(but, str, maxlen, value, false, float_precision);
}
else {
- const int prec = (float_precision == -1) ? ui_but_calc_float_precision(but, value) : float_precision;
- BLI_snprintf(str, maxlen, "%.*f", prec, value);
+ int prec = (float_precision == -1) ? ui_but_calc_float_precision(but, value) : float_precision;
+ if (use_exp_float) {
+ const int int_digits_num = integer_digits_f(value);
+ if (int_digits_num < -6 || int_digits_num > 12) {
+ BLI_snprintf(str, maxlen, "%.*g", prec, value);
+ if (r_use_exp_float) {
+ *r_use_exp_float = true;
+ }
+ }
+ else {
+ prec -= int_digits_num;
+ CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
+ BLI_snprintf(str, maxlen, "%.*f", prec, value);
+ }
+ }
+ else {
+#if 0 /* TODO, but will likely break some stuff, so better after 2.79 release. */
+ prec -= int_digits_num;
+ CLAMP(prec, 0, UI_PRECISION_FLOAT_MAX);
+#endif
+ BLI_snprintf(str, maxlen, "%.*f", prec, value);
+ }
}
}
- else
+ else {
BLI_snprintf(str, maxlen, "%d", (int)value);
+ }
}
}
void ui_but_string_get(uiBut *but, char *str, const size_t maxlen)
{
- ui_but_string_get_ex(but, str, maxlen, -1);
+ ui_but_string_get_ex(but, str, maxlen, -1, false, NULL);
}
/**
@@ -2288,7 +2339,7 @@ char *ui_but_string_get_dynamic(uiBut *but, int *r_str_size)
#ifdef WITH_PYTHON
-static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *value)
+static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char *str, double *r_value)
{
char str_unit_convert[256];
const int unit_type = UI_but_unit_type_get(but);
@@ -2300,13 +2351,13 @@ static bool ui_set_but_string_eval_num_unit(bContext *C, uiBut *but, const char
bUnit_ReplaceString(str_unit_convert, sizeof(str_unit_convert), but->drawstr,
ui_get_but_scale_unit(but, 1.0), but->block->unit->system, RNA_SUBTYPE_UNIT_VALUE(unit_type));
- return BPY_execute_string_as_number(C, str_unit_convert, value, true);
+ return BPY_execute_string_as_number(C, str_unit_convert, true, r_value);
}
#endif /* WITH_PYTHON */
-bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double *value)
+bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double *r_value)
{
bool ok = false;
@@ -2315,13 +2366,13 @@ bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double
if (str[0] != '\0') {
bool is_unit_but = (ui_but_is_float(but) && ui_but_is_unit(but));
/* only enable verbose if we won't run again with units */
- if (BPY_execute_string_as_number(C, str, value, is_unit_but == false)) {
+ if (BPY_execute_string_as_number(C, str, is_unit_but == false, r_value)) {
/* if the value parsed ok without unit conversion this button may still need a unit multiplier */
if (is_unit_but) {
char str_new[128];
- BLI_snprintf(str_new, sizeof(str_new), "%f", *value);
- ok = ui_set_but_string_eval_num_unit(C, but, str_new, value);
+ BLI_snprintf(str_new, sizeof(str_new), "%f", *r_value);
+ ok = ui_set_but_string_eval_num_unit(C, but, str_new, r_value);
}
else {
ok = true; /* parse normal string via py (no unit conversion needed) */
@@ -2329,17 +2380,16 @@ bool ui_but_string_set_eval_num(bContext *C, uiBut *but, const char *str, double
}
else if (is_unit_but) {
/* parse failed, this is a unit but so run replacements and parse again */
- ok = ui_set_but_string_eval_num_unit(C, but, str, value);
+ ok = ui_set_but_string_eval_num_unit(C, but, str, r_value);
}
}
#else /* WITH_PYTHON */
- *value = atof(str);
+ *r_value = atof(str);
ok = true;
- (void)C;
- (void)but;
+ UNUSED_VARS(C, but);
#endif /* WITH_PYTHON */
@@ -2449,7 +2499,9 @@ bool ui_but_string_set(bContext *C, uiBut *but, const char *str)
return false;
}
- if (!ui_but_is_float(but)) value = (int)floor(value + 0.5);
+ if (!ui_but_is_float(but)) {
+ value = floor(value + 0.5);
+ }
/* not that we use hard limits here */
if (value < (double)but->hardmin) value = but->hardmin;
@@ -2629,6 +2681,10 @@ static void ui_but_free(const bContext *C, uiBut *but)
MEM_freeN(but->tip_argN);
}
+ if (but->hold_argN) {
+ MEM_freeN(but->hold_argN);
+ }
+
if (but->active) {
/* XXX solve later, buttons should be free-able without context ideally,
* however they may have open tooltips or popup windows, which need to
@@ -3168,7 +3224,9 @@ static uiBut *ui_def_but(
}
if (block->flag & UI_BLOCK_RADIAL) {
- but->drawflag |= (UI_BUT_TEXT_LEFT | UI_BUT_ICON_LEFT);
+ but->drawflag |= UI_BUT_TEXT_LEFT;
+ if (but->str && but->str[0])
+ but->drawflag |= UI_BUT_ICON_LEFT;
}
else if ((block->flag & UI_BLOCK_LOOP) ||
ELEM(but->type,
@@ -3245,7 +3303,7 @@ static void ui_def_but_rna__menu(bContext *UNUSED(C), uiLayout *layout, void *bu
uiBut *but = (uiBut *)but_p;
/* see comment in ui_item_enum_expand, re: uiname */
- EnumPropertyItem *item, *item_array;
+ const EnumPropertyItem *item, *item_array;
bool free;
uiLayout *split, *column = NULL;
@@ -3355,9 +3413,8 @@ static void ui_def_but_rna__menu(bContext *UNUSED(C), uiLayout *layout, void *bu
UI_block_layout_set_current(block, layout);
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
-
BLI_assert((block->flag & UI_BLOCK_IS_FLIP) == 0);
block->flag |= UI_BLOCK_IS_FLIP;
}
@@ -3388,7 +3445,7 @@ static uiBut *ui_def_but_rna(
/* use rna values if parameters are not specified */
if ((proptype == PROP_ENUM) && ELEM(type, UI_BTYPE_MENU, UI_BTYPE_ROW, UI_BTYPE_LISTROW)) {
/* UI_BTYPE_MENU is handled a little differently here */
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int value;
bool free;
int i;
@@ -3430,7 +3487,7 @@ static uiBut *ui_def_but_rna(
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
}
else {
@@ -3913,6 +3970,8 @@ uiBut *uiDefIconTextButO_ptr(uiBlock *block, int type, wmOperatorType *ot, int o
uiBut *uiDefIconTextButO(uiBlock *block, int type, const char *opname, int opcontext, int icon, const char *str, int x, int y, short width, short height, const char *tip)
{
wmOperatorType *ot = WM_operatortype_find(opname, 0);
+ if (str && str[0] == '\0')
+ return uiDefIconButO_ptr(block, type, ot, opcontext, icon, x, y, width, height, tip);
return uiDefIconTextButO_ptr(block, type, ot, opcontext, icon, str, x, y, width, height, tip);
}
@@ -4390,7 +4449,7 @@ static void operator_enum_search_cb(const struct bContext *C, void *but, const c
}
else {
PointerRNA *ptr = UI_but_operator_ptr_get(but); /* Will create it if needed! */
- EnumPropertyItem *item, *item_array;
+ const EnumPropertyItem *item, *item_array;
bool do_free;
RNA_property_enum_items_gettexted((bContext *)C, ptr, prop, &item_array, NULL, &do_free);
@@ -4403,8 +4462,9 @@ static void operator_enum_search_cb(const struct bContext *C, void *but, const c
}
}
- if (do_free)
- MEM_freeN(item_array);
+ if (do_free) {
+ MEM_freeN((void *)item_array);
+ }
}
}
@@ -4473,12 +4533,18 @@ void UI_but_focus_on_enter_event(wmWindow *win, uiBut *but)
wm_event_add(win, &event);
}
+void UI_but_func_hold_set(uiBut *but, uiButHandleHoldFunc func, void *argN)
+{
+ but->hold_func = func;
+ but->hold_argN = argN;
+}
+
void UI_but_string_info_get(bContext *C, uiBut *but, ...)
{
va_list args;
uiStringInfo *si;
- EnumPropertyItem *items = NULL, *item = NULL;
+ const EnumPropertyItem *items = NULL, *item = NULL;
int totitems;
bool free_items = false;
@@ -4654,8 +4720,9 @@ void UI_but_string_info_get(bContext *C, uiBut *but, ...)
}
va_end(args);
- if (free_items && items)
- MEM_freeN(items);
+ if (free_items && items) {
+ MEM_freeN((void *)items);
+ }
}
/* Program Init/Exit */
diff --git a/source/blender/editors/interface/interface_anim.c b/source/blender/editors/interface/interface_anim.c
index 5da294302e9..a04360b3395 100644
--- a/source/blender/editors/interface/interface_anim.c
+++ b/source/blender/editors/interface/interface_anim.c
@@ -39,6 +39,7 @@
#include "BLI_utildefines.h"
#include "BKE_context.h"
+#include "BKE_depsgraph.h"
#include "BKE_fcurve.h"
#include "BKE_global.h"
#include "BKE_nla.h"
@@ -210,6 +211,7 @@ bool ui_but_anim_expression_create(uiBut *but, const char *str)
/* updates */
driver->flag |= DRIVER_FLAG_RECOMPILE;
+ DAG_relations_tag_update(CTX_data_main(C));
WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME, NULL);
ok = true;
}
diff --git a/source/blender/editors/interface/interface_draw.c b/source/blender/editors/interface/interface_draw.c
index 01ea1e953fa..7583dc654bb 100644
--- a/source/blender/editors/interface/interface_draw.c
+++ b/source/blender/editors/interface/interface_draw.c
@@ -40,9 +40,9 @@
#include "BLI_string.h"
#include "BLI_utildefines.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_node.h"
-#include "BKE_texture.h"
#include "BKE_tracking.h"
@@ -831,7 +831,7 @@ static void vectorscope_draw_target(float centerx, float centery, float diam, co
float tangle = 0.f, tampli;
float dangle, dampli, dangle2, dampli2;
- rgb_to_yuv(colf[0], colf[1], colf[2], &y, &u, &v);
+ rgb_to_yuv(colf[0], colf[1], colf[2], &y, &u, &v, BLI_YUV_ITU_BT709);
if (u > 0 && v >= 0) tangle = atanf(v / u);
else if (u > 0 && v < 0) tangle = atanf(v / u) + 2.0f * (float)M_PI;
else if (u < 0) tangle = atanf(v / u) + (float)M_PI;
@@ -1121,7 +1121,7 @@ void ui_draw_but_COLORBAND(uiBut *but, uiWidgetColors *UNUSED(wcol), const rcti
glBegin(GL_TRIANGLE_STRIP);
for (int a = 0; a <= sizex; a++) {
float pos = ((float)a) / sizex;
- do_colorband(coba, pos, colf);
+ BKE_colorband_evaluate(coba, pos, colf);
if (display)
IMB_colormanagement_scene_linear_to_display_v3(colf, display);
@@ -1140,7 +1140,7 @@ void ui_draw_but_COLORBAND(uiBut *but, uiWidgetColors *UNUSED(wcol), const rcti
glBegin(GL_TRIANGLE_STRIP);
for (int a = 0; a <= sizex; a++) {
float pos = ((float)a) / sizex;
- do_colorband(coba, pos, colf);
+ BKE_colorband_evaluate(coba, pos, colf);
if (display)
IMB_colormanagement_scene_linear_to_display_v3(colf, display);
diff --git a/source/blender/editors/interface/interface_eyedropper.c b/source/blender/editors/interface/interface_eyedropper.c
index 5154a77ad21..381d9f3cc42 100644
--- a/source/blender/editors/interface/interface_eyedropper.c
+++ b/source/blender/editors/interface/interface_eyedropper.c
@@ -27,53 +27,23 @@
* \ingroup edinterface
*/
-#include "MEM_guardedalloc.h"
-
-#include "DNA_anim_types.h"
#include "DNA_space_types.h"
#include "DNA_screen_types.h"
-#include "DNA_object_types.h"
#include "BLI_blenlib.h"
#include "BLI_math_vector.h"
-#include "BLT_translation.h"
-
#include "BKE_context.h"
#include "BKE_screen.h"
-#include "BKE_report.h"
-#include "BKE_animsys.h"
-#include "BKE_depsgraph.h"
-#include "BKE_idcode.h"
-#include "BKE_unit.h"
-
-#include "RNA_access.h"
-#include "RNA_define.h"
-
-#include "BIF_gl.h"
#include "UI_interface.h"
-#include "IMB_colormanagement.h"
-
#include "WM_api.h"
#include "WM_types.h"
#include "interface_intern.h"
-/* for HDR color sampling */
-#include "ED_image.h"
-#include "ED_node.h"
-#include "ED_clip.h"
-
-/* for ID data eyedropper */
-#include "ED_space_api.h"
-#include "ED_screen.h"
-#include "ED_view3d.h"
-
-/* for Driver eyedropper */
-#include "ED_keyframing.h"
-
+#include "interface_eyedropper_intern.h" /* own include */
/* -------------------------------------------------------------------- */
/* Keymap
@@ -81,16 +51,10 @@
/** \name Modal Keymap
* \{ */
-enum {
- EYE_MODAL_CANCEL = 1,
- EYE_MODAL_SAMPLE_CONFIRM,
- EYE_MODAL_SAMPLE_BEGIN,
- EYE_MODAL_SAMPLE_RESET,
-};
wmKeyMap *eyedropper_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{EYE_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{EYE_MODAL_SAMPLE_CONFIRM, "SAMPLE_CONFIRM", 0, "Confirm Sampling", ""},
{EYE_MODAL_SAMPLE_BEGIN, "SAMPLE_BEGIN", 0, "Start Sampling", ""},
@@ -116,6 +80,7 @@ wmKeyMap *eyedropper_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, SPACEKEY, KM_RELEASE, KM_ANY, 0, EYE_MODAL_SAMPLE_RESET);
/* assign to operators */
+ WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_colorband");
WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_color");
WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_id");
WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_depth");
@@ -124,6 +89,37 @@ wmKeyMap *eyedropper_modal_keymap(wmKeyConfig *keyconf)
return keymap;
}
+wmKeyMap *eyedropper_colorband_modal_keymap(wmKeyConfig *keyconf)
+{
+ static const EnumPropertyItem modal_items_point[] = {
+ {EYE_MODAL_POINT_CANCEL, "CANCEL", 0, "Cancel", ""},
+ {EYE_MODAL_POINT_SAMPLE, "SAMPLE_SAMPLE", 0, "Sample a point", ""},
+ {EYE_MODAL_POINT_CONFIRM, "SAMPLE_CONFIRM", 0, "Confirm Sampling", ""},
+ {EYE_MODAL_POINT_RESET, "SAMPLE_RESET", 0, "Reset Sampling", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "Eyedropper ColorBand PointSampling Map");
+ if (keymap && keymap->modal_items)
+ return keymap;
+
+ keymap = WM_modalkeymap_add(keyconf, "Eyedropper ColorBand PointSampling Map", modal_items_point);
+
+ /* items for modal map */
+ WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, EYE_MODAL_CANCEL);
+ WM_modalkeymap_add_item(keymap, BACKSPACEKEY, KM_PRESS, KM_ANY, 0, EYE_MODAL_POINT_REMOVE_LAST);
+ WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_PRESS, KM_ANY, 0, EYE_MODAL_POINT_CONFIRM);
+ WM_modalkeymap_add_item(keymap, RETKEY, KM_RELEASE, KM_ANY, 0, EYE_MODAL_POINT_CONFIRM);
+ WM_modalkeymap_add_item(keymap, PADENTER, KM_RELEASE, KM_ANY, 0, EYE_MODAL_POINT_CONFIRM);
+ WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_ANY, 0, EYE_MODAL_POINT_SAMPLE);
+ WM_modalkeymap_add_item(keymap, SPACEKEY, KM_RELEASE, KM_ANY, 0, EYE_MODAL_POINT_RESET);
+
+ /* assign to operators */
+ WM_modalkeymap_assign(keymap, "UI_OT_eyedropper_colorband_point");
+
+ return keymap;
+}
+
/** \} */
@@ -133,7 +129,7 @@ wmKeyMap *eyedropper_modal_keymap(wmKeyConfig *keyconf)
/** \name Generic Shared Functions
* \{ */
-static void eyedropper_draw_cursor_text(const struct bContext *C, ARegion *ar, const char *name)
+void eyedropper_draw_cursor_text(const struct bContext *C, const ARegion *ar, const char *name)
{
const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
wmWindow *win = CTX_wm_window(C);
@@ -167,14 +163,14 @@ static void eyedropper_draw_cursor_text(const struct bContext *C, ARegion *ar, c
*
* \return A button under the mouse which relates to some RNA Property, or NULL
*/
-static uiBut *eyedropper_get_property_button_under_mouse(bContext *C, const wmEvent *event)
+uiBut *eyedropper_get_property_button_under_mouse(bContext *C, const wmEvent *event)
{
wmWindow *win = CTX_wm_window(C);
ScrArea *sa = BKE_screen_find_area_xy(win->screen, SPACE_TYPE_ANY, event->x, event->y);
ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_ANY, event->x, event->y);
-
+
uiBut *but = ui_but_find_mouse_over(ar, event);
-
+
if (ELEM(NULL, but, but->rnapoin.data, but->rnaprop)) {
return NULL;
}
@@ -185,1121 +181,3 @@ static uiBut *eyedropper_get_property_button_under_mouse(bContext *C, const wmEv
/** \} */
-
-/* -------------------------------------------------------------------- */
-/* Eyedropper
- */
-
-/** \name Eyedropper (RGB Color)
- * \{ */
-
-typedef struct Eyedropper {
- struct ColorManagedDisplay *display;
-
- PointerRNA ptr;
- PropertyRNA *prop;
- int index;
-
- float init_col[3]; /* for resetting on cancel */
-
- bool accum_start; /* has mouse been pressed */
- float accum_col[3];
- int accum_tot;
-} Eyedropper;
-
-static bool eyedropper_init(bContext *C, wmOperator *op)
-{
- Scene *scene = CTX_data_scene(C);
- Eyedropper *eye;
-
- op->customdata = eye = MEM_callocN(sizeof(Eyedropper), "Eyedropper");
-
- UI_context_active_but_prop_get(C, &eye->ptr, &eye->prop, &eye->index);
-
- if ((eye->ptr.data == NULL) ||
- (eye->prop == NULL) ||
- (RNA_property_editable(&eye->ptr, eye->prop) == false) ||
- (RNA_property_array_length(&eye->ptr, eye->prop) < 3) ||
- (RNA_property_type(eye->prop) != PROP_FLOAT))
- {
- return false;
- }
-
- if (RNA_property_subtype(eye->prop) == PROP_COLOR) {
- const char *display_device;
- float col[4];
-
- display_device = scene->display_settings.display_device;
- eye->display = IMB_colormanagement_display_get_named(display_device);
-
- /* store inital color */
- RNA_property_float_get_array(&eye->ptr, eye->prop, col);
- if (eye->display) {
- IMB_colormanagement_scene_linear_to_display_v3(col, eye->display);
- }
- copy_v3_v3(eye->init_col, col);
- }
-
- return true;
-}
-
-static void eyedropper_exit(bContext *C, wmOperator *op)
-{
- WM_cursor_modal_restore(CTX_wm_window(C));
-
- if (op->customdata) {
- MEM_freeN(op->customdata);
- op->customdata = NULL;
- }
-}
-
-/* *** eyedropper_color_ helper functions *** */
-
-/**
- * \brief get the color from the screen.
- *
- * Special check for image or nodes where we MAY have HDR pixels which don't display.
- */
-static void eyedropper_color_sample_fl(bContext *C, Eyedropper *UNUSED(eye), int mx, int my, float r_col[3])
-{
-
- /* we could use some clever */
- wmWindow *win = CTX_wm_window(C);
- ScrArea *sa = BKE_screen_find_area_xy(win->screen, SPACE_TYPE_ANY, mx, my);
-
- if (sa) {
- if (sa->spacetype == SPACE_IMAGE) {
- ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
- if (ar) {
- SpaceImage *sima = sa->spacedata.first;
- int mval[2] = {mx - ar->winrct.xmin,
- my - ar->winrct.ymin};
-
- if (ED_space_image_color_sample(CTX_data_scene(C), sima, ar, mval, r_col)) {
- return;
- }
- }
- }
- else if (sa->spacetype == SPACE_NODE) {
- ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
- if (ar) {
- SpaceNode *snode = sa->spacedata.first;
- int mval[2] = {mx - ar->winrct.xmin,
- my - ar->winrct.ymin};
-
- if (ED_space_node_color_sample(CTX_data_scene(C), snode, ar, mval, r_col)) {
- return;
- }
- }
- }
- else if (sa->spacetype == SPACE_CLIP) {
- ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
- if (ar) {
- SpaceClip *sc = sa->spacedata.first;
- int mval[2] = {mx - ar->winrct.xmin,
- my - ar->winrct.ymin};
-
- if (ED_space_clip_color_sample(CTX_data_scene(C), sc, ar, mval, r_col)) {
- return;
- }
- }
- }
- }
-
- /* fallback to simple opengl picker */
- glReadBuffer(GL_FRONT);
- glReadPixels(mx, my, 1, 1, GL_RGB, GL_FLOAT, r_col);
- glReadBuffer(GL_BACK);
-}
-
-/* sets the sample color RGB, maintaining A */
-static void eyedropper_color_set(bContext *C, Eyedropper *eye, const float col[3])
-{
- float col_conv[4];
-
- /* to maintain alpha */
- RNA_property_float_get_array(&eye->ptr, eye->prop, col_conv);
-
- /* convert from display space to linear rgb space */
- if (eye->display) {
- copy_v3_v3(col_conv, col);
- IMB_colormanagement_display_to_scene_linear_v3(col_conv, eye->display);
- }
- else {
- copy_v3_v3(col_conv, col);
- }
-
- RNA_property_float_set_array(&eye->ptr, eye->prop, col_conv);
-
- RNA_property_update(C, &eye->ptr, eye->prop);
-}
-
-/* set sample from accumulated values */
-static void eyedropper_color_set_accum(bContext *C, Eyedropper *eye)
-{
- float col[3];
- mul_v3_v3fl(col, eye->accum_col, 1.0f / (float)eye->accum_tot);
- eyedropper_color_set(C, eye, col);
-}
-
-/* single point sample & set */
-static void eyedropper_color_sample(bContext *C, Eyedropper *eye, int mx, int my)
-{
- float col[3];
- eyedropper_color_sample_fl(C, eye, mx, my, col);
- eyedropper_color_set(C, eye, col);
-}
-
-static void eyedropper_color_sample_accum(bContext *C, Eyedropper *eye, int mx, int my)
-{
- float col[3];
- eyedropper_color_sample_fl(C, eye, mx, my, col);
- /* delay linear conversion */
- add_v3_v3(eye->accum_col, col);
- eye->accum_tot++;
-}
-
-static void eyedropper_cancel(bContext *C, wmOperator *op)
-{
- Eyedropper *eye = op->customdata;
- eyedropper_color_set(C, eye, eye->init_col);
- eyedropper_exit(C, op);
-}
-
-/* main modal status check */
-static int eyedropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- Eyedropper *eye = (Eyedropper *)op->customdata;
-
- /* handle modal keymap */
- if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case EYE_MODAL_CANCEL:
- eyedropper_cancel(C, op);
- return OPERATOR_CANCELLED;
- case EYE_MODAL_SAMPLE_CONFIRM:
- if (eye->accum_tot == 0) {
- eyedropper_color_sample(C, eye, event->x, event->y);
- }
- else {
- eyedropper_color_set_accum(C, eye);
- }
- eyedropper_exit(C, op);
- return OPERATOR_FINISHED;
- case EYE_MODAL_SAMPLE_BEGIN:
- /* enable accum and make first sample */
- eye->accum_start = true;
- eyedropper_color_sample_accum(C, eye, event->x, event->y);
- break;
- case EYE_MODAL_SAMPLE_RESET:
- eye->accum_tot = 0;
- zero_v3(eye->accum_col);
- eyedropper_color_sample_accum(C, eye, event->x, event->y);
- eyedropper_color_set_accum(C, eye);
- break;
- }
- }
- else if (event->type == MOUSEMOVE) {
- if (eye->accum_start) {
- /* button is pressed so keep sampling */
- eyedropper_color_sample_accum(C, eye, event->x, event->y);
- eyedropper_color_set_accum(C, eye);
- }
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-/* Modal Operator init */
-static int eyedropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
- /* init */
- if (eyedropper_init(C, op)) {
- WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
-
- /* add temp handler */
- WM_event_add_modal_handler(C, op);
-
- return OPERATOR_RUNNING_MODAL;
- }
- else {
- eyedropper_exit(C, op);
- return OPERATOR_CANCELLED;
- }
-}
-
-/* Repeat operator */
-static int eyedropper_exec(bContext *C, wmOperator *op)
-{
- /* init */
- if (eyedropper_init(C, op)) {
-
- /* do something */
-
- /* cleanup */
- eyedropper_exit(C, op);
-
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static int eyedropper_poll(bContext *C)
-{
- PointerRNA ptr;
- PropertyRNA *prop;
- int index_dummy;
- uiBut *but;
-
- /* Only color buttons */
- if ((CTX_wm_window(C) != NULL) &&
- (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
- (but->type == UI_BTYPE_COLOR))
- {
- return 1;
- }
-
- return 0;
-}
-
-void UI_OT_eyedropper_color(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Eyedropper";
- ot->idname = "UI_OT_eyedropper_color";
- ot->description = "Sample a color from the Blender Window to store in a property";
-
- /* api callbacks */
- ot->invoke = eyedropper_invoke;
- ot->modal = eyedropper_modal;
- ot->cancel = eyedropper_cancel;
- ot->exec = eyedropper_exec;
- ot->poll = eyedropper_poll;
-
- /* flags */
- ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
-
- /* properties */
-}
-
-/** \} */
-
-
-/* -------------------------------------------------------------------- */
-/* Data Dropper */
-
-/** \name Eyedropper (ID data-blocks)
- *
- * \note: datadropper is only internal name to avoid confusion in this file.
- * \{ */
-
-typedef struct DataDropper {
- PointerRNA ptr;
- PropertyRNA *prop;
- short idcode;
- const char *idcode_name;
-
- ID *init_id; /* for resetting on cancel */
-
- ARegionType *art;
- void *draw_handle_pixel;
- char name[200];
-} DataDropper;
-
-
-static void datadropper_draw_cb(const struct bContext *C, ARegion *ar, void *arg)
-{
- DataDropper *ddr = arg;
- eyedropper_draw_cursor_text(C, ar, ddr->name);
-}
-
-
-static int datadropper_init(bContext *C, wmOperator *op)
-{
- DataDropper *ddr;
- int index_dummy;
- StructRNA *type;
-
- SpaceType *st;
- ARegionType *art;
-
- st = BKE_spacetype_from_id(SPACE_VIEW3D);
- art = BKE_regiontype_from_id(st, RGN_TYPE_WINDOW);
-
- op->customdata = ddr = MEM_callocN(sizeof(DataDropper), "DataDropper");
-
- UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &index_dummy);
-
- if ((ddr->ptr.data == NULL) ||
- (ddr->prop == NULL) ||
- (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
- (RNA_property_type(ddr->prop) != PROP_POINTER))
- {
- return false;
- }
-
- ddr->art = art;
- ddr->draw_handle_pixel = ED_region_draw_cb_activate(art, datadropper_draw_cb, ddr, REGION_DRAW_POST_PIXEL);
-
- type = RNA_property_pointer_type(&ddr->ptr, ddr->prop);
- ddr->idcode = RNA_type_to_ID_code(type);
- BLI_assert(ddr->idcode != 0);
- /* Note we can translate here (instead of on draw time), because this struct has very short lifetime. */
- ddr->idcode_name = TIP_(BKE_idcode_to_name(ddr->idcode));
-
- PointerRNA ptr = RNA_property_pointer_get(&ddr->ptr, ddr->prop);
- ddr->init_id = ptr.id.data;
-
- return true;
-}
-
-static void datadropper_exit(bContext *C, wmOperator *op)
-{
- WM_cursor_modal_restore(CTX_wm_window(C));
-
- if (op->customdata) {
- DataDropper *ddr = (DataDropper *)op->customdata;
-
- if (ddr->art) {
- ED_region_draw_cb_exit(ddr->art, ddr->draw_handle_pixel);
- }
-
- MEM_freeN(op->customdata);
-
- op->customdata = NULL;
- }
-
- WM_event_add_mousemove(C);
-}
-
-/* *** datadropper id helper functions *** */
-/**
- * \brief get the ID from the screen.
- *
- */
-static void datadropper_id_sample_pt(bContext *C, DataDropper *ddr, int mx, int my, ID **r_id)
-{
- /* we could use some clever */
- wmWindow *win = CTX_wm_window(C);
- ScrArea *sa = BKE_screen_find_area_xy(win->screen, -1, mx, my);
-
- ScrArea *area_prev = CTX_wm_area(C);
- ARegion *ar_prev = CTX_wm_region(C);
-
- ddr->name[0] = '\0';
-
- if (sa) {
- if (sa->spacetype == SPACE_VIEW3D) {
- ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
- if (ar) {
- const int mval[2] = {
- mx - ar->winrct.xmin,
- my - ar->winrct.ymin};
- Base *base;
-
- CTX_wm_area_set(C, sa);
- CTX_wm_region_set(C, ar);
-
- /* grr, always draw else we leave stale text */
- ED_region_tag_redraw(ar);
-
- base = ED_view3d_give_base_under_cursor(C, mval);
- if (base) {
- Object *ob = base->object;
- ID *id = NULL;
- if (ddr->idcode == ID_OB) {
- id = (ID *)ob;
- }
- else if (ob->data) {
- if (GS(((ID *)ob->data)->name) == ddr->idcode) {
- id = (ID *)ob->data;
- }
- else {
- BLI_snprintf(ddr->name, sizeof(ddr->name), "Incompatible, expected a %s",
- ddr->idcode_name);
- }
- }
-
- if (id) {
- BLI_snprintf(ddr->name, sizeof(ddr->name), "%s: %s",
- ddr->idcode_name, id->name + 2);
- *r_id = id;
- }
- }
- }
- }
- }
-
- CTX_wm_area_set(C, area_prev);
- CTX_wm_region_set(C, ar_prev);
-}
-
-/* sets the ID, returns success */
-static bool datadropper_id_set(bContext *C, DataDropper *ddr, ID *id)
-{
- PointerRNA ptr_value;
-
- RNA_id_pointer_create(id, &ptr_value);
-
- RNA_property_pointer_set(&ddr->ptr, ddr->prop, ptr_value);
-
- RNA_property_update(C, &ddr->ptr, ddr->prop);
-
- ptr_value = RNA_property_pointer_get(&ddr->ptr, ddr->prop);
-
- return (ptr_value.id.data == id);
-}
-
-/* single point sample & set */
-static bool datadropper_id_sample(bContext *C, DataDropper *ddr, int mx, int my)
-{
- ID *id = NULL;
-
- datadropper_id_sample_pt(C, ddr, mx, my, &id);
- return datadropper_id_set(C, ddr, id);
-}
-
-static void datadropper_cancel(bContext *C, wmOperator *op)
-{
- DataDropper *ddr = op->customdata;
- datadropper_id_set(C, ddr, ddr->init_id);
- datadropper_exit(C, op);
-}
-
-/* main modal status check */
-static int datadropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- DataDropper *ddr = (DataDropper *)op->customdata;
-
- /* handle modal keymap */
- if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case EYE_MODAL_CANCEL:
- datadropper_cancel(C, op);
- return OPERATOR_CANCELLED;
- case EYE_MODAL_SAMPLE_CONFIRM:
- {
- bool success;
-
- success = datadropper_id_sample(C, ddr, event->x, event->y);
- datadropper_exit(C, op);
-
- if (success) {
- return OPERATOR_FINISHED;
- }
- else {
- BKE_report(op->reports, RPT_WARNING, "Failed to set value");
- return OPERATOR_CANCELLED;
- }
- }
- }
- }
- else if (event->type == MOUSEMOVE) {
- ID *id = NULL;
- datadropper_id_sample_pt(C, ddr, event->x, event->y, &id);
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-/* Modal Operator init */
-static int datadropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
- /* init */
- if (datadropper_init(C, op)) {
- WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
-
- /* add temp handler */
- WM_event_add_modal_handler(C, op);
-
- return OPERATOR_RUNNING_MODAL;
- }
- else {
- datadropper_exit(C, op);
- return OPERATOR_CANCELLED;
- }
-}
-
-/* Repeat operator */
-static int datadropper_exec(bContext *C, wmOperator *op)
-{
- /* init */
- if (datadropper_init(C, op)) {
- /* cleanup */
- datadropper_exit(C, op);
-
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static int datadropper_poll(bContext *C)
-{
- PointerRNA ptr;
- PropertyRNA *prop;
- int index_dummy;
- uiBut *but;
-
- /* data dropper only supports object data */
- if ((CTX_wm_window(C) != NULL) &&
- (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
- (but->type == UI_BTYPE_SEARCH_MENU) &&
- (but->flag & UI_BUT_VALUE_CLEAR))
- {
- if (prop && RNA_property_type(prop) == PROP_POINTER) {
- StructRNA *type = RNA_property_pointer_type(&ptr, prop);
- const short idcode = RNA_type_to_ID_code(type);
- if ((idcode == ID_OB) || OB_DATA_SUPPORT_ID(idcode)) {
- return 1;
- }
- }
- }
-
- return 0;
-}
-
-void UI_OT_eyedropper_id(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Eyedropper Data-Block";
- ot->idname = "UI_OT_eyedropper_id";
- ot->description = "Sample a data-block from the 3D View to store in a property";
-
- /* api callbacks */
- ot->invoke = datadropper_invoke;
- ot->modal = datadropper_modal;
- ot->cancel = datadropper_cancel;
- ot->exec = datadropper_exec;
- ot->poll = datadropper_poll;
-
- /* flags */
- ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
-
- /* properties */
-}
-
-/** \} */
-
-
-/* -------------------------------------------------------------------- */
-/* Depth Dropper */
-
-/** \name Eyedropper (Depth)
- *
- * \note: depthdropper is only internal name to avoid confusion in this file.
- * \{ */
-
-typedef struct DepthDropper {
- PointerRNA ptr;
- PropertyRNA *prop;
-
- float init_depth; /* for resetting on cancel */
-
- bool accum_start; /* has mouse been presed */
- float accum_depth;
- int accum_tot;
-
- ARegionType *art;
- void *draw_handle_pixel;
- char name[200];
-} DepthDropper;
-
-
-static void depthdropper_draw_cb(const struct bContext *C, ARegion *ar, void *arg)
-{
- DepthDropper *ddr = arg;
- eyedropper_draw_cursor_text(C, ar, ddr->name);
-}
-
-
-static int depthdropper_init(bContext *C, wmOperator *op)
-{
- DepthDropper *ddr;
- int index_dummy;
-
- SpaceType *st;
- ARegionType *art;
-
- st = BKE_spacetype_from_id(SPACE_VIEW3D);
- art = BKE_regiontype_from_id(st, RGN_TYPE_WINDOW);
-
- op->customdata = ddr = MEM_callocN(sizeof(DepthDropper), "DepthDropper");
-
- UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &index_dummy);
-
- /* fallback to the active camera's dof */
- if (ddr->prop == NULL) {
- RegionView3D *rv3d = CTX_wm_region_view3d(C);
- if (rv3d && rv3d->persp == RV3D_CAMOB) {
- View3D *v3d = CTX_wm_view3d(C);
- if (v3d->camera && v3d->camera->data && !ID_IS_LINKED_DATABLOCK(v3d->camera->data)) {
- RNA_id_pointer_create(v3d->camera->data, &ddr->ptr);
- ddr->prop = RNA_struct_find_property(&ddr->ptr, "dof_distance");
- }
- }
- }
-
- if ((ddr->ptr.data == NULL) ||
- (ddr->prop == NULL) ||
- (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
- (RNA_property_type(ddr->prop) != PROP_FLOAT))
- {
- return false;
- }
-
- ddr->art = art;
- ddr->draw_handle_pixel = ED_region_draw_cb_activate(art, depthdropper_draw_cb, ddr, REGION_DRAW_POST_PIXEL);
- ddr->init_depth = RNA_property_float_get(&ddr->ptr, ddr->prop);
-
- return true;
-}
-
-static void depthdropper_exit(bContext *C, wmOperator *op)
-{
- WM_cursor_modal_restore(CTX_wm_window(C));
-
- if (op->customdata) {
- DepthDropper *ddr = (DepthDropper *)op->customdata;
-
- if (ddr->art) {
- ED_region_draw_cb_exit(ddr->art, ddr->draw_handle_pixel);
- }
-
- MEM_freeN(op->customdata);
-
- op->customdata = NULL;
- }
-}
-
-/* *** depthdropper id helper functions *** */
-/**
- * \brief get the ID from the screen.
- *
- */
-static void depthdropper_depth_sample_pt(bContext *C, DepthDropper *ddr, int mx, int my, float *r_depth)
-{
- /* we could use some clever */
- wmWindow *win = CTX_wm_window(C);
- ScrArea *sa = BKE_screen_find_area_xy(win->screen, SPACE_TYPE_ANY, mx, my);
- Scene *scene = win->screen->scene;
- UnitSettings *unit = &scene->unit;
- const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
-
- ScrArea *area_prev = CTX_wm_area(C);
- ARegion *ar_prev = CTX_wm_region(C);
-
- ddr->name[0] = '\0';
-
- if (sa) {
- if (sa->spacetype == SPACE_VIEW3D) {
- ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
- if (ar) {
- View3D *v3d = sa->spacedata.first;
- RegionView3D *rv3d = ar->regiondata;
- /* weak, we could pass in some reference point */
- const float *view_co = v3d->camera ? v3d->camera->obmat[3] : rv3d->viewinv[3];
- const int mval[2] = {
- mx - ar->winrct.xmin,
- my - ar->winrct.ymin};
- float co[3];
-
- CTX_wm_area_set(C, sa);
- CTX_wm_region_set(C, ar);
-
- /* grr, always draw else we leave stale text */
- ED_region_tag_redraw(ar);
-
- view3d_operator_needs_opengl(C);
-
- if (ED_view3d_autodist(scene, ar, v3d, mval, co, true, NULL)) {
- const float mval_center_fl[2] = {
- (float)ar->winx / 2,
- (float)ar->winy / 2};
- float co_align[3];
-
- /* quick way to get view-center aligned point */
- ED_view3d_win_to_3d(v3d, ar, co, mval_center_fl, co_align);
-
- *r_depth = len_v3v3(view_co, co_align);
-
- bUnit_AsString(ddr->name, sizeof(ddr->name),
- (double)*r_depth,
- 4, unit->system, B_UNIT_LENGTH, do_split, false);
- }
- else {
- BLI_strncpy(ddr->name, "Nothing under cursor", sizeof(ddr->name));
- }
- }
- }
- }
-
- CTX_wm_area_set(C, area_prev);
- CTX_wm_region_set(C, ar_prev);
-}
-
-/* sets the sample depth RGB, maintaining A */
-static void depthdropper_depth_set(bContext *C, DepthDropper *ddr, const float depth)
-{
- RNA_property_float_set(&ddr->ptr, ddr->prop, depth);
- RNA_property_update(C, &ddr->ptr, ddr->prop);
-}
-
-/* set sample from accumulated values */
-static void depthdropper_depth_set_accum(bContext *C, DepthDropper *ddr)
-{
- float depth = ddr->accum_depth;
- if (ddr->accum_tot) {
- depth /= (float)ddr->accum_tot;
- }
- depthdropper_depth_set(C, ddr, depth);
-}
-
-/* single point sample & set */
-static void depthdropper_depth_sample(bContext *C, DepthDropper *ddr, int mx, int my)
-{
- float depth = -1.0f;
- if (depth != -1.0f) {
- depthdropper_depth_sample_pt(C, ddr, mx, my, &depth);
- depthdropper_depth_set(C, ddr, depth);
- }
-}
-
-static void depthdropper_depth_sample_accum(bContext *C, DepthDropper *ddr, int mx, int my)
-{
- float depth = -1.0f;
- depthdropper_depth_sample_pt(C, ddr, mx, my, &depth);
- if (depth != -1.0f) {
- ddr->accum_depth += depth;
- ddr->accum_tot++;
- }
-}
-
-static void depthdropper_cancel(bContext *C, wmOperator *op)
-{
- DepthDropper *ddr = op->customdata;
- depthdropper_depth_set(C, ddr, ddr->init_depth);
- depthdropper_exit(C, op);
-}
-
-/* main modal status check */
-static int depthdropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- DepthDropper *ddr = (DepthDropper *)op->customdata;
-
- /* handle modal keymap */
- if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case EYE_MODAL_CANCEL:
- depthdropper_cancel(C, op);
- return OPERATOR_CANCELLED;
- case EYE_MODAL_SAMPLE_CONFIRM:
- if (ddr->accum_tot == 0) {
- depthdropper_depth_sample(C, ddr, event->x, event->y);
- }
- else {
- depthdropper_depth_set_accum(C, ddr);
- }
- depthdropper_exit(C, op);
- return OPERATOR_FINISHED;
- case EYE_MODAL_SAMPLE_BEGIN:
- /* enable accum and make first sample */
- ddr->accum_start = true;
- depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
- break;
- case EYE_MODAL_SAMPLE_RESET:
- ddr->accum_tot = 0;
- ddr->accum_depth = 0.0f;
- depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
- depthdropper_depth_set_accum(C, ddr);
- break;
- }
- }
- else if (event->type == MOUSEMOVE) {
- if (ddr->accum_start) {
- /* button is pressed so keep sampling */
- depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
- depthdropper_depth_set_accum(C, ddr);
- }
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-/* Modal Operator init */
-static int depthdropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
- /* init */
- if (depthdropper_init(C, op)) {
- WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
-
- /* add temp handler */
- WM_event_add_modal_handler(C, op);
-
- return OPERATOR_RUNNING_MODAL;
- }
- else {
- depthdropper_exit(C, op);
- return OPERATOR_CANCELLED;
- }
-}
-
-/* Repeat operator */
-static int depthdropper_exec(bContext *C, wmOperator *op)
-{
- /* init */
- if (depthdropper_init(C, op)) {
- /* cleanup */
- depthdropper_exit(C, op);
-
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static int depthdropper_poll(bContext *C)
-{
- PointerRNA ptr;
- PropertyRNA *prop;
- int index_dummy;
- uiBut *but;
-
- /* check if there's an active button taking depth value */
- if ((CTX_wm_window(C) != NULL) &&
- (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
- (but->type == UI_BTYPE_NUM) &&
- (prop != NULL))
- {
- if ((RNA_property_type(prop) == PROP_FLOAT) &&
- (RNA_property_subtype(prop) & PROP_UNIT_LENGTH) &&
- (RNA_property_array_check(prop) == false))
- {
- return 1;
- }
- }
- else {
- RegionView3D *rv3d = CTX_wm_region_view3d(C);
- if (rv3d && rv3d->persp == RV3D_CAMOB) {
- View3D *v3d = CTX_wm_view3d(C);
- if (v3d->camera && v3d->camera->data && !ID_IS_LINKED_DATABLOCK(v3d->camera->data)) {
- return 1;
- }
- }
- }
-
- return 0;
-}
-
-void UI_OT_eyedropper_depth(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Eyedropper Depth";
- ot->idname = "UI_OT_eyedropper_depth";
- ot->description = "Sample depth from the 3D view";
-
- /* api callbacks */
- ot->invoke = depthdropper_invoke;
- ot->modal = depthdropper_modal;
- ot->cancel = depthdropper_cancel;
- ot->exec = depthdropper_exec;
- ot->poll = depthdropper_poll;
-
- /* flags */
- ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
-
- /* properties */
-}
-
-/** \} */
-
-/* -------------------------------------------------------------------- */
-/* Eyedropper
- */
-
-/* NOTE: This is here (instead of in drivers.c) because we need access the button internals,
- * which we cannot access outside of the interface module
- */
-
-/** \name Eyedropper (Driver Target)
- * \{ */
-
-typedef struct DriverDropper {
- /* Destination property (i.e. where we'll add a driver) */
- PointerRNA ptr;
- PropertyRNA *prop;
- int index;
-
- // TODO: new target?
-} DriverDropper;
-
-static bool driverdropper_init(bContext *C, wmOperator *op)
-{
- DriverDropper *ddr;
- uiBut *but;
-
- op->customdata = ddr = MEM_callocN(sizeof(DriverDropper), "DriverDropper");
-
- but = UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &ddr->index);
-
- if ((ddr->ptr.data == NULL) ||
- (ddr->prop == NULL) ||
- (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
- (RNA_property_animateable(&ddr->ptr, ddr->prop) == false) ||
- (but->flag & UI_BUT_DRIVEN))
- {
- return false;
- }
-
- return true;
-}
-
-static void driverdropper_exit(bContext *C, wmOperator *op)
-{
- WM_cursor_modal_restore(CTX_wm_window(C));
-
- if (op->customdata) {
- MEM_freeN(op->customdata);
- op->customdata = NULL;
- }
-}
-
-static void driverdropper_sample(bContext *C, wmOperator *op, const wmEvent *event)
-{
- DriverDropper *ddr = (DriverDropper *)op->customdata;
- uiBut *but = eyedropper_get_property_button_under_mouse(C, event);
-
- short mapping_type = RNA_enum_get(op->ptr, "mapping_type");
- short flag = 0;
-
- /* we can only add a driver if we know what RNA property it corresponds to */
- if (but == NULL) {
- return;
- }
- else {
- /* Get paths for src... */
- PointerRNA *target_ptr = &but->rnapoin;
- PropertyRNA *target_prop = but->rnaprop;
- int target_index = but->rnaindex;
-
- char *target_path = RNA_path_from_ID_to_property(target_ptr, target_prop);
-
- /* ... and destination */
- char *dst_path = BKE_animdata_driver_path_hack(C, &ddr->ptr, ddr->prop, NULL);
-
- /* Now create driver(s) */
- if (target_path && dst_path) {
- int success = ANIM_add_driver_with_target(op->reports,
- ddr->ptr.id.data, dst_path, ddr->index,
- target_ptr->id.data, target_path, target_index,
- flag, DRIVER_TYPE_PYTHON, mapping_type);
-
- if (success) {
- /* send updates */
- UI_context_update_anim_flag(C);
- DAG_relations_tag_update(CTX_data_main(C));
- DAG_id_tag_update(ddr->ptr.id.data, OB_RECALC_OB | OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_ANIMATION | ND_FCURVES_ORDER, NULL); // XXX
- }
- }
-
- /* cleanup */
- if (target_path)
- MEM_freeN(target_path);
- if (dst_path)
- MEM_freeN(dst_path);
- }
-}
-
-static void driverdropper_cancel(bContext *C, wmOperator *op)
-{
- driverdropper_exit(C, op);
-}
-
-/* main modal status check */
-static int driverdropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- /* handle modal keymap */
- if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case EYE_MODAL_CANCEL:
- driverdropper_cancel(C, op);
- return OPERATOR_CANCELLED;
-
- case EYE_MODAL_SAMPLE_CONFIRM:
- driverdropper_sample(C, op, event);
- driverdropper_exit(C, op);
-
- return OPERATOR_FINISHED;
- }
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-/* Modal Operator init */
-static int driverdropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
-{
- /* init */
- if (driverdropper_init(C, op)) {
- WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
-
- /* add temp handler */
- WM_event_add_modal_handler(C, op);
-
- return OPERATOR_RUNNING_MODAL;
- }
- else {
- driverdropper_exit(C, op);
- return OPERATOR_CANCELLED;
- }
-}
-
-/* Repeat operator */
-static int driverdropper_exec(bContext *C, wmOperator *op)
-{
- /* init */
- if (driverdropper_init(C, op)) {
- /* cleanup */
- driverdropper_exit(C, op);
-
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static int driverdropper_poll(bContext *C)
-{
- if (!CTX_wm_window(C)) return 0;
- else return 1;
-}
-
-void UI_OT_eyedropper_driver(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Eyedropper Driver";
- ot->idname = "UI_OT_eyedropper_driver";
- ot->description = "Pick a property to use as a driver target";
-
- /* api callbacks */
- ot->invoke = driverdropper_invoke;
- ot->modal = driverdropper_modal;
- ot->cancel = driverdropper_cancel;
- ot->exec = driverdropper_exec;
- ot->poll = driverdropper_poll;
-
- /* flags */
- ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL | OPTYPE_UNDO;
-
- /* properties */
- RNA_def_enum(ot->srna, "mapping_type", prop_driver_create_mapping_types, 0,
- "Mapping Type", "Method used to match target and driven properties");
-}
-
-/** \} */
diff --git a/source/blender/editors/interface/interface_eyedropper_color.c b/source/blender/editors/interface/interface_eyedropper_color.c
new file mode 100644
index 00000000000..052da74623f
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_color.c
@@ -0,0 +1,356 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2009 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_color.c
+ * \ingroup edinterface
+ *
+ * Eyedropper (RGB Color)
+ *
+ * Defines:
+ * - #UI_OT_eyedropper_color
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_space_types.h"
+#include "DNA_screen_types.h"
+
+#include "BLI_math_vector.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+
+#include "RNA_access.h"
+
+#include "BIF_gl.h"
+
+#include "UI_interface.h"
+
+#include "IMB_colormanagement.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "interface_intern.h"
+
+#include "ED_image.h"
+#include "ED_node.h"
+#include "ED_clip.h"
+
+#include "interface_eyedropper_intern.h"
+
+typedef struct Eyedropper {
+ struct ColorManagedDisplay *display;
+
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index;
+
+ float init_col[3]; /* for resetting on cancel */
+
+ bool accum_start; /* has mouse been pressed */
+ float accum_col[3];
+ int accum_tot;
+} Eyedropper;
+
+static bool eyedropper_init(bContext *C, wmOperator *op)
+{
+ Scene *scene = CTX_data_scene(C);
+ Eyedropper *eye;
+
+ op->customdata = eye = MEM_callocN(sizeof(Eyedropper), "Eyedropper");
+
+ UI_context_active_but_prop_get(C, &eye->ptr, &eye->prop, &eye->index);
+
+ if ((eye->ptr.data == NULL) ||
+ (eye->prop == NULL) ||
+ (RNA_property_editable(&eye->ptr, eye->prop) == false) ||
+ (RNA_property_array_length(&eye->ptr, eye->prop) < 3) ||
+ (RNA_property_type(eye->prop) != PROP_FLOAT))
+ {
+ return false;
+ }
+
+ if (RNA_property_subtype(eye->prop) != PROP_COLOR) {
+ const char *display_device;
+ float col[4];
+
+ display_device = scene->display_settings.display_device;
+ eye->display = IMB_colormanagement_display_get_named(display_device);
+
+ /* store inital color */
+ RNA_property_float_get_array(&eye->ptr, eye->prop, col);
+ if (eye->display) {
+ IMB_colormanagement_display_to_scene_linear_v3(col, eye->display);
+ }
+ copy_v3_v3(eye->init_col, col);
+ }
+
+ return true;
+}
+
+static void eyedropper_exit(bContext *C, wmOperator *op)
+{
+ WM_cursor_modal_restore(CTX_wm_window(C));
+
+ if (op->customdata) {
+ MEM_freeN(op->customdata);
+ op->customdata = NULL;
+ }
+}
+
+/* *** eyedropper_color_ helper functions *** */
+
+/**
+ * \brief get the color from the screen.
+ *
+ * Special check for image or nodes where we MAY have HDR pixels which don't display.
+ *
+ * \note Exposed by 'interface_eyedropper_intern.h' for use with color band picking.
+ */
+void eyedropper_color_sample_fl(bContext *C, int mx, int my, float r_col[3])
+{
+ /* we could use some clever */
+ wmWindow *win = CTX_wm_window(C);
+ ScrArea *sa = BKE_screen_find_area_xy(win->screen, SPACE_TYPE_ANY, mx, my);
+ const char *display_device = CTX_data_scene(C)->display_settings.display_device;
+ struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
+
+ if (sa) {
+ if (sa->spacetype == SPACE_IMAGE) {
+ ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
+ if (ar) {
+ SpaceImage *sima = sa->spacedata.first;
+ int mval[2] = {mx - ar->winrct.xmin,
+ my - ar->winrct.ymin};
+
+ if (ED_space_image_color_sample(sima, ar, mval, r_col)) {
+ return;
+ }
+ }
+ }
+ else if (sa->spacetype == SPACE_NODE) {
+ ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
+ if (ar) {
+ SpaceNode *snode = sa->spacedata.first;
+ int mval[2] = {mx - ar->winrct.xmin,
+ my - ar->winrct.ymin};
+
+ if (ED_space_node_color_sample(snode, ar, mval, r_col)) {
+ return;
+ }
+ }
+ }
+ else if (sa->spacetype == SPACE_CLIP) {
+ ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
+ if (ar) {
+ SpaceClip *sc = sa->spacedata.first;
+ int mval[2] = {mx - ar->winrct.xmin,
+ my - ar->winrct.ymin};
+
+ if (ED_space_clip_color_sample(sc, ar, mval, r_col)) {
+ return;
+ }
+ }
+ }
+ }
+
+ /* fallback to simple opengl picker */
+ glReadBuffer(GL_FRONT);
+ glReadPixels(mx, my, 1, 1, GL_RGB, GL_FLOAT, r_col);
+ glReadBuffer(GL_BACK);
+
+ IMB_colormanagement_display_to_scene_linear_v3(r_col, display);
+}
+
+/* sets the sample color RGB, maintaining A */
+static void eyedropper_color_set(bContext *C, Eyedropper *eye, const float col[3])
+{
+ float col_conv[4];
+
+ /* to maintain alpha */
+ RNA_property_float_get_array(&eye->ptr, eye->prop, col_conv);
+
+ /* convert from linear rgb space to display space */
+ if (eye->display) {
+ copy_v3_v3(col_conv, col);
+ IMB_colormanagement_scene_linear_to_display_v3(col_conv, eye->display);
+ }
+ else {
+ copy_v3_v3(col_conv, col);
+ }
+
+ RNA_property_float_set_array(&eye->ptr, eye->prop, col_conv);
+
+ RNA_property_update(C, &eye->ptr, eye->prop);
+}
+
+/* set sample from accumulated values */
+static void eyedropper_color_set_accum(bContext *C, Eyedropper *eye)
+{
+ float col[3];
+ mul_v3_v3fl(col, eye->accum_col, 1.0f / (float)eye->accum_tot);
+ eyedropper_color_set(C, eye, col);
+}
+
+/* single point sample & set */
+static void eyedropper_color_sample(bContext *C, Eyedropper *eye, int mx, int my)
+{
+ float col[3];
+ eyedropper_color_sample_fl(C, mx, my, col);
+ eyedropper_color_set(C, eye, col);
+}
+
+static void eyedropper_color_sample_accum(bContext *C, Eyedropper *eye, int mx, int my)
+{
+ float col[3];
+ eyedropper_color_sample_fl(C, mx, my, col);
+ /* delay linear conversion */
+ add_v3_v3(eye->accum_col, col);
+ eye->accum_tot++;
+}
+
+static void eyedropper_cancel(bContext *C, wmOperator *op)
+{
+ Eyedropper *eye = op->customdata;
+ eyedropper_color_set(C, eye, eye->init_col);
+ eyedropper_exit(C, op);
+}
+
+/* main modal status check */
+static int eyedropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ Eyedropper *eye = (Eyedropper *)op->customdata;
+
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_CANCEL:
+ eyedropper_cancel(C, op);
+ return OPERATOR_CANCELLED;
+ case EYE_MODAL_SAMPLE_CONFIRM:
+ if (eye->accum_tot == 0) {
+ eyedropper_color_sample(C, eye, event->x, event->y);
+ }
+ else {
+ eyedropper_color_set_accum(C, eye);
+ }
+ eyedropper_exit(C, op);
+ return OPERATOR_FINISHED;
+ case EYE_MODAL_SAMPLE_BEGIN:
+ /* enable accum and make first sample */
+ eye->accum_start = true;
+ eyedropper_color_sample_accum(C, eye, event->x, event->y);
+ break;
+ case EYE_MODAL_SAMPLE_RESET:
+ eye->accum_tot = 0;
+ zero_v3(eye->accum_col);
+ eyedropper_color_sample_accum(C, eye, event->x, event->y);
+ eyedropper_color_set_accum(C, eye);
+ break;
+ }
+ }
+ else if (event->type == MOUSEMOVE) {
+ if (eye->accum_start) {
+ /* button is pressed so keep sampling */
+ eyedropper_color_sample_accum(C, eye, event->x, event->y);
+ eyedropper_color_set_accum(C, eye);
+ }
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+/* Modal Operator init */
+static int eyedropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ /* init */
+ if (eyedropper_init(C, op)) {
+ WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
+
+ /* add temp handler */
+ WM_event_add_modal_handler(C, op);
+
+ return OPERATOR_RUNNING_MODAL;
+ }
+ else {
+ eyedropper_exit(C, op);
+ return OPERATOR_CANCELLED;
+ }
+}
+
+/* Repeat operator */
+static int eyedropper_exec(bContext *C, wmOperator *op)
+{
+ /* init */
+ if (eyedropper_init(C, op)) {
+
+ /* do something */
+
+ /* cleanup */
+ eyedropper_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+static int eyedropper_poll(bContext *C)
+{
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index_dummy;
+ uiBut *but;
+
+ /* Only color buttons */
+ if ((CTX_wm_window(C) != NULL) &&
+ (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
+ (but->type == UI_BTYPE_COLOR))
+ {
+ return 1;
+ }
+
+ return 0;
+}
+
+void UI_OT_eyedropper_color(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper";
+ ot->idname = "UI_OT_eyedropper_color";
+ ot->description = "Sample a color from the Blender Window to store in a property";
+
+ /* api callbacks */
+ ot->invoke = eyedropper_invoke;
+ ot->modal = eyedropper_modal;
+ ot->cancel = eyedropper_cancel;
+ ot->exec = eyedropper_exec;
+ ot->poll = eyedropper_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
+
+ /* properties */
+}
diff --git a/source/blender/editors/interface/interface_eyedropper_colorband.c b/source/blender/editors/interface/interface_eyedropper_colorband.c
new file mode 100644
index 00000000000..b13d552dbeb
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_colorband.c
@@ -0,0 +1,337 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2009 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_colorband.c
+ * \ingroup edinterface
+ *
+ * Eyedropper (Color Band).
+ *
+ * Operates by either:
+ * - Dragging a straight line, sampling pixels formed by the line to extract a gradient.
+ * - Clicking on points, adding each color to the end of the color-band.
+ *
+ * Defines:
+ * - #UI_OT_eyedropper_colorband
+ * - #UI_OT_eyedropper_colorband_point
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_screen_types.h"
+
+#include "BLI_bitmap_draw_2d.h"
+#include "BLI_math_vector.h"
+
+#include "BKE_context.h"
+#include "BKE_colorband.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "interface_intern.h"
+
+#include "interface_eyedropper_intern.h"
+
+typedef struct Colorband_RNAUpdateCb {
+ PointerRNA ptr;
+ PropertyRNA *prop;
+} Colorband_RNAUpdateCb;
+
+typedef struct EyedropperColorband {
+ int last_x, last_y;
+ /* Alpha is currently fixed at 1.0, may support in future. */
+ float (*color_buffer)[4];
+ int color_buffer_alloc;
+ int color_buffer_len;
+ bool sample_start;
+ ColorBand init_color_band;
+ ColorBand *color_band;
+ PointerRNA ptr;
+ PropertyRNA *prop;
+} EyedropperColorband;
+
+/* For user-data only. */
+struct EyedropperColorband_Context {
+ bContext *context;
+ EyedropperColorband *eye;
+};
+
+static bool eyedropper_colorband_init(bContext *C, wmOperator *op)
+{
+ ColorBand *band = NULL;
+ EyedropperColorband *eye;
+
+ uiBut *but = UI_context_active_but_get(C);
+
+ if (but == NULL) {
+ /* pass */
+ }
+ else if (but->type == UI_BTYPE_COLORBAND) {
+ /* When invoked with a hotkey, we can find the band in 'but->poin'. */
+ band = (ColorBand *)but->poin;
+ }
+ else {
+ /* When invoked from a button it's in custom_data field. */
+ band = (ColorBand *)but->custom_data;
+ }
+
+ if (!band)
+ return false;
+
+ op->customdata = eye = MEM_callocN(sizeof(EyedropperColorband), __func__);
+ eye->color_buffer_alloc = 16;
+ eye->color_buffer = MEM_mallocN(sizeof(*eye->color_buffer) * eye->color_buffer_alloc, __func__);
+ eye->color_buffer_len = 0;
+ eye->color_band = band;
+ eye->init_color_band = *eye->color_band;
+ eye->ptr = ((Colorband_RNAUpdateCb *)but->func_argN)->ptr;
+ eye->prop = ((Colorband_RNAUpdateCb *)but->func_argN)->prop;
+
+ return true;
+}
+
+static void eyedropper_colorband_sample_point(bContext *C, EyedropperColorband *eye, int mx, int my)
+{
+ if (eye->last_x != mx || eye->last_y != my) {
+ float col[4];
+ col[3] = 1.0f; /* TODO: sample alpha */
+ eyedropper_color_sample_fl(C, mx, my, col);
+ if (eye->color_buffer_len + 1 == eye->color_buffer_alloc) {
+ eye->color_buffer_alloc *= 2;
+ eye->color_buffer = MEM_reallocN(eye->color_buffer, sizeof(*eye->color_buffer) * eye->color_buffer_alloc);
+ }
+ copy_v4_v4(eye->color_buffer[eye->color_buffer_len], col);
+ eye->color_buffer_len += 1;
+ eye->last_x = mx;
+ eye->last_y = my;
+ }
+}
+
+static bool eyedropper_colorband_sample_callback(int mx, int my, void *userdata)
+{
+ struct EyedropperColorband_Context *data = userdata;
+ bContext *C = data->context;
+ EyedropperColorband *eye = data->eye;
+ eyedropper_colorband_sample_point(C, eye, mx, my);
+ return true;
+}
+
+static void eyedropper_colorband_sample_segment(bContext *C, EyedropperColorband *eye, int mx, int my)
+{
+ /* Since the mouse tends to move rather rapidly we use #BLI_bitmap_draw_2d_line_v2v2i
+ * to interpolate between the reported coordinates */
+ struct EyedropperColorband_Context userdata = {C, eye};
+ int p1[2] = {eye->last_x, eye->last_y};
+ int p2[2] = {mx, my};
+ BLI_bitmap_draw_2d_line_v2v2i(p1, p2, eyedropper_colorband_sample_callback, &userdata);
+}
+
+static void eyedropper_colorband_exit(bContext *C, wmOperator *op)
+{
+ WM_cursor_modal_restore(CTX_wm_window(C));
+
+ if (op->customdata) {
+ EyedropperColorband *eye = op->customdata;
+ MEM_freeN(eye->color_buffer);
+ MEM_freeN(eye);
+ op->customdata = NULL;
+ }
+}
+
+static void eyedropper_colorband_apply(bContext *C, wmOperator *op)
+{
+ EyedropperColorband *eye = op->customdata;
+ /* Always filter, avoids noise in resulting color-band. */
+ bool filter_samples = true;
+ BKE_colorband_init_from_table_rgba(eye->color_band, eye->color_buffer, eye->color_buffer_len, filter_samples);
+ RNA_property_update(C, &eye->ptr, eye->prop);
+}
+
+static void eyedropper_colorband_cancel(bContext *C, wmOperator *op)
+{
+ EyedropperColorband *eye = op->customdata;
+ *eye->color_band = eye->init_color_band;
+ RNA_property_update(C, &eye->ptr, eye->prop);
+ eyedropper_colorband_exit(C, op);
+}
+
+/* main modal status check */
+static int eyedropper_colorband_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ EyedropperColorband *eye = op->customdata;
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_CANCEL:
+ eyedropper_colorband_cancel(C, op);
+ return OPERATOR_CANCELLED;
+ case EYE_MODAL_SAMPLE_CONFIRM:
+ eyedropper_colorband_sample_segment(C, eye, event->x, event->y);
+ eyedropper_colorband_apply(C, op);
+ eyedropper_colorband_exit(C, op);
+ return OPERATOR_FINISHED;
+ case EYE_MODAL_SAMPLE_BEGIN:
+ /* enable accum and make first sample */
+ eye->sample_start = true;
+ eyedropper_colorband_sample_point(C, eye, event->x, event->y);
+ eyedropper_colorband_apply(C, op);
+ eye->last_x = event->x;
+ eye->last_y = event->y;
+ break;
+ case EYE_MODAL_SAMPLE_RESET:
+ break;
+ }
+ }
+ else if (event->type == MOUSEMOVE) {
+ if (eye->sample_start) {
+ eyedropper_colorband_sample_segment(C, eye, event->x, event->y);
+ eyedropper_colorband_apply(C, op);
+ }
+ }
+ return OPERATOR_RUNNING_MODAL;
+}
+
+static int eyedropper_colorband_point_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ EyedropperColorband *eye = op->customdata;
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_POINT_CANCEL:
+ eyedropper_colorband_cancel(C, op);
+ return OPERATOR_CANCELLED;
+ case EYE_MODAL_POINT_CONFIRM:
+ eyedropper_colorband_apply(C, op);
+ eyedropper_colorband_exit(C, op);
+ return OPERATOR_FINISHED;
+ case EYE_MODAL_POINT_REMOVE_LAST:
+ if (eye->color_buffer_len > 0) {
+ eye->color_buffer_len -= 1;
+ eyedropper_colorband_apply(C, op);
+ }
+ break;
+ case EYE_MODAL_POINT_SAMPLE:
+ eyedropper_colorband_sample_point(C, eye, event->x, event->y);
+ eyedropper_colorband_apply(C, op);
+ if (eye->color_buffer_len == MAXCOLORBAND ) {
+ eyedropper_colorband_exit(C, op);
+ return OPERATOR_FINISHED;
+ }
+ break;
+ case EYE_MODAL_SAMPLE_RESET:
+ *eye->color_band = eye->init_color_band;
+ RNA_property_update(C, &eye->ptr, eye->prop);
+ eye->color_buffer_len = 0;
+ break;
+ }
+ }
+ return OPERATOR_RUNNING_MODAL;
+}
+
+
+/* Modal Operator init */
+static int eyedropper_colorband_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ /* init */
+ if (eyedropper_colorband_init(C, op)) {
+ WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
+
+ /* add temp handler */
+ WM_event_add_modal_handler(C, op);
+
+ return OPERATOR_RUNNING_MODAL;
+ }
+ else {
+ eyedropper_colorband_exit(C, op);
+ return OPERATOR_CANCELLED;
+ }
+}
+
+/* Repeat operator */
+static int eyedropper_colorband_exec(bContext *C, wmOperator *op)
+{
+ /* init */
+ if (eyedropper_colorband_init(C, op)) {
+
+ /* do something */
+
+ /* cleanup */
+ eyedropper_colorband_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+static int eyedropper_colorband_poll(bContext *C)
+{
+ uiBut *but = UI_context_active_but_get(C);
+ return (but && but->type == UI_BTYPE_COLORBAND);
+}
+
+
+void UI_OT_eyedropper_colorband(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper colorband";
+ ot->idname = "UI_OT_eyedropper_colorband";
+ ot->description = "Sample a color band";
+
+ /* api callbacks */
+ ot->invoke = eyedropper_colorband_invoke;
+ ot->modal = eyedropper_colorband_modal;
+ ot->cancel = eyedropper_colorband_cancel;
+ ot->exec = eyedropper_colorband_exec;
+ ot->poll = eyedropper_colorband_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
+
+ /* properties */
+}
+
+void UI_OT_eyedropper_colorband_point(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper colorband (points)";
+ ot->idname = "UI_OT_eyedropper_colorband_point";
+ ot->description = "Pointsample a color band";
+
+ /* api callbacks */
+ ot->invoke = eyedropper_colorband_invoke;
+ ot->modal = eyedropper_colorband_point_modal;
+ ot->cancel = eyedropper_colorband_cancel;
+ ot->exec = eyedropper_colorband_exec;
+ ot->poll = eyedropper_colorband_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
+
+ /* properties */
+}
diff --git a/source/blender/editors/interface/interface_eyedropper_datablock.c b/source/blender/editors/interface/interface_eyedropper_datablock.c
new file mode 100644
index 00000000000..416022a9dd0
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_datablock.c
@@ -0,0 +1,351 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2009 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_datablock.c
+ * \ingroup edinterface
+ *
+ * Eyedropper (ID data-blocks)
+ *
+ * Defines:
+ * - #UI_OT_eyedropper_id
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_space_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_string.h"
+#include "BLI_math_vector.h"
+
+#include "BLT_translation.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+#include "BKE_report.h"
+#include "BKE_idcode.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_space_api.h"
+#include "ED_screen.h"
+#include "ED_view3d.h"
+
+#include "interface_intern.h"
+#include "interface_eyedropper_intern.h"
+
+/**
+ * \note #DataDropper is only internal name to avoid confusion with other kinds of eye-droppers.
+ */
+typedef struct DataDropper {
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ short idcode;
+ const char *idcode_name;
+
+ ID *init_id; /* for resetting on cancel */
+
+ ARegionType *art;
+ void *draw_handle_pixel;
+ char name[200];
+} DataDropper;
+
+
+static void datadropper_draw_cb(const struct bContext *C, ARegion *ar, void *arg)
+{
+ DataDropper *ddr = arg;
+ eyedropper_draw_cursor_text(C, ar, ddr->name);
+}
+
+
+static int datadropper_init(bContext *C, wmOperator *op)
+{
+ DataDropper *ddr;
+ int index_dummy;
+ StructRNA *type;
+
+ SpaceType *st;
+ ARegionType *art;
+
+ st = BKE_spacetype_from_id(SPACE_VIEW3D);
+ art = BKE_regiontype_from_id(st, RGN_TYPE_WINDOW);
+
+ op->customdata = ddr = MEM_callocN(sizeof(DataDropper), "DataDropper");
+
+ UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &index_dummy);
+
+ if ((ddr->ptr.data == NULL) ||
+ (ddr->prop == NULL) ||
+ (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
+ (RNA_property_type(ddr->prop) != PROP_POINTER))
+ {
+ return false;
+ }
+
+ ddr->art = art;
+ ddr->draw_handle_pixel = ED_region_draw_cb_activate(art, datadropper_draw_cb, ddr, REGION_DRAW_POST_PIXEL);
+
+ type = RNA_property_pointer_type(&ddr->ptr, ddr->prop);
+ ddr->idcode = RNA_type_to_ID_code(type);
+ BLI_assert(ddr->idcode != 0);
+ /* Note we can translate here (instead of on draw time), because this struct has very short lifetime. */
+ ddr->idcode_name = TIP_(BKE_idcode_to_name(ddr->idcode));
+
+ PointerRNA ptr = RNA_property_pointer_get(&ddr->ptr, ddr->prop);
+ ddr->init_id = ptr.id.data;
+
+ return true;
+}
+
+static void datadropper_exit(bContext *C, wmOperator *op)
+{
+ WM_cursor_modal_restore(CTX_wm_window(C));
+
+ if (op->customdata) {
+ DataDropper *ddr = (DataDropper *)op->customdata;
+
+ if (ddr->art) {
+ ED_region_draw_cb_exit(ddr->art, ddr->draw_handle_pixel);
+ }
+
+ MEM_freeN(op->customdata);
+
+ op->customdata = NULL;
+ }
+
+ WM_event_add_mousemove(C);
+}
+
+/* *** datadropper id helper functions *** */
+/**
+ * \brief get the ID from the screen.
+ *
+ */
+static void datadropper_id_sample_pt(bContext *C, DataDropper *ddr, int mx, int my, ID **r_id)
+{
+ /* we could use some clever */
+ wmWindow *win = CTX_wm_window(C);
+ ScrArea *sa = BKE_screen_find_area_xy(win->screen, -1, mx, my);
+
+ ScrArea *area_prev = CTX_wm_area(C);
+ ARegion *ar_prev = CTX_wm_region(C);
+
+ ddr->name[0] = '\0';
+
+ if (sa) {
+ if (sa->spacetype == SPACE_VIEW3D) {
+ ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
+ if (ar) {
+ const int mval[2] = {
+ mx - ar->winrct.xmin,
+ my - ar->winrct.ymin};
+ Base *base;
+
+ CTX_wm_area_set(C, sa);
+ CTX_wm_region_set(C, ar);
+
+ /* grr, always draw else we leave stale text */
+ ED_region_tag_redraw(ar);
+
+ base = ED_view3d_give_base_under_cursor(C, mval);
+ if (base) {
+ Object *ob = base->object;
+ ID *id = NULL;
+ if (ddr->idcode == ID_OB) {
+ id = (ID *)ob;
+ }
+ else if (ob->data) {
+ if (GS(((ID *)ob->data)->name) == ddr->idcode) {
+ id = (ID *)ob->data;
+ }
+ else {
+ BLI_snprintf(ddr->name, sizeof(ddr->name), "Incompatible, expected a %s",
+ ddr->idcode_name);
+ }
+ }
+
+ if (id) {
+ BLI_snprintf(ddr->name, sizeof(ddr->name), "%s: %s",
+ ddr->idcode_name, id->name + 2);
+ *r_id = id;
+ }
+ }
+ }
+ }
+ }
+
+ CTX_wm_area_set(C, area_prev);
+ CTX_wm_region_set(C, ar_prev);
+}
+
+/* sets the ID, returns success */
+static bool datadropper_id_set(bContext *C, DataDropper *ddr, ID *id)
+{
+ PointerRNA ptr_value;
+
+ RNA_id_pointer_create(id, &ptr_value);
+
+ RNA_property_pointer_set(&ddr->ptr, ddr->prop, ptr_value);
+
+ RNA_property_update(C, &ddr->ptr, ddr->prop);
+
+ ptr_value = RNA_property_pointer_get(&ddr->ptr, ddr->prop);
+
+ return (ptr_value.id.data == id);
+}
+
+/* single point sample & set */
+static bool datadropper_id_sample(bContext *C, DataDropper *ddr, int mx, int my)
+{
+ ID *id = NULL;
+
+ datadropper_id_sample_pt(C, ddr, mx, my, &id);
+ return datadropper_id_set(C, ddr, id);
+}
+
+static void datadropper_cancel(bContext *C, wmOperator *op)
+{
+ DataDropper *ddr = op->customdata;
+ datadropper_id_set(C, ddr, ddr->init_id);
+ datadropper_exit(C, op);
+}
+
+/* main modal status check */
+static int datadropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ DataDropper *ddr = (DataDropper *)op->customdata;
+
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_CANCEL:
+ datadropper_cancel(C, op);
+ return OPERATOR_CANCELLED;
+ case EYE_MODAL_SAMPLE_CONFIRM:
+ {
+ bool success;
+
+ success = datadropper_id_sample(C, ddr, event->x, event->y);
+ datadropper_exit(C, op);
+
+ if (success) {
+ return OPERATOR_FINISHED;
+ }
+ else {
+ BKE_report(op->reports, RPT_WARNING, "Failed to set value");
+ return OPERATOR_CANCELLED;
+ }
+ }
+ }
+ }
+ else if (event->type == MOUSEMOVE) {
+ ID *id = NULL;
+ datadropper_id_sample_pt(C, ddr, event->x, event->y, &id);
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+/* Modal Operator init */
+static int datadropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ /* init */
+ if (datadropper_init(C, op)) {
+ WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
+
+ /* add temp handler */
+ WM_event_add_modal_handler(C, op);
+
+ return OPERATOR_RUNNING_MODAL;
+ }
+ else {
+ datadropper_exit(C, op);
+ return OPERATOR_CANCELLED;
+ }
+}
+
+/* Repeat operator */
+static int datadropper_exec(bContext *C, wmOperator *op)
+{
+ /* init */
+ if (datadropper_init(C, op)) {
+ /* cleanup */
+ datadropper_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+static int datadropper_poll(bContext *C)
+{
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index_dummy;
+ uiBut *but;
+
+ /* data dropper only supports object data */
+ if ((CTX_wm_window(C) != NULL) &&
+ (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
+ (but->type == UI_BTYPE_SEARCH_MENU) &&
+ (but->flag & UI_BUT_VALUE_CLEAR))
+ {
+ if (prop && RNA_property_type(prop) == PROP_POINTER) {
+ StructRNA *type = RNA_property_pointer_type(&ptr, prop);
+ const short idcode = RNA_type_to_ID_code(type);
+ if ((idcode == ID_OB) || OB_DATA_SUPPORT_ID(idcode)) {
+ return 1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+void UI_OT_eyedropper_id(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper Data-Block";
+ ot->idname = "UI_OT_eyedropper_id";
+ ot->description = "Sample a data-block from the 3D View to store in a property";
+
+ /* api callbacks */
+ ot->invoke = datadropper_invoke;
+ ot->modal = datadropper_modal;
+ ot->cancel = datadropper_cancel;
+ ot->exec = datadropper_exec;
+ ot->poll = datadropper_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
+
+ /* properties */
+}
diff --git a/source/blender/editors/interface/interface_eyedropper_depth.c b/source/blender/editors/interface/interface_eyedropper_depth.c
new file mode 100644
index 00000000000..b2ba7594fcb
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_depth.c
@@ -0,0 +1,384 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2009 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_depth.c
+ * \ingroup edinterface
+ *
+ * This file defines an eyedropper for picking 3D depth value (primary use is depth-of-field).
+ *
+ * Defines:
+ * - #UI_OT_eyedropper_depth
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_space_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_object_types.h"
+#include "DNA_view3d_types.h"
+
+#include "BLI_string.h"
+#include "BLI_math_vector.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+#include "BKE_unit.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_screen.h"
+#include "ED_space_api.h"
+#include "ED_view3d.h"
+
+#include "interface_intern.h"
+#include "interface_eyedropper_intern.h"
+
+/**
+ * \note #DepthDropper is only internal name to avoid confusion with other kinds of eye-droppers.
+ */
+typedef struct DepthDropper {
+ PointerRNA ptr;
+ PropertyRNA *prop;
+
+ float init_depth; /* for resetting on cancel */
+
+ bool accum_start; /* has mouse been presed */
+ float accum_depth;
+ int accum_tot;
+
+ ARegionType *art;
+ void *draw_handle_pixel;
+ char name[200];
+} DepthDropper;
+
+
+static void depthdropper_draw_cb(const struct bContext *C, ARegion *ar, void *arg)
+{
+ DepthDropper *ddr = arg;
+ eyedropper_draw_cursor_text(C, ar, ddr->name);
+}
+
+
+static int depthdropper_init(bContext *C, wmOperator *op)
+{
+ DepthDropper *ddr;
+ int index_dummy;
+
+ SpaceType *st;
+ ARegionType *art;
+
+ st = BKE_spacetype_from_id(SPACE_VIEW3D);
+ art = BKE_regiontype_from_id(st, RGN_TYPE_WINDOW);
+
+ op->customdata = ddr = MEM_callocN(sizeof(DepthDropper), "DepthDropper");
+
+ UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &index_dummy);
+
+ /* fallback to the active camera's dof */
+ if (ddr->prop == NULL) {
+ RegionView3D *rv3d = CTX_wm_region_view3d(C);
+ if (rv3d && rv3d->persp == RV3D_CAMOB) {
+ View3D *v3d = CTX_wm_view3d(C);
+ if (v3d->camera && v3d->camera->data && !ID_IS_LINKED(v3d->camera->data)) {
+ RNA_id_pointer_create(v3d->camera->data, &ddr->ptr);
+ ddr->prop = RNA_struct_find_property(&ddr->ptr, "dof_distance");
+ }
+ }
+ }
+
+ if ((ddr->ptr.data == NULL) ||
+ (ddr->prop == NULL) ||
+ (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
+ (RNA_property_type(ddr->prop) != PROP_FLOAT))
+ {
+ return false;
+ }
+
+ ddr->art = art;
+ ddr->draw_handle_pixel = ED_region_draw_cb_activate(art, depthdropper_draw_cb, ddr, REGION_DRAW_POST_PIXEL);
+ ddr->init_depth = RNA_property_float_get(&ddr->ptr, ddr->prop);
+
+ return true;
+}
+
+static void depthdropper_exit(bContext *C, wmOperator *op)
+{
+ WM_cursor_modal_restore(CTX_wm_window(C));
+
+ if (op->customdata) {
+ DepthDropper *ddr = (DepthDropper *)op->customdata;
+
+ if (ddr->art) {
+ ED_region_draw_cb_exit(ddr->art, ddr->draw_handle_pixel);
+ }
+
+ MEM_freeN(op->customdata);
+
+ op->customdata = NULL;
+ }
+}
+
+/* *** depthdropper id helper functions *** */
+/**
+ * \brief get the ID from the screen.
+ *
+ */
+static void depthdropper_depth_sample_pt(bContext *C, DepthDropper *ddr, int mx, int my, float *r_depth)
+{
+ /* we could use some clever */
+ wmWindow *win = CTX_wm_window(C);
+ ScrArea *sa = BKE_screen_find_area_xy(win->screen, SPACE_TYPE_ANY, mx, my);
+ Scene *scene = win->screen->scene;
+ UnitSettings *unit = &scene->unit;
+ const bool do_split = (unit->flag & USER_UNIT_OPT_SPLIT) != 0;
+
+ ScrArea *area_prev = CTX_wm_area(C);
+ ARegion *ar_prev = CTX_wm_region(C);
+
+ ddr->name[0] = '\0';
+
+ if (sa) {
+ if (sa->spacetype == SPACE_VIEW3D) {
+ ARegion *ar = BKE_area_find_region_xy(sa, RGN_TYPE_WINDOW, mx, my);
+ if (ar) {
+ View3D *v3d = sa->spacedata.first;
+ RegionView3D *rv3d = ar->regiondata;
+ /* weak, we could pass in some reference point */
+ const float *view_co = v3d->camera ? v3d->camera->obmat[3] : rv3d->viewinv[3];
+ const int mval[2] = {
+ mx - ar->winrct.xmin,
+ my - ar->winrct.ymin};
+ float co[3];
+
+ CTX_wm_area_set(C, sa);
+ CTX_wm_region_set(C, ar);
+
+ /* grr, always draw else we leave stale text */
+ ED_region_tag_redraw(ar);
+
+ view3d_operator_needs_opengl(C);
+
+ if (ED_view3d_autodist(scene, ar, v3d, mval, co, true, NULL)) {
+ const float mval_center_fl[2] = {
+ (float)ar->winx / 2,
+ (float)ar->winy / 2};
+ float co_align[3];
+
+ /* quick way to get view-center aligned point */
+ ED_view3d_win_to_3d(v3d, ar, co, mval_center_fl, co_align);
+
+ *r_depth = len_v3v3(view_co, co_align);
+
+ bUnit_AsString(ddr->name, sizeof(ddr->name),
+ (double)*r_depth,
+ 4, unit->system, B_UNIT_LENGTH, do_split, false);
+ }
+ else {
+ BLI_strncpy(ddr->name, "Nothing under cursor", sizeof(ddr->name));
+ }
+ }
+ }
+ }
+
+ CTX_wm_area_set(C, area_prev);
+ CTX_wm_region_set(C, ar_prev);
+}
+
+/* sets the sample depth RGB, maintaining A */
+static void depthdropper_depth_set(bContext *C, DepthDropper *ddr, const float depth)
+{
+ RNA_property_float_set(&ddr->ptr, ddr->prop, depth);
+ RNA_property_update(C, &ddr->ptr, ddr->prop);
+}
+
+/* set sample from accumulated values */
+static void depthdropper_depth_set_accum(bContext *C, DepthDropper *ddr)
+{
+ float depth = ddr->accum_depth;
+ if (ddr->accum_tot) {
+ depth /= (float)ddr->accum_tot;
+ }
+ depthdropper_depth_set(C, ddr, depth);
+}
+
+/* single point sample & set */
+static void depthdropper_depth_sample(bContext *C, DepthDropper *ddr, int mx, int my)
+{
+ float depth = -1.0f;
+ if (depth != -1.0f) {
+ depthdropper_depth_sample_pt(C, ddr, mx, my, &depth);
+ depthdropper_depth_set(C, ddr, depth);
+ }
+}
+
+static void depthdropper_depth_sample_accum(bContext *C, DepthDropper *ddr, int mx, int my)
+{
+ float depth = -1.0f;
+ depthdropper_depth_sample_pt(C, ddr, mx, my, &depth);
+ if (depth != -1.0f) {
+ ddr->accum_depth += depth;
+ ddr->accum_tot++;
+ }
+}
+
+static void depthdropper_cancel(bContext *C, wmOperator *op)
+{
+ DepthDropper *ddr = op->customdata;
+ depthdropper_depth_set(C, ddr, ddr->init_depth);
+ depthdropper_exit(C, op);
+}
+
+/* main modal status check */
+static int depthdropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ DepthDropper *ddr = (DepthDropper *)op->customdata;
+
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_CANCEL:
+ depthdropper_cancel(C, op);
+ return OPERATOR_CANCELLED;
+ case EYE_MODAL_SAMPLE_CONFIRM:
+ if (ddr->accum_tot == 0) {
+ depthdropper_depth_sample(C, ddr, event->x, event->y);
+ }
+ else {
+ depthdropper_depth_set_accum(C, ddr);
+ }
+ depthdropper_exit(C, op);
+ return OPERATOR_FINISHED;
+ case EYE_MODAL_SAMPLE_BEGIN:
+ /* enable accum and make first sample */
+ ddr->accum_start = true;
+ depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
+ break;
+ case EYE_MODAL_SAMPLE_RESET:
+ ddr->accum_tot = 0;
+ ddr->accum_depth = 0.0f;
+ depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
+ depthdropper_depth_set_accum(C, ddr);
+ break;
+ }
+ }
+ else if (event->type == MOUSEMOVE) {
+ if (ddr->accum_start) {
+ /* button is pressed so keep sampling */
+ depthdropper_depth_sample_accum(C, ddr, event->x, event->y);
+ depthdropper_depth_set_accum(C, ddr);
+ }
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+/* Modal Operator init */
+static int depthdropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ /* init */
+ if (depthdropper_init(C, op)) {
+ WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
+
+ /* add temp handler */
+ WM_event_add_modal_handler(C, op);
+
+ return OPERATOR_RUNNING_MODAL;
+ }
+ else {
+ depthdropper_exit(C, op);
+ return OPERATOR_CANCELLED;
+ }
+}
+
+/* Repeat operator */
+static int depthdropper_exec(bContext *C, wmOperator *op)
+{
+ /* init */
+ if (depthdropper_init(C, op)) {
+ /* cleanup */
+ depthdropper_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+static int depthdropper_poll(bContext *C)
+{
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index_dummy;
+ uiBut *but;
+
+ /* check if there's an active button taking depth value */
+ if ((CTX_wm_window(C) != NULL) &&
+ (but = UI_context_active_but_prop_get(C, &ptr, &prop, &index_dummy)) &&
+ (but->type == UI_BTYPE_NUM) &&
+ (prop != NULL))
+ {
+ if ((RNA_property_type(prop) == PROP_FLOAT) &&
+ (RNA_property_subtype(prop) & PROP_UNIT_LENGTH) &&
+ (RNA_property_array_check(prop) == false))
+ {
+ return 1;
+ }
+ }
+ else {
+ RegionView3D *rv3d = CTX_wm_region_view3d(C);
+ if (rv3d && rv3d->persp == RV3D_CAMOB) {
+ View3D *v3d = CTX_wm_view3d(C);
+ if (v3d->camera && v3d->camera->data && !ID_IS_LINKED(v3d->camera->data)) {
+ return 1;
+ }
+ }
+ }
+
+ return 0;
+}
+
+void UI_OT_eyedropper_depth(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper Depth";
+ ot->idname = "UI_OT_eyedropper_depth";
+ ot->description = "Sample depth from the 3D view";
+
+ /* api callbacks */
+ ot->invoke = depthdropper_invoke;
+ ot->modal = depthdropper_modal;
+ ot->cancel = depthdropper_cancel;
+ ot->exec = depthdropper_exec;
+ ot->poll = depthdropper_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
+
+ /* properties */
+}
diff --git a/source/blender/editors/interface/interface_eyedropper_driver.c b/source/blender/editors/interface/interface_eyedropper_driver.c
new file mode 100644
index 00000000000..1b7407c87dd
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_driver.c
@@ -0,0 +1,232 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2009 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation, Joshua Leung
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_driver.c
+ * \ingroup edinterface
+ *
+ * Eyedropper (Animation Driver Targets).
+ *
+ * Defines:
+ * - #UI_OT_eyedropper_driver
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_anim_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_object_types.h"
+
+#include "BLI_math_vector.h"
+
+#include "BKE_context.h"
+#include "BKE_animsys.h"
+#include "BKE_depsgraph.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+
+#include "UI_interface.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_keyframing.h"
+
+#include "interface_intern.h"
+#include "interface_eyedropper_intern.h"
+
+typedef struct DriverDropper {
+ /* Destination property (i.e. where we'll add a driver) */
+ PointerRNA ptr;
+ PropertyRNA *prop;
+ int index;
+
+ // TODO: new target?
+} DriverDropper;
+
+static bool driverdropper_init(bContext *C, wmOperator *op)
+{
+ DriverDropper *ddr;
+ uiBut *but;
+
+ op->customdata = ddr = MEM_callocN(sizeof(DriverDropper), "DriverDropper");
+
+ but = UI_context_active_but_prop_get(C, &ddr->ptr, &ddr->prop, &ddr->index);
+
+ if ((ddr->ptr.data == NULL) ||
+ (ddr->prop == NULL) ||
+ (RNA_property_editable(&ddr->ptr, ddr->prop) == false) ||
+ (RNA_property_animateable(&ddr->ptr, ddr->prop) == false) ||
+ (but->flag & UI_BUT_DRIVEN))
+ {
+ return false;
+ }
+
+ return true;
+}
+
+static void driverdropper_exit(bContext *C, wmOperator *op)
+{
+ WM_cursor_modal_restore(CTX_wm_window(C));
+
+ if (op->customdata) {
+ MEM_freeN(op->customdata);
+ op->customdata = NULL;
+ }
+}
+
+static void driverdropper_sample(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ DriverDropper *ddr = (DriverDropper *)op->customdata;
+ uiBut *but = eyedropper_get_property_button_under_mouse(C, event);
+
+ short mapping_type = RNA_enum_get(op->ptr, "mapping_type");
+ short flag = 0;
+
+ /* we can only add a driver if we know what RNA property it corresponds to */
+ if (but == NULL) {
+ return;
+ }
+ else {
+ /* Get paths for src... */
+ PointerRNA *target_ptr = &but->rnapoin;
+ PropertyRNA *target_prop = but->rnaprop;
+ int target_index = but->rnaindex;
+
+ char *target_path = RNA_path_from_ID_to_property(target_ptr, target_prop);
+
+ /* ... and destination */
+ char *dst_path = BKE_animdata_driver_path_hack(C, &ddr->ptr, ddr->prop, NULL);
+
+ /* Now create driver(s) */
+ if (target_path && dst_path) {
+ int success = ANIM_add_driver_with_target(op->reports,
+ ddr->ptr.id.data, dst_path, ddr->index,
+ target_ptr->id.data, target_path, target_index,
+ flag, DRIVER_TYPE_PYTHON, mapping_type);
+
+ if (success) {
+ /* send updates */
+ UI_context_update_anim_flag(C);
+ DAG_relations_tag_update(CTX_data_main(C));
+ DAG_id_tag_update(ddr->ptr.id.data, OB_RECALC_OB | OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_FCURVES_ORDER, NULL); // XXX
+ }
+ }
+
+ /* cleanup */
+ if (target_path)
+ MEM_freeN(target_path);
+ if (dst_path)
+ MEM_freeN(dst_path);
+ }
+}
+
+static void driverdropper_cancel(bContext *C, wmOperator *op)
+{
+ driverdropper_exit(C, op);
+}
+
+/* main modal status check */
+static int driverdropper_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ /* handle modal keymap */
+ if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case EYE_MODAL_CANCEL:
+ driverdropper_cancel(C, op);
+ return OPERATOR_CANCELLED;
+
+ case EYE_MODAL_SAMPLE_CONFIRM:
+ driverdropper_sample(C, op, event);
+ driverdropper_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+/* Modal Operator init */
+static int driverdropper_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ /* init */
+ if (driverdropper_init(C, op)) {
+ WM_cursor_modal_set(CTX_wm_window(C), BC_EYEDROPPER_CURSOR);
+
+ /* add temp handler */
+ WM_event_add_modal_handler(C, op);
+
+ return OPERATOR_RUNNING_MODAL;
+ }
+ else {
+ driverdropper_exit(C, op);
+ return OPERATOR_CANCELLED;
+ }
+}
+
+/* Repeat operator */
+static int driverdropper_exec(bContext *C, wmOperator *op)
+{
+ /* init */
+ if (driverdropper_init(C, op)) {
+ /* cleanup */
+ driverdropper_exit(C, op);
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+static int driverdropper_poll(bContext *C)
+{
+ if (!CTX_wm_window(C)) return 0;
+ else return 1;
+}
+
+void UI_OT_eyedropper_driver(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Eyedropper Driver";
+ ot->idname = "UI_OT_eyedropper_driver";
+ ot->description = "Pick a property to use as a driver target";
+
+ /* api callbacks */
+ ot->invoke = driverdropper_invoke;
+ ot->modal = driverdropper_modal;
+ ot->cancel = driverdropper_cancel;
+ ot->exec = driverdropper_exec;
+ ot->poll = driverdropper_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL | OPTYPE_UNDO;
+
+ /* properties */
+ RNA_def_enum(ot->srna, "mapping_type", prop_driver_create_mapping_types, 0,
+ "Mapping Type", "Method used to match target and driven properties");
+}
diff --git a/source/blender/editors/interface/interface_eyedropper_intern.h b/source/blender/editors/interface/interface_eyedropper_intern.h
new file mode 100644
index 00000000000..18935c6cc9f
--- /dev/null
+++ b/source/blender/editors/interface/interface_eyedropper_intern.h
@@ -0,0 +1,54 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_eyedropper_intern.h
+ * \ingroup edinterface
+ *
+ * Share between interface_eyedropper_*.c files.
+ */
+
+#ifndef __INTERFACE_EYEDROPPER_INTERN_H__
+#define __INTERFACE_EYEDROPPER_INTERN_H__
+
+/* interface_eyedropper.c */
+void eyedropper_draw_cursor_text(const struct bContext *C, const struct ARegion *ar, const char *name);
+uiBut *eyedropper_get_property_button_under_mouse(bContext *C, const wmEvent *event);
+
+/* interface_eyedropper_color.c (expose for color-band picker) */
+void eyedropper_color_sample_fl(bContext *C, int mx, int my, float r_col[3]);
+
+/* Used for most eye-dropper operators. */
+enum {
+ EYE_MODAL_CANCEL = 1,
+ EYE_MODAL_SAMPLE_CONFIRM,
+ EYE_MODAL_SAMPLE_BEGIN,
+ EYE_MODAL_SAMPLE_RESET,
+};
+
+/* Color-band point sample. */
+enum {
+ EYE_MODAL_POINT_CANCEL = 1,
+ EYE_MODAL_POINT_SAMPLE,
+ EYE_MODAL_POINT_CONFIRM,
+ EYE_MODAL_POINT_RESET,
+ EYE_MODAL_POINT_REMOVE_LAST,
+};
+
+#endif /* __INTERFACE_EYEDROPPER_INTERN_H__ */
diff --git a/source/blender/editors/interface/interface_handlers.c b/source/blender/editors/interface/interface_handlers.c
index 734cd02a056..9f7cd62227c 100644
--- a/source/blender/editors/interface/interface_handlers.c
+++ b/source/blender/editors/interface/interface_handlers.c
@@ -61,6 +61,7 @@
#include "PIL_time.h"
+#include "BKE_colorband.h"
#include "BKE_blender_undo.h"
#include "BKE_brush.h"
#include "BKE_colortools.h"
@@ -68,13 +69,12 @@
#include "BKE_idprop.h"
#include "BKE_report.h"
#include "BKE_screen.h"
-#include "BKE_texture.h"
#include "BKE_tracking.h"
#include "BKE_unit.h"
#include "BKE_paint.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_keyframing.h"
#include "UI_interface.h"
@@ -87,6 +87,7 @@
#include "WM_api.h"
#include "WM_types.h"
+#include "wm_event_system.h"
#ifdef WITH_INPUT_IME
# include "wm_window.h"
@@ -129,7 +130,6 @@ static bool ui_mouse_motion_keynav_test(struct uiKeyNavLock *keynav, const wmEve
/***************** structs and defines ****************/
-#define BUTTON_TOOLTIP_DELAY 0.500
#define BUTTON_FLASH_DELAY 0.020
#define MENU_SCROLL_INTERVAL 0.1
#define PIE_MENU_INTERVAL 0.01
@@ -295,14 +295,15 @@ typedef struct uiHandleButtonData {
ColorBand *coba;
/* tooltip */
- ARegion *tooltip;
- wmTimer *tooltiptimer;
unsigned int tooltip_force : 1;
/* auto open */
bool used_mouse;
wmTimer *autoopentimer;
+ /* auto open (hold) */
+ wmTimer *hold_action_timer;
+
/* text selection/editing */
/* size of 'str' (including terminator) */
int maxlen;
@@ -380,6 +381,7 @@ typedef struct uiAfterFunc {
void *butm_func_arg;
int a2;
+ wmOperator *popup_op;
wmOperatorType *optype;
int opcontext;
PointerRNA *opptr;
@@ -635,13 +637,24 @@ PointerRNA *ui_handle_afterfunc_add_operator(wmOperatorType *ot, int opcontext,
return ptr;
}
+static void popup_check(bContext *C, wmOperator *op)
+{
+ if (op && op->type->check && op->type->check(C, op)) {
+ /* check for popup and re-layout buttons */
+ ARegion *ar_menu = CTX_wm_menu(C);
+ if (ar_menu)
+ ED_region_tag_refresh_ui(ar_menu);
+ }
+}
+
/**
* Check if a #uiAfterFunc is needed for this button.
*/
static bool ui_afterfunc_check(const uiBlock *block, const uiBut *but)
{
return (but->func || but->funcN || but->rename_func || but->optype || but->rnaprop || block->handle_func ||
- (but->type == UI_BTYPE_BUT_MENU && block->butm_func));
+ (but->type == UI_BTYPE_BUT_MENU && block->butm_func) ||
+ (block->handle && block->handle->popup_op));
}
static void ui_apply_but_func(bContext *C, uiBut *but)
@@ -682,6 +695,9 @@ static void ui_apply_but_func(bContext *C, uiBut *but)
after->butm_func_arg = block->butm_func_arg;
after->a2 = but->a2;
}
+
+ if (block->handle)
+ after->popup_op = block->handle->popup_op;
after->optype = but->optype;
after->opcontext = but->opcontext;
@@ -766,6 +782,9 @@ static void ui_apply_but_funcs_after(bContext *C)
if (after.context)
CTX_store_set(C, after.context);
+ if (after.popup_op)
+ popup_check(C, after.popup_op);
+
if (after.opptr) {
/* free in advance to avoid leak on exit */
opptr = *after.opptr;
@@ -1268,7 +1287,7 @@ static bool ui_drag_toggle_set_xy_xy(
}
}
if (changed) {
- /* apply now, not on release (or if handlers are cancelled for whatever reason) */
+ /* apply now, not on release (or if handlers are canceled for whatever reason) */
ui_apply_but_funcs_after(C);
}
@@ -1421,87 +1440,82 @@ static bool ui_selectcontext_begin(
const bool is_array = RNA_property_array_check(prop);
const int rna_type = RNA_property_type(prop);
- if (!UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path)) {
- goto finally;
- }
-
- selctx_data->elems_len = BLI_listbase_count(&lb);
- if (selctx_data->elems_len == 0) {
- goto finally;
- }
-
- selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
+ if (UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path) &&
+ !BLI_listbase_is_empty(&lb))
+ {
+ selctx_data->elems_len = BLI_listbase_count(&lb);
+ selctx_data->elems = MEM_mallocN(sizeof(uiSelectContextElem) * selctx_data->elems_len, __func__);
- for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
- uiSelectContextElem *other = &selctx_data->elems[i];
- /* TODO,. de-duplicate copy_to_selected_button */
- if (link->ptr.data != ptr.data) {
- if (use_path_from_id) {
- /* Path relative to ID. */
- lprop = NULL;
- RNA_id_pointer_create(link->ptr.id.data, &idptr);
- RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
- }
- else if (path) {
- /* Path relative to elements from list. */
- lprop = NULL;
- RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
- }
- else {
- lptr = link->ptr;
- lprop = prop;
- }
+ for (i = 0, link = lb.first; i < selctx_data->elems_len; i++, link = link->next) {
+ uiSelectContextElem *other = &selctx_data->elems[i];
+ /* TODO,. de-duplicate copy_to_selected_button */
+ if (link->ptr.data != ptr.data) {
+ if (use_path_from_id) {
+ /* Path relative to ID. */
+ lprop = NULL;
+ RNA_id_pointer_create(link->ptr.id.data, &idptr);
+ RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
+ }
+ else if (path) {
+ /* Path relative to elements from list. */
+ lprop = NULL;
+ RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
+ }
+ else {
+ lptr = link->ptr;
+ lprop = prop;
+ }
- /* lptr might not be the same as link->ptr! */
- if ((lptr.data != ptr.data) &&
- (lprop == prop) &&
- RNA_property_editable(&lptr, lprop))
- {
- other->ptr = lptr;
- if (is_array) {
- if (rna_type == PROP_FLOAT) {
- other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
- }
- else if (rna_type == PROP_INT) {
- other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
- }
- /* ignored for now */
+ /* lptr might not be the same as link->ptr! */
+ if ((lptr.data != ptr.data) &&
+ (lprop == prop) &&
+ RNA_property_editable(&lptr, lprop))
+ {
+ other->ptr = lptr;
+ if (is_array) {
+ if (rna_type == PROP_FLOAT) {
+ other->val_f = RNA_property_float_get_index(&lptr, lprop, index);
+ }
+ else if (rna_type == PROP_INT) {
+ other->val_i = RNA_property_int_get_index(&lptr, lprop, index);
+ }
+ /* ignored for now */
#if 0
- else if (rna_type == PROP_BOOLEAN) {
- other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
- }
+ else if (rna_type == PROP_BOOLEAN) {
+ other->val_b = RNA_property_boolean_get_index(&lptr, lprop, index);
+ }
#endif
- }
- else {
- if (rna_type == PROP_FLOAT) {
- other->val_f = RNA_property_float_get(&lptr, lprop);
- }
- else if (rna_type == PROP_INT) {
- other->val_i = RNA_property_int_get(&lptr, lprop);
}
- /* ignored for now */
+ else {
+ if (rna_type == PROP_FLOAT) {
+ other->val_f = RNA_property_float_get(&lptr, lprop);
+ }
+ else if (rna_type == PROP_INT) {
+ other->val_i = RNA_property_int_get(&lptr, lprop);
+ }
+ /* ignored for now */
#if 0
- else if (rna_type == PROP_BOOLEAN) {
- other->val_b = RNA_property_boolean_get(&lptr, lprop);
- }
- else if (rna_type == PROP_ENUM) {
- other->val_i = RNA_property_enum_get(&lptr, lprop);
- }
+ else if (rna_type == PROP_BOOLEAN) {
+ other->val_b = RNA_property_boolean_get(&lptr, lprop);
+ }
+ else if (rna_type == PROP_ENUM) {
+ other->val_i = RNA_property_enum_get(&lptr, lprop);
+ }
#endif
- }
+ }
- continue;
+ continue;
+ }
}
+
+ selctx_data->elems_len -= 1;
+ i -= 1;
}
- selctx_data->elems_len -= 1;
- i -= 1;
+ success = (selctx_data->elems_len != 0);
}
}
- success = (selctx_data->elems_len != 0);
-
-finally:
if (selctx_data->elems_len == 0) {
MEM_SAFE_FREE(selctx_data->elems);
}
@@ -2268,7 +2282,7 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
char buf_copy[UI_MAX_DRAW_STR];
if (array_length == 4) {
- values[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
+ values[3] = RNA_property_float_get_index(&but->rnapoin, but->rnaprop, 3);
}
else {
values[3] = 0.0f;
@@ -2300,7 +2314,7 @@ static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data,
/* Get many decimal places, then strip trailing zeros.
* note: too high values start to give strange results */
char buf_copy[UI_MAX_DRAW_STR];
- ui_but_string_get_ex(but, buf_copy, sizeof(buf_copy), UI_PRECISION_FLOAT_MAX);
+ ui_but_string_get_ex(but, buf_copy, sizeof(buf_copy), UI_PRECISION_FLOAT_MAX, false, NULL);
BLI_str_rstrip_float_zero(buf_copy, '\0');
WM_clipboard_text_set(buf_copy, 0);
@@ -2802,8 +2816,8 @@ static bool ui_textedit_insert_ascii(uiBut *but, uiHandleButtonData *data, char
}
static void ui_textedit_move(
- uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
- const bool select, strCursorJumpType jump)
+ uiBut *but, uiHandleButtonData *data, eStrCursorJumpDirection direction,
+ const bool select, eStrCursorJumpType jump)
{
const char *str = data->str;
const int len = strlen(str);
@@ -2879,7 +2893,7 @@ static void ui_textedit_move(
}
}
-static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
+static bool ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, eStrCursorJumpType jump)
{
char *str = data->str;
const int len = strlen(str);
@@ -3041,6 +3055,7 @@ static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
wmWindow *win = CTX_wm_window(C);
int len;
const bool is_num_but = ELEM(but->type, UI_BTYPE_NUM, UI_BTYPE_NUM_SLIDER);
+ bool no_zero_strip = false;
if (data->str) {
MEM_freeN(data->str);
@@ -3073,14 +3088,16 @@ static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
data->maxlen = ui_but_string_get_max_length(but);
if (data->maxlen != 0) {
data->str = MEM_callocN(sizeof(char) * data->maxlen, "textedit str");
- ui_but_string_get(but, data->str, data->maxlen);
+ /* We do not want to truncate precision to default here, it's nice to show value,
+ * not to edit it - way too much precision is lost then. */
+ ui_but_string_get_ex(but, data->str, data->maxlen, UI_PRECISION_FLOAT_MAX, true, &no_zero_strip);
}
else {
data->is_str_dynamic = true;
data->str = ui_but_string_get_dynamic(but, &data->maxlen);
}
- if (ui_but_is_float(but) && !ui_but_is_unit(but) && !ui_but_anim_expression_get(but, NULL, 0)) {
+ if (ui_but_is_float(but) && !ui_but_is_unit(but) && !ui_but_anim_expression_get(but, NULL, 0) && !no_zero_strip) {
BLI_str_rstrip_float_zero(data->str, '\0');
}
@@ -3359,7 +3376,7 @@ static void ui_do_but_textedit(
if (event->type == WHEELDOWNMOUSE) {
break;
}
- /* fall-through */
+ ATTR_FALLTHROUGH;
case ENDKEY:
ui_textedit_move(but, data, STRCUR_DIR_NEXT,
event->shift != 0, STRCUR_JUMP_ALL);
@@ -3377,7 +3394,7 @@ static void ui_do_but_textedit(
if (event->type == WHEELUPMOUSE) {
break;
}
- /* fall-through */
+ ATTR_FALLTHROUGH;
case HOMEKEY:
ui_textedit_move(but, data, STRCUR_DIR_PREV,
event->shift != 0, STRCUR_JUMP_ALL);
@@ -4278,7 +4295,7 @@ static bool ui_numedit_but_NUM(
if (!is_float) {
- temp = iroundf(tempf);
+ temp = round_fl_to_int(tempf);
temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
@@ -4563,7 +4580,7 @@ static bool ui_numedit_but_SLI(
tempf = softmin + f * softrange;
- temp = iroundf(tempf);
+ temp = round_fl_to_int(tempf);
if (snap) {
if (tempf == softmin || tempf == softmax) {
@@ -5913,7 +5930,7 @@ static bool ui_numedit_but_COLORBAND(uiBut *but, uiHandleButtonData *data, int m
data->dragcbd->pos += dx;
CLAMP(data->dragcbd->pos, 0.0f, 1.0f);
- colorband_update_sort(data->coba);
+ BKE_colorband_update_sort(data->coba);
data->dragcbd = data->coba->data + data->coba->cur; /* because qsort */
data->draglastx = mx;
@@ -5943,7 +5960,7 @@ static int ui_do_but_COLORBAND(
if (event->ctrl) {
/* insert new key on mouse location */
float pos = ((float)(mx - but->rect.xmin)) / BLI_rctf_size_x(&but->rect);
- colorband_element_add(coba, pos);
+ BKE_colorband_element_add(coba, pos);
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
else {
@@ -5964,6 +5981,7 @@ static int ui_do_but_COLORBAND(
}
data->dragcbd = coba->data + coba->cur;
+ data->dragfstart = data->dragcbd->pos;
button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
}
@@ -5980,7 +5998,15 @@ static int ui_do_but_COLORBAND(
else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
button_activate_state(C, but, BUTTON_STATE_EXIT);
}
-
+ else if (ELEM(event->type, ESCKEY, RIGHTMOUSE)) {
+ if (event->val == KM_PRESS) {
+ data->dragcbd->pos = data->dragfstart;
+ BKE_colorband_update_sort(data->coba);
+ data->cancel = true;
+ data->escapecancel = true;
+ button_activate_state(C, but, BUTTON_STATE_EXIT);
+ }
+ }
return WM_UI_HANDLER_BREAK;
}
@@ -5989,8 +6015,8 @@ static int ui_do_but_COLORBAND(
static bool ui_numedit_but_CURVE(
uiBlock *block, uiBut *but, uiHandleButtonData *data,
- int evtx, int evty,
- bool snap, const bool shift)
+ int evtx, int evty,
+ bool snap, const bool shift)
{
CurveMapping *cumap = (CurveMapping *)but->poin;
CurveMap *cuma = cumap->cm + cumap->cur;
@@ -6524,8 +6550,9 @@ static void but_shortcut_name_func(bContext *C, void *arg1, int UNUSED(event))
IDProperty *prop = (but->opptr) ? but->opptr->data : NULL;
/* complex code to change name of button */
- if (WM_key_event_operator_string(C, but->optype->idname, but->opcontext, prop, true,
- sizeof(shortcut_str), shortcut_str))
+ if (WM_key_event_operator_string(
+ C, but->optype->idname, but->opcontext, prop, true,
+ shortcut_str, sizeof(shortcut_str)))
{
ui_but_add_shortcut(but, shortcut_str, true);
}
@@ -6665,7 +6692,7 @@ static void remove_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2))
static void popup_add_shortcut_func(bContext *C, void *arg1, void *UNUSED(arg2))
{
uiBut *but = (uiBut *)arg1;
- UI_popup_block_ex(C, menu_add_shortcut, NULL, menu_add_shortcut_cancel, but);
+ UI_popup_block_ex(C, menu_add_shortcut, NULL, menu_add_shortcut_cancel, but, NULL);
}
/**
@@ -6721,16 +6748,15 @@ static void ui_but_menu_add_path_operators(uiLayout *layout, PointerRNA *ptr, Pr
if (file[0]) {
BLI_assert(subtype == PROP_FILEPATH);
-
- props_ptr = uiItemFullO_ptr(
- layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open File Externally"),
- ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(
+ layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open File Externally"),
+ ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr);
RNA_string_set(&props_ptr, "filepath", filepath);
}
- props_ptr = uiItemFullO_ptr(
- layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open Location Externally"),
- ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(
+ layout, ot, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Open Location Externally"),
+ ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &props_ptr);
RNA_string_set(&props_ptr, "filepath", dir);
}
@@ -6738,6 +6764,7 @@ static bool ui_but_menu(bContext *C, uiBut *but)
{
uiPopupMenu *pup;
uiLayout *layout;
+ MenuType *mt = WM_menutype_find("WM_MT_button_context", true);
bool is_array, is_array_component;
uiStringInfo label = {BUT_GET_LABEL, NULL};
@@ -6769,6 +6796,9 @@ static bool ui_but_menu(bContext *C, uiBut *but)
/*bool is_idprop = RNA_property_is_idprop(prop);*/ /* XXX does not work as expected, not strictly needed */
bool is_set = RNA_property_is_set(ptr, prop);
+ /* Set the (button_pointer, button_prop) and pointer data for Python access to the hovered ui element. */
+ uiLayoutSetContextFromBut(layout, but);
+
/* second slower test, saved people finding keyframe items in menus when its not possible */
if (is_anim)
is_anim = RNA_property_path_from_ID_check(&but->rnapoin, but->rnaprop);
@@ -6984,7 +7014,10 @@ static bool ui_but_menu(bContext *C, uiBut *but)
0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, "");
UI_but_func_set(but2, popup_add_shortcut_func, but, NULL);
}
-
+
+ /* Set the operator pointer for python access */
+ uiLayoutSetContextFromBut(layout, but);
+
uiItemS(layout);
}
@@ -6999,26 +7032,25 @@ static bool ui_but_menu(bContext *C, uiBut *but)
{ /* Docs */
char buf[512];
- PointerRNA ptr_props;
if (UI_but_online_manual_id(but, buf, sizeof(buf))) {
+ PointerRNA ptr_props;
uiItemO(layout, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Manual"),
ICON_URL, "WM_OT_doc_view_manual_ui_context");
- WM_operator_properties_create(&ptr_props, "WM_OT_doc_view");
+ uiItemFullO(
+ layout, "WM_OT_doc_view",
+ CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Python Reference"),
+ ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr_props);
RNA_string_set(&ptr_props, "doc_id", buf);
- uiItemFullO(layout, "WM_OT_doc_view",
- CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, "Online Python Reference"),
- ICON_NONE, ptr_props.data, WM_OP_EXEC_DEFAULT, 0);
/* XXX inactive option, not for public! */
#if 0
- WM_operator_properties_create(&ptr_props, "WM_OT_doc_edit");
+ uiItemFullO(
+ layout, "WM_OT_doc_edit", "Submit Description", ICON_NONE,
+ NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr_props);
RNA_string_set(&ptr_props, "doc_id", buf);
RNA_string_set(&ptr_props, "doc_new", RNA_property_description(but->rnaprop));
-
- uiItemFullO(layout, "WM_OT_doc_edit",
- "Submit Description", ICON_NONE, ptr_props.data, WM_OP_INVOKE_DEFAULT, 0);
#endif
}
}
@@ -7030,9 +7062,14 @@ static bool ui_but_menu(bContext *C, uiBut *but)
/* perhaps we should move this into (G.debug & G_DEBUG) - campbell */
if (ui_block_is_menu(but->block) == false) {
- uiItemFullO(layout, "UI_OT_editsource", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(layout, "UI_OT_editsource", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL);
+ }
+ uiItemFullO(layout, "UI_OT_edittranslation_init", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL);
+
+ mt = WM_menutype_find("WM_MT_button_context", true);
+ if (mt) {
+ UI_menutype_draw(C, mt, uiLayoutColumn(layout, false));
}
- uiItemFullO(layout, "UI_OT_edittranslation_init", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0);
UI_popup_menu_end(C, pup);
@@ -7613,12 +7650,12 @@ static bool button_modal_state(uiHandleButtonState state)
*/
void UI_but_tooltip_refresh(bContext *C, uiBut *but)
{
- uiHandleButtonData *data;
-
- data = but->active;
- if (data && data->tooltip) {
- ui_tooltip_free(C, data->tooltip);
- data->tooltip = ui_tooltip_create(C, data->region, but);
+ uiHandleButtonData *data = but->active;
+ if (data) {
+ bScreen *sc = data->window->screen;
+ if (sc->tool_tip && sc->tool_tip->region) {
+ WM_tooltip_refresh(C, data->window);
+ }
}
}
@@ -7629,39 +7666,38 @@ void UI_but_tooltip_timer_remove(bContext *C, uiBut *but)
data = but->active;
if (data) {
-
- if (data->tooltiptimer) {
- WM_event_remove_timer(data->wm, data->window, data->tooltiptimer);
- data->tooltiptimer = NULL;
- }
- if (data->tooltip) {
- ui_tooltip_free(C, data->tooltip);
- data->tooltip = NULL;
- }
-
if (data->autoopentimer) {
WM_event_remove_timer(data->wm, data->window, data->autoopentimer);
data->autoopentimer = NULL;
}
+
+ if (data->window) {
+ WM_tooltip_clear(C, data->window);
+ }
+ }
+}
+
+static ARegion *ui_but_tooltip_init(bContext *C, ARegion *ar, bool *r_exit_on_event)
+{
+ uiBut *but = UI_region_active_but_get(ar);
+ *r_exit_on_event = false;
+ if (but) {
+ return UI_tooltip_create_from_button(C, ar, but);
}
+ return NULL;
}
static void button_tooltip_timer_reset(bContext *C, uiBut *but)
{
wmWindowManager *wm = CTX_wm_manager(C);
- uiHandleButtonData *data;
-
- data = but->active;
+ uiHandleButtonData *data = but->active;
- if (data->tooltiptimer) {
- WM_event_remove_timer(data->wm, data->window, data->tooltiptimer);
- data->tooltiptimer = NULL;
- }
+ WM_tooltip_timer_clear(C, data->window);
if ((U.flag & USER_TOOLTIPS) || (data->tooltip_force)) {
if (!but->block->tooltipdisabled) {
if (!wm->drags.first) {
- data->tooltiptimer = WM_event_add_timer(data->wm, data->window, TIMER, BUTTON_TOOLTIP_DELAY);
+ WM_tooltip_timer_init(C, data->window, data->region, ui_but_tooltip_init);
}
}
}
@@ -7677,7 +7713,10 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
/* highlight has timers for tooltips and auto open */
if (state == BUTTON_STATE_HIGHLIGHT) {
- but->flag &= ~UI_SELECT;
+ /* for list-items (that are not drawn with regular emboss), don't change selection based on hovering */
+ if (((but->flag & UI_BUT_LIST_ITEM) == 0) && (but->dragflag & UI_EMBOSS_NONE)) {
+ but->flag &= ~UI_SELECT;
+ }
button_tooltip_timer_reset(C, but);
@@ -7741,7 +7780,8 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
if (ui_but_is_cursor_warp(but)) {
#ifdef USE_CONT_MOUSE_CORRECT
- if (data->ungrab_mval[0] != FLT_MAX) {
+ /* stereo3d has issues with changing cursor location so rather avoid */
+ if (data->ungrab_mval[0] != FLT_MAX && !WM_stereo3d_enabled(data->window, false)) {
int mouse_ungrab_xy[2];
ui_block_to_window_fl(data->region, but->block, &data->ungrab_mval[0], &data->ungrab_mval[1]);
mouse_ungrab_xy[0] = data->ungrab_mval[0];
@@ -7772,6 +7812,15 @@ static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState s
data->flashtimer = NULL;
}
+ /* add hold timer if it's used */
+ if (state == BUTTON_STATE_WAIT_RELEASE && (but->hold_func != NULL)) {
+ data->hold_action_timer = WM_event_add_timer(data->wm, data->window, TIMER, BUTTON_AUTO_OPEN_THRESH);
+ }
+ else if (data->hold_action_timer) {
+ WM_event_remove_timer(data->wm, data->window, data->hold_action_timer);
+ data->hold_action_timer = NULL;
+ }
+
/* add a blocking ui handler at the window handler for blocking, modal states
* but not for popups, because we already have a window level handler*/
if (!(but->block->handle && but->block->handle->popup)) {
@@ -7990,7 +8039,7 @@ static void button_activate_exit(
ui_but_update(but);
/* adds empty mousemove in queue for re-init handler, in case mouse is
- * still over a button. we cannot just check for this ourselfs because
+ * still over a button. We cannot just check for this ourselves because
* at this point the mouse may be over a button in another region */
if (mousemove)
WM_event_add_mousemove(C);
@@ -8011,12 +8060,10 @@ void ui_but_active_free(const bContext *C, uiBut *but)
}
/* returns the active button with an optional checking function */
-static uiBut *ui_context_button_active(const bContext *C, bool (*but_check_cb)(uiBut *))
+static uiBut *ui_context_button_active(ARegion *ar, bool (*but_check_cb)(uiBut *))
{
uiBut *but_found = NULL;
- ARegion *ar = CTX_wm_region(C);
-
while (ar) {
uiBlock *block;
uiBut *but, *activebut = NULL;
@@ -8059,12 +8106,17 @@ static bool ui_context_rna_button_active_test(uiBut *but)
}
static uiBut *ui_context_rna_button_active(const bContext *C)
{
- return ui_context_button_active(C, ui_context_rna_button_active_test);
+ return ui_context_button_active(CTX_wm_region(C), ui_context_rna_button_active_test);
}
uiBut *UI_context_active_but_get(const struct bContext *C)
{
- return ui_context_button_active(C, NULL);
+ return ui_context_button_active(CTX_wm_region(C), NULL);
+}
+
+uiBut *UI_region_active_but_get(ARegion *ar)
+{
+ return ui_context_button_active(ar, NULL);
}
/**
@@ -8346,16 +8398,8 @@ static int ui_handle_button_event(bContext *C, const wmEvent *event, uiBut *but)
}
case TIMER:
{
- /* handle tooltip timer */
- if (event->customdata == data->tooltiptimer) {
- WM_event_remove_timer(data->wm, data->window, data->tooltiptimer);
- data->tooltiptimer = NULL;
-
- if (!data->tooltip)
- data->tooltip = ui_tooltip_create(C, data->region, but);
- }
/* handle menu auto open timer */
- else if (event->customdata == data->autoopentimer) {
+ if (event->customdata == data->autoopentimer) {
WM_event_remove_timer(data->wm, data->window, data->autoopentimer);
data->autoopentimer = NULL;
@@ -8372,7 +8416,7 @@ static int ui_handle_button_event(bContext *C, const wmEvent *event, uiBut *but)
case MIDDLEMOUSE:
case MOUSEPAN:
UI_but_tooltip_timer_remove(C, but);
- /* fall-through */
+ ATTR_FALLTHROUGH;
default:
/* handle button type specific events */
retval = ui_do_button(C, block, but, event);
@@ -8386,6 +8430,25 @@ static int ui_handle_button_event(bContext *C, const wmEvent *event, uiBut *but)
button_activate_state(C, but, BUTTON_STATE_EXIT);
break;
+ case TIMER:
+ {
+ if (event->customdata == data->hold_action_timer) {
+ if (true) {
+ data->cancel = true;
+ button_activate_state(C, but, BUTTON_STATE_EXIT);
+ }
+ else {
+ /* Do this so we can still mouse-up, closing the menu and running the button.
+ * This is nice to support but there are times when the button gets left pressed.
+ * Keep disavled for now. */
+ WM_event_remove_timer(data->wm, data->window, data->hold_action_timer);
+ data->hold_action_timer = NULL;
+ }
+ retval = WM_UI_HANDLER_CONTINUE;
+ but->hold_func(C, data->region, but);
+ }
+ break;
+ }
case MOUSEMOVE:
if (ELEM(but->type, UI_BTYPE_LINK, UI_BTYPE_INLINK)) {
but->flag |= UI_SELECT;
@@ -9166,23 +9229,23 @@ static int ui_handle_menu_event(
break;
case ONEKEY: case PAD1:
- act = 1;
+ act = 1; ATTR_FALLTHROUGH;
case TWOKEY: case PAD2:
- if (act == 0) act = 2;
+ if (act == 0) act = 2; ATTR_FALLTHROUGH;
case THREEKEY: case PAD3:
- if (act == 0) act = 3;
+ if (act == 0) act = 3; ATTR_FALLTHROUGH;
case FOURKEY: case PAD4:
- if (act == 0) act = 4;
+ if (act == 0) act = 4; ATTR_FALLTHROUGH;
case FIVEKEY: case PAD5:
- if (act == 0) act = 5;
+ if (act == 0) act = 5; ATTR_FALLTHROUGH;
case SIXKEY: case PAD6:
- if (act == 0) act = 6;
+ if (act == 0) act = 6; ATTR_FALLTHROUGH;
case SEVENKEY: case PAD7:
- if (act == 0) act = 7;
+ if (act == 0) act = 7; ATTR_FALLTHROUGH;
case EIGHTKEY: case PAD8:
- if (act == 0) act = 8;
+ if (act == 0) act = 8; ATTR_FALLTHROUGH;
case NINEKEY: case PAD9:
- if (act == 0) act = 9;
+ if (act == 0) act = 9; ATTR_FALLTHROUGH;
case ZEROKEY: case PAD0:
if (act == 0) act = 10;
@@ -9209,11 +9272,17 @@ static int ui_handle_menu_event(
doit = true;
}
}
- else if (count == act) {
+ else if (ELEM(but->type,
+ UI_BTYPE_BUT,
+ UI_BTYPE_BUT_MENU,
+ UI_BTYPE_MENU, UI_BTYPE_BLOCK,
+ UI_BTYPE_PULLDOWN) &&
+ count == act)
+ {
doit = true;
}
- if (doit) {
+ if (!(but->flag & UI_BUT_DISABLED) && doit) {
/* activate buttons but open menu's */
uiButtonActivateType activate;
if (but->type == UI_BTYPE_PULLDOWN) {
@@ -9267,8 +9336,7 @@ static int ui_handle_menu_event(
break;
for (but = block->buttons.first; but; but = but->next) {
-
- if (but->menu_key == event->type) {
+ if (!(but->flag & UI_BUT_DISABLED) && but->menu_key == event->type) {
if (ELEM(but->type, UI_BTYPE_BUT, UI_BTYPE_BUT_MENU)) {
/* mainly for operator buttons */
ui_handle_button_activate(C, ar, but, BUTTON_ACTIVATE_APPLY);
@@ -9307,21 +9375,29 @@ static int ui_handle_menu_event(
if (inside == 0) {
uiSafetyRct *saferct = block->saferct.first;
- if (ELEM(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE) &&
- ELEM(event->val, KM_PRESS, KM_DBL_CLICK))
- {
- if ((is_parent_menu == false) && (U.uiflag & USER_MENUOPENAUTO) == 0) {
- /* for root menus, allow clicking to close */
- if (block->flag & (UI_BLOCK_OUT_1))
- menu->menuretval = UI_RETURN_OK;
- else
- menu->menuretval = UI_RETURN_OUT;
+ if (ELEM(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE)) {
+ if (ELEM(event->val, KM_PRESS, KM_DBL_CLICK)) {
+ if ((is_parent_menu == false) && (U.uiflag & USER_MENUOPENAUTO) == 0) {
+ /* for root menus, allow clicking to close */
+ if (block->flag & (UI_BLOCK_OUT_1))
+ menu->menuretval = UI_RETURN_OK;
+ else
+ menu->menuretval = UI_RETURN_OUT;
+ }
+ else if (saferct && !BLI_rctf_isect_pt(&saferct->parent, event->x, event->y)) {
+ if (block->flag & (UI_BLOCK_OUT_1))
+ menu->menuretval = UI_RETURN_OK;
+ else
+ menu->menuretval = UI_RETURN_OUT;
+ }
}
- else if (saferct && !BLI_rctf_isect_pt(&saferct->parent, event->x, event->y)) {
- if (block->flag & (UI_BLOCK_OUT_1))
- menu->menuretval = UI_RETURN_OK;
- else
- menu->menuretval = UI_RETURN_OUT;
+ else if (ELEM(event->val, KM_RELEASE, KM_CLICK)) {
+ /* For buttons that use a hold function, exit when mouse-up outside the menu. */
+ if (block->flag & UI_BLOCK_POPUP_HOLD) {
+ /* Note, we could check the cursor is over the parent button. */
+ menu->menuretval = UI_RETURN_CANCEL;
+ retval = WM_UI_HANDLER_CONTINUE;
+ }
}
}
}
@@ -9777,13 +9853,13 @@ static int ui_pie_handler(bContext *C, const wmEvent *event, uiPopupBlockHandle
case (ZEROKEY + n): case (PAD0 + n): \
{ if (num_dir == UI_RADIAL_NONE) num_dir = d; } (void)0
- CASE_NUM_TO_DIR(1, UI_RADIAL_SW);
- CASE_NUM_TO_DIR(2, UI_RADIAL_S);
- CASE_NUM_TO_DIR(3, UI_RADIAL_SE);
- CASE_NUM_TO_DIR(4, UI_RADIAL_W);
- CASE_NUM_TO_DIR(6, UI_RADIAL_E);
- CASE_NUM_TO_DIR(7, UI_RADIAL_NW);
- CASE_NUM_TO_DIR(8, UI_RADIAL_N);
+ CASE_NUM_TO_DIR(1, UI_RADIAL_SW); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(2, UI_RADIAL_S); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(3, UI_RADIAL_SE); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(4, UI_RADIAL_W); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(6, UI_RADIAL_E); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(7, UI_RADIAL_NW); ATTR_FALLTHROUGH;
+ CASE_NUM_TO_DIR(8, UI_RADIAL_N); ATTR_FALLTHROUGH;
CASE_NUM_TO_DIR(9, UI_RADIAL_NE);
{
but = ui_block_pie_dir_activate(block, event, num_dir);
@@ -10181,6 +10257,25 @@ void UI_popup_handlers_add(bContext *C, ListBase *handlers, uiPopupBlockHandle *
void UI_popup_handlers_remove(ListBase *handlers, uiPopupBlockHandle *popup)
{
+ wmEventHandler *handler;
+
+ for (handler = handlers->first; handler; handler = handler->next) {
+ if (handler->ui_handle == ui_popup_handler &&
+ handler->ui_remove == ui_popup_handler_remove &&
+ handler->ui_userdata == popup)
+ {
+ /* tag refresh parent popup */
+ if (handler->next &&
+ handler->next->ui_handle == ui_popup_handler &&
+ handler->next->ui_remove == ui_popup_handler_remove)
+ {
+ uiPopupBlockHandle *parent_popup = handler->next->ui_userdata;
+ ED_region_tag_refresh_ui(parent_popup->region);
+ }
+ break;
+ }
+ }
+
WM_event_remove_ui_handler(handlers, ui_popup_handler, ui_popup_handler_remove, popup, false);
}
diff --git a/source/blender/editors/interface/interface_icons.c b/source/blender/editors/interface/interface_icons.c
index 65b12fcd64e..ed57412c05c 100644
--- a/source/blender/editors/interface/interface_icons.c
+++ b/source/blender/editors/interface/interface_icons.c
@@ -139,7 +139,7 @@ static DrawInfo *def_internal_icon(ImBuf *bbuf, int icon_id, int xofs, int yofs,
new_icon = MEM_callocN(sizeof(Icon), "texicon");
new_icon->obj = NULL; /* icon is not for library object */
- new_icon->type = 0;
+ new_icon->id_type = 0;
di = MEM_callocN(sizeof(DrawInfo), "drawinfo");
di->type = type;
@@ -191,7 +191,7 @@ static void def_internal_vicon(int icon_id, VectorDrawFunc drawFunc)
new_icon = MEM_callocN(sizeof(Icon), "texicon");
new_icon->obj = NULL; /* icon is not for library object */
- new_icon->type = 0;
+ new_icon->id_type = 0;
di = MEM_callocN(sizeof(DrawInfo), "drawinfo");
di->type = ICON_TYPE_VECTOR;
@@ -849,7 +849,7 @@ void ui_icon_ensure_deferred(const bContext *C, const int icon_id, const bool bi
switch (di->type) {
case ICON_TYPE_PREVIEW:
{
- ID *id = (icon->type != 0) ? icon->obj : NULL;
+ ID *id = (icon->id_type != 0) ? icon->obj : NULL;
PreviewImage *prv = id ? BKE_previewimg_id_ensure(id) : icon->obj;
if (prv) {
@@ -905,7 +905,7 @@ PreviewImage *UI_icon_to_preview(int icon_id)
DrawInfo *di = (DrawInfo *)icon->drawinfo;
if (di) {
if (di->type == ICON_TYPE_PREVIEW) {
- PreviewImage *prv = (icon->type != 0) ? BKE_previewimg_id_ensure((ID *)icon->obj) : icon->obj;
+ PreviewImage *prv = (icon->id_type != 0) ? BKE_previewimg_id_ensure((ID *)icon->obj) : icon->obj;
if (prv) {
return BKE_previewimg_copy(prv);
@@ -1124,7 +1124,7 @@ static void icon_draw_size(
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
else if (di->type == ICON_TYPE_PREVIEW) {
- PreviewImage *pi = (icon->type != 0) ? BKE_previewimg_id_ensure((ID *)icon->obj) : icon->obj;
+ PreviewImage *pi = (icon->id_type != 0) ? BKE_previewimg_id_ensure((ID *)icon->obj) : icon->obj;
if (pi) {
/* no create icon on this level in code */
@@ -1192,7 +1192,7 @@ static int ui_id_brush_get_icon(const bContext *C, ID *id)
else {
Object *ob = CTX_data_active_object(C);
SpaceImage *sima;
- EnumPropertyItem *items = NULL;
+ const EnumPropertyItem *items = NULL;
int tool = PAINT_TOOL_DRAW, mode = 0;
/* XXX: this is not nice, should probably make brushes
@@ -1301,7 +1301,7 @@ int UI_idcode_icon_get(const int idcode)
{
switch (idcode) {
case ID_AC:
- return ICON_ANIM_DATA;
+ return ICON_ACTION;
case ID_AR:
return ICON_ARMATURE_DATA;
case ID_BR:
diff --git a/source/blender/editors/interface/interface_intern.h b/source/blender/editors/interface/interface_intern.h
index d8f9fdcbaae..d5e89357a9f 100644
--- a/source/blender/editors/interface/interface_intern.h
+++ b/source/blender/editors/interface/interface_intern.h
@@ -118,8 +118,8 @@ enum {
UI_SCROLLED = (1 << 1), /* temp hidden, scrolled away */
UI_ACTIVE = (1 << 2),
UI_HAS_ICON = (1 << 3),
- UI_TEXTINPUT = (1 << 4),
- UI_HIDDEN = (1 << 5),
+ UI_HIDDEN = (1 << 4),
+ UI_SELECT_DRAW = (1 << 5), /* Display selected, doesn't impact interaction. */
/* warn: rest of uiBut->flag in UI_interface.h */
};
@@ -264,6 +264,10 @@ struct uiBut {
void *rename_arg1;
void *rename_orig;
+ /* Run an action when holding the button down. */
+ uiButHandleHoldFunc hold_func;
+ void *hold_argN;
+
uiLink *link;
short linkto[2]; /* region relative coords */
@@ -473,7 +477,9 @@ extern void ui_hsvcircle_pos_from_vals(struct uiBut *but, const rcti *rect, floa
extern void ui_hsvcube_pos_from_vals(struct uiBut *but, const rcti *rect, float *hsv, float *xp, float *yp);
bool ui_but_is_colorpicker_display_space(struct uiBut *but);
-extern void ui_but_string_get_ex(uiBut *but, char *str, const size_t maxlen, const int float_precision) ATTR_NONNULL();
+extern void ui_but_string_get_ex(
+ uiBut *but, char *str, const size_t maxlen,
+ const int float_precision, const bool use_exp_float, bool *r_use_exp_float) ATTR_NONNULL(1, 2);
extern void ui_but_string_get(uiBut *but, char *str, const size_t maxlen) ATTR_NONNULL();
extern char *ui_but_string_get_dynamic(uiBut *but, int *r_str_size);
extern void ui_but_convert_to_unit_alt_name(uiBut *but, char *str, size_t maxlen) ATTR_NONNULL();
@@ -556,6 +562,7 @@ struct uiPopupBlockHandle {
struct uiKeyNavLock keynav_state;
/* for operator popups */
+ struct wmOperator *popup_op;
struct wmOperatorType *optype;
ScrArea *ctx_area;
ARegion *ctx_region;
@@ -576,25 +583,23 @@ struct uiPopupBlockHandle {
/* #endif */
};
-uiBlock *ui_block_func_COLOR(struct bContext *C, uiPopupBlockHandle *handle, void *arg_but);
-
-struct ARegion *ui_tooltip_create(struct bContext *C, struct ARegion *butregion, uiBut *but);
-void ui_tooltip_free(struct bContext *C, struct ARegion *ar);
-
-uiBut *ui_popup_menu_memory_get(struct uiBlock *block);
-void ui_popup_menu_memory_set(uiBlock *block, struct uiBut *but);
+/* -------------------------------------------------------------------- */
+/* interface_region_*.c */
-void ui_popup_translate(struct bContext *C, struct ARegion *ar, const int mdiff[2]);
-
-ColorPicker *ui_block_colorpicker_create(struct uiBlock *block);
-void ui_popup_block_scrolltest(struct uiBlock *block);
+/* interface_region_tooltip.c */
+/* exposed as public API in UI_interface.h */
+/* interface_region_color_picker.c */
void ui_rgb_to_color_picker_compat_v(const float rgb[3], float r_cp[3]);
void ui_rgb_to_color_picker_v(const float rgb[3], float r_cp[3]);
void ui_color_picker_to_rgb_v(const float r_cp[3], float rgb[3]);
void ui_color_picker_to_rgb(float r_cp0, float r_cp1, float r_cp2, float *r, float *g, float *b);
-/* searchbox for string button */
+uiBlock *ui_block_func_COLOR(struct bContext *C, uiPopupBlockHandle *handle, void *arg_but);
+ColorPicker *ui_block_colorpicker_create(struct uiBlock *block);
+
+/* interface_region_search.c */
+/* Searchbox for string button */
ARegion *ui_searchbox_create_generic(struct bContext *C, struct ARegion *butregion, uiBut *but);
ARegion *ui_searchbox_create_operator(struct bContext *C, struct ARegion *butregion, uiBut *but);
bool ui_searchbox_inside(struct ARegion *ar, int x, int y);
@@ -606,6 +611,12 @@ bool ui_searchbox_apply(uiBut *but, struct ARegion *ar);
void ui_searchbox_free(struct bContext *C, struct ARegion *ar);
void ui_but_search_refresh(uiBut *but);
+/* interface_region_menu_popup.c */
+int ui_but_menu_step(uiBut *but, int step);
+bool ui_but_menu_step_poll(const uiBut *but);
+uiBut *ui_popup_menu_memory_get(struct uiBlock *block);
+void ui_popup_menu_memory_set(uiBlock *block, struct uiBut *but);
+
uiBlock *ui_popup_block_refresh(
struct bContext *C, uiPopupBlockHandle *handle,
ARegion *butregion, uiBut *but);
@@ -618,14 +629,17 @@ uiPopupBlockHandle *ui_popup_menu_create(
struct bContext *C, struct ARegion *butregion, uiBut *but,
uiMenuCreateFunc create_func, void *arg);
+/* interface_region_menu_pie.c */
void ui_pie_menu_level_create(
uiBlock *block, struct wmOperatorType *ot, const char *propname, IDProperty *properties,
const EnumPropertyItem *items, int totitem, int context, int flag);
+/* interface_region_popup.c */
+void ui_popup_translate(struct bContext *C, struct ARegion *ar, const int mdiff[2]);
void ui_popup_block_free(struct bContext *C, uiPopupBlockHandle *handle);
+void ui_popup_block_scrolltest(struct uiBlock *block);
-int ui_but_menu_step(uiBut *but, int step);
-bool ui_but_menu_step_poll(const uiBut *but);
+/* end interface_region_*.c */
/* interface_panel.c */
@@ -738,9 +752,22 @@ void ui_but_anim_autokey(struct bContext *C, uiBut *but, struct Scene *scene, fl
/* interface_eyedropper.c */
struct wmKeyMap *eyedropper_modal_keymap(struct wmKeyConfig *keyconf);
+struct wmKeyMap *eyedropper_colorband_modal_keymap(struct wmKeyConfig *keyconf);
+
+/* interface_eyedropper_color.c */
void UI_OT_eyedropper_color(struct wmOperatorType *ot);
+
+/* interface_eyedropper_colorband.c */
+void UI_OT_eyedropper_colorband(struct wmOperatorType *ot);
+void UI_OT_eyedropper_colorband_point(struct wmOperatorType *ot);
+
+/* interface_eyedropper_datablock.c */
void UI_OT_eyedropper_id(struct wmOperatorType *ot);
+
+/* interface_eyedropper_depth.c */
void UI_OT_eyedropper_depth(struct wmOperatorType *ot);
+
+/* interface_eyedropper_driver.c */
void UI_OT_eyedropper_driver(struct wmOperatorType *ot);
#endif /* __INTERFACE_INTERN_H__ */
diff --git a/source/blender/editors/interface/interface_layout.c b/source/blender/editors/interface/interface_layout.c
index 9acc8cf8271..ff752ddddba 100644
--- a/source/blender/editors/interface/interface_layout.c
+++ b/source/blender/editors/interface/interface_layout.c
@@ -64,8 +64,6 @@
/************************ Structs and Defines *************************/
-// #define USE_OP_RESET_BUT // we may want to make this optional, disable for now.
-
#define UI_OPERATOR_ERROR_RET(_ot, _opname, return_statement) \
if (ot == NULL) { \
ui_item_disabled(layout, _opname); \
@@ -128,6 +126,8 @@ typedef struct uiItem {
enum {
UI_ITEM_FIXED = 1 << 0,
UI_ITEM_MIN = 1 << 1,
+
+ UI_ITEM_BOX_ITEM = 1 << 2, /* The item is "inside" a box item */
};
typedef struct uiButtonItem {
@@ -189,29 +189,37 @@ static const char *ui_item_name_add_colon(const char *name, char namestr[UI_MAX_
return name;
}
-static int ui_item_fit(int item, int pos, int all, int available, bool is_last, int alignment)
+static int ui_item_fit(int item, int pos, int all, int available, bool is_last, int alignment, float *extra_pixel)
{
/* available == 0 is unlimited */
- if (available == 0)
+ if (ELEM(0, available, all)) {
return item;
+ }
if (all > available) {
/* contents is bigger than available space */
if (is_last)
return available - pos;
- else
- return (item * available) / all;
+ else {
+ float width = *extra_pixel + (item * available) / (float)all;
+ *extra_pixel = width - (int)width;
+ return (int)width;
+ }
}
else {
/* contents is smaller or equal to available space */
if (alignment == UI_LAYOUT_ALIGN_EXPAND) {
if (is_last)
return available - pos;
- else
- return (item * available) / all;
+ else {
+ float width = *extra_pixel + (item * available) / (float)all;
+ *extra_pixel = width - (int)width;
+ return (int)width;
+ }
}
- else
+ else {
return item;
+ }
}
}
@@ -237,7 +245,9 @@ static int ui_text_icon_width(uiLayout *layout, const char *name, int icon, bool
variable = (ui_layout_vary_direction(layout) == UI_ITEM_VARY_X);
if (variable) {
- layout->item.flag |= UI_ITEM_MIN;
+ if (layout->alignment != UI_LAYOUT_ALIGN_EXPAND) {
+ layout->item.flag |= UI_ITEM_MIN;
+ }
const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
/* it may seem odd that the icon only adds (UI_UNIT_X / 4)
* but taking margins into account its fine */
@@ -302,6 +312,26 @@ static void ui_item_position(uiItem *item, int x, int y, int w, int h)
}
}
+static void ui_item_move(uiItem *item, int delta_xmin, int delta_xmax)
+{
+ if (item->type == ITEM_BUTTON) {
+ uiButtonItem *bitem = (uiButtonItem *)item;
+
+ bitem->but->rect.xmin += delta_xmin;
+ bitem->but->rect.xmax += delta_xmax;
+
+ ui_but_update(bitem->but); /* for strlen */
+ }
+ else {
+ uiLayout *litem = (uiLayout *)item;
+
+ if (delta_xmin > 0)
+ litem->x += delta_xmin;
+ else
+ litem->w += delta_xmax;
+ }
+}
+
/******************** Special RNA Items *********************/
static int ui_layout_local_dir(uiLayout *layout)
@@ -563,7 +593,7 @@ static void ui_item_enum_expand(
uiBut *but;
uiLayout *layout_radial = NULL;
- EnumPropertyItem *item, *item_array;
+ const EnumPropertyItem *item, *item_array;
const char *name;
int itemw, icon, value;
bool free;
@@ -624,7 +654,7 @@ static void ui_item_enum_expand(
UI_block_layout_set_current(block, layout);
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
}
@@ -674,13 +704,13 @@ static uiBut *ui_item_with_label(uiLayout *layout, uiBlock *block, const char *n
WM_OP_INVOKE_DEFAULT, ICON_FILESEL, x, y, UI_UNIT_X, h, NULL);
}
else if (flag & UI_ITEM_R_EVENT) {
- uiDefButR_prop(block, UI_BTYPE_KEY_EVENT, 0, name, x, y, w, h, ptr, prop, index, 0, 0, -1, -1, NULL);
+ but = uiDefButR_prop(block, UI_BTYPE_KEY_EVENT, 0, name, x, y, w, h, ptr, prop, index, 0, 0, -1, -1, NULL);
}
else if (flag & UI_ITEM_R_FULL_EVENT) {
if (RNA_struct_is_a(ptr->type, &RNA_KeyMapItem)) {
char buf[128];
- WM_keymap_item_to_string(ptr->data, false, sizeof(buf), buf);
+ WM_keymap_item_to_string(ptr->data, false, buf, sizeof(buf));
but = uiDefButR_prop(block, UI_BTYPE_HOTKEY_EVENT, 0, buf, x, y, w, h, ptr, prop, 0, 0, 0, -1, -1, NULL);
UI_but_func_set(but, ui_keymap_but_cb, but, NULL);
@@ -760,9 +790,17 @@ static void ui_item_disabled(uiLayout *layout, const char *name)
but->disabled_info = "";
}
-/* operator items */
-PointerRNA uiItemFullO_ptr(uiLayout *layout, wmOperatorType *ot, const char *name, int icon, IDProperty *properties, int context, int flag)
+/**
+ * Operator Item
+ * \param r_opptr: Optional, initialize with operator properties when not NULL.
+ * Will always be written to even in the case of errors.
+ */
+static uiBut *uiItemFullO_ptr_ex(
+ uiLayout *layout, wmOperatorType *ot,
+ const char *name, int icon, IDProperty *properties, int context, int flag,
+ PointerRNA *r_opptr)
{
+ /* Take care to fill 'r_opptr' whatever happens. */
uiBlock *block = layout->root->block;
uiBut *but;
int w;
@@ -807,13 +845,16 @@ PointerRNA uiItemFullO_ptr(uiLayout *layout, wmOperatorType *ot, const char *nam
if (flag & UI_ITEM_R_NO_BG)
UI_block_emboss_set(block, UI_EMBOSS);
+ if (flag & UI_ITEM_O_DEPRESS) {
+ but->flag |= UI_SELECT_DRAW;
+ }
+
if (layout->redalert)
UI_but_flag_enable(but, UI_BUT_REDALERT);
/* assign properties */
- if (properties || (flag & UI_ITEM_O_RETURN_PROPS)) {
+ if (properties || r_opptr) {
PointerRNA *opptr = UI_but_operator_ptr_get(but);
-
if (properties) {
opptr->data = properties;
}
@@ -821,25 +862,75 @@ PointerRNA uiItemFullO_ptr(uiLayout *layout, wmOperatorType *ot, const char *nam
IDPropertyTemplate val = {0};
opptr->data = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
}
+ if (r_opptr) {
+ *r_opptr = *opptr;
+ }
+ }
- return *opptr;
+ return but;
+}
+
+static void ui_item_hold_menu(struct bContext *C, ARegion *butregion, uiBut *but)
+{
+ uiPopupMenu *pup = UI_popup_menu_begin(C, "", ICON_NONE);
+ uiLayout *layout = UI_popup_menu_layout(pup);
+ uiBlock *block = layout->root->block;
+ UI_popup_menu_but_set(pup, butregion, but);
+
+ block->flag |= UI_BLOCK_POPUP_HOLD;
+
+ const char *menu_id = but->hold_argN;
+ MenuType *mt = WM_menutype_find(menu_id, true);
+ if (mt) {
+ uiLayoutSetContextFromBut(layout, but);
+ UI_menutype_draw(C, mt, layout);
+ }
+ else {
+ uiItemL(layout, "Menu Missing:", ICON_NONE);
+ uiItemL(layout, menu_id, ICON_NONE);
}
+ UI_popup_menu_end(C, pup);
+}
- return PointerRNA_NULL;
+void uiItemFullO_ptr(
+ uiLayout *layout, wmOperatorType *ot,
+ const char *name, int icon, IDProperty *properties, int context, int flag,
+ PointerRNA *r_opptr)
+{
+ uiItemFullO_ptr_ex(layout, ot, name, icon, properties, context, flag, r_opptr);
}
-PointerRNA uiItemFullO(uiLayout *layout, const char *opname, const char *name, int icon, IDProperty *properties, int context, int flag)
+void uiItemFullOMenuHold_ptr(
+ uiLayout *layout, wmOperatorType *ot,
+ const char *name, int icon, IDProperty *properties, int context, int flag,
+ const char *menu_id,
+ PointerRNA *r_opptr)
+{
+ uiBut *but = uiItemFullO_ptr_ex(layout, ot, name, icon, properties, context, flag, r_opptr);
+ UI_but_func_hold_set(but, ui_item_hold_menu, BLI_strdup(menu_id));
+}
+
+void uiItemFullO(
+ uiLayout *layout, const char *opname,
+ const char *name, int icon, IDProperty *properties, int context, int flag,
+ PointerRNA *r_opptr)
{
wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
- UI_OPERATOR_ERROR_RET(ot, opname, return PointerRNA_NULL);
+ UI_OPERATOR_ERROR_RET(
+ ot, opname, {
+ if (r_opptr) {
+ *r_opptr = PointerRNA_NULL;
+ }
+ return;
+ });
- return uiItemFullO_ptr(layout, ot, name, icon, properties, context, flag);
+ uiItemFullO_ptr(layout, ot, name, icon, properties, context, flag, r_opptr);
}
static const char *ui_menu_enumpropname(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int retval)
{
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
bool free;
const char *name;
@@ -852,7 +943,7 @@ static const char *ui_menu_enumpropname(uiLayout *layout, PointerRNA *ptr, Prope
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
return name;
@@ -878,7 +969,7 @@ void uiItemEnumO_ptr(uiLayout *layout, wmOperatorType *ot, const char *name, int
if (!name)
name = ui_menu_enumpropname(layout, &ptr, prop, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemEnumO(uiLayout *layout, const char *opname, const char *name, int icon, const char *propname, int value)
{
@@ -972,7 +1063,7 @@ void uiItemsFullEnumO_items(
}
RNA_property_enum_set(&tptr, prop, item->value);
- uiItemFullO_ptr(target, ot, item->name, item->icon, tptr.data, context, flag);
+ uiItemFullO_ptr(target, ot, item->name, item->icon, tptr.data, context, flag, NULL);
ui_but_tip_from_enum_item(block->buttons.last, item);
}
@@ -1038,7 +1129,7 @@ void uiItemsFullEnumO(
BLI_assert((prop == NULL) || (RNA_property_type(prop) == PROP_ENUM));
if (prop && RNA_property_type(prop) == PROP_ENUM) {
- EnumPropertyItem *item_array = NULL;
+ const EnumPropertyItem *item_array = NULL;
int totitem;
bool free;
@@ -1055,7 +1146,7 @@ void uiItemsFullEnumO(
item_array, totitem);
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
/* intentionally don't touch UI_BLOCK_IS_FLIP here,
@@ -1102,7 +1193,7 @@ void uiItemEnumO_value(uiLayout *layout, const char *name, int icon, const char
if (!name)
name = ui_menu_enumpropname(layout, &ptr, prop, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value_str)
@@ -1111,7 +1202,7 @@ void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char
PointerRNA ptr;
PropertyRNA *prop;
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int value;
bool free;
@@ -1125,14 +1216,14 @@ void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char
RNA_property_enum_items(layout->root->block->evil_C, &ptr, prop, &item, NULL, &free);
if (item == NULL || RNA_enum_value_from_id(item, value_str, &value) == 0) {
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
RNA_warning("%s.%s, enum %s not found", RNA_struct_identifier(ptr.type), propname, value_str);
return;
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
}
else {
@@ -1146,7 +1237,7 @@ void uiItemEnumO_string(uiLayout *layout, const char *name, int icon, const char
if (!name)
name = ui_menu_enumpropname(layout, &ptr, prop, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemBooleanO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, int value)
@@ -1159,7 +1250,7 @@ void uiItemBooleanO(uiLayout *layout, const char *name, int icon, const char *op
WM_operator_properties_create_ptr(&ptr, ot);
RNA_boolean_set(&ptr, propname, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemIntO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, int value)
@@ -1172,7 +1263,7 @@ void uiItemIntO(uiLayout *layout, const char *name, int icon, const char *opname
WM_operator_properties_create_ptr(&ptr, ot);
RNA_int_set(&ptr, propname, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemFloatO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, float value)
@@ -1185,7 +1276,7 @@ void uiItemFloatO(uiLayout *layout, const char *name, int icon, const char *opna
WM_operator_properties_create_ptr(&ptr, ot);
RNA_float_set(&ptr, propname, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemStringO(uiLayout *layout, const char *name, int icon, const char *opname, const char *propname, const char *value)
@@ -1198,12 +1289,12 @@ void uiItemStringO(uiLayout *layout, const char *name, int icon, const char *opn
WM_operator_properties_create_ptr(&ptr, ot);
RNA_string_set(&ptr, propname, value);
- uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0);
+ uiItemFullO_ptr(layout, ot, name, icon, ptr.data, layout->root->opcontext, 0, NULL);
}
void uiItemO(uiLayout *layout, const char *name, int icon, const char *opname)
{
- uiItemFullO(layout, opname, name, icon, NULL, layout->root->opcontext, 0);
+ uiItemFullO(layout, opname, name, icon, NULL, layout->root->opcontext, 0, NULL);
}
/* RNA property items */
@@ -1230,7 +1321,7 @@ static void ui_item_rna_size(
}
else if (type == PROP_ENUM) {
/* Find the longest enum item name, instead of using a dummy text! */
- EnumPropertyItem *item, *item_array;
+ const EnumPropertyItem *item, *item_array;
bool free;
RNA_property_enum_items_gettexted(layout->root->block->evil_C, ptr, prop, &item_array, NULL, &free);
@@ -1240,7 +1331,7 @@ static void ui_item_rna_size(
}
}
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
}
}
@@ -1248,7 +1339,8 @@ static void ui_item_rna_size(
if (!w) {
if (type == PROP_ENUM && icon_only) {
w = ui_text_icon_width(layout, "", ICON_BLANK1, 0);
- w += 0.6f * UI_UNIT_X;
+ if (index != RNA_ENUM_VALUE)
+ w += 0.6f * UI_UNIT_X;
}
else {
w = ui_text_icon_width(layout, name, icon, 0);
@@ -1394,7 +1486,7 @@ void uiItemFullR(uiLayout *layout, PointerRNA *ptr, PropertyRNA *prop, int index
}
/* Mark non-embossed textfields inside a listbox. */
- if (but && (block->flag & UI_BLOCK_LIST_ITEM) && (but->type == UI_BTYPE_TEXT) && (but->dt & UI_EMBOSS_NONE)) {
+ if (but && (block->flag & UI_BLOCK_LIST_ITEM) && (but->dt & UI_EMBOSS_NONE)) {
UI_but_flag_enable(but, UI_BUT_LIST_ITEM);
}
@@ -1449,7 +1541,7 @@ void uiItemEnumR(uiLayout *layout, const char *name, int icon, struct PointerRNA
void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *propname, const char *value, const char *name, int icon)
{
PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int ivalue, a;
bool free;
@@ -1463,7 +1555,7 @@ void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *pr
if (!RNA_enum_value_from_id(item, value, &ivalue)) {
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
ui_item_disabled(layout, propname);
RNA_warning("enum property value not found: %s", value);
@@ -1481,7 +1573,7 @@ void uiItemEnumR_string(uiLayout *layout, struct PointerRNA *ptr, const char *pr
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
}
@@ -1504,7 +1596,7 @@ void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname
return;
}
else {
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int totitem, i;
bool free;
uiLayout *split = uiLayoutSplit(layout, 0.0f, false);
@@ -1537,7 +1629,7 @@ void uiItemsEnumR(uiLayout *layout, struct PointerRNA *ptr, const char *propname
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
}
@@ -1693,6 +1785,10 @@ void ui_but_add_search(uiBut *but, PointerRNA *ptr, PropertyRNA *prop, PointerRN
UI_but_func_search_set(but, ui_searchbox_create_generic, rna_search_cb, but, NULL, NULL);
}
+ else if (but->type == UI_BTYPE_SEARCH_MENU) {
+ /* In case we fail to find proper searchprop, so other code might have already set but->type to search menu... */
+ but->flag |= UI_BUT_DISABLED;
+ }
}
void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propname, struct PointerRNA *searchptr, const char *searchpropname, const char *name, int icon)
@@ -1762,22 +1858,8 @@ void uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const char *propna
static void ui_item_menutype_func(bContext *C, uiLayout *layout, void *arg_mt)
{
MenuType *mt = (MenuType *)arg_mt;
- Menu menu = {NULL};
-
- menu.type = mt;
- menu.layout = layout;
- if (G.debug & G_DEBUG_WM) {
- printf("%s: opening menu \"%s\"\n", __func__, mt->idname);
- }
-
- if (layout->context)
- CTX_store_set(C, layout->context);
-
- mt->draw(C, &menu);
-
- if (layout->context)
- CTX_store_set(C, NULL);
+ UI_menutype_draw(C, mt, layout);
/* menus are created flipped (from event handling pov) */
layout->root->block->flag ^= UI_BLOCK_IS_FLIP;
@@ -1981,19 +2063,15 @@ static void menu_item_enum_opname_menu(bContext *UNUSED(C), uiLayout *layout, vo
UI_block_direction_set(layout->root->block, UI_DIR_DOWN);
}
-void uiItemMenuEnumO(uiLayout *layout, bContext *C, const char *opname, const char *propname, const char *name, int icon)
+void uiItemMenuEnumO_ptr(
+ uiLayout *layout, bContext *C, wmOperatorType *ot, const char *propname,
+ const char *name, int icon)
{
- wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
MenuItemLevel *lvl;
uiBut *but;
- UI_OPERATOR_ERROR_RET(ot, opname, return);
-
- if (!ot->srna) {
- ui_item_disabled(layout, opname);
- RNA_warning("operator missing srna '%s'", opname);
- return;
- }
+ /* Caller must check */
+ BLI_assert(ot->srna != NULL);
if (name == NULL) {
name = RNA_struct_ui_name(ot->srna);
@@ -2003,7 +2081,7 @@ void uiItemMenuEnumO(uiLayout *layout, bContext *C, const char *opname, const ch
icon = ICON_BLANK1;
lvl = MEM_callocN(sizeof(MenuItemLevel), "MenuItemLevel");
- BLI_strncpy(lvl->opname, opname, sizeof(lvl->opname));
+ BLI_strncpy(lvl->opname, ot->idname, sizeof(lvl->opname));
BLI_strncpy(lvl->propname, propname, sizeof(lvl->propname));
lvl->opcontext = layout->root->opcontext;
@@ -2015,14 +2093,32 @@ void uiItemMenuEnumO(uiLayout *layout, bContext *C, const char *opname, const ch
(ot->prop && ot->invoke))
{
char keybuf[128];
- if (WM_key_event_operator_string(C, ot->idname, layout->root->opcontext, NULL, false,
- sizeof(keybuf), keybuf))
+ if (WM_key_event_operator_string(
+ C, ot->idname, layout->root->opcontext, NULL, false,
+ keybuf, sizeof(keybuf)))
{
ui_but_add_shortcut(but, keybuf, false);
}
}
}
+void uiItemMenuEnumO(
+ uiLayout *layout, bContext *C, const char *opname, const char *propname,
+ const char *name, int icon)
+{
+ wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
+
+ UI_OPERATOR_ERROR_RET(ot, opname, return);
+
+ if (!ot->srna) {
+ ui_item_disabled(layout, opname);
+ RNA_warning("operator missing srna '%s'", opname);
+ return;
+ }
+
+ uiItemMenuEnumO_ptr(layout, C, ot, propname, name, icon);
+}
+
static void menu_item_enum_rna_menu(bContext *UNUSED(C), uiLayout *layout, void *arg)
{
MenuItemLevel *lvl = (MenuItemLevel *)(((uiBut *)arg)->func_argN);
@@ -2099,9 +2195,10 @@ static int ui_litem_min_width(int itemw)
static void ui_litem_layout_row(uiLayout *litem)
{
- uiItem *item;
+ uiItem *item, *last_free_item = NULL;
int x, y, w, tot, totw, neww, newtotw, itemw, minw, itemh, offset;
int fixedw, freew, fixedx, freex, flag = 0, lastw = 0;
+ float extra_pixel;
/* x = litem->x; */ /* UNUSED */
y = litem->y;
@@ -2128,6 +2225,7 @@ static void ui_litem_layout_row(uiLayout *litem)
x = 0;
flag = 0;
newtotw = totw;
+ extra_pixel = 0.0f;
for (item = litem->items.first; item; item = item->next) {
if (item->flag & UI_ITEM_FIXED)
@@ -2137,13 +2235,23 @@ static void ui_litem_layout_row(uiLayout *litem)
minw = ui_litem_min_width(itemw);
if (w - lastw > 0)
- neww = ui_item_fit(itemw, x, totw, w - lastw, !item->next, litem->alignment);
+ neww = ui_item_fit(itemw, x, totw, w - lastw, !item->next, litem->alignment, &extra_pixel);
else
neww = 0; /* no space left, all will need clamping to minimum size */
x += neww;
- if ((neww < minw || itemw == minw || item->flag & UI_ITEM_MIN) && w != 0) {
+ bool min_flag = item->flag & UI_ITEM_MIN;
+ /* ignore min flag for rows with right or center alignment */
+ if (item->type != ITEM_BUTTON &&
+ ELEM(((uiLayout *)item)->alignment, UI_LAYOUT_ALIGN_RIGHT, UI_LAYOUT_ALIGN_CENTER) &&
+ litem->alignment == UI_LAYOUT_ALIGN_EXPAND &&
+ ((uiItem *)litem)->flag & UI_ITEM_MIN)
+ {
+ min_flag = false;
+ }
+
+ if ((neww < minw || min_flag) && w != 0) {
/* fixed size */
item->flag |= UI_ITEM_FIXED;
if (item->type != ITEM_BUTTON && item->flag & UI_ITEM_MIN) {
@@ -2166,6 +2274,7 @@ static void ui_litem_layout_row(uiLayout *litem)
freex = 0;
fixedx = 0;
+ extra_pixel = 0.0f;
x = litem->x;
for (item = litem->items.first; item; item = item->next) {
@@ -2177,13 +2286,14 @@ static void ui_litem_layout_row(uiLayout *litem)
if (item->type != ITEM_BUTTON && item->flag & UI_ITEM_MIN) {
minw = itemw;
}
- itemw = ui_item_fit(minw, fixedx, fixedw, min_ii(w, fixedw), !item->next, litem->alignment);
+ itemw = ui_item_fit(minw, fixedx, fixedw, min_ii(w, fixedw), !item->next, litem->alignment, &extra_pixel);
fixedx += itemw;
}
else {
/* free size item */
- itemw = ui_item_fit(itemw, freex, freew, w - fixedw, !item->next, litem->alignment);
+ itemw = ui_item_fit(itemw, freex, freew, w - fixedw, !item->next, litem->alignment, &extra_pixel);
freex += itemw;
+ last_free_item = item;
}
/* align right/center */
@@ -2205,6 +2315,17 @@ static void ui_litem_layout_row(uiLayout *litem)
x += litem->space;
}
+ /* add extra pixel */
+ uiItem *last_item = litem->items.last;
+ extra_pixel = litem->w - (x - litem->x);
+ if (extra_pixel > 0 && litem->alignment == UI_LAYOUT_ALIGN_EXPAND &&
+ last_free_item && last_item && last_item->flag & UI_ITEM_FIXED)
+ {
+ ui_item_move(last_free_item, 0, extra_pixel);
+ for (item = last_free_item->next; item; item = item->next)
+ ui_item_move(item, extra_pixel, extra_pixel);
+ }
+
litem->w = x - litem->x;
litem->h = litem->y - y;
litem->x = x;
@@ -2212,10 +2333,11 @@ static void ui_litem_layout_row(uiLayout *litem)
}
/* single-column layout */
-static void ui_litem_estimate_column(uiLayout *litem)
+static void ui_litem_estimate_column(uiLayout *litem, bool is_box)
{
uiItem *item;
int itemw, itemh;
+ bool min_size_flag = true;
litem->w = 0;
litem->h = 0;
@@ -2223,15 +2345,21 @@ static void ui_litem_estimate_column(uiLayout *litem)
for (item = litem->items.first; item; item = item->next) {
ui_item_size(item, &itemw, &itemh);
+ min_size_flag = min_size_flag && (item->flag & UI_ITEM_MIN);
+
litem->w = MAX2(litem->w, itemw);
litem->h += itemh;
- if (item->next)
+ if (item->next && (!is_box || item != litem->items.first))
litem->h += litem->space;
}
+
+ if (min_size_flag) {
+ litem->item.flag |= UI_ITEM_MIN;
+ }
}
-static void ui_litem_layout_column(uiLayout *litem)
+static void ui_litem_layout_column(uiLayout *litem, bool is_box)
{
uiItem *item;
int itemh, x, y;
@@ -2245,8 +2373,12 @@ static void ui_litem_layout_column(uiLayout *litem)
y -= itemh;
ui_item_position(item, x, y, litem->w, itemh);
- if (item->next)
+ if (item->next && (!is_box || item != litem->items.first))
y -= litem->space;
+
+ if (is_box) {
+ item->flag |= UI_ITEM_BOX_ITEM;
+ }
}
litem->h = litem->y - y;
@@ -2337,8 +2469,10 @@ static void ui_litem_layout_radial(uiLayout *litem)
/* add a little bit more here to include number */
bitem->but->rect.xmax += 1.5f * UI_UNIT_X;
/* enable drawing as pie item if supported by widget */
- if (ui_item_is_radial_drawable(bitem))
+ if (ui_item_is_radial_drawable(bitem)) {
bitem->but->dt = UI_EMBOSS_RADIAL;
+ bitem->but->drawflag |= UI_BUT_ICON_LEFT;
+ }
}
ui_item_size(item, &itemw, &itemh);
@@ -2387,7 +2521,7 @@ static void ui_litem_layout_root(uiLayout *litem)
else if (litem->root->type == UI_LAYOUT_PIEMENU)
ui_litem_layout_root_radial(litem);
else
- ui_litem_layout_column(litem);
+ ui_litem_layout_column(litem, false);
}
/* box layout */
@@ -2395,9 +2529,9 @@ static void ui_litem_estimate_box(uiLayout *litem)
{
uiStyle *style = litem->root->style;
- ui_litem_estimate_column(litem);
+ ui_litem_estimate_column(litem, true);
litem->w += 2 * style->boxspace;
- litem->h += style->boxspace;
+ litem->h += 2 * style->boxspace;
}
static void ui_litem_layout_box(uiLayout *litem)
@@ -2411,17 +2545,18 @@ static void ui_litem_layout_box(uiLayout *litem)
h = litem->h;
litem->x += style->boxspace;
+ litem->y -= style->boxspace;
if (w != 0) litem->w -= 2 * style->boxspace;
if (h != 0) litem->h -= 2 * style->boxspace;
- ui_litem_layout_column(litem);
+ ui_litem_layout_column(litem, true);
litem->x -= style->boxspace;
litem->y -= style->boxspace;
if (w != 0) litem->w += 2 * style->boxspace;
- if (h != 0) litem->h += style->boxspace;
+ if (h != 0) litem->h += 2 * style->boxspace;
/* roundbox around the sublayout */
but = box->roundbox;
@@ -2641,13 +2776,14 @@ static void ui_litem_layout_absolute(uiLayout *litem)
static void ui_litem_estimate_split(uiLayout *litem)
{
ui_litem_estimate_row(litem);
+ litem->item.flag &= ~UI_ITEM_MIN;
}
static void ui_litem_layout_split(uiLayout *litem)
{
uiLayoutItemSplit *split = (uiLayoutItemSplit *)litem;
uiItem *item;
- float percentage;
+ float percentage, extra_pixel = 0.0f;
const int tot = BLI_listbase_count(&litem->items);
int itemh, x, y, w, colw = 0;
@@ -2670,7 +2806,9 @@ static void ui_litem_layout_split(uiLayout *litem)
x += colw;
if (item->next) {
- colw = (w - (int)(w * percentage)) / (tot - 1);
+ const float width = extra_pixel + (w - (int)(w * percentage)) / ((float)tot - 1);
+ extra_pixel = width - (int)width;
+ colw = (int)width;
colw = MAX2(colw, 0);
x += litem->space;
@@ -3063,15 +3201,18 @@ static void ui_item_estimate(uiItem *item)
for (subitem = litem->items.first; subitem; subitem = subitem->next)
ui_item_estimate(subitem);
- if (BLI_listbase_is_empty(&litem->items))
+ if (BLI_listbase_is_empty(&litem->items)) {
+ litem->w = 0;
+ litem->h = 0;
return;
+ }
if (litem->scale[0] != 0.0f || litem->scale[1] != 0.0f)
ui_item_scale(litem, litem->scale);
switch (litem->item.type) {
case ITEM_LAYOUT_COLUMN:
- ui_litem_estimate_column(litem);
+ ui_litem_estimate_column(litem, false);
break;
case ITEM_LAYOUT_COLUMN_FLOW:
ui_litem_estimate_column_flow(litem);
@@ -3126,7 +3267,9 @@ static void ui_item_align(uiLayout *litem, short nr)
}
else if (item->type == ITEM_LAYOUT_BOX) {
box = (uiLayoutItemBx *)item;
- box->roundbox->alignnr = nr;
+ if (!box->roundbox->alignnr) {
+ box->roundbox->alignnr = nr;
+ }
}
else if (((uiLayout *)item)->align) {
ui_item_align((uiLayout *)item, nr);
@@ -3168,7 +3311,7 @@ static void ui_item_layout(uiItem *item)
switch (litem->item.type) {
case ITEM_LAYOUT_COLUMN:
- ui_litem_layout_column(litem);
+ ui_litem_layout_column(litem, false);
break;
case ITEM_LAYOUT_COLUMN_FLOW:
ui_litem_layout_column_flow(litem);
@@ -3198,8 +3341,18 @@ static void ui_item_layout(uiItem *item)
break;
}
- for (subitem = litem->items.first; subitem; subitem = subitem->next)
+ for (subitem = litem->items.first; subitem; subitem = subitem->next) {
+ if (item->flag & UI_ITEM_BOX_ITEM) {
+ subitem->flag |= UI_ITEM_BOX_ITEM;
+ }
ui_item_layout(subitem);
+ }
+ }
+ else {
+ if (item->flag & UI_ITEM_BOX_ITEM) {
+ uiButtonItem *bitem = (uiButtonItem *)item;
+ bitem->but->drawflag |= UI_BUT_BOX_ITEM;
+ }
}
}
@@ -3316,8 +3469,9 @@ void ui_layout_add_but(uiLayout *layout, uiBut *but)
ui_item_size((uiItem *)bitem, &w, &h);
/* XXX uiBut hasn't scaled yet
* we can flag the button as not expandable, depending on its size */
- if (w <= 2 * UI_UNIT_X)
+ if (w <= 2 * UI_UNIT_X && (!but->str || but->str[0] == '\0')) {
bitem->item.flag |= UI_ITEM_MIN;
+ }
BLI_addtail(&layout->items, bitem);
@@ -3378,6 +3532,20 @@ void uiLayoutContextCopy(uiLayout *layout, bContextStore *context)
layout->context = CTX_store_add_all(&block->contexts, context);
}
+void uiLayoutSetContextFromBut(uiLayout *layout, uiBut *but)
+{
+ if (but->opptr) {
+ uiLayoutSetContextPointer(layout, "button_operator", but->opptr);
+ }
+
+ if (but->rnapoin.data && but->rnaprop) {
+ /* TODO: index could be supported as well */
+ PointerRNA ptr_prop;
+ RNA_pointer_create(NULL, &RNA_Property, but->rnaprop, &ptr_prop);
+ uiLayoutSetContextPointer(layout, "button_prop", &ptr_prop);
+ uiLayoutSetContextPointer(layout, "button_pointer", &but->rnapoin);
+ }
+}
/* introspect funcs */
#include "BLI_dynstr.h"
@@ -3466,133 +3634,35 @@ const char *uiLayoutIntrospect(uiLayout *layout)
return str;
}
-#ifdef USE_OP_RESET_BUT
-static void ui_layout_operator_buts__reset_cb(bContext *UNUSED(C), void *op_pt, void *UNUSED(arg_dummy2))
-{
- WM_operator_properties_reset((wmOperator *)op_pt);
-}
-#endif
-
-/* this function does not initialize the layout, functions can be called on the layout before and after */
-void uiLayoutOperatorButs(
- const bContext *C, uiLayout *layout, wmOperator *op,
- bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *),
- const char label_align, const short flag)
+/* this is a bit of a hack but best keep it in one place at least */
+MenuType *UI_but_menutype_get(uiBut *but)
{
- if (!op->properties) {
- IDPropertyTemplate val = {0};
- op->properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
- }
-
- if (flag & UI_LAYOUT_OP_SHOW_TITLE) {
- uiItemL(layout, RNA_struct_ui_name(op->type->srna), ICON_NONE);
- }
-
- /* poll() on this operator may still fail, at the moment there is no nice feedback when this happens
- * just fails silently */
- if (!WM_operator_repeat_check(C, op)) {
- UI_block_lock_set(uiLayoutGetBlock(layout), true, "Operator can't' redo");
-
- /* XXX, could give some nicer feedback or not show redo panel at all? */
- uiItemL(layout, IFACE_("* Redo Unsupported *"), ICON_NONE);
+ if (but->menu_create_func == ui_item_menutype_func) {
+ return (MenuType *)but->poin;
}
else {
- /* useful for macros where only one of the steps can't be re-done */
- UI_block_lock_clear(uiLayoutGetBlock(layout));
- }
-
- /* menu */
- if (op->type->flag & OPTYPE_PRESET) {
- /* XXX, no simple way to get WM_MT_operator_presets.bl_label from python! Label remains the same always! */
- PointerRNA op_ptr;
- uiLayout *row;
-
- uiLayoutGetBlock(layout)->ui_operator = op;
-
- row = uiLayoutRow(layout, true);
- uiItemM(row, (bContext *)C, "WM_MT_operator_presets", NULL, ICON_NONE);
-
- WM_operator_properties_create(&op_ptr, "WM_OT_operator_preset_add");
- RNA_string_set(&op_ptr, "operator", op->type->idname);
- uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMIN, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
-
- WM_operator_properties_create(&op_ptr, "WM_OT_operator_preset_add");
- RNA_string_set(&op_ptr, "operator", op->type->idname);
- RNA_boolean_set(&op_ptr, "remove_active", true);
- uiItemFullO(row, "WM_OT_operator_preset_add", "", ICON_ZOOMOUT, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
- }
-
- if (op->type->ui) {
- op->layout = layout;
- op->type->ui((bContext *)C, op);
- op->layout = NULL;
-
- /* UI_LAYOUT_OP_SHOW_EMPTY ignored */
+ return NULL;
}
- else {
- wmWindowManager *wm = CTX_wm_manager(C);
- PointerRNA ptr;
- int empty;
-
- RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);
+}
- /* main draw call */
- empty = uiDefAutoButsRNA(layout, &ptr, check_prop, label_align) == 0;
+void UI_menutype_draw(bContext *C, MenuType *mt, struct uiLayout *layout)
+{
+ Menu menu = {
+ .layout = layout,
+ .type = mt,
+ };
- if (empty && (flag & UI_LAYOUT_OP_SHOW_EMPTY)) {
- uiItemL(layout, IFACE_("No Properties"), ICON_NONE);
- }
+ if (G.debug & G_DEBUG_WM) {
+ printf("%s: opening menu \"%s\"\n", __func__, mt->idname);
}
-#ifdef USE_OP_RESET_BUT
- /* its possible that reset can do nothing if all have PROP_SKIP_SAVE enabled
- * but this is not so important if this button is drawn in those cases
- * (which isn't all that likely anyway) - campbell */
- if (op->properties->len) {
- uiBlock *block;
- uiBut *but;
- uiLayout *col; /* needed to avoid alignment errors with previous buttons */
-
- col = uiLayoutColumn(layout, false);
- block = uiLayoutGetBlock(col);
- but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILE_REFRESH, IFACE_("Reset"), 0, 0, UI_UNIT_X, UI_UNIT_Y,
- NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Reset operator defaults"));
- UI_but_func_set(but, ui_layout_operator_buts__reset_cb, op, NULL);
+ if (layout->context) {
+ CTX_store_set(C, layout->context);
}
-#endif
-
- /* set various special settings for buttons */
- {
- uiBlock *block = uiLayoutGetBlock(layout);
- const bool is_popup = (block->flag & UI_BLOCK_KEEP_OPEN) != 0;
- uiBut *but;
-
- for (but = block->buttons.first; but; but = but->next) {
- /* no undo for buttons for operator redo panels */
- UI_but_flag_disable(but, UI_BUT_UNDO);
-
- /* only for popups, see [#36109] */
-
- /* if button is operator's default property, and a text-field, enable focus for it
- * - this is used for allowing operators with popups to rename stuff with fewer clicks
- */
- if (is_popup) {
- if ((but->rnaprop == op->type->prop) && (but->type == UI_BTYPE_TEXT)) {
- UI_but_focus_on_enter_event(CTX_wm_window(C), but);
- }
- }
- }
- }
-}
+ mt->draw(C, &menu);
-/* this is a bit of a hack but best keep it in one place at least */
-MenuType *UI_but_menutype_get(uiBut *but)
-{
- if (but->menu_create_func == ui_item_menutype_func) {
- return (MenuType *)but->poin;
- }
- else {
- return NULL;
+ if (layout->context) {
+ CTX_store_set(C, NULL);
}
}
diff --git a/source/blender/editors/interface/interface_ops.c b/source/blender/editors/interface/interface_ops.c
index 40ebc946e79..046bb114a62 100644
--- a/source/blender/editors/interface/interface_ops.c
+++ b/source/blender/editors/interface/interface_ops.c
@@ -360,6 +360,9 @@ bool UI_context_copy_to_selected_list(
else if (RNA_struct_is_a(ptr->type, &RNA_Sequence)) {
*r_lb = CTX_data_collection_get(C, "selected_editable_sequences");
}
+ else if (RNA_struct_is_a(ptr->type, &RNA_FCurve)) {
+ *r_lb = CTX_data_collection_get(C, "selected_editable_fcurves");
+ }
else if (RNA_struct_is_a(ptr->type, &RNA_Node) ||
RNA_struct_is_a(ptr->type, &RNA_NodeSocket))
{
@@ -436,7 +439,7 @@ bool UI_context_copy_to_selected_list(
if ((id_data == NULL) ||
(id_data->tag & LIB_TAG_DOIT) == 0 ||
- ID_IS_LINKED_DATABLOCK(id_data) ||
+ ID_IS_LINKED(id_data) ||
(GS(id_data->name) != id_code))
{
BLI_remlink(&lb, link);
@@ -494,51 +497,51 @@ static bool copy_to_selected_button(bContext *C, bool all, bool poll)
char *path = NULL;
bool use_path_from_id;
CollectionPointerLink *link;
- ListBase lb;
-
- if (!UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path))
- return success;
+ ListBase lb = {NULL};
- for (link = lb.first; link; link = link->next) {
- if (link->ptr.data != ptr.data) {
- if (use_path_from_id) {
- /* Path relative to ID. */
- lprop = NULL;
- RNA_id_pointer_create(link->ptr.id.data, &idptr);
- RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
- }
- else if (path) {
- /* Path relative to elements from list. */
- lprop = NULL;
- RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
- }
- else {
- lptr = link->ptr;
- lprop = prop;
- }
+ if (UI_context_copy_to_selected_list(C, &ptr, prop, &lb, &use_path_from_id, &path) &&
+ !BLI_listbase_is_empty(&lb))
+ {
+ for (link = lb.first; link; link = link->next) {
+ if (link->ptr.data != ptr.data) {
+ if (use_path_from_id) {
+ /* Path relative to ID. */
+ lprop = NULL;
+ RNA_id_pointer_create(link->ptr.id.data, &idptr);
+ RNA_path_resolve_property(&idptr, path, &lptr, &lprop);
+ }
+ else if (path) {
+ /* Path relative to elements from list. */
+ lprop = NULL;
+ RNA_path_resolve_property(&link->ptr, path, &lptr, &lprop);
+ }
+ else {
+ lptr = link->ptr;
+ lprop = prop;
+ }
- if (lptr.data == ptr.data) {
- /* lptr might not be the same as link->ptr! */
- continue;
- }
+ if (lptr.data == ptr.data) {
+ /* lptr might not be the same as link->ptr! */
+ continue;
+ }
- if (lprop == prop) {
- if (RNA_property_editable(&lptr, lprop)) {
- if (poll) {
- success = true;
- break;
- }
- else {
- if (RNA_property_copy(&lptr, &ptr, prop, (all) ? -1 : index)) {
- RNA_property_update(C, &lptr, prop);
+ if (lprop == prop) {
+ if (RNA_property_editable(&lptr, lprop)) {
+ if (poll) {
success = true;
+ break;
+ }
+ else {
+ if (RNA_property_copy(&lptr, &ptr, prop, (all) ? -1 : index)) {
+ RNA_property_update(C, &lptr, prop);
+ success = true;
+ }
}
}
}
}
}
}
-
MEM_SAFE_FREE(path);
BLI_freelistN(&lb);
}
@@ -608,7 +611,8 @@ static int reports_to_text_exec(bContext *C, wmOperator *UNUSED(op))
str = BKE_reports_string(reports, (G.debug & G_DEBUG) ? RPT_DEBUG : RPT_INFO);
if (str) {
- BKE_text_write(txt, str);
+ TextUndoBuf *utxt = NULL; // FIXME
+ BKE_text_write(txt, utxt, str);
MEM_freeN(str);
return OPERATOR_FINISHED;
@@ -739,6 +743,7 @@ static int editsource_text_edit(
if (text == NULL) {
text = BKE_text_load(bmain, filepath, bmain->name);
+ id_us_ensure_real(&text->id);
}
if (text == NULL) {
@@ -1124,6 +1129,8 @@ void ED_operatortypes_ui(void)
/* external */
WM_operatortype_append(UI_OT_eyedropper_color);
+ WM_operatortype_append(UI_OT_eyedropper_colorband);
+ WM_operatortype_append(UI_OT_eyedropper_colorband_point);
WM_operatortype_append(UI_OT_eyedropper_id);
WM_operatortype_append(UI_OT_eyedropper_depth);
WM_operatortype_append(UI_OT_eyedropper_driver);
@@ -1140,6 +1147,8 @@ void ED_keymap_ui(wmKeyConfig *keyconf)
/* eyedroppers - notice they all have the same shortcut, but pass the event
* through until a suitable eyedropper for the active button is found */
WM_keymap_add_item(keymap, "UI_OT_eyedropper_color", EKEY, KM_PRESS, 0, 0);
+ WM_keymap_add_item(keymap, "UI_OT_eyedropper_colorband", EKEY, KM_PRESS, 0, 0);
+ WM_keymap_add_item(keymap, "UI_OT_eyedropper_colorband_point", EKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_add_item(keymap, "UI_OT_eyedropper_id", EKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "UI_OT_eyedropper_depth", EKEY, KM_PRESS, 0, 0);
@@ -1162,4 +1171,5 @@ void ED_keymap_ui(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "ANIM_OT_keyingset_button_remove", KKEY, KM_PRESS, KM_ALT, 0);
eyedropper_modal_keymap(keyconf);
+ eyedropper_colorband_modal_keymap(keyconf);
}
diff --git a/source/blender/editors/interface/interface_panel.c b/source/blender/editors/interface/interface_panel.c
index c131bcb8e14..d9685d7281b 100644
--- a/source/blender/editors/interface/interface_panel.c
+++ b/source/blender/editors/interface/interface_panel.c
@@ -496,14 +496,14 @@ static void ui_draw_panel_dragwidget(const rctf *rect)
const int col_tint = 84;
const int px = (int)U.pixelsize;
- const int px_zoom = max_ii(iroundf(BLI_rctf_size_y(rect) / 22.0f), 1);
+ const int px_zoom = max_ii(round_fl_to_int(BLI_rctf_size_y(rect) / 22.0f), 1);
- const int box_margin = max_ii(iroundf((float)(px_zoom * 2.0f)), px);
- const int box_size = max_ii(iroundf((BLI_rctf_size_y(rect) / 8.0f) - px), px);
+ const int box_margin = max_ii(round_fl_to_int((float)(px_zoom * 2.0f)), px);
+ const int box_size = max_ii(round_fl_to_int((BLI_rctf_size_y(rect) / 8.0f) - px), px);
const int x_min = rect->xmin;
const int y_min = rect->ymin;
- const int y_ofs = max_ii(iroundf(BLI_rctf_size_y(rect) / 3.0f), px);
+ const int y_ofs = max_ii(round_fl_to_int(BLI_rctf_size_y(rect) / 3.0f), px);
const int x_ofs = y_ofs;
int i_x, i_y;
@@ -877,8 +877,8 @@ static bool uiAlignPanelStep(ScrArea *sa, ARegion *ar, const float fac, const bo
for (a = 0; a < tot; a++, ps++) {
if ((ps->pa->flag & PNL_SELECT) == 0) {
if ((ps->orig->ofsx != ps->pa->ofsx) || (ps->orig->ofsy != ps->pa->ofsy)) {
- ps->orig->ofsx = iroundf(fac * (float)ps->pa->ofsx + (1.0f - fac) * (float)ps->orig->ofsx);
- ps->orig->ofsy = iroundf(fac * (float)ps->pa->ofsy + (1.0f - fac) * (float)ps->orig->ofsy);
+ ps->orig->ofsx = round_fl_to_int(fac * (float)ps->pa->ofsx + (1.0f - fac) * (float)ps->orig->ofsx);
+ ps->orig->ofsy = round_fl_to_int(fac * (float)ps->pa->ofsy + (1.0f - fac) * (float)ps->orig->ofsy);
done = true;
}
}
@@ -1281,7 +1281,7 @@ static int ui_panel_drag_collapse_handler(bContext *C, const wmEvent *event, voi
static void ui_panel_drag_collapse_handler_add(const bContext *C, const bool was_open)
{
wmWindow *win = CTX_wm_window(C);
- wmEvent *event = win->eventstate;
+ const wmEvent *event = win->eventstate;
uiPanelDragCollapseHandle *dragcol_data = MEM_mallocN(sizeof(*dragcol_data), __func__);
dragcol_data->was_first_open = was_open;
@@ -1615,11 +1615,11 @@ void UI_panel_category_draw_all(ARegion *ar, const char *category_id_active)
PanelCategoryDyn *pc_dyn;
const float aspect = ((uiBlock *)ar->uiblocks.first)->aspect;
const float zoom = 1.0f / aspect;
- const int px = max_ii(1, iroundf(U.pixelsize));
- const int category_tabs_width = iroundf(UI_PANEL_CATEGORY_MARGIN_WIDTH * zoom);
+ const int px = max_ii(1, round_fl_to_int(U.pixelsize));
+ const int category_tabs_width = round_fl_to_int(UI_PANEL_CATEGORY_MARGIN_WIDTH * zoom);
const float dpi_fac = UI_DPI_FAC;
- const int tab_v_pad_text = iroundf((2 + ((px * 3) * dpi_fac)) * zoom); /* pading of tabs around text */
- const int tab_v_pad = iroundf((4 + (2 * px * dpi_fac)) * zoom); /* padding between tabs */
+ const int tab_v_pad_text = round_fl_to_int((2 + ((px * 3) * dpi_fac)) * zoom); /* pading of tabs around text */
+ const int tab_v_pad = round_fl_to_int((4 + (2 * px * dpi_fac)) * zoom); /* padding between tabs */
const float tab_curve_radius = ((px * 3) * dpi_fac) * zoom;
const int roundboxtype = UI_CNR_TOP_LEFT | UI_CNR_BOTTOM_LEFT;
bool is_alpha;
diff --git a/source/blender/editors/interface/interface_region_color_picker.c b/source/blender/editors/interface/interface_region_color_picker.c
new file mode 100644
index 00000000000..4309e913d9e
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_color_picker.c
@@ -0,0 +1,650 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_color_picker.c
+ * \ingroup edinterface
+ *
+ * Color Picker Region & Color Utils
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_math.h"
+#include "BLI_listbase.h"
+#include "BLI_string.h"
+
+#include "BKE_context.h"
+
+#include "WM_types.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "BLT_translation.h"
+
+#include "ED_screen.h"
+
+#include "IMB_colormanagement.h"
+
+#include "interface_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Color Conversion
+ * \{ */
+
+void ui_rgb_to_color_picker_compat_v(const float rgb[3], float r_cp[3])
+{
+ switch (U.color_picker_type) {
+ case USER_CP_CIRCLE_HSL:
+ rgb_to_hsl_compat_v(rgb, r_cp);
+ break;
+ default:
+ rgb_to_hsv_compat_v(rgb, r_cp);
+ break;
+ }
+}
+
+void ui_rgb_to_color_picker_v(const float rgb[3], float r_cp[3])
+{
+ switch (U.color_picker_type) {
+ case USER_CP_CIRCLE_HSL:
+ rgb_to_hsl_v(rgb, r_cp);
+ break;
+ default:
+ rgb_to_hsv_v(rgb, r_cp);
+ break;
+ }
+}
+
+void ui_color_picker_to_rgb_v(const float r_cp[3], float rgb[3])
+{
+ switch (U.color_picker_type) {
+ case USER_CP_CIRCLE_HSL:
+ hsl_to_rgb_v(r_cp, rgb);
+ break;
+ default:
+ hsv_to_rgb_v(r_cp, rgb);
+ break;
+ }
+}
+
+void ui_color_picker_to_rgb(float r_cp0, float r_cp1, float r_cp2, float *r, float *g, float *b)
+{
+ switch (U.color_picker_type) {
+ case USER_CP_CIRCLE_HSL:
+ hsl_to_rgb(r_cp0, r_cp1, r_cp2, r, g, b);
+ break;
+ default:
+ hsv_to_rgb(r_cp0, r_cp1, r_cp2, r, g, b);
+ break;
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Color Picker
+ * \{ */
+
+/* for picker, while editing hsv */
+void ui_but_hsv_set(uiBut *but)
+{
+ float col[3];
+ ColorPicker *cpicker = but->custom_data;
+ float *hsv = cpicker->color_data;
+
+ ui_color_picker_to_rgb_v(hsv, col);
+
+ ui_but_v3_set(but, col);
+}
+
+/* Updates all buttons who share the same color picker as the one passed
+ * also used by small picker, be careful with name checks below... */
+static void ui_update_color_picker_buts_rgb(
+ uiBlock *block, ColorPicker *cpicker, const float rgb[3], bool is_display_space)
+{
+ uiBut *bt;
+ float *hsv = cpicker->color_data;
+ struct ColorManagedDisplay *display = NULL;
+ /* this is to keep the H and S value when V is equal to zero
+ * and we are working in HSV mode, of course!
+ */
+ if (is_display_space) {
+ ui_rgb_to_color_picker_compat_v(rgb, hsv);
+ }
+ else {
+ /* we need to convert to display space to use hsv, because hsv is stored in display space */
+ float rgb_display[3];
+
+ copy_v3_v3(rgb_display, rgb);
+ ui_block_cm_to_display_space_v3(block, rgb_display);
+ ui_rgb_to_color_picker_compat_v(rgb_display, hsv);
+ }
+
+ if (block->color_profile)
+ display = ui_block_cm_display_get(block);
+
+ /* this updates button strings, is hackish... but button pointers are on stack of caller function */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if (bt->custom_data != cpicker)
+ continue;
+
+ if (bt->rnaprop) {
+ ui_but_v3_set(bt, rgb);
+
+ /* original button that created the color picker already does undo
+ * push, so disable it on RNA buttons in the color picker block */
+ UI_but_flag_disable(bt, UI_BUT_UNDO);
+ }
+ else if (STREQ(bt->str, "Hex: ")) {
+ float rgb_gamma[3];
+ unsigned char rgb_gamma_uchar[3];
+ double intpart;
+ char col[16];
+
+ /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
+
+ copy_v3_v3(rgb_gamma, rgb);
+
+ if (display) {
+ /* make a display version, for Hex code */
+ IMB_colormanagement_scene_linear_to_display_v3(rgb_gamma, display);
+ }
+
+ if (rgb_gamma[0] > 1.0f) rgb_gamma[0] = modf(rgb_gamma[0], &intpart);
+ if (rgb_gamma[1] > 1.0f) rgb_gamma[1] = modf(rgb_gamma[1], &intpart);
+ if (rgb_gamma[2] > 1.0f) rgb_gamma[2] = modf(rgb_gamma[2], &intpart);
+
+ rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
+ BLI_snprintf(col, sizeof(col), "%02X%02X%02X", UNPACK3_EX((uint), rgb_gamma_uchar, ));
+
+ strcpy(bt->poin, col);
+ }
+ else if (bt->str[1] == ' ') {
+ if (bt->str[0] == 'R') {
+ ui_but_value_set(bt, rgb[0]);
+ }
+ else if (bt->str[0] == 'G') {
+ ui_but_value_set(bt, rgb[1]);
+ }
+ else if (bt->str[0] == 'B') {
+ ui_but_value_set(bt, rgb[2]);
+ }
+ else if (bt->str[0] == 'H') {
+ ui_but_value_set(bt, hsv[0]);
+ }
+ else if (bt->str[0] == 'S') {
+ ui_but_value_set(bt, hsv[1]);
+ }
+ else if (bt->str[0] == 'V') {
+ ui_but_value_set(bt, hsv[2]);
+ }
+ else if (bt->str[0] == 'L') {
+ ui_but_value_set(bt, hsv[2]);
+ }
+ }
+
+ ui_but_update(bt);
+ }
+}
+
+static void ui_colorpicker_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
+{
+ uiBut *but = (uiBut *)bt1;
+ uiPopupBlockHandle *popup = but->block->handle;
+ PropertyRNA *prop = but->rnaprop;
+ PointerRNA ptr = but->rnapoin;
+ float rgb[4];
+
+ if (prop) {
+ RNA_property_float_get_array(&ptr, prop, rgb);
+ ui_update_color_picker_buts_rgb(
+ but->block, but->custom_data, rgb, (RNA_property_subtype(prop) == PROP_COLOR_GAMMA));
+ }
+
+ if (popup)
+ popup->menuretval = UI_RETURN_UPDATE;
+}
+
+static void ui_color_wheel_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
+{
+ uiBut *but = (uiBut *)bt1;
+ uiPopupBlockHandle *popup = but->block->handle;
+ float rgb[3];
+ ColorPicker *cpicker = but->custom_data;
+ float *hsv = cpicker->color_data;
+ bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
+
+ ui_color_picker_to_rgb_v(hsv, rgb);
+
+ /* hsv is saved in display space so convert back */
+ if (use_display_colorspace) {
+ ui_block_cm_to_scene_linear_v3(but->block, rgb);
+ }
+
+ ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, !use_display_colorspace);
+
+ if (popup)
+ popup->menuretval = UI_RETURN_UPDATE;
+}
+
+static void ui_colorpicker_hex_rna_cb(bContext *UNUSED(C), void *bt1, void *hexcl)
+{
+ uiBut *but = (uiBut *)bt1;
+ uiPopupBlockHandle *popup = but->block->handle;
+ ColorPicker *cpicker = but->custom_data;
+ char *hexcol = (char *)hexcl;
+ float rgb[3];
+
+ hex_to_rgb(hexcol, rgb, rgb + 1, rgb + 2);
+
+ /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
+ if (but->block->color_profile) {
+ /* so we need to linearise it for Blender */
+ ui_block_cm_to_scene_linear_v3(but->block, rgb);
+ }
+
+ ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, false);
+
+ if (popup)
+ popup->menuretval = UI_RETURN_UPDATE;
+}
+
+static void ui_popup_close_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
+{
+ uiBut *but = (uiBut *)bt1;
+ uiPopupBlockHandle *popup = but->block->handle;
+
+ if (popup)
+ popup->menuretval = UI_RETURN_OK;
+}
+
+static void ui_colorpicker_hide_reveal(uiBlock *block, short colormode)
+{
+ uiBut *bt;
+
+ /* tag buttons */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if ((bt->func == ui_colorpicker_rna_cb) && bt->type == UI_BTYPE_NUM_SLIDER && bt->rnaindex != 3) {
+ /* RGB sliders (color circle and alpha are always shown) */
+ if (colormode == 0) bt->flag &= ~UI_HIDDEN;
+ else bt->flag |= UI_HIDDEN;
+ }
+ else if (bt->func == ui_color_wheel_rna_cb) {
+ /* HSV sliders */
+ if (colormode == 1) bt->flag &= ~UI_HIDDEN;
+ else bt->flag |= UI_HIDDEN;
+ }
+ else if (bt->func == ui_colorpicker_hex_rna_cb || bt->type == UI_BTYPE_LABEL) {
+ /* hex input or gamma correction status label */
+ if (colormode == 2) bt->flag &= ~UI_HIDDEN;
+ else bt->flag |= UI_HIDDEN;
+ }
+ }
+}
+
+static void ui_colorpicker_create_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
+{
+ uiBut *bt = bt1;
+ short colormode = ui_but_value_get(bt);
+ ui_colorpicker_hide_reveal(bt->block, colormode);
+}
+
+#define PICKER_H (7.5f * U.widget_unit)
+#define PICKER_W (7.5f * U.widget_unit)
+#define PICKER_SPACE (0.3f * U.widget_unit)
+#define PICKER_BAR (0.7f * U.widget_unit)
+
+#define PICKER_TOTAL_W (PICKER_W + PICKER_SPACE + PICKER_BAR)
+
+static void ui_colorpicker_circle(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, ColorPicker *cpicker)
+{
+ uiBut *bt;
+
+ /* HS circle */
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, PICKER_H, PICKER_W,
+ ptr, prop, -1, 0.0, 0.0, 0.0, 0, TIP_("Color"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+
+ /* value */
+ if (U.color_picker_type == USER_CP_CIRCLE_HSL) {
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H,
+ ptr, prop, -1, 0.0, 0.0, UI_GRAD_L_ALT, 0, "Lightness");
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ }
+ else {
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H,
+ ptr, prop, -1, 0.0, 0.0, UI_GRAD_V_ALT, 0, TIP_("Value"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ }
+ bt->custom_data = cpicker;
+}
+
+
+static void ui_colorpicker_square(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int type, ColorPicker *cpicker)
+{
+ uiBut *bt;
+ int bartype = type + 3;
+
+ /* HS square */
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_HSVCUBE, 0, "", 0, PICKER_BAR + PICKER_SPACE, PICKER_TOTAL_W, PICKER_H,
+ ptr, prop, -1, 0.0, 0.0, type, 0, TIP_("Color"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+
+ /* value */
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, PICKER_TOTAL_W, PICKER_BAR,
+ ptr, prop, -1, 0.0, 0.0, bartype, 0, TIP_("Value"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+}
+
+/* a HS circle, V slider, rgb/hsv/hex sliders */
+static void ui_block_colorpicker(
+ uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop, bool show_picker)
+{
+ static short colormode = 0; /* temp? 0=rgb, 1=hsv, 2=hex */
+ uiBut *bt;
+ int width, butwidth;
+ static char tip[50];
+ static char hexcol[128];
+ float rgb_gamma[3];
+ unsigned char rgb_gamma_uchar[3];
+ float softmin, softmax, hardmin, hardmax, step, precision;
+ int yco;
+ ColorPicker *cpicker = ui_block_colorpicker_create(block);
+ float *hsv = cpicker->color_data;
+
+ width = PICKER_TOTAL_W;
+ butwidth = width - 1.5f * UI_UNIT_X;
+
+ /* existence of profile means storage is in linear color space, with display correction */
+ /* XXX That tip message is not use anywhere! */
+ if (!block->color_profile) {
+ BLI_strncpy(tip, N_("Value in Display Color Space"), sizeof(tip));
+ copy_v3_v3(rgb_gamma, rgba);
+ }
+ else {
+ BLI_strncpy(tip, N_("Value in Linear RGB Color Space"), sizeof(tip));
+
+ /* make a display version, for Hex code */
+ copy_v3_v3(rgb_gamma, rgba);
+ ui_block_cm_to_display_space_v3(block, rgb_gamma);
+ }
+
+ /* sneaky way to check for alpha */
+ rgba[3] = FLT_MAX;
+
+ RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
+ RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
+ RNA_property_float_get_array(ptr, prop, rgba);
+
+ /* when the softmax isn't defined in the RNA,
+ * using very large numbers causes sRGB/linear round trip to fail. */
+ if (softmax == FLT_MAX) {
+ softmax = 1.0f;
+ }
+
+ switch (U.color_picker_type) {
+ case USER_CP_SQUARE_SV:
+ ui_colorpicker_square(block, ptr, prop, UI_GRAD_SV, cpicker);
+ break;
+ case USER_CP_SQUARE_HS:
+ ui_colorpicker_square(block, ptr, prop, UI_GRAD_HS, cpicker);
+ break;
+ case USER_CP_SQUARE_HV:
+ ui_colorpicker_square(block, ptr, prop, UI_GRAD_HV, cpicker);
+ break;
+
+ /* user default */
+ case USER_CP_CIRCLE_HSV:
+ case USER_CP_CIRCLE_HSL:
+ default:
+ ui_colorpicker_circle(block, ptr, prop, cpicker);
+ break;
+ }
+
+ /* mode */
+ yco = -1.5f * UI_UNIT_Y;
+ UI_block_align_begin(block);
+ bt = uiDefButS(
+ block, UI_BTYPE_ROW, 0, IFACE_("RGB"), 0, yco, width / 3, UI_UNIT_Y,
+ &colormode, 0.0, 0.0, 0, 0, "");
+ UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ if (U.color_picker_type == USER_CP_CIRCLE_HSL) {
+ bt = uiDefButS(
+ block, UI_BTYPE_ROW, 0, IFACE_("HSL"), width / 3, yco, width / 3, UI_UNIT_Y,
+ &colormode, 0.0, 1.0, 0, 0, "");
+ }
+ else {
+ bt = uiDefButS(
+ block, UI_BTYPE_ROW, 0, IFACE_("HSV"), width / 3, yco, width / 3, UI_UNIT_Y,
+ &colormode, 0.0, 1.0, 0, 0, "");
+ }
+ UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ bt = uiDefButS(
+ block, UI_BTYPE_ROW, 0, IFACE_("Hex"), 2 * width / 3, yco, width / 3, UI_UNIT_Y,
+ &colormode, 0.0, 2.0, 0, 0, "");
+ UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ UI_block_align_end(block);
+
+ yco = -3.0f * UI_UNIT_Y;
+ if (show_picker) {
+ bt = uiDefIconButO(
+ block, UI_BTYPE_BUT, "UI_OT_eyedropper_color", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER,
+ butwidth + 10, yco, UI_UNIT_X, UI_UNIT_Y, NULL);
+ UI_but_func_set(bt, ui_popup_close_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ }
+
+ /* RGB values */
+ UI_block_align_begin(block);
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("R:"), 0, yco, butwidth, UI_UNIT_Y,
+ ptr, prop, 0, 0.0, 0.0, 0, 3, TIP_("Red"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("G:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y,
+ ptr, prop, 1, 0.0, 0.0, 0, 3, TIP_("Green"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("B:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y,
+ ptr, prop, 2, 0.0, 0.0, 0, 3, TIP_("Blue"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+
+ /* could use uiItemFullR(col, ptr, prop, -1, 0, UI_ITEM_R_EXPAND|UI_ITEM_R_SLIDER, "", ICON_NONE);
+ * but need to use UI_but_func_set for updating other fake buttons */
+
+ /* HSV values */
+ yco = -3.0f * UI_UNIT_Y;
+ UI_block_align_begin(block);
+ bt = uiDefButF(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("H:"), 0, yco, butwidth,
+ UI_UNIT_Y, hsv, 0.0, 1.0, 10, 3, TIP_("Hue"));
+ UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
+ bt->custom_data = cpicker;
+ bt = uiDefButF(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("S:"), 0, yco -= UI_UNIT_Y,
+ butwidth, UI_UNIT_Y, hsv + 1, 0.0, 1.0, 10, 3, TIP_("Saturation"));
+ UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
+ bt->custom_data = cpicker;
+ if (U.color_picker_type == USER_CP_CIRCLE_HSL) {
+ bt = uiDefButF(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("L:"), 0, yco -= UI_UNIT_Y,
+ butwidth, UI_UNIT_Y, hsv + 2, 0.0, 1.0, 10, 3, TIP_("Lightness"));
+ }
+ else {
+ bt = uiDefButF(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("V:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y,
+ hsv + 2, 0.0, softmax, 10, 3, TIP_("Value"));
+ }
+
+ bt->hardmax = hardmax; /* not common but rgb may be over 1.0 */
+ UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
+ bt->custom_data = cpicker;
+
+ UI_block_align_end(block);
+
+ if (rgba[3] != FLT_MAX) {
+ bt = uiDefButR_prop(
+ block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("A: "), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y,
+ ptr, prop, 3, 0.0, 0.0, 0, 3, TIP_("Alpha"));
+ UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
+ bt->custom_data = cpicker;
+ }
+ else {
+ rgba[3] = 1.0f;
+ }
+
+ rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
+ BLI_snprintf(hexcol, sizeof(hexcol), "%02X%02X%02X", UNPACK3_EX((uint), rgb_gamma_uchar, ));
+
+ yco = -3.0f * UI_UNIT_Y;
+ bt = uiDefBut(
+ block, UI_BTYPE_TEXT, 0, IFACE_("Hex: "), 0, yco, butwidth, UI_UNIT_Y,
+ hexcol, 0, 8, 0, 0, TIP_("Hex triplet for color (#RRGGBB)"));
+ UI_but_func_set(bt, ui_colorpicker_hex_rna_cb, bt, hexcol);
+ bt->custom_data = cpicker;
+ uiDefBut(
+ block, UI_BTYPE_LABEL, 0, IFACE_("(Gamma Corrected)"), 0, yco - UI_UNIT_Y,
+ butwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
+
+ ui_rgb_to_color_picker_v(rgb_gamma, hsv);
+
+ ui_colorpicker_hide_reveal(block, colormode);
+}
+
+
+static int ui_colorpicker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *block, const wmEvent *event)
+{
+ float add = 0.0f;
+
+ if (event->type == WHEELUPMOUSE)
+ add = 0.05f;
+ else if (event->type == WHEELDOWNMOUSE)
+ add = -0.05f;
+
+ if (add != 0.0f) {
+ uiBut *but;
+
+ for (but = block->buttons.first; but; but = but->next) {
+ if (but->type == UI_BTYPE_HSVCUBE && but->active == NULL) {
+ uiPopupBlockHandle *popup = block->handle;
+ float rgb[3];
+ ColorPicker *cpicker = but->custom_data;
+ float *hsv = cpicker->color_data;
+ bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
+
+ ui_but_v3_get(but, rgb);
+
+ if (use_display_colorspace)
+ ui_block_cm_to_display_space_v3(block, rgb);
+
+ ui_rgb_to_color_picker_compat_v(rgb, hsv);
+
+ hsv[2] = CLAMPIS(hsv[2] + add, 0.0f, 1.0f);
+ ui_color_picker_to_rgb_v(hsv, rgb);
+
+ if (use_display_colorspace)
+ ui_block_cm_to_scene_linear_v3(block, rgb);
+
+ ui_but_v3_set(but, rgb);
+
+ ui_update_color_picker_buts_rgb(block, cpicker, rgb, !use_display_colorspace);
+ if (popup)
+ popup->menuretval = UI_RETURN_UPDATE;
+
+ return 1;
+ }
+ }
+ }
+ return 0;
+}
+
+uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_but)
+{
+ uiBut *but = arg_but;
+ uiBlock *block;
+ bool show_picker = true;
+
+ block = UI_block_begin(C, handle->region, __func__, UI_EMBOSS);
+
+ if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
+ block->color_profile = false;
+ }
+
+ if (but->block) {
+ /* if color block is invoked from a popup we wouldn't be able to set color properly
+ * this is because color picker will close popups first and then will try to figure
+ * out active button RNA, and of course it'll fail
+ */
+ show_picker = (but->block->flag & UI_BLOCK_POPUP) == 0;
+ }
+
+ copy_v3_v3(handle->retvec, but->editvec);
+
+ ui_block_colorpicker(block, handle->retvec, &but->rnapoin, but->rnaprop, show_picker);
+
+ block->flag = UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_OUT_1 | UI_BLOCK_MOVEMOUSE_QUIT;
+ UI_block_bounds_set_normal(block, 0.5 * UI_UNIT_X);
+
+ block->block_event_func = ui_colorpicker_small_wheel_cb;
+
+ /* and lets go */
+ block->direction = UI_DIR_UP;
+
+ return block;
+}
+
+ColorPicker *ui_block_colorpicker_create(struct uiBlock *block)
+{
+ ColorPicker *cpicker = MEM_callocN(sizeof(ColorPicker), "color_picker");
+ BLI_addhead(&block->color_pickers.list, cpicker);
+
+ return cpicker;
+}
+
+/** \} */
diff --git a/source/blender/editors/interface/interface_region_menu_pie.c b/source/blender/editors/interface/interface_region_menu_pie.c
new file mode 100644
index 00000000000..37a603d967f
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_menu_pie.c
@@ -0,0 +1,380 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_menu_pie.c
+ * \ingroup edinterface
+ *
+ * Pie Menu Region
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_utildefines.h"
+
+#include "PIL_time.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "BLT_translation.h"
+
+#include "ED_screen.h"
+
+#include "interface_intern.h"
+#include "interface_regions_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Pie Menu
+ * \{ */
+
+struct uiPieMenu {
+ uiBlock *block_radial; /* radial block of the pie menu (more could be added later) */
+ uiLayout *layout;
+ int mx, my;
+};
+
+static uiBlock *ui_block_func_PIE(bContext *UNUSED(C), uiPopupBlockHandle *handle, void *arg_pie)
+{
+ uiBlock *block;
+ uiPieMenu *pie = arg_pie;
+ int minwidth, width, height;
+
+ minwidth = 50;
+ block = pie->block_radial;
+
+ /* in some cases we create the block before the region,
+ * so we set it delayed here if necessary */
+ if (BLI_findindex(&handle->region->uiblocks, block) == -1)
+ UI_block_region_set(block, handle->region);
+
+ UI_block_layout_resolve(block, &width, &height);
+
+ UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
+
+ block->minbounds = minwidth;
+ block->bounds = 1;
+ block->mx = 0;
+ block->my = 0;
+ block->bounds_type = UI_BLOCK_BOUNDS_PIE_CENTER;
+
+ block->pie_data.pie_center_spawned[0] = pie->mx;
+ block->pie_data.pie_center_spawned[1] = pie->my;
+
+ return pie->block_radial;
+}
+
+static float ui_pie_menu_title_width(const char *name, int icon)
+{
+ const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
+ return (UI_fontstyle_string_width(fstyle, name) +
+ (UI_UNIT_X * (1.50f + (icon ? 0.25f : 0.0f))));
+}
+
+uiPieMenu *UI_pie_menu_begin(struct bContext *C, const char *title, int icon, const wmEvent *event)
+{
+ uiStyle *style;
+ uiPieMenu *pie;
+ short event_type;
+
+ wmWindow *win = CTX_wm_window(C);
+
+ style = UI_style_get_dpi();
+ pie = MEM_callocN(sizeof(*pie), "pie menu");
+
+ pie->block_radial = UI_block_begin(C, NULL, __func__, UI_EMBOSS);
+ /* may be useful later to allow spawning pies
+ * from old positions */
+ /* pie->block_radial->flag |= UI_BLOCK_POPUP_MEMORY; */
+ pie->block_radial->puphash = ui_popup_menu_hash(title);
+ pie->block_radial->flag |= UI_BLOCK_RADIAL;
+
+ /* if pie is spawned by a left click, release or click event, it is always assumed to be click style */
+ if (event->type == LEFTMOUSE || ELEM(event->val, KM_RELEASE, KM_CLICK)) {
+ pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
+ pie->block_radial->pie_data.event = EVENT_NONE;
+ win->lock_pie_event = EVENT_NONE;
+ }
+ else {
+ if (win->last_pie_event != EVENT_NONE) {
+ /* original pie key has been released, so don't propagate the event */
+ if (win->lock_pie_event == EVENT_NONE) {
+ event_type = EVENT_NONE;
+ pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
+ }
+ else
+ event_type = win->last_pie_event;
+ }
+ else {
+ event_type = event->type;
+ }
+
+ pie->block_radial->pie_data.event = event_type;
+ win->lock_pie_event = event_type;
+ }
+
+ pie->layout = UI_block_layout(pie->block_radial, UI_LAYOUT_VERTICAL, UI_LAYOUT_PIEMENU, 0, 0, 200, 0, 0, style);
+ pie->mx = event->x;
+ pie->my = event->y;
+
+ /* create title button */
+ if (title[0]) {
+ uiBut *but;
+ char titlestr[256];
+ int w;
+ if (icon) {
+ BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
+ w = ui_pie_menu_title_width(titlestr, icon);
+ but = uiDefIconTextBut(
+ pie->block_radial, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, w, UI_UNIT_Y,
+ NULL, 0.0, 0.0, 0, 0, "");
+ }
+ else {
+ w = ui_pie_menu_title_width(title, 0);
+ but = uiDefBut(
+ pie->block_radial, UI_BTYPE_LABEL, 0, title, 0, 0, w, UI_UNIT_Y,
+ NULL, 0.0, 0.0, 0, 0, "");
+ }
+ /* do not align left */
+ but->drawflag &= ~UI_BUT_TEXT_LEFT;
+ pie->block_radial->pie_data.title = but->str;
+ pie->block_radial->pie_data.icon = icon;
+ }
+
+ return pie;
+}
+
+void UI_pie_menu_end(bContext *C, uiPieMenu *pie)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiPopupBlockHandle *menu;
+
+ menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_PIE, pie);
+ menu->popup = true;
+ menu->towardstime = PIL_check_seconds_timer();
+
+ UI_popup_handlers_add(
+ C, &window->modalhandlers,
+ menu, WM_HANDLER_ACCEPT_DBL_CLICK);
+ WM_event_add_mousemove(C);
+
+ menu->can_refresh = false;
+ MEM_freeN(pie);
+}
+
+uiLayout *UI_pie_menu_layout(uiPieMenu *pie)
+{
+ return pie->layout;
+}
+
+int UI_pie_menu_invoke(struct bContext *C, const char *idname, const wmEvent *event)
+{
+ uiPieMenu *pie;
+ uiLayout *layout;
+ MenuType *mt = WM_menutype_find(idname, true);
+
+ if (mt == NULL) {
+ printf("%s: named menu \"%s\" not found\n", __func__, idname);
+ return OPERATOR_CANCELLED;
+ }
+
+ if (WM_menutype_poll(C, mt) == false) {
+ /* cancel but allow event to pass through, just like operators do */
+ return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH);
+ }
+
+ pie = UI_pie_menu_begin(C, IFACE_(mt->label), ICON_NONE, event);
+ layout = UI_pie_menu_layout(pie);
+
+ UI_menutype_draw(C, mt, layout);
+
+ UI_pie_menu_end(C, pie);
+
+ return OPERATOR_INTERFACE;
+}
+
+int UI_pie_menu_invoke_from_operator_enum(
+ struct bContext *C, const char *title, const char *opname,
+ const char *propname, const wmEvent *event)
+{
+ uiPieMenu *pie;
+ uiLayout *layout;
+
+ pie = UI_pie_menu_begin(C, IFACE_(title), ICON_NONE, event);
+ layout = UI_pie_menu_layout(pie);
+
+ layout = uiLayoutRadial(layout);
+ uiItemsEnumO(layout, opname, propname);
+
+ UI_pie_menu_end(C, pie);
+
+ return OPERATOR_INTERFACE;
+}
+
+int UI_pie_menu_invoke_from_rna_enum(
+ struct bContext *C, const char *title, const char *path,
+ const wmEvent *event)
+{
+ PointerRNA ctx_ptr;
+ PointerRNA r_ptr;
+ PropertyRNA *r_prop;
+ uiPieMenu *pie;
+ uiLayout *layout;
+
+ RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
+
+ if (!RNA_path_resolve(&ctx_ptr, path, &r_ptr, &r_prop)) {
+ return OPERATOR_CANCELLED;
+ }
+
+ /* invalid property, only accept enums */
+ if (RNA_property_type(r_prop) != PROP_ENUM) {
+ BLI_assert(0);
+ return OPERATOR_CANCELLED;
+ }
+
+ pie = UI_pie_menu_begin(C, IFACE_(title), ICON_NONE, event);
+
+ layout = UI_pie_menu_layout(pie);
+
+ layout = uiLayoutRadial(layout);
+ uiItemFullR(layout, &r_ptr, r_prop, RNA_NO_INDEX, 0, UI_ITEM_R_EXPAND, NULL, 0);
+
+ UI_pie_menu_end(C, pie);
+
+ return OPERATOR_INTERFACE;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/**
+ * \name Pie Menu Levels
+ *
+ * Pie menus can't contain more than 8 items (yet). When using #uiItemsFullEnumO, a "More" button is created that calls
+ * a new pie menu if the enum has too many items. We call this a new "level".
+ * Indirect recursion is used, so that a theoretically unlimited number of items is supported.
+ *
+ * This is a implementation specifically for operator enums, needed since the object mode pie now has more than 8
+ * items. Ideally we'd have some way of handling this for all kinds of pie items, but that's tricky.
+ *
+ * - Julian (Feb 2016)
+ *
+ * \{ */
+
+typedef struct PieMenuLevelData {
+ char title[UI_MAX_NAME_STR]; /* parent pie title, copied for level */
+ int icon; /* parent pie icon, copied for level */
+ int totitem; /* total count of *remaining* items */
+
+ /* needed for calling uiItemsFullEnumO_array again for new level */
+ wmOperatorType *ot;
+ const char *propname;
+ IDProperty *properties;
+ int context, flag;
+} PieMenuLevelData;
+
+/**
+ * Invokes a new pie menu for a new level.
+ */
+static void ui_pie_menu_level_invoke(bContext *C, void *argN, void *arg2)
+{
+ EnumPropertyItem *item_array = (EnumPropertyItem *)argN;
+ PieMenuLevelData *lvl = (PieMenuLevelData *)arg2;
+ wmWindow *win = CTX_wm_window(C);
+
+ uiPieMenu *pie = UI_pie_menu_begin(C, IFACE_(lvl->title), lvl->icon, win->eventstate);
+ uiLayout *layout = UI_pie_menu_layout(pie);
+
+ layout = uiLayoutRadial(layout);
+
+ PointerRNA ptr;
+
+ WM_operator_properties_create_ptr(&ptr, lvl->ot);
+ /* so the context is passed to itemf functions (some need it) */
+ WM_operator_properties_sanitize(&ptr, false);
+ PropertyRNA *prop = RNA_struct_find_property(&ptr, lvl->propname);
+
+ if (prop) {
+ uiItemsFullEnumO_items(
+ layout, lvl->ot, ptr, prop, lvl->properties, lvl->context, lvl->flag,
+ item_array, lvl->totitem);
+ }
+ else {
+ RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), lvl->propname);
+ }
+
+ UI_pie_menu_end(C, pie);
+}
+
+/**
+ * Set up data for defining a new pie menu level and add button that invokes it.
+ */
+void ui_pie_menu_level_create(
+ uiBlock *block, wmOperatorType *ot, const char *propname, IDProperty *properties,
+ const EnumPropertyItem *items, int totitem, int context, int flag)
+{
+ const int totitem_parent = PIE_MAX_ITEMS - 1;
+ const int totitem_remain = totitem - totitem_parent;
+ size_t array_size = sizeof(EnumPropertyItem) * totitem_remain;
+
+ /* used as but->func_argN so freeing is handled elsewhere */
+ EnumPropertyItem *remaining = MEM_mallocN(array_size + sizeof(EnumPropertyItem), "pie_level_item_array");
+ memcpy(remaining, items + totitem_parent, array_size);
+ /* a NULL terminating sentinal element is required */
+ memset(&remaining[totitem_remain], 0, sizeof(EnumPropertyItem));
+
+
+ /* yuk, static... issue is we can't reliably free this without doing dangerous changes */
+ static PieMenuLevelData lvl;
+ BLI_strncpy(lvl.title, block->pie_data.title, UI_MAX_NAME_STR);
+ lvl.totitem = totitem_remain;
+ lvl.ot = ot;
+ lvl.propname = propname;
+ lvl.properties = properties;
+ lvl.context = context;
+ lvl.flag = flag;
+
+ /* add a 'more' menu entry */
+ uiBut *but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_PLUS, "More", 0, 0, UI_UNIT_X * 3, UI_UNIT_Y, NULL,
+ 0.0f, 0.0f, 0.0f, 0.0f, "Show more items of this menu");
+ UI_but_funcN_set(but, ui_pie_menu_level_invoke, remaining, &lvl);
+}
+
+/** \} */ /* Pie Menu Levels */
diff --git a/source/blender/editors/interface/interface_region_menu_popup.c b/source/blender/editors/interface/interface_region_menu_popup.c
new file mode 100644
index 00000000000..9aec955413f
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_menu_popup.c
@@ -0,0 +1,626 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_menu_popup.c
+ * \ingroup edinterface
+ *
+ * PopUp Menu Region
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_math.h"
+#include "BLI_listbase.h"
+
+#include "BLI_string.h"
+#include "BLI_rect.h"
+#include "BLI_utildefines.h"
+#include "BLI_ghash.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+#include "BKE_report.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "RNA_access.h"
+
+#include "UI_interface.h"
+
+#include "BLT_translation.h"
+
+#include "ED_screen.h"
+
+#include "interface_intern.h"
+#include "interface_regions_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Utility Functions
+ * \{ */
+
+bool ui_but_menu_step_poll(const uiBut *but)
+{
+ BLI_assert(but->type == UI_BTYPE_MENU);
+
+ /* currently only RNA buttons */
+ return ((but->menu_step_func != NULL) ||
+ (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM));
+}
+
+int ui_but_menu_step(uiBut *but, int direction)
+{
+ if (ui_but_menu_step_poll(but)) {
+ if (but->menu_step_func) {
+ return but->menu_step_func(but->block->evil_C, direction, but->poin);
+ }
+ else {
+ const int curval = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
+ return RNA_property_enum_step(but->block->evil_C, &but->rnapoin, but->rnaprop, curval, direction);
+ }
+ }
+
+ printf("%s: cannot cycle button '%s'\n", __func__, but->str);
+ return 0;
+}
+
+static uint ui_popup_string_hash(const char *str)
+{
+ /* sometimes button contains hotkey, sometimes not, strip for proper compare */
+ int hash;
+ const char *delimit = strrchr(str, UI_SEP_CHAR);
+
+ if (delimit) {
+ hash = BLI_ghashutil_strhash_n(str, delimit - str);
+ }
+ else {
+ hash = BLI_ghashutil_strhash(str);
+ }
+
+ return hash;
+}
+
+uint ui_popup_menu_hash(const char *str)
+{
+ return BLI_ghashutil_strhash(str);
+}
+
+/* but == NULL read, otherwise set */
+static uiBut *ui_popup_menu_memory__internal(uiBlock *block, uiBut *but)
+{
+ static uint mem[256];
+ static bool first = true;
+
+ const uint hash = block->puphash;
+ const uint hash_mod = hash & 255;
+
+ if (first) {
+ /* init */
+ memset(mem, -1, sizeof(mem));
+ first = 0;
+ }
+
+ if (but) {
+ /* set */
+ mem[hash_mod] = ui_popup_string_hash(but->str);
+ return NULL;
+ }
+ else {
+ /* get */
+ for (but = block->buttons.first; but; but = but->next) {
+ if (ui_popup_string_hash(but->str) == mem[hash_mod]) {
+ return but;
+ }
+ }
+
+ return NULL;
+ }
+}
+
+uiBut *ui_popup_menu_memory_get(uiBlock *block)
+{
+ return ui_popup_menu_memory__internal(block, NULL);
+}
+
+void ui_popup_menu_memory_set(uiBlock *block, uiBut *but)
+{
+ ui_popup_menu_memory__internal(block, but);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Popup Menu with Callback or String
+ * \{ */
+
+struct uiPopupMenu {
+ uiBlock *block;
+ uiLayout *layout;
+ uiBut *but;
+ ARegion *butregion;
+
+ int mx, my;
+ bool popup, slideout;
+
+ uiMenuCreateFunc menu_func;
+ void *menu_arg;
+};
+
+static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, void *arg_pup)
+{
+ uiBlock *block;
+ uiPopupMenu *pup = arg_pup;
+ int minwidth, width, height;
+ char direction;
+ bool flip;
+
+ if (pup->menu_func) {
+ pup->block->handle = handle;
+ pup->menu_func(C, pup->layout, pup->menu_arg);
+ pup->block->handle = NULL;
+ }
+
+ if (pup->but) {
+ /* minimum width to enforece */
+ minwidth = BLI_rctf_size_x(&pup->but->rect);
+
+ /* settings (typically rna-enum-popups) show above the button,
+ * menu's like file-menu, show below */
+ if (pup->block->direction != 0) {
+ /* allow overriding the direction from menu_func */
+ direction = pup->block->direction;
+ }
+ else if ((pup->but->type == UI_BTYPE_PULLDOWN) ||
+ (UI_but_menutype_get(pup->but) != NULL))
+ {
+ direction = UI_DIR_DOWN;
+ }
+ else {
+ direction = UI_DIR_UP;
+ }
+ }
+ else {
+ minwidth = 50;
+ direction = UI_DIR_DOWN;
+ }
+
+ flip = (direction == UI_DIR_DOWN);
+
+ block = pup->block;
+
+ /* in some cases we create the block before the region,
+ * so we set it delayed here if necessary */
+ if (BLI_findindex(&handle->region->uiblocks, block) == -1) {
+ UI_block_region_set(block, handle->region);
+ }
+
+ block->direction = direction;
+
+ UI_block_layout_resolve(block, &width, &height);
+
+ UI_block_flag_enable(block, UI_BLOCK_MOVEMOUSE_QUIT);
+
+ if (pup->popup) {
+ uiBut *bt;
+ int offset[2];
+
+ uiBut *but_activate = NULL;
+ UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
+ UI_block_direction_set(block, direction);
+
+ /* offset the mouse position, possibly based on earlier selection */
+ if ((block->flag & UI_BLOCK_POPUP_MEMORY) &&
+ (bt = ui_popup_menu_memory_get(block)))
+ {
+ /* position mouse on last clicked item, at 0.8*width of the
+ * button, so it doesn't overlap the text too much, also note
+ * the offset is negative because we are inverse moving the
+ * block to be under the mouse */
+ offset[0] = -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect));
+ offset[1] = -(bt->rect.ymin + 0.5f * UI_UNIT_Y);
+
+ if (ui_but_is_editable(bt)) {
+ but_activate = bt;
+ }
+ }
+ else {
+ /* position mouse at 0.8*width of the button and below the tile
+ * on the first item */
+ offset[0] = 0;
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ offset[0] = min_ii(offset[0], -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect)));
+ }
+
+ offset[1] = 2.1 * UI_UNIT_Y;
+
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if (ui_but_is_editable(bt)) {
+ but_activate = bt;
+ break;
+ }
+ }
+ }
+
+ /* in rare cases this is needed since moving the popup
+ * to be within the window bounds may move it away from the mouse,
+ * This ensures we set an item to be active. */
+ if (but_activate) {
+ ui_but_activate_over(C, handle->region, but_activate);
+ }
+
+ block->minbounds = minwidth;
+ UI_block_bounds_set_menu(block, 1, offset[0], offset[1]);
+ }
+ else {
+ /* for a header menu we set the direction automatic */
+ if (!pup->slideout && flip) {
+ ScrArea *sa = CTX_wm_area(C);
+ if (sa && sa->headertype == HEADERDOWN) {
+ ARegion *ar = CTX_wm_region(C);
+ if (ar && ar->regiontype == RGN_TYPE_HEADER) {
+ UI_block_direction_set(block, UI_DIR_UP);
+ UI_block_order_flip(block);
+ }
+ }
+ }
+
+ block->minbounds = minwidth;
+ UI_block_bounds_set_text(block, 3.0f * UI_UNIT_X);
+ }
+
+ /* if menu slides out of other menu, override direction */
+ if (pup->slideout) {
+ UI_block_direction_set(block, UI_DIR_RIGHT);
+ }
+
+ return pup->block;
+}
+
+uiPopupBlockHandle *ui_popup_menu_create(
+ bContext *C, ARegion *butregion, uiBut *but,
+ uiMenuCreateFunc menu_func, void *arg)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiStyle *style = UI_style_get_dpi();
+ uiPopupBlockHandle *handle;
+ uiPopupMenu *pup;
+
+ pup = MEM_callocN(sizeof(uiPopupMenu), __func__);
+ pup->block = UI_block_begin(C, NULL, __func__, UI_EMBOSS_PULLDOWN);
+ pup->block->flag |= UI_BLOCK_NUMSELECT; /* default menus to numselect */
+ pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
+ pup->slideout = but ? ui_block_is_menu(but->block) : false;
+ pup->but = but;
+ uiLayoutSetOperatorContext(pup->layout, WM_OP_INVOKE_REGION_WIN);
+
+ if (!but) {
+ /* no button to start from, means we are a popup */
+ pup->mx = window->eventstate->x;
+ pup->my = window->eventstate->y;
+ pup->popup = true;
+ pup->block->flag |= UI_BLOCK_NO_FLIP;
+ }
+ /* some enums reversing is strange, currently we have no good way to
+ * reverse some enum's but not others, so reverse all so the first menu
+ * items are always close to the mouse cursor */
+ else {
+#if 0
+ /* if this is an rna button then we can assume its an enum
+ * flipping enums is generally not good since the order can be
+ * important [#28786] */
+ if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
+ pup->block->flag |= UI_BLOCK_NO_FLIP;
+ }
+#endif
+ if (but->context) {
+ uiLayoutContextCopy(pup->layout, but->context);
+ }
+ }
+
+ /* menu is created from a callback */
+ pup->menu_func = menu_func;
+ pup->menu_arg = arg;
+
+ handle = ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
+
+ if (!but) {
+ handle->popup = true;
+
+ UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
+ WM_event_add_mousemove(C);
+ }
+
+ handle->can_refresh = false;
+ MEM_freeN(pup);
+
+ return handle;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Popup Menu API with begin & end
+ * \{ */
+
+/**
+ * Only return handler, and set optional title.
+ * \param block_name: Assigned to uiBlock.name (useful info for debugging).
+ */
+uiPopupMenu *UI_popup_menu_begin_ex(bContext *C, const char *title, const char *block_name, int icon)
+{
+ uiStyle *style = UI_style_get_dpi();
+ uiPopupMenu *pup = MEM_callocN(sizeof(uiPopupMenu), "popup menu");
+ uiBut *but;
+
+ pup->block = UI_block_begin(C, NULL, block_name, UI_EMBOSS_PULLDOWN);
+ pup->block->flag |= UI_BLOCK_POPUP_MEMORY | UI_BLOCK_IS_FLIP;
+ pup->block->puphash = ui_popup_menu_hash(title);
+ pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
+
+ /* note, this intentionally differs from the menu & submenu default because many operators
+ * use popups like this to select one of their options - where having invoke doesn't make sense */
+ uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
+
+ /* create in advance so we can let buttons point to retval already */
+ pup->block->handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
+
+ /* create title button */
+ if (title[0]) {
+ char titlestr[256];
+
+ if (icon) {
+ BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
+ uiDefIconTextBut(
+ pup->block, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
+ }
+ else {
+ but = uiDefBut(pup->block, UI_BTYPE_LABEL, 0, title, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
+ but->drawflag = UI_BUT_TEXT_LEFT;
+ }
+
+ uiItemS(pup->layout);
+ }
+
+ return pup;
+}
+
+uiPopupMenu *UI_popup_menu_begin(bContext *C, const char *title, int icon)
+{
+ return UI_popup_menu_begin_ex(C, title, __func__, icon);
+}
+
+/**
+ * Setting the button makes the popup open from the button instead of the cursor.
+ */
+void UI_popup_menu_but_set(uiPopupMenu *pup, struct ARegion *butregion, uiBut *but)
+{
+ pup->but = but;
+ pup->butregion = butregion;
+}
+
+/* set the whole structure to work */
+void UI_popup_menu_end(bContext *C, uiPopupMenu *pup)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiPopupBlockHandle *menu;
+ uiBut *but = NULL;
+ ARegion *butregion = NULL;
+
+ pup->popup = true;
+ pup->mx = window->eventstate->x;
+ pup->my = window->eventstate->y;
+
+ if (pup->but) {
+ but = pup->but;
+ butregion = pup->butregion;
+ }
+
+ menu = ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
+ menu->popup = true;
+
+ UI_popup_handlers_add(C, &window->modalhandlers, menu, 0);
+ WM_event_add_mousemove(C);
+
+ menu->can_refresh = false;
+ MEM_freeN(pup);
+}
+
+uiLayout *UI_popup_menu_layout(uiPopupMenu *pup)
+{
+ return pup->layout;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Standard Popup Menus
+ * \{ */
+
+void UI_popup_menu_reports(bContext *C, ReportList *reports)
+{
+ Report *report;
+
+ uiPopupMenu *pup = NULL;
+ uiLayout *layout;
+
+ if (!CTX_wm_window(C))
+ return;
+
+ for (report = reports->list.first; report; report = report->next) {
+ int icon;
+ const char *msg, *msg_next;
+
+ if (report->type < reports->printlevel) {
+ continue;
+ }
+
+ if (pup == NULL) {
+ char title[UI_MAX_DRAW_STR];
+ BLI_snprintf(title, sizeof(title), "%s: %s", IFACE_("Report"), report->typestr);
+ /* popup_menu stuff does just what we need (but pass meaningful block name) */
+ pup = UI_popup_menu_begin_ex(C, title, __func__, ICON_NONE);
+ layout = UI_popup_menu_layout(pup);
+ }
+ else {
+ uiItemS(layout);
+ }
+
+ /* split each newline into a label */
+ msg = report->message;
+ icon = UI_icon_from_report_type(report->type);
+ do {
+ char buf[UI_MAX_DRAW_STR];
+ msg_next = strchr(msg, '\n');
+ if (msg_next) {
+ msg_next++;
+ BLI_strncpy(buf, msg, MIN2(sizeof(buf), msg_next - msg));
+ msg = buf;
+ }
+ uiItemL(layout, msg, icon);
+ icon = ICON_NONE;
+ } while ((msg = msg_next) && *msg);
+ }
+
+ if (pup) {
+ UI_popup_menu_end(C, pup);
+ }
+}
+
+int UI_popup_menu_invoke(bContext *C, const char *idname, ReportList *reports)
+{
+ uiPopupMenu *pup;
+ uiLayout *layout;
+ MenuType *mt = WM_menutype_find(idname, true);
+
+ if (mt == NULL) {
+ BKE_reportf(reports, RPT_ERROR, "Menu \"%s\" not found", idname);
+ return OPERATOR_CANCELLED;
+ }
+
+ if (WM_menutype_poll(C, mt) == false) {
+ /* cancel but allow event to pass through, just like operators do */
+ return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH);
+ }
+
+ pup = UI_popup_menu_begin(C, IFACE_(mt->label), ICON_NONE);
+ layout = UI_popup_menu_layout(pup);
+
+ UI_menutype_draw(C, mt, layout);
+
+ UI_popup_menu_end(C, pup);
+
+ return OPERATOR_INTERFACE;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Popup Block API
+ * \{ */
+
+void UI_popup_block_invoke_ex(bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiPopupBlockHandle *handle;
+
+ handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
+ handle->popup = true;
+ handle->optype = (opname) ? WM_operatortype_find(opname, 0) : NULL;
+ handle->opcontext = opcontext;
+
+ UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
+ WM_event_add_mousemove(C);
+}
+
+void UI_popup_block_invoke(bContext *C, uiBlockCreateFunc func, void *arg)
+{
+ UI_popup_block_invoke_ex(C, func, arg, NULL, WM_OP_INVOKE_DEFAULT);
+}
+
+void UI_popup_block_ex(
+ bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func,
+ void *arg, wmOperator *op)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiPopupBlockHandle *handle;
+
+ handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
+ handle->popup = true;
+ handle->retvalue = 1;
+
+ handle->popup_op = op;
+ handle->popup_arg = arg;
+ handle->popup_func = popup_func;
+ handle->cancel_func = cancel_func;
+ // handle->opcontext = opcontext;
+
+ UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
+ WM_event_add_mousemove(C);
+}
+
+#if 0 /* UNUSED */
+void uiPupBlockOperator(bContext *C, uiBlockCreateFunc func, wmOperator *op, int opcontext)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiPopupBlockHandle *handle;
+
+ handle = ui_popup_block_create(C, NULL, NULL, func, NULL, op);
+ handle->popup = 1;
+ handle->retvalue = 1;
+
+ handle->popup_arg = op;
+ handle->popup_func = operator_cb;
+ handle->cancel_func = confirm_cancel_operator;
+ handle->opcontext = opcontext;
+
+ UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
+ WM_event_add_mousemove(C);
+}
+#endif
+
+void UI_popup_block_close(bContext *C, wmWindow *win, uiBlock *block)
+{
+ /* if loading new .blend while popup is open, window will be NULL */
+ if (block->handle) {
+ if (win) {
+ UI_popup_handlers_remove(&win->modalhandlers, block->handle);
+ ui_popup_block_free(C, block->handle);
+
+ /* In the case we have nested popups, closing one may need to redraw another, see: T48874 */
+ for (ARegion *ar = win->screen->regionbase.first; ar; ar = ar->next) {
+ ED_region_tag_refresh_ui(ar);
+ }
+ }
+ }
+}
+
+/** \} */
diff --git a/source/blender/editors/interface/interface_region_popup.c b/source/blender/editors/interface/interface_region_popup.c
new file mode 100644
index 00000000000..656c59055af
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_popup.c
@@ -0,0 +1,683 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_popup.c
+ * \ingroup edinterface
+ *
+ * PopUp Region (Generic)
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_math.h"
+#include "BLI_listbase.h"
+#include "BLI_rect.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+#include "wm_subwindow.h"
+
+#include "UI_interface.h"
+
+#include "ED_screen.h"
+
+#include "interface_intern.h"
+#include "interface_regions_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Utility Functions
+ * \{ */
+
+/**
+ * Translate any popup regions (so we can drag them).
+ */
+void ui_popup_translate(bContext *C, ARegion *ar, const int mdiff[2])
+{
+ uiBlock *block;
+
+ BLI_rcti_translate(&ar->winrct, UNPACK2(mdiff));
+
+ ED_region_update_rect(C, ar);
+
+ ED_region_tag_redraw(ar);
+
+ /* update blocks */
+ for (block = ar->uiblocks.first; block; block = block->next) {
+ uiSafetyRct *saferct;
+ for (saferct = block->saferct.first; saferct; saferct = saferct->next) {
+ BLI_rctf_translate(&saferct->parent, UNPACK2(mdiff));
+ BLI_rctf_translate(&saferct->safety, UNPACK2(mdiff));
+ }
+ }
+}
+
+/* position block relative to but, result is in window space */
+static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but, uiBlock *block)
+{
+ uiBut *bt;
+ uiSafetyRct *saferct;
+ rctf butrct;
+ /*float aspect;*/ /*UNUSED*/
+ int size_x, size_y, offset_x = 0, offset_y = 0;
+ short dir1 = 0, dir2 = 0;
+
+ /* transform to window coordinates, using the source button region/block */
+ ui_block_to_window_rctf(butregion, but->block, &butrct, &but->rect);
+
+ /* widget_roundbox_set has this correction too, keep in sync */
+ if (but->type != UI_BTYPE_PULLDOWN) {
+ if (but->drawflag & UI_BUT_ALIGN_TOP)
+ butrct.ymax += U.pixelsize;
+ if (but->drawflag & UI_BUT_ALIGN_LEFT)
+ butrct.xmin -= U.pixelsize;
+ }
+
+ /* calc block rect */
+ if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
+ if (block->buttons.first) {
+ BLI_rctf_init_minmax(&block->rect);
+
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ BLI_rctf_union(&block->rect, &bt->rect);
+ }
+ }
+ else {
+ /* we're nice and allow empty blocks too */
+ block->rect.xmin = block->rect.ymin = 0;
+ block->rect.xmax = block->rect.ymax = 20;
+ }
+ }
+
+ /* aspect = (float)(BLI_rcti_size_x(&block->rect) + 4);*/ /*UNUSED*/
+ ui_block_to_window_rctf(butregion, but->block, &block->rect, &block->rect);
+
+ //block->rect.xmin -= 2.0; block->rect.ymin -= 2.0;
+ //block->rect.xmax += 2.0; block->rect.ymax += 2.0;
+
+ size_x = BLI_rctf_size_x(&block->rect) + 0.2f * UI_UNIT_X; /* 4 for shadow */
+ size_y = BLI_rctf_size_y(&block->rect) + 0.2f * UI_UNIT_Y;
+ /* aspect /= (float)size_x;*/ /*UNUSED*/
+
+ {
+ bool left = 0, right = 0, top = 0, down = 0;
+ // int offscreen;
+
+ const int win_x = WM_window_pixels_x(window);
+ const int win_y = WM_window_pixels_y(window);
+ // wm_window_get_size(window, &win_x, &win_y);
+
+ const int center_y = (block->direction & UI_DIR_CENTER_Y) ? size_y / 2 : 0;
+
+ /* check if there's space at all */
+ if (butrct.xmin - size_x > 0.0f) left = 1;
+ if (butrct.xmax + size_x < win_x) right = 1;
+ if (butrct.ymin - size_y + center_y > 0.0f) down = 1;
+ if (butrct.ymax + size_y - center_y < win_y) top = 1;
+
+ if (top == 0 && down == 0) {
+ if (butrct.ymin - size_y < win_y - butrct.ymax - size_y)
+ top = 1;
+ else
+ down = 1;
+ }
+
+ dir1 = (block->direction & UI_DIR_ALL);
+
+ /* Secondary directions. */
+ if (dir1 & (UI_DIR_UP | UI_DIR_DOWN)) {
+ if (dir1 & UI_DIR_LEFT) dir2 = UI_DIR_LEFT;
+ else if (dir1 & UI_DIR_RIGHT) dir2 = UI_DIR_RIGHT;
+ dir1 &= (UI_DIR_UP | UI_DIR_DOWN);
+ }
+
+ if ((dir2 == 0) && (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT)) dir2 = UI_DIR_DOWN;
+ if ((dir2 == 0) && (dir1 == UI_DIR_UP || dir1 == UI_DIR_DOWN)) dir2 = UI_DIR_LEFT;
+
+ /* no space at all? don't change */
+ if (left || right) {
+ if (dir1 == UI_DIR_LEFT && left == 0) dir1 = UI_DIR_RIGHT;
+ if (dir1 == UI_DIR_RIGHT && right == 0) dir1 = UI_DIR_LEFT;
+ /* this is aligning, not append! */
+ if (dir2 == UI_DIR_LEFT && right == 0) dir2 = UI_DIR_RIGHT;
+ if (dir2 == UI_DIR_RIGHT && left == 0) dir2 = UI_DIR_LEFT;
+ }
+ if (down || top) {
+ if (dir1 == UI_DIR_UP && top == 0) dir1 = UI_DIR_DOWN;
+ if (dir1 == UI_DIR_DOWN && down == 0) dir1 = UI_DIR_UP;
+ BLI_assert(dir2 != UI_DIR_UP);
+// if (dir2 == UI_DIR_UP && top == 0) dir2 = UI_DIR_DOWN;
+ if (dir2 == UI_DIR_DOWN && down == 0) dir2 = UI_DIR_UP;
+ }
+
+ if (dir1 == UI_DIR_LEFT) {
+ offset_x = butrct.xmin - block->rect.xmax;
+ if (dir2 == UI_DIR_UP) offset_y = butrct.ymin - block->rect.ymin - center_y - MENU_PADDING;
+ else offset_y = butrct.ymax - block->rect.ymax + center_y + MENU_PADDING;
+ }
+ else if (dir1 == UI_DIR_RIGHT) {
+ offset_x = butrct.xmax - block->rect.xmin;
+ if (dir2 == UI_DIR_UP) offset_y = butrct.ymin - block->rect.ymin - center_y - MENU_PADDING;
+ else offset_y = butrct.ymax - block->rect.ymax + center_y + MENU_PADDING;
+ }
+ else if (dir1 == UI_DIR_UP) {
+ offset_y = butrct.ymax - block->rect.ymin;
+ if (dir2 == UI_DIR_RIGHT) offset_x = butrct.xmax - block->rect.xmax;
+ else offset_x = butrct.xmin - block->rect.xmin;
+ /* changed direction? */
+ if ((dir1 & block->direction) == 0) {
+ UI_block_order_flip(block);
+ }
+ }
+ else if (dir1 == UI_DIR_DOWN) {
+ offset_y = butrct.ymin - block->rect.ymax;
+ if (dir2 == UI_DIR_RIGHT) offset_x = butrct.xmax - block->rect.xmax;
+ else offset_x = butrct.xmin - block->rect.xmin;
+ /* changed direction? */
+ if ((dir1 & block->direction) == 0) {
+ UI_block_order_flip(block);
+ }
+ }
+
+ /* and now we handle the exception; no space below or to top */
+ if (top == 0 && down == 0) {
+ if (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT) {
+ /* align with bottom of screen */
+ // offset_y = size_y; (not with menu scrolls)
+ }
+ }
+
+#if 0 /* seems redundant and causes issues with blocks inside big regions */
+ /* or no space left or right */
+ if (left == 0 && right == 0) {
+ if (dir1 == UI_DIR_UP || dir1 == UI_DIR_DOWN) {
+ /* align with left size of screen */
+ offset_x = -block->rect.xmin + 5;
+ }
+ }
+#endif
+
+#if 0
+ /* clamp to window bounds, could be made into an option if its ever annoying */
+ if ( (offscreen = (block->rect.ymin + offset_y)) < 0) offset_y -= offscreen; /* bottom */
+ else if ((offscreen = (block->rect.ymax + offset_y) - winy) > 0) offset_y -= offscreen; /* top */
+ if ( (offscreen = (block->rect.xmin + offset_x)) < 0) offset_x -= offscreen; /* left */
+ else if ((offscreen = (block->rect.xmax + offset_x) - winx) > 0) offset_x -= offscreen; /* right */
+#endif
+ }
+
+ /* apply offset, buttons in window coords */
+
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ ui_block_to_window_rctf(butregion, but->block, &bt->rect, &bt->rect);
+
+ BLI_rctf_translate(&bt->rect, offset_x, offset_y);
+
+ /* ui_but_update recalculates drawstring size in pixels */
+ ui_but_update(bt);
+ }
+
+ BLI_rctf_translate(&block->rect, offset_x, offset_y);
+
+ /* safety calculus */
+ {
+ const float midx = BLI_rctf_cent_x(&butrct);
+ const float midy = BLI_rctf_cent_y(&butrct);
+
+ /* when you are outside parent button, safety there should be smaller */
+
+ /* parent button to left */
+ if (midx < block->rect.xmin) block->safety.xmin = block->rect.xmin - 3;
+ else block->safety.xmin = block->rect.xmin - 40;
+ /* parent button to right */
+ if (midx > block->rect.xmax) block->safety.xmax = block->rect.xmax + 3;
+ else block->safety.xmax = block->rect.xmax + 40;
+
+ /* parent button on bottom */
+ if (midy < block->rect.ymin) block->safety.ymin = block->rect.ymin - 3;
+ else block->safety.ymin = block->rect.ymin - 40;
+ /* parent button on top */
+ if (midy > block->rect.ymax) block->safety.ymax = block->rect.ymax + 3;
+ else block->safety.ymax = block->rect.ymax + 40;
+
+ /* exception for switched pulldowns... */
+ if (dir1 && (dir1 & block->direction) == 0) {
+ if (dir2 == UI_DIR_RIGHT) block->safety.xmax = block->rect.xmax + 3;
+ if (dir2 == UI_DIR_LEFT) block->safety.xmin = block->rect.xmin - 3;
+ }
+ block->direction = dir1;
+ }
+
+ /* keep a list of these, needed for pulldown menus */
+ saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
+ saferct->parent = butrct;
+ saferct->safety = block->safety;
+ BLI_freelistN(&block->saferct);
+ BLI_duplicatelist(&block->saferct, &but->block->saferct);
+ BLI_addhead(&block->saferct, saferct);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Menu Block Creation
+ * \{ */
+
+static void ui_block_region_draw(const bContext *C, ARegion *ar)
+{
+ ScrArea *ctx_area = CTX_wm_area(C);
+ ARegion *ctx_region = CTX_wm_region(C);
+ uiBlock *block;
+
+ if (ar->do_draw & RGN_DRAW_REFRESH_UI) {
+ ScrArea *handle_ctx_area;
+ ARegion *handle_ctx_region;
+ uiBlock *block_next;
+
+ ar->do_draw &= ~RGN_DRAW_REFRESH_UI;
+ for (block = ar->uiblocks.first; block; block = block_next) {
+ block_next = block->next;
+ if (block->handle->can_refresh) {
+ handle_ctx_area = block->handle->ctx_area;
+ handle_ctx_region = block->handle->ctx_region;
+
+ if (handle_ctx_area) {
+ CTX_wm_area_set((bContext *)C, handle_ctx_area);
+ }
+ if (handle_ctx_region) {
+ CTX_wm_region_set((bContext *)C, handle_ctx_region);
+ }
+ ui_popup_block_refresh((bContext *)C, block->handle, NULL, NULL);
+ }
+ }
+ }
+
+ CTX_wm_area_set((bContext *)C, ctx_area);
+ CTX_wm_region_set((bContext *)C, ctx_region);
+
+ for (block = ar->uiblocks.first; block; block = block->next)
+ UI_block_draw(C, block);
+}
+
+/**
+ * Use to refresh centered popups on screen resizing (for splash).
+ */
+static void ui_block_region_popup_window_listener(
+ bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegion *ar, wmNotifier *wmn)
+{
+ switch (wmn->category) {
+ case NC_WINDOW:
+ {
+ switch (wmn->action) {
+ case NA_EDITED:
+ {
+ /* window resize */
+ ED_region_tag_refresh_ui(ar);
+ break;
+ }
+ }
+ break;
+ }
+ }
+}
+
+static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
+{
+ uiBut *bt;
+ float xofs = 0.0f;
+ int width = UI_SCREEN_MARGIN;
+ int winx, winy;
+
+ if (block->flag & UI_BLOCK_NO_WIN_CLIP) {
+ return;
+ }
+
+ winx = WM_window_pixels_x(window);
+ winy = WM_window_pixels_y(window);
+
+ /* shift menus to right if outside of view */
+ if (block->rect.xmin < width) {
+ xofs = (width - block->rect.xmin);
+ block->rect.xmin += xofs;
+ block->rect.xmax += xofs;
+ }
+ /* or shift to left if outside of view */
+ if (block->rect.xmax > winx - width) {
+ xofs = winx - width - block->rect.xmax;
+ block->rect.xmin += xofs;
+ block->rect.xmax += xofs;
+ }
+
+ if (block->rect.ymin < width)
+ block->rect.ymin = width;
+ if (block->rect.ymax > winy - UI_POPUP_MENU_TOP)
+ block->rect.ymax = winy - UI_POPUP_MENU_TOP;
+
+ /* ensure menu items draw inside left/right boundary */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ bt->rect.xmin += xofs;
+ bt->rect.xmax += xofs;
+ }
+
+}
+
+void ui_popup_block_scrolltest(uiBlock *block)
+{
+ uiBut *bt;
+
+ block->flag &= ~(UI_BLOCK_CLIPBOTTOM | UI_BLOCK_CLIPTOP);
+
+ for (bt = block->buttons.first; bt; bt = bt->next)
+ bt->flag &= ~UI_SCROLLED;
+
+ if (block->buttons.first == block->buttons.last)
+ return;
+
+ /* mark buttons that are outside boundary */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if (bt->rect.ymin < block->rect.ymin) {
+ bt->flag |= UI_SCROLLED;
+ block->flag |= UI_BLOCK_CLIPBOTTOM;
+ }
+ if (bt->rect.ymax > block->rect.ymax) {
+ bt->flag |= UI_SCROLLED;
+ block->flag |= UI_BLOCK_CLIPTOP;
+ }
+ }
+
+ /* mark buttons overlapping arrows, if we have them */
+ for (bt = block->buttons.first; bt; bt = bt->next) {
+ if (block->flag & UI_BLOCK_CLIPBOTTOM) {
+ if (bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
+ bt->flag |= UI_SCROLLED;
+ }
+ if (block->flag & UI_BLOCK_CLIPTOP) {
+ if (bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
+ bt->flag |= UI_SCROLLED;
+ }
+ }
+}
+
+static void ui_popup_block_remove(bContext *C, uiPopupBlockHandle *handle)
+{
+ wmWindow *win = CTX_wm_window(C);
+ bScreen *sc = CTX_wm_screen(C);
+
+ ui_region_temp_remove(C, sc, handle->region);
+
+ /* reset to region cursor (only if there's not another menu open) */
+ if (BLI_listbase_is_empty(&sc->regionbase)) {
+ ED_region_cursor_set(win, CTX_wm_area(C), CTX_wm_region(C));
+ /* in case cursor needs to be changed again */
+ WM_event_add_mousemove(C);
+ }
+
+ if (handle->scrolltimer)
+ WM_event_remove_timer(CTX_wm_manager(C), win, handle->scrolltimer);
+}
+
+/**
+ * Called for creating new popups and refreshing existing ones.
+ */
+uiBlock *ui_popup_block_refresh(
+ bContext *C, uiPopupBlockHandle *handle,
+ ARegion *butregion, uiBut *but)
+{
+ BLI_assert(handle->can_refresh == true);
+
+ const int margin = UI_POPUP_MARGIN;
+ wmWindow *window = CTX_wm_window(C);
+ ARegion *ar = handle->region;
+
+ uiBlockCreateFunc create_func = handle->popup_create_vars.create_func;
+ uiBlockHandleCreateFunc handle_create_func = handle->popup_create_vars.handle_create_func;
+ void *arg = handle->popup_create_vars.arg;
+
+ uiBlock *block_old = ar->uiblocks.first;
+ uiBlock *block;
+
+#ifdef DEBUG
+ wmEvent *event_back = window->eventstate;
+#endif
+
+ /* create ui block */
+ if (create_func)
+ block = create_func(C, ar, arg);
+ else
+ block = handle_create_func(C, handle, arg);
+
+ /* callbacks _must_ leave this for us, otherwise we can't call UI_block_update_from_old */
+ BLI_assert(!block->endblock);
+
+ /* ensure we don't use mouse coords here! */
+#ifdef DEBUG
+ window->eventstate = NULL;
+#endif
+
+ if (block->handle) {
+ memcpy(block->handle, handle, sizeof(uiPopupBlockHandle));
+ MEM_freeN(handle);
+ handle = block->handle;
+ }
+ else
+ block->handle = handle;
+
+ ar->regiondata = handle;
+
+ /* set UI_BLOCK_NUMSELECT before UI_block_end() so we get alphanumeric keys assigned */
+ if (but == NULL) {
+ block->flag |= UI_BLOCK_POPUP;
+ }
+
+ block->flag |= UI_BLOCK_LOOP;
+
+ /* defer this until blocks are translated (below) */
+ block->oldblock = NULL;
+
+ if (!block->endblock) {
+ UI_block_end_ex(C, block, handle->popup_create_vars.event_xy, handle->popup_create_vars.event_xy);
+ }
+
+ /* if this is being created from a button */
+ if (but) {
+ block->aspect = but->block->aspect;
+ ui_block_position(window, butregion, but, block);
+ handle->direction = block->direction;
+ }
+ else {
+ uiSafetyRct *saferct;
+ /* keep a list of these, needed for pulldown menus */
+ saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
+ saferct->safety = block->safety;
+ BLI_addhead(&block->saferct, saferct);
+ }
+
+ if (block->flag & UI_BLOCK_RADIAL) {
+ int win_width = UI_SCREEN_MARGIN;
+ int winx, winy;
+
+ int x_offset = 0, y_offset = 0;
+
+ winx = WM_window_pixels_x(window);
+ winy = WM_window_pixels_y(window);
+
+ copy_v2_v2(block->pie_data.pie_center_init, block->pie_data.pie_center_spawned);
+
+ /* only try translation if area is large enough */
+ if (BLI_rctf_size_x(&block->rect) < winx - (2.0f * win_width)) {
+ if (block->rect.xmin < win_width ) x_offset += win_width - block->rect.xmin;
+ if (block->rect.xmax > winx - win_width) x_offset += winx - win_width - block->rect.xmax;
+ }
+
+ if (BLI_rctf_size_y(&block->rect) < winy - (2.0f * win_width)) {
+ if (block->rect.ymin < win_width ) y_offset += win_width - block->rect.ymin;
+ if (block->rect.ymax > winy - win_width) y_offset += winy - win_width - block->rect.ymax;
+ }
+ /* if we are offsetting set up initial data for timeout functionality */
+
+ if ((x_offset != 0) || (y_offset != 0)) {
+ block->pie_data.pie_center_spawned[0] += x_offset;
+ block->pie_data.pie_center_spawned[1] += y_offset;
+
+ ui_block_translate(block, x_offset, y_offset);
+
+ if (U.pie_initial_timeout > 0)
+ block->pie_data.flags |= UI_PIE_INITIAL_DIRECTION;
+ }
+
+ ar->winrct.xmin = 0;
+ ar->winrct.xmax = winx;
+ ar->winrct.ymin = 0;
+ ar->winrct.ymax = winy;
+
+ ui_block_calc_pie_segment(block, block->pie_data.pie_center_init);
+
+ /* lastly set the buttons at the center of the pie menu, ready for animation */
+ if (U.pie_animation_timeout > 0) {
+ for (uiBut *but_iter = block->buttons.first; but_iter; but_iter = but_iter->next) {
+ if (but_iter->pie_dir != UI_RADIAL_NONE) {
+ BLI_rctf_recenter(&but_iter->rect, UNPACK2(block->pie_data.pie_center_spawned));
+ }
+ }
+ }
+ }
+ else {
+ /* clip block with window boundary */
+ ui_popup_block_clip(window, block);
+ /* the block and buttons were positioned in window space as in 2.4x, now
+ * these menu blocks are regions so we bring it back to region space.
+ * additionally we add some padding for the menu shadow or rounded menus */
+ ar->winrct.xmin = block->rect.xmin - margin;
+ ar->winrct.xmax = block->rect.xmax + margin;
+ ar->winrct.ymin = block->rect.ymin - margin;
+ ar->winrct.ymax = block->rect.ymax + UI_POPUP_MENU_TOP;
+
+ ui_block_translate(block, -ar->winrct.xmin, -ar->winrct.ymin);
+ }
+
+ if (block_old) {
+ block->oldblock = block_old;
+ UI_block_update_from_old(C, block);
+ UI_blocklist_free_inactive(C, &ar->uiblocks);
+ }
+
+ /* checks which buttons are visible, sets flags to prevent draw (do after region init) */
+ ui_popup_block_scrolltest(block);
+
+ /* adds subwindow */
+ ED_region_init(C, ar);
+
+ /* get winmat now that we actually have the subwindow */
+ wmSubWindowSet(window, ar->swinid);
+
+ wm_subwindow_matrix_get(window, ar->swinid, block->winmat);
+
+ /* notify change and redraw */
+ ED_region_tag_redraw(ar);
+
+ ED_region_update_rect(C, ar);
+
+#ifdef DEBUG
+ window->eventstate = event_back;
+#endif
+
+ return block;
+}
+
+uiPopupBlockHandle *ui_popup_block_create(
+ bContext *C, ARegion *butregion, uiBut *but,
+ uiBlockCreateFunc create_func, uiBlockHandleCreateFunc handle_create_func,
+ void *arg)
+{
+ wmWindow *window = CTX_wm_window(C);
+ uiBut *activebut = UI_context_active_but_get(C);
+ static ARegionType type;
+ ARegion *ar;
+ uiBlock *block;
+ uiPopupBlockHandle *handle;
+
+ /* disable tooltips from buttons below */
+ if (activebut) {
+ UI_but_tooltip_timer_remove(C, activebut);
+ }
+ /* standard cursor by default */
+ WM_cursor_set(window, CURSOR_STD);
+
+ /* create handle */
+ handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
+
+ /* store context for operator */
+ handle->ctx_area = CTX_wm_area(C);
+ handle->ctx_region = CTX_wm_region(C);
+
+ /* store vars to refresh popup (RGN_DRAW_REFRESH_UI) */
+ handle->popup_create_vars.create_func = create_func;
+ handle->popup_create_vars.handle_create_func = handle_create_func;
+ handle->popup_create_vars.arg = arg;
+ handle->popup_create_vars.butregion = but ? butregion : NULL;
+ copy_v2_v2_int(handle->popup_create_vars.event_xy, &window->eventstate->x);
+ /* caller may free vars used to create this popup, in that case this variable should be disabled. */
+ handle->can_refresh = true;
+
+ /* create area region */
+ ar = ui_region_temp_add(CTX_wm_screen(C));
+ handle->region = ar;
+
+ memset(&type, 0, sizeof(ARegionType));
+ type.draw = ui_block_region_draw;
+ type.regionid = RGN_TYPE_TEMPORARY;
+ ar->type = &type;
+
+ UI_region_handlers_add(&ar->handlers);
+
+ block = ui_popup_block_refresh(C, handle, butregion, but);
+ handle = block->handle;
+
+ /* keep centered on window resizing */
+ if ((block->bounds_type == UI_BLOCK_BOUNDS_POPUP_CENTER) && handle->can_refresh) {
+ type.listener = ui_block_region_popup_window_listener;
+ }
+
+ return handle;
+}
+
+void ui_popup_block_free(bContext *C, uiPopupBlockHandle *handle)
+{
+ ui_popup_block_remove(C, handle);
+
+ MEM_freeN(handle);
+}
+
+/** \} */
diff --git a/source/blender/editors/interface/interface_region_search.c b/source/blender/editors/interface/interface_region_search.c
new file mode 100644
index 00000000000..c9d313a4bab
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_search.c
@@ -0,0 +1,800 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_search.c
+ * \ingroup edinterface
+ *
+ * Search Box Region & Interaction
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_math.h"
+
+#include "BLI_string.h"
+#include "BLI_rect.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "RNA_access.h"
+
+#include "BIF_gl.h"
+
+#include "UI_interface.h"
+#include "UI_interface_icons.h"
+#include "UI_view2d.h"
+
+#include "BLT_translation.h"
+
+#include "ED_screen.h"
+
+#include "interface_intern.h"
+#include "interface_regions_intern.h"
+
+#define MENU_BORDER (int)(0.3f * U.widget_unit)
+
+/* -------------------------------------------------------------------- */
+/** \name Search Box Creation
+ * \{ */
+
+struct uiSearchItems {
+ int maxitem, totitem, maxstrlen;
+
+ int offset, offset_i; /* offset for inserting in array */
+ int more; /* flag indicating there are more items */
+
+ char **names;
+ void **pointers;
+ int *icons;
+
+ AutoComplete *autocpl;
+ void *active;
+};
+
+typedef struct uiSearchboxData {
+ rcti bbox;
+ uiFontStyle fstyle;
+ uiSearchItems items;
+ int active; /* index in items array */
+ bool noback; /* when menu opened with enough space for this */
+ bool preview; /* draw thumbnail previews, rather than list */
+ bool use_sep; /* use the UI_SEP_CHAR char for splitting shortcuts (good for operators, bad for data) */
+ int prv_rows, prv_cols;
+} uiSearchboxData;
+
+#define SEARCH_ITEMS 10
+
+/* exported for use by search callbacks */
+/* returns zero if nothing to add */
+bool UI_search_item_add(uiSearchItems *items, const char *name, void *poin, int iconid)
+{
+ /* hijack for autocomplete */
+ if (items->autocpl) {
+ UI_autocomplete_update_name(items->autocpl, name);
+ return true;
+ }
+
+ /* hijack for finding active item */
+ if (items->active) {
+ if (poin == items->active)
+ items->offset_i = items->totitem;
+ items->totitem++;
+ return true;
+ }
+
+ if (items->totitem >= items->maxitem) {
+ items->more = 1;
+ return false;
+ }
+
+ /* skip first items in list */
+ if (items->offset_i > 0) {
+ items->offset_i--;
+ return true;
+ }
+
+ if (items->names)
+ BLI_strncpy(items->names[items->totitem], name, items->maxstrlen);
+ if (items->pointers)
+ items->pointers[items->totitem] = poin;
+ if (items->icons)
+ items->icons[items->totitem] = iconid;
+
+ items->totitem++;
+
+ return true;
+}
+
+int UI_searchbox_size_y(void)
+{
+ return SEARCH_ITEMS * UI_UNIT_Y + 2 * UI_POPUP_MENU_TOP;
+}
+
+int UI_searchbox_size_x(void)
+{
+ return 12 * UI_UNIT_X;
+}
+
+int UI_search_items_find_index(uiSearchItems *items, const char *name)
+{
+ int i;
+ for (i = 0; i < items->totitem; i++) {
+ if (STREQ(name, items->names[i])) {
+ return i;
+ }
+ }
+ return -1;
+}
+
+/* ar is the search box itself */
+static void ui_searchbox_select(bContext *C, ARegion *ar, uiBut *but, int step)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ /* apply step */
+ data->active += step;
+
+ if (data->items.totitem == 0) {
+ data->active = -1;
+ }
+ else if (data->active >= data->items.totitem) {
+ if (data->items.more) {
+ data->items.offset++;
+ data->active = data->items.totitem - 1;
+ ui_searchbox_update(C, ar, but, false);
+ }
+ else {
+ data->active = data->items.totitem - 1;
+ }
+ }
+ else if (data->active < 0) {
+ if (data->items.offset) {
+ data->items.offset--;
+ data->active = 0;
+ ui_searchbox_update(C, ar, but, false);
+ }
+ else {
+ /* only let users step into an 'unset' state for unlink buttons */
+ data->active = (but->flag & UI_BUT_VALUE_CLEAR) ? -1 : 0;
+ }
+ }
+
+ ED_region_tag_redraw(ar);
+}
+
+static void ui_searchbox_butrect(rcti *r_rect, uiSearchboxData *data, int itemnr)
+{
+ /* thumbnail preview */
+ if (data->preview) {
+ int butw = (BLI_rcti_size_x(&data->bbox) - 2 * MENU_BORDER) / data->prv_cols;
+ int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_BORDER) / data->prv_rows;
+ int row, col;
+
+ *r_rect = data->bbox;
+
+ col = itemnr % data->prv_cols;
+ row = itemnr / data->prv_cols;
+
+ r_rect->xmin += MENU_BORDER + (col * butw);
+ r_rect->xmax = r_rect->xmin + butw;
+
+ r_rect->ymax -= MENU_BORDER + (row * buth);
+ r_rect->ymin = r_rect->ymax - buth;
+ }
+ /* list view */
+ else {
+ int buth = (BLI_rcti_size_y(&data->bbox) - 2 * UI_POPUP_MENU_TOP) / SEARCH_ITEMS;
+
+ *r_rect = data->bbox;
+ r_rect->xmin = data->bbox.xmin + 3.0f;
+ r_rect->xmax = data->bbox.xmax - 3.0f;
+
+ r_rect->ymax = data->bbox.ymax - UI_POPUP_MENU_TOP - itemnr * buth;
+ r_rect->ymin = r_rect->ymax - buth;
+ }
+
+}
+
+int ui_searchbox_find_index(ARegion *ar, const char *name)
+{
+ uiSearchboxData *data = ar->regiondata;
+ return UI_search_items_find_index(&data->items, name);
+}
+
+/* x and y in screencoords */
+bool ui_searchbox_inside(ARegion *ar, int x, int y)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ return BLI_rcti_isect_pt(&data->bbox, x - ar->winrct.xmin, y - ar->winrct.ymin);
+}
+
+/* string validated to be of correct length (but->hardmax) */
+bool ui_searchbox_apply(uiBut *but, ARegion *ar)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ but->func_arg2 = NULL;
+
+ if (data->active != -1) {
+ const char *name = data->items.names[data->active];
+ const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
+
+ BLI_strncpy(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen);
+
+ but->func_arg2 = data->items.pointers[data->active];
+
+ return true;
+ }
+ else if (but->flag & UI_BUT_VALUE_CLEAR) {
+ /* It is valid for _VALUE_CLEAR flavor to have no active element (it's a valid way to unlink). */
+ but->editstr[0] = '\0';
+
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+void ui_searchbox_event(bContext *C, ARegion *ar, uiBut *but, const wmEvent *event)
+{
+ uiSearchboxData *data = ar->regiondata;
+ int type = event->type, val = event->val;
+
+ if (type == MOUSEPAN)
+ ui_pan_to_scroll(event, &type, &val);
+
+ switch (type) {
+ case WHEELUPMOUSE:
+ case UPARROWKEY:
+ ui_searchbox_select(C, ar, but, -1);
+ break;
+ case WHEELDOWNMOUSE:
+ case DOWNARROWKEY:
+ ui_searchbox_select(C, ar, but, 1);
+ break;
+ case MOUSEMOVE:
+ if (BLI_rcti_isect_pt(&ar->winrct, event->x, event->y)) {
+ rcti rect;
+ int a;
+
+ for (a = 0; a < data->items.totitem; a++) {
+ ui_searchbox_butrect(&rect, data, a);
+ if (BLI_rcti_isect_pt(&rect, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin)) {
+ if (data->active != a) {
+ data->active = a;
+ ui_searchbox_select(C, ar, but, 0);
+ break;
+ }
+ }
+ }
+ }
+ break;
+ }
+}
+
+/* ar is the search box itself */
+void ui_searchbox_update(bContext *C, ARegion *ar, uiBut *but, const bool reset)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ /* reset vars */
+ data->items.totitem = 0;
+ data->items.more = 0;
+ if (reset == false) {
+ data->items.offset_i = data->items.offset;
+ }
+ else {
+ data->items.offset_i = data->items.offset = 0;
+ data->active = -1;
+
+ /* handle active */
+ if (but->search_func && but->func_arg2) {
+ data->items.active = but->func_arg2;
+ but->search_func(C, but->search_arg, but->editstr, &data->items);
+ data->items.active = NULL;
+
+ /* found active item, calculate real offset by centering it */
+ if (data->items.totitem) {
+ /* first case, begin of list */
+ if (data->items.offset_i < data->items.maxitem) {
+ data->active = data->items.offset_i;
+ data->items.offset_i = 0;
+ }
+ else {
+ /* second case, end of list */
+ if (data->items.totitem - data->items.offset_i <= data->items.maxitem) {
+ data->active = data->items.offset_i - data->items.totitem + data->items.maxitem;
+ data->items.offset_i = data->items.totitem - data->items.maxitem;
+ }
+ else {
+ /* center active item */
+ data->items.offset_i -= data->items.maxitem / 2;
+ data->active = data->items.maxitem / 2;
+ }
+ }
+ }
+ data->items.offset = data->items.offset_i;
+ data->items.totitem = 0;
+ }
+ }
+
+ /* callback */
+ if (but->search_func)
+ but->search_func(C, but->search_arg, but->editstr, &data->items);
+
+ /* handle case where editstr is equal to one of items */
+ if (reset && data->active == -1) {
+ int a;
+
+ for (a = 0; a < data->items.totitem; a++) {
+ const char *name = data->items.names[a];
+ const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
+ if (STREQLEN(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen)) {
+ data->active = a;
+ break;
+ }
+ }
+ if (data->items.totitem == 1 && but->editstr[0])
+ data->active = 0;
+ }
+
+ /* validate selected item */
+ ui_searchbox_select(C, ar, but, 0);
+
+ ED_region_tag_redraw(ar);
+}
+
+int ui_searchbox_autocomplete(bContext *C, ARegion *ar, uiBut *but, char *str)
+{
+ uiSearchboxData *data = ar->regiondata;
+ int match = AUTOCOMPLETE_NO_MATCH;
+
+ if (str[0]) {
+ data->items.autocpl = UI_autocomplete_begin(str, ui_but_string_get_max_length(but));
+
+ but->search_func(C, but->search_arg, but->editstr, &data->items);
+
+ match = UI_autocomplete_end(data->items.autocpl, str);
+ data->items.autocpl = NULL;
+ }
+
+ return match;
+}
+
+static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ /* pixel space */
+ wmOrtho2_region_pixelspace(ar);
+
+ if (data->noback == false)
+ ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */
+
+ /* draw text */
+ if (data->items.totitem) {
+ rcti rect;
+ int a;
+
+ if (data->preview) {
+ /* draw items */
+ for (a = 0; a < data->items.totitem; a++) {
+ ui_searchbox_butrect(&rect, data, a);
+
+ /* widget itself */
+ ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
+ (a == data->active) ? UI_ACTIVE : 0);
+ }
+
+ /* indicate more */
+ if (data->items.more) {
+ ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
+ glEnable(GL_BLEND);
+ UI_icon_draw(rect.xmax - 18, rect.ymin - 7, ICON_TRIA_DOWN);
+ glDisable(GL_BLEND);
+ }
+ if (data->items.offset) {
+ ui_searchbox_butrect(&rect, data, 0);
+ glEnable(GL_BLEND);
+ UI_icon_draw(rect.xmin, rect.ymax - 9, ICON_TRIA_UP);
+ glDisable(GL_BLEND);
+ }
+
+ }
+ else {
+ /* draw items */
+ for (a = 0; a < data->items.totitem; a++) {
+ ui_searchbox_butrect(&rect, data, a);
+
+ /* widget itself */
+ ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
+ (a == data->active) ? UI_ACTIVE : 0, data->use_sep);
+
+ }
+ /* indicate more */
+ if (data->items.more) {
+ ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
+ glEnable(GL_BLEND);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
+ glDisable(GL_BLEND);
+ }
+ if (data->items.offset) {
+ ui_searchbox_butrect(&rect, data, 0);
+ glEnable(GL_BLEND);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
+ glDisable(GL_BLEND);
+ }
+ }
+ }
+}
+
+static void ui_searchbox_region_free_cb(ARegion *ar)
+{
+ uiSearchboxData *data = ar->regiondata;
+ int a;
+
+ /* free search data */
+ for (a = 0; a < data->items.maxitem; a++) {
+ MEM_freeN(data->items.names[a]);
+ }
+ MEM_freeN(data->items.names);
+ MEM_freeN(data->items.pointers);
+ MEM_freeN(data->items.icons);
+
+ MEM_freeN(data);
+ ar->regiondata = NULL;
+}
+
+ARegion *ui_searchbox_create_generic(bContext *C, ARegion *butregion, uiBut *but)
+{
+ wmWindow *win = CTX_wm_window(C);
+ uiStyle *style = UI_style_get();
+ static ARegionType type;
+ ARegion *ar;
+ uiSearchboxData *data;
+ float aspect = but->block->aspect;
+ rctf rect_fl;
+ rcti rect_i;
+ const int margin = UI_POPUP_MARGIN;
+ int winx /*, winy */, ofsx, ofsy;
+ int i;
+
+ /* create area region */
+ ar = ui_region_temp_add(CTX_wm_screen(C));
+
+ memset(&type, 0, sizeof(ARegionType));
+ type.draw = ui_searchbox_region_draw_cb;
+ type.free = ui_searchbox_region_free_cb;
+ type.regionid = RGN_TYPE_TEMPORARY;
+ ar->type = &type;
+
+ /* create searchbox data */
+ data = MEM_callocN(sizeof(uiSearchboxData), "uiSearchboxData");
+
+ /* set font, get bb */
+ data->fstyle = style->widget; /* copy struct */
+ data->fstyle.align = UI_STYLE_TEXT_CENTER;
+ ui_fontscale(&data->fstyle.points, aspect);
+ UI_fontstyle_set(&data->fstyle);
+
+ ar->regiondata = data;
+
+ /* special case, hardcoded feature, not draw backdrop when called from menus,
+ * assume for design that popup already added it */
+ if (but->block->flag & UI_BLOCK_SEARCH_MENU)
+ data->noback = true;
+
+ if (but->a1 > 0 && but->a2 > 0) {
+ data->preview = true;
+ data->prv_rows = but->a1;
+ data->prv_cols = but->a2;
+ }
+
+ /* only show key shortcuts when needed (not rna buttons) [#36699] */
+ if (but->rnaprop == NULL) {
+ data->use_sep = true;
+ }
+
+ /* compute position */
+ if (but->block->flag & UI_BLOCK_SEARCH_MENU) {
+ const int search_but_h = BLI_rctf_size_y(&but->rect) + 10;
+ /* this case is search menu inside other menu */
+ /* we copy region size */
+
+ ar->winrct = butregion->winrct;
+
+ /* widget rect, in region coords */
+ data->bbox.xmin = margin;
+ data->bbox.xmax = BLI_rcti_size_x(&ar->winrct) - margin;
+ data->bbox.ymin = margin;
+ data->bbox.ymax = BLI_rcti_size_y(&ar->winrct) - margin;
+
+ /* check if button is lower half */
+ if (but->rect.ymax < BLI_rctf_cent_y(&but->block->rect)) {
+ data->bbox.ymin += search_but_h;
+ }
+ else {
+ data->bbox.ymax -= search_but_h;
+ }
+ }
+ else {
+ const int searchbox_width = UI_searchbox_size_x();
+
+ rect_fl.xmin = but->rect.xmin - 5; /* align text with button */
+ rect_fl.xmax = but->rect.xmax + 5; /* symmetrical */
+ rect_fl.ymax = but->rect.ymin;
+ rect_fl.ymin = rect_fl.ymax - UI_searchbox_size_y();
+
+ ofsx = (but->block->panel) ? but->block->panel->ofsx : 0;
+ ofsy = (but->block->panel) ? but->block->panel->ofsy : 0;
+
+ BLI_rctf_translate(&rect_fl, ofsx, ofsy);
+
+ /* minimal width */
+ if (BLI_rctf_size_x(&rect_fl) < searchbox_width) {
+ rect_fl.xmax = rect_fl.xmin + searchbox_width;
+ }
+
+ /* copy to int, gets projected if possible too */
+ BLI_rcti_rctf_copy(&rect_i, &rect_fl);
+
+ if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
+ UI_view2d_view_to_region_rcti(&butregion->v2d, &rect_fl, &rect_i);
+ }
+
+ BLI_rcti_translate(&rect_i, butregion->winrct.xmin, butregion->winrct.ymin);
+
+ winx = WM_window_pixels_x(win);
+ // winy = WM_window_pixels_y(win); /* UNUSED */
+ //wm_window_get_size(win, &winx, &winy);
+
+ if (rect_i.xmax > winx) {
+ /* super size */
+ if (rect_i.xmax > winx + rect_i.xmin) {
+ rect_i.xmax = winx;
+ rect_i.xmin = 0;
+ }
+ else {
+ rect_i.xmin -= rect_i.xmax - winx;
+ rect_i.xmax = winx;
+ }
+ }
+
+ if (rect_i.ymin < 0) {
+ int newy1 = but->rect.ymax + ofsy;
+
+ if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax)
+ newy1 = UI_view2d_view_to_region_y(&butregion->v2d, newy1);
+
+ newy1 += butregion->winrct.ymin;
+
+ rect_i.ymax = BLI_rcti_size_y(&rect_i) + newy1;
+ rect_i.ymin = newy1;
+ }
+
+ /* widget rect, in region coords */
+ data->bbox.xmin = margin;
+ data->bbox.xmax = BLI_rcti_size_x(&rect_i) + margin;
+ data->bbox.ymin = margin;
+ data->bbox.ymax = BLI_rcti_size_y(&rect_i) + margin;
+
+ /* region bigger for shadow */
+ ar->winrct.xmin = rect_i.xmin - margin;
+ ar->winrct.xmax = rect_i.xmax + margin;
+ ar->winrct.ymin = rect_i.ymin - margin;
+ ar->winrct.ymax = rect_i.ymax;
+ }
+
+ /* adds subwindow */
+ ED_region_init(C, ar);
+
+ /* notify change and redraw */
+ ED_region_tag_redraw(ar);
+
+ /* prepare search data */
+ if (data->preview) {
+ data->items.maxitem = data->prv_rows * data->prv_cols;
+ }
+ else {
+ data->items.maxitem = SEARCH_ITEMS;
+ }
+ data->items.maxstrlen = but->hardmax;
+ data->items.totitem = 0;
+ data->items.names = MEM_callocN(data->items.maxitem * sizeof(void *), "search names");
+ data->items.pointers = MEM_callocN(data->items.maxitem * sizeof(void *), "search pointers");
+ data->items.icons = MEM_callocN(data->items.maxitem * sizeof(int), "search icons");
+ for (i = 0; i < data->items.maxitem; i++)
+ data->items.names[i] = MEM_callocN(but->hardmax + 1, "search pointers");
+
+ return ar;
+}
+
+/**
+ * Similar to Python's `str.title` except...
+ *
+ * - we know words are upper case and ascii only.
+ * - '_' are replaces by spaces.
+ */
+static void str_tolower_titlecaps_ascii(char *str, const size_t len)
+{
+ size_t i;
+ bool prev_delim = true;
+
+ for (i = 0; (i < len) && str[i]; i++) {
+ if (str[i] >= 'A' && str[i] <= 'Z') {
+ if (prev_delim == false) {
+ str[i] += 'a' - 'A';
+ }
+ }
+ else if (str[i] == '_') {
+ str[i] = ' ';
+ }
+
+ prev_delim = ELEM(str[i], ' ') || (str[i] >= '0' && str[i] <= '9');
+ }
+
+}
+
+static void ui_searchbox_region_draw_cb__operator(const bContext *UNUSED(C), ARegion *ar)
+{
+ uiSearchboxData *data = ar->regiondata;
+
+ /* pixel space */
+ wmOrtho2_region_pixelspace(ar);
+
+ if (data->noback == false)
+ ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */
+
+ /* draw text */
+ if (data->items.totitem) {
+ rcti rect;
+ int a;
+
+ /* draw items */
+ for (a = 0; a < data->items.totitem; a++) {
+ rcti rect_pre, rect_post;
+ ui_searchbox_butrect(&rect, data, a);
+
+ rect_pre = rect;
+ rect_post = rect;
+
+ rect_pre.xmax = rect_post.xmin = rect.xmin + ((rect.xmax - rect.xmin) / 4);
+
+ /* widget itself */
+ /* NOTE: i18n messages extracting tool does the same, please keep it in sync. */
+ {
+ wmOperatorType *ot = data->items.pointers[a];
+
+ int state = (a == data->active) ? UI_ACTIVE : 0;
+ char text_pre[128];
+ char *text_pre_p = strstr(ot->idname, "_OT_");
+ if (text_pre_p == NULL) {
+ text_pre[0] = '\0';
+ }
+ else {
+ int text_pre_len;
+ text_pre_p += 1;
+ text_pre_len = BLI_strncpy_rlen(
+ text_pre, ot->idname, min_ii(sizeof(text_pre), text_pre_p - ot->idname));
+ text_pre[text_pre_len] = ':';
+ text_pre[text_pre_len + 1] = '\0';
+ str_tolower_titlecaps_ascii(text_pre, sizeof(text_pre));
+ }
+
+ rect_pre.xmax += 4; /* sneaky, avoid showing ugly margin */
+ ui_draw_menu_item(&data->fstyle, &rect_pre, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, text_pre),
+ data->items.icons[a], state, false);
+ ui_draw_menu_item(&data->fstyle, &rect_post, data->items.names[a], 0, state, data->use_sep);
+ }
+
+ }
+ /* indicate more */
+ if (data->items.more) {
+ ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
+ glEnable(GL_BLEND);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
+ glDisable(GL_BLEND);
+ }
+ if (data->items.offset) {
+ ui_searchbox_butrect(&rect, data, 0);
+ glEnable(GL_BLEND);
+ UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
+ glDisable(GL_BLEND);
+ }
+ }
+}
+
+ARegion *ui_searchbox_create_operator(bContext *C, ARegion *butregion, uiBut *but)
+{
+ ARegion *ar;
+
+ ar = ui_searchbox_create_generic(C, butregion, but);
+
+ ar->type->draw = ui_searchbox_region_draw_cb__operator;
+
+ return ar;
+}
+
+void ui_searchbox_free(bContext *C, ARegion *ar)
+{
+ ui_region_temp_remove(C, CTX_wm_screen(C), ar);
+}
+
+/* sets red alert if button holds a string it can't find */
+/* XXX weak: search_func adds all partial matches... */
+void ui_but_search_refresh(uiBut *but)
+{
+ uiSearchItems *items;
+ int x1;
+
+ /* possibly very large lists (such as ID datablocks) only
+ * only validate string RNA buts (not pointers) */
+ if (but->rnaprop && RNA_property_type(but->rnaprop) != PROP_STRING) {
+ return;
+ }
+
+ items = MEM_callocN(sizeof(uiSearchItems), "search items");
+
+ /* setup search struct */
+ items->maxitem = 10;
+ items->maxstrlen = 256;
+ items->names = MEM_callocN(items->maxitem * sizeof(void *), "search names");
+ for (x1 = 0; x1 < items->maxitem; x1++)
+ items->names[x1] = MEM_callocN(but->hardmax + 1, "search names");
+
+ but->search_func(but->block->evil_C, but->search_arg, but->drawstr, items);
+
+ /* only redalert when we are sure of it, this can miss cases when >10 matches */
+ if (items->totitem == 0) {
+ UI_but_flag_enable(but, UI_BUT_REDALERT);
+ }
+ else if (items->more == 0) {
+ if (UI_search_items_find_index(items, but->drawstr) == -1) {
+ UI_but_flag_enable(but, UI_BUT_REDALERT);
+ }
+ }
+
+ for (x1 = 0; x1 < items->maxitem; x1++) {
+ MEM_freeN(items->names[x1]);
+ }
+ MEM_freeN(items->names);
+ MEM_freeN(items);
+}
+
+/** \} */
diff --git a/source/blender/editors/interface/interface_region_tooltip.c b/source/blender/editors/interface/interface_region_tooltip.c
new file mode 100644
index 00000000000..1eec3737215
--- /dev/null
+++ b/source/blender/editors/interface/interface_region_tooltip.c
@@ -0,0 +1,764 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_region_tooltip.c
+ * \ingroup edinterface
+ *
+ * ToolTip Region and Construction
+ */
+
+/* TODO(campbell):
+ * We may want to have a higher level API that initializes a timer,
+ * checks for mouse motion and clears the tool-tip afterwards.
+ * We never want multiple tool-tips at once so this could be handled on the window / window-manager level.
+ *
+ * For now it's not a priority, so leave as-is.
+ */
+
+#include <stdarg.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_userdef_types.h"
+
+#include "BLI_math.h"
+#include "BLI_string.h"
+#include "BLI_string_utf8.h"
+#include "BLI_rect.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+#include "BKE_screen.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "RNA_access.h"
+
+#include "BIF_gl.h"
+
+#include "UI_interface.h"
+
+#include "BLF_api.h"
+#include "BLT_translation.h"
+
+#include "ED_screen.h"
+
+#include "interface_intern.h"
+#include "interface_regions_intern.h"
+
+#define UI_TIP_PAD_FAC 1.3f
+#define UI_TIP_PADDING (int)(UI_TIP_PAD_FAC * UI_UNIT_Y)
+#define UI_TIP_MAXWIDTH 600
+
+
+typedef struct uiTooltipFormat {
+ enum {
+ UI_TIP_STYLE_NORMAL = 0,
+ UI_TIP_STYLE_HEADER,
+ UI_TIP_STYLE_MONO,
+ } style : 3;
+ enum {
+ UI_TIP_LC_MAIN = 0, /* primary text */
+ UI_TIP_LC_VALUE, /* the value of buttons (also shortcuts) */
+ UI_TIP_LC_ACTIVE, /* titles of active enum values */
+ UI_TIP_LC_NORMAL, /* regular text */
+ UI_TIP_LC_PYTHON, /* Python snippet */
+ UI_TIP_LC_ALERT, /* description of why operator can't run */
+ } color_id : 4;
+ int is_pad : 1;
+} uiTooltipFormat;
+
+typedef struct uiTooltipField {
+ char *text;
+ char *text_suffix;
+ struct {
+ uint x_pos; /* x cursor position at the end of the last line */
+ uint lines; /* number of lines, 1 or more with word-wrap */
+ } geom;
+ uiTooltipFormat format;
+
+} uiTooltipField;
+
+typedef struct uiTooltipData {
+ rcti bbox;
+ uiTooltipField *fields;
+ uint fields_len;
+ uiFontStyle fstyle;
+ int wrap_width;
+ int toth, lineh;
+} uiTooltipData;
+
+#define UI_TIP_LC_MAX 6
+
+BLI_STATIC_ASSERT(UI_TIP_LC_MAX == UI_TIP_LC_ALERT + 1, "invalid lc-max");
+BLI_STATIC_ASSERT(sizeof(uiTooltipFormat) <= sizeof(int), "oversize");
+
+static uiTooltipField *text_field_add_only(
+ uiTooltipData *data)
+{
+ data->fields_len += 1;
+ data->fields = MEM_recallocN(data->fields, sizeof(*data->fields) * data->fields_len);
+ return &data->fields[data->fields_len - 1];
+}
+
+static uiTooltipField *text_field_add(
+ uiTooltipData *data,
+ const uiTooltipFormat *format)
+{
+ uiTooltipField *field = text_field_add_only(data);
+ field->format = *format;
+ return field;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name ToolTip Callbacks (Draw & Free)
+ * \{ */
+
+static void rgb_tint(
+ float col[3],
+ float h, float h_strength,
+ float v, float v_strength)
+{
+ float col_hsv_from[3];
+ float col_hsv_to[3];
+
+ rgb_to_hsv_v(col, col_hsv_from);
+
+ col_hsv_to[0] = h;
+ col_hsv_to[1] = h_strength;
+ col_hsv_to[2] = (col_hsv_from[2] * (1.0f - v_strength)) + (v * v_strength);
+
+ hsv_to_rgb_v(col_hsv_to, col);
+}
+
+static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
+{
+ const float pad_px = UI_TIP_PADDING;
+ uiTooltipData *data = ar->regiondata;
+ uiWidgetColors *theme = ui_tooltip_get_theme();
+ rcti bbox = data->bbox;
+ float tip_colors[UI_TIP_LC_MAX][3];
+
+ float *main_color = tip_colors[UI_TIP_LC_MAIN]; /* the color from the theme */
+ float *value_color = tip_colors[UI_TIP_LC_VALUE];
+ float *active_color = tip_colors[UI_TIP_LC_ACTIVE];
+ float *normal_color = tip_colors[UI_TIP_LC_NORMAL];
+ float *python_color = tip_colors[UI_TIP_LC_PYTHON];
+ float *alert_color = tip_colors[UI_TIP_LC_ALERT];
+
+ float background_color[3];
+ float tone_bg;
+ int i, multisample_enabled;
+
+ /* disable AA, makes widgets too blurry */
+ multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
+ if (multisample_enabled)
+ glDisable(GL_MULTISAMPLE);
+
+ wmOrtho2_region_pixelspace(ar);
+
+ /* draw background */
+ ui_draw_tooltip_background(UI_style_get(), NULL, &bbox);
+
+ /* set background_color */
+ rgb_uchar_to_float(background_color, (const unsigned char *)theme->inner);
+
+ /* calculate normal_color */
+ rgb_uchar_to_float(main_color, (const unsigned char *)theme->text);
+ copy_v3_v3(active_color, main_color);
+ copy_v3_v3(normal_color, main_color);
+ copy_v3_v3(python_color, main_color);
+ copy_v3_v3(alert_color, main_color);
+ copy_v3_v3(value_color, main_color);
+
+ /* find the brightness difference between background and text colors */
+
+ tone_bg = rgb_to_grayscale(background_color);
+ /* tone_fg = rgb_to_grayscale(main_color); */
+
+ /* mix the colors */
+ rgb_tint(value_color, 0.0f, 0.0f, tone_bg, 0.2f); /* light gray */
+ rgb_tint(active_color, 0.6f, 0.2f, tone_bg, 0.2f); /* light blue */
+ rgb_tint(normal_color, 0.0f, 0.0f, tone_bg, 0.4f); /* gray */
+ rgb_tint(python_color, 0.0f, 0.0f, tone_bg, 0.5f); /* dark gray */
+ rgb_tint(alert_color, 0.0f, 0.8f, tone_bg, 0.1f); /* red */
+
+ /* draw text */
+ BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
+ BLF_wordwrap(blf_mono_font, data->wrap_width);
+
+ bbox.xmin += 0.5f * pad_px; /* add padding to the text */
+ bbox.ymax -= 0.25f * pad_px;
+
+ for (i = 0; i < data->fields_len; i++) {
+ const uiTooltipField *field = &data->fields[i];
+ const uiTooltipField *field_next = (i + 1) != data->fields_len ? &data->fields[i + 1] : NULL;
+
+ bbox.ymin = bbox.ymax - (data->lineh * field->geom.lines);
+ if (field->format.style == UI_TIP_STYLE_HEADER) {
+ /* draw header and active data (is done here to be able to change color) */
+ uiFontStyle fstyle_header = data->fstyle;
+
+ /* override text-style */
+ fstyle_header.shadow = 1;
+ fstyle_header.shadowcolor = rgb_to_grayscale(tip_colors[UI_TIP_LC_MAIN]);
+ fstyle_header.shadx = fstyle_header.shady = 0;
+ fstyle_header.shadowalpha = 1.0f;
+ fstyle_header.word_wrap = true;
+
+ UI_fontstyle_set(&fstyle_header);
+ glColor3fv(tip_colors[UI_TIP_LC_MAIN]);
+ UI_fontstyle_draw(&fstyle_header, &bbox, field->text);
+
+ fstyle_header.shadow = 0;
+
+ /* offset to the end of the last line */
+ if (field->text_suffix) {
+ float xofs = field->geom.x_pos;
+ float yofs = data->lineh * (field->geom.lines - 1);
+ bbox.xmin += xofs;
+ bbox.ymax -= yofs;
+
+ glColor3fv(tip_colors[UI_TIP_LC_ACTIVE]);
+ UI_fontstyle_draw(&fstyle_header, &bbox, field->text_suffix);
+
+ /* undo offset */
+ bbox.xmin -= xofs;
+ bbox.ymax += yofs;
+ }
+ }
+ else if (field->format.style == UI_TIP_STYLE_MONO) {
+ uiFontStyle fstyle_mono = data->fstyle;
+ fstyle_mono.uifont_id = blf_mono_font;
+ fstyle_mono.word_wrap = true;
+
+ UI_fontstyle_set(&fstyle_mono);
+ /* XXX, needed because we dont have mono in 'U.uifonts' */
+ BLF_size(fstyle_mono.uifont_id, fstyle_mono.points * U.pixelsize, U.dpi);
+ glColor3fv(tip_colors[field->format.color_id]);
+ UI_fontstyle_draw(&fstyle_mono, &bbox, field->text);
+ }
+ else {
+ uiFontStyle fstyle_normal = data->fstyle;
+ BLI_assert(field->format.style == UI_TIP_STYLE_NORMAL);
+ fstyle_normal.word_wrap = true;
+
+ /* draw remaining data */
+ UI_fontstyle_set(&fstyle_normal);
+ glColor3fv(tip_colors[field->format.color_id]);
+ UI_fontstyle_draw(&fstyle_normal, &bbox, field->text);
+ }
+
+ bbox.ymax -= data->lineh * field->geom.lines;
+
+ if (field_next && field_next->format.is_pad) {
+ bbox.ymax -= data->lineh * (UI_TIP_PAD_FAC - 1);
+ }
+ }
+
+ BLF_disable(data->fstyle.uifont_id, BLF_WORD_WRAP);
+ BLF_disable(blf_mono_font, BLF_WORD_WRAP);
+
+ if (multisample_enabled)
+ glEnable(GL_MULTISAMPLE);
+}
+
+static void ui_tooltip_region_free_cb(ARegion *ar)
+{
+ uiTooltipData *data;
+
+ data = ar->regiondata;
+
+ for (int i = 0; i < data->fields_len; i++) {
+ const uiTooltipField *field = &data->fields[i];
+ MEM_freeN(field->text);
+ if (field->text_suffix) {
+ MEM_freeN(field->text_suffix);
+ }
+ }
+ MEM_freeN(data->fields);
+ MEM_freeN(data);
+ ar->regiondata = NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ToolTip Creation
+ * \{ */
+
+static uiTooltipData *ui_tooltip_data_from_button(bContext *C, uiBut *but)
+{
+ uiStringInfo but_tip = {BUT_GET_TIP, NULL};
+ uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
+ uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
+ uiStringInfo op_keymap = {BUT_GET_OP_KEYMAP, NULL};
+ uiStringInfo prop_keymap = {BUT_GET_PROP_KEYMAP, NULL};
+ uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
+ uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
+
+ char buf[512];
+
+ /* create tooltip data */
+ uiTooltipData *data = MEM_callocN(sizeof(uiTooltipData), "uiTooltipData");
+
+ UI_but_string_info_get(C, but, &but_tip, &enum_label, &enum_tip, &op_keymap, &prop_keymap, &rna_struct, &rna_prop, NULL);
+
+ /* Tip */
+ if (but_tip.strinfo) {
+ {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_HEADER,
+ .color_id = UI_TIP_LC_NORMAL,
+ });
+ if (enum_label.strinfo) {
+ field->text = BLI_sprintfN("%s: ", but_tip.strinfo);
+ field->text_suffix = BLI_strdup(enum_label.strinfo);
+ }
+ else {
+ field->text = BLI_sprintfN("%s.", but_tip.strinfo);
+ }
+ }
+
+ /* special case enum rna buttons */
+ if ((but->type & UI_BTYPE_ROW) && but->rnaprop && RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_NORMAL,
+ });
+ field->text = BLI_strdup(IFACE_("(Shift-Click/Drag to select multiple)"));
+ }
+
+ }
+ /* Enum field label & tip */
+ if (enum_tip.strinfo) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_VALUE,
+ .is_pad = true,
+ });
+ field->text = BLI_strdup(enum_tip.strinfo);
+ }
+
+ /* Op shortcut */
+ if (op_keymap.strinfo) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_VALUE,
+ .is_pad = true,
+ });
+ field->text = BLI_sprintfN(TIP_("Shortcut: %s"), op_keymap.strinfo);
+ }
+
+ /* Property context-toggle shortcut */
+ if (prop_keymap.strinfo) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_VALUE,
+ .is_pad = true,
+ });
+ field->text = BLI_sprintfN(TIP_("Shortcut: %s"), prop_keymap.strinfo);
+ }
+
+ if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
+ /* better not show the value of a password */
+ if ((but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) == 0) {
+ /* full string */
+ ui_but_string_get(but, buf, sizeof(buf));
+ if (buf[0]) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_VALUE,
+ .is_pad = true,
+ });
+ field->text = BLI_sprintfN(TIP_("Value: %s"), buf);
+ }
+ }
+ }
+
+ if (but->rnaprop) {
+ int unit_type = UI_but_unit_type_get(but);
+
+ if (unit_type == PROP_UNIT_ROTATION) {
+ if (RNA_property_type(but->rnaprop) == PROP_FLOAT) {
+ float value = RNA_property_array_check(but->rnaprop) ?
+ RNA_property_float_get_index(&but->rnapoin, but->rnaprop, but->rnaindex) :
+ RNA_property_float_get(&but->rnapoin, but->rnaprop);
+
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_VALUE,
+ });
+ field->text = BLI_sprintfN(TIP_("Radians: %f"), value);
+ }
+ }
+
+ if (but->flag & UI_BUT_DRIVEN) {
+ if (ui_but_anim_expression_get(but, buf, sizeof(buf))) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_NORMAL,
+ });
+ field->text = BLI_sprintfN(TIP_("Expression: %s"), buf);
+ }
+ }
+
+ if (but->rnapoin.id.data) {
+ const ID *id = but->rnapoin.id.data;
+ if (ID_IS_LINKED(id)) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_NORMAL,
+ });
+ field->text = BLI_sprintfN(TIP_("Library: %s"), id->lib->name);
+ }
+ }
+ }
+ else if (but->optype) {
+ PointerRNA *opptr;
+ char *str;
+ opptr = UI_but_operator_ptr_get(but); /* allocated when needed, the button owns it */
+
+ /* so the context is passed to fieldf functions (some py fieldf functions use it) */
+ WM_operator_properties_sanitize(opptr, false);
+
+ str = WM_operator_pystring_ex(C, NULL, false, false, but->optype, opptr);
+
+ /* avoid overly verbose tips (eg, arrays of 20 layers), exact limit is arbitrary */
+ WM_operator_pystring_abbreviate(str, 32);
+
+ /* operator info */
+ if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_MONO,
+ .color_id = UI_TIP_LC_PYTHON,
+ .is_pad = true,
+ });
+ field->text = BLI_sprintfN(TIP_("Python: %s"), str);
+ }
+
+ MEM_freeN(str);
+ }
+
+ /* button is disabled, we may be able to tell user why */
+ if (but->flag & UI_BUT_DISABLED) {
+ const char *disabled_msg = NULL;
+
+ /* if operator poll check failed, it can give pretty precise info why */
+ if (but->optype) {
+ CTX_wm_operator_poll_msg_set(C, NULL);
+ WM_operator_poll_context(C, but->optype, but->opcontext);
+ disabled_msg = CTX_wm_operator_poll_msg_get(C);
+ }
+ /* alternatively, buttons can store some reasoning too */
+ else if (but->disabled_info) {
+ disabled_msg = TIP_(but->disabled_info);
+ }
+
+ if (disabled_msg && disabled_msg[0]) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_NORMAL,
+ .color_id = UI_TIP_LC_ALERT,
+ });
+ field->text = BLI_sprintfN(TIP_("Disabled: %s"), disabled_msg);
+ }
+ }
+
+ if ((U.flag & USER_TOOLTIPS_PYTHON) == 0 && !but->optype && rna_struct.strinfo) {
+ {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_MONO,
+ .color_id = UI_TIP_LC_PYTHON,
+ .is_pad = true,
+ });
+ if (rna_prop.strinfo) {
+ /* Struct and prop */
+ field->text = BLI_sprintfN(TIP_("Python: %s.%s"), rna_struct.strinfo, rna_prop.strinfo);
+ }
+ else {
+ /* Only struct (e.g. menus) */
+ field->text = BLI_sprintfN(TIP_("Python: %s"), rna_struct.strinfo);
+ }
+ }
+
+ if (but->rnapoin.id.data) {
+ uiTooltipField *field = text_field_add(
+ data, &(uiTooltipFormat){
+ .style = UI_TIP_STYLE_MONO,
+ .color_id = UI_TIP_LC_PYTHON,
+ });
+
+ /* this could get its own 'BUT_GET_...' type */
+
+ /* never fails */
+ /* move ownership (no need for re-alloc) */
+ if (but->rnaprop) {
+ field->text = RNA_path_full_property_py_ex(&but->rnapoin, but->rnaprop, but->rnaindex, true);
+ }
+ else {
+ field->text = RNA_path_full_struct_py(&but->rnapoin);
+ }
+
+ }
+ }
+
+ /* Free strinfo's... */
+ if (but_tip.strinfo)
+ MEM_freeN(but_tip.strinfo);
+ if (enum_label.strinfo)
+ MEM_freeN(enum_label.strinfo);
+ if (enum_tip.strinfo)
+ MEM_freeN(enum_tip.strinfo);
+ if (op_keymap.strinfo)
+ MEM_freeN(op_keymap.strinfo);
+ if (prop_keymap.strinfo)
+ MEM_freeN(prop_keymap.strinfo);
+ if (rna_struct.strinfo)
+ MEM_freeN(rna_struct.strinfo);
+ if (rna_prop.strinfo)
+ MEM_freeN(rna_prop.strinfo);
+
+ if (data->fields_len == 0) {
+ MEM_freeN(data);
+ return NULL;
+ }
+ else {
+ return data;
+ }
+}
+
+static ARegion *ui_tooltip_create_with_data(
+ bContext *C, uiTooltipData *data,
+ const float init_position[2],
+ const float aspect)
+{
+ const float pad_px = UI_TIP_PADDING;
+ wmWindow *win = CTX_wm_window(C);
+ const int winx = WM_window_pixels_x(win);
+ uiStyle *style = UI_style_get();
+ static ARegionType type;
+ ARegion *ar;
+ int fonth, fontw;
+ int h, i;
+ rctf rect_fl;
+ rcti rect_i;
+ int font_flag = 0;
+
+ /* create area region */
+ ar = ui_region_temp_add(CTX_wm_screen(C));
+
+ memset(&type, 0, sizeof(ARegionType));
+ type.draw = ui_tooltip_region_draw_cb;
+ type.free = ui_tooltip_region_free_cb;
+ type.regionid = RGN_TYPE_TEMPORARY;
+ ar->type = &type;
+
+ /* set font, get bb */
+ data->fstyle = style->widget; /* copy struct */
+ ui_fontscale(&data->fstyle.points, aspect);
+
+ UI_fontstyle_set(&data->fstyle);
+
+ data->wrap_width = min_ii(UI_TIP_MAXWIDTH * U.pixelsize / aspect, winx - (UI_TIP_PADDING * 2));
+
+ font_flag |= BLF_WORD_WRAP;
+ if (data->fstyle.kerning == 1) {
+ font_flag |= BLF_KERNING_DEFAULT;
+ }
+ BLF_enable(data->fstyle.uifont_id, font_flag);
+ BLF_enable(blf_mono_font, font_flag);
+ BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
+ BLF_wordwrap(blf_mono_font, data->wrap_width);
+
+ /* these defines tweaked depending on font */
+#define TIP_BORDER_X (16.0f / aspect)
+#define TIP_BORDER_Y (6.0f / aspect)
+
+ h = BLF_height_max(data->fstyle.uifont_id);
+
+ for (i = 0, fontw = 0, fonth = 0; i < data->fields_len; i++) {
+ uiTooltipField *field = &data->fields[i];
+ uiTooltipField *field_next = (i + 1) != data->fields_len ? &data->fields[i + 1] : NULL;
+
+ struct ResultBLF info;
+ int w, x_pos = 0;
+ int font_id;
+
+ if (field->format.style == UI_TIP_STYLE_MONO) {
+ BLF_size(blf_mono_font, data->fstyle.points * U.pixelsize, U.dpi);
+ font_id = blf_mono_font;
+ }
+ else {
+ BLI_assert(ELEM(field->format.style, UI_TIP_STYLE_NORMAL, UI_TIP_STYLE_HEADER));
+ font_id = data->fstyle.uifont_id;
+ }
+ w = BLF_width_ex(font_id, field->text, BLF_DRAW_STR_DUMMY_MAX, &info);
+
+ /* check for suffix (enum label) */
+ if (field->text_suffix && field->text_suffix[0]) {
+ x_pos = info.width;
+ w = max_ii(w, x_pos + BLF_width(font_id, field->text_suffix, BLF_DRAW_STR_DUMMY_MAX));
+ }
+ fontw = max_ii(fontw, w);
+
+ fonth += h * info.lines;
+ if (field_next && field_next->format.is_pad) {
+ fonth += h * (UI_TIP_PAD_FAC - 1);
+ }
+
+ field->geom.lines = info.lines;
+ field->geom.x_pos = x_pos;
+ }
+
+ //fontw *= aspect;
+
+ BLF_disable(data->fstyle.uifont_id, font_flag);
+ BLF_disable(blf_mono_font, font_flag);
+
+ ar->regiondata = data;
+
+ data->toth = fonth;
+ data->lineh = h;
+
+ /* compute position */
+
+ rect_fl.xmin = init_position[0] - TIP_BORDER_X;
+ rect_fl.xmax = rect_fl.xmin + fontw + pad_px;
+ rect_fl.ymax = init_position[1] - TIP_BORDER_Y;
+ rect_fl.ymin = rect_fl.ymax - fonth - TIP_BORDER_Y;
+
+ BLI_rcti_rctf_copy(&rect_i, &rect_fl);
+
+#undef TIP_BORDER_X
+#undef TIP_BORDER_Y
+
+ /* clip with window boundaries */
+ if (rect_i.xmax > winx) {
+ /* super size */
+ if (rect_i.xmax > winx + rect_i.xmin) {
+ rect_i.xmax = winx;
+ rect_i.xmin = 0;
+ }
+ else {
+ rect_i.xmin -= rect_i.xmax - winx;
+ rect_i.xmax = winx;
+ }
+ }
+ /* ensure at least 5 px above screen bounds
+ * 25 is just a guess to be above the menu item */
+ if (rect_i.ymin < 5) {
+ rect_i.ymax += (-rect_i.ymin) + 30;
+ rect_i.ymin = 30;
+ }
+
+ /* add padding */
+ BLI_rcti_resize(&rect_i,
+ BLI_rcti_size_x(&rect_i) + pad_px,
+ BLI_rcti_size_y(&rect_i) + pad_px);
+
+ /* widget rect, in region coords */
+ {
+ const int margin = UI_POPUP_MARGIN;
+
+ data->bbox.xmin = margin;
+ data->bbox.xmax = BLI_rcti_size_x(&rect_i) - margin;
+ data->bbox.ymin = margin;
+ data->bbox.ymax = BLI_rcti_size_y(&rect_i);
+
+ /* region bigger for shadow */
+ ar->winrct.xmin = rect_i.xmin - margin;
+ ar->winrct.xmax = rect_i.xmax + margin;
+ ar->winrct.ymin = rect_i.ymin - margin;
+ ar->winrct.ymax = rect_i.ymax + margin;
+ }
+
+ /* adds subwindow */
+ ED_region_init(C, ar);
+
+ /* notify change and redraw */
+ ED_region_tag_redraw(ar);
+
+ return ar;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name ToolTip Public API
+ * \{ */
+
+
+ARegion *UI_tooltip_create_from_button(bContext *C, ARegion *butregion, uiBut *but)
+{
+ wmWindow *win = CTX_wm_window(C);
+ /* aspect values that shrink text are likely unreadable */
+ const float aspect = min_ff(1.0f, but->block->aspect);
+ float init_position[2];
+
+ if (but->drawflag & UI_BUT_NO_TOOLTIP) {
+ return NULL;
+ }
+ uiTooltipData *data = NULL;
+
+ if (data == NULL) {
+ data = ui_tooltip_data_from_button(C, but);
+ }
+ if (data == NULL) {
+ return NULL;
+ }
+
+ init_position[0] = BLI_rctf_cent_x(&but->rect);
+ init_position[1] = but->rect.ymin;
+
+ if (butregion) {
+ ui_block_to_window_fl(butregion, but->block, &init_position[0], &init_position[1]);
+ init_position[0] = win->eventstate->x;
+ }
+
+ return ui_tooltip_create_with_data(C, data, init_position, aspect);
+}
+
+void UI_tooltip_free(bContext *C, bScreen *sc, ARegion *ar)
+{
+ ui_region_temp_remove(C, sc, ar);
+}
+
+/** \} */
diff --git a/source/blender/editors/interface/interface_regions.c b/source/blender/editors/interface/interface_regions.c
index 466978272bc..dd1d38bbe2e 100644
--- a/source/blender/editors/interface/interface_regions.c
+++ b/source/blender/editors/interface/interface_regions.c
@@ -25,83 +25,27 @@
/** \file blender/editors/interface/interface_regions.c
* \ingroup edinterface
+ *
+ * General Interface Region Code
+ *
+ * \note Most logic is now in 'interface_region_*.c'
*/
-#include <stdarg.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-
-#include "MEM_guardedalloc.h"
-
-#include "DNA_userdef_types.h"
-
-#include "BLI_math.h"
-#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
-#include "BLI_ghash.h"
-
-#include "PIL_time.h"
+#include "MEM_guardedalloc.h"
+#include "BLI_listbase.h"
#include "BKE_context.h"
#include "BKE_screen.h"
-#include "BKE_report.h"
-#include "BKE_global.h"
#include "WM_api.h"
-#include "WM_types.h"
#include "wm_draw.h"
-#include "wm_subwindow.h"
-
-#include "RNA_access.h"
-
-#include "BIF_gl.h"
-
-#include "UI_interface.h"
-#include "UI_interface_icons.h"
-#include "UI_view2d.h"
-
-#include "BLF_api.h"
-#include "BLT_translation.h"
#include "ED_screen.h"
-#include "IMB_colormanagement.h"
-
-#include "interface_intern.h"
-
-#define MENU_PADDING (int)(0.2f * UI_UNIT_Y)
-#define MENU_BORDER (int)(0.3f * U.widget_unit)
-
-
-bool ui_but_menu_step_poll(const uiBut *but)
-{
- BLI_assert(but->type == UI_BTYPE_MENU);
-
- /* currently only RNA buttons */
- return ((but->menu_step_func != NULL) ||
- (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM));
-}
-
-int ui_but_menu_step(uiBut *but, int direction)
-{
- if (ui_but_menu_step_poll(but)) {
- if (but->menu_step_func) {
- return but->menu_step_func(but->block->evil_C, direction, but->poin);
- }
- else {
- const int curval = RNA_property_enum_get(&but->rnapoin, but->rnaprop);
- return RNA_property_enum_step(but->block->evil_C, &but->rnapoin, but->rnaprop, curval, direction);
- }
- }
-
- printf("%s: cannot cycle button '%s'\n", __func__, but->str);
- return 0;
-}
-
-/******************** Creating Temporary regions ******************/
+#include "interface_regions_intern.h"
-static ARegion *ui_region_temp_add(bScreen *sc)
+ARegion *ui_region_temp_add(bScreen *sc)
{
ARegion *ar;
@@ -114,7 +58,7 @@ static ARegion *ui_region_temp_add(bScreen *sc)
return ar;
}
-static void ui_region_temp_remove(bContext *C, bScreen *sc, ARegion *ar)
+void ui_region_temp_remove(bContext *C, bScreen *sc, ARegion *ar)
{
wmWindow *win = CTX_wm_window(C);
if (win)
@@ -124,3273 +68,3 @@ static void ui_region_temp_remove(bContext *C, bScreen *sc, ARegion *ar)
BKE_area_region_free(NULL, ar); /* NULL: no spacetype */
BLI_freelinkN(&sc->regionbase, ar);
}
-
-/************************* Creating Tooltips **********************/
-
-#define UI_TIP_PAD_FAC 1.3f
-#define UI_TIP_PADDING (int)(UI_TIP_PAD_FAC * UI_UNIT_Y)
-#define UI_TIP_MAXWIDTH 600
-
-#define MAX_TOOLTIP_LINES 8
-typedef struct uiTooltipData {
- rcti bbox;
- uiFontStyle fstyle;
- char lines[MAX_TOOLTIP_LINES][2048];
- char header[2048], active_info[2048];
- struct {
- enum {
- UI_TIP_STYLE_NORMAL = 0,
- UI_TIP_STYLE_HEADER,
- UI_TIP_STYLE_MONO,
- } style : 3;
- enum {
- UI_TIP_LC_MAIN = 0, /* primary text */
- UI_TIP_LC_VALUE, /* the value of buttons (also shortcuts) */
- UI_TIP_LC_ACTIVE, /* titles of active enum values */
- UI_TIP_LC_NORMAL, /* regular text */
- UI_TIP_LC_PYTHON, /* Python snippet */
- UI_TIP_LC_ALERT, /* description of why operator can't run */
- } color_id : 4;
- int is_pad : 1;
- } format[MAX_TOOLTIP_LINES];
-
- struct {
- unsigned int x_pos; /* x cursor position at the end of the last line */
- unsigned int lines; /* number of lines, 1 or more with word-wrap */
- } line_geom[MAX_TOOLTIP_LINES];
-
- int wrap_width;
-
- int totline;
- int toth, lineh;
-} uiTooltipData;
-
-#define UI_TIP_LC_MAX 6
-
-BLI_STATIC_ASSERT(UI_TIP_LC_MAX == UI_TIP_LC_ALERT + 1, "invalid lc-max");
-BLI_STATIC_ASSERT(sizeof(((uiTooltipData *)NULL)->format[0]) <= sizeof(int), "oversize");
-
-static void rgb_tint(
- float col[3],
- float h, float h_strength,
- float v, float v_strength)
-{
- float col_hsv_from[3];
- float col_hsv_to[3];
-
- rgb_to_hsv_v(col, col_hsv_from);
-
- col_hsv_to[0] = h;
- col_hsv_to[1] = h_strength;
- col_hsv_to[2] = (col_hsv_from[2] * (1.0f - v_strength)) + (v * v_strength);
-
- hsv_to_rgb_v(col_hsv_to, col);
-}
-
-static void ui_tooltip_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
-{
- const float pad_px = UI_TIP_PADDING;
- uiTooltipData *data = ar->regiondata;
- uiWidgetColors *theme = ui_tooltip_get_theme();
- rcti bbox = data->bbox;
- float tip_colors[UI_TIP_LC_MAX][3];
-
- float *main_color = tip_colors[UI_TIP_LC_MAIN]; /* the color from the theme */
- float *value_color = tip_colors[UI_TIP_LC_VALUE];
- float *active_color = tip_colors[UI_TIP_LC_ACTIVE];
- float *normal_color = tip_colors[UI_TIP_LC_NORMAL];
- float *python_color = tip_colors[UI_TIP_LC_PYTHON];
- float *alert_color = tip_colors[UI_TIP_LC_ALERT];
-
- float background_color[3];
- float tone_bg;
- int i, multisample_enabled;
-
- /* disable AA, makes widgets too blurry */
- multisample_enabled = glIsEnabled(GL_MULTISAMPLE);
- if (multisample_enabled)
- glDisable(GL_MULTISAMPLE);
-
- wmOrtho2_region_pixelspace(ar);
-
- /* draw background */
- ui_draw_tooltip_background(UI_style_get(), NULL, &bbox);
-
- /* set background_color */
- rgb_uchar_to_float(background_color, (const unsigned char *)theme->inner);
-
- /* calculate normal_color */
- rgb_uchar_to_float(main_color, (const unsigned char *)theme->text);
- copy_v3_v3(active_color, main_color);
- copy_v3_v3(normal_color, main_color);
- copy_v3_v3(python_color, main_color);
- copy_v3_v3(alert_color, main_color);
- copy_v3_v3(value_color, main_color);
-
- /* find the brightness difference between background and text colors */
-
- tone_bg = rgb_to_grayscale(background_color);
- /* tone_fg = rgb_to_grayscale(main_color); */
-
- /* mix the colors */
- rgb_tint(value_color, 0.0f, 0.0f, tone_bg, 0.2f); /* light gray */
- rgb_tint(active_color, 0.6f, 0.2f, tone_bg, 0.2f); /* light blue */
- rgb_tint(normal_color, 0.0f, 0.0f, tone_bg, 0.4f); /* gray */
- rgb_tint(python_color, 0.0f, 0.0f, tone_bg, 0.5f); /* dark gray */
- rgb_tint(alert_color, 0.0f, 0.8f, tone_bg, 0.1f); /* red */
-
- /* draw text */
- BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
- BLF_wordwrap(blf_mono_font, data->wrap_width);
-
- bbox.xmin += 0.5f * pad_px; /* add padding to the text */
- bbox.ymax -= 0.25f * pad_px;
-
- for (i = 0; i < data->totline; i++) {
- bbox.ymin = bbox.ymax - (data->lineh * data->line_geom[i].lines);
- if (data->format[i].style == UI_TIP_STYLE_HEADER) {
- /* draw header and active data (is done here to be able to change color) */
- uiFontStyle fstyle_header = data->fstyle;
- float xofs, yofs;
-
- /* override text-style */
- fstyle_header.shadow = 1;
- fstyle_header.shadowcolor = rgb_to_grayscale(tip_colors[UI_TIP_LC_MAIN]);
- fstyle_header.shadx = fstyle_header.shady = 0;
- fstyle_header.shadowalpha = 1.0f;
- fstyle_header.word_wrap = true;
-
- UI_fontstyle_set(&fstyle_header);
- glColor3fv(tip_colors[UI_TIP_LC_MAIN]);
- UI_fontstyle_draw(&fstyle_header, &bbox, data->header);
-
- /* offset to the end of the last line */
- xofs = data->line_geom[i].x_pos;
- yofs = data->lineh * (data->line_geom[i].lines - 1);
- bbox.xmin += xofs;
- bbox.ymax -= yofs;
-
- glColor3fv(tip_colors[UI_TIP_LC_ACTIVE]);
- fstyle_header.shadow = 0;
- UI_fontstyle_draw(&fstyle_header, &bbox, data->active_info);
-
- /* undo offset */
- bbox.xmin -= xofs;
- bbox.ymax += yofs;
- }
- else if (data->format[i].style == UI_TIP_STYLE_MONO) {
- uiFontStyle fstyle_mono = data->fstyle;
- fstyle_mono.uifont_id = blf_mono_font;
- fstyle_mono.word_wrap = true;
-
- UI_fontstyle_set(&fstyle_mono);
- /* XXX, needed because we dont have mono in 'U.uifonts' */
- BLF_size(fstyle_mono.uifont_id, fstyle_mono.points * U.pixelsize, U.dpi);
- glColor3fv(tip_colors[data->format[i].color_id]);
- UI_fontstyle_draw(&fstyle_mono, &bbox, data->lines[i]);
- }
- else {
- uiFontStyle fstyle_normal = data->fstyle;
- BLI_assert(data->format[i].style == UI_TIP_STYLE_NORMAL);
- fstyle_normal.word_wrap = true;
-
- /* draw remaining data */
- UI_fontstyle_set(&fstyle_normal);
- glColor3fv(tip_colors[data->format[i].color_id]);
- UI_fontstyle_draw(&fstyle_normal, &bbox, data->lines[i]);
- }
-
- bbox.ymax -= data->lineh * data->line_geom[i].lines;
-
- if ((i + 1 != data->totline) && data->format[i + 1].is_pad) {
- bbox.ymax -= data->lineh * (UI_TIP_PAD_FAC - 1);
- }
- }
-
- BLF_disable(data->fstyle.uifont_id, BLF_WORD_WRAP);
- BLF_disable(blf_mono_font, BLF_WORD_WRAP);
-
- if (multisample_enabled)
- glEnable(GL_MULTISAMPLE);
-}
-
-static void ui_tooltip_region_free_cb(ARegion *ar)
-{
- uiTooltipData *data;
-
- data = ar->regiondata;
- MEM_freeN(data);
- ar->regiondata = NULL;
-}
-
-static uiTooltipData *ui_tooltip_data_from_button(bContext *C, uiBut *but)
-{
- uiStringInfo but_tip = {BUT_GET_TIP, NULL};
- uiStringInfo enum_label = {BUT_GET_RNAENUM_LABEL, NULL};
- uiStringInfo enum_tip = {BUT_GET_RNAENUM_TIP, NULL};
- uiStringInfo op_keymap = {BUT_GET_OP_KEYMAP, NULL};
- uiStringInfo prop_keymap = {BUT_GET_PROP_KEYMAP, NULL};
- uiStringInfo rna_struct = {BUT_GET_RNASTRUCT_IDENTIFIER, NULL};
- uiStringInfo rna_prop = {BUT_GET_RNAPROP_IDENTIFIER, NULL};
-
- char buf[512];
-
- /* create tooltip data */
- uiTooltipData *data = MEM_callocN(sizeof(uiTooltipData), "uiTooltipData");
-
- UI_but_string_info_get(C, but, &but_tip, &enum_label, &enum_tip, &op_keymap, &prop_keymap, &rna_struct, &rna_prop, NULL);
-
- /* Tip */
- if (but_tip.strinfo) {
- BLI_strncpy(data->header, but_tip.strinfo, sizeof(data->lines[0]));
- if (enum_label.strinfo) {
- BLI_snprintf(data->header, sizeof(data->header), "%s: ", but_tip.strinfo);
- BLI_strncpy(data->active_info, enum_label.strinfo, sizeof(data->lines[0]));
- }
- data->format[data->totline].style = UI_TIP_STYLE_HEADER;
- data->totline++;
-
- /* special case enum rna buttons */
- if ((but->type & UI_BTYPE_ROW) && but->rnaprop && RNA_property_flag(but->rnaprop) & PROP_ENUM_FLAG) {
- BLI_strncpy(data->lines[data->totline], IFACE_("(Shift-Click/Drag to select multiple)"),
- sizeof(data->lines[0]));
-
- data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
- data->totline++;
- }
-
- }
- /* Enum item label & tip */
- if (enum_tip.strinfo) {
- BLI_strncpy(data->lines[data->totline], enum_tip.strinfo, sizeof(data->lines[0]));
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_VALUE;
- data->totline++;
- }
-
- /* Op shortcut */
- if (op_keymap.strinfo) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), op_keymap.strinfo);
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_VALUE;
- data->totline++;
- }
-
- /* Property context-toggle shortcut */
- if (prop_keymap.strinfo) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Shortcut: %s"), prop_keymap.strinfo);
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_VALUE;
- data->totline++;
- }
-
- if (ELEM(but->type, UI_BTYPE_TEXT, UI_BTYPE_SEARCH_MENU)) {
- /* better not show the value of a password */
- if ((but->rnaprop && (RNA_property_subtype(but->rnaprop) == PROP_PASSWORD)) == 0) {
- /* full string */
- ui_but_string_get(but, buf, sizeof(buf));
- if (buf[0]) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Value: %s"), buf);
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_VALUE;
- data->totline++;
- }
- }
- }
-
- if (but->rnaprop) {
- int unit_type = UI_but_unit_type_get(but);
-
- if (unit_type == PROP_UNIT_ROTATION) {
- if (RNA_property_type(but->rnaprop) == PROP_FLOAT) {
- float value = RNA_property_array_check(but->rnaprop) ?
- RNA_property_float_get_index(&but->rnapoin, but->rnaprop, but->rnaindex) :
- RNA_property_float_get(&but->rnapoin, but->rnaprop);
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Radians: %f"), value);
- data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
- data->totline++;
- }
- }
-
- if (but->flag & UI_BUT_DRIVEN) {
- if (ui_but_anim_expression_get(but, buf, sizeof(buf))) {
- /* expression */
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Expression: %s"), buf);
- data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
- data->totline++;
- }
- }
-
- if (but->rnapoin.id.data) {
- ID *id = but->rnapoin.id.data;
- if (ID_IS_LINKED_DATABLOCK(id)) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Library: %s"), id->lib->name);
- data->format[data->totline].color_id = UI_TIP_LC_NORMAL;
- data->totline++;
- }
- }
- }
- else if (but->optype) {
- PointerRNA *opptr;
- char *str;
- opptr = UI_but_operator_ptr_get(but); /* allocated when needed, the button owns it */
-
- /* so the context is passed to itemf functions (some py itemf functions use it) */
- WM_operator_properties_sanitize(opptr, false);
-
- str = WM_operator_pystring_ex(C, NULL, false, false, but->optype, opptr);
-
- /* avoid overly verbose tips (eg, arrays of 20 layers), exact limit is arbitrary */
- WM_operator_pystring_abbreviate(str, 32);
-
- /* operator info */
- if ((U.flag & USER_TOOLTIPS_PYTHON) == 0) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Python: %s"), str);
- data->format[data->totline].style = UI_TIP_STYLE_MONO;
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
- data->totline++;
- }
-
- MEM_freeN(str);
- }
-
- /* button is disabled, we may be able to tell user why */
- if (but->flag & UI_BUT_DISABLED) {
- const char *disabled_msg = NULL;
-
- /* if operator poll check failed, it can give pretty precise info why */
- if (but->optype) {
- CTX_wm_operator_poll_msg_set(C, NULL);
- WM_operator_poll_context(C, but->optype, but->opcontext);
- disabled_msg = CTX_wm_operator_poll_msg_get(C);
- }
- /* alternatively, buttons can store some reasoning too */
- else if (but->disabled_info) {
- disabled_msg = TIP_(but->disabled_info);
- }
-
- if (disabled_msg && disabled_msg[0]) {
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]), TIP_("Disabled: %s"), disabled_msg);
- data->format[data->totline].color_id = UI_TIP_LC_ALERT;
- data->totline++;
- }
- }
-
- if ((U.flag & USER_TOOLTIPS_PYTHON) == 0 && !but->optype && rna_struct.strinfo) {
- if (rna_prop.strinfo) {
- /* Struct and prop */
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
- TIP_("Python: %s.%s"),
- rna_struct.strinfo, rna_prop.strinfo);
- }
- else {
- /* Only struct (e.g. menus) */
- BLI_snprintf(data->lines[data->totline], sizeof(data->lines[0]),
- TIP_("Python: %s"), rna_struct.strinfo);
- }
- data->format[data->totline].style = UI_TIP_STYLE_MONO;
- data->format[data->totline].is_pad = true;
- data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
- data->totline++;
-
- if (but->rnapoin.id.data) {
- /* this could get its own 'BUT_GET_...' type */
-
- /* never fails */
- char *id_path;
-
- if (but->rnaprop) {
- id_path = RNA_path_full_property_py_ex(&but->rnapoin, but->rnaprop, but->rnaindex, true);
- }
- else {
- id_path = RNA_path_full_struct_py(&but->rnapoin);
- }
-
- BLI_strncat_utf8(data->lines[data->totline], id_path, sizeof(data->lines[0]));
- MEM_freeN(id_path);
-
- data->format[data->totline].style = UI_TIP_STYLE_MONO;
- data->format[data->totline].color_id = UI_TIP_LC_PYTHON;
- data->totline++;
- }
- }
-
- /* Free strinfo's... */
- if (but_tip.strinfo)
- MEM_freeN(but_tip.strinfo);
- if (enum_label.strinfo)
- MEM_freeN(enum_label.strinfo);
- if (enum_tip.strinfo)
- MEM_freeN(enum_tip.strinfo);
- if (op_keymap.strinfo)
- MEM_freeN(op_keymap.strinfo);
- if (prop_keymap.strinfo)
- MEM_freeN(prop_keymap.strinfo);
- if (rna_struct.strinfo)
- MEM_freeN(rna_struct.strinfo);
- if (rna_prop.strinfo)
- MEM_freeN(rna_prop.strinfo);
-
- BLI_assert(data->totline < MAX_TOOLTIP_LINES);
-
- if (data->totline == 0) {
- MEM_freeN(data);
- return NULL;
- }
- else {
- return data;
- }
-}
-
-ARegion *ui_tooltip_create(bContext *C, ARegion *butregion, uiBut *but)
-{
- const float pad_px = UI_TIP_PADDING;
- wmWindow *win = CTX_wm_window(C);
- const int winx = WM_window_pixels_x(win);
- uiStyle *style = UI_style_get();
- static ARegionType type;
- ARegion *ar;
-/* IDProperty *prop;*/
- /* aspect values that shrink text are likely unreadable */
- const float aspect = min_ff(1.0f, but->block->aspect);
- int fonth, fontw;
- int ofsx, ofsy, h, i;
- rctf rect_fl;
- rcti rect_i;
- int font_flag = 0;
-
- if (but->drawflag & UI_BUT_NO_TOOLTIP) {
- return NULL;
- }
-
- uiTooltipData *data = ui_tooltip_data_from_button(C, but);
- if (data == NULL) {
- return NULL;
- }
-
- /* create area region */
- ar = ui_region_temp_add(CTX_wm_screen(C));
-
- memset(&type, 0, sizeof(ARegionType));
- type.draw = ui_tooltip_region_draw_cb;
- type.free = ui_tooltip_region_free_cb;
- type.regionid = RGN_TYPE_TEMPORARY;
- ar->type = &type;
-
- /* set font, get bb */
- data->fstyle = style->widget; /* copy struct */
- ui_fontscale(&data->fstyle.points, aspect);
-
- UI_fontstyle_set(&data->fstyle);
-
- data->wrap_width = min_ii(UI_TIP_MAXWIDTH * U.pixelsize / aspect, winx - (UI_TIP_PADDING * 2));
-
- font_flag |= BLF_WORD_WRAP;
- if (data->fstyle.kerning == 1) {
- font_flag |= BLF_KERNING_DEFAULT;
- }
- BLF_enable(data->fstyle.uifont_id, font_flag);
- BLF_enable(blf_mono_font, font_flag);
- BLF_wordwrap(data->fstyle.uifont_id, data->wrap_width);
- BLF_wordwrap(blf_mono_font, data->wrap_width);
-
- /* these defines tweaked depending on font */
-#define TIP_BORDER_X (16.0f / aspect)
-#define TIP_BORDER_Y (6.0f / aspect)
-
- h = BLF_height_max(data->fstyle.uifont_id);
-
- for (i = 0, fontw = 0, fonth = 0; i < data->totline; i++) {
- struct ResultBLF info;
- int w, x_pos = 0;
-
- if (data->format[i].style == UI_TIP_STYLE_HEADER) {
- w = BLF_width_ex(data->fstyle.uifont_id, data->header, sizeof(data->header), &info);
- /* check for enum label */
- if (data->active_info[0]) {
- x_pos = info.width;
- w = max_ii(w, x_pos + BLF_width(data->fstyle.uifont_id, data->active_info, sizeof(data->active_info)));
- }
- }
- else if (data->format[i].style == UI_TIP_STYLE_MONO) {
- BLF_size(blf_mono_font, data->fstyle.points * U.pixelsize, U.dpi);
-
- w = BLF_width_ex(blf_mono_font, data->lines[i], sizeof(data->lines[i]), &info);
- }
- else {
- BLI_assert(data->format[i].style == UI_TIP_STYLE_NORMAL);
-
- w = BLF_width_ex(data->fstyle.uifont_id, data->lines[i], sizeof(data->lines[i]), &info);
- }
-
- fontw = max_ii(fontw, w);
-
- fonth += h * info.lines;
- if ((i + 1 != data->totline) && data->format[i + 1].is_pad) {
- fonth += h * (UI_TIP_PAD_FAC - 1);
- }
-
- data->line_geom[i].lines = info.lines;
- data->line_geom[i].x_pos = x_pos;
- }
-
- //fontw *= aspect;
-
- BLF_disable(data->fstyle.uifont_id, font_flag);
- BLF_disable(blf_mono_font, font_flag);
-
- ar->regiondata = data;
-
- data->toth = fonth;
- data->lineh = h;
-
- /* compute position */
- ofsx = 0; //(but->block->panel) ? but->block->panel->ofsx : 0;
- ofsy = 0; //(but->block->panel) ? but->block->panel->ofsy : 0;
-
- rect_fl.xmin = BLI_rctf_cent_x(&but->rect) + ofsx - TIP_BORDER_X;
- rect_fl.xmax = rect_fl.xmin + fontw + pad_px;
- rect_fl.ymax = but->rect.ymin + ofsy - TIP_BORDER_Y;
- rect_fl.ymin = rect_fl.ymax - fonth - TIP_BORDER_Y;
-
- /* since the text has beens caled already, the size of tooltips is defined now */
- /* here we try to figure out the right location */
- if (butregion) {
- float mx, my;
- float ofsx_fl = rect_fl.xmin, ofsy_fl = rect_fl.ymax;
- ui_block_to_window_fl(butregion, but->block, &ofsx_fl, &ofsy_fl);
-
-#if 1
- /* use X mouse location */
- mx = (win->eventstate->x + (TIP_BORDER_X * 2)) - BLI_rctf_cent_x(&but->rect);
-#else
- mx = ofsx_fl - rect_fl.xmin;
-#endif
- my = ofsy_fl - rect_fl.ymax;
-
- BLI_rctf_translate(&rect_fl, mx, my);
- }
- BLI_rcti_rctf_copy(&rect_i, &rect_fl);
-
-#undef TIP_BORDER_X
-#undef TIP_BORDER_Y
-
- /* clip with window boundaries */
- if (rect_i.xmax > winx) {
- /* super size */
- if (rect_i.xmax > winx + rect_i.xmin) {
- rect_i.xmax = winx;
- rect_i.xmin = 0;
- }
- else {
- rect_i.xmin -= rect_i.xmax - winx;
- rect_i.xmax = winx;
- }
- }
- /* ensure at least 5 px above screen bounds
- * 25 is just a guess to be above the menu item */
- if (rect_i.ymin < 5) {
- rect_i.ymax += (-rect_i.ymin) + 30;
- rect_i.ymin = 30;
- }
-
- /* add padding */
- BLI_rcti_resize(&rect_i,
- BLI_rcti_size_x(&rect_i) + pad_px,
- BLI_rcti_size_y(&rect_i) + pad_px);
-
- /* widget rect, in region coords */
- {
- const int margin = UI_POPUP_MARGIN;
-
- data->bbox.xmin = margin;
- data->bbox.xmax = BLI_rcti_size_x(&rect_i) - margin;
- data->bbox.ymin = margin;
- data->bbox.ymax = BLI_rcti_size_y(&rect_i);
-
- /* region bigger for shadow */
- ar->winrct.xmin = rect_i.xmin - margin;
- ar->winrct.xmax = rect_i.xmax + margin;
- ar->winrct.ymin = rect_i.ymin - margin;
- ar->winrct.ymax = rect_i.ymax + margin;
- }
-
- /* adds subwindow */
- ED_region_init(C, ar);
-
- /* notify change and redraw */
- ED_region_tag_redraw(ar);
-
- return ar;
-}
-
-void ui_tooltip_free(bContext *C, ARegion *ar)
-{
- ui_region_temp_remove(C, CTX_wm_screen(C), ar);
-}
-
-
-/************************* Creating Search Box **********************/
-
-struct uiSearchItems {
- int maxitem, totitem, maxstrlen;
-
- int offset, offset_i; /* offset for inserting in array */
- int more; /* flag indicating there are more items */
-
- char **names;
- void **pointers;
- int *icons;
-
- AutoComplete *autocpl;
- void *active;
-};
-
-typedef struct uiSearchboxData {
- rcti bbox;
- uiFontStyle fstyle;
- uiSearchItems items;
- int active; /* index in items array */
- bool noback; /* when menu opened with enough space for this */
- bool preview; /* draw thumbnail previews, rather than list */
- bool use_sep; /* use the UI_SEP_CHAR char for splitting shortcuts (good for operators, bad for data) */
- int prv_rows, prv_cols;
-} uiSearchboxData;
-
-#define SEARCH_ITEMS 10
-
-/* exported for use by search callbacks */
-/* returns zero if nothing to add */
-bool UI_search_item_add(uiSearchItems *items, const char *name, void *poin, int iconid)
-{
- /* hijack for autocomplete */
- if (items->autocpl) {
- UI_autocomplete_update_name(items->autocpl, name);
- return true;
- }
-
- /* hijack for finding active item */
- if (items->active) {
- if (poin == items->active)
- items->offset_i = items->totitem;
- items->totitem++;
- return true;
- }
-
- if (items->totitem >= items->maxitem) {
- items->more = 1;
- return false;
- }
-
- /* skip first items in list */
- if (items->offset_i > 0) {
- items->offset_i--;
- return true;
- }
-
- if (items->names)
- BLI_strncpy(items->names[items->totitem], name, items->maxstrlen);
- if (items->pointers)
- items->pointers[items->totitem] = poin;
- if (items->icons)
- items->icons[items->totitem] = iconid;
-
- items->totitem++;
-
- return true;
-}
-
-int UI_searchbox_size_y(void)
-{
- return SEARCH_ITEMS * UI_UNIT_Y + 2 * UI_POPUP_MENU_TOP;
-}
-
-int UI_searchbox_size_x(void)
-{
- return 12 * UI_UNIT_X;
-}
-
-int UI_search_items_find_index(uiSearchItems *items, const char *name)
-{
- int i;
- for (i = 0; i < items->totitem; i++) {
- if (STREQ(name, items->names[i])) {
- return i;
- }
- }
- return -1;
-}
-
-/* ar is the search box itself */
-static void ui_searchbox_select(bContext *C, ARegion *ar, uiBut *but, int step)
-{
- uiSearchboxData *data = ar->regiondata;
-
- /* apply step */
- data->active += step;
-
- if (data->items.totitem == 0) {
- data->active = -1;
- }
- else if (data->active >= data->items.totitem) {
- if (data->items.more) {
- data->items.offset++;
- data->active = data->items.totitem - 1;
- ui_searchbox_update(C, ar, but, false);
- }
- else {
- data->active = data->items.totitem - 1;
- }
- }
- else if (data->active < 0) {
- if (data->items.offset) {
- data->items.offset--;
- data->active = 0;
- ui_searchbox_update(C, ar, but, false);
- }
- else {
- /* only let users step into an 'unset' state for unlink buttons */
- data->active = (but->flag & UI_BUT_VALUE_CLEAR) ? -1 : 0;
- }
- }
-
- ED_region_tag_redraw(ar);
-}
-
-static void ui_searchbox_butrect(rcti *r_rect, uiSearchboxData *data, int itemnr)
-{
- /* thumbnail preview */
- if (data->preview) {
- int butw = (BLI_rcti_size_x(&data->bbox) - 2 * MENU_BORDER) / data->prv_cols;
- int buth = (BLI_rcti_size_y(&data->bbox) - 2 * MENU_BORDER) / data->prv_rows;
- int row, col;
-
- *r_rect = data->bbox;
-
- col = itemnr % data->prv_cols;
- row = itemnr / data->prv_cols;
-
- r_rect->xmin += MENU_BORDER + (col * butw);
- r_rect->xmax = r_rect->xmin + butw;
-
- r_rect->ymax -= MENU_BORDER + (row * buth);
- r_rect->ymin = r_rect->ymax - buth;
- }
- /* list view */
- else {
- int buth = (BLI_rcti_size_y(&data->bbox) - 2 * UI_POPUP_MENU_TOP) / SEARCH_ITEMS;
-
- *r_rect = data->bbox;
- r_rect->xmin = data->bbox.xmin + 3.0f;
- r_rect->xmax = data->bbox.xmax - 3.0f;
-
- r_rect->ymax = data->bbox.ymax - UI_POPUP_MENU_TOP - itemnr * buth;
- r_rect->ymin = r_rect->ymax - buth;
- }
-
-}
-
-int ui_searchbox_find_index(ARegion *ar, const char *name)
-{
- uiSearchboxData *data = ar->regiondata;
- return UI_search_items_find_index(&data->items, name);
-}
-
-/* x and y in screencoords */
-bool ui_searchbox_inside(ARegion *ar, int x, int y)
-{
- uiSearchboxData *data = ar->regiondata;
-
- return BLI_rcti_isect_pt(&data->bbox, x - ar->winrct.xmin, y - ar->winrct.ymin);
-}
-
-/* string validated to be of correct length (but->hardmax) */
-bool ui_searchbox_apply(uiBut *but, ARegion *ar)
-{
- uiSearchboxData *data = ar->regiondata;
-
- but->func_arg2 = NULL;
-
- if (data->active != -1) {
- const char *name = data->items.names[data->active];
- const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
-
- BLI_strncpy(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen);
-
- but->func_arg2 = data->items.pointers[data->active];
-
- return true;
- }
- else if (but->flag & UI_BUT_VALUE_CLEAR) {
- /* It is valid for _VALUE_CLEAR flavor to have no active element (it's a valid way to unlink). */
- but->editstr[0] = '\0';
-
- return true;
- }
- else {
- return false;
- }
-}
-
-void ui_searchbox_event(bContext *C, ARegion *ar, uiBut *but, const wmEvent *event)
-{
- uiSearchboxData *data = ar->regiondata;
- int type = event->type, val = event->val;
-
- if (type == MOUSEPAN)
- ui_pan_to_scroll(event, &type, &val);
-
- switch (type) {
- case WHEELUPMOUSE:
- case UPARROWKEY:
- ui_searchbox_select(C, ar, but, -1);
- break;
- case WHEELDOWNMOUSE:
- case DOWNARROWKEY:
- ui_searchbox_select(C, ar, but, 1);
- break;
- case MOUSEMOVE:
- if (BLI_rcti_isect_pt(&ar->winrct, event->x, event->y)) {
- rcti rect;
- int a;
-
- for (a = 0; a < data->items.totitem; a++) {
- ui_searchbox_butrect(&rect, data, a);
- if (BLI_rcti_isect_pt(&rect, event->x - ar->winrct.xmin, event->y - ar->winrct.ymin)) {
- if (data->active != a) {
- data->active = a;
- ui_searchbox_select(C, ar, but, 0);
- break;
- }
- }
- }
- }
- break;
- }
-}
-
-/* ar is the search box itself */
-void ui_searchbox_update(bContext *C, ARegion *ar, uiBut *but, const bool reset)
-{
- uiSearchboxData *data = ar->regiondata;
-
- /* reset vars */
- data->items.totitem = 0;
- data->items.more = 0;
- if (reset == false) {
- data->items.offset_i = data->items.offset;
- }
- else {
- data->items.offset_i = data->items.offset = 0;
- data->active = -1;
-
- /* handle active */
- if (but->search_func && but->func_arg2) {
- data->items.active = but->func_arg2;
- but->search_func(C, but->search_arg, but->editstr, &data->items);
- data->items.active = NULL;
-
- /* found active item, calculate real offset by centering it */
- if (data->items.totitem) {
- /* first case, begin of list */
- if (data->items.offset_i < data->items.maxitem) {
- data->active = data->items.offset_i;
- data->items.offset_i = 0;
- }
- else {
- /* second case, end of list */
- if (data->items.totitem - data->items.offset_i <= data->items.maxitem) {
- data->active = data->items.offset_i - data->items.totitem + data->items.maxitem;
- data->items.offset_i = data->items.totitem - data->items.maxitem;
- }
- else {
- /* center active item */
- data->items.offset_i -= data->items.maxitem / 2;
- data->active = data->items.maxitem / 2;
- }
- }
- }
- data->items.offset = data->items.offset_i;
- data->items.totitem = 0;
- }
- }
-
- /* callback */
- if (but->search_func)
- but->search_func(C, but->search_arg, but->editstr, &data->items);
-
- /* handle case where editstr is equal to one of items */
- if (reset && data->active == -1) {
- int a;
-
- for (a = 0; a < data->items.totitem; a++) {
- const char *name = data->items.names[a];
- const char *name_sep = data->use_sep ? strrchr(name, UI_SEP_CHAR) : NULL;
- if (STREQLEN(but->editstr, name, name_sep ? (name_sep - name) : data->items.maxstrlen)) {
- data->active = a;
- break;
- }
- }
- if (data->items.totitem == 1 && but->editstr[0])
- data->active = 0;
- }
-
- /* validate selected item */
- ui_searchbox_select(C, ar, but, 0);
-
- ED_region_tag_redraw(ar);
-}
-
-int ui_searchbox_autocomplete(bContext *C, ARegion *ar, uiBut *but, char *str)
-{
- uiSearchboxData *data = ar->regiondata;
- int match = AUTOCOMPLETE_NO_MATCH;
-
- if (str[0]) {
- data->items.autocpl = UI_autocomplete_begin(str, ui_but_string_get_max_length(but));
-
- but->search_func(C, but->search_arg, but->editstr, &data->items);
-
- match = UI_autocomplete_end(data->items.autocpl, str);
- data->items.autocpl = NULL;
- }
-
- return match;
-}
-
-static void ui_searchbox_region_draw_cb(const bContext *UNUSED(C), ARegion *ar)
-{
- uiSearchboxData *data = ar->regiondata;
-
- /* pixel space */
- wmOrtho2_region_pixelspace(ar);
-
- if (data->noback == false)
- ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */
-
- /* draw text */
- if (data->items.totitem) {
- rcti rect;
- int a;
-
- if (data->preview) {
- /* draw items */
- for (a = 0; a < data->items.totitem; a++) {
- ui_searchbox_butrect(&rect, data, a);
-
- /* widget itself */
- ui_draw_preview_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
- (a == data->active) ? UI_ACTIVE : 0);
- }
-
- /* indicate more */
- if (data->items.more) {
- ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
- glEnable(GL_BLEND);
- UI_icon_draw(rect.xmax - 18, rect.ymin - 7, ICON_TRIA_DOWN);
- glDisable(GL_BLEND);
- }
- if (data->items.offset) {
- ui_searchbox_butrect(&rect, data, 0);
- glEnable(GL_BLEND);
- UI_icon_draw(rect.xmin, rect.ymax - 9, ICON_TRIA_UP);
- glDisable(GL_BLEND);
- }
-
- }
- else {
- /* draw items */
- for (a = 0; a < data->items.totitem; a++) {
- ui_searchbox_butrect(&rect, data, a);
-
- /* widget itself */
- ui_draw_menu_item(&data->fstyle, &rect, data->items.names[a], data->items.icons[a],
- (a == data->active) ? UI_ACTIVE : 0, data->use_sep);
-
- }
- /* indicate more */
- if (data->items.more) {
- ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
- glEnable(GL_BLEND);
- UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
- glDisable(GL_BLEND);
- }
- if (data->items.offset) {
- ui_searchbox_butrect(&rect, data, 0);
- glEnable(GL_BLEND);
- UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
- glDisable(GL_BLEND);
- }
- }
- }
-}
-
-static void ui_searchbox_region_free_cb(ARegion *ar)
-{
- uiSearchboxData *data = ar->regiondata;
- int a;
-
- /* free search data */
- for (a = 0; a < data->items.maxitem; a++) {
- MEM_freeN(data->items.names[a]);
- }
- MEM_freeN(data->items.names);
- MEM_freeN(data->items.pointers);
- MEM_freeN(data->items.icons);
-
- MEM_freeN(data);
- ar->regiondata = NULL;
-}
-
-ARegion *ui_searchbox_create_generic(bContext *C, ARegion *butregion, uiBut *but)
-{
- wmWindow *win = CTX_wm_window(C);
- uiStyle *style = UI_style_get();
- static ARegionType type;
- ARegion *ar;
- uiSearchboxData *data;
- float aspect = but->block->aspect;
- rctf rect_fl;
- rcti rect_i;
- const int margin = UI_POPUP_MARGIN;
- int winx /*, winy */, ofsx, ofsy;
- int i;
-
- /* create area region */
- ar = ui_region_temp_add(CTX_wm_screen(C));
-
- memset(&type, 0, sizeof(ARegionType));
- type.draw = ui_searchbox_region_draw_cb;
- type.free = ui_searchbox_region_free_cb;
- type.regionid = RGN_TYPE_TEMPORARY;
- ar->type = &type;
-
- /* create searchbox data */
- data = MEM_callocN(sizeof(uiSearchboxData), "uiSearchboxData");
-
- /* set font, get bb */
- data->fstyle = style->widget; /* copy struct */
- data->fstyle.align = UI_STYLE_TEXT_CENTER;
- ui_fontscale(&data->fstyle.points, aspect);
- UI_fontstyle_set(&data->fstyle);
-
- ar->regiondata = data;
-
- /* special case, hardcoded feature, not draw backdrop when called from menus,
- * assume for design that popup already added it */
- if (but->block->flag & UI_BLOCK_SEARCH_MENU)
- data->noback = true;
-
- if (but->a1 > 0 && but->a2 > 0) {
- data->preview = true;
- data->prv_rows = but->a1;
- data->prv_cols = but->a2;
- }
-
- /* only show key shortcuts when needed (not rna buttons) [#36699] */
- if (but->rnaprop == NULL) {
- data->use_sep = true;
- }
-
- /* compute position */
- if (but->block->flag & UI_BLOCK_SEARCH_MENU) {
- const int search_but_h = BLI_rctf_size_y(&but->rect) + 10;
- /* this case is search menu inside other menu */
- /* we copy region size */
-
- ar->winrct = butregion->winrct;
-
- /* widget rect, in region coords */
- data->bbox.xmin = margin;
- data->bbox.xmax = BLI_rcti_size_x(&ar->winrct) - margin;
- data->bbox.ymin = margin;
- data->bbox.ymax = BLI_rcti_size_y(&ar->winrct) - margin;
-
- /* check if button is lower half */
- if (but->rect.ymax < BLI_rctf_cent_y(&but->block->rect)) {
- data->bbox.ymin += search_but_h;
- }
- else {
- data->bbox.ymax -= search_but_h;
- }
- }
- else {
- const int searchbox_width = UI_searchbox_size_x();
-
- rect_fl.xmin = but->rect.xmin - 5; /* align text with button */
- rect_fl.xmax = but->rect.xmax + 5; /* symmetrical */
- rect_fl.ymax = but->rect.ymin;
- rect_fl.ymin = rect_fl.ymax - UI_searchbox_size_y();
-
- ofsx = (but->block->panel) ? but->block->panel->ofsx : 0;
- ofsy = (but->block->panel) ? but->block->panel->ofsy : 0;
-
- BLI_rctf_translate(&rect_fl, ofsx, ofsy);
-
- /* minimal width */
- if (BLI_rctf_size_x(&rect_fl) < searchbox_width) {
- rect_fl.xmax = rect_fl.xmin + searchbox_width;
- }
-
- /* copy to int, gets projected if possible too */
- BLI_rcti_rctf_copy(&rect_i, &rect_fl);
-
- if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax) {
- UI_view2d_view_to_region_rcti(&butregion->v2d, &rect_fl, &rect_i);
- }
-
- BLI_rcti_translate(&rect_i, butregion->winrct.xmin, butregion->winrct.ymin);
-
- winx = WM_window_pixels_x(win);
- // winy = WM_window_pixels_y(win); /* UNUSED */
- //wm_window_get_size(win, &winx, &winy);
-
- if (rect_i.xmax > winx) {
- /* super size */
- if (rect_i.xmax > winx + rect_i.xmin) {
- rect_i.xmax = winx;
- rect_i.xmin = 0;
- }
- else {
- rect_i.xmin -= rect_i.xmax - winx;
- rect_i.xmax = winx;
- }
- }
-
- if (rect_i.ymin < 0) {
- int newy1 = but->rect.ymax + ofsy;
-
- if (butregion->v2d.cur.xmin != butregion->v2d.cur.xmax)
- newy1 = UI_view2d_view_to_region_y(&butregion->v2d, newy1);
-
- newy1 += butregion->winrct.ymin;
-
- rect_i.ymax = BLI_rcti_size_y(&rect_i) + newy1;
- rect_i.ymin = newy1;
- }
-
- /* widget rect, in region coords */
- data->bbox.xmin = margin;
- data->bbox.xmax = BLI_rcti_size_x(&rect_i) + margin;
- data->bbox.ymin = margin;
- data->bbox.ymax = BLI_rcti_size_y(&rect_i) + margin;
-
- /* region bigger for shadow */
- ar->winrct.xmin = rect_i.xmin - margin;
- ar->winrct.xmax = rect_i.xmax + margin;
- ar->winrct.ymin = rect_i.ymin - margin;
- ar->winrct.ymax = rect_i.ymax;
- }
-
- /* adds subwindow */
- ED_region_init(C, ar);
-
- /* notify change and redraw */
- ED_region_tag_redraw(ar);
-
- /* prepare search data */
- if (data->preview) {
- data->items.maxitem = data->prv_rows * data->prv_cols;
- }
- else {
- data->items.maxitem = SEARCH_ITEMS;
- }
- data->items.maxstrlen = but->hardmax;
- data->items.totitem = 0;
- data->items.names = MEM_callocN(data->items.maxitem * sizeof(void *), "search names");
- data->items.pointers = MEM_callocN(data->items.maxitem * sizeof(void *), "search pointers");
- data->items.icons = MEM_callocN(data->items.maxitem * sizeof(int), "search icons");
- for (i = 0; i < data->items.maxitem; i++)
- data->items.names[i] = MEM_callocN(but->hardmax + 1, "search pointers");
-
- return ar;
-}
-
-/**
- * Similar to Python's `str.title` except...
- *
- * - we know words are upper case and ascii only.
- * - '_' are replaces by spaces.
- */
-static void str_tolower_titlecaps_ascii(char *str, const size_t len)
-{
- size_t i;
- bool prev_delim = true;
-
- for (i = 0; (i < len) && str[i]; i++) {
- if (str[i] >= 'A' && str[i] <= 'Z') {
- if (prev_delim == false) {
- str[i] += 'a' - 'A';
- }
- }
- else if (str[i] == '_') {
- str[i] = ' ';
- }
-
- prev_delim = ELEM(str[i], ' ') || (str[i] >= '0' && str[i] <= '9');
- }
-
-}
-
-static void ui_searchbox_region_draw_cb__operator(const bContext *UNUSED(C), ARegion *ar)
-{
- uiSearchboxData *data = ar->regiondata;
-
- /* pixel space */
- wmOrtho2_region_pixelspace(ar);
-
- if (data->noback == false)
- ui_draw_search_back(NULL, NULL, &data->bbox); /* style not used yet */
-
- /* draw text */
- if (data->items.totitem) {
- rcti rect;
- int a;
-
- /* draw items */
- for (a = 0; a < data->items.totitem; a++) {
- rcti rect_pre, rect_post;
- ui_searchbox_butrect(&rect, data, a);
-
- rect_pre = rect;
- rect_post = rect;
-
- rect_pre.xmax = rect_post.xmin = rect.xmin + ((rect.xmax - rect.xmin) / 4);
-
- /* widget itself */
- /* NOTE: i18n messages extracting tool does the same, please keep it in sync. */
- {
- wmOperatorType *ot = data->items.pointers[a];
-
- int state = (a == data->active) ? UI_ACTIVE : 0;
- char text_pre[128];
- char *text_pre_p = strstr(ot->idname, "_OT_");
- if (text_pre_p == NULL) {
- text_pre[0] = '\0';
- }
- else {
- int text_pre_len;
- text_pre_p += 1;
- text_pre_len = BLI_strncpy_rlen(
- text_pre, ot->idname, min_ii(sizeof(text_pre), text_pre_p - ot->idname));
- text_pre[text_pre_len] = ':';
- text_pre[text_pre_len + 1] = '\0';
- str_tolower_titlecaps_ascii(text_pre, sizeof(text_pre));
- }
-
- rect_pre.xmax += 4; /* sneaky, avoid showing ugly margin */
- ui_draw_menu_item(&data->fstyle, &rect_pre, CTX_IFACE_(BLT_I18NCONTEXT_OPERATOR_DEFAULT, text_pre),
- data->items.icons[a], state, false);
- ui_draw_menu_item(&data->fstyle, &rect_post, data->items.names[a], 0, state, data->use_sep);
- }
-
- }
- /* indicate more */
- if (data->items.more) {
- ui_searchbox_butrect(&rect, data, data->items.maxitem - 1);
- glEnable(GL_BLEND);
- UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymin - 9, ICON_TRIA_DOWN);
- glDisable(GL_BLEND);
- }
- if (data->items.offset) {
- ui_searchbox_butrect(&rect, data, 0);
- glEnable(GL_BLEND);
- UI_icon_draw((BLI_rcti_size_x(&rect)) / 2, rect.ymax - 7, ICON_TRIA_UP);
- glDisable(GL_BLEND);
- }
- }
-}
-
-ARegion *ui_searchbox_create_operator(bContext *C, ARegion *butregion, uiBut *but)
-{
- ARegion *ar;
-
- ar = ui_searchbox_create_generic(C, butregion, but);
-
- ar->type->draw = ui_searchbox_region_draw_cb__operator;
-
- return ar;
-}
-
-void ui_searchbox_free(bContext *C, ARegion *ar)
-{
- ui_region_temp_remove(C, CTX_wm_screen(C), ar);
-}
-
-/* sets red alert if button holds a string it can't find */
-/* XXX weak: search_func adds all partial matches... */
-void ui_but_search_refresh(uiBut *but)
-{
- uiSearchItems *items;
- int x1;
-
- /* possibly very large lists (such as ID datablocks) only
- * only validate string RNA buts (not pointers) */
- if (but->rnaprop && RNA_property_type(but->rnaprop) != PROP_STRING) {
- return;
- }
-
- items = MEM_callocN(sizeof(uiSearchItems), "search items");
-
- /* setup search struct */
- items->maxitem = 10;
- items->maxstrlen = 256;
- items->names = MEM_callocN(items->maxitem * sizeof(void *), "search names");
- for (x1 = 0; x1 < items->maxitem; x1++)
- items->names[x1] = MEM_callocN(but->hardmax + 1, "search names");
-
- but->search_func(but->block->evil_C, but->search_arg, but->drawstr, items);
-
- /* only redalert when we are sure of it, this can miss cases when >10 matches */
- if (items->totitem == 0) {
- UI_but_flag_enable(but, UI_BUT_REDALERT);
- }
- else if (items->more == 0) {
- if (UI_search_items_find_index(items, but->drawstr) == -1) {
- UI_but_flag_enable(but, UI_BUT_REDALERT);
- }
- }
-
- for (x1 = 0; x1 < items->maxitem; x1++) {
- MEM_freeN(items->names[x1]);
- }
- MEM_freeN(items->names);
- MEM_freeN(items);
-}
-
-
-/************************* Creating Menu Blocks **********************/
-
-/* position block relative to but, result is in window space */
-static void ui_block_position(wmWindow *window, ARegion *butregion, uiBut *but, uiBlock *block)
-{
- uiBut *bt;
- uiSafetyRct *saferct;
- rctf butrct;
- /*float aspect;*/ /*UNUSED*/
- int xsize, ysize, xof = 0, yof = 0, center;
- short dir1 = 0, dir2 = 0;
-
- /* transform to window coordinates, using the source button region/block */
- ui_block_to_window_rctf(butregion, but->block, &butrct, &but->rect);
-
- /* widget_roundbox_set has this correction too, keep in sync */
- if (but->type != UI_BTYPE_PULLDOWN) {
- if (but->drawflag & UI_BUT_ALIGN_TOP)
- butrct.ymax += U.pixelsize;
- if (but->drawflag & UI_BUT_ALIGN_LEFT)
- butrct.xmin -= U.pixelsize;
- }
-
- /* calc block rect */
- if (block->rect.xmin == 0.0f && block->rect.xmax == 0.0f) {
- if (block->buttons.first) {
- BLI_rctf_init_minmax(&block->rect);
-
- for (bt = block->buttons.first; bt; bt = bt->next) {
- BLI_rctf_union(&block->rect, &bt->rect);
- }
- }
- else {
- /* we're nice and allow empty blocks too */
- block->rect.xmin = block->rect.ymin = 0;
- block->rect.xmax = block->rect.ymax = 20;
- }
- }
-
- /* aspect = (float)(BLI_rcti_size_x(&block->rect) + 4);*/ /*UNUSED*/
- ui_block_to_window_rctf(butregion, but->block, &block->rect, &block->rect);
-
- //block->rect.xmin -= 2.0; block->rect.ymin -= 2.0;
- //block->rect.xmax += 2.0; block->rect.ymax += 2.0;
-
- xsize = BLI_rctf_size_x(&block->rect) + 0.2f * UI_UNIT_X; /* 4 for shadow */
- ysize = BLI_rctf_size_y(&block->rect) + 0.2f * UI_UNIT_Y;
- /* aspect /= (float)xsize;*/ /*UNUSED*/
-
- {
- bool left = 0, right = 0, top = 0, down = 0;
- int winx, winy;
- // int offscreen;
-
- winx = WM_window_pixels_x(window);
- winy = WM_window_pixels_y(window);
- // wm_window_get_size(window, &winx, &winy);
-
- if (block->direction & UI_DIR_CENTER_Y) {
- center = ysize / 2;
- }
- else {
- center = 0;
- }
-
- /* check if there's space at all */
- if (butrct.xmin - xsize > 0.0f) left = 1;
- if (butrct.xmax + xsize < winx) right = 1;
- if (butrct.ymin - ysize + center > 0.0f) down = 1;
- if (butrct.ymax + ysize - center < winy) top = 1;
-
- if (top == 0 && down == 0) {
- if (butrct.ymin - ysize < winy - butrct.ymax - ysize)
- top = 1;
- else
- down = 1;
- }
-
- dir1 = (block->direction & UI_DIR_ALL);
-
- /* secundary directions */
- if (dir1 & (UI_DIR_UP | UI_DIR_DOWN)) {
- if (dir1 & UI_DIR_LEFT) dir2 = UI_DIR_LEFT;
- else if (dir1 & UI_DIR_RIGHT) dir2 = UI_DIR_RIGHT;
- dir1 &= (UI_DIR_UP | UI_DIR_DOWN);
- }
-
- if ((dir2 == 0) && (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT)) dir2 = UI_DIR_DOWN;
- if ((dir2 == 0) && (dir1 == UI_DIR_UP || dir1 == UI_DIR_DOWN)) dir2 = UI_DIR_LEFT;
-
- /* no space at all? don't change */
- if (left || right) {
- if (dir1 == UI_DIR_LEFT && left == 0) dir1 = UI_DIR_RIGHT;
- if (dir1 == UI_DIR_RIGHT && right == 0) dir1 = UI_DIR_LEFT;
- /* this is aligning, not append! */
- if (dir2 == UI_DIR_LEFT && right == 0) dir2 = UI_DIR_RIGHT;
- if (dir2 == UI_DIR_RIGHT && left == 0) dir2 = UI_DIR_LEFT;
- }
- if (down || top) {
- if (dir1 == UI_DIR_UP && top == 0) dir1 = UI_DIR_DOWN;
- if (dir1 == UI_DIR_DOWN && down == 0) dir1 = UI_DIR_UP;
- BLI_assert(dir2 != UI_DIR_UP);
-// if (dir2 == UI_DIR_UP && top == 0) dir2 = UI_DIR_DOWN;
- if (dir2 == UI_DIR_DOWN && down == 0) dir2 = UI_DIR_UP;
- }
-
- if (dir1 == UI_DIR_LEFT) {
- xof = butrct.xmin - block->rect.xmax;
- if (dir2 == UI_DIR_UP) yof = butrct.ymin - block->rect.ymin - center - MENU_PADDING;
- else yof = butrct.ymax - block->rect.ymax + center + MENU_PADDING;
- }
- else if (dir1 == UI_DIR_RIGHT) {
- xof = butrct.xmax - block->rect.xmin;
- if (dir2 == UI_DIR_UP) yof = butrct.ymin - block->rect.ymin - center - MENU_PADDING;
- else yof = butrct.ymax - block->rect.ymax + center + MENU_PADDING;
- }
- else if (dir1 == UI_DIR_UP) {
- yof = butrct.ymax - block->rect.ymin;
- if (dir2 == UI_DIR_RIGHT) xof = butrct.xmax - block->rect.xmax;
- else xof = butrct.xmin - block->rect.xmin;
- /* changed direction? */
- if ((dir1 & block->direction) == 0) {
- UI_block_order_flip(block);
- }
- }
- else if (dir1 == UI_DIR_DOWN) {
- yof = butrct.ymin - block->rect.ymax;
- if (dir2 == UI_DIR_RIGHT) xof = butrct.xmax - block->rect.xmax;
- else xof = butrct.xmin - block->rect.xmin;
- /* changed direction? */
- if ((dir1 & block->direction) == 0) {
- UI_block_order_flip(block);
- }
- }
-
- /* and now we handle the exception; no space below or to top */
- if (top == 0 && down == 0) {
- if (dir1 == UI_DIR_LEFT || dir1 == UI_DIR_RIGHT) {
- /* align with bottom of screen */
- // yof = ysize; (not with menu scrolls)
- }
- }
-
-#if 0 /* seems redundant and causes issues with blocks inside big regions */
- /* or no space left or right */
- if (left == 0 && right == 0) {
- if (dir1 == UI_DIR_UP || dir1 == UI_DIR_DOWN) {
- /* align with left size of screen */
- xof = -block->rect.xmin + 5;
- }
- }
-#endif
-
-#if 0
- /* clamp to window bounds, could be made into an option if its ever annoying */
- if ( (offscreen = (block->rect.ymin + yof)) < 0) yof -= offscreen; /* bottom */
- else if ((offscreen = (block->rect.ymax + yof) - winy) > 0) yof -= offscreen; /* top */
- if ( (offscreen = (block->rect.xmin + xof)) < 0) xof -= offscreen; /* left */
- else if ((offscreen = (block->rect.xmax + xof) - winx) > 0) xof -= offscreen; /* right */
-#endif
- }
-
- /* apply offset, buttons in window coords */
-
- for (bt = block->buttons.first; bt; bt = bt->next) {
- ui_block_to_window_rctf(butregion, but->block, &bt->rect, &bt->rect);
-
- BLI_rctf_translate(&bt->rect, xof, yof);
-
- /* ui_but_update recalculates drawstring size in pixels */
- ui_but_update(bt);
- }
-
- BLI_rctf_translate(&block->rect, xof, yof);
-
- /* safety calculus */
- {
- const float midx = BLI_rctf_cent_x(&butrct);
- const float midy = BLI_rctf_cent_y(&butrct);
-
- /* when you are outside parent button, safety there should be smaller */
-
- /* parent button to left */
- if (midx < block->rect.xmin) block->safety.xmin = block->rect.xmin - 3;
- else block->safety.xmin = block->rect.xmin - 40;
- /* parent button to right */
- if (midx > block->rect.xmax) block->safety.xmax = block->rect.xmax + 3;
- else block->safety.xmax = block->rect.xmax + 40;
-
- /* parent button on bottom */
- if (midy < block->rect.ymin) block->safety.ymin = block->rect.ymin - 3;
- else block->safety.ymin = block->rect.ymin - 40;
- /* parent button on top */
- if (midy > block->rect.ymax) block->safety.ymax = block->rect.ymax + 3;
- else block->safety.ymax = block->rect.ymax + 40;
-
- /* exception for switched pulldowns... */
- if (dir1 && (dir1 & block->direction) == 0) {
- if (dir2 == UI_DIR_RIGHT) block->safety.xmax = block->rect.xmax + 3;
- if (dir2 == UI_DIR_LEFT) block->safety.xmin = block->rect.xmin - 3;
- }
- block->direction = dir1;
- }
-
- /* keep a list of these, needed for pulldown menus */
- saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
- saferct->parent = butrct;
- saferct->safety = block->safety;
- BLI_freelistN(&block->saferct);
- BLI_duplicatelist(&block->saferct, &but->block->saferct);
- BLI_addhead(&block->saferct, saferct);
-}
-
-static void ui_block_region_draw(const bContext *C, ARegion *ar)
-{
- uiBlock *block;
-
- if (ar->do_draw & RGN_DRAW_REFRESH_UI) {
- uiBlock *block_next;
- ar->do_draw &= ~RGN_DRAW_REFRESH_UI;
- for (block = ar->uiblocks.first; block; block = block_next) {
- block_next = block->next;
- if (block->handle->can_refresh) {
- ui_popup_block_refresh((bContext *)C, block->handle, NULL, NULL);
- }
- }
- }
-
- for (block = ar->uiblocks.first; block; block = block->next)
- UI_block_draw(C, block);
-}
-
-static void ui_popup_block_clip(wmWindow *window, uiBlock *block)
-{
- uiBut *bt;
- float xofs = 0.0f;
- int width = UI_SCREEN_MARGIN;
- int winx, winy;
-
- if (block->flag & UI_BLOCK_NO_WIN_CLIP) {
- return;
- }
-
- winx = WM_window_pixels_x(window);
- winy = WM_window_pixels_y(window);
-
- /* shift menus to right if outside of view */
- if (block->rect.xmin < width) {
- xofs = (width - block->rect.xmin);
- block->rect.xmin += xofs;
- block->rect.xmax += xofs;
- }
- /* or shift to left if outside of view */
- if (block->rect.xmax > winx - width) {
- xofs = winx - width - block->rect.xmax;
- block->rect.xmin += xofs;
- block->rect.xmax += xofs;
- }
-
- if (block->rect.ymin < width)
- block->rect.ymin = width;
- if (block->rect.ymax > winy - UI_POPUP_MENU_TOP)
- block->rect.ymax = winy - UI_POPUP_MENU_TOP;
-
- /* ensure menu items draw inside left/right boundary */
- for (bt = block->buttons.first; bt; bt = bt->next) {
- bt->rect.xmin += xofs;
- bt->rect.xmax += xofs;
- }
-
-}
-
-void ui_popup_block_scrolltest(uiBlock *block)
-{
- uiBut *bt;
-
- block->flag &= ~(UI_BLOCK_CLIPBOTTOM | UI_BLOCK_CLIPTOP);
-
- for (bt = block->buttons.first; bt; bt = bt->next)
- bt->flag &= ~UI_SCROLLED;
-
- if (block->buttons.first == block->buttons.last)
- return;
-
- /* mark buttons that are outside boundary */
- for (bt = block->buttons.first; bt; bt = bt->next) {
- if (bt->rect.ymin < block->rect.ymin) {
- bt->flag |= UI_SCROLLED;
- block->flag |= UI_BLOCK_CLIPBOTTOM;
- }
- if (bt->rect.ymax > block->rect.ymax) {
- bt->flag |= UI_SCROLLED;
- block->flag |= UI_BLOCK_CLIPTOP;
- }
- }
-
- /* mark buttons overlapping arrows, if we have them */
- for (bt = block->buttons.first; bt; bt = bt->next) {
- if (block->flag & UI_BLOCK_CLIPBOTTOM) {
- if (bt->rect.ymin < block->rect.ymin + UI_MENU_SCROLL_ARROW)
- bt->flag |= UI_SCROLLED;
- }
- if (block->flag & UI_BLOCK_CLIPTOP) {
- if (bt->rect.ymax > block->rect.ymax - UI_MENU_SCROLL_ARROW)
- bt->flag |= UI_SCROLLED;
- }
- }
-}
-
-static void ui_popup_block_remove(bContext *C, uiPopupBlockHandle *handle)
-{
- wmWindow *win = CTX_wm_window(C);
- bScreen *sc = CTX_wm_screen(C);
-
- ui_region_temp_remove(C, sc, handle->region);
-
- /* reset to region cursor (only if there's not another menu open) */
- if (BLI_listbase_is_empty(&sc->regionbase)) {
- ED_region_cursor_set(win, CTX_wm_area(C), CTX_wm_region(C));
- /* in case cursor needs to be changed again */
- WM_event_add_mousemove(C);
- }
-
- if (handle->scrolltimer)
- WM_event_remove_timer(CTX_wm_manager(C), win, handle->scrolltimer);
-}
-
-/**
- * Called for creating new popups and refreshing existing ones.
- */
-uiBlock *ui_popup_block_refresh(
- bContext *C, uiPopupBlockHandle *handle,
- ARegion *butregion, uiBut *but)
-{
- BLI_assert(handle->can_refresh == true);
-
- const int margin = UI_POPUP_MARGIN;
- wmWindow *window = CTX_wm_window(C);
- ARegion *ar = handle->region;
-
- uiBlockCreateFunc create_func = handle->popup_create_vars.create_func;
- uiBlockHandleCreateFunc handle_create_func = handle->popup_create_vars.handle_create_func;
- void *arg = handle->popup_create_vars.arg;
-
- uiBlock *block_old = ar->uiblocks.first;
- uiBlock *block;
-
-#ifdef DEBUG
- wmEvent *event_back = window->eventstate;
-#endif
-
- /* create ui block */
- if (create_func)
- block = create_func(C, ar, arg);
- else
- block = handle_create_func(C, handle, arg);
-
- /* callbacks _must_ leave this for us, otherwise we can't call UI_block_update_from_old */
- BLI_assert(!block->endblock);
-
- /* ensure we don't use mouse coords here! */
-#ifdef DEBUG
- window->eventstate = NULL;
-#endif
-
- if (block->handle) {
- memcpy(block->handle, handle, sizeof(uiPopupBlockHandle));
- MEM_freeN(handle);
- handle = block->handle;
- }
- else
- block->handle = handle;
-
- ar->regiondata = handle;
-
- /* set UI_BLOCK_NUMSELECT before UI_block_end() so we get alphanumeric keys assigned */
- if (but == NULL) {
- block->flag |= UI_BLOCK_POPUP;
- }
-
- block->flag |= UI_BLOCK_LOOP;
-
- /* defer this until blocks are translated (below) */
- block->oldblock = NULL;
-
- if (!block->endblock)
- UI_block_end_ex(C, block, handle->popup_create_vars.event_xy);
-
- /* if this is being created from a button */
- if (but) {
- block->aspect = but->block->aspect;
- ui_block_position(window, butregion, but, block);
- handle->direction = block->direction;
- }
- else {
- uiSafetyRct *saferct;
- /* keep a list of these, needed for pulldown menus */
- saferct = MEM_callocN(sizeof(uiSafetyRct), "uiSafetyRct");
- saferct->safety = block->safety;
- BLI_addhead(&block->saferct, saferct);
- }
-
- if (block->flag & UI_BLOCK_RADIAL) {
- int win_width = UI_SCREEN_MARGIN;
- int winx, winy;
-
- int x_offset = 0, y_offset = 0;
-
- winx = WM_window_pixels_x(window);
- winy = WM_window_pixels_y(window);
-
- copy_v2_v2(block->pie_data.pie_center_init, block->pie_data.pie_center_spawned);
-
- /* only try translation if area is large enough */
- if (BLI_rctf_size_x(&block->rect) < winx - (2.0f * win_width)) {
- if (block->rect.xmin < win_width ) x_offset += win_width - block->rect.xmin;
- if (block->rect.xmax > winx - win_width) x_offset += winx - win_width - block->rect.xmax;
- }
-
- if (BLI_rctf_size_y(&block->rect) < winy - (2.0f * win_width)) {
- if (block->rect.ymin < win_width ) y_offset += win_width - block->rect.ymin;
- if (block->rect.ymax > winy - win_width) y_offset += winy - win_width - block->rect.ymax;
- }
- /* if we are offsetting set up initial data for timeout functionality */
-
- if ((x_offset != 0) || (y_offset != 0)) {
- block->pie_data.pie_center_spawned[0] += x_offset;
- block->pie_data.pie_center_spawned[1] += y_offset;
-
- ui_block_translate(block, x_offset, y_offset);
-
- if (U.pie_initial_timeout > 0)
- block->pie_data.flags |= UI_PIE_INITIAL_DIRECTION;
- }
-
- ar->winrct.xmin = 0;
- ar->winrct.xmax = winx;
- ar->winrct.ymin = 0;
- ar->winrct.ymax = winy;
-
- ui_block_calc_pie_segment(block, block->pie_data.pie_center_init);
-
- /* lastly set the buttons at the center of the pie menu, ready for animation */
- if (U.pie_animation_timeout > 0) {
- for (uiBut *but_iter = block->buttons.first; but_iter; but_iter = but_iter->next) {
- if (but_iter->pie_dir != UI_RADIAL_NONE) {
- BLI_rctf_recenter(&but_iter->rect, UNPACK2(block->pie_data.pie_center_spawned));
- }
- }
- }
- }
- else {
- /* clip block with window boundary */
- ui_popup_block_clip(window, block);
- /* the block and buttons were positioned in window space as in 2.4x, now
- * these menu blocks are regions so we bring it back to region space.
- * additionally we add some padding for the menu shadow or rounded menus */
- ar->winrct.xmin = block->rect.xmin - margin;
- ar->winrct.xmax = block->rect.xmax + margin;
- ar->winrct.ymin = block->rect.ymin - margin;
- ar->winrct.ymax = block->rect.ymax + UI_POPUP_MENU_TOP;
-
- ui_block_translate(block, -ar->winrct.xmin, -ar->winrct.ymin);
- }
-
- if (block_old) {
- block->oldblock = block_old;
- UI_block_update_from_old(C, block);
- UI_blocklist_free_inactive(C, &ar->uiblocks);
- }
-
- /* checks which buttons are visible, sets flags to prevent draw (do after region init) */
- ui_popup_block_scrolltest(block);
-
- /* adds subwindow */
- ED_region_init(C, ar);
-
- /* get winmat now that we actually have the subwindow */
- wmSubWindowSet(window, ar->swinid);
-
- wm_subwindow_matrix_get(window, ar->swinid, block->winmat);
-
- /* notify change and redraw */
- ED_region_tag_redraw(ar);
-
- ED_region_update_rect(C, ar);
-
-#ifdef DEBUG
- window->eventstate = event_back;
-#endif
-
- return block;
-}
-
-uiPopupBlockHandle *ui_popup_block_create(
- bContext *C, ARegion *butregion, uiBut *but,
- uiBlockCreateFunc create_func, uiBlockHandleCreateFunc handle_create_func,
- void *arg)
-{
- wmWindow *window = CTX_wm_window(C);
- uiBut *activebut = UI_context_active_but_get(C);
- static ARegionType type;
- ARegion *ar;
- uiBlock *block;
- uiPopupBlockHandle *handle;
-
- /* disable tooltips from buttons below */
- if (activebut) {
- UI_but_tooltip_timer_remove(C, activebut);
- }
- /* standard cursor by default */
- WM_cursor_set(window, CURSOR_STD);
-
- /* create handle */
- handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
-
- /* store context for operator */
- handle->ctx_area = CTX_wm_area(C);
- handle->ctx_region = CTX_wm_region(C);
-
- /* store vars to refresh popup (RGN_DRAW_REFRESH_UI) */
- handle->popup_create_vars.create_func = create_func;
- handle->popup_create_vars.handle_create_func = handle_create_func;
- handle->popup_create_vars.arg = arg;
- handle->popup_create_vars.butregion = but ? butregion : NULL;
- copy_v2_v2_int(handle->popup_create_vars.event_xy, &window->eventstate->x);
- /* caller may free vars used to create this popup, in that case this variable should be disabled. */
- handle->can_refresh = true;
-
- /* create area region */
- ar = ui_region_temp_add(CTX_wm_screen(C));
- handle->region = ar;
-
- memset(&type, 0, sizeof(ARegionType));
- type.draw = ui_block_region_draw;
- type.regionid = RGN_TYPE_TEMPORARY;
- ar->type = &type;
-
- UI_region_handlers_add(&ar->handlers);
-
- block = ui_popup_block_refresh(C, handle, butregion, but);
- handle = block->handle;
-
- return handle;
-}
-
-void ui_popup_block_free(bContext *C, uiPopupBlockHandle *handle)
-{
- ui_popup_block_remove(C, handle);
-
- MEM_freeN(handle);
-}
-
-/***************************** Menu Button ***************************/
-
-#if 0
-static void ui_warp_pointer(int x, int y)
-{
- /* XXX 2.50 which function to use for this? */
- /* OSX has very poor mouse-warp support, it sends events;
- * this causes a menu being pressed immediately ... */
-# ifndef __APPLE__
- warp_pointer(x, y);
-# endif
-}
-#endif
-
-/********************* Color Button ****************/
-
-/* for picker, while editing hsv */
-void ui_but_hsv_set(uiBut *but)
-{
- float col[3];
- ColorPicker *cpicker = but->custom_data;
- float *hsv = cpicker->color_data;
-
- ui_color_picker_to_rgb_v(hsv, col);
-
- ui_but_v3_set(but, col);
-}
-
-/* Updates all buttons who share the same color picker as the one passed
- * also used by small picker, be careful with name checks below... */
-static void ui_update_color_picker_buts_rgb(uiBlock *block, ColorPicker *cpicker, const float rgb[3], bool is_display_space)
-{
- uiBut *bt;
- float *hsv = cpicker->color_data;
- struct ColorManagedDisplay *display = NULL;
- /* this is to keep the H and S value when V is equal to zero
- * and we are working in HSV mode, of course!
- */
- if (is_display_space) {
- ui_rgb_to_color_picker_compat_v(rgb, hsv);
- }
- else {
- /* we need to convert to display space to use hsv, because hsv is stored in display space */
- float rgb_display[3];
-
- copy_v3_v3(rgb_display, rgb);
- ui_block_cm_to_display_space_v3(block, rgb_display);
- ui_rgb_to_color_picker_compat_v(rgb_display, hsv);
- }
-
- if (block->color_profile)
- display = ui_block_cm_display_get(block);
-
- /* this updates button strings, is hackish... but button pointers are on stack of caller function */
- for (bt = block->buttons.first; bt; bt = bt->next) {
- if (bt->custom_data != cpicker)
- continue;
-
- if (bt->rnaprop) {
-
- ui_but_v3_set(bt, rgb);
-
- }
- else if (STREQ(bt->str, "Hex: ")) {
- float rgb_gamma[3];
- unsigned char rgb_gamma_uchar[3];
- double intpart;
- char col[16];
-
- /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
-
- copy_v3_v3(rgb_gamma, rgb);
-
- if (display) {
- /* make a display version, for Hex code */
- IMB_colormanagement_scene_linear_to_display_v3(rgb_gamma, display);
- }
-
- if (rgb_gamma[0] > 1.0f) rgb_gamma[0] = modf(rgb_gamma[0], &intpart);
- if (rgb_gamma[1] > 1.0f) rgb_gamma[1] = modf(rgb_gamma[1], &intpart);
- if (rgb_gamma[2] > 1.0f) rgb_gamma[2] = modf(rgb_gamma[2], &intpart);
-
- rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
- BLI_snprintf(col, sizeof(col), "%02X%02X%02X", UNPACK3_EX((unsigned int), rgb_gamma_uchar, ));
-
- strcpy(bt->poin, col);
- }
- else if (bt->str[1] == ' ') {
- if (bt->str[0] == 'R') {
- ui_but_value_set(bt, rgb[0]);
- }
- else if (bt->str[0] == 'G') {
- ui_but_value_set(bt, rgb[1]);
- }
- else if (bt->str[0] == 'B') {
- ui_but_value_set(bt, rgb[2]);
- }
- else if (bt->str[0] == 'H') {
- ui_but_value_set(bt, hsv[0]);
- }
- else if (bt->str[0] == 'S') {
- ui_but_value_set(bt, hsv[1]);
- }
- else if (bt->str[0] == 'V') {
- ui_but_value_set(bt, hsv[2]);
- }
- else if (bt->str[0] == 'L') {
- ui_but_value_set(bt, hsv[2]);
- }
- }
-
- ui_but_update(bt);
- }
-}
-
-static void ui_colorpicker_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
-{
- uiBut *but = (uiBut *)bt1;
- uiPopupBlockHandle *popup = but->block->handle;
- PropertyRNA *prop = but->rnaprop;
- PointerRNA ptr = but->rnapoin;
- float rgb[4];
-
- if (prop) {
- RNA_property_float_get_array(&ptr, prop, rgb);
- ui_update_color_picker_buts_rgb(but->block, but->custom_data, rgb, (RNA_property_subtype(prop) == PROP_COLOR_GAMMA));
- }
-
- if (popup)
- popup->menuretval = UI_RETURN_UPDATE;
-}
-
-static void ui_color_wheel_rna_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
-{
- uiBut *but = (uiBut *)bt1;
- uiPopupBlockHandle *popup = but->block->handle;
- float rgb[3];
- ColorPicker *cpicker = but->custom_data;
- float *hsv = cpicker->color_data;
- bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
-
- ui_color_picker_to_rgb_v(hsv, rgb);
-
- /* hsv is saved in display space so convert back */
- if (use_display_colorspace) {
- ui_block_cm_to_scene_linear_v3(but->block, rgb);
- }
-
- ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, !use_display_colorspace);
-
- if (popup)
- popup->menuretval = UI_RETURN_UPDATE;
-}
-
-static void ui_colorpicker_hex_rna_cb(bContext *UNUSED(C), void *bt1, void *hexcl)
-{
- uiBut *but = (uiBut *)bt1;
- uiPopupBlockHandle *popup = but->block->handle;
- ColorPicker *cpicker = but->custom_data;
- char *hexcol = (char *)hexcl;
- float rgb[3];
-
- hex_to_rgb(hexcol, rgb, rgb + 1, rgb + 2);
-
- /* Hex code is assumed to be in sRGB space (coming from other applications, web, etc) */
- if (but->block->color_profile) {
- /* so we need to linearise it for Blender */
- ui_block_cm_to_scene_linear_v3(but->block, rgb);
- }
-
- ui_update_color_picker_buts_rgb(but->block, cpicker, rgb, false);
-
- if (popup)
- popup->menuretval = UI_RETURN_UPDATE;
-}
-
-static void ui_popup_close_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
-{
- uiBut *but = (uiBut *)bt1;
- uiPopupBlockHandle *popup = but->block->handle;
-
- if (popup)
- popup->menuretval = UI_RETURN_OK;
-}
-
-static void ui_colorpicker_hide_reveal(uiBlock *block, short colormode)
-{
- uiBut *bt;
-
- /* tag buttons */
- for (bt = block->buttons.first; bt; bt = bt->next) {
- if ((bt->func == ui_colorpicker_rna_cb) && bt->type == UI_BTYPE_NUM_SLIDER && bt->rnaindex != 3) {
- /* RGB sliders (color circle and alpha are always shown) */
- if (colormode == 0) bt->flag &= ~UI_HIDDEN;
- else bt->flag |= UI_HIDDEN;
- }
- else if (bt->func == ui_color_wheel_rna_cb) {
- /* HSV sliders */
- if (colormode == 1) bt->flag &= ~UI_HIDDEN;
- else bt->flag |= UI_HIDDEN;
- }
- else if (bt->func == ui_colorpicker_hex_rna_cb || bt->type == UI_BTYPE_LABEL) {
- /* hex input or gamma correction status label */
- if (colormode == 2) bt->flag &= ~UI_HIDDEN;
- else bt->flag |= UI_HIDDEN;
- }
- }
-}
-
-static void ui_colorpicker_create_mode_cb(bContext *UNUSED(C), void *bt1, void *UNUSED(arg))
-{
- uiBut *bt = bt1;
- short colormode = ui_but_value_get(bt);
- ui_colorpicker_hide_reveal(bt->block, colormode);
-}
-
-#define PICKER_H (7.5f * U.widget_unit)
-#define PICKER_W (7.5f * U.widget_unit)
-#define PICKER_SPACE (0.3f * U.widget_unit)
-#define PICKER_BAR (0.7f * U.widget_unit)
-
-#define PICKER_TOTAL_W (PICKER_W + PICKER_SPACE + PICKER_BAR)
-
-static void ui_colorpicker_circle(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, ColorPicker *cpicker)
-{
- uiBut *bt;
-
- /* HS circle */
- bt = uiDefButR_prop(block, UI_BTYPE_HSVCIRCLE, 0, "", 0, 0, PICKER_H, PICKER_W, ptr, prop, -1, 0.0, 0.0, 0.0, 0, TIP_("Color"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
-
- /* value */
- if (U.color_picker_type == USER_CP_CIRCLE_HSL) {
- bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H, ptr, prop, -1, 0.0, 0.0, UI_GRAD_L_ALT, 0, "Lightness");
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- }
- else {
- bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", PICKER_W + PICKER_SPACE, 0, PICKER_BAR, PICKER_H, ptr, prop, -1, 0.0, 0.0, UI_GRAD_V_ALT, 0, TIP_("Value"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- }
- bt->custom_data = cpicker;
-}
-
-
-static void ui_colorpicker_square(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int type, ColorPicker *cpicker)
-{
- uiBut *bt;
- int bartype = type + 3;
-
- /* HS square */
- bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, PICKER_BAR + PICKER_SPACE, PICKER_TOTAL_W, PICKER_H, ptr, prop, -1, 0.0, 0.0, type, 0, TIP_("Color"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
-
- /* value */
- bt = uiDefButR_prop(block, UI_BTYPE_HSVCUBE, 0, "", 0, 0, PICKER_TOTAL_W, PICKER_BAR, ptr, prop, -1, 0.0, 0.0, bartype, 0, TIP_("Value"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
-}
-
-
-/* a HS circle, V slider, rgb/hsv/hex sliders */
-static void ui_block_colorpicker(uiBlock *block, float rgba[4], PointerRNA *ptr, PropertyRNA *prop, bool show_picker)
-{
- static short colormode = 0; /* temp? 0=rgb, 1=hsv, 2=hex */
- uiBut *bt;
- int width, butwidth;
- static char tip[50];
- static char hexcol[128];
- float rgb_gamma[3];
- unsigned char rgb_gamma_uchar[3];
- float softmin, softmax, hardmin, hardmax, step, precision;
- int yco;
- ColorPicker *cpicker = ui_block_colorpicker_create(block);
- float *hsv = cpicker->color_data;
-
- width = PICKER_TOTAL_W;
- butwidth = width - 1.5f * UI_UNIT_X;
-
- /* existence of profile means storage is in linear color space, with display correction */
- /* XXX That tip message is not use anywhere! */
- if (!block->color_profile) {
- BLI_strncpy(tip, N_("Value in Display Color Space"), sizeof(tip));
- copy_v3_v3(rgb_gamma, rgba);
- }
- else {
- BLI_strncpy(tip, N_("Value in Linear RGB Color Space"), sizeof(tip));
-
- /* make a display version, for Hex code */
- copy_v3_v3(rgb_gamma, rgba);
- ui_block_cm_to_display_space_v3(block, rgb_gamma);
- }
-
- /* sneaky way to check for alpha */
- rgba[3] = FLT_MAX;
-
- RNA_property_float_ui_range(ptr, prop, &softmin, &softmax, &step, &precision);
- RNA_property_float_range(ptr, prop, &hardmin, &hardmax);
- RNA_property_float_get_array(ptr, prop, rgba);
-
- /* when the softmax isn't defined in the RNA,
- * using very large numbers causes sRGB/linear round trip to fail. */
- if (softmax == FLT_MAX) {
- softmax = 1.0f;
- }
-
- switch (U.color_picker_type) {
- case USER_CP_SQUARE_SV:
- ui_colorpicker_square(block, ptr, prop, UI_GRAD_SV, cpicker);
- break;
- case USER_CP_SQUARE_HS:
- ui_colorpicker_square(block, ptr, prop, UI_GRAD_HS, cpicker);
- break;
- case USER_CP_SQUARE_HV:
- ui_colorpicker_square(block, ptr, prop, UI_GRAD_HV, cpicker);
- break;
-
- /* user default */
- case USER_CP_CIRCLE_HSV:
- case USER_CP_CIRCLE_HSL:
- default:
- ui_colorpicker_circle(block, ptr, prop, cpicker);
- break;
- }
-
- /* mode */
- yco = -1.5f * UI_UNIT_Y;
- UI_block_align_begin(block);
- bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("RGB"), 0, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 0.0, 0, 0, "");
- UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
- bt->custom_data = cpicker;
- if (U.color_picker_type == USER_CP_CIRCLE_HSL)
- bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("HSL"), width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
- else
- bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("HSV"), width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 1.0, 0, 0, "");
- UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
- bt->custom_data = cpicker;
- bt = uiDefButS(block, UI_BTYPE_ROW, 0, IFACE_("Hex"), 2 * width / 3, yco, width / 3, UI_UNIT_Y, &colormode, 0.0, 2.0, 0, 0, "");
- UI_but_func_set(bt, ui_colorpicker_create_mode_cb, bt, NULL);
- bt->custom_data = cpicker;
- UI_block_align_end(block);
-
- yco = -3.0f * UI_UNIT_Y;
- if (show_picker) {
- bt = uiDefIconButO(block, UI_BTYPE_BUT, "UI_OT_eyedropper_color", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, butwidth + 10, yco, UI_UNIT_X, UI_UNIT_Y, NULL);
- UI_but_func_set(bt, ui_popup_close_cb, bt, NULL);
- bt->custom_data = cpicker;
- }
-
- /* RGB values */
- UI_block_align_begin(block);
- bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("R:"), 0, yco, butwidth, UI_UNIT_Y, ptr, prop, 0, 0.0, 0.0, 0, 3, TIP_("Red"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
- bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("G:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 1, 0.0, 0.0, 0, 3, TIP_("Green"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
- bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("B:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 2, 0.0, 0.0, 0, 3, TIP_("Blue"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
-
- /* could use uiItemFullR(col, ptr, prop, -1, 0, UI_ITEM_R_EXPAND|UI_ITEM_R_SLIDER, "", ICON_NONE);
- * but need to use UI_but_func_set for updating other fake buttons */
-
- /* HSV values */
- yco = -3.0f * UI_UNIT_Y;
- UI_block_align_begin(block);
- bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("H:"), 0, yco, butwidth, UI_UNIT_Y, hsv, 0.0, 1.0, 10, 3, TIP_("Hue"));
- UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
- bt->custom_data = cpicker;
- bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("S:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 1, 0.0, 1.0, 10, 3, TIP_("Saturation"));
- UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
- bt->custom_data = cpicker;
- if (U.color_picker_type == USER_CP_CIRCLE_HSL)
- bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("L:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 2, 0.0, 1.0, 10, 3, TIP_("Lightness"));
- else
- bt = uiDefButF(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("V:"), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, hsv + 2, 0.0, softmax, 10, 3, TIP_("Value"));
-
- bt->hardmax = hardmax; /* not common but rgb may be over 1.0 */
- UI_but_func_set(bt, ui_color_wheel_rna_cb, bt, hsv);
- bt->custom_data = cpicker;
-
- UI_block_align_end(block);
-
- if (rgba[3] != FLT_MAX) {
- bt = uiDefButR_prop(block, UI_BTYPE_NUM_SLIDER, 0, IFACE_("A: "), 0, yco -= UI_UNIT_Y, butwidth, UI_UNIT_Y, ptr, prop, 3, 0.0, 0.0, 0, 3, TIP_("Alpha"));
- UI_but_func_set(bt, ui_colorpicker_rna_cb, bt, NULL);
- bt->custom_data = cpicker;
- }
- else {
- rgba[3] = 1.0f;
- }
-
- rgb_float_to_uchar(rgb_gamma_uchar, rgb_gamma);
- BLI_snprintf(hexcol, sizeof(hexcol), "%02X%02X%02X", UNPACK3_EX((unsigned int), rgb_gamma_uchar, ));
-
- yco = -3.0f * UI_UNIT_Y;
- bt = uiDefBut(block, UI_BTYPE_TEXT, 0, IFACE_("Hex: "), 0, yco, butwidth, UI_UNIT_Y, hexcol, 0, 7, 0, 0, TIP_("Hex triplet for color (#RRGGBB)"));
- UI_but_func_set(bt, ui_colorpicker_hex_rna_cb, bt, hexcol);
- bt->custom_data = cpicker;
- uiDefBut(block, UI_BTYPE_LABEL, 0, IFACE_("(Gamma Corrected)"), 0, yco - UI_UNIT_Y, butwidth, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
-
- ui_rgb_to_color_picker_v(rgb_gamma, hsv);
-
- ui_colorpicker_hide_reveal(block, colormode);
-}
-
-
-static int ui_colorpicker_small_wheel_cb(const bContext *UNUSED(C), uiBlock *block, const wmEvent *event)
-{
- float add = 0.0f;
-
- if (event->type == WHEELUPMOUSE)
- add = 0.05f;
- else if (event->type == WHEELDOWNMOUSE)
- add = -0.05f;
-
- if (add != 0.0f) {
- uiBut *but;
-
- for (but = block->buttons.first; but; but = but->next) {
- if (but->type == UI_BTYPE_HSVCUBE && but->active == NULL) {
- uiPopupBlockHandle *popup = block->handle;
- float rgb[3];
- ColorPicker *cpicker = but->custom_data;
- float *hsv = cpicker->color_data;
- bool use_display_colorspace = ui_but_is_colorpicker_display_space(but);
-
- ui_but_v3_get(but, rgb);
-
- if (use_display_colorspace)
- ui_block_cm_to_display_space_v3(block, rgb);
-
- ui_rgb_to_color_picker_compat_v(rgb, hsv);
-
- hsv[2] = CLAMPIS(hsv[2] + add, 0.0f, 1.0f);
- ui_color_picker_to_rgb_v(hsv, rgb);
-
- if (use_display_colorspace)
- ui_block_cm_to_scene_linear_v3(block, rgb);
-
- ui_but_v3_set(but, rgb);
-
- ui_update_color_picker_buts_rgb(block, cpicker, rgb, !use_display_colorspace);
- if (popup)
- popup->menuretval = UI_RETURN_UPDATE;
-
- return 1;
- }
- }
- }
- return 0;
-}
-
-uiBlock *ui_block_func_COLOR(bContext *C, uiPopupBlockHandle *handle, void *arg_but)
-{
- uiBut *but = arg_but;
- uiBlock *block;
- bool show_picker = true;
-
- block = UI_block_begin(C, handle->region, __func__, UI_EMBOSS);
-
- if (RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA) {
- block->color_profile = false;
- }
-
- if (but->block) {
- /* if color block is invoked from a popup we wouldn't be able to set color properly
- * this is because color picker will close popups first and then will try to figure
- * out active button RNA, and of course it'll fail
- */
- show_picker = (but->block->flag & UI_BLOCK_POPUP) == 0;
- }
-
- copy_v3_v3(handle->retvec, but->editvec);
-
- ui_block_colorpicker(block, handle->retvec, &but->rnapoin, but->rnaprop, show_picker);
-
- block->flag = UI_BLOCK_LOOP | UI_BLOCK_KEEP_OPEN | UI_BLOCK_OUT_1 | UI_BLOCK_MOVEMOUSE_QUIT;
- UI_block_bounds_set_normal(block, 0.5 * UI_UNIT_X);
-
- block->block_event_func = ui_colorpicker_small_wheel_cb;
-
- /* and lets go */
- block->direction = UI_DIR_UP;
-
- return block;
-}
-
-/************************ Popup Menu Memory ****************************/
-
-static unsigned int ui_popup_string_hash(const char *str)
-{
- /* sometimes button contains hotkey, sometimes not, strip for proper compare */
- int hash;
- const char *delimit = strrchr(str, UI_SEP_CHAR);
-
- if (delimit) {
- hash = BLI_ghashutil_strhash_n(str, delimit - str);
- }
- else {
- hash = BLI_ghashutil_strhash(str);
- }
-
- return hash;
-}
-
-static unsigned int ui_popup_menu_hash(const char *str)
-{
- return BLI_ghashutil_strhash(str);
-}
-
-/* but == NULL read, otherwise set */
-static uiBut *ui_popup_menu_memory__internal(uiBlock *block, uiBut *but)
-{
- static unsigned int mem[256];
- static bool first = true;
-
- const unsigned int hash = block->puphash;
- const unsigned int hash_mod = hash & 255;
-
- if (first) {
- /* init */
- memset(mem, -1, sizeof(mem));
- first = 0;
- }
-
- if (but) {
- /* set */
- mem[hash_mod] = ui_popup_string_hash(but->str);
- return NULL;
- }
- else {
- /* get */
- for (but = block->buttons.first; but; but = but->next)
- if (ui_popup_string_hash(but->str) == mem[hash_mod])
- return but;
-
- return NULL;
- }
-}
-
-uiBut *ui_popup_menu_memory_get(uiBlock *block)
-{
- return ui_popup_menu_memory__internal(block, NULL);
-}
-
-void ui_popup_menu_memory_set(uiBlock *block, uiBut *but)
-{
- ui_popup_menu_memory__internal(block, but);
-}
-
-/**
- * Translate any popup regions (so we can drag them).
- */
-void ui_popup_translate(bContext *C, ARegion *ar, const int mdiff[2])
-{
- uiBlock *block;
-
- BLI_rcti_translate(&ar->winrct, UNPACK2(mdiff));
-
- ED_region_update_rect(C, ar);
-
- ED_region_tag_redraw(ar);
-
- /* update blocks */
- for (block = ar->uiblocks.first; block; block = block->next) {
- uiSafetyRct *saferct;
- for (saferct = block->saferct.first; saferct; saferct = saferct->next) {
- BLI_rctf_translate(&saferct->parent, UNPACK2(mdiff));
- BLI_rctf_translate(&saferct->safety, UNPACK2(mdiff));
- }
- }
-}
-
-/******************** Popup Menu with callback or string **********************/
-
-struct uiPopupMenu {
- uiBlock *block;
- uiLayout *layout;
- uiBut *but;
-
- int mx, my;
- bool popup, slideout;
-
- uiMenuCreateFunc menu_func;
- void *menu_arg;
-};
-
-struct uiPieMenu {
- uiBlock *block_radial; /* radial block of the pie menu (more could be added later) */
- uiLayout *layout;
- int mx, my;
-};
-
-static uiBlock *ui_block_func_POPUP(bContext *C, uiPopupBlockHandle *handle, void *arg_pup)
-{
- uiBlock *block;
- uiBut *bt;
- uiPopupMenu *pup = arg_pup;
- int offset[2], minwidth, width, height;
- char direction;
- bool flip;
-
- if (pup->menu_func) {
- pup->block->handle = handle;
- pup->menu_func(C, pup->layout, pup->menu_arg);
- pup->block->handle = NULL;
- }
-
- if (pup->but) {
- /* minimum width to enforece */
- minwidth = BLI_rctf_size_x(&pup->but->rect);
-
- /* settings (typically rna-enum-popups) show above the button,
- * menu's like file-menu, show below */
- if (pup->block->direction != 0) {
- /* allow overriding the direction from menu_func */
- direction = pup->block->direction;
- }
- else if ((pup->but->type == UI_BTYPE_PULLDOWN) ||
- (UI_but_menutype_get(pup->but) != NULL))
- {
- direction = UI_DIR_DOWN;
- }
- else {
- direction = UI_DIR_UP;
- }
- }
- else {
- minwidth = 50;
- direction = UI_DIR_DOWN;
- }
-
- flip = (direction == UI_DIR_DOWN);
-
- block = pup->block;
-
- /* in some cases we create the block before the region,
- * so we set it delayed here if necessary */
- if (BLI_findindex(&handle->region->uiblocks, block) == -1)
- UI_block_region_set(block, handle->region);
-
- block->direction = direction;
-
- UI_block_layout_resolve(block, &width, &height);
-
- UI_block_flag_enable(block, UI_BLOCK_MOVEMOUSE_QUIT);
-
- if (pup->popup) {
- uiBut *but_activate = NULL;
- UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
- UI_block_direction_set(block, direction);
-
- /* offset the mouse position, possibly based on earlier selection */
- if ((block->flag & UI_BLOCK_POPUP_MEMORY) &&
- (bt = ui_popup_menu_memory_get(block)))
- {
- /* position mouse on last clicked item, at 0.8*width of the
- * button, so it doesn't overlap the text too much, also note
- * the offset is negative because we are inverse moving the
- * block to be under the mouse */
- offset[0] = -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect));
- offset[1] = -(bt->rect.ymin + 0.5f * UI_UNIT_Y);
-
- if (ui_but_is_editable(bt)) {
- but_activate = bt;
- }
- }
- else {
- /* position mouse at 0.8*width of the button and below the tile
- * on the first item */
- offset[0] = 0;
- for (bt = block->buttons.first; bt; bt = bt->next)
- offset[0] = min_ii(offset[0], -(bt->rect.xmin + 0.8f * BLI_rctf_size_x(&bt->rect)));
-
- offset[1] = 2.1 * UI_UNIT_Y;
-
- for (bt = block->buttons.first; bt; bt = bt->next) {
- if (ui_but_is_editable(bt)) {
- but_activate = bt;
- break;
- }
- }
- }
-
- /* in rare cases this is needed since moving the popup
- * to be within the window bounds may move it away from the mouse,
- * This ensures we set an item to be active. */
- if (but_activate) {
- ui_but_activate_over(C, handle->region, but_activate);
- }
-
- block->minbounds = minwidth;
- UI_block_bounds_set_menu(block, 1, offset[0], offset[1]);
- }
- else {
- /* for a header menu we set the direction automatic */
- if (!pup->slideout && flip) {
- ScrArea *sa = CTX_wm_area(C);
- if (sa && sa->headertype == HEADERDOWN) {
- ARegion *ar = CTX_wm_region(C);
- if (ar && ar->regiontype == RGN_TYPE_HEADER) {
- UI_block_direction_set(block, UI_DIR_UP);
- UI_block_order_flip(block);
- }
- }
- }
-
- block->minbounds = minwidth;
- UI_block_bounds_set_text(block, 3.0f * UI_UNIT_X);
- }
-
- /* if menu slides out of other menu, override direction */
- if (pup->slideout)
- UI_block_direction_set(block, UI_DIR_RIGHT);
-
- return pup->block;
-}
-
-uiPopupBlockHandle *ui_popup_menu_create(
- bContext *C, ARegion *butregion, uiBut *but,
- uiMenuCreateFunc menu_func, void *arg)
-{
- wmWindow *window = CTX_wm_window(C);
- uiStyle *style = UI_style_get_dpi();
- uiPopupBlockHandle *handle;
- uiPopupMenu *pup;
-
- pup = MEM_callocN(sizeof(uiPopupMenu), __func__);
- pup->block = UI_block_begin(C, NULL, __func__, UI_EMBOSS_PULLDOWN);
- pup->block->flag |= UI_BLOCK_NUMSELECT; /* default menus to numselect */
- pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
- pup->slideout = but ? ui_block_is_menu(but->block) : false;
- pup->but = but;
- uiLayoutSetOperatorContext(pup->layout, WM_OP_INVOKE_REGION_WIN);
-
- if (!but) {
- /* no button to start from, means we are a popup */
- pup->mx = window->eventstate->x;
- pup->my = window->eventstate->y;
- pup->popup = true;
- pup->block->flag |= UI_BLOCK_NO_FLIP;
- }
- /* some enums reversing is strange, currently we have no good way to
- * reverse some enum's but not others, so reverse all so the first menu
- * items are always close to the mouse cursor */
- else {
-#if 0
- /* if this is an rna button then we can assume its an enum
- * flipping enums is generally not good since the order can be
- * important [#28786] */
- if (but->rnaprop && RNA_property_type(but->rnaprop) == PROP_ENUM) {
- pup->block->flag |= UI_BLOCK_NO_FLIP;
- }
-#endif
- if (but->context)
- uiLayoutContextCopy(pup->layout, but->context);
- }
-
- /* menu is created from a callback */
- pup->menu_func = menu_func;
- pup->menu_arg = arg;
-
- handle = ui_popup_block_create(C, butregion, but, NULL, ui_block_func_POPUP, pup);
-
- if (!but) {
- handle->popup = true;
-
- UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
- WM_event_add_mousemove(C);
- }
-
- handle->can_refresh = false;
- MEM_freeN(pup);
-
- return handle;
-}
-
-/******************** Popup Menu API with begin and end ***********************/
-
-/**
- * Only return handler, and set optional title.
- * \param block_name: Assigned to uiBlock.name (useful info for debugging).
- */
-uiPopupMenu *UI_popup_menu_begin_ex(bContext *C, const char *title, const char *block_name, int icon)
-{
- uiStyle *style = UI_style_get_dpi();
- uiPopupMenu *pup = MEM_callocN(sizeof(uiPopupMenu), "popup menu");
- uiBut *but;
-
- pup->block = UI_block_begin(C, NULL, block_name, UI_EMBOSS_PULLDOWN);
- pup->block->flag |= UI_BLOCK_POPUP_MEMORY | UI_BLOCK_IS_FLIP;
- pup->block->puphash = ui_popup_menu_hash(title);
- pup->layout = UI_block_layout(pup->block, UI_LAYOUT_VERTICAL, UI_LAYOUT_MENU, 0, 0, 200, 0, MENU_PADDING, style);
-
- /* note, this intentionally differs from the menu & submenu default because many operators
- * use popups like this to select one of their options - where having invoke doesn't make sense */
- uiLayoutSetOperatorContext(pup->layout, WM_OP_EXEC_REGION_WIN);
-
- /* create in advance so we can let buttons point to retval already */
- pup->block->handle = MEM_callocN(sizeof(uiPopupBlockHandle), "uiPopupBlockHandle");
-
- /* create title button */
- if (title[0]) {
- char titlestr[256];
-
- if (icon) {
- BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
- uiDefIconTextBut(pup->block, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
- }
- else {
- but = uiDefBut(pup->block, UI_BTYPE_LABEL, 0, title, 0, 0, 200, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
- but->drawflag = UI_BUT_TEXT_LEFT;
- }
-
- uiItemS(pup->layout);
- }
-
- return pup;
-}
-
-uiPopupMenu *UI_popup_menu_begin(bContext *C, const char *title, int icon)
-{
- return UI_popup_menu_begin_ex(C, title, __func__, icon);
-}
-
-/* set the whole structure to work */
-void UI_popup_menu_end(bContext *C, uiPopupMenu *pup)
-{
- wmWindow *window = CTX_wm_window(C);
- uiPopupBlockHandle *menu;
-
- pup->popup = true;
- pup->mx = window->eventstate->x;
- pup->my = window->eventstate->y;
-
- menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_POPUP, pup);
- menu->popup = true;
-
- UI_popup_handlers_add(C, &window->modalhandlers, menu, 0);
- WM_event_add_mousemove(C);
-
- menu->can_refresh = false;
- MEM_freeN(pup);
-}
-
-uiLayout *UI_popup_menu_layout(uiPopupMenu *pup)
-{
- return pup->layout;
-}
-
-/*************************** Pie Menus ***************************************/
-
-static uiBlock *ui_block_func_PIE(bContext *UNUSED(C), uiPopupBlockHandle *handle, void *arg_pie)
-{
- uiBlock *block;
- uiPieMenu *pie = arg_pie;
- int minwidth, width, height;
-
- minwidth = 50;
- block = pie->block_radial;
-
- /* in some cases we create the block before the region,
- * so we set it delayed here if necessary */
- if (BLI_findindex(&handle->region->uiblocks, block) == -1)
- UI_block_region_set(block, handle->region);
-
- UI_block_layout_resolve(block, &width, &height);
-
- UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_NUMSELECT);
-
- block->minbounds = minwidth;
- block->bounds = 1;
- block->mx = 0;
- block->my = 0;
- block->bounds_type = UI_BLOCK_BOUNDS_PIE_CENTER;
-
- block->pie_data.pie_center_spawned[0] = pie->mx;
- block->pie_data.pie_center_spawned[1] = pie->my;
-
- return pie->block_radial;
-}
-
-static float ui_pie_menu_title_width(const char *name, int icon)
-{
- const uiFontStyle *fstyle = UI_FSTYLE_WIDGET;
- return (UI_fontstyle_string_width(fstyle, name) +
- (UI_UNIT_X * (1.50f + (icon ? 0.25f : 0.0f))));
-}
-
-uiPieMenu *UI_pie_menu_begin(struct bContext *C, const char *title, int icon, const wmEvent *event)
-{
- uiStyle *style;
- uiPieMenu *pie;
- short event_type;
-
- wmWindow *win = CTX_wm_window(C);
-
- style = UI_style_get_dpi();
- pie = MEM_callocN(sizeof(uiPopupMenu), "pie menu");
-
- pie->block_radial = UI_block_begin(C, NULL, __func__, UI_EMBOSS);
- /* may be useful later to allow spawning pies
- * from old positions */
- /* pie->block_radial->flag |= UI_BLOCK_POPUP_MEMORY; */
- pie->block_radial->puphash = ui_popup_menu_hash(title);
- pie->block_radial->flag |= UI_BLOCK_RADIAL;
-
- /* if pie is spawned by a left click, it is always assumed to be click style */
- if (event->type == LEFTMOUSE) {
- pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
- pie->block_radial->pie_data.event = EVENT_NONE;
- win->lock_pie_event = EVENT_NONE;
- }
- else {
- if (win->last_pie_event != EVENT_NONE) {
- /* original pie key has been released, so don't propagate the event */
- if (win->lock_pie_event == EVENT_NONE) {
- event_type = EVENT_NONE;
- pie->block_radial->pie_data.flags |= UI_PIE_CLICK_STYLE;
- }
- else
- event_type = win->last_pie_event;
- }
- else {
- event_type = event->type;
- }
-
- pie->block_radial->pie_data.event = event_type;
- win->lock_pie_event = event_type;
- }
-
- pie->layout = UI_block_layout(pie->block_radial, UI_LAYOUT_VERTICAL, UI_LAYOUT_PIEMENU, 0, 0, 200, 0, 0, style);
- pie->mx = event->x;
- pie->my = event->y;
-
- /* create title button */
- if (title[0]) {
- uiBut *but;
- char titlestr[256];
- int w;
- if (icon) {
- BLI_snprintf(titlestr, sizeof(titlestr), " %s", title);
- w = ui_pie_menu_title_width(titlestr, icon);
- but = uiDefIconTextBut(pie->block_radial, UI_BTYPE_LABEL, 0, icon, titlestr, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
- }
- else {
- w = ui_pie_menu_title_width(title, 0);
- but = uiDefBut(pie->block_radial, UI_BTYPE_LABEL, 0, title, 0, 0, w, UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
- }
- /* do not align left */
- but->drawflag &= ~UI_BUT_TEXT_LEFT;
- pie->block_radial->pie_data.title = but->str;
- pie->block_radial->pie_data.icon = icon;
- }
-
- return pie;
-}
-
-void UI_pie_menu_end(bContext *C, uiPieMenu *pie)
-{
- wmWindow *window = CTX_wm_window(C);
- uiPopupBlockHandle *menu;
-
- menu = ui_popup_block_create(C, NULL, NULL, NULL, ui_block_func_PIE, pie);
- menu->popup = true;
- menu->towardstime = PIL_check_seconds_timer();
-
- UI_popup_handlers_add(
- C, &window->modalhandlers,
- menu, WM_HANDLER_ACCEPT_DBL_CLICK);
- WM_event_add_mousemove(C);
-
- menu->can_refresh = false;
- MEM_freeN(pie);
-}
-
-uiLayout *UI_pie_menu_layout(uiPieMenu *pie)
-{
- return pie->layout;
-}
-
-int UI_pie_menu_invoke(struct bContext *C, const char *idname, const wmEvent *event)
-{
- uiPieMenu *pie;
- uiLayout *layout;
- Menu menu;
- MenuType *mt = WM_menutype_find(idname, true);
-
- if (mt == NULL) {
- printf("%s: named menu \"%s\" not found\n", __func__, idname);
- return OPERATOR_CANCELLED;
- }
-
- if (mt->poll && mt->poll(C, mt) == 0)
- /* cancel but allow event to pass through, just like operators do */
- return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH);
-
- pie = UI_pie_menu_begin(C, IFACE_(mt->label), ICON_NONE, event);
- layout = UI_pie_menu_layout(pie);
-
- menu.layout = layout;
- menu.type = mt;
-
- if (G.debug & G_DEBUG_WM) {
- printf("%s: opening menu \"%s\"\n", __func__, idname);
- }
-
- mt->draw(C, &menu);
-
- UI_pie_menu_end(C, pie);
-
- return OPERATOR_INTERFACE;
-}
-
-int UI_pie_menu_invoke_from_operator_enum(
- struct bContext *C, const char *title, const char *opname,
- const char *propname, const wmEvent *event)
-{
- uiPieMenu *pie;
- uiLayout *layout;
-
- pie = UI_pie_menu_begin(C, IFACE_(title), ICON_NONE, event);
- layout = UI_pie_menu_layout(pie);
-
- layout = uiLayoutRadial(layout);
- uiItemsEnumO(layout, opname, propname);
-
- UI_pie_menu_end(C, pie);
-
- return OPERATOR_INTERFACE;
-}
-
-int UI_pie_menu_invoke_from_rna_enum(
- struct bContext *C, const char *title, const char *path,
- const wmEvent *event)
-{
- PointerRNA ctx_ptr;
- PointerRNA r_ptr;
- PropertyRNA *r_prop;
- uiPieMenu *pie;
- uiLayout *layout;
-
- RNA_pointer_create(NULL, &RNA_Context, C, &ctx_ptr);
-
- if (!RNA_path_resolve(&ctx_ptr, path, &r_ptr, &r_prop)) {
- return OPERATOR_CANCELLED;
- }
-
- /* invalid property, only accept enums */
- if (RNA_property_type(r_prop) != PROP_ENUM) {
- BLI_assert(0);
- return OPERATOR_CANCELLED;
- }
-
- pie = UI_pie_menu_begin(C, IFACE_(title), ICON_NONE, event);
-
- layout = UI_pie_menu_layout(pie);
-
- layout = uiLayoutRadial(layout);
- uiItemFullR(layout, &r_ptr, r_prop, RNA_NO_INDEX, 0, UI_ITEM_R_EXPAND, NULL, 0);
-
- UI_pie_menu_end(C, pie);
-
- return OPERATOR_INTERFACE;
-}
-
-/**
- * \name Pie Menu Levels
- *
- * Pie menus can't contain more than 8 items (yet). When using #uiItemsFullEnumO, a "More" button is created that calls
- * a new pie menu if the enum has too many items. We call this a new "level".
- * Indirect recursion is used, so that a theoretically unlimited number of items is supported.
- *
- * This is a implementation specifically for operator enums, needed since the object mode pie now has more than 8
- * items. Ideally we'd have some way of handling this for all kinds of pie items, but that's tricky.
- *
- * - Julian (Feb 2016)
- *
- * \{ */
-
-typedef struct PieMenuLevelData {
- char title[UI_MAX_NAME_STR]; /* parent pie title, copied for level */
- int icon; /* parent pie icon, copied for level */
- int totitem; /* total count of *remaining* items */
-
- /* needed for calling uiItemsFullEnumO_array again for new level */
- wmOperatorType *ot;
- const char *propname;
- IDProperty *properties;
- int context, flag;
-} PieMenuLevelData;
-
-/**
- * Invokes a new pie menu for a new level.
- */
-static void ui_pie_menu_level_invoke(bContext *C, void *argN, void *arg2)
-{
- EnumPropertyItem *item_array = (EnumPropertyItem *)argN;
- PieMenuLevelData *lvl = (PieMenuLevelData *)arg2;
- wmWindow *win = CTX_wm_window(C);
-
- uiPieMenu *pie = UI_pie_menu_begin(C, IFACE_(lvl->title), lvl->icon, win->eventstate);
- uiLayout *layout = UI_pie_menu_layout(pie);
-
- layout = uiLayoutRadial(layout);
-
- PointerRNA ptr;
-
- WM_operator_properties_create_ptr(&ptr, lvl->ot);
- /* so the context is passed to itemf functions (some need it) */
- WM_operator_properties_sanitize(&ptr, false);
- PropertyRNA *prop = RNA_struct_find_property(&ptr, lvl->propname);
-
- if (prop) {
- uiItemsFullEnumO_items(
- layout, lvl->ot, ptr, prop, lvl->properties, lvl->context, lvl->flag,
- item_array, lvl->totitem);
- }
- else {
- RNA_warning("%s.%s not found", RNA_struct_identifier(ptr.type), lvl->propname);
- }
-
- UI_pie_menu_end(C, pie);
-}
-
-/**
- * Set up data for defining a new pie menu level and add button that invokes it.
- */
-void ui_pie_menu_level_create(
- uiBlock *block, wmOperatorType *ot, const char *propname, IDProperty *properties,
- const EnumPropertyItem *items, int totitem, int context, int flag)
-{
- const int totitem_parent = PIE_MAX_ITEMS - 1;
- const int totitem_remain = totitem - totitem_parent;
- size_t array_size = sizeof(EnumPropertyItem) * totitem_remain;
-
- /* used as but->func_argN so freeing is handled elsewhere */
- EnumPropertyItem *remaining = MEM_mallocN(array_size + sizeof(EnumPropertyItem), "pie_level_item_array");
- memcpy(remaining, items + totitem_parent, array_size);
- /* a NULL terminating sentinal element is required */
- memset(&remaining[totitem_remain], 0, sizeof(EnumPropertyItem));
-
-
- /* yuk, static... issue is we can't reliably free this without doing dangerous changes */
- static PieMenuLevelData lvl;
- BLI_strncpy(lvl.title, block->pie_data.title, UI_MAX_NAME_STR);
- lvl.totitem = totitem_remain;
- lvl.ot = ot;
- lvl.propname = propname;
- lvl.properties = properties;
- lvl.context = context;
- lvl.flag = flag;
-
- /* add a 'more' menu entry */
- uiBut *but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_PLUS, "More", 0, 0, UI_UNIT_X * 3, UI_UNIT_Y, NULL,
- 0.0f, 0.0f, 0.0f, 0.0f, "Show more items of this menu");
- UI_but_funcN_set(but, ui_pie_menu_level_invoke, remaining, &lvl);
-}
-
-/** \} */ /* Pie Menu Levels */
-
-
-/*************************** Standard Popup Menus ****************************/
-
-void UI_popup_menu_reports(bContext *C, ReportList *reports)
-{
- Report *report;
-
- uiPopupMenu *pup = NULL;
- uiLayout *layout;
-
- if (!CTX_wm_window(C))
- return;
-
- for (report = reports->list.first; report; report = report->next) {
- int icon;
- const char *msg, *msg_next;
-
- if (report->type < reports->printlevel) {
- continue;
- }
-
- if (pup == NULL) {
- char title[UI_MAX_DRAW_STR];
- BLI_snprintf(title, sizeof(title), "%s: %s", IFACE_("Report"), report->typestr);
- /* popup_menu stuff does just what we need (but pass meaningful block name) */
- pup = UI_popup_menu_begin_ex(C, title, __func__, ICON_NONE);
- layout = UI_popup_menu_layout(pup);
- }
- else {
- uiItemS(layout);
- }
-
- /* split each newline into a label */
- msg = report->message;
- icon = UI_icon_from_report_type(report->type);
- do {
- char buf[UI_MAX_DRAW_STR];
- msg_next = strchr(msg, '\n');
- if (msg_next) {
- msg_next++;
- BLI_strncpy(buf, msg, MIN2(sizeof(buf), msg_next - msg));
- msg = buf;
- }
- uiItemL(layout, msg, icon);
- icon = ICON_NONE;
- } while ((msg = msg_next) && *msg);
- }
-
- if (pup) {
- UI_popup_menu_end(C, pup);
- }
-}
-
-int UI_popup_menu_invoke(bContext *C, const char *idname, ReportList *reports)
-{
- uiPopupMenu *pup;
- uiLayout *layout;
- Menu menu;
- MenuType *mt = WM_menutype_find(idname, true);
-
- if (mt == NULL) {
- BKE_reportf(reports, RPT_ERROR, "Menu \"%s\" not found", idname);
- return OPERATOR_CANCELLED;
- }
-
- if (mt->poll && mt->poll(C, mt) == 0)
- /* cancel but allow event to pass through, just like operators do */
- return (OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH);
-
- pup = UI_popup_menu_begin(C, IFACE_(mt->label), ICON_NONE);
- layout = UI_popup_menu_layout(pup);
-
- menu.layout = layout;
- menu.type = mt;
-
- if (G.debug & G_DEBUG_WM) {
- printf("%s: opening menu \"%s\"\n", __func__, idname);
- }
-
- mt->draw(C, &menu);
-
- UI_popup_menu_end(C, pup);
-
- return OPERATOR_INTERFACE;
-}
-
-
-/*************************** Popup Block API **************************/
-
-void UI_popup_block_invoke_ex(bContext *C, uiBlockCreateFunc func, void *arg, const char *opname, int opcontext)
-{
- wmWindow *window = CTX_wm_window(C);
- uiPopupBlockHandle *handle;
-
- handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
- handle->popup = true;
- handle->optype = (opname) ? WM_operatortype_find(opname, 0) : NULL;
- handle->opcontext = opcontext;
-
- UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
- WM_event_add_mousemove(C);
-}
-
-void UI_popup_block_invoke(bContext *C, uiBlockCreateFunc func, void *arg)
-{
- UI_popup_block_invoke_ex(C, func, arg, NULL, WM_OP_INVOKE_DEFAULT);
-}
-
-void UI_popup_block_ex(bContext *C, uiBlockCreateFunc func, uiBlockHandleFunc popup_func, uiBlockCancelFunc cancel_func, void *arg)
-{
- wmWindow *window = CTX_wm_window(C);
- uiPopupBlockHandle *handle;
-
- handle = ui_popup_block_create(C, NULL, NULL, func, NULL, arg);
- handle->popup = true;
- handle->retvalue = 1;
-
- handle->popup_arg = arg;
- handle->popup_func = popup_func;
- handle->cancel_func = cancel_func;
- // handle->opcontext = opcontext;
-
- UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
- WM_event_add_mousemove(C);
-}
-
-#if 0 /* UNUSED */
-void uiPupBlockOperator(bContext *C, uiBlockCreateFunc func, wmOperator *op, int opcontext)
-{
- wmWindow *window = CTX_wm_window(C);
- uiPopupBlockHandle *handle;
-
- handle = ui_popup_block_create(C, NULL, NULL, func, NULL, op);
- handle->popup = 1;
- handle->retvalue = 1;
-
- handle->popup_arg = op;
- handle->popup_func = operator_cb;
- handle->cancel_func = confirm_cancel_operator;
- handle->opcontext = opcontext;
-
- UI_popup_handlers_add(C, &window->modalhandlers, handle, 0);
- WM_event_add_mousemove(C);
-}
-#endif
-
-void UI_popup_block_close(bContext *C, wmWindow *win, uiBlock *block)
-{
- /* if loading new .blend while popup is open, window will be NULL */
- if (block->handle) {
- if (win) {
- UI_popup_handlers_remove(&win->modalhandlers, block->handle);
- ui_popup_block_free(C, block->handle);
-
- /* In the case we have nested popups, closing one may need to redraw another, see: T48874 */
- for (ARegion *ar = win->screen->regionbase.first; ar; ar = ar->next) {
- ED_region_tag_refresh_ui(ar);
- }
- }
- }
-}
-
-ColorPicker *ui_block_colorpicker_create(struct uiBlock *block)
-{
- ColorPicker *cpicker = MEM_callocN(sizeof(ColorPicker), "color_picker");
- BLI_addhead(&block->color_pickers.list, cpicker);
-
- return cpicker;
-}
-
-void ui_rgb_to_color_picker_compat_v(const float rgb[3], float r_cp[3])
-{
- switch (U.color_picker_type) {
- case USER_CP_CIRCLE_HSL:
- rgb_to_hsl_compat_v(rgb, r_cp);
- break;
- default:
- rgb_to_hsv_compat_v(rgb, r_cp);
- break;
- }
-}
-
-void ui_rgb_to_color_picker_v(const float rgb[3], float r_cp[3])
-{
- switch (U.color_picker_type) {
- case USER_CP_CIRCLE_HSL:
- rgb_to_hsl_v(rgb, r_cp);
- break;
- default:
- rgb_to_hsv_v(rgb, r_cp);
- break;
- }
-}
-
-void ui_color_picker_to_rgb_v(const float r_cp[3], float rgb[3])
-{
- switch (U.color_picker_type) {
- case USER_CP_CIRCLE_HSL:
- hsl_to_rgb_v(r_cp, rgb);
- break;
- default:
- hsv_to_rgb_v(r_cp, rgb);
- break;
- }
-}
-
-void ui_color_picker_to_rgb(float r_cp0, float r_cp1, float r_cp2, float *r, float *g, float *b)
-{
- switch (U.color_picker_type) {
- case USER_CP_CIRCLE_HSL:
- hsl_to_rgb(r_cp0, r_cp1, r_cp2, r, g, b);
- break;
- default:
- hsv_to_rgb(r_cp0, r_cp1, r_cp2, r, g, b);
- break;
- }
-}
diff --git a/source/blender/editors/interface/interface_regions_intern.h b/source/blender/editors/interface/interface_regions_intern.h
new file mode 100644
index 00000000000..d23cf964c5e
--- /dev/null
+++ b/source/blender/editors/interface/interface_regions_intern.h
@@ -0,0 +1,39 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/interface/interface_regions_intern.h
+ * \ingroup edinterface
+ *
+ * Share between interface_region_*.c files.
+ */
+
+#ifndef __INTERFACE_REGIONS_INTERN_H__
+#define __INTERFACE_REGIONS_INTERN_H__
+
+#define MENU_PADDING (int)(0.2f * UI_UNIT_Y)
+
+/* interface_region_menu_popup.c */
+unsigned int ui_popup_menu_hash(const char *str);
+
+/* interface_regions_intern.h */
+ARegion *ui_region_temp_add(bScreen *sc);
+void ui_region_temp_remove(struct bContext *C, bScreen *sc, ARegion *ar);
+
+#endif /* __INTERFACE_REGIONS_INTERN_H__ */
diff --git a/source/blender/editors/interface/interface_templates.c b/source/blender/editors/interface/interface_templates.c
index 4db1c845c23..b92216138fd 100644
--- a/source/blender/editors/interface/interface_templates.c
+++ b/source/blender/editors/interface/interface_templates.c
@@ -36,7 +36,7 @@
#include "DNA_node_types.h"
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_brush_types.h"
#include "DNA_texture_types.h"
@@ -53,11 +53,13 @@
#include "BLF_api.h"
#include "BLT_translation.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_idcode.h"
+#include "BKE_idprop.h"
#include "BKE_library.h"
#include "BKE_linestyle.h"
#include "BKE_main.h"
@@ -69,12 +71,11 @@
#include "BKE_report.h"
#include "BKE_sca.h"
#include "BKE_screen.h"
-#include "BKE_texture.h"
#include "ED_screen.h"
#include "ED_object.h"
#include "ED_render.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "RNA_access.h"
@@ -87,6 +88,10 @@
#include "PIL_time.h"
+
+// #define USE_OP_RESET_BUT // we may want to make this optional, disable for now.
+
+
void UI_template_fix_linking(void)
{
}
@@ -108,6 +113,8 @@ typedef struct TemplateID {
PropertyRNA *prop;
ListBase *idlb;
+ short idcode;
+ short filter;
int prv_rows, prv_cols;
bool preview;
} TemplateID;
@@ -115,94 +122,165 @@ typedef struct TemplateID {
/* Search browse menu, assign */
static void id_search_call_cb(bContext *C, void *arg_template, void *item)
{
- TemplateID *template = (TemplateID *)arg_template;
+ TemplateID *template_ui = (TemplateID *)arg_template;
/* ID */
if (item) {
PointerRNA idptr;
RNA_id_pointer_create(item, &idptr);
- RNA_property_pointer_set(&template->ptr, template->prop, idptr);
- RNA_property_update(C, &template->ptr, template->prop);
+ RNA_property_pointer_set(&template_ui->ptr, template_ui->prop, idptr);
+ RNA_property_update(C, &template_ui->ptr, template_ui->prop);
+ }
+}
+
+static bool id_search_add(
+ const bContext *C, TemplateID *template_ui,
+ const int flag, const char *str, uiSearchItems *items,
+ ID *id)
+{
+ ID *id_from = template_ui->ptr.id.data;
+
+ if (!((flag & PROP_ID_SELF_CHECK) && id == id_from)) {
+
+ /* use filter */
+ if (RNA_property_type(template_ui->prop) == PROP_POINTER) {
+ PointerRNA ptr;
+ RNA_id_pointer_create(id, &ptr);
+ if (RNA_property_pointer_poll(&template_ui->ptr, template_ui->prop, &ptr) == 0) {
+ return true;
+ }
+ }
+
+ /* hide dot-datablocks, but only if filter does not force it visible */
+ if (U.uiflag & USER_HIDE_DOT) {
+ if ((id->name[2] == '.') && (str[0] != '.')) {
+ return true;
+ }
+ }
+
+ if (*str == '\0' || BLI_strcasestr(id->name + 2, str)) {
+ /* +1 is needed because BKE_id_ui_prefix used 3 letter prefix
+ * followed by ID_NAME-2 characters from id->name
+ */
+ char name_ui[MAX_ID_NAME + 1];
+ BKE_id_ui_prefix(name_ui, id);
+
+ int iconid = ui_id_icon_get(C, id, template_ui->preview);
+
+ if (false == UI_search_item_add(items, name_ui, id, iconid)) {
+ return false;
+ }
+ }
}
+ return true;
}
/* ID Search browse menu, do the search */
static void id_search_cb(const bContext *C, void *arg_template, const char *str, uiSearchItems *items)
{
- TemplateID *template = (TemplateID *)arg_template;
- ListBase *lb = template->idlb;
- ID *id, *id_from = template->ptr.id.data;
- int iconid;
- int flag = RNA_property_flag(template->prop);
+ TemplateID *template_ui = (TemplateID *)arg_template;
+ ListBase *lb = template_ui->idlb;
+ ID *id;
+ int flag = RNA_property_flag(template_ui->prop);
/* ID listbase */
for (id = lb->first; id; id = id->next) {
- if (!((flag & PROP_ID_SELF_CHECK) && id == id_from)) {
-
- /* use filter */
- if (RNA_property_type(template->prop) == PROP_POINTER) {
- PointerRNA ptr;
- RNA_id_pointer_create(id, &ptr);
- if (RNA_property_pointer_poll(&template->ptr, template->prop, &ptr) == 0)
- continue;
- }
-
- /* hide dot-datablocks, but only if filter does not force it visible */
- if (U.uiflag & USER_HIDE_DOT)
- if ((id->name[2] == '.') && (str[0] != '.'))
- continue;
-
- if (*str == '\0' || BLI_strcasestr(id->name + 2, str)) {
- /* +1 is needed because BKE_id_ui_prefix used 3 letter prefix
- * followed by ID_NAME-2 characters from id->name
- */
- char name_ui[MAX_ID_NAME + 1];
- BKE_id_ui_prefix(name_ui, id);
+ if (!id_search_add(C, template_ui, flag, str, items, id)) {
+ break;
+ }
+ }
+}
- iconid = ui_id_icon_get(C, id, template->preview);
+/**
+ * Use id tags for filtering.
+ */
+static void id_search_cb_tagged(const bContext *C, void *arg_template, const char *str, uiSearchItems *items)
+{
+ TemplateID *template_ui = (TemplateID *)arg_template;
+ ListBase *lb = template_ui->idlb;
+ ID *id;
+ int flag = RNA_property_flag(template_ui->prop);
- if (false == UI_search_item_add(items, name_ui, id, iconid))
- break;
+ /* ID listbase */
+ for (id = lb->first; id; id = id->next) {
+ if (id->tag & LIB_TAG_DOIT) {
+ if (!id_search_add(C, template_ui, flag, str, items, id)) {
+ break;
}
+ id->tag &= ~LIB_TAG_DOIT;
}
}
}
+/**
+ * A version of 'id_search_cb' that lists scene objects.
+ */
+static void id_search_cb_objects_from_scene(const bContext *C, void *arg_template, const char *str, uiSearchItems *items)
+{
+ TemplateID *template_ui = (TemplateID *)arg_template;
+ ListBase *lb = template_ui->idlb;
+ Scene *scene = NULL;
+ ID *id_from = template_ui->ptr.id.data;
+
+ if (id_from && GS(id_from->name) == ID_SCE) {
+ scene = (Scene *)id_from;
+ }
+ else {
+ scene = CTX_data_scene(C);
+ }
+
+ BKE_main_id_flag_listbase(lb, LIB_TAG_DOIT, false);
+ for (Base *base = scene->base.first; base; base = base->next) {
+ base->object->id.tag |= LIB_TAG_DOIT;
+ }
+ id_search_cb_tagged(C, arg_template, str, items);
+}
+
/* ID Search browse menu, open */
static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
{
static char search[256];
- static TemplateID template;
+ static TemplateID template_ui;
PointerRNA idptr;
wmWindow *win = CTX_wm_window(C);
uiBlock *block;
uiBut *but;
-
+ void (*id_search_cb_p)(const bContext *, void *, const char *, uiSearchItems *) = id_search_cb;
+
/* clear initial search string, then all items show */
search[0] = 0;
/* arg_litem is malloced, can be freed by parent button */
- template = *((TemplateID *)arg_litem);
+ template_ui = *((TemplateID *)arg_litem);
/* get active id for showing first item */
- idptr = RNA_property_pointer_get(&template.ptr, template.prop);
+ idptr = RNA_property_pointer_get(&template_ui.ptr, template_ui.prop);
+
+ if (template_ui.filter) {
+ /* Currently only used for objects. */
+ if (template_ui.idcode == ID_OB) {
+ if (template_ui.filter == UI_TEMPLATE_ID_FILTER_AVAILABLE) {
+ id_search_cb_p = id_search_cb_objects_from_scene;
+ }
+ }
+ }
block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_SEARCH_MENU);
/* preview thumbnails */
- if (template.prv_rows > 0 && template.prv_cols > 0) {
- int w = 4 * U.widget_unit * template.prv_cols;
- int h = 5 * U.widget_unit * template.prv_rows;
+ if (template_ui.prv_rows > 0 && template_ui.prv_cols > 0) {
+ int w = 4 * U.widget_unit * template_ui.prv_cols;
+ int h = 5 * U.widget_unit * template_ui.prv_rows;
/* fake button, it holds space for search items */
uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 26, w, h, NULL, 0, 0, 0, 0, NULL);
but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, w, UI_UNIT_Y,
- template.prv_rows, template.prv_cols, "");
+ template_ui.prv_rows, template_ui.prv_cols, "");
UI_but_func_search_set(
- but, ui_searchbox_create_generic, id_search_cb,
- &template, id_search_call_cb, idptr.data);
+ but, ui_searchbox_create_generic, id_search_cb_p,
+ &template_ui, id_search_call_cb, idptr.data);
}
/* list view */
else {
@@ -213,8 +291,8 @@ static uiBlock *id_search_menu(bContext *C, ARegion *ar, void *arg_litem)
uiDefBut(block, UI_BTYPE_LABEL, 0, "", 10, 15, searchbox_width, searchbox_height, NULL, 0, 0, 0, 0, NULL);
but = uiDefSearchBut(block, search, 0, ICON_VIEWZOOM, sizeof(search), 10, 0, searchbox_width, UI_UNIT_Y - 1, 0, 0, "");
UI_but_func_search_set(
- but, ui_searchbox_create_generic, id_search_cb,
- &template, id_search_call_cb, idptr.data);
+ but, ui_searchbox_create_generic, id_search_cb_p,
+ &template_ui, id_search_call_cb, idptr.data);
}
@@ -237,7 +315,7 @@ void UI_context_active_but_prop_get_templateID(
bContext *C,
PointerRNA *r_ptr, PropertyRNA **r_prop)
{
- TemplateID *template;
+ TemplateID *template_ui;
ARegion *ar = CTX_wm_region(C);
uiBlock *block;
uiBut *but;
@@ -253,9 +331,9 @@ void UI_context_active_but_prop_get_templateID(
/* find the button before the active one */
if ((but->flag & (UI_BUT_LAST_ACTIVE | UI_ACTIVE))) {
if (but->func_argN) {
- template = but->func_argN;
- *r_ptr = template->ptr;
- *r_prop = template->prop;
+ template_ui = but->func_argN;
+ *r_ptr = template_ui->ptr;
+ *r_prop = template_ui->prop;
return;
}
}
@@ -266,8 +344,8 @@ void UI_context_active_but_prop_get_templateID(
static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
{
- TemplateID *template = (TemplateID *)arg_litem;
- PointerRNA idptr = RNA_property_pointer_get(&template->ptr, template->prop);
+ TemplateID *template_ui = (TemplateID *)arg_litem;
+ PointerRNA idptr = RNA_property_pointer_get(&template_ui->ptr, template_ui->prop);
ID *id = idptr.data;
int event = GET_INT_FROM_POINTER(arg_event);
@@ -282,8 +360,8 @@ static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
break;
case UI_ID_DELETE:
memset(&idptr, 0, sizeof(idptr));
- RNA_property_pointer_set(&template->ptr, template->prop, idptr);
- RNA_property_update(C, &template->ptr, template->prop);
+ RNA_property_pointer_set(&template_ui->ptr, template_ui->prop, idptr);
+ RNA_property_update(C, &template_ui->ptr, template_ui->prop);
if (id && CTX_wm_window(C)->eventstate->shift) {
/* only way to force-remove data (on save) */
@@ -308,16 +386,16 @@ static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
BKE_main_id_clear_newpoins(bmain);
/* reassign to get get proper updates/notifiers */
- idptr = RNA_property_pointer_get(&template->ptr, template->prop);
- RNA_property_pointer_set(&template->ptr, template->prop, idptr);
- RNA_property_update(C, &template->ptr, template->prop);
+ idptr = RNA_property_pointer_get(&template_ui->ptr, template_ui->prop);
+ RNA_property_pointer_set(&template_ui->ptr, template_ui->prop, idptr);
+ RNA_property_update(C, &template_ui->ptr, template_ui->prop);
}
}
break;
case UI_ID_ALONE:
if (id) {
const bool do_scene_obj = (GS(id->name) == ID_OB) &&
- (template->ptr.type == &RNA_SceneObjects);
+ (template_ui->ptr.type == &RNA_SceneObjects);
/* make copy */
if (do_scene_obj) {
@@ -330,7 +408,7 @@ static void template_id_cb(bContext *C, void *arg_litem, void *arg_event)
else {
if (id) {
Main *bmain = CTX_data_main(C);
- id_single_user(C, id, &template->ptr, template->prop);
+ id_single_user(C, id, &template_ui->ptr, template_ui->prop);
DAG_relations_tag_update(bmain);
}
}
@@ -395,7 +473,7 @@ static const char *template_id_context(StructRNA *type)
#endif
static void template_ID(
- bContext *C, uiLayout *layout, TemplateID *template, StructRNA *type, short idcode, int flag,
+ bContext *C, uiLayout *layout, TemplateID *template_ui, StructRNA *type, int flag,
const char *newop, const char *openop, const char *unlinkop)
{
uiBut *but;
@@ -403,12 +481,12 @@ static void template_ID(
PointerRNA idptr;
// ListBase *lb; // UNUSED
ID *id, *idfrom;
- const bool editable = RNA_property_editable(&template->ptr, template->prop);
+ const bool editable = RNA_property_editable(&template_ui->ptr, template_ui->prop);
- idptr = RNA_property_pointer_get(&template->ptr, template->prop);
+ idptr = RNA_property_pointer_get(&template_ui->ptr, template_ui->prop);
id = idptr.data;
- idfrom = template->ptr.id.data;
- // lb = template->idlb;
+ idfrom = template_ui->ptr.id.data;
+ // lb = template_ui->idlb;
block = uiLayoutGetBlock(layout);
UI_block_align_begin(block);
@@ -417,9 +495,9 @@ static void template_ID(
type = idptr.type;
if (flag & UI_ID_PREVIEWS) {
- template->preview = true;
+ template_ui->preview = true;
- but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6,
+ but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 6, UI_UNIT_Y * 6,
TIP_(template_id_browse_tip(type)));
ui_def_but_icon(but, id ? ui_id_icon_get(C, id, true) : RNA_struct_ui_icon(type),
UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
@@ -430,7 +508,7 @@ static void template_ID(
uiLayoutRow(layout, true);
}
else if (flag & UI_ID_BROWSE) {
- but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template), "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y,
+ but = uiDefBlockButN(block, id_search_menu, MEM_dupallocN(template_ui), "", 0, 0, UI_UNIT_X * 1.6, UI_UNIT_Y,
TIP_(template_id_browse_tip(type)));
ui_def_but_icon(but, RNA_struct_ui_icon(type), UI_HAS_ICON);
/* default dragging of icon for id browse buttons */
@@ -450,7 +528,7 @@ static void template_ID(
name[0] = '\0';
but = uiDefButR(block, UI_BTYPE_TEXT, 0, name, 0, 0, UI_UNIT_X * 6, UI_UNIT_Y,
&idptr, "name", -1, 0, 0, -1, -1, RNA_struct_ui_description(type));
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_RENAME));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_RENAME));
if (user_alert) UI_but_flag_enable(but, UI_BUT_REDALERT);
if (id->lib) {
@@ -466,7 +544,7 @@ static void template_ID(
UI_but_flag_enable(but, UI_BUT_DISABLED);
}
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_LOCAL));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_LOCAL));
}
if (id->us > 1) {
@@ -480,7 +558,7 @@ static void template_ID(
TIP_("Display number of users of this data (click to make a single-user copy)"));
but->flag |= UI_BUT_UNDO;
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ALONE));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ALONE));
if (/* test only */
(id_copy(CTX_data_main(C), id, NULL, true) == false) ||
(idfrom && idfrom->lib) ||
@@ -533,12 +611,12 @@ static void template_ID(
if (newop) {
but = uiDefIconTextButO(block, UI_BTYPE_BUT, newop, WM_OP_INVOKE_DEFAULT, ICON_ZOOMIN,
(id) ? "" : CTX_IFACE_(template_id_context(type), "New"), 0, 0, w, UI_UNIT_Y, NULL);
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
}
else {
but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ZOOMIN, (id) ? "" : CTX_IFACE_(template_id_context(type), "New"),
0, 0, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_ADD_NEW));
}
if ((idfrom && idfrom->lib) || !editable)
@@ -562,12 +640,12 @@ static void template_ID(
if (openop) {
but = uiDefIconTextButO(block, UI_BTYPE_BUT, openop, WM_OP_INVOKE_DEFAULT, ICON_FILESEL, (id) ? "" : IFACE_("Open"),
0, 0, w, UI_UNIT_Y, NULL);
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_OPEN));
}
else {
but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILESEL, (id) ? "" : IFACE_("Open"), 0, 0, w, UI_UNIT_Y,
NULL, 0, 0, 0, 0, NULL);
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_OPEN));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_OPEN));
}
if ((idfrom && idfrom->lib) || !editable)
@@ -583,16 +661,16 @@ static void template_ID(
if (unlinkop) {
but = uiDefIconButO(block, UI_BTYPE_BUT, unlinkop, WM_OP_INVOKE_REGION_WIN, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL);
/* so we can access the template from operators, font unlinking needs this */
- UI_but_funcN_set(but, NULL, MEM_dupallocN(template), NULL);
+ UI_but_funcN_set(but, NULL, MEM_dupallocN(template_ui), NULL);
}
else {
- if ((RNA_property_flag(template->prop) & PROP_NEVER_UNLINK) == 0) {
+ if ((RNA_property_flag(template_ui->prop) & PROP_NEVER_UNLINK) == 0) {
but = uiDefIconBut(block, UI_BTYPE_BUT, 0, ICON_X, 0, 0, UI_UNIT_X, UI_UNIT_Y, NULL, 0, 0, 0, 0,
TIP_("Unlink data-block "
"(Shift + Click to set users to zero, data will then not be saved)"));
- UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template), SET_INT_IN_POINTER(UI_ID_DELETE));
+ UI_but_funcN_set(but, template_id_cb, MEM_dupallocN(template_ui), SET_INT_IN_POINTER(UI_ID_DELETE));
- if (RNA_property_flag(template->prop) & PROP_NEVER_NULL) {
+ if (RNA_property_flag(template_ui->prop) & PROP_NEVER_NULL) {
UI_but_flag_enable(but, UI_BUT_DISABLED);
}
}
@@ -605,17 +683,17 @@ static void template_ID(
}
}
- if (idcode == ID_TE)
- uiTemplateTextureShow(layout, C, &template->ptr, template->prop);
-
+ if (template_ui->idcode == ID_TE) {
+ uiTemplateTextureShow(layout, C, &template_ui->ptr, template_ui->prop);
+ }
UI_block_align_end(block);
}
static void ui_template_id(
uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
- const char *openop, const char *unlinkop, int flag, int prv_rows, int prv_cols)
+ const char *openop, const char *unlinkop, int flag, int prv_rows, int prv_cols, int filter)
{
- TemplateID *template;
+ TemplateID *template_ui;
PropertyRNA *prop;
StructRNA *type;
short idcode;
@@ -627,11 +705,18 @@ static void ui_template_id(
return;
}
- template = MEM_callocN(sizeof(TemplateID), "TemplateID");
- template->ptr = *ptr;
- template->prop = prop;
- template->prv_rows = prv_rows;
- template->prv_cols = prv_cols;
+ template_ui = MEM_callocN(sizeof(TemplateID), "TemplateID");
+ template_ui->ptr = *ptr;
+ template_ui->prop = prop;
+ template_ui->prv_rows = prv_rows;
+ template_ui->prv_cols = prv_cols;
+
+ if ((flag & UI_ID_PIN) == 0) {
+ template_ui->filter = filter;
+ }
+ else {
+ template_ui->filter = 0;
+ }
if (newop)
flag |= UI_ID_ADD_NEW;
@@ -640,40 +725,41 @@ static void ui_template_id(
type = RNA_property_pointer_type(ptr, prop);
idcode = RNA_type_to_ID_code(type);
- template->idlb = which_libbase(CTX_data_main(C), idcode);
-
+ template_ui->idcode = idcode;
+ template_ui->idlb = which_libbase(CTX_data_main(C), idcode);
+
/* create UI elements for this template
* - template_ID makes a copy of the template data and assigns it to the relevant buttons
*/
- if (template->idlb) {
+ if (template_ui->idlb) {
uiLayoutRow(layout, true);
- template_ID(C, layout, template, type, idcode, flag, newop, openop, unlinkop);
+ template_ID(C, layout, template_ui, type, flag, newop, openop, unlinkop);
}
- MEM_freeN(template);
+ MEM_freeN(template_ui);
}
void uiTemplateID(
uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
- const char *openop, const char *unlinkop)
+ const char *openop, const char *unlinkop, int filter)
{
ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
- UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0);
+ UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE, 0, 0, filter);
}
void uiTemplateIDBrowse(
uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
- const char *openop, const char *unlinkop)
+ const char *openop, const char *unlinkop, int filter)
{
- ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, UI_ID_BROWSE | UI_ID_RENAME, 0, 0);
+ ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop, UI_ID_BROWSE | UI_ID_RENAME, 0, 0, filter);
}
void uiTemplateIDPreview(
uiLayout *layout, bContext *C, PointerRNA *ptr, const char *propname, const char *newop,
- const char *openop, const char *unlinkop, int rows, int cols)
+ const char *openop, const char *unlinkop, int rows, int cols, int filter)
{
ui_template_id(layout, C, ptr, propname, newop, openop, unlinkop,
- UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols);
+ UI_ID_BROWSE | UI_ID_RENAME | UI_ID_DELETE | UI_ID_PREVIEWS, rows, cols, filter);
}
/************************ ID Chooser Template ***************************/
@@ -981,7 +1067,7 @@ static uiLayout *draw_modifier(
}
UI_block_lock_clear(block);
- UI_block_lock_set(block, ob && ID_IS_LINKED_DATABLOCK(ob), ERROR_LIBDATA_MESSAGE);
+ UI_block_lock_set(block, ob && ID_IS_LINKED(ob), ERROR_LIBDATA_MESSAGE);
if (!ELEM(md->type, eModifierType_Fluidsim, eModifierType_Softbody, eModifierType_ParticleSystem,
eModifierType_Cloth, eModifierType_Smoke))
@@ -1028,7 +1114,7 @@ uiLayout *uiTemplateModifier(uiLayout *layout, bContext *C, PointerRNA *ptr)
return NULL;
}
- UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED_DATABLOCK(ob)), ERROR_LIBDATA_MESSAGE);
+ UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
/* find modifier and draw it */
cageIndex = modifiers_getCageIndex(scene, ob, &lastCageIndex, 0);
@@ -1256,7 +1342,7 @@ uiLayout *uiTemplateConstraint(uiLayout *layout, PointerRNA *ptr)
return NULL;
}
- UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED_DATABLOCK(ob)), ERROR_LIBDATA_MESSAGE);
+ UI_block_lock_set(uiLayoutGetBlock(layout), (ob && ID_IS_LINKED(ob)), ERROR_LIBDATA_MESSAGE);
/* hrms, the temporal constraint should not draw! */
if (con->type == CONSTRAINT_TYPE_KINEMATIC) {
@@ -1446,7 +1532,7 @@ static void colorband_add_cb(bContext *C, void *cb_v, void *coba_v)
else pos = (coba->data[coba->cur + 1].pos + coba->data[coba->cur].pos) * 0.5f;
}
- if (colorband_element_add(coba, pos)) {
+ if (BKE_colorband_element_add(coba, pos)) {
rna_update_cb(C, cb_v, NULL);
ED_undo_push(C, "Add colorband");
}
@@ -1456,7 +1542,7 @@ static void colorband_del_cb(bContext *C, void *cb_v, void *coba_v)
{
ColorBand *coba = coba_v;
- if (colorband_element_remove(coba, coba->cur)) {
+ if (BKE_colorband_element_remove(coba, coba->cur)) {
ED_undo_push(C, "Delete colorband");
rna_update_cb(C, cb_v, NULL);
}
@@ -1492,7 +1578,7 @@ static void colorband_update_cb(bContext *UNUSED(C), void *bt_v, void *coba_v)
/* sneaky update here, we need to sort the colorband points to be in order,
* however the RNA pointer then is wrong, so we update it */
- colorband_update_sort(coba);
+ BKE_colorband_update_sort(coba);
bt->rnapoin.data = coba->data + coba->cur;
}
@@ -1527,6 +1613,11 @@ static void colorband_buttons_layout(
bt = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_ARROW_LEFTRIGHT, "", xs + 4.0f * unit, ys + UI_UNIT_Y, 2.0f * unit, UI_UNIT_Y,
NULL, 0, 0, 0, 0, TIP_("Flip the color ramp"));
UI_but_funcN_set(bt, colorband_flip_cb, MEM_dupallocN(cb), coba);
+
+ bt = uiDefIconButO(block, UI_BTYPE_BUT, "UI_OT_eyedropper_colorband", WM_OP_INVOKE_DEFAULT, ICON_EYEDROPPER, xs + 6.0f * unit, ys + UI_UNIT_Y, UI_UNIT_X, UI_UNIT_Y, NULL);
+ bt->custom_data = coba;
+ bt->func_argN = MEM_dupallocN(cb);
+
UI_block_align_end(block);
UI_block_emboss_set(block, UI_EMBOSS);
@@ -1618,7 +1709,7 @@ void uiTemplateColorRamp(uiLayout *layout, PointerRNA *ptr, const char *propname
block = uiLayoutAbsoluteBlock(layout);
id = cptr.id.data;
- UI_block_lock_set(block, (id && ID_IS_LINKED_DATABLOCK(id)), ERROR_LIBDATA_MESSAGE);
+ UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
colorband_buttons_layout(layout, block, cptr.data, &rect, cb, expand);
@@ -1643,7 +1734,7 @@ static uiBlock *ui_icon_view_menu_cb(bContext *C, ARegion *ar, void *arg_litem)
uiBlock *block;
uiBut *but;
int icon, value;
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int a;
bool free;
int w, h;
@@ -1683,7 +1774,7 @@ static uiBlock *ui_icon_view_menu_cb(bContext *C, ARegion *ar, void *arg_litem)
UI_block_direction_set(block, UI_DIR_DOWN);
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
return block;
@@ -1696,7 +1787,7 @@ void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname,
{
PropertyRNA *prop = RNA_struct_find_property(ptr, propname);
IconViewMenuArgs *cb_args;
- EnumPropertyItem *items;
+ const EnumPropertyItem *items;
uiBlock *block;
uiBut *but;
int value, icon = ICON_NONE, tot_items;
@@ -1724,7 +1815,7 @@ void uiTemplateIconView(uiLayout *layout, PointerRNA *ptr, const char *propname,
ui_def_but_icon(but, icon, UI_HAS_ICON | UI_BUT_ICON_PREVIEW);
if (free_items) {
- MEM_freeN(items);
+ MEM_freeN((void *)items);
}
}
@@ -1978,6 +2069,7 @@ static void curvemap_tools_dofunc(bContext *C, void *cumap_v, int event)
case UICURVE_FUNC_HANDLE_AUTO_ANIM: /* set auto-clamped */
curvemap_handle_set(cuma, HD_AUTO_ANIM);
curvemapping_changed(cumap, false);
+ break;
case UICURVE_FUNC_EXTEND_HOZ: /* extend horiz */
cuma->flag &= ~CUMA_EXTEND_EXTRAPOLATE;
curvemapping_changed(cumap, false);
@@ -2277,7 +2369,7 @@ void uiTemplateCurveMapping(
cb->prop = prop;
id = cptr.id.data;
- UI_block_lock_set(block, (id && ID_IS_LINKED_DATABLOCK(id)), ERROR_LIBDATA_MESSAGE);
+ UI_block_lock_set(block, (id && ID_IS_LINKED(id)), ERROR_LIBDATA_MESSAGE);
curvemap_buttons_layout(layout, &cptr, type, levels, brush, neg_slope, cb);
@@ -2840,7 +2932,7 @@ static void uilist_resize_update_cb(bContext *C, void *arg1, void *UNUSED(arg2))
uiListDyn *dyn_data = ui_list->dyn_data;
/* This way we get diff in number of additional items to show (positive) or hide (negative). */
- const int diff = iroundf((float)(dyn_data->resize - dyn_data->resize_prev) / (float)UI_UNIT_Y);
+ const int diff = round_fl_to_int((float)(dyn_data->resize - dyn_data->resize_prev) / (float)UI_UNIT_Y);
if (diff != 0) {
ui_list->list_grip += diff;
@@ -3350,8 +3442,9 @@ static void operator_search_cb(const bContext *C, void *UNUSED(arg), const char
/* check for hotkey */
if (len < sizeof(name) - 6) {
- if (WM_key_event_operator_string(C, ot->idname, WM_OP_EXEC_DEFAULT, NULL, true,
- sizeof(name) - len - 1, &name[len + 1]))
+ if (WM_key_event_operator_string(
+ C, ot->idname, WM_OP_EXEC_DEFAULT, NULL, true,
+ &name[len + 1], sizeof(name) - len - 1))
{
name[len] = UI_SEP_CHAR;
}
@@ -3384,6 +3477,129 @@ void uiTemplateOperatorSearch(uiLayout *layout)
UI_but_func_operator_search(but);
}
+/************************* Operator Redo Properties Template **************************/
+
+#ifdef USE_OP_RESET_BUT
+static void ui_layout_operator_buts__reset_cb(bContext *UNUSED(C), void *op_pt, void *UNUSED(arg_dummy2))
+{
+ WM_operator_properties_reset((wmOperator *)op_pt);
+}
+#endif
+
+/**
+ * Draw Operator property buttons for redoing execution with different settings.
+ * This function does not initialize the layout, functions can be called on the layout before and after.
+ */
+void uiTemplateOperatorPropertyButs(
+ const bContext *C, uiLayout *layout, wmOperator *op,
+ bool (*check_prop)(struct PointerRNA *, struct PropertyRNA *),
+ const char label_align, const short flag)
+{
+ if (!op->properties) {
+ IDPropertyTemplate val = {0};
+ op->properties = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
+ }
+
+ if (flag & UI_TEMPLATE_OP_PROPS_SHOW_TITLE) {
+ uiItemL(layout, RNA_struct_ui_name(op->type->srna), ICON_NONE);
+ }
+
+ /* poll() on this operator may still fail, at the moment there is no nice feedback when this happens
+ * just fails silently */
+ if (!WM_operator_repeat_check(C, op)) {
+ UI_block_lock_set(uiLayoutGetBlock(layout), true, "Operator can't' redo");
+
+ /* XXX, could give some nicer feedback or not show redo panel at all? */
+ uiItemL(layout, IFACE_("* Redo Unsupported *"), ICON_NONE);
+ }
+ else {
+ /* useful for macros where only one of the steps can't be re-done */
+ UI_block_lock_clear(uiLayoutGetBlock(layout));
+ }
+
+ /* menu */
+ if (op->type->flag & OPTYPE_PRESET) {
+ /* XXX, no simple way to get WM_MT_operator_presets.bl_label from python! Label remains the same always! */
+ PointerRNA op_ptr;
+ uiLayout *row;
+
+ uiLayoutGetBlock(layout)->ui_operator = op;
+
+ row = uiLayoutRow(layout, true);
+ uiItemM(row, (bContext *)C, "WM_MT_operator_presets", NULL, ICON_NONE);
+
+ wmOperatorType *ot = WM_operatortype_find("WM_OT_operator_preset_add", false);
+ uiItemFullO_ptr(row, ot, "", ICON_ZOOMIN, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
+ RNA_string_set(&op_ptr, "operator", op->type->idname);
+
+ uiItemFullO_ptr(row, ot, "", ICON_ZOOMOUT, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
+ RNA_string_set(&op_ptr, "operator", op->type->idname);
+ RNA_boolean_set(&op_ptr, "remove_active", true);
+ }
+
+ if (op->type->ui) {
+ op->layout = layout;
+ op->type->ui((bContext *)C, op);
+ op->layout = NULL;
+
+ /* UI_LAYOUT_OP_SHOW_EMPTY ignored */
+ }
+ else {
+ wmWindowManager *wm = CTX_wm_manager(C);
+ PointerRNA ptr;
+ int empty;
+
+ RNA_pointer_create(&wm->id, op->type->srna, op->properties, &ptr);
+
+ /* main draw call */
+ empty = uiDefAutoButsRNA(layout, &ptr, check_prop, label_align) == 0;
+
+ if (empty && (flag & UI_TEMPLATE_OP_PROPS_SHOW_EMPTY)) {
+ uiItemL(layout, IFACE_("No Properties"), ICON_NONE);
+ }
+ }
+
+#ifdef USE_OP_RESET_BUT
+ /* its possible that reset can do nothing if all have PROP_SKIP_SAVE enabled
+ * but this is not so important if this button is drawn in those cases
+ * (which isn't all that likely anyway) - campbell */
+ if (op->properties->len) {
+ uiBlock *block;
+ uiBut *but;
+ uiLayout *col; /* needed to avoid alignment errors with previous buttons */
+
+ col = uiLayoutColumn(layout, false);
+ block = uiLayoutGetBlock(col);
+ but = uiDefIconTextBut(block, UI_BTYPE_BUT, 0, ICON_FILE_REFRESH, IFACE_("Reset"), 0, 0, UI_UNIT_X, UI_UNIT_Y,
+ NULL, 0.0, 0.0, 0.0, 0.0, TIP_("Reset operator defaults"));
+ UI_but_func_set(but, ui_layout_operator_buts__reset_cb, op, NULL);
+ }
+#endif
+
+ /* set various special settings for buttons */
+ {
+ uiBlock *block = uiLayoutGetBlock(layout);
+ const bool is_popup = (block->flag & UI_BLOCK_KEEP_OPEN) != 0;
+ uiBut *but;
+
+ for (but = block->buttons.first; but; but = but->next) {
+ /* no undo for buttons for operator redo panels */
+ UI_but_flag_disable(but, UI_BUT_UNDO);
+
+ /* only for popups, see [#36109] */
+
+ /* if button is operator's default property, and a text-field, enable focus for it
+ * - this is used for allowing operators with popups to rename stuff with fewer clicks
+ */
+ if (is_popup) {
+ if ((but->rnaprop == op->type->prop) && (but->type == UI_BTYPE_TEXT)) {
+ UI_but_focus_on_enter_event(CTX_wm_window(C), but);
+ }
+ }
+ }
+ }
+}
+
/************************* Running Jobs Template **************************/
#define B_STOPRENDER 1
@@ -3883,7 +4099,7 @@ void uiTemplateCacheFile(uiLayout *layout, bContext *C, PointerRNA *ptr, const c
uiLayoutSetContextPointer(layout, "edit_cachefile", &fileptr);
- uiTemplateID(layout, C, ptr, propname, NULL, "CACHEFILE_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, propname, NULL, "CACHEFILE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!file) {
return;
@@ -3913,6 +4129,9 @@ void uiTemplateCacheFile(uiLayout *layout, bContext *C, PointerRNA *ptr, const c
uiItemR(row, &fileptr, "frame", 0, "Frame", ICON_NONE);
row = uiLayoutRow(layout, false);
+ uiItemR(row, &fileptr, "frame_offset", 0, "Frame Offset", ICON_NONE);
+
+ row = uiLayoutRow(layout, false);
uiItemL(row, IFACE_("Manual Transform:"), ICON_NONE);
row = uiLayoutRow(layout, false);
diff --git a/source/blender/editors/interface/interface_utils.c b/source/blender/editors/interface/interface_utils.c
index df6f098ee81..1927d7280f3 100644
--- a/source/blender/editors/interface/interface_utils.c
+++ b/source/blender/editors/interface/interface_utils.c
@@ -127,12 +127,10 @@ uiBut *uiDefAutoButR(uiBlock *block, PointerRNA *ptr, PropertyRNA *prop, int ind
break;
case PROP_POINTER:
{
- PointerRNA pptr;
-
- pptr = RNA_property_pointer_get(ptr, prop);
- if (!pptr.type)
- pptr.type = RNA_property_pointer_type(ptr, prop);
- icon = RNA_struct_ui_icon(pptr.type);
+ if (icon == 0) {
+ PointerRNA pptr = RNA_property_pointer_get(ptr, prop);
+ icon = RNA_struct_ui_icon(pptr.type ? pptr.type : RNA_property_pointer_type(ptr, prop));
+ }
if (icon == ICON_DOT)
icon = 0;
@@ -267,7 +265,7 @@ int UI_icon_from_report_type(int type)
*/
int UI_calc_float_precision(int prec, double value)
{
- static const double pow10_neg[UI_PRECISION_FLOAT_MAX + 1] = {1e0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7};
+ static const double pow10_neg[UI_PRECISION_FLOAT_MAX + 1] = {1e0, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6};
static const double max_pow = 10000000.0; /* pow(10, UI_PRECISION_FLOAT_MAX) */
BLI_assert(prec <= UI_PRECISION_FLOAT_MAX);
@@ -382,6 +380,17 @@ uiButStore *UI_butstore_create(uiBlock *block)
void UI_butstore_free(uiBlock *block, uiButStore *bs_handle)
{
+ /* Workaround for button store being moved into new block,
+ * which then can't use the previous buttons state ('ui_but_update_from_old_block' fails to find a match),
+ * keeping the active button in the old block holding a reference to the button-state in the new block: see T49034.
+ *
+ * Ideally we would manage moving the 'uiButStore', keeping a correct state.
+ * All things considered this is the most straightforward fix - Campbell.
+ */
+ if (block != bs_handle->block && bs_handle->block != NULL) {
+ block = bs_handle->block;
+ }
+
BLI_freelistN(&bs_handle->items);
BLI_remlink(&block->butstore, bs_handle);
diff --git a/source/blender/editors/interface/interface_widgets.c b/source/blender/editors/interface/interface_widgets.c
index b3736a71e74..f1f193f1b02 100644
--- a/source/blender/editors/interface/interface_widgets.c
+++ b/source/blender/editors/interface/interface_widgets.c
@@ -66,6 +66,19 @@
/* icons are 80% of height of button (16 pixels inside 20 height) */
#define ICON_SIZE_FROM_BUTRECT(rect) (0.8f * BLI_rcti_size_y(rect))
+/* Button state argument shares bits with 'uiBut.flag'.
+ * reuse flags that aren't needed for drawing to avoid collision. */
+enum {
+ /* Show that holding the button opens a menu. */
+ UI_STATE_HOLD_ACTION = UI_BUT_UPDATE_DELAY,
+ UI_STATE_TEXT_INPUT = UI_BUT_UNDO,
+
+ UI_STATE_FLAGS_ALL = (UI_STATE_HOLD_ACTION | UI_STATE_TEXT_INPUT),
+};
+/* Prevent accidental use. */
+#define UI_BUT_UPDATE_DELAY ((void)0)
+#define UI_BUT_UNDO ((void)0)
+
/* ************** widget base functions ************** */
/**
* - in: roundbox codes for corner types and radius
@@ -145,45 +158,54 @@ static const float jit[WIDGET_AA_JITTER][2] = {
{-0.272855, 0.269918}, { 0.095909, 0.388710}
};
-static const float num_tria_vert[3][2] = {
+/* -------------------------------------------------------------------- */
+/** \name Shape Preset Data
+ * \{ */
+
+static const float g_shape_preset_number_arrow_vert[3][2] = {
{-0.352077, 0.532607}, {-0.352077, -0.549313}, {0.330000, -0.008353}
};
-
-static const unsigned int num_tria_face[1][3] = {
+static const uint g_shape_preset_number_arrow_face[1][3] = {
{0, 1, 2}
};
-static const float scroll_circle_vert[16][2] = {
+static const float g_shape_preset_scroll_circle_vert[16][2] = {
{0.382684, 0.923879}, {0.000001, 1.000000}, {-0.382683, 0.923880}, {-0.707107, 0.707107},
{-0.923879, 0.382684}, {-1.000000, 0.000000}, {-0.923880, -0.382684}, {-0.707107, -0.707107},
{-0.382683, -0.923880}, {0.000000, -1.000000}, {0.382684, -0.923880}, {0.707107, -0.707107},
{0.923880, -0.382684}, {1.000000, -0.000000}, {0.923880, 0.382683}, {0.707107, 0.707107}
};
-
-static const unsigned int scroll_circle_face[14][3] = {
+static const uint g_shape_preset_scroll_circle_face[14][3] = {
{0, 1, 2}, {2, 0, 3}, {3, 0, 15}, {3, 15, 4}, {4, 15, 14}, {4, 14, 5}, {5, 14, 13}, {5, 13, 6},
{6, 13, 12}, {6, 12, 7}, {7, 12, 11}, {7, 11, 8}, {8, 11, 10}, {8, 10, 9}
};
-
-static const float menu_tria_vert[6][2] = {
+static const float g_shape_preset_menu_arrow_vert[6][2] = {
{-0.33, 0.16}, {0.33, 0.16}, {0, 0.82},
{0, -0.82}, {-0.33, -0.16}, {0.33, -0.16}
};
+static const uint g_shape_preset_menu_arrow_face[2][3] = {{2, 0, 1}, {3, 5, 4}};
-
-
-static const unsigned int menu_tria_face[2][3] = {{2, 0, 1}, {3, 5, 4}};
-
-static const float check_tria_vert[6][2] = {
+static const float g_shape_preset_checkmark_vert[6][2] = {
{-0.578579, 0.253369}, {-0.392773, 0.412794}, {-0.004241, -0.328551},
{-0.003001, 0.034320}, {1.055313, 0.864744}, {0.866408, 1.026895}
};
-static const unsigned int check_tria_face[4][3] = {
+static const uint g_shape_preset_checkmark_face[4][3] = {
{3, 2, 4}, {3, 4, 5}, {1, 0, 3}, {0, 2, 3}
};
+#define OY -0.2
+#define SC 0.35
+static const float g_shape_preset_hold_action_vert[6][2] = {
+ {-0.5 + SC, 1.0 + OY}, {0.5, 1.0 + OY}, {0.5, 0.0 + OY + SC},
+};
+static const uint g_shape_preset_hold_action_face[2][3] = {{2, 0, 1}, {3, 5, 4}};
+#undef OY
+#undef SC
+
+/** \} */
+
/* ************************************************* */
void ui_draw_anti_tria(float x1, float y1, float x2, float y2, float x3, float y3)
@@ -480,9 +502,12 @@ static void round_box_edges(uiWidgetBase *wt, int roundboxalign, const rcti *rec
round_box__edges(wt, roundboxalign, rect, rad, rad - U.pixelsize);
}
+/* -------------------------------------------------------------------- */
+/** \name Shape Preset Mini API
+ * \{ */
/* based on button rect, return scaled array of triangles */
-static void widget_draw_tria_ex(
+static void shape_preset_init_trias_ex(
uiWidgetTrias *tria, const rcti *rect, float triasize, char where,
/* input data */
const float verts[][2], const int verts_tot,
@@ -521,23 +546,31 @@ static void widget_draw_tria_ex(
tria->index = tris;
}
-static void widget_num_tria(uiWidgetTrias *tria, const rcti *rect, float triasize, char where)
+static void shape_preset_init_number_arrows(uiWidgetTrias *tria, const rcti *rect, float triasize, char where)
+{
+ shape_preset_init_trias_ex(
+ tria, rect, triasize, where,
+ g_shape_preset_number_arrow_vert, ARRAY_SIZE(g_shape_preset_number_arrow_vert),
+ g_shape_preset_number_arrow_face, ARRAY_SIZE(g_shape_preset_number_arrow_face));
+}
+
+static void shape_preset_init_hold_action(uiWidgetTrias *tria, const rcti *rect, float triasize, char where)
{
- widget_draw_tria_ex(
+ shape_preset_init_trias_ex(
tria, rect, triasize, where,
- num_tria_vert, ARRAY_SIZE(num_tria_vert),
- num_tria_face, ARRAY_SIZE(num_tria_face));
+ g_shape_preset_hold_action_vert, ARRAY_SIZE(g_shape_preset_hold_action_vert),
+ g_shape_preset_hold_action_face, ARRAY_SIZE(g_shape_preset_hold_action_face));
}
-static void widget_scroll_circle(uiWidgetTrias *tria, const rcti *rect, float triasize, char where)
+static void shape_preset_init_scroll_circle(uiWidgetTrias *tria, const rcti *rect, float triasize, char where)
{
- widget_draw_tria_ex(
+ shape_preset_init_trias_ex(
tria, rect, triasize, where,
- scroll_circle_vert, ARRAY_SIZE(scroll_circle_vert),
- scroll_circle_face, ARRAY_SIZE(scroll_circle_face));
+ g_shape_preset_scroll_circle_vert, ARRAY_SIZE(g_shape_preset_scroll_circle_vert),
+ g_shape_preset_scroll_circle_face, ARRAY_SIZE(g_shape_preset_scroll_circle_face));
}
-static void widget_trias_draw(uiWidgetTrias *tria)
+static void shape_preset_draw_trias(uiWidgetTrias *tria)
{
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, tria->vec);
@@ -545,7 +578,7 @@ static void widget_trias_draw(uiWidgetTrias *tria)
glDisableClientState(GL_VERTEX_ARRAY);
}
-static void widget_menu_trias(uiWidgetTrias *tria, const rcti *rect)
+static void shape_preset_trias_from_rect_menu(uiWidgetTrias *tria, const rcti *rect)
{
float centx, centy, size;
int a;
@@ -556,15 +589,15 @@ static void widget_menu_trias(uiWidgetTrias *tria, const rcti *rect)
size = 0.4f * BLI_rcti_size_y(rect);
for (a = 0; a < 6; a++) {
- tria->vec[a][0] = size * menu_tria_vert[a][0] + centx;
- tria->vec[a][1] = size * menu_tria_vert[a][1] + centy;
+ tria->vec[a][0] = size * g_shape_preset_menu_arrow_vert[a][0] + centx;
+ tria->vec[a][1] = size * g_shape_preset_menu_arrow_vert[a][1] + centy;
}
tria->tot = 2;
- tria->index = menu_tria_face;
+ tria->index = g_shape_preset_menu_arrow_face;
}
-static void widget_check_trias(uiWidgetTrias *tria, const rcti *rect)
+static void shape_preset_trias_from_rect_checkmark(uiWidgetTrias *tria, const rcti *rect)
{
float centx, centy, size;
int a;
@@ -575,14 +608,16 @@ static void widget_check_trias(uiWidgetTrias *tria, const rcti *rect)
size = 0.5f * BLI_rcti_size_y(rect);
for (a = 0; a < 6; a++) {
- tria->vec[a][0] = size * check_tria_vert[a][0] + centx;
- tria->vec[a][1] = size * check_tria_vert[a][1] + centy;
+ tria->vec[a][0] = size * g_shape_preset_checkmark_vert[a][0] + centx;
+ tria->vec[a][1] = size * g_shape_preset_checkmark_vert[a][1] + centy;
}
tria->tot = 4;
- tria->index = check_tria_face;
+ tria->index = g_shape_preset_checkmark_face;
}
+/** \} */
+
/* prepares shade colors */
static void shadecolors4(char coltop[4], char coldown[4], const char *color, short shadetop, short shadedown)
@@ -650,6 +685,7 @@ static void widgetbase_draw(uiWidgetBase *wtb, uiWidgetColors *wcol)
/* backdrop non AA */
if (wtb->draw_inner) {
+ BLI_assert(wtb->totvert != 0);
if (wcol->shaded == 0) {
if (wcol->alpha_check) {
float inner_v_half[WIDGET_SIZE_MAX][2];
@@ -729,6 +765,7 @@ static void widgetbase_draw(uiWidgetBase *wtb, uiWidgetColors *wcol)
/* for each AA step */
if (wtb->draw_outline) {
+ BLI_assert(wtb->totvert != 0);
float triangle_strip[WIDGET_SIZE_MAX * 2 + 2][2]; /* + 2 because the last pair is wrapped */
float triangle_strip_emboss[WIDGET_SIZE_MAX * 2][2]; /* only for emboss */
@@ -783,12 +820,13 @@ static void widgetbase_draw(uiWidgetBase *wtb, uiWidgetColors *wcol)
for (j = 0; j < WIDGET_AA_JITTER; j++) {
glTranslate2fv(jit[j]);
- if (wtb->tria1.tot)
- widget_trias_draw(&wtb->tria1);
+ if (wtb->tria1.tot) {
+ shape_preset_draw_trias(&wtb->tria1);
+ }
+ if (wtb->tria2.tot) {
+ shape_preset_draw_trias(&wtb->tria2);
+ }
- if (wtb->tria2.tot)
- widget_trias_draw(&wtb->tria2);
-
glTranslatef(-jit[j][0], -jit[j][1], 0.0f);
}
}
@@ -830,9 +868,9 @@ static int ui_but_draw_menu_icon(const uiBut *but)
/* icons have been standardized... and this call draws in untransformed coordinates */
-static void widget_draw_icon(
- const uiBut *but, BIFIconID icon, float alpha, const rcti *rect,
- const bool show_menu_icon)
+static void widget_draw_icon_ex(
+ const uiBut *but, BIFIconID icon, float alpha, const rcti *rect, const bool show_menu_icon,
+ const int icon_size)
{
float xs = 0.0f, ys = 0.0f;
float aspect, height;
@@ -848,7 +886,7 @@ static void widget_draw_icon(
if (icon == ICON_BLANK1 && (but->flag & UI_BUT_ICON_SUBMENU) == 0) return;
aspect = but->block->aspect / UI_DPI_FAC;
- height = ICON_DEFAULT_HEIGHT / aspect;
+ height = icon_size / aspect;
/* calculate blend color */
if (ELEM(but->type, UI_BTYPE_TOGGLE, UI_BTYPE_ROW, UI_BTYPE_TOGGLE_N, UI_BTYPE_LISTROW)) {
@@ -874,21 +912,18 @@ static void widget_draw_icon(
float ofs = 1.0f / aspect;
if (but->drawflag & UI_BUT_ICON_LEFT) {
- if (but->block->flag & UI_BLOCK_LOOP) {
- if (but->type == UI_BTYPE_SEARCH_MENU)
- xs = rect->xmin + 4.0f * ofs;
- else
- xs = rect->xmin + ofs;
- }
- else {
+ /* special case - icon_only pie buttons */
+ if (ui_block_is_pie_menu(but->block) && but->type != UI_BTYPE_MENU && but->str && but->str[0] == '\0')
+ xs = rect->xmin + 2.0f * ofs;
+ else if (but->dt == UI_EMBOSS_NONE || but->type == UI_BTYPE_LABEL)
+ xs = rect->xmin + 2.0f * ofs;
+ else
xs = rect->xmin + 4.0f * ofs;
- }
- ys = (rect->ymin + rect->ymax - height) / 2.0f;
}
else {
xs = (rect->xmin + rect->xmax - height) / 2.0f;
- ys = (rect->ymin + rect->ymax - height) / 2.0f;
}
+ ys = (rect->ymin + rect->ymax - height) / 2.0f;
/* force positions to integers, for zoom levels near 1. draws icons crisp. */
if (aspect > 0.95f && aspect < 1.05f) {
@@ -915,6 +950,12 @@ static void widget_draw_icon(
glDisable(GL_BLEND);
}
+static void widget_draw_icon(
+ const uiBut *but, BIFIconID icon, float alpha, const rcti *rect, const bool show_menu_icon)
+{
+ widget_draw_icon_ex(but, icon, alpha, rect, show_menu_icon, ICON_DEFAULT_HEIGHT);
+}
+
static void ui_text_clip_give_prev_off(uiBut *but, const char *str)
{
const char *prev_utf8 = BLI_str_find_prev_char_utf8(str, str + but->ofs);
@@ -1520,6 +1561,7 @@ static void widget_draw_text_icon(uiFontStyle *fstyle, uiWidgetColors *wcol, uiB
rcti temp = *rect;
temp.xmin = rect->xmax - BLI_rcti_size_y(rect) - 1;
widget_draw_icon(but, ICON_LAYER_USED, alpha, &temp, false);
+ rect->xmax = temp.xmin;
}
/* If there's an icon too (made with uiDefIconTextBut) then draw the icon
@@ -1554,11 +1596,15 @@ static void widget_draw_text_icon(uiFontStyle *fstyle, uiWidgetColors *wcol, uiB
/* Icons on the left with optional text label on the right */
else if (but->flag & UI_HAS_ICON || show_menu_icon) {
const BIFIconID icon = (but->flag & UI_HAS_ICON) ? but->icon + but->iconadd : ICON_NONE;
- const float icon_size = ICON_SIZE_FROM_BUTRECT(rect);
+ const float icon_size = ICON_DEFAULT_WIDTH_SCALE;
/* menu item - add some more padding so menus don't feel cramped. it must
* be part of the button so that this area is still clickable */
- if (ui_block_is_menu(but->block))
+ if (ui_block_is_pie_menu(but->block)) {
+ if (but->dt == UI_EMBOSS_RADIAL)
+ rect->xmin += 0.3f * U.widget_unit;
+ }
+ else if (ui_block_is_menu(but->block))
rect->xmin += 0.3f * U.widget_unit;
widget_draw_icon(but, icon, alpha, rect, show_menu_icon);
@@ -1951,7 +1997,7 @@ static void widget_state(uiWidgetType *wt, int state)
{
uiWidgetStateColors *wcol_state = wt->wcol_state;
- if ((state & UI_BUT_LIST_ITEM) && !(state & UI_TEXTINPUT)) {
+ if ((state & UI_BUT_LIST_ITEM) && !(state & UI_STATE_TEXT_INPUT)) {
/* Override default widget's colors. */
bTheme *btheme = UI_GetTheme();
wt->wcol_theme = &btheme->tui.wcol_list_item;
@@ -2643,16 +2689,20 @@ static void widget_numbut_draw(uiWidgetColors *wcol, rcti *rect, int state, int
if (!emboss) {
round_box_edges(&wtb, roundboxalign, rect, rad);
}
+ else {
+ wtb.draw_inner = false;
+ wtb.draw_outline = false;
+ }
/* decoration */
- if (!(state & UI_TEXTINPUT)) {
- widget_num_tria(&wtb.tria1, rect, 0.6f, 'l');
- widget_num_tria(&wtb.tria2, rect, 0.6f, 'r');
+ if (!(state & UI_STATE_TEXT_INPUT)) {
+ shape_preset_init_number_arrows(&wtb.tria1, rect, 0.6f, 'l');
+ shape_preset_init_number_arrows(&wtb.tria2, rect, 0.6f, 'r');
}
widgetbase_draw(&wtb, wcol);
- if (!(state & UI_TEXTINPUT)) {
+ if (!(state & UI_STATE_TEXT_INPUT)) {
/* text space */
rect->xmin += textofs;
rect->xmax -= textofs;
@@ -2782,12 +2832,12 @@ void UI_draw_widget_scroll(uiWidgetColors *wcol, const rcti *rect, const rcti *s
wcol->item[3] = 255;
if (horizontal) {
- widget_scroll_circle(&wtb.tria1, slider, 0.6f, 'l');
- widget_scroll_circle(&wtb.tria2, slider, 0.6f, 'r');
+ shape_preset_init_scroll_circle(&wtb.tria1, slider, 0.6f, 'l');
+ shape_preset_init_scroll_circle(&wtb.tria2, slider, 0.6f, 'r');
}
else {
- widget_scroll_circle(&wtb.tria1, slider, 0.6f, 'b');
- widget_scroll_circle(&wtb.tria2, slider, 0.6f, 't');
+ shape_preset_init_scroll_circle(&wtb.tria1, slider, 0.6f, 'b');
+ shape_preset_init_scroll_circle(&wtb.tria2, slider, 0.6f, 't');
}
}
widgetbase_draw(&wtb, wcol);
@@ -2931,7 +2981,7 @@ static void widget_numslider(uiBut *but, uiWidgetColors *wcol, rcti *rect, int s
widgetbase_draw(&wtb, wcol);
/* draw left/right parts only when not in text editing */
- if (!(state & UI_TEXTINPUT)) {
+ if (!(state & UI_STATE_TEXT_INPUT)) {
int roundboxalign_slider;
/* slider part */
@@ -2982,7 +3032,7 @@ static void widget_numslider(uiBut *but, uiWidgetColors *wcol, rcti *rect, int s
widgetbase_draw(&wtb, wcol);
/* add space at either side of the button so text aligns with numbuttons (which have arrow icons) */
- if (!(state & UI_TEXTINPUT)) {
+ if (!(state & UI_STATE_TEXT_INPUT)) {
rect->xmax -= toffs;
rect->xmin += toffs;
}
@@ -3124,7 +3174,7 @@ static void widget_menubut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state),
round_box_edges(&wtb, roundboxalign, rect, rad);
/* decoration */
- widget_menu_trias(&wtb.tria1, rect);
+ shape_preset_trias_from_rect_menu(&wtb.tria1, rect);
widgetbase_draw(&wtb, wcol);
@@ -3263,7 +3313,7 @@ static void widget_optionbut(uiWidgetColors *wcol, rcti *rect, int state, int UN
/* decoration */
if (state & UI_SELECT) {
- widget_check_trias(&wtb.tria1, &recttemp);
+ shape_preset_trias_from_rect_checkmark(&wtb.tria1, &recttemp);
}
widgetbase_draw(&wtb, wcol);
@@ -3346,6 +3396,7 @@ static void widget_but(uiWidgetColors *wcol, rcti *rect, int UNUSED(state), int
widgetbase_draw(&wtb, wcol);
}
+#if 0
static void widget_roundbut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state), int roundboxalign)
{
uiWidgetBase wtb;
@@ -3358,6 +3409,25 @@ static void widget_roundbut(uiWidgetColors *wcol, rcti *rect, int UNUSED(state),
widgetbase_draw(&wtb, wcol);
}
+#endif
+
+static void widget_roundbut_exec(uiWidgetColors *wcol, rcti *rect, int state, int roundboxalign)
+{
+ uiWidgetBase wtb;
+ const float rad = 0.25f * U.widget_unit;
+
+ widget_init(&wtb);
+
+ if (state & UI_STATE_HOLD_ACTION) {
+ /* Show that keeping pressed performs another action (typically a menu). */
+ shape_preset_init_hold_action(&wtb.tria1, rect, 0.75f, 'r');
+ }
+
+ /* half rounded */
+ round_box_edges(&wtb, roundboxalign, rect, rad);
+
+ widgetbase_draw(&wtb, wcol);
+}
static void widget_draw_extra_mask(const bContext *C, uiBut *but, uiWidgetType *wt, rcti *rect)
{
@@ -3438,7 +3508,7 @@ static uiWidgetType *widget_type(uiWidgetTypeEnum type)
case UI_WTYPE_EXEC:
wt.wcol_theme = &btheme->tui.wcol_tool;
- wt.draw = widget_roundbut;
+ wt.draw = widget_roundbut_exec;
break;
case UI_WTYPE_TOOLTIP:
@@ -3613,6 +3683,10 @@ static int widget_roundbox_set(uiBut *but, rcti *rect)
return roundbox;
}
+/* -------------------------------------------------------------------- */
+/** \name Public API
+ * \{ */
+
/* conversion from old to new buttons, so still messy */
void ui_draw_but(const bContext *C, ARegion *ar, uiStyle *style, uiBut *but, rcti *rect)
{
@@ -3654,11 +3728,15 @@ void ui_draw_but(const bContext *C, ARegion *ar, uiStyle *style, uiBut *but, rct
switch (but->type) {
case UI_BTYPE_LABEL:
- if (but->block->flag & UI_BLOCK_LOOP)
- widget_draw_text_icon(&style->widgetlabel, &tui->wcol_menu_back, but, rect);
- else {
- wt = widget_type(UI_WTYPE_LABEL);
- fstyle = &style->widgetlabel;
+ wt = widget_type(UI_WTYPE_LABEL);
+ fstyle = &style->widgetlabel;
+ if (but->drawflag & UI_BUT_BOX_ITEM) {
+ wt->wcol_theme = &tui->wcol_box;
+ wt->state = widget_state;
+ }
+ else if (but->block->flag & UI_BLOCK_LOOP) {
+ wt->wcol_theme = &tui->wcol_menu_back;
+ wt->state = widget_state;
}
break;
@@ -3844,12 +3922,21 @@ void ui_draw_but(const bContext *C, ARegion *ar, uiStyle *style, uiBut *but, rct
roundboxalign = widget_roundbox_set(but, rect);
- state = but->flag;
+ /* Mask out flags re-used for local state. */
+ state = but->flag & ~UI_STATE_FLAGS_ALL;
+
+ if (state & UI_SELECT_DRAW) {
+ state |= UI_SELECT;
+ }
if ((but->editstr) ||
(UNLIKELY(but->flag & UI_BUT_DRAG_MULTI) && ui_but_drag_multi_edit_get(but)))
{
- state |= UI_TEXTINPUT;
+ state |= UI_STATE_TEXT_INPUT;
+ }
+
+ if (but->hold_func) {
+ state |= UI_STATE_HOLD_ACTION;
}
if (state & (UI_BUT_DISABLED | UI_BUT_INACTIVE))
@@ -4178,3 +4265,5 @@ void ui_draw_preview_item(uiFontStyle *fstyle, rcti *rect, const char *name, int
UI_fontstyle_draw(fstyle, &trect, drawstr);
}
}
+
+/** \} */
diff --git a/source/blender/editors/interface/resources.c b/source/blender/editors/interface/resources.c
index 539284030c2..33d0b2ae608 100644
--- a/source/blender/editors/interface/resources.c
+++ b/source/blender/editors/interface/resources.c
@@ -45,11 +45,12 @@
#include "BLI_utildefines.h"
#include "BLI_math.h"
+#include "BKE_addon.h"
#include "BKE_appdir.h"
+#include "BKE_colorband.h"
#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
#include "BKE_main.h"
-#include "BKE_texture.h"
#include "BIF_gl.h"
@@ -1839,7 +1840,7 @@ void init_userdef_do_versions(void)
rgba_char_args_set(btheme->tv3d.editmesh_active, 255, 255, 255, 128);
}
if (U.coba_weight.tot == 0)
- init_colorband(&U.coba_weight, true);
+ BKE_colorband_init(&U.coba_weight, true);
}
if (!USER_VERSION_ATLEAST(245, 3)) {
bTheme *btheme;
@@ -2146,13 +2147,9 @@ void init_userdef_do_versions(void)
if (btheme->tipo.handle_sel_auto_clamped[3] == 0)
rgba_char_args_set(btheme->tipo.handle_sel_auto_clamped, 0xf0, 0xaf, 0x90, 255);
}
-
+
/* enable (Cycles) addon by default */
- if (!BLI_findstring(&U.addons, "cycles", offsetof(bAddon, module))) {
- bAddon *baddon = MEM_callocN(sizeof(bAddon), "bAddon");
- BLI_strncpy(baddon->module, "cycles", sizeof(baddon->module));
- BLI_addtail(&U.addons, baddon);
- }
+ BKE_addon_ensure(&U.addons, "cycles");
}
if (!USER_VERSION_ATLEAST(260, 5)) {
@@ -2758,13 +2755,29 @@ void init_userdef_do_versions(void)
}
}
+ if (!USER_VERSION_ATLEAST(278, 6)) {
+ /* Clear preference flags for re-use. */
+ U.flag &= ~(
+ USER_FLAG_DEPRECATED_1 | USER_FLAG_DEPRECATED_2 | USER_FLAG_DEPRECATED_3 |
+ USER_FLAG_DEPRECATED_6 | USER_FLAG_DEPRECATED_7 |
+ USER_FLAG_DEPRECATED_9 | USER_FLAG_DEPRECATED_10);
+ U.uiflag &= ~(
+ USER_UIFLAG_DEPRECATED_7);
+ U.transopts &= ~(
+ USER_TR_DEPRECATED_2 | USER_TR_DEPRECATED_3 | USER_TR_DEPRECATED_4 |
+ USER_TR_DEPRECATED_6 | USER_TR_DEPRECATED_7);
+ U.gameflags &= ~(
+ USER_GL_RENDER_DEPRECATED_0 | USER_GL_RENDER_DEPRECATED_1 |
+ USER_GL_RENDER_DEPRECATED_3 | USER_GL_RENDER_DEPRECATED_4);
+
+ U.uiflag |= USER_LOCK_CURSOR_ADJUST;
+ }
+
/**
* Include next version bump.
- *
- * (keep this block even if it becomes empty).
*/
{
-
+ /* (keep this block even if it becomes empty). */
}
if (U.pixelsize == 0.0f)
@@ -2779,6 +2792,15 @@ void init_userdef_do_versions(void)
U.audiodevice = 0;
#endif
+ /* Not versioning, just avoid errors. */
+#ifndef WITH_CYCLES
+ bAddon *addon = BLI_findstring(&U.addons, "cycles", offsetof(bAddon, module));
+ if (addon) {
+ BLI_remlink(&U.addons, addon);
+ BKE_addon_free(addon);
+ }
+#endif
+
/* funny name, but it is GE stuff, moves userdef stuff to engine */
// XXX space_set_commmandline_options();
/* this timer uses U */
diff --git a/source/blender/editors/interface/view2d.c b/source/blender/editors/interface/view2d.c
index c78d97ef86f..d2907cb03ea 100644
--- a/source/blender/editors/interface/view2d.c
+++ b/source/blender/editors/interface/view2d.c
@@ -1027,6 +1027,13 @@ bool UI_view2d_tab_set(View2D *v2d, int tab)
void UI_view2d_zoom_cache_reset(void)
{
+ /* TODO(sergey): This way we avoid threading conflict with VSE rendering
+ * text strip. But ideally we want to make glyph cache to be fully safe
+ * for threading.
+ */
+ if (G.is_rendering) {
+ return;
+ }
/* While scaling we can accumulate fonts at many sizes (~20 or so).
* Not an issue with embedded font, but can use over 500Mb with i18n ones! See [#38244]. */
@@ -1210,10 +1217,10 @@ static void step_to_grid(float *step, int *power, int unit)
* - Units + clamping args will be checked, to make sure they are valid values that can be used
* so it is very possible that we won't return grid at all!
*
- * - xunits,yunits = V2D_UNIT_* grid steps in seconds or frames
- * - xclamp,yclamp = V2D_CLAMP_* only show whole-number intervals
- * - winx = width of region we're drawing to, note: not used but keeping for completeness.
- * - winy = height of region we're drawing into
+ * - xunits,yunits = V2D_UNIT_* grid steps in seconds or frames
+ * - xclamp,yclamp = V2D_CLAMP_* only show whole-number intervals
+ * - winx = width of region we're drawing to, note: not used but keeping for completeness.
+ * - winy = height of region we're drawing into
*/
View2DGrid *UI_view2d_grid_calc(
Scene *scene, View2D *v2d,
@@ -1395,9 +1402,9 @@ void UI_view2d_grid_draw(View2D *v2d, View2DGrid *grid, int flag)
}
/* Draw a constant grid in given 2d-region */
-void UI_view2d_constant_grid_draw(View2D *v2d)
+void UI_view2d_constant_grid_draw(View2D *v2d, float step)
{
- float start, step = 25.0f;
+ float start;
UI_ThemeColorShade(TH_BACK, -10);
@@ -2138,6 +2145,14 @@ void UI_view2d_view_to_region_rcti(View2D *v2d, const rctf *rect_src, rcti *rect
clamp_rctf_to_rcti(rect_dst, &rect_tmp);
}
+void UI_view2d_view_to_region_m4(View2D *v2d, float matrix[4][4])
+{
+ rctf mask;
+ unit_m4(matrix);
+ BLI_rctf_rcti_copy(&mask, &v2d->mask);
+ BLI_rctf_transform_calc_m4_pivot_min(&v2d->cur, &mask, matrix);
+}
+
bool UI_view2d_view_to_region_rcti_clip(View2D *v2d, const rctf *rect_src, rcti *rect_dst)
{
const float cur_size[2] = {BLI_rctf_size_x(&v2d->cur), BLI_rctf_size_y(&v2d->cur)};
diff --git a/source/blender/editors/interface/view2d_ops.c b/source/blender/editors/interface/view2d_ops.c
index fa2c1f25cfc..dc68c8b58de 100644
--- a/source/blender/editors/interface/view2d_ops.c
+++ b/source/blender/editors/interface/view2d_ops.c
@@ -1223,7 +1223,6 @@ static int view_borderzoom_exec(bContext *C, wmOperator *op)
View2D *v2d = &ar->v2d;
rctf rect;
rctf cur_new = v2d->cur;
- int gesture_mode;
const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
/* convert coordinates of rect to 'tot' rect coordinates */
@@ -1231,9 +1230,9 @@ static int view_borderzoom_exec(bContext *C, wmOperator *op)
UI_view2d_region_to_view_rctf(v2d, &rect, &rect);
/* check if zooming in/out view */
- gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool zoom_in = !RNA_boolean_get(op->ptr, "zoom_out");
- if (gesture_mode == GESTURE_MODAL_IN) {
+ if (zoom_in) {
/* zoom in:
* - 'cur' rect will be defined by the coordinates of the border region
* - just set the 'cur' rect to have the same coordinates as the border region
@@ -1248,8 +1247,7 @@ static int view_borderzoom_exec(bContext *C, wmOperator *op)
cur_new.ymax = rect.ymax;
}
}
- else { /* if (gesture_mode == GESTURE_MODAL_OUT) */
-
+ else {
/* zoom out:
* - the current 'cur' rect coordinates are going to end up where the 'rect' ones are,
* but the 'cur' rect coordinates will need to be adjusted to take in more of the view
@@ -1289,15 +1287,15 @@ static void VIEW2D_OT_zoom_border(wmOperatorType *ot)
ot->idname = "VIEW2D_OT_zoom_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = view_borderzoom_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = view_zoom_poll;
/* rna */
- WM_operator_properties_gesture_border(ot, false);
+ WM_operator_properties_gesture_border_zoom(ot);
}
#ifdef WITH_INPUT_NDOF
@@ -1511,6 +1509,9 @@ static int view2d_smoothview_invoke(bContext *C, wmOperator *UNUSED(op), const w
WM_event_remove_timer(CTX_wm_manager(C), CTX_wm_window(C), v2d->smooth_timer);
v2d->smooth_timer = NULL;
+
+ /* Event handling won't know if a UI item has been moved under the pointer. */
+ WM_event_add_mousemove(C);
}
else {
/* ease in/out */
@@ -1545,7 +1546,7 @@ static void VIEW2D_OT_smoothview(wmOperatorType *ot)
ot->flag = OPTYPE_INTERNAL;
/* rna */
- WM_operator_properties_gesture_border(ot, false);
+ WM_operator_properties_gesture_border(ot);
}
/* ********************************************************* */
diff --git a/source/blender/editors/io/io_alembic.c b/source/blender/editors/io/io_alembic.c
index a991f59e8e2..08181af2ef3 100644
--- a/source/blender/editors/io/io_alembic.c
+++ b/source/blender/editors/io/io_alembic.c
@@ -31,6 +31,9 @@
# include "BLI_winstuff.h"
#endif
+#include <string.h>
+#include <errno.h>
+
#include "MEM_guardedalloc.h"
#include "DNA_mesh_types.h"
@@ -56,6 +59,8 @@
#include "RNA_define.h"
#include "RNA_enum_types.h"
+#include "ED_object.h"
+
#include "UI_interface.h"
#include "UI_resources.h"
@@ -102,12 +107,12 @@ static int wm_alembic_export_exec(bContext *C, wmOperator *op)
char filename[FILE_MAX];
RNA_string_get(op->ptr, "filepath", filename);
- const struct AlembicExportParams params = {
+ struct AlembicExportParams params = {
.frame_start = RNA_int_get(op->ptr, "start"),
.frame_end = RNA_int_get(op->ptr, "end"),
- .frame_step_xform = 1.0 / (double)RNA_int_get(op->ptr, "xsamples"),
- .frame_step_shape = 1.0 / (double)RNA_int_get(op->ptr, "gsamples"),
+ .frame_samples_xform = RNA_int_get(op->ptr, "xsamples"),
+ .frame_samples_shape = RNA_int_get(op->ptr, "gsamples"),
.shutter_open = RNA_float_get(op->ptr, "sh_open"),
.shutter_close = RNA_float_get(op->ptr, "sh_close"),
@@ -122,24 +127,37 @@ static int wm_alembic_export_exec(bContext *C, wmOperator *op)
.renderable_only = RNA_boolean_get(op->ptr, "renderable_only"),
.face_sets = RNA_boolean_get(op->ptr, "face_sets"),
.use_subdiv_schema = RNA_boolean_get(op->ptr, "subdiv_schema"),
+ .export_hair = RNA_boolean_get(op->ptr, "export_hair"),
+ .export_particles = RNA_boolean_get(op->ptr, "export_particles"),
.compression_type = RNA_enum_get(op->ptr, "compression_type"),
.packuv = RNA_boolean_get(op->ptr, "packuv"),
- .triangulate = RNA_boolean_get(op->ptr, "triangulate"),
- .quad_method = RNA_enum_get(op->ptr, "quad_method"),
- .ngon_method = RNA_enum_get(op->ptr, "ngon_method"),
+ .triangulate = RNA_boolean_get(op->ptr, "triangulate"),
+ .quad_method = RNA_enum_get(op->ptr, "quad_method"),
+ .ngon_method = RNA_enum_get(op->ptr, "ngon_method"),
.global_scale = RNA_float_get(op->ptr, "global_scale"),
};
- ABC_export(CTX_data_scene(C), C, filename, &params);
+ /* Take some defaults from the scene, if not specified explicitly. */
+ Scene *scene = CTX_data_scene(C);
+ if (params.frame_start == INT_MIN) {
+ params.frame_start = SFRA;
+ }
+ if (params.frame_end == INT_MIN) {
+ params.frame_end = EFRA;
+ }
+
+ const bool as_background_job = RNA_boolean_get(op->ptr, "as_background_job");
+ bool ok = ABC_export(scene, C, filename, &params, as_background_job);
- return OPERATOR_FINISHED;
+ return as_background_job || ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
static void ui_alembic_export_settings(uiLayout *layout, PointerRNA *imfptr)
{
uiLayout *box;
uiLayout *row;
+ uiLayout *col;
#ifdef WITH_ALEMBIC_HDF5
box = uiLayoutBox(layout);
@@ -231,6 +249,15 @@ static void ui_alembic_export_settings(uiLayout *layout, PointerRNA *imfptr)
row = uiLayoutRow(box, false);
uiLayoutSetEnabled(row, triangulate);
uiItemR(row, imfptr, "ngon_method", 0, NULL, ICON_NONE);
+
+ /* Object Data */
+ box = uiLayoutBox(layout);
+ row = uiLayoutRow(box, false);
+ uiItemL(row, IFACE_("Particle Systems:"), ICON_PARTICLE_DATA);
+
+ col = uiLayoutColumn(box, true);
+ uiItemR(col, imfptr, "export_hair", 0, NULL, ICON_NONE);
+ uiItemR(col, imfptr, "export_particles", 0, NULL, ICON_NONE);
}
static void wm_alembic_export_draw(bContext *C, wmOperator *op)
@@ -282,11 +309,17 @@ void WM_OT_alembic_export(wmOperatorType *ot)
FILE_BLENDER, FILE_SAVE, WM_FILESEL_FILEPATH,
FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
- RNA_def_int(ot->srna, "start", 1, INT_MIN, INT_MAX,
- "Start Frame", "Start Frame", INT_MIN, INT_MAX);
+ RNA_def_int(ot->srna, "start", INT_MIN, INT_MIN, INT_MAX,
+ "Start Frame",
+ "Start frame of the export, use the default value to "
+ "take the start frame of the current scene",
+ INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "end", 1, INT_MIN, INT_MAX,
- "End Frame", "End Frame", INT_MIN, INT_MAX);
+ RNA_def_int(ot->srna, "end", INT_MIN, INT_MIN, INT_MAX,
+ "End Frame",
+ "End frame of the export, use the default value to "
+ "take the end frame of the current scene",
+ INT_MIN, INT_MAX);
RNA_def_int(ot->srna, "xsamples", 1, 1, 128,
"Transform Samples", "Number of times per frame transformations are sampled", 1, 128);
@@ -348,9 +381,15 @@ void WM_OT_alembic_export(wmOperatorType *ot)
RNA_def_enum(ot->srna, "ngon_method", rna_enum_modifier_triangulate_quad_method_items,
MOD_TRIANGULATE_NGON_BEAUTY, "Polygon Method", "Method for splitting the polygons into triangles");
+ RNA_def_boolean(ot->srna, "export_hair", 1, "Export Hair", "Exports hair particle systems as animated curves");
+ RNA_def_boolean(ot->srna, "export_particles", 1, "Export Particles", "Exports non-hair particle systems");
+
+ RNA_def_boolean(ot->srna, "as_background_job", true, "Run as Background Job",
+ "Enable this to run the import in the background, disable to block Blender while importing");
+
/* This dummy prop is used to check whether we need to init the start and
- * end frame values to that of the scene's, otherwise they are reset at
- * every change, draw update. */
+ * end frame values to that of the scene's, otherwise they are reset at
+ * every change, draw update. */
RNA_def_boolean(ot->srna, "init_scene_frame_range", false, "", "");
}
@@ -383,9 +422,20 @@ static int get_sequence_len(char *filename, int *ofs)
}
char path[FILE_MAX];
+ BLI_path_abs(filename, G.main->name);
BLI_split_dir_part(filename, path, FILE_MAX);
+ if (path[0] == '\0') {
+ /* The filename had no path, so just use the blend file path. */
+ BLI_split_dir_part(G.main->name, path, FILE_MAX);
+ }
+
DIR *dir = opendir(path);
+ if (dir == NULL) {
+ fprintf(stderr, "Error opening directory '%s': %s\n",
+ path, errno ? strerror(errno) : "unknown error");
+ return -1;
+ }
const char *ext = ".abc";
const char *basename = BLI_path_basename(filename);
@@ -482,17 +532,40 @@ static int wm_alembic_import_exec(bContext *C, wmOperator *op)
const bool is_sequence = RNA_boolean_get(op->ptr, "is_sequence");
const bool set_frame_range = RNA_boolean_get(op->ptr, "set_frame_range");
const bool validate_meshes = RNA_boolean_get(op->ptr, "validate_meshes");
+ const bool as_background_job = RNA_boolean_get(op->ptr, "as_background_job");
int offset = 0;
int sequence_len = 1;
if (is_sequence) {
sequence_len = get_sequence_len(filename, &offset);
+ if (sequence_len < 0) {
+ BKE_report(op->reports, RPT_ERROR, "Unable to determine ABC sequence length");
+ return OPERATOR_CANCELLED;
+ }
+ }
+
+ /* Switch to object mode to avoid being stuck in other modes (T54326). */
+ if (CTX_data_mode_enum(C) != CTX_MODE_OBJECT) {
+ Object *obedit = CTX_data_edit_object(C);
+
+ if (obedit != NULL) {
+ ED_object_mode_toggle(C, obedit->mode);
+ }
+ else {
+ Object *ob = CTX_data_active_object(C);
+
+ if (ob) {
+ ED_object_mode_toggle(C, ob->mode);
+ }
+ }
}
- ABC_import(C, filename, scale, is_sequence, set_frame_range, sequence_len, offset, validate_meshes);
+ bool ok = ABC_import(C, filename, scale, is_sequence, set_frame_range,
+ sequence_len, offset, validate_meshes,
+ as_background_job);
- return OPERATOR_FINISHED;
+ return as_background_job || ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
void WM_OT_alembic_import(wmOperatorType *ot)
@@ -523,6 +596,9 @@ void WM_OT_alembic_import(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "is_sequence", false, "Is Sequence",
"Set to true if the cache is split into separate files");
+
+ RNA_def_boolean(ot->srna, "as_background_job", true, "Run as Background Job",
+ "Enable this to run the export in the background, disable to block Blender while exporting");
}
#endif
diff --git a/source/blender/editors/io/io_cache.c b/source/blender/editors/io/io_cache.c
index ebe8898571d..eb79d0bec13 100644
--- a/source/blender/editors/io/io_cache.c
+++ b/source/blender/editors/io/io_cache.c
@@ -33,7 +33,6 @@
#include "BKE_cachefile.h"
#include "BKE_context.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_report.h"
@@ -93,26 +92,28 @@ static int cachefile_open_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
- CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, BLI_path_basename(filename));
+ CacheFile *cache_file = BKE_libblock_alloc(bmain, ID_CF, BLI_path_basename(filename), 0);
BLI_strncpy(cache_file->filepath, filename, FILE_MAX);
BKE_cachefile_reload(bmain, cache_file);
- /* hook into UI */
- PropertyPointerRNA *pprop = op->customdata;
-
- if (pprop->prop) {
- /* when creating new ID blocks, use is already 1, but RNA
- * pointer se also increases user, so this compensates it */
- id_us_min(&cache_file->id);
-
- PointerRNA idptr;
- RNA_id_pointer_create(&cache_file->id, &idptr);
- RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
- RNA_property_update(C, &pprop->ptr, pprop->prop);
+ /* Will be set when running invoke, not exec directly. */
+ if (op->customdata != NULL) {
+ /* hook into UI */
+ PropertyPointerRNA *pprop = op->customdata;
+ if (pprop->prop) {
+ /* when creating new ID blocks, use is already 1, but RNA
+ * pointer se also increases user, so this compensates it */
+ id_us_min(&cache_file->id);
+
+ PointerRNA idptr;
+ RNA_id_pointer_create(&cache_file->id, &idptr);
+ RNA_property_pointer_set(&pprop->ptr, pprop->prop, idptr);
+ RNA_property_update(C, &pprop->ptr, pprop->prop);
+ }
+
+ MEM_freeN(op->customdata);
}
- MEM_freeN(op->customdata);
-
return OPERATOR_FINISHED;
}
@@ -143,7 +144,7 @@ static int cachefile_reload_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
- BLI_listbase_clear(&cache_file->object_paths);
+ BLI_freelistN(&cache_file->object_paths);
BKE_cachefile_reload(bmain, cache_file);
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/io/io_collada.c b/source/blender/editors/io/io_collada.c
index baae92f962e..42c19c6bc65 100644
--- a/source/blender/editors/io/io_collada.c
+++ b/source/blender/editors/io/io_collada.c
@@ -36,9 +36,11 @@
#include "BLI_utildefines.h"
#include "BKE_context.h"
+#include "BKE_depsgraph.h"
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_report.h"
+#include "BKE_object.h"
#include "ED_screen.h"
#include "ED_object.h"
@@ -87,8 +89,11 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
int include_shapekeys;
int deform_bones_only;
- int include_uv_textures;
- int include_material_textures;
+ int include_animations;
+ int sample_animations;
+ int sampling_rate;
+
+ int export_texture_type;
int use_texture_copies;
int active_uv_only;
@@ -97,7 +102,10 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
int use_blender_profile;
int sort_by_name;
int export_transformation_type;
+
int open_sim;
+ int limit_precision;
+ int keep_bind_info;
int export_count;
@@ -134,10 +142,14 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
include_children = RNA_boolean_get(op->ptr, "include_children");
include_armatures = RNA_boolean_get(op->ptr, "include_armatures");
include_shapekeys = RNA_boolean_get(op->ptr, "include_shapekeys");
+
+ include_animations = RNA_boolean_get(op->ptr, "include_animations");
+ sample_animations = RNA_boolean_get(op->ptr, "sample_animations");
+ sampling_rate = (sample_animations) ? RNA_int_get(op->ptr, "sampling_rate") : 0;
+
deform_bones_only = RNA_boolean_get(op->ptr, "deform_bones_only");
- include_uv_textures = RNA_boolean_get(op->ptr, "include_uv_textures");
- include_material_textures = RNA_boolean_get(op->ptr, "include_material_textures");
+ export_texture_type = RNA_enum_get(op->ptr, "export_texture_type_selection");
use_texture_copies = RNA_boolean_get(op->ptr, "use_texture_copies");
active_uv_only = RNA_boolean_get(op->ptr, "active_uv_only");
@@ -148,31 +160,50 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
export_transformation_type = RNA_enum_get(op->ptr, "export_transformation_type_selection");
open_sim = RNA_boolean_get(op->ptr, "open_sim");
+ limit_precision = RNA_boolean_get(op->ptr, "limit_precision");
+ keep_bind_info = RNA_boolean_get(op->ptr, "keep_bind_info");
+
/* get editmode results */
ED_object_editmode_load(CTX_data_edit_object(C));
-
- export_count = collada_export(CTX_data_scene(C),
- filepath,
- apply_modifiers,
- export_mesh_type,
- selected,
- include_children,
- include_armatures,
- include_shapekeys,
- deform_bones_only,
-
- active_uv_only,
- include_uv_textures,
- include_material_textures,
- use_texture_copies,
-
- triangulate,
- use_object_instantiation,
- use_blender_profile,
- sort_by_name,
- export_transformation_type,
- open_sim);
+ EvaluationContext *eval_ctx = G.main->eval_ctx;
+ Scene *scene = CTX_data_scene(C);
+ ExportSettings export_settings;
+
+ export_settings.filepath = filepath;
+
+ export_settings.apply_modifiers = apply_modifiers != 0;
+ export_settings.export_mesh_type = export_mesh_type;
+ export_settings.selected = selected != 0;
+ export_settings.include_children = include_children != 0;
+ export_settings.include_armatures = include_armatures != 0;
+ export_settings.include_shapekeys = include_shapekeys != 0;
+ export_settings.deform_bones_only = deform_bones_only != 0;
+ export_settings.include_animations = include_animations;
+ export_settings.sampling_rate = sampling_rate;
+
+ export_settings.active_uv_only = active_uv_only != 0;
+ export_settings.export_texture_type = export_texture_type;
+ export_settings.use_texture_copies = use_texture_copies != 0;
+
+ export_settings.triangulate = triangulate != 0;
+ export_settings.use_object_instantiation = use_object_instantiation != 0;
+ export_settings.use_blender_profile = use_blender_profile != 0;
+ export_settings.sort_by_name = sort_by_name != 0;
+ export_settings.export_transformation_type = export_transformation_type;
+ export_settings.open_sim = open_sim != 0;
+ export_settings.limit_precision = limit_precision != 0;
+ export_settings.keep_bind_info = keep_bind_info != 0;
+
+ int includeFilter = OB_REL_NONE;
+ if (export_settings.include_armatures) includeFilter |= OB_REL_MOD_ARMATURE;
+ if (export_settings.include_children) includeFilter |= OB_REL_CHILDREN_RECURSIVE;
+
+
+ export_count = collada_export(eval_ctx,
+ scene,
+ &export_settings
+ );
if (export_count == 0) {
BKE_report(op->reports, RPT_WARNING, "No objects selected -- Created empty export file");
@@ -193,6 +224,7 @@ static int wm_collada_export_exec(bContext *C, wmOperator *op)
static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
{
uiLayout *box, *row, *col, *split;
+ bool include_animations = RNA_boolean_get(imfptr, "include_animations");
/* Export Options: */
box = uiLayoutBox(layout);
@@ -222,6 +254,16 @@ static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
uiItemR(row, imfptr, "include_shapekeys", 0, NULL, ICON_NONE);
uiLayoutSetEnabled(row, RNA_boolean_get(imfptr, "selected"));
+ row = uiLayoutRow(box, false);
+ uiItemR(row, imfptr, "include_animations", 0, NULL, ICON_NONE);
+ row = uiLayoutRow(box, false);
+ if (include_animations) {
+ uiItemR(row, imfptr, "sample_animations", 0, NULL, ICON_NONE);
+ row = uiLayoutColumn(box, false);
+ uiItemR(row, imfptr, "sampling_rate", 0, NULL, ICON_NONE);
+ uiLayoutSetEnabled(row, RNA_boolean_get(imfptr, "sample_animations"));
+ }
+
/* Texture options */
box = uiLayoutBox(layout);
row = uiLayoutRow(box, false);
@@ -231,10 +273,7 @@ static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
uiItemR(row, imfptr, "active_uv_only", 0, NULL, ICON_NONE);
row = uiLayoutRow(box, false);
- uiItemR(row, imfptr, "include_uv_textures", 0, NULL, ICON_NONE);
-
- row = uiLayoutRow(box, false);
- uiItemR(row, imfptr, "include_material_textures", 0, NULL, ICON_NONE);
+ uiItemR(row, imfptr, "export_texture_type_selection", 0, "", ICON_NONE);
row = uiLayoutRow(box, false);
uiItemR(row, imfptr, "use_texture_copies", 1, NULL, ICON_NONE);
@@ -247,6 +286,7 @@ static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
row = uiLayoutRow(box, false);
uiItemR(row, imfptr, "deform_bones_only", 0, NULL, ICON_NONE);
+
row = uiLayoutRow(box, false);
uiItemR(row, imfptr, "open_sim", 0, NULL, ICON_NONE);
@@ -256,20 +296,25 @@ static void uiCollada_exportSettings(uiLayout *layout, PointerRNA *imfptr)
uiItemL(row, IFACE_("Collada Options:"), ICON_MODIFIER);
row = uiLayoutRow(box, false);
- uiItemR(row, imfptr, "triangulate", 0, NULL, ICON_NONE);
+ uiItemR(row, imfptr, "triangulate", 1, NULL, ICON_NONE);
row = uiLayoutRow(box, false);
- uiItemR(row, imfptr, "use_object_instantiation", 0, NULL, ICON_NONE);
+ uiItemR(row, imfptr, "use_object_instantiation", 1, NULL, ICON_NONE);
row = uiLayoutRow(box, false);
- uiItemR(row, imfptr, "use_blender_profile", 0, NULL, ICON_NONE);
+ uiItemR(row, imfptr, "use_blender_profile", 1, NULL, ICON_NONE);
row = uiLayoutRow(box, false);
split = uiLayoutSplit(row, 0.6f, UI_LAYOUT_ALIGN_RIGHT);
uiItemL(split, IFACE_("Transformation Type"), ICON_NONE);
uiItemR(split, imfptr, "export_transformation_type_selection", 0, "", ICON_NONE);
-
row = uiLayoutRow(box, false);
uiItemR(row, imfptr, "sort_by_name", 0, NULL, ICON_NONE);
+ row = uiLayoutRow(box, false);
+ uiItemR(row, imfptr, "keep_bind_info", 0, NULL, ICON_NONE);
+
+ row = uiLayoutRow(box, false);
+ uiItemR(row, imfptr, "limit_precision", 0, NULL, ICON_NONE);
+
}
static void wm_collada_export_draw(bContext *UNUSED(C), wmOperator *op)
@@ -296,16 +341,24 @@ static bool wm_collada_export_check(bContext *UNUSED(C), wmOperator *op)
void WM_OT_collada_export(wmOperatorType *ot)
{
- static EnumPropertyItem prop_bc_export_mesh_type[] = {
+ struct StructRNA *func = ot->srna;
+
+ static const EnumPropertyItem prop_bc_export_mesh_type[] = {
{BC_MESH_TYPE_VIEW, "view", 0, "View", "Apply modifier's view settings"},
{BC_MESH_TYPE_RENDER, "render", 0, "Render", "Apply modifier's render settings"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_bc_export_transformation_type[] = {
- {BC_TRANSFORMATION_TYPE_MATRIX, "matrix", 0, "Matrix", "Use <matrix> to specify transformations"},
- {BC_TRANSFORMATION_TYPE_TRANSROTLOC, "transrotloc", 0, "TransRotLoc", "Use <translate>, <rotate>, <scale> to specify transformations"},
- {0, NULL, 0, NULL, NULL}
+ static const EnumPropertyItem prop_bc_export_transformation_type[] = {
+ { BC_TRANSFORMATION_TYPE_MATRIX, "matrix", 0, "Matrix", "Use <matrix> to specify transformations" },
+ { BC_TRANSFORMATION_TYPE_TRANSROTLOC, "transrotloc", 0, "TransRotLoc", "Use <translate>, <rotate>, <scale> to specify transformations" },
+ { 0, NULL, 0, NULL, NULL }
+ };
+
+ static const EnumPropertyItem prop_bc_export_texture_type[] = {
+ { BC_TEXTURE_TYPE_MAT, "mat", 0, "Materials", "Export Materials" },
+ { BC_TEXTURE_TYPE_UV, "uv", 0, "UV Textures", "Export UV Textures (Face textures) as materials" },
+ { 0, NULL, 0, NULL, NULL }
};
ot->name = "Export COLLADA";
@@ -325,65 +378,83 @@ void WM_OT_collada_export(wmOperatorType *ot)
ot, FILE_TYPE_FOLDER | FILE_TYPE_COLLADA, FILE_BLENDER, FILE_SAVE,
WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
- RNA_def_boolean(ot->srna,
+ RNA_def_boolean(func,
"apply_modifiers", 0, "Apply Modifiers",
"Apply modifiers to exported mesh (non destructive))");
- RNA_def_int(ot->srna, "export_mesh_type", 0, INT_MIN, INT_MAX,
+ RNA_def_int(func, "export_mesh_type", 0, INT_MIN, INT_MAX,
"Resolution", "Modifier resolution for export", INT_MIN, INT_MAX);
- RNA_def_enum(ot->srna, "export_mesh_type_selection", prop_bc_export_mesh_type, 0,
+ RNA_def_enum(func, "export_mesh_type_selection", prop_bc_export_mesh_type, 0,
"Resolution", "Modifier resolution for export");
- RNA_def_boolean(ot->srna, "selected", 0, "Selection Only",
+ RNA_def_boolean(func, "selected", false, "Selection Only",
"Export only selected elements");
- RNA_def_boolean(ot->srna, "include_children", 0, "Include Children",
+ RNA_def_boolean(func, "include_children", false, "Include Children",
"Export all children of selected objects (even if not selected)");
- RNA_def_boolean(ot->srna, "include_armatures", 0, "Include Armatures",
+ RNA_def_boolean(func, "include_armatures", false, "Include Armatures",
"Export related armatures (even if not selected)");
- RNA_def_boolean(ot->srna, "include_shapekeys", 1, "Include Shape Keys",
+ RNA_def_boolean(func, "include_shapekeys", false, "Include Shape Keys",
"Export all Shape Keys from Mesh Objects");
- RNA_def_boolean(ot->srna, "deform_bones_only", 0, "Deform Bones only",
- "Only export deforming bones with armatures");
+ RNA_def_boolean(func, "deform_bones_only", false, "Deform Bones only",
+ "Only export deforming bones with armatures");
+ RNA_def_boolean(func, "include_animations", true,
+ "Include Animations", "Export Animations if available.\nExporting Animations will enforce the decomposition of node transforms\ninto <translation> <rotation> and <scale> components");
- RNA_def_boolean(ot->srna, "active_uv_only", 0, "Only Selected UV Map",
- "Export only the selected UV Map");
+ RNA_def_boolean(func, "sample_animations", 0,
+ "Sample Animations", "Auto-generate keyframes with a frame distance set by 'Sampling Rate'.\nWhen disabled, export only the keyframes defined in the animation f-curves (may be less accurate)");
- RNA_def_boolean(ot->srna, "include_uv_textures", 0, "Include UV Textures",
- "Export textures assigned to the object UV Maps");
+ RNA_def_int(func, "sampling_rate", 1, 1, INT_MAX,
+ "Sampling Rate", "The distance between 2 keyframes. 1 means: Every frame is keyed", 1, INT_MAX);
- RNA_def_boolean(ot->srna, "include_material_textures", 0, "Include Material Textures",
- "Export textures assigned to the object Materials");
+ RNA_def_boolean(func, "active_uv_only", 0, "Only Selected UV Map",
+ "Export only the selected UV Map");
- RNA_def_boolean(ot->srna, "use_texture_copies", 1, "Copy",
+ RNA_def_boolean(func, "use_texture_copies", 1, "Copy",
"Copy textures to same folder where the .dae file is exported");
- RNA_def_boolean(ot->srna, "triangulate", 1, "Triangulate",
+ RNA_def_boolean(func, "triangulate", 1, "Triangulate",
"Export Polygons (Quads & NGons) as Triangles");
- RNA_def_boolean(ot->srna, "use_object_instantiation", 1, "Use Object Instances",
+ RNA_def_boolean(func, "use_object_instantiation", 1, "Use Object Instances",
"Instantiate multiple Objects from same Data");
- RNA_def_boolean(ot->srna, "use_blender_profile", 1, "Use Blender Profile",
+ RNA_def_boolean(func, "use_blender_profile", 1, "Use Blender Profile",
"Export additional Blender specific information (for material, shaders, bones, etc.)");
- RNA_def_boolean(ot->srna, "sort_by_name", 0, "Sort by Object name",
+ RNA_def_boolean(func, "sort_by_name", 0, "Sort by Object name",
"Sort exported data by Object name");
- RNA_def_int(ot->srna, "export_transformation_type", 0, INT_MIN, INT_MAX,
- "Transform", "Transformation type for translation, scale and rotation", INT_MIN, INT_MAX);
- RNA_def_enum(ot->srna, "export_transformation_type_selection", prop_bc_export_transformation_type, 0,
- "Transform", "Transformation type for translation, scale and rotation");
+ RNA_def_int(func, "export_transformation_type", 0, INT_MIN, INT_MAX,
+ "Transform", "Transformation type for translation, scale and rotation", INT_MIN, INT_MAX);
+
+ RNA_def_enum(func, "export_transformation_type_selection", prop_bc_export_transformation_type, 0,
+ "Transform", "Transformation type for translation, scale and rotation");
+
+
+ RNA_def_int(func, "export_texture_type", 0, INT_MIN, INT_MAX,
+ "Texture Type", "Type for exported Textures (UV or MAT)", INT_MIN, INT_MAX);
+
+ RNA_def_enum(func, "export_texture_type_selection", prop_bc_export_texture_type, 0,
+ "Texture Type", "Type for exported Textures (UV or MAT)");
- RNA_def_boolean(ot->srna, "open_sim", 0, "Export to SL/OpenSim",
+
+ RNA_def_boolean(func, "open_sim", 0, "Export to SL/OpenSim",
"Compatibility mode for SL, OpenSim and other compatible online worlds");
+
+ RNA_def_boolean(func, "limit_precision", 0,
+ "Limit Precision", "Reduce the precision of the exported data to 6 digits");
+
+ RNA_def_boolean(func, "keep_bind_info", 0,
+ "Keep Bind Info", "Store Bindpose information in custom bone properties for later use during Collada export");
+
}
@@ -395,7 +466,10 @@ static int wm_collada_import_exec(bContext *C, wmOperator *op)
int find_chains;
int auto_connect;
int fix_orientation;
- int min_chain_length;
+ int min_chain_length;
+
+ int keep_bind_info;
+ ImportSettings import_settings;
if (!RNA_struct_property_is_set(op->ptr, "filepath")) {
BKE_report(op->reports, RPT_ERROR, "No filename given");
@@ -407,17 +481,22 @@ static int wm_collada_import_exec(bContext *C, wmOperator *op)
find_chains = RNA_boolean_get(op->ptr, "find_chains");
auto_connect = RNA_boolean_get(op->ptr, "auto_connect");
fix_orientation = RNA_boolean_get(op->ptr, "fix_orientation");
+
+ keep_bind_info = RNA_boolean_get(op->ptr, "keep_bind_info");
+
min_chain_length = RNA_int_get(op->ptr, "min_chain_length");
RNA_string_get(op->ptr, "filepath", filename);
- if (collada_import(
- C, filename,
- import_units,
- find_chains,
- auto_connect,
- fix_orientation,
- min_chain_length))
- {
+
+ import_settings.filepath = filename;
+ import_settings.import_units = import_units != 0;
+ import_settings.auto_connect = auto_connect != 0;
+ import_settings.find_chains = find_chains != 0;
+ import_settings.fix_orientation = fix_orientation != 0;
+ import_settings.min_chain_length = min_chain_length;
+ import_settings.keep_bind_info = keep_bind_info != 0;
+
+ if (collada_import(C, &import_settings)) {
return OPERATOR_FINISHED;
}
else {
@@ -453,6 +532,13 @@ static void uiCollada_importSettings(uiLayout *layout, PointerRNA *imfptr)
row = uiLayoutRow(box, false);
uiItemR(row, imfptr, "min_chain_length", 0, NULL, ICON_NONE);
+
+ box = uiLayoutBox(layout);
+ row = uiLayoutRow(box, false);
+
+ row = uiLayoutRow(box, false);
+ uiItemR(row, imfptr, "keep_bind_info", 0, NULL, ICON_NONE);
+
}
static void wm_collada_import_draw(bContext *UNUSED(C), wmOperator *op)
@@ -508,5 +594,9 @@ void WM_OT_collada_import(wmOperatorType *ot)
0,
INT_MAX);
+ RNA_def_boolean(ot->srna,
+ "keep_bind_info", 0, "Keep Bind Info",
+ "Store Bindpose information in custom bone properties for later use during Collada export");
+
}
#endif
diff --git a/source/blender/editors/lattice/CMakeLists.txt b/source/blender/editors/lattice/CMakeLists.txt
new file mode 100644
index 00000000000..3bb954ddf46
--- /dev/null
+++ b/source/blender/editors/lattice/CMakeLists.txt
@@ -0,0 +1,45 @@
+# ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# Contributor(s): Jacques Beaurain.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+set(INC
+ ../include
+ ../../blenkernel
+ ../../blenlib
+ ../../makesdna
+ ../../makesrna
+ ../../render/extern/include
+ ../../windowmanager
+ ../../../../intern/guardedalloc
+)
+
+set(INC_SYS
+
+)
+
+set(SRC
+ editlattice_select.c
+ editlattice_tools.c
+ editlattice_undo.c
+ lattice_ops.c
+
+ lattice_intern.h
+)
+
+blender_add_lib(bf_editor_lattice "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/object/object_lattice.c b/source/blender/editors/lattice/editlattice_select.c
index 73ce1fae605..d0d64b85195 100644
--- a/source/blender/editors/object/object_lattice.c
+++ b/source/blender/editors/lattice/editlattice_select.c
@@ -23,14 +23,11 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/editors/object/object_lattice.c
- * \ingroup edobj
+/** \file blender/editors/lattice/editlattice_select.c
+ * \ingroup edlattice
*/
-
#include <stdlib.h>
-#include <string.h>
-#include <math.h>
#include "MEM_guardedalloc.h"
@@ -41,7 +38,6 @@
#include "BLI_bitmap.h"
#include "DNA_curve_types.h"
-#include "DNA_key_types.h"
#include "DNA_lattice_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
@@ -52,127 +48,21 @@
#include "RNA_enum_types.h"
#include "BKE_context.h"
-#include "BKE_depsgraph.h"
-#include "BKE_key.h"
#include "BKE_lattice.h"
-#include "BKE_deform.h"
#include "BKE_report.h"
-#include "BKE_utildefines.h"
-#include "ED_lattice.h"
-#include "ED_object.h"
#include "ED_screen.h"
+#include "ED_lattice.h"
#include "ED_view3d.h"
-#include "ED_util.h"
#include "WM_api.h"
#include "WM_types.h"
-#include "object_intern.h"
-
-/********************** Load/Make/Free ********************/
-
-void ED_lattice_editlatt_free(Object *ob)
-{
- Lattice *lt = ob->data;
-
- if (lt->editlatt) {
- Lattice *editlt = lt->editlatt->latt;
-
- if (editlt->def)
- MEM_freeN(editlt->def);
- if (editlt->dvert)
- BKE_defvert_array_free(editlt->dvert, editlt->pntsu * editlt->pntsv * editlt->pntsw);
-
- MEM_freeN(editlt);
- MEM_freeN(lt->editlatt);
-
- lt->editlatt = NULL;
- }
-}
-
-void ED_lattice_editlatt_make(Object *obedit)
-{
- Lattice *lt = obedit->data;
- KeyBlock *actkey;
-
- ED_lattice_editlatt_free(obedit);
-
- actkey = BKE_keyblock_from_object(obedit);
- if (actkey)
- BKE_keyblock_convert_to_lattice(actkey, lt);
-
- lt->editlatt = MEM_callocN(sizeof(EditLatt), "editlatt");
- lt->editlatt->latt = MEM_dupallocN(lt);
- lt->editlatt->latt->def = MEM_dupallocN(lt->def);
-
- if (lt->dvert) {
- int tot = lt->pntsu * lt->pntsv * lt->pntsw;
- lt->editlatt->latt->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
- BKE_defvert_array_copy(lt->editlatt->latt->dvert, lt->dvert, tot);
- }
-
- if (lt->key) lt->editlatt->shapenr = obedit->shapenr;
-}
-
-void ED_lattice_editlatt_load(Object *obedit)
-{
- Lattice *lt, *editlt;
- KeyBlock *actkey;
- BPoint *bp;
- float *fp;
- int tot;
-
- lt = obedit->data;
- editlt = lt->editlatt->latt;
-
- if (lt->editlatt->shapenr) {
- actkey = BLI_findlink(&lt->key->block, lt->editlatt->shapenr - 1);
-
- /* active key: vertices */
- tot = editlt->pntsu * editlt->pntsv * editlt->pntsw;
-
- if (actkey->data) MEM_freeN(actkey->data);
-
- fp = actkey->data = MEM_callocN(lt->key->elemsize * tot, "actkey->data");
- actkey->totelem = tot;
-
- bp = editlt->def;
- while (tot--) {
- copy_v3_v3(fp, bp->vec);
- fp += 3;
- bp++;
- }
- }
- else {
- MEM_freeN(lt->def);
-
- lt->def = MEM_dupallocN(editlt->def);
-
- lt->flag = editlt->flag;
-
- lt->pntsu = editlt->pntsu;
- lt->pntsv = editlt->pntsv;
- lt->pntsw = editlt->pntsw;
-
- lt->typeu = editlt->typeu;
- lt->typev = editlt->typev;
- lt->typew = editlt->typew;
- lt->actbp = editlt->actbp;
- }
-
- if (lt->dvert) {
- BKE_defvert_array_free(lt->dvert, lt->pntsu * lt->pntsv * lt->pntsw);
- lt->dvert = NULL;
- }
-
- if (editlt->dvert) {
- tot = lt->pntsu * lt->pntsv * lt->pntsw;
+#include "lattice_intern.h"
- lt->dvert = MEM_mallocN(sizeof(MDeformVert) * tot, "Lattice MDeformVert");
- BKE_defvert_array_copy(lt->dvert, editlt->dvert, tot);
- }
-}
+/* -------------------------------------------------------------------- */
+/** \name Utility Functions
+ * \{ */
static void bpoint_select_set(BPoint *bp, bool select)
{
@@ -186,7 +76,11 @@ static void bpoint_select_set(BPoint *bp, bool select)
}
}
-/************************** Select Random Operator **********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Random Operator
+ * \{ */
static int lattice_select_random_exec(bContext *C, wmOperator *op)
{
@@ -242,9 +136,11 @@ void LATTICE_OT_select_random(wmOperatorType *ot)
WM_operator_properties_select_random(ot);
}
+/** \} */
/* -------------------------------------------------------------------- */
-/* Select Mirror Operator */
+/** \name Select Mirror Operator
+ * \{ */
static void ed_lattice_select_mirrored(Lattice *lt, const int axis, const bool extend)
{
@@ -323,8 +219,11 @@ void LATTICE_OT_select_mirror(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
}
+/** \} */
-/************************** Select More/Less Operator *************************/
+/* -------------------------------------------------------------------- */
+/** \name Select More/Less Operator
+ * \{ */
static bool lattice_test_bitmap_uvw(Lattice *lt, BLI_bitmap *selpoints, int u, int v, int w, const bool selected)
{
@@ -369,7 +268,7 @@ static int lattice_select_more_less(bContext *C, const bool select)
lattice_test_bitmap_uvw(lt, selpoints, u, v, w + 1, select) ||
lattice_test_bitmap_uvw(lt, selpoints, u, v, w - 1, select))
{
- BKE_BIT_TEST_SET(bp->f1, select, SELECT);
+ SET_FLAG_FROM_TEST(bp->f1, select, SELECT);
}
}
bp++;
@@ -423,16 +322,20 @@ void LATTICE_OT_select_less(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/************************** Select All Operator *************************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select All Operator
+ * \{ */
void ED_lattice_flags_set(Object *obedit, int flag)
{
Lattice *lt = obedit->data;
BPoint *bp;
int a;
-
+
bp = lt->editlatt->latt->def;
-
+
a = lt->editlatt->latt->pntsu * lt->editlatt->latt->pntsv * lt->editlatt->latt->pntsw;
lt->editlatt->latt->actbp = LT_ACTBP_NONE;
@@ -501,18 +404,22 @@ void LATTICE_OT_select_all(wmOperatorType *ot)
ot->name = "(De)select All";
ot->description = "Change selection of all UVW control points";
ot->idname = "LATTICE_OT_select_all";
-
+
/* api callbacks */
ot->exec = lattice_select_all_exec;
ot->poll = ED_operator_editlattice;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
WM_operator_properties_select_all(ot);
}
-/************************** Select Ungrouped Verts Operator *************************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Ungrouped Verts Operator
+ * \{ */
static int lattice_select_ungrouped_exec(bContext *C, wmOperator *op)
{
@@ -564,291 +471,22 @@ void LATTICE_OT_select_ungrouped(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
}
-/************************** Make Regular Operator *************************/
-
-static int make_regular_poll(bContext *C)
-{
- Object *ob;
-
- if (ED_operator_editlattice(C)) return 1;
+/** \} */
- ob = CTX_data_active_object(C);
- return (ob && ob->type == OB_LATTICE);
-}
-static int make_regular_exec(bContext *C, wmOperator *UNUSED(op))
-{
- Object *ob = CTX_data_edit_object(C);
- Lattice *lt;
-
- if (ob) {
- lt = ob->data;
- BKE_lattice_resize(lt->editlatt->latt, lt->pntsu, lt->pntsv, lt->pntsw, NULL);
- }
- else {
- ob = CTX_data_active_object(C);
- lt = ob->data;
- BKE_lattice_resize(lt, lt->pntsu, lt->pntsv, lt->pntsw, NULL);
- }
-
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
-
- return OPERATOR_FINISHED;
-}
-
-void LATTICE_OT_make_regular(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Make Regular";
- ot->description = "Set UVW control points a uniform distance apart";
- ot->idname = "LATTICE_OT_make_regular";
-
- /* api callbacks */
- ot->exec = make_regular_exec;
- ot->poll = make_regular_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-}
-
-/************************** Flip Verts Operator *************************/
-
-/* flipping options */
-typedef enum eLattice_FlipAxes {
- LATTICE_FLIP_U = 0,
- LATTICE_FLIP_V = 1,
- LATTICE_FLIP_W = 2
-} eLattice_FlipAxes;
-
-/* Flip midpoint value so that relative distances between midpoint and neighbor-pair is maintained
- * ! Assumes that uvw <=> xyz (i.e. axis-aligned index-axes with coordinate-axes)
- * - Helper for lattice_flip_exec()
- */
-static void lattice_flip_point_value(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
-{
- BPoint *bp;
- float diff;
-
- /* just the point in the middle (unpaired) */
- bp = &lt->def[BKE_lattice_index_from_uvw(lt, u, v, w)];
-
- /* flip over axis */
- diff = mid - bp->vec[axis];
- bp->vec[axis] = mid + diff;
-}
-
-/* Swap pairs of lattice points along a specified axis
- * - Helper for lattice_flip_exec()
- */
-static void lattice_swap_point_pairs(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
-{
- BPoint *bpA, *bpB;
-
- int numU = lt->pntsu;
- int numV = lt->pntsv;
- int numW = lt->pntsw;
-
- int u0 = u, u1 = u;
- int v0 = v, v1 = v;
- int w0 = w, w1 = w;
-
- /* get pair index by just overriding the relevant pair-value
- * - "-1" else buffer overflow
- */
- switch (axis) {
- case LATTICE_FLIP_U:
- u1 = numU - u - 1;
- break;
- case LATTICE_FLIP_V:
- v1 = numV - v - 1;
- break;
- case LATTICE_FLIP_W:
- w1 = numW - w - 1;
- break;
- }
-
- /* get points to operate on */
- bpA = &lt->def[BKE_lattice_index_from_uvw(lt, u0, v0, w0)];
- bpB = &lt->def[BKE_lattice_index_from_uvw(lt, u1, v1, w1)];
-
- /* Swap all coordinates, so that flipped coordinates belong to
- * the indices on the correct side of the lattice.
- *
- * Coords: (-2 4) |0| (3 4) --> (3 4) |0| (-2 4)
- * Indices: (0,L) (1,R) --> (0,L) (1,R)
- */
- swap_v3_v3(bpA->vec, bpB->vec);
-
- /* However, we need to mirror the coordinate values on the axis we're dealing with,
- * otherwise we'd have effectively only rotated the points around. If we don't do this,
- * we'd just be reimplementing the naive mirroring algorithm, which causes unwanted deforms
- * such as flipped normals, etc.
- *
- * Coords: (3 4) |0| (-2 4) --\
- * \-> (-3 4) |0| (2 4)
- * Indices: (0,L) (1,R) --> (0,L) (1,R)
- */
- lattice_flip_point_value(lt, u0, v0, w0, mid, axis);
- lattice_flip_point_value(lt, u1, v1, w1, mid, axis);
-}
-
-static int lattice_flip_exec(bContext *C, wmOperator *op)
-{
- Object *obedit = CTX_data_edit_object(C);
- Lattice *lt;
-
- eLattice_FlipAxes axis = RNA_enum_get(op->ptr, "axis");
- int numU, numV, numW;
- int totP;
-
- float mid = 0.0f;
- short isOdd = 0;
-
- /* get lattice - we need the "edit lattice" from the lattice... confusing... */
- lt = (Lattice *)obedit->data;
- lt = lt->editlatt->latt;
-
- numU = lt->pntsu;
- numV = lt->pntsv;
- numW = lt->pntsw;
- totP = numU * numV * numW;
-
- /* First Pass: determine midpoint - used for flipping center verts if there are odd number of points on axis */
- switch (axis) {
- case LATTICE_FLIP_U:
- isOdd = numU & 1;
- break;
- case LATTICE_FLIP_V:
- isOdd = numV & 1;
- break;
- case LATTICE_FLIP_W:
- isOdd = numW & 1;
- break;
-
- default:
- printf("lattice_flip(): Unknown flipping axis (%u)\n", axis);
- return OPERATOR_CANCELLED;
- }
-
- if (isOdd) {
- BPoint *bp;
- float avgInv = 1.0f / (float)totP;
- int i;
-
- /* midpoint calculation - assuming that u/v/w are axis-aligned */
- for (i = 0, bp = lt->def; i < totP; i++, bp++) {
- mid += bp->vec[axis] * avgInv;
- }
- }
-
- /* Second Pass: swap pairs of vertices per axis, assuming they are all sorted */
- switch (axis) {
- case LATTICE_FLIP_U:
- {
- int u, v, w;
-
- /* v/w strips - front to back, top to bottom */
- for (w = 0; w < numW; w++) {
- for (v = 0; v < numV; v++) {
- /* swap coordinates of pairs of vertices on u */
- for (u = 0; u < (numU / 2); u++) {
- lattice_swap_point_pairs(lt, u, v, w, mid, axis);
- }
-
- /* flip u-coordinate of midpoint (i.e. unpaired point on u) */
- if (isOdd) {
- u = (numU / 2);
- lattice_flip_point_value(lt, u, v, w, mid, axis);
- }
- }
- }
- break;
- }
- case LATTICE_FLIP_V:
- {
- int u, v, w;
-
- /* u/w strips - front to back, left to right */
- for (w = 0; w < numW; w++) {
- for (u = 0; u < numU; u++) {
- /* swap coordinates of pairs of vertices on v */
- for (v = 0; v < (numV / 2); v++) {
- lattice_swap_point_pairs(lt, u, v, w, mid, axis);
- }
-
- /* flip v-coordinate of midpoint (i.e. unpaired point on v) */
- if (isOdd) {
- v = (numV / 2);
- lattice_flip_point_value(lt, u, v, w, mid, axis);
- }
- }
- }
- break;
- }
- case LATTICE_FLIP_W:
- {
- int u, v, w;
-
- for (v = 0; v < numV; v++) {
- for (u = 0; u < numU; u++) {
- /* swap coordinates of pairs of vertices on w */
- for (w = 0; w < (numW / 2); w++) {
- lattice_swap_point_pairs(lt, u, v, w, mid, axis);
- }
-
- /* flip w-coordinate of midpoint (i.e. unpaired point on w) */
- if (isOdd) {
- w = (numW / 2);
- lattice_flip_point_value(lt, u, v, w, mid, axis);
- }
- }
- }
- break;
- }
- default: /* shouldn't happen, but just in case */
- break;
- }
-
- /* updates */
- DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
-
- return OPERATOR_FINISHED;
-}
-
-void LATTICE_OT_flip(wmOperatorType *ot)
-{
- static EnumPropertyItem flip_items[] = {
- {LATTICE_FLIP_U, "U", 0, "U (X) Axis", ""},
- {LATTICE_FLIP_V, "V", 0, "V (Y) Axis", ""},
- {LATTICE_FLIP_W, "W", 0, "W (Z) Axis", ""},
- {0, NULL, 0, NULL, NULL}};
-
- /* identifiers */
- ot->name = "Flip (Distortion Free)";
- ot->description = "Mirror all control points without inverting the lattice deform";
- ot->idname = "LATTICE_OT_flip";
-
- /* api callbacks */
- ot->poll = ED_operator_editlattice;
- ot->invoke = WM_menu_invoke;
- ot->exec = lattice_flip_exec;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* properties */
- ot->prop = RNA_def_enum(ot->srna, "axis", flip_items, LATTICE_FLIP_U, "Flip Axis", "Coordinates along this axis get flipped");
-}
+/* -------------------------------------------------------------------- */
+/** \name Select Picking API
+ *
+ * Here actual select happens,
+ * Gets called via generic mouse select operator.
+ * \{ */
-/****************************** Mouse Selection *************************/
static void findnearestLattvert__doClosest(void *userData, BPoint *bp, const float screen_co[2])
{
struct { BPoint *bp; float dist; int select; float mval_fl[2]; } *data = userData;
float dist_test = len_manhattan_v2v2(data->mval_fl, screen_co);
-
+
if ((bp->f1 & SELECT) && data->select)
dist_test += 5.0f;
@@ -883,7 +521,7 @@ bool ED_lattice_select_pick(bContext *C, const int mval[2], bool extend, bool de
BPoint *bp = NULL;
Lattice *lt;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
lt = ((Lattice *)vc.obedit->data)->editlatt->latt;
bp = findnearestLattvert(&vc, mval, true);
@@ -917,70 +555,4 @@ bool ED_lattice_select_pick(bContext *C, const int mval[2], bool extend, bool de
return false;
}
-/******************************** Undo *************************/
-
-typedef struct UndoLattice {
- BPoint *def;
- int pntsu, pntsv, pntsw, actbp;
-} UndoLattice;
-
-static void undoLatt_to_editLatt(void *data, void *edata, void *UNUSED(obdata))
-{
- UndoLattice *ult = (UndoLattice *)data;
- EditLatt *editlatt = (EditLatt *)edata;
- int a = editlatt->latt->pntsu * editlatt->latt->pntsv * editlatt->latt->pntsw;
-
- memcpy(editlatt->latt->def, ult->def, a * sizeof(BPoint));
- editlatt->latt->actbp = ult->actbp;
-}
-
-static void *editLatt_to_undoLatt(void *edata, void *UNUSED(obdata))
-{
- UndoLattice *ult = MEM_callocN(sizeof(UndoLattice), "UndoLattice");
- EditLatt *editlatt = (EditLatt *)edata;
-
- ult->def = MEM_dupallocN(editlatt->latt->def);
- ult->pntsu = editlatt->latt->pntsu;
- ult->pntsv = editlatt->latt->pntsv;
- ult->pntsw = editlatt->latt->pntsw;
- ult->actbp = editlatt->latt->actbp;
-
- return ult;
-}
-
-static void free_undoLatt(void *data)
-{
- UndoLattice *ult = (UndoLattice *)data;
-
- if (ult->def) MEM_freeN(ult->def);
- MEM_freeN(ult);
-}
-
-static int validate_undoLatt(void *data, void *edata)
-{
- UndoLattice *ult = (UndoLattice *)data;
- EditLatt *editlatt = (EditLatt *)edata;
-
- return (ult->pntsu == editlatt->latt->pntsu &&
- ult->pntsv == editlatt->latt->pntsv &&
- ult->pntsw == editlatt->latt->pntsw);
-}
-
-static void *get_editlatt(bContext *C)
-{
- Object *obedit = CTX_data_edit_object(C);
-
- if (obedit && obedit->type == OB_LATTICE) {
- Lattice *lt = obedit->data;
- return lt->editlatt;
- }
-
- return NULL;
-}
-
-/* and this is all the undo system needs to know */
-void undo_push_lattice(bContext *C, const char *name)
-{
- undo_editmode_push(C, name, get_editlatt, free_undoLatt, undoLatt_to_editLatt, editLatt_to_undoLatt, validate_undoLatt);
-}
-
+/** \} */
diff --git a/source/blender/editors/lattice/editlattice_tools.c b/source/blender/editors/lattice/editlattice_tools.c
new file mode 100644
index 00000000000..c39ba44c1dc
--- /dev/null
+++ b/source/blender/editors/lattice/editlattice_tools.c
@@ -0,0 +1,340 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/lattice/editlattice_tools.c
+ * \ingroup edlattice
+ */
+
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+
+#include "DNA_curve_types.h"
+#include "DNA_lattice_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_lattice.h"
+
+#include "ED_screen.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "lattice_intern.h"
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Make Regular Operator
+ * \{ */
+
+static int make_regular_poll(bContext *C)
+{
+ Object *ob;
+
+ if (ED_operator_editlattice(C)) return 1;
+
+ ob = CTX_data_active_object(C);
+ return (ob && ob->type == OB_LATTICE);
+}
+
+static int make_regular_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Object *ob = CTX_data_edit_object(C);
+ Lattice *lt;
+
+ if (ob) {
+ lt = ob->data;
+ BKE_lattice_resize(lt->editlatt->latt, lt->pntsu, lt->pntsv, lt->pntsw, NULL);
+ }
+ else {
+ ob = CTX_data_active_object(C);
+ lt = ob->data;
+ BKE_lattice_resize(lt, lt->pntsu, lt->pntsv, lt->pntsw, NULL);
+ }
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, ob->data);
+
+ return OPERATOR_FINISHED;
+}
+
+void LATTICE_OT_make_regular(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Make Regular";
+ ot->description = "Set UVW control points a uniform distance apart";
+ ot->idname = "LATTICE_OT_make_regular";
+
+ /* api callbacks */
+ ot->exec = make_regular_exec;
+ ot->poll = make_regular_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Flip Verts Operator
+ * \{ */
+
+/* flipping options */
+typedef enum eLattice_FlipAxes {
+ LATTICE_FLIP_U = 0,
+ LATTICE_FLIP_V = 1,
+ LATTICE_FLIP_W = 2
+} eLattice_FlipAxes;
+
+/**
+ * Flip midpoint value so that relative distances between midpoint and neighbor-pair is maintained
+ * ! Assumes that uvw <=> xyz (i.e. axis-aligned index-axes with coordinate-axes)
+ * - Helper for lattice_flip_exec()
+ */
+static void lattice_flip_point_value(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
+{
+ BPoint *bp;
+ float diff;
+
+ /* just the point in the middle (unpaired) */
+ bp = &lt->def[BKE_lattice_index_from_uvw(lt, u, v, w)];
+
+ /* flip over axis */
+ diff = mid - bp->vec[axis];
+ bp->vec[axis] = mid + diff;
+}
+
+/**
+ * Swap pairs of lattice points along a specified axis
+ * - Helper for lattice_flip_exec()
+ */
+static void lattice_swap_point_pairs(Lattice *lt, int u, int v, int w, float mid, eLattice_FlipAxes axis)
+{
+ BPoint *bpA, *bpB;
+
+ int numU = lt->pntsu;
+ int numV = lt->pntsv;
+ int numW = lt->pntsw;
+
+ int u0 = u, u1 = u;
+ int v0 = v, v1 = v;
+ int w0 = w, w1 = w;
+
+ /* get pair index by just overriding the relevant pair-value
+ * - "-1" else buffer overflow
+ */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ u1 = numU - u - 1;
+ break;
+ case LATTICE_FLIP_V:
+ v1 = numV - v - 1;
+ break;
+ case LATTICE_FLIP_W:
+ w1 = numW - w - 1;
+ break;
+ }
+
+ /* get points to operate on */
+ bpA = &lt->def[BKE_lattice_index_from_uvw(lt, u0, v0, w0)];
+ bpB = &lt->def[BKE_lattice_index_from_uvw(lt, u1, v1, w1)];
+
+ /* Swap all coordinates, so that flipped coordinates belong to
+ * the indices on the correct side of the lattice.
+ *
+ * Coords: (-2 4) |0| (3 4) --> (3 4) |0| (-2 4)
+ * Indices: (0,L) (1,R) --> (0,L) (1,R)
+ */
+ swap_v3_v3(bpA->vec, bpB->vec);
+
+ /* However, we need to mirror the coordinate values on the axis we're dealing with,
+ * otherwise we'd have effectively only rotated the points around. If we don't do this,
+ * we'd just be reimplementing the naive mirroring algorithm, which causes unwanted deforms
+ * such as flipped normals, etc.
+ *
+ * Coords: (3 4) |0| (-2 4) --\
+ * \-> (-3 4) |0| (2 4)
+ * Indices: (0,L) (1,R) --> (0,L) (1,R)
+ */
+ lattice_flip_point_value(lt, u0, v0, w0, mid, axis);
+ lattice_flip_point_value(lt, u1, v1, w1, mid, axis);
+}
+
+static int lattice_flip_exec(bContext *C, wmOperator *op)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ Lattice *lt;
+
+ eLattice_FlipAxes axis = RNA_enum_get(op->ptr, "axis");
+ int numU, numV, numW;
+ int totP;
+
+ float mid = 0.0f;
+ short isOdd = 0;
+
+ /* get lattice - we need the "edit lattice" from the lattice... confusing... */
+ lt = (Lattice *)obedit->data;
+ lt = lt->editlatt->latt;
+
+ numU = lt->pntsu;
+ numV = lt->pntsv;
+ numW = lt->pntsw;
+ totP = numU * numV * numW;
+
+ /* First Pass: determine midpoint - used for flipping center verts if there are odd number of points on axis */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ isOdd = numU & 1;
+ break;
+ case LATTICE_FLIP_V:
+ isOdd = numV & 1;
+ break;
+ case LATTICE_FLIP_W:
+ isOdd = numW & 1;
+ break;
+
+ default:
+ printf("lattice_flip(): Unknown flipping axis (%u)\n", axis);
+ return OPERATOR_CANCELLED;
+ }
+
+ if (isOdd) {
+ BPoint *bp;
+ float avgInv = 1.0f / (float)totP;
+ int i;
+
+ /* midpoint calculation - assuming that u/v/w are axis-aligned */
+ for (i = 0, bp = lt->def; i < totP; i++, bp++) {
+ mid += bp->vec[axis] * avgInv;
+ }
+ }
+
+ /* Second Pass: swap pairs of vertices per axis, assuming they are all sorted */
+ switch (axis) {
+ case LATTICE_FLIP_U:
+ {
+ int u, v, w;
+
+ /* v/w strips - front to back, top to bottom */
+ for (w = 0; w < numW; w++) {
+ for (v = 0; v < numV; v++) {
+ /* swap coordinates of pairs of vertices on u */
+ for (u = 0; u < (numU / 2); u++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip u-coordinate of midpoint (i.e. unpaired point on u) */
+ if (isOdd) {
+ u = (numU / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ break;
+ }
+ case LATTICE_FLIP_V:
+ {
+ int u, v, w;
+
+ /* u/w strips - front to back, left to right */
+ for (w = 0; w < numW; w++) {
+ for (u = 0; u < numU; u++) {
+ /* swap coordinates of pairs of vertices on v */
+ for (v = 0; v < (numV / 2); v++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip v-coordinate of midpoint (i.e. unpaired point on v) */
+ if (isOdd) {
+ v = (numV / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ break;
+ }
+ case LATTICE_FLIP_W:
+ {
+ int u, v, w;
+
+ for (v = 0; v < numV; v++) {
+ for (u = 0; u < numU; u++) {
+ /* swap coordinates of pairs of vertices on w */
+ for (w = 0; w < (numW / 2); w++) {
+ lattice_swap_point_pairs(lt, u, v, w, mid, axis);
+ }
+
+ /* flip w-coordinate of midpoint (i.e. unpaired point on w) */
+ if (isOdd) {
+ w = (numW / 2);
+ lattice_flip_point_value(lt, u, v, w, mid, axis);
+ }
+ }
+ }
+ break;
+ }
+ default: /* shouldn't happen, but just in case */
+ break;
+ }
+
+ /* updates */
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, obedit->data);
+
+ return OPERATOR_FINISHED;
+}
+
+void LATTICE_OT_flip(wmOperatorType *ot)
+{
+ static const EnumPropertyItem flip_items[] = {
+ {LATTICE_FLIP_U, "U", 0, "U (X) Axis", ""},
+ {LATTICE_FLIP_V, "V", 0, "V (Y) Axis", ""},
+ {LATTICE_FLIP_W, "W", 0, "W (Z) Axis", ""},
+ {0, NULL, 0, NULL, NULL}};
+
+ /* identifiers */
+ ot->name = "Flip (Distortion Free)";
+ ot->description = "Mirror all control points without inverting the lattice deform";
+ ot->idname = "LATTICE_OT_flip";
+
+ /* api callbacks */
+ ot->poll = ED_operator_editlattice;
+ ot->invoke = WM_menu_invoke;
+ ot->exec = lattice_flip_exec;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "axis", flip_items, LATTICE_FLIP_U, "Flip Axis", "Coordinates along this axis get flipped");
+}
+
+/** \} */
diff --git a/source/blender/editors/lattice/editlattice_undo.c b/source/blender/editors/lattice/editlattice_undo.c
new file mode 100644
index 00000000000..7a7372f5a6a
--- /dev/null
+++ b/source/blender/editors/lattice/editlattice_undo.c
@@ -0,0 +1,195 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/lattice/editlattice_undo.c
+ * \ingroup edlattice
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_array_utils.h"
+
+#include "DNA_curve_types.h"
+#include "DNA_lattice_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+
+#include "ED_object.h"
+#include "ED_lattice.h"
+#include "ED_util.h"
+
+#include "WM_types.h"
+#include "WM_api.h"
+
+#include "lattice_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct UndoLattice {
+ BPoint *def;
+ int pntsu, pntsv, pntsw, actbp;
+ size_t undo_size;
+} UndoLattice;
+
+static void undolatt_to_editlatt(UndoLattice *ult, EditLatt *editlatt)
+{
+ int len = editlatt->latt->pntsu * editlatt->latt->pntsv * editlatt->latt->pntsw;
+
+ memcpy(editlatt->latt->def, ult->def, sizeof(BPoint) * len);
+ editlatt->latt->actbp = ult->actbp;
+}
+
+static void *undolatt_from_editlatt(UndoLattice *ult, EditLatt *editlatt)
+{
+ BLI_assert(BLI_array_is_zeroed(ult, 1));
+
+ ult->def = MEM_dupallocN(editlatt->latt->def);
+ ult->pntsu = editlatt->latt->pntsu;
+ ult->pntsv = editlatt->latt->pntsv;
+ ult->pntsw = editlatt->latt->pntsw;
+ ult->actbp = editlatt->latt->actbp;
+
+ ult->undo_size += sizeof(*ult->def) * ult->pntsu * ult->pntsv * ult->pntsw;
+
+ return ult;
+}
+
+static void undolatt_free_data(UndoLattice *ult)
+{
+ if (ult->def) {
+ MEM_freeN(ult->def);
+ }
+}
+
+#if 0
+static int validate_undoLatt(void *data, void *edata)
+{
+ UndoLattice *ult = (UndoLattice *)data;
+ EditLatt *editlatt = (EditLatt *)edata;
+
+ return (ult->pntsu == editlatt->latt->pntsu &&
+ ult->pntsv == editlatt->latt->pntsv &&
+ ult->pntsw == editlatt->latt->pntsw);
+}
+#endif
+
+static Object *editlatt_object_from_context(bContext *C)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ if (obedit && obedit->type == OB_LATTICE) {
+ Lattice *lt = obedit->data;
+ if (lt->editlatt != NULL) {
+ return obedit;
+ }
+ }
+
+ return NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct LatticeUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ UndoLattice data;
+} LatticeUndoStep;
+
+static bool lattice_undosys_poll(bContext *C)
+{
+ return editlatt_object_from_context(C) != NULL;
+}
+
+static bool lattice_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ LatticeUndoStep *us = (LatticeUndoStep *)us_p;
+ us->obedit_ref.ptr = editlatt_object_from_context(C);
+ Lattice *lt = us->obedit_ref.ptr->data;
+ undolatt_from_editlatt(&us->data, lt->editlatt);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void lattice_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_EDIT);
+ BLI_assert(lattice_undosys_poll(C));
+
+ LatticeUndoStep *us = (LatticeUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ Lattice *lt = obedit->data;
+ EditLatt *editlatt = lt->editlatt;
+ undolatt_to_editlatt(&us->data, editlatt);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
+}
+
+static void lattice_undosys_step_free(UndoStep *us_p)
+{
+ LatticeUndoStep *us = (LatticeUndoStep *)us_p;
+ undolatt_free_data(&us->data);
+}
+
+static void lattice_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ LatticeUndoStep *us = (LatticeUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
+}
+
+/* Export for ED_undo_sys. */
+void ED_lattice_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Lattice";
+ ut->poll = lattice_undosys_poll;
+ ut->step_encode = lattice_undosys_step_encode;
+ ut->step_decode = lattice_undosys_step_decode;
+ ut->step_free = lattice_undosys_step_free;
+
+ ut->step_foreach_ID_ref = lattice_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(LatticeUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/util/util_intern.h b/source/blender/editors/lattice/lattice_intern.h
index 0f650330951..7902b992270 100644
--- a/source/blender/editors/util/util_intern.h
+++ b/source/blender/editors/lattice/lattice_intern.h
@@ -4,7 +4,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
@@ -18,29 +18,27 @@
* The Original Code is Copyright (C) 2008 Blender Foundation.
* All rights reserved.
*
- *
- * Contributor(s): Blender Foundation
- *
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/editors/util/util_intern.h
- * \ingroup edutil
+/** \file blender/editors/lattice/lattice_intern.h
+ * \ingroup edlattice
*/
-#ifndef __UTIL_INTERN_H__
-#define __UTIL_INTERN_H__
-
-/* internal exports only */
+#ifndef __LATTICE_INTERN_H__
+#define __LATTICE_INTERN_H__
-/* editmode_undo.c */
-void undo_editmode_name(struct bContext *C, const char *undoname);
-bool undo_editmode_is_valid(const char *undoname);
-const char *undo_editmode_get_name(struct bContext *C, int nr, bool *r_active);
-void *undo_editmode_get_prev(struct Object *ob);
-void undo_editmode_step(struct bContext *C, int step);
-void undo_editmode_number(struct bContext *C, int nr);
+/* editlattice_select.c */
+void LATTICE_OT_select_all(struct wmOperatorType *ot);
+void LATTICE_OT_select_more(struct wmOperatorType *ot);
+void LATTICE_OT_select_less(struct wmOperatorType *ot);
+void LATTICE_OT_select_ungrouped(struct wmOperatorType *ot);
+void LATTICE_OT_select_random(struct wmOperatorType *ot);
+void LATTICE_OT_select_mirror(struct wmOperatorType *ot);
-#endif /* __UTIL_INTERN_H__ */
+/* editlattice_tools.c */
+void LATTICE_OT_make_regular(struct wmOperatorType *ot);
+void LATTICE_OT_flip(struct wmOperatorType *ot);
+#endif /* __LATTICE_INTERN_H__ */
diff --git a/source/blender/editors/lattice/lattice_ops.c b/source/blender/editors/lattice/lattice_ops.c
new file mode 100644
index 00000000000..d3d57a0b510
--- /dev/null
+++ b/source/blender/editors/lattice/lattice_ops.c
@@ -0,0 +1,80 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/lattice/lattice_ops.c
+ * \ingroup edlattice
+ */
+
+#include "DNA_scene_types.h"
+
+#include "RNA_access.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_screen.h"
+#include "ED_object.h"
+#include "ED_lattice.h"
+
+#include "lattice_intern.h"
+
+void ED_operatortypes_lattice(void)
+{
+ WM_operatortype_append(LATTICE_OT_select_all);
+ WM_operatortype_append(LATTICE_OT_select_more);
+ WM_operatortype_append(LATTICE_OT_select_less);
+ WM_operatortype_append(LATTICE_OT_select_ungrouped);
+ WM_operatortype_append(LATTICE_OT_select_random);
+ WM_operatortype_append(LATTICE_OT_select_mirror);
+ WM_operatortype_append(LATTICE_OT_make_regular);
+ WM_operatortype_append(LATTICE_OT_flip);
+}
+
+void ED_keymap_lattice(wmKeyConfig *keyconf)
+{
+ wmKeyMap *keymap;
+ wmKeyMapItem *kmi;
+
+ keymap = WM_keymap_find(keyconf, "Lattice", 0, 0);
+ keymap->poll = ED_operator_editlattice;
+
+ kmi = WM_keymap_add_item(keymap, "LATTICE_OT_select_all", AKEY, KM_PRESS, 0, 0);
+ RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE);
+ kmi = WM_keymap_add_item(keymap, "LATTICE_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0);
+ RNA_enum_set(kmi->ptr, "action", SEL_INVERT);
+ WM_keymap_add_item(keymap, "LATTICE_OT_select_more", PADPLUSKEY, KM_PRESS, KM_CTRL, 0);
+ WM_keymap_add_item(keymap, "LATTICE_OT_select_less", PADMINUS, KM_PRESS, KM_CTRL, 0);
+
+ WM_keymap_add_item(keymap, "OBJECT_OT_vertex_parent_set", PKEY, KM_PRESS, KM_CTRL, 0);
+
+ WM_keymap_add_item(keymap, "LATTICE_OT_flip", FKEY, KM_PRESS, KM_CTRL, 0);
+
+ /* menus */
+ WM_keymap_add_menu(keymap, "VIEW3D_MT_hook", HKEY, KM_PRESS, KM_CTRL, 0);
+
+ ED_keymap_proportional_cycle(keyconf, keymap);
+ ED_keymap_proportional_editmode(keyconf, keymap, false);
+}
diff --git a/source/blender/editors/mask/mask_add.c b/source/blender/editors/mask/mask_add.c
index f01af22cec9..69335195b96 100644
--- a/source/blender/editors/mask/mask_add.c
+++ b/source/blender/editors/mask/mask_add.c
@@ -770,14 +770,17 @@ static int create_primitive_from_points(bContext *C, wmOperator *op, const float
new_spline = BKE_mask_spline_add(mask_layer);
new_spline->flag = MASK_SPLINE_CYCLIC | SELECT;
- new_spline->tot_point = num_points;
new_spline->points = MEM_recallocN(new_spline->points,
- sizeof(MaskSplinePoint) * new_spline->tot_point);
+ sizeof(MaskSplinePoint) * num_points);
mask_layer->act_spline = new_spline;
mask_layer->act_point = NULL;
+ const int spline_index = BKE_mask_layer_shape_spline_to_index(mask_layer, new_spline);
+
for (i = 0; i < num_points; i++) {
+ new_spline->tot_point = i + 1;
+
MaskSplinePoint *new_point = &new_spline->points[i];
BKE_mask_parent_init(&new_point->parent);
@@ -788,6 +791,12 @@ static int create_primitive_from_points(bContext *C, wmOperator *op, const float
new_point->bezt.h1 = handle_type;
new_point->bezt.h2 = handle_type;
BKE_mask_point_select_set(new_point, true);
+
+ if (mask_layer->splines_shapes.first) {
+ BKE_mask_layer_shape_changed_add(mask_layer,
+ spline_index + i,
+ true, true);
+ }
}
WM_event_add_notifier(C, NC_MASK | NA_EDITED, mask);
diff --git a/source/blender/editors/mask/mask_draw.c b/source/blender/editors/mask/mask_draw.c
index 2b4f94a37ef..407c19a3860 100644
--- a/source/blender/editors/mask/mask_draw.c
+++ b/source/blender/editors/mask/mask_draw.c
@@ -658,87 +658,18 @@ void ED_mask_draw(const bContext *C,
draw_masklays(C, mask, draw_flag, draw_type, width, height, xscale * aspx, yscale * aspy);
}
-typedef struct ThreadedMaskRasterizeState {
- MaskRasterHandle *handle;
- float *buffer;
- int width, height;
-} ThreadedMaskRasterizeState;
-
-typedef struct ThreadedMaskRasterizeData {
- int start_scanline;
- int num_scanlines;
-} ThreadedMaskRasterizeData;
-
-static void mask_rasterize_func(TaskPool * __restrict pool, void *taskdata, int UNUSED(threadid))
+static float *mask_rasterize(Mask *mask, const int width, const int height)
{
- ThreadedMaskRasterizeState *state = (ThreadedMaskRasterizeState *) BLI_task_pool_userdata(pool);
- ThreadedMaskRasterizeData *data = (ThreadedMaskRasterizeData *) taskdata;
- int scanline;
- const float x_inv = 1.0f / (float)state->width;
- const float y_inv = 1.0f / (float)state->height;
- const float x_px_ofs = x_inv * 0.5f;
- const float y_px_ofs = y_inv * 0.5f;
-
- for (scanline = 0; scanline < data->num_scanlines; scanline++) {
- float xy[2];
- int x, y = data->start_scanline + scanline;
-
- xy[1] = ((float)y * y_inv) + y_px_ofs;
-
- for (x = 0; x < state->width; x++) {
- int index = y * state->width + x;
-
- xy[0] = ((float)x * x_inv) + x_px_ofs;
-
- state->buffer[index] = BKE_maskrasterize_handle_sample(state->handle, xy);
- }
- }
-}
-
-static float *threaded_mask_rasterize(Mask *mask, const int width, const int height)
-{
- TaskScheduler *task_scheduler = BLI_task_scheduler_get();
- TaskPool *task_pool;
MaskRasterHandle *handle;
- ThreadedMaskRasterizeState state;
- float *buffer;
- int i, num_threads = BLI_task_scheduler_num_threads(task_scheduler), scanlines_per_thread;
-
- buffer = MEM_mallocN(sizeof(float) * height * width, "rasterized mask buffer");
+ float *buffer = MEM_mallocN(sizeof(float) * height * width, "rasterized mask buffer");
/* Initialize rasterization handle. */
handle = BKE_maskrasterize_handle_new();
BKE_maskrasterize_handle_init(handle, mask, width, height, true, true, true);
- state.handle = handle;
- state.buffer = buffer;
- state.width = width;
- state.height = height;
-
- task_pool = BLI_task_pool_create(task_scheduler, &state);
-
- scanlines_per_thread = height / num_threads;
- for (i = 0; i < num_threads; i++) {
- ThreadedMaskRasterizeData *data = MEM_mallocN(sizeof(ThreadedMaskRasterizeData),
- "threaded mask rasterize data");
-
- data->start_scanline = i * scanlines_per_thread;
-
- if (i < num_threads - 1) {
- data->num_scanlines = scanlines_per_thread;
- }
- else {
- data->num_scanlines = height - data->start_scanline;
- }
-
- BLI_task_pool_push(task_pool, mask_rasterize_func, data, true, TASK_PRIORITY_LOW);
- }
-
- /* work and wait until tasks are done */
- BLI_task_pool_work_and_wait(task_pool);
+ BKE_maskrasterize_buffer(handle, width, height, buffer);
/* Free memory. */
- BLI_task_pool_free(task_pool);
BKE_maskrasterize_handle_free(handle);
return buffer;
@@ -802,7 +733,7 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
}
if (draw_flag & MASK_DRAWFLAG_OVERLAY) {
- float *buffer = threaded_mask_rasterize(mask, width, height);
+ float *buffer = mask_rasterize(mask, width, height);
int format;
if (overlay_mode == MASK_OVERLAY_ALPHACHANNEL) {
@@ -834,13 +765,12 @@ void ED_mask_draw_region(Mask *mask, ARegion *ar,
/* apply transformation so mask editing tools will assume drawing from the origin in normalized space */
glPushMatrix();
-
+ glTranslatef(x + xofs, y + yofs, 0);
+ glScalef(zoomx, zoomy, 0);
if (stabmat) {
glMultMatrixf(stabmat);
}
-
- glTranslatef(x + xofs, y + yofs, 0);
- glScalef(maxdim * zoomx, maxdim * zoomy, 0);
+ glScalef(maxdim, maxdim, 0);
if (do_draw_cb) {
ED_region_draw_cb_draw(C, ar, REGION_DRAW_PRE_VIEW);
diff --git a/source/blender/editors/mask/mask_ops.c b/source/blender/editors/mask/mask_ops.c
index eef03852007..97d5ee1eff0 100644
--- a/source/blender/editors/mask/mask_ops.c
+++ b/source/blender/editors/mask/mask_ops.c
@@ -889,7 +889,7 @@ static int slide_point_modal(bContext *C, wmOperator *op, const wmEvent *event)
if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY))
data->is_accurate = (event->val == KM_PRESS);
- /* fall-through */ /* update CV position */
+ ATTR_FALLTHROUGH; /* update CV position */
case MOUSEMOVE:
{
ScrArea *sa = CTX_wm_area(C);
@@ -999,7 +999,7 @@ static int slide_point_modal(bContext *C, wmOperator *op, const wmEvent *event)
if (weight) {
sub_v2_v2v2(c, offco, p);
- project_v2_v2v2(vec, c, no);
+ project_v2_v2v2_normalized(vec, c, no);
w = len_v2(vec);
@@ -1376,7 +1376,7 @@ static int slide_spline_curvature_modal(bContext *C, wmOperator *op, const wmEve
}
- /* fall-through */ /* update CV position */
+ ATTR_FALLTHROUGH; /* update CV position */
case MOUSEMOVE:
{
float B[2], mouse_coord[2], delta[2];
@@ -1909,7 +1909,7 @@ static int set_handle_type_exec(bContext *C, wmOperator *op)
void MASK_OT_handle_type_set(wmOperatorType *ot)
{
- static EnumPropertyItem editcurve_handle_type_items[] = {
+ static const EnumPropertyItem editcurve_handle_type_items[] = {
{HD_AUTO, "AUTO", 0, "Auto", ""},
{HD_VECT, "VECTOR", 0, "Vector", ""},
{HD_ALIGN, "ALIGNED", 0, "Aligned Single", ""},
@@ -1937,16 +1937,17 @@ void MASK_OT_handle_type_set(wmOperatorType *ot)
/* ********* clear/set restrict view *********/
-static int mask_hide_view_clear_exec(bContext *C, wmOperator *UNUSED(op))
+static int mask_hide_view_clear_exec(bContext *C, wmOperator *op)
{
Mask *mask = CTX_data_edit_mask(C);
MaskLayer *masklay;
bool changed = false;
+ const bool select = RNA_boolean_get(op->ptr, "select");
for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
if (masklay->restrictflag & OB_RESTRICT_VIEW) {
- ED_mask_layer_select_set(masklay, true);
+ ED_mask_layer_select_set(masklay, select);
masklay->restrictflag &= ~OB_RESTRICT_VIEW;
changed = true;
}
@@ -1977,6 +1978,8 @@ void MASK_OT_hide_view_clear(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
static int mask_hide_view_set_exec(bContext *C, wmOperator *op)
@@ -2151,7 +2154,7 @@ static int mask_layer_move_exec(bContext *C, wmOperator *op)
void MASK_OT_layer_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/mask/mask_select.c b/source/blender/editors/mask/mask_select.c
index a4268bddaf5..7ffd82e262c 100644
--- a/source/blender/editors/mask/mask_select.c
+++ b/source/blender/editors/mask/mask_select.c
@@ -33,7 +33,7 @@
#include "BLI_utildefines.h"
#include "BLI_rect.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_math.h"
#include "BKE_context.h"
@@ -408,8 +408,9 @@ static int border_select_exec(bContext *C, wmOperator *op)
rcti rect;
rctf rectf;
- int mode;
- bool changed = false, extend;
+ bool changed = false;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* get rectangle from operator */
WM_operator_properties_border_to_rcti(op, &rect);
@@ -417,9 +418,6 @@ static int border_select_exec(bContext *C, wmOperator *op)
ED_mask_point_pos(sa, ar, rect.xmin, rect.ymin, &rectf.xmin, &rectf.ymin);
ED_mask_point_pos(sa, ar, rect.xmax, rect.ymax, &rectf.xmax, &rectf.ymax);
- mode = RNA_int_get(op->ptr, "gesture_mode");
- extend = RNA_boolean_get(op->ptr, "extend");
-
/* do actual selection */
for (masklay = mask->masklayers.first; masklay; masklay = masklay->next) {
MaskSpline *spline;
@@ -439,8 +437,8 @@ static int border_select_exec(bContext *C, wmOperator *op)
/* TODO: uw? */
if (BLI_rctf_isect_pt_v(&rectf, point_deform->bezt.vec[1])) {
- BKE_mask_point_select_set(point, mode == GESTURE_MODAL_SELECT);
- BKE_mask_point_select_set_handle(point, MASK_WHICH_HANDLE_BOTH, mode == GESTURE_MODAL_SELECT);
+ BKE_mask_point_select_set(point, select);
+ BKE_mask_point_select_set_handle(point, MASK_WHICH_HANDLE_BOTH, select);
}
else if (!extend) {
BKE_mask_point_select_set(point, false);
@@ -471,16 +469,16 @@ void MASK_OT_select_border(wmOperatorType *ot)
ot->idname = "MASK_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = border_select_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = ED_maskedit_mask_poll;
/* flags */
ot->flag = OPTYPE_UNDO;
/* properties */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
static bool do_lasso_select_mask(bContext *C, const int mcords[][2], short moves, short select)
@@ -580,9 +578,7 @@ void MASK_OT_select_lasso(wmOperatorType *ot)
ot->flag = OPTYPE_UNDO;
/* properties */
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
+ WM_operator_properties_gesture_lasso_select(ot);
}
/********************** circle select operator *********************/
@@ -608,15 +604,15 @@ static int circle_select_exec(bContext *C, wmOperator *op)
int i;
float zoomx, zoomy, offset[2], ellipse[2];
- int x, y, radius, width, height, mode;
+ int width, height;
bool changed = false;
/* get operator properties */
- x = RNA_int_get(op->ptr, "x");
- y = RNA_int_get(op->ptr, "y");
- radius = RNA_int_get(op->ptr, "radius");
+ const int x = RNA_int_get(op->ptr, "x");
+ const int y = RNA_int_get(op->ptr, "y");
+ const int radius = RNA_int_get(op->ptr, "radius");
- mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
/* compute ellipse and position in unified coordinates */
ED_mask_get_size(sa, &width, &height);
@@ -644,8 +640,8 @@ static int circle_select_exec(bContext *C, wmOperator *op)
MaskSplinePoint *point_deform = &points_array[i];
if (mask_spline_point_inside_ellipse(&point_deform->bezt, offset, ellipse)) {
- BKE_mask_point_select_set(point, mode == GESTURE_MODAL_SELECT);
- BKE_mask_point_select_set_handle(point, MASK_WHICH_HANDLE_BOTH, mode == GESTURE_MODAL_SELECT);
+ BKE_mask_point_select_set(point, select);
+ BKE_mask_point_select_set_handle(point, MASK_WHICH_HANDLE_BOTH, select);
changed = true;
}
@@ -681,10 +677,7 @@ void MASK_OT_select_circle(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
+ WM_operator_properties_gesture_circle_select(ot);
}
static int mask_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
diff --git a/source/blender/editors/mesh/CMakeLists.txt b/source/blender/editors/mesh/CMakeLists.txt
index 8783367ef7e..725d31a64ba 100644
--- a/source/blender/editors/mesh/CMakeLists.txt
+++ b/source/blender/editors/mesh/CMakeLists.txt
@@ -58,6 +58,7 @@ set(SRC
editmesh_undo.c
editmesh_utils.c
mesh_data.c
+ mesh_mirror.c
mesh_ops.c
meshtools.c
diff --git a/source/blender/editors/mesh/editface.c b/source/blender/editors/mesh/editface.c
index c4e87614732..c453284a617 100644
--- a/source/blender/editors/mesh/editface.c
+++ b/source/blender/editors/mesh/editface.c
@@ -24,7 +24,6 @@
* \ingroup edmesh
*/
-
#include "MEM_guardedalloc.h"
#include "BLI_blenlib.h"
@@ -41,8 +40,6 @@
#include "BKE_global.h"
#include "BKE_mesh.h"
#include "BKE_context.h"
-#include "BKE_editmesh.h"
-#include "BKE_utildefines.h"
#include "BIF_gl.h"
@@ -139,7 +136,7 @@ void paintface_hide(Object *ob, const bool unselected)
}
-void paintface_reveal(Object *ob)
+void paintface_reveal(Object *ob, const bool select)
{
Mesh *me;
MPoly *mpoly;
@@ -152,8 +149,8 @@ void paintface_reveal(Object *ob)
a = me->totpoly;
while (a--) {
if (mpoly->flag & ME_HIDE) {
- mpoly->flag |= ME_FACE_SEL;
- mpoly->flag -= ME_HIDE;
+ SET_FLAG_FROM_TEST(mpoly->flag, select, ME_FACE_SEL);
+ mpoly->flag &= ~ME_HIDE;
}
mpoly++;
}
@@ -231,7 +228,7 @@ static void select_linked_tfaces_with_seams(Mesh *me, const unsigned int index,
for (a = 0, mp = me->mpoly; a < me->totpoly; a++, mp++) {
if (BLI_BITMAP_TEST(poly_tag, a)) {
- BKE_BIT_TEST_SET(mp->flag, select, ME_FACE_SEL);
+ SET_FLAG_FROM_TEST(mp->flag, select, ME_FACE_SEL);
}
}
@@ -306,31 +303,30 @@ void paintface_deselect_all_visible(Object *ob, int action, bool flush_flags)
bool paintface_minmax(Object *ob, float r_min[3], float r_max[3])
{
- Mesh *me;
- MPoly *mp;
- MTexPoly *tf;
- MLoop *ml;
- MVert *mvert;
+ const Mesh *me;
+ const MPoly *mp;
+ const MLoop *ml;
+ const MVert *mvert;
int a, b;
bool ok = false;
float vec[3], bmat[3][3];
me = BKE_mesh_from_object(ob);
- if (!me || !me->mtpoly) return ok;
+ if (!me || !me->mloopuv) {
+ return ok;
+ }
copy_m3_m4(bmat, ob->obmat);
mvert = me->mvert;
mp = me->mpoly;
- tf = me->mtpoly;
- for (a = me->totpoly; a > 0; a--, mp++, tf++) {
+ for (a = me->totpoly; a > 0; a--, mp++) {
if (mp->flag & ME_HIDE || !(mp->flag & ME_FACE_SEL))
continue;
ml = me->mloop + mp->totloop;
for (b = 0; b < mp->totloop; b++, ml++) {
- copy_v3_v3(vec, (mvert[ml->v].co));
- mul_m3_v3(bmat, vec);
+ mul_v3_m3v3(vec, bmat, mvert[ml->v].co);
add_v3_v3v3(vec, vec, ob->obmat[3]);
minmax_v3v3_v3(r_min, r_max, vec);
}
@@ -607,236 +603,3 @@ void paintvert_select_ungrouped(Object *ob, bool extend, bool flush_flags)
paintvert_flush_flags(ob);
}
}
-
-/* ********************* MESH VERTEX MIRR TOPO LOOKUP *************** */
-/* note, this is not the best place for the function to be but moved
- * here for the purpose of syncing with bmesh */
-
-typedef unsigned int MirrTopoHash_t;
-
-typedef struct MirrTopoVert_t {
- MirrTopoHash_t hash;
- int v_index;
-} MirrTopoVert_t;
-
-static int mirrtopo_hash_sort(const void *l1, const void *l2)
-{
- if ((MirrTopoHash_t)(intptr_t)l1 > (MirrTopoHash_t)(intptr_t)l2) return 1;
- else if ((MirrTopoHash_t)(intptr_t)l1 < (MirrTopoHash_t)(intptr_t)l2) return -1;
- return 0;
-}
-
-static int mirrtopo_vert_sort(const void *v1, const void *v2)
-{
- if (((MirrTopoVert_t *)v1)->hash > ((MirrTopoVert_t *)v2)->hash) return 1;
- else if (((MirrTopoVert_t *)v1)->hash < ((MirrTopoVert_t *)v2)->hash) return -1;
- return 0;
-}
-
-bool ED_mesh_mirrtopo_recalc_check(Mesh *me, DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store)
-{
- int totvert;
- int totedge;
-
- if (dm) {
- totvert = dm->getNumVerts(dm);
- totedge = dm->getNumEdges(dm);
- }
- else if (me->edit_btmesh) {
- totvert = me->edit_btmesh->bm->totvert;
- totedge = me->edit_btmesh->bm->totedge;
- }
- else {
- totvert = me->totvert;
- totedge = me->totedge;
- }
-
- if ((mesh_topo_store->index_lookup == NULL) ||
- (mesh_topo_store->prev_ob_mode != ob_mode) ||
- (totvert != mesh_topo_store->prev_vert_tot) ||
- (totedge != mesh_topo_store->prev_edge_tot))
- {
- return true;
- }
- else {
- return false;
- }
-
-}
-
-void ED_mesh_mirrtopo_init(Mesh *me, DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store,
- const bool skip_em_vert_array_init)
-{
- MEdge *medge = NULL, *med;
- BMEditMesh *em = dm ? NULL : me->edit_btmesh;
-
- /* editmode*/
- BMEdge *eed;
- BMIter iter;
-
- int a, last;
- int totvert, totedge;
- int tot_unique = -1, tot_unique_prev = -1;
- int tot_unique_edges = 0, tot_unique_edges_prev;
-
- MirrTopoHash_t *topo_hash = NULL;
- MirrTopoHash_t *topo_hash_prev = NULL;
- MirrTopoVert_t *topo_pairs;
- MirrTopoHash_t topo_pass = 1;
-
- intptr_t *index_lookup; /* direct access to mesh_topo_store->index_lookup */
-
- /* reallocate if needed */
- ED_mesh_mirrtopo_free(mesh_topo_store);
-
- mesh_topo_store->prev_ob_mode = ob_mode;
-
- if (em) {
- BM_mesh_elem_index_ensure(em->bm, BM_VERT);
-
- totvert = em->bm->totvert;
- }
- else {
- totvert = dm ? dm->getNumVerts(dm) : me->totvert;
- }
-
- topo_hash = MEM_callocN(totvert * sizeof(MirrTopoHash_t), "TopoMirr");
-
- /* Initialize the vert-edge-user counts used to detect unique topology */
- if (em) {
- totedge = me->edit_btmesh->bm->totedge;
-
- BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
- const int i1 = BM_elem_index_get(eed->v1), i2 = BM_elem_index_get(eed->v2);
- topo_hash[i1]++;
- topo_hash[i2]++;
- }
- }
- else {
- totedge = dm ? dm->getNumEdges(dm) : me->totedge;
- medge = dm ? dm->getEdgeArray(dm) : me->medge;
-
- for (a = 0, med = medge; a < totedge; a++, med++) {
- const unsigned int i1 = med->v1, i2 = med->v2;
- topo_hash[i1]++;
- topo_hash[i2]++;
- }
- }
-
- topo_hash_prev = MEM_dupallocN(topo_hash);
-
- tot_unique_prev = -1;
- tot_unique_edges_prev = -1;
- while (1) {
- /* use the number of edges per vert to give verts unique topology IDs */
-
- tot_unique_edges = 0;
-
- /* This can make really big numbers, wrapping around here is fine */
- if (em) {
- BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
- const int i1 = BM_elem_index_get(eed->v1), i2 = BM_elem_index_get(eed->v2);
- topo_hash[i1] += topo_hash_prev[i2] * topo_pass;
- topo_hash[i2] += topo_hash_prev[i1] * topo_pass;
- tot_unique_edges += (topo_hash[i1] != topo_hash[i2]);
- }
- }
- else {
- for (a = 0, med = medge; a < totedge; a++, med++) {
- const unsigned int i1 = med->v1, i2 = med->v2;
- topo_hash[i1] += topo_hash_prev[i2] * topo_pass;
- topo_hash[i2] += topo_hash_prev[i1] * topo_pass;
- tot_unique_edges += (topo_hash[i1] != topo_hash[i2]);
- }
- }
- memcpy(topo_hash_prev, topo_hash, sizeof(MirrTopoHash_t) * totvert);
-
- /* sort so we can count unique values */
- qsort(topo_hash_prev, totvert, sizeof(MirrTopoHash_t), mirrtopo_hash_sort);
-
- tot_unique = 1; /* account for skiping the first value */
- for (a = 1; a < totvert; a++) {
- if (topo_hash_prev[a - 1] != topo_hash_prev[a]) {
- tot_unique++;
- }
- }
-
- if ((tot_unique <= tot_unique_prev) && (tot_unique_edges <= tot_unique_edges_prev)) {
- /* Finish searching for unique values when 1 loop dosnt give a
- * higher number of unique values compared to the previous loop */
- break;
- }
- else {
- tot_unique_prev = tot_unique;
- tot_unique_edges_prev = tot_unique_edges;
- }
- /* Copy the hash calculated this iter, so we can use them next time */
- memcpy(topo_hash_prev, topo_hash, sizeof(MirrTopoHash_t) * totvert);
-
- topo_pass++;
- }
-
- /* Hash/Index pairs are needed for sorting to find index pairs */
- topo_pairs = MEM_callocN(sizeof(MirrTopoVert_t) * totvert, "MirrTopoPairs");
-
- /* since we are looping through verts, initialize these values here too */
- index_lookup = MEM_mallocN(totvert * sizeof(*index_lookup), "mesh_topo_lookup");
-
- if (em) {
- if (skip_em_vert_array_init == false) {
- BM_mesh_elem_table_ensure(em->bm, BM_VERT);
- }
- }
-
- for (a = 0; a < totvert; a++) {
- topo_pairs[a].hash = topo_hash[a];
- topo_pairs[a].v_index = a;
-
- /* initialize lookup */
- index_lookup[a] = -1;
- }
-
- qsort(topo_pairs, totvert, sizeof(MirrTopoVert_t), mirrtopo_vert_sort);
-
- /* Since the loop starts at 2, we must define the last index where the hash's differ */
- last = ((totvert >= 2) && (topo_pairs[0].hash == topo_pairs[1].hash)) ? 0 : 1;
-
- /* Get the pairs out of the sorted hashes, note, totvert+1 means we can use the previous 2,
- * but you cant ever access the last 'a' index of MirrTopoPairs */
- for (a = 2; a <= totvert; a++) {
- /* printf("I %d %ld %d\n", (a-last), MirrTopoPairs[a ].hash, MirrTopoPairs[a ].v_index ); */
- if ((a == totvert) || (topo_pairs[a - 1].hash != topo_pairs[a].hash)) {
- if (a - last == 2) {
- if (em) {
- index_lookup[topo_pairs[a - 1].v_index] = (intptr_t)BM_vert_at_index(em->bm, topo_pairs[a - 2].v_index);
- index_lookup[topo_pairs[a - 2].v_index] = (intptr_t)BM_vert_at_index(em->bm, topo_pairs[a - 1].v_index);
- }
- else {
- index_lookup[topo_pairs[a - 1].v_index] = topo_pairs[a - 2].v_index;
- index_lookup[topo_pairs[a - 2].v_index] = topo_pairs[a - 1].v_index;
- }
- }
- last = a;
- }
- }
-
- MEM_freeN(topo_pairs);
- topo_pairs = NULL;
-
- MEM_freeN(topo_hash);
- MEM_freeN(topo_hash_prev);
-
- mesh_topo_store->index_lookup = index_lookup;
- mesh_topo_store->prev_vert_tot = totvert;
- mesh_topo_store->prev_edge_tot = totedge;
-}
-
-void ED_mesh_mirrtopo_free(MirrTopoStore_t *mesh_topo_store)
-{
- if (mesh_topo_store->index_lookup) {
- MEM_freeN(mesh_topo_store->index_lookup);
- }
- mesh_topo_store->index_lookup = NULL;
- mesh_topo_store->prev_vert_tot = -1;
- mesh_topo_store->prev_edge_tot = -1;
-}
diff --git a/source/blender/editors/mesh/editmesh_add.c b/source/blender/editors/mesh/editmesh_add.c
index 3725590c188..22cb28f0b1b 100644
--- a/source/blender/editors/mesh/editmesh_add.c
+++ b/source/blender/editors/mesh/editmesh_add.c
@@ -60,9 +60,10 @@
/* ********* add primitive operators ************* */
-static Object *make_prim_init(bContext *C, const char *idname,
- float *dia, float mat[4][4],
- bool *was_editmode, const float loc[3], const float rot[3], const unsigned int layer)
+static Object *make_prim_init(
+ bContext *C, const char *idname,
+ float *dia, float mat[4][4],
+ bool *was_editmode, const float loc[3], const float rot[3], const unsigned int layer)
{
Object *obedit = CTX_data_edit_object(C);
@@ -233,7 +234,7 @@ static int add_primitive_circle_exec(bContext *C, wmOperator *op)
if (!EDBM_op_call_and_selectf(
em, op, "verts.out", false,
- "create_circle segments=%i diameter=%f cap_ends=%b cap_tris=%b matrix=%m4 calc_uvs=%b",
+ "create_circle segments=%i radius=%f cap_ends=%b cap_tris=%b matrix=%m4 calc_uvs=%b",
RNA_int_get(op->ptr, "vertices"), RNA_float_get(op->ptr, "radius"),
cap_end, cap_tri, mat, calc_uvs))
{
@@ -384,7 +385,7 @@ void MESH_OT_primitive_cone_add(wmOperatorType *ot)
/* props */
RNA_def_int(ot->srna, "vertices", 32, 3, MESH_ADD_VERTS_MAXI, "Vertices", "", 3, 500);
RNA_def_float_distance(ot->srna, "radius1", 1.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Radius 1", "", 0.001, 100.00);
- RNA_def_float_distance(ot->srna, "radius2", 0.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Radius 2", "", 0.001, 100.00);
+ RNA_def_float_distance(ot->srna, "radius2", 0.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Radius 2", "", 0.0, 100.00);
RNA_def_float_distance(ot->srna, "depth", 2.0f, 0.0, OBJECT_ADD_SIZE_MAXF, "Depth", "", 0.001, 100.00);
RNA_def_enum(ot->srna, "end_fill_type", fill_type_items, 1, "Base Fill Type", "");
diff --git a/source/blender/editors/mesh/editmesh_bevel.c b/source/blender/editors/mesh/editmesh_bevel.c
index a81add7a86e..c8d33a9cc60 100644
--- a/source/blender/editors/mesh/editmesh_bevel.c
+++ b/source/blender/editors/mesh/editmesh_bevel.c
@@ -58,8 +58,7 @@
#define MVAL_PIXEL_MARGIN 5.0f
-/* until implement profile = 0 case, need to clamp somewhat above zero */
-#define PROFILE_HARD_MIN 0.15f
+#define PROFILE_HARD_MIN 0.0f
#define SEGMENTS_HARD_MAX 1000
@@ -140,6 +139,10 @@ static bool edbm_bevel_init(bContext *C, wmOperator *op, const bool is_modal)
return false;
}
+ if (is_modal) {
+ RNA_float_set(op->ptr, "offset", 0.0f);
+ }
+
op->customdata = opdata = MEM_mallocN(sizeof(BevelData), "beveldata_mesh_operator");
opdata->em = em;
@@ -150,6 +153,7 @@ static bool edbm_bevel_init(bContext *C, wmOperator *op, const bool is_modal)
for (i = 0; i < NUM_VALUE_KINDS; i++) {
opdata->shift_value[i] = -1.0f;
+ opdata->initial_length[i] = -1.0f;
/* note: scale for OFFSET_VALUE will get overwritten in edbm_bevel_invoke */
opdata->scale[i] = value_scale_per_inch[i] / pixels_per_inch;
@@ -300,7 +304,7 @@ static void edbm_bevel_calc_initial_length(wmOperator *op, const wmEvent *event,
mlen[1] = opdata->mcenter[1] - event->mval[1];
len = len_v2(mlen);
vmode = opdata->value_mode;
- if (mode_changed) {
+ if (mode_changed || opdata->initial_length[vmode] == -1.0f) {
/* If current value is not default start value, adjust len so that
* the scaling and offset in edbm_bevel_mouse_set_value will
* start at current value */
@@ -334,11 +338,12 @@ static int edbm_bevel_invoke(bContext *C, wmOperator *op, const wmEvent *event)
* ideally this will never happen and should be checked for above */
opdata->mcenter[0] = opdata->mcenter[1] = 0;
}
- edbm_bevel_calc_initial_length(op, event, false);
/* for OFFSET_VALUE only, the scale is the size of a pixel under the mouse in 3d space */
opdata->scale[OFFSET_VALUE] = rv3d ? ED_view3d_pixel_size(rv3d, center_3d) : 1.0f;
+ edbm_bevel_calc_initial_length(op, event, false);
+
edbm_bevel_update_header(C, op);
if (!edbm_bevel_calc(op)) {
@@ -506,6 +511,8 @@ static int edbm_bevel_modal(bContext *C, wmOperator *op, const wmEvent *event)
else if (opdata->value_mode == OFFSET_VALUE_PERCENT && type != BEVEL_AMT_PERCENT)
opdata->value_mode = OFFSET_VALUE;
RNA_property_enum_set(op->ptr, prop, type);
+ if (opdata->initial_length[opdata->value_mode] == -1.0f)
+ edbm_bevel_calc_initial_length(op, event, true);
}
/* Update offset accordingly to new offset_type. */
if (!has_numinput &&
@@ -593,7 +600,7 @@ void MESH_OT_bevel(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem offset_type_items[] = {
+ static const EnumPropertyItem offset_type_items[] = {
{BEVEL_AMT_OFFSET, "OFFSET", 0, "Offset", "Amount is offset of new edges from original"},
{BEVEL_AMT_WIDTH, "WIDTH", 0, "Width", "Amount is width of new face"},
{BEVEL_AMT_DEPTH, "DEPTH", 0, "Depth", "Amount is perpendicular distance from original edge to bevel face"},
diff --git a/source/blender/editors/mesh/editmesh_extrude.c b/source/blender/editors/mesh/editmesh_extrude.c
index 0f1badd93cd..78bc361b222 100644
--- a/source/blender/editors/mesh/editmesh_extrude.c
+++ b/source/blender/editors/mesh/editmesh_extrude.c
@@ -36,8 +36,6 @@
#include "BLI_listbase.h"
#include "BKE_context.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
#include "BKE_object.h"
#include "BKE_report.h"
#include "BKE_editmesh.h"
@@ -54,6 +52,10 @@
#include "mesh_intern.h" /* own include */
+/* -------------------------------------------------------------------- */
+/** \name Extrude Internal Utilities
+ * \{ */
+
static void edbm_extrude_edge_exclude_mirror(
Object *obedit, BMEditMesh *em,
const char hflag,
@@ -142,7 +144,7 @@ static bool edbm_extrude_discrete_faces(BMEditMesh *em, wmOperator *op, const ch
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
BMO_op_exec(em->bm, &bmop);
-
+
BMO_ITER (f, &siter, bmop.slots_out, "faces.out", BM_FACE) {
BM_face_select_set(em->bm, f, true);
@@ -242,7 +244,7 @@ static bool edbm_extrude_ex(
BMOIter siter;
BMOperator extop;
BMElem *ele;
-
+
/* needed to remove the faces left behind */
if (htype & BM_FACE) {
htype |= BM_EDGE;
@@ -264,7 +266,7 @@ static bool edbm_extrude_ex(
BM_SELECT_HISTORY_RESTORE(bm);
BMO_op_exec(bm, &extop);
-
+
BMO_ITER (ele, &siter, extop.slots_out, "geom.out", BM_ALL_NOLOOP) {
BM_elem_select_set(bm, ele, true);
}
@@ -274,14 +276,20 @@ static bool edbm_extrude_ex(
return true;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Extrude Repeat Operator
+ * \{ */
+
static int edbm_extrude_repeat_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
-
+
const int steps = RNA_int_get(op->ptr, "steps");
-
+
const float offs = RNA_float_get(op->ptr, "offset");
float dvec[3], tmat[3][3], bmat[3][3];
short a;
@@ -302,7 +310,7 @@ static int edbm_extrude_repeat_exec(bContext *C, wmOperator *op)
"translate vec=%v verts=%hv",
dvec, BM_ELEM_SELECT);
}
-
+
EDBM_mesh_normals_update(em);
EDBM_update_generic(em, true, true);
@@ -316,19 +324,25 @@ void MESH_OT_extrude_repeat(wmOperatorType *ot)
ot->name = "Extrude Repeat Mesh";
ot->description = "Extrude selected vertices, edges or faces repeatedly";
ot->idname = "MESH_OT_extrude_repeat";
-
+
/* api callbacks */
ot->exec = edbm_extrude_repeat_exec;
ot->poll = ED_operator_editmesh_view3d;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_float_distance(ot->srna, "offset", 2.0f, 0.0f, 1e12f, "Offset", "", 0.0f, 100.0f);
RNA_def_int(ot->srna, "steps", 10, 0, 1000000, "Steps", "", 0, 180);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Extrude Operator
+ * \{ */
+
/* generic extern called extruder */
static bool edbm_extrude_mesh(Object *obedit, BMEditMesh *em, wmOperator *op)
{
@@ -365,7 +379,7 @@ static bool edbm_extrude_mesh(Object *obedit, BMEditMesh *em, wmOperator *op)
changed = edbm_extrude_edges_indiv(em, op, BM_ELEM_SELECT);
break;
}
-
+
if (changed) {
return true;
}
@@ -380,7 +394,7 @@ static int edbm_extrude_region_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
+
edbm_extrude_mesh(obedit, em, op);
/* This normally happens when pushing undo but modal operators
@@ -389,7 +403,7 @@ static int edbm_extrude_region_exec(bContext *C, wmOperator *op)
EDBM_mesh_normals_update(em);
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -399,27 +413,33 @@ void MESH_OT_extrude_region(wmOperatorType *ot)
ot->name = "Extrude Region";
ot->idname = "MESH_OT_extrude_region";
ot->description = "Extrude region of faces";
-
+
/* api callbacks */
//ot->invoke = mesh_extrude_region_invoke;
ot->exec = edbm_extrude_region_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
Transform_Properties(ot, P_NO_DEFAULTS | P_MIRROR_DUMMY);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Extrude Verts Operator
+ * \{ */
+
static int edbm_extrude_verts_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
edbm_extrude_verts_indiv(em, op, BM_ELEM_SELECT);
-
+
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -429,11 +449,11 @@ void MESH_OT_extrude_verts_indiv(wmOperatorType *ot)
ot->name = "Extrude Only Vertices";
ot->idname = "MESH_OT_extrude_verts_indiv";
ot->description = "Extrude individual vertices only";
-
+
/* api callbacks */
ot->exec = edbm_extrude_verts_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -441,15 +461,21 @@ void MESH_OT_extrude_verts_indiv(wmOperatorType *ot)
Transform_Properties(ot, P_NO_DEFAULTS | P_MIRROR_DUMMY);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Extrude Edges Operator
+ * \{ */
+
static int edbm_extrude_edges_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
edbm_extrude_edges_indiv(em, op, BM_ELEM_SELECT);
-
+
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -459,11 +485,11 @@ void MESH_OT_extrude_edges_indiv(wmOperatorType *ot)
ot->name = "Extrude Only Edges";
ot->idname = "MESH_OT_extrude_edges_indiv";
ot->description = "Extrude individual edges only";
-
+
/* api callbacks */
ot->exec = edbm_extrude_edges_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -471,15 +497,21 @@ void MESH_OT_extrude_edges_indiv(wmOperatorType *ot)
Transform_Properties(ot, P_NO_DEFAULTS | P_MIRROR_DUMMY);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Extrude Faces Operator
+ * \{ */
+
static int edbm_extrude_faces_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
edbm_extrude_discrete_faces(em, op, BM_ELEM_SELECT);
-
+
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -489,57 +521,70 @@ void MESH_OT_extrude_faces_indiv(wmOperatorType *ot)
ot->name = "Extrude Individual Faces";
ot->idname = "MESH_OT_extrude_faces_indiv";
ot->description = "Extrude individual faces only";
-
+
/* api callbacks */
ot->exec = edbm_extrude_faces_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
Transform_Properties(ot, P_NO_DEFAULTS | P_MIRROR_DUMMY);
}
-/* *************** add-click-mesh (extrude) operator ************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Dupli-Extrude Operator
+ *
+ * Add-click-mesh (extrude) operator.
+ * \{ */
+
static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
ViewContext vc;
BMVert *v1;
BMIter iter;
- float min[3], max[3];
- bool done = false;
+ float center[3];
+ uint verts_len;
bool use_proj;
em_setup_viewcontext(C, &vc);
+ invert_m4_m4(vc.obedit->imat, vc.obedit->obmat);
+
ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
use_proj = ((vc.scene->toolsettings->snap_flag & SCE_SNAP) &&
(vc.scene->toolsettings->snap_mode == SCE_SNAP_MODE_FACE));
- INIT_MINMAX(min, max);
-
+ zero_v3(center);
+ verts_len = 0;
+
BM_ITER_MESH (v1, &iter, vc.em->bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(v1, BM_ELEM_SELECT)) {
- minmax_v3v3_v3(min, max, v1->co);
- done = true;
+ add_v3_v3(center, v1->co);
+ verts_len += 1;
}
}
/* call extrude? */
- if (done) {
+ if (verts_len != 0) {
const char extrude_htype = edbm_extrude_htype_from_em_select(vc.em);
const bool rot_src = RNA_boolean_get(op->ptr, "rotate_source");
BMEdge *eed;
- float vec[3], cent[3], mat[3][3];
+ float mat[3][3];
+ float vec[3], ofs[3];
float nor[3] = {0.0, 0.0, 0.0};
/* 2D normal calc */
const float mval_f[2] = {(float)event->mval[0],
(float)event->mval[1]};
+ mul_v3_fl(center, 1.0f / (float)verts_len);
+
/* check for edges that are half selected, use for rotation */
- done = false;
+ bool done = false;
BM_ITER_MESH (eed, &iter, vc.em->bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
float co1[2], co2[2];
@@ -578,23 +623,22 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const w
cross_v3_v3v3(nor, view_vec, cross);
normalize_v3(nor);
}
-
+
/* center */
- mid_v3_v3v3(cent, min, max);
- copy_v3_v3(min, cent);
+ copy_v3_v3(ofs, center);
- mul_m4_v3(vc.obedit->obmat, min); /* view space */
- ED_view3d_win_to_3d_int(vc.v3d, vc.ar, min, event->mval, min);
- mul_m4_v3(vc.obedit->imat, min); // back in object space
+ mul_m4_v3(vc.obedit->obmat, ofs); /* view space */
+ ED_view3d_win_to_3d_int(vc.v3d, vc.ar, ofs, event->mval, ofs);
+ mul_m4_v3(vc.obedit->imat, ofs); // back in object space
+
+ sub_v3_v3(ofs, center);
- sub_v3_v3(min, cent);
-
/* calculate rotation */
unit_m3(mat);
if (done) {
float angle;
- normalize_v3_v3(vec, min);
+ normalize_v3_v3(vec, ofs);
angle = angle_normalized_v3v3(vec, nor);
@@ -611,10 +655,10 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const w
axis_angle_to_mat3(mat, axis, angle);
}
}
-
+
if (rot_src) {
EDBM_op_callf(vc.em, op, "rotate verts=%hv cent=%v matrix=%m3",
- BM_ELEM_SELECT, cent, mat);
+ BM_ELEM_SELECT, center, mat);
/* also project the source, for retopo workflow */
if (use_proj)
@@ -623,22 +667,21 @@ static int edbm_dupli_extrude_cursor_invoke(bContext *C, wmOperator *op, const w
edbm_extrude_ex(vc.obedit, vc.em, extrude_htype, BM_ELEM_SELECT, true, true);
EDBM_op_callf(vc.em, op, "rotate verts=%hv cent=%v matrix=%m3",
- BM_ELEM_SELECT, cent, mat);
+ BM_ELEM_SELECT, center, mat);
EDBM_op_callf(vc.em, op, "translate verts=%hv vec=%v",
- BM_ELEM_SELECT, min);
+ BM_ELEM_SELECT, ofs);
}
else {
- const float *curs = ED_view3d_cursor3d_get(vc.scene, vc.v3d);
+ const float *cursor = ED_view3d_cursor3d_get(vc.scene, vc.v3d);
BMOperator bmop;
BMOIter oiter;
-
- copy_v3_v3(min, curs);
- ED_view3d_win_to_3d_int(vc.v3d, vc.ar, min, event->mval, min);
-
- invert_m4_m4(vc.obedit->imat, vc.obedit->obmat);
- mul_m4_v3(vc.obedit->imat, min); // back in object space
-
- EDBM_op_init(vc.em, &bmop, op, "create_vert co=%v", min);
+
+ copy_v3_v3(center, cursor);
+ ED_view3d_win_to_3d_int(vc.v3d, vc.ar, center, event->mval, center);
+
+ mul_m4_v3(vc.obedit->imat, center); // back in object space
+
+ EDBM_op_init(vc.em, &bmop, op, "create_vert co=%v", center);
BMO_op_exec(vc.em->bm, &bmop);
BMO_ITER (v1, &oiter, bmop.slots_out, "vert.out", BM_VERT) {
@@ -669,17 +712,22 @@ void MESH_OT_dupli_extrude_cursor(wmOperatorType *ot)
ot->name = "Duplicate or Extrude to Cursor";
ot->idname = "MESH_OT_dupli_extrude_cursor";
ot->description = "Duplicate and extrude selected vertices, edges or faces towards the mouse cursor";
-
+
/* api callbacks */
ot->invoke = edbm_dupli_extrude_cursor_invoke;
ot->poll = ED_operator_editmesh_region_view3d;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
RNA_def_boolean(ot->srna, "rotate_source", true, "Rotate Source", "Rotate initial selection giving better shape");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Spin Operator
+ * \{ */
static int edbm_spin_exec(bContext *C, wmOperator *op)
{
@@ -776,6 +824,12 @@ void MESH_OT_spin(wmOperatorType *ot)
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Screw Operator
+ * \{ */
+
static int edbm_screw_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -906,3 +960,5 @@ void MESH_OT_screw(wmOperatorType *ot)
RNA_def_float_vector(ot->srna, "axis", 3, NULL, -1.0f, 1.0f,
"Axis", "Axis in global view space", -1.0f, 1.0f);
}
+
+/** \} */
diff --git a/source/blender/editors/mesh/editmesh_inset.c b/source/blender/editors/mesh/editmesh_inset.c
index 3e0747f055f..3833b84b5d2 100644
--- a/source/blender/editors/mesh/editmesh_inset.c
+++ b/source/blender/editors/mesh/editmesh_inset.c
@@ -80,8 +80,10 @@ static void edbm_inset_update_header(wmOperator *op, bContext *C)
{
InsetData *opdata = op->customdata;
- const char *str = IFACE_("Confirm: Enter/LClick, Cancel: (Esc/RClick), Thickness: %s, "
- "Depth (Ctrl to tweak): %s (%s), Outset (O): (%s), Boundary (B): (%s), Individual (I): (%s)");
+ const char *str = IFACE_(
+ "Confirm: Enter/LClick, Cancel: (Esc/RClick), Thickness: %s, "
+ "Depth (Ctrl to tweak): %s (%s), Outset (O): (%s), Boundary (B): (%s), Individual (I): (%s)"
+ );
char msg[UI_MAX_DRAW_STR];
ScrArea *sa = CTX_wm_area(C);
@@ -120,6 +122,11 @@ static bool edbm_inset_init(bContext *C, wmOperator *op, const bool is_modal)
return false;
}
+ if (is_modal) {
+ RNA_float_set(op->ptr, "thickness", 0.01f);
+ RNA_float_set(op->ptr, "depth", 0.0f);
+ }
+
op->customdata = opdata = MEM_mallocN(sizeof(InsetData), "inset_operator_data");
opdata->old_thickness = 0.01;
@@ -141,7 +148,8 @@ static bool edbm_inset_init(bContext *C, wmOperator *op, const bool is_modal)
ARegion *ar = CTX_wm_region(C);
opdata->mesh_backup = EDBM_redo_state_store(em);
- opdata->draw_handle_pixel = ED_region_draw_cb_activate(ar->type, ED_region_draw_mouse_line_cb, opdata->mcenter, REGION_DRAW_POST_PIXEL);
+ opdata->draw_handle_pixel = ED_region_draw_cb_activate(
+ ar->type, ED_region_draw_mouse_line_cb, opdata->mcenter, REGION_DRAW_POST_PIXEL);
G.moving = G_TRANSFORM_EDIT;
if (v3d) {
opdata->twtype = v3d->twtype;
@@ -370,10 +378,12 @@ static int edbm_inset_modal(bContext *C, wmOperator *op, const wmEvent *event)
case LEFTMOUSE:
case PADENTER:
case RETKEY:
- edbm_inset_calc(op);
- edbm_inset_exit(C, op);
- return OPERATOR_FINISHED;
-
+ if (event->val == KM_PRESS) {
+ edbm_inset_calc(op);
+ edbm_inset_exit(C, op);
+ return OPERATOR_FINISHED;
+ }
+ break;
case LEFTSHIFTKEY:
case RIGHTSHIFTKEY:
if (event->val == KM_PRESS) {
@@ -506,14 +516,23 @@ void MESH_OT_inset(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_GRAB_CURSOR | OPTYPE_BLOCKING;
/* properties */
- RNA_def_boolean(ot->srna, "use_boundary", true, "Boundary", "Inset face boundaries");
- RNA_def_boolean(ot->srna, "use_even_offset", true, "Offset Even", "Scale the offset to give more even thickness");
- RNA_def_boolean(ot->srna, "use_relative_offset", false, "Offset Relative", "Scale the offset by surrounding geometry");
- RNA_def_boolean(ot->srna, "use_edge_rail", false, "Edge Rail", "Inset the region along existing edges");
+ RNA_def_boolean(
+ ot->srna, "use_boundary",
+ true, "Boundary", "Inset face boundaries");
+ RNA_def_boolean(
+ ot->srna, "use_even_offset",
+ true, "Offset Even", "Scale the offset to give more even thickness");
+ RNA_def_boolean(
+ ot->srna, "use_relative_offset",
+ false, "Offset Relative", "Scale the offset by surrounding geometry");
+ RNA_def_boolean(
+ ot->srna, "use_edge_rail",
+ false, "Edge Rail", "Inset the region along existing edges");
prop = RNA_def_float_distance(ot->srna, "thickness", 0.01f, 0.0f, 1e12f, "Thickness", "", 0.0f, 10.0f);
/* use 1 rather then 10 for max else dragging the button moves too far */
RNA_def_property_ui_range(prop, 0.0, 1.0, 0.01, 4);
+
prop = RNA_def_float_distance(ot->srna, "depth", 0.0f, -1e12f, 1e12f, "Depth", "", -10.0f, 10.0f);
RNA_def_property_ui_range(prop, -10.0f, 10.0f, 0.01, 4);
diff --git a/source/blender/editors/mesh/editmesh_intersect.c b/source/blender/editors/mesh/editmesh_intersect.c
index de93211bec4..d681d904e74 100644
--- a/source/blender/editors/mesh/editmesh_intersect.c
+++ b/source/blender/editors/mesh/editmesh_intersect.c
@@ -51,6 +51,7 @@
#include "mesh_intern.h" /* own include */
#include "tools/bmesh_intersect.h"
+#include "tools/bmesh_separate.h"
/* detect isolated holes and fill them */
@@ -137,6 +138,12 @@ enum {
ISECT_SEL_UNSEL = 1,
};
+enum {
+ ISECT_SEPARATE_ALL = 0,
+ ISECT_SEPARATE_CUT = 1,
+ ISECT_SEPARATE_NONE = 2,
+};
+
static int edbm_intersect_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -144,7 +151,9 @@ static int edbm_intersect_exec(bContext *C, wmOperator *op)
BMesh *bm = em->bm;
const int mode = RNA_enum_get(op->ptr, "mode");
int (*test_fn)(BMFace *, void *);
- bool use_separate = RNA_boolean_get(op->ptr, "use_separate");
+ bool use_separate_all = false;
+ bool use_separate_cut = false;
+ const int separate_mode = RNA_enum_get(op->ptr, "separate_mode");
const float eps = RNA_float_get(op->ptr, "threshold");
bool use_self;
bool has_isect;
@@ -160,15 +169,38 @@ static int edbm_intersect_exec(bContext *C, wmOperator *op)
break;
}
+ switch (separate_mode) {
+ case ISECT_SEPARATE_ALL:
+ use_separate_all = true;
+ break;
+ case ISECT_SEPARATE_CUT:
+ if (use_self == false) {
+ use_separate_cut = true;
+ }
+ else {
+ /* we could support this but would require more advanced logic inside 'BM_mesh_intersect'
+ * for now just separate all */
+ use_separate_all = true;
+ }
+ break;
+ default: /* ISECT_SEPARATE_NONE */
+ break;
+ }
has_isect = BM_mesh_intersect(
bm,
em->looptris, em->tottri,
test_fn, NULL,
- use_self, use_separate, true, true,
+ use_self, use_separate_all, true, true, true,
-1,
eps);
+ if (use_separate_cut) {
+ /* detach selected/un-selected faces */
+ BM_mesh_separate_faces(
+ bm,
+ BM_elem_cb_check_hflag_enabled_simple(const BMFace *, BM_ELEM_SELECT));
+ }
if (has_isect) {
edbm_intersect_select(em);
@@ -182,7 +214,7 @@ static int edbm_intersect_exec(bContext *C, wmOperator *op)
void MESH_OT_intersect(struct wmOperatorType *ot)
{
- static EnumPropertyItem isect_mode_items[] = {
+ static const EnumPropertyItem isect_mode_items[] = {
{ISECT_SEL, "SELECT", 0, "Self Intersect",
"Self intersect selected faces"},
{ISECT_SEL_UNSEL, "SELECT_UNSELECT", 0, "Selected/Unselected",
@@ -190,6 +222,16 @@ void MESH_OT_intersect(struct wmOperatorType *ot)
{0, NULL, 0, NULL, NULL}
};
+ static const EnumPropertyItem isect_separate_items[] = {
+ {ISECT_SEPARATE_ALL, "ALL", 0, "All",
+ "Separate all geometry from intersections"},
+ {ISECT_SEPARATE_CUT, "CUT", 0, "Cut",
+ "Cut into geometry keeping each side separate (Selected/Unselected only)"},
+ {ISECT_SEPARATE_NONE, "NONE", 0, "Merge",
+ "Merge all geometry from the intersection"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
/* identifiers */
ot->name = "Intersect (Knife)";
ot->description = "Cut an intersection into faces";
@@ -201,7 +243,7 @@ void MESH_OT_intersect(struct wmOperatorType *ot)
/* props */
RNA_def_enum(ot->srna, "mode", isect_mode_items, ISECT_SEL_UNSEL, "Source", "");
- RNA_def_boolean(ot->srna, "use_separate", true, "Separate", "");
+ RNA_def_enum(ot->srna, "separate_mode", isect_separate_items, ISECT_SEPARATE_CUT, "Separate Mode", "");
RNA_def_float_distance(ot->srna, "threshold", 0.000001f, 0.0, 0.01, "Merge threshold", "", 0.0, 0.001);
/* flags */
@@ -239,7 +281,7 @@ static int edbm_intersect_boolean_exec(bContext *C, wmOperator *op)
bm,
em->looptris, em->tottri,
test_fn, NULL,
- false, false, true, true,
+ false, false, true, true, true,
boolean_operation,
eps);
@@ -256,7 +298,7 @@ static int edbm_intersect_boolean_exec(bContext *C, wmOperator *op)
void MESH_OT_intersect_boolean(struct wmOperatorType *ot)
{
- static EnumPropertyItem isect_boolean_operation_items[] = {
+ static const EnumPropertyItem isect_boolean_operation_items[] = {
{BMESH_ISECT_BOOLEAN_ISECT, "INTERSECT", 0, "Intersect", ""},
{BMESH_ISECT_BOOLEAN_UNION, "UNION", 0, "Union", ""},
{BMESH_ISECT_BOOLEAN_DIFFERENCE, "DIFFERENCE", 0, "Difference", ""},
@@ -358,7 +400,7 @@ static void bm_face_split_by_edges(
bm, f, edge_net_temp_buf->data, edge_net_temp_buf->count,
&face_arr, &face_arr_len);
- BLI_buffer_empty(edge_net_temp_buf);
+ BLI_buffer_clear(edge_net_temp_buf);
if (face_arr_len) {
int i;
diff --git a/source/blender/editors/mesh/editmesh_knife.c b/source/blender/editors/mesh/editmesh_knife.c
index bf59693b856..053e932fe75 100644
--- a/source/blender/editors/mesh/editmesh_knife.c
+++ b/source/blender/editors/mesh/editmesh_knife.c
@@ -271,6 +271,8 @@ static bool knife_verts_edge_in_face(KnifeVert *v1, KnifeVert *v2, BMFace *f);
static void knifetool_free_bmbvh(KnifeTool_OpData *kcd);
+static int knifetool_modal(bContext *C, wmOperator *op, const wmEvent *event);
+
static void knife_update_header(bContext *C, wmOperator *op, KnifeTool_OpData *kcd)
{
char header[UI_MAX_DRAW_STR];
@@ -855,7 +857,7 @@ static void knife_cut_face(KnifeTool_OpData *kcd, BMFace *f, ListBase *hits)
{
Ref *r;
- if (BLI_listbase_count_ex(hits, 2) != 2)
+ if (BLI_listbase_count_at_most(hits, 2) != 2)
return;
for (r = hits->first; r->next; r = r->next) {
@@ -1206,6 +1208,7 @@ static bool knife_ray_intersect_face(
for (; tri_i < tottri; tri_i++) {
const float *lv1, *lv2, *lv3;
+ float ray_tri_uv[2];
tri = kcd->em->looptris[tri_i];
if (tri[0]->f != f)
@@ -1217,7 +1220,7 @@ static bool knife_ray_intersect_face(
* tesselation edge and might not hit either tesselation tri with
* an exact test;
* we will exclude hits near real edges by a later test */
- if (isect_ray_tri_epsilon_v3(v1, raydir, lv1, lv2, lv3, &lambda, NULL, KNIFE_FLT_EPS)) {
+ if (isect_ray_tri_epsilon_v3(v1, raydir, lv1, lv2, lv3, &lambda, ray_tri_uv, KNIFE_FLT_EPS)) {
/* check if line coplanar with tri */
normal_tri_v3(tri_norm, lv1, lv2, lv3);
plane_from_point_normal_v3(tri_plane, lv1, tri_norm);
@@ -1226,8 +1229,7 @@ static bool knife_ray_intersect_face(
{
return false;
}
- copy_v3_v3(hit_cageco, v1);
- madd_v3_v3fl(hit_cageco, raydir, lambda);
+ interp_v3_v3v3v3_uv(hit_cageco, lv1, lv2, lv3, ray_tri_uv);
/* Now check that far enough away from verts and edges */
lst = knife_get_face_kedges(kcd, f);
for (ref = lst->first; ref; ref = ref->next) {
@@ -1239,11 +1241,7 @@ static bool knife_ray_intersect_face(
return false;
}
}
-
- transform_point_by_tri_v3(
- hit_co, hit_cageco,
- tri[0]->v->co, tri[1]->v->co, tri[2]->v->co,
- lv1, lv2, lv3);
+ interp_v3_v3v3v3_uv(hit_co, tri[0]->v->co, tri[1]->v->co, tri[2]->v->co, ray_tri_uv);
return true;
}
}
@@ -1472,7 +1470,7 @@ static void clip_to_ortho_planes(float v1[3], float v2[3], const float center[3]
/* could be v1 or v2 */
sub_v3_v3(v1, center);
- project_plane_v3_v3v3(closest, v1, dir);
+ project_plane_normalized_v3_v3v3(closest, v1, dir);
add_v3_v3(closest, center);
madd_v3_v3v3fl(v1, closest, dir, d);
@@ -1764,7 +1762,7 @@ static void knife_find_line_hits(KnifeTool_OpData *kcd)
}
kcd->linehits = linehits;
- kcd->totlinehit = BLI_array_count(linehits);
+ kcd->totlinehit = BLI_array_len(linehits);
/* find position along screen line, used for sorting */
for (i = 0; i < kcd->totlinehit; i++) {
@@ -1947,7 +1945,7 @@ static KnifeEdge *knife_find_closest_edge(KnifeTool_OpData *kcd, float p[3], flo
/* check if we're close enough and calculate 'lambda' */
if (kcd->is_angle_snapping) {
- /* if snapping, check we're in bounds */
+ /* if snapping, check we're in bounds */
float sco_snap[2];
isect_line_line_v2_point(kfe->v1->sco, kfe->v2->sco, kcd->prev.mval, kcd->curr.mval, sco_snap);
lambda = line_point_factor_v2(sco_snap, kfe->v1->sco, kfe->v2->sco);
@@ -2286,7 +2284,7 @@ static void knife_make_face_cuts(KnifeTool_OpData *kcd, BMFace *f, ListBase *kfe
/* point to knife edges we've created edges in, edge_array aligned */
KnifeEdge **kfe_array = BLI_array_alloca(kfe_array, edge_array_len);
- BLI_assert(BLI_gset_size(kcd->edgenet.edge_visit) == 0);
+ BLI_assert(BLI_gset_len(kcd->edgenet.edge_visit) == 0);
i = 0;
for (ref = kfedges->first; ref; ref = ref->next) {
@@ -2666,6 +2664,7 @@ static int knifetool_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
const bool only_select = RNA_boolean_get(op->ptr, "only_selected");
const bool cut_through = !RNA_boolean_get(op->ptr, "use_occlude_geometry");
+ const bool wait_for_input = RNA_boolean_get(op->ptr, "wait_for_input");
KnifeTool_OpData *kcd;
@@ -2693,6 +2692,18 @@ static int knifetool_invoke(bContext *C, wmOperator *op, const wmEvent *event)
knifetool_update_mval_i(kcd, event->mval);
+ if (wait_for_input == false) {
+ /* Avoid copy-paste logic. */
+ wmEvent event_modal = {
+ .prevval = KM_NOTHING,
+ .type = EVT_MODAL_MAP,
+ .val = KNF_MODAL_ADD_CUT,
+ };
+ int ret = knifetool_modal(C, op, &event_modal);
+ BLI_assert(ret == OPERATOR_RUNNING_MODAL);
+ UNUSED_VARS_NDEBUG(ret);
+ }
+
knife_update_header(C, op, kcd);
return OPERATOR_RUNNING_MODAL;
@@ -2700,7 +2711,7 @@ static int knifetool_invoke(bContext *C, wmOperator *op, const wmEvent *event)
wmKeyMap *knifetool_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{KNF_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{KNF_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
{KNF_MODAL_MIDPOINT_ON, "SNAP_MIDPOINTS_ON", 0, "Snap To Midpoints On", ""},
@@ -2959,8 +2970,13 @@ void MESH_OT_knife_tool(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
+ /* properties */
+ PropertyRNA *prop;
RNA_def_boolean(ot->srna, "use_occlude_geometry", true, "Occlude Geometry", "Only cut the front most geometry");
RNA_def_boolean(ot->srna, "only_selected", false, "Only Selected", "Only cut selected geometry");
+
+ prop = RNA_def_boolean(ot->srna, "wait_for_input", true, "Wait for Input", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
diff --git a/source/blender/editors/mesh/editmesh_loopcut.c b/source/blender/editors/mesh/editmesh_loopcut.c
index f1c1e4105d0..5d4f6242e4f 100644
--- a/source/blender/editors/mesh/editmesh_loopcut.c
+++ b/source/blender/editors/mesh/editmesh_loopcut.c
@@ -517,9 +517,6 @@ static int ringsel_init(bContext *C, wmOperator *op, bool do_cut)
lcd->num.unit_type[0] = B_UNIT_NONE;
lcd->num.unit_type[1] = B_UNIT_NONE;
- /* XXX, temp, workaround for [# ] */
- EDBM_mesh_ensure_valid_dm_hack(scene, lcd->em);
-
em_setup_viewcontext(C, &lcd->vc);
ED_region_tag_redraw(lcd->ar);
@@ -743,7 +740,15 @@ static int loopcut_modal(bContext *C, wmOperator *op, const wmEvent *event)
handled = true;
break;
case MOUSEMOVE: /* mouse moved somewhere to select another loop */
- if (!has_numinput) {
+
+ /* This is normally disabled for all modal operators.
+ * This is an exception since mouse movement doesn't relate to numeric input.
+ *
+ * If numeric input changes we'll need to add this back see: D2973 */
+#if 0
+ if (!has_numinput)
+#endif
+ {
lcd->vc.mval[0] = event->mval[0];
lcd->vc.mval[1] = event->mval[1];
loopcut_mouse_move(lcd, (int)lcd->cuts);
diff --git a/source/blender/editors/mesh/editmesh_path.c b/source/blender/editors/mesh/editmesh_path.c
index 4431712e720..bf5a7e3a053 100644
--- a/source/blender/editors/mesh/editmesh_path.c
+++ b/source/blender/editors/mesh/editmesh_path.c
@@ -61,6 +61,10 @@
#include "mesh_intern.h" /* own include */
+/* -------------------------------------------------------------------- */
+/** \name Path Select Struct & Properties
+ * \{ */
+
struct PathSelectParams {
bool track_active; /* ensure the active element is the last selected item (handy for picking) */
bool use_topology_distance;
@@ -100,8 +104,11 @@ struct UserData {
const struct PathSelectParams *op_params;
};
+/** \} */
+
/* -------------------------------------------------------------------- */
-/* Vert Path */
+/** \name Vert Path
+ * \{ */
/* callbacks */
static bool verttag_filter_cb(BMVert *v, void *UNUSED(user_data_v))
@@ -204,10 +211,11 @@ static void mouse_mesh_shortest_path_vert(
EDBM_update_generic(em, false, false);
}
-
+/** \} */
/* -------------------------------------------------------------------- */
-/* Edge Path */
+/** \name Edge Path
+ * \{ */
/* callbacks */
static bool edgetag_filter_cb(BMEdge *e, void *UNUSED(user_data_v))
@@ -427,10 +435,11 @@ static void mouse_mesh_shortest_path_edge(
EDBM_update_generic(em, false, false);
}
-
+/** \} */
/* -------------------------------------------------------------------- */
-/* Face Path */
+/** \name Face Path
+ * \{ */
/* callbacks */
static bool facetag_filter_cb(BMFace *f, void *UNUSED(user_data_v))
@@ -478,7 +487,6 @@ static void mouse_mesh_shortest_path_face(
facetag_filter_cb, &user_data);
}
-
if (f_act != f_dst) {
if (path) {
if (op_params->track_active) {
@@ -539,10 +547,11 @@ static void mouse_mesh_shortest_path_face(
EDBM_update_generic(em, false, false);
}
-
+/** \} */
/* -------------------------------------------------------------------- */
-/* Main Operator for vert/edge/face tag */
+/** \name Main Operator for vert/edge/face tag
+ * \{ */
static bool edbm_shortest_path_pick_ex(
Scene *scene, const struct PathSelectParams *op_params,
@@ -709,9 +718,11 @@ void MESH_OT_shortest_path_pick(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
+/** \} */
/* -------------------------------------------------------------------- */
-/* Select path between existing selection */
+/** \name Select Path Between Existing Selection
+ * \{ */
static int edbm_shortest_path_select_exec(bContext *C, wmOperator *op)
{
@@ -784,7 +795,7 @@ void MESH_OT_shortest_path_select(wmOperatorType *ot)
/* identifiers */
ot->name = "Select Shortest Path";
ot->idname = "MESH_OT_shortest_path_select";
- ot->description = "Selected vertex path between two vertices";
+ ot->description = "Selected shortest path between two vertices/edges/faces";
/* api callbacks */
ot->exec = edbm_shortest_path_select_exec;
@@ -796,3 +807,5 @@ void MESH_OT_shortest_path_select(wmOperatorType *ot)
/* properties */
path_select_properties(ot);
}
+
+/** \} */
diff --git a/source/blender/editors/mesh/editmesh_rip.c b/source/blender/editors/mesh/editmesh_rip.c
index e05ce727e22..0c8bd560bb2 100644
--- a/source/blender/editors/mesh/editmesh_rip.c
+++ b/source/blender/editors/mesh/editmesh_rip.c
@@ -590,13 +590,13 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, const wmEvent *eve
}
}
- if (e_best && (is_manifold_region == false)) {
+ if (e_best && e_best->l && (is_manifold_region == false)) {
/* Try to split off a non-manifold fan (when we have multiple disconnected fans) */
BMLoop *l_sep = e_best->l->v == v ? e_best->l : e_best->l->next;
BMVert *v_new;
BLI_assert(l_sep->v == v);
- v_new = bmesh_urmv_loop_region(bm, l_sep);
+ v_new = BM_face_loop_separate_multi_isolated(bm, l_sep);
BLI_assert(BM_vert_find_first_loop(v));
BM_vert_select_set(bm, v, false);
@@ -665,7 +665,7 @@ static int edbm_rip_invoke__vert(bContext *C, wmOperator *op, const wmEvent *eve
BM_vert_select_set(bm, v, false);
- bmesh_vert_separate(bm, v, &vout, &vout_len, true);
+ bmesh_kernel_vert_separate(bm, v, &vout, &vout_len, true);
if (vout_len < 2) {
MEM_freeN(vout);
diff --git a/source/blender/editors/mesh/editmesh_select.c b/source/blender/editors/mesh/editmesh_select.c
index a6de1b284b7..019aa6d4201 100644
--- a/source/blender/editors/mesh/editmesh_select.c
+++ b/source/blender/editors/mesh/editmesh_select.c
@@ -73,7 +73,9 @@
/* use bmesh operator flags for a few operators */
#define BMO_ELE_TAG 1
-/* ****************************** MIRROR **************** */
+/* -------------------------------------------------------------------- */
+/** \name Select Mirror
+ * \{ */
void EDBM_select_mirrored(
BMEditMesh *em, const int axis, const bool extend,
@@ -166,21 +168,34 @@ void EDBM_select_mirrored(
*r_totfail = totfail;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Auto-Merge
+ *
+ * Used after transform operations.
+ * \{ */
+
void EDBM_automerge(Scene *scene, Object *obedit, bool update, const char hflag)
{
bool ok;
BMEditMesh *em = BKE_editmesh_from_object(obedit);
- ok = BMO_op_callf(em->bm, BMO_FLAG_DEFAULTS,
- "automerge verts=%hv dist=%f",
- hflag, scene->toolsettings->doublimit);
+ ok = BMO_op_callf(
+ em->bm, BMO_FLAG_DEFAULTS,
+ "automerge verts=%hv dist=%f",
+ hflag, scene->toolsettings->doublimit);
if (LIKELY(ok) && update) {
EDBM_update_generic(em, true, true);
}
}
-/* ****************************** SELECTION ROUTINES **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Back-Buffer OpenGL Selection
+ * \{ */
unsigned int bm_solidoffs = 0, bm_wireoffs = 0, bm_vertoffs = 0; /* set in drawobject.c ... for colorindices */
@@ -199,21 +214,21 @@ bool EDBM_backbuf_border_init(ViewContext *vc, short xmin, short ymin, short xma
struct ImBuf *buf;
unsigned int *dr;
int a;
-
+
if (vc->obedit == NULL || !V3D_IS_ZBUF(vc->v3d)) {
return false;
}
-
+
buf = ED_view3d_backbuf_read(vc, xmin, ymin, xmax, ymax);
if ((buf == NULL) || (bm_vertoffs == 0)) {
return false;
}
dr = buf->rect;
-
+
/* build selection lookup */
selbuf = edbm_backbuf_alloc(bm_vertoffs + 1);
-
+
a = (xmax - xmin + 1) * (ymax - ymin + 1);
while (a--) {
if (*dr > 0 && *dr <= bm_vertoffs) {
@@ -263,9 +278,9 @@ static void edbm_mask_lasso_px_cb(int x, int x_end, int y, void *user_data)
/* mcords is a polygon mask
* - grab backbuffer,
- * - draw with black in backbuffer,
+ * - draw with black in backbuffer,
* - grab again and compare
- * returns 'OK'
+ * returns 'OK'
*/
bool EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short tot, short xmin, short ymin, short xmax, short ymax)
{
@@ -273,7 +288,7 @@ bool EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short
struct ImBuf *buf;
int a;
struct LassoMaskData lasso_mask_data;
-
+
/* method in use for face selecting too */
if (vc->obedit == NULL) {
if (!BKE_paint_select_elem_test(vc->obact)) {
@@ -302,7 +317,7 @@ bool EDBM_backbuf_border_mask_init(ViewContext *vc, const int mcords[][2], short
/* build selection lookup */
selbuf = edbm_backbuf_alloc(bm_vertoffs + 1);
-
+
a = (xmax - xmin + 1) * (ymax - ymin + 1);
while (a--) {
if (*dr > 0 && *dr <= bm_vertoffs && *dr_mask == true) {
@@ -323,7 +338,7 @@ bool EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
unsigned int *dr;
short xmin, ymin, xmax, ymax, xc, yc;
int radsq;
-
+
/* method in use for face selecting too */
if (vc->obedit == NULL) {
if (!BKE_paint_select_elem_test(vc->obact)) {
@@ -342,7 +357,7 @@ bool EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
}
dr = buf->rect;
-
+
/* build selection lookup */
selbuf = edbm_backbuf_alloc(bm_vertoffs + 1);
radsq = rads * rads;
@@ -358,12 +373,12 @@ bool EDBM_backbuf_circle_init(ViewContext *vc, short xs, short ys, short rads)
IMB_freeImBuf(buf);
return true;
-
+
}
+/** \} */
/* -------------------------------------------------------------------- */
-
/** \name Find Nearest Vert/Edge/Face
*
* \note Screen-space manhatten distances are used here,
@@ -445,11 +460,14 @@ BMVert *EDBM_vert_find_nearest_ex(
float dist_test;
unsigned int index;
BMVert *eve;
-
+
+ /* No afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad. */
+ ED_view3d_backbuf_validate(vc);
+
index = ED_view3d_backbuf_sample_rect(
vc, vc->mval, dist_px, bm_wireoffs, 0xFFFFFF, &dist_test);
eve = index ? BM_vert_at_index_find_or_table(bm, index - 1) : NULL;
-
+
if (eve) {
if (dist_test < *r_dist) {
*r_dist = dist_test;
@@ -630,9 +648,18 @@ BMEdge *EDBM_edge_find_nearest_ex(
float dist_test = 0.0f;
unsigned int index;
BMEdge *eed;
-
+
+ /* Make sure that the edges are considered for selection.
+ * TODO: cleanup: add `selectmode` as a parameter */
+ const short ts_selectmode = vc->scene->toolsettings->selectmode;
+ vc->scene->toolsettings->selectmode |= SCE_SELECT_EDGE;
+
+ /* No afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad. */
ED_view3d_backbuf_validate(vc);
+ /* restore `selectmode` */
+ vc->scene->toolsettings->selectmode = ts_selectmode;
+
index = ED_view3d_backbuf_sample_rect(vc, vc->mval, dist_px, bm_solidoffs, bm_wireoffs, &dist_test);
eed = index ? BM_edge_at_index_find_or_table(bm, index - 1) : NULL;
@@ -799,7 +826,7 @@ BMFace *EDBM_face_find_nearest_ex(
index = ED_view3d_backbuf_sample(vc, vc->mval[0], vc->mval[1]);
efa = index ? BM_face_at_index_find_or_table(bm, index - 1) : NULL;
-
+
if (r_efa_zbuf) {
*r_efa_zbuf = efa;
}
@@ -877,8 +904,8 @@ BMFace *EDBM_face_find_nearest(ViewContext *vc, float *r_dist)
#undef FIND_NEAR_CYCLE_THRESHOLD_MIN
-/* best distance based on screen coords.
- * use em->selectmode to define how to use
+/* best distance based on screen coords.
+ * use em->selectmode to define how to use
* selected vertices and edges get disadvantage
* return 1 if found one
*/
@@ -894,7 +921,7 @@ static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed,
float dist = dist_init;
BMFace *efa_zbuf = NULL;
BMEdge *eed_zbuf = NULL;
-
+
BMVert *eve = NULL;
BMEdge *eed = NULL;
BMFace *efa = NULL;
@@ -956,9 +983,11 @@ static int unified_findnearest(ViewContext *vc, BMVert **r_eve, BMEdge **r_eed,
/** \} */
+/* -------------------------------------------------------------------- */
+/** \name Select Similar (Vert/Edge/Face) Operator
+ * \{ */
-/* **************** SIMILAR "group" SELECTS. FACE, EDGE AND VERTEX ************** */
-static EnumPropertyItem prop_similar_compare_types[] = {
+static const EnumPropertyItem prop_similar_compare_types[] = {
{SIM_CMP_EQ, "EQUAL", 0, "Equal", ""},
{SIM_CMP_GT, "GREATER", 0, "Greater", ""},
{SIM_CMP_LT, "LESS", 0, "Less", ""},
@@ -966,7 +995,7 @@ static EnumPropertyItem prop_similar_compare_types[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_similar_types[] = {
+static const EnumPropertyItem prop_similar_types[] = {
{SIMVERT_NORMAL, "NORMAL", 0, "Normal", ""},
{SIMVERT_FACE, "FACE", 0, "Amount of Adjacent Faces", ""},
{SIMVERT_VGROUP, "VGROUP", 0, "Vertex Groups", ""},
@@ -1034,7 +1063,7 @@ static int similar_face_select_exec(bContext *C, wmOperator *op)
EDBM_update_generic(em, false, false);
return OPERATOR_FINISHED;
-}
+}
/* ***************************************************** */
@@ -1140,8 +1169,9 @@ static int edbm_select_similar_exec(bContext *C, wmOperator *op)
else return similar_face_select_exec(C, op);
}
-static EnumPropertyItem *select_similar_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
- bool *r_free)
+static const EnumPropertyItem *select_similar_type_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop),
+ bool *r_free)
{
Object *obedit;
@@ -1193,15 +1223,15 @@ void MESH_OT_select_similar(wmOperatorType *ot)
ot->name = "Select Similar";
ot->idname = "MESH_OT_select_similar";
ot->description = "Select similar vertices, edges or faces by property types";
-
+
/* api callbacks */
ot->invoke = WM_menu_invoke;
ot->exec = edbm_select_similar_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* properties */
prop = ot->prop = RNA_def_enum(ot->srna, "type", prop_similar_types, SIMVERT_NORMAL, "Type", "");
RNA_def_enum_funcs(prop, select_similar_type_itemf);
@@ -1211,9 +1241,11 @@ void MESH_OT_select_similar(wmOperatorType *ot)
RNA_def_float(ot->srna, "threshold", 0.0f, 0.0f, 1.0f, "Threshold", "", 0.0f, 1.0f);
}
+/** \} */
/* -------------------------------------------------------------------- */
-/* Select Similar Regions */
+/** \name Select Similar Region Operator
+ * \{ */
static int edbm_select_similar_region_exec(bContext *C, wmOperator *op)
{
@@ -1234,9 +1266,10 @@ static int edbm_select_similar_region_exec(bContext *C, wmOperator *op)
}
groups_array = MEM_mallocN(sizeof(*groups_array) * bm->totfacesel, __func__);
- group_tot = BM_mesh_calc_face_groups(bm, groups_array, &group_index,
- NULL, NULL,
- BM_ELEM_SELECT, BM_VERT);
+ group_tot = BM_mesh_calc_face_groups(
+ bm, groups_array, &group_index,
+ NULL, NULL,
+ BM_ELEM_SELECT, BM_VERT);
BM_mesh_elem_table_ensure(bm, BM_FACE);
@@ -1277,7 +1310,7 @@ static int edbm_select_similar_region_exec(bContext *C, wmOperator *op)
MEM_freeN(group_index);
if (changed) {
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
}
else {
BKE_report(op->reports, RPT_WARNING, "No matching face regions found");
@@ -1301,8 +1334,11 @@ void MESH_OT_select_similar_region(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
-/* **************** Mode Select *************** */
+/* -------------------------------------------------------------------- */
+/** \name Select Mode Vert/Edge/Face Operator
+ * \{ */
static int edbm_select_mode_exec(bContext *C, wmOperator *op)
{
@@ -1335,14 +1371,14 @@ void MESH_OT_select_mode(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem elem_items[] = {
+ static const EnumPropertyItem elem_items[] = {
{SCE_SELECT_VERTEX, "VERT", ICON_VERTEXSEL, "Vertices", ""},
{SCE_SELECT_EDGE, "EDGE", ICON_EDGESEL, "Edges", ""},
{SCE_SELECT_FACE, "FACE", ICON_FACESEL, "Faces", ""},
{0, NULL, 0, NULL, NULL},
};
- static EnumPropertyItem actions_items[] = {
+ static const EnumPropertyItem actions_items[] = {
{0, "DISABLE", 0, "Disable", "Disable selected markers"},
{1, "ENABLE", 0, "Enable", "Enable selected markers"},
{2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
@@ -1373,12 +1409,15 @@ void MESH_OT_select_mode(wmOperatorType *ot)
RNA_def_enum(ot->srna, "action", actions_items, 2, "Action", "Selection action to execute");
}
-/* ***************************************************** */
+/** \} */
-/* **************** LOOP SELECTS *************** */
+/* -------------------------------------------------------------------- */
+/** \name Select Loop (Non Modal) Operator
+ * \{ */
-static void walker_select_count(BMEditMesh *em, int walkercode, void *start, const bool select, const bool select_mix,
- int *r_totsel, int *r_totunsel)
+static void walker_select_count(
+ BMEditMesh *em, int walkercode, void *start, const bool select, const bool select_mix,
+ int *r_totsel, int *r_totunsel)
{
BMesh *bm = em->bm;
BMElem *ele;
@@ -1433,7 +1472,7 @@ static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
BMEdge **edarray;
int edindex;
const bool is_ring = RNA_boolean_get(op->ptr, "ring");
-
+
BMIter iter;
int totedgesel = 0;
@@ -1442,17 +1481,17 @@ static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
totedgesel++;
}
}
-
+
edarray = MEM_mallocN(sizeof(BMEdge *) * totedgesel, "edge array");
edindex = 0;
-
+
BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(eed, BM_ELEM_SELECT)) {
edarray[edindex] = eed;
edindex++;
}
}
-
+
if (is_ring) {
for (edindex = 0; edindex < totedgesel; edindex += 1) {
eed = edarray[edindex];
@@ -1469,8 +1508,8 @@ static int edbm_loop_multiselect_exec(bContext *C, wmOperator *op)
}
MEM_freeN(edarray);
// if (EM_texFaceCheck())
-
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -1481,23 +1520,23 @@ void MESH_OT_loop_multi_select(wmOperatorType *ot)
ot->name = "Multi Select Loops";
ot->idname = "MESH_OT_loop_multi_select";
ot->description = "Select a loop of connected edges by connection type";
-
+
/* api callbacks */
ot->exec = edbm_loop_multiselect_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* properties */
RNA_def_boolean(ot->srna, "ring", 0, "Ring", "");
}
-
-/* ***************** MAIN MOUSE SELECTION ************** */
-
+/** \} */
-/* ***************** loop select (non modal) ************** */
+/* -------------------------------------------------------------------- */
+/** \name Select Loop (Cursor Pick) Operator
+ * \{ */
static void mouse_mesh_loop_face(BMEditMesh *em, BMEdge *eed, bool select, bool select_clear)
{
@@ -1552,7 +1591,6 @@ static void mouse_mesh_loop_edge(BMEditMesh *em, BMEdge *eed, bool select, bool
}
}
-
static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle, bool ring)
{
ViewContext vc;
@@ -1569,9 +1607,17 @@ static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool de
mvalf[1] = (float)(vc.mval[1] = mval[1]);
em = vc.em;
+ /* Make sure that the edges are also considered for selection.
+ * TODO: cleanup: add `selectmode` as a parameter */
+ const short ts_selectmode = vc.scene->toolsettings->selectmode;
+ vc.scene->toolsettings->selectmode |= SCE_SELECT_EDGE;
+
/* no afterqueue (yet), so we check it now, otherwise the bm_xxxofs indices are bad */
ED_view3d_backbuf_validate(&vc);
+ /* restore `selectmode` */
+ vc.scene->toolsettings->selectmode = ts_selectmode;
+
eed = EDBM_edge_find_nearest_ex(&vc, &dist, NULL, true, true, NULL);
if (eed == NULL) {
return false;
@@ -1621,11 +1667,15 @@ static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool de
/* We can't be sure this has already been set... */
ED_view3d_init_mats_rv3d(vc.obedit, vc.rv3d);
- if (ED_view3d_project_float_object(vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
+ if (ED_view3d_project_float_object(
+ vc.ar, eed->v1->co, v1_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ {
length_1 = len_squared_v2v2(mvalf, v1_co);
}
- if (ED_view3d_project_float_object(vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
+ if (ED_view3d_project_float_object(
+ vc.ar, eed->v2->co, v2_co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ {
length_2 = len_squared_v2v2(mvalf, v2_co);
}
#if 0
@@ -1652,7 +1702,9 @@ static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool de
float co[2], tdist;
BM_face_calc_center_mean(f, cent);
- if (ED_view3d_project_float_object(vc.ar, cent, co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK) {
+ if (ED_view3d_project_float_object(
+ vc.ar, cent, co, V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ {
tdist = len_squared_v2v2(mvalf, co);
if (tdist < best_dist) {
/* printf("Best face: %p (%f)\n", f, tdist);*/
@@ -1669,21 +1721,22 @@ static bool mouse_mesh_loop(bContext *C, const int mval[2], bool extend, bool de
}
}
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
return true;
}
static int edbm_select_loop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
-
+
view3d_operator_needs_opengl(C);
-
- if (mouse_mesh_loop(C, event->mval,
- RNA_boolean_get(op->ptr, "extend"),
- RNA_boolean_get(op->ptr, "deselect"),
- RNA_boolean_get(op->ptr, "toggle"),
- RNA_boolean_get(op->ptr, "ring")))
+
+ if (mouse_mesh_loop(
+ C, event->mval,
+ RNA_boolean_get(op->ptr, "extend"),
+ RNA_boolean_get(op->ptr, "deselect"),
+ RNA_boolean_get(op->ptr, "toggle"),
+ RNA_boolean_get(op->ptr, "ring")))
{
return OPERATOR_FINISHED;
}
@@ -1698,14 +1751,14 @@ void MESH_OT_loop_select(wmOperatorType *ot)
ot->name = "Loop Select";
ot->idname = "MESH_OT_loop_select";
ot->description = "Select a loop of connected edges";
-
+
/* api callbacks */
ot->invoke = edbm_select_loop_invoke;
ot->poll = ED_operator_editmesh_region_view3d;
-
+
/* flags */
ot->flag = OPTYPE_UNDO;
-
+
/* properties */
RNA_def_boolean(ot->srna, "extend", 0, "Extend Select", "Extend the selection");
RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Remove from the selection");
@@ -1719,11 +1772,11 @@ void MESH_OT_edgering_select(wmOperatorType *ot)
ot->name = "Edge Ring Select";
ot->idname = "MESH_OT_edgering_select";
ot->description = "Select an edge ring";
-
+
/* callbacks */
ot->invoke = edbm_select_loop_invoke;
ot->poll = ED_operator_editmesh_region_view3d;
-
+
/* flags */
ot->flag = OPTYPE_UNDO;
@@ -1733,7 +1786,12 @@ void MESH_OT_edgering_select(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "ring", 1, "Select Ring", "Select ring");
}
-/* ******************** (de)select all operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name (De)Select All Operator
+ * \{ */
+
static int edbm_select_all_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -1756,7 +1814,7 @@ static int edbm_select_all_exec(bContext *C, wmOperator *op)
break;
}
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -1778,13 +1836,19 @@ void MESH_OT_select_all(wmOperatorType *ot)
WM_operator_properties_select_all(ot);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Interior Faces Operator
+ * \{ */
+
static int edbm_faces_select_interior_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
if (EDBM_select_interior_faces(em)) {
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -1809,10 +1873,15 @@ void MESH_OT_select_interior_faces(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Picking API
+ *
+ * Here actual select happens,
+ * Gets called via generic mouse select operator.
+ * \{ */
-/* ************************************************** */
-/* here actual select happens */
-/* gets called via generic mouse select operator */
bool EDBM_select_pick(bContext *C, const int mval[2], bool extend, bool deselect, bool toggle)
{
ViewContext vc;
@@ -1921,13 +1990,19 @@ bool EDBM_select_pick(bContext *C, const int mval[2], bool extend, bool deselect
}
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, vc.obedit->data);
return true;
}
return false;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Mode Utilities
+ * \{ */
+
static void edbm_strip_selections(BMEditMesh *em)
{
BMEditSelection *ese, *nextese;
@@ -1966,11 +2041,11 @@ void EDBM_selectmode_set(BMEditMesh *em)
BMEdge *eed;
BMFace *efa;
BMIter iter;
-
+
em->bm->selectmode = em->selectmode;
edbm_strip_selections(em); /* strip BMEditSelections from em->selected that are not relevant to new mode */
-
+
if (em->bm->totvertsel == 0 &&
em->bm->totedgesel == 0 &&
em->bm->totfacesel == 0)
@@ -2133,8 +2208,9 @@ void EDBM_selectmode_convert(BMEditMesh *em, const short selectmode_old, const s
}
/* user facing function, does notification */
-bool EDBM_selectmode_toggle(bContext *C, const short selectmode_new,
- const int action, const bool use_extend, const bool use_expand)
+bool EDBM_selectmode_toggle(
+ bContext *C, const short selectmode_new,
+ const int action, const bool use_extend, const bool use_expand)
{
ToolSettings *ts = CTX_data_tool_settings(C);
Object *obedit = CTX_data_edit_object(C);
@@ -2230,9 +2306,10 @@ bool EDBM_selectmode_toggle(bContext *C, const short selectmode_new,
*
* \return true if the mode is changed.
*/
-bool EDBM_selectmode_disable(Scene *scene, BMEditMesh *em,
- const short selectmode_disable,
- const short selectmode_fallback)
+bool EDBM_selectmode_disable(
+ Scene *scene, BMEditMesh *em,
+ const short selectmode_disable,
+ const short selectmode_fallback)
{
/* note essential, but switch out of vertex mode since the
* selected regions wont be nicely isolated after flushing */
@@ -2255,6 +2332,12 @@ bool EDBM_selectmode_disable(Scene *scene, BMEditMesh *em,
}
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Toggle
+ * \{ */
+
void EDBM_deselect_by_material(BMEditMesh *em, const short index, const bool select)
{
BMIter iter;
@@ -2283,7 +2366,7 @@ void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
BMVert *eve;
BMEdge *eed;
BMFace *efa;
-
+
if (em->bm->selectmode & SCE_SELECT_VERTEX) {
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
@@ -2306,9 +2389,17 @@ void EDBM_select_swap(BMEditMesh *em) /* exported for UV */
}
}
-// if (EM_texFaceCheck())
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Interior Faces
+ *
+ * \note This algorithm is limited to single faces and could be improved, see:
+ * https://blender.stackexchange.com/questions/18916
+ * \{ */
+
bool EDBM_select_interior_faces(BMEditMesh *em)
{
BMesh *bm = em->bm;
@@ -2341,8 +2432,13 @@ bool EDBM_select_interior_faces(BMEditMesh *em)
return changed;
}
+/** \} */
-/************************ Select Linked Operator *************************/
+/* -------------------------------------------------------------------- */
+/** \name Select Linked Operator
+ *
+ * Support delimiting on different edge properties.
+ * \{ */
/* so we can have last-used default depend on selection mode (rare exception!) */
#define USE_LINKED_SELECT_DEFAULT_HACK
@@ -2402,10 +2498,10 @@ static bool select_linked_delimit_test(
* Gets the default from the operator fallback to own last-used value
* (selected based on mode)
*/
-static int select_linked_delimit_default_from_op(wmOperator *op, BMEditMesh *em)
+static int select_linked_delimit_default_from_op(wmOperator *op, int select_mode)
{
static char delimit_last_store[2] = {0, BMO_DELIM_SEAM};
- int delimit_last_index = (em->selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) == 0;
+ int delimit_last_index = (select_mode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) == 0;
char *delimit_last = &delimit_last_store[delimit_last_index];
PropertyRNA *prop_delimit = RNA_struct_find_property(op->ptr, "delimit");
int delimit;
@@ -2475,7 +2571,7 @@ static int edbm_select_linked_exec(bContext *C, wmOperator *op)
BMWalker walker;
#ifdef USE_LINKED_SELECT_DEFAULT_HACK
- int delimit = select_linked_delimit_default_from_op(op, em);
+ int delimit = select_linked_delimit_default_from_op(op, em->selectmode);
#else
int delimit = RNA_enum_get(op->ptr, "delimit");
#endif
@@ -2633,7 +2729,7 @@ static int edbm_select_linked_exec(bContext *C, wmOperator *op)
select_linked_delimit_end(em);
}
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -2645,7 +2741,7 @@ void MESH_OT_select_linked(wmOperatorType *ot)
/* identifiers */
ot->name = "Select Linked All";
ot->idname = "MESH_OT_select_linked";
- ot->description = "Select all vertices linked to the active mesh";
+ ot->description = "Select all vertices connected to the current selection";
/* api callbacks */
ot->exec = edbm_select_linked_exec;
@@ -2663,6 +2759,12 @@ void MESH_OT_select_linked(wmOperatorType *ot)
#endif
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Linked (Cursor Pick) Operator
+ * \{ */
+
static int edbm_select_linked_pick_exec(bContext *C, wmOperator *op);
static void edbm_select_linked_pick_ex(BMEditMesh *em, BMElem *ele, bool sel, int delimit)
@@ -2801,13 +2903,13 @@ static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmE
/* return warning! */
if (unified_findnearest(&vc, &eve, &eed, &efa) == 0) {
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_CANCELLED;
}
#ifdef USE_LINKED_SELECT_DEFAULT_HACK
- int delimit = select_linked_delimit_default_from_op(op, em);
+ int delimit = select_linked_delimit_default_from_op(op, em->selectmode);
#else
int delimit = RNA_enum_get(op->ptr, "delimit");
#endif
@@ -2822,7 +2924,7 @@ static int edbm_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmE
RNA_int_set(op->ptr, "index", index);
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -2844,14 +2946,14 @@ static int edbm_select_linked_pick_exec(bContext *C, wmOperator *op)
BMElem *ele = EDBM_elem_from_index_any(em, index);
#ifdef USE_LINKED_SELECT_DEFAULT_HACK
- int delimit = select_linked_delimit_default_from_op(op, em);
+ int delimit = select_linked_delimit_default_from_op(op, em->selectmode);
#else
int delimit = RNA_enum_get(op->ptr, "delimit");
#endif
edbm_select_linked_pick_ex(em, ele, sel, delimit);
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -2864,15 +2966,15 @@ void MESH_OT_select_linked_pick(wmOperatorType *ot)
ot->name = "Select Linked";
ot->idname = "MESH_OT_select_linked_pick";
ot->description = "(De)select all vertices linked to the edge under the mouse cursor";
-
+
/* api callbacks */
ot->invoke = edbm_select_linked_pick_invoke;
ot->exec = edbm_select_linked_pick_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "");
prop = RNA_def_enum_flag(ot->srna, "delimit", rna_enum_mesh_delimit_mode_items, BMO_DELIM_SEAM, "Delimit",
"Delimit selected region");
@@ -2885,6 +2987,11 @@ void MESH_OT_select_linked_pick(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Face by Sides Operator
+ * \{ */
static int edbm_select_face_by_sides_exec(bContext *C, wmOperator *op)
{
@@ -2960,6 +3067,11 @@ void MESH_OT_select_face_by_sides(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend the selection");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Loose Operator
+ * \{ */
static int edbm_select_loose_exec(bContext *C, wmOperator *op)
{
@@ -3031,6 +3143,11 @@ void MESH_OT_select_loose(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Mirror Operator
+ * \{ */
static int edbm_select_mirror_exec(bContext *C, wmOperator *op)
{
@@ -3079,7 +3196,11 @@ void MESH_OT_select_mirror(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend the existing selection");
}
-/* ******************** **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select More Operator
+ * \{ */
static int edbm_select_more_exec(bContext *C, wmOperator *op)
{
@@ -3089,7 +3210,7 @@ static int edbm_select_more_exec(bContext *C, wmOperator *op)
EDBM_select_more(em, use_face_step);
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -3103,13 +3224,19 @@ void MESH_OT_select_more(wmOperatorType *ot)
/* api callbacks */
ot->exec = edbm_select_more_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
RNA_def_boolean(ot->srna, "use_face_step", true, "Face Step", "Connected faces (instead of edges)");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select More Operator
+ * \{ */
+
static int edbm_select_less_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3118,7 +3245,7 @@ static int edbm_select_less_exec(bContext *C, wmOperator *op)
EDBM_select_less(em, use_face_step);
- WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit);
+ WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
}
@@ -3132,13 +3259,19 @@ void MESH_OT_select_less(wmOperatorType *ot)
/* api callbacks */
ot->exec = edbm_select_less_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
RNA_def_boolean(ot->srna, "use_face_step", true, "Face Step", "Connected faces (instead of edges)");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select N'th Operator
+ * \{ */
+
/**
* Check if we're connected to another selected efge.
*/
@@ -3361,13 +3494,18 @@ void MESH_OT_select_nth(wmOperatorType *ot)
void em_setup_viewcontext(bContext *C, ViewContext *vc)
{
- view3d_set_viewcontext(C, vc);
-
+ ED_view3d_viewcontext_init(C, vc);
+
if (vc->obedit) {
vc->em = BKE_editmesh_from_object(vc->obedit);
}
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Sharp Edges Operator
+ * \{ */
static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op)
{
@@ -3395,6 +3533,13 @@ static int edbm_select_sharp_edges_exec(bContext *C, wmOperator *op)
}
}
+ if ((em->bm->selectmode & (SCE_SELECT_VERTEX | SCE_SELECT_EDGE)) == 0) {
+ /* Since we can't select individual edges, select faces connected to them. */
+ EDBM_selectmode_convert(em, SCE_SELECT_EDGE, SCE_SELECT_FACE);
+ }
+ else {
+ EDBM_selectmode_flush(em);
+ }
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
@@ -3408,20 +3553,26 @@ void MESH_OT_edges_select_sharp(wmOperatorType *ot)
ot->name = "Select Sharp Edges";
ot->description = "Select all sharp-enough edges";
ot->idname = "MESH_OT_edges_select_sharp";
-
+
/* api callbacks */
ot->exec = edbm_select_sharp_edges_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
"Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
RNA_def_property_float_default(prop, DEG2RADF(30.0f));
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Linked Flat Faces Operator
+ * \{ */
+
static int edbm_select_linked_flat_faces_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3489,20 +3640,26 @@ void MESH_OT_faces_select_linked_flat(wmOperatorType *ot)
ot->name = "Select Linked Flat Faces";
ot->description = "Select linked faces by angle";
ot->idname = "MESH_OT_faces_select_linked_flat";
-
+
/* api callbacks */
ot->exec = edbm_select_linked_flat_faces_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
prop = RNA_def_float_rotation(ot->srna, "sharpness", 0, NULL, DEG2RADF(0.01f), DEG2RADF(180.0f),
"Sharpness", "", DEG2RADF(1.0f), DEG2RADF(180.0f));
RNA_def_property_float_default(prop, DEG2RADF(1.0f));
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Non-Manifold Operator
+ * \{ */
+
static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3524,12 +3681,12 @@ static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
/* Selects isolated verts, and edges that do not have 2 neighboring
* faces
*/
-
+
if (em->selectmode == SCE_SELECT_FACE) {
BKE_report(op->reports, RPT_ERROR, "Does not work in face selection mode");
return OPERATOR_CANCELLED;
}
-
+
if (use_verts) {
BM_ITER_MESH (v, &iter, em->bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
@@ -3539,7 +3696,7 @@ static int edbm_select_non_manifold_exec(bContext *C, wmOperator *op)
}
}
}
-
+
if (use_wire || use_boundary || use_multi_face || use_non_contiguous) {
BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
if (!BM_elem_flag_test(e, BM_ELEM_HIDDEN)) {
@@ -3570,11 +3727,11 @@ void MESH_OT_select_non_manifold(wmOperatorType *ot)
ot->name = "Select Non Manifold";
ot->description = "Select all non-manifold vertices or edges";
ot->idname = "MESH_OT_select_non_manifold";
-
+
/* api callbacks */
ot->exec = edbm_select_non_manifold_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -3594,6 +3751,12 @@ void MESH_OT_select_non_manifold(wmOperatorType *ot)
"Vertices connecting multiple face regions");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Random Operator
+ * \{ */
+
static int edbm_select_random_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3640,9 +3803,9 @@ static int edbm_select_random_exec(bContext *C, wmOperator *op)
else {
EDBM_deselect_flush(em);
}
-
+
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
-
+
return OPERATOR_FINISHED;
}
@@ -3659,11 +3822,17 @@ void MESH_OT_select_random(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
WM_operator_properties_select_random(ot);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Ungrouped Operator
+ * \{ */
+
static int edbm_select_ungrouped_poll(bContext *C)
{
if (ED_operator_editmesh(C)) {
@@ -3730,6 +3899,11 @@ void MESH_OT_select_ungrouped(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "extend", false, "Extend", "Extend the selection");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Axis Operator
+ * \{ */
/* BMESH_TODO - some way to select on an arbitrary axis */
static int edbm_select_axis_exec(bContext *C, wmOperator *op)
@@ -3784,14 +3958,14 @@ static int edbm_select_axis_exec(bContext *C, wmOperator *op)
void MESH_OT_select_axis(wmOperatorType *ot)
{
- static EnumPropertyItem axis_mode_items[] = {
+ static const EnumPropertyItem axis_mode_items[] = {
{0, "POSITIVE", 0, "Positive Axis", ""},
{1, "NEGATIVE", 0, "Negative Axis", ""},
{-1, "ALIGNED", 0, "Aligned Axis", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem axis_items_xyz[] = {
+ static const EnumPropertyItem axis_items_xyz[] = {
{0, "X_AXIS", 0, "X Axis", ""},
{1, "Y_AXIS", 0, "Y Axis", ""},
{2, "Z_AXIS", 0, "Z Axis", ""},
@@ -3816,6 +3990,12 @@ void MESH_OT_select_axis(wmOperatorType *ot)
RNA_def_float(ot->srna, "threshold", 0.0001f, 0.000001f, 50.0f, "Threshold", "", 0.00001f, 10.0f);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Region to Loop Operator
+ * \{ */
+
static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *obedit = CTX_data_edit_object(C);
@@ -3829,22 +4009,22 @@ static int edbm_region_to_loop_exec(bContext *C, wmOperator *UNUSED(op))
BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
BMLoop *l1, *l2;
BMIter liter1, liter2;
-
+
BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
int tot = 0, totsel = 0;
-
+
BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
tot++;
totsel += BM_elem_flag_test(l2->f, BM_ELEM_SELECT) != 0;
}
-
+
if ((tot != totsel && totsel > 0) || (totsel == 1 && tot == 1))
BM_elem_flag_enable(l1->e, BM_ELEM_TAG);
}
}
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
-
+
BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
if (BM_elem_flag_test(e, BM_ELEM_TAG)) {
BM_edge_select_set(em->bm, e, true);
@@ -3879,29 +4059,36 @@ void MESH_OT_region_to_loop(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-static int loop_find_region(BMLoop *l, int flag,
- GSet *visit_face_set, BMFace ***region_out)
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Loop to Region Operator
+ * \{ */
+
+static int loop_find_region(
+ BMLoop *l, int flag,
+ GSet *visit_face_set, BMFace ***region_out)
{
BMFace **region = NULL;
BMFace **stack = NULL;
BLI_array_declare(region);
BLI_array_declare(stack);
BMFace *f;
-
+
BLI_array_append(stack, l->f);
BLI_gset_insert(visit_face_set, l->f);
-
- while (BLI_array_count(stack) > 0) {
+
+ while (BLI_array_len(stack) > 0) {
BMIter liter1, liter2;
BMLoop *l1, *l2;
-
+
f = BLI_array_pop(stack);
BLI_array_append(region, f);
-
+
BM_ITER_ELEM (l1, &liter1, f, BM_LOOPS_OF_FACE) {
if (BM_elem_flag_test(l1->e, flag))
continue;
-
+
BM_ITER_ELEM (l2, &liter2, l1->e, BM_LOOPS_OF_EDGE) {
/* avoids finding same region twice
* (otherwise) the logic works fine without */
@@ -3915,11 +4102,11 @@ static int loop_find_region(BMLoop *l, int flag,
}
}
}
-
+
BLI_array_free(stack);
-
+
*region_out = region;
- return BLI_array_count(region);
+ return BLI_array_len(region);
}
static int verg_radial(const void *va, const void *vb)
@@ -3927,10 +4114,9 @@ static int verg_radial(const void *va, const void *vb)
const BMEdge *e_a = *((const BMEdge **)va);
const BMEdge *e_b = *((const BMEdge **)vb);
- int a, b;
- a = BM_edge_face_count(e_a);
- b = BM_edge_face_count(e_b);
-
+ const int a = BM_edge_face_count(e_a);
+ const int b = BM_edge_face_count(e_b);
+
if (a > b) return -1;
if (a < b) return 1;
return 0;
@@ -3949,7 +4135,7 @@ static int loop_find_regions(BMEditMesh *em, const bool selbigger)
const int edges_len = em->bm->totedgesel;
BMEdge *e, **edges;
int count = 0, i;
-
+
visit_face_set = BLI_gset_ptr_new_ex(__func__, edges_len);
edges = MEM_mallocN(sizeof(*edges) * edges_len, __func__);
@@ -3963,21 +4149,21 @@ static int loop_find_regions(BMEditMesh *em, const bool selbigger)
BM_elem_flag_disable(e, BM_ELEM_TAG);
}
}
-
+
/* sort edges by radial cycle length */
qsort(edges, edges_len, sizeof(*edges), verg_radial);
-
+
for (i = 0; i < edges_len; i++) {
BMIter liter;
BMLoop *l;
BMFace **region = NULL, **region_out;
int c, tot = 0;
-
+
e = edges[i];
-
+
if (!BM_elem_flag_test(e, BM_ELEM_TAG))
continue;
-
+
BM_ITER_ELEM (l, &liter, e, BM_LOOPS_OF_EDGE) {
if (BLI_gset_haskey(visit_face_set, l->f))
continue;
@@ -3999,26 +4185,26 @@ static int loop_find_regions(BMEditMesh *em, const bool selbigger)
MEM_freeN(region_out);
}
}
-
+
if (region) {
int j;
-
+
for (j = 0; j < tot; j++) {
BM_elem_flag_enable(region[j], BM_ELEM_TAG);
BM_ITER_ELEM (l, &liter, region[j], BM_LOOPS_OF_FACE) {
BM_elem_flag_disable(l->e, BM_ELEM_TAG);
}
}
-
+
count += tot;
-
+
MEM_freeN(region);
}
}
-
+
MEM_freeN(edges);
BLI_gset_free(visit_face_set, NULL);
-
+
return count;
}
@@ -4029,25 +4215,23 @@ static int edbm_loop_to_region_exec(bContext *C, wmOperator *op)
BMIter iter;
BMFace *f;
const bool select_bigger = RNA_boolean_get(op->ptr, "select_bigger");
- int a, b;
-
/* find the set of regions with smallest number of total faces */
BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
- a = loop_find_regions(em, select_bigger);
- b = loop_find_regions(em, !select_bigger);
+ const int a = loop_find_regions(em, select_bigger);
+ const int b = loop_find_regions(em, !select_bigger);
BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
loop_find_regions(em, ((a <= b) != select_bigger) ? select_bigger : !select_bigger);
-
+
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
-
+
BM_ITER_MESH (f, &iter, em->bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(f, BM_ELEM_TAG) && !BM_elem_flag_test(f, BM_ELEM_HIDDEN)) {
BM_face_select_set(em->bm, f, true);
}
}
-
+
EDBM_selectmode_flush(em);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
@@ -4067,9 +4251,8 @@ void MESH_OT_loop_to_region(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
RNA_def_boolean(ot->srna, "select_bigger", 0, "Select Bigger", "Select bigger regions instead of smaller ones");
}
-
-/************************ Select Path Operator *************************/
+/** \} */
diff --git a/source/blender/editors/mesh/editmesh_tools.c b/source/blender/editors/mesh/editmesh_tools.c
index 65ee097e8e1..683e69a4ff6 100644
--- a/source/blender/editors/mesh/editmesh_tools.c
+++ b/source/blender/editors/mesh/editmesh_tools.c
@@ -84,6 +84,10 @@
#define USE_FACE_CREATE_SEL_EXTEND
+/* -------------------------------------------------------------------- */
+/** \name Subdivide Operator
+ * \{ */
+
static int edbm_subdivide_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -93,19 +97,20 @@ static int edbm_subdivide_exec(bContext *C, wmOperator *op)
const float fractal = RNA_float_get(op->ptr, "fractal") / 2.5f;
const float along_normal = RNA_float_get(op->ptr, "fractal_along_normal");
- if (RNA_boolean_get(op->ptr, "quadtri") &&
+ if (RNA_boolean_get(op->ptr, "quadtri") &&
RNA_enum_get(op->ptr, "quadcorner") == SUBD_CORNER_STRAIGHT_CUT)
{
RNA_enum_set(op->ptr, "quadcorner", SUBD_CORNER_INNERVERT);
}
-
- BM_mesh_esubdivide(em->bm, BM_ELEM_SELECT,
- smooth, SUBD_FALLOFF_LIN, false,
- fractal, along_normal,
- cuts,
- SUBDIV_SELECT_ORIG, RNA_enum_get(op->ptr, "quadcorner"),
- RNA_boolean_get(op->ptr, "quadtri"), true, false,
- RNA_int_get(op->ptr, "seed"));
+
+ BM_mesh_esubdivide(
+ em->bm, BM_ELEM_SELECT,
+ smooth, SUBD_FALLOFF_LIN, false,
+ fractal, along_normal,
+ cuts,
+ SUBDIV_SELECT_ORIG, RNA_enum_get(op->ptr, "quadcorner"),
+ RNA_boolean_get(op->ptr, "quadtri"), true, false,
+ RNA_int_get(op->ptr, "seed"));
EDBM_update_generic(em, true, true);
@@ -113,7 +118,7 @@ static int edbm_subdivide_exec(bContext *C, wmOperator *op)
}
/* Note, these values must match delete_mesh() event values */
-static EnumPropertyItem prop_mesh_cornervert_types[] = {
+static const EnumPropertyItem prop_mesh_cornervert_types[] = {
{SUBD_CORNER_INNERVERT, "INNERVERT", 0, "Inner Vert", ""},
{SUBD_CORNER_PATH, "PATH", 0, "Path", ""},
{SUBD_CORNER_STRAIGHT_CUT, "STRAIGHT_CUT", 0, "Straight Cut", ""},
@@ -154,10 +159,14 @@ void MESH_OT_subdivide(wmOperatorType *ot)
RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Random Seed", "Seed for the random number generator", 0, 255);
}
+/** \} */
+
/* -------------------------------------------------------------------- */
-/* Edge Ring Subdiv
- * (bridge code shares props)
- */
+/** \name Edge Ring Subdivide Operator
+ *
+ * Bridge code shares props.
+ *
+ * \{ */
struct EdgeRingOpSubdProps {
int interp_mode;
@@ -169,10 +178,10 @@ struct EdgeRingOpSubdProps {
};
-static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_default)
+static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_min, const int cuts_default)
{
/* Note, these values must match delete_mesh() event values */
- static EnumPropertyItem prop_subd_edgering_types[] = {
+ static const EnumPropertyItem prop_subd_edgering_types[] = {
{SUBD_RING_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
{SUBD_RING_INTERP_PATH, "PATH", 0, "Blend Path", ""},
{SUBD_RING_INTERP_SURF, "SURFACE", 0, "Blend Surface", ""},
@@ -181,7 +190,7 @@ static void mesh_operator_edgering_props(wmOperatorType *ot, const int cuts_defa
PropertyRNA *prop;
- prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, 1000, "Number of Cuts", "", 0, 64);
+ prop = RNA_def_int(ot->srna, "number_cuts", cuts_default, 0, 1000, "Number of Cuts", "", cuts_min, 64);
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
RNA_def_enum(ot->srna, "interpolation", prop_subd_edgering_types, SUBD_RING_INTERP_PATH,
@@ -219,11 +228,12 @@ static int edbm_subdivide_edge_ring_exec(bContext *C, wmOperator *op)
mesh_operator_edgering_props_get(op, &op_props);
- if (!EDBM_op_callf(em, op,
- "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f "
- "profile_shape=%i profile_shape_factor=%f",
- BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth,
- op_props.profile_shape, op_props.profile_shape_factor))
+ if (!EDBM_op_callf(
+ em, op,
+ "subdivide_edgering edges=%he interp_mode=%i cuts=%i smooth=%f "
+ "profile_shape=%i profile_shape_factor=%f",
+ BM_ELEM_SELECT, op_props.interp_mode, op_props.cuts, op_props.smooth,
+ op_props.profile_shape, op_props.profile_shape_factor))
{
return OPERATOR_CANCELLED;
}
@@ -248,9 +258,14 @@ void MESH_OT_subdivide_edgering(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- mesh_operator_edgering_props(ot, 10);
+ mesh_operator_edgering_props(ot, 1, 10);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Un-Subdivide Operator
+ * \{ */
static int edbm_unsubdivide_exec(bContext *C, wmOperator *op)
{
@@ -332,6 +347,11 @@ void EMBM_project_snap_verts(bContext *C, ARegion *ar, BMEditMesh *em)
ED_transform_snap_object_context_destroy(snap_context);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Delete Operator
+ * \{ */
/* Note, these values must match delete_mesh() event values */
enum {
@@ -386,13 +406,13 @@ static int edbm_delete_exec(bContext *C, wmOperator *op)
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
void MESH_OT_delete(wmOperatorType *ot)
{
- static EnumPropertyItem prop_mesh_delete_types[] = {
+ static const EnumPropertyItem prop_mesh_delete_types[] = {
{MESH_DELETE_VERT, "VERT", 0, "Vertices", ""},
{MESH_DELETE_EDGE, "EDGE", 0, "Edges", ""},
{MESH_DELETE_FACE, "FACE", 0, "Faces", ""},
@@ -405,13 +425,13 @@ void MESH_OT_delete(wmOperatorType *ot)
ot->name = "Delete";
ot->description = "Delete selected vertices, edges or faces";
ot->idname = "MESH_OT_delete";
-
+
/* api callbacks */
ot->invoke = WM_menu_invoke;
ot->exec = edbm_delete_exec;
-
+
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -420,6 +440,11 @@ void MESH_OT_delete(wmOperatorType *ot)
"Type", "Method used for deleting mesh data");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Delete Loose Operator
+ * \{ */
static bool bm_face_is_loose(BMFace *f)
{
@@ -518,6 +543,11 @@ void MESH_OT_delete_loose(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_faces", false, "Faces", "Remove loose faces");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Collapse Edge Operator
+ * \{ */
static int edbm_collapse_edge_exec(bContext *C, wmOperator *op)
{
@@ -547,6 +577,12 @@ void MESH_OT_edge_collapse(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Create Edge/Face Operator
+ * \{ */
+
static bool edbm_add_edge_face__smooth_get(BMesh *bm)
{
BMEdge *e;
@@ -616,8 +652,9 @@ static BMElem *edbm_add_edge_face_exec__tricky_extend_sel(BMesh *bm)
(BM_edge_share_face_check(ed_pair[0], ed_pair[1]) == false))
)
{
- BMEdge *e_other = BM_edge_exists(BM_edge_other_vert(ed_pair[0], v),
- BM_edge_other_vert(ed_pair[1], v));
+ BMEdge *e_other = BM_edge_exists(
+ BM_edge_other_vert(ed_pair[0], v),
+ BM_edge_other_vert(ed_pair[1], v));
BM_edge_select_set(bm, ed_pair[0], true);
BM_edge_select_set(bm, ed_pair[1], true);
if (e_other) {
@@ -740,13 +777,14 @@ static int edbm_add_edge_face_exec(bContext *C, wmOperator *op)
ele_desel = edbm_add_edge_face_exec__tricky_extend_sel(em->bm);
#endif
- if (!EDBM_op_init(em, &bmop, op,
- "contextual_create geom=%hfev mat_nr=%i use_smooth=%b",
- BM_ELEM_SELECT, em->mat_nr, use_smooth))
+ if (!EDBM_op_init(
+ em, &bmop, op,
+ "contextual_create geom=%hfev mat_nr=%i use_smooth=%b",
+ BM_ELEM_SELECT, em->mat_nr, use_smooth))
{
return OPERATOR_CANCELLED;
}
-
+
BMO_op_exec(em->bm, &bmop);
/* cancel if nothing was done */
@@ -796,16 +834,20 @@ void MESH_OT_edge_face_add(wmOperatorType *ot)
ot->name = "Make Edge/Face";
ot->description = "Add an edge or face to selected";
ot->idname = "MESH_OT_edge_face_add";
-
+
/* api callbacks */
ot->exec = edbm_add_edge_face_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/* ************************* SEAMS AND EDGES **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mark Edge (Seam) Operator
+ * \{ */
static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
{
@@ -817,7 +859,7 @@ static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
BMEdge *eed;
BMIter iter;
const bool clear = RNA_boolean_get(op->ptr, "clear");
-
+
/* auto-enable seams drawing */
if (clear == 0) {
me->drawflag |= ME_DRAWSEAMS;
@@ -827,7 +869,7 @@ static int edbm_mark_seam_exec(bContext *C, wmOperator *op)
BM_ITER_MESH (eed, &iter, bm, BM_EDGES_OF_MESH) {
if (!BM_elem_flag_test(eed, BM_ELEM_SELECT) || BM_elem_flag_test(eed, BM_ELEM_HIDDEN))
continue;
-
+
BM_elem_flag_disable(eed, BM_ELEM_SEAM);
}
}
@@ -853,18 +895,24 @@ void MESH_OT_mark_seam(wmOperatorType *ot)
ot->name = "Mark Seam";
ot->idname = "MESH_OT_mark_seam";
ot->description = "(Un)mark selected edges as a seam";
-
+
/* api callbacks */
ot->exec = edbm_mark_seam_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
prop = RNA_def_boolean(ot->srna, "clear", 0, "Clear", "");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mark Edge (Sharp) Operator
+ * \{ */
+
static int edbm_mark_sharp_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -907,14 +955,14 @@ void MESH_OT_mark_sharp(wmOperatorType *ot)
ot->name = "Mark Sharp";
ot->idname = "MESH_OT_mark_sharp";
ot->description = "(Un)mark selected edges as sharp";
-
+
/* api callbacks */
ot->exec = edbm_mark_sharp_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
prop = RNA_def_boolean(ot->srna, "clear", false, "Clear", "");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
prop = RNA_def_boolean(ot->srna, "use_verts", false, "Vertices",
@@ -958,17 +1006,19 @@ static int edbm_vert_connect_exec(bContext *C, wmOperator *op)
}
if (is_pair) {
- if (!EDBM_op_init(em, &bmop, op,
- "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf",
- verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN))
+ if (!EDBM_op_init(
+ em, &bmop, op,
+ "connect_vert_pair verts=%eb verts_exclude=%hv faces_exclude=%hf",
+ verts, verts_len, BM_ELEM_HIDDEN, BM_ELEM_HIDDEN))
{
goto finally;
}
}
else {
- if (!EDBM_op_init(em, &bmop, op,
- "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b",
- verts, verts_len, BM_ELEM_HIDDEN, check_degenerate))
+ if (!EDBM_op_init(
+ em, &bmop, op,
+ "connect_verts verts=%eb faces_exclude=%hf check_degenerate=%b",
+ verts, verts_len, BM_ELEM_HIDDEN, check_degenerate))
{
goto finally;
}
@@ -1005,15 +1055,20 @@ void MESH_OT_vert_connect(wmOperatorType *ot)
ot->name = "Vertex Connect";
ot->idname = "MESH_OT_vert_connect";
ot->description = "Connect selected vertices of faces, splitting the face";
-
+
/* api callbacks */
ot->exec = edbm_vert_connect_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Split Concave Faces Operator
+ * \{ */
/**
* check that endpoints are verts and only have a single selected edge connected.
@@ -1064,7 +1119,7 @@ static bool bm_vert_connect_select_history(BMesh *bm)
* - Otherwise connect faces.
* - If all edges have been created already, closed the loop.
*/
- if (BLI_listbase_count_ex(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) {
+ if (BLI_listbase_count_at_most(&bm->selected, 2) == 2 && (bm->totvertsel > 2)) {
BMEditSelection *ese;
int tot = 0;
bool changed = false;
@@ -1318,6 +1373,11 @@ void MESH_OT_vert_connect_concave(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Split Non-Planar Faces Operator
+ * \{ */
static int edbm_vert_connect_nonplaner_exec(bContext *C, wmOperator *op)
{
@@ -1362,6 +1422,12 @@ void MESH_OT_vert_connect_nonplanar(wmOperatorType *ot)
RNA_def_property_float_default(prop, DEG2RADF(5.0f));
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Make Planar Faces Operator
+ * \{ */
+
static int edbm_face_make_planar_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -1399,6 +1465,11 @@ void MESH_OT_face_make_planar(wmOperatorType *ot)
RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Split Edge Operator
+ * \{ */
static int edbm_edge_split_exec(bContext *C, wmOperator *op)
{
@@ -1413,7 +1484,7 @@ static int edbm_edge_split_exec(bContext *C, wmOperator *op)
{
return OPERATOR_CANCELLED;
}
-
+
if (em->selectmode == SCE_SELECT_FACE) {
EDBM_select_flush(em);
}
@@ -1429,16 +1500,20 @@ void MESH_OT_edge_split(wmOperatorType *ot)
ot->name = "Edge Split";
ot->idname = "MESH_OT_edge_split";
ot->description = "Split selected edges so that each neighbor face gets its own copy";
-
+
/* api callbacks */
ot->exec = edbm_edge_split_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/****************** add duplicate operator ***************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Duplicate Operator
+ * \{ */
static int edbm_duplicate_exec(bContext *C, wmOperator *op)
{
@@ -1469,7 +1544,7 @@ static int edbm_duplicate_exec(bContext *C, wmOperator *op)
}
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -1478,7 +1553,7 @@ static int edbm_duplicate_invoke(bContext *C, wmOperator *op, const wmEvent *UNU
WM_cursor_wait(1);
edbm_duplicate_exec(C, op);
WM_cursor_wait(0);
-
+
return OPERATOR_FINISHED;
}
@@ -1488,29 +1563,34 @@ void MESH_OT_duplicate(wmOperatorType *ot)
ot->name = "Duplicate";
ot->description = "Duplicate selected vertices, edges or faces";
ot->idname = "MESH_OT_duplicate";
-
+
/* api callbacks */
ot->invoke = edbm_duplicate_invoke;
ot->exec = edbm_duplicate_exec;
-
+
ot->poll = ED_operator_editmesh;
-
+
/* to give to transform */
RNA_def_int(ot->srna, "mode", TFM_TRANSLATION, 0, INT_MAX, "Mode", "", 0, INT_MAX);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Flip Normals Operator
+ * \{ */
static int edbm_flip_normals_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
+
if (!EDBM_op_callf(
em, op, "reverse_faces faces=%hf flip_multires=%b",
BM_ELEM_SELECT, true))
{
return OPERATOR_CANCELLED;
}
-
+
EDBM_update_generic(em, true, false);
return OPERATOR_FINISHED;
@@ -1522,16 +1602,24 @@ void MESH_OT_flip_normals(wmOperatorType *ot)
ot->name = "Flip Normals";
ot->description = "Flip the direction of selected faces' normals (and of their vertices)";
ot->idname = "MESH_OT_flip_normals";
-
+
/* api callbacks */
ot->exec = edbm_flip_normals_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/* only accepts 1 selected edge, or 2 selected faces */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Rotate Edge Operator
+ * \{ */
+
+/**
+ * Rotate the edges between selected faces, otherwise rotate the selected edges.
+ */
static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -1562,7 +1650,7 @@ static int edbm_edge_rotate_selected_exec(bContext *C, wmOperator *op)
}
}
}
-
+
/* ok, we don't have two adjacent faces, but we do have two selected ones.
* that's an error condition.*/
if (tot == 0) {
@@ -1621,12 +1709,17 @@ void MESH_OT_edge_rotate(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_ccw", false, "Counter Clockwise", "");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Hide Operator
+ * \{ */
static int edbm_hide_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
+
EDBM_mesh_hide(em, RNA_boolean_get(op->ptr, "unselected"));
EDBM_update_generic(em, true, false);
@@ -1640,24 +1733,31 @@ void MESH_OT_hide(wmOperatorType *ot)
ot->name = "Hide Selection";
ot->idname = "MESH_OT_hide";
ot->description = "Hide (un)selected vertices, edges or faces";
-
+
/* api callbacks */
ot->exec = edbm_hide_exec;
ot->poll = ED_operator_editmesh;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* props */
RNA_def_boolean(ot->srna, "unselected", false, "Unselected", "Hide unselected rather than selected");
}
-static int edbm_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Reveal Operator
+ * \{ */
+
+static int edbm_reveal_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
- EDBM_mesh_reveal(em);
+ const bool select = RNA_boolean_get(op->ptr, "select");
+
+ EDBM_mesh_reveal(em, select);
EDBM_update_generic(em, true, false);
@@ -1670,20 +1770,28 @@ void MESH_OT_reveal(wmOperatorType *ot)
ot->name = "Reveal Hidden";
ot->idname = "MESH_OT_reveal";
ot->description = "Reveal all hidden vertices, edges and faces";
-
+
/* api callbacks */
ot->exec = edbm_reveal_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Recalculate Normals Operator
+ * \{ */
+
static int edbm_normals_make_consistent_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
+
/* doflip has to do with bmesh_rationalize_normals, it's an internal
* thing */
if (!EDBM_op_callf(em, op, "recalc_face_normals faces=%hf", BM_ELEM_SELECT))
@@ -1704,18 +1812,22 @@ void MESH_OT_normals_make_consistent(wmOperatorType *ot)
ot->name = "Make Normals Consistent";
ot->description = "Make face and vertex normals point either outside or inside the mesh";
ot->idname = "MESH_OT_normals_make_consistent";
-
+
/* api callbacks */
ot->exec = edbm_normals_make_consistent_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
RNA_def_boolean(ot->srna, "inside", false, "Inside", "");
}
+/** \} */
+/* -------------------------------------------------------------------- */
+/** \name Smooth Vertex Operator
+ * \{ */
static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
{
@@ -1739,12 +1851,12 @@ static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
}
/* if there is a mirror modifier with clipping, flag the verts that
- * are within tolerance of the plane(s) of reflection
+ * are within tolerance of the plane(s) of reflection
*/
for (md = obedit->modifiers.first; md; md = md->next) {
if (md->type == eModifierType_Mirror && (md->mode & eModifierMode_Realtime)) {
MirrorModifierData *mmd = (MirrorModifierData *)md;
-
+
if (mmd->flag & MOD_MIR_CLIPPING) {
if (mmd->flag & MOD_MIR_AXIS_X)
mirrx = true;
@@ -1763,10 +1875,11 @@ static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
repeat = 1;
for (i = 0; i < repeat; i++) {
- if (!EDBM_op_callf(em, op,
- "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b "
- "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b",
- BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
+ if (!EDBM_op_callf(
+ em, op,
+ "smooth_vert verts=%hv factor=%f mirror_clip_x=%b mirror_clip_y=%b mirror_clip_z=%b "
+ "clip_dist=%f use_axis_x=%b use_axis_y=%b use_axis_z=%b",
+ BM_ELEM_SELECT, fac, mirrx, mirry, mirrz, clip_dist, xaxis, yaxis, zaxis))
{
return OPERATOR_CANCELLED;
}
@@ -1781,19 +1894,20 @@ static int edbm_do_smooth_vertex_exec(bContext *C, wmOperator *op)
EDBM_update_generic(em, true, false);
return OPERATOR_FINISHED;
-}
-
+}
+
+
void MESH_OT_vertices_smooth(wmOperatorType *ot)
{
/* identifiers */
ot->name = "Smooth Vertex";
ot->description = "Flatten angles of selected vertices";
ot->idname = "MESH_OT_vertices_smooth";
-
+
/* api callbacks */
ot->exec = edbm_do_smooth_vertex_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1804,6 +1918,12 @@ void MESH_OT_vertices_smooth(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "zaxis", true, "Z-Axis", "Smooth along the Z axis");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Laplacian Vertex Smooth Operator
+ * \{ */
+
static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -1817,13 +1937,13 @@ static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
BMIter fiter;
BMFace *f;
- /* Check if select faces are triangles */
+ /* Check if select faces are triangles */
BM_ITER_MESH (f, &fiter, em->bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(f, BM_ELEM_SELECT)) {
if (f->len > 4) {
BKE_report(op->reports, RPT_WARNING, "Selected faces must be triangles or quads");
return OPERATOR_CANCELLED;
- }
+ }
}
}
@@ -1841,11 +1961,12 @@ static int edbm_do_smooth_laplacian_vertex_exec(bContext *C, wmOperator *op)
preserve_volume = RNA_boolean_get(op->ptr, "preserve_volume");
if (!repeat)
repeat = 1;
-
+
for (i = 0; i < repeat; i++) {
- if (!EDBM_op_callf(em, op,
- "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
- BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
+ if (!EDBM_op_callf(
+ em, op,
+ "smooth_laplacian_vert verts=%hv lambda_factor=%f lambda_border=%f use_x=%b use_y=%b use_z=%b preserve_volume=%b",
+ BM_ELEM_SELECT, lambda_factor, lambda_border, usex, usey, usez, preserve_volume))
{
return OPERATOR_CANCELLED;
}
@@ -1868,11 +1989,11 @@ void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
ot->name = "Laplacian Smooth Vertex";
ot->description = "Laplacian smooth of selected vertices";
ot->idname = "MESH_OT_vertices_smooth_laplacian";
-
+
/* api callbacks */
ot->exec = edbm_do_smooth_laplacian_vertex_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -1888,7 +2009,11 @@ void MESH_OT_vertices_smooth_laplacian(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "preserve_volume", true, "Preserve Volume", "Apply volume preservation after smooth");
}
-/********************** Smooth/Solid Operators *************************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Faces Smooth Shading Operator
+ * \{ */
static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
{
@@ -1896,7 +2021,7 @@ static void mesh_set_smooth_faces(BMEditMesh *em, short smooth)
BMFace *efa;
if (em == NULL) return;
-
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
BM_elem_flag_set(efa, BM_ELEM_SMOOTH, smooth);
@@ -1931,6 +2056,12 @@ void MESH_OT_faces_shade_smooth(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Faces Flat Shading Operator
+ * \{ */
+
static int edbm_faces_shade_flat_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *obedit = CTX_data_edit_object(C);
@@ -1958,8 +2089,11 @@ void MESH_OT_faces_shade_flat(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
-/********************** UV/Color Operators *************************/
+/* -------------------------------------------------------------------- */
+/** \name UV/Color Rotate/Reverse Operator
+ * \{ */
static int edbm_rotate_uvs_exec(bContext *C, wmOperator *op)
{
@@ -2129,6 +2263,11 @@ void MESH_OT_colors_reverse(wmOperatorType *ot)
//RNA_def_enum(ot->srna, "axis", axis_items, DIRECTION_CW, "Axis", "Axis to mirror colors around");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Merge Vertices Operator
+ * \{ */
enum {
MESH_MERGE_LAST = 1,
@@ -2165,7 +2304,7 @@ static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use
if (!BM_elem_flag_test(mergevert, BM_ELEM_SELECT))
return false;
-
+
if (use_uvmerge) {
if (!EDBM_op_callf(em, wmop, "pointmerge_facedata verts=%hv vert_snap=%e", BM_ELEM_SELECT, mergevert))
return false;
@@ -2177,8 +2316,9 @@ static bool merge_firstlast(BMEditMesh *em, const bool use_first, const bool use
return true;
}
-static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
- const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
+static bool merge_target(
+ BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
+ const bool use_cursor, const bool use_uvmerge, wmOperator *wmop)
{
BMIter iter;
BMVert *v;
@@ -2188,6 +2328,7 @@ static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
if (use_cursor) {
vco = ED_view3d_cursor3d_get(scene, v3d);
copy_v3_v3(co, vco);
+ invert_m4_m4(ob->imat, ob->obmat);
mul_m4_v3(ob->imat, co);
}
else {
@@ -2199,7 +2340,7 @@ static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
add_v3_v3(cent, v->co);
i++;
}
-
+
if (!i)
return false;
@@ -2211,7 +2352,7 @@ static bool merge_target(BMEditMesh *em, Scene *scene, View3D *v3d, Object *ob,
if (!vco)
return false;
-
+
if (use_uvmerge) {
if (!EDBM_op_callf(em, wmop, "average_vert_facedata verts=%hv", BM_ELEM_SELECT))
return false;
@@ -2268,7 +2409,7 @@ static int edbm_merge_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem merge_type_items[] = {
+static const EnumPropertyItem merge_type_items[] = {
{MESH_MERGE_FIRST, "FIRST", 0, "At First", ""},
{MESH_MERGE_LAST, "LAST", 0, "At Last", ""},
{MESH_MERGE_CENTER, "CENTER", 0, "At Center", ""},
@@ -2277,15 +2418,15 @@ static EnumPropertyItem merge_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
-{
+static const EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+{
Object *obedit;
EnumPropertyItem *item = NULL;
int totitem = 0;
-
+
if (!C) /* needed for docs */
return merge_type_items;
-
+
obedit = CTX_data_edit_object(C);
if (obedit && obedit->type == OB_MESH) {
BMEditMesh *em = BKE_editmesh_from_object(obedit);
@@ -2315,7 +2456,7 @@ static EnumPropertyItem *merge_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),
return item;
}
-
+
return NULL;
}
@@ -2340,6 +2481,11 @@ void MESH_OT_merge(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "uvs", false, "UVs", "Move UVs according to merge");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Remove Doubles Operator
+ * \{ */
static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
{
@@ -2362,9 +2508,10 @@ static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
if (use_unselected) {
- EDBM_op_init(em, &bmop, op,
- "automerge verts=%hv dist=%f",
- BM_ELEM_SELECT, threshold);
+ EDBM_op_init(
+ em, &bmop, op,
+ "automerge verts=%hv dist=%f",
+ BM_ELEM_SELECT, threshold);
BMO_op_exec(em->bm, &bmop);
if (!EDBM_op_finish(em, &bmop, op, true)) {
@@ -2372,9 +2519,10 @@ static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
}
}
else {
- EDBM_op_init(em, &bmop, op,
- "find_doubles verts=%hv dist=%f",
- BM_ELEM_SELECT, threshold);
+ EDBM_op_init(
+ em, &bmop, op,
+ "find_doubles verts=%hv dist=%f",
+ BM_ELEM_SELECT, threshold);
BMO_op_exec(em->bm, &bmop);
if (!EDBM_op_callf(em, op, "weld_verts targetmap=%S", &bmop, "targetmap.out")) {
@@ -2386,7 +2534,7 @@ static int edbm_remove_doubles_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
}
-
+
count = totvert_orig - em->bm->totvert;
BKE_reportf(op->reports, RPT_INFO, "Removed %d vertices", count);
@@ -2418,8 +2566,11 @@ void MESH_OT_remove_doubles(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_unselected", false, "Unselected", "Merge selected to other unselected vertices");
}
+/** \} */
-/************************ Shape Operators *************************/
+/* -------------------------------------------------------------------- */
+/** \name Shape Key Propagate Operator
+ * \{ */
/* BMESH_TODO this should be properly encapsulated in a bmop. but later.*/
static void shape_propagate(BMEditMesh *em, wmOperator *op)
@@ -2433,7 +2584,7 @@ static void shape_propagate(BMEditMesh *em, wmOperator *op)
BKE_report(op->reports, RPT_ERROR, "Mesh does not have shape keys");
return;
}
-
+
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
continue;
@@ -2484,6 +2635,12 @@ void MESH_OT_shape_propagate_to_all(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Blend from Shape Operator
+ * \{ */
+
/* BMESH_TODO this should be properly encapsulated in a bmop. but later.*/
static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
{
@@ -2510,23 +2667,23 @@ static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
if (key) {
kb = BLI_findlink(&key->block, shape);
}
-
+
/* perform blending on selected vertices*/
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (!BM_elem_flag_test(eve, BM_ELEM_SELECT) || BM_elem_flag_test(eve, BM_ELEM_HIDDEN))
continue;
-
+
/* get coordinates of shapekey we're blending from */
sco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, shape);
copy_v3_v3(co, sco);
-
+
if (use_add) {
/* in add mode, we add relative shape key offset */
if (kb) {
const float *rco = CustomData_bmesh_get_n(&em->bm->vdata, eve->head.data, CD_SHAPEKEY, kb->relative);
sub_v3_v3v3(co, co, rco);
}
-
+
madd_v3_v3fl(eve->co, co, blend);
}
else {
@@ -2540,8 +2697,8 @@ static int edbm_blend_from_shape_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
-{
+static const EnumPropertyItem *shape_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+{
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em;
EnumPropertyItem *item = NULL;
@@ -2614,6 +2771,12 @@ void MESH_OT_blend_from_shape(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "add", true, "Add", "Add rather than blend between shapes");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Solidify Mesh Operator
+ * \{ */
+
static int edbm_solidify_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -2668,6 +2831,12 @@ void MESH_OT_solidify(wmOperatorType *ot)
RNA_def_property_ui_range(prop, -10.0, 10.0, 0.1, 4);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Knife Subdivide Operator
+ * \{ */
+
/* ******************************************************************** */
/* Knife Subdivide Tool. Subdivides edges intersected by a mouse trail
* drawn by user.
@@ -2692,7 +2861,7 @@ void MESH_OT_solidify(wmOperatorType *ot)
#define KNIFE_MIDPOINT 2
#define KNIFE_MULTICUT 3
-static EnumPropertyItem knife_items[] = {
+static const EnumPropertyItem knife_items[] = {
{KNIFE_EXACT, "EXACT", 0, "Exact", ""},
{KNIFE_MIDPOINT, "MIDPOINTS", 0, "Midpoints", ""},
{KNIFE_MULTICUT, "MULTICUT", 0, "Multicut", ""},
@@ -2701,8 +2870,9 @@ static EnumPropertyItem knife_items[] = {
/* bm_edge_seg_isect() Determines if and where a mouse trail intersects an BMEdge */
-static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
- float (*mouse_path)[2], int len, char mode, int *isected)
+static float bm_edge_seg_isect(
+ const float sco_a[2], const float sco_b[2],
+ float (*mouse_path)[2], int len, char mode, int *isected)
{
#define MAXSLOPE 100000
float x11, y11, x12 = 0, y12 = 0, x2max, x2min, y2max;
@@ -2711,17 +2881,17 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
float yi, x1min, x1max, y1max, y1min, perc = 0;
float threshold = 0.0;
int i;
-
+
//threshold = 0.000001; /* tolerance for vertex intersection */
// XXX threshold = scene->toolsettings->select_thresh / 100;
-
+
/* Get screen coords of verts */
x21 = sco_a[0];
y21 = sco_a[1];
-
+
x22 = sco_b[0];
y22 = sco_b[1];
-
+
xdiff2 = (x22 - x21);
if (xdiff2) {
m2 = (y22 - y21) / xdiff2;
@@ -2747,7 +2917,7 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
}
x12 = mouse_path[i][0];
y12 = mouse_path[i][1];
-
+
/* test e->v1 */
if ((x11 == x21 && y11 == y21) || (x12 == x21 && y12 == y21)) {
perc = 0;
@@ -2762,7 +2932,7 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
}
}
}
-
+
/* now check for edge intersect (may produce vertex intersection as well) */
for (i = 0; i < len; i++) {
if (i > 0) {
@@ -2775,14 +2945,14 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
}
x12 = mouse_path[i][0];
y12 = mouse_path[i][1];
-
+
/* Perp. Distance from point to line */
if (m2 != MAXSLOPE) dist = (y12 - m2 * x12 - b2); /* /sqrt(m2 * m2 + 1); Only looking for */
/* change in sign. Skip extra math */
else dist = x22 - x12;
-
+
if (i == 0) lastdist = dist;
-
+
/* if dist changes sign, and intersect point in edge's Bound Box */
if ((lastdist * dist) <= 0) {
xdiff1 = (x12 - x11); /* Equation of line between last 2 points */
@@ -2798,14 +2968,14 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
x2min = min_ff(x21, x22) - 0.001f; /* due to round off error */
y2max = max_ff(y21, y22) + 0.001f;
y2min = min_ff(y21, y22) - 0.001f;
-
+
/* Found an intersect, calc intersect point */
if (m1 == m2) { /* co-incident lines */
/* cut at 50% of overlap area */
x1max = max_ff(x11, x12);
x1min = min_ff(x11, x12);
xi = (min_ff(x2max, x1max) + max_ff(x2min, x1min)) / 2.0f;
-
+
y1max = max_ff(y11, y12);
y1min = min_ff(y11, y12);
yi = (min_ff(y2max, y1max) + max_ff(y2min, y1min)) / 2.0f;
@@ -2822,7 +2992,7 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
xi = (b1 - b2) / (m2 - m1);
yi = (b1 * m2 - m1 * b2) / (m2 - m1);
}
-
+
/* Intersect inside bounding box of edge?*/
if ((xi >= x2min) && (xi <= x2max) && (yi <= y2max) && (yi >= y2min)) {
/* test for vertex intersect that may be 'close enough'*/
@@ -2845,7 +3015,7 @@ static float bm_edge_seg_isect(const float sco_a[2], const float sco_b[2],
if ((m2 <= 1.0f) && (m2 >= -1.0f)) perc = (xi - x21) / (x22 - x21);
else perc = (yi - y21) / (y22 - y21); /* lower slope more accurate */
//isect = 32768.0 * (perc + 0.0000153); /* Percentage in 1 / 32768ths */
-
+
break;
}
}
@@ -2874,11 +3044,11 @@ static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
/* allocd vars */
float (*screen_vert_coords)[2], (*sco)[2], (*mouse_path)[2];
-
+
/* edit-object needed for matrix, and ar->regiondata for projections to work */
if (ELEM(NULL, obedit, ar, ar->regiondata))
return OPERATOR_CANCELLED;
-
+
if (bm->totvertsel < 2) {
BKE_report(op->reports, RPT_ERROR, "No edges are selected to operate on");
return OPERATOR_CANCELLED;
@@ -2963,7 +3133,7 @@ static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
BMO_slot_bool_set(bmop.slots_in, "use_grid_fill", false);
BMO_slot_float_set(bmop.slots_in, "radius", 0);
-
+
BMO_op_exec(bm, &bmop);
if (!EDBM_op_finish(em, &bmop, op, true)) {
return OPERATOR_CANCELLED;
@@ -2978,31 +3148,35 @@ static int edbm_knife_cut_exec(bContext *C, wmOperator *op)
void MESH_OT_knife_cut(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
ot->name = "Knife Cut";
ot->description = "Cut selected edges and faces into parts";
ot->idname = "MESH_OT_knife_cut";
-
+
ot->invoke = WM_gesture_lines_invoke;
ot->modal = WM_gesture_lines_modal;
ot->exec = edbm_knife_cut_exec;
-
+
ot->poll = EDBM_view3d_poll;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
+ /* properties */
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
RNA_def_enum(ot->srna, "type", knife_items, KNIFE_EXACT, "Type", "");
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
-
+
/* internal */
RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, BC_NUMCURSORS, "Cursor", "", 0, BC_NUMCURSORS);
}
+/** \} */
-/* *************** Operator: separate parts *************/
+/* -------------------------------------------------------------------- */
+/** \name Separate Parts Operator
+ * \{ */
enum {
MESH_SEPARATE_SELECTED = 0,
@@ -3053,7 +3227,7 @@ static Base *mesh_separate_tagged(Main *bmain, Scene *scene, Base *base_old, BMe
BM_mesh_free(bm_new);
((Mesh *)base_new->object->data)->edit_btmesh = NULL;
-
+
return base_new;
}
@@ -3281,7 +3455,7 @@ static int edbm_separate_exec(bContext *C, wmOperator *op)
Scene *scene = CTX_data_scene(C);
const int type = RNA_enum_get(op->ptr, "type");
int retval = 0;
-
+
if (ED_operator_editmesh(C)) {
Base *base = CTX_data_active_base(C);
BMEditMesh *em = BKE_editmesh_from_object(base->object);
@@ -3328,7 +3502,7 @@ static int edbm_separate_exec(bContext *C, wmOperator *op)
Object *ob = base_iter->object;
if (ob->type == OB_MESH) {
Mesh *me = ob->data;
- if (!ID_IS_LINKED_DATABLOCK(me)) {
+ if (!ID_IS_LINKED(me)) {
BMesh *bm_old = NULL;
int retval_iter = 0;
@@ -3351,7 +3525,11 @@ static int edbm_separate_exec(bContext *C, wmOperator *op)
}
if (retval_iter) {
- BM_mesh_bm_to_me(bm_old, me, (&(struct BMeshToMeshParams){0}));
+ BM_mesh_bm_to_me(
+ bm_old, me,
+ (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
DAG_id_tag_update(&me->id, OB_RECALC_DATA);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
@@ -3379,7 +3557,7 @@ static int edbm_separate_exec(bContext *C, wmOperator *op)
void MESH_OT_separate(wmOperatorType *ot)
{
- static EnumPropertyItem prop_separate_types[] = {
+ static const EnumPropertyItem prop_separate_types[] = {
{MESH_SEPARATE_SELECTED, "SELECTED", 0, "Selection", ""},
{MESH_SEPARATE_MATERIAL, "MATERIAL", 0, "By Material", ""},
{MESH_SEPARATE_LOOSE, "LOOSE", 0, "By loose parts", ""},
@@ -3390,18 +3568,23 @@ void MESH_OT_separate(wmOperatorType *ot)
ot->name = "Separate";
ot->description = "Separate selected geometry into a new mesh";
ot->idname = "MESH_OT_separate";
-
+
/* api callbacks */
ot->invoke = WM_menu_invoke;
ot->exec = edbm_separate_exec;
ot->poll = ED_operator_scene_editable; /* object and editmode */
-
+
/* flags */
ot->flag = OPTYPE_UNDO;
-
+
ot->prop = RNA_def_enum(ot->srna, "type", prop_separate_types, MESH_SEPARATE_SELECTED, "Type", "");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Triangle Fill Operator
+ * \{ */
static int edbm_fill_exec(bContext *C, wmOperator *op)
{
@@ -3423,9 +3606,9 @@ static int edbm_fill_exec(bContext *C, wmOperator *op)
{
return OPERATOR_CANCELLED;
}
-
+
BMO_op_exec(em->bm, &bmop);
-
+
if (totface_orig != em->bm->totface) {
/* select new geometry */
BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_FACE | BM_EDGE, BM_ELEM_SELECT, true);
@@ -3463,9 +3646,11 @@ void MESH_OT_fill(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_beauty", true, "Beauty", "Use best triangulation division");
}
+/** \} */
/* -------------------------------------------------------------------- */
-/* Grid Fill (and helper functions) */
+/** \name Grid Fill Operator
+ * \{ */
static bool bm_edge_test_fill_grid_cb(BMEdge *e, void *UNUSED(bm_v))
{
@@ -3561,7 +3746,7 @@ static void edbm_fill_grid_prepare(BMesh *bm, int offset, int *r_span, bool span
*
* note: we may have already checked 'edbm_fill_grid_vert_tag_angle()' on each
* vert, but advantage of de-duplicating is minimal. */
- struct SortPointerByFloat *ele_sort = MEM_mallocN(sizeof(*ele_sort) * verts_len, __func__);
+ struct SortPtrByFloat *ele_sort = MEM_mallocN(sizeof(*ele_sort) * verts_len, __func__);
LinkData *v_link;
for (v_link = verts->first, i = 0; v_link; v_link = v_link->next, i++) {
BMVert *v = v_link->data;
@@ -3656,10 +3841,11 @@ static int edbm_fill_grid_exec(bContext *C, wmOperator *op)
/* end tricky prepare code */
- if (!EDBM_op_init(em, &bmop, op,
- "grid_fill edges=%he mat_nr=%i use_smooth=%b use_interp_simple=%b",
- use_prepare ? BM_ELEM_TAG : BM_ELEM_SELECT,
- em->mat_nr, use_smooth, use_interp_simple))
+ if (!EDBM_op_init(
+ em, &bmop, op,
+ "grid_fill edges=%he mat_nr=%i use_smooth=%b use_interp_simple=%b",
+ use_prepare ? BM_ELEM_TAG : BM_ELEM_SELECT,
+ em->mat_nr, use_smooth, use_interp_simple))
{
return OPERATOR_CANCELLED;
}
@@ -3709,6 +3895,12 @@ void MESH_OT_fill_grid(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_interp_simple", false, "Simple Blending", "");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Hole Fill Operator
+ * \{ */
+
static int edbm_fill_holes_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3748,6 +3940,12 @@ void MESH_OT_fill_holes(wmOperatorType *ot)
"Sides", "Number of sides in hole required to fill (zero fills all holes)", 0, 100);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Beauty Fill Operator
+ * \{ */
+
static int edbm_beautify_fill_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -3765,9 +3963,10 @@ static int edbm_beautify_fill_exec(bContext *C, wmOperator *op)
BMEdge *e;
BM_ITER_MESH (e, &iter, em->bm, BM_EDGES_OF_MESH) {
- BM_elem_flag_set(e, BM_ELEM_TAG,
- (BM_elem_flag_test(e, BM_ELEM_SELECT) &&
- BM_edge_calc_face_angle_ex(e, angle_max) < angle_limit));
+ BM_elem_flag_set(
+ e, BM_ELEM_TAG,
+ (BM_elem_flag_test(e, BM_ELEM_SELECT) &&
+ BM_edge_calc_face_angle_ex(e, angle_max) < angle_limit));
}
@@ -3783,7 +3982,7 @@ static int edbm_beautify_fill_exec(bContext *C, wmOperator *op)
}
EDBM_update_generic(em, true, true);
-
+
return OPERATOR_FINISHED;
}
@@ -3809,8 +4008,11 @@ void MESH_OT_beautify_fill(wmOperatorType *ot)
RNA_def_property_float_default(prop, DEG2RADF(180.0f));
}
+/** \} */
-/********************** Poke Face **********************/
+/* -------------------------------------------------------------------- */
+/** \name Poke Face Operator
+ * \{ */
static int edbm_poke_face_exec(bContext *C, wmOperator *op)
{
@@ -3845,7 +4047,7 @@ static int edbm_poke_face_exec(bContext *C, wmOperator *op)
void MESH_OT_poke(wmOperatorType *ot)
{
- static EnumPropertyItem poke_center_modes[] = {
+ static const EnumPropertyItem poke_center_modes[] = {
{BMOP_POKE_MEAN_WEIGHTED, "MEAN_WEIGHTED", 0, "Weighted Mean", "Weighted Mean Face Center"},
{BMOP_POKE_MEAN, "MEAN", 0, "Mean", "Mean Face Center"},
{BMOP_POKE_BOUNDS, "BOUNDS", 0, "Bounds", "Face Bounds Center"},
@@ -3870,7 +4072,11 @@ void MESH_OT_poke(wmOperatorType *ot)
"Poke Center", "Poke Face Center Calculation");
}
-/********************** Quad/Tri Operators *************************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Triangulate Face Operator
+ * \{ */
static int edbm_quads_convert_to_tris_exec(bContext *C, wmOperator *op)
{
@@ -3925,6 +4131,12 @@ void MESH_OT_quads_convert_to_tris(wmOperatorType *ot)
"Polygon Method", "Method for splitting the polygons into triangles");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Convert to Quads Operator
+ * \{ */
+
static int edbm_tris_convert_to_quads_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -4015,10 +4227,10 @@ void MESH_OT_tris_convert_to_quads(wmOperatorType *ot)
join_triangle_props(ot);
}
+/** \} */
/* -------------------------------------------------------------------- */
-
-/** \name Decimate
+/** \name Decimate Operator
*
* \note The function to decimate is intended for use as a modifier,
* while its handy allow access as a tool - this does cause access to be a little awkward
@@ -4204,9 +4416,9 @@ void MESH_OT_decimate(wmOperatorType *ot)
/** \} */
-
/* -------------------------------------------------------------------- */
-/* Dissolve */
+/** \name Dissolve Vertices Operator
+ * \{ */
static void edbm_dissolve_prop__use_verts(wmOperatorType *ot, bool value, int flag)
{
@@ -4238,9 +4450,10 @@ static int edbm_dissolve_verts_exec(bContext *C, wmOperator *op)
const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split");
const bool use_boundary_tear = RNA_boolean_get(op->ptr, "use_boundary_tear");
- if (!EDBM_op_callf(em, op,
- "dissolve_verts verts=%hv use_face_split=%b use_boundary_tear=%b",
- BM_ELEM_SELECT, use_face_split, use_boundary_tear))
+ if (!EDBM_op_callf(
+ em, op,
+ "dissolve_verts verts=%hv use_face_split=%b use_boundary_tear=%b",
+ BM_ELEM_SELECT, use_face_split, use_boundary_tear))
{
return OPERATOR_CANCELLED;
}
@@ -4268,6 +4481,12 @@ void MESH_OT_dissolve_verts(wmOperatorType *ot)
edbm_dissolve_prop__use_boundary_tear(ot);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Dissolve Edges Operator
+ * \{ */
+
static int edbm_dissolve_edges_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -4276,9 +4495,10 @@ static int edbm_dissolve_edges_exec(bContext *C, wmOperator *op)
const bool use_verts = RNA_boolean_get(op->ptr, "use_verts");
const bool use_face_split = RNA_boolean_get(op->ptr, "use_face_split");
- if (!EDBM_op_callf(em, op,
- "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
- BM_ELEM_SELECT, use_verts, use_face_split))
+ if (!EDBM_op_callf(
+ em, op,
+ "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
+ BM_ELEM_SELECT, use_verts, use_face_split))
{
return OPERATOR_CANCELLED;
}
@@ -4306,6 +4526,12 @@ void MESH_OT_dissolve_edges(wmOperatorType *ot)
edbm_dissolve_prop__use_face_split(ot);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Dissolve Faces Operator
+ * \{ */
+
static int edbm_dissolve_faces_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -4344,6 +4570,11 @@ void MESH_OT_dissolve_faces(wmOperatorType *ot)
edbm_dissolve_prop__use_verts(ot, false, 0);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Dissolve (Context Sensitive) Operator
+ * \{ */
static int edbm_dissolve_mode_exec(bContext *C, wmOperator *op)
{
@@ -4389,6 +4620,12 @@ void MESH_OT_dissolve_mode(wmOperatorType *ot)
edbm_dissolve_prop__use_boundary_tear(ot);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Limited Dissolve Operator
+ * \{ */
+
static int edbm_dissolve_limited_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -4466,6 +4703,12 @@ void MESH_OT_dissolve_limited(wmOperatorType *ot)
"Delimit dissolve operation");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Degenerate Dissolve Operator
+ * \{ */
+
static int edbm_dissolve_degenerate_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -4510,6 +4753,11 @@ void MESH_OT_dissolve_degenerate(wmOperatorType *ot)
"Minimum distance between elements to merge", 1e-5f, 10.0f);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Delete Edge-Loop Operator
+ * \{ */
/* internally uses dissolve */
static int edbm_delete_edgeloop_exec(bContext *C, wmOperator *op)
@@ -4536,9 +4784,10 @@ static int edbm_delete_edgeloop_exec(bContext *C, wmOperator *op)
}
}
- if (!EDBM_op_callf(em, op,
- "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
- BM_ELEM_SELECT, true, use_face_split))
+ if (!EDBM_op_callf(
+ em, op,
+ "dissolve_edges edges=%he use_verts=%b use_face_split=%b",
+ BM_ELEM_SELECT, true, use_face_split))
{
return OPERATOR_CANCELLED;
}
@@ -4570,6 +4819,12 @@ void MESH_OT_delete_edgeloop(wmOperatorType *ot)
"Split off face corners to maintain surrounding geometry");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Split Geometry Operator
+ * \{ */
+
static int edbm_split_exec(bContext *C, wmOperator *op)
{
Object *ob = CTX_data_edit_object(C);
@@ -4607,16 +4862,21 @@ void MESH_OT_split(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/******************************************************************************
- * qsort routines.
- * Now unified, for vertices/edges/faces. */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Sort Geometry Elements Operator
+ *
+ * Unified for vertices/edges/faces.
+ *
+ * \{ */
enum {
SRT_VIEW_ZAXIS = 1, /* Use view Z (deep) axis. */
SRT_VIEW_XAXIS, /* Use view X (left to right) axis. */
SRT_CURSOR_DISTANCE, /* Use distance from element to 3D cursor. */
SRT_MATERIAL, /* Face only: use mat number. */
- SRT_SELECTED, /* Move selected elements in first, without modifying
+ SRT_SELECTED, /* Move selected elements in first, without modifying
* relative order of selected and unselected elements. */
SRT_RANDOMIZE, /* Randomize selected elements. */
SRT_REVERSE, /* Reverse current order of selected elements. */
@@ -4635,10 +4895,11 @@ static int bmelemsort_comp(const void *v1, const void *v2)
}
/* Reorders vertices/edges/faces using a given methods. Loops are not supported. */
-static void sort_bmelem_flag(Scene *scene, Object *ob,
- View3D *v3d, RegionView3D *rv3d,
- const int types, const int flag, const int action,
- const int reverse, const unsigned int seed)
+static void sort_bmelem_flag(
+ Scene *scene, Object *ob,
+ View3D *v3d, RegionView3D *rv3d,
+ const int types, const int flag, const int action,
+ const int reverse, const unsigned int seed)
{
BMEditMesh *em = BKE_editmesh_from_object(ob);
@@ -5104,8 +5365,9 @@ static int edbm_sort_elements_exec(bContext *C, wmOperator *op)
RNA_enum_set(op->ptr, "elements", elem_types);
}
- sort_bmelem_flag(scene, ob, v3d, rv3d,
- elem_types, BM_ELEM_SELECT, action, use_reverse, seed);
+ sort_bmelem_flag(
+ scene, ob, v3d, rv3d,
+ elem_types, BM_ELEM_SELECT, action, use_reverse, seed);
return OPERATOR_FINISHED;
}
@@ -5147,7 +5409,7 @@ static void edbm_sort_elements_ui(bContext *C, wmOperator *op)
void MESH_OT_sort_elements(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{SRT_VIEW_ZAXIS, "VIEW_ZAXIS", 0, "View Z Axis",
"Sort selected elements from farthest to nearest one in current view"},
{SRT_VIEW_XAXIS, "VIEW_XAXIS", 0, "View X Axis",
@@ -5164,7 +5426,7 @@ void MESH_OT_sort_elements(wmOperatorType *ot)
{0, NULL, 0, NULL, NULL},
};
- static EnumPropertyItem elem_items[] = {
+ static const EnumPropertyItem elem_items[] = {
{BM_VERT, "VERT", 0, "Vertices", ""},
{BM_EDGE, "EDGE", 0, "Edges", ""},
{BM_FACE, "FACE", 0, "Faces", ""},
@@ -5194,7 +5456,11 @@ void MESH_OT_sort_elements(wmOperatorType *ot)
RNA_def_int(ot->srna, "seed", 0, 0, INT_MAX, "Seed", "Seed for random-based operations", 0, 255);
}
-/****** end of qsort stuff ****/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Noise (Deform Vertices) Operator
+ * \{ */
static int edbm_noise_exec(bContext *C, wmOperator *op)
{
@@ -5227,7 +5493,7 @@ static int edbm_noise_exec(bContext *C, wmOperator *op)
vec[0] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0] + ofs, eve->co[1], eve->co[2]));
vec[1] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1] + ofs, eve->co[2]));
vec[2] = fac * (b2 - BLI_hnoise(tex->noisesize, eve->co[0], eve->co[1], eve->co[2] + ofs));
-
+
add_v3_v3(eve->co, vec);
}
}
@@ -5235,8 +5501,10 @@ static int edbm_noise_exec(bContext *C, wmOperator *op)
else {
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
- float tin, dum;
- externtex(ma->mtex[0], eve->co, &tin, &dum, &dum, &dum, &dum, 0, NULL, false, false);
+ float tin = 0.0f, dum;
+ if (ma->mtex[ma->texact] != NULL) {
+ externtex(ma->mtex[ma->texact], eve->co, &tin, &dum, &dum, &dum, &dum, 0, NULL, false, false);
+ }
eve->co[2] += fac * tin;
}
}
@@ -5266,6 +5534,11 @@ void MESH_OT_noise(wmOperatorType *ot)
RNA_def_float(ot->srna, "factor", 0.1f, -1e4f, 1e4f, "Factor", "", 0.0f, 1.0f);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Bridge Operator
+ * \{ */
enum {
MESH_BRIDGELOOP_SINGLE = 0,
@@ -5352,9 +5625,10 @@ static int edbm_bridge_edge_loops_exec(bContext *C, wmOperator *op)
edge_hflag = BM_ELEM_SELECT;
}
- EDBM_op_init(em, &bmop, op,
- "bridge_loops edges=%he use_pairs=%b use_cyclic=%b use_merge=%b merge_factor=%f twist_offset=%i",
- edge_hflag, use_pairs, use_cyclic, use_merge, merge_factor, twist_offset);
+ EDBM_op_init(
+ em, &bmop, op,
+ "bridge_loops edges=%he use_pairs=%b use_cyclic=%b use_merge=%b merge_factor=%f twist_offset=%i",
+ edge_hflag, use_pairs, use_cyclic, use_merge, merge_factor, twist_offset);
if (use_faces && totface_del) {
int i;
@@ -5362,9 +5636,10 @@ static int edbm_bridge_edge_loops_exec(bContext *C, wmOperator *op)
for (i = 0; i < totface_del; i++) {
BM_elem_flag_enable(totface_del_arr[i], BM_ELEM_TAG);
}
- BMO_op_callf(em->bm, BMO_FLAG_DEFAULTS,
- "delete geom=%hf context=%i",
- BM_ELEM_TAG, DEL_FACES_KEEP_BOUNDARY);
+ BMO_op_callf(
+ em->bm, BMO_FLAG_DEFAULTS,
+ "delete geom=%hf context=%i",
+ BM_ELEM_TAG, DEL_FACES_KEEP_BOUNDARY);
}
BMO_op_exec(em->bm, &bmop);
@@ -5419,7 +5694,7 @@ static int edbm_bridge_edge_loops_exec(bContext *C, wmOperator *op)
void MESH_OT_bridge_edge_loops(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{MESH_BRIDGELOOP_SINGLE, "SINGLE", 0, "Open Loop", ""},
{MESH_BRIDGELOOP_CLOSED, "CLOSED", 0, "Closed Loop", ""},
{MESH_BRIDGELOOP_PAIRS, "PAIRS", 0, "Loop Pairs", ""},
@@ -5430,11 +5705,11 @@ void MESH_OT_bridge_edge_loops(wmOperatorType *ot)
ot->name = "Bridge Edge Loops";
ot->description = "Make faces between two or more edge loops";
ot->idname = "MESH_OT_bridge_edge_loops";
-
+
/* api callbacks */
ot->exec = edbm_bridge_edge_loops_exec;
ot->poll = ED_operator_editmesh;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -5445,9 +5720,15 @@ void MESH_OT_bridge_edge_loops(wmOperatorType *ot)
RNA_def_float(ot->srna, "merge_factor", 0.5f, 0.0f, 1.0f, "Merge Factor", "", 0.0f, 1.0f);
RNA_def_int(ot->srna, "twist_offset", 0, -1000, 1000, "Twist", "Twist offset for closed loops", -1000, 1000);
- mesh_operator_edgering_props(ot, 0);
+ mesh_operator_edgering_props(ot, 0, 0);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Wire-Frame Operator
+ * \{ */
+
static int edbm_wireframe_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -5462,11 +5743,12 @@ static int edbm_wireframe_exec(bContext *C, wmOperator *op)
const float thickness = RNA_float_get(op->ptr, "thickness");
const float offset = RNA_float_get(op->ptr, "offset");
- EDBM_op_init(em, &bmop, op,
- "wireframe faces=%hf use_replace=%b use_boundary=%b use_even_offset=%b use_relative_offset=%b "
- "use_crease=%b crease_weight=%f thickness=%f offset=%f",
- BM_ELEM_SELECT, use_replace, use_boundary, use_even_offset, use_relative_offset,
- use_crease, crease_weight, thickness, offset);
+ EDBM_op_init(
+ em, &bmop, op,
+ "wireframe faces=%hf use_replace=%b use_boundary=%b use_even_offset=%b use_relative_offset=%b "
+ "use_crease=%b crease_weight=%f thickness=%f offset=%f",
+ BM_ELEM_SELECT, use_replace, use_boundary, use_even_offset, use_relative_offset,
+ use_crease, crease_weight, thickness, offset);
BMO_op_exec(em->bm, &bmop);
@@ -5512,6 +5794,12 @@ void MESH_OT_wireframe(wmOperatorType *ot)
RNA_def_property_ui_range(prop, 0.0, 1.0, 0.1, 2);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Offset Edge-Loop Operator
+ * \{ */
+
static int edbm_offset_edgeloop_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -5566,6 +5854,12 @@ void MESH_OT_offset_edge_loops(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "use_cap_endpoint", false, "Cap Endpoint", "Extend loop around end-points");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Convex Hull Operator
+ * \{ */
+
#ifdef WITH_BULLET
static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
{
@@ -5573,10 +5867,11 @@ static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
BMEditMesh *em = BKE_editmesh_from_object(obedit);
BMOperator bmop;
- EDBM_op_init(em, &bmop, op, "convex_hull input=%hvef "
- "use_existing_faces=%b",
- BM_ELEM_SELECT,
- RNA_boolean_get(op->ptr, "use_existing_faces"));
+ EDBM_op_init(
+ em, &bmop, op, "convex_hull input=%hvef "
+ "use_existing_faces=%b",
+ BM_ELEM_SELECT,
+ RNA_boolean_get(op->ptr, "use_existing_faces"));
BMO_op_exec(em->bm, &bmop);
/* Hull fails if input is coplanar */
@@ -5589,8 +5884,9 @@ static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
/* Delete unused vertices, edges, and faces */
if (RNA_boolean_get(op->ptr, "delete_unused")) {
- if (!EDBM_op_callf(em, op, "delete geom=%S context=%i",
- &bmop, "geom_unused.out", DEL_ONLYTAGGED))
+ if (!EDBM_op_callf(
+ em, op, "delete geom=%S context=%i",
+ &bmop, "geom_unused.out", DEL_ONLYTAGGED))
{
EDBM_op_finish(em, &bmop, op, true);
return OPERATOR_CANCELLED;
@@ -5599,8 +5895,9 @@ static int edbm_convex_hull_exec(bContext *C, wmOperator *op)
/* Delete hole edges/faces */
if (RNA_boolean_get(op->ptr, "make_holes")) {
- if (!EDBM_op_callf(em, op, "delete geom=%S context=%i",
- &bmop, "geom_holes.out", DEL_ONLYTAGGED))
+ if (!EDBM_op_callf(
+ em, op, "delete geom=%S context=%i",
+ &bmop, "geom_holes.out", DEL_ONLYTAGGED))
{
EDBM_op_finish(em, &bmop, op, true);
return OPERATOR_CANCELLED;
@@ -5668,7 +5965,13 @@ void MESH_OT_convex_hull(wmOperatorType *ot)
join_triangle_props(ot);
}
-#endif
+#endif /* WITH_BULLET */
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Symmetrize Operator
+ * \{ */
static int mesh_symmetrize_exec(bContext *C, wmOperator *op)
{
@@ -5678,9 +5981,10 @@ static int mesh_symmetrize_exec(bContext *C, wmOperator *op)
const float thresh = RNA_float_get(op->ptr, "threshold");
- EDBM_op_init(em, &bmop, op,
- "symmetrize input=%hvef direction=%i dist=%f",
- BM_ELEM_SELECT, RNA_enum_get(op->ptr, "direction"), thresh);
+ EDBM_op_init(
+ em, &bmop, op,
+ "symmetrize input=%hvef direction=%i dist=%f",
+ BM_ELEM_SELECT, RNA_enum_get(op->ptr, "direction"), thresh);
BMO_op_exec(em->bm, &bmop);
EDBM_flag_disable_all(em, BM_ELEM_SELECT);
@@ -5711,12 +6015,19 @@ void MESH_OT_symmetrize(struct wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- ot->prop = RNA_def_enum(ot->srna, "direction", rna_enum_symmetrize_direction_items,
- BMO_SYMMETRIZE_NEGATIVE_X,
- "Direction", "Which sides to copy from and to");
+ ot->prop = RNA_def_enum(
+ ot->srna, "direction", rna_enum_symmetrize_direction_items,
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ "Direction", "Which sides to copy from and to");
RNA_def_float(ot->srna, "threshold", 1e-4f, 0.0f, 10.0f, "Threshold", "", 1e-5f, 0.1f);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Snap to Symmetry Operator
+ * \{ */
+
static int mesh_symmetry_snap_exec(bContext *C, wmOperator *op)
{
const float eps = 0.00001f;
@@ -5835,16 +6146,23 @@ void MESH_OT_symmetry_snap(struct wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- ot->prop = RNA_def_enum(ot->srna, "direction", rna_enum_symmetrize_direction_items,
- BMO_SYMMETRIZE_NEGATIVE_X,
- "Direction", "Which sides to copy from and to");
+ ot->prop = RNA_def_enum(
+ ot->srna, "direction", rna_enum_symmetrize_direction_items,
+ BMO_SYMMETRIZE_NEGATIVE_X,
+ "Direction", "Which sides to copy from and to");
RNA_def_float_distance(ot->srna, "threshold", 0.05f, 0.0f, 10.0f, "Threshold", "", 1e-4f, 1.0f);
RNA_def_float(ot->srna, "factor", 0.5f, 0.0f, 1.0f, "Factor", "", 0.0f, 1.0f);
RNA_def_boolean(ot->srna, "use_center", true, "Center", "Snap mid verts to the axis center");
}
+/** \} */
+
#ifdef WITH_FREESTYLE
+/* -------------------------------------------------------------------- */
+/** \name Mark Edge (FreeStyle) Operator
+ * \{ */
+
static int edbm_mark_freestyle_edge_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -5910,6 +6228,12 @@ void MESH_OT_mark_freestyle_edge(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mark Face (FreeStyle) Operator
+ * \{ */
+
static int edbm_mark_freestyle_face_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
@@ -5974,4 +6298,6 @@ void MESH_OT_mark_freestyle_face(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-#endif
+/** \} */
+
+#endif /* WITH_FREESTYLE */
diff --git a/source/blender/editors/mesh/editmesh_undo.c b/source/blender/editors/mesh/editmesh_undo.c
index 534ca22178e..50aecd0a821 100644
--- a/source/blender/editors/mesh/editmesh_undo.c
+++ b/source/blender/editors/mesh/editmesh_undo.c
@@ -29,16 +29,24 @@
#include "DNA_key_types.h"
#include "BLI_listbase.h"
+#include "BLI_array_utils.h"
+#include "BLI_alloca.h"
#include "BKE_DerivedMesh.h"
#include "BKE_context.h"
#include "BKE_key.h"
#include "BKE_mesh.h"
#include "BKE_editmesh.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+#include "ED_object.h"
#include "ED_mesh.h"
#include "ED_util.h"
+#include "WM_types.h"
+#include "WM_api.h"
+
#define USE_ARRAY_STORE
#ifdef USE_ARRAY_STORE
@@ -60,6 +68,9 @@
# include "BLI_task.h"
#endif
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
#ifdef USE_ARRAY_STORE
@@ -95,6 +106,8 @@ typedef struct UndoMesh {
BArrayState *mselect;
} store;
#endif /* USE_ARRAY_STORE */
+
+ size_t undo_size;
} UndoMesh;
@@ -247,7 +260,7 @@ static void um_arraystore_cd_free(BArrayCustomData *bcd)
BArrayCustomData *bcd_next = bcd->next;
const int stride = CustomData_sizeof(bcd->type);
BArrayStore *bs = BLI_array_store_at_size_get(&um_arraystore.bs_stride, stride);
- for (int i = 0; i < bcd->states_len; i++) {
+ for (int i = 0; i < bcd->states_len; i++) {
if (bcd->states[i]) {
BLI_array_store_state_remove(bs, bcd->states[i]);
}
@@ -474,28 +487,24 @@ static void um_arraystore_free(UndoMesh *um)
/* for callbacks */
/* undo simply makes copies of a bmesh */
-static void *editbtMesh_to_undoMesh(void *emv, void *obdata)
+static void *undomesh_from_editmesh(UndoMesh *um, BMEditMesh *em, Key *key)
{
-
+ BLI_assert(BLI_array_is_zeroed(um, 1));
#ifdef USE_ARRAY_STORE_THREAD
/* changes this waits is low, but must have finished */
if (um_arraystore.task_pool) {
BLI_task_pool_work_and_wait(um_arraystore.task_pool);
}
#endif
-
- BMEditMesh *em = emv;
- Mesh *obme = obdata;
-
- UndoMesh *um = MEM_callocN(sizeof(UndoMesh), "undo Mesh");
-
/* make sure shape keys work */
- um->me.key = obme->key ? BKE_key_copy_nolib(obme->key) : NULL;
+ um->me.key = key ? BKE_key_copy_nolib(key) : NULL;
/* BM_mesh_validate(em->bm); */ /* for troubleshooting */
BM_mesh_bm_to_me(
em->bm, &um->me, (&(struct BMeshToMeshParams){
+ /* Undo code should not be manipulating 'G.main->object' hooks/vertex-parent. */
+ .calc_object_remap = false,
.cd_mask_extra = CD_MASK_SHAPE_KEYINDEX,
}));
@@ -534,13 +543,12 @@ static void *editbtMesh_to_undoMesh(void *emv, void *obdata)
return um;
}
-static void undoMesh_to_editbtMesh(void *um_v, void *em_v, void *obdata)
+static void undomesh_to_editmesh(UndoMesh *um, BMEditMesh *em, Mesh *obmesh)
{
- BMEditMesh *em = em_v, *em_tmp;
+ BMEditMesh *em_tmp;
Object *ob = em->ob;
- UndoMesh *um = um_v;
BMesh *bm;
- Key *key = ((Mesh *) obdata)->key;
+ Key *key = obmesh->key;
#ifdef USE_ARRAY_STORE
#ifdef USE_ARRAY_STORE_THREAD
@@ -613,9 +621,8 @@ static void undoMesh_to_editbtMesh(void *um_v, void *em_v, void *obdata)
#endif
}
-static void free_undo(void *um_v)
+static void undomesh_free_data(UndoMesh *um)
{
- UndoMesh *um = um_v;
Mesh *me = &um->me;
#ifdef USE_ARRAY_STORE
@@ -642,28 +649,165 @@ static void free_undo(void *um_v)
}
BKE_mesh_free(me);
- MEM_freeN(me);
}
-static void *getEditMesh(bContext *C)
+static Object *editmesh_object_from_context(bContext *C)
{
Object *obedit = CTX_data_edit_object(C);
if (obedit && obedit->type == OB_MESH) {
Mesh *me = obedit->data;
- return me->edit_btmesh;
+ if (me->edit_btmesh != NULL) {
+ return obedit;
+ }
}
return NULL;
}
-/* and this is all the undo system needs to know */
-void undo_push_mesh(bContext *C, const char *name)
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct MeshUndoStep {
+ UndoStep step;
+ /* Use for all ID lookups (can be NULL). */
+ struct UndoIDPtrMap *id_map;
+
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ /* Needed for MTexPoly's image use. */
+ UndoRefID_Object *image_array_ref;
+ UndoMesh data;
+} MeshUndoStep;
+
+static void mesh_undosys_step_encode_store_ids(MeshUndoStep *us)
{
- /* em->ob gets out of date and crashes on mesh undo,
- * this is an easy way to ensure its OK
- * though we could investigate the matter further. */
- Object *obedit = CTX_data_edit_object(C);
- BMEditMesh *em = BKE_editmesh_from_object(obedit);
- em->ob = obedit;
+ Mesh *me = us->obedit_ref.ptr->data;
+ BMesh *bm = me->edit_btmesh->bm;
+ const int mtex_len = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ if (mtex_len != 0) {
+ ID **id_prev_array = BLI_array_alloca(id_prev_array, mtex_len);
+ memset(id_prev_array, 0x0, sizeof(*id_prev_array) * mtex_len);
+
+ BMIter iter;
+ BMFace *efa;
+
+ if (us->id_map == NULL) {
+ us->id_map = BKE_undosys_ID_map_create();
+ }
+
+ uint cd_poly_tex_offset_first = CustomData_get_n_offset(&bm->pdata, CD_MTEXPOLY, 0);
+ uint cd_poly_tex_offset_end = cd_poly_tex_offset_first + (sizeof(MTexPoly) * mtex_len);
+ BM_ITER_MESH(efa, &iter, bm, BM_FACES_OF_MESH) {
+ for (uint cd_poly_tex_offset = cd_poly_tex_offset_first, i = 0;
+ cd_poly_tex_offset < cd_poly_tex_offset_end;
+ cd_poly_tex_offset += sizeof(MTexPoly), i++)
+ {
+ const MTexPoly *tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
+ if (tf->tpage != NULL) {
+ BKE_undosys_ID_map_add_with_prev(us->id_map, (ID *)tf->tpage, &id_prev_array[i]);
+ }
+ }
+ }
+ }
+}
+
+static void mesh_undosys_step_decode_restore_ids(MeshUndoStep *us)
+{
+ Mesh *me = us->obedit_ref.ptr->data;
+ BMesh *bm = me->edit_btmesh->bm;
+ const int mtex_len = CustomData_number_of_layers(&bm->pdata, CD_MTEXPOLY);
+ if (mtex_len != 0 && us->id_map) {
+ BMIter iter;
+ BMFace *efa;
+
+ ID *(*id_prev_array)[2] = BLI_array_alloca(id_prev_array, mtex_len);
+ memset(id_prev_array, 0x0, sizeof(*id_prev_array) * mtex_len);
+
+ uint cd_poly_tex_offset_first = CustomData_get_n_offset(&bm->pdata, CD_MTEXPOLY, 0);
+ uint cd_poly_tex_offset_end = cd_poly_tex_offset_first + (sizeof(MTexPoly) * mtex_len);
+ BM_ITER_MESH(efa, &iter, bm, BM_FACES_OF_MESH) {
+ for (uint cd_poly_tex_offset = cd_poly_tex_offset_first, i = 0;
+ cd_poly_tex_offset < cd_poly_tex_offset_end;
+ cd_poly_tex_offset += sizeof(MTexPoly), i++)
+ {
+ MTexPoly *tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
+ if (tf->tpage != NULL) {
+ tf->tpage = (Image *)BKE_undosys_ID_map_lookup_with_prev(us->id_map, (ID *)tf->tpage, id_prev_array[i]);
+ }
+ }
+ }
+ }
+}
+
+static bool mesh_undosys_poll(bContext *C)
+{
+ return editmesh_object_from_context(C) != NULL;
+}
+
+static bool mesh_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ MeshUndoStep *us = (MeshUndoStep *)us_p;
+ us->obedit_ref.ptr = editmesh_object_from_context(C);
+ Mesh *me = us->obedit_ref.ptr->data;
+ undomesh_from_editmesh(&us->data, me->edit_btmesh, me->key);
+ mesh_undosys_step_encode_store_ids(us);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
- undo_editmode_push(C, name, getEditMesh, free_undo, undoMesh_to_editbtMesh, editbtMesh_to_undoMesh, NULL);
+static void mesh_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_EDIT);
+ BLI_assert(mesh_undosys_poll(C));
+
+ MeshUndoStep *us = (MeshUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ Mesh *me = obedit->data;
+ BMEditMesh *em = me->edit_btmesh;
+ undomesh_to_editmesh(&us->data, em, obedit->data);
+ mesh_undosys_step_decode_restore_ids(us);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
}
+
+static void mesh_undosys_step_free(UndoStep *us_p)
+{
+ MeshUndoStep *us = (MeshUndoStep *)us_p;
+ undomesh_free_data(&us->data);
+
+ if (us->id_map != NULL) {
+ BKE_undosys_ID_map_destroy(us->id_map);
+ }
+}
+
+static void mesh_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ MeshUndoStep *us = (MeshUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
+ if (us->id_map != NULL) {
+ BKE_undosys_ID_map_foreach_ID_ref(us->id_map, foreach_ID_ref_fn, user_data);
+ }
+}
+
+/* Export for ED_undo_sys. */
+void ED_mesh_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Mesh";
+ ut->poll = mesh_undosys_poll;
+ ut->step_encode = mesh_undosys_step_encode;
+ ut->step_decode = mesh_undosys_step_decode;
+ ut->step_free = mesh_undosys_step_free;
+
+ ut->step_foreach_ID_ref = mesh_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(MeshUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/mesh/editmesh_utils.c b/source/blender/editors/mesh/editmesh_utils.c
index 438c3acdb11..41e8a963383 100644
--- a/source/blender/editors/mesh/editmesh_utils.c
+++ b/source/blender/editors/mesh/editmesh_utils.c
@@ -43,16 +43,14 @@
#include "BKE_DerivedMesh.h"
#include "BKE_context.h"
-#include "BKE_global.h"
#include "BKE_depsgraph.h"
-#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
#include "BKE_report.h"
#include "BKE_editmesh.h"
#include "BKE_editmesh_bvh.h"
-#include "BKE_object.h" /* XXX. only for EDBM_mesh_ensure_valid_dm_hack() which will be removed */
+#include "BKE_object.h" /* XXX. only for EDBM_mesh_load(). */
#include "WM_api.h"
#include "WM_types.h"
@@ -63,8 +61,14 @@
#include "mesh_intern.h" /* own include */
-/* mesh backup implementation. This would greatly benefit from some sort of binary diffing
- * just as the undo stack would. So leaving this as an interface for further work */
+/* -------------------------------------------------------------------- */
+/** \name Redo API
+ * \{ */
+
+/* Mesh backup implementation.
+ * This would greatly benefit from some sort of binary diffing
+ * just as the undo stack would.
+ * So leaving this as an interface for further work */
BMBackup EDBM_redo_state_store(BMEditMesh *em)
{
@@ -76,8 +80,9 @@ BMBackup EDBM_redo_state_store(BMEditMesh *em)
void EDBM_redo_state_restore(BMBackup backup, BMEditMesh *em, int recalctess)
{
BMesh *tmpbm;
- if (!em || !backup.bmcopy)
+ if (!em || !backup.bmcopy) {
return;
+ }
BM_mesh_data_free(em->bm);
tmpbm = BM_mesh_copy(backup.bmcopy);
@@ -85,8 +90,9 @@ void EDBM_redo_state_restore(BMBackup backup, BMEditMesh *em, int recalctess)
MEM_freeN(tmpbm);
tmpbm = NULL;
- if (recalctess)
+ if (recalctess) {
BKE_editmesh_tessface_calc(em);
+ }
}
void EDBM_redo_state_free(BMBackup *backup, BMEditMesh *em, int recalctess)
@@ -99,83 +105,21 @@ void EDBM_redo_state_free(BMBackup *backup, BMEditMesh *em, int recalctess)
BM_mesh_data_free(backup->bmcopy);
}
- if (backup->bmcopy)
+ if (backup->bmcopy) {
MEM_freeN(backup->bmcopy);
+ }
backup->bmcopy = NULL;
- if (recalctess && em)
+ if (recalctess && em) {
BKE_editmesh_tessface_calc(em);
-}
-
-/* hack to workaround multiple operators being called within the same event loop without an update
- * see: [#31811] */
-void EDBM_mesh_ensure_valid_dm_hack(Scene *scene, BMEditMesh *em)
-{
- if ((((ID *)em->ob->data)->tag & LIB_TAG_ID_RECALC) ||
- (em->ob->recalc & OB_RECALC_DATA))
- {
- /* since we may not have done selection flushing */
- if ((em->ob->recalc & OB_RECALC_DATA) == 0) {
- DAG_id_tag_update(&em->ob->id, OB_RECALC_DATA);
- }
- BKE_object_handle_update(G.main->eval_ctx, scene, em->ob);
- }
-}
-
-void EDBM_mesh_normals_update(BMEditMesh *em)
-{
- BM_mesh_normals_update(em->bm);
-}
-
-void EDBM_mesh_clear(BMEditMesh *em)
-{
- /* clear bmesh */
- BM_mesh_clear(em->bm);
-
- /* free derived meshes */
- BKE_editmesh_free_derivedmesh(em);
-
- /* free tessellation data */
- em->tottri = 0;
- if (em->looptris) {
- MEM_freeN(em->looptris);
- em->looptris = NULL;
}
}
-void EDBM_stats_update(BMEditMesh *em)
-{
- const char iter_types[3] = {BM_VERTS_OF_MESH,
- BM_EDGES_OF_MESH,
- BM_FACES_OF_MESH};
-
- BMIter iter;
- BMElem *ele;
- int *tots[3];
- int i;
-
- tots[0] = &em->bm->totvertsel;
- tots[1] = &em->bm->totedgesel;
- tots[2] = &em->bm->totfacesel;
-
- em->bm->totvertsel = em->bm->totedgesel = em->bm->totfacesel = 0;
-
- for (i = 0; i < 3; i++) {
- ele = BM_iter_new(&iter, em->bm, iter_types[i], NULL);
- for ( ; ele; ele = BM_iter_step(&iter)) {
- if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
- (*tots[i])++;
- }
- }
- }
-}
+/** \} */
-DerivedMesh *EDBM_mesh_deform_dm_get(BMEditMesh *em)
-{
- return ((em->derivedFinal != NULL) &&
- (em->derivedFinal->type == DM_TYPE_EDITBMESH) &&
- (em->derivedFinal->deformedOnly != false)) ? em->derivedFinal : NULL;
-}
+/* -------------------------------------------------------------------- */
+/** \name BMesh Operator (BMO) API Wrapper
+ * \{ */
bool EDBM_op_init(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const char *fmt, ...)
{
@@ -189,9 +133,10 @@ bool EDBM_op_init(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const char *
va_end(list);
return false;
}
-
- if (!em->emcopy)
+
+ if (!em->emcopy) {
em->emcopy = BKE_editmesh_copy(em);
+ }
em->emcopyusers++;
va_end(list);
@@ -199,12 +144,11 @@ bool EDBM_op_init(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const char *
return true;
}
-
/* returns 0 on error, 1 on success. executes and finishes a bmesh operator */
bool EDBM_op_finish(BMEditMesh *em, BMOperator *bmop, wmOperator *op, const bool do_report)
{
const char *errmsg;
-
+
BMO_op_finish(em->bm, bmop);
if (BMO_error_get(em->bm, &errmsg, NULL)) {
@@ -259,8 +203,9 @@ bool EDBM_op_callf(BMEditMesh *em, wmOperator *op, const char *fmt, ...)
return false;
}
- if (!em->emcopy)
+ if (!em->emcopy) {
em->emcopy = BKE_editmesh_copy(em);
+ }
em->emcopyusers++;
BMO_op_exec(bm, &bmop);
@@ -269,9 +214,10 @@ bool EDBM_op_callf(BMEditMesh *em, wmOperator *op, const char *fmt, ...)
return EDBM_op_finish(em, &bmop, op, true);
}
-bool EDBM_op_call_and_selectf(BMEditMesh *em, wmOperator *op,
- const char *select_slot_out, const bool select_extend,
- const char *fmt, ...)
+bool EDBM_op_call_and_selectf(
+ BMEditMesh *em, wmOperator *op,
+ const char *select_slot_out, const bool select_extend,
+ const char *fmt, ...)
{
BMOpSlot *slot_select_out;
BMesh *bm = em->bm;
@@ -287,8 +233,9 @@ bool EDBM_op_call_and_selectf(BMEditMesh *em, wmOperator *op,
return false;
}
- if (!em->emcopy)
+ if (!em->emcopy) {
em->emcopy = BKE_editmesh_copy(em);
+ }
em->emcopyusers++;
BMO_op_exec(bm, &bmop);
@@ -320,8 +267,9 @@ bool EDBM_op_call_silentf(BMEditMesh *em, const char *fmt, ...)
return false;
}
- if (!em->emcopy)
+ if (!em->emcopy) {
em->emcopy = BKE_editmesh_copy(em);
+ }
em->emcopyusers++;
BMO_op_exec(bm, &bmop);
@@ -330,22 +278,15 @@ bool EDBM_op_call_silentf(BMEditMesh *em, const char *fmt, ...)
return EDBM_op_finish(em, &bmop, NULL, false);
}
-void EDBM_selectmode_to_scene(bContext *C)
-{
- Scene *scene = CTX_data_scene(C);
- Object *obedit = CTX_data_edit_object(C);
- BMEditMesh *em = BKE_editmesh_from_object(obedit);
-
- if (!em)
- return;
+/** \} */
- scene->toolsettings->selectmode = em->selectmode;
-
- /* Request redraw of header buttons (to show new select mode) */
- WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, scene);
-}
+/* -------------------------------------------------------------------- */
+/** \name Edit BMesh API
+ *
+ * Make/Clear/Free functions.
+ * \{ */
-void EDBM_mesh_make(ToolSettings *ts, Object *ob, const bool add_key_index)
+void EDBM_mesh_make(Object *ob, const int select_mode, const bool add_key_index)
{
Mesh *me = ob->data;
BMesh *bm;
@@ -372,7 +313,7 @@ void EDBM_mesh_make(ToolSettings *ts, Object *ob, const bool add_key_index)
me->edit_btmesh = BKE_editmesh_create(bm, false);
#endif
- me->edit_btmesh->selectmode = me->edit_btmesh->bm->selectmode = ts->selectmode;
+ me->edit_btmesh->selectmode = me->edit_btmesh->bm->selectmode = select_mode;
me->edit_btmesh->mat_nr = (ob->actcol > 0) ? ob->actcol - 1 : 0;
me->edit_btmesh->ob = ob;
@@ -395,7 +336,10 @@ void EDBM_mesh_load(Object *ob)
bm->shapenr = 1;
}
- BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){0}));
+ BM_mesh_bm_to_me(
+ bm, me, (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
#ifdef USE_TESSFACE_DEFAULT
BKE_mesh_tessface_calc(me);
@@ -412,6 +356,7 @@ void EDBM_mesh_load(Object *ob)
* of freed data on scene update, especially in cases when there are dependency
* cycles.
*/
+#if 0
for (Object *other_object = G.main->object.first;
other_object != NULL;
other_object = other_object->id.next)
@@ -420,6 +365,23 @@ void EDBM_mesh_load(Object *ob)
BKE_object_free_derived_caches(other_object);
}
}
+#endif
+}
+
+void EDBM_mesh_clear(BMEditMesh *em)
+{
+ /* clear bmesh */
+ BM_mesh_clear(em->bm);
+
+ /* free derived meshes */
+ BKE_editmesh_free_derivedmesh(em);
+
+ /* free tessellation data */
+ em->tottri = 0;
+ if (em->looptris) {
+ MEM_freeN(em->looptris);
+ em->looptris = NULL;
+ }
}
/**
@@ -436,6 +398,28 @@ void EDBM_mesh_free(BMEditMesh *em)
BKE_editmesh_free(em);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Selection Utilities
+ * \{ */
+
+void EDBM_selectmode_to_scene(bContext *C)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *obedit = CTX_data_edit_object(C);
+ BMEditMesh *em = BKE_editmesh_from_object(obedit);
+
+ if (!em) {
+ return;
+ }
+
+ scene->toolsettings->selectmode = em->selectmode;
+
+ /* Request redraw of header buttons (to show new select mode) */
+ WM_event_add_notifier(C, NC_SCENE | ND_TOOLSETTINGS, scene);
+}
+
void EDBM_selectmode_flush_ex(BMEditMesh *em, const short selectmode)
{
BM_mesh_select_mode_flush_ex(em->bm, selectmode);
@@ -453,7 +437,6 @@ void EDBM_deselect_flush(BMEditMesh *em)
BM_mesh_deselect_flush(em->bm);
}
-
void EDBM_select_flush(BMEditMesh *em)
{
/* function below doesnt use. just do this to keep the values in sync */
@@ -466,9 +449,10 @@ void EDBM_select_more(BMEditMesh *em, const bool use_face_step)
BMOperator bmop;
const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
- BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
- "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
- BM_ELEM_SELECT, false, use_faces, use_face_step);
+ BMO_op_initf(
+ em->bm, &bmop, BMO_FLAG_DEFAULTS,
+ "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
+ BM_ELEM_SELECT, false, use_faces, use_face_step);
BMO_op_exec(em->bm, &bmop);
/* don't flush selection in edge/vertex mode */
BMO_slot_buffer_hflag_enable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
@@ -482,9 +466,10 @@ void EDBM_select_less(BMEditMesh *em, const bool use_face_step)
BMOperator bmop;
const bool use_faces = (em->selectmode == SCE_SELECT_FACE);
- BMO_op_initf(em->bm, &bmop, BMO_FLAG_DEFAULTS,
- "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
- BM_ELEM_SELECT, true, use_faces, use_face_step);
+ BMO_op_initf(
+ em->bm, &bmop, BMO_FLAG_DEFAULTS,
+ "region_extend geom=%hvef use_contract=%b use_faces=%b use_face_step=%b",
+ BM_ELEM_SELECT, true, use_faces, use_face_step);
BMO_op_exec(em->bm, &bmop);
/* don't flush selection in edge/vertex mode */
BMO_slot_buffer_hflag_disable(em->bm, bmop.slots_out, "geom.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, use_faces ? true : false);
@@ -506,6 +491,12 @@ void EDBM_flag_enable_all(BMEditMesh *em, const char hflag)
BM_mesh_elem_hflag_enable_all(em->bm, BM_VERT | BM_EDGE | BM_FACE, hflag, true);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name UV Vertex Map API
+ * \{ */
+
/**
* Return a new UVVertMap from the editmesh
*/
@@ -529,7 +520,7 @@ UvVertMap *BM_uv_vert_map_create(
BLI_buffer_declare_static(vec2f, tf_uv_buf, BLI_BUFFER_NOP, BM_DEFAULT_NGON_STACK_SIZE);
BM_mesh_elem_index_ensure(bm, BM_VERT | BM_FACE);
-
+
totfaces = bm->totface;
totverts = bm->totvert;
totuv = 0;
@@ -559,7 +550,7 @@ UvVertMap *BM_uv_vert_map_create(
BKE_mesh_uv_vert_map_free(vmap);
return NULL;
}
-
+
BM_ITER_MESH_INDEX (efa, &iter, bm, BM_FACES_OF_MESH, a) {
if ((use_select == false) || BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
float (*tf_uv)[2];
@@ -572,7 +563,7 @@ UvVertMap *BM_uv_vert_map_create(
buf->tfindex = i;
buf->f = a;
buf->separate = 0;
-
+
buf->next = vmap->vert[BM_elem_index_get(l->v)];
vmap->vert[BM_elem_index_get(l->v)] = buf;
buf++;
@@ -584,11 +575,11 @@ UvVertMap *BM_uv_vert_map_create(
}
if (use_winding) {
- winding[a] = cross_poly_v2((const float (*)[2])tf_uv, efa->len) > 0;
+ winding[a] = cross_poly_v2(tf_uv, efa->len) > 0;
}
}
}
-
+
/* sort individual uvs for each vert */
BM_ITER_MESH_INDEX (ev, &iter, bm, BM_VERTS_OF_MESH, a) {
UvMapVert *newvlist = NULL, *vlist = vmap->vert[a];
@@ -603,11 +594,11 @@ UvVertMap *BM_uv_vert_map_create(
efa = BM_face_at_index(bm, v->f);
/* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */
-
+
l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, v->tfindex);
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
uv = luv->uv;
-
+
lastv = NULL;
iterv = vlist;
@@ -615,11 +606,11 @@ UvVertMap *BM_uv_vert_map_create(
next = iterv->next;
efa = BM_face_at_index(bm, iterv->f);
/* tf = CustomData_bmesh_get(&bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */
-
+
l = BM_iter_at_index(bm, BM_LOOPS_OF_FACE, efa, iterv->tfindex);
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
uv2 = luv->uv;
-
+
sub_v2_v2v2(uvdiff, uv2, uv);
if (fabsf(uvdiff[0]) < limit[0] && fabsf(uvdiff[1]) < limit[1] &&
@@ -652,13 +643,11 @@ UvVertMap *BM_uv_vert_map_create(
return vmap;
}
-
UvMapVert *BM_uv_vert_map_at_index(UvVertMap *vmap, unsigned int v)
{
return vmap->vert[v];
}
-
/* A specialized vert map used by stitch operator */
UvElementMap *BM_uv_element_map_create(
BMesh *bm,
@@ -736,7 +725,7 @@ UvElementMap *BM_uv_element_map_create(
}
if (use_winding) {
- winding[j] = cross_poly_v2((const float (*)[2])tf_uv, efa->len) > 0;
+ winding[j] = cross_poly_v2(tf_uv, efa->len) > 0;
}
}
}
@@ -916,42 +905,51 @@ void BM_uv_element_map_free(UvElementMap *element_map)
UvElement *BM_uv_element_get(UvElementMap *map, BMFace *efa, BMLoop *l)
{
- UvElement *element;
-
- element = map->vert[BM_elem_index_get(l->v)];
-
- for (; element; element = element->next)
- if (element->l->f == efa)
+ for (UvElement *element = map->vert[BM_elem_index_get(l->v)];
+ element;
+ element = element->next)
+ {
+ if (element->l->f == efa) {
return element;
+ }
+ }
return NULL;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Data Layer Checks
+ * \{ */
+
/* last_sel, use em->act_face otherwise get the last selected face in the editselections
* at the moment, last_sel is mainly useful for making sure the space image dosnt flicker */
-MTexPoly *EDBM_mtexpoly_active_get(BMEditMesh *em, BMFace **r_act_efa, const bool sloppy, const bool selected)
+BMFace *EDBM_uv_active_face_get(BMEditMesh *em, const bool sloppy, const bool selected, MTexPoly **r_tf)
{
BMFace *efa = NULL;
-
- if (!EDBM_mtexpoly_check(em))
+
+ if (!EDBM_uv_check(em)) {
return NULL;
-
+ }
+
efa = BM_mesh_active_face_get(em->bm, sloppy, selected);
if (efa) {
- if (r_act_efa) *r_act_efa = efa;
- return CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
+ if (r_tf) *r_tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY);
+ return efa;
}
- if (r_act_efa) *r_act_efa = NULL;
+ if (r_tf) *r_tf = NULL;
return NULL;
}
/* can we edit UV's for this mesh?*/
-bool EDBM_mtexpoly_check(BMEditMesh *em)
+bool EDBM_uv_check(BMEditMesh *em)
{
/* some of these checks could be a touch overkill */
- return em && em->bm->totface && CustomData_has_layer(&em->bm->pdata, CD_MTEXPOLY) &&
+ return em && em->bm->totface &&
+ CustomData_has_layer(&em->bm->pdata, CD_MTEXPOLY) &&
CustomData_has_layer(&em->bm->ldata, CD_MLOOPUV);
}
@@ -961,6 +959,12 @@ bool EDBM_vert_color_check(BMEditMesh *em)
return em && em->bm->totface && CustomData_has_layer(&em->bm->ldata, CD_MLOOPCOL);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mirror Cache API
+ * \{ */
+
static BMVert *cache_mirr_intptr_as_bmvert(intptr_t *index_lookup, int index)
{
intptr_t eve_i = index_lookup[index];
@@ -995,9 +999,10 @@ static BMVert *cache_mirr_intptr_as_bmvert(intptr_t *index_lookup, int index)
* \param maxdist Distance for close point test.
* \param r_index Optional array to write into, as an alternative to a customdata layer (length of total verts).
*/
-void EDBM_verts_mirror_cache_begin_ex(BMEditMesh *em, const int axis, const bool use_self, const bool use_select,
- /* extra args */
- const bool use_topology, float maxdist, int *r_index)
+void EDBM_verts_mirror_cache_begin_ex(
+ BMEditMesh *em, const int axis, const bool use_self, const bool use_select,
+ /* extra args */
+ const bool use_topology, float maxdist, int *r_index)
{
Mesh *me = (Mesh *)em->ob->data;
BMesh *bm = em->bm;
@@ -1021,8 +1026,9 @@ void EDBM_verts_mirror_cache_begin_ex(BMEditMesh *em, const int axis, const bool
em->mirror_cdlayer = CustomData_get_named_layer_index(&bm->vdata, CD_PROP_INT, layer_id);
}
- cd_vmirr_offset = CustomData_get_n_offset(&bm->vdata, CD_PROP_INT,
- em->mirror_cdlayer - CustomData_get_layer_index(&bm->vdata, CD_PROP_INT));
+ cd_vmirr_offset = CustomData_get_n_offset(
+ &bm->vdata, CD_PROP_INT,
+ em->mirror_cdlayer - CustomData_get_layer_index(&bm->vdata, CD_PROP_INT));
bm->vdata.layers[em->mirror_cdlayer].flag |= CD_FLAG_TEMPORARY;
}
@@ -1095,14 +1101,16 @@ void EDBM_verts_mirror_cache_begin_ex(BMEditMesh *em, const int axis, const bool
}
}
-void EDBM_verts_mirror_cache_begin(BMEditMesh *em, const int axis,
- const bool use_self, const bool use_select,
- const bool use_topology)
+void EDBM_verts_mirror_cache_begin(
+ BMEditMesh *em, const int axis,
+ const bool use_self, const bool use_select,
+ const bool use_topology)
{
- EDBM_verts_mirror_cache_begin_ex(em, axis,
- use_self, use_select,
- /* extra args */
- use_topology, BM_SEARCH_MAXDIST_MIRR, NULL);
+ EDBM_verts_mirror_cache_begin_ex(
+ em, axis,
+ use_self, use_select,
+ /* extra args */
+ use_topology, BM_SEARCH_MAXDIST_MIRR, NULL);
}
BMVert *EDBM_verts_mirror_get(BMEditMesh *em, BMVert *v)
@@ -1190,6 +1198,11 @@ void EDBM_verts_mirror_apply(BMEditMesh *em, const int sel_from, const int sel_t
}
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Hide/Reveal API
+ * \{ */
/* swap is 0 or 1, if 1 it hides not selected */
void EDBM_mesh_hide(BMEditMesh *em, bool swap)
@@ -1224,23 +1237,23 @@ void EDBM_mesh_hide(BMEditMesh *em, bool swap)
*/
}
-
-void EDBM_mesh_reveal(BMEditMesh *em)
+void EDBM_mesh_reveal(BMEditMesh *em, bool select)
{
- const char iter_types[3] = {BM_VERTS_OF_MESH,
- BM_EDGES_OF_MESH,
- BM_FACES_OF_MESH};
+ const char iter_types[3] = {
+ BM_VERTS_OF_MESH,
+ BM_EDGES_OF_MESH,
+ BM_FACES_OF_MESH,
+ };
const bool sels[3] = {
- (em->selectmode & SCE_SELECT_VERTEX) != 0,
- (em->selectmode & SCE_SELECT_EDGE) != 0,
- (em->selectmode & SCE_SELECT_FACE) != 0,
+ (em->selectmode & SCE_SELECT_VERTEX) != 0,
+ (em->selectmode & SCE_SELECT_EDGE) != 0,
+ (em->selectmode & SCE_SELECT_FACE) != 0,
};
int i;
/* Use tag flag to remember what was hidden before all is revealed.
* BM_ELEM_HIDDEN --> BM_ELEM_TAG */
-#pragma omp parallel for schedule(static) if (em->bm->totvert + em->bm->totedge + em->bm->totface >= BM_OMP_LIMIT)
for (i = 0; i < 3; i++) {
BMIter iter;
BMElem *ele;
@@ -1264,7 +1277,7 @@ void EDBM_mesh_reveal(BMEditMesh *em)
BM_ITER_MESH (ele, &iter, em->bm, iter_types[i]) {
if (BM_elem_flag_test(ele, BM_ELEM_TAG)) {
- BM_elem_select_set(em->bm, ele, true);
+ BM_elem_select_set(em->bm, ele, select);
}
}
}
@@ -1275,6 +1288,46 @@ void EDBM_mesh_reveal(BMEditMesh *em)
EDBM_mesh_normals_update(em);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Update API
+ * \{ */
+
+void EDBM_mesh_normals_update(BMEditMesh *em)
+{
+ BM_mesh_normals_update(em->bm);
+}
+
+void EDBM_stats_update(BMEditMesh *em)
+{
+ const char iter_types[3] = {
+ BM_VERTS_OF_MESH,
+ BM_EDGES_OF_MESH,
+ BM_FACES_OF_MESH,
+ };
+
+ BMIter iter;
+ BMElem *ele;
+ int *tots[3];
+ int i;
+
+ tots[0] = &em->bm->totvertsel;
+ tots[1] = &em->bm->totedgesel;
+ tots[2] = &em->bm->totfacesel;
+
+ em->bm->totvertsel = em->bm->totedgesel = em->bm->totfacesel = 0;
+
+ for (i = 0; i < 3; i++) {
+ ele = BM_iter_new(&iter, em->bm, iter_types[i], NULL);
+ for ( ; ele; ele = BM_iter_step(&iter)) {
+ if (BM_elem_flag_test(ele, BM_ELEM_SELECT)) {
+ (*tots[i])++;
+ }
+ }
+ }
+}
+
/* so many tools call these that we better make it a generic function.
*/
void EDBM_update_generic(BMEditMesh *em, const bool do_tessface, const bool is_destructive)
@@ -1310,15 +1363,41 @@ void EDBM_update_generic(BMEditMesh *em, const bool do_tessface, const bool is_d
#endif
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Data Access
+ * \{ */
+
+DerivedMesh *EDBM_mesh_deform_dm_get(BMEditMesh *em)
+{
+ return ((em->derivedFinal != NULL) &&
+ (em->derivedFinal->type == DM_TYPE_EDITBMESH) &&
+ (em->derivedFinal->deformedOnly != false)) ? em->derivedFinal : NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Operator Helpers
+ * \{ */
+
/* poll call for mesh operators requiring a view3d context */
int EDBM_view3d_poll(bContext *C)
{
- if (ED_operator_editmesh(C) && ED_operator_view3d_active(C))
+ if (ED_operator_editmesh(C) && ED_operator_view3d_active(C)) {
return 1;
+ }
return 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name BMesh Element API
+ * \{ */
+
BMElem *EDBM_elem_from_selectmode(BMEditMesh *em, BMVert *eve, BMEdge *eed, BMFace *efa)
{
BMElem *ele = NULL;
@@ -1383,22 +1462,19 @@ BMElem *EDBM_elem_from_index_any(BMEditMesh *em, int index)
return NULL;
}
-/* -------------------------------------------------------------------- */
-/* BMBVH functions */
-// XXX
-#if 0 //BMESH_TODO: not implemented yet
-int BMBVH_VertVisible(BMBVHTree *tree, BMEdge *e, RegionView3D *r3d)
-{
+/** \} */
-}
-#endif
+/* -------------------------------------------------------------------- */
+/** \name BMesh BVH API
+ * \{ */
static BMFace *edge_ray_cast(struct BMBVHTree *tree, const float co[3], const float dir[3], float *r_hitout, BMEdge *e)
{
BMFace *f = BKE_bmbvh_ray_cast(tree, co, dir, 0.0f, NULL, r_hitout, NULL);
- if (f && BM_edge_in_face(e, f))
+ if (f && BM_edge_in_face(e, f)) {
return NULL;
+ }
return f;
}
@@ -1417,8 +1493,10 @@ bool BMBVH_EdgeVisible(struct BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v
float origin[3], invmat[4][4];
float epsilon = 0.01f;
float end[3];
- const float mval_f[2] = {ar->winx / 2.0f,
- ar->winy / 2.0f};
+ const float mval_f[2] = {
+ ar->winx / 2.0f,
+ ar->winy / 2.0f,
+ };
ED_view3d_win_to_segment(ar, v3d, mval_f, origin, end, false);
@@ -1454,12 +1532,17 @@ bool BMBVH_EdgeVisible(struct BMBVHTree *tree, BMEdge *e, ARegion *ar, View3D *v
/* do three samplings: left, middle, right */
f = edge_ray_cast(tree, co1, dir1, NULL, e);
- if (f && !edge_ray_cast(tree, co2, dir2, NULL, e))
+ if (f && !edge_ray_cast(tree, co2, dir2, NULL, e)) {
return true;
- else if (f && !edge_ray_cast(tree, co3, dir3, NULL, e))
+ }
+ else if (f && !edge_ray_cast(tree, co3, dir3, NULL, e)) {
return true;
- else if (!f)
+ }
+ else if (!f) {
return true;
+ }
return false;
}
+
+/** \} */
diff --git a/source/blender/editors/mesh/mesh_data.c b/source/blender/editors/mesh/mesh_data.c
index 772bb1bd308..84d2ac3cef1 100644
--- a/source/blender/editors/mesh/mesh_data.c
+++ b/source/blender/editors/mesh/mesh_data.c
@@ -252,7 +252,7 @@ void ED_mesh_uv_loop_reset(struct bContext *C, struct Mesh *me)
{
/* could be ldata or pdata */
CustomData *pdata = GET_CD_DATA(me, pdata);
- const int layernum = CustomData_get_active_layer_index(pdata, CD_MTEXPOLY);
+ const int layernum = CustomData_get_active_layer(pdata, CD_MTEXPOLY);
ED_mesh_uv_loop_reset_ex(me, layernum);
WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
@@ -464,6 +464,20 @@ int ED_mesh_color_add(Mesh *me, const char *name, const bool active_set)
return layernum;
}
+bool ED_mesh_color_ensure(struct Mesh *me, const char *name)
+{
+ BLI_assert(me->edit_btmesh == NULL);
+
+ if (!me->mloopcol && me->totloop) {
+ CustomData_add_layer_named(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop, name);
+ BKE_mesh_update_customdata_pointers(me, true);
+ }
+
+ DAG_id_tag_update(&me->id, 0);
+
+ return (me->mloopcol != NULL);
+}
+
bool ED_mesh_color_remove_index(Mesh *me, const int n)
{
CustomData *ldata = GET_CD_DATA(me, ldata);
@@ -511,7 +525,7 @@ static int layers_poll(bContext *C)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && ob->type == OB_MESH && data && !ID_IS_LINKED_DATABLOCK(data));
+ return (ob && !ID_IS_LINKED(ob) && ob->type == OB_MESH && data && !ID_IS_LINKED(data));
}
static int mesh_uv_texture_add_exec(bContext *C, wmOperator *UNUSED(op))
@@ -582,7 +596,7 @@ static int drop_named_image_invoke(bContext *C, wmOperator *op, const wmEvent *e
obedit = base->object;
me = obedit->data;
if (me->edit_btmesh == NULL) {
- EDBM_mesh_make(scene->toolsettings, obedit, false);
+ EDBM_mesh_make(obedit, scene->toolsettings->selectmode, false);
exitmode = 1;
}
if (me->edit_btmesh == NULL)
@@ -759,7 +773,7 @@ static int mesh_customdata_mask_clear_poll(bContext *C)
return false;
}
- if (!ID_IS_LINKED_DATABLOCK(me)) {
+ if (!ID_IS_LINKED(me)) {
CustomData *data = GET_CD_DATA(me, vdata);
if (CustomData_has_layer(data, CD_PAINT_MASK)) {
return true;
@@ -813,7 +827,7 @@ static int mesh_customdata_skin_state(bContext *C)
if (ob && ob->type == OB_MESH) {
Mesh *me = ob->data;
- if (!ID_IS_LINKED_DATABLOCK(me)) {
+ if (!ID_IS_LINKED(me)) {
CustomData *data = GET_CD_DATA(me, vdata);
return CustomData_has_layer(data, CD_MVERT_SKIN);
}
@@ -889,9 +903,38 @@ static int mesh_customdata_custom_splitnormals_add_exec(bContext *C, wmOperator
CustomData *data = GET_CD_DATA(me, ldata);
if (me->edit_btmesh) {
+ /* Tag edges as sharp according to smooth threshold if needed, to preserve autosmooth shading. */
+ if (me->flag & ME_AUTOSMOOTH) {
+ BM_edges_sharp_from_angle_set(me->edit_btmesh->bm, me->smoothresh);
+
+ me->drawflag |= ME_DRAWSHARP;
+ }
+
BM_data_layer_add(me->edit_btmesh->bm, data, CD_CUSTOMLOOPNORMAL);
}
else {
+ /* Tag edges as sharp according to smooth threshold if needed, to preserve autosmooth shading. */
+ if (me->flag & ME_AUTOSMOOTH) {
+ float (*polynors)[3] = MEM_mallocN(sizeof(*polynors) * (size_t)me->totpoly, __func__);
+
+ BKE_mesh_calc_normals_poly(
+ me->mvert, NULL, me->totvert,
+ me->mloop, me->mpoly,
+ me->totloop, me->totpoly,
+ polynors, true);
+
+ BKE_edges_sharp_from_angle_set(
+ me->mvert, me->totvert,
+ me->medge, me->totedge,
+ me->mloop, me->totloop,
+ me->mpoly, polynors, me->totpoly,
+ me->smoothresh);
+
+ MEM_freeN(polynors);
+
+ me->drawflag |= ME_DRAWSHARP;
+ }
+
CustomData_add_layer(data, CD_CUSTOMLOOPNORMAL, CD_DEFAULT, NULL, me->totloop);
}
diff --git a/source/blender/editors/mesh/mesh_mirror.c b/source/blender/editors/mesh/mesh_mirror.c
new file mode 100644
index 00000000000..96b9f054252
--- /dev/null
+++ b/source/blender/editors/mesh/mesh_mirror.c
@@ -0,0 +1,374 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Blender Foundation, Campbell Barton
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/mesh/mesh_mirror.c
+ * \ingroup edmesh
+ *
+ * Mirror calculation for edit-mode and object mode.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+#include "BLI_bitmap.h"
+
+#include "DNA_mesh_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BLI_kdtree.h"
+#include "BKE_editmesh.h"
+
+#include "ED_mesh.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Mesh Spatial Mirror API
+ * \{ */
+
+#define KD_THRESH 0.00002f
+
+static struct { void *tree; } MirrKdStore = {NULL};
+
+/* mode is 's' start, or 'e' end, or 'u' use */
+/* if end, ob can be NULL */
+int ED_mesh_mirror_spatial_table(Object *ob, BMEditMesh *em, DerivedMesh *dm, const float co[3], char mode)
+{
+ if (mode == 'u') { /* use table */
+ if (MirrKdStore.tree == NULL)
+ ED_mesh_mirror_spatial_table(ob, em, dm, NULL, 's');
+
+ if (MirrKdStore.tree) {
+ KDTreeNearest nearest;
+ const int i = BLI_kdtree_find_nearest(MirrKdStore.tree, co, &nearest);
+
+ if (i != -1) {
+ if (nearest.dist < KD_THRESH) {
+ return i;
+ }
+ }
+ }
+ return -1;
+ }
+ else if (mode == 's') { /* start table */
+ Mesh *me = ob->data;
+ const bool use_em = (!dm && em && me->edit_btmesh == em);
+ const int totvert = use_em ? em->bm->totvert : dm ? dm->getNumVerts(dm) : me->totvert;
+
+ if (MirrKdStore.tree) /* happens when entering this call without ending it */
+ ED_mesh_mirror_spatial_table(ob, em, dm, co, 'e');
+
+ MirrKdStore.tree = BLI_kdtree_new(totvert);
+
+ if (use_em) {
+ BMVert *eve;
+ BMIter iter;
+ int i;
+
+ /* this needs to be valid for index lookups later (callers need) */
+ BM_mesh_elem_table_ensure(em->bm, BM_VERT);
+
+ BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
+ BLI_kdtree_insert(MirrKdStore.tree, i, eve->co);
+ }
+ }
+ else {
+ MVert *mvert = dm ? dm->getVertArray(dm) : me->mvert;
+ int i;
+
+ for (i = 0; i < totvert; i++, mvert++) {
+ BLI_kdtree_insert(MirrKdStore.tree, i, mvert->co);
+ }
+ }
+
+ BLI_kdtree_balance(MirrKdStore.tree);
+ }
+ else if (mode == 'e') { /* end table */
+ if (MirrKdStore.tree) {
+ BLI_kdtree_free(MirrKdStore.tree);
+ MirrKdStore.tree = NULL;
+ }
+ }
+ else {
+ BLI_assert(0);
+ }
+
+ return 0;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mesh Topology Mirror API
+ * \{ */
+
+typedef unsigned int MirrTopoHash_t;
+
+typedef struct MirrTopoVert_t {
+ MirrTopoHash_t hash;
+ int v_index;
+} MirrTopoVert_t;
+
+static int mirrtopo_hash_sort(const void *l1, const void *l2)
+{
+ if ((MirrTopoHash_t)(intptr_t)l1 > (MirrTopoHash_t)(intptr_t)l2) return 1;
+ else if ((MirrTopoHash_t)(intptr_t)l1 < (MirrTopoHash_t)(intptr_t)l2) return -1;
+ return 0;
+}
+
+static int mirrtopo_vert_sort(const void *v1, const void *v2)
+{
+ if (((MirrTopoVert_t *)v1)->hash > ((MirrTopoVert_t *)v2)->hash) return 1;
+ else if (((MirrTopoVert_t *)v1)->hash < ((MirrTopoVert_t *)v2)->hash) return -1;
+ return 0;
+}
+
+bool ED_mesh_mirrtopo_recalc_check(Mesh *me, DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store)
+{
+ int totvert;
+ int totedge;
+
+ if (dm) {
+ totvert = dm->getNumVerts(dm);
+ totedge = dm->getNumEdges(dm);
+ }
+ else if (me->edit_btmesh) {
+ totvert = me->edit_btmesh->bm->totvert;
+ totedge = me->edit_btmesh->bm->totedge;
+ }
+ else {
+ totvert = me->totvert;
+ totedge = me->totedge;
+ }
+
+ if ((mesh_topo_store->index_lookup == NULL) ||
+ (mesh_topo_store->prev_ob_mode != ob_mode) ||
+ (totvert != mesh_topo_store->prev_vert_tot) ||
+ (totedge != mesh_topo_store->prev_edge_tot))
+ {
+ return true;
+ }
+ else {
+ return false;
+ }
+
+}
+
+void ED_mesh_mirrtopo_init(Mesh *me, DerivedMesh *dm, const int ob_mode, MirrTopoStore_t *mesh_topo_store,
+ const bool skip_em_vert_array_init)
+{
+ MEdge *medge = NULL, *med;
+ BMEditMesh *em = dm ? NULL : me->edit_btmesh;
+
+ /* editmode*/
+ BMEdge *eed;
+ BMIter iter;
+
+ int a, last;
+ int totvert, totedge;
+ int tot_unique = -1, tot_unique_prev = -1;
+ int tot_unique_edges = 0, tot_unique_edges_prev;
+
+ MirrTopoHash_t *topo_hash = NULL;
+ MirrTopoHash_t *topo_hash_prev = NULL;
+ MirrTopoVert_t *topo_pairs;
+ MirrTopoHash_t topo_pass = 1;
+
+ intptr_t *index_lookup; /* direct access to mesh_topo_store->index_lookup */
+
+ /* reallocate if needed */
+ ED_mesh_mirrtopo_free(mesh_topo_store);
+
+ mesh_topo_store->prev_ob_mode = ob_mode;
+
+ if (em) {
+ BM_mesh_elem_index_ensure(em->bm, BM_VERT);
+
+ totvert = em->bm->totvert;
+ }
+ else {
+ totvert = dm ? dm->getNumVerts(dm) : me->totvert;
+ }
+
+ topo_hash = MEM_callocN(totvert * sizeof(MirrTopoHash_t), "TopoMirr");
+
+ /* Initialize the vert-edge-user counts used to detect unique topology */
+ if (em) {
+ totedge = me->edit_btmesh->bm->totedge;
+
+ BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
+ const int i1 = BM_elem_index_get(eed->v1), i2 = BM_elem_index_get(eed->v2);
+ topo_hash[i1]++;
+ topo_hash[i2]++;
+ }
+ }
+ else {
+ totedge = dm ? dm->getNumEdges(dm) : me->totedge;
+ medge = dm ? dm->getEdgeArray(dm) : me->medge;
+
+ for (a = 0, med = medge; a < totedge; a++, med++) {
+ const unsigned int i1 = med->v1, i2 = med->v2;
+ topo_hash[i1]++;
+ topo_hash[i2]++;
+ }
+ }
+
+ topo_hash_prev = MEM_dupallocN(topo_hash);
+
+ tot_unique_prev = -1;
+ tot_unique_edges_prev = -1;
+ while (1) {
+ /* use the number of edges per vert to give verts unique topology IDs */
+
+ tot_unique_edges = 0;
+
+ /* This can make really big numbers, wrapping around here is fine */
+ if (em) {
+ BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
+ const int i1 = BM_elem_index_get(eed->v1), i2 = BM_elem_index_get(eed->v2);
+ topo_hash[i1] += topo_hash_prev[i2] * topo_pass;
+ topo_hash[i2] += topo_hash_prev[i1] * topo_pass;
+ tot_unique_edges += (topo_hash[i1] != topo_hash[i2]);
+ }
+ }
+ else {
+ for (a = 0, med = medge; a < totedge; a++, med++) {
+ const unsigned int i1 = med->v1, i2 = med->v2;
+ topo_hash[i1] += topo_hash_prev[i2] * topo_pass;
+ topo_hash[i2] += topo_hash_prev[i1] * topo_pass;
+ tot_unique_edges += (topo_hash[i1] != topo_hash[i2]);
+ }
+ }
+ memcpy(topo_hash_prev, topo_hash, sizeof(MirrTopoHash_t) * totvert);
+
+ /* sort so we can count unique values */
+ qsort(topo_hash_prev, totvert, sizeof(MirrTopoHash_t), mirrtopo_hash_sort);
+
+ tot_unique = 1; /* account for skiping the first value */
+ for (a = 1; a < totvert; a++) {
+ if (topo_hash_prev[a - 1] != topo_hash_prev[a]) {
+ tot_unique++;
+ }
+ }
+
+ if ((tot_unique <= tot_unique_prev) && (tot_unique_edges <= tot_unique_edges_prev)) {
+ /* Finish searching for unique values when 1 loop dosnt give a
+ * higher number of unique values compared to the previous loop */
+ break;
+ }
+ else {
+ tot_unique_prev = tot_unique;
+ tot_unique_edges_prev = tot_unique_edges;
+ }
+ /* Copy the hash calculated this iter, so we can use them next time */
+ memcpy(topo_hash_prev, topo_hash, sizeof(MirrTopoHash_t) * totvert);
+
+ topo_pass++;
+ }
+
+ /* Hash/Index pairs are needed for sorting to find index pairs */
+ topo_pairs = MEM_callocN(sizeof(MirrTopoVert_t) * totvert, "MirrTopoPairs");
+
+ /* since we are looping through verts, initialize these values here too */
+ index_lookup = MEM_mallocN(totvert * sizeof(*index_lookup), "mesh_topo_lookup");
+
+ if (em) {
+ if (skip_em_vert_array_init == false) {
+ BM_mesh_elem_table_ensure(em->bm, BM_VERT);
+ }
+ }
+
+ for (a = 0; a < totvert; a++) {
+ topo_pairs[a].hash = topo_hash[a];
+ topo_pairs[a].v_index = a;
+
+ /* initialize lookup */
+ index_lookup[a] = -1;
+ }
+
+ qsort(topo_pairs, totvert, sizeof(MirrTopoVert_t), mirrtopo_vert_sort);
+
+ last = 0;
+
+ /* Get the pairs out of the sorted hashes, note, totvert+1 means we can use the previous 2,
+ * but you cant ever access the last 'a' index of MirrTopoPairs */
+ if (em) {
+ BMVert **vtable = em->bm->vtable;
+ for (a = 1; a <= totvert; a++) {
+ /* printf("I %d %ld %d\n", (a - last), MirrTopoPairs[a].hash, MirrTopoPairs[a].v_indexs); */
+ if ((a == totvert) || (topo_pairs[a - 1].hash != topo_pairs[a].hash)) {
+ const int match_count = a - last;
+ if (match_count == 2) {
+ const int j = topo_pairs[a - 1].v_index, k = topo_pairs[a - 2].v_index;
+ index_lookup[j] = (intptr_t)vtable[k];
+ index_lookup[k] = (intptr_t)vtable[j];
+ }
+ else if (match_count == 1) {
+ /* Center vertex. */
+ const int j = topo_pairs[a - 1].v_index;
+ index_lookup[j] = (intptr_t)vtable[j];
+ }
+ last = a;
+ }
+ }
+ }
+ else {
+ /* same as above, for mesh */
+ for (a = 1; a <= totvert; a++) {
+ if ((a == totvert) || (topo_pairs[a - 1].hash != topo_pairs[a].hash)) {
+ const int match_count = a - last;
+ if (match_count == 2) {
+ const int j = topo_pairs[a - 1].v_index, k = topo_pairs[a - 2].v_index;
+ index_lookup[j] = k;
+ index_lookup[k] = j;
+ }
+ else if (match_count == 1) {
+ /* Center vertex. */
+ const int j = topo_pairs[a - 1].v_index;
+ index_lookup[j] = j;
+ }
+ last = a;
+ }
+ }
+ }
+
+ MEM_freeN(topo_pairs);
+ topo_pairs = NULL;
+
+ MEM_freeN(topo_hash);
+ MEM_freeN(topo_hash_prev);
+
+ mesh_topo_store->index_lookup = index_lookup;
+ mesh_topo_store->prev_vert_tot = totvert;
+ mesh_topo_store->prev_edge_tot = totedge;
+}
+
+void ED_mesh_mirrtopo_free(MirrTopoStore_t *mesh_topo_store)
+{
+ if (mesh_topo_store->index_lookup) {
+ MEM_freeN(mesh_topo_store->index_lookup);
+ }
+ mesh_topo_store->index_lookup = NULL;
+ mesh_topo_store->prev_vert_tot = -1;
+ mesh_topo_store->prev_edge_tot = -1;
+}
+
+/** \} */
diff --git a/source/blender/editors/mesh/mesh_navmesh.c b/source/blender/editors/mesh/mesh_navmesh.c
index b95921964eb..0f1884f4017 100644
--- a/source/blender/editors/mesh/mesh_navmesh.c
+++ b/source/blender/editors/mesh/mesh_navmesh.c
@@ -72,7 +72,7 @@ static void createVertsTrisData(bContext *C, LinkNode *obs,
LinkNode *oblink, *dmlink;
DerivedMesh *dm;
Scene *scene = CTX_data_scene(C);
- LinkNode *dms = NULL;
+ LinkNodePair dms_pair = {NULL, NULL};
int nverts, ntris, *tris;
float *verts;
@@ -85,7 +85,7 @@ static void createVertsTrisData(bContext *C, LinkNode *obs,
ob = (Object *) oblink->link;
dm = mesh_create_derived_no_virtual(scene, ob, NULL, CD_MASK_MESH);
DM_ensure_tessface(dm);
- BLI_linklist_prepend(&dms, dm);
+ BLI_linklist_append(&dms_pair, dm);
nverts += dm->getNumVerts(dm);
nfaces = dm->getNumTessFaces(dm);
@@ -101,6 +101,7 @@ static void createVertsTrisData(bContext *C, LinkNode *obs,
*r_lay |= ob->lay;
}
+ LinkNode *dms = dms_pair.list;
/* create data */
verts = MEM_mallocN(sizeof(float) * 3 * nverts, "createVertsTrisData verts");
diff --git a/source/blender/editors/mesh/meshtools.c b/source/blender/editors/mesh/meshtools.c
index 743efb246ab..d3d29b61182 100644
--- a/source/blender/editors/mesh/meshtools.c
+++ b/source/blender/editors/mesh/meshtools.c
@@ -46,8 +46,6 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
-
-#include "BLI_kdtree.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_deform.h"
@@ -57,6 +55,8 @@
#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_material.h"
+#include "BKE_object.h"
+#include "BKE_object_deform.h"
#include "BKE_report.h"
#include "BKE_editmesh.h"
#include "BKE_multires.h"
@@ -77,7 +77,7 @@
static void join_mesh_single(
Main *bmain, Scene *scene,
- Object *ob_dst, Base *base_src, float imat[4][4],
+ Object *ob_dst, Object *ob_src, float imat[4][4],
MVert **mvert_pp, MEdge **medge_pp, MLoop **mloop_pp, MPoly **mpoly_pp,
CustomData *vdata, CustomData *edata, CustomData *ldata, CustomData *pdata,
int totvert, int totedge, int totloop, int totpoly,
@@ -87,7 +87,7 @@ static void join_mesh_single(
{
int a, b;
- Mesh *me = base_src->object->data;
+ Mesh *me = ob_src->data;
MVert *mvert = *mvert_pp;
MEdge *medge = *medge_pp;
MLoop *mloop = *mloop_pp;
@@ -103,33 +103,28 @@ static void join_mesh_single(
/* vertex groups */
MDeformVert *dvert = CustomData_get(vdata, *vertofs, CD_MDEFORMVERT);
-
- /* NB: vertex groups here are new version */
- if (dvert) {
- for (a = 0; a < me->totvert; a++) {
- for (b = 0; b < dvert[a].totweight; b++) {
- /* Find the old vertex group */
- bDeformGroup *dg, *odg = BLI_findlink(&base_src->object->defbase, dvert[a].dw[b].def_nr);
- int index;
- if (odg) {
- /* Search for a match in the new object, and set new index */
- for (dg = ob_dst->defbase.first, index = 0; dg; dg = dg->next, index++) {
- if (STREQ(dg->name, odg->name)) {
- dvert[a].dw[b].def_nr = index;
- break;
- }
- }
- }
- }
+ MDeformVert *dvert_src = CustomData_get(&me->vdata, 0, CD_MDEFORMVERT);
+
+ /* Remap to correct new vgroup indices, if needed. */
+ if (dvert_src) {
+ BLI_assert(dvert != NULL);
+
+ /* Build src to merged mapping of vgroup indices. */
+ int *vgroup_index_map;
+ int vgroup_index_map_len;
+ vgroup_index_map = BKE_object_defgroup_index_map_create(ob_src, ob_dst, &vgroup_index_map_len);
+ BKE_object_defgroup_index_map_apply(dvert, me->totvert, vgroup_index_map, vgroup_index_map_len);
+ if (vgroup_index_map != NULL) {
+ MEM_freeN(vgroup_index_map);
}
}
/* if this is the object we're merging into, no need to do anything */
- if (base_src->object != ob_dst) {
+ if (ob_src != ob_dst) {
float cmat[4][4];
/* watch this: switch matmul order really goes wrong */
- mul_m4_m4m4(cmat, imat, base_src->object->obmat);
+ mul_m4_m4m4(cmat, imat, ob_src->obmat);
/* transform vertex coordinates into new space */
for (a = 0, mvert = *mvert_pp; a < me->totvert; a++, mvert++) {
@@ -206,13 +201,13 @@ static void join_mesh_single(
}
if (me->totloop) {
- if (base_src->object != ob_dst) {
+ if (ob_src != ob_dst) {
MultiresModifierData *mmd;
- multiresModifier_prepare_join(scene, base_src->object, ob_dst);
+ multiresModifier_prepare_join(scene, ob_src, ob_dst);
- if ((mmd = get_multires_modifier(scene, base_src->object, true))) {
- ED_object_iter_other(bmain, base_src->object, true,
+ if ((mmd = get_multires_modifier(scene, ob_src, true))) {
+ ED_object_iter_other(bmain, ob_src, true,
ED_object_multires_update_totlevels_cb,
&mmd->totlvl);
}
@@ -230,8 +225,8 @@ static void join_mesh_single(
if (me->totpoly) {
if (matmap) {
/* make mapping for materials */
- for (a = 1; a <= base_src->object->totcol; a++) {
- Material *ma = give_current_material(base_src->object, a);
+ for (a = 1; a <= ob_src->totcol; a++) {
+ Material *ma = give_current_material(ob_src, a);
for (b = 0; b < totcol; b++) {
if (ma == matar[b]) {
@@ -266,8 +261,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
{
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
- Base *ob_base = CTX_data_active_base(C);
- Object *ob = ob_base->object;
+ Object *ob = CTX_data_active_object(C);
Material **matar = NULL, *ma;
Mesh *me;
MVert *mvert = NULL;
@@ -444,15 +438,6 @@ int join_mesh_exec(bContext *C, wmOperator *op)
/* adjust settings to fit (allocate a new data-array) */
kbn->data = MEM_callocN(sizeof(float) * 3 * totvert, "joined_shapekey");
kbn->totelem = totvert;
-
- /* XXX 2.5 Animato */
-#if 0
- /* also, copy corresponding ipo-curve to ipo-block if applicable */
- if (me->key->ipo && key->ipo) {
- /* FIXME... this is a luxury item! */
- puts("FIXME: ignoring IPO's when joining shapekeys on Meshes for now...");
- }
-#endif
}
kb_map[i] = kbn;
@@ -499,7 +484,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
*/
join_mesh_single(
bmain, scene,
- ob, ob_base, imat,
+ ob, ob, imat,
&mvert, &medge, &mloop, &mpoly,
&vdata, &edata, &ldata, &pdata,
totvert, totedge, totloop, totpoly,
@@ -516,7 +501,7 @@ int join_mesh_exec(bContext *C, wmOperator *op)
if (base->object->type == OB_MESH) {
join_mesh_single(
bmain, scene,
- ob, base, imat,
+ ob, base->object, imat,
&mvert, &medge, &mloop, &mpoly,
&vdata, &edata, &ldata, &pdata,
totvert, totedge, totloop, totpoly,
@@ -567,12 +552,10 @@ int join_mesh_exec(bContext *C, wmOperator *op)
if (ma)
id_us_min(&ma->id);
}
- if (ob->mat) MEM_freeN(ob->mat);
- if (ob->matbits) MEM_freeN(ob->matbits);
- if (me->mat) MEM_freeN(me->mat);
- ob->mat = me->mat = NULL;
- ob->matbits = NULL;
-
+ MEM_SAFE_FREE(ob->mat);
+ MEM_SAFE_FREE(ob->matbits);
+ MEM_SAFE_FREE(me->mat);
+
if (totcol) {
me->mat = matar;
ob->mat = MEM_callocN(sizeof(*ob->mat) * totcol, "join obmatar");
@@ -596,6 +579,9 @@ int join_mesh_exec(bContext *C, wmOperator *op)
BKE_key_sort(key);
}
+ /* Due to dependnecy cycle some other object might access old derived data. */
+ BKE_object_free_derived_caches(ob);
+
DAG_relations_tag_update(bmain); /* removed objects, need to rebuild dag */
DAG_id_tag_update(&ob->id, OB_RECALC_OB | OB_RECALC_DATA);
@@ -681,84 +667,6 @@ int join_mesh_shapes_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-/* -------------------------------------------------------------------- */
-/* Mesh Mirror (Spatial) */
-
-/** \name Mesh Spatial Mirror API
- * \{ */
-
-#define KD_THRESH 0.00002f
-
-static struct { void *tree; } MirrKdStore = {NULL};
-
-/* mode is 's' start, or 'e' end, or 'u' use */
-/* if end, ob can be NULL */
-int ED_mesh_mirror_spatial_table(Object *ob, BMEditMesh *em, DerivedMesh *dm, const float co[3], char mode)
-{
- if (mode == 'u') { /* use table */
- if (MirrKdStore.tree == NULL)
- ED_mesh_mirror_spatial_table(ob, em, dm, NULL, 's');
-
- if (MirrKdStore.tree) {
- KDTreeNearest nearest;
- const int i = BLI_kdtree_find_nearest(MirrKdStore.tree, co, &nearest);
-
- if (i != -1) {
- if (nearest.dist < KD_THRESH) {
- return i;
- }
- }
- }
- return -1;
- }
- else if (mode == 's') { /* start table */
- Mesh *me = ob->data;
- const bool use_em = (!dm && em && me->edit_btmesh == em);
- const int totvert = use_em ? em->bm->totvert : dm ? dm->getNumVerts(dm) : me->totvert;
-
- if (MirrKdStore.tree) /* happens when entering this call without ending it */
- ED_mesh_mirror_spatial_table(ob, em, dm, co, 'e');
-
- MirrKdStore.tree = BLI_kdtree_new(totvert);
-
- if (use_em) {
- BMVert *eve;
- BMIter iter;
- int i;
-
- /* this needs to be valid for index lookups later (callers need) */
- BM_mesh_elem_table_ensure(em->bm, BM_VERT);
-
- BM_ITER_MESH_INDEX (eve, &iter, em->bm, BM_VERTS_OF_MESH, i) {
- BLI_kdtree_insert(MirrKdStore.tree, i, eve->co);
- }
- }
- else {
- MVert *mvert = dm ? dm->getVertArray(dm) : me->mvert;
- int i;
-
- for (i = 0; i < totvert; i++, mvert++) {
- BLI_kdtree_insert(MirrKdStore.tree, i, mvert->co);
- }
- }
-
- BLI_kdtree_balance(MirrKdStore.tree);
- }
- else if (mode == 'e') { /* end table */
- if (MirrKdStore.tree) {
- BLI_kdtree_free(MirrKdStore.tree);
- MirrKdStore.tree = NULL;
- }
- }
- else {
- BLI_assert(0);
- }
-
- return 0;
-}
-
-/** \} */
-
/* -------------------------------------------------------------------- */
/* Mesh Mirror (Topology) */
@@ -1098,7 +1006,7 @@ bool ED_mesh_pick_face(bContext *C, Object *ob, const int mval[2], unsigned int
if (!me || me->totpoly == 0)
return false;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
if (size) {
/* sample rect to increase chances of selecting, so that when clicking
@@ -1263,7 +1171,7 @@ bool ED_mesh_pick_vert(bContext *C, Object *ob, const int mval[2], unsigned int
if (!me || me->totvert == 0)
return false;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
if (use_zbuf) {
if (size > 0) {
diff --git a/source/blender/editors/metaball/CMakeLists.txt b/source/blender/editors/metaball/CMakeLists.txt
index 0f9de8dbf87..7815240b7a4 100644
--- a/source/blender/editors/metaball/CMakeLists.txt
+++ b/source/blender/editors/metaball/CMakeLists.txt
@@ -34,6 +34,7 @@ set(INC_SYS
)
set(SRC
+ editmball_undo.c
mball_edit.c
mball_ops.c
diff --git a/source/blender/editors/metaball/editmball_undo.c b/source/blender/editors/metaball/editmball_undo.c
new file mode 100644
index 00000000000..dc64f61a916
--- /dev/null
+++ b/source/blender/editors/metaball/editmball_undo.c
@@ -0,0 +1,199 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/metaball/editmball_undo.c
+ * \ingroup edmeta
+ */
+
+#include <math.h>
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_utildefines.h"
+#include "BLI_listbase.h"
+#include "BLI_array_utils.h"
+
+#include "DNA_defs.h"
+#include "DNA_meta_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_undo_system.h"
+
+#include "ED_object.h"
+#include "ED_mball.h"
+#include "ED_util.h"
+
+#include "WM_types.h"
+#include "WM_api.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct UndoMBall {
+ ListBase editelems;
+ int lastelem_index;
+ size_t undo_size;
+} UndoMBall;
+
+/* free all MetaElems from ListBase */
+static void freeMetaElemlist(ListBase *lb)
+{
+ MetaElem *ml;
+
+ if (lb == NULL) {
+ return;
+ }
+
+ while ((ml = BLI_pophead(lb))) {
+ MEM_freeN(ml);
+ }
+}
+
+static void undomball_to_editmball(UndoMBall *umb, MetaBall *mb)
+{
+ freeMetaElemlist(mb->editelems);
+ mb->lastelem = NULL;
+
+ /* copy 'undo' MetaElems to 'edit' MetaElems */
+ int index = 0;
+ for (MetaElem *ml_undo = umb->editelems.first; ml_undo; ml_undo = ml_undo->next, index += 1) {
+ MetaElem *ml_edit = MEM_dupallocN(ml_undo);
+ BLI_addtail(mb->editelems, ml_edit);
+ if (index == umb->lastelem_index) {
+ mb->lastelem = ml_edit;
+ }
+ }
+}
+
+static void *editmball_from_undomball(UndoMBall *umb, MetaBall *mb)
+{
+ BLI_assert(BLI_array_is_zeroed(umb, 1));
+
+ /* allocate memory for undo ListBase */
+ umb->lastelem_index = -1;
+
+ /* copy contents of current ListBase to the undo ListBase */
+ int index = 0;
+ for (MetaElem *ml_edit = mb->editelems->first; ml_edit; ml_edit = ml_edit->next, index += 1) {
+ MetaElem *ml_undo = MEM_dupallocN(ml_edit);
+ BLI_addtail(&umb->editelems, ml_undo);
+ if (ml_edit == mb->lastelem) {
+ umb->lastelem_index = index;
+ }
+ umb->undo_size += sizeof(MetaElem);
+ }
+
+ return umb;
+}
+
+/* free undo ListBase of MetaElems */
+static void undomball_free_data(UndoMBall *umb)
+{
+ freeMetaElemlist(&umb->editelems);
+}
+
+static Object *editmball_object_from_context(bContext *C)
+{
+ Object *obedit = CTX_data_edit_object(C);
+ if (obedit && obedit->type == OB_MBALL) {
+ MetaBall *mb = obedit->data;
+ if (mb->editelems != NULL) {
+ return obedit;
+ }
+ }
+ return NULL;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct MBallUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-editmode. */
+ UndoRefID_Object obedit_ref;
+ UndoMBall data;
+} MBallUndoStep;
+
+static bool mball_undosys_poll(bContext *C)
+{
+ return editmball_object_from_context(C) != NULL;
+}
+
+static bool mball_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ MBallUndoStep *us = (MBallUndoStep *)us_p;
+ us->obedit_ref.ptr = editmball_object_from_context(C);
+ MetaBall *mb = us->obedit_ref.ptr->data;
+ editmball_from_undomball(&us->data, mb);
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void mball_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ ED_object_mode_set(C, OB_MODE_EDIT);
+
+ MBallUndoStep *us = (MBallUndoStep *)us_p;
+ Object *obedit = us->obedit_ref.ptr;
+ MetaBall *mb = obedit->data;
+ undomball_to_editmball(&us->data, mb);
+ DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
+}
+
+static void mball_undosys_step_free(UndoStep *us_p)
+{
+ MBallUndoStep *us = (MBallUndoStep *)us_p;
+ undomball_free_data(&us->data);
+}
+
+static void mball_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ MBallUndoStep *us = (MBallUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->obedit_ref));
+}
+
+/* Export for ED_undo_sys. */
+void ED_mball_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit MBall";
+ ut->poll = mball_undosys_poll;
+ ut->step_encode = mball_undosys_step_encode;
+ ut->step_decode = mball_undosys_step_decode;
+ ut->step_free = mball_undosys_step_free;
+
+ ut->step_foreach_ID_ref = mball_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(MBallUndoStep);
+
+}
+
+/** \} */
diff --git a/source/blender/editors/metaball/mball_edit.c b/source/blender/editors/metaball/mball_edit.c
index ed5bf4a92b4..27140bcdf3b 100644
--- a/source/blender/editors/metaball/mball_edit.c
+++ b/source/blender/editors/metaball/mball_edit.c
@@ -29,7 +29,6 @@
* \ingroup edmeta
*/
-
#include <math.h>
#include <string.h>
@@ -55,7 +54,6 @@
#include "ED_mball.h"
#include "ED_screen.h"
#include "ED_view3d.h"
-#include "ED_util.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -187,7 +185,7 @@ enum {
SIMMBALL_ROTATION
};
-static EnumPropertyItem prop_similar_types[] = {
+static const EnumPropertyItem prop_similar_types[] = {
{SIMMBALL_TYPE, "TYPE", 0, "Type", ""},
{SIMMBALL_RADIUS, "RADIUS", 0, "Radius", ""},
{SIMMBALL_STIFFNESS, "STIFFNESS", 0, "Stiffness", ""},
@@ -542,19 +540,21 @@ void MBALL_OT_hide_metaelems(wmOperatorType *ot)
/***************************** Unhide operator *****************************/
/* Unhide all edited MetaElems */
-static int reveal_metaelems_exec(bContext *C, wmOperator *UNUSED(op))
+static int reveal_metaelems_exec(bContext *C, wmOperator *op)
{
Object *obedit = CTX_data_edit_object(C);
MetaBall *mb = (MetaBall *)obedit->data;
- MetaElem *ml;
-
- ml = mb->editelems->first;
+ const bool select = RNA_boolean_get(op->ptr, "select");
+ bool changed = false;
- if (ml) {
- while (ml) {
+ for (MetaElem *ml = mb->editelems->first; ml; ml = ml->next) {
+ if (ml->flag & MB_HIDE) {
+ SET_FLAG_FROM_TEST(ml->flag, select, SELECT);
ml->flag &= ~MB_HIDE;
- ml = ml->next;
+ changed = true;
}
+ }
+ if (changed) {
WM_event_add_notifier(C, NC_GEOM | ND_DATA, mb);
DAG_id_tag_update(obedit->data, 0);
}
@@ -575,6 +575,9 @@ void MBALL_OT_reveal_metaelems(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* props */
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/* Select MetaElement with mouse click (user can select radius circle or
@@ -590,14 +593,11 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese
unsigned int buffer[MAXPICKBUF];
rcti rect;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
- rect.xmin = mval[0] - 12;
- rect.xmax = mval[0] + 12;
- rect.ymin = mval[1] - 12;
- rect.ymax = mval[1] + 12;
+ BLI_rcti_init_pt_radius(&rect, mval, 12);
- hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, true);
+ hits = view3d_opengl_select(&vc, buffer, MAXPICKBUF, &rect, VIEW3D_SELECT_PICK_NEAREST);
/* does startelem exist? */
ml = mb->editelems->first;
@@ -663,94 +663,3 @@ bool ED_mball_select_pick(bContext *C, const int mval[2], bool extend, bool dese
}
-/* ************* undo for MetaBalls ************* */
-
-typedef struct UndoMBall {
- ListBase editelems;
- int lastelem_index;
-} UndoMBall;
-
-/* free all MetaElems from ListBase */
-static void freeMetaElemlist(ListBase *lb)
-{
- MetaElem *ml;
-
- if (lb == NULL) return;
-
- while ((ml = BLI_pophead(lb))) {
- MEM_freeN(ml);
- }
-}
-
-
-static void undoMball_to_editMball(void *umb_v, void *mb_v, void *UNUSED(obdata))
-{
- MetaBall *mb = mb_v;
- UndoMBall *umb = umb_v;
-
- freeMetaElemlist(mb->editelems);
- mb->lastelem = NULL;
-
- /* copy 'undo' MetaElems to 'edit' MetaElems */
- int index = 0;
- for (MetaElem *ml_undo = umb->editelems.first; ml_undo; ml_undo = ml_undo->next, index += 1) {
- MetaElem *ml_edit = MEM_dupallocN(ml_undo);
- BLI_addtail(mb->editelems, ml_edit);
- if (index == umb->lastelem_index) {
- mb->lastelem = ml_edit;
- }
- }
-
-}
-
-static void *editMball_to_undoMball(void *mb_v, void *UNUSED(obdata))
-{
- MetaBall *mb = mb_v;
- UndoMBall *umb;
-
- /* allocate memory for undo ListBase */
- umb = MEM_callocN(sizeof(UndoMBall), __func__);
- umb->lastelem_index = -1;
-
- /* copy contents of current ListBase to the undo ListBase */
- int index = 0;
- for (MetaElem *ml_edit = mb->editelems->first; ml_edit; ml_edit = ml_edit->next, index += 1) {
- MetaElem *ml_undo = MEM_dupallocN(ml_edit);
- BLI_addtail(&umb->editelems, ml_undo);
- if (ml_edit == mb->lastelem) {
- umb->lastelem_index = index;
- }
- }
-
- return umb;
-}
-
-/* free undo ListBase of MetaElems */
-static void free_undoMball(void *umb_v)
-{
- UndoMBall *umb = umb_v;
-
- freeMetaElemlist(&umb->editelems);
- MEM_freeN(umb);
-}
-
-static MetaBall *metaball_get_obdata(Object *ob)
-{
- if (ob && ob->type == OB_MBALL) {
- return ob->data;
- }
- return NULL;
-}
-
-
-static void *get_data(bContext *C)
-{
- Object *obedit = CTX_data_edit_object(C);
- return metaball_get_obdata(obedit);
-}
-
-/* this is undo system for MetaBalls */
-void undo_push_mball(bContext *C, const char *name)
-{
- undo_editmode_push(C, name, get_data, free_undoMball, undoMball_to_editMball, editMball_to_undoMball, NULL);
-}
diff --git a/source/blender/editors/object/CMakeLists.txt b/source/blender/editors/object/CMakeLists.txt
index b3d02d45e13..24740a3372b 100644
--- a/source/blender/editors/object/CMakeLists.txt
+++ b/source/blender/editors/object/CMakeLists.txt
@@ -48,8 +48,8 @@ set(SRC
object_edit.c
object_group.c
object_hook.c
- object_lattice.c
object_lod.c
+ object_modes.c
object_modifier.c
object_ops.c
object_random.c
diff --git a/source/blender/editors/object/object_add.c b/source/blender/editors/object/object_add.c
index 02b2d8492b4..461b71a8a05 100644
--- a/source/blender/editors/object/object_add.c
+++ b/source/blender/editors/object/object_add.c
@@ -42,8 +42,8 @@
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meta_types.h"
-#include "DNA_object_fluidsim.h"
-#include "DNA_object_force.h"
+#include "DNA_object_fluidsim_types.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_vfont_types.h"
@@ -64,6 +64,7 @@
#include "BKE_armature.h"
#include "BKE_camera.h"
#include "BKE_context.h"
+#include "BKE_constraint.h"
#include "BKE_curve.h"
#include "BKE_depsgraph.h"
#include "BKE_DerivedMesh.h"
@@ -89,7 +90,6 @@
#include "BKE_scene.h"
#include "BKE_screen.h"
#include "BKE_speaker.h"
-#include "BKE_texture.h"
#include "RNA_access.h"
#include "RNA_define.h"
@@ -119,7 +119,7 @@
/* this is an exact copy of the define in rna_lamp.c
* kept here because of linking order.
* Icons are only defined here */
-EnumPropertyItem rna_enum_lamp_type_items[] = {
+const EnumPropertyItem rna_enum_lamp_type_items[] = {
{LA_LOCAL, "POINT", ICON_LAMP_POINT, "Point", "Omnidirectional point light source"},
{LA_SUN, "SUN", ICON_LAMP_SUN, "Sun", "Constant direction parallel ray light source"},
{LA_SPOT, "SPOT", ICON_LAMP_SPOT, "Spot", "Directional cone light source"},
@@ -129,7 +129,7 @@ EnumPropertyItem rna_enum_lamp_type_items[] = {
};
/* copy from rna_object_force.c */
-static EnumPropertyItem field_type_items[] = {
+static const EnumPropertyItem field_type_items[] = {
{PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", ""},
{PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", ""},
{PFIELD_VORTEX, "VORTEX", ICON_FORCE_VORTEX, "Vortex", ""},
@@ -413,7 +413,7 @@ Object *ED_object_add_type(
/* for as long scene has editmode... */
if (CTX_data_edit_object(C))
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO); /* freedata, and undo */
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO); /* freedata, and undo */
/* deselects all, sets scene->basact */
ob = BKE_object_add(bmain, scene, type, name);
@@ -753,7 +753,7 @@ static int object_armature_add_exec(bContext *C, wmOperator *op)
}
dia = RNA_float_get(op->ptr, "radius");
- ED_armature_edit_bone_add_primitive(obedit, dia, view_aligned);
+ ED_armature_ebone_add_primitive(obedit, dia, view_aligned);
/* userdef */
if (newob && !enter_editmode)
@@ -978,7 +978,7 @@ static int group_instance_add_exec(bContext *C, wmOperator *op)
group = (Group *)BKE_libblock_find_name(ID_GR, name);
if (0 == RNA_struct_property_is_set(op->ptr, "location")) {
- wmEvent *event = CTX_wm_window(C)->eventstate;
+ const wmEvent *event = CTX_wm_window(C)->eventstate;
ARegion *ar = CTX_wm_region(C);
const int mval[2] = {event->x - ar->winrct.xmin,
event->y - ar->winrct.ymin};
@@ -1059,8 +1059,8 @@ static int object_speaker_add_exec(bContext *C, wmOperator *op)
{
/* create new data for NLA hierarchy */
AnimData *adt = BKE_animdata_add_id(&ob->id);
- NlaTrack *nlt = add_nlatrack(adt, NULL);
- NlaStrip *strip = add_nla_soundstrip(scene, ob->data);
+ NlaTrack *nlt = BKE_nlatrack_add(adt, NULL);
+ NlaStrip *strip = BKE_nla_add_soundstrip(scene, ob->data);
strip->start = CFRA;
strip->end += strip->start;
@@ -1153,7 +1153,21 @@ static int object_delete_exec(bContext *C, wmOperator *op)
base->object->id.name + 2, scene->id.name + 2);
continue;
}
+
+ /* This is sort of a quick hack to address T51243 - Proper thing to do here would be to nuke most of all this
+ * custom scene/object/base handling, and use generic lib remap/query for that.
+ * But this is for later (aka 2.8, once layers & co are settled and working).
+ */
+ if (use_global && base->object->id.lib == NULL) {
+ /* We want to nuke the object, let's nuke it the easy way (not for linked data though)... */
+ BKE_libblock_delete(bmain, &base->object->id);
+ changed = true;
+ continue;
+ }
+
/* remove from Grease Pencil parent */
+ /* XXX This is likely not correct? Will also remove parent from grease pencil from other scenes,
+ * even when use_global is false... */
for (bGPdata *gpd = bmain->gpencil.first; gpd; gpd = gpd->id.next) {
for (bGPDlayer *gpl = gpd->layers.first; gpl; gpl = gpl->next) {
if (gpl->parent != NULL) {
@@ -1178,7 +1192,7 @@ static int object_delete_exec(bContext *C, wmOperator *op)
Base *base_other;
for (scene_iter = bmain->scene.first; scene_iter; scene_iter = scene_iter->id.next) {
- if (scene_iter != scene && !ID_IS_LINKED_DATABLOCK(scene_iter)) {
+ if (scene_iter != scene && !ID_IS_LINKED(scene_iter)) {
base_other = BKE_scene_base_find(scene_iter, base->object);
if (base_other) {
if (is_indirectly_used && ID_REAL_USERS(base->object) <= 1 && ID_EXTRA_USERS(base->object) == 0) {
@@ -1329,89 +1343,87 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
const bool use_hierarchy)
{
Main *bmain = CTX_data_main(C);
- ListBase *lb;
+ ListBase *lb_duplis;
DupliObject *dob;
- GHash *dupli_gh = NULL, *parent_gh = NULL;
- Object *object;
+ GHash *dupli_gh, *parent_gh = NULL;
- if (!(base->object->transflag & OB_DUPLI))
+ if (!(base->object->transflag & OB_DUPLI)) {
return;
+ }
- lb = object_duplilist(bmain->eval_ctx, scene, base->object);
+ lb_duplis = object_duplilist(bmain->eval_ctx, scene, base->object);
- if (use_hierarchy || use_base_parent) {
- dupli_gh = BLI_ghash_ptr_new(__func__);
- if (use_hierarchy) {
- if (base->object->transflag & OB_DUPLIGROUP) {
- parent_gh = BLI_ghash_new(dupliobject_group_hash, dupliobject_group_cmp, __func__);
- }
- else {
- parent_gh = BLI_ghash_new(dupliobject_hash, dupliobject_cmp, __func__);
- }
+ dupli_gh = BLI_ghash_ptr_new(__func__);
+ if (use_hierarchy) {
+ if (base->object->transflag & OB_DUPLIGROUP) {
+ parent_gh = BLI_ghash_new(dupliobject_group_hash, dupliobject_group_cmp, __func__);
+ }
+ else {
+ parent_gh = BLI_ghash_new(dupliobject_hash, dupliobject_cmp, __func__);
}
}
- for (dob = lb->first; dob; dob = dob->next) {
- Base *basen;
- Object *ob = ID_NEW_SET(dob->ob, BKE_object_copy(bmain, dob->ob));
+ for (dob = lb_duplis->first; dob; dob = dob->next) {
+ Object *ob_src = dob->ob;
+ Object *ob_dst = ID_NEW_SET(dob->ob, BKE_object_copy(bmain, ob_src));
+ Base *base_dst;
/* font duplis can have a totcol without material, we get them from parent
* should be implemented better...
*/
- if (ob->mat == NULL) ob->totcol = 0;
+ if (ob_dst->mat == NULL) {
+ ob_dst->totcol = 0;
+ }
- basen = MEM_dupallocN(base);
- basen->flag &= ~(OB_FROMDUPLI | OB_FROMGROUP);
- ob->flag = basen->flag;
- basen->lay = base->lay;
- BLI_addhead(&scene->base, basen); /* addhead: othwise eternal loop */
- basen->object = ob;
+ base_dst = MEM_dupallocN(base);
+ base_dst->flag &= ~(OB_FROMDUPLI | OB_FROMGROUP);
+ ob_dst->flag = base_dst->flag;
+ base_dst->lay = base->lay;
+ BLI_addhead(&scene->base, base_dst); /* addhead: othwise eternal loop */
+ base_dst->object = ob_dst;
/* make sure apply works */
- BKE_animdata_free(&ob->id, true);
- ob->adt = NULL;
+ BKE_animdata_free(&ob_dst->id, true);
+ ob_dst->adt = NULL;
/* Proxies are not to be copied. */
- ob->proxy_from = NULL;
- ob->proxy_group = NULL;
- ob->proxy = NULL;
+ ob_dst->proxy_from = NULL;
+ ob_dst->proxy_group = NULL;
+ ob_dst->proxy = NULL;
- ob->parent = NULL;
- BLI_listbase_clear(&ob->constraints);
- ob->curve_cache = NULL;
- ob->transflag &= ~OB_DUPLI;
- ob->lay = base->lay;
+ ob_dst->parent = NULL;
+ BKE_constraints_free(&ob_dst->constraints);
+ ob_dst->curve_cache = NULL;
+ ob_dst->transflag &= ~OB_DUPLI;
+ ob_dst->lay = base->lay;
- copy_m4_m4(ob->obmat, dob->mat);
- BKE_object_apply_mat4(ob, ob->obmat, false, false);
+ copy_m4_m4(ob_dst->obmat, dob->mat);
+ BKE_object_apply_mat4(ob_dst, ob_dst->obmat, false, false);
- if (dupli_gh) {
- BLI_ghash_insert(dupli_gh, dob, ob);
- }
+ BLI_ghash_insert(dupli_gh, dob, ob_dst);
if (parent_gh) {
void **val;
/* Due to nature of hash/comparison of this ghash, a lot of duplis may be considered as 'the same',
* this avoids trying to insert same key several time and raise asserts in debug builds... */
if (!BLI_ghash_ensure_p(parent_gh, dob, &val)) {
- *val = ob;
+ *val = ob_dst;
}
}
+ }
+
+ for (dob = lb_duplis->first; dob; dob = dob->next) {
+ Object *ob_src = dob->ob;
+ Object *ob_dst = BLI_ghash_lookup(dupli_gh, dob);
/* Remap new object to itself, and clear again newid pointer of orig object. */
- BKE_libblock_relink_to_newid(&ob->id);
- set_sca_new_poins_ob(ob);
- BKE_id_clear_newpoin(&dob->ob->id);
+ BKE_libblock_relink_to_newid(&ob_dst->id);
+ set_sca_new_poins_ob(ob_dst);
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
- }
+ DAG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
- if (use_hierarchy) {
- for (dob = lb->first; dob; dob = dob->next) {
+ if (use_hierarchy) {
/* original parents */
- Object *ob_src = dob->ob;
Object *ob_src_par = ob_src->parent;
-
- Object *ob_dst = BLI_ghash_lookup(dupli_gh, dob);
Object *ob_dst_par = NULL;
/* find parent that was also made real */
@@ -1422,8 +1434,8 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
dob_key.ob = ob_src_par;
if (base->object->transflag & OB_DUPLIGROUP) {
memcpy(&dob_key.persistent_id[1],
- &dob->persistent_id[1],
- sizeof(dob->persistent_id[1]) * (MAX_DUPLI_RECUR - 1));
+ &dob->persistent_id[1],
+ sizeof(dob->persistent_id[1]) * (MAX_DUPLI_RECUR - 1));
}
else {
dob_key.persistent_id[0] = dob->persistent_id[0];
@@ -1447,52 +1459,42 @@ static void make_object_duplilist_real(bContext *C, Scene *scene, Base *base,
ob_dst->parent = base->object;
ob_dst->partype = PAROBJECT;
}
-
- if (ob_dst->parent) {
- invert_m4_m4(ob_dst->parentinv, dob->mat);
-
- /* note, this may be the parent of other objects, but it should
- * still work out ok */
- BKE_object_apply_mat4(ob_dst, dob->mat, false, true);
-
- /* to set ob_dst->orig and in case theres any other discrepicies */
- DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB);
- }
}
- }
- else if (use_base_parent) {
- /* since we are ignoring the internal hierarchy - parent all to the
- * base object */
- for (dob = lb->first; dob; dob = dob->next) {
- /* original parents */
- Object *ob_dst = BLI_ghash_lookup(dupli_gh, dob);
-
+ else if (use_base_parent) {
+ /* since we are ignoring the internal hierarchy - parent all to the
+ * base object */
ob_dst->parent = base->object;
ob_dst->partype = PAROBJECT;
+ }
- /* similer to the code above, see comments */
- invert_m4_m4(ob_dst->parentinv, dob->mat);
+ if (ob_dst->parent) {
+ /* note, this may be the parent of other objects, but it should
+ * still work out ok */
BKE_object_apply_mat4(ob_dst, dob->mat, false, true);
+
+ /* to set ob_dst->orig and in case theres any other discrepicies */
DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB);
}
}
if (base->object->transflag & OB_DUPLIGROUP && base->object->dup_group) {
- for (object = bmain->object.first; object; object = object->id.next) {
- if (object->proxy_group == base->object) {
- object->proxy = NULL;
- object->proxy_from = NULL;
- DAG_id_tag_update(&object->id, OB_RECALC_OB);
+ for (Object *ob = bmain->object.first; ob; ob = ob->id.next) {
+ if (ob->proxy_group == base->object) {
+ ob->proxy = NULL;
+ ob->proxy_from = NULL;
+ DAG_id_tag_update(&ob->id, OB_RECALC_OB);
}
}
}
- if (dupli_gh)
- BLI_ghash_free(dupli_gh, NULL, NULL);
- if (parent_gh)
+ BLI_ghash_free(dupli_gh, NULL, NULL);
+ if (parent_gh) {
BLI_ghash_free(parent_gh, NULL, NULL);
+ }
+
+ free_object_duplilist(lb_duplis);
- free_object_duplilist(lb);
+ BKE_main_id_clear_newpoins(bmain);
base->object->transflag &= ~OB_DUPLI;
}
@@ -1544,7 +1546,7 @@ void OBJECT_OT_duplicates_make_real(wmOperatorType *ot)
/**************************** Convert **************************/
-static EnumPropertyItem convert_target_items[] = {
+static const EnumPropertyItem convert_target_items[] = {
{OB_CURVE, "CURVE", ICON_OUTLINER_OB_CURVE, "Curve from Mesh/Text", ""},
{OB_MESH, "MESH", ICON_OUTLINER_OB_MESH, "Mesh from Curve/Meta/Surf/Text", ""},
{0, NULL, 0, NULL, NULL}
@@ -1571,7 +1573,7 @@ static void curvetomesh(Main *bmain, Scene *scene, Object *ob)
BKE_mesh_from_nurbs(ob); /* also does users */
if (ob->type == OB_MESH) {
- BKE_object_free_modifiers(ob);
+ BKE_object_free_modifiers(ob, 0);
/* Game engine defaults for mesh objects */
ob->body_type = OB_BODY_TYPE_STATIC;
@@ -1584,8 +1586,8 @@ static int convert_poll(bContext *C)
Object *obact = CTX_data_active_object(C);
Scene *scene = CTX_data_scene(C);
- return (!ID_IS_LINKED_DATABLOCK(scene) && obact && scene->obedit != obact &&
- (obact->flag & SELECT) && !ID_IS_LINKED_DATABLOCK(obact));
+ return (!ID_IS_LINKED(scene) && obact && scene->obedit != obact &&
+ (obact->flag & SELECT) && !ID_IS_LINKED(obact));
}
/* Helper for convert_exec */
@@ -1625,7 +1627,7 @@ static int convert_exec(bContext *C, wmOperator *op)
MetaBall *mb;
Mesh *me;
const short target = RNA_enum_get(op->ptr, "target");
- const bool keep_original = RNA_boolean_get(op->ptr, "keep_original");
+ bool keep_original = RNA_boolean_get(op->ptr, "keep_original");
int a, mballConverted = 0;
/* don't forget multiple users! */
@@ -1655,8 +1657,38 @@ static int convert_exec(bContext *C, wmOperator *op)
}
}
- CTX_DATA_BEGIN (C, Base *, base, selected_editable_bases)
+ ListBase selected_editable_bases = CTX_data_collection_get(C, "selected_editable_bases");
+
+ /* Ensure we get all meshes calculated with a sufficient data-mask,
+ * needed since re-evaluating single modifiers causes bugs if they depend
+ * on other objects data masks too, see: T50950. */
{
+ for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
+ Base *base = link->ptr.data;
+ ob = base->object;
+
+ /* The way object type conversion works currently (enforcing conversion of *all* objetcs using converted
+ * obdata, even some un-selected/hidden/inother scene ones, sounds totally bad to me.
+ * However, changing this is more design than bugfix, not to mention convoluted code below,
+ * so that will be for later.
+ * But at the very least, do not do that with linked IDs! */
+ if ((ID_IS_LINKED(ob) || (ob->data && ID_IS_LINKED(ob->data))) && !keep_original) {
+ keep_original = true;
+ BKE_reportf(op->reports, RPT_INFO,
+ "Converting some linked object/object data, enforcing 'Keep Original' option to True");
+ }
+
+ DAG_id_tag_update(&base->object->id, OB_RECALC_DATA);
+ }
+
+ uint64_t customdata_mask_prev = scene->customdata_mask;
+ scene->customdata_mask |= CD_MASK_MESH;
+ BKE_scene_update_tagged(bmain->eval_ctx, bmain, scene);
+ scene->customdata_mask = customdata_mask_prev;
+ }
+
+ for (CollectionPointerLink *link = selected_editable_bases.first; link; link = link->next) {
+ Base *base = link->ptr.data;
ob = base->object;
if (ob->flag & OB_DONE || !IS_TAGGED(ob->data)) {
@@ -1670,7 +1702,7 @@ static int convert_exec(bContext *C, wmOperator *op)
/* When 2 objects with linked data are selected, converting both
* would keep modifiers on all but the converted object [#26003] */
if (ob->type == OB_MESH) {
- BKE_object_free_modifiers(ob); /* after derivedmesh calls! */
+ BKE_object_free_modifiers(ob, 0); /* after derivedmesh calls! */
}
}
}
@@ -1695,11 +1727,11 @@ static int convert_exec(bContext *C, wmOperator *op)
BKE_mesh_to_curve(scene, newob);
if (newob->type == OB_CURVE) {
- BKE_object_free_modifiers(newob); /* after derivedmesh calls! */
+ BKE_object_free_modifiers(newob, 0); /* after derivedmesh calls! */
ED_rigidbody_object_remove(bmain, scene, newob);
}
}
- else if (ob->type == OB_MESH && ob->modifiers.first) { /* converting a mesh with no modifiers causes a segfault */
+ else if (ob->type == OB_MESH) {
ob->flag |= OB_DONE;
if (keep_original) {
@@ -1723,13 +1755,12 @@ static int convert_exec(bContext *C, wmOperator *op)
* cases this doesnt give correct results (when MDEF is used for eg)
*/
dm = mesh_get_derived_final(scene, newob, CD_MASK_MESH);
- // dm = mesh_create_derived_no_deform(ob1, NULL); /* this was called original (instead of get_derived). man o man why! (ton) */
DM_to_mesh(dm, newob->data, newob, CD_MASK_MESH, true);
/* re-tessellation is called by DM_to_mesh */
- BKE_object_free_modifiers(newob); /* after derivedmesh calls! */
+ BKE_object_free_modifiers(newob, 0); /* after derivedmesh calls! */
}
else if (ob->type == OB_FONT) {
ob->flag |= OB_DONE;
@@ -1888,7 +1919,7 @@ static int convert_exec(bContext *C, wmOperator *op)
((ID *)ob->data)->tag &= ~LIB_TAG_DOIT; /* flag not to convert this datablock again */
}
}
- CTX_DATA_END;
+ BLI_freelistN(&selected_editable_bases);
if (!keep_original) {
if (mballConverted) {
@@ -2157,6 +2188,11 @@ static Base *object_add_duplicate_internal(Main *bmain, Scene *scene, Base *base
if (didit) {
Key *key = BKE_key_from_object(obn);
+ Key *oldkey = BKE_key_from_object(ob);
+ if (oldkey != NULL) {
+ ID_NEW_SET(oldkey, key);
+ }
+
if (dupflag & USER_DUP_ACT) {
bActuator *act;
@@ -2362,7 +2398,8 @@ static int add_named_exec(bContext *C, wmOperator *op)
MEM_freeN(base);
- WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT | ND_OB_ACTIVE, scene);
+ WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
+ WM_event_add_notifier(C, NC_SCENE | ND_OB_ACTIVE, scene);
return OPERATOR_FINISHED;
}
@@ -2391,7 +2428,7 @@ static int join_poll(bContext *C)
{
Object *ob = CTX_data_active_object(C);
- if (!ob || ID_IS_LINKED_DATABLOCK(ob)) return 0;
+ if (!ob || ID_IS_LINKED(ob)) return 0;
if (ELEM(ob->type, OB_MESH, OB_CURVE, OB_SURF, OB_ARMATURE))
return ED_operator_screenactive(C);
@@ -2444,7 +2481,7 @@ static int join_shapes_poll(bContext *C)
{
Object *ob = CTX_data_active_object(C);
- if (!ob || ID_IS_LINKED_DATABLOCK(ob)) return 0;
+ if (!ob || ID_IS_LINKED(ob)) return 0;
/* only meshes supported at the moment */
if (ob->type == OB_MESH)
diff --git a/source/blender/editors/object/object_bake.c b/source/blender/editors/object/object_bake.c
index 11d96da5786..9837fec2b1e 100644
--- a/source/blender/editors/object/object_bake.c
+++ b/source/blender/editors/object/object_bake.c
@@ -832,9 +832,9 @@ static int bake_image_exec(bContext *C, wmOperator *op)
RE_Database_Baking(bkr.re, bmain, scene, scene->lay, scene->r.bake_mode, (scene->r.bake_flag & R_BAKE_TO_ACTIVE) ? OBACT : NULL);
/* baking itself is threaded, cannot use test_break in threads */
- BLI_init_threads(&threads, do_bake_render, 1);
+ BLI_threadpool_init(&threads, do_bake_render, 1);
bkr.ready = 0;
- BLI_insert_thread(&threads, &bkr);
+ BLI_threadpool_insert(&threads, &bkr);
while (bkr.ready == 0) {
PIL_sleep_ms(50);
@@ -845,7 +845,7 @@ static int bake_image_exec(bContext *C, wmOperator *op)
if (!G.background)
BKE_blender_test_break();
}
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
if (bkr.result == BAKE_RESULT_NO_OBJECTS)
BKE_report(op->reports, RPT_ERROR, "No valid images found to bake to");
diff --git a/source/blender/editors/object/object_bake_api.c b/source/blender/editors/object/object_bake_api.c
index 6b06e7b0a6c..c78b9b37da1 100644
--- a/source/blender/editors/object/object_bake_api.c
+++ b/source/blender/editors/object/object_bake_api.c
@@ -51,6 +51,7 @@
#include "BKE_image.h"
#include "BKE_library.h"
#include "BKE_main.h"
+#include "BKE_material.h"
#include "BKE_node.h"
#include "BKE_report.h"
#include "BKE_modifier.h"
@@ -86,7 +87,7 @@ typedef struct BakeAPIRender {
ReportList *reports;
ListBase selected_objects;
- ScenePassType pass_type;
+ eScenePassType pass_type;
int pass_filter;
int margin;
@@ -100,7 +101,7 @@ typedef struct BakeAPIRender {
float cage_extrusion;
int normal_space;
- BakeNormalSwizzle normal_swizzle[3];
+ eBakeNormalSwizzle normal_swizzle[3];
char uv_layer[MAX_CUSTOMDATA_LAYER_NAME];
char custom_cage[MAX_NAME];
@@ -339,7 +340,7 @@ static bool write_external_bake_pixels(
return ok;
}
-static bool is_noncolor_pass(ScenePassType pass_type)
+static bool is_noncolor_pass(eScenePassType pass_type)
{
return ELEM(pass_type,
SCE_PASS_Z,
@@ -352,12 +353,17 @@ static bool is_noncolor_pass(ScenePassType pass_type)
}
/* if all is good tag image and return true */
-static bool bake_object_check(Object *ob, ReportList *reports)
+static bool bake_object_check(Scene *scene, Object *ob, ReportList *reports)
{
Image *image;
void *lock;
int i;
+ if ((ob->lay & scene->lay) == 0) {
+ BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is not on a scene layer", ob->id.name + 2);
+ return false;
+ }
+
if (ob->type != OB_MESH) {
BKE_reportf(reports, RPT_ERROR, "Object \"%s\" is not a mesh", ob->id.name + 2);
return false;
@@ -406,22 +412,18 @@ static bool bake_object_check(Object *ob, ReportList *reports)
}
}
else {
- if (ob->mat[i]) {
- BKE_reportf(reports, RPT_ERROR,
+ Material *mat = give_current_material(ob, i);
+ if (mat != NULL) {
+ BKE_reportf(reports, RPT_INFO,
"No active image found in material \"%s\" (%d) for object \"%s\"",
- ob->mat[i]->id.name + 2, i, ob->id.name + 2);
- }
- else if (((Mesh *) ob->data)->mat[i]) {
- BKE_reportf(reports, RPT_ERROR,
- "No active image found in material \"%s\" (%d) for object \"%s\"",
- ((Mesh *) ob->data)->mat[i]->id.name + 2, i, ob->id.name + 2);
+ mat->id.name + 2, i, ob->id.name + 2);
}
else {
- BKE_reportf(reports, RPT_ERROR,
- "No active image found in material (%d) for object \"%s\"",
+ BKE_reportf(reports, RPT_INFO,
+ "No active image found in material slot (%d) for object \"%s\"",
i, ob->id.name + 2);
}
- return false;
+ continue;
}
image->id.tag |= LIB_TAG_DOIT;
@@ -429,7 +431,7 @@ static bool bake_object_check(Object *ob, ReportList *reports)
return true;
}
-static bool bake_pass_filter_check(ScenePassType pass_type, const int pass_filter, ReportList *reports)
+static bool bake_pass_filter_check(eScenePassType pass_type, const int pass_filter, ReportList *reports)
{
switch (pass_type) {
case SCE_PASS_COMBINED:
@@ -491,7 +493,7 @@ static bool bake_pass_filter_check(ScenePassType pass_type, const int pass_filte
}
/* before even getting in the bake function we check for some basic errors */
-static bool bake_objects_check(Main *bmain, Object *ob, ListBase *selected_objects,
+static bool bake_objects_check(Main *bmain, Scene *scene, Object *ob, ListBase *selected_objects,
ReportList *reports, const bool is_selected_to_active)
{
CollectionPointerLink *link;
@@ -502,7 +504,7 @@ static bool bake_objects_check(Main *bmain, Object *ob, ListBase *selected_objec
if (is_selected_to_active) {
int tot_objects = 0;
- if (!bake_object_check(ob, reports))
+ if (!bake_object_check(scene, ob, reports))
return false;
for (link = selected_objects->first; link; link = link->next) {
@@ -530,7 +532,7 @@ static bool bake_objects_check(Main *bmain, Object *ob, ListBase *selected_objec
}
for (link = selected_objects->first; link; link = link->next) {
- if (!bake_object_check(link->ptr.data, reports))
+ if (!bake_object_check(scene, link->ptr.data, reports))
return false;
}
}
@@ -561,7 +563,11 @@ static void build_image_lookup(Main *bmain, Object *ob, BakeImages *bake_images)
Image *image;
ED_object_get_active_image(ob, i + 1, &image, NULL, NULL, NULL);
- if ((image->id.tag & LIB_TAG_DOIT)) {
+ /* Some materials have no image, we just ignore those cases. */
+ if (image == NULL) {
+ bake_images->lookup[i] = -1;
+ }
+ else if (image->id.tag & LIB_TAG_DOIT) {
for (j = 0; j < i; j++) {
if (bake_images->data[j].image == image) {
bake_images->lookup[i] = j;
@@ -615,21 +621,22 @@ static size_t initialize_internal_images(BakeImages *bake_images, ReportList *re
/* create new mesh with edit mode changes and modifiers applied */
static Mesh *bake_mesh_new_from_object(Main *bmain, Scene *scene, Object *ob)
{
- if (ob->mode & OB_MODE_EDIT)
- ED_object_editmode_load(ob);
+ ED_object_editmode_load(ob);
Mesh *me = BKE_mesh_new_from_object(bmain, scene, ob, 1, 2, 0, 0);
- BKE_mesh_split_faces(me, true);
+ if (me->flag & ME_AUTOSMOOTH) {
+ BKE_mesh_split_faces(me, true);
+ }
return me;
}
static int bake(
Render *re, Main *bmain, Scene *scene, Object *ob_low, ListBase *selected_objects, ReportList *reports,
- const ScenePassType pass_type, const int pass_filter, const int margin,
- const BakeSaveMode save_mode, const bool is_clear, const bool is_split_materials,
+ const eScenePassType pass_type, const int pass_filter, const int margin,
+ const eBakeSaveMode save_mode, const bool is_clear, const bool is_split_materials,
const bool is_automatic_name, const bool is_selected_to_active, const bool is_cage,
- const float cage_extrusion, const int normal_space, const BakeNormalSwizzle normal_swizzle[],
+ const float cage_extrusion, const int normal_space, const eBakeNormalSwizzle normal_swizzle[],
const char *custom_cage, const char *filepath, const int width, const int height,
const char *identifier, ScrArea *sa, const char *uv_layer)
{
@@ -1023,7 +1030,7 @@ cage_cleanup:
}
else {
/* if everything else fails, use the material index */
- char tmp[4];
+ char tmp[5];
sprintf(tmp, "%d", i % 1000);
BLI_path_suffix(name, FILE_MAX, tmp, "_");
}
@@ -1153,7 +1160,7 @@ static void bake_init_api_data(wmOperator *op, bContext *C, BakeAPIRender *bkr)
bkr->result = OPERATOR_CANCELLED;
- bkr->render = RE_NewRender(bkr->scene->id.name);
+ bkr->render = RE_NewSceneRender(bkr->scene);
/* XXX hack to force saving to always be internal. Whether (and how) to support
* external saving will be addressed later */
@@ -1167,6 +1174,9 @@ static int bake_exec(bContext *C, wmOperator *op)
BakeAPIRender bkr = {NULL};
Scene *scene = CTX_data_scene(C);
+ G.is_break = false;
+ G.is_rendering = true;
+
bake_set_props(op, scene);
bake_init_api_data(op, C, &bkr);
@@ -1179,7 +1189,7 @@ static int bake_exec(bContext *C, wmOperator *op)
goto finally;
}
- if (!bake_objects_check(bkr.main, bkr.ob, &bkr.selected_objects, bkr.reports, bkr.is_selected_to_active)) {
+ if (!bake_objects_check(bkr.main, bkr.scene, bkr.ob, &bkr.selected_objects, bkr.reports, bkr.is_selected_to_active)) {
goto finally;
}
@@ -1218,6 +1228,7 @@ static int bake_exec(bContext *C, wmOperator *op)
finally:
+ G.is_rendering = false;
BLI_freelistN(&bkr.selected_objects);
return result;
}
@@ -1237,7 +1248,7 @@ static void bake_startjob(void *bkv, short *UNUSED(stop), short *do_update, floa
return;
}
- if (!bake_objects_check(bkr->main, bkr->ob, &bkr->selected_objects, bkr->reports, bkr->is_selected_to_active)) {
+ if (!bake_objects_check(bkr->main, bkr->scene, bkr->ob, &bkr->selected_objects, bkr->reports, bkr->is_selected_to_active)) {
bkr->result = OPERATOR_CANCELLED;
return;
}
diff --git a/source/blender/editors/object/object_constraint.c b/source/blender/editors/object/object_constraint.c
index 59d78f13ccb..94caaedec19 100644
--- a/source/blender/editors/object/object_constraint.c
+++ b/source/blender/editors/object/object_constraint.c
@@ -570,7 +570,7 @@ static void object_test_constraint(Object *owner, bConstraint *con)
#define EDIT_CONSTRAINT_OWNER_OBJECT 0
#define EDIT_CONSTRAINT_OWNER_BONE 1
-static EnumPropertyItem constraint_owner_items[] = {
+static const EnumPropertyItem constraint_owner_items[] = {
{EDIT_CONSTRAINT_OWNER_OBJECT, "OBJECT", 0, "Object", "Edit a constraint on the active object"},
{EDIT_CONSTRAINT_OWNER_BONE, "BONE", 0, "Bone", "Edit a constraint on the active bone"},
{0, NULL, 0, NULL, NULL}};
@@ -591,7 +591,7 @@ static int edit_constraint_poll_generic(bContext *C, StructRNA *rna_type)
return 0;
}
- if (ID_IS_LINKED_DATABLOCK(ob) || (ptr.id.data && ID_IS_LINKED_DATABLOCK(ptr.id.data))) {
+ if (ID_IS_LINKED(ob) || (ptr.id.data && ID_IS_LINKED(ptr.id.data))) {
CTX_wm_operator_poll_msg_set(C, "Cannot edit library data");
return 0;
}
@@ -1025,7 +1025,7 @@ static int followpath_path_animate_exec(bContext *C, wmOperator *op)
* and define basic slope of this curve based on the properties
*/
if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first) {
- FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
+ FModifier *fcm = add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
FMod_Generator *gen = fcm->data;
/* Assume that we have the following equation:
diff --git a/source/blender/editors/object/object_data_transfer.c b/source/blender/editors/object/object_data_transfer.c
index acee69daab7..7845cfe1022 100644
--- a/source/blender/editors/object/object_data_transfer.c
+++ b/source/blender/editors/object/object_data_transfer.c
@@ -63,7 +63,7 @@
/* All possible data to transfer.
* Note some are 'fake' ones, i.e. they are not hold by real CDLayers. */
/* Not shared with modifier, since we use a usual enum here, not a multi-choice one. */
-static EnumPropertyItem DT_layer_items[] = {
+static const EnumPropertyItem DT_layer_items[] = {
{0, "", 0, "Vertex Data", ""},
{DT_TYPE_MDEFORMVERT, "VGROUP_WEIGHTS", 0, "Vertex Group(s)", "Transfer active or all vertex groups"},
#if 0 /* XXX For now, would like to finish/merge work from 2014 gsoc first. */
@@ -90,7 +90,7 @@ static EnumPropertyItem DT_layer_items[] = {
};
/* Note: rna_enum_dt_layers_select_src_items enum is from rna_modifier.c */
-static EnumPropertyItem *dt_layers_select_src_itemf(
+static const EnumPropertyItem *dt_layers_select_src_itemf(
bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL, tmp_item = {0};
@@ -183,7 +183,7 @@ static EnumPropertyItem *dt_layers_select_src_itemf(
}
/* Note: rna_enum_dt_layers_select_dst_items enum is from rna_modifier.c */
-static EnumPropertyItem *dt_layers_select_dst_itemf(
+static const EnumPropertyItem *dt_layers_select_dst_itemf(
bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
@@ -209,7 +209,7 @@ static EnumPropertyItem *dt_layers_select_dst_itemf(
return item;
}
-static EnumPropertyItem *dt_layers_select_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *dt_layers_select_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
{
const bool reverse_transfer = RNA_boolean_get(ptr, "use_reverse_transfer");
@@ -230,7 +230,7 @@ static EnumPropertyItem *dt_layers_select_itemf(bContext *C, PointerRNA *ptr, Pr
}
/* Note: rna_enum_dt_mix_mode_items enum is from rna_modifier.c */
-static EnumPropertyItem *dt_mix_mode_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *dt_mix_mode_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
int totitem = 0;
@@ -300,7 +300,7 @@ static void data_transfer_exec_preprocess_objects(
}
me = ob->data;
- if (ID_IS_LINKED_DATABLOCK(me)) {
+ if (ID_IS_LINKED(me)) {
/* Do not transfer to linked data, not supported. */
BKE_reportf(op->reports, RPT_WARNING, "Skipping object '%s', linked data '%s' cannot be modified",
ob->id.name + 2, me->id.name + 2);
@@ -330,7 +330,7 @@ static bool data_transfer_exec_is_object_valid(
me->id.tag &= ~LIB_TAG_DOIT;
return true;
}
- else if (!ID_IS_LINKED_DATABLOCK(me)) {
+ else if (!ID_IS_LINKED(me)) {
/* Do not transfer apply operation more than once. */
/* XXX This is not nice regarding vgroups, which are half-Object data... :/ */
BKE_reportf(op->reports, RPT_WARNING,
@@ -387,7 +387,7 @@ static int data_transfer_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
- if (reverse_transfer && ID_IS_LINKED_DATABLOCK(ob_src->data)) {
+ if (reverse_transfer && ID_IS_LINKED(ob_src->data)) {
/* Do not transfer to linked data, not supported. */
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/object/object_edit.c b/source/blender/editors/object/object_edit.c
index edd7b5dd1be..844ed168157 100644
--- a/source/blender/editors/object/object_edit.c
+++ b/source/blender/editors/object/object_edit.c
@@ -54,10 +54,11 @@
#include "DNA_property_types.h"
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_vfont_types.h"
#include "DNA_mesh_types.h"
+#include "DNA_lattice_types.h"
#include "IMB_imbuf_types.h"
@@ -81,8 +82,10 @@
#include "BKE_sca.h"
#include "BKE_softbody.h"
#include "BKE_modifier.h"
+#include "BKE_editlattice.h"
#include "BKE_editmesh.h"
#include "BKE_report.h"
+#include "BKE_undo_system.h"
#include "ED_armature.h"
#include "ED_curve.h"
@@ -91,7 +94,7 @@
#include "ED_lattice.h"
#include "ED_object.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_image.h"
#include "RNA_access.h"
@@ -133,7 +136,7 @@ Object *ED_object_active_context(bContext *C)
/* ********* clear/set restrict view *********/
-static int object_hide_view_clear_exec(bContext *C, wmOperator *UNUSED(op))
+static int object_hide_view_clear_exec(bContext *C, wmOperator *op)
{
Main *bmain = CTX_data_main(C);
ScrArea *sa = CTX_wm_area(C);
@@ -141,12 +144,13 @@ static int object_hide_view_clear_exec(bContext *C, wmOperator *UNUSED(op))
Scene *scene = CTX_data_scene(C);
Base *base;
bool changed = false;
+ const bool select = RNA_boolean_get(op->ptr, "select");
/* XXX need a context loop to handle such cases */
for (base = FIRSTBASE; base; base = base->next) {
if ((base->lay & v3d->lay) && base->object->restrictflag & OB_RESTRICT_VIEW) {
if (!(base->object->restrictflag & OB_RESTRICT_SELECT)) {
- base->flag |= SELECT;
+ SET_FLAG_FROM_TEST(base->flag, select, SELECT);
}
base->object->flag = base->flag;
base->object->restrictflag &= ~OB_RESTRICT_VIEW;
@@ -176,6 +180,8 @@ void OBJECT_OT_hide_view_clear(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
static int object_hide_view_set_exec(bContext *C, wmOperator *op)
@@ -350,6 +356,9 @@ static bool ED_object_editmode_load_ex(Main *bmain, Object *obedit, const bool f
if (obedit->type == OB_MESH) {
Mesh *me = obedit->data;
+ if (me->edit_btmesh == NULL) {
+ return false;
+ }
if (me->edit_btmesh->bm->totvert > MESH_MAX_VERTS) {
error("Too many vertices");
@@ -363,15 +372,21 @@ static bool ED_object_editmode_load_ex(Main *bmain, Object *obedit, const bool f
MEM_freeN(me->edit_btmesh);
me->edit_btmesh = NULL;
}
- if (obedit->restore_mode & OB_MODE_WEIGHT_PAINT) {
+ /* will be recalculated as needed. */
+ {
ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
ED_mesh_mirror_topo_table(NULL, NULL, 'e');
}
}
else if (obedit->type == OB_ARMATURE) {
+ const bArmature *arm = obedit->data;
+ if (arm->edbo == NULL) {
+ return false;
+ }
ED_armature_from_edit(obedit->data);
- if (freedata)
+ if (freedata) {
ED_armature_edit_free(obedit->data);
+ }
/* TODO(sergey): Pose channels might have been changed, so need
* to inform dependency graph about this. But is it really the
* best place to do this?
@@ -379,27 +394,46 @@ static bool ED_object_editmode_load_ex(Main *bmain, Object *obedit, const bool f
DAG_relations_tag_update(bmain);
}
else if (ELEM(obedit->type, OB_CURVE, OB_SURF)) {
+ const Curve *cu = obedit->data;
+ if (cu->editnurb == NULL) {
+ return false;
+ }
ED_curve_editnurb_load(obedit);
- if (freedata) ED_curve_editnurb_free(obedit);
+ if (freedata) {
+ ED_curve_editnurb_free(obedit);
+ }
}
else if (obedit->type == OB_FONT) {
+ const Curve *cu = obedit->data;
+ if (cu->editfont == NULL) {
+ return false;
+ }
ED_curve_editfont_load(obedit);
- if (freedata) ED_curve_editfont_free(obedit);
+ if (freedata) {
+ ED_curve_editfont_free(obedit);
+ }
}
else if (obedit->type == OB_LATTICE) {
- ED_lattice_editlatt_load(obedit);
- if (freedata) ED_lattice_editlatt_free(obedit);
+ const Lattice *lt = obedit->data;
+ if (lt->editlatt == NULL) {
+ return false;
+ }
+ BKE_editlattice_load(obedit);
+ if (freedata) {
+ BKE_editlattice_free(obedit);
+ }
}
else if (obedit->type == OB_MBALL) {
+ const MetaBall *mb = obedit->data;
+ if (mb->editelems == NULL) {
+ return false;
+ }
ED_mball_editmball_load(obedit);
- if (freedata) ED_mball_editmball_free(obedit);
+ if (freedata) {
+ ED_mball_editmball_free(obedit);
+ }
}
- /* Tag update so no access to freed data referenced from
- * derived cache will happen.
- */
- DAG_id_tag_update((ID *)obedit->data, 0);
-
return true;
}
@@ -409,17 +443,20 @@ bool ED_object_editmode_load(Object *obedit)
return ED_object_editmode_load_ex(G.main, obedit, false);
}
-void ED_object_editmode_exit(bContext *C, int flag)
+/**
+ * \param C: Can be NULL, only if #EM_DO_UNDO isn't set.
+ * \param flag:
+ * - Only in exceptional cases should #EM_DO_UNDO NOT be in the flag.
+ * - If #EM_FREEDATA isn't in the flag, use ED_object_editmode_load directly.
+ */
+void ED_object_editmode_exit_ex(bContext *C, Scene *scene, Object *obedit, int flag)
{
- /* Note! only in exceptional cases should 'EM_DO_UNDO' NOT be in the flag */
- /* Note! if 'EM_FREEDATA' isn't in the flag, use ED_object_editmode_load directly */
- Scene *scene = CTX_data_scene(C);
- Object *obedit = CTX_data_edit_object(C);
+ BLI_assert(C || !(flag & EM_DO_UNDO));
const bool freedata = (flag & EM_FREEDATA) != 0;
if (flag & EM_WAITCURSOR) waitcursor(1);
- if (ED_object_editmode_load_ex(CTX_data_main(C), obedit, freedata) == false) {
+ if (ED_object_editmode_load_ex(G.main, obedit, freedata) == false) {
/* in rare cases (background mode) its possible active object
* is flagged for editmode, without 'obedit' being set [#35489] */
if (UNLIKELY(scene->basact && (scene->basact->object->mode & OB_MODE_EDIT))) {
@@ -453,7 +490,12 @@ void ED_object_editmode_exit(bContext *C, int flag)
if (flag & EM_DO_UNDO)
ED_undo_push(C, "Editmode");
- WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, scene);
+ if (C != NULL) {
+ WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_MODE_OBJECT, scene);
+ }
+ else {
+ WM_main_add_notifier(NC_SCENE | ND_MODE | NS_MODE_OBJECT, scene);
+ }
obedit->mode &= ~OB_MODE_EDIT;
}
@@ -461,6 +503,12 @@ void ED_object_editmode_exit(bContext *C, int flag)
if (flag & EM_WAITCURSOR) waitcursor(0);
}
+void ED_object_editmode_exit(bContext *C, int flag)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *obedit = CTX_data_edit_object(C);
+ ED_object_editmode_exit_ex(C, scene, obedit, flag);
+}
void ED_object_editmode_enter(bContext *C, int flag)
{
@@ -471,7 +519,7 @@ void ED_object_editmode_enter(bContext *C, int flag)
View3D *v3d = NULL;
bool ok = false;
- if (ID_IS_LINKED_DATABLOCK(scene)) return;
+ if (ID_IS_LINKED(scene)) return;
if (sa && sa->spacetype == SPACE_VIEW3D)
v3d = sa->spacedata.first;
@@ -507,7 +555,7 @@ void ED_object_editmode_enter(bContext *C, int flag)
/* note, when switching scenes the object can have editmode data but
* not be scene->obedit: bug 22954, this avoids calling self eternally */
if ((ob->restore_mode & OB_MODE_EDIT) == 0)
- ED_object_toggle_modes(C, ob->mode);
+ ED_object_mode_toggle(C, ob->mode);
ob->mode = OB_MODE_EDIT;
@@ -518,7 +566,7 @@ void ED_object_editmode_enter(bContext *C, int flag)
const bool use_key_index = mesh_needs_keyindex(ob->data);
- EDBM_mesh_make(scene->toolsettings, ob, use_key_index);
+ EDBM_mesh_make(ob, scene->toolsettings->selectmode, use_key_index);
em = BKE_editmesh_from_object(ob);
if (LIKELY(em)) {
@@ -540,7 +588,7 @@ void ED_object_editmode_enter(bContext *C, int flag)
* BKE_object_obdata_is_libdata that prevent the bugfix #6614, so
* i add this little hack here.
*/
- if (ID_IS_LINKED_DATABLOCK(arm)) {
+ if (ID_IS_LINKED(arm)) {
error_libdata();
return;
}
@@ -569,7 +617,7 @@ void ED_object_editmode_enter(bContext *C, int flag)
else if (ob->type == OB_LATTICE) {
scene->obedit = ob; /* XXX for context */
ok = 1;
- ED_lattice_editlatt_make(ob);
+ BKE_editlattice_make(ob);
WM_event_add_notifier(C, NC_SCENE | ND_MODE | NS_EDITMODE_LATTICE, scene);
}
@@ -610,7 +658,7 @@ static int editmode_toggle_exec(bContext *C, wmOperator *op)
if (!is_mode_set)
ED_object_editmode_enter(C, EM_WAITCURSOR);
else
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR); /* had EM_DO_UNDO but op flag calls undo too [#24685] */
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR); /* had EM_DO_UNDO but op flag calls undo too [#24685] */
ED_space_image_uv_sculpt_update(CTX_wm_manager(C), scene);
@@ -622,7 +670,7 @@ static int editmode_toggle_poll(bContext *C)
Object *ob = CTX_data_active_object(C);
/* covers proxies too */
- if (ELEM(NULL, ob, ob->data) || ID_IS_LINKED_DATABLOCK(ob->data))
+ if (ELEM(NULL, ob, ob->data) || ID_IS_LINKED(ob->data))
return 0;
/* if hidden but in edit mode, we still display */
@@ -655,7 +703,7 @@ static int posemode_exec(bContext *C, wmOperator *op)
Base *base = CTX_data_active_base(C);
Object *ob = base->object;
const int mode_flag = OB_MODE_POSE;
- const bool is_mode_set = (ob->mode & mode_flag) != 0;
+ bool is_mode_set = (ob->mode & mode_flag) != 0;
if (!is_mode_set) {
if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
@@ -666,12 +714,15 @@ static int posemode_exec(bContext *C, wmOperator *op)
if (ob->type == OB_ARMATURE) {
if (ob == CTX_data_edit_object(C)) {
ED_object_editmode_exit(C, EM_FREEDATA | EM_DO_UNDO);
- ED_armature_enter_posemode(C, base);
+ is_mode_set = false;
+ }
+
+ if (is_mode_set) {
+ ED_object_posemode_exit(C, ob);
+ }
+ else {
+ ED_object_posemode_enter(C, ob);
}
- else if (is_mode_set)
- ED_armature_exit_posemode(C, base);
- else
- ED_armature_enter_posemode(C, base);
return OPERATOR_FINISHED;
}
@@ -773,9 +824,9 @@ static void copymenu_logicbricks(Scene *scene, View3D *v3d, Object *ob)
/* now copy it, this also works without logicbricks! */
clear_sca_new_poins_ob(ob);
- copy_sensors(&base->object->sensors, &ob->sensors);
- copy_controllers(&base->object->controllers, &ob->controllers);
- copy_actuators(&base->object->actuators, &ob->actuators);
+ copy_sensors(&base->object->sensors, &ob->sensors, 0);
+ copy_controllers(&base->object->controllers, &ob->controllers, 0);
+ copy_actuators(&base->object->actuators, &ob->actuators, 0);
set_sca_new_poins_ob(base->object);
/* some menu settings */
@@ -849,7 +900,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
Nurb *nu;
bool do_depgraph_update = false;
- if (ID_IS_LINKED_DATABLOCK(scene)) return;
+ if (ID_IS_LINKED(scene)) return;
if (!(ob = OBACT)) return;
@@ -934,7 +985,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
base->object->collision_boundtype = ob->collision_boundtype;
}
base->object->margin = ob->margin;
- base->object->bsoft = copy_bulletsoftbody(ob->bsoft);
+ base->object->bsoft = copy_bulletsoftbody(ob->bsoft, 0);
}
else if (event == 17) { /* tex space */
@@ -1042,7 +1093,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
base->object->softflag = ob->softflag;
if (base->object->soft) sbFree(base->object->soft);
- base->object->soft = copy_softbody(ob->soft, false);
+ base->object->soft = copy_softbody(ob->soft, 0);
if (!modifiers_findByType(base->object, eModifierType_Softbody)) {
BLI_addhead(&base->object->modifiers, modifier_new(eModifierType_Softbody));
@@ -1050,7 +1101,7 @@ static void copy_attr(Main *bmain, Scene *scene, View3D *v3d, short event)
}
else if (event == 26) {
#if 0 // XXX old animation system
- copy_nlastrips(&base->object->nlastrips, &ob->nlastrips);
+ BKE_nlastrip_copy(s(&base->object->nlastrips, &ob->nlastrips);
#endif // XXX old animation system
}
else if (event == 27) { /* autosmooth */
@@ -1158,13 +1209,16 @@ void ED_object_check_force_modifiers(Main *bmain, Scene *scene, Object *object)
/* add/remove modifier as needed */
if (!md) {
- if (pd && (pd->shape == PFIELD_SHAPE_SURFACE) && ELEM(pd->forcefield, PFIELD_GUIDE, PFIELD_TEXTURE) == 0)
- if (ELEM(object->type, OB_MESH, OB_SURF, OB_FONT, OB_CURVE))
+ if (pd && (pd->shape == PFIELD_SHAPE_SURFACE) && !ELEM(pd->forcefield, 0, PFIELD_GUIDE, PFIELD_TEXTURE)) {
+ if (ELEM(object->type, OB_MESH, OB_SURF, OB_FONT, OB_CURVE)) {
ED_object_modifier_add(NULL, bmain, scene, object, NULL, eModifierType_Surface);
+ }
+ }
}
else {
- if (!pd || pd->shape != PFIELD_SHAPE_SURFACE || pd->forcefield != PFIELD_FORCE)
+ if (!pd || (pd->shape != PFIELD_SHAPE_SURFACE) || ELEM(pd->forcefield, 0, PFIELD_GUIDE, PFIELD_TEXTURE)) {
ED_object_modifier_remove(NULL, bmain, object, md);
+ }
}
}
@@ -1437,7 +1491,7 @@ static int shade_smooth_exec(bContext *C, wmOperator *op)
{
data = ob->data;
- if (data && ID_IS_LINKED_DATABLOCK(data)) {
+ if (data && ID_IS_LINKED(data)) {
linked_data = true;
continue;
}
@@ -1520,7 +1574,7 @@ static void UNUSED_FUNCTION(image_aspect) (Scene *scene, View3D *v3d)
int a, b, done;
if (scene->obedit) return; // XXX get from context
- if (ID_IS_LINKED_DATABLOCK(scene)) return;
+ if (ID_IS_LINKED(scene)) return;
for (base = FIRSTBASE; base; base = base->next) {
if (TESTBASELIB(v3d, base)) {
@@ -1571,9 +1625,10 @@ static void UNUSED_FUNCTION(image_aspect) (Scene *scene, View3D *v3d)
}
-static EnumPropertyItem *object_mode_set_itemsf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *object_mode_set_itemsf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
- EnumPropertyItem *input = rna_enum_object_mode_items;
+ const EnumPropertyItem *input = rna_enum_object_mode_items;
EnumPropertyItem *item = NULL;
Object *ob;
bGPdata *gpd;
@@ -1620,91 +1675,6 @@ static EnumPropertyItem *object_mode_set_itemsf(bContext *C, PointerRNA *UNUSED(
return item;
}
-static const char *object_mode_op_string(int mode)
-{
- if (mode & OB_MODE_EDIT)
- return "OBJECT_OT_editmode_toggle";
- if (mode == OB_MODE_SCULPT)
- return "SCULPT_OT_sculptmode_toggle";
- if (mode == OB_MODE_VERTEX_PAINT)
- return "PAINT_OT_vertex_paint_toggle";
- if (mode == OB_MODE_WEIGHT_PAINT)
- return "PAINT_OT_weight_paint_toggle";
- if (mode == OB_MODE_TEXTURE_PAINT)
- return "PAINT_OT_texture_paint_toggle";
- if (mode == OB_MODE_PARTICLE_EDIT)
- return "PARTICLE_OT_particle_edit_toggle";
- if (mode == OB_MODE_POSE)
- return "OBJECT_OT_posemode_toggle";
- if (mode == OB_MODE_GPENCIL)
- return "GPENCIL_OT_editmode_toggle";
- return NULL;
-}
-
-/* checks the mode to be set is compatible with the object
- * should be made into a generic function
- */
-static bool object_mode_compat_test(Object *ob, ObjectMode mode)
-{
- if (ob) {
- if (mode == OB_MODE_OBJECT)
- return true;
- else if (mode == OB_MODE_GPENCIL)
- return true; /* XXX: assume this is the case for now... */
-
- switch (ob->type) {
- case OB_MESH:
- if (mode & (OB_MODE_EDIT | OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT |
- OB_MODE_TEXTURE_PAINT | OB_MODE_PARTICLE_EDIT))
- {
- return true;
- }
- break;
- case OB_CURVE:
- case OB_SURF:
- case OB_FONT:
- case OB_MBALL:
- if (mode & (OB_MODE_EDIT))
- return true;
- break;
- case OB_LATTICE:
- if (mode & (OB_MODE_EDIT | OB_MODE_WEIGHT_PAINT))
- return true;
- break;
- case OB_ARMATURE:
- if (mode & (OB_MODE_EDIT | OB_MODE_POSE))
- return true;
- break;
- }
- }
-
- return false;
-}
-
-/**
- * Sets the mode to a compatible state (use before entering the mode).
- *
- * This is so each mode's exec function can call
- */
-bool ED_object_mode_compat_set(bContext *C, Object *ob, int mode, ReportList *reports)
-{
- bool ok;
- if (!ELEM(ob->mode, mode, OB_MODE_OBJECT)) {
- const char *opstring = object_mode_op_string(ob->mode);
- WM_operator_name_call(C, opstring, WM_OP_EXEC_REGION_WIN, NULL);
- ok = ELEM(ob->mode, mode, OB_MODE_OBJECT);
- if (!ok) {
- wmOperatorType *ot = WM_operatortype_find(opstring, false);
- BKE_reportf(reports, RPT_ERROR, "Unable to execute '%s', error changing modes", ot->name);
- }
- }
- else {
- ok = true;
- }
-
- return ok;
-}
-
static int object_mode_set_poll(bContext *C)
{
/* Since Grease Pencil editmode is also handled here,
@@ -1722,8 +1692,8 @@ static int object_mode_set_exec(bContext *C, wmOperator *op)
{
Object *ob = CTX_data_active_object(C);
bGPdata *gpd = CTX_data_gpencil_data(C);
- ObjectMode mode = RNA_enum_get(op->ptr, "mode");
- ObjectMode restore_mode = (ob) ? ob->mode : OB_MODE_OBJECT;
+ eObjectMode mode = RNA_enum_get(op->ptr, "mode");
+ eObjectMode restore_mode = (ob) ? ob->mode : OB_MODE_OBJECT;
const bool toggle = RNA_boolean_get(op->ptr, "toggle");
if (gpd) {
@@ -1744,7 +1714,7 @@ static int object_mode_set_exec(bContext *C, wmOperator *op)
}
}
- if (!ob || !object_mode_compat_test(ob, mode))
+ if (!ob || !ED_object_mode_compat_test(ob, mode))
return OPERATOR_PASS_THROUGH;
if (ob->mode != mode) {
@@ -1755,20 +1725,20 @@ static int object_mode_set_exec(bContext *C, wmOperator *op)
/* Exit current mode if it's not the mode we're setting */
if (mode != OB_MODE_OBJECT && (ob->mode != mode || toggle)) {
/* Enter new mode */
- ED_object_toggle_modes(C, mode);
+ ED_object_mode_toggle(C, mode);
}
if (toggle) {
/* Special case for Object mode! */
if (mode == OB_MODE_OBJECT && restore_mode == OB_MODE_OBJECT && ob->restore_mode != OB_MODE_OBJECT) {
- ED_object_toggle_modes(C, ob->restore_mode);
+ ED_object_mode_toggle(C, ob->restore_mode);
}
else if (ob->mode == mode) {
/* For toggling, store old mode so we know what to go back to */
ob->restore_mode = restore_mode;
}
else if (ob->restore_mode != OB_MODE_OBJECT && ob->restore_mode != mode) {
- ED_object_toggle_modes(C, ob->restore_mode);
+ ED_object_mode_toggle(C, ob->restore_mode);
}
}
@@ -1800,18 +1770,6 @@ void OBJECT_OT_mode_set(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-
-
-void ED_object_toggle_modes(bContext *C, int mode)
-{
- if (mode != OB_MODE_OBJECT) {
- const char *opstring = object_mode_op_string(mode);
- if (opstring) {
- WM_operator_name_call(C, opstring, WM_OP_EXEC_REGION_WIN, NULL);
- }
- }
-}
-
/************************ Game Properties ***********************/
static int game_property_new_exec(bContext *C, wmOperator *op)
@@ -1936,7 +1894,7 @@ static int game_property_move(bContext *C, wmOperator *op)
void OBJECT_OT_game_property_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_property_move[] = {
+ static const EnumPropertyItem direction_property_move[] = {
{GAME_PROPERTY_MOVE_UP, "UP", 0, "Up", ""},
{GAME_PROPERTY_MOVE_DOWN, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -1969,14 +1927,14 @@ void OBJECT_OT_game_property_move(wmOperatorType *ot)
#define COPY_PROPERTIES_MERGE 2
#define COPY_PROPERTIES_COPY 3
-static EnumPropertyItem game_properties_copy_operations[] = {
+static const EnumPropertyItem game_properties_copy_operations[] = {
{COPY_PROPERTIES_REPLACE, "REPLACE", 0, "Replace Properties", ""},
{COPY_PROPERTIES_MERGE, "MERGE", 0, "Merge Properties", ""},
{COPY_PROPERTIES_COPY, "COPY", 0, "Copy a Property", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem *gameprops_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *gameprops_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = ED_object_active_context(C);
EnumPropertyItem tmp = {0, "", 0, "", ""};
@@ -2106,9 +2064,9 @@ static int logicbricks_copy_exec(bContext *C, wmOperator *UNUSED(op))
/* now copy it, this also works without logicbricks! */
clear_sca_new_poins_ob(ob);
- copy_sensors(&ob_iter->sensors, &ob->sensors);
- copy_controllers(&ob_iter->controllers, &ob->controllers);
- copy_actuators(&ob_iter->actuators, &ob->actuators);
+ copy_sensors(&ob_iter->sensors, &ob->sensors, 0);
+ copy_controllers(&ob_iter->controllers, &ob->controllers, 0);
+ copy_actuators(&ob_iter->actuators, &ob->actuators, 0);
set_sca_new_poins_ob(ob_iter);
/* some menu settings */
@@ -2169,7 +2127,7 @@ static int game_physics_copy_exec(bContext *C, wmOperator *UNUSED(op))
copy_v3_v3(ob_iter->anisotropicFriction, ob->anisotropicFriction);
ob_iter->collision_boundtype = ob->collision_boundtype;
ob_iter->margin = ob->margin;
- ob_iter->bsoft = copy_bulletsoftbody(ob->bsoft);
+ ob_iter->bsoft = copy_bulletsoftbody(ob->bsoft, 0);
if (ob->restrictflag & OB_RESTRICT_RENDER)
ob_iter->restrictflag |= OB_RESTRICT_RENDER;
else
diff --git a/source/blender/editors/object/object_group.c b/source/blender/editors/object/object_group.c
index 0fe43c44d7d..46c2c4e4b7d 100644
--- a/source/blender/editors/object/object_group.c
+++ b/source/blender/editors/object/object_group.c
@@ -63,7 +63,7 @@
/********************* 3d view operators ***********************/
/* can be called with C == NULL */
-static EnumPropertyItem *group_object_active_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *group_object_active_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob;
EnumPropertyItem *item = NULL, item_tmp = {0};
@@ -528,8 +528,7 @@ static int group_unlink_exec(bContext *C, wmOperator *UNUSED(op))
if (!group)
return OPERATOR_CANCELLED;
- BKE_libblock_unlink(bmain, group, false, false);
- BKE_libblock_free(bmain, group);
+ BKE_libblock_delete(bmain, group);
WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, NULL);
diff --git a/source/blender/editors/object/object_hook.c b/source/blender/editors/object/object_hook.c
index 438c10c51fa..e9203fa1972 100644
--- a/source/blender/editors/object/object_hook.c
+++ b/source/blender/editors/object/object_hook.c
@@ -316,7 +316,7 @@ static bool object_hook_index_array(Scene *scene, Object *obedit,
BMEditMesh *em;
EDBM_mesh_load(obedit);
- EDBM_mesh_make(scene->toolsettings, obedit, true);
+ EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true);
DAG_id_tag_update(obedit->data, 0);
@@ -661,7 +661,7 @@ static int object_hook_remove_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem *hook_mod_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *hook_mod_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = CTX_data_edit_object(C);
EnumPropertyItem tmp = {0, "", 0, "", ""};
diff --git a/source/blender/editors/object/object_intern.h b/source/blender/editors/object/object_intern.h
index 9710e4f843d..d9524f40a3c 100644
--- a/source/blender/editors/object/object_intern.h
+++ b/source/blender/editors/object/object_intern.h
@@ -140,16 +140,6 @@ void OBJECT_OT_hook_assign(struct wmOperatorType *ot);
void OBJECT_OT_hook_reset(struct wmOperatorType *ot);
void OBJECT_OT_hook_recenter(struct wmOperatorType *ot);
-/* object_lattice.c */
-void LATTICE_OT_select_all(struct wmOperatorType *ot);
-void LATTICE_OT_select_more(struct wmOperatorType *ot);
-void LATTICE_OT_select_less(struct wmOperatorType *ot);
-void LATTICE_OT_select_ungrouped(struct wmOperatorType *ot);
-void LATTICE_OT_select_random(struct wmOperatorType *ot);
-void LATTICE_OT_select_mirror(struct wmOperatorType *ot);
-void LATTICE_OT_make_regular(struct wmOperatorType *ot);
-void LATTICE_OT_flip(struct wmOperatorType *ot);
-
/* object_group.c */
void GROUP_OT_create(struct wmOperatorType *ot);
void GROUP_OT_objects_remove_all(struct wmOperatorType *ot);
@@ -186,6 +176,7 @@ void OBJECT_OT_skin_loose_mark_clear(struct wmOperatorType *ot);
void OBJECT_OT_skin_radii_equalize(struct wmOperatorType *ot);
void OBJECT_OT_skin_armature_create(struct wmOperatorType *ot);
void OBJECT_OT_laplaciandeform_bind(struct wmOperatorType *ot);
+void OBJECT_OT_surfacedeform_bind(struct wmOperatorType *ot);
/* object_constraint.c */
void OBJECT_OT_constraint_add(struct wmOperatorType *ot);
diff --git a/source/blender/editors/object/object_modes.c b/source/blender/editors/object/object_modes.c
new file mode 100644
index 00000000000..d70a69e30f8
--- /dev/null
+++ b/source/blender/editors/object/object_modes.c
@@ -0,0 +1,178 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Blender Foundation, 2002-2008 full recode
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/object/object_modes.c
+ * \ingroup edobj
+ *
+ * General utils to handle mode switching,
+ * actual mode switching logic is per-object type.
+ */
+
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+#include "BKE_report.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_object.h"
+
+static const char *object_mode_op_string(eObjectMode mode)
+{
+ if (mode & OB_MODE_EDIT)
+ return "OBJECT_OT_editmode_toggle";
+ if (mode == OB_MODE_SCULPT)
+ return "SCULPT_OT_sculptmode_toggle";
+ if (mode == OB_MODE_VERTEX_PAINT)
+ return "PAINT_OT_vertex_paint_toggle";
+ if (mode == OB_MODE_WEIGHT_PAINT)
+ return "PAINT_OT_weight_paint_toggle";
+ if (mode == OB_MODE_TEXTURE_PAINT)
+ return "PAINT_OT_texture_paint_toggle";
+ if (mode == OB_MODE_PARTICLE_EDIT)
+ return "PARTICLE_OT_particle_edit_toggle";
+ if (mode == OB_MODE_POSE)
+ return "OBJECT_OT_posemode_toggle";
+ if (mode == OB_MODE_GPENCIL)
+ return "GPENCIL_OT_editmode_toggle";
+ return NULL;
+}
+
+/**
+ * Checks the mode to be set is compatible with the object
+ * should be made into a generic function
+ */
+bool ED_object_mode_compat_test(const Object *ob, eObjectMode mode)
+{
+ if (ob) {
+ if (mode == OB_MODE_OBJECT)
+ return true;
+ else if (mode == OB_MODE_GPENCIL)
+ return true; /* XXX: assume this is the case for now... */
+
+ switch (ob->type) {
+ case OB_MESH:
+ if (mode & (OB_MODE_EDIT | OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT |
+ OB_MODE_TEXTURE_PAINT | OB_MODE_PARTICLE_EDIT))
+ {
+ return true;
+ }
+ break;
+ case OB_CURVE:
+ case OB_SURF:
+ case OB_FONT:
+ case OB_MBALL:
+ if (mode & (OB_MODE_EDIT))
+ return true;
+ break;
+ case OB_LATTICE:
+ if (mode & (OB_MODE_EDIT | OB_MODE_WEIGHT_PAINT))
+ return true;
+ break;
+ case OB_ARMATURE:
+ if (mode & (OB_MODE_EDIT | OB_MODE_POSE))
+ return true;
+ break;
+ }
+ }
+
+ return false;
+}
+
+
+/**
+ * Sets the mode to a compatible state (use before entering the mode).
+ *
+ * This is so each mode's exec function can call
+ */
+bool ED_object_mode_compat_set(bContext *C, Object *ob, eObjectMode mode, ReportList *reports)
+{
+ bool ok;
+ if (!ELEM(ob->mode, mode, OB_MODE_OBJECT)) {
+ const char *opstring = object_mode_op_string(ob->mode);
+ WM_operator_name_call(C, opstring, WM_OP_EXEC_REGION_WIN, NULL);
+ ok = ELEM(ob->mode, mode, OB_MODE_OBJECT);
+ if (!ok) {
+ wmOperatorType *ot = WM_operatortype_find(opstring, false);
+ BKE_reportf(reports, RPT_ERROR, "Unable to execute '%s', error changing modes", ot->name);
+ }
+ }
+ else {
+ ok = true;
+ }
+
+ return ok;
+}
+
+void ED_object_mode_toggle(bContext *C, eObjectMode mode)
+{
+ if (mode != OB_MODE_OBJECT) {
+ const char *opstring = object_mode_op_string(mode);
+ if (opstring) {
+ WM_operator_name_call(C, opstring, WM_OP_EXEC_REGION_WIN, NULL);
+ }
+ }
+}
+
+/* Wrapper for operator */
+void ED_object_mode_set(bContext *C, eObjectMode mode)
+{
+#if 0
+ wmOperatorType *ot = WM_operatortype_find("OBJECT_OT_mode_set", false);
+ PointerRNA ptr;
+
+ WM_operator_properties_create_ptr(&ptr, ot);
+ RNA_enum_set(&ptr, "mode", mode);
+ RNA_boolean_set(&ptr, "toggle", false);
+ WM_operator_name_call_ptr(C, ot, WM_OP_EXEC_DEFAULT, &ptr);
+ WM_operator_properties_free(&ptr);
+#else
+ Object *ob = CTX_data_active_object(C);
+ if (ob == NULL) {
+ return;
+ }
+ if (ob->mode == mode) {
+ /* pass */
+ }
+ else if (mode != OB_MODE_OBJECT) {
+ if (ob && (ob->mode & mode) == 0) {
+ /* needed so we don't do undo pushes. */
+ wmWindowManager *wm = CTX_wm_manager(C);
+ wm->op_undo_depth++;
+ ED_object_mode_toggle(C, mode);
+ wm->op_undo_depth--;
+ }
+ }
+ else {
+ /* needed so we don't do undo pushes. */
+ wmWindowManager *wm = CTX_wm_manager(C);
+ wm->op_undo_depth++;
+ ED_object_mode_toggle(C, ob->mode);
+ wm->op_undo_depth--;
+
+ }
+#endif
+}
diff --git a/source/blender/editors/object/object_modifier.c b/source/blender/editors/object/object_modifier.c
index 06f495fb9f1..bf99d1c52ac 100644
--- a/source/blender/editors/object/object_modifier.c
+++ b/source/blender/editors/object/object_modifier.c
@@ -40,7 +40,7 @@
#include "DNA_key_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_scene_types.h"
#include "BLI_bitmap.h"
@@ -744,10 +744,12 @@ static int modifier_add_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem *modifier_add_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *modifier_add_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = ED_object_active_context(C);
- EnumPropertyItem *item = NULL, *md_item, *group_item = NULL;
+ EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *md_item, *group_item = NULL;
const ModifierTypeInfo *mti;
int totitem = 0, a;
@@ -793,7 +795,7 @@ void OBJECT_OT_modifier_add(wmOperatorType *ot)
/* identifiers */
ot->name = "Add Modifier";
- ot->description = "Add a modifier to the active object";
+ ot->description = "Add a procedural operation/effect to the active object";
ot->idname = "OBJECT_OT_modifier_add";
/* api callbacks */
@@ -817,9 +819,9 @@ int edit_modifier_poll_generic(bContext *C, StructRNA *rna_type, int obtype_flag
PointerRNA ptr = CTX_data_pointer_get_type(C, "modifier", rna_type);
Object *ob = (ptr.id.data) ? ptr.id.data : ED_object_active_context(C);
- if (!ob || ID_IS_LINKED_DATABLOCK(ob)) return 0;
+ if (!ob || ID_IS_LINKED(ob)) return 0;
if (obtype_flag && ((1 << ob->type) & obtype_flag) == 0) return 0;
- if (ptr.id.data && ID_IS_LINKED_DATABLOCK(ptr.id.data)) return 0;
+ if (ptr.id.data && ID_IS_LINKED(ptr.id.data)) return 0;
return 1;
}
@@ -1019,7 +1021,7 @@ static int modifier_apply_invoke(bContext *C, wmOperator *op, const wmEvent *UNU
return OPERATOR_CANCELLED;
}
-static EnumPropertyItem modifier_apply_as_items[] = {
+static const EnumPropertyItem modifier_apply_as_items[] = {
{MODIFIER_APPLY_DATA, "DATA", 0, "Object Data", "Apply modifier to the object's data"},
{MODIFIER_APPLY_SHAPE, "SHAPE", 0, "New Shape", "Apply deform-only modifier to a new shape on this object"},
{0, NULL, 0, NULL, NULL}
@@ -1484,7 +1486,6 @@ static int skin_root_mark_exec(bContext *C, wmOperator *UNUSED(op))
Object *ob = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(ob);
BMesh *bm = em->bm;
- const int cd_vert_skin_offset = CustomData_get_offset(&bm->vdata, CD_MVERT_SKIN);
BMVert *bm_vert;
BMIter bm_iter;
GSet *visited;
@@ -1493,6 +1494,8 @@ static int skin_root_mark_exec(bContext *C, wmOperator *UNUSED(op))
BKE_mesh_ensure_skin_customdata(ob->data);
+ const int cd_vert_skin_offset = CustomData_get_offset(&bm->vdata, CD_MVERT_SKIN);
+
BM_ITER_MESH (bm_vert, &bm_iter, bm, BM_VERTS_OF_MESH) {
if (BM_elem_flag_test(bm_vert, BM_ELEM_SELECT) &&
BLI_gset_add(visited, bm_vert))
@@ -1572,7 +1575,7 @@ static int skin_loose_mark_clear_exec(bContext *C, wmOperator *op)
void OBJECT_OT_skin_loose_mark_clear(wmOperatorType *ot)
{
- static EnumPropertyItem action_items[] = {
+ static const EnumPropertyItem action_items[] = {
{SKIN_LOOSE_MARK, "MARK", 0, "Mark", "Mark selected vertices as loose"},
{SKIN_LOOSE_CLEAR, "CLEAR", 0, "Clear", "Set selected vertices as not loose"},
{0, NULL, 0, NULL, NULL}
@@ -1657,7 +1660,7 @@ static void skin_armature_bone_create(Object *skin_ob,
v = (e->v1 == parent_v ? e->v2 : e->v1);
- bone = ED_armature_edit_bone_add(arm, "Bone");
+ bone = ED_armature_ebone_add(arm, "Bone");
bone->parent = parent_bone;
bone->flag |= BONE_CONNECTED;
@@ -1730,7 +1733,7 @@ static Object *modifier_skin_armature_create(Main *bmain, Scene *scene, Object *
* a fake root bone (have it going off in the Y direction
* (arbitrary) */
if (emap[v].count > 1) {
- bone = ED_armature_edit_bone_add(arm, "Bone");
+ bone = ED_armature_ebone_add(arm, "Bone");
copy_v3_v3(bone->head, me->mvert[v].co);
copy_v3_v3(bone->tail, me->mvert[v].co);
@@ -1931,7 +1934,7 @@ static int meshdeform_bind_exec(bContext *C, wmOperator *op)
int mode = mmd->modifier.mode;
/* force modifier to run, it will call binding routine */
- mmd->bindfunc = mesh_deform_bind;
+ mmd->bindfunc = ED_mesh_deform_bind_callback;
mmd->modifier.mode |= eModifierMode_Realtime;
if (ob->type == OB_MESH) {
@@ -2294,3 +2297,56 @@ void OBJECT_OT_laplaciandeform_bind(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL;
edit_modifier_properties(ot);
}
+
+/************************ sdef bind operator *********************/
+
+static int surfacedeform_bind_poll(bContext *C)
+{
+ return edit_modifier_poll_generic(C, &RNA_SurfaceDeformModifier, 0);
+}
+
+static int surfacedeform_bind_exec(bContext *C, wmOperator *op)
+{
+ Object *ob = ED_object_active_context(C);
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)edit_modifier_property_get(op, ob, eModifierType_SurfaceDeform);
+
+ if (!smd)
+ return OPERATOR_CANCELLED;
+
+ if (smd->flags & MOD_SDEF_BIND) {
+ smd->flags &= ~MOD_SDEF_BIND;
+ }
+ else if (smd->target) {
+ smd->flags |= MOD_SDEF_BIND;
+ }
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_MODIFIER, ob);
+
+ return OPERATOR_FINISHED;
+}
+
+static int surfacedeform_bind_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
+{
+ if (edit_modifier_invoke_properties(C, op))
+ return surfacedeform_bind_exec(C, op);
+ else
+ return OPERATOR_CANCELLED;
+}
+
+void OBJECT_OT_surfacedeform_bind(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Surface Deform Bind";
+ ot->description = "Bind mesh to target in surface deform modifier";
+ ot->idname = "OBJECT_OT_surfacedeform_bind";
+
+ /* api callbacks */
+ ot->poll = surfacedeform_bind_poll;
+ ot->invoke = surfacedeform_bind_invoke;
+ ot->exec = surfacedeform_bind_exec;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_INTERNAL;
+ edit_modifier_properties(ot);
+}
diff --git a/source/blender/editors/object/object_ops.c b/source/blender/editors/object/object_ops.c
index 7e7e1ef182c..c090b8684d0 100644
--- a/source/blender/editors/object/object_ops.c
+++ b/source/blender/editors/object/object_ops.c
@@ -219,15 +219,6 @@ void ED_operatortypes_object(void)
WM_operatortype_append(OBJECT_OT_shape_key_mirror);
WM_operatortype_append(OBJECT_OT_shape_key_move);
- WM_operatortype_append(LATTICE_OT_select_all);
- WM_operatortype_append(LATTICE_OT_select_more);
- WM_operatortype_append(LATTICE_OT_select_less);
- WM_operatortype_append(LATTICE_OT_select_ungrouped);
- WM_operatortype_append(LATTICE_OT_select_random);
- WM_operatortype_append(LATTICE_OT_select_mirror);
- WM_operatortype_append(LATTICE_OT_make_regular);
- WM_operatortype_append(LATTICE_OT_flip);
-
WM_operatortype_append(OBJECT_OT_group_add);
WM_operatortype_append(OBJECT_OT_group_link);
WM_operatortype_append(OBJECT_OT_group_remove);
@@ -255,6 +246,7 @@ void ED_operatortypes_object(void)
WM_operatortype_append(OBJECT_OT_data_transfer);
WM_operatortype_append(OBJECT_OT_datalayout_transfer);
+ WM_operatortype_append(OBJECT_OT_surfacedeform_bind);
}
void ED_operatormacros_object(void)
@@ -373,13 +365,6 @@ void ED_keymap_object(wmKeyConfig *keyconf)
kmi = WM_keymap_add_item(keymap, "OBJECT_OT_scale_clear", SKEY, KM_PRESS, KM_ALT, 0);
RNA_boolean_set(kmi->ptr, "clear_delta", false);
- kmi = WM_keymap_add_item(keymap, "OBJECT_OT_location_clear", GKEY, KM_PRESS, KM_ALT | KM_SHIFT, 0);
- RNA_boolean_set(kmi->ptr, "clear_delta", true);
- kmi = WM_keymap_add_item(keymap, "OBJECT_OT_rotation_clear", RKEY, KM_PRESS, KM_ALT | KM_SHIFT, 0);
- RNA_boolean_set(kmi->ptr, "clear_delta", true);
- kmi = WM_keymap_add_item(keymap, "OBJECT_OT_scale_clear", SKEY, KM_PRESS, KM_ALT | KM_SHIFT, 0);
- RNA_boolean_set(kmi->ptr, "clear_delta", true);
-
WM_keymap_verify_item(keymap, "OBJECT_OT_origin_clear", OKEY, KM_PRESS, KM_ALT, 0);
WM_keymap_add_item(keymap, "OBJECT_OT_hide_view_clear", HKEY, KM_PRESS, KM_ALT, 0);
@@ -449,30 +434,6 @@ void ED_keymap_object(wmKeyConfig *keyconf)
kmi = WM_keymap_add_item(keymap, "OBJECT_OT_subdivision_set", ZEROKEY + i, KM_PRESS, KM_CTRL, 0);
RNA_int_set(kmi->ptr, "level", i);
}
-
- /* ############################################################################ */
- /* ################################ LATTICE ################################### */
- /* ############################################################################ */
-
- keymap = WM_keymap_find(keyconf, "Lattice", 0, 0);
- keymap->poll = ED_operator_editlattice;
-
- kmi = WM_keymap_add_item(keymap, "LATTICE_OT_select_all", AKEY, KM_PRESS, 0, 0);
- RNA_enum_set(kmi->ptr, "action", SEL_TOGGLE);
- kmi = WM_keymap_add_item(keymap, "LATTICE_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0);
- RNA_enum_set(kmi->ptr, "action", SEL_INVERT);
- WM_keymap_add_item(keymap, "LATTICE_OT_select_more", PADPLUSKEY, KM_PRESS, KM_CTRL, 0);
- WM_keymap_add_item(keymap, "LATTICE_OT_select_less", PADMINUS, KM_PRESS, KM_CTRL, 0);
-
- WM_keymap_add_item(keymap, "OBJECT_OT_vertex_parent_set", PKEY, KM_PRESS, KM_CTRL, 0);
-
- WM_keymap_add_item(keymap, "LATTICE_OT_flip", FKEY, KM_PRESS, KM_CTRL, 0);
-
- /* menus */
- WM_keymap_add_menu(keymap, "VIEW3D_MT_hook", HKEY, KM_PRESS, KM_CTRL, 0);
-
- ED_keymap_proportional_cycle(keyconf, keymap);
- ED_keymap_proportional_editmode(keyconf, keymap, false);
}
void ED_keymap_proportional_cycle(struct wmKeyConfig *UNUSED(keyconf), struct wmKeyMap *keymap)
diff --git a/source/blender/editors/object/object_relations.c b/source/blender/editors/object/object_relations.c
index b5fbe4ba586..4618d05133e 100644
--- a/source/blender/editors/object/object_relations.c
+++ b/source/blender/editors/object/object_relations.c
@@ -72,6 +72,7 @@
#include "BKE_global.h"
#include "BKE_group.h"
#include "BKE_fcurve.h"
+#include "BKE_idprop.h"
#include "BKE_lamp.h"
#include "BKE_lattice.h"
#include "BKE_library.h"
@@ -82,6 +83,7 @@
#include "BKE_mball.h"
#include "BKE_mesh.h"
#include "BKE_modifier.h"
+#include "BKE_node.h"
#include "BKE_object.h"
#include "BKE_report.h"
#include "BKE_sca.h"
@@ -138,7 +140,7 @@ static int vertex_parent_set_exec(bContext *C, wmOperator *op)
BMEditMesh *em;
EDBM_mesh_load(obedit);
- EDBM_mesh_make(scene->toolsettings, obedit, true);
+ EDBM_mesh_make(obedit, scene->toolsettings->selectmode, true);
DAG_id_tag_update(obedit->data, 0);
@@ -293,23 +295,24 @@ static int make_proxy_invoke(bContext *C, wmOperator *op, const wmEvent *event)
Object *ob = ED_object_active_context(C);
/* sanity checks */
- if (!scene || ID_IS_LINKED_DATABLOCK(scene) || !ob)
+ if (!scene || ID_IS_LINKED(scene) || !ob)
return OPERATOR_CANCELLED;
/* Get object to work on - use a menu if we need to... */
- if (ob->dup_group && ID_IS_LINKED_DATABLOCK(ob->dup_group)) {
+ if (ob->dup_group && ID_IS_LINKED(ob->dup_group)) {
/* gives menu with list of objects in group */
/* proxy_group_objects_menu(C, op, ob, ob->dup_group); */
WM_enum_search_invoke(C, op, event);
return OPERATOR_CANCELLED;
}
- else if (ID_IS_LINKED_DATABLOCK(ob)) {
+ else if (ID_IS_LINKED(ob)) {
uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("OK?"), ICON_QUESTION);
uiLayout *layout = UI_popup_menu_layout(pup);
/* create operator menu item with relevant properties filled in */
+ PointerRNA opptr_dummy;
uiItemFullO_ptr(layout, op->type, op->type->name, ICON_NONE, NULL,
- WM_OP_EXEC_REGION_WIN, UI_ITEM_O_RETURN_PROPS);
+ WM_OP_EXEC_REGION_WIN, 0, &opptr_dummy);
/* present the menu and be done... */
UI_popup_menu_end(C, pup);
@@ -378,7 +381,7 @@ static int make_proxy_exec(bContext *C, wmOperator *op)
}
/* Generic itemf's for operators that take library args */
-static EnumPropertyItem *proxy_group_object_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *proxy_group_object_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem item_tmp = {0}, *item = NULL;
@@ -635,7 +638,7 @@ bool ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object
/* setup dummy 'generator' modifier here to get 1-1 correspondence still working */
if (!fcu->bezt && !fcu->fpt && !fcu->modifiers.first)
- add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR);
+ add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_GENERATOR, fcu);
}
/* fall back on regular parenting now (for follow only) */
@@ -770,12 +773,12 @@ bool ED_object_parent_set(ReportList *reports, Main *bmain, Scene *scene, Object
}
else if (pararm && (ob->type == OB_MESH) && (par->type == OB_ARMATURE)) {
if (partype == PAR_ARMATURE_NAME)
- create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_NAME, false);
+ ED_object_vgroup_calc_from_armature(reports, scene, ob, par, ARM_GROUPS_NAME, false);
else if (partype == PAR_ARMATURE_ENVELOPE)
- create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_ENVELOPE, xmirror);
+ ED_object_vgroup_calc_from_armature(reports, scene, ob, par, ARM_GROUPS_ENVELOPE, xmirror);
else if (partype == PAR_ARMATURE_AUTO) {
WM_cursor_wait(1);
- create_vgroups_from_armature(reports, scene, ob, par, ARM_GROUPS_AUTO, xmirror);
+ ED_object_vgroup_calc_from_armature(reports, scene, ob, par, ARM_GROUPS_AUTO, xmirror);
WM_cursor_wait(0);
}
/* get corrected inverse */
@@ -896,12 +899,13 @@ static int parent_set_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent
#if 0
uiItemEnumO_ptr(layout, ot, NULL, 0, "type", PAR_OBJECT);
#else
- opptr = uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, IFACE_("Object"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "type", PAR_OBJECT);
RNA_boolean_set(&opptr, "keep_transform", false);
- opptr = uiItemFullO_ptr(layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT,
- UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(
+ layout, ot, IFACE_("Object (Keep Transform)"), ICON_NONE,
+ NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "type", PAR_OBJECT);
RNA_boolean_set(&opptr, "keep_transform", true);
#endif
@@ -1122,7 +1126,7 @@ enum {
CLEAR_TRACK_KEEP_TRANSFORM = 2,
};
-static EnumPropertyItem prop_clear_track_types[] = {
+static const EnumPropertyItem prop_clear_track_types[] = {
{CLEAR_TRACK, "CLEAR", 0, "Clear Track", ""},
{CLEAR_TRACK_KEEP_TRANSFORM, "CLEAR_KEEP_TRANSFORM", 0, "Clear and Keep Transformation (Clear Track)", ""},
{0, NULL, 0, NULL, NULL}
@@ -1191,7 +1195,7 @@ enum {
CREATE_TRACK_LOCKTRACK = 3,
};
-static EnumPropertyItem prop_make_track_types[] = {
+static const EnumPropertyItem prop_make_track_types[] = {
{CREATE_TRACK_DAMPTRACK, "DAMPTRACK", 0, "Damped Track Constraint", ""},
{CREATE_TRACK_TRACKTO, "TRACKTO", 0, "Track To Constraint", ""},
{CREATE_TRACK_LOCKTRACK, "LOCKTRACK", 0, "Lock Track Constraint", ""},
@@ -1468,7 +1472,7 @@ static int make_links_scene_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- if (ID_IS_LINKED_DATABLOCK(scene_to)) {
+ if (ID_IS_LINKED(scene_to)) {
BKE_report(op->reports, RPT_ERROR, "Cannot link objects into a linked scene");
return OPERATOR_CANCELLED;
}
@@ -1579,13 +1583,13 @@ static int make_links_data_exec(bContext *C, wmOperator *op)
DAG_id_tag_update(&ob_dst->id, OB_RECALC_DATA);
break;
case MAKE_LINKS_ANIMDATA:
- BKE_animdata_copy_id((ID *)ob_dst, (ID *)ob_src, false);
+ BKE_animdata_copy_id(bmain, (ID *)ob_dst, (ID *)ob_src, false);
if (ob_dst->data && ob_src->data) {
- if (ID_IS_LINKED_DATABLOCK(obdata_id)) {
+ if (ID_IS_LINKED(obdata_id)) {
is_lib = true;
break;
}
- BKE_animdata_copy_id((ID *)ob_dst->data, (ID *)ob_src->data, false);
+ BKE_animdata_copy_id(bmain, (ID *)ob_dst->data, (ID *)ob_src->data, false);
}
DAG_id_tag_update(&ob_dst->id, OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME);
break;
@@ -1623,7 +1627,7 @@ static int make_links_data_exec(bContext *C, wmOperator *op)
Curve *cu_src = ob_src->data;
Curve *cu_dst = ob_dst->data;
- if (ID_IS_LINKED_DATABLOCK(obdata_id)) {
+ if (ID_IS_LINKED(obdata_id)) {
is_lib = true;
break;
}
@@ -1703,7 +1707,7 @@ void OBJECT_OT_make_links_scene(wmOperatorType *ot)
void OBJECT_OT_make_links_data(wmOperatorType *ot)
{
- static EnumPropertyItem make_links_items[] = {
+ static const EnumPropertyItem make_links_items[] = {
{MAKE_LINKS_OBDATA, "OBDATA", 0, "Object Data", ""},
{MAKE_LINKS_MATERIALS, "MATERIAL", 0, "Materials", ""},
{MAKE_LINKS_ANIMDATA, "ANIMATION", 0, "Animation Data", ""},
@@ -1747,7 +1751,7 @@ static void single_object_users(Main *bmain, Scene *scene, View3D *v3d, const in
ob = base->object;
if ((base->flag & flag) == flag) {
- if (!ID_IS_LINKED_DATABLOCK(ob) && ob->id.us > 1) {
+ if (!ID_IS_LINKED(ob) && ob->id.us > 1) {
/* base gets copy of object */
base->object = obn = ID_NEW_SET(ob, BKE_object_copy(bmain, ob));
@@ -1837,7 +1841,7 @@ static void new_id_matar(Main *bmain, Material **matar, const int totcol)
for (a = 0; a < totcol; a++) {
id = (ID *)matar[a];
- if (id && !ID_IS_LINKED_DATABLOCK(id)) {
+ if (id && !ID_IS_LINKED(id)) {
if (id->newid) {
matar[a] = (Material *)id->newid;
id_us_plus(id->newid);
@@ -1865,10 +1869,10 @@ static void single_obdata_users(Main *bmain, Scene *scene, const int flag)
for (base = FIRSTBASE; base; base = base->next) {
ob = base->object;
- if (!ID_IS_LINKED_DATABLOCK(ob) && (base->flag & flag) == flag) {
+ if (!ID_IS_LINKED(ob) && (base->flag & flag) == flag) {
id = ob->data;
- if (id && id->us > 1 && !ID_IS_LINKED_DATABLOCK(id)) {
+ if (id && id->us > 1 && !ID_IS_LINKED(id)) {
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
switch (ob->type) {
@@ -1946,7 +1950,7 @@ static void single_object_action_users(Scene *scene, const int flag)
for (base = FIRSTBASE; base; base = base->next) {
ob = base->object;
- if (!ID_IS_LINKED_DATABLOCK(ob) && (flag == 0 || (base->flag & SELECT)) ) {
+ if (!ID_IS_LINKED(ob) && (flag == 0 || (base->flag & SELECT)) ) {
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
BKE_animdata_copy_id_action(&ob->id, false);
}
@@ -1963,7 +1967,7 @@ static void single_mat_users(Main *bmain, Scene *scene, const int flag, const bo
for (base = FIRSTBASE; base; base = base->next) {
ob = base->object;
- if (!ID_IS_LINKED_DATABLOCK(ob) && (flag == 0 || (base->flag & SELECT)) ) {
+ if (!ID_IS_LINKED(ob) && (flag == 0 || (base->flag & SELECT)) ) {
for (a = 1; a <= ob->totcol; a++) {
ma = give_current_material(ob, a);
if (ma) {
@@ -2101,30 +2105,54 @@ void ED_object_single_users(Main *bmain, Scene *scene, const bool full, const bo
single_tex_users_expand(bmain);
}
- BKE_main_id_clear_newpoins(bmain);
- DAG_relations_tag_update(bmain);
-}
+ /* Relink nodetrees' pointers that have been duplicated. */
+ FOREACH_NODETREE(bmain, ntree, id)
+ {
+ /* This is a bit convoluted, we want to root ntree of copied IDs and only those,
+ * so we first check that old ID has been copied and that ntree is root tree of old ID,
+ * then get root tree of new ID and remap its pointers to new ID... */
+ if (id->newid && (&ntree->id != id)) {
+ ntree = ntreeFromID(id->newid);
+ BKE_libblock_relink_to_newid(&ntree->id);
+ }
+ } FOREACH_NODETREE_END
-/******************************* Make Local ***********************************/
+ /* Relink datablock pointer properties */
+ {
+ IDP_RelinkProperty(scene->id.properties);
-/* helper for below, ma was checked to be not NULL */
-static void make_local_makelocalmaterial(Material *ma)
-{
- AnimData *adt;
- int b;
+ for (Base *base = scene->base.first; base; base = base->next) {
+ Object *ob = base->object;
+ if (!ID_IS_LINKED(ob)) {
+ IDP_RelinkProperty(ob->id.properties);
+ }
+ }
- id_make_local(G.main, &ma->id, false, false);
+ if (scene->nodetree) {
+ IDP_RelinkProperty(scene->nodetree->id.properties);
+ for (bNode *node = scene->nodetree->nodes.first; node; node = node->next) {
+ IDP_RelinkProperty(node->prop);
+ }
+ }
- for (b = 0; b < MAX_MTEX; b++)
- if (ma->mtex[b] && ma->mtex[b]->tex)
- id_make_local(G.main, &ma->mtex[b]->tex->id, false, false);
+ if (scene->gpd) {
+ IDP_RelinkProperty(scene->gpd->id.properties);
+ }
- adt = BKE_animdata_from_id(&ma->id);
- if (adt) BKE_animdata_make_local(adt);
+ if (scene->world) {
+ IDP_RelinkProperty(scene->world->id.properties);
+ }
- /* nodetree? XXX */
+ if (scene->clip) {
+ IDP_RelinkProperty(scene->clip->id.properties);
+ }
+ }
+ BKE_main_id_clear_newpoins(bmain);
+ DAG_relations_tag_update(bmain);
}
+/******************************* Make Local ***********************************/
+
enum {
MAKE_LOCAL_SELECT_OB = 1,
MAKE_LOCAL_SELECT_OBDATA = 2,
@@ -2193,7 +2221,7 @@ static bool make_local_all__instance_indirect_unused(Main *bmain, Scene *scene)
bool changed = false;
for (ob = bmain->object.first; ob; ob = ob->id.next) {
- if (ID_IS_LINKED_DATABLOCK(ob) && (ob->id.us == 0)) {
+ if (ID_IS_LINKED(ob) && (ob->id.us == 0)) {
Base *base;
id_us_plus(&ob->id);
@@ -2210,129 +2238,148 @@ static bool make_local_all__instance_indirect_unused(Main *bmain, Scene *scene)
return changed;
}
-static int make_local_exec(bContext *C, wmOperator *op)
+static void make_local_animdata_tag_strips(ListBase *strips)
{
- Main *bmain = CTX_data_main(C);
- Scene *scene = CTX_data_scene(C);
- AnimData *adt;
- ParticleSystem *psys;
- Material *ma, ***matarar;
- Lamp *la;
- ID *id;
- const int mode = RNA_enum_get(op->ptr, "type");
- int a, b;
-
- if (mode == MAKE_LOCAL_ALL) {
- /* de-select so the user can differentiate newly instanced from existing objects */
- BKE_scene_base_deselect_all(scene);
+ NlaStrip *strip;
- if (make_local_all__instance_indirect_unused(bmain, scene)) {
- BKE_report(op->reports, RPT_INFO,
- "Orphan library objects added to the current scene to avoid loss");
+ for (strip = strips->first; strip; strip = strip->next) {
+ if (strip->act) {
+ strip->act->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ }
+ if (strip->remap && strip->remap->target) {
+ strip->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
}
- BKE_library_make_local(bmain, NULL, NULL, false, false); /* NULL is all libs */
- WM_event_add_notifier(C, NC_WINDOW, NULL);
- return OPERATOR_FINISHED;
+ make_local_animdata_tag_strips(&strip->strips);
}
+}
- tag_localizable_objects(C, mode);
-
- CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
- {
- if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
- continue;
+/* Tag all actions used by given animdata to be made local. */
+static void make_local_animdata_tag(AnimData *adt)
+{
+ if (adt) {
+ /* Actions - Active and Temp */
+ if (adt->action) {
+ adt->action->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ }
+ if (adt->tmpact) {
+ adt->tmpact->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ }
+ /* Remaps */
+ if (adt->remap && adt->remap->target) {
+ adt->remap->target->id.tag &= ~LIB_TAG_PRE_EXISTING;
}
- if (ob->id.lib)
- id_make_local(bmain, &ob->id, false, false);
- }
- CTX_DATA_END;
+ /* Drivers */
+ /* TODO: need to handle the ID-targets too? */
- /* maybe object pointers */
- CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
- {
- if (ob->id.lib == NULL) {
- ID_NEW_REMAP(ob->parent);
+ /* NLA Data */
+ for (NlaTrack *nlt = adt->nla_tracks.first; nlt; nlt = nlt->next) {
+ make_local_animdata_tag_strips(&nlt->strips);
}
}
- CTX_DATA_END;
-
- CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
- {
- if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
- continue;
- }
+}
- id = ob->data;
+static void make_local_material_tag(Material *ma)
+{
+ if (ma) {
+ ma->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ make_local_animdata_tag(BKE_animdata_from_id(&ma->id));
- if (id && (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL))) {
- id_make_local(bmain, id, false, false);
- adt = BKE_animdata_from_id(id);
- if (adt) BKE_animdata_make_local(adt);
+ /* About nodetrees: root one is made local together with material, others we keep linked for now... */
- /* tag indirect data direct */
- matarar = give_matarar(ob);
- if (matarar) {
- for (a = 0; a < ob->totcol; a++) {
- ma = (*matarar)[a];
- if (ma)
- id_lib_extern(&ma->id);
- }
+ for (int a = 0; a < MAX_MTEX; a++) {
+ if (ma->mtex[a] && ma->mtex[a]->tex) {
+ ma->mtex[a]->tex->id.tag &= ~LIB_TAG_PRE_EXISTING;
}
}
+ }
+}
- for (psys = ob->particlesystem.first; psys; psys = psys->next)
- id_make_local(bmain, &psys->part->id, false, false);
+static int make_local_exec(bContext *C, wmOperator *op)
+{
+ Main *bmain = CTX_data_main(C);
+ Scene *scene = CTX_data_scene(C);
+ ParticleSystem *psys;
+ Material *ma, ***matarar;
+ Lamp *la;
+ const int mode = RNA_enum_get(op->ptr, "type");
+ int a;
+
+ /* Note: we (ab)use LIB_TAG_PRE_EXISTING to cherry pick which ID to make local... */
+ if (mode == MAKE_LOCAL_ALL) {
+ BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
- adt = BKE_animdata_from_id(&ob->id);
- if (adt) BKE_animdata_make_local(adt);
+ /* de-select so the user can differentiate newly instanced from existing objects */
+ BKE_scene_base_deselect_all(scene);
+
+ if (make_local_all__instance_indirect_unused(bmain, scene)) {
+ BKE_report(op->reports, RPT_INFO, "Orphan library objects added to the current scene to avoid loss");
+ }
}
- CTX_DATA_END;
+ else {
+ BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
+ tag_localizable_objects(C, mode);
- if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
CTX_DATA_BEGIN (C, Object *, ob, selected_objects)
{
if ((ob->id.tag & LIB_TAG_DOIT) == 0) {
continue;
}
- if (ob->type == OB_LAMP) {
- la = ob->data;
-
- for (b = 0; b < MAX_MTEX; b++)
- if (la->mtex[b] && la->mtex[b]->tex)
- id_make_local(bmain, &la->mtex[b]->tex->id, false, false);
+ ob->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ make_local_animdata_tag(BKE_animdata_from_id(&ob->id));
+ for (psys = ob->particlesystem.first; psys; psys = psys->next) {
+ psys->part->id.tag &= ~LIB_TAG_PRE_EXISTING;
}
- else {
+
+ if (mode == MAKE_LOCAL_SELECT_OBDATA_MATERIAL) {
for (a = 0; a < ob->totcol; a++) {
ma = ob->mat[a];
- if (ma)
- make_local_makelocalmaterial(ma);
+ if (ma) {
+ make_local_material_tag(ma);
+ }
}
matarar = (Material ***)give_matarar(ob);
if (matarar) {
for (a = 0; a < ob->totcol; a++) {
ma = (*matarar)[a];
- if (ma)
- make_local_makelocalmaterial(ma);
+ if (ma) {
+ make_local_material_tag(ma);
+ }
+ }
+ }
+
+ if (ob->type == OB_LAMP) {
+ BLI_assert(ob->data != NULL);
+ la = ob->data;
+ for (a = 0; a < MAX_MTEX; a++) {
+ if (la->mtex[a] && la->mtex[a]->tex) {
+ la->id.tag &= ~LIB_TAG_PRE_EXISTING;
+ }
}
}
}
+
+ if (ELEM(mode, MAKE_LOCAL_SELECT_OBDATA, MAKE_LOCAL_SELECT_OBDATA_MATERIAL) && ob->data != NULL) {
+ ID *ob_data = ob->data;
+ ob_data->tag &= ~LIB_TAG_PRE_EXISTING;
+ make_local_animdata_tag(BKE_animdata_from_id(ob_data));
+ }
}
CTX_DATA_END;
}
- BKE_main_id_clear_newpoins(bmain);
- WM_event_add_notifier(C, NC_WINDOW, NULL);
+ BKE_library_make_local(bmain, NULL, NULL, true, false); /* NULL is all libs */
+ WM_event_add_notifier(C, NC_WINDOW, NULL);
return OPERATOR_FINISHED;
}
void OBJECT_OT_make_local(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{MAKE_LOCAL_SELECT_OB, "SELECT_OBJECT", 0, "Selected Objects", ""},
{MAKE_LOCAL_SELECT_OBDATA, "SELECT_OBDATA", 0, "Selected Objects and Data", ""},
{MAKE_LOCAL_SELECT_OBDATA_MATERIAL, "SELECT_OBDATA_MATERIAL", 0, "Selected Objects, Data and Materials", ""},
@@ -2407,7 +2454,7 @@ static int make_single_user_exec(bContext *C, wmOperator *op)
void OBJECT_OT_make_single_user(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{MAKE_SINGLE_USER_SELECTED, "SELECTED_OBJECTS", 0, "Selected Objects", ""},
{MAKE_SINGLE_USER_ALL, "ALL", 0, "All", ""},
{0, NULL, 0, NULL, NULL}};
diff --git a/source/blender/editors/object/object_select.c b/source/blender/editors/object/object_select.c
index b5131df3eaa..8d5c2387fe9 100644
--- a/source/blender/editors/object/object_select.c
+++ b/source/blender/editors/object/object_select.c
@@ -198,7 +198,7 @@ enum {
OBJECT_SELECT_LINKED_LIBRARY_OBDATA
};
-static EnumPropertyItem prop_select_linked_types[] = {
+static const EnumPropertyItem prop_select_linked_types[] = {
//{OBJECT_SELECT_LINKED_IPO, "IPO", 0, "Object IPO", ""}, // XXX deprecated animation system stuff...
{OBJECT_SELECT_LINKED_OBDATA, "OBDATA", 0, "Object Data", ""},
{OBJECT_SELECT_LINKED_MATERIAL, "MATERIAL", 0, "Material", ""},
@@ -527,7 +527,7 @@ enum {
OBJECT_GRPSEL_LAMP_TYPE = 12,
};
-static EnumPropertyItem prop_select_grouped_types[] = {
+static const EnumPropertyItem prop_select_grouped_types[] = {
{OBJECT_GRPSEL_CHILDREN_RECURSIVE, "CHILDREN_RECURSIVE", 0, "Children", ""},
{OBJECT_GRPSEL_CHILDREN, "CHILDREN", 0, "Immediate Children", ""},
{OBJECT_GRPSEL_PARENT, "PARENT", 0, "Parent", ""},
@@ -982,7 +982,7 @@ static int object_select_by_layer_exec(bContext *C, wmOperator *op)
void OBJECT_OT_select_by_layer(wmOperatorType *ot)
{
- static EnumPropertyItem match_items[] = {
+ static const EnumPropertyItem match_items[] = {
{OB_SEL_LAYERMATCH_EXACT, "EXACT", 0, "Exact Match", ""},
{OB_SEL_LAYERMATCH_SHARED, "SHARED", 0, "Shared Layers", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/object/object_shapekey.c b/source/blender/editors/object/object_shapekey.c
index e04114761e4..27da607c696 100644
--- a/source/blender/editors/object/object_shapekey.c
+++ b/source/blender/editors/object/object_shapekey.c
@@ -225,7 +225,7 @@ static int shape_key_mode_poll(bContext *C)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data) && ob->mode != OB_MODE_EDIT);
+ return (ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data) && ob->mode != OB_MODE_EDIT);
}
static int shape_key_mode_exists_poll(bContext *C)
@@ -234,7 +234,7 @@ static int shape_key_mode_exists_poll(bContext *C)
ID *data = (ob) ? ob->data : NULL;
/* same as shape_key_mode_poll */
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data) && ob->mode != OB_MODE_EDIT) &&
+ return (ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data) && ob->mode != OB_MODE_EDIT) &&
/* check a keyblock exists */
(BKE_keyblock_from_object(ob) != NULL);
}
@@ -246,7 +246,7 @@ static int shape_key_move_poll(bContext *C)
ID *data = (ob) ? ob->data : NULL;
Key *key = BKE_key_from_object(ob);
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data) &&
+ return (ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data) &&
ob->mode != OB_MODE_EDIT && key && key->totkey > 1);
}
@@ -254,7 +254,7 @@ static int shape_key_poll(bContext *C)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data));
+ return (ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data));
}
static int shape_key_add_exec(bContext *C, wmOperator *op)
@@ -477,7 +477,7 @@ static int shape_key_move_exec(bContext *C, wmOperator *op)
void OBJECT_OT_shape_key_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{KB_MOVE_TOP, "TOP", 0, "Top", "Top of the list"},
{KB_MOVE_UP, "UP", 0, "Up", ""},
{KB_MOVE_DOWN, "DOWN", 0, "Down", ""},
diff --git a/source/blender/editors/object/object_transform.c b/source/blender/editors/object/object_transform.c
index 4d7d7df0d2f..e29d49d00cb 100644
--- a/source/blender/editors/object/object_transform.c
+++ b/source/blender/editors/object/object_transform.c
@@ -35,6 +35,7 @@
#include "DNA_armature_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meta_types.h"
+#include "DNA_lamp_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_group_types.h"
@@ -414,7 +415,10 @@ static void ignore_parent_tx(Main *bmain, Scene *scene, Object *ob)
}
}
-static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_loc, bool apply_rot, bool apply_scale)
+static int apply_objects_internal(
+ bContext *C, ReportList *reports,
+ bool apply_loc, bool apply_rot, bool apply_scale,
+ bool do_props)
{
Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
@@ -433,7 +437,7 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
changed = false;
}
- if (ID_IS_LINKED_DATABLOCK(obdata)) {
+ if (ID_IS_LINKED(obdata)) {
BKE_reportf(reports, RPT_ERROR,
"Cannot apply to library data: Object \"%s\", %s \"%s\", aborting",
ob->id.name + 2, BKE_idcode_to_name(GS(obdata->name)), obdata->name + 2);
@@ -469,6 +473,18 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
changed = false;
}
}
+
+ if (ob->type == OB_LAMP) {
+ Lamp *la = ob->data;
+ if (la->type == LA_AREA) {
+ if (apply_rot || apply_loc) {
+ BKE_reportf(reports, RPT_ERROR,
+ "Area Lamps can only have scale applied: \"%s\"",
+ ob->id.name + 2);
+ changed = false;
+ }
+ }
+ }
}
CTX_DATA_END;
@@ -531,7 +547,7 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
BKE_mesh_calc_normals(me);
}
else if (ob->type == OB_ARMATURE) {
- ED_armature_apply_transform(ob, mat);
+ ED_armature_transform_apply(ob, mat, do_props);
}
else if (ob->type == OB_LATTICE) {
Lattice *lt = ob->data;
@@ -540,12 +556,12 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
}
else if (ob->type == OB_MBALL) {
MetaBall *mb = ob->data;
- BKE_mball_transform(mb, mat);
+ BKE_mball_transform(mb, mat, do_props);
}
else if (ELEM(ob->type, OB_CURVE, OB_SURF)) {
Curve *cu = ob->data;
scale = mat3_to_scale(rsmat);
- BKE_curve_transform_ex(cu, mat, true, scale);
+ BKE_curve_transform_ex(cu, mat, true, do_props, scale);
}
else if (ob->type == OB_FONT) {
Curve *cu = ob->data;
@@ -561,7 +577,9 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
tb->h *= scale;
}
- cu->fsize *= scale;
+ if (do_props) {
+ cu->fsize *= scale;
+ }
}
else if (ob->type == OB_CAMERA) {
MovieClip *clip = BKE_object_movieclip_get(scene, ob, false);
@@ -596,6 +614,22 @@ static int apply_objects_internal(bContext *C, ReportList *reports, bool apply_l
ob->empty_drawsize *= max_scale;
}
}
+ else if (ob->type == OB_LAMP) {
+ Lamp *la = ob->data;
+ if (la->type != LA_AREA) {
+ continue;
+ }
+
+ bool keeps_aspect_ratio = compare_ff_relative(rsmat[0][0], rsmat[1][1], FLT_EPSILON, 64);
+ if ((la->area_shape == LA_AREA_SQUARE) && !keeps_aspect_ratio) {
+ la->area_shape = LA_AREA_RECT;
+ la->area_sizey = la->area_size;
+ }
+
+ la->area_size *= rsmat[0][0];
+ la->area_sizey *= rsmat[1][1];
+ la->area_sizez *= rsmat[2][2];
+ }
else {
continue;
}
@@ -677,9 +711,10 @@ static int object_transform_apply_exec(bContext *C, wmOperator *op)
const bool loc = RNA_boolean_get(op->ptr, "location");
const bool rot = RNA_boolean_get(op->ptr, "rotation");
const bool sca = RNA_boolean_get(op->ptr, "scale");
+ const bool do_props = RNA_boolean_get(op->ptr, "properties");
if (loc || rot || sca) {
- return apply_objects_internal(C, op->reports, loc, rot, sca);
+ return apply_objects_internal(C, op->reports, loc, rot, sca, do_props);
}
else {
/* allow for redo */
@@ -704,6 +739,8 @@ void OBJECT_OT_transform_apply(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "location", 0, "Location", "");
RNA_def_boolean(ot->srna, "rotation", 0, "Rotation", "");
RNA_def_boolean(ot->srna, "scale", 0, "Scale", "");
+ RNA_def_boolean(ot->srna, "properties", true, "Apply Properties",
+ "Modify properties such as curve vertex radius, font size and bone envelope");
}
/********************* Set Object Center ************************/
@@ -712,7 +749,8 @@ enum {
GEOMETRY_TO_ORIGIN = 0,
ORIGIN_TO_GEOMETRY,
ORIGIN_TO_CURSOR,
- ORIGIN_TO_CENTER_OF_MASS
+ ORIGIN_TO_CENTER_OF_MASS_SURFACE,
+ ORIGIN_TO_CENTER_OF_MASS_VOLUME,
};
static int object_origin_set_exec(bContext *C, wmOperator *op)
@@ -834,7 +872,7 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
if (ob->data == NULL) {
/* special support for dupligroups */
if ((ob->transflag & OB_DUPLIGROUP) && ob->dup_group && (ob->dup_group->id.tag & LIB_TAG_DOIT) == 0) {
- if (ID_IS_LINKED_DATABLOCK(ob->dup_group)) {
+ if (ID_IS_LINKED(ob->dup_group)) {
tot_lib_error++;
}
else {
@@ -859,17 +897,28 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
}
}
}
- else if (ID_IS_LINKED_DATABLOCK(ob->data)) {
+ else if (ID_IS_LINKED(ob->data)) {
tot_lib_error++;
}
if (obedit == NULL && ob->type == OB_MESH) {
Mesh *me = ob->data;
- if (centermode == ORIGIN_TO_CURSOR) { /* done */ }
- else if (centermode == ORIGIN_TO_CENTER_OF_MASS) { BKE_mesh_center_centroid(me, cent); }
- else if (around == V3D_AROUND_CENTER_MEAN) { BKE_mesh_center_median(me, cent); }
- else { BKE_mesh_center_bounds(me, cent); }
+ if (centermode == ORIGIN_TO_CURSOR) {
+ /* done */
+ }
+ else if (centermode == ORIGIN_TO_CENTER_OF_MASS_SURFACE) {
+ BKE_mesh_center_of_surface(me, cent);
+ }
+ else if (centermode == ORIGIN_TO_CENTER_OF_MASS_VOLUME) {
+ BKE_mesh_center_of_volume(me, cent);
+ }
+ else if (around == V3D_AROUND_CENTER_MEAN) {
+ BKE_mesh_center_median(me, cent);
+ }
+ else {
+ BKE_mesh_center_bounds(me, cent);
+ }
negate_v3_v3(cent_neg, cent);
BKE_mesh_translate(me, cent_neg, 1);
@@ -923,8 +972,8 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
cent[2] = 0.0f;
- cu->xof = cu->xof - (cent[0] / cu->fsize);
- cu->yof = cu->yof - (cent[1] / cu->fsize);
+ cu->xof = cu->xof - cent[0];
+ cu->yof = cu->yof - cent[1];
tot_change++;
cu->id.tag |= LIB_TAG_DOIT;
@@ -1074,18 +1123,21 @@ static int object_origin_set_exec(bContext *C, wmOperator *op)
void OBJECT_OT_origin_set(wmOperatorType *ot)
{
- static EnumPropertyItem prop_set_center_types[] = {
+ static const EnumPropertyItem prop_set_center_types[] = {
{GEOMETRY_TO_ORIGIN, "GEOMETRY_ORIGIN", 0, "Geometry to Origin", "Move object geometry to object origin"},
{ORIGIN_TO_GEOMETRY, "ORIGIN_GEOMETRY", 0, "Origin to Geometry",
- "Move object origin to center of object geometry"},
+ "Calculate the center of geometry based on the current pivot point (median, otherwise bounding-box)"},
{ORIGIN_TO_CURSOR, "ORIGIN_CURSOR", 0, "Origin to 3D Cursor",
- "Move object origin to position of the 3D cursor"},
- {ORIGIN_TO_CENTER_OF_MASS, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass",
- "Move object origin to the object center of mass (assuming uniform density)"},
+ "Move object origin to position of the 3D cursor"},
+ /* Intentional naming mismatch since some scripts refer to this. */
+ {ORIGIN_TO_CENTER_OF_MASS_SURFACE, "ORIGIN_CENTER_OF_MASS", 0, "Origin to Center of Mass (Surface)",
+ "Calculate the center of mass from the surface area"},
+ {ORIGIN_TO_CENTER_OF_MASS_VOLUME, "ORIGIN_CENTER_OF_VOLUME", 0, "Origin to Center of Mass (Volume)",
+ "Calculate the center of mass from the volume (must be manifold geometry with consistent normals)"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_set_bounds_types[] = {
+ static const EnumPropertyItem prop_set_bounds_types[] = {
{V3D_AROUND_CENTER_MEAN, "MEDIAN", 0, "Median Center", ""},
{V3D_AROUND_CENTER_BOUNDS, "BOUNDS", 0, "Bounds Center", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/object/object_vgroup.c b/source/blender/editors/object/object_vgroup.c
index 3c406764157..c6c20182ac3 100644
--- a/source/blender/editors/object/object_vgroup.c
+++ b/source/blender/editors/object/object_vgroup.c
@@ -50,7 +50,7 @@
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BLI_linklist_stack.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BKE_context.h"
@@ -238,6 +238,9 @@ bool ED_vgroup_parray_alloc(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, co
}
return false;
}
+
+ default:
+ break;
}
}
@@ -250,9 +253,10 @@ bool ED_vgroup_parray_alloc(ID *id, MDeformVert ***dvert_arr, int *dvert_tot, co
*
* \note \a dvert_array has mirrored weights filled in, incase cleanup operations are needed on both.
*/
-void ED_vgroup_parray_mirror_sync(Object *ob,
- MDeformVert **dvert_array, const int dvert_tot,
- const bool *vgroup_validmap, const int vgroup_tot)
+void ED_vgroup_parray_mirror_sync(
+ Object *ob,
+ MDeformVert **dvert_array, const int dvert_tot,
+ const bool *vgroup_validmap, const int vgroup_tot)
{
BMEditMesh *em = BKE_editmesh_from_object(ob);
MDeformVert **dvert_array_all = NULL;
@@ -295,8 +299,9 @@ void ED_vgroup_parray_mirror_sync(Object *ob,
*
* similar to #ED_vgroup_parray_mirror_sync but only fill in mirror points.
*/
-void ED_vgroup_parray_mirror_assign(Object *ob,
- MDeformVert **dvert_array, const int dvert_tot)
+void ED_vgroup_parray_mirror_assign(
+ Object *ob,
+ MDeformVert **dvert_array, const int dvert_tot)
{
BMEditMesh *em = BKE_editmesh_from_object(ob);
MDeformVert **dvert_array_all = NULL;
@@ -327,9 +332,10 @@ void ED_vgroup_parray_mirror_assign(Object *ob,
MEM_freeN(dvert_array_all);
}
-void ED_vgroup_parray_remove_zero(MDeformVert **dvert_array, const int dvert_tot,
- const bool *vgroup_validmap, const int vgroup_tot,
- const float epsilon, const bool keep_single)
+void ED_vgroup_parray_remove_zero(
+ MDeformVert **dvert_array, const int dvert_tot,
+ const bool *vgroup_validmap, const int vgroup_tot,
+ const float epsilon, const bool keep_single)
{
MDeformVert *dv;
int i;
@@ -479,9 +485,10 @@ void ED_vgroup_parray_from_weight_array(
/* TODO, cache flip data to speedup calls within a loop. */
-static void mesh_defvert_mirror_update_internal(Object *ob,
- MDeformVert *dvert_dst, MDeformVert *dvert_src,
- const int def_nr)
+static void mesh_defvert_mirror_update_internal(
+ Object *ob,
+ MDeformVert *dvert_dst, MDeformVert *dvert_src,
+ const int def_nr)
{
if (def_nr == -1) {
/* all vgroups, add groups where neded */
@@ -499,8 +506,9 @@ static void mesh_defvert_mirror_update_internal(Object *ob,
}
}
-static void ED_mesh_defvert_mirror_update_em(Object *ob, BMVert *eve, int def_nr, int vidx,
- const int cd_dvert_offset)
+static void ED_mesh_defvert_mirror_update_em(
+ Object *ob, BMVert *eve, int def_nr, int vidx,
+ const int cd_dvert_offset)
{
Mesh *me = ob->data;
BMEditMesh *em = me->edit_btmesh;
@@ -663,7 +671,7 @@ static void vgroup_copy_active_to_sel(Object *ob, eVGroupSelect subset_type)
/***********************Start weight transfer (WT)*********************************/
-static EnumPropertyItem WT_vertex_group_select_item[] = {
+static const EnumPropertyItem WT_vertex_group_select_item[] = {
{WT_VGROUP_ACTIVE,
"ACTIVE", 0, "Active Group", "The active Vertex Group"},
{WT_VGROUP_BONE_SELECT,
@@ -675,7 +683,7 @@ static EnumPropertyItem WT_vertex_group_select_item[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
+const EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
const bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free, const unsigned int selection_mask)
{
@@ -683,9 +691,10 @@ EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
EnumPropertyItem *item = NULL;
int totitem = 0;
-
- if (!C) /* needed for docs and i18n tools */
+ if (C == NULL) {
+ /* needed for docs and i18n tools */
return WT_vertex_group_select_item;
+ }
ob = CTX_data_active_object(C);
if (selection_mask & (1 << WT_VGROUP_ACTIVE))
@@ -707,26 +716,30 @@ EnumPropertyItem *ED_object_vgroup_selection_itemf_helper(
return item;
}
-static EnumPropertyItem *rna_vertex_group_with_single_itemf(bContext *C, PointerRNA *ptr,
- PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *rna_vertex_group_with_single_itemf(
+ bContext *C, PointerRNA *ptr,
+ PropertyRNA *prop, bool *r_free)
{
return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, r_free, WT_VGROUP_MASK_ALL);
}
-static EnumPropertyItem *rna_vertex_group_select_itemf(bContext *C, PointerRNA *ptr,
- PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *rna_vertex_group_select_itemf(
+ bContext *C, PointerRNA *ptr,
+ PropertyRNA *prop, bool *r_free)
{
- return ED_object_vgroup_selection_itemf_helper(C, ptr, prop, r_free, WT_VGROUP_MASK_ALL & ~(1 << WT_VGROUP_ACTIVE));
+ return ED_object_vgroup_selection_itemf_helper(
+ C, ptr, prop, r_free, WT_VGROUP_MASK_ALL & ~(1 << WT_VGROUP_ACTIVE));
}
static void vgroup_operator_subset_select_props(wmOperatorType *ot, bool use_active)
{
PropertyRNA *prop;
- prop = RNA_def_enum(ot->srna,
- "group_select_mode", DummyRNA_NULL_items,
- use_active ? WT_VGROUP_ACTIVE : WT_VGROUP_ALL, "Subset",
- "Define which subset of Groups shall be used");
+ prop = RNA_def_enum(
+ ot->srna,
+ "group_select_mode", DummyRNA_NULL_items,
+ use_active ? WT_VGROUP_ACTIVE : WT_VGROUP_ALL, "Subset",
+ "Define which subset of Groups shall be used");
if (use_active) {
RNA_def_enum_funcs(prop, rna_vertex_group_with_single_itemf);
@@ -743,9 +756,10 @@ static void vgroup_operator_subset_select_props(wmOperatorType *ot, bool use_act
/* for Mesh in Object mode */
/* allows editmode for Lattice */
-static void ED_vgroup_nr_vert_add(Object *ob,
- const int def_nr, const int vertnum,
- const float weight, const int assignmode)
+static void ED_vgroup_nr_vert_add(
+ Object *ob,
+ const int def_nr, const int vertnum,
+ const float weight, const int assignmode)
{
/* add the vert to the deform group with the
* specified number
@@ -1173,7 +1187,7 @@ static int *getSurroundingVerts(Mesh *me, int vert, int *count)
}
/* Append a and b verts to array, if not yet present. */
- k = BLI_array_count(verts);
+ k = BLI_array_len(verts);
/* XXX Maybe a == b is enough? */
while (k-- && !(a == b && a == -1)) {
if (verts[k] == a)
@@ -1195,7 +1209,7 @@ static int *getSurroundingVerts(Mesh *me, int vert, int *count)
}
/* Do not free the array! */
- *count = BLI_array_count(verts);
+ *count = BLI_array_len(verts);
return verts;
}
@@ -1216,9 +1230,10 @@ static void getSingleCoordinate(MVert *points, int count, float coord[3])
* compute the amount of vertical distance relative to the plane and store it in dists,
* then get the horizontal and vertical change and store them in changes
*/
-static void getVerticalAndHorizontalChange(const float norm[3], float d, const float coord[3],
- const float start[3], float distToStart,
- float *end, float (*changes)[2], float *dists, int index)
+static void getVerticalAndHorizontalChange(
+ const float norm[3], float d, const float coord[3],
+ const float start[3], float distToStart,
+ float *end, float (*changes)[2], float *dists, int index)
{
/* A = Q - ((Q - P).N)N
* D = (a * x0 + b * y0 +c * z0 + d) */
@@ -1269,8 +1284,9 @@ static DerivedMesh *dm_deform_recalc(Scene *scene, Object *ob)
* norm and d are the plane's properties for the equation: ax + by + cz + d = 0
* coord is a point on the plane
*/
-static void moveCloserToDistanceFromPlane(Scene *scene, Object *ob, Mesh *me, int index, float norm[3],
- float coord[3], float d, float distToBe, float strength, float cp)
+static void moveCloserToDistanceFromPlane(
+ Scene *scene, Object *ob, Mesh *me, int index, float norm[3],
+ float coord[3], float d, float distToBe, float strength, float cp)
{
DerivedMesh *dm;
MDeformWeight *dw;
@@ -1490,9 +1506,10 @@ static void vgroup_fix(Scene *scene, Object *ob, float distToBe, float strength,
}
}
-static void vgroup_levels_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot,
- const int UNUSED(subset_count),
- const float offset, const float gain)
+static void vgroup_levels_subset(
+ Object *ob, const bool *vgroup_validmap, const int vgroup_tot,
+ const int UNUSED(subset_count),
+ const float offset, const float gain)
{
MDeformWeight *dw;
MDeformVert *dv, **dvert_array = NULL;
@@ -1527,8 +1544,9 @@ static void vgroup_levels_subset(Object *ob, const bool *vgroup_validmap, const
}
if (use_mirror && use_vert_sel) {
- ED_vgroup_parray_mirror_sync(ob, dvert_array, dvert_tot,
- vgroup_validmap, vgroup_tot);
+ ED_vgroup_parray_mirror_sync(
+ ob, dvert_array, dvert_tot,
+ vgroup_validmap, vgroup_tot);
}
MEM_freeN(dvert_array);
@@ -1585,12 +1603,14 @@ static bool vgroup_normalize_all(
/* in case its not selected */
if ((dv = dvert_array[i])) {
if (lock_flags) {
- defvert_normalize_lock_map(dv, vgroup_validmap, vgroup_tot,
- lock_flags, defbase_tot);
+ defvert_normalize_lock_map(
+ dv, vgroup_validmap, vgroup_tot,
+ lock_flags, defbase_tot);
}
else if (lock_active) {
- defvert_normalize_lock_single(dv, vgroup_validmap, vgroup_tot,
- def_nr);
+ defvert_normalize_lock_single(
+ dv, vgroup_validmap, vgroup_tot,
+ def_nr);
}
else {
defvert_normalize_subset(dv, vgroup_validmap, vgroup_tot);
@@ -1620,7 +1640,7 @@ enum {
VGROUP_INVERT
};
-static EnumPropertyItem vgroup_lock_actions[] = {
+static const EnumPropertyItem vgroup_lock_actions[] = {
{VGROUP_TOGGLE, "TOGGLE", 0, "Toggle", "Unlock all vertex groups if there is at least one locked group, lock all in other case"},
{VGROUP_LOCK, "LOCK", 0, "Lock", "Lock all vertex groups"},
{VGROUP_UNLOCK, "UNLOCK", 0, "Unlock", "Unlock all vertex groups"},
@@ -1657,9 +1677,10 @@ static void vgroup_lock_all(Object *ob, int action)
}
}
-static void vgroup_invert_subset(Object *ob,
- const bool *vgroup_validmap, const int vgroup_tot,
- const int UNUSED(subset_count), const bool auto_assign, const bool auto_remove)
+static void vgroup_invert_subset(
+ Object *ob,
+ const bool *vgroup_validmap, const int vgroup_tot,
+ const int UNUSED(subset_count), const bool auto_assign, const bool auto_remove)
{
MDeformWeight *dw;
MDeformVert *dv, **dvert_array = NULL;
@@ -1698,31 +1719,27 @@ static void vgroup_invert_subset(Object *ob,
}
if (use_mirror && use_vert_sel) {
- ED_vgroup_parray_mirror_sync(ob, dvert_array, dvert_tot,
- vgroup_validmap, vgroup_tot);
+ ED_vgroup_parray_mirror_sync(
+ ob, dvert_array, dvert_tot,
+ vgroup_validmap, vgroup_tot);
}
if (auto_remove) {
- ED_vgroup_parray_remove_zero(dvert_array, dvert_tot,
- vgroup_validmap, vgroup_tot,
- 0.0f, false);
+ ED_vgroup_parray_remove_zero(
+ dvert_array, dvert_tot,
+ vgroup_validmap, vgroup_tot,
+ 0.0f, false);
}
MEM_freeN(dvert_array);
}
}
-enum {
- WEIGHT_SMOOTH_ALL = -1,
- WEIGHT_SMOOTH_DESELECT = false,
- WEIGHT_SMOOTH_SELECT = true,
-};
-
static void vgroup_smooth_subset(
Object *ob, const bool *vgroup_validmap, const int vgroup_tot,
const int subset_count,
const float fac, const int repeat,
- const float fac_expand, const int source)
+ const float fac_expand)
{
const float ifac = 1.0f - fac;
MDeformVert **dvert_array = NULL;
@@ -1730,6 +1747,8 @@ static void vgroup_smooth_subset(
int *vgroup_subset_map = BLI_array_alloca(vgroup_subset_map, subset_count);
float *vgroup_subset_weights = BLI_array_alloca(vgroup_subset_weights, subset_count);
const bool use_mirror = (ob->type == OB_MESH) ? (((Mesh *)ob->data)->editflag & ME_EDIT_MIRROR_X) != 0 : false;
+ const bool use_select = vertex_group_use_vert_sel(ob);
+ const bool use_hide = use_select;
const int expand_sign = signum_i(fac_expand);
const float expand = fabsf(fac_expand);
@@ -1773,19 +1792,26 @@ static void vgroup_smooth_subset(
verts_used = MEM_mallocN(sizeof(*verts_used) * dvert_tot, __func__);
STACK_INIT(verts_used, dvert_tot);
+#define IS_BM_VERT_READ(v) \
+ (use_hide ? (BM_elem_flag_test(v, BM_ELEM_HIDDEN) == 0) : true)
+#define IS_BM_VERT_WRITE(v) \
+ (use_select ? (BM_elem_flag_test(v, BM_ELEM_SELECT) != 0) : true)
+
+#define IS_ME_VERT_READ(v) \
+ (use_hide ? (((v)->flag & ME_HIDE) == 0) : true)
+#define IS_ME_VERT_WRITE(v) \
+ (use_select ? (((v)->flag & SELECT) != 0) : true)
/* initialize used verts */
if (bm) {
for (int i = 0; i < dvert_tot; i++) {
BMVert *v = BM_vert_at_index(bm, i);
- if (BM_elem_flag_test(v, BM_ELEM_SELECT)) {
+ if (IS_BM_VERT_WRITE(v)) {
BMIter eiter;
BMEdge *e;
BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
BMVert *v_other = BM_edge_other_vert(e, v);
- if ((source == WEIGHT_SMOOTH_ALL) ||
- (source == (BM_elem_flag_test(v_other, BM_ELEM_SELECT) != 0)))
- {
+ if (IS_BM_VERT_READ(v_other)) {
STACK_PUSH(verts_used, i);
break;
}
@@ -1795,13 +1821,12 @@ static void vgroup_smooth_subset(
}
else {
for (int i = 0; i < dvert_tot; i++) {
- MVert *v = &me->mvert[i];
- if (v->flag & SELECT) {
+ const MVert *v = &me->mvert[i];
+ if (IS_ME_VERT_WRITE(v)) {
for (int j = 0; j < emap[i].count; j++) {
- MVert *v_other = &me->mvert[emap[i].indices[j]];
- if ((source == WEIGHT_SMOOTH_ALL) ||
- (source == ((v_other->flag & SELECT) != 0)))
- {
+ const MEdge *e = &me->medge[emap[i].indices[j]];
+ const MVert *v_other = &me->mvert[(e->v1 == i) ? e->v2 : e->v1];
+ if (IS_ME_VERT_READ(v_other)) {
STACK_PUSH(verts_used, i);
break;
}
@@ -1854,13 +1879,11 @@ static void vgroup_smooth_subset(
BMEdge *e;
/* checked already */
- BLI_assert(BM_elem_flag_test(v, BM_ELEM_SELECT));
+ BLI_assert(IS_BM_VERT_WRITE(v));
BM_ITER_ELEM (e, &eiter, v, BM_EDGES_OF_VERT) {
BMVert *v_other = BM_edge_other_vert(e, v);
- if ((source == WEIGHT_SMOOTH_ALL) ||
- (source == (BM_elem_flag_test(v_other, BM_ELEM_SELECT) != 0)))
- {
+ if (IS_BM_VERT_READ(v_other)) {
const int i_other = BM_elem_index_get(v_other);
WEIGHT_ACCUMULATE;
@@ -1871,16 +1894,14 @@ static void vgroup_smooth_subset(
int j;
/* checked already */
- BLI_assert(me->mvert[i].flag & SELECT);
+ BLI_assert(IS_ME_VERT_WRITE(&me->mvert[i]));
for (j = 0; j < emap[i].count; j++) {
MEdge *e = &me->medge[emap[i].indices[j]];
const int i_other = (e->v1 == i ? e->v2 : e->v1);
MVert *v_other = &me->mvert[i_other];
- if ((source == WEIGHT_SMOOTH_ALL) ||
- (source == ((v_other->flag & SELECT) != 0)))
- {
+ if (IS_ME_VERT_READ(v_other)) {
WEIGHT_ACCUMULATE;
}
}
@@ -1904,6 +1925,11 @@ static void vgroup_smooth_subset(
ED_vgroup_parray_from_weight_array(dvert_array, dvert_tot, weight_accum_prev, def_nr, true);
}
+#undef IS_BM_VERT_READ
+#undef IS_BM_VERT_WRITE
+#undef IS_ME_VERT_READ
+#undef IS_ME_VERT_WRITE
+
MEM_freeN(weight_accum_curr);
MEM_freeN(weight_accum_prev);
MEM_freeN(verts_used);
@@ -1922,8 +1948,9 @@ static void vgroup_smooth_subset(
/* not so efficient to get 'dvert_array' again just so unselected verts are NULL'd */
if (use_mirror) {
ED_vgroup_parray_alloc(ob->data, &dvert_array, &dvert_tot, true);
- ED_vgroup_parray_mirror_sync(ob, dvert_array, dvert_tot,
- vgroup_validmap, vgroup_tot);
+ ED_vgroup_parray_mirror_sync(
+ ob, dvert_array, dvert_tot,
+ vgroup_validmap, vgroup_tot);
if (dvert_array)
MEM_freeN(dvert_array);
}
@@ -1947,11 +1974,12 @@ static int inv_cmp_mdef_vert_weights(const void *a1, const void *a2)
/* Used for limiting the number of influencing bones per vertex when exporting
* skinned meshes. if all_deform_weights is True, limit all deform modifiers
* to max_weights regardless of type, otherwise, only limit the number of influencing bones per vertex*/
-static int vgroup_limit_total_subset(Object *ob,
- const bool *vgroup_validmap,
- const int vgroup_tot,
- const int subset_count,
- const int max_weights)
+static int vgroup_limit_total_subset(
+ Object *ob,
+ const bool *vgroup_validmap,
+ const int vgroup_tot,
+ const int subset_count,
+ const int max_weights)
{
MDeformVert *dv, **dvert_array = NULL;
int i, dvert_tot = 0;
@@ -2018,8 +2046,9 @@ static int vgroup_limit_total_subset(Object *ob,
}
-static void vgroup_clean_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
- const float epsilon, const bool keep_single)
+static void vgroup_clean_subset(
+ Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
+ const float epsilon, const bool keep_single)
{
MDeformVert **dvert_array = NULL;
int dvert_tot = 0;
@@ -2036,16 +2065,18 @@ static void vgroup_clean_subset(Object *ob, const bool *vgroup_validmap, const i
ED_vgroup_parray_mirror_assign(ob, dvert_array, dvert_tot);
}
- ED_vgroup_parray_remove_zero(dvert_array, dvert_tot,
- vgroup_validmap, vgroup_tot,
- epsilon, keep_single);
+ ED_vgroup_parray_remove_zero(
+ dvert_array, dvert_tot,
+ vgroup_validmap, vgroup_tot,
+ epsilon, keep_single);
MEM_freeN(dvert_array);
}
}
-static void vgroup_quantize_subset(Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
- const int steps)
+static void vgroup_quantize_subset(
+ Object *ob, const bool *vgroup_validmap, const int vgroup_tot, const int UNUSED(subset_count),
+ const int steps)
{
MDeformVert **dvert_array = NULL;
int dvert_tot = 0;
@@ -2083,11 +2114,12 @@ static void vgroup_quantize_subset(Object *ob, const bool *vgroup_validmap, cons
}
}
-static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
- const char sel, const char sel_mirr,
- const int *flip_map, const int flip_map_len,
- const bool mirror_weights, const bool flip_vgroups, const bool all_vgroups,
- const int act_vgroup)
+static void dvert_mirror_op(
+ MDeformVert *dvert, MDeformVert *dvert_mirr,
+ const char sel, const char sel_mirr,
+ const int *flip_map, const int flip_map_len,
+ const bool mirror_weights, const bool flip_vgroups, const bool all_vgroups,
+ const int act_vgroup)
{
BLI_assert(sel || sel_mirr);
@@ -2146,10 +2178,11 @@ static void dvert_mirror_op(MDeformVert *dvert, MDeformVert *dvert_mirr,
/* TODO, vgroup locking */
/* TODO, face masking */
-void ED_vgroup_mirror(Object *ob,
- const bool mirror_weights, const bool flip_vgroups,
- const bool all_vgroups, const bool use_topology,
- int *r_totmirr, int *r_totfail)
+void ED_vgroup_mirror(
+ Object *ob,
+ const bool mirror_weights, const bool flip_vgroups,
+ const bool all_vgroups, const bool use_topology,
+ int *r_totmirr, int *r_totfail)
{
#define VGROUP_MIRR_OP \
@@ -2452,8 +2485,8 @@ static int vertex_group_poll(bContext *C)
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) &&
- data && !ID_IS_LINKED_DATABLOCK(data) &&
+ return (ob && !ID_IS_LINKED(ob) &&
+ data && !ID_IS_LINKED(data) &&
OB_TYPE_SUPPORT_VGROUP(ob->type) &&
ob->defbase.first);
}
@@ -2462,8 +2495,8 @@ static int vertex_group_supported_poll(bContext *C)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && OB_TYPE_SUPPORT_VGROUP(ob->type) &&
- data && !ID_IS_LINKED_DATABLOCK(data));
+ return (ob && !ID_IS_LINKED(ob) && OB_TYPE_SUPPORT_VGROUP(ob->type) &&
+ data && !ID_IS_LINKED(data));
}
static int vertex_group_mesh_poll(bContext *C)
@@ -2471,8 +2504,8 @@ static int vertex_group_mesh_poll(bContext *C)
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) &&
- data && !ID_IS_LINKED_DATABLOCK(data) &&
+ return (ob && !ID_IS_LINKED(ob) &&
+ data && !ID_IS_LINKED(data) &&
ob->type == OB_MESH &&
ob->defbase.first);
}
@@ -2481,7 +2514,7 @@ static int UNUSED_FUNCTION(vertex_group_mesh_supported_poll)(bContext *C)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- return (ob && !ID_IS_LINKED_DATABLOCK(ob) && ob->type == OB_MESH && data && !ID_IS_LINKED_DATABLOCK(data));
+ return (ob && !ID_IS_LINKED(ob) && ob->type == OB_MESH && data && !ID_IS_LINKED(data));
}
@@ -2490,19 +2523,19 @@ static int UNUSED_FUNCTION(vertex_group_poll_edit) (bContext *C)
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- if (!(ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data)))
+ if (!(ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data)))
return 0;
return BKE_object_is_in_editmode_vgroup(ob);
}
/* editmode _or_ weight paint vertex sel */
-static int vertex_group_vert_select_poll_ex(bContext *C, const short ob_type_flag)
+static int vertex_group_vert_poll_ex(bContext *C, const bool needs_select, const short ob_type_flag)
{
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- if (!(ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data)))
+ if (!(ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data)))
return false;
if (ob_type_flag && (((1 << ob->type) & ob_type_flag)) == 0) {
@@ -2513,12 +2546,17 @@ static int vertex_group_vert_select_poll_ex(bContext *C, const short ob_type_fla
return true;
}
else if (ob->mode & OB_MODE_WEIGHT_PAINT) {
- if (BKE_object_is_in_wpaint_select_vert(ob)) {
- return true;
+ if (needs_select) {
+ if (BKE_object_is_in_wpaint_select_vert(ob)) {
+ return true;
+ }
+ else {
+ CTX_wm_operator_poll_msg_set(C, "Vertex select needs to be enabled in weight paint mode");
+ return false;
+ }
}
else {
- CTX_wm_operator_poll_msg_set(C, "Vertex select needs to be enabled in weight paint mode");
- return false;
+ return true;
}
}
else {
@@ -2526,15 +2564,31 @@ static int vertex_group_vert_select_poll_ex(bContext *C, const short ob_type_fla
}
}
+#if 0
+static int vertex_group_vert_poll(bContext *C)
+{
+ return vertex_group_vert_poll_ex(C, false, 0);
+}
+#endif
+
+
+static int vertex_group_mesh_vert_poll(bContext *C)
+{
+ return vertex_group_vert_poll_ex(C, false, (1 << OB_MESH));
+}
+
static int vertex_group_vert_select_poll(bContext *C)
{
- return vertex_group_vert_select_poll_ex(C, 0);
+ return vertex_group_vert_poll_ex(C, true, 0);
}
+#if 0
static int vertex_group_mesh_vert_select_poll(bContext *C)
{
- return vertex_group_vert_select_poll_ex(C, (1 << OB_MESH));
+ return vertex_group_vert_poll_ex(C, true, (1 << OB_MESH));
}
+#endif
+
/* editmode _or_ weight paint vertex sel and active group unlocked */
static int vertex_group_vert_select_unlocked_poll(bContext *C)
@@ -2542,7 +2596,7 @@ static int vertex_group_vert_select_unlocked_poll(bContext *C)
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- if (!(ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data)))
+ if (!(ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data)))
return 0;
if (!(BKE_object_is_in_editmode_vgroup(ob) ||
@@ -2565,7 +2619,7 @@ static int vertex_group_vert_select_mesh_poll(bContext *C)
Object *ob = ED_object_context(C);
ID *data = (ob) ? ob->data : NULL;
- if (!(ob && !ID_IS_LINKED_DATABLOCK(ob) && data && !ID_IS_LINKED_DATABLOCK(data)))
+ if (!(ob && !ID_IS_LINKED(ob) && data && !ID_IS_LINKED(data)))
return 0;
/* only difference to #vertex_group_vert_select_poll */
@@ -2757,7 +2811,7 @@ static int vertex_group_select_exec(bContext *C, wmOperator *UNUSED(op))
{
Object *ob = ED_object_context(C);
- if (!ob || ID_IS_LINKED_DATABLOCK(ob))
+ if (!ob || ID_IS_LINKED(ob))
return OPERATOR_CANCELLED;
vgroup_select_verts(ob, 1);
@@ -3081,13 +3135,12 @@ static int vertex_group_smooth_exec(bContext *C, wmOperator *op)
const float fac = RNA_float_get(op->ptr, "factor");
const int repeat = RNA_int_get(op->ptr, "repeat");
eVGroupSelect subset_type = RNA_enum_get(op->ptr, "group_select_mode");
- const int source = RNA_enum_get(op->ptr, "source");
const float fac_expand = RNA_float_get(op->ptr, "expand");
int subset_count, vgroup_tot;
const bool *vgroup_validmap = BKE_object_defgroup_subset_from_select_type(ob, subset_type, &vgroup_tot, &subset_count);
- vgroup_smooth_subset(ob, vgroup_validmap, vgroup_tot, subset_count, fac, repeat, fac_expand, source);
+ vgroup_smooth_subset(ob, vgroup_validmap, vgroup_tot, subset_count, fac, repeat, fac_expand);
MEM_freeN((void *)vgroup_validmap);
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
@@ -3099,20 +3152,13 @@ static int vertex_group_smooth_exec(bContext *C, wmOperator *op)
void OBJECT_OT_vertex_group_smooth(wmOperatorType *ot)
{
- static EnumPropertyItem smooth_source_item[] = {
- {WEIGHT_SMOOTH_ALL, "ALL", 0, "All", ""},
- {WEIGHT_SMOOTH_SELECT, "SELECT", 0, "Only Selected", ""},
- {WEIGHT_SMOOTH_DESELECT, "DESELECT", 0, "Only Deselected", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
/* identifiers */
ot->name = "Smooth Vertex Weights";
ot->idname = "OBJECT_OT_vertex_group_smooth";
ot->description = "Smooth weights for selected vertices";
/* api callbacks */
- ot->poll = vertex_group_mesh_vert_select_poll;
+ ot->poll = vertex_group_mesh_vert_poll;
ot->exec = vertex_group_smooth_exec;
/* flags */
@@ -3123,7 +3169,6 @@ void OBJECT_OT_vertex_group_smooth(wmOperatorType *ot)
RNA_def_int(ot->srna, "repeat", 1, 1, 10000, "Iterations", "", 1, 200);
RNA_def_float(ot->srna, "expand", 0.0f, -1.0f, 1.0, "Expand/Contract", "Expand/contract weights", -1.0f, 1.0f);
- RNA_def_enum(ot->srna, "source", smooth_source_item, -1, "Source", "Vertices to mix with");
}
static int vertex_group_clean_exec(bContext *C, wmOperator *op)
@@ -3258,12 +3303,13 @@ static int vertex_group_mirror_exec(bContext *C, wmOperator *op)
Object *ob = ED_object_context(C);
int totmirr = 0, totfail = 0;
- ED_vgroup_mirror(ob,
- RNA_boolean_get(op->ptr, "mirror_weights"),
- RNA_boolean_get(op->ptr, "flip_group_names"),
- RNA_boolean_get(op->ptr, "all_groups"),
- RNA_boolean_get(op->ptr, "use_topology"),
- &totmirr, &totfail);
+ ED_vgroup_mirror(
+ ob,
+ RNA_boolean_get(op->ptr, "mirror_weights"),
+ RNA_boolean_get(op->ptr, "flip_group_names"),
+ RNA_boolean_get(op->ptr, "all_groups"),
+ RNA_boolean_get(op->ptr, "use_topology"),
+ &totmirr, &totfail);
ED_mesh_report_mirror(op, totmirr, totfail);
@@ -3397,7 +3443,7 @@ static int set_active_group_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem *vgroup_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *vgroup_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = ED_object_context(C);
EnumPropertyItem tmp = {0, "", 0, "", ""};
@@ -3616,7 +3662,7 @@ static int vertex_group_sort_exec(bContext *C, wmOperator *op)
void OBJECT_OT_vertex_group_sort(wmOperatorType *ot)
{
- static EnumPropertyItem vgroup_sort_type[] = {
+ static const EnumPropertyItem vgroup_sort_type[] = {
{SORT_TYPE_NAME, "NAME", 0, "Name", ""},
{SORT_TYPE_BONEHIERARCHY, "BONE_HIERARCHY", 0, "Bone Hierarchy", ""},
{0, NULL, 0, NULL, NULL}
@@ -3667,7 +3713,7 @@ static int vgroup_move_exec(bContext *C, wmOperator *op)
void OBJECT_OT_vertex_group_move(wmOperatorType *ot)
{
- static EnumPropertyItem vgroup_slot_move[] = {
+ static const EnumPropertyItem vgroup_slot_move[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/physics/CMakeLists.txt b/source/blender/editors/physics/CMakeLists.txt
index 898422dac51..a04ebb24d2c 100644
--- a/source/blender/editors/physics/CMakeLists.txt
+++ b/source/blender/editors/physics/CMakeLists.txt
@@ -40,6 +40,7 @@ set(SRC
dynamicpaint_ops.c
particle_boids.c
particle_edit.c
+ particle_edit_undo.c
particle_object.c
physics_fluid.c
physics_ops.c
@@ -48,6 +49,7 @@ set(SRC
rigidbody_object.c
rigidbody_world.c
+ particle_edit_utildefines.h
physics_intern.h
)
diff --git a/source/blender/editors/physics/dynamicpaint_ops.c b/source/blender/editors/physics/dynamicpaint_ops.c
index 3d7a45843cc..86db76bfcd6 100644
--- a/source/blender/editors/physics/dynamicpaint_ops.c
+++ b/source/blender/editors/physics/dynamicpaint_ops.c
@@ -253,7 +253,7 @@ static int output_toggle_exec(bContext *C, wmOperator *op)
void DPAINT_OT_output_toggle(wmOperatorType *ot)
{
- static EnumPropertyItem prop_output_toggle_types[] = {
+ static const EnumPropertyItem prop_output_toggle_types[] = {
{0, "A", 0, "Output A", ""},
{1, "B", 0, "Output B", ""},
{0, NULL, 0, NULL, NULL}
@@ -279,10 +279,10 @@ void DPAINT_OT_output_toggle(wmOperatorType *ot)
/***************************** Image Sequence Baking ******************************/
typedef struct DynamicPaintBakeJob {
- /* from wmJob */
- void *owner;
- short *stop, *do_update;
- float *progress;
+ /* from wmJob */
+ void *owner;
+ short *stop, *do_update;
+ float *progress;
struct Main *bmain;
Scene *scene;
@@ -297,13 +297,13 @@ typedef struct DynamicPaintBakeJob {
static void dpaint_bake_free(void *customdata)
{
- DynamicPaintBakeJob *job = customdata;
- MEM_freeN(job);
+ DynamicPaintBakeJob *job = customdata;
+ MEM_freeN(job);
}
static void dpaint_bake_endjob(void *customdata)
{
- DynamicPaintBakeJob *job = customdata;
+ DynamicPaintBakeJob *job = customdata;
DynamicPaintCanvasSettings *canvas = job->canvas;
canvas->flags &= ~MOD_DPAINT_BAKING;
@@ -311,7 +311,7 @@ static void dpaint_bake_endjob(void *customdata)
dynamicPaint_freeSurfaceData(job->surface);
G.is_rendering = false;
- BKE_spacedata_draw_locks(false);
+ BKE_spacedata_draw_locks(false);
WM_set_locked_interface(G.main->wm.first, false);
@@ -359,7 +359,7 @@ static void dynamicPaint_bakeImageSequence(DynamicPaintBakeJob *job)
scene->r.cfra = (int)frame;
ED_update_for_newframe(job->bmain, scene, 1);
- /* Init surface */
+ /* Init surface */
if (!dynamicPaint_createUVSurface(scene, surface, job->progress, job->do_update)) {
job->success = 0;
return;
@@ -421,26 +421,26 @@ static void dynamicPaint_bakeImageSequence(DynamicPaintBakeJob *job)
static void dpaint_bake_startjob(void *customdata, short *stop, short *do_update, float *progress)
{
- DynamicPaintBakeJob *job = customdata;
+ DynamicPaintBakeJob *job = customdata;
- job->stop = stop;
- job->do_update = do_update;
- job->progress = progress;
+ job->stop = stop;
+ job->do_update = do_update;
+ job->progress = progress;
job->start = PIL_check_seconds_timer();
job->success = 1;
- G.is_break = false; /* reset BKE_blender_test_break*/
+ G.is_break = false; /* reset BKE_blender_test_break*/
/* XXX annoying hack: needed to prevent data corruption when changing
* scene frame in separate threads
- */
- G.is_rendering = true;
- BKE_spacedata_draw_locks(true);
+ */
+ G.is_rendering = true;
+ BKE_spacedata_draw_locks(true);
dynamicPaint_bakeImageSequence(job);
- *do_update = true;
- *stop = 0;
+ *do_update = true;
+ *stop = 0;
}
/*
@@ -493,7 +493,7 @@ static int dynamicpaint_bake_exec(struct bContext *C, struct wmOperator *op)
WM_set_locked_interface(CTX_wm_manager(C), true);
- /* Bake Dynamic Paint */
+ /* Bake Dynamic Paint */
WM_jobs_start(CTX_wm_manager(C), wm_job);
return OPERATOR_FINISHED;
diff --git a/source/blender/editors/physics/particle_edit.c b/source/blender/editors/physics/particle_edit.c
index e22a145b3a6..50e3e20223d 100644
--- a/source/blender/editors/physics/particle_edit.c
+++ b/source/blender/editors/physics/particle_edit.c
@@ -29,7 +29,6 @@
* \ingroup edphys
*/
-
#include <stdlib.h>
#include <math.h>
#include <string.h>
@@ -45,9 +44,8 @@
#include "DNA_space_types.h"
#include "BLI_math.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_listbase.h"
-#include "BLI_string.h"
#include "BLI_kdtree.h"
#include "BLI_rand.h"
#include "BLI_utildefines.h"
@@ -83,26 +81,7 @@
#include "physics_intern.h"
-void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys);
-void PTCacheUndo_clear(PTCacheEdit *edit);
-void recalc_lengths(PTCacheEdit *edit);
-void recalc_emitter_field(Object *ob, ParticleSystem *psys);
-void update_world_cos(Object *ob, PTCacheEdit *edit);
-
-#define KEY_K PTCacheEditKey *key; int k
-#define POINT_P PTCacheEditPoint *point; int p
-#define LOOP_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++)
-#define LOOP_VISIBLE_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE))
-#define LOOP_SELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point_is_selected(point))
-#define LOOP_UNSELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!point_is_selected(point))
-#define LOOP_EDITED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC)
-#define LOOP_TAGGED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_TAG)
-#define LOOP_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++)
-#define LOOP_VISIBLE_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (!(key->flag & PEK_HIDE))
-#define LOOP_SELECTED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
-#define LOOP_TAGGED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (key->flag & PEK_TAG)
-
-#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co)
+#include "particle_edit_utildefines.h"
/**************************** utilities *******************************/
@@ -147,8 +126,6 @@ void PE_free_ptcache_edit(PTCacheEdit *edit)
if (edit==0) return;
- PTCacheUndo_clear(edit);
-
if (edit->points) {
LOOP_POINTS {
if (point->keys)
@@ -396,7 +373,7 @@ static void PE_set_view3d_data(bContext *C, PEData *data)
{
PE_set_data(C, data);
- view3d_set_viewcontext(C, &data->vc);
+ ED_view3d_viewcontext_init(C, &data->vc);
/* note, the object argument means the modelview matrix does not account for the objects matrix, use viewmat rather than (obmat * viewmat) */
view3d_get_transformation(data->vc.ar, data->vc.rv3d, NULL, &data->mats);
@@ -424,7 +401,6 @@ static bool PE_create_shape_tree(PEData *data, Object *shapeob)
return false;
}
- DM_ensure_looptri(dm);
return (bvhtree_from_mesh_looptri(&data->shape_bvh, dm, 0.0f, 4, 8) != NULL);
}
@@ -1371,28 +1347,28 @@ static void toggle_key_select(PEData *data, int point_index, int key_index)
static void select_action_apply(PTCacheEditPoint *point, PTCacheEditKey *key, int action)
{
switch (action) {
- case SEL_SELECT:
- if ((key->flag & PEK_SELECT) == 0) {
- key->flag |= PEK_SELECT;
- point->flag |= PEP_EDIT_RECALC;
- }
- break;
- case SEL_DESELECT:
- if (key->flag & PEK_SELECT) {
- key->flag &= ~PEK_SELECT;
- point->flag |= PEP_EDIT_RECALC;
- }
- break;
- case SEL_INVERT:
- if ((key->flag & PEK_SELECT) == 0) {
- key->flag |= PEK_SELECT;
- point->flag |= PEP_EDIT_RECALC;
- }
- else {
- key->flag &= ~PEK_SELECT;
- point->flag |= PEP_EDIT_RECALC;
- }
- break;
+ case SEL_SELECT:
+ if ((key->flag & PEK_SELECT) == 0) {
+ key->flag |= PEK_SELECT;
+ point->flag |= PEP_EDIT_RECALC;
+ }
+ break;
+ case SEL_DESELECT:
+ if (key->flag & PEK_SELECT) {
+ key->flag &= ~PEK_SELECT;
+ point->flag |= PEP_EDIT_RECALC;
+ }
+ break;
+ case SEL_INVERT:
+ if ((key->flag & PEK_SELECT) == 0) {
+ key->flag |= PEK_SELECT;
+ point->flag |= PEP_EDIT_RECALC;
+ }
+ else {
+ key->flag &= ~PEK_SELECT;
+ point->flag |= PEP_EDIT_RECALC;
+ }
+ break;
}
}
@@ -1614,7 +1590,7 @@ void PARTICLE_OT_select_tips(wmOperatorType *ot)
enum { RAN_HAIR, RAN_POINTS };
-static EnumPropertyItem select_random_type_items[] = {
+static const EnumPropertyItem select_random_type_items[] = {
{RAN_HAIR, "HAIR", 0, "Hair", ""},
{RAN_POINTS, "POINTS", 0, "Points", ""},
{0, NULL, 0, NULL, NULL}
@@ -1951,11 +1927,12 @@ void PARTICLE_OT_hide(wmOperatorType *ot)
/*************************** reveal operator **************************/
-static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int reveal_exec(bContext *C, wmOperator *op)
{
Object *ob= CTX_data_active_object(C);
Scene *scene= CTX_data_scene(C);
- PTCacheEdit *edit= PE_get_current(scene, ob);
+ PTCacheEdit *edit = PE_get_current(scene, ob);
+ const bool select = RNA_boolean_get(op->ptr, "select");
POINT_P; KEY_K;
LOOP_POINTS {
@@ -1963,8 +1940,9 @@ static int reveal_exec(bContext *C, wmOperator *UNUSED(op))
point->flag &= ~PEP_HIDE;
point->flag |= PEP_EDIT_RECALC;
- LOOP_KEYS
- key->flag |= PEK_SELECT;
+ LOOP_KEYS {
+ SET_FLAG_FROM_TEST(key->flag, select, PEK_SELECT);
+ }
}
}
@@ -1987,6 +1965,9 @@ void PARTICLE_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
+
+ /* props */
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/************************ select less operator ************************/
@@ -2727,7 +2708,7 @@ static void toggle_particle_cursor(bContext *C, int enable)
enum { DEL_PARTICLE, DEL_KEY };
-static EnumPropertyItem delete_type_items[] = {
+static const EnumPropertyItem delete_type_items[] = {
{DEL_PARTICLE, "PARTICLE", 0, "Particle", ""},
{DEL_KEY, "KEY", 0, "Key", ""},
{0, NULL, 0, NULL, NULL}};
@@ -4067,7 +4048,9 @@ void PARTICLE_OT_brush_edit(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO|OPTYPE_BLOCKING;
/* properties */
- RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
/*********************** cut shape ***************************/
@@ -4250,293 +4233,6 @@ void PARTICLE_OT_shape_cut(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
}
-/*********************** undo ***************************/
-
-static void free_PTCacheUndo(PTCacheUndo *undo)
-{
- PTCacheEditPoint *point;
- int i;
-
- for (i=0, point=undo->points; i<undo->totpoint; i++, point++) {
- if (undo->particles && (undo->particles + i)->hair)
- MEM_freeN((undo->particles + i)->hair);
- if (point->keys)
- MEM_freeN(point->keys);
- }
- if (undo->points)
- MEM_freeN(undo->points);
-
- if (undo->particles)
- MEM_freeN(undo->particles);
-
- BKE_ptcache_free_mem(&undo->mem_cache);
-}
-
-static void make_PTCacheUndo(PTCacheEdit *edit, PTCacheUndo *undo)
-{
- PTCacheEditPoint *point;
- int i;
-
- undo->totpoint= edit->totpoint;
-
- if (edit->psys) {
- ParticleData *pa;
-
- pa= undo->particles= MEM_dupallocN(edit->psys->particles);
-
- for (i=0; i<edit->totpoint; i++, pa++)
- pa->hair= MEM_dupallocN(pa->hair);
-
- undo->psys_flag = edit->psys->flag;
- }
- else {
- PTCacheMem *pm;
-
- BLI_duplicatelist(&undo->mem_cache, &edit->pid.cache->mem_cache);
- pm = undo->mem_cache.first;
-
- for (; pm; pm=pm->next) {
- for (i=0; i<BPHYS_TOT_DATA; i++)
- pm->data[i] = MEM_dupallocN(pm->data[i]);
- }
- }
-
- point= undo->points = MEM_dupallocN(edit->points);
- undo->totpoint = edit->totpoint;
-
- for (i=0; i<edit->totpoint; i++, point++) {
- point->keys= MEM_dupallocN(point->keys);
- /* no need to update edit key->co & key->time pointers here */
- }
-}
-
-static void get_PTCacheUndo(PTCacheEdit *edit, PTCacheUndo *undo)
-{
- ParticleSystem *psys = edit->psys;
- ParticleData *pa;
- HairKey *hkey;
- POINT_P; KEY_K;
-
- LOOP_POINTS {
- if (psys && psys->particles[p].hair)
- MEM_freeN(psys->particles[p].hair);
-
- if (point->keys)
- MEM_freeN(point->keys);
- }
- if (psys && psys->particles)
- MEM_freeN(psys->particles);
- if (edit->points)
- MEM_freeN(edit->points);
- if (edit->mirror_cache) {
- MEM_freeN(edit->mirror_cache);
- edit->mirror_cache= NULL;
- }
-
- edit->points= MEM_dupallocN(undo->points);
- edit->totpoint = undo->totpoint;
-
- LOOP_POINTS {
- point->keys= MEM_dupallocN(point->keys);
- }
-
- if (psys) {
- psys->particles= MEM_dupallocN(undo->particles);
-
- psys->totpart= undo->totpoint;
-
- LOOP_POINTS {
- pa = psys->particles + p;
- hkey= pa->hair = MEM_dupallocN(pa->hair);
-
- LOOP_KEYS {
- key->co= hkey->co;
- key->time= &hkey->time;
- hkey++;
- }
- }
-
- psys->flag = undo->psys_flag;
- }
- else {
- PTCacheMem *pm;
- int i;
-
- BKE_ptcache_free_mem(&edit->pid.cache->mem_cache);
-
- BLI_duplicatelist(&edit->pid.cache->mem_cache, &undo->mem_cache);
-
- pm = edit->pid.cache->mem_cache.first;
-
- for (; pm; pm=pm->next) {
- for (i=0; i<BPHYS_TOT_DATA; i++)
- pm->data[i] = MEM_dupallocN(pm->data[i]);
-
- BKE_ptcache_mem_pointers_init(pm);
-
- LOOP_POINTS {
- LOOP_KEYS {
- if ((int)key->ftime == (int)pm->frame) {
- key->co = pm->cur[BPHYS_DATA_LOCATION];
- key->vel = pm->cur[BPHYS_DATA_VELOCITY];
- key->rot = pm->cur[BPHYS_DATA_ROTATION];
- key->time = &key->ftime;
- }
- }
- BKE_ptcache_mem_pointers_incr(pm);
- }
- }
- }
-}
-
-void PE_undo_push(Scene *scene, const char *str)
-{
- PTCacheEdit *edit= PE_get_current(scene, OBACT);
- PTCacheUndo *undo;
- int nr;
-
- if (!edit) return;
-
- /* remove all undos after (also when curundo==NULL) */
- while (edit->undo.last != edit->curundo) {
- undo= edit->undo.last;
- BLI_remlink(&edit->undo, undo);
- free_PTCacheUndo(undo);
- MEM_freeN(undo);
- }
-
- /* make new */
- edit->curundo= undo= MEM_callocN(sizeof(PTCacheUndo), "particle undo file");
- BLI_strncpy(undo->name, str, sizeof(undo->name));
- BLI_addtail(&edit->undo, undo);
-
- /* and limit amount to the maximum */
- nr= 0;
- undo= edit->undo.last;
- while (undo) {
- nr++;
- if (nr==U.undosteps) break;
- undo= undo->prev;
- }
- if (undo) {
- while (edit->undo.first!=undo) {
- PTCacheUndo *first= edit->undo.first;
- BLI_remlink(&edit->undo, first);
- free_PTCacheUndo(first);
- MEM_freeN(first);
- }
- }
-
- /* copy */
- make_PTCacheUndo(edit, edit->curundo);
-}
-
-void PE_undo_step(Scene *scene, int step)
-{
- PTCacheEdit *edit= PE_get_current(scene, OBACT);
-
- if (!edit) return;
-
- if (step==0) {
- get_PTCacheUndo(edit, edit->curundo);
- }
- else if (step==1) {
-
- if (edit->curundo==NULL || edit->curundo->prev==NULL) {
- /* pass */
- }
- else {
- if (G.debug & G_DEBUG) printf("undo %s\n", edit->curundo->name);
- edit->curundo= edit->curundo->prev;
- get_PTCacheUndo(edit, edit->curundo);
- }
- }
- else {
- /* curundo has to remain current situation! */
-
- if (edit->curundo==NULL || edit->curundo->next==NULL) {
- /* pass */
- }
- else {
- get_PTCacheUndo(edit, edit->curundo->next);
- edit->curundo= edit->curundo->next;
- if (G.debug & G_DEBUG) printf("redo %s\n", edit->curundo->name);
- }
- }
-
- DAG_id_tag_update(&OBACT->id, OB_RECALC_DATA);
-}
-
-bool PE_undo_is_valid(Scene *scene)
-{
- PTCacheEdit *edit= PE_get_current(scene, OBACT);
-
- if (edit) {
- return (edit->undo.last != edit->undo.first);
- }
- return 0;
-}
-
-void PTCacheUndo_clear(PTCacheEdit *edit)
-{
- PTCacheUndo *undo;
-
- if (edit==NULL) return;
-
- undo= edit->undo.first;
- while (undo) {
- free_PTCacheUndo(undo);
- undo= undo->next;
- }
- BLI_freelistN(&edit->undo);
- edit->curundo= NULL;
-}
-
-void PE_undo(Scene *scene)
-{
- PE_undo_step(scene, 1);
-}
-
-void PE_redo(Scene *scene)
-{
- PE_undo_step(scene, -1);
-}
-
-void PE_undo_number(Scene *scene, int nr)
-{
- PTCacheEdit *edit= PE_get_current(scene, OBACT);
- PTCacheUndo *undo;
- int a=0;
-
- for (undo= edit->undo.first; undo; undo= undo->next, a++) {
- if (a==nr) break;
- }
- edit->curundo= undo;
- PE_undo_step(scene, 0);
-}
-
-
-/* get name of undo item, return null if no item with this index */
-/* if active pointer, set it to 1 if true */
-const char *PE_undo_get_name(Scene *scene, int nr, bool *r_active)
-{
- PTCacheEdit *edit= PE_get_current(scene, OBACT);
- PTCacheUndo *undo;
-
- if (r_active) *r_active = false;
-
- if (edit) {
- undo= BLI_findlink(&edit->undo, nr);
- if (undo) {
- if (r_active && (undo == edit->curundo)) {
- *r_active = true;
- }
- return undo->name;
- }
- }
- return NULL;
-}
-
/************************ utilities ******************************/
int PE_minmax(Scene *scene, float min[3], float max[3])
@@ -4681,9 +4377,6 @@ void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, Partic
if (psys && !cache)
recalc_emitter_field(ob, psys);
PE_update_object(scene, ob, 1);
-
- PTCacheUndo_clear(edit);
- PE_undo_push(scene, "Original");
}
}
@@ -4693,7 +4386,7 @@ static int particle_edit_toggle_poll(bContext *C)
if (ob == NULL || ob->type != OB_MESH)
return 0;
- if (!ob->data || ID_IS_LINKED_DATABLOCK(ob->data))
+ if (!ob->data || ID_IS_LINKED(ob->data))
return 0;
if (CTX_data_edit_object(C))
return 0;
diff --git a/source/blender/editors/physics/particle_edit_undo.c b/source/blender/editors/physics/particle_edit_undo.c
new file mode 100644
index 00000000000..ef0a2711fdd
--- /dev/null
+++ b/source/blender/editors/physics/particle_edit_undo.c
@@ -0,0 +1,297 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2007 by Janne Karhu.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/physics/particle_edit_undo.c
+ * \ingroup edphys
+ */
+
+#include <stdlib.h>
+#include <math.h>
+#include <string.h>
+#include <assert.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_scene_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_windowmanager_types.h"
+
+#include "BLI_listbase.h"
+#include "BLI_string.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_depsgraph.h"
+#include "BKE_particle.h"
+#include "BKE_pointcache.h"
+#include "BKE_context.h"
+#include "BKE_undo_system.h"
+
+#include "ED_object.h"
+#include "ED_particle.h"
+#include "ED_physics.h"
+
+#include "particle_edit_utildefines.h"
+
+#include "physics_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+static void undoptcache_from_editcache(PTCacheUndo *undo, PTCacheEdit *edit)
+{
+ PTCacheEditPoint *point;
+ int i;
+
+ size_t mem_used_prev = MEM_get_memory_in_use();
+
+ undo->totpoint= edit->totpoint;
+
+ if (edit->psys) {
+ ParticleData *pa;
+
+ pa= undo->particles= MEM_dupallocN(edit->psys->particles);
+
+ for (i=0; i<edit->totpoint; i++, pa++) {
+ pa->hair= MEM_dupallocN(pa->hair);
+ }
+
+ undo->psys_flag = edit->psys->flag;
+ }
+ else {
+ PTCacheMem *pm;
+
+ BLI_duplicatelist(&undo->mem_cache, &edit->pid.cache->mem_cache);
+ pm = undo->mem_cache.first;
+
+ for (; pm; pm=pm->next) {
+ for (i=0; i<BPHYS_TOT_DATA; i++) {
+ pm->data[i] = MEM_dupallocN(pm->data[i]);
+ }
+ }
+ }
+
+ point= undo->points = MEM_dupallocN(edit->points);
+ undo->totpoint = edit->totpoint;
+
+ for (i=0; i<edit->totpoint; i++, point++) {
+ point->keys= MEM_dupallocN(point->keys);
+ /* no need to update edit key->co & key->time pointers here */
+ }
+
+ size_t mem_used_curr = MEM_get_memory_in_use();
+
+ undo->undo_size = mem_used_prev < mem_used_curr ? mem_used_curr - mem_used_prev : sizeof(PTCacheUndo);
+}
+
+static void undoptcache_to_editcache(PTCacheUndo *undo, PTCacheEdit *edit)
+{
+ ParticleSystem *psys = edit->psys;
+ ParticleData *pa;
+ HairKey *hkey;
+ POINT_P; KEY_K;
+
+ LOOP_POINTS {
+ if (psys && psys->particles[p].hair) {
+ MEM_freeN(psys->particles[p].hair);
+ }
+
+ if (point->keys) {
+ MEM_freeN(point->keys);
+ }
+ }
+ if (psys && psys->particles) {
+ MEM_freeN(psys->particles);
+ }
+ if (edit->points) {
+ MEM_freeN(edit->points);
+ }
+ if (edit->mirror_cache) {
+ MEM_freeN(edit->mirror_cache);
+ edit->mirror_cache= NULL;
+ }
+
+ edit->points= MEM_dupallocN(undo->points);
+ edit->totpoint = undo->totpoint;
+
+ LOOP_POINTS {
+ point->keys= MEM_dupallocN(point->keys);
+ }
+
+ if (psys) {
+ psys->particles= MEM_dupallocN(undo->particles);
+
+ psys->totpart= undo->totpoint;
+
+ LOOP_POINTS {
+ pa = psys->particles + p;
+ hkey= pa->hair = MEM_dupallocN(pa->hair);
+
+ LOOP_KEYS {
+ key->co= hkey->co;
+ key->time= &hkey->time;
+ hkey++;
+ }
+ }
+
+ psys->flag = undo->psys_flag;
+ }
+ else {
+ PTCacheMem *pm;
+ int i;
+
+ BKE_ptcache_free_mem(&edit->pid.cache->mem_cache);
+
+ BLI_duplicatelist(&edit->pid.cache->mem_cache, &undo->mem_cache);
+
+ pm = edit->pid.cache->mem_cache.first;
+
+ for (; pm; pm=pm->next) {
+ for (i = 0; i < BPHYS_TOT_DATA; i++) {
+ pm->data[i] = MEM_dupallocN(pm->data[i]);
+ }
+ BKE_ptcache_mem_pointers_init(pm);
+
+ LOOP_POINTS {
+ LOOP_KEYS {
+ if ((int)key->ftime == (int)pm->frame) {
+ key->co = pm->cur[BPHYS_DATA_LOCATION];
+ key->vel = pm->cur[BPHYS_DATA_VELOCITY];
+ key->rot = pm->cur[BPHYS_DATA_ROTATION];
+ key->time = &key->ftime;
+ }
+ }
+ BKE_ptcache_mem_pointers_incr(pm);
+ }
+ }
+ }
+}
+
+static void undoptcache_free_data(PTCacheUndo *undo)
+{
+ PTCacheEditPoint *point;
+ int i;
+
+ for (i = 0, point=undo->points; i < undo->totpoint; i++, point++) {
+ if (undo->particles && (undo->particles + i)->hair) {
+ MEM_freeN((undo->particles + i)->hair);
+ }
+ if (point->keys) {
+ MEM_freeN(point->keys);
+ }
+ }
+ if (undo->points) {
+ MEM_freeN(undo->points);
+ }
+ if (undo->particles) {
+ MEM_freeN(undo->particles);
+ }
+ BKE_ptcache_free_mem(&undo->mem_cache);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct ParticleUndoStep {
+ UndoStep step;
+ UndoRefID_Scene scene_ref;
+ UndoRefID_Object object_ref;
+ PTCacheUndo data;
+} ParticleUndoStep;
+
+static bool particle_undosys_poll(struct bContext *C)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = OBACT;
+ PTCacheEdit *edit = PE_get_current(scene, ob);
+ return (edit != NULL);
+}
+
+static bool particle_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ ParticleUndoStep *us = (ParticleUndoStep *)us_p;
+ us->scene_ref.ptr = CTX_data_scene(C);
+ us->object_ref.ptr = us->scene_ref.ptr->basact->object;
+ PTCacheEdit *edit = PE_get_current(us->scene_ref.ptr, us->object_ref.ptr);
+ undoptcache_from_editcache(&us->data, edit);
+ return true;
+}
+
+static void particle_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_PARTICLE_EDIT);
+ BLI_assert(particle_undosys_poll(C));
+
+ ParticleUndoStep *us = (ParticleUndoStep *)us_p;
+ Scene *scene = us->scene_ref.ptr;
+ Object *ob = us->object_ref.ptr;
+ PTCacheEdit *edit = PE_get_current(scene, ob);
+ if (edit) {
+ undoptcache_to_editcache(&us->data, edit);
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
+ else {
+ BLI_assert(0);
+ }
+}
+
+static void particle_undosys_step_free(UndoStep *us_p)
+{
+ ParticleUndoStep *us = (ParticleUndoStep *)us_p;
+ undoptcache_free_data(&us->data);
+}
+
+static void particle_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ ParticleUndoStep *us = (ParticleUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->scene_ref));
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->object_ref));
+}
+
+/* Export for ED_undo_sys. */
+void ED_particle_undosys_type(UndoType *ut)
+{
+ ut->name = "Edit Particle";
+ ut->poll = particle_undosys_poll;
+ ut->step_encode = particle_undosys_step_encode;
+ ut->step_decode = particle_undosys_step_decode;
+ ut->step_free = particle_undosys_step_free;
+
+ ut->step_foreach_ID_ref = particle_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(ParticleUndoStep);
+}
+
+/** \} */
diff --git a/source/blender/editors/physics/particle_edit_utildefines.h b/source/blender/editors/physics/particle_edit_utildefines.h
new file mode 100644
index 00000000000..7608b885459
--- /dev/null
+++ b/source/blender/editors/physics/particle_edit_utildefines.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2007 by Janne Karhu.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/physics/particle_edit_utildefines.h
+ * \ingroup edphys
+ */
+
+#ifndef __PARTICLE_EDIT_UTILDEFNIES_H__
+#define __PARTICLE_EDIT_UTILDEFNIES_H__
+
+#define KEY_K PTCacheEditKey *key; int k
+#define POINT_P PTCacheEditPoint *point; int p
+#define LOOP_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++)
+#define LOOP_VISIBLE_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE))
+#define LOOP_SELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point_is_selected(point))
+#define LOOP_UNSELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!point_is_selected(point))
+#define LOOP_EDITED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC)
+#define LOOP_TAGGED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_TAG)
+#define LOOP_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++)
+#define LOOP_VISIBLE_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (!(key->flag & PEK_HIDE))
+#define LOOP_SELECTED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
+#define LOOP_TAGGED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (key->flag & PEK_TAG)
+
+#define KEY_WCO ((key->flag & PEK_USE_WCO) ? key->world_co : key->co)
+
+#endif /* __PARTICLE_EDIT_UTILDEFNIES_H__ */
diff --git a/source/blender/editors/physics/particle_object.c b/source/blender/editors/physics/particle_object.c
index 4a4474868a2..546fac6b7a3 100644
--- a/source/blender/editors/physics/particle_object.c
+++ b/source/blender/editors/physics/particle_object.c
@@ -67,32 +67,9 @@
#include "UI_resources.h"
-#include "physics_intern.h"
+#include "particle_edit_utildefines.h"
-extern void PE_create_particle_edit(Scene *scene, Object *ob, PointCache *cache, ParticleSystem *psys);
-extern void PTCacheUndo_clear(PTCacheEdit *edit);
-extern void recalc_lengths(PTCacheEdit *edit);
-extern void recalc_emitter_field(Object *ob, ParticleSystem *psys);
-extern void update_world_cos(Object *ob, PTCacheEdit *edit);
-
-#define KEY_K PTCacheEditKey *key; int k
-#define POINT_P PTCacheEditPoint *point; int p
-#define LOOP_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++)
-#if 0
-#define LOOP_VISIBLE_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!(point->flag & PEP_HIDE))
-#define LOOP_SELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point_is_selected(point))
-#define LOOP_UNSELECTED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (!point_is_selected(point))
-#define LOOP_EDITED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_EDIT_RECALC)
-#define LOOP_TAGGED_POINTS for (p=0, point=edit->points; p<edit->totpoint; p++, point++) if (point->flag & PEP_TAG)
-#endif
-#define LOOP_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++)
-#if 0
-#define LOOP_VISIBLE_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (!(key->flag & PEK_HIDE))
-#define LOOP_SELECTED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if ((key->flag & PEK_SELECT) && !(key->flag & PEK_HIDE))
-#define LOOP_TAGGED_KEYS for (k=0, key=point->keys; k<point->totkey; k++, key++) if (key->flag & PEK_TAG)
-
-#define KEY_WCO (key->flag & PEK_USE_WCO ? key->world_co : key->co)
-#endif
+#include "physics_intern.h"
static float I[4][4] = {{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}};
@@ -197,7 +174,7 @@ static int new_particle_settings_exec(bContext *C, wmOperator *UNUSED(op))
if (psys->part)
part= BKE_particlesettings_copy(bmain, psys->part);
else
- part= psys_new_settings("ParticleSettings", bmain);
+ part= BKE_particlesettings_add(bmain, "ParticleSettings");
ob= ptr.id.data;
@@ -728,8 +705,8 @@ static bool remap_hair_emitter(Scene *scene, Object *ob, ParticleSystem *psys,
for (i = 0, tpa = target_psys->particles, pa = psys->particles;
i < target_psys->totpart;
- i++, tpa++, pa++) {
-
+ i++, tpa++, pa++)
+ {
float from_co[3];
BVHTreeNearest nearest;
@@ -934,10 +911,7 @@ static void copy_particle_edit(Scene *scene, Object *ob, ParticleSystem *psys, P
edit->emitter_field = NULL;
edit->emitter_cosnos = NULL;
-
- BLI_listbase_clear(&edit->undo);
- edit->curundo = NULL;
-
+
edit->points = MEM_dupallocN(edit_from->points);
pa = psys->particles;
LOOP_POINTS {
@@ -966,9 +940,6 @@ static void copy_particle_edit(Scene *scene, Object *ob, ParticleSystem *psys, P
recalc_lengths(edit);
recalc_emitter_field(ob, psys);
PE_update_object(scene, ob, true);
-
- PTCacheUndo_clear(edit);
- PE_undo_push(scene, "Original");
}
static void remove_particle_systems_from_object(Object *ob_to)
@@ -977,7 +948,7 @@ static void remove_particle_systems_from_object(Object *ob_to)
if (ob_to->type != OB_MESH)
return;
- if (!ob_to->data || ID_IS_LINKED_DATABLOCK(ob_to->data))
+ if (!ob_to->data || ID_IS_LINKED(ob_to->data))
return;
for (md = ob_to->modifiers.first; md; md = md_next) {
@@ -1013,7 +984,7 @@ static bool copy_particle_systems_to_object(Main *bmain,
if (ob_to->type != OB_MESH)
return false;
- if (!ob_to->data || ID_IS_LINKED_DATABLOCK(ob_to->data))
+ if (!ob_to->data || ID_IS_LINKED(ob_to->data))
return false;
/* For remapping we need a valid DM.
@@ -1033,9 +1004,9 @@ static bool copy_particle_systems_to_object(Main *bmain,
cdmask = 0;
for (psys_from = PSYS_FROM_FIRST, i = 0;
psys_from;
- psys_from = PSYS_FROM_NEXT(psys_from), ++i) {
-
- psys = BKE_object_copy_particlesystem(psys_from);
+ psys_from = PSYS_FROM_NEXT(psys_from), ++i)
+ {
+ psys = BKE_object_copy_particlesystem(psys_from, 0);
tmp_psys[i] = psys;
if (psys_start == NULL)
@@ -1054,8 +1025,8 @@ static bool copy_particle_systems_to_object(Main *bmain,
/* now append psys to the object and make modifiers */
for (i = 0, psys_from = PSYS_FROM_FIRST;
i < totpsys;
- ++i, psys_from = PSYS_FROM_NEXT(psys_from)) {
-
+ ++i, psys_from = PSYS_FROM_NEXT(psys_from))
+ {
ParticleSystemModifierData *psmd;
psys = tmp_psys[i];
@@ -1092,8 +1063,8 @@ static bool copy_particle_systems_to_object(Main *bmain,
*/
for (psys = psys_start, psys_from = PSYS_FROM_FIRST, i = 0;
psys;
- psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i) {
-
+ psys = psys->next, psys_from = PSYS_FROM_NEXT(psys_from), ++i)
+ {
float (*from_mat)[4], (*to_mat)[4];
switch (space) {
@@ -1183,7 +1154,7 @@ static int copy_particle_systems_exec(bContext *C, wmOperator *op)
void PARTICLE_OT_copy_particle_systems(wmOperatorType *ot)
{
- static EnumPropertyItem space_items[] = {
+ static const EnumPropertyItem space_items[] = {
{PAR_COPY_SPACE_OBJECT, "OBJECT", 0, "Object", "Copy inside each object's local space"},
{PAR_COPY_SPACE_WORLD, "WORLD", 0, "World", "Copy in world space"},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/physics/physics_fluid.c b/source/blender/editors/physics/physics_fluid.c
index b5adf38527b..ce1e9d5cf6a 100644
--- a/source/blender/editors/physics/physics_fluid.c
+++ b/source/blender/editors/physics/physics_fluid.c
@@ -39,7 +39,7 @@
/* types */
#include "DNA_action_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "BLI_blenlib.h"
#include "BLI_math.h"
@@ -48,8 +48,6 @@
#include "BKE_context.h"
#include "BKE_customdata.h"
#include "BKE_fluidsim.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
#include "BKE_modifier.h"
#include "BKE_object.h"
#include "BKE_report.h"
@@ -67,6 +65,8 @@
/* enable/disable overall compilation */
#ifdef WITH_MOD_FLUID
+#include "BKE_global.h"
+
#include "WM_api.h"
#include "DNA_scene_types.h"
@@ -631,71 +631,63 @@ static int fluid_validate_scene(ReportList *reports, Scene *scene, Object *fsDom
#define FLUID_SUFFIX_CONFIG_TMP (FLUID_SUFFIX_CONFIG ".tmp")
#define FLUID_SUFFIX_SURFACE "fluidsurface"
-static int fluid_init_filepaths(Object *fsDomain, char *targetDir, char *targetFile, char *debugStrBuffer)
+static bool fluid_init_filepaths(
+ ReportList *reports, FluidsimSettings *domainSettings, Object *fsDomain,
+ char *targetDir, char *targetFile)
{
- FluidsimModifierData *fluidmd = (FluidsimModifierData *)modifiers_findByType(fsDomain, eModifierType_Fluidsim);
- FluidsimSettings *domainSettings= fluidmd->fss;
- FILE *fileCfg;
- int dirExist = 0;
- char newSurfdataPath[FILE_MAX]; /* modified output settings */
const char *suffixConfigTmp = FLUID_SUFFIX_CONFIG_TMP;
- int outStringsChanged = 0;
/* prepare names... */
- const char *relbase= modifier_path_relbase(fsDomain);
+ const char *relbase = modifier_path_relbase(fsDomain);
+
+ /* We do not accept empty paths, they can end in random places silently, see T51176. */
+ if (domainSettings->surfdataPath[0] == '\0') {
+ modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath),
+ OB_FLUIDSIM_SURF_DIR_DEFAULT);
+ BKE_reportf(reports, RPT_WARNING, "Fluidsim: empty cache path, reset to default '%s'",
+ domainSettings->surfdataPath);
+ }
BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
- BLI_strncpy(newSurfdataPath, domainSettings->surfdataPath, FILE_MAXDIR); /* if 0'd out below, this value is never used! */
- BLI_path_abs(targetDir, relbase); /* fixed #frame-no */
+ BLI_path_abs(targetDir, relbase);
/* .tmp: don't overwrite/delete original file */
BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp);
- // make sure all directories exist
- // as the bobjs use the same dir, this only needs to be checked
- // for the cfg output
- BLI_make_existing_file(targetFile);
-
- // check selected directory
- // simply try to open cfg file for writing to test validity of settings
- fileCfg = BLI_fopen(targetFile, "w");
- if (fileCfg) {
- dirExist = 1; fclose(fileCfg);
- // remove cfg dummy from directory test
- BLI_delete(targetFile, false, false);
- }
-
- if (targetDir[0] == '\0' || (!dirExist)) {
- char blendFile[FILE_MAX];
-
- // invalid dir, reset to current/previous
- BLI_split_file_part(G.main->name, blendFile, sizeof(blendFile));
- BLI_replace_extension(blendFile, FILE_MAX, ""); /* strip .blend */
- BLI_snprintf(newSurfdataPath, FILE_MAX, "//fluidsimdata/%s_%s_", blendFile, fsDomain->id.name);
-
- BLI_snprintf(debugStrBuffer, 256, "fluidsimBake::error - warning resetting output dir to '%s'\n", newSurfdataPath);
- elbeemDebugOut(debugStrBuffer);
- outStringsChanged=1;
- }
-
- /* check if modified output dir is ok */
-#if 0
- if (outStringsChanged) {
- char dispmsg[FILE_MAX+256];
- int selection=0;
- BLI_strncpy(dispmsg, "Output settings set to: '", sizeof(dispmsg));
- strcat(dispmsg, newSurfdataPath);
- strcat(dispmsg, "'%t|Continue with changed settings %x1|Discard and abort %x0");
-
- /* ask user if thats what he/she wants... */
- selection = pupmenu(dispmsg);
- if (selection < 1) return 0; /* 0 from menu, or -1 aborted */
- BLI_strncpy(targetDir, newSurfdataPath, sizeof(targetDir));
- strncpy(domainSettings->surfdataPath, newSurfdataPath, FILE_MAXDIR);
- BLI_path_abs(targetDir, G.main->name); /* fixed #frame-no */
+ /* Ensure whole path exists and is wirtable. */
+ const bool dir_exists = BLI_dir_create_recursive(targetDir);
+ const bool is_writable = BLI_file_is_writable(targetFile);
+
+ /* We change path to some presumably valid default value, but do not allow bake process to continue,
+ * this gives user chance to set manually another path. */
+ if (!dir_exists || !is_writable) {
+ modifier_path_init(domainSettings->surfdataPath, sizeof(domainSettings->surfdataPath),
+ OB_FLUIDSIM_SURF_DIR_DEFAULT);
+
+ if (!dir_exists) {
+ BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not create cache directory '%s', reset to default '%s'",
+ targetDir, domainSettings->surfdataPath);
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR, "Fluidsim: cache directory '%s' is not writable, reset to default '%s'",
+ targetDir, domainSettings->surfdataPath);
+ }
+
+ BLI_strncpy(targetDir, domainSettings->surfdataPath, FILE_MAXDIR);
+ BLI_path_abs(targetDir, relbase);
+
+ /* .tmp: don't overwrite/delete original file */
+ BLI_join_dirfile(targetFile, FILE_MAX, targetDir, suffixConfigTmp);
+
+ /* Ensure whole path exists and is wirtable. */
+ if (!BLI_dir_create_recursive(targetDir) || !BLI_file_is_writable(targetFile)) {
+ BKE_reportf(reports, RPT_ERROR, "Fluidsim: could not use default cache directory '%s', "
+ "please define a valid cache path manually", targetDir);
+ }
+ return false;
}
-#endif
- return outStringsChanged;
+
+ return true;
}
/* ******************************************************************************** */
@@ -857,7 +849,6 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
char targetDir[FILE_MAX]; // store & modify output settings
char targetFile[FILE_MAX]; // temp. store filename from targetDir for access
- int outStringsChanged = 0; // modified? copy back before baking
float domainMat[4][4];
float invDomMat[4][4];
@@ -943,7 +934,11 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
/* ******** prepare output file paths ******** */
- outStringsChanged = fluid_init_filepaths(fsDomain, targetDir, targetFile, debugStrBuffer);
+ if (!fluid_init_filepaths(reports, domainSettings, fsDomain, targetDir, targetFile)) {
+ fluidbake_free_data(channels, fobjects, fsset, fb);
+ return false;
+ }
+
channels->length = scene->r.efra; // DG TODO: why using endframe and not "noFrames" here? .. because "noFrames" is buggy too? (not using sfra)
channels->aniFrameTime = (double)((double)domainSettings->animEnd - (double)domainSettings->animStart) / (double)noFrames;
@@ -968,11 +963,6 @@ static int fluidsimBake(bContext *C, ReportList *reports, Object *fsDomain, shor
/* ******** start writing / exporting ******** */
// use .tmp, don't overwrite/delete original file
BLI_join_dirfile(targetFile, sizeof(targetFile), targetDir, suffixConfigTmp);
-
- // make sure these directories exist as well
- if (outStringsChanged) {
- BLI_make_existing_file(targetFile);
- }
/* ******** export domain to elbeem ******** */
elbeemResetSettings(fsset);
diff --git a/source/blender/editors/physics/physics_intern.h b/source/blender/editors/physics/physics_intern.h
index 6b6df15e987..f3f3697caaa 100644
--- a/source/blender/editors/physics/physics_intern.h
+++ b/source/blender/editors/physics/physics_intern.h
@@ -33,6 +33,11 @@
#ifndef __PHYSICS_INTERN_H__
#define __PHYSICS_INTERN_H__
+struct Object;
+struct PTCacheEdit;
+struct ParticleSystem;
+struct PointCache;
+struct Scene;
struct wmOperatorType;
/* particle_edit.c */
@@ -63,6 +68,11 @@ void PARTICLE_OT_edited_clear(struct wmOperatorType *ot);
void PARTICLE_OT_unify_length(struct wmOperatorType *ot);
+void PE_create_particle_edit(struct Scene *scene, struct Object *ob, struct PointCache *cache, struct ParticleSystem *psys);
+void recalc_lengths(struct PTCacheEdit *edit);
+void recalc_emitter_field(struct Object *ob, struct ParticleSystem *psys);
+void update_world_cos(struct Object *ob, struct PTCacheEdit *edit);
+
/* particle_object.c */
void OBJECT_OT_particle_system_add(struct wmOperatorType *ot);
void OBJECT_OT_particle_system_remove(struct wmOperatorType *ot);
diff --git a/source/blender/editors/physics/physics_ops.c b/source/blender/editors/physics/physics_ops.c
index 0c907f19753..b1d708ebc07 100644
--- a/source/blender/editors/physics/physics_ops.c
+++ b/source/blender/editors/physics/physics_ops.c
@@ -138,13 +138,21 @@ static void keymap_particle(wmKeyConfig *keyconf)
RNA_boolean_set(kmi->ptr, "unselected", true);
/* Shift+LMB behavior first, so it has priority over KM_ANY item below. */
- kmi = WM_keymap_verify_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "release_confirm", true);
RNA_boolean_set(kmi->ptr, "use_planar_constraint", true);
+ RNA_boolean_set(kmi->ptr, "use_accurate", false);
+
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "release_confirm", true);
+ RNA_boolean_set(kmi->ptr, "use_planar_constraint", false);
+ RNA_boolean_set(kmi->ptr, "use_accurate", true);
+
/* Using KM_ANY here to allow holding modifiers before starting to transform. */
kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_ANY, 0);
RNA_boolean_set(kmi->ptr, "release_confirm", true);
RNA_boolean_set(kmi->ptr, "use_planar_constraint", false);
+ RNA_boolean_set(kmi->ptr, "use_accurate", false);
WM_keymap_add_item(keymap, "PARTICLE_OT_brush_edit", LEFTMOUSE, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "PARTICLE_OT_brush_edit", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
diff --git a/source/blender/editors/physics/physics_pointcache.c b/source/blender/editors/physics/physics_pointcache.c
index e81aa584586..f36ebb3715e 100644
--- a/source/blender/editors/physics/physics_pointcache.c
+++ b/source/blender/editors/physics/physics_pointcache.c
@@ -99,45 +99,45 @@ static int ptcache_job_break(void *customdata)
static void ptcache_job_update(void *customdata, float progress, int *cancel)
{
- PointCacheJob *job = customdata;
+ PointCacheJob *job = customdata;
- if (ptcache_job_break(job)) {
- *cancel = 1;
- }
+ if (ptcache_job_break(job)) {
+ *cancel = 1;
+ }
- *(job->do_update) = true;
- *(job->progress) = progress;
+ *(job->do_update) = true;
+ *(job->progress) = progress;
}
static void ptcache_job_startjob(void *customdata, short *stop, short *do_update, float *progress)
{
- PointCacheJob *job = customdata;
+ PointCacheJob *job = customdata;
- job->stop = stop;
- job->do_update = do_update;
- job->progress = progress;
+ job->stop = stop;
+ job->do_update = do_update;
+ job->progress = progress;
- G.is_break = false;
+ G.is_break = false;
- /* XXX annoying hack: needed to prevent data corruption when changing
- * scene frame in separate threads
- */
- G.is_rendering = true;
- BKE_spacedata_draw_locks(true);
+ /* XXX annoying hack: needed to prevent data corruption when changing
+ * scene frame in separate threads
+ */
+ G.is_rendering = true;
+ BKE_spacedata_draw_locks(true);
BKE_ptcache_bake(job->baker);
- *do_update = true;
- *stop = 0;
+ *do_update = true;
+ *stop = 0;
}
static void ptcache_job_endjob(void *customdata)
{
- PointCacheJob *job = customdata;
+ PointCacheJob *job = customdata;
Scene *scene = job->baker->scene;
- G.is_rendering = false;
- BKE_spacedata_draw_locks(false);
+ G.is_rendering = false;
+ BKE_spacedata_draw_locks(false);
WM_set_locked_interface(G.main->wm.first, false);
diff --git a/source/blender/editors/physics/rigidbody_constraint.c b/source/blender/editors/physics/rigidbody_constraint.c
index 1bfc162a331..412f9acf718 100644
--- a/source/blender/editors/physics/rigidbody_constraint.c
+++ b/source/blender/editors/physics/rigidbody_constraint.c
@@ -39,7 +39,6 @@
#include "BKE_context.h"
#include "BKE_depsgraph.h"
-#include "BKE_global.h"
#include "BKE_group.h"
#include "BKE_main.h"
#include "BKE_report.h"
diff --git a/source/blender/editors/physics/rigidbody_object.c b/source/blender/editors/physics/rigidbody_object.c
index 30597d95497..b7083c29721 100644
--- a/source/blender/editors/physics/rigidbody_object.c
+++ b/source/blender/editors/physics/rigidbody_object.c
@@ -44,7 +44,6 @@
#include "BKE_context.h"
#include "BKE_depsgraph.h"
-#include "BKE_global.h"
#include "BKE_group.h"
#include "BKE_main.h"
#include "BKE_report.h"
@@ -455,7 +454,7 @@ static const int NUM_RB_MATERIAL_PRESETS = sizeof(RB_MATERIAL_DENSITY_TABLE) / s
* - Although there is a runtime cost, this has a lower maintenance cost
* in the long run than other two-list solutions...
*/
-static EnumPropertyItem *rigidbody_materials_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rigidbody_materials_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem item_tmp = {0};
EnumPropertyItem *item = NULL;
diff --git a/source/blender/editors/render/CMakeLists.txt b/source/blender/editors/render/CMakeLists.txt
index 971ab9f3458..ec8bf3e955d 100644
--- a/source/blender/editors/render/CMakeLists.txt
+++ b/source/blender/editors/render/CMakeLists.txt
@@ -51,16 +51,6 @@ set(SRC
render_intern.h
)
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../../quicktime
- )
- list(APPEND INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_HEADLESS)
add_definitions(-DWITH_HEADLESS)
endif()
diff --git a/source/blender/editors/render/render_internal.c b/source/blender/editors/render/render_internal.c
index 8c5d25ad44d..509fdcf080a 100644
--- a/source/blender/editors/render/render_internal.c
+++ b/source/blender/editors/render/render_internal.c
@@ -65,6 +65,7 @@
#include "BKE_sequencer.h"
#include "BKE_screen.h"
#include "BKE_scene.h"
+#include "BKE_undo_system.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -73,6 +74,7 @@
#include "ED_render.h"
#include "ED_screen.h"
#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_view3d.h"
#include "RE_pipeline.h"
@@ -88,6 +90,7 @@
#include "RNA_access.h"
#include "RNA_define.h"
+#include "BLO_undofile.h"
#include "render_intern.h"
@@ -116,6 +119,7 @@ typedef struct RenderJob {
ScrArea *sa;
ColorManagedViewSettings view_settings;
ColorManagedDisplaySettings display_settings;
+ bool supports_glsl_draw;
bool interface_locked;
} RenderJob;
@@ -210,7 +214,7 @@ static void image_buffer_rect_update(RenderJob *rj, RenderResult *rr, ImBuf *ibu
}
else {
if (rr->renlay == NULL) return;
- rectf = RE_RenderLayerGetPass(rr->renlay, SCE_PASS_COMBINED, viewname);
+ rectf = RE_RenderLayerGetPass(rr->renlay, RE_PASSNAME_COMBINED, viewname);
}
}
if (rectf == NULL) return;
@@ -304,7 +308,7 @@ static int screen_render_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- re = RE_NewRender(scene->id.name);
+ re = RE_NewSceneRender(scene);
lay_override = (v3d && v3d->lay != scene->lay) ? v3d->lay : 0;
G.is_break = false;
@@ -322,12 +326,12 @@ static int screen_render_exec(bContext *C, wmOperator *op)
RE_SetReports(re, op->reports);
- BLI_begin_threaded_malloc();
+ BLI_threaded_malloc_begin();
if (is_animation)
RE_BlenderAnim(re, mainp, scene, camera_override, lay_override, scene->r.sfra, scene->r.efra, scene->r.frame_step);
else
RE_BlenderFrame(re, mainp, scene, srl, camera_override, lay_override, scene->r.cfra, is_write_still);
- BLI_end_threaded_malloc();
+ BLI_threaded_malloc_end();
RE_SetReports(re, NULL);
@@ -520,10 +524,8 @@ static void render_image_update_pass_and_layer(RenderJob *rj, RenderResult *rr,
int layer = BLI_findstringindex(&main_rr->layers,
(char *)rr->renlay->name,
offsetof(RenderLayer, name));
- if (layer != rj->last_layer) {
- sima->iuser.layer = layer;
- rj->last_layer = layer;
- }
+ sima->iuser.layer = layer;
+ rj->last_layer = layer;
}
iuser->pass = sima->iuser.pass;
@@ -569,6 +571,7 @@ static void image_rect_update(void *rjv, RenderResult *rr, volatile rcti *renrec
* operate with.
*/
if (rr->do_exr_tile ||
+ !rj->supports_glsl_draw ||
ibuf->channels == 1 ||
U.image_draw_method != IMAGE_DRAW_METHOD_GLSL)
{
@@ -619,7 +622,21 @@ static void render_image_restore_layer(RenderJob *rj)
if (sa == rj->sa) {
if (sa->spacetype == SPACE_IMAGE) {
SpaceImage *sima = sa->spacedata.first;
- sima->iuser.layer = rj->orig_layer;
+
+ if (RE_HasSingleLayer(rj->re)) {
+ /* For single layer renders keep the active layer
+ * visible, or show the compositing result. */
+ RenderResult *rr = RE_AcquireResultRead(rj->re);
+ if (RE_HasCombinedLayer(rr)) {
+ sima->iuser.layer = 0;
+ }
+ RE_ReleaseResult(rj->re);
+ }
+ else {
+ /* For multiple layer render, set back the layer
+ * that was set at the start of rendering. */
+ sima->iuser.layer = rj->orig_layer;
+ }
}
return;
}
@@ -852,7 +869,8 @@ static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *even
/* get main */
if (G.debug_value == 101) {
/* thread-safety experiment, copy main from the undo buffer */
- mainp = BKE_undo_get_main(&scene);
+ struct MemFile *memfile = ED_undosys_stack_memfile_get_active(CTX_wm_manager(C)->undo_stack);
+ mainp = BLO_memfile_main_get(memfile, CTX_data_main(C), &scene);
}
else
mainp = CTX_data_main(C);
@@ -904,6 +922,7 @@ static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *even
rj->orig_layer = 0;
rj->last_layer = 0;
rj->sa = sa;
+ rj->supports_glsl_draw = IMB_colormanagement_support_glsl_draw(&scene->view_settings);
BKE_color_managed_display_settings_copy(&rj->display_settings, &scene->display_settings);
BKE_color_managed_view_settings_copy(&rj->view_settings, &scene->view_settings);
@@ -961,7 +980,7 @@ static int screen_render_invoke(bContext *C, wmOperator *op, const wmEvent *even
rj->image = ima;
/* setup new render */
- re = RE_NewRender(scene->id.name);
+ re = RE_NewSceneRender(scene);
RE_test_break_cb(re, rj, render_breakjob);
RE_draw_lock_cb(re, rj, render_drawlock);
RE_display_update_cb(re, rj, image_rect_update);
@@ -1012,9 +1031,11 @@ void RENDER_OT_render(wmOperatorType *ot)
/*ot->poll = ED_operator_screenactive;*/ /* this isn't needed, causes failer in background mode */
- RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
+ prop = RNA_def_boolean(ot->srna, "animation", 0, "Animation", "Render files from the animation range of this scene");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
RNA_def_boolean(ot->srna, "write_still", 0, "Write Image", "Save rendered the image to the output path (used only when animation is disabled)");
- RNA_def_boolean(ot->srna, "use_viewport", 0, "Use 3D Viewport", "When inside a 3D viewport, use layers and camera of the viewport");
+ prop = RNA_def_boolean(ot->srna, "use_viewport", 0, "Use 3D Viewport", "When inside a 3D viewport, use layers and camera of the viewport");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
prop = RNA_def_string(ot->srna, "layer", NULL, RE_MAXNAME, "Render Layer", "Single render layer to re-render (used only when animation is disabled)");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
prop = RNA_def_string(ot->srna, "scene", NULL, MAX_ID_NAME - 2, "Scene", "Scene to render, current scene if not specified");
@@ -1168,7 +1189,7 @@ static void render_update_resolution(Render *re, const RenderPreview *rp,
}
if (rp->has_freestyle) {
- if (rp->resolution_divider == 1) {
+ if (rp->resolution_divider == BKE_render_preview_pixel_size(&rp->scene->r)) {
RE_ChangeModeFlag(re, R_EDGE_FRS, false);
}
else {
@@ -1234,7 +1255,7 @@ static void render_view3d_startjob(void *customdata, short *stop, short *do_upda
use_border = render_view3d_disprect(rp->scene, rp->ar, rp->v3d,
rp->rv3d, &cliprct);
- if ((update_flag & (PR_UPDATE_RENDERSIZE | PR_UPDATE_DATABASE)) || rstats->convertdone == 0) {
+ if ((update_flag & (PR_UPDATE_RENDERSIZE | PR_UPDATE_DATABASE | PR_UPDATE_VIEW)) || rstats->convertdone == 0) {
RenderData rdata;
/* no osa, blur, seq, layers, savebuffer etc for preview render */
@@ -1309,11 +1330,12 @@ static void render_view3d_startjob(void *customdata, short *stop, short *do_upda
RE_updateRenderInstances(re, ob_inst_update_flag);
for (;;) {
+ int pixel_size = BKE_render_preview_pixel_size(&rp->scene->r);
if (first_time == false) {
if (restore)
RE_DataBase_IncrementalView(re, rp->viewmat, 1);
- rp->resolution_divider /= 2;
+ rp->resolution_divider = MAX2(rp->resolution_divider / 2, pixel_size);
*do_update = 1;
render_update_resolution(re, rp, use_border, &cliprct);
@@ -1330,7 +1352,7 @@ static void render_view3d_startjob(void *customdata, short *stop, short *do_upda
first_time = false;
- if (*stop || rp->resolution_divider == 1) {
+ if (*stop || rp->resolution_divider == pixel_size) {
break;
}
}
@@ -1432,7 +1454,7 @@ static void render_view3d_do(RenderEngine *engine, const bContext *C)
Scene *scene = CTX_data_scene(C);
ARegion *ar = CTX_wm_region(C);
int width = ar->winx, height = ar->winy;
- int divider = 1;
+ int divider = BKE_render_preview_pixel_size(&scene->r);
int resolution_threshold = scene->r.preview_start_resolution *
scene->r.preview_start_resolution;
@@ -1673,7 +1695,7 @@ static int render_shutter_curve_preset_exec(bContext *C, wmOperator *op)
void RENDER_OT_shutter_curve_preset(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_shape_items[] = {
+ static const EnumPropertyItem prop_shape_items[] = {
{CURVE_PRESET_SHARP, "SHARP", 0, "Sharp", ""},
{CURVE_PRESET_SMOOTH, "SMOOTH", 0, "Smooth", ""},
{CURVE_PRESET_MAX, "MAX", 0, "Max", ""},
diff --git a/source/blender/editors/render/render_opengl.c b/source/blender/editors/render/render_opengl.c
index 55c07140216..1133b5f79d1 100644
--- a/source/blender/editors/render/render_opengl.c
+++ b/source/blender/editors/render/render_opengl.c
@@ -38,7 +38,6 @@
#include "BLI_math_color_blend.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
-#include "BLI_jitter.h"
#include "BLI_threads.h"
#include "BLI_task.h"
@@ -257,10 +256,8 @@ static void screen_opengl_views_setup(OGLRender *oglrender)
}
}
- BLI_lock_thread(LOCK_DRAW_IMAGE);
if (!(is_multiview && BKE_scene_multiview_is_stereo3d(rd)))
oglrender->iuser.flag &= ~IMA_SHOW_STEREO;
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
/* will only work for non multiview correctly */
if (v3d) {
@@ -315,7 +312,7 @@ static void screen_opengl_render_doit(OGLRender *oglrender, RenderResult *rr)
RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
IMB_freeImBuf(out);
}
- else if (gpd){
+ else if (gpd) {
/* If there are no strips, Grease Pencil still needs a buffer to draw on */
ImBuf *out = IMB_allocImBuf(oglrender->sizex, oglrender->sizey, 32, IB_rect);
RE_render_result_rect_from_ibuf(rr, &scene->r, out, oglrender->view_id);
@@ -356,11 +353,15 @@ static void screen_opengl_render_doit(OGLRender *oglrender, RenderResult *rr)
ImBuf *ibuf_view;
const int alpha_mode = (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL;
+ unsigned int draw_flags = V3D_OFSDRAW_NONE;
+ draw_flags |= (oglrender->ofs_full_samples) ? V3D_OFSDRAW_USE_FULL_SAMPLE : 0;
+
if (view_context) {
+ draw_flags |= (draw_bgpic) ? V3D_OFSDRAW_USE_BACKGROUND : 0;
+
ibuf_view = ED_view3d_draw_offscreen_imbuf(
scene, v3d, ar, sizex, sizey,
- IB_rect, draw_bgpic,
- alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
+ IB_rect, draw_flags, alpha_mode, oglrender->ofs_samples, viewname,
oglrender->fx, oglrender->ofs, err_out);
/* for stamp only */
@@ -369,10 +370,11 @@ static void screen_opengl_render_doit(OGLRender *oglrender, RenderResult *rr)
}
}
else {
+ draw_flags |= (V3D_OFSDRAW_USE_GPENCIL | V3D_OFSDRAW_USE_BACKGROUND);
ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(
scene, scene->camera, oglrender->sizex, oglrender->sizey,
- IB_rect, OB_SOLID, false, true, true,
- alpha_mode, oglrender->ofs_samples, oglrender->ofs_full_samples, viewname,
+ IB_rect, draw_flags, OB_SOLID,
+ alpha_mode, oglrender->ofs_samples, viewname,
oglrender->fx, oglrender->ofs, err_out);
camera = scene->camera;
}
@@ -682,9 +684,18 @@ static bool screen_opengl_render_init(bContext *C, wmOperator *op)
oglrender->fx = GPU_fx_compositor_create();
}
}
+ else if (is_sequencer) {
+ /* NOTE: We allow animation of DoF setting for flexibility in edits, so
+ * we can't check in advance whether we need FX compositor or not.
+ * We just always allocated it and make sure it doesn't add extra
+ * overhead rather than memory allocation here if it's not really
+ * needed.
+ */
+ oglrender->fx = GPU_fx_compositor_create();
+ }
/* create render */
- oglrender->re = RE_NewRender(scene->id.name);
+ oglrender->re = RE_NewSceneRender(scene);
/* create image and image user */
oglrender->ima = BKE_image_verify_viewer(IMA_TYPE_R_RESULT, "Render Result");
@@ -715,7 +726,6 @@ static bool screen_opengl_render_init(bContext *C, wmOperator *op)
oglrender->task_scheduler = task_scheduler;
oglrender->task_pool = BLI_task_pool_create_background(task_scheduler,
oglrender);
- BLI_pool_set_num_threads(oglrender->task_pool, 1);
}
else {
oglrender->task_scheduler = NULL;
@@ -747,6 +757,23 @@ static void screen_opengl_render_end(bContext *C, OGLRender *oglrender)
int i;
if (oglrender->is_animation) {
+ /* Trickery part for movie output:
+ *
+ * We MUST write frames in an exact order, so we only let background
+ * thread to work on that, and main thread is simply waits for that
+ * thread to do all the dirty work.
+ *
+ * After this loop is done work_and_wait() will have nothing to do,
+ * so we don't run into wrong order of frames written to the stream.
+ */
+ if (BKE_imtype_is_movie(scene->r.im_format.imtype)) {
+ BLI_mutex_lock(&oglrender->task_mutex);
+ while (oglrender->num_scheduled_frames > 0) {
+ BLI_condition_wait(&oglrender->task_condition,
+ &oglrender->task_mutex);
+ }
+ BLI_mutex_unlock(&oglrender->task_mutex);
+ }
BLI_task_pool_work_and_wait(oglrender->task_pool);
BLI_task_pool_free(oglrender->task_pool);
/* Depending on various things we might or might not use global scheduler. */
@@ -858,7 +885,7 @@ static bool screen_opengl_render_anim_initialize(bContext *C, wmOperator *op)
typedef struct WriteTaskData {
RenderResult *rr;
- int cfra;
+ Scene tmp_scene;
} WriteTaskData;
static void write_result_func(TaskPool * __restrict pool,
@@ -867,10 +894,10 @@ static void write_result_func(TaskPool * __restrict pool,
{
OGLRender *oglrender = (OGLRender *) BLI_task_pool_userdata(pool);
WriteTaskData *task_data = (WriteTaskData *) task_data_v;
- Scene *scene = oglrender->scene;
+ Scene *scene = &task_data->tmp_scene;
RenderResult *rr = task_data->rr;
const bool is_movie = BKE_imtype_is_movie(scene->r.im_format.imtype);
- const int cfra = task_data->cfra;
+ const int cfra = scene->r.cfra;
bool ok;
/* Don't attempt to write if we've got an error. */
if (!oglrender->pool_ok) {
@@ -886,18 +913,17 @@ static void write_result_func(TaskPool * __restrict pool,
*/
ReportList reports;
BKE_reports_init(&reports, oglrender->reports->flag & ~RPT_PRINT);
- /* Do actual save logic here, depending on the file format. */
- Scene tmp_scene = *scene;
- tmp_scene.r.cfra = cfra;
+ /* Do actual save logic here, depending on the file format.
+ *
+ * NOTE: We have to construct temporary scene with proper scene->r.cfra.
+ * This is because underlying calls do not use r.cfra but use scene
+ * for that.
+ */
if (is_movie) {
- /* We have to construct temporary scene with proper scene->r.cfra.
- * This is because underlying calls do not use r.cfra but use scene
- * for that.
- */
ok = RE_WriteRenderViewsMovie(&reports,
rr,
- &tmp_scene,
- &tmp_scene.r,
+ scene,
+ &scene->r,
oglrender->mh,
oglrender->movie_ctx_arr,
oglrender->totvideos,
@@ -917,8 +943,8 @@ static void write_result_func(TaskPool * __restrict pool,
true,
NULL);
- BKE_render_result_stamp_info(&tmp_scene, tmp_scene.camera, rr, false);
- ok = RE_WriteRenderViewsImage(NULL, rr, &tmp_scene, true, name);
+ BKE_render_result_stamp_info(scene, scene->camera, rr, false);
+ ok = RE_WriteRenderViewsImage(NULL, rr, scene, true, name);
if (!ok) {
BKE_reportf(&reports,
RPT_ERROR,
@@ -957,7 +983,7 @@ static bool schedule_write_result(OGLRender *oglrender, RenderResult *rr)
Scene *scene = oglrender->scene;
WriteTaskData *task_data = MEM_mallocN(sizeof(WriteTaskData), "write task data");
task_data->rr = rr;
- task_data->cfra = scene->r.cfra;
+ task_data->tmp_scene = *scene;
BLI_mutex_lock(&oglrender->task_mutex);
oglrender->num_scheduled_frames++;
if (oglrender->num_scheduled_frames > MAX_SCHEDULED_FRAMES) {
@@ -1071,7 +1097,7 @@ static int screen_opengl_render_modal(bContext *C, wmOperator *op, const wmEvent
/* render frame? */
if (oglrender->timer == event->customdata)
break;
- /* fall-through */
+ ATTR_FALLTHROUGH;
default:
/* nothing to do */
return OPERATOR_RUNNING_MODAL;
diff --git a/source/blender/editors/render/render_preview.c b/source/blender/editors/render/render_preview.c
index 87c08dc6583..e52dd7c65c8 100644
--- a/source/blender/editors/render/render_preview.c
+++ b/source/blender/editors/render/render_preview.c
@@ -196,7 +196,7 @@ static Main *load_main_from_memory(const void *blend, int blend_size)
BlendFileData *bfd;
G.fileflags |= G_FILE_NO_UI;
- bfd = BLO_read_from_memory(blend, blend_size, NULL);
+ bfd = BLO_read_from_memory(blend, blend_size, NULL, BLO_READ_SKIP_NONE);
if (bfd) {
bmain = bfd->main;
@@ -331,7 +331,7 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
if (origmat) {
/* work on a copy */
- mat = localize_material(origmat);
+ mat = BKE_material_localize(origmat);
sp->matcopy = mat;
BLI_addtail(&pr_main->mat, mat);
@@ -382,9 +382,18 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
}
}
else {
- /* use current scene world to light sphere */
- if (mat->pr_type == MA_SPHERE_A)
+ if (mat->pr_type == MA_SPHERE_A && sp->pr_method == PR_BUTS_RENDER) {
+ /* Use current scene world to light sphere. */
sce->world = scene->world;
+ }
+ else if (sce->world) {
+ /* Use a default world color. Using the current
+ * scene world can be slow if it has big textures. */
+ sce->world->use_nodes = false;
+ sce->world->horr = 0.5f;
+ sce->world->horg = 0.5f;
+ sce->world->horb = 0.5f;
+ }
}
if (sp->pr_method == PR_ICON_RENDER) {
@@ -393,10 +402,6 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
}
else {
sce->lay = 1 << MA_SPHERE_A;
-
- /* same as above, use current scene world to light sphere */
- if (BKE_scene_use_new_shading_nodes(scene))
- sce->world = scene->world;
}
}
else {
@@ -476,7 +481,7 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
/* work on a copy */
if (origla) {
- la = localize_lamp(origla);
+ la = BKE_lamp_localize(origla);
sp->lampcopy = la;
BLI_addtail(&pr_main->lamp, la);
}
@@ -494,6 +499,15 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
sce->camera = (Object *)BLI_findstring(&pr_main->object, "Camera", offsetof(ID, name) + 2);
}
}
+ else {
+ if (sce->world) {
+ /* Only use lighting from the lamp. */
+ sce->world->use_nodes = false;
+ sce->world->horr = 0.0f;
+ sce->world->horg = 0.0f;
+ sce->world->horb = 0.0f;
+ }
+ }
for (base = sce->base.first; base; base = base->next) {
if (base->object->id.name[2] == 'p') {
@@ -512,7 +526,7 @@ static Scene *preview_prepare_scene(Main *bmain, Scene *scene, ID *id, int id_ty
World *wrld = NULL, *origwrld = (World *)id;
if (origwrld) {
- wrld = localize_world(origwrld);
+ wrld = BKE_world_localize(origwrld);
sp->worldcopy = wrld;
BLI_addtail(&pr_main->world, wrld);
}
@@ -637,7 +651,7 @@ void ED_preview_draw(const bContext *C, void *idp, void *parentp, void *slotp, r
if (ok)
*rect = newrect;
- /* start a new preview render job if signalled through sbuts->preview,
+ /* start a new preview render job if signaled through sbuts->preview,
* if no render result was found and no preview render job is running,
* or if the job is running and the size of preview changed */
if ((sbuts != NULL && sbuts->preview) ||
@@ -1180,7 +1194,7 @@ void ED_preview_icon_render(Main *bmain, Scene *scene, ID *id, unsigned int *rec
ip.bmain = bmain;
ip.scene = scene;
- ip.owner = id;
+ ip.owner = BKE_previewimg_id_ensure(id);
ip.id = id;
icon_preview_add_size(&ip, rect, sizex, sizey);
diff --git a/source/blender/editors/render/render_shading.c b/source/blender/editors/render/render_shading.c
index 837573ad175..49d74c25633 100644
--- a/source/blender/editors/render/render_shading.c
+++ b/source/blender/editors/render/render_shading.c
@@ -425,14 +425,15 @@ static int material_slot_move_exec(bContext *C, wmOperator *op)
MEM_freeN(slot_remap);
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW | ND_DATA, ob);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DATA, ob);
return OPERATOR_FINISHED;
}
void OBJECT_OT_material_slot_move(wmOperatorType *ot)
{
- static EnumPropertyItem material_slot_move[] = {
+ static const EnumPropertyItem material_slot_move[] = {
{1, "UP", 0, "Up", ""},
{-1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -580,7 +581,7 @@ static int new_world_exec(bContext *C, wmOperator *UNUSED(op))
wo = BKE_world_copy(bmain, wo);
}
else {
- wo = add_world(bmain, DATA_("World"));
+ wo = BKE_world_add(bmain, DATA_("World"));
if (BKE_scene_use_new_shading_nodes(scene)) {
ED_node_shader_default(C, &wo->id);
@@ -611,7 +612,7 @@ void WORLD_OT_new(wmOperatorType *ot)
/* identifiers */
ot->name = "New World";
ot->idname = "WORLD_OT_new";
- ot->description = "Add a new world";
+ ot->description = "Create a new world Data-Block";
/* api callbacks */
ot->exec = new_world_exec;
@@ -839,7 +840,7 @@ static int freestyle_module_move_exec(bContext *C, wmOperator *op)
void SCENE_OT_freestyle_module_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -999,7 +1000,7 @@ static int freestyle_lineset_move_exec(bContext *C, wmOperator *op)
void SCENE_OT_freestyle_lineset_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -1298,16 +1299,16 @@ static int freestyle_modifier_copy_exec(bContext *C, wmOperator *op)
switch (freestyle_get_modifier_type(&ptr)) {
case LS_MODIFIER_TYPE_COLOR:
- BKE_linestyle_color_modifier_copy(lineset->linestyle, modifier);
+ BKE_linestyle_color_modifier_copy(lineset->linestyle, modifier, 0);
break;
case LS_MODIFIER_TYPE_ALPHA:
- BKE_linestyle_alpha_modifier_copy(lineset->linestyle, modifier);
+ BKE_linestyle_alpha_modifier_copy(lineset->linestyle, modifier, 0);
break;
case LS_MODIFIER_TYPE_THICKNESS:
- BKE_linestyle_thickness_modifier_copy(lineset->linestyle, modifier);
+ BKE_linestyle_thickness_modifier_copy(lineset->linestyle, modifier, 0);
break;
case LS_MODIFIER_TYPE_GEOMETRY:
- BKE_linestyle_geometry_modifier_copy(lineset->linestyle, modifier);
+ BKE_linestyle_geometry_modifier_copy(lineset->linestyle, modifier, 0);
break;
default:
BKE_report(op->reports, RPT_ERROR, "The object the data pointer refers to is not a valid modifier");
@@ -1376,7 +1377,7 @@ static int freestyle_modifier_move_exec(bContext *C, wmOperator *op)
void SCENE_OT_freestyle_modifier_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -1497,7 +1498,7 @@ static int texture_slot_move_exec(bContext *C, wmOperator *op)
void TEXTURE_OT_slot_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{-1, "UP", 0, "Up", ""},
{1, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -1781,6 +1782,8 @@ static void copy_mtex_copybuf(ID *id)
case ID_LS:
mtex = &(((FreestyleLineStyle *)id)->mtex[(int)((FreestyleLineStyle *)id)->texact]);
break;
+ default:
+ break;
}
if (mtex && *mtex) {
@@ -1818,7 +1821,7 @@ static void paste_mtex_copybuf(ID *id)
mtex = &(((FreestyleLineStyle *)id)->mtex[(int)((FreestyleLineStyle *)id)->texact]);
break;
default:
- BLI_assert("invalid id type");
+ BLI_assert(!"invalid id type");
return;
}
diff --git a/source/blender/editors/render/render_update.c b/source/blender/editors/render/render_update.c
index f11a8177bf8..4e02ff77a31 100644
--- a/source/blender/editors/render/render_update.c
+++ b/source/blender/editors/render/render_update.c
@@ -189,8 +189,12 @@ void ED_render_engine_changed(Main *bmain)
RE_FreePersistentData();
- for (scene = bmain->scene.first; scene; scene = scene->id.next)
+ for (scene = bmain->scene.first; scene; scene = scene->id.next) {
ED_render_id_flush_update(bmain, &scene->id);
+ if (scene->nodetree) {
+ ntreeCompositUpdateRLayers(scene->nodetree);
+ }
+ }
}
/***************************** Updates ***********************************
diff --git a/source/blender/editors/render/render_view.c b/source/blender/editors/render/render_view.c
index 65f0fec50bc..c4a9af79ec2 100644
--- a/source/blender/editors/render/render_view.c
+++ b/source/blender/editors/render/render_view.c
@@ -44,6 +44,7 @@
#include "WM_types.h"
#include "ED_screen.h"
+#include "UI_interface.h"
#include "wm_window.h"
@@ -128,8 +129,8 @@ static ScrArea *find_area_image_empty(bContext *C)
/* new window uses x,y to set position */
ScrArea *render_view_open(bContext *C, int mx, int my, ReportList *reports)
{
- wmWindow *win = CTX_wm_window(C);
Scene *scene = CTX_data_scene(C);
+ wmWindow *win = NULL;
ScrArea *sa = NULL;
SpaceImage *sima;
bool area_was_image = false;
@@ -138,25 +139,15 @@ ScrArea *render_view_open(bContext *C, int mx, int my, ReportList *reports)
return NULL;
if (scene->r.displaymode == R_OUTPUT_WINDOW) {
- rcti rect;
- int sizex, sizey;
-
- sizex = 10 + (scene->r.xsch * scene->r.size) / 100;
- sizey = 40 + (scene->r.ysch * scene->r.size) / 100;
+ int sizex = 30 * UI_DPI_FAC + (scene->r.xsch * scene->r.size) / 100;
+ int sizey = 60 * UI_DPI_FAC + (scene->r.ysch * scene->r.size) / 100;
/* arbitrary... miniature image window views don't make much sense */
if (sizex < 320) sizex = 320;
if (sizey < 256) sizey = 256;
- /* some magic to calculate postition */
- /* pixelsize: mouse coords are in U.pixelsize units :/ */
- rect.xmin = (mx / U.pixelsize) + win->posx - sizex / 2;
- rect.ymin = (my / U.pixelsize) + win->posy - sizey / 2;
- rect.xmax = rect.xmin + sizex;
- rect.ymax = rect.ymin + sizey;
-
/* changes context! */
- if (WM_window_open_temp(C, &rect, WM_WINDOW_RENDER) == NULL) {
+ if (WM_window_open_temp(C, mx, my, sizex, sizey, WM_WINDOW_RENDER) == NULL) {
BKE_report(reports, RPT_ERROR, "Failed to open window!");
return NULL;
}
diff --git a/source/blender/editors/screen/CMakeLists.txt b/source/blender/editors/screen/CMakeLists.txt
index ed86ffa5e16..43e044b613a 100644
--- a/source/blender/editors/screen/CMakeLists.txt
+++ b/source/blender/editors/screen/CMakeLists.txt
@@ -42,6 +42,7 @@ set(SRC
area.c
glutil.c
screen_context.c
+ screen_draw.c
screen_edit.c
screen_ops.c
screendump.c
diff --git a/source/blender/editors/screen/area.c b/source/blender/editors/screen/area.c
index e6bb604d387..a53a16906d3 100644
--- a/source/blender/editors/screen/area.c
+++ b/source/blender/editors/screen/area.c
@@ -63,6 +63,7 @@
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
+#include "IMB_metadata.h"
#include "UI_interface.h"
#include "UI_interface_icons.h"
@@ -666,6 +667,10 @@ static void area_azone_initialize(wmWindow *win, bScreen *screen, ScrArea *sa)
return;
}
+ if (U.app_flag & USER_APP_LOCK_UI_LAYOUT) {
+ return;
+ }
+
/* can't click on bottom corners on OS X, already used for resizing */
#ifdef __APPLE__
if (!(sa->totrct.xmin == 0 && sa->totrct.ymin == 0) || WM_window_is_fullscreen(win))
@@ -1749,7 +1754,7 @@ int ED_area_header_switchbutton(const bContext *C, uiBlock *block, int yco)
RNA_pointer_create(&(scr->id), &RNA_Area, sa, &areaptr);
- uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.5 * U.widget_unit, U.widget_unit,
+ uiDefButR(block, UI_BTYPE_MENU, 0, "", xco, yco, 1.6 * U.widget_unit, U.widget_unit,
&areaptr, "type", 0, 0.0f, 0.0f, 0.0f, 0.0f, "");
return xco + 1.7 * U.widget_unit;
@@ -1934,15 +1939,29 @@ void ED_region_panels(const bContext *C, ARegion *ar, const char *context, int c
/* before setting the view */
if (vertical) {
/* we always keep the scroll offset - so the total view gets increased with the scrolled away part */
- if (v2d->cur.ymax < - 0.001f)
- y = min_ii(y, v2d->cur.ymin);
-
+ if (v2d->cur.ymax < -FLT_EPSILON) {
+ /* Clamp to lower view boundary */
+ if (v2d->tot.ymin < -v2d->winy) {
+ y = min_ii(y, 0);
+ }
+ else {
+ y = min_ii(y, v2d->cur.ymin);
+ }
+ }
+
y = -y;
}
else {
/* don't jump back when panels close or hide */
- if (!is_context_new)
- x = max_ii(x, v2d->cur.xmax);
+ if (!is_context_new) {
+ if (v2d->tot.xmax > v2d->winx) {
+ x = max_ii(x, 0);
+ }
+ else {
+ x = max_ii(x, v2d->cur.xmax);
+ }
+ }
+
y = -y;
}
@@ -2134,7 +2153,7 @@ static const char *meta_data_list[] =
BLI_INLINE bool metadata_is_valid(ImBuf *ibuf, char *r_str, short index, int offset)
{
- return (IMB_metadata_get_field(ibuf, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
+ return (IMB_metadata_get_field(ibuf->metadata, meta_data_list[index], r_str + offset, MAX_METADATA_STR - offset) && r_str[0]);
}
static void metadata_draw_imbuf(ImBuf *ibuf, const rctf *rect, int fontid, const bool is_top)
diff --git a/source/blender/editors/screen/glutil.c b/source/blender/editors/screen/glutil.c
index 93bac3f6660..216cbe9d7f4 100644
--- a/source/blender/editors/screen/glutil.c
+++ b/source/blender/editors/screen/glutil.c
@@ -566,7 +566,7 @@ void glaDrawPixelsSafe(float x, float y, int img_w, int img_h, int row_w, int fo
float rast_x = x + off_x * xzoom;
float rast_y = y + off_y * yzoom;
- GLfloat scissor[4];
+ GLfloat viewport[4];
int draw_w, draw_h;
/* Determine the smallest number of pixels we need to draw
@@ -581,9 +581,9 @@ void glaDrawPixelsSafe(float x, float y, int img_w, int img_h, int row_w, int fo
* fails if we zoom in on one really huge pixel so that it
* covers the entire screen).
*/
- glGetFloatv(GL_SCISSOR_BOX, scissor);
- draw_w = min_ii(img_w - off_x, ceil((scissor[2] - rast_x) / xzoom));
- draw_h = min_ii(img_h - off_y, ceil((scissor[3] - rast_y) / yzoom));
+ glGetFloatv(GL_VIEWPORT, viewport);
+ draw_w = min_ii(img_w - off_x, ceil((viewport[2] - rast_x) / xzoom));
+ draw_h = min_ii(img_h - off_y, ceil((viewport[3] - rast_y) / yzoom));
if (draw_w > 0 && draw_h > 0) {
diff --git a/source/blender/editors/screen/screen_context.c b/source/blender/editors/screen/screen_context.c
index c165bbfd301..e714e095ef9 100644
--- a/source/blender/editors/screen/screen_context.c
+++ b/source/blender/editors/screen/screen_context.c
@@ -54,6 +54,7 @@
#include "ED_armature.h"
#include "ED_gpencil.h"
+#include "ED_anim_api.h"
#include "WM_api.h"
#include "UI_interface.h"
@@ -87,7 +88,7 @@ const char *screen_context_dir[] = {
"visible_gpencil_layers", "editable_gpencil_layers", "editable_gpencil_strokes",
"active_gpencil_layer", "active_gpencil_frame", "active_gpencil_palette",
"active_gpencil_palettecolor", "active_gpencil_brush",
- "active_operator",
+ "active_operator", "selected_editable_fcurves",
NULL};
int ed_screen_context(const bContext *C, const char *member, bContextDataResult *result)
@@ -216,7 +217,7 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult
* bones will be operated on twice.
*/
if (arm->flag & ARM_MIRROR_EDIT)
- flipbone = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
/* if we're filtering for editable too, use the check for that instead, as it has selection check too */
if (editable_bones) {
@@ -258,7 +259,7 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult
* bones will be operated on twice.
*/
if (arm->flag & ARM_MIRROR_EDIT)
- flipbone = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ flipbone = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
/* if we're filtering for editable too, use the check for that instead, as it has selection check too */
if (selected_editable_bones) {
@@ -608,6 +609,29 @@ int ed_screen_context(const bContext *C, const char *member, bContextDataResult
return 1;
}
}
+ else if (CTX_data_equals(member, "selected_editable_fcurves")) {
+ bAnimContext ac;
+
+ if (ANIM_animdata_get_context(C, &ac) && ELEM(ac.spacetype, SPACE_ACTION, SPACE_IPO)) {
+ bAnimListElem *ale;
+ ListBase anim_data = {NULL, NULL};
+
+ int filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_FOREDIT | ANIMFILTER_NODUPLIS | ANIMFILTER_SEL) |
+ (ac.spacetype == SPACE_IPO ? ANIMFILTER_CURVE_VISIBLE : ANIMFILTER_LIST_VISIBLE);
+
+ ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
+
+ for (ale = anim_data.first; ale; ale = ale->next) {
+ if (ale->type == ANIMTYPE_FCURVE)
+ CTX_data_list_add(result, ale->id, &RNA_FCurve, ale->data);
+ }
+
+ ANIM_animdata_freelist(&anim_data);
+
+ CTX_data_type_set(result, CTX_DATA_TYPE_COLLECTION);
+ return 1;
+ }
+ }
else {
return 0; /* not found */
}
diff --git a/source/blender/editors/screen/screen_draw.c b/source/blender/editors/screen/screen_draw.c
new file mode 100644
index 00000000000..e67ae4e321c
--- /dev/null
+++ b/source/blender/editors/screen/screen_draw.c
@@ -0,0 +1,355 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/screen/screen_draw.c
+ * \ingroup edscr
+ */
+
+#include "BIF_gl.h"
+
+#include "WM_api.h"
+
+#include "ED_screen.h"
+
+#include "screen_intern.h"
+
+/**
+ * Draw horizontal shape visualizing future joining (left as well right direction of future joining).
+ */
+static void draw_horizontal_join_shape(ScrArea *sa, char dir)
+{
+ vec2f points[10];
+ short i;
+ float w, h;
+ float width = sa->v3->vec.x - sa->v1->vec.x;
+ float height = sa->v3->vec.y - sa->v1->vec.y;
+
+ if (height < width) {
+ h = height / 8;
+ w = height / 4;
+ }
+ else {
+ h = width / 8;
+ w = width / 4;
+ }
+
+ points[0].x = sa->v1->vec.x;
+ points[0].y = sa->v1->vec.y + height / 2;
+
+ points[1].x = sa->v1->vec.x;
+ points[1].y = sa->v1->vec.y;
+
+ points[2].x = sa->v4->vec.x - w;
+ points[2].y = sa->v4->vec.y;
+
+ points[3].x = sa->v4->vec.x - w;
+ points[3].y = sa->v4->vec.y + height / 2 - 2 * h;
+
+ points[4].x = sa->v4->vec.x - 2 * w;
+ points[4].y = sa->v4->vec.y + height / 2;
+
+ points[5].x = sa->v4->vec.x - w;
+ points[5].y = sa->v4->vec.y + height / 2 + 2 * h;
+
+ points[6].x = sa->v3->vec.x - w;
+ points[6].y = sa->v3->vec.y;
+
+ points[7].x = sa->v2->vec.x;
+ points[7].y = sa->v2->vec.y;
+
+ points[8].x = sa->v4->vec.x;
+ points[8].y = sa->v4->vec.y + height / 2 - h;
+
+ points[9].x = sa->v4->vec.x;
+ points[9].y = sa->v4->vec.y + height / 2 + h;
+
+ if (dir == 'l') {
+ /* when direction is left, then we flip direction of arrow */
+ float cx = sa->v1->vec.x + width;
+ for (i = 0; i < 10; i++) {
+ points[i].x -= cx;
+ points[i].x = -points[i].x;
+ points[i].x += sa->v1->vec.x;
+ }
+ }
+
+ glBegin(GL_POLYGON);
+ for (i = 0; i < 5; i++)
+ glVertex2f(points[i].x, points[i].y);
+ glEnd();
+ glBegin(GL_POLYGON);
+ for (i = 4; i < 8; i++)
+ glVertex2f(points[i].x, points[i].y);
+ glVertex2f(points[0].x, points[0].y);
+ glEnd();
+
+ glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
+ glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
+}
+
+/**
+ * Draw vertical shape visualizing future joining (up/down direction).
+ */
+static void draw_vertical_join_shape(ScrArea *sa, char dir)
+{
+ vec2f points[10];
+ short i;
+ float w, h;
+ float width = sa->v3->vec.x - sa->v1->vec.x;
+ float height = sa->v3->vec.y - sa->v1->vec.y;
+
+ if (height < width) {
+ h = height / 4;
+ w = height / 8;
+ }
+ else {
+ h = width / 4;
+ w = width / 8;
+ }
+
+ points[0].x = sa->v1->vec.x + width / 2;
+ points[0].y = sa->v3->vec.y;
+
+ points[1].x = sa->v2->vec.x;
+ points[1].y = sa->v2->vec.y;
+
+ points[2].x = sa->v1->vec.x;
+ points[2].y = sa->v1->vec.y + h;
+
+ points[3].x = sa->v1->vec.x + width / 2 - 2 * w;
+ points[3].y = sa->v1->vec.y + h;
+
+ points[4].x = sa->v1->vec.x + width / 2;
+ points[4].y = sa->v1->vec.y + 2 * h;
+
+ points[5].x = sa->v1->vec.x + width / 2 + 2 * w;
+ points[5].y = sa->v1->vec.y + h;
+
+ points[6].x = sa->v4->vec.x;
+ points[6].y = sa->v4->vec.y + h;
+
+ points[7].x = sa->v3->vec.x;
+ points[7].y = sa->v3->vec.y;
+
+ points[8].x = sa->v1->vec.x + width / 2 - w;
+ points[8].y = sa->v1->vec.y;
+
+ points[9].x = sa->v1->vec.x + width / 2 + w;
+ points[9].y = sa->v1->vec.y;
+
+ if (dir == 'u') {
+ /* when direction is up, then we flip direction of arrow */
+ float cy = sa->v1->vec.y + height;
+ for (i = 0; i < 10; i++) {
+ points[i].y -= cy;
+ points[i].y = -points[i].y;
+ points[i].y += sa->v1->vec.y;
+ }
+ }
+
+ glBegin(GL_POLYGON);
+ for (i = 0; i < 5; i++)
+ glVertex2f(points[i].x, points[i].y);
+ glEnd();
+ glBegin(GL_POLYGON);
+ for (i = 4; i < 8; i++)
+ glVertex2f(points[i].x, points[i].y);
+ glVertex2f(points[0].x, points[0].y);
+ glEnd();
+
+ glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
+ glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
+}
+
+/**
+ * Draw join shape due to direction of joining.
+ */
+static void draw_join_shape(ScrArea *sa, char dir)
+{
+ if (dir == 'u' || dir == 'd') {
+ draw_vertical_join_shape(sa, dir);
+ }
+ else {
+ draw_horizontal_join_shape(sa, dir);
+ }
+}
+
+/**
+ * Draw screen area darker with arrow (visualization of future joining).
+ */
+static void scrarea_draw_shape_dark(ScrArea *sa, char dir)
+{
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ glColor4ub(0, 0, 0, 50);
+ draw_join_shape(sa, dir);
+}
+
+/**
+ * Draw screen area ligher with arrow shape ("eraser" of previous dark shape).
+ */
+static void scrarea_draw_shape_light(ScrArea *sa, char UNUSED(dir))
+{
+ glBlendFunc(GL_DST_COLOR, GL_SRC_ALPHA);
+ /* value 181 was hardly computed: 181~105 */
+ glColor4ub(255, 255, 255, 50);
+ /* draw_join_shape(sa, dir); */
+ glRecti(sa->v1->vec.x, sa->v1->vec.y, sa->v3->vec.x, sa->v3->vec.y);
+}
+
+static void drawscredge_area_draw(int sizex, int sizey, short x1, short y1, short x2, short y2)
+{
+ /* right border area */
+ if (x2 < sizex - 1) {
+ glVertex2s(x2, y1);
+ glVertex2s(x2, y2);
+ }
+
+ /* left border area */
+ if (x1 > 0) { /* otherwise it draws the emboss of window over */
+ glVertex2s(x1, y1);
+ glVertex2s(x1, y2);
+ }
+
+ /* top border area */
+ if (y2 < sizey - 1) {
+ glVertex2s(x1, y2);
+ glVertex2s(x2, y2);
+ }
+
+ /* bottom border area */
+ if (y1 > 0) {
+ glVertex2s(x1, y1);
+ glVertex2s(x2, y1);
+ }
+}
+
+/**
+ * \brief Screen edges drawing.
+ */
+static void drawscredge_area(ScrArea *sa, int sizex, int sizey)
+{
+ short x1 = sa->v1->vec.x;
+ short y1 = sa->v1->vec.y;
+ short x2 = sa->v3->vec.x;
+ short y2 = sa->v3->vec.y;
+
+ drawscredge_area_draw(sizex, sizey, x1, y1, x2, y2);
+}
+
+/**
+ * Only for edge lines between areas.
+ */
+void ED_screen_draw_edges(wmWindow *win)
+{
+ const int winsize_x = WM_window_pixels_x(win);
+ const int winsize_y = WM_window_pixels_y(win);
+
+ ScrArea *sa;
+
+ wmSubWindowSet(win, win->screen->mainwin);
+
+ /* Note: first loop only draws if U.pixelsize > 1, skip otherwise */
+ if (U.pixelsize > 1.0f) {
+ /* FIXME: doesn't our glLineWidth already scale by U.pixelsize? */
+ glLineWidth((2.0f * U.pixelsize) - 1);
+ glColor3ub(0x50, 0x50, 0x50);
+ glBegin(GL_LINES);
+ for (sa = win->screen->areabase.first; sa; sa = sa->next)
+ drawscredge_area(sa, winsize_x, winsize_y);
+ glEnd();
+ }
+
+ glLineWidth(1);
+ glColor3ub(0, 0, 0);
+ glBegin(GL_LINES);
+ for (sa = win->screen->areabase.first; sa; sa = sa->next) {
+ drawscredge_area(sa, winsize_x, winsize_y);
+ }
+ glEnd();
+
+ win->screen->do_draw = false;
+}
+
+/**
+ * The blended join arrows.
+ *
+ * \param sa1: Area from which the resultant originates.
+ * \param sa2: Target area that will be replaced.
+ */
+void ED_screen_draw_join_shape(ScrArea *sa1, ScrArea *sa2)
+{
+ glLineWidth(1);
+
+ /* blended join arrow */
+ int dir = area_getorientation(sa1, sa2);
+ int dira = -1;
+ if (dir != -1) {
+ switch (dir) {
+ case 0: /* W */
+ dir = 'r';
+ dira = 'l';
+ break;
+ case 1: /* N */
+ dir = 'd';
+ dira = 'u';
+ break;
+ case 2: /* E */
+ dir = 'l';
+ dira = 'r';
+ break;
+ case 3: /* S */
+ dir = 'u';
+ dira = 'd';
+ break;
+ }
+ glEnable(GL_BLEND);
+ scrarea_draw_shape_dark(sa2, dir);
+ scrarea_draw_shape_light(sa1, dira);
+ glDisable(GL_BLEND);
+ }
+}
+
+void ED_screen_draw_split_preview(ScrArea *sa, const int dir, const float fac)
+{
+ /* splitpoint */
+ glEnable(GL_BLEND);
+ glBegin(GL_LINES);
+ glColor4ub(255, 255, 255, 100);
+
+ if (dir == 'h') {
+ const float y = (1 - fac) * sa->totrct.ymin + fac * sa->totrct.ymax;
+ glVertex2s(sa->totrct.xmin, y);
+ glVertex2s(sa->totrct.xmax, y);
+ glColor4ub(0, 0, 0, 100);
+ glVertex2s(sa->totrct.xmin, y + 1);
+ glVertex2s(sa->totrct.xmax, y + 1);
+ }
+ else {
+ const float x = (1 - fac) * sa->totrct.xmin + fac * sa->totrct.xmax;
+ glVertex2s(x, sa->totrct.ymin);
+ glVertex2s(x, sa->totrct.ymax);
+ glColor4ub(0, 0, 0, 100);
+ glVertex2s(x + 1, sa->totrct.ymin);
+ glVertex2s(x + 1, sa->totrct.ymax);
+ }
+ glEnd();
+ glDisable(GL_BLEND);
+}
+
diff --git a/source/blender/editors/screen/screen_edit.c b/source/blender/editors/screen/screen_edit.c
index 5cd0d33c365..2cd8ee9223f 100644
--- a/source/blender/editors/screen/screen_edit.c
+++ b/source/blender/editors/screen/screen_edit.c
@@ -467,7 +467,7 @@ bScreen *ED_screen_add(wmWindow *win, Scene *scene, const char *name)
bScreen *sc;
ScrVert *sv1, *sv2, *sv3, *sv4;
- sc = BKE_libblock_alloc(G.main, ID_SCR, name);
+ sc = BKE_libblock_alloc(G.main, ID_SCR, name, 0);
sc->scene = scene;
sc->do_refresh = true;
sc->redraws_flag = TIME_ALL_3D_WIN | TIME_ALL_ANIM_WIN;
@@ -582,8 +582,6 @@ int screen_area_join(bContext *C, bScreen *scr, ScrArea *sa1, ScrArea *sa2)
/*printf("dir is : %i\n", dir);*/
if (dir == -1) {
- if (sa1) sa1->flag &= ~AREA_FLAG_DRAWJOINFROM;
- if (sa2) sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
return 0;
}
@@ -614,8 +612,7 @@ int screen_area_join(bContext *C, bScreen *scr, ScrArea *sa1, ScrArea *sa2)
screen_delarea(C, scr, sa2);
removedouble_scrverts(scr);
- sa1->flag &= ~AREA_FLAG_DRAWJOINFROM;
-
+
return 1;
}
@@ -766,7 +763,9 @@ static void screen_test_scale(bScreen *sc, int winsize_x, int winsize_y)
/* lower edge */
const int yval = sa->v2->vec.y - headery_init;
se = screen_findedge(sc, sa->v4, sa->v1);
- select_connected_scredge(sc, se);
+ if (se != NULL) {
+ select_connected_scredge(sc, se);
+ }
for (sv = sc->vertbase.first; sv; sv = sv->next) {
if (sv != sa->v2 && sv != sa->v3) {
if (sv->flag) {
@@ -779,7 +778,9 @@ static void screen_test_scale(bScreen *sc, int winsize_x, int winsize_y)
/* upper edge */
const int yval = sa->v1->vec.y + headery_init;
se = screen_findedge(sc, sa->v2, sa->v3);
- select_connected_scredge(sc, se);
+ if (se != NULL) {
+ select_connected_scredge(sc, se);
+ }
for (sv = sc->vertbase.first; sv; sv = sv->next) {
if (sv != sa->v1 && sv != sa->v4) {
if (sv->flag) {
@@ -834,218 +835,6 @@ static void screen_test_scale(bScreen *sc, int winsize_x, int winsize_y)
}
-/* *********************** DRAWING **************************************** */
-
-/* draw vertical shape visualizing future joining (left as well
- * right direction of future joining) */
-static void draw_horizontal_join_shape(ScrArea *sa, char dir)
-{
- vec2f points[10];
- short i;
- float w, h;
- float width = sa->v3->vec.x - sa->v1->vec.x;
- float height = sa->v3->vec.y - sa->v1->vec.y;
-
- if (height < width) {
- h = height / 8;
- w = height / 4;
- }
- else {
- h = width / 8;
- w = width / 4;
- }
-
- points[0].x = sa->v1->vec.x;
- points[0].y = sa->v1->vec.y + height / 2;
-
- points[1].x = sa->v1->vec.x;
- points[1].y = sa->v1->vec.y;
-
- points[2].x = sa->v4->vec.x - w;
- points[2].y = sa->v4->vec.y;
-
- points[3].x = sa->v4->vec.x - w;
- points[3].y = sa->v4->vec.y + height / 2 - 2 * h;
-
- points[4].x = sa->v4->vec.x - 2 * w;
- points[4].y = sa->v4->vec.y + height / 2;
-
- points[5].x = sa->v4->vec.x - w;
- points[5].y = sa->v4->vec.y + height / 2 + 2 * h;
-
- points[6].x = sa->v3->vec.x - w;
- points[6].y = sa->v3->vec.y;
-
- points[7].x = sa->v2->vec.x;
- points[7].y = sa->v2->vec.y;
-
- points[8].x = sa->v4->vec.x;
- points[8].y = sa->v4->vec.y + height / 2 - h;
-
- points[9].x = sa->v4->vec.x;
- points[9].y = sa->v4->vec.y + height / 2 + h;
-
- if (dir == 'l') {
- /* when direction is left, then we flip direction of arrow */
- float cx = sa->v1->vec.x + width;
- for (i = 0; i < 10; i++) {
- points[i].x -= cx;
- points[i].x = -points[i].x;
- points[i].x += sa->v1->vec.x;
- }
- }
-
- glBegin(GL_POLYGON);
- for (i = 0; i < 5; i++)
- glVertex2f(points[i].x, points[i].y);
- glEnd();
- glBegin(GL_POLYGON);
- for (i = 4; i < 8; i++)
- glVertex2f(points[i].x, points[i].y);
- glVertex2f(points[0].x, points[0].y);
- glEnd();
-
- glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
- glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
-}
-
-/* draw vertical shape visualizing future joining (up/down direction) */
-static void draw_vertical_join_shape(ScrArea *sa, char dir)
-{
- vec2f points[10];
- short i;
- float w, h;
- float width = sa->v3->vec.x - sa->v1->vec.x;
- float height = sa->v3->vec.y - sa->v1->vec.y;
-
- if (height < width) {
- h = height / 4;
- w = height / 8;
- }
- else {
- h = width / 4;
- w = width / 8;
- }
-
- points[0].x = sa->v1->vec.x + width / 2;
- points[0].y = sa->v3->vec.y;
-
- points[1].x = sa->v2->vec.x;
- points[1].y = sa->v2->vec.y;
-
- points[2].x = sa->v1->vec.x;
- points[2].y = sa->v1->vec.y + h;
-
- points[3].x = sa->v1->vec.x + width / 2 - 2 * w;
- points[3].y = sa->v1->vec.y + h;
-
- points[4].x = sa->v1->vec.x + width / 2;
- points[4].y = sa->v1->vec.y + 2 * h;
-
- points[5].x = sa->v1->vec.x + width / 2 + 2 * w;
- points[5].y = sa->v1->vec.y + h;
-
- points[6].x = sa->v4->vec.x;
- points[6].y = sa->v4->vec.y + h;
-
- points[7].x = sa->v3->vec.x;
- points[7].y = sa->v3->vec.y;
-
- points[8].x = sa->v1->vec.x + width / 2 - w;
- points[8].y = sa->v1->vec.y;
-
- points[9].x = sa->v1->vec.x + width / 2 + w;
- points[9].y = sa->v1->vec.y;
-
- if (dir == 'u') {
- /* when direction is up, then we flip direction of arrow */
- float cy = sa->v1->vec.y + height;
- for (i = 0; i < 10; i++) {
- points[i].y -= cy;
- points[i].y = -points[i].y;
- points[i].y += sa->v1->vec.y;
- }
- }
-
- glBegin(GL_POLYGON);
- for (i = 0; i < 5; i++)
- glVertex2f(points[i].x, points[i].y);
- glEnd();
- glBegin(GL_POLYGON);
- for (i = 4; i < 8; i++)
- glVertex2f(points[i].x, points[i].y);
- glVertex2f(points[0].x, points[0].y);
- glEnd();
-
- glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
- glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
-}
-
-/* draw join shape due to direction of joining */
-static void draw_join_shape(ScrArea *sa, char dir)
-{
- if (dir == 'u' || dir == 'd')
- draw_vertical_join_shape(sa, dir);
- else
- draw_horizontal_join_shape(sa, dir);
-}
-
-/* draw screen area darker with arrow (visualization of future joining) */
-static void scrarea_draw_shape_dark(ScrArea *sa, char dir)
-{
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glColor4ub(0, 0, 0, 50);
- draw_join_shape(sa, dir);
-}
-
-/* draw screen area ligher with arrow shape ("eraser" of previous dark shape) */
-static void scrarea_draw_shape_light(ScrArea *sa, char UNUSED(dir))
-{
- glBlendFunc(GL_DST_COLOR, GL_SRC_ALPHA);
- /* value 181 was hardly computed: 181~105 */
- glColor4ub(255, 255, 255, 50);
- /* draw_join_shape(sa, dir); */
- glRecti(sa->v1->vec.x, sa->v1->vec.y, sa->v3->vec.x, sa->v3->vec.y);
-}
-
-static void drawscredge_area_draw(int sizex, int sizey, short x1, short y1, short x2, short y2)
-{
- /* right border area */
- if (x2 < sizex - 1) {
- glVertex2s(x2, y1);
- glVertex2s(x2, y2);
- }
-
- /* left border area */
- if (x1 > 0) { /* otherwise it draws the emboss of window over */
- glVertex2s(x1, y1);
- glVertex2s(x1, y2);
- }
-
- /* top border area */
- if (y2 < sizey - 1) {
- glVertex2s(x1, y2);
- glVertex2s(x2, y2);
- }
-
- /* bottom border area */
- if (y1 > 0) {
- glVertex2s(x1, y1);
- glVertex2s(x2, y1);
- }
-}
-
-/** screen edges drawing **/
-static void drawscredge_area(ScrArea *sa, int sizex, int sizey)
-{
- short x1 = sa->v1->vec.x;
- short y1 = sa->v1->vec.y;
- short x2 = sa->v3->vec.x;
- short y2 = sa->v3->vec.y;
-
- drawscredge_area_draw(sizex, sizey, x1, y1, x2, y2);
-}
-
/* ****************** EXPORTED API TO OTHER MODULES *************************** */
bScreen *ED_screen_duplicate(wmWindow *win, bScreen *sc)
@@ -1101,100 +890,6 @@ void ED_screen_do_listen(bContext *C, wmNotifier *note)
}
}
-/* only for edge lines between areas, and the blended join arrows */
-void ED_screen_draw(wmWindow *win)
-{
- const int winsize_x = WM_window_pixels_x(win);
- const int winsize_y = WM_window_pixels_y(win);
-
- ScrArea *sa;
- ScrArea *sa1 = NULL;
- ScrArea *sa2 = NULL;
- ScrArea *sa3 = NULL;
-
- wmSubWindowSet(win, win->screen->mainwin);
-
- /* Note: first loop only draws if U.pixelsize > 1, skip otherwise */
- if (U.pixelsize > 1.0f) {
- /* FIXME: doesn't our glLineWidth already scale by U.pixelsize? */
- glLineWidth((2.0f * U.pixelsize) - 1);
- glColor3ub(0x50, 0x50, 0x50);
- glBegin(GL_LINES);
- for (sa = win->screen->areabase.first; sa; sa = sa->next)
- drawscredge_area(sa, winsize_x, winsize_y);
- glEnd();
- }
-
- glLineWidth(1);
- glColor3ub(0, 0, 0);
- glBegin(GL_LINES);
- for (sa = win->screen->areabase.first; sa; sa = sa->next) {
- drawscredge_area(sa, winsize_x, winsize_y);
-
- /* gather area split/join info */
- if (sa->flag & AREA_FLAG_DRAWJOINFROM) sa1 = sa;
- if (sa->flag & AREA_FLAG_DRAWJOINTO) sa2 = sa;
- if (sa->flag & (AREA_FLAG_DRAWSPLIT_H | AREA_FLAG_DRAWSPLIT_V)) sa3 = sa;
- }
- glEnd();
-
- /* blended join arrow */
- if (sa1 && sa2) {
- int dir = area_getorientation(sa1, sa2);
- int dira = -1;
- if (dir != -1) {
- switch (dir) {
- case 0: /* W */
- dir = 'r';
- dira = 'l';
- break;
- case 1: /* N */
- dir = 'd';
- dira = 'u';
- break;
- case 2: /* E */
- dir = 'l';
- dira = 'r';
- break;
- case 3: /* S */
- dir = 'u';
- dira = 'd';
- break;
- }
- }
- glEnable(GL_BLEND);
- scrarea_draw_shape_dark(sa2, dir);
- scrarea_draw_shape_light(sa1, dira);
- glDisable(GL_BLEND);
- }
-
- /* splitpoint */
- if (sa3) {
- glEnable(GL_BLEND);
- glBegin(GL_LINES);
- glColor4ub(255, 255, 255, 100);
-
- if (sa3->flag & AREA_FLAG_DRAWSPLIT_H) {
- glVertex2s(sa3->totrct.xmin, win->eventstate->y);
- glVertex2s(sa3->totrct.xmax, win->eventstate->y);
- glColor4ub(0, 0, 0, 100);
- glVertex2s(sa3->totrct.xmin, win->eventstate->y + 1);
- glVertex2s(sa3->totrct.xmax, win->eventstate->y + 1);
- }
- else {
- glVertex2s(win->eventstate->x, sa3->totrct.ymin);
- glVertex2s(win->eventstate->x, sa3->totrct.ymax);
- glColor4ub(0, 0, 0, 100);
- glVertex2s(win->eventstate->x + 1, sa3->totrct.ymin);
- glVertex2s(win->eventstate->x + 1, sa3->totrct.ymax);
- }
- glEnd();
- glDisable(GL_BLEND);
- }
-
- win->screen->do_draw = false;
-}
-
/* helper call for below, dpi changes headers */
static void screen_refresh_headersizes(void)
{
@@ -1224,6 +919,7 @@ void ED_screen_refresh(wmWindowManager *wm, wmWindow *win)
winrct.ymax = winsize_y - 1;
/* header size depends on DPI, let's verify */
+ WM_window_set_dpi(win);
screen_refresh_headersizes();
screen_test_scale(win->screen, winsize_x, winsize_y);
@@ -1358,7 +1054,7 @@ void ED_screen_exit(bContext *C, wmWindow *window, bScreen *screen)
/* *********************************** */
/* case when on area-edge or in azones, or outside window */
-static void screen_cursor_set(wmWindow *win, wmEvent *event)
+static void screen_cursor_set(wmWindow *win, const wmEvent *event)
{
const int winsize_x = WM_window_pixels_x(win);
const int winsize_y = WM_window_pixels_y(win);
@@ -1397,7 +1093,7 @@ static void screen_cursor_set(wmWindow *win, wmEvent *event)
/* called in wm_event_system.c. sets state vars in screen, cursors */
/* event type is mouse move */
-void ED_screen_set_subwinactive(bContext *C, wmEvent *event)
+void ED_screen_set_subwinactive(bContext *C, const wmEvent *event)
{
wmWindow *win = CTX_wm_window(C);
@@ -1758,7 +1454,10 @@ bool ED_screen_delete_scene(bContext *C, Scene *scene)
BKE_libblock_remap(bmain, scene, newscene, ID_REMAP_SKIP_INDIRECT_USAGE | ID_REMAP_SKIP_NEVER_NULL_USAGE);
- BKE_libblock_free(bmain, scene);
+ id_us_clear_real(&scene->id);
+ if (scene->id.us == 0) {
+ BKE_libblock_free(bmain, scene);
+ }
return true;
}
@@ -1889,17 +1588,28 @@ ScrArea *ED_screen_state_toggle(bContext *C, wmWindow *win, ScrArea *sa, const s
if (sa && sa->full) {
/* restoring back to SCREENNORMAL */
- ScrArea *old;
-
sc = sa->full; /* the old screen to restore */
oldscreen = win->screen; /* the one disappearing */
sc->state = SCREENNORMAL;
- /* find old area */
- for (old = sc->areabase.first; old; old = old->next)
- if (old->full) break;
- if (old == NULL) {
+ /* find old area to restore from */
+ ScrArea *fullsa = NULL;
+ for (ScrArea *old = sc->areabase.first; old; old = old->next) {
+ /* area to restore from is always first */
+ if (old->full && !fullsa) {
+ fullsa = old;
+ }
+
+ /* clear full screen state */
+ old->full = NULL;
+ old->flag &= ~AREA_TEMP_INFO;
+ }
+
+ sa->flag &= ~AREA_TEMP_INFO;
+ sa->full = NULL;
+
+ if (fullsa == NULL) {
if (G.debug & G_DEBUG)
printf("%s: something wrong in areafullscreen\n", __func__);
return NULL;
@@ -1912,9 +1622,7 @@ ScrArea *ED_screen_state_toggle(bContext *C, wmWindow *win, ScrArea *sa, const s
}
}
- ED_area_data_swap(old, sa);
- if (sa->flag & AREA_TEMP_INFO) sa->flag &= ~AREA_TEMP_INFO;
- old->full = NULL;
+ ED_area_data_swap(fullsa, sa);
/* animtimer back */
sc->animtimer = oldscreen->animtimer;
@@ -1922,7 +1630,6 @@ ScrArea *ED_screen_state_toggle(bContext *C, wmWindow *win, ScrArea *sa, const s
ED_screen_set(C, sc);
- BKE_screen_free(oldscreen);
BKE_libblock_free(CTX_data_main(C), oldscreen);
/* After we've restored back to SCREENNORMAL, we have to wait with
@@ -2166,10 +1873,11 @@ void ED_update_for_newframe(Main *bmain, Scene *scene, int UNUSED(mute))
/* update animated texture nodes */
{
Tex *tex;
- for (tex = bmain->tex.first; tex; tex = tex->id.next)
+ for (tex = bmain->tex.first; tex; tex = tex->id.next) {
if (tex->use_nodes && tex->nodetree) {
ntreeTexTagAnimated(tex->nodetree);
}
+ }
}
}
diff --git a/source/blender/editors/screen/screen_intern.h b/source/blender/editors/screen/screen_intern.h
index ccb6d5a6dca..db5259f5865 100644
--- a/source/blender/editors/screen/screen_intern.h
+++ b/source/blender/editors/screen/screen_intern.h
@@ -31,6 +31,9 @@
#ifndef __SCREEN_INTERN_H__
#define __SCREEN_INTERN_H__
+struct bContext;
+struct bContextDataResult;
+
/* internal exports only */
#define AZONESPOT (0.6f * U.widget_unit)
@@ -40,12 +43,12 @@
/* area.c */
void ED_area_data_copy(ScrArea *sa_dst, ScrArea *sa_src, const bool do_free);
void ED_area_data_swap(ScrArea *sa1, ScrArea *sa2);
-void region_toggle_hidden(bContext *C, ARegion *ar, const bool do_fade);
+void region_toggle_hidden(struct bContext *C, ARegion *ar, const bool do_fade);
/* screen_edit.c */
ScrEdge *screen_findedge(bScreen *sc, ScrVert *v1, ScrVert *v2);
ScrArea *area_split(bScreen *sc, ScrArea *sa, char dir, float fac, int merge);
-int screen_area_join(bContext *C, bScreen *scr, ScrArea *sa1, ScrArea *sa2);
+int screen_area_join(struct bContext *C, bScreen *scr, ScrArea *sa1, ScrArea *sa2);
int area_getorientation(ScrArea *sa, ScrArea *sb);
void select_connected_scredge(bScreen *sc, ScrEdge *edge);
@@ -61,7 +64,8 @@ ScrEdge *screen_find_active_scredge(bScreen *sc,
struct AZone *is_in_area_actionzone(ScrArea *sa, const int xy[2]);
/* screen_context.c */
-int ed_screen_context(const bContext *C, const char *member, bContextDataResult *result);
+int ed_screen_context(
+ const struct bContext *C, const char *member, struct bContextDataResult *result);
extern const char *screen_context_dir[]; /* doc access */
diff --git a/source/blender/editors/screen/screen_ops.c b/source/blender/editors/screen/screen_ops.c
index a7a0a240259..cbdf05a1c82 100644
--- a/source/blender/editors/screen/screen_ops.c
+++ b/source/blender/editors/screen/screen_ops.c
@@ -74,6 +74,7 @@
#include "ED_screen_types.h"
#include "ED_sequencer.h"
#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_view3d.h"
#include "RNA_access.h"
@@ -87,10 +88,12 @@
#define KM_MODAL_CANCEL 1
#define KM_MODAL_APPLY 2
-#define KM_MODAL_STEP10 3
-#define KM_MODAL_STEP10_OFF 4
+#define KM_MODAL_SNAP_ON 3
+#define KM_MODAL_SNAP_OFF 4
-/* ************** Exported Poll tests ********************** */
+/* -------------------------------------------------------------------- */
+/** \name Public Poll API
+ * \{ */
int ED_operator_regionactive(bContext *C)
{
@@ -124,36 +127,6 @@ static int ED_operator_screenactive_norender(bContext *C)
return 1;
}
-
-static int screen_active_editable(bContext *C)
-{
- if (ED_operator_screenactive(C)) {
- /* no full window splitting allowed */
- if (CTX_wm_screen(C)->state != SCREENNORMAL)
- return 0;
- return 1;
- }
- return 0;
-}
-
-static ARegion *screen_find_region_type(bContext *C, int type)
-{
- ARegion *ar = CTX_wm_region(C);
-
- /* find the header region
- * - try context first, but upon failing, search all regions in area...
- */
- if ((ar == NULL) || (ar->regiontype != type)) {
- ScrArea *sa = CTX_wm_area(C);
- ar = BKE_area_find_region_type(sa, type);
- }
- else {
- ar = NULL;
- }
-
- return ar;
-}
-
/* when mouse is over area-edge */
int ED_operator_screen_mainwinactive(bContext *C)
{
@@ -168,7 +141,7 @@ int ED_operator_screen_mainwinactive(bContext *C)
int ED_operator_scene_editable(bContext *C)
{
Scene *scene = CTX_data_scene(C);
- if (scene && !ID_IS_LINKED_DATABLOCK(scene))
+ if (scene && !ID_IS_LINKED(scene))
return 1;
return 0;
}
@@ -178,7 +151,7 @@ int ED_operator_objectmode(bContext *C)
Scene *scene = CTX_data_scene(C);
Object *obact = CTX_data_active_object(C);
- if (scene == NULL || ID_IS_LINKED_DATABLOCK(scene))
+ if (scene == NULL || ID_IS_LINKED(scene))
return 0;
if (CTX_data_edit_object(C))
return 0;
@@ -279,7 +252,7 @@ int ED_operator_node_editable(bContext *C)
{
SpaceNode *snode = CTX_wm_space_node(C);
- if (snode && snode->edittree && !ID_IS_LINKED_DATABLOCK(snode->edittree))
+ if (snode && snode->edittree && !ID_IS_LINKED(snode->edittree))
return 1;
return 0;
@@ -341,20 +314,20 @@ int ED_operator_object_active(bContext *C)
int ED_operator_object_active_editable(bContext *C)
{
Object *ob = ED_object_active_context(C);
- return ((ob != NULL) && !ID_IS_LINKED_DATABLOCK(ob) && !ed_object_hidden(ob));
+ return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob));
}
int ED_operator_object_active_editable_mesh(bContext *C)
{
Object *ob = ED_object_active_context(C);
- return ((ob != NULL) && !ID_IS_LINKED_DATABLOCK(ob) && !ed_object_hidden(ob) &&
- (ob->type == OB_MESH) && !ID_IS_LINKED_DATABLOCK(ob->data));
+ return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) &&
+ (ob->type == OB_MESH) && !ID_IS_LINKED(ob->data));
}
int ED_operator_object_active_editable_font(bContext *C)
{
Object *ob = ED_object_active_context(C);
- return ((ob != NULL) && !ID_IS_LINKED_DATABLOCK(ob) && !ed_object_hidden(ob) &&
+ return ((ob != NULL) && !ID_IS_LINKED(ob) && !ed_object_hidden(ob) &&
(ob->type == OB_FONT));
}
@@ -447,8 +420,8 @@ int ED_operator_posemode_local(bContext *C)
if (ED_operator_posemode(C)) {
Object *ob = BKE_object_pose_armature_get(CTX_data_active_object(C));
bArmature *arm = ob->data;
- return !(ID_IS_LINKED_DATABLOCK(&ob->id) ||
- ID_IS_LINKED_DATABLOCK(&arm->id));
+ return !(ID_IS_LINKED(&ob->id) ||
+ ID_IS_LINKED(&arm->id));
}
return false;
}
@@ -580,7 +553,46 @@ int ED_operator_mask(bContext *C)
return false;
}
-/* *************************** action zone operator ************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Screen Utilities
+ * \{ */
+
+static int screen_active_editable(bContext *C)
+{
+ if (ED_operator_screenactive(C)) {
+ /* no full window splitting allowed */
+ if (CTX_wm_screen(C)->state != SCREENNORMAL)
+ return 0;
+ return 1;
+ }
+ return 0;
+}
+
+static ARegion *screen_find_region_type(bContext *C, int type)
+{
+ ARegion *ar = CTX_wm_region(C);
+
+ /* find the header region
+ * - try context first, but upon failing, search all regions in area...
+ */
+ if ((ar == NULL) || (ar->regiontype != type)) {
+ ScrArea *sa = CTX_wm_area(C);
+ ar = BKE_area_find_region_type(sa, type);
+ }
+ else {
+ ar = NULL;
+ }
+
+ return ar;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Action Zone Operator
+ * \{ */
/* operator state vars used:
* none
@@ -852,25 +864,29 @@ static void SCREEN_OT_actionzone(wmOperatorType *ot)
RNA_def_int(ot->srna, "modifier", 0, 0, 2, "Modifier", "Modifier state", 0, 2);
}
-/* ************** swap area operator *********************************** */
+/** \} */
-/* operator state vars used:
- * sa1 start area
- * sa2 area to swap with
- *
+/* -------------------------------------------------------------------- */
+/** \name Swap Area Operator
+ * \{ */
+
+/* operator state vars used:
+ * sa1 start area
+ * sa2 area to swap with
+ *
* functions:
- *
+ *
* init() set custom data for operator, based on actionzone event custom data
- *
- * cancel() cancel the operator
- *
- * exit() cleanup, send notifier
- *
+ *
+ * cancel() cancel the operator
+ *
+ * exit() cleanup, send notifier
+ *
* callbacks:
- *
+ *
* invoke() gets called on shift+lmb drag in actionzone
* call init(), add handler
- *
+ *
* modal() accept modal events while doing it
*/
@@ -972,7 +988,13 @@ static void SCREEN_OT_area_swap(wmOperatorType *ot)
ot->flag = OPTYPE_BLOCKING;
}
-/* *********** Duplicate area as new window operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Area Duplicate Operator
+ *
+ * Create new window from area.
+ * \{ */
/* operator callback */
static int area_dupli_invoke(bContext *C, wmOperator *op, const wmEvent *event)
@@ -1045,8 +1067,11 @@ static void SCREEN_OT_area_dupli(wmOperatorType *ot)
ot->poll = ED_operator_areaactive;
}
+/** \} */
-/* ************** move area edge operator *********************************** */
+/* -------------------------------------------------------------------- */
+/** \name Move Area Edge Operator
+ * \{ */
/* operator state vars used:
* x, y mouse coord near edge
@@ -1077,8 +1102,9 @@ static void SCREEN_OT_area_dupli(wmOperatorType *ot)
*/
typedef struct sAreaMoveData {
- int bigger, smaller, origval, step;
+ int bigger, smaller, origval;
char dir;
+ bool do_snap;
} sAreaMoveData;
/* helper call to move area-edge, sets limits
@@ -1170,55 +1196,98 @@ static int area_move_init(bContext *C, wmOperator *op)
return 1;
}
+static int area_snap_calc_location(
+ const bScreen *sc, const int delta,
+ const int origval, const int dir,
+ const int bigger, const int smaller)
+{
+ int final_loc = -1;
+
+ const int m_loc = origval + delta;
+ const int axis = (dir == 'v') ? 0 : 1;
+ int snap_dist;
+ int dist;
+ {
+ /* Test the snap to middle. */
+ int middle = origval + (bigger - smaller) / 2;
+ middle -= (middle % AREAGRID);
+
+ snap_dist = abs(m_loc - middle);
+ final_loc = middle;
+ }
+
+ for (const ScrVert *v1 = sc->vertbase.first; v1; v1 = v1->next) {
+ if (v1->editflag) {
+ const int v_loc = (&v1->vec.x)[!axis];
+
+ for (const ScrVert *v2 = sc->vertbase.first; v2; v2 = v2->next) {
+ if (!v2->editflag) {
+ if (v_loc == (&v2->vec.x)[!axis]) {
+ const int v_loc2 = (&v2->vec.x)[axis];
+ /* Do not snap to the vertices at the ends. */
+ if ((origval - smaller) < v_loc2 && v_loc2 < (origval + bigger)) {
+ dist = abs(m_loc - v_loc2);
+ if (dist <= snap_dist) {
+ snap_dist = dist;
+ final_loc = v_loc2;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return final_loc;
+}
+
/* moves selected screen edge amount of delta, used by split & move */
-static void area_move_apply_do(bContext *C, int origval, int delta, int dir, int bigger, int smaller)
+static void area_move_apply_do(
+ const bContext *C, int delta,
+ const int origval, const int dir,
+ const int bigger, const int smaller,
+ const bool do_snap)
{
- wmWindow *win = CTX_wm_window(C);
- const int winsize_x = WM_window_pixels_x(win);
- const int winsize_y = WM_window_pixels_y(win);
bScreen *sc = CTX_wm_screen(C);
ScrVert *v1;
- ScrArea *sa;
- int doredraw = 0;
- int oldval;
-
- delta = CLAMPIS(delta, -smaller, bigger);
-
+ bool doredraw = false;
+ CLAMP(delta, -smaller, bigger);
+
+ short final_loc = -1;
+
+ if (do_snap) {
+ final_loc = area_snap_calc_location(sc, delta, origval, dir, bigger, smaller);
+ }
+ else {
+ final_loc = origval + delta;
+ if (delta != bigger && delta != -smaller) {
+ final_loc -= (final_loc % AREAGRID);
+ }
+ }
+
+ BLI_assert(final_loc != -1);
+ short axis = (dir == 'v') ? 0 : 1;
+
for (v1 = sc->vertbase.first; v1; v1 = v1->next) {
if (v1->editflag) {
- /* that way a nice AREAGRID */
- if ((dir == 'v') && v1->vec.x > 0 && v1->vec.x < winsize_x - 1) {
- oldval = v1->vec.x;
- v1->vec.x = origval + delta;
-
- if (delta != bigger && delta != -smaller) {
- v1->vec.x -= (v1->vec.x % AREAGRID);
- v1->vec.x = CLAMPIS(v1->vec.x, origval - smaller, origval + bigger);
- }
- if (oldval != v1->vec.x)
- doredraw = 1;
- }
- if ((dir == 'h') && v1->vec.y > 0 && v1->vec.y < winsize_y - 1) {
- oldval = v1->vec.y;
- v1->vec.y = origval + delta;
-
- if (delta != bigger && delta != smaller) {
- v1->vec.y -= (v1->vec.y % AREAGRID);
- v1->vec.y = CLAMPIS(v1->vec.y, origval - smaller, origval + bigger);
- }
- if (oldval != v1->vec.y)
- doredraw = 1;
+ short oldval = (&v1->vec.x)[axis];
+ (&v1->vec.x)[axis] = final_loc;
+
+ if (oldval == final_loc) {
+ /* nothing will change to the other vertices either. */
+ break;
}
+ doredraw = true;
}
}
/* only redraw if we actually moved a screen vert, for AREAGRID */
if (doredraw) {
- for (sa = sc->areabase.first; sa; sa = sa->next) {
- if (sa->v1->editflag || sa->v2->editflag || sa->v3->editflag || sa->v4->editflag)
+ for (ScrArea *sa = sc->areabase.first; sa; sa = sa->next) {
+ if (sa->v1->editflag || sa->v2->editflag || sa->v3->editflag || sa->v4->editflag) {
ED_area_tag_redraw(sa);
+ }
}
-
WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL); /* redraw everything */
}
}
@@ -1226,10 +1295,9 @@ static void area_move_apply_do(bContext *C, int origval, int delta, int dir, int
static void area_move_apply(bContext *C, wmOperator *op)
{
sAreaMoveData *md = op->customdata;
- int delta;
-
- delta = RNA_int_get(op->ptr, "delta");
- area_move_apply_do(C, md->origval, delta, md->dir, md->bigger, md->smaller);
+ int delta = RNA_int_get(op->ptr, "delta");
+
+ area_move_apply_do(C, delta, md->origval, md->dir, md->bigger, md->smaller, md->do_snap);
}
static void area_move_exit(bContext *C, wmOperator *op)
@@ -1291,7 +1359,6 @@ static int area_move_modal(bContext *C, wmOperator *op, const wmEvent *event)
y = RNA_int_get(op->ptr, "y");
delta = (md->dir == 'v') ? event->x - x : event->y - y;
- if (md->step) delta = delta - (delta % md->step);
RNA_int_set(op->ptr, "delta", delta);
area_move_apply(C, op);
@@ -1307,12 +1374,12 @@ static int area_move_modal(bContext *C, wmOperator *op, const wmEvent *event)
case KM_MODAL_CANCEL:
area_move_cancel(C, op);
return OPERATOR_CANCELLED;
-
- case KM_MODAL_STEP10:
- md->step = 10;
+
+ case KM_MODAL_SNAP_ON:
+ md->do_snap = true;
break;
- case KM_MODAL_STEP10_OFF:
- md->step = 0;
+ case KM_MODAL_SNAP_OFF:
+ md->do_snap = false;
break;
}
break;
@@ -1344,50 +1411,54 @@ static void SCREEN_OT_area_move(wmOperatorType *ot)
RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
}
-/* ************** split area operator *********************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Split Area Operator
+ * \{ */
-/*
- * operator state vars:
+/*
+ * operator state vars:
* fac spit point
* dir direction 'v' or 'h'
- *
+ *
* operator customdata:
* area pointer to (active) area
- * x, y last used mouse pos
+ * x, y last used mouse pos
* (more, see below)
- *
+ *
* functions:
- *
+ *
* init() set default property values, find area based on context
- *
- * apply() split area based on state vars
- *
- * exit() cleanup, send notifier
- *
+ *
+ * apply() split area based on state vars
+ *
+ * exit() cleanup, send notifier
+ *
* cancel() remove duplicated area
- *
+ *
* callbacks:
- *
+ *
* exec() execute without any user interaction, based on state vars
* call init(), apply(), exit()
- *
+ *
* invoke() gets called on mouse click in action-widget
* call init(), add modal handler
* call apply() with initial motion
- *
+ *
* modal() accept modal events while doing it
* call move-areas code with delta motion
* call exit() or cancel() and remove handler
*/
typedef struct sAreaSplitData {
- int x, y; /* last used mouse position */
-
int origval; /* for move areas */
int bigger, smaller; /* constraints for moving new edge */
int delta; /* delta move edge */
int origmin, origsize; /* to calculate fac, for property storage */
int previewmode; /* draw previewline, then split */
+ void *draw_callback; /* call `ED_screen_draw_split_preview` */
+ bool do_snap;
ScrEdge *nedge; /* new edge */
ScrArea *sarea; /* start area */
@@ -1395,6 +1466,19 @@ typedef struct sAreaSplitData {
} sAreaSplitData;
+static void area_split_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
+{
+ const wmOperator *op = userdata;
+
+ sAreaSplitData *sd = op->customdata;
+ if (sd->sarea) {
+ int dir = RNA_enum_get(op->ptr, "direction");
+ float fac = RNA_float_get(op->ptr, "factor");
+
+ ED_screen_draw_split_preview(sd->sarea, dir, fac);
+ }
+}
+
/* generic init, menu case, doesn't need active area */
static int area_split_menu_init(bContext *C, wmOperator *op)
{
@@ -1405,15 +1489,7 @@ static int area_split_menu_init(bContext *C, wmOperator *op)
op->customdata = sd;
sd->sarea = CTX_wm_area(C);
-
- if (sd->sarea) {
- int dir = RNA_enum_get(op->ptr, "direction");
- if (dir == 'h')
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_H;
- else
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_V;
- }
return 1;
}
@@ -1522,9 +1598,9 @@ static void area_split_exit(bContext *C, wmOperator *op)
if (sd->sarea) ED_area_tag_redraw(sd->sarea);
if (sd->narea) ED_area_tag_redraw(sd->narea);
- if (sd->sarea)
- sd->sarea->flag &= ~(AREA_FLAG_DRAWSPLIT_H | AREA_FLAG_DRAWSPLIT_V);
-
+ if (sd->draw_callback)
+ WM_draw_cb_exit(CTX_wm_window(C), sd->draw_callback);
+
MEM_freeN(op->customdata);
op->customdata = NULL;
}
@@ -1537,6 +1613,12 @@ static void area_split_exit(bContext *C, wmOperator *op)
removedouble_scredges(CTX_wm_screen(C));
}
+static void area_split_preview_update_cursor(bContext *C, wmOperator *op)
+{
+ wmWindow *win = CTX_wm_window(C);
+ int dir = RNA_enum_get(op->ptr, "direction");
+ WM_cursor_set(win, (dir == 'v') ? CURSOR_X_MOVE : CURSOR_Y_MOVE);
+}
/* UI callback, adds new handler */
static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event)
@@ -1614,9 +1696,6 @@ static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event)
sd = (sAreaSplitData *)op->customdata;
- sd->x = event->x;
- sd->y = event->y;
-
if (event->type == EVT_ACTIONZONE_AREA) {
/* do the split */
@@ -1631,9 +1710,11 @@ static int area_split_invoke(bContext *C, wmOperator *op, const wmEvent *event)
}
else {
sd->previewmode = 1;
+ sd->draw_callback = WM_draw_cb_activate(win, area_split_draw_cb, op);
/* add temp handler for edge move or cancel */
WM_event_add_modal_handler(C, op);
-
+ area_split_preview_update_cursor(C, op);
+
return OPERATOR_RUNNING_MODAL;
}
@@ -1660,6 +1741,7 @@ static void area_split_cancel(bContext *C, wmOperator *op)
sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
if (sd->previewmode) {
+ /* pass */
}
else {
if (screen_area_join(C, CTX_wm_screen(C), sd->sarea, sd->narea)) {
@@ -1676,48 +1758,15 @@ static void area_split_cancel(bContext *C, wmOperator *op)
static int area_split_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
sAreaSplitData *sd = (sAreaSplitData *)op->customdata;
- float fac;
- int dir;
-
+ PropertyRNA *prop_dir = RNA_struct_find_property(op->ptr, "direction");
+ bool update_factor = false;
+
/* execute the events */
switch (event->type) {
case MOUSEMOVE:
- dir = RNA_enum_get(op->ptr, "direction");
-
- sd->delta = (dir == 'v') ? event->x - sd->origval : event->y - sd->origval;
- if (sd->previewmode == 0)
- area_move_apply_do(C, sd->origval, sd->delta, dir, sd->bigger, sd->smaller);
- else {
- if (sd->sarea) {
- sd->sarea->flag &= ~(AREA_FLAG_DRAWSPLIT_H | AREA_FLAG_DRAWSPLIT_V);
- ED_area_tag_redraw(sd->sarea);
- }
- /* area context not set */
- sd->sarea = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
-
- if (sd->sarea) {
- ED_area_tag_redraw(sd->sarea);
- if (dir == 'v') {
- sd->origsize = sd->sarea->winx;
- sd->origmin = sd->sarea->totrct.xmin;
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_V;
- }
- else {
- sd->origsize = sd->sarea->winy;
- sd->origmin = sd->sarea->totrct.ymin;
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_H;
- }
- }
-
- CTX_wm_window(C)->screen->do_draw = true;
-
- }
-
- fac = (dir == 'v') ? event->x - sd->origmin : event->y - sd->origmin;
- RNA_float_set(op->ptr, "factor", fac / (float)sd->origsize);
-
+ update_factor = true;
break;
-
+
case LEFTMOUSE:
if (sd->previewmode) {
area_split_apply(C, op);
@@ -1735,27 +1784,15 @@ static int area_split_modal(bContext *C, wmOperator *op, const wmEvent *event)
case MIDDLEMOUSE:
case TABKEY:
if (sd->previewmode == 0) {
+ /* pass */
}
else {
- dir = RNA_enum_get(op->ptr, "direction");
-
if (event->val == KM_PRESS) {
if (sd->sarea) {
- sd->sarea->flag &= ~(AREA_FLAG_DRAWSPLIT_H | AREA_FLAG_DRAWSPLIT_V);
- ED_area_tag_redraw(sd->sarea);
-
- if (dir == 'v') {
- RNA_enum_set(op->ptr, "direction", 'h');
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_H;
-
- WM_cursor_set(CTX_wm_window(C), CURSOR_X_MOVE);
- }
- else {
- RNA_enum_set(op->ptr, "direction", 'v');
- sd->sarea->flag |= AREA_FLAG_DRAWSPLIT_V;
-
- WM_cursor_set(CTX_wm_window(C), CURSOR_Y_MOVE);
- }
+ int dir = RNA_property_enum_get(op->ptr, prop_dir);
+ RNA_property_enum_set(op->ptr, prop_dir, (dir == 'v') ? 'h' : 'v');
+ area_split_preview_update_cursor(C, op);
+ update_factor = true;
}
}
}
@@ -1766,12 +1803,68 @@ static int area_split_modal(bContext *C, wmOperator *op, const wmEvent *event)
case ESCKEY:
area_split_cancel(C, op);
return OPERATOR_CANCELLED;
+
+ case LEFTCTRLKEY:
+ sd->do_snap = event->val == KM_PRESS;
+ update_factor = true;
+ break;
}
-
+
+ if (update_factor) {
+ const int dir = RNA_property_enum_get(op->ptr, prop_dir);
+
+ sd->delta = (dir == 'v') ? event->x - sd->origval : event->y - sd->origval;
+
+ if (sd->previewmode == 0) {
+ if (sd->do_snap) {
+ const int snap_loc = area_snap_calc_location(
+ CTX_wm_screen(C), sd->delta, sd->origval, dir, sd->bigger, sd->smaller);
+ sd->delta = snap_loc - sd->origval;
+ }
+ area_move_apply_do(C, sd->delta, sd->origval, dir, sd->bigger, sd->smaller, false);
+ }
+ else {
+ if (sd->sarea) {
+ ED_area_tag_redraw(sd->sarea);
+ }
+ /* area context not set */
+ sd->sarea = BKE_screen_find_area_xy(CTX_wm_screen(C), SPACE_TYPE_ANY, event->x, event->y);
+
+ if (sd->sarea) {
+ ScrArea *sa = sd->sarea;
+ if (dir == 'v') {
+ sd->origsize = sa->winx;
+ sd->origmin = sa->totrct.xmin;
+ }
+ else {
+ sd->origsize = sa->winy;
+ sd->origmin = sa->totrct.ymin;
+ }
+
+ if (sd->do_snap) {
+ sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 1;
+
+ const int snap_loc = area_snap_calc_location(
+ CTX_wm_screen(C), sd->delta, sd->origval, dir, sd->origmin + sd->origsize, -sd->origmin);
+
+ sa->v1->editflag = sa->v2->editflag = sa->v3->editflag = sa->v4->editflag = 0;
+ sd->delta = snap_loc - sd->origval;
+ }
+
+ ED_area_tag_redraw(sd->sarea);
+ }
+
+ CTX_wm_window(C)->screen->do_draw = true;
+ }
+
+ float fac = (float)(sd->delta + sd->origval - sd->origmin) / sd->origsize;
+ RNA_float_set(op->ptr, "factor", fac);
+ }
+
return OPERATOR_RUNNING_MODAL;
}
-static EnumPropertyItem prop_direction_items[] = {
+static const EnumPropertyItem prop_direction_items[] = {
{'h', "HORIZONTAL", 0, "Horizontal", ""},
{'v', "VERTICAL", 0, "Vertical", ""},
{0, NULL, 0, NULL, NULL}
@@ -1800,9 +1893,11 @@ static void SCREEN_OT_area_split(wmOperatorType *ot)
RNA_def_int(ot->srna, "mouse_y", -100, INT_MIN, INT_MAX, "Mouse Y", "", INT_MIN, INT_MAX);
}
+/** \} */
-
-/* ************** scale region edge operator *********************************** */
+/* -------------------------------------------------------------------- */
+/** \name Scale Region Edge Operator
+ * \{ */
typedef struct RegionMoveData {
AZone *az;
@@ -2071,8 +2166,11 @@ static void SCREEN_OT_region_scale(wmOperatorType *ot)
ot->flag = OPTYPE_BLOCKING | OPTYPE_INTERNAL;
}
+/** \} */
-/* ************** frame change operator ***************************** */
+/* -------------------------------------------------------------------- */
+/** \name Frame Change Operator
+ * \{ */
static void areas_do_frame_follow(bContext *C, bool middle)
{
@@ -2154,6 +2252,11 @@ static void SCREEN_OT_frame_offset(wmOperatorType *ot)
RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Frame Jump Operator
+ * \{ */
/* function to be called outside UI context, or for redo */
static int frame_jump_exec(bContext *C, wmOperator *op)
@@ -2208,8 +2311,11 @@ static void SCREEN_OT_frame_jump(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "end", 0, "Last Frame", "Jump to the last frame of the frame range");
}
+/** \} */
-/* ************** jump to keyframe operator ***************************** */
+/* -------------------------------------------------------------------- */
+/** \name Jump to Key-Frame Operator
+ * \{ */
/* function to be called outside UI context, or for redo */
static int keyframe_jump_exec(bContext *C, wmOperator *op)
@@ -2260,25 +2366,28 @@ static int keyframe_jump_exec(bContext *C, wmOperator *op)
BLI_dlrbTree_linkedlist_sync(&keys);
/* find matching keyframe in the right direction */
- do {
- if (next)
- ak = (ActKeyColumn *)BLI_dlrbTree_search_next(&keys, compare_ak_cfraPtr, &cfra);
- else
- ak = (ActKeyColumn *)BLI_dlrbTree_search_prev(&keys, compare_ak_cfraPtr, &cfra);
-
- if (ak) {
- if (CFRA != (int)ak->cfra) {
- /* this changes the frame, so set the frame and we're done */
- CFRA = (int)ak->cfra;
- done = true;
+ if (next)
+ ak = (ActKeyColumn *)BLI_dlrbTree_search_next(&keys, compare_ak_cfraPtr, &cfra);
+ else
+ ak = (ActKeyColumn *)BLI_dlrbTree_search_prev(&keys, compare_ak_cfraPtr, &cfra);
+
+ while ((ak != NULL) && (done == false)) {
+ if (CFRA != (int)ak->cfra) {
+ /* this changes the frame, so set the frame and we're done */
+ CFRA = (int)ak->cfra;
+ done = true;
+ }
+ else {
+ /* take another step... */
+ if (next) {
+ ak = ak->next;
}
else {
- /* make this the new starting point for the search */
- cfra = ak->cfra;
+ ak = ak->prev;
}
}
- } while ((ak != NULL) && (done == false));
-
+ }
+
/* free temp stuff */
BLI_dlrbTree_free(&keys);
@@ -2315,7 +2424,11 @@ static void SCREEN_OT_keyframe_jump(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "next", true, "Next Keyframe", "");
}
-/* ************** jump to marker operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Jump to Marker Operator
+ * \{ */
/* function to be called outside UI context, or for redo */
static int marker_jump_exec(bContext *C, wmOperator *op)
@@ -2378,7 +2491,11 @@ static void SCREEN_OT_marker_jump(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "next", true, "Next Marker", "");
}
-/* ************** switch screen operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Screen Operator
+ * \{ */
static bool screen_set_is_ok(bScreen *screen, bScreen *screen_prev)
{
@@ -2454,8 +2571,11 @@ static void SCREEN_OT_screen_set(wmOperatorType *ot)
RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
}
-/* ************** screen full-area operator ***************************** */
+/** \} */
+/* -------------------------------------------------------------------- */
+/** \name Screen Full-Area Operator
+ * \{ */
/* function to be called outside UI context, or for redo */
static int screen_maximize_area_exec(bContext *C, wmOperator *op)
@@ -2506,7 +2626,11 @@ static void SCREEN_OT_screen_full_area(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-/* ************** join area operator ********************************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Screen Join-Area Operator
+ * \{ */
/* operator state vars used:
* x1, y1 mouse coord in first area, which will disappear
@@ -2536,13 +2660,23 @@ static void SCREEN_OT_screen_full_area(wmOperatorType *ot)
*/
typedef struct sAreaJoinData {
- ScrArea *sa1; /* first area to be considered */
- ScrArea *sa2; /* second area to be considered */
- ScrArea *scr; /* designed for removal */
+ ScrArea *sa1; /* first area to be considered */
+ ScrArea *sa2; /* second area to be considered */
+ void *draw_callback; /* call `ED_screen_draw_join_shape` */
} sAreaJoinData;
+static void area_join_draw_cb(const struct wmWindow *UNUSED(win), void *userdata)
+{
+ const wmOperator *op = userdata;
+
+ sAreaJoinData *sd = op->customdata;
+ if (sd->sa1 && sd->sa2) {
+ ED_screen_draw_join_shape(sd->sa1, sd->sa2);
+ }
+}
+
/* validate selection inside screen, set variables OK */
/* return 0: init failed */
/* XXX todo: find edge based on (x,y) and set other area? */
@@ -2576,14 +2710,14 @@ static int area_join_init(bContext *C, wmOperator *op)
}
jd = (sAreaJoinData *)MEM_callocN(sizeof(sAreaJoinData), "op_area_join");
-
+
jd->sa1 = sa1;
- jd->sa1->flag |= AREA_FLAG_DRAWJOINFROM;
jd->sa2 = sa2;
- jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
-
+
op->customdata = jd;
-
+
+ jd->draw_callback = WM_draw_cb_activate(CTX_wm_window(C), area_join_draw_cb, op);
+
return 1;
}
@@ -2607,8 +2741,13 @@ static int area_join_apply(bContext *C, wmOperator *op)
/* finish operation */
static void area_join_exit(bContext *C, wmOperator *op)
{
- if (op->customdata) {
- MEM_freeN(op->customdata);
+ sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
+
+ if (jd) {
+ if (jd->draw_callback)
+ WM_draw_cb_exit(CTX_wm_window(C), jd->draw_callback);
+
+ MEM_freeN(jd);
op->customdata = NULL;
}
@@ -2667,17 +2806,6 @@ static int area_join_invoke(bContext *C, wmOperator *op, const wmEvent *event)
static void area_join_cancel(bContext *C, wmOperator *op)
{
- sAreaJoinData *jd = (sAreaJoinData *)op->customdata;
-
- if (jd->sa1) {
- jd->sa1->flag &= ~AREA_FLAG_DRAWJOINFROM;
- jd->sa1->flag &= ~AREA_FLAG_DRAWJOINTO;
- }
- if (jd->sa2) {
- jd->sa2->flag &= ~AREA_FLAG_DRAWJOINFROM;
- jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
- }
-
WM_event_add_notifier(C, NC_WINDOW, NULL);
area_join_exit(C, op);
@@ -2701,9 +2829,7 @@ static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
if (jd->sa1 != sa) {
dir = area_getorientation(jd->sa1, sa);
if (dir != -1) {
- if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa2 = sa;
- jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
}
else {
/* we are not bordering on the previously selected area
@@ -2712,15 +2838,10 @@ static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
*/
dir = area_getorientation(sa, jd->sa2);
if (dir != -1) {
- if (jd->sa1) jd->sa1->flag &= ~AREA_FLAG_DRAWJOINFROM;
- if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa1 = jd->sa2;
jd->sa2 = sa;
- if (jd->sa1) jd->sa1->flag |= AREA_FLAG_DRAWJOINFROM;
- if (jd->sa2) jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
}
else {
- if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa2 = NULL;
}
}
@@ -2730,12 +2851,8 @@ static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
/* we are back in the area previously selected for keeping
* we swap the areas if possible to allow user to choose */
if (jd->sa2 != NULL) {
- if (jd->sa1) jd->sa1->flag &= ~AREA_FLAG_DRAWJOINFROM;
- if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa1 = jd->sa2;
jd->sa2 = sa;
- if (jd->sa1) jd->sa1->flag |= AREA_FLAG_DRAWJOINFROM;
- if (jd->sa2) jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
dir = area_getorientation(jd->sa1, jd->sa2);
if (dir == -1) {
printf("oops, didn't expect that!\n");
@@ -2744,9 +2861,7 @@ static int area_join_modal(bContext *C, wmOperator *op, const wmEvent *event)
else {
dir = area_getorientation(jd->sa1, sa);
if (dir != -1) {
- if (jd->sa2) jd->sa2->flag &= ~AREA_FLAG_DRAWJOINTO;
jd->sa2 = sa;
- jd->sa2->flag |= AREA_FLAG_DRAWJOINTO;
}
}
WM_event_add_notifier(C, NC_WINDOW, NULL);
@@ -2800,7 +2915,11 @@ static void SCREEN_OT_area_join(wmOperatorType *ot)
RNA_def_int(ot->srna, "max_y", -100, INT_MIN, INT_MAX, "Y 2", "", INT_MIN, INT_MAX);
}
-/* ******************************* */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Screen Area Options Operator
+ * \{ */
static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
@@ -2808,7 +2927,7 @@ static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent
bScreen *sc = CTX_wm_screen(C);
uiPopupMenu *pup;
uiLayout *layout;
- PointerRNA ptr1, ptr2;
+ PointerRNA ptr;
ScrEdge *actedge;
const int winsize_x = WM_window_pixels_x(win);
const int winsize_y = WM_window_pixels_y(win);
@@ -2820,22 +2939,17 @@ static int screen_area_options_invoke(bContext *C, wmOperator *op, const wmEvent
pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
layout = UI_popup_menu_layout(pup);
- WM_operator_properties_create(&ptr1, "SCREEN_OT_area_join");
-
- /* mouse cursor on edge, '4' can fail on wide edges... */
- RNA_int_set(&ptr1, "min_x", event->x + 4);
- RNA_int_set(&ptr1, "min_y", event->y + 4);
- RNA_int_set(&ptr1, "max_x", event->x - 4);
- RNA_int_set(&ptr1, "max_y", event->y - 4);
-
- WM_operator_properties_create(&ptr2, "SCREEN_OT_area_split");
-
+ uiItemFullO(layout, "SCREEN_OT_area_split", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
/* store initial mouse cursor position */
- RNA_int_set(&ptr2, "mouse_x", event->x);
- RNA_int_set(&ptr2, "mouse_y", event->y);
-
- uiItemFullO(layout, "SCREEN_OT_area_split", NULL, ICON_NONE, ptr2.data, WM_OP_INVOKE_DEFAULT, 0);
- uiItemFullO(layout, "SCREEN_OT_area_join", NULL, ICON_NONE, ptr1.data, WM_OP_INVOKE_DEFAULT, 0);
+ RNA_int_set(&ptr, "mouse_x", event->x);
+ RNA_int_set(&ptr, "mouse_y", event->y);
+
+ uiItemFullO(layout, "SCREEN_OT_area_join", NULL, ICON_NONE, NULL, WM_OP_INVOKE_DEFAULT, 0, &ptr);
+ /* mouse cursor on edge, '4' can fail on wide edges... */
+ RNA_int_set(&ptr, "min_x", event->x + 4);
+ RNA_int_set(&ptr, "min_y", event->y + 4);
+ RNA_int_set(&ptr, "max_x", event->x - 4);
+ RNA_int_set(&ptr, "max_y", event->y - 4);
UI_popup_menu_end(C, pup);
@@ -2858,9 +2972,11 @@ static void SCREEN_OT_area_options(wmOperatorType *ot)
ot->flag = OPTYPE_INTERNAL;
}
+/** \} */
-/* ******************************* */
-
+/* -------------------------------------------------------------------- */
+/** \name Space Data Cleanup Operator
+ * \{ */
static int spacedata_cleanup_exec(bContext *C, wmOperator *op)
{
@@ -2899,14 +3015,31 @@ static void SCREEN_OT_spacedata_cleanup(wmOperatorType *ot)
}
-/* ************** repeat last operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Repeat Last Operator
+ * \{ */
static int repeat_last_exec(bContext *C, wmOperator *UNUSED(op))
{
- wmOperator *lastop = CTX_wm_manager(C)->operators.last;
-
- if (lastop)
+ wmWindowManager *wm = CTX_wm_manager(C);
+ wmOperator *lastop = wm->operators.last;
+
+ /* Seek last registered operator */
+ while (lastop) {
+ if (lastop->type->flag & OPTYPE_REGISTER) {
+ break;
+ }
+ else {
+ lastop = lastop->prev;
+ }
+ }
+
+ if (lastop) {
+ WM_operator_free_all_after(wm, lastop);
WM_operator_repeat(C, lastop);
+ }
return OPERATOR_CANCELLED;
}
@@ -2925,6 +3058,12 @@ static void SCREEN_OT_repeat_last(wmOperatorType *ot)
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Repeat History Operator
+ * \{ */
+
static int repeat_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
wmWindowManager *wm = CTX_wm_manager(C);
@@ -2941,8 +3080,9 @@ static int repeat_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNU
layout = UI_popup_menu_layout(pup);
for (i = items - 1, lastop = wm->operators.last; lastop; lastop = lastop->prev, i--)
- if (WM_operator_repeat_check(C, lastop))
+ if ((lastop->type->flag & OPTYPE_REGISTER) && WM_operator_repeat_check(C, lastop)) {
uiItemIntO(layout, RNA_struct_ui_name(lastop->type->srna), ICON_NONE, op->type->idname, "index", i);
+ }
UI_popup_menu_end(C, pup);
@@ -2981,7 +3121,11 @@ static void SCREEN_OT_repeat_history(wmOperatorType *ot)
RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "", 0, 1000);
}
-/* ********************** redo operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Redo Operator
+ * \{ */
static int redo_last_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
{
@@ -3006,7 +3150,11 @@ static void SCREEN_OT_redo_last(wmOperatorType *ot)
ot->poll = ED_operator_screenactive;
}
-/* ************** region four-split operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Region Quad-View Operator
+ * \{ */
static void view3d_localview_update_rv3d(struct RegionView3D *rv3d)
{
@@ -3159,8 +3307,11 @@ static void SCREEN_OT_region_quadview(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
-/* ************** region flip operator ***************************** */
+/* -------------------------------------------------------------------- */
+/** \name Region Flip Operator
+ * \{ */
/* flip a region alignment */
static int region_flip_exec(bContext *C, wmOperator *UNUSED(op))
@@ -3199,7 +3350,12 @@ static void SCREEN_OT_region_flip(wmOperatorType *ot)
ot->flag = 0;
}
-/* ************** header operator ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Header Toggle Operator
+ * \{ */
+
static int header_exec(bContext *C, wmOperator *UNUSED(op))
{
ARegion *ar = screen_find_region_type(C, RGN_TYPE_HEADER);
@@ -3228,52 +3384,11 @@ static void SCREEN_OT_header(wmOperatorType *ot)
ot->exec = header_exec;
}
-/* ************** header flip operator ***************************** */
-
-/* flip a header region alignment */
-static int header_flip_exec(bContext *C, wmOperator *UNUSED(op))
-{
- ARegion *ar = screen_find_region_type(C, RGN_TYPE_HEADER);
-
- if (ar == NULL) {
- return OPERATOR_CANCELLED;
- }
-
- /* copied from SCREEN_OT_region_flip */
- if (ar->alignment == RGN_ALIGN_TOP)
- ar->alignment = RGN_ALIGN_BOTTOM;
- else if (ar->alignment == RGN_ALIGN_BOTTOM)
- ar->alignment = RGN_ALIGN_TOP;
- else if (ar->alignment == RGN_ALIGN_LEFT)
- ar->alignment = RGN_ALIGN_RIGHT;
- else if (ar->alignment == RGN_ALIGN_RIGHT)
- ar->alignment = RGN_ALIGN_LEFT;
+/** \} */
- ED_area_tag_redraw(CTX_wm_area(C));
-
- WM_event_add_notifier(C, NC_SCREEN | NA_EDITED, NULL);
-
- return OPERATOR_FINISHED;
-}
-
-
-static void SCREEN_OT_header_flip(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Flip Header Region";
- ot->idname = "SCREEN_OT_header_flip";
- ot->description = "Toggle the header over/below the main window area";
-
- /* api callbacks */
- ot->exec = header_flip_exec;
-
- ot->poll = ED_operator_areaactive;
- ot->flag = 0;
-}
-
-
-
-/* ************** show menus operator ***************************** */
+/* -------------------------------------------------------------------- */
+/** \name Header Toggle Menu Operator
+ * \{ */
/* show/hide header text menus */
static int header_toggle_menus_exec(bContext *C, wmOperator *UNUSED(op))
@@ -3302,19 +3417,22 @@ static void SCREEN_OT_header_toggle_menus(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Header Tools Operator
+ * \{ */
-/* ************** header tools operator ***************************** */
void ED_screens_header_tools_menu_create(bContext *C, uiLayout *layout, void *UNUSED(arg))
{
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
+ const char *but_flip_str = (ar->alignment == RGN_ALIGN_TOP) ? IFACE_("Flip to Bottom") : IFACE_("Flip to Top");
- /* XXX SCREEN_OT_region_flip doesn't work - gets wrong context for active region, so added custom operator. */
- if (ar->alignment == RGN_ALIGN_TOP)
- uiItemO(layout, IFACE_("Flip to Bottom"), ICON_NONE, "SCREEN_OT_header_flip");
- else
- uiItemO(layout, IFACE_("Flip to Top"), ICON_NONE, "SCREEN_OT_header_flip");
+ /* default is WM_OP_INVOKE_REGION_WIN, which we don't want here. */
+ uiLayoutSetOperatorContext(layout, WM_OP_INVOKE_DEFAULT);
+ uiItemO(layout, but_flip_str, ICON_NONE, "SCREEN_OT_region_flip");
uiItemO(layout, IFACE_("Collapse Menus"),
(sa->flag & HEADER_NO_PULLDOWN) ? ICON_CHECKBOX_HLT : ICON_CHECKBOX_DEHLT,
"SCREEN_OT_header_toggle_menus");
@@ -3356,7 +3474,13 @@ static void SCREEN_OT_header_toolbox(wmOperatorType *ot)
ot->invoke = header_toolbox_invoke;
}
-/* ****************** anim player, with timer ***************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Animation Step Operator
+ *
+ * Animation Step.
+ * \{ */
static int match_area_with_refresh(int spacetype, int refresh)
{
@@ -3649,7 +3773,13 @@ static void SCREEN_OT_animation_step(wmOperatorType *ot)
}
-/* ****************** anim player, starts or ends timer ***************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Animation Playback Operator
+ *
+ * Animation Playback with Timer.
+ * \{ */
/* find window that owns the animation timer */
bScreen *ED_screen_animation_playing(const wmWindowManager *wm)
@@ -3742,12 +3872,18 @@ static void SCREEN_OT_animation_play(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Animation Cancel Operator
+ * \{ */
+
static int screen_animation_cancel_exec(bContext *C, wmOperator *op)
{
bScreen *screen = ED_screen_animation_playing(CTX_wm_manager(C));
if (screen) {
- if (RNA_boolean_get(op->ptr, "restore_frame")) {
+ if (RNA_boolean_get(op->ptr, "restore_frame") && screen->animtimer) {
ScreenAnimData *sad = screen->animtimer->customdata;
Scene *scene = CTX_data_scene(C);
@@ -3781,7 +3917,11 @@ static void SCREEN_OT_animation_cancel(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "restore_frame", true, "Restore Frame", "Restore the frame when animation was initialized");
}
-/* ************** border select operator (template) ***************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Border Select Operator (Template)
+ * \{ */
/* operator state vars used: (added by default WM callbacks)
* xmin, ymin
@@ -3824,9 +3964,9 @@ static void SCREEN_OT_border_select(wmOperatorType *ot)
/* api callbacks */
ot->exec = border_select_exec;
- ot->invoke = WM_border_select_invoke;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->invoke = WM_gesture_border_invoke;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_areaactive;
@@ -3836,6 +3976,12 @@ static void SCREEN_OT_border_select(wmOperatorType *ot)
}
#endif
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Full Screen Back Operator
+ * \{ */
+
/* *********************** generic fullscreen 'back' button *************** */
@@ -3870,26 +4016,19 @@ static void SCREEN_OT_back_to_previous(struct wmOperatorType *ot)
ot->poll = ED_operator_screenactive;
}
-/* *********** show user pref window ****** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Show User Preferences Operator
+ * \{ */
static int userpref_show_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
- wmWindow *win = CTX_wm_window(C);
- rcti rect;
- int sizex, sizey;
-
- sizex = 800 * UI_DPI_WINDOW_FAC;
- sizey = 480 * UI_DPI_WINDOW_FAC;
-
- /* some magic to calculate postition */
- /* pixelsize: mouse coords are in U.pixelsize units :/ */
- rect.xmin = (event->x / U.pixelsize) + win->posx - sizex / 2;
- rect.ymin = (event->y / U.pixelsize) + win->posy - sizey / 2;
- rect.xmax = rect.xmin + sizex;
- rect.ymax = rect.ymin + sizey;
+ int sizex = 800 * UI_DPI_FAC;
+ int sizey = 480 * UI_DPI_FAC;
/* changes context! */
- if (WM_window_open_temp(C, &rect, WM_WINDOW_USERPREFS) != NULL) {
+ if (WM_window_open_temp(C, event->x, event->y, sizex, sizey, WM_WINDOW_USERPREFS) != NULL) {
return OPERATOR_FINISHED;
}
else {
@@ -3911,7 +4050,11 @@ static void SCREEN_OT_userpref_show(struct wmOperatorType *ot)
ot->poll = ED_operator_screenactive;
}
-/********************* new screen operator *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name New Screen Operator
+ * \{ */
static int screen_new_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -3936,7 +4079,11 @@ static void SCREEN_OT_new(wmOperatorType *ot)
ot->poll = WM_operator_winactive;
}
-/********************* delete screen operator *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Delete Screen Operator
+ * \{ */
static int screen_delete_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -3958,7 +4105,11 @@ static void SCREEN_OT_delete(wmOperatorType *ot)
ot->exec = screen_delete_exec;
}
-/********************* new scene operator *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name New Scene Operator
+ * \{ */
static int scene_new_exec(bContext *C, wmOperator *op)
{
@@ -3991,7 +4142,7 @@ static int scene_new_exec(bContext *C, wmOperator *op)
static void SCENE_OT_new(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{SCE_COPY_NEW, "NEW", 0, "New", "Add new scene"},
{SCE_COPY_EMPTY, "EMPTY", 0, "Copy Settings", "Make a copy without any objects"},
{SCE_COPY_LINK_OB, "LINK_OBJECTS", 0, "Link Objects", "Link to the objects from the current scene"},
@@ -4015,7 +4166,11 @@ static void SCENE_OT_new(wmOperatorType *ot)
ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "");
}
-/********************* delete scene operator *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Delete Screen Operator
+ * \{ */
static int scene_delete_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -4047,7 +4202,11 @@ static void SCENE_OT_delete(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/* ***************** region alpha blending ***************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Region Alpha Blending Operator
+ * \{ */
/* implementation note: a disappearing region needs at least 1 last draw with 100% backbuffer
* texture over it- then triple buffer will clear it entirely.
@@ -4189,7 +4348,11 @@ static void SCREEN_OT_region_blend(wmOperatorType *ot)
/* properties */
}
-/* ******************** space context cycling operator ******************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Space Context Cycle Operator
+ * \{ */
/* SCREEN_OT_space_context_cycle direction */
enum {
@@ -4197,7 +4360,7 @@ enum {
SPACE_CONTEXT_CYCLE_NEXT,
};
-static EnumPropertyItem space_context_cycle_direction[] = {
+static const EnumPropertyItem space_context_cycle_direction[] = {
{SPACE_CONTEXT_CYCLE_PREV, "PREV", 0, "Previous", ""},
{SPACE_CONTEXT_CYCLE_NEXT, "NEXT", 0, "Next", ""},
{0, NULL, 0, NULL, NULL}
@@ -4272,9 +4435,11 @@ static void SCREEN_OT_space_context_cycle(wmOperatorType *ot)
"Direction to cycle through");
}
+/** \} */
-/* **************** Assigning operatortypes to global list, adding handlers **************** */
-
+/* -------------------------------------------------------------------- */
+/** \name Assigning Operator Types
+ * \{ */
/* called in spacetypes.c */
void ED_operatortypes_screen(void)
@@ -4295,7 +4460,6 @@ void ED_operatortypes_screen(void)
WM_operatortype_append(SCREEN_OT_region_quadview);
WM_operatortype_append(SCREEN_OT_region_scale);
WM_operatortype_append(SCREEN_OT_region_flip);
- WM_operatortype_append(SCREEN_OT_header_flip);
WM_operatortype_append(SCREEN_OT_header);
WM_operatortype_append(SCREEN_OT_header_toggle_menus);
WM_operatortype_append(SCREEN_OT_header_toolbox);
@@ -4336,13 +4500,19 @@ void ED_operatortypes_screen(void)
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Operator Key Map
+ * \{ */
+
static void keymap_modal_set(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{KM_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{KM_MODAL_APPLY, "APPLY", 0, "Apply", ""},
- {KM_MODAL_STEP10, "STEP10", 0, "Steps on", ""},
- {KM_MODAL_STEP10_OFF, "STEP10_OFF", 0, "Steps off", ""},
+ {KM_MODAL_SNAP_ON, "SNAP", 0, "Snap on", ""},
+ {KM_MODAL_SNAP_OFF, "SNAP_OFF", 0, "Snap off", ""},
{0, NULL, 0, NULL, NULL}};
wmKeyMap *keymap;
@@ -4354,8 +4524,8 @@ static void keymap_modal_set(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, RETKEY, KM_PRESS, KM_ANY, 0, KM_MODAL_APPLY);
WM_modalkeymap_add_item(keymap, PADENTER, KM_PRESS, KM_ANY, 0, KM_MODAL_APPLY);
- WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, KM_MODAL_STEP10);
- WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, KM_MODAL_STEP10_OFF);
+ WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, KM_MODAL_SNAP_ON);
+ WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, KM_MODAL_SNAP_OFF);
WM_modalkeymap_assign(keymap, "SCREEN_OT_area_move");
@@ -4537,3 +4707,4 @@ void ED_keymap_screen(wmKeyConfig *keyconf)
keymap_modal_set(keyconf);
}
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/CMakeLists.txt b/source/blender/editors/sculpt_paint/CMakeLists.txt
index 46753df4e13..9527dc4fe83 100644
--- a/source/blender/editors/sculpt_paint/CMakeLists.txt
+++ b/source/blender/editors/sculpt_paint/CMakeLists.txt
@@ -42,16 +42,21 @@ set(INC_SYS
set(SRC
paint_cursor.c
paint_curve.c
+ paint_curve_undo.c
paint_hide.c
paint_image.c
paint_image_2d.c
paint_image_proj.c
+ paint_image_undo.c
paint_mask.c
paint_ops.c
paint_stroke.c
- paint_undo.c
paint_utils.c
paint_vertex.c
+ paint_vertex_color_ops.c
+ paint_vertex_color_utils.c
+ paint_vertex_weight_ops.c
+ paint_vertex_weight_utils.c
paint_vertex_proj.c
sculpt.c
sculpt_undo.c
diff --git a/source/blender/editors/sculpt_paint/paint_cursor.c b/source/blender/editors/sculpt_paint/paint_cursor.c
index 53c11e2a6a9..e6219b4fae1 100644
--- a/source/blender/editors/sculpt_paint/paint_cursor.c
+++ b/source/blender/editors/sculpt_paint/paint_cursor.c
@@ -42,6 +42,7 @@
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
#include "DNA_userdef_types.h"
+#include "DNA_view3d_types.h"
#include "BKE_brush.h"
#include "BKE_context.h"
@@ -150,7 +151,10 @@ typedef struct LoadTexData {
float radius;
} LoadTexData;
-static void load_tex_task_cb_ex(void *userdata, void *UNUSED(userdata_chunck), const int j, const int thread_id)
+static void load_tex_task_cb_ex(
+ void *__restrict userdata,
+ const int j,
+ const ParallelRangeTLS *__restrict tls)
{
LoadTexData *data = userdata;
Brush *br = data->br;
@@ -211,7 +215,7 @@ static void load_tex_task_cb_ex(void *userdata, void *UNUSED(userdata_chunck), c
if (col) {
float rgba[4];
- paint_get_tex_pixel_col(mtex, x, y, rgba, pool, thread_id, convert_to_linear, colorspace);
+ paint_get_tex_pixel_col(mtex, x, y, rgba, pool, tls->thread_id, convert_to_linear, colorspace);
buffer[index * 4] = rgba[0] * 255;
buffer[index * 4 + 1] = rgba[1] * 255;
@@ -219,7 +223,7 @@ static void load_tex_task_cb_ex(void *userdata, void *UNUSED(userdata_chunck), c
buffer[index * 4 + 3] = rgba[3] * 255;
}
else {
- float avg = paint_get_tex_pixel(mtex, x, y, pool, thread_id);
+ float avg = paint_get_tex_pixel(mtex, x, y, pool, tls->thread_id);
avg += br->texture_sample_bias;
@@ -248,12 +252,12 @@ static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool prima
TexSnapshot *target;
MTex *mtex = (primary) ? &br->mtex : &br->mask_mtex;
- OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
+ eOverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
GLubyte *buffer = NULL;
int size;
bool refresh;
- OverlayControlFlags invalid = (primary) ? (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
+ eOverlayControlFlags invalid = (primary) ? (overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_PRIMARY) :
(overlay_flags & PAINT_INVALID_OVERLAY_TEXTURE_SECONDARY);
target = (primary) ? &primary_snap : &secondary_snap;
@@ -317,7 +321,9 @@ static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool prima
.pool = pool, .size = size, .rotation = rotation, .radius = radius,
};
- BLI_task_parallel_range_ex(0, size, &data, NULL, 0, load_tex_task_cb_ex, true, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ BLI_task_parallel_range(0, size, &data, load_tex_task_cb_ex, &settings);
if (mtex->tex && mtex->tex->nodetree)
ntreeTexEndExecTree(mtex->tex->nodetree->execdata);
@@ -366,7 +372,10 @@ static int load_tex(Brush *br, ViewContext *vc, float zoom, bool col, bool prima
return 1;
}
-static void load_tex_cursor_task_cb(void *userdata, const int j)
+static void load_tex_cursor_task_cb(
+ void *__restrict userdata,
+ const int j,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
LoadTexData *data = userdata;
Brush *br = data->br;
@@ -398,7 +407,7 @@ static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
{
bool init;
- OverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
+ eOverlayControlFlags overlay_flags = BKE_paint_get_overlay_flags();
GLubyte *buffer = NULL;
int size;
@@ -446,7 +455,9 @@ static int load_tex_cursor(Brush *br, ViewContext *vc, float zoom)
.br = br, .buffer = buffer, .size = size,
};
- BLI_task_parallel_range(0, size, &data, load_tex_cursor_task_cb, true);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ BLI_task_parallel_range(0, size, &data, load_tex_cursor_task_cb, &settings);
if (!cursor_snap.overlay_texture)
glGenTextures(1, &cursor_snap.overlay_texture);
@@ -769,11 +780,11 @@ static void paint_draw_cursor_overlay(UnifiedPaintSettings *ups, Brush *brush,
}
static void paint_draw_alpha_overlay(UnifiedPaintSettings *ups, Brush *brush,
- ViewContext *vc, int x, int y, float zoom, PaintMode mode)
+ ViewContext *vc, int x, int y, float zoom, ePaintMode mode)
{
/* color means that primary brush texture is colured and secondary is used for alpha/mask control */
bool col = ELEM(mode, ePaintTextureProjective, ePaintTexture2D, ePaintVertex) ? true : false;
- OverlayControlFlags flags = BKE_paint_get_overlay_flags();
+ eOverlayControlFlags flags = BKE_paint_get_overlay_flags();
/* save lots of GL state
* TODO: check on whether all of these are needed? */
glPushAttrib(GL_COLOR_BUFFER_BIT |
@@ -970,7 +981,7 @@ static void paint_cursor_on_hit(UnifiedPaintSettings *ups, Brush *brush, ViewCon
}
}
-static bool ommit_cursor_drawing(Paint *paint, PaintMode mode, Brush *brush)
+static bool ommit_cursor_drawing(Paint *paint, ePaintMode mode, Brush *brush)
{
if (paint->flags & PAINT_SHOW_BRUSH) {
if (ELEM(mode, ePaintTexture2D, ePaintTextureProjective) && brush->imagepaint_tool == PAINT_TOOL_FILL) {
@@ -987,7 +998,7 @@ static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings;
Paint *paint = BKE_paint_get_active_from_context(C);
Brush *brush = BKE_paint_brush(paint);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
ViewContext vc;
float final_radius;
float translation[2];
@@ -1000,10 +1011,11 @@ static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
/* can't use stroke vc here because this will be called during
* mouse over too, not just during a stroke */
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
- get_imapaint_zoom(C, &zoomx, &zoomy);
- zoomx = max_ff(zoomx, zoomy);
+ if (vc.rv3d && (vc.rv3d->rflag & RV3D_NAVIGATING)) {
+ return;
+ }
/* skip everything and draw brush here */
if (brush->flag & BRUSH_CURVE) {
@@ -1011,6 +1023,9 @@ static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
return;
}
+ get_imapaint_zoom(C, &zoomx, &zoomy);
+ zoomx = max_ff(zoomx, zoomy);
+
/* set various defaults */
translation[0] = x;
translation[1] = y;
@@ -1043,11 +1058,8 @@ static void paint_draw_cursor(bContext *C, int x, int y, void *UNUSED(unused))
/* check if brush is subtracting, use different color then */
/* TODO: no way currently to know state of pen flip or
* invert key modifier without starting a stroke */
- if (((ups->draw_inverted == 0) ^
- ((brush->flag & BRUSH_DIR_IN) == 0)) &&
- ELEM(brush->sculpt_tool, SCULPT_TOOL_DRAW,
- SCULPT_TOOL_INFLATE, SCULPT_TOOL_CLAY,
- SCULPT_TOOL_PINCH, SCULPT_TOOL_CREASE))
+ if (((ups->draw_inverted == 0) ^ ((brush->flag & BRUSH_DIR_IN) == 0)) &&
+ BKE_brush_sculpt_has_secondary_color(brush))
{
outline_col = brush->sub_col;
}
diff --git a/source/blender/editors/sculpt_paint/paint_curve.c b/source/blender/editors/sculpt_paint/paint_curve.c
index 9704db9d035..120514762f4 100644
--- a/source/blender/editors/sculpt_paint/paint_curve.c
+++ b/source/blender/editors/sculpt_paint/paint_curve.c
@@ -33,15 +33,14 @@
#include "DNA_space_types.h"
#include "DNA_view3d_types.h"
+#include "BLI_math_vector.h"
+
#include "BKE_context.h"
#include "BKE_main.h"
#include "BKE_paint.h"
-#include "BLI_math_vector.h"
-#include "BLI_string.h"
-
-#include "ED_paint.h"
#include "ED_view3d.h"
+#include "ED_paint.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -56,7 +55,6 @@
#define PAINT_CURVE_SELECT_THRESHOLD 40.0f
#define PAINT_CURVE_POINT_SELECT(pcp, i) (*(&pcp->bez.f1 + i) = SELECT)
-
int paint_curve_poll(bContext *C)
{
Object *ob = CTX_data_active_object(C);
@@ -81,91 +79,6 @@ int paint_curve_poll(bContext *C)
return false;
}
-/* Paint Curve Undo*/
-
-typedef struct UndoCurve {
- struct UndoImageTile *next, *prev;
-
- PaintCurvePoint *points; /* points of curve */
- int tot_points;
- int active_point;
-
- char idname[MAX_ID_NAME]; /* name instead of pointer*/
-} UndoCurve;
-
-static void paintcurve_undo_restore(bContext *C, ListBase *lb)
-{
- Paint *p = BKE_paint_get_active_from_context(C);
- UndoCurve *uc;
- PaintCurve *pc = NULL;
-
- if (p->brush) {
- pc = p->brush->paint_curve;
- }
-
- if (!pc)
- return;
-
- uc = (UndoCurve *)lb->first;
-
- if (STREQLEN(uc->idname, pc->id.name, BLI_strnlen(uc->idname, sizeof(uc->idname)))) {
- SWAP(PaintCurvePoint *, pc->points, uc->points);
- SWAP(int, pc->tot_points, uc->tot_points);
- SWAP(int, pc->add_index, uc->active_point);
- }
-}
-
-static void paintcurve_undo_delete(ListBase *lb)
-{
- UndoCurve *uc;
- uc = (UndoCurve *)lb->first;
-
- if (uc->points)
- MEM_freeN(uc->points);
- uc->points = NULL;
-}
-
-
-static void paintcurve_undo_begin(bContext *C, wmOperator *op, PaintCurve *pc)
-{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
- ListBase *lb = NULL;
- int undo_stack_id;
- UndoCurve *uc;
-
- switch (mode) {
- case ePaintTexture2D:
- case ePaintTextureProjective:
- undo_stack_id = UNDO_PAINT_IMAGE;
- break;
-
- case ePaintSculpt:
- undo_stack_id = UNDO_PAINT_MESH;
- break;
-
- default:
- /* do nothing, undo is handled by global */
- return;
- }
-
-
- ED_undo_paint_push_begin(undo_stack_id, op->type->name,
- paintcurve_undo_restore, paintcurve_undo_delete, NULL);
- lb = undo_paint_push_get_list(undo_stack_id);
-
- uc = MEM_callocN(sizeof(*uc), "Undo_curve");
-
- lb->first = uc;
-
- BLI_strncpy(uc->idname, pc->id.name, sizeof(uc->idname));
- uc->tot_points = pc->tot_points;
- uc->active_point = pc->add_index;
- uc->points = MEM_dupallocN(pc->points);
-
- undo_paint_push_count_alloc(undo_stack_id, sizeof(*uc) + sizeof(*pc->points) * pc->tot_points);
-
- ED_undo_paint_push_end(undo_stack_id);
-}
#define SEL_F1 (1 << 0)
#define SEL_F2 (1 << 1)
#define SEL_F3 (1 << 2)
@@ -291,7 +204,7 @@ static void paintcurve_point_add(bContext *C, wmOperator *op, const int loc[2])
br->paint_curve = pc = BKE_paint_curve_add(bmain, "PaintCurve");
}
- paintcurve_undo_begin(C, op, pc);
+ ED_paintcurve_undo_push_begin(op->type->name);
pcp = MEM_mallocN((pc->tot_points + 1) * sizeof(PaintCurvePoint), "PaintCurvePoint");
add_index = pc->add_index;
@@ -329,6 +242,8 @@ static void paintcurve_point_add(bContext *C, wmOperator *op, const int loc[2])
pcp[add_index].bez.h1 = HD_ALIGN;
}
+ ED_paintcurve_undo_push_end();
+
WM_paint_cursor_tag_redraw(window, ar);
}
@@ -390,7 +305,7 @@ static int paintcurve_delete_point_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- paintcurve_undo_begin(C, op, pc);
+ ED_paintcurve_undo_push_begin(op->type->name);
#define DELETE_TAG 2
@@ -430,6 +345,8 @@ static int paintcurve_delete_point_exec(bContext *C, wmOperator *op)
#undef DELETE_TAG
+ ED_paintcurve_undo_push_end();
+
WM_paint_cursor_tag_redraw(window, ar);
return OPERATOR_FINISHED;
@@ -467,7 +384,7 @@ static bool paintcurve_point_select(bContext *C, wmOperator *op, const int loc[2
if (!pc)
return false;
- paintcurve_undo_begin(C, op, pc);
+ ED_paintcurve_undo_push_begin(op->type->name);
if (toggle) {
PaintCurvePoint *pcp;
@@ -532,10 +449,14 @@ static bool paintcurve_point_select(bContext *C, wmOperator *op, const int loc[2
}
}
- if (!pcp)
+ if (!pcp) {
+ ED_paintcurve_undo_push_end();
return false;
+ }
}
+ ED_paintcurve_undo_push_end();
+
WM_paint_cursor_tag_redraw(window, ar);
return true;
@@ -650,9 +571,6 @@ static int paintcurve_slide_invoke(bContext *C, wmOperator *op, const wmEvent *e
psd->align = align;
op->customdata = psd;
- if (do_select)
- paintcurve_undo_begin(C, op, pc);
-
/* first, clear all selection from points */
for (i = 0; i < pc->tot_points; i++)
pc->points[i].bez.f1 = pc->points[i].bez.f3 = pc->points[i].bez.f2 = 0;
@@ -675,6 +593,8 @@ static int paintcurve_slide_modal(bContext *C, wmOperator *op, const wmEvent *ev
if (event->type == psd->event && event->val == KM_RELEASE) {
MEM_freeN(psd);
+ ED_paintcurve_undo_push_begin(op->type->name);
+ ED_paintcurve_undo_push_end();
return OPERATOR_FINISHED;
}
@@ -733,7 +653,7 @@ void PAINTCURVE_OT_slide(wmOperatorType *ot)
static int paintcurve_draw_exec(bContext *C, wmOperator *UNUSED(op))
{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
const char *name;
switch (mode) {
@@ -774,7 +694,7 @@ void PAINTCURVE_OT_draw(wmOperatorType *ot)
static int paintcurve_cursor_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *event)
{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
switch (mode) {
case ePaintTexture2D:
diff --git a/source/blender/editors/sculpt_paint/paint_curve_undo.c b/source/blender/editors/sculpt_paint/paint_curve_undo.c
new file mode 100644
index 00000000000..77f06180df6
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_curve_undo.c
@@ -0,0 +1,168 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_curve_undo.c
+ * \ingroup edsculpt
+ */
+
+#include <string.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_brush_types.h"
+#include "DNA_space_types.h"
+
+#include "BLI_string.h"
+#include "BLI_array_utils.h"
+
+#include "BKE_context.h"
+#include "BKE_paint.h"
+#include "BKE_undo_system.h"
+
+#include "ED_paint.h"
+#include "ED_undo.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "paint_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct UndoCurve {
+ PaintCurvePoint *points; /* points of curve */
+ int tot_points;
+ int add_index;
+} UndoCurve;
+
+static void undocurve_from_paintcurve(UndoCurve *uc, const PaintCurve *pc)
+{
+ BLI_assert(BLI_array_is_zeroed(uc, 1));
+ uc->points = MEM_dupallocN(pc->points);
+ uc->tot_points = pc->tot_points;
+ uc->add_index = pc->add_index;
+}
+
+static void undocurve_to_paintcurve(const UndoCurve *uc, PaintCurve *pc)
+{
+ MEM_SAFE_FREE(pc->points);
+ pc->points = MEM_dupallocN(uc->points);
+ pc->tot_points = uc->tot_points;
+ pc->add_index = uc->add_index;
+}
+
+static void undocurve_free_data(UndoCurve *uc)
+{
+ MEM_SAFE_FREE(uc->points);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct PaintCurveUndoStep {
+ UndoStep step;
+ PaintCurve *pc;
+ UndoCurve data;
+} PaintCurveUndoStep;
+
+static bool paintcurve_undosys_poll(bContext *C)
+{
+ Paint *p = BKE_paint_get_active_from_context(C);
+ return (p->brush && p->brush->paint_curve);
+}
+
+static void paintcurve_undosys_step_encode_init(struct bContext *C, UndoStep *us_p)
+{
+ /* XXX, use to set the undo type only. */
+ UNUSED_VARS(C, us_p);
+}
+
+static bool paintcurve_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ Paint *p = BKE_paint_get_active_from_context(C);
+ PaintCurve *pc = p ? (p->brush ? p->brush->paint_curve : NULL) : NULL;
+ if (pc == NULL) {
+ return false;
+ }
+
+ PaintCurveUndoStep *us = (PaintCurveUndoStep *)us_p;
+ BLI_assert(us->step.data_size == 0);
+
+ us->pc = pc;
+ undocurve_from_paintcurve(&us->data, pc);
+
+ return true;
+}
+
+static void paintcurve_undosys_step_decode(struct bContext *UNUSED(C), UndoStep *us_p, int UNUSED(dir))
+{
+ PaintCurveUndoStep *us = (PaintCurveUndoStep *)us_p;
+ undocurve_to_paintcurve(&us->data, us->pc);
+}
+
+static void paintcurve_undosys_step_free(UndoStep *us_p)
+{
+ PaintCurveUndoStep *us = (PaintCurveUndoStep *)us_p;
+ undocurve_free_data(&us->data);
+}
+
+/* Export for ED_undo_sys. */
+void ED_paintcurve_undosys_type(UndoType *ut)
+{
+ ut->name = "Paint Curve";
+ /* don't poll for now */
+ ut->poll = paintcurve_undosys_poll;
+ ut->step_encode_init = paintcurve_undosys_step_encode_init;
+ ut->step_encode = paintcurve_undosys_step_encode;
+ ut->step_decode = paintcurve_undosys_step_decode;
+ ut->step_free = paintcurve_undosys_step_free;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = false;
+
+ ut->step_size = sizeof(PaintCurveUndoStep);
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+void ED_paintcurve_undo_push_begin(const char *name)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ bContext *C = NULL; /* special case, we never read from this. */
+ BKE_undosys_step_push_init_with_type(ustack, C, name, BKE_UNDOSYS_TYPE_PAINTCURVE);
+}
+
+void ED_paintcurve_undo_push_end(void)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ BKE_undosys_step_push(ustack, NULL, NULL);
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/paint_hide.c b/source/blender/editors/sculpt_paint/paint_hide.c
index 5af6792f10f..e2b318710a8 100644
--- a/source/blender/editors/sculpt_paint/paint_hide.c
+++ b/source/blender/editors/sculpt_paint/paint_hide.c
@@ -326,7 +326,7 @@ static void clip_planes_from_rect(bContext *C,
bglMats mats = {{0}};
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
view3d_get_transformation(vc.ar, vc.rv3d, vc.obact, &mats);
ED_view3d_clipping_calc(&bb, clip_planes, &mats, rect);
negate_m4(clip_planes);
@@ -417,7 +417,7 @@ static int hide_show_exec(bContext *C, wmOperator *op)
MEM_freeN(nodes);
/* end undo */
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
/* ensure that edges and faces get hidden as well (not used by
* sculpt but it looks wrong when entering editmode otherwise) */
@@ -435,20 +435,20 @@ static int hide_show_invoke(bContext *C, wmOperator *op, const wmEvent *event)
PartialVisArea area = RNA_enum_get(op->ptr, "area");
if (!ELEM(area, PARTIALVIS_ALL, PARTIALVIS_MASKED))
- return WM_border_select_invoke(C, op, event);
+ return WM_gesture_border_invoke(C, op, event);
else
return op->type->exec(C, op);
}
void PAINT_OT_hide_show(struct wmOperatorType *ot)
{
- static EnumPropertyItem action_items[] = {
+ static const EnumPropertyItem action_items[] = {
{PARTIALVIS_HIDE, "HIDE", 0, "Hide", "Hide vertices"},
{PARTIALVIS_SHOW, "SHOW", 0, "Show", "Show vertices"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem area_items[] = {
+ static const EnumPropertyItem area_items[] = {
{PARTIALVIS_OUTSIDE, "OUTSIDE", 0, "Outside", "Hide or show vertices outside the selection"},
{PARTIALVIS_INSIDE, "INSIDE", 0, "Inside", "Hide or show vertices inside the selection"},
{PARTIALVIS_ALL, "ALL", 0, "All", "Hide or show all vertices"},
@@ -463,7 +463,7 @@ void PAINT_OT_hide_show(struct wmOperatorType *ot)
/* api callbacks */
ot->invoke = hide_show_invoke;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->exec = hide_show_exec;
/* sculpt-only for now */
ot->poll = sculpt_mode_poll_view3d;
diff --git a/source/blender/editors/sculpt_paint/paint_image.c b/source/blender/editors/sculpt_paint/paint_image.c
index bf344e1f721..cb6dba4772f 100644
--- a/source/blender/editors/sculpt_paint/paint_image.c
+++ b/source/blender/editors/sculpt_paint/paint_image.c
@@ -39,7 +39,6 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
-#include "BLI_threads.h"
#include "BLT_translation.h"
@@ -50,16 +49,17 @@
#include "DNA_node_types.h"
#include "DNA_object_types.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_DerivedMesh.h"
#include "BKE_brush.h"
-#include "BKE_image.h"
#include "BKE_main.h"
#include "BKE_material.h"
#include "BKE_node.h"
#include "BKE_paint.h"
-#include "BKE_texture.h"
+#include "BKE_undo_system.h"
+
#include "UI_interface.h"
#include "UI_view2d.h"
@@ -86,43 +86,10 @@
#include "paint_intern.h"
-typedef struct UndoImageTile {
- struct UndoImageTile *next, *prev;
-
- char idname[MAX_ID_NAME]; /* name instead of pointer*/
- char ibufname[IMB_FILENAME_SIZE];
-
- union {
- float *fp;
- unsigned int *uint;
- void *pt;
- } rect;
-
- unsigned short *mask;
-
- int x, y;
-
- Image *ima;
- short source, use_float;
- char gen_type;
- bool valid;
-} UndoImageTile;
-
/* this is a static resource for non-globality,
* Maybe it should be exposed as part of the
* paint operation, but for now just give a public interface */
static ImagePaintPartialRedraw imapaintpartial = {0, 0, 0, 0, 0};
-static SpinLock undolock;
-
-void image_undo_init_locks(void)
-{
- BLI_spin_init(&undolock);
-}
-
-void image_undo_end_locks(void)
-{
- BLI_spin_end(&undolock);
-}
ImagePaintPartialRedraw *get_imapaintpartial(void)
{
@@ -134,296 +101,6 @@ void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr)
imapaintpartial = *ippr;
}
-/* UNDO */
-typedef enum {
- COPY = 0,
- RESTORE = 1,
- RESTORE_COPY = 2
-} CopyMode;
-
-static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, CopyMode mode)
-{
- if (mode == COPY) {
- /* copy or swap contents of tile->rect and region in ibuf->rect */
- IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
- tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
-
- if (ibuf->rect_float) {
- SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
- }
- else {
- SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
- }
- }
- else {
- if (mode == RESTORE_COPY) {
- IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
- tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
- }
- /* swap to the tmpbuf for easy copying */
- if (ibuf->rect_float) {
- SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
- }
- else {
- SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
- }
-
- IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
- tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
-
- if (mode == RESTORE) {
- if (ibuf->rect_float) {
- SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
- }
- else {
- SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
- }
- }
- }
-}
-
-void *image_undo_find_tile(Image *ima, ImBuf *ibuf, int x_tile, int y_tile, unsigned short **mask, bool validate)
-{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
- UndoImageTile *tile;
- short use_float = ibuf->rect_float ? 1 : 0;
-
- for (tile = lb->first; tile; tile = tile->next) {
- if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source) {
- if (tile->use_float == use_float) {
- if (STREQ(tile->idname, ima->id.name) && STREQ(tile->ibufname, ibuf->name)) {
- if (mask) {
- /* allocate mask if requested */
- if (!tile->mask) {
- tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
- "UndoImageTile.mask");
- }
-
- *mask = tile->mask;
- }
- if (validate)
- tile->valid = true;
-
- return tile->rect.pt;
- }
- }
- }
- }
-
- return NULL;
-}
-
-void *image_undo_push_tile(Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile, unsigned short **mask, bool **valid, bool proj, bool find_prev)
-{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
- UndoImageTile *tile;
- int allocsize;
- short use_float = ibuf->rect_float ? 1 : 0;
- void *data;
-
- /* check if tile is already pushed */
-
- /* in projective painting we keep accounting of tiles, so if we need one pushed, just push! */
- if (find_prev) {
- data = image_undo_find_tile(ima, ibuf, x_tile, y_tile, mask, true);
- if (data)
- return data;
- }
-
- if (*tmpibuf == NULL)
- *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
-
- tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
- BLI_strncpy(tile->idname, ima->id.name, sizeof(tile->idname));
- tile->x = x_tile;
- tile->y = y_tile;
-
- /* add mask explicitly here */
- if (mask)
- *mask = tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
- "UndoImageTile.mask");
-
- allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
- allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
- tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
-
- BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
-
- tile->gen_type = ima->gen_type;
- tile->source = ima->source;
- tile->use_float = use_float;
- tile->valid = true;
- tile->ima = ima;
-
- if (valid)
- *valid = &tile->valid;
-
- undo_copy_tile(tile, *tmpibuf, ibuf, COPY);
-
- if (proj)
- BLI_spin_lock(&undolock);
-
- undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, allocsize);
- BLI_addtail(lb, tile);
-
- if (proj)
- BLI_spin_unlock(&undolock);
-
- return tile->rect.pt;
-}
-
-void image_undo_remove_masks(void)
-{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
- UndoImageTile *tile;
-
- for (tile = lb->first; tile; tile = tile->next) {
- if (tile->mask) {
- MEM_freeN(tile->mask);
- tile->mask = NULL;
- }
- }
-}
-
-static void image_undo_restore_runtime(ListBase *lb)
-{
- ImBuf *ibuf, *tmpibuf;
- UndoImageTile *tile;
-
- tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
- IB_rectfloat | IB_rect);
-
- for (tile = lb->first; tile; tile = tile->next) {
- Image *ima = tile->ima;
- ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
-
- undo_copy_tile(tile, tmpibuf, ibuf, RESTORE);
-
- GPU_free_image(ima); /* force OpenGL reload (maybe partial update will operate better?) */
- if (ibuf->rect_float)
- ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
- if (ibuf->mipmap[0])
- ibuf->userflags |= IB_MIPMAP_INVALID; /* force mipmap recreatiom */
- ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
-
- BKE_image_release_ibuf(ima, ibuf, NULL);
- }
-
- IMB_freeImBuf(tmpibuf);
-}
-
-void ED_image_undo_restore(bContext *C, ListBase *lb)
-{
- Main *bmain = CTX_data_main(C);
- Image *ima = NULL;
- ImBuf *ibuf, *tmpibuf;
- UndoImageTile *tile;
-
- tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
- IB_rectfloat | IB_rect);
-
- for (tile = lb->first; tile; tile = tile->next) {
- short use_float;
-
- /* find image based on name, pointer becomes invalid with global undo */
- if (ima && STREQ(tile->idname, ima->id.name)) {
- /* ima is valid */
- }
- else {
- ima = BLI_findstring(&bmain->image, tile->idname, offsetof(ID, name));
- }
-
- ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
-
- if (ima && ibuf && !STREQ(tile->ibufname, ibuf->name)) {
- /* current ImBuf filename was changed, probably current frame
- * was changed when painting on image sequence, rather than storing
- * full image user (which isn't so obvious, btw) try to find ImBuf with
- * matched file name in list of already loaded images */
-
- BKE_image_release_ibuf(ima, ibuf, NULL);
-
- ibuf = BKE_image_get_ibuf_with_name(ima, tile->ibufname);
- }
-
- if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
- BKE_image_release_ibuf(ima, ibuf, NULL);
- continue;
- }
-
- if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
- BKE_image_release_ibuf(ima, ibuf, NULL);
- continue;
- }
-
- use_float = ibuf->rect_float ? 1 : 0;
-
- if (use_float != tile->use_float) {
- BKE_image_release_ibuf(ima, ibuf, NULL);
- continue;
- }
-
- undo_copy_tile(tile, tmpibuf, ibuf, RESTORE_COPY);
-
- GPU_free_image(ima); /* force OpenGL reload */
- if (ibuf->rect_float)
- ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
- if (ibuf->mipmap[0])
- ibuf->userflags |= IB_MIPMAP_INVALID; /* force mipmap recreatiom */
- ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
-
- DAG_id_tag_update(&ima->id, 0);
-
- BKE_image_release_ibuf(ima, ibuf, NULL);
- }
-
- IMB_freeImBuf(tmpibuf);
-}
-
-void ED_image_undo_free(ListBase *lb)
-{
- UndoImageTile *tile;
-
- for (tile = lb->first; tile; tile = tile->next)
- MEM_freeN(tile->rect.pt);
-}
-
-static void image_undo_end(void)
-{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
- UndoImageTile *tile;
- int deallocsize = 0;
- int allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
-
- /* first dispose of invalid tiles (may happen due to drag dot for instance) */
- for (tile = lb->first; tile;) {
- if (!tile->valid) {
- UndoImageTile *tmp_tile = tile->next;
- deallocsize += allocsize * ((tile->use_float) ? sizeof(float) : sizeof(char));
- MEM_freeN(tile->rect.pt);
- BLI_freelinkN(lb, tile);
- tile = tmp_tile;
- }
- else {
- tile = tile->next;
- }
- }
-
- /* don't forget to remove the size of deallocated tiles */
- undo_paint_push_count_alloc(UNDO_PAINT_IMAGE, -deallocsize);
-
- ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
-}
-
-static void image_undo_invalidate(void)
-{
- UndoImageTile *tile;
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
-
- for (tile = lb->first; tile; tile = tile->next)
- tile->valid = false;
-}
-
/* Imagepaint Partial Redraw & Dirty Region */
void ED_imapaint_clear_partial_redraw(void)
@@ -453,7 +130,7 @@ void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int
if (w == 0 || h == 0)
return;
-
+
if (!imapaintpartial.enabled) {
imapaintpartial.x1 = x;
imapaintpartial.y1 = y;
@@ -470,12 +147,14 @@ void ED_imapaint_dirty_region(Image *ima, ImBuf *ibuf, int x, int y, int w, int
imapaint_region_tiles(ibuf, x, y, w, h, &tilex, &tiley, &tilew, &tileh);
+ ListBase *undo_tiles = ED_image_undo_get_tiles();
+
for (ty = tiley; ty <= tileh; ty++)
for (tx = tilex; tx <= tilew; tx++)
- image_undo_push_tile(ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
+ image_undo_push_tile(undo_tiles, ima, ibuf, &tmpibuf, tx, ty, NULL, NULL, false, find_old);
ibuf->userflags |= IB_BITMAPDIRTY;
-
+
if (tmpibuf)
IMB_freeImBuf(tmpibuf);
}
@@ -510,7 +189,7 @@ BlurKernel *paint_new_blur_kernel(Brush *br, bool proj)
BlurKernel *kernel = MEM_mallocN(sizeof(BlurKernel), "blur kernel");
float radius;
int side;
- BlurKernelType type = br->blur_mode;
+ eBlurKernelType type = br->blur_mode;
if (proj) {
radius = 0.5f;
@@ -624,13 +303,13 @@ static int image_paint_2d_clone_poll(bContext *C)
}
/************************ paint operator ************************/
-typedef enum TexPaintMode {
+typedef enum eTexPaintMode {
PAINT_MODE_2D,
PAINT_MODE_3D_PROJECT
-} TexPaintMode;
+} eTexPaintMode;
typedef struct PaintOperation {
- TexPaintMode mode;
+ eTexPaintMode mode;
void *custom_paint;
@@ -655,8 +334,9 @@ bool paint_use_opacity_masking(Brush *brush)
false : true;
}
-void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
- float pressure, float color[3], struct ColorManagedDisplay *display)
+void paint_brush_color_get(
+ struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance,
+ float pressure, float color[3], struct ColorManagedDisplay *display)
{
if (invert)
copy_v3_v3(color, BKE_brush_secondary_color_get(scene, br));
@@ -665,17 +345,17 @@ void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_cor
float color_gr[4];
switch (br->gradient_stroke_mode) {
case BRUSH_GRADIENT_PRESSURE:
- do_colorband(br->gradient, pressure, color_gr);
+ BKE_colorband_evaluate(br->gradient, pressure, color_gr);
break;
case BRUSH_GRADIENT_SPACING_REPEAT:
{
float coord = fmod(distance / br->gradient_spacing, 1.0);
- do_colorband(br->gradient, coord, color_gr);
+ BKE_colorband_evaluate(br->gradient, coord, color_gr);
break;
}
case BRUSH_GRADIENT_SPACING_CLAMP:
{
- do_colorband(br->gradient, distance / br->gradient_spacing, color_gr);
+ BKE_colorband_evaluate(br->gradient, distance / br->gradient_spacing, color_gr);
break;
}
}
@@ -741,7 +421,7 @@ static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const flo
PaintOperation *pop = MEM_callocN(sizeof(PaintOperation), "PaintOperation"); /* caller frees */
Brush *brush = BKE_paint_brush(&settings->imapaint.paint);
int mode = RNA_enum_get(op->ptr, "mode");
- view3d_set_viewcontext(C, &pop->vc);
+ ED_view3d_viewcontext_init(C, &pop->vc);
copy_v2_v2(pop->prevmouse, mouse);
copy_v2_v2(pop->startmouse, mouse);
@@ -774,20 +454,11 @@ static PaintOperation *texture_paint_init(bContext *C, wmOperator *op, const flo
}
settings->imapaint.flag |= IMAGEPAINT_DRAWING;
- ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
- ED_image_undo_restore, ED_image_undo_free, NULL);
+ ED_image_undo_push_begin(op->type->name);
return pop;
}
-/* restore painting image to previous state. Used for anchored and drag-dot style brushes*/
-static void paint_stroke_restore(void)
-{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_IMAGE);
- image_undo_restore_runtime(lb);
- image_undo_invalidate();
-}
-
static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
{
PaintOperation *pop = paint_stroke_mode_data(stroke);
@@ -824,7 +495,8 @@ static void paint_stroke_update_step(bContext *C, struct PaintStroke *stroke, Po
BKE_brush_alpha_set(scene, brush, max_ff(0.0f, startalpha * alphafac));
if ((brush->flag & BRUSH_DRAG_DOT) || (brush->flag & BRUSH_ANCHORED)) {
- paint_stroke_restore();
+ UndoStack *ustack = CTX_wm_manager(C)->undo_stack;
+ ED_image_undo_restore(ustack->step_init);
}
if (pop->mode == PAINT_MODE_3D_PROJECT) {
@@ -901,7 +573,7 @@ static void paint_stroke_done(const bContext *C, struct PaintStroke *stroke)
WM_paint_cursor_end(CTX_wm_manager(C), pop->cursor);
}
- image_undo_end();
+ ED_image_undo_push_end();
/* duplicate warning, see texpaint_init */
#if 0
@@ -1186,7 +858,7 @@ static int sample_color_exec(bContext *C, wmOperator *op)
{
Paint *paint = BKE_paint_get_active_from_context(C);
Brush *brush = BKE_paint_brush(paint);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
ARegion *ar = CTX_wm_region(C);
wmWindow *win = CTX_wm_window(C);
const bool show_cursor = ((paint->flags & PAINT_SHOW_BRUSH) != 0);
@@ -1238,7 +910,7 @@ static int sample_color_invoke(bContext *C, wmOperator *op, const wmEvent *event
RNA_int_set_array(op->ptr, "location", event->mval);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
paint_sample_color(C, ar, event->mval[0], event->mval[1], use_sample_texture, false);
@@ -1274,7 +946,7 @@ static int sample_color_modal(bContext *C, wmOperator *op, const wmEvent *event)
return OPERATOR_FINISHED;
}
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
const bool use_sample_texture = (mode == ePaintTextureProjective) && !RNA_boolean_get(op->ptr, "merged");
switch (event->type) {
@@ -1342,7 +1014,7 @@ static int texture_paint_toggle_poll(bContext *C)
Object *ob = CTX_data_active_object(C);
if (ob == NULL || ob->type != OB_MESH)
return 0;
- if (!ob->data || ID_IS_LINKED_DATABLOCK(ob->data))
+ if (!ob->data || ID_IS_LINKED(ob->data))
return 0;
if (CTX_data_edit_object(C))
return 0;
@@ -1448,7 +1120,20 @@ void PAINT_OT_texture_paint_toggle(wmOperatorType *ot)
static int brush_colors_flip_exec(bContext *C, wmOperator *UNUSED(op))
{
UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
- Brush *br = image_paint_brush(C);
+
+ Brush *br;
+ Object *ob = CTX_data_active_object(C);
+ if (!(ob && (ob->mode & OB_MODE_VERTEX_PAINT))) {
+ br = image_paint_brush(C);
+ }
+ else {
+ /* At the moment, wpaint does not support the color flipper.
+ * So for now we're only handling vpaint */
+ ToolSettings *ts = CTX_data_tool_settings(C);
+ VPaint *vp = ts->vpaint;
+ br = BKE_paint_brush(&vp->paint);
+ }
+
if (ups->flag & UNIFIED_PAINT_COLOR) {
swap_v3_v3(ups->rgb, ups->secondary_rgb);
}
@@ -1467,7 +1152,12 @@ static int brush_colors_flip_poll(bContext *C)
if (br->imagepaint_tool == PAINT_TOOL_DRAW)
return 1;
}
-
+ else {
+ Object *ob = CTX_data_active_object(C);
+ if (ob && (ob->mode & OB_MODE_VERTEX_PAINT)) {
+ return 1;
+ }
+ }
return 0;
}
@@ -1489,15 +1179,17 @@ void PAINT_OT_brush_colors_flip(wmOperatorType *ot)
void ED_imapaint_bucket_fill(struct bContext *C, float color[3], wmOperator *op)
{
+ wmWindowManager *wm = CTX_wm_manager(C);
SpaceImage *sima = CTX_wm_space_image(C);
Image *ima = sima->image;
- ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
- ED_image_undo_restore, ED_image_undo_free, NULL);
+ BKE_undosys_step_push_init_with_type(wm->undo_stack, C, op->type->name, BKE_UNDOSYS_TYPE_IMAGE);
+
+ ED_image_undo_push_begin(op->type->name);
paint_2d_bucket_fill(C, color, NULL, NULL, NULL);
- ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
+ BKE_undosys_step_push(wm->undo_stack, C, op->type->name);
DAG_id_tag_update(&ima->id, 0);
}
diff --git a/source/blender/editors/sculpt_paint/paint_image_2d.c b/source/blender/editors/sculpt_paint/paint_image_2d.c
index 4f93c12385d..c1dd31ea055 100644
--- a/source/blender/editors/sculpt_paint/paint_image_2d.c
+++ b/source/blender/editors/sculpt_paint/paint_image_2d.c
@@ -44,13 +44,13 @@
#include "BLI_bitmap.h"
#include "BLI_task.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_brush.h"
#include "BKE_image.h"
#include "BKE_paint.h"
#include "BKE_report.h"
-#include "BKE_texture.h"
#include "ED_paint.h"
#include "ED_screen.h"
@@ -797,6 +797,7 @@ static void paint_2d_ibuf_rgb_set(ImBuf *ibuf, int x, int y, const bool is_torus
float map_alpha = (rgb[3] == 0.0f) ? rrgbf[3] : rrgbf[3] / rgb[3];
mul_v3_v3fl(rrgbf, rgb, map_alpha);
+ rrgbf[3] = rgb[3];
}
else {
unsigned char straight[4];
@@ -806,6 +807,7 @@ static void paint_2d_ibuf_rgb_set(ImBuf *ibuf, int x, int y, const bool is_torus
rrgb[0] = straight[0];
rrgb[1] = straight[1];
rrgb[2] = straight[2];
+ rrgb[3] = straight[3];
}
}
@@ -995,7 +997,7 @@ static void paint_2d_lift_smear(ImBuf *ibuf, ImBuf *ibufb, int *pos, short tile)
IMB_rectblend(ibufb, ibufb, ibuf, NULL, NULL, NULL, 0, region[a].destx, region[a].desty,
region[a].destx, region[a].desty,
region[a].srcx, region[a].srcy,
- region[a].width, region[a].height, IMB_BLEND_COPY_RGB, false);
+ region[a].width, region[a].height, IMB_BLEND_COPY, false);
}
static ImBuf *paint_2d_lift_clone(ImBuf *ibuf, ImBuf *ibufb, int *pos)
@@ -1033,6 +1035,8 @@ static void paint_2d_do_making_brush(ImagePaintState *s,
ImBuf tmpbuf;
IMB_initImBuf(&tmpbuf, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, 0);
+ ListBase *undo_tiles = ED_image_undo_get_tiles();
+
for (int ty = tiley; ty <= tileh; ty++) {
for (int tx = tilex; tx <= tilew; tx++) {
/* retrieve original pixels + mask from undo buffer */
@@ -1041,9 +1045,9 @@ static void paint_2d_do_making_brush(ImagePaintState *s,
int origy = region->desty - ty * IMAPAINT_TILE_SIZE;
if (s->canvas->rect_float)
- tmpbuf.rect_float = image_undo_find_tile(s->image, s->canvas, tx, ty, &mask, false);
+ tmpbuf.rect_float = image_undo_find_tile(undo_tiles, s->image, s->canvas, tx, ty, &mask, false);
else
- tmpbuf.rect = image_undo_find_tile(s->image, s->canvas, tx, ty, &mask, false);
+ tmpbuf.rect = image_undo_find_tile(undo_tiles, s->image, s->canvas, tx, ty, &mask, false);
IMB_rectblend(s->canvas, &tmpbuf, frombuf, mask,
curveb, texmaskb, mask_max,
@@ -1068,7 +1072,10 @@ typedef struct Paint2DForeachData {
int tilew;
} Paint2DForeachData;
-static void paint_2d_op_foreach_do(void *data_v, const int iter)
+static void paint_2d_op_foreach_do(
+ void *__restrict data_v,
+ const int iter,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
Paint2DForeachData *data = (Paint2DForeachData *)data_v;
paint_2d_do_making_brush(data->s, data->region, data->curveb,
@@ -1096,6 +1103,7 @@ static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsign
/* lift from canvas */
if (s->tool == PAINT_TOOL_SOFTEN) {
paint_2d_lift_soften(s, s->canvas, ibufb, bpos, tile);
+ blend = IMB_BLEND_INTERPOLATE;
}
else if (s->tool == PAINT_TOOL_SMEAR) {
if (lastpos[0] == pos[0] && lastpos[1] == pos[1])
@@ -1103,6 +1111,7 @@ static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsign
paint_2d_convert_brushco(ibufb, lastpos, blastpos);
paint_2d_lift_smear(s->canvas, ibufb, blastpos, tile);
+ blend = IMB_BLEND_INTERPOLATE;
}
else if (s->tool == PAINT_TOOL_CLONE && s->clonecanvas) {
liftpos[0] = pos[0] - offset[0] * s->canvas->x;
@@ -1152,9 +1161,12 @@ static int paint_2d_op(void *state, ImBuf *ibufb, unsigned short *curveb, unsign
data.blend = blend;
data.tilex = tilex;
data.tilew = tilew;
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
BLI_task_parallel_range(tiley, tileh + 1, &data,
paint_2d_op_foreach_do,
- true);
+ &settings);
}
}
@@ -1662,7 +1674,7 @@ void paint_2d_gradient_fill(
break;
}
}
- do_colorband(br->gradient, f, color_f);
+ BKE_colorband_evaluate(br->gradient, f, color_f);
/* convert to premultiplied */
mul_v3_fl(color_f, color_f[3]);
color_f[3] *= br->alpha;
@@ -1692,7 +1704,7 @@ void paint_2d_gradient_fill(
}
}
- do_colorband(br->gradient, f, color_f);
+ BKE_colorband_evaluate(br->gradient, f, color_f);
linearrgb_to_srgb_v3_v3(color_f, color_f);
rgba_float_to_uchar((unsigned char *)&color_b, color_f);
((unsigned char *)&color_b)[3] *= br->alpha;
diff --git a/source/blender/editors/sculpt_paint/paint_image_proj.c b/source/blender/editors/sculpt_paint/paint_image_proj.c
index f5d115442c6..e5bddae971d 100644
--- a/source/blender/editors/sculpt_paint/paint_image_proj.c
+++ b/source/blender/editors/sculpt_paint/paint_image_proj.c
@@ -62,6 +62,7 @@
#include "DNA_object_types.h"
#include "BKE_camera.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_colortools.h"
#include "BKE_depsgraph.h"
@@ -1498,15 +1499,16 @@ static int project_paint_undo_subtiles(const TileInfo *tinf, int tx, int ty)
if (generate_tile) {
+ ListBase *undo_tiles = ED_image_undo_get_tiles();
volatile void *undorect;
if (tinf->masked) {
undorect = image_undo_push_tile(
- pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
+ undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
tx, ty, &pjIma->maskRect[tile_index], &pjIma->valid[tile_index], true, false);
}
else {
undorect = image_undo_push_tile(
- pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
+ undo_tiles, pjIma->ima, pjIma->ibuf, tinf->tmpibuf,
tx, ty, NULL, &pjIma->valid[tile_index], true, false);
}
@@ -2691,7 +2693,7 @@ static void project_paint_face_init(
int face_seam_flag;
if (threaded)
- BLI_lock_thread(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
+ BLI_thread_lock(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
face_seam_flag = ps->faceSeamFlags[tri_index];
@@ -2708,7 +2710,7 @@ static void project_paint_face_init(
if ((face_seam_flag & (PROJ_FACE_SEAM1 | PROJ_FACE_SEAM2 | PROJ_FACE_SEAM3)) == 0) {
if (threaded)
- BLI_unlock_thread(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
+ BLI_thread_unlock(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
}
else {
@@ -2734,7 +2736,7 @@ static void project_paint_face_init(
/* ps->faceSeamUVs cant be modified when threading, now this is done we can unlock */
if (threaded)
- BLI_unlock_thread(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
+ BLI_thread_unlock(LOCK_CUSTOM1); /* Other threads could be modifying these vars */
vCoSS[0] = ps->screenCoords[lt_vtri[0]];
vCoSS[1] = ps->screenCoords[lt_vtri[1]];
@@ -2777,7 +2779,7 @@ static void project_paint_face_init(
interp_v3_v3v3(edge_verts_inset_clip[1], insetCos[fidx1], insetCos[fidx2], fac2);
- if (pixel_bounds_uv((const float (*)[2])seam_subsection, &bounds_px, ibuf->x, ibuf->y)) {
+ if (pixel_bounds_uv(seam_subsection, &bounds_px, ibuf->x, ibuf->y)) {
/* bounds between the seam rect and the uvspace bucket pixels */
has_isect = 0;
@@ -3712,8 +3714,12 @@ static void project_paint_prepare_all_faces(
}
/* don't allow using the same inage for painting and stencilling */
- if (slot->ima == ps->stencil_ima)
+ if (slot->ima == ps->stencil_ima) {
+ /* While this shouldn't be used, face-winding reads all polys.
+ * It's less trouble to set all faces to valid UV's, avoiding NULL checks all over. */
+ ps->dm_mloopuv[lt->poly] = mloopuv_base;
continue;
+ }
tpage = slot->ima;
}
@@ -4128,7 +4134,7 @@ static bool project_bucket_iter_next(
const int diameter = 2 * ps->brush_size;
if (ps->thread_tot > 1)
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
//printf("%d %d\n", ps->context_bucket_x, ps->context_bucket_y);
@@ -4145,7 +4151,7 @@ static bool project_bucket_iter_next(
ps->context_bucket_x++;
if (ps->thread_tot > 1)
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return 1;
}
@@ -4154,7 +4160,7 @@ static bool project_bucket_iter_next(
}
if (ps->thread_tot > 1)
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return 0;
}
@@ -4291,7 +4297,7 @@ static void do_projectpaint_soften_f(ProjPaintState *ps, ProjPixel *projPixel, f
return;
}
else {
- blend_color_interpolate_float(rgba, rgba, projPixel->pixel.f_pt, mask);
+ blend_color_interpolate_float(rgba, projPixel->pixel.f_pt, rgba, mask);
}
BLI_linklist_prepend_arena(softenPixels, (void *)projPixel, softenArena);
@@ -4574,7 +4580,7 @@ static void *do_projectpaint_thread(void *ph_v)
break;
}
}
- do_colorband(brush->gradient, f, color_f);
+ BKE_colorband_evaluate(brush->gradient, f, color_f);
color_f[3] *= ((float)projPixel->mask) * (1.0f / 65535.0f) * brush->alpha;
if (is_floatbuf) {
@@ -4750,6 +4756,9 @@ static void *do_projectpaint_thread(void *ph_v)
copy_v3_v3(texrgb, texrgba);
mask *= texrgba[3];
}
+ else {
+ zero_v3(texrgb);
+ }
/* extra mask for normal, layer stencil, .. */
mask *= ((float)projPixel->mask) * (1.0f / 65535.0f);
@@ -4870,7 +4879,7 @@ static bool project_paint_op(void *state, const float lastpos[2], const float po
}
if (ps->thread_tot > 1)
- BLI_init_threads(&threads, do_projectpaint_thread, ps->thread_tot);
+ BLI_threadpool_init(&threads, do_projectpaint_thread, ps->thread_tot);
pool = BKE_image_pool_new();
@@ -4900,11 +4909,11 @@ static bool project_paint_op(void *state, const float lastpos[2], const float po
handles[a].pool = pool;
if (ps->thread_tot > 1)
- BLI_insert_thread(&threads, &handles[a]);
+ BLI_threadpool_insert(&threads, &handles[a]);
}
if (ps->thread_tot > 1) /* wait for everything to be done */
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
else
do_projectpaint_thread(&handles[0]);
@@ -5376,8 +5385,7 @@ static int texture_paint_camera_project_exec(bContext *C, wmOperator *op)
scene->toolsettings->imapaint.flag |= IMAGEPAINT_DRAWING;
- ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
- ED_image_undo_restore, ED_image_undo_free, NULL);
+ ED_image_undo_push_begin(op->type->name);
/* allocate and initialize spatial data structures */
project_paint_begin(&ps, false, 0);
@@ -5453,7 +5461,7 @@ static int texture_paint_image_from_view_exec(bContext *C, wmOperator *op)
ibuf = ED_view3d_draw_offscreen_imbuf(
scene, CTX_wm_view3d(C), CTX_wm_region(C),
- w, h, IB_rect, false, R_ALPHAPREMUL, 0, false, NULL,
+ w, h, IB_rect, V3D_OFSDRAW_NONE, R_ALPHAPREMUL, 0, NULL,
NULL, NULL, err_out);
if (!ibuf) {
/* Mostly happens when OpenGL offscreen buffer was failed to create, */
@@ -5624,7 +5632,7 @@ bool BKE_paint_proj_mesh_data_check(Scene *scene, Object *ob, bool *uvs, bool *m
/* Add layer operator */
-static EnumPropertyItem layer_type_items[] = {
+static const EnumPropertyItem layer_type_items[] = {
{MAP_COL, "DIFFUSE_COLOR", 0, "Diffuse Color", ""},
{MAP_REF, "DIFFUSE_INTENSITY", 0, "Diffuse Intensity", ""},
{MAP_ALPHA, "ALPHA", 0, "Alpha", ""},
@@ -5711,21 +5719,16 @@ static bool proj_paint_add_slot(bContext *C, wmOperator *op)
/* successful creation of mtex layer, now create set */
if (mtex) {
int type = MAP_COL;
- int type_id = 0;
+ char imagename_buff[MAX_ID_NAME - 2];
+ const char *imagename = DATA_("Diffuse Color");
if (op) {
- int i;
type = RNA_enum_get(op->ptr, "type");
-
- for (i = 0; i < ARRAY_SIZE(layer_type_items); i++) {
- if (layer_type_items[i].value == type) {
- type_id = i;
- break;
- }
- }
+ RNA_string_get(op->ptr, "name", imagename_buff);
+ imagename = imagename_buff;
}
- mtex->tex = BKE_texture_add(bmain, DATA_(layer_type_items[type_id].name));
+ mtex->tex = BKE_texture_add(bmain, imagename);
mtex->mapto = type;
if (mtex->tex) {
@@ -5902,7 +5905,7 @@ static int add_simple_uvs_exec(bContext *C, wmOperator *UNUSED(op))
}));
/* select all uv loops first - pack parameters needs this to make sure charts are registered */
ED_uvedit_select_all(bm);
- ED_uvedit_unwrap_cube_project(ob, bm, 1.0, false);
+ ED_uvedit_unwrap_cube_project(bm, 1.0, false, NULL);
/* set the margin really quickly before the packing operation*/
scene->toolsettings->uvcalc_margin = 0.001f;
ED_uvedit_pack_islands(scene, ob, bm, false, false, true);
diff --git a/source/blender/editors/sculpt_paint/paint_image_undo.c b/source/blender/editors/sculpt_paint/paint_image_undo.c
new file mode 100644
index 00000000000..ef28dafa8c9
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_image_undo.c
@@ -0,0 +1,533 @@
+/*
+ * ***** 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.
+ *
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_image_undo.c
+ * \ingroup edsculpt
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_math.h"
+#include "BLI_blenlib.h"
+#include "BLI_utildefines.h"
+#include "BLI_threads.h"
+
+#include "DNA_image_types.h"
+#include "DNA_windowmanager_types.h"
+#include "DNA_object_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_space_types.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_image.h"
+#include "BKE_main.h"
+#include "BKE_undo_system.h"
+
+#include "ED_paint.h"
+#include "ED_undo.h"
+
+#include "GPU_draw.h"
+
+#include "paint_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Undo Conversion
+ * \{ */
+
+typedef struct UndoImageTile {
+ struct UndoImageTile *next, *prev;
+
+ char ibufname[IMB_FILENAME_SIZE];
+
+ union {
+ float *fp;
+ unsigned int *uint;
+ void *pt;
+ } rect;
+
+ unsigned short *mask;
+
+ int x, y;
+
+ Image *ima;
+ short source, use_float;
+ char gen_type;
+ bool valid;
+
+ size_t undo_size;
+} UndoImageTile;
+
+/* this is a static resource for non-globality,
+ * Maybe it should be exposed as part of the
+ * paint operation, but for now just give a public interface */
+static SpinLock undolock;
+
+void image_undo_init_locks(void)
+{
+ BLI_spin_init(&undolock);
+}
+
+void image_undo_end_locks(void)
+{
+ BLI_spin_end(&undolock);
+}
+
+/* UNDO */
+typedef enum {
+ COPY = 0,
+ RESTORE = 1,
+ RESTORE_COPY = 2
+} CopyMode;
+
+static void undo_copy_tile(UndoImageTile *tile, ImBuf *tmpibuf, ImBuf *ibuf, CopyMode mode)
+{
+ if (mode == COPY) {
+ /* copy or swap contents of tile->rect and region in ibuf->rect */
+ IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
+ tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
+
+ if (ibuf->rect_float) {
+ SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
+ }
+ else {
+ SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
+ }
+ }
+ else {
+ if (mode == RESTORE_COPY) {
+ IMB_rectcpy(tmpibuf, ibuf, 0, 0, tile->x * IMAPAINT_TILE_SIZE,
+ tile->y * IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
+ }
+ /* swap to the tmpbuf for easy copying */
+ if (ibuf->rect_float) {
+ SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
+ }
+ else {
+ SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
+ }
+
+ IMB_rectcpy(ibuf, tmpibuf, tile->x * IMAPAINT_TILE_SIZE,
+ tile->y * IMAPAINT_TILE_SIZE, 0, 0, IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE);
+
+ if (mode == RESTORE) {
+ if (ibuf->rect_float) {
+ SWAP(float *, tmpibuf->rect_float, tile->rect.fp);
+ }
+ else {
+ SWAP(unsigned int *, tmpibuf->rect, tile->rect.uint);
+ }
+ }
+ }
+}
+
+void *image_undo_find_tile(
+ ListBase *undo_tiles,
+ Image *ima, ImBuf *ibuf, int x_tile, int y_tile, unsigned short **mask, bool validate)
+{
+ UndoImageTile *tile;
+ short use_float = ibuf->rect_float ? 1 : 0;
+
+ for (tile = undo_tiles->first; tile; tile = tile->next) {
+ if (tile->x == x_tile && tile->y == y_tile && ima->gen_type == tile->gen_type && ima->source == tile->source) {
+ if (tile->use_float == use_float) {
+ if (STREQ(tile->ibufname, ibuf->name)) {
+ if (mask) {
+ /* allocate mask if requested */
+ if (!tile->mask) {
+ tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
+ "UndoImageTile.mask");
+ }
+
+ *mask = tile->mask;
+ }
+ if (validate) {
+ tile->valid = true;
+ }
+ return tile->rect.pt;
+ }
+ }
+ }
+ }
+
+ return NULL;
+}
+
+void *image_undo_push_tile(
+ ListBase *undo_tiles,
+ Image *ima, ImBuf *ibuf, ImBuf **tmpibuf, int x_tile, int y_tile,
+ unsigned short **mask, bool **valid, bool proj, bool find_prev)
+{
+ UndoImageTile *tile;
+ int allocsize;
+ short use_float = ibuf->rect_float ? 1 : 0;
+ void *data;
+
+ /* check if tile is already pushed */
+
+ /* in projective painting we keep accounting of tiles, so if we need one pushed, just push! */
+ if (find_prev) {
+ data = image_undo_find_tile(undo_tiles, ima, ibuf, x_tile, y_tile, mask, true);
+ if (data) {
+ return data;
+ }
+ }
+
+ if (*tmpibuf == NULL) {
+ *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
+ }
+
+ tile = MEM_callocN(sizeof(UndoImageTile), "UndoImageTile");
+ tile->x = x_tile;
+ tile->y = y_tile;
+
+ /* add mask explicitly here */
+ if (mask) {
+ *mask = tile->mask = MEM_callocN(sizeof(unsigned short) * IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE,
+ "UndoImageTile.mask");
+ }
+ allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
+ allocsize *= (ibuf->rect_float) ? sizeof(float) : sizeof(char);
+ tile->rect.pt = MEM_mapallocN(allocsize, "UndeImageTile.rect");
+
+ BLI_strncpy(tile->ibufname, ibuf->name, sizeof(tile->ibufname));
+
+ tile->gen_type = ima->gen_type;
+ tile->source = ima->source;
+ tile->use_float = use_float;
+ tile->valid = true;
+ tile->ima = ima;
+
+ if (valid) {
+ *valid = &tile->valid;
+ }
+ undo_copy_tile(tile, *tmpibuf, ibuf, COPY);
+
+ if (proj) {
+ BLI_spin_lock(&undolock);
+ }
+ BLI_addtail(undo_tiles, tile);
+
+ if (proj) {
+ BLI_spin_unlock(&undolock);
+ }
+ return tile->rect.pt;
+}
+
+void image_undo_remove_masks(void)
+{
+ ListBase *undo_tiles = ED_image_undo_get_tiles();
+ UndoImageTile *tile;
+
+ for (tile = undo_tiles->first; tile; tile = tile->next) {
+ if (tile->mask) {
+ MEM_freeN(tile->mask);
+ tile->mask = NULL;
+ }
+ }
+}
+
+static void image_undo_restore_runtime(ListBase *lb)
+{
+ ImBuf *ibuf, *tmpibuf;
+ UndoImageTile *tile;
+
+ tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32,
+ IB_rectfloat | IB_rect);
+
+ for (tile = lb->first; tile; tile = tile->next) {
+ Image *ima = tile->ima;
+ ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
+
+ undo_copy_tile(tile, tmpibuf, ibuf, RESTORE);
+
+ GPU_free_image(ima); /* force OpenGL reload (maybe partial update will operate better?) */
+ if (ibuf->rect_float) {
+ ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
+ }
+ if (ibuf->mipmap[0]) {
+ ibuf->userflags |= IB_MIPMAP_INVALID; /* force mipmap recreatiom */
+ }
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
+
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ }
+
+ IMB_freeImBuf(tmpibuf);
+}
+
+static void image_undo_restore_list(ListBase *lb, struct UndoIDPtrMap *id_map)
+{
+ ImBuf *tmpibuf = IMB_allocImBuf(IMAPAINT_TILE_SIZE, IMAPAINT_TILE_SIZE, 32, IB_rectfloat | IB_rect);
+
+ /* Store last found image. */
+ ID *image_prev[2] = {NULL};
+
+ for (UndoImageTile *tile = lb->first; tile; tile = tile->next) {
+ short use_float;
+
+ Image *ima = (Image *)BKE_undosys_ID_map_lookup_with_prev(id_map, &tile->ima->id, image_prev);
+
+ ImBuf *ibuf = BKE_image_acquire_ibuf(ima, NULL, NULL);
+
+ if (ima && ibuf && !STREQ(tile->ibufname, ibuf->name)) {
+ /* current ImBuf filename was changed, probably current frame
+ * was changed when painting on image sequence, rather than storing
+ * full image user (which isn't so obvious, btw) try to find ImBuf with
+ * matched file name in list of already loaded images */
+
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+
+ ibuf = BKE_image_get_ibuf_with_name(ima, tile->ibufname);
+ }
+
+ if (!ima || !ibuf || !(ibuf->rect || ibuf->rect_float)) {
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ continue;
+ }
+
+ if (ima->gen_type != tile->gen_type || ima->source != tile->source) {
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ continue;
+ }
+
+ use_float = ibuf->rect_float ? 1 : 0;
+
+ if (use_float != tile->use_float) {
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ continue;
+ }
+
+ undo_copy_tile(tile, tmpibuf, ibuf, RESTORE_COPY);
+
+ GPU_free_image(ima); /* force OpenGL reload */
+ if (ibuf->rect_float) {
+ ibuf->userflags |= IB_RECT_INVALID; /* force recreate of char rect */
+ }
+ if (ibuf->mipmap[0]) {
+ ibuf->userflags |= IB_MIPMAP_INVALID; /* force mipmap recreatiom */
+ }
+ ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;
+
+ DAG_id_tag_update(&ima->id, 0);
+
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ }
+
+ IMB_freeImBuf(tmpibuf);
+}
+
+static void image_undo_free_list(ListBase *lb)
+{
+ UndoImageTile *tile;
+
+ for (tile = lb->first; tile; tile = tile->next) {
+ MEM_freeN(tile->rect.pt);
+ }
+}
+
+void ED_image_undo_push_begin(const char *name)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ bContext *C = NULL; /* special case, we never read from this. */
+ BKE_undosys_step_push_init_with_type(ustack, C, name, BKE_UNDOSYS_TYPE_IMAGE);
+}
+
+void ED_image_undo_push_end(void)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ BKE_undosys_step_push(ustack, NULL, NULL);
+}
+
+static void image_undo_invalidate(void)
+{
+ UndoImageTile *tile;
+ ListBase *lb = ED_image_undo_get_tiles();
+
+ for (tile = lb->first; tile; tile = tile->next) {
+ tile->valid = false;
+ }
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct ImageUndoStep {
+ UndoStep step;
+ ListBase tiles;
+
+ /* Use for all ID lookups (can be NULL). */
+ struct UndoIDPtrMap *id_map;
+} ImageUndoStep;
+
+static void image_undosys_step_encode_store_ids(ImageUndoStep *us)
+{
+ us->id_map = BKE_undosys_ID_map_create();
+
+ ID *image_prev = NULL;
+ for (UndoImageTile *tile = us->tiles.first; tile; tile = tile->next) {
+ BKE_undosys_ID_map_add_with_prev(us->id_map, &tile->ima->id, &image_prev);
+ }
+}
+
+/* Restore at runtime. */
+#if 0
+static void paint_undosys_step_decode_restore_ids(ImageUndoStep *us)
+{
+ ID *image_prev[2] = {NULL};
+ for (UndoImageTile *tile = us->tiles.first; tile; tile = tile->next) {
+ tile->ima = (Image *)BKE_undosys_ID_map_lookup_with_prev(us->id_map, &tile->ima->id, image_prev);
+ }
+}
+#endif
+
+static bool image_undosys_poll(bContext *C)
+{
+ Object *obact = CTX_data_active_object(C);
+
+ ScrArea *sa = CTX_wm_area(C);
+ if (sa && (sa->spacetype == SPACE_IMAGE)) {
+ SpaceImage *sima = (SpaceImage *)sa->spacedata.first;
+ if ((obact && (obact->mode & OB_MODE_TEXTURE_PAINT)) || (sima->mode == SI_MODE_PAINT)) {
+ return true;
+ }
+ }
+ else if (sa && (sa->spacetype == SPACE_VIEW3D)) {
+ if (obact && (obact->mode & OB_MODE_TEXTURE_PAINT)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void image_undosys_step_encode_init(struct bContext *UNUSED(C), UndoStep *us_p)
+{
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+ /* dummy, memory is cleared anyway. */
+ BLI_listbase_clear(&us->tiles);
+}
+
+static bool image_undosys_step_encode(struct bContext *UNUSED(C), UndoStep *us_p)
+{
+ /* dummy, encoding is done along the way by adding tiles
+ * to the current 'ImageUndoStep' added by encode_init. */
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+
+ BLI_assert(us->step.data_size == 0);
+
+ int allocsize = IMAPAINT_TILE_SIZE * IMAPAINT_TILE_SIZE * 4;
+
+
+ /* first dispose of invalid tiles (may happen due to drag dot for instance) */
+ for (UndoImageTile *tile = us->tiles.first; tile;) {
+ if (!tile->valid) {
+ UndoImageTile *tmp_tile = tile->next;
+ MEM_freeN(tile->rect.pt);
+ BLI_freelinkN(&us->tiles, tile);
+ tile = tmp_tile;
+ }
+ else {
+ us->step.data_size += allocsize * ((tile->use_float) ? sizeof(float) : sizeof(char));
+ tile = tile->next;
+ }
+ }
+
+ image_undosys_step_encode_store_ids(us);
+
+ return true;
+}
+
+static void image_undosys_step_decode(struct bContext *UNUSED(C), UndoStep *us_p, int UNUSED(dir))
+{
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+#if 0
+ paint_undosys_step_decode_restore_ids(us);
+#endif
+ image_undo_restore_list(&us->tiles, us->id_map);
+}
+
+static void image_undosys_step_free(UndoStep *us_p)
+{
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+ image_undo_free_list(&us->tiles);
+ BKE_undosys_ID_map_destroy(us->id_map);
+}
+
+static void image_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+ if (us->id_map != NULL) {
+ BKE_undosys_ID_map_foreach_ID_ref(us->id_map, foreach_ID_ref_fn, user_data);
+ }
+}
+
+/* Export for ED_undo_sys. */
+void ED_image_undosys_type(UndoType *ut)
+{
+ ut->name = "Image";
+ ut->poll = image_undosys_poll;
+ ut->step_encode_init = image_undosys_step_encode_init;
+ ut->step_encode = image_undosys_step_encode;
+ ut->step_decode = image_undosys_step_decode;
+ ut->step_free = image_undosys_step_free;
+
+ ut->step_foreach_ID_ref = image_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_ACCUMULATE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(ImageUndoStep);
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+ListBase *ED_image_undosys_step_get_tiles(UndoStep *us_p)
+{
+ ImageUndoStep *us = (ImageUndoStep *)us_p;
+ return &us->tiles;
+}
+
+ListBase *ED_image_undo_get_tiles(void)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ UndoStep *us = BKE_undosys_stack_init_or_active_with_type(ustack, BKE_UNDOSYS_TYPE_IMAGE);
+ return ED_image_undosys_step_get_tiles(us);
+}
+
+/* restore painting image to previous state. Used for anchored and drag-dot style brushes*/
+void ED_image_undo_restore(UndoStep *us)
+{
+ ListBase *lb = ED_image_undosys_step_get_tiles(us);
+ image_undo_restore_runtime(lb);
+ image_undo_invalidate();
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/paint_intern.h b/source/blender/editors/sculpt_paint/paint_intern.h
index 7e05ab929ae..63a12b3c145 100644
--- a/source/blender/editors/sculpt_paint/paint_intern.h
+++ b/source/blender/editors/sculpt_paint/paint_intern.h
@@ -43,6 +43,7 @@ struct MTex;
struct Object;
struct PaintStroke;
struct Paint;
+struct PaintCurve;
struct PointerRNA;
struct rcti;
struct Scene;
@@ -54,7 +55,8 @@ struct wmOperator;
struct wmOperatorType;
struct wmWindowManager;
struct DMCoNo;
-enum PaintMode;
+struct UndoStep;
+enum ePaintMode;
/* paint_stroke.c */
typedef bool (*StrokeGetLocation)(struct bContext *C, float location[3], const float mouse[2]);
@@ -69,12 +71,12 @@ struct PaintStroke *paint_stroke_new(struct bContext *C, struct wmOperator *op,
StrokeDone done, int event_type);
void paint_stroke_data_free(struct wmOperator *op);
-bool paint_space_stroke_enabled(struct Brush *br, enum PaintMode mode);
-bool paint_supports_dynamic_size(struct Brush *br, enum PaintMode mode);
-bool paint_supports_dynamic_tex_coords(struct Brush *br, enum PaintMode mode);
-bool paint_supports_smooth_stroke(struct Brush *br, enum PaintMode mode);
-bool paint_supports_texture(enum PaintMode mode);
-bool paint_supports_jitter(enum PaintMode mode);
+bool paint_space_stroke_enabled(struct Brush *br, enum ePaintMode mode);
+bool paint_supports_dynamic_size(struct Brush *br, enum ePaintMode mode);
+bool paint_supports_dynamic_tex_coords(struct Brush *br, enum ePaintMode mode);
+bool paint_supports_smooth_stroke(struct Brush *br, enum ePaintMode mode);
+bool paint_supports_texture(enum ePaintMode mode);
+bool paint_supports_jitter(enum ePaintMode mode);
struct wmKeyMap *paint_stroke_modal_keymap(struct wmKeyConfig *keyconf);
int paint_stroke_modal(struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
@@ -96,21 +98,11 @@ int weight_paint_mode_poll(struct bContext *C);
int vertex_paint_poll(struct bContext *C);
int vertex_paint_mode_poll(struct bContext *C);
-bool ED_vpaint_fill(struct Object *ob, unsigned int paintcol);
-bool ED_wpaint_fill(struct VPaint *wp, struct Object *ob, float paintweight);
-
-bool ED_vpaint_smooth(struct Object *ob);
-
typedef void (*VPaintTransform_Callback)(const float col[3], const void *user_data, float r_col[3]);
-bool ED_vpaint_color_transform(struct Object *ob, VPaintTransform_Callback vpaint_tx_fn, const void *user_data);
-
void PAINT_OT_weight_paint_toggle(struct wmOperatorType *ot);
void PAINT_OT_weight_paint(struct wmOperatorType *ot);
void PAINT_OT_weight_set(struct wmOperatorType *ot);
-void PAINT_OT_weight_from_bones(struct wmOperatorType *ot);
-void PAINT_OT_weight_sample(struct wmOperatorType *ot);
-void PAINT_OT_weight_sample_group(struct wmOperatorType *ot);
enum {
WPAINT_GRADIENT_TYPE_LINEAR,
@@ -123,6 +115,44 @@ void PAINT_OT_vertex_paint(struct wmOperatorType *ot);
unsigned int vpaint_get_current_col(struct Scene *scene, struct VPaint *vp);
+/* paint_vertex_color_utils.c */
+unsigned int ED_vpaint_blend_tool(
+ const int tool, const uint col,
+ const uint paintcol, const int alpha_i);
+bool ED_vpaint_color_transform(
+ struct Object *ob, VPaintTransform_Callback vpaint_tx_fn, const void *user_data);
+
+/* paint_vertex_weight_utils.c */
+float ED_wpaint_blend_tool(
+ const int tool,
+ const float weight,
+ const float paintval, const float alpha);
+/* Utility for tools to ensure vertex groups exist before they begin. */
+enum eWPaintFlag {
+ WPAINT_ENSURE_MIRROR = (1 << 0),
+};
+struct WPaintVGroupIndex {
+ int active;
+ int mirror;
+};
+bool ED_wpaint_ensure_data(
+ struct bContext *C, struct ReportList *reports,
+ enum eWPaintFlag flag, struct WPaintVGroupIndex *vgroup_index);
+int ED_wpaint_mirror_vgroup_ensure(struct Object *ob, const int vgroup_active);
+
+/* paint_vertex_color_ops.c */
+void PAINT_OT_vertex_color_set(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_from_weight(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_smooth(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_brightness_contrast(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_hsv(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_invert(struct wmOperatorType *ot);
+void PAINT_OT_vertex_color_levels(struct wmOperatorType *ot);
+
+/* paint_vertex_weight_ops.c */
+void PAINT_OT_weight_from_bones(struct wmOperatorType *ot);
+void PAINT_OT_weight_sample(struct wmOperatorType *ot);
+void PAINT_OT_weight_sample_group(struct wmOperatorType *ot);
/* paint_vertex_proj.c */
struct VertProjHandle;
@@ -148,29 +178,33 @@ typedef struct ImagePaintPartialRedraw {
#define IMAPAINT_TILE_NUMBER(size) (((size) + IMAPAINT_TILE_SIZE - 1) >> IMAPAINT_TILE_BITS)
int image_texture_paint_poll(struct bContext *C);
-void *image_undo_find_tile(struct Image *ima, struct ImBuf *ibuf, int x_tile, int y_tile, unsigned short **mask, bool validate);
-void *image_undo_push_tile(struct Image *ima, struct ImBuf *ibuf, struct ImBuf **tmpibuf, int x_tile, int y_tile, unsigned short **, bool **valid, bool proj, bool find_prev);
-void image_undo_remove_masks(void);
-void image_undo_init_locks(void);
-void image_undo_end_locks(void);
-
void imapaint_image_update(struct SpaceImage *sima, struct Image *image, struct ImBuf *ibuf, short texpaint);
struct ImagePaintPartialRedraw *get_imapaintpartial(void);
void set_imapaintpartial(struct ImagePaintPartialRedraw *ippr);
void imapaint_region_tiles(struct ImBuf *ibuf, int x, int y, int w, int h, int *tx, int *ty, int *tw, int *th);
int get_imapaint_zoom(struct bContext *C, float *zoomx, float *zoomy);
void *paint_2d_new_stroke(struct bContext *, struct wmOperator *, int mode);
-void paint_2d_redraw(const bContext *C, void *ps, bool final);
+void paint_2d_redraw(const struct bContext *C, void *ps, bool final);
void paint_2d_stroke_done(void *ps);
-void paint_2d_stroke(void *ps, const float prev_mval[2], const float mval[2], const bool eraser, float pressure, float distance, float size);
-void paint_2d_bucket_fill(const struct bContext *C, const float color[3], struct Brush *br, const float mouse_init[2], void *ps);
-void paint_2d_gradient_fill(const struct bContext *C, struct Brush *br, const float mouse_init[2], const float mouse_final[2], void *ps);
-void *paint_proj_new_stroke(struct bContext *C, struct Object *ob, const float mouse[2], int mode);
-void paint_proj_stroke(const struct bContext *C, void *ps, const float prevmval_i[2], const float mval_i[2], const bool eraser, float pressure, float distance, float size);
+void paint_2d_stroke(
+ void *ps, const float prev_mval[2], const float mval[2],
+ const bool eraser, float pressure, float distance, float size);
+void paint_2d_bucket_fill(
+ const struct bContext *C, const float color[3], struct Brush *br, const float mouse_init[2], void *ps);
+void paint_2d_gradient_fill(
+ const struct bContext *C, struct Brush *br, const float mouse_init[2], const float mouse_final[2], void *ps);
+void *paint_proj_new_stroke(
+ struct bContext *C, struct Object *ob, const float mouse[2], int mode);
+void paint_proj_stroke(
+ const struct bContext *C, void *ps, const float prevmval_i[2], const float mval_i[2],
+ const bool eraser, float pressure, float distance, float size);
void paint_proj_redraw(const struct bContext *C, void *pps, bool final);
void paint_proj_stroke_done(void *ps);
-void paint_brush_color_get(struct Scene *scene, struct Brush *br, bool color_correction, bool invert, float distance, float pressure, float color[3], struct ColorManagedDisplay *display);
+void paint_brush_color_get(
+ struct Scene *scene, struct Brush *br,
+ bool color_correction, bool invert, float distance, float pressure, float color[3],
+ struct ColorManagedDisplay *display);
bool paint_use_opacity_masking(struct Brush *brush);
void paint_brush_init_tex(struct Brush *brush);
void paint_brush_exit_tex(struct Brush *brush);
@@ -186,7 +220,23 @@ void PAINT_OT_delete_texture_paint_slot(struct wmOperatorType *ot);
void PAINT_OT_image_paint(struct wmOperatorType *ot);
void PAINT_OT_add_simple_uvs(struct wmOperatorType *ot);
-/* uv sculpting */
+/* paint_image_undo.c */
+void *image_undo_find_tile(
+ ListBase *undo_tiles,
+ struct Image *ima, struct ImBuf *ibuf, int x_tile, int y_tile,
+ unsigned short **mask, bool validate);
+void *image_undo_push_tile(
+ ListBase *undo_tiles,
+ struct Image *ima, struct ImBuf *ibuf, struct ImBuf **tmpibuf, int x_tile, int y_tile,
+ unsigned short **, bool **valid, bool proj, bool find_prev);
+void image_undo_remove_masks(void);
+void image_undo_init_locks(void);
+void image_undo_end_locks(void);
+
+struct ListBase *ED_image_undosys_step_get_tiles(struct UndoStep *us_p);
+struct ListBase *ED_image_undo_get_tiles(void);
+
+/* sculpt_uv.c */
int uv_sculpt_poll(struct bContext *C);
int uv_sculpt_keymap_poll(struct bContext *C);
@@ -214,10 +264,10 @@ void paint_calc_redraw_planes(float planes[4][4],
const struct rcti *screen_rect);
float paint_calc_object_space_radius(struct ViewContext *vc, const float center[3], float pixel_radius);
-float paint_get_tex_pixel(struct MTex *mtex, float u, float v, struct ImagePool *pool, int thread);
-void paint_get_tex_pixel_col(struct MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert, struct ColorSpace *colorspace);
+float paint_get_tex_pixel(const struct MTex *mtex, float u, float v, struct ImagePool *pool, int thread);
+void paint_get_tex_pixel_col(const struct MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert, struct ColorSpace *colorspace);
-void paint_sample_color(bContext *C, struct ARegion *ar, int x, int y, bool texpaint_proj, bool palette);
+void paint_sample_color(struct bContext *C, struct ARegion *ar, int x, int y, bool texpaint_proj, bool palette);
void paint_stroke_operator_properties(struct wmOperatorType *ot);
@@ -260,10 +310,6 @@ typedef enum {
void set_brush_rc_props(struct PointerRNA *ptr, const char *paint, const char *prop, const char *secondary_prop,
RCFlags flags);
-/* paint_undo.c */
-struct ListBase *undo_paint_push_get_list(int type);
-void undo_paint_push_count_alloc(int type, int size);
-
/* paint_hide.c */
typedef enum {
@@ -300,6 +346,9 @@ void PAINTCURVE_OT_slide(struct wmOperatorType *ot);
void PAINTCURVE_OT_draw(struct wmOperatorType *ot);
void PAINTCURVE_OT_cursor(struct wmOperatorType *ot);
+/* paint_curve_undo.c */
+void ED_paintcurve_undo_push(struct bContext *C, struct wmOperator *op, struct PaintCurve *pc);
+
/* image painting blur kernel */
typedef struct {
float *wdata; /* actual kernel */
@@ -308,7 +357,7 @@ typedef struct {
int pixel_len; /* pixels around center that kernel is wide */
} BlurKernel;
-enum BlurKernelType;
+enum eBlurKernelType;
/* can be extended to other blur kernels later */
BlurKernel *paint_new_blur_kernel(struct Brush *br, bool proj);
void paint_delete_blur_kernel(BlurKernel *);
diff --git a/source/blender/editors/sculpt_paint/paint_mask.c b/source/blender/editors/sculpt_paint/paint_mask.c
index a4887c579ac..76b629395e2 100644
--- a/source/blender/editors/sculpt_paint/paint_mask.c
+++ b/source/blender/editors/sculpt_paint/paint_mask.c
@@ -41,7 +41,7 @@
#include "BLI_math_matrix.h"
#include "BLI_math_geom.h"
#include "BLI_utildefines.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_task.h"
#include "BKE_pbvh.h"
@@ -69,7 +69,7 @@
#include <stdlib.h>
-static EnumPropertyItem mode_items[] = {
+static const EnumPropertyItem mode_items[] = {
{PAINT_MASK_FLOOD_VALUE, "VALUE", 0, "Value", "Set mask to the level specified by the 'value' property"},
{PAINT_MASK_FLOOD_VALUE_INVERSE, "VALUE_INVERSE", 0, "Value Inverted", "Set mask to the level specified by the inverted 'value' property"},
{PAINT_MASK_INVERT, "INVERT", 0, "Invert", "Invert the mask"},
@@ -104,7 +104,10 @@ typedef struct MaskTaskData {
float (*clip_planes_final)[4];
} MaskTaskData;
-static void mask_flood_fill_task_cb(void *userdata, const int i)
+static void mask_flood_fill_task_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
MaskTaskData *data = userdata;
@@ -155,14 +158,17 @@ static int mask_flood_fill_exec(bContext *C, wmOperator *op)
.mode = mode, .value = value,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
0, totnode, &data, mask_flood_fill_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ &settings);
if (multires)
multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
if (nodes)
MEM_freeN(nodes);
@@ -218,7 +224,10 @@ static void flip_plane(float out[4], const float in[4], const char symm)
out[3] = in[3];
}
-static void mask_box_select_task_cb(void *userdata, const int i)
+static void mask_box_select_task_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
MaskTaskData *data = userdata;
@@ -299,9 +308,12 @@ int ED_sculpt_mask_box_select(struct bContext *C, ViewContext *vc, const rcti *r
.mode = mode, .value = value, .clip_planes_final = clip_planes_final,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
0, totnode, &data, mask_box_select_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ &settings);
if (nodes)
MEM_freeN(nodes);
@@ -311,7 +323,7 @@ int ED_sculpt_mask_box_select(struct bContext *C, ViewContext *vc, const rcti *r
if (multires)
multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
ED_region_tag_redraw(ar);
@@ -373,7 +385,10 @@ static void mask_lasso_px_cb(int x, int x_end, int y, void *user_data)
} while (++index != index_end);
}
-static void mask_gesture_lasso_task_cb(void *userdata, const int i)
+static void mask_gesture_lasso_task_cb(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
LassoMaskData *lasso_data = userdata;
MaskTaskData *data = &lasso_data->task_data;
@@ -428,7 +443,7 @@ static int paint_mask_gesture_lasso_exec(bContext *C, wmOperator *op)
/* Calculations of individual vertices are done in 2D screen space to diminish the amount of
* calculations done. Bounding box PBVH collision is not computed against enclosing rectangle
* of lasso */
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
view3d_get_transformation(vc.ar, vc.rv3d, vc.obact, &mats);
/* lasso data calculations */
@@ -479,9 +494,12 @@ static int paint_mask_gesture_lasso_exec(bContext *C, wmOperator *op)
data.task_data.mode = mode;
data.task_data.value = value;
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && (totnode > SCULPT_THREADED_LIMIT));
BLI_task_parallel_range(
0, totnode, &data, mask_gesture_lasso_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && (totnode > SCULPT_THREADED_LIMIT)));
+ &settings);
if (nodes)
MEM_freeN(nodes);
@@ -491,7 +509,7 @@ static int paint_mask_gesture_lasso_exec(bContext *C, wmOperator *op)
if (multires)
multires_mark_as_modified(ob, MULTIRES_COORDS_MODIFIED);
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
ED_region_tag_redraw(vc.ar);
MEM_freeN((void *)mcords);
@@ -506,8 +524,6 @@ static int paint_mask_gesture_lasso_exec(bContext *C, wmOperator *op)
void PAINT_OT_mask_lasso_gesture(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
ot->name = "Mask Lasso Gesture";
ot->idname = "PAINT_OT_mask_lasso_gesture";
ot->description = "Add mask within the lasso as you move the brush";
@@ -520,8 +536,8 @@ void PAINT_OT_mask_lasso_gesture(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
+ /* properties */
+ WM_operator_properties_gesture_lasso(ot);
RNA_def_enum(ot->srna, "mode", mode_items, PAINT_MASK_FLOOD_VALUE, "Mode", NULL);
RNA_def_float(ot->srna, "value", 1.0, 0, 1.0, "Value",
diff --git a/source/blender/editors/sculpt_paint/paint_ops.c b/source/blender/editors/sculpt_paint/paint_ops.c
index f88b64129e7..004d2757a71 100644
--- a/source/blender/editors/sculpt_paint/paint_ops.c
+++ b/source/blender/editors/sculpt_paint/paint_ops.c
@@ -66,12 +66,15 @@ static int brush_add_exec(bContext *C, wmOperator *UNUSED(op))
Paint *paint = BKE_paint_get_active_from_context(C);
Brush *br = BKE_paint_brush(paint);
Main *bmain = CTX_data_main(C);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
- if (br)
+ if (br) {
br = BKE_brush_copy(bmain, br);
- else
+ }
+ else {
br = BKE_brush_add(bmain, "Brush", BKE_paint_object_mode_from_paint_mode(mode));
+ id_us_min(&br->id); /* fake user only */
+ }
BKE_paint_brush_set(paint, br);
@@ -195,7 +198,7 @@ static int palette_color_add_exec(bContext *C, wmOperator *UNUSED(op))
Scene *scene = CTX_data_scene(C);
Paint *paint = BKE_paint_get_active_from_context(C);
Brush *brush = paint->brush;
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
Palette *palette = paint->palette;
PaletteColor *color;
@@ -256,300 +259,6 @@ static void PALETTE_OT_color_delete(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-
-
-static int vertex_color_set_exec(bContext *C, wmOperator *UNUSED(op))
-{
- Scene *scene = CTX_data_scene(C);
- Object *obact = CTX_data_active_object(C);
- unsigned int paintcol = vpaint_get_current_col(scene, scene->toolsettings->vpaint);
-
- if (ED_vpaint_fill(obact, paintcol)) {
- ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_set(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Set Vertex Colors";
- ot->idname = "PAINT_OT_vertex_color_set";
- ot->description = "Fill the active vertex color layer with the current paint color";
-
- /* api callbacks */
- ot->exec = vertex_color_set_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-}
-
-static int vertex_color_smooth_exec(bContext *C, wmOperator *UNUSED(op))
-{
- Object *obact = CTX_data_active_object(C);
- if (ED_vpaint_smooth(obact)) {
- ED_region_tag_redraw(CTX_wm_region(C)); // XXX - should redraw all 3D views
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_smooth(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Smooth Vertex Colors";
- ot->idname = "PAINT_OT_vertex_color_smooth";
- ot->description = "Smooth colors across vertices";
-
- /* api callbacks */
- ot->exec = vertex_color_smooth_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-}
-
-
-/** \name Vertex Color Transformations
- * \{ */
-
-struct VPaintTx_BrightContrastData {
- /* pre-calculated */
- float gain;
- float offset;
-};
-
-static void vpaint_tx_brightness_contrast(const float col[3], const void *user_data, float r_col[3])
-{
- const struct VPaintTx_BrightContrastData *data = user_data;
-
- for (int i = 0; i < 3; i++) {
- r_col[i] = data->gain * col[i] + data->offset;
- }
-}
-
-static int vertex_color_brightness_contrast_exec(bContext *C, wmOperator *op)
-{
- Object *obact = CTX_data_active_object(C);
-
- float gain, offset;
- {
- float brightness = RNA_float_get(op->ptr, "brightness");
- float contrast = RNA_float_get(op->ptr, "contrast");
- brightness /= 100.0f;
- float delta = contrast / 200.0f;
- gain = 1.0f - delta * 2.0f;
- /*
- * The algorithm is by Werner D. Streidt
- * (http://visca.com/ffactory/archives/5-99/msg00021.html)
- * Extracted of OpenCV demhist.c
- */
- if (contrast > 0) {
- gain = 1.0f / ((gain != 0.0f) ? gain : FLT_EPSILON);
- offset = gain * (brightness - delta);
- }
- else {
- delta *= -1;
- offset = gain * (brightness + delta);
- }
- }
-
- const struct VPaintTx_BrightContrastData user_data = {
- .gain = gain,
- .offset = offset,
- };
-
- if (ED_vpaint_color_transform(obact, vpaint_tx_brightness_contrast, &user_data)) {
- ED_region_tag_redraw(CTX_wm_region(C));
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_brightness_contrast(wmOperatorType *ot)
-{
- PropertyRNA *prop;
-
- /* identifiers */
- ot->name = "Vertex Paint Bright/Contrast";
- ot->idname = "PAINT_OT_vertex_color_brightness_contrast";
- ot->description = "Adjust vertex color brightness/contrast";
-
- /* api callbacks */
- ot->exec = vertex_color_brightness_contrast_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* params */
- const float min = -100, max = +100;
- prop = RNA_def_float(ot->srna, "brightness", 0.0f, min, max, "Brightness", "", min, max);
- prop = RNA_def_float(ot->srna, "contrast", 0.0f, min, max, "Contrast", "", min, max);
- RNA_def_property_ui_range(prop, min, max, 1, 1);
-}
-
-struct VPaintTx_HueSatData {
- float hue;
- float sat;
- float val;
-};
-
-static void vpaint_tx_hsv(const float col[3], const void *user_data, float r_col[3])
-{
- const struct VPaintTx_HueSatData *data = user_data;
- float hsv[3];
- rgb_to_hsv_v(col, hsv);
-
- hsv[0] += (data->hue - 0.5f);
- if (hsv[0] > 1.0f) {
- hsv[0] -= 1.0f;
- }
- else if (hsv[0] < 0.0f) {
- hsv[0] += 1.0f;
- }
- hsv[1] *= data->sat;
- hsv[2] *= data->val;
-
- hsv_to_rgb_v(hsv, r_col);
-}
-
-static int vertex_color_hsv_exec(bContext *C, wmOperator *op)
-{
- Object *obact = CTX_data_active_object(C);
-
- const struct VPaintTx_HueSatData user_data = {
- .hue = RNA_float_get(op->ptr, "h"),
- .sat = RNA_float_get(op->ptr, "s"),
- .val = RNA_float_get(op->ptr, "v"),
- };
-
- if (ED_vpaint_color_transform(obact, vpaint_tx_hsv, &user_data)) {
- ED_region_tag_redraw(CTX_wm_region(C));
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_hsv(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Vertex Paint Hue Saturation Value";
- ot->idname = "PAINT_OT_vertex_color_hsv";
- ot->description = "Adjust vertex color HSV values";
-
- /* api callbacks */
- ot->exec = vertex_color_hsv_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* params */
- RNA_def_float(ot->srna, "h", 0.5f, 0.0f, 1.0f, "Hue", "", 0.0f, 1.0f);
- RNA_def_float(ot->srna, "s", 1.0f, 0.0f, 2.0f, "Saturation", "", 0.0f, 2.0f);
- RNA_def_float(ot->srna, "v", 1.0f, 0.0f, 2.0f, "Value", "", 0.0f, 2.0f);
-}
-
-static void vpaint_tx_invert(const float col[3], const void *UNUSED(user_data), float r_col[3])
-{
- for (int i = 0; i < 3; i++) {
- r_col[i] = 1.0f - col[i];
- }
-}
-
-static int vertex_color_invert_exec(bContext *C, wmOperator *UNUSED(op))
-{
- Object *obact = CTX_data_active_object(C);
-
- if (ED_vpaint_color_transform(obact, vpaint_tx_invert, NULL)) {
- ED_region_tag_redraw(CTX_wm_region(C));
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_invert(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Vertex Paint Invert";
- ot->idname = "PAINT_OT_vertex_color_invert";
- ot->description = "Invert RGB values";
-
- /* api callbacks */
- ot->exec = vertex_color_invert_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-}
-
-
-struct VPaintTx_LevelsData {
- float gain;
- float offset;
-};
-
-static void vpaint_tx_levels(const float col[3], const void *user_data, float r_col[3])
-{
- const struct VPaintTx_LevelsData *data = user_data;
- for (int i = 0; i < 3; i++) {
- r_col[i] = data->gain * (col[i] + data->offset);
- }
-}
-
-static int vertex_color_levels_exec(bContext *C, wmOperator *op)
-{
- Object *obact = CTX_data_active_object(C);
-
- const struct VPaintTx_LevelsData user_data = {
- .gain = RNA_float_get(op->ptr, "gain"),
- .offset = RNA_float_get(op->ptr, "offset"),
- };
-
- if (ED_vpaint_color_transform(obact, vpaint_tx_levels, &user_data)) {
- ED_region_tag_redraw(CTX_wm_region(C));
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-static void PAINT_OT_vertex_color_levels(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Vertex Paint Levels";
- ot->idname = "PAINT_OT_vertex_color_levels";
- ot->description = "Adjust levels of vertex colors";
-
- /* api callbacks */
- ot->exec = vertex_color_levels_exec;
- ot->poll = vertex_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* params */
- RNA_def_float(ot->srna, "offset", 0.0f, -1.0f, 1.0f, "Offset", "Value to add to colors", -1.0f, 1.0f);
- RNA_def_float(ot->srna, "gain", 1.0f, 0.0f, FLT_MAX, "Gain", "Value to multiply colors by", 0.0f, 10.0f);
-}
-
-/** \} */
-
-
static int brush_reset_exec(bContext *C, wmOperator *UNUSED(op))
{
Paint *paint = BKE_paint_get_active_from_context(C);
@@ -558,9 +267,14 @@ static int brush_reset_exec(bContext *C, wmOperator *UNUSED(op))
if (!ob || !brush) return OPERATOR_CANCELLED;
- if (ob->mode & OB_MODE_SCULPT)
- BKE_brush_sculpt_reset(brush);
/* TODO: other modes */
+ if (ob->mode & OB_MODE_SCULPT) {
+ BKE_brush_sculpt_reset(brush);
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+ WM_event_add_notifier(C, NC_BRUSH | NA_EDITED, brush);
return OPERATOR_FINISHED;
}
@@ -665,6 +379,7 @@ static int brush_generic_tool_set(Main *bmain, Paint *paint, const int tool,
if (!brush && brush_tool(brush_orig, tool_offset) != tool && create_missing) {
brush = BKE_brush_add(bmain, tool_name, ob_mode);
+ id_us_min(&brush->id); /* fake user only */
brush_tool_set(brush, tool_offset, tool);
brush->toggle_brush = brush_orig;
}
@@ -744,7 +459,7 @@ static int brush_select_exec(bContext *C, wmOperator *op)
static void PAINT_OT_brush_select(wmOperatorType *ot)
{
- static EnumPropertyItem paint_mode_items[] = {
+ static const EnumPropertyItem paint_mode_items[] = {
{OB_MODE_ACTIVE, "ACTIVE", 0, "Current", "Set brush for active paint mode"},
{OB_MODE_SCULPT, "SCULPT", ICON_SCULPTMODE_HLT, "Sculpt", ""},
{OB_MODE_VERTEX_PAINT, "VERTEX_PAINT", ICON_VPAINT_HLT, "Vertex Paint", ""},
@@ -821,8 +536,6 @@ static int brush_uv_sculpt_tool_set_exec(bContext *C, wmOperator *op)
static void BRUSH_OT_uv_sculpt_tool_set(wmOperatorType *ot)
{
- /* from rna_scene.c */
- extern EnumPropertyItem uv_sculpt_tool_items[];
/* identifiers */
ot->name = "UV Sculpt Tool Set";
ot->description = "Set the UV sculpt tool";
@@ -836,7 +549,7 @@ static void BRUSH_OT_uv_sculpt_tool_set(wmOperatorType *ot)
ot->flag = 0;
/* props */
- ot->prop = RNA_def_enum(ot->srna, "tool", uv_sculpt_tool_items, 0, "Tool", "");
+ ot->prop = RNA_def_enum(ot->srna, "tool", rna_enum_uv_sculpt_tool_items, 0, "Tool", "");
}
/***** Stencil Control *****/
@@ -1067,7 +780,7 @@ static int stencil_control_modal(bContext *C, wmOperator *op, const wmEvent *eve
static int stencil_control_poll(bContext *C)
{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
Paint *paint;
Brush *br;
@@ -1084,14 +797,14 @@ static int stencil_control_poll(bContext *C)
static void BRUSH_OT_stencil_control(wmOperatorType *ot)
{
- static EnumPropertyItem stencil_control_items[] = {
+ static const EnumPropertyItem stencil_control_items[] = {
{STENCIL_TRANSLATE, "TRANSLATION", 0, "Translation", ""},
{STENCIL_SCALE, "SCALE", 0, "Scale", ""},
{STENCIL_ROTATE, "ROTATION", 0, "Rotation", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem stencil_texture_items[] = {
+ static const EnumPropertyItem stencil_texture_items[] = {
{STENCIL_PRIMARY, "PRIMARY", 0, "Primary", ""},
{STENCIL_SECONDARY, "SECONDARY", 0, "Secondary", ""},
{0, NULL, 0, NULL, NULL}
@@ -1351,6 +1064,7 @@ void ED_operatortypes_paint(void)
WM_operatortype_append(PAINT_OT_vertex_color_hsv);
WM_operatortype_append(PAINT_OT_vertex_color_invert);
WM_operatortype_append(PAINT_OT_vertex_color_levels);
+ WM_operatortype_append(PAINT_OT_vertex_color_from_weight);
/* face-select */
WM_operatortype_append(PAINT_OT_face_select_linked);
@@ -1563,6 +1277,10 @@ void ED_keymap_paint(wmKeyConfig *keyconf)
WM_keymap_add_item(keymap, "PAINT_OT_mask_lasso_gesture", LEFTMOUSE, KM_PRESS, KM_CTRL | KM_SHIFT, 0);
+ /* Toggle mask visibility */
+ kmi = WM_keymap_add_item(keymap, "WM_OT_context_toggle", MKEY, KM_PRESS, KM_CTRL, 0);
+ RNA_string_set(kmi->ptr, "data_path", "scene.tool_settings.sculpt.show_mask");
+
/* Toggle dynamic topology */
WM_keymap_add_item(keymap, "SCULPT_OT_dynamic_topology_toggle", DKEY, KM_PRESS, KM_CTRL, 0);
@@ -1615,6 +1333,7 @@ void ED_keymap_paint(wmKeyConfig *keyconf)
keymap->poll = vertex_paint_mode_poll;
WM_keymap_verify_item(keymap, "PAINT_OT_vertex_paint", LEFTMOUSE, KM_PRESS, 0, 0);
+ WM_keymap_add_item(keymap, "PAINT_OT_brush_colors_flip", XKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap, "PAINT_OT_sample_color", SKEY, KM_PRESS, 0, 0);
WM_keymap_add_item(keymap,
diff --git a/source/blender/editors/sculpt_paint/paint_stroke.c b/source/blender/editors/sculpt_paint/paint_stroke.c
index 05270dbfa09..e6a9fd9adf8 100644
--- a/source/blender/editors/sculpt_paint/paint_stroke.c
+++ b/source/blender/editors/sculpt_paint/paint_stroke.c
@@ -108,6 +108,8 @@ typedef struct PaintStroke {
* e.g. in sculpt mode, stroke doesn't start until cursor
* passes over the mesh */
bool stroke_started;
+ /* Set when enough motion was found for rake rotation */
+ bool rake_started;
/* event that started stroke, for modal() return */
int event_type;
/* check if stroke variables have been initialized */
@@ -192,7 +194,7 @@ static void paint_draw_line_cursor(bContext *C, int x, int y, void *customdata)
glDisable(GL_LINE_SMOOTH);
}
-static bool paint_tool_require_location(Brush *brush, PaintMode mode)
+static bool paint_tool_require_location(Brush *brush, ePaintMode mode)
{
switch (mode) {
case ePaintSculpt:
@@ -214,7 +216,7 @@ static bool paint_tool_require_location(Brush *brush, PaintMode mode)
/* Initialize the stroke cache variants from operator properties */
static bool paint_brush_update(bContext *C,
Brush *brush,
- PaintMode mode,
+ ePaintMode mode,
struct PaintStroke *stroke,
const float mouse_init[2],
float mouse[2], float pressure,
@@ -224,6 +226,9 @@ static bool paint_brush_update(bContext *C,
UnifiedPaintSettings *ups = stroke->ups;
bool location_sampled = false;
bool location_success = false;
+ /* Use to perform all operations except applying the stroke,
+ * needed for operations that require cursor motion (rake). */
+ bool is_dry_run = false;
bool do_random = false;
bool do_random_mask = false;
/* XXX: Use pressure value from first brush step for brushes which don't
@@ -362,7 +367,15 @@ static bool paint_brush_update(bContext *C,
}
/* curve strokes do their own rake calculation */
else if (!(brush->flag & BRUSH_CURVE)) {
- paint_calculate_rake_rotation(ups, brush, mouse_init);
+ if (!paint_calculate_rake_rotation(ups, brush, mouse_init)) {
+ /* Not enough motion to define an angle. */
+ if (!stroke->rake_started) {
+ is_dry_run = true;
+ }
+ }
+ else {
+ stroke->rake_started = true;
+ }
}
}
@@ -393,10 +406,10 @@ static bool paint_brush_update(bContext *C,
}
}
- return location_success;
+ return location_success && (is_dry_run == false);
}
-static bool paint_stroke_use_jitter(PaintMode mode, Brush *brush, bool invert)
+static bool paint_stroke_use_jitter(ePaintMode mode, Brush *brush, bool invert)
{
bool use_jitter = (brush->flag & BRUSH_ABSOLUTE_JITTER) ?
(brush->jitter_absolute != 0) : (brush->jitter != 0);
@@ -416,7 +429,7 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, const float
{
Scene *scene = CTX_data_scene(C);
Paint *paint = BKE_paint_get_active_from_context(C);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
Brush *brush = BKE_paint_brush(paint);
PaintStroke *stroke = op->customdata;
UnifiedPaintSettings *ups = stroke->ups;
@@ -491,7 +504,7 @@ static void paint_brush_stroke_add_step(bContext *C, wmOperator *op, const float
/* Returns zero if no sculpt changes should be made, non-zero otherwise */
static bool paint_smooth_stroke(
- PaintStroke *stroke, const PaintSample *sample, PaintMode mode,
+ PaintStroke *stroke, const PaintSample *sample, ePaintMode mode,
float r_mouse[2], float *r_pressure)
{
if (paint_supports_smooth_stroke(stroke->brush, mode)) {
@@ -580,7 +593,10 @@ static float paint_stroke_integrate_overlap(Brush *br, float factor)
max = overlap;
}
- return 1.0f / max;
+ if (max == 0.0f)
+ return 1.0f;
+ else
+ return 1.0f / max;
}
static float paint_space_stroke_spacing_variable(const Scene *scene, PaintStroke *stroke, float pressure, float dpressure, float length)
@@ -673,7 +689,7 @@ PaintStroke *paint_stroke_new(bContext *C,
Brush *br = stroke->brush = BKE_paint_brush(p);
float zoomx, zoomy;
- view3d_set_viewcontext(C, &stroke->vc);
+ ED_view3d_viewcontext_init(C, &stroke->vc);
stroke->get_location = get_location;
stroke->test_start = test_start;
@@ -754,7 +770,7 @@ static void stroke_done(struct bContext *C, struct wmOperator *op)
}
/* Returns zero if the stroke dots should not be spaced, non-zero otherwise */
-bool paint_space_stroke_enabled(Brush *br, PaintMode mode)
+bool paint_space_stroke_enabled(Brush *br, ePaintMode mode)
{
return (br->flag & BRUSH_SPACE) && paint_supports_dynamic_size(br, mode);
}
@@ -769,7 +785,7 @@ static bool sculpt_is_grab_tool(Brush *br)
}
/* return true if the brush size can change during paint (normally used for pressure) */
-bool paint_supports_dynamic_size(Brush *br, PaintMode mode)
+bool paint_supports_dynamic_size(Brush *br, ePaintMode mode)
{
if (br->flag & BRUSH_ANCHORED)
return false;
@@ -795,7 +811,7 @@ bool paint_supports_dynamic_size(Brush *br, PaintMode mode)
return true;
}
-bool paint_supports_smooth_stroke(Brush *br, PaintMode mode)
+bool paint_supports_smooth_stroke(Brush *br, ePaintMode mode)
{
if (!(br->flag & BRUSH_SMOOTH_STROKE) ||
(br->flag & (BRUSH_ANCHORED | BRUSH_DRAG_DOT | BRUSH_LINE)))
@@ -814,14 +830,14 @@ bool paint_supports_smooth_stroke(Brush *br, PaintMode mode)
return true;
}
-bool paint_supports_texture(PaintMode mode)
+bool paint_supports_texture(ePaintMode mode)
{
/* omit: PAINT_WEIGHT, PAINT_SCULPT_UV, PAINT_INVALID */
return ELEM(mode, ePaintSculpt, ePaintVertex, ePaintTextureProjective, ePaintTexture2D);
}
/* return true if the brush size can change during paint (normally used for pressure) */
-bool paint_supports_dynamic_tex_coords(Brush *br, PaintMode mode)
+bool paint_supports_dynamic_tex_coords(Brush *br, ePaintMode mode)
{
if (br->flag & BRUSH_ANCHORED)
return false;
@@ -1083,7 +1099,7 @@ static void paint_stroke_line_constrain(PaintStroke *stroke, float mouse[2])
int paint_stroke_modal(bContext *C, wmOperator *op, const wmEvent *event)
{
Paint *p = BKE_paint_get_active_from_context(C);
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
PaintStroke *stroke = op->customdata;
Brush *br = stroke->brush;
PaintSample sample_average;
diff --git a/source/blender/editors/sculpt_paint/paint_undo.c b/source/blender/editors/sculpt_paint/paint_undo.c
deleted file mode 100644
index 27d3f6648a2..00000000000
--- a/source/blender/editors/sculpt_paint/paint_undo.c
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/editors/sculpt_paint/paint_undo.c
- * \ingroup edsculpt
- * \brief Undo system for painting and sculpting.
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "MEM_guardedalloc.h"
-
-#include "BLI_listbase.h"
-#include "BLI_utildefines.h"
-#include "BLI_string.h"
-
-#include "DNA_userdef_types.h"
-
-#include "BKE_blender_undo.h"
-#include "BKE_context.h"
-#include "BKE_global.h"
-
-#include "ED_paint.h"
-
-#include "paint_intern.h"
-
-typedef struct UndoElem {
- struct UndoElem *next, *prev;
- char name[BKE_UNDO_STR_MAX];
- uintptr_t undosize;
-
- ListBase elems;
-
- UndoRestoreCb restore;
- UndoFreeCb free;
- UndoCleanupCb cleanup;
-} UndoElem;
-
-typedef struct UndoStack {
- int type;
- ListBase elems;
- UndoElem *current;
-} UndoStack;
-
-static UndoStack ImageUndoStack = {UNDO_PAINT_IMAGE, {NULL, NULL}, NULL};
-static UndoStack MeshUndoStack = {UNDO_PAINT_MESH, {NULL, NULL}, NULL};
-
-/* Generic */
-
-static void undo_restore(bContext *C, UndoStack *UNUSED(stack), UndoElem *uel)
-{
- if (uel && uel->restore)
- uel->restore(C, &uel->elems);
-}
-
-static void undo_elem_free(UndoStack *UNUSED(stack), UndoElem *uel)
-{
- if (uel && uel->free) {
- uel->free(&uel->elems);
- BLI_freelistN(&uel->elems);
- }
-}
-
-static void undo_stack_push_begin(UndoStack *stack, const char *name, UndoRestoreCb restore, UndoFreeCb free, UndoCleanupCb cleanup)
-{
- UndoElem *uel;
- int nr;
-
- /* Undo push is split up in begin and end, the reason is that as painting
- * happens more tiles/nodes are added to the list, and at the very end we
- * know how much memory the undo used to remove old undo elements */
-
- /* remove all undos after (also when stack->current==NULL) */
- while (stack->elems.last != stack->current) {
- uel = stack->elems.last;
- undo_elem_free(stack, uel);
- BLI_freelinkN(&stack->elems, uel);
- }
-
- /* make new */
- stack->current = uel = MEM_callocN(sizeof(UndoElem), "undo file");
- uel->restore = restore;
- uel->free = free;
- uel->cleanup = cleanup;
- BLI_addtail(&stack->elems, uel);
-
- /* name can be a dynamic string */
- BLI_strncpy(uel->name, name, sizeof(uel->name));
-
- /* limit amount to the maximum amount*/
- nr = 0;
- uel = stack->elems.last;
- while (uel) {
- nr++;
- if (nr == U.undosteps) break;
- uel = uel->prev;
- }
- if (uel) {
- while (stack->elems.first != uel) {
- UndoElem *first = stack->elems.first;
- undo_elem_free(stack, first);
- BLI_freelinkN(&stack->elems, first);
- }
- }
-}
-
-static void undo_stack_push_end(UndoStack *stack)
-{
- UndoElem *uel;
- uintptr_t totmem, maxmem;
- int totundo = 0;
-
- /* first limit to undo steps */
- uel = stack->elems.last;
-
- while (uel) {
- totundo++;
- if (totundo > U.undosteps) break;
- uel = uel->prev;
- }
-
- if (uel) {
- UndoElem *first;
-
- /* in case the undo steps are zero, the current pointer will be invalid */
- if (uel == stack->current)
- stack->current = NULL;
-
- do {
- first = stack->elems.first;
- undo_elem_free(stack, first);
- BLI_freelinkN(&stack->elems, first);
- } while (first != uel);
- }
-
- if (U.undomemory != 0) {
- /* limit to maximum memory (afterwards, we can't know in advance) */
- totmem = 0;
- maxmem = ((uintptr_t)U.undomemory) * 1024 * 1024;
-
- uel = stack->elems.last;
- while (uel) {
- totmem += uel->undosize;
- if (totmem > maxmem) break;
- uel = uel->prev;
- }
-
- if (uel) {
- while (stack->elems.first != uel) {
- UndoElem *first = stack->elems.first;
- undo_elem_free(stack, first);
- BLI_freelinkN(&stack->elems, first);
- }
- }
- }
-}
-
-static void undo_stack_cleanup(UndoStack *stack, bContext *C)
-{
- UndoElem *uel = stack->elems.first;
- bool stack_reset = false;
-
- while (uel) {
- if (uel->cleanup && uel->cleanup(C, &uel->elems)) {
- UndoElem *uel_tmp = uel->next;
- if (stack->current == uel) {
- stack->current = NULL;
- stack_reset = true;
- }
- undo_elem_free(stack, uel);
- BLI_freelinkN(&stack->elems, uel);
- uel = uel_tmp;
- }
- else
- uel = uel->next;
- }
- if (stack_reset) {
- stack->current = stack->elems.last;
- }
-
-}
-
-static int undo_stack_step(bContext *C, UndoStack *stack, int step, const char *name)
-{
- UndoElem *undo;
-
- /* first cleanup any old undo steps that may belong to invalid data */
- undo_stack_cleanup(stack, C);
-
- if (step == 1) {
- if (stack->current == NULL) {
- /* pass */
- }
- else {
- if (!name || STREQ(stack->current->name, name)) {
- if (G.debug & G_DEBUG_WM) {
- printf("%s: undo '%s'\n", __func__, stack->current->name);
- }
- undo_restore(C, stack, stack->current);
- stack->current = stack->current->prev;
- return 1;
- }
- }
- }
- else if (step == -1) {
- if ((stack->current != NULL && stack->current->next == NULL) || BLI_listbase_is_empty(&stack->elems)) {
- /* pass */
- }
- else {
- if (!name || STREQ(stack->current->name, name)) {
- undo = (stack->current && stack->current->next) ? stack->current->next : stack->elems.first;
- undo_restore(C, stack, undo);
- stack->current = undo;
- if (G.debug & G_DEBUG_WM) {
- printf("%s: redo %s\n", __func__, undo->name);
- }
- return 1;
- }
- }
- }
-
- return 0;
-}
-
-static void undo_stack_free(UndoStack *stack)
-{
- UndoElem *uel;
-
- for (uel = stack->elems.first; uel; uel = uel->next)
- undo_elem_free(stack, uel);
-
- BLI_freelistN(&stack->elems);
- stack->current = NULL;
-}
-
-/* Exported Functions */
-
-void ED_undo_paint_push_begin(int type, const char *name, UndoRestoreCb restore, UndoFreeCb free, UndoCleanupCb cleanup)
-{
- if (type == UNDO_PAINT_IMAGE)
- undo_stack_push_begin(&ImageUndoStack, name, restore, free, cleanup);
- else if (type == UNDO_PAINT_MESH)
- undo_stack_push_begin(&MeshUndoStack, name, restore, free, cleanup);
-}
-
-ListBase *undo_paint_push_get_list(int type)
-{
- if (type == UNDO_PAINT_IMAGE) {
- if (ImageUndoStack.current) {
- return &ImageUndoStack.current->elems;
- }
- }
- else if (type == UNDO_PAINT_MESH) {
- if (MeshUndoStack.current) {
- return &MeshUndoStack.current->elems;
- }
- }
-
- return NULL;
-}
-
-void undo_paint_push_count_alloc(int type, int size)
-{
- if (type == UNDO_PAINT_IMAGE)
- ImageUndoStack.current->undosize += size;
- else if (type == UNDO_PAINT_MESH)
- MeshUndoStack.current->undosize += size;
-}
-
-void ED_undo_paint_push_end(int type)
-{
- if (type == UNDO_PAINT_IMAGE)
- undo_stack_push_end(&ImageUndoStack);
- else if (type == UNDO_PAINT_MESH)
- undo_stack_push_end(&MeshUndoStack);
-}
-
-int ED_undo_paint_step(bContext *C, int type, int step, const char *name)
-{
- if (type == UNDO_PAINT_IMAGE)
- return undo_stack_step(C, &ImageUndoStack, step, name);
- else if (type == UNDO_PAINT_MESH)
- return undo_stack_step(C, &MeshUndoStack, step, name);
-
- return 0;
-}
-
-static void undo_step_num(bContext *C, UndoStack *stack, int step)
-{
- UndoElem *uel;
- int a = 0;
- int curnum = BLI_findindex(&stack->elems, stack->current);
-
- for (uel = stack->elems.first; uel; uel = uel->next, a++) {
- if (a == step) break;
- }
-
- if (curnum > a) {
- while (a++ != curnum)
- undo_stack_step(C, stack, 1, NULL);
- }
- else if (curnum < a) {
- while (a-- != curnum)
- undo_stack_step(C, stack, -1, NULL);
- }
-}
-
-void ED_undo_paint_step_num(bContext *C, int type, int step)
-{
- if (type == UNDO_PAINT_IMAGE)
- undo_step_num(C, &ImageUndoStack, step);
- else if (type == UNDO_PAINT_MESH)
- undo_step_num(C, &MeshUndoStack, step);
-}
-
-static char *undo_stack_get_name(UndoStack *stack, int nr, bool *r_active)
-{
- UndoElem *uel;
-
- if (r_active) *r_active = false;
-
- uel = BLI_findlink(&stack->elems, nr);
- if (uel) {
- if (r_active && (uel == stack->current)) {
- *r_active = true;
- }
- return uel->name;
- }
-
- return NULL;
-}
-
-const char *ED_undo_paint_get_name(bContext *C, int type, int nr, bool *r_active)
-{
-
- if (type == UNDO_PAINT_IMAGE) {
- undo_stack_cleanup(&ImageUndoStack, C);
- return undo_stack_get_name(&ImageUndoStack, nr, r_active);
- }
- else if (type == UNDO_PAINT_MESH) {
- undo_stack_cleanup(&MeshUndoStack, C);
- return undo_stack_get_name(&MeshUndoStack, nr, r_active);
- }
- return NULL;
-}
-
-bool ED_undo_paint_empty(int type)
-{
- UndoStack *stack;
-
- if (type == UNDO_PAINT_IMAGE)
- stack = &ImageUndoStack;
- else if (type == UNDO_PAINT_MESH)
- stack = &MeshUndoStack;
- else
- return true;
-
- if (stack->current == NULL) {
- return true;
- }
-
- return false;
-}
-
-bool ED_undo_paint_is_valid(int type, const char *name)
-{
- UndoStack *stack;
-
- if (type == UNDO_PAINT_IMAGE)
- stack = &ImageUndoStack;
- else if (type == UNDO_PAINT_MESH)
- stack = &MeshUndoStack;
- else
- return 0;
-
- if (stack->current == NULL) {
- /* pass */
- }
- else {
- if (name && STREQ(stack->current->name, name))
- return 1;
- else
- return stack->elems.first != stack->elems.last;
- }
- return 0;
-}
-
-void ED_undo_paint_free(void)
-{
- undo_stack_free(&ImageUndoStack);
- undo_stack_free(&MeshUndoStack);
-}
diff --git a/source/blender/editors/sculpt_paint/paint_utils.c b/source/blender/editors/sculpt_paint/paint_utils.c
index 31c471c3517..70fd57830c0 100644
--- a/source/blender/editors/sculpt_paint/paint_utils.c
+++ b/source/blender/editors/sculpt_paint/paint_utils.c
@@ -171,7 +171,7 @@ float paint_calc_object_space_radius(ViewContext *vc, const float center[3],
return len_v3(delta) / scale;
}
-float paint_get_tex_pixel(MTex *mtex, float u, float v, struct ImagePool *pool, int thread)
+float paint_get_tex_pixel(const MTex *mtex, float u, float v, struct ImagePool *pool, int thread)
{
float intensity, rgba[4];
float co[3] = {u, v, 0.0f};
@@ -182,7 +182,7 @@ float paint_get_tex_pixel(MTex *mtex, float u, float v, struct ImagePool *pool,
return intensity;
}
-void paint_get_tex_pixel_col(MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert_to_linear, struct ColorSpace *colorspace)
+void paint_get_tex_pixel_col(const MTex *mtex, float u, float v, float rgba[4], struct ImagePool *pool, int thread, bool convert_to_linear, struct ColorSpace *colorspace)
{
float co[3] = {u, v, 0.0f};
int hasrgb;
@@ -210,14 +210,17 @@ void paint_get_tex_pixel_col(MTex *mtex, float u, float v, float rgba[4], struct
void paint_stroke_operator_properties(wmOperatorType *ot)
{
- static EnumPropertyItem stroke_mode_items[] = {
+ static const EnumPropertyItem stroke_mode_items[] = {
{BRUSH_STROKE_NORMAL, "NORMAL", 0, "Normal", "Apply brush normally"},
{BRUSH_STROKE_INVERT, "INVERT", 0, "Invert", "Invert action of brush for duration of stroke"},
{BRUSH_STROKE_SMOOTH, "SMOOTH", 0, "Smooth", "Switch brush to smooth mode for duration of stroke"},
{0}
};
- RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ PropertyRNA *prop;
+
+ prop = RNA_def_collection_runtime(ot->srna, "stroke", &RNA_OperatorStrokeElement, "Stroke", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
RNA_def_enum(ot->srna, "mode", stroke_mode_items, BRUSH_STROKE_NORMAL,
"Stroke Mode",
@@ -282,7 +285,7 @@ static void imapaint_pick_uv(Scene *scene, Object *ob, unsigned int faceindex, c
float p[2], w[3], absw, minabsw;
float matrix[4][4], proj[4][4];
GLint view[4];
- const ImagePaintMode mode = scene->toolsettings->imapaint.mode;
+ const eImagePaintMode mode = scene->toolsettings->imapaint.mode;
const MLoopTri *lt = dm->getLoopTriArray(dm);
const MPoly *mpoly = dm->getPolyArray(dm);
const MLoop *mloop = dm->getLoopArray(dm);
@@ -426,7 +429,7 @@ void paint_sample_color(bContext *C, ARegion *ar, int x, int y, bool texpaint_pr
Scene *scene = CTX_data_scene(C);
Paint *paint = BKE_paint_get_active_from_context(C);
Palette *palette = BKE_paint_palette(paint);
- PaletteColor *color;
+ PaletteColor *color = NULL;
Brush *br = BKE_paint_brush(BKE_paint_get_active_from_context(C));
unsigned int col;
const unsigned char *cp;
@@ -462,7 +465,7 @@ void paint_sample_color(bContext *C, ARegion *ar, int x, int y, bool texpaint_pr
unsigned int totpoly = me->totpoly;
if (dm->getLoopDataArray(dm, CD_MLOOPUV)) {
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
view3d_operator_needs_opengl(C);
@@ -578,7 +581,7 @@ static int brush_curve_preset_poll(bContext *C)
void BRUSH_OT_curve_preset(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_shape_items[] = {
+ static const EnumPropertyItem prop_shape_items[] = {
{CURVE_PRESET_SHARP, "SHARP", 0, "Sharp", ""},
{CURVE_PRESET_SMOOTH, "SMOOTH", 0, "Smooth", ""},
{CURVE_PRESET_MAX, "MAX", 0, "Max", ""},
@@ -746,10 +749,11 @@ void PAINT_OT_face_select_hide(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected objects");
}
-static int face_select_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int face_select_reveal_exec(bContext *C, wmOperator *op)
{
+ const bool select = RNA_boolean_get(op->ptr, "select");
Object *ob = CTX_data_active_object(C);
- paintface_reveal(ob);
+ paintface_reveal(ob, select);
ED_region_tag_redraw(CTX_wm_region(C));
return OPERATOR_FINISHED;
}
@@ -765,5 +769,5 @@ void PAINT_OT_face_select_reveal(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected objects");
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
diff --git a/source/blender/editors/sculpt_paint/paint_vertex.c b/source/blender/editors/sculpt_paint/paint_vertex.c
index 729dd9dc57b..4b2eb0fdd30 100644
--- a/source/blender/editors/sculpt_paint/paint_vertex.c
+++ b/source/blender/editors/sculpt_paint/paint_vertex.c
@@ -27,20 +27,20 @@
/** \file blender/editors/sculpt_paint/paint_vertex.c
* \ingroup edsculpt
+ *
+ * Used for vertex color & weight paint and mode switching.
+ *
+ * \note This file is already big,
+ * use `paint_vertex_color_ops.c` & `paint_vertex_weight_ops.c` for general purpose operators.
*/
#include "MEM_guardedalloc.h"
-#include "BLI_blenlib.h"
+#include "BLI_listbase.h"
+#include "BLI_rect.h"
#include "BLI_math.h"
#include "BLI_array_utils.h"
-#include "BLI_bitmap.h"
-#include "BLI_stack.h"
-#include "BLI_string_utils.h"
-
-#include "IMB_imbuf.h"
-#include "IMB_imbuf_types.h"
-#include "IMB_colormanagement.h"
+#include "BLI_task.h"
#include "DNA_armature_types.h"
#include "DNA_mesh_types.h"
@@ -51,39 +51,119 @@
#include "RNA_access.h"
#include "RNA_define.h"
-#include "RNA_enum_types.h"
-#include "BKE_DerivedMesh.h"
-#include "BKE_action.h"
#include "BKE_brush.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_deform.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
-#include "BKE_modifier.h"
#include "BKE_object_deform.h"
#include "BKE_paint.h"
#include "BKE_report.h"
-#include "BKE_colortools.h"
+#include "BKE_subsurf.h"
#include "WM_api.h"
#include "WM_types.h"
-#include "ED_armature.h"
#include "ED_object.h"
#include "ED_mesh.h"
#include "ED_screen.h"
#include "ED_view3d.h"
+#include "bmesh.h"
+#include "BKE_ccg.h"
+
+#include "sculpt_intern.h"
#include "paint_intern.h" /* own include */
-/* small structure to defer applying weight-paint results */
-struct WPaintDefer {
- int index;
- float alpha, weight;
+/* Use for 'blur' brush, align with PBVH nodes, created and freed on each update. */
+struct VPaintAverageAccum {
+ uint len;
+ uint value[3];
};
+struct WPaintAverageAccum {
+ uint len;
+ double value;
+};
+
+struct NormalAnglePrecalc {
+ bool do_mask_normal;
+ /* what angle to mask at */
+ float angle;
+ /* cos(angle), faster to compare */
+ float angle__cos;
+ float angle_inner;
+ float angle_inner__cos;
+ /* difference between angle and angle_inner, for easy access */
+ float angle_range;
+};
+
+
+static void view_angle_limits_init(
+ struct NormalAnglePrecalc *a, float angle, bool do_mask_normal)
+{
+ angle = RAD2DEGF(angle);
+ a->do_mask_normal = do_mask_normal;
+ if (do_mask_normal) {
+ a->angle_inner = angle;
+ a->angle = (a->angle_inner + 90.0f) * 0.5f;
+ }
+ else {
+ a->angle_inner = a->angle = angle;
+ }
+
+ a->angle_inner *= (float)(M_PI_2 / 90);
+ a->angle *= (float)(M_PI_2 / 90);
+ a->angle_range = a->angle - a->angle_inner;
+
+ if (a->angle_range <= 0.0f) {
+ a->do_mask_normal = false; /* no need to do blending */
+ }
+
+ a->angle__cos = cosf(a->angle);
+ a->angle_inner__cos = cosf(a->angle_inner);
+}
+
+static float view_angle_limits_apply_falloff(
+ const struct NormalAnglePrecalc *a, float angle_cos, float *mask_p)
+{
+ if (angle_cos <= a->angle__cos) {
+ /* outsize the normal limit */
+ return false;
+ }
+ else if (angle_cos < a->angle_inner__cos) {
+ *mask_p *= (a->angle - acosf(angle_cos)) / a->angle_range;
+ return true;
+ }
+ else {
+ return true;
+ }
+}
+
+static bool vwpaint_use_normal(const VPaint *vp)
+{
+ return ((vp->paint.brush->flag & BRUSH_FRONTFACE) != 0) ||
+ ((vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
+}
+
+static bool brush_use_accumulate(const Brush *brush)
+{
+ return (brush->flag & BRUSH_ACCUMULATE) != 0 || brush->vertexpaint_tool == PAINT_BLEND_SMEAR;
+}
+
+static MDeformVert *defweight_prev_init(MDeformVert *dvert_prev, MDeformVert *dvert_curr, int index)
+{
+ MDeformVert *dv_curr = &dvert_curr[index];
+ MDeformVert *dv_prev = &dvert_prev[index];
+ if (dv_prev->flag == 1) {
+ dv_prev->flag = 0;
+ defvert_copy(dv_prev, dv_curr);
+ }
+ return dv_prev;
+}
+
/* check if we can do partial updates and have them draw realtime
* (without rebuilding the 'derivedFinal') */
static bool vertex_paint_use_fast_update_check(Object *ob)
@@ -125,7 +205,7 @@ int vertex_paint_mode_poll(bContext *C)
int vertex_paint_poll(bContext *C)
{
- if (vertex_paint_mode_poll(C) &&
+ if (vertex_paint_mode_poll(C) &&
BKE_paint_brush(&CTX_data_tool_settings(C)->vpaint->paint))
{
ScrArea *sa = CTX_wm_area(C);
@@ -164,639 +244,47 @@ int weight_paint_poll(bContext *C)
return 0;
}
-static VPaint *new_vpaint(int wpaint)
+static VPaint *new_vpaint(void)
{
VPaint *vp = MEM_callocN(sizeof(VPaint), "VPaint");
-
- vp->flag = (wpaint) ? 0 : VP_SPRAY;
+
vp->paint.flags |= PAINT_SHOW_BRUSH;
return vp;
}
-static int *get_indexarray(Mesh *me)
-{
- return MEM_mallocN(sizeof(int) * (me->totpoly + 1), "vertexpaint");
-}
-
-unsigned int vpaint_get_current_col(Scene *scene, VPaint *vp)
+uint vpaint_get_current_col(Scene *scene, VPaint *vp)
{
Brush *brush = BKE_paint_brush(&vp->paint);
- unsigned char col[4];
+ uchar col[4];
rgb_float_to_uchar(col, BKE_brush_color_get(scene, brush));
col[3] = 255; /* alpha isn't used, could even be removed to speedup paint a little */
- return *(unsigned int *)col;
-}
-
-static void do_shared_vertexcol(Mesh *me, bool *mlooptag)
-{
- const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
- MPoly *mp;
- int (*scol)[4];
- int i, j;
- bool has_shared = false;
-
- /* if no mloopcol: do not do */
- /* if mtexpoly: only the involved faces, otherwise all */
-
- if (me->mloopcol == NULL || me->totvert == 0 || me->totpoly == 0) return;
-
- scol = MEM_callocN(sizeof(int) * me->totvert * 5, "scol");
-
- for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
- if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
- MLoop *ml = me->mloop + mp->loopstart;
- MLoopCol *lcol = me->mloopcol + mp->loopstart;
- for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
- scol[ml->v][0] += lcol->r;
- scol[ml->v][1] += lcol->g;
- scol[ml->v][2] += lcol->b;
- scol[ml->v][3] += 1;
- has_shared = 1;
- }
- }
- }
-
- if (has_shared) {
- for (i = 0; i < me->totvert; i++) {
- if (scol[i][3] != 0) {
- scol[i][0] = divide_round_i(scol[i][0], scol[i][3]);
- scol[i][1] = divide_round_i(scol[i][1], scol[i][3]);
- scol[i][2] = divide_round_i(scol[i][2], scol[i][3]);
- }
- }
-
- for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
- if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
- MLoop *ml = me->mloop + mp->loopstart;
- MLoopCol *lcol = me->mloopcol + mp->loopstart;
- for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
- if (mlooptag[mp->loopstart + j]) {
- lcol->r = scol[ml->v][0];
- lcol->g = scol[ml->v][1];
- lcol->b = scol[ml->v][2];
- }
- }
- }
- }
- }
-
- MEM_freeN(scol);
-}
-
-static bool make_vertexcol(Object *ob) /* single ob */
-{
- Mesh *me;
-
- if (ID_IS_LINKED_DATABLOCK(ob) ||
- ((me = BKE_mesh_from_object(ob)) == NULL) ||
- (me->totpoly == 0) ||
- (me->edit_btmesh))
- {
- return false;
- }
-
- /* copies from shadedisplist to mcol */
- if (!me->mloopcol && me->totloop) {
- CustomData_add_layer(&me->ldata, CD_MLOOPCOL, CD_DEFAULT, NULL, me->totloop);
- BKE_mesh_update_customdata_pointers(me, true);
- }
-
- DAG_id_tag_update(&me->id, 0);
-
- return (me->mloopcol != NULL);
-}
-
-/* mirror_vgroup is set to -1 when invalid */
-static int wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
-{
- bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
-
- if (defgroup) {
- int mirrdef;
- char name_flip[MAXBONENAME];
-
- BLI_string_flip_side_name(name_flip, defgroup->name, false, sizeof(name_flip));
- mirrdef = defgroup_name_index(ob, name_flip);
- if (mirrdef == -1) {
- if (BKE_defgroup_new(ob, name_flip)) {
- mirrdef = BLI_listbase_count(&ob->defbase) - 1;
- }
- }
-
- /* curdef should never be NULL unless this is
- * a lamp and BKE_object_defgroup_add_name fails */
- return mirrdef;
- }
-
- return -1;
-}
-
-static void free_vpaint_prev(VPaint *vp)
-{
- if (vp->vpaint_prev) {
- MEM_freeN(vp->vpaint_prev);
- vp->vpaint_prev = NULL;
- vp->tot = 0;
- }
-}
-
-static void free_wpaint_prev(VPaint *vp)
-{
- if (vp->wpaint_prev) {
- BKE_defvert_array_free(vp->wpaint_prev, vp->tot);
- vp->wpaint_prev = NULL;
- vp->tot = 0;
- }
-}
-
-static void copy_vpaint_prev(VPaint *vp, unsigned int *lcol, int tot)
-{
- free_vpaint_prev(vp);
-
- vp->tot = tot;
-
- if (lcol == NULL || tot == 0) return;
-
- vp->vpaint_prev = MEM_mallocN(sizeof(int) * tot, "vpaint_prev");
- memcpy(vp->vpaint_prev, lcol, sizeof(int) * tot);
-
-}
-
-static void copy_wpaint_prev(VPaint *wp, MDeformVert *dverts, int dcount)
-{
- free_wpaint_prev(wp);
-
- if (dverts && dcount) {
-
- wp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
- wp->tot = dcount;
- BKE_defvert_array_copy(wp->wpaint_prev, dverts, dcount);
- }
-}
-
-bool ED_vpaint_fill(Object *ob, unsigned int paintcol)
-{
- Mesh *me;
- MPoly *mp;
- int i, j;
- bool selected;
-
- if (((me = BKE_mesh_from_object(ob)) == NULL) ||
- (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
- {
- return false;
- }
-
- selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
-
- mp = me->mpoly;
- for (i = 0; i < me->totpoly; i++, mp++) {
- MLoopCol *lcol = me->mloopcol + mp->loopstart;
-
- if (selected && !(mp->flag & ME_FACE_SEL))
- continue;
-
- for (j = 0; j < mp->totloop; j++, lcol++) {
- *(int *)lcol = paintcol;
- }
- }
-
- /* remove stale me->mcol, will be added later */
- BKE_mesh_tessface_clear(me);
-
- DAG_id_tag_update(&me->id, 0);
-
- return true;
-}
-
-
-/* fills in the selected faces with the current weight and vertex group */
-bool ED_wpaint_fill(VPaint *wp, Object *ob, float paintweight)
-{
- Mesh *me = ob->data;
- MPoly *mp;
- MDeformWeight *dw, *dw_prev;
- int vgroup_active, vgroup_mirror = -1;
- unsigned int index;
- const bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
-
- /* mutually exclusive, could be made into a */
- const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
-
- if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) {
- return false;
- }
-
- vgroup_active = ob->actdef - 1;
-
- /* if mirror painting, find the other group */
- if (me->editflag & ME_EDIT_MIRROR_X) {
- vgroup_mirror = wpaint_mirror_vgroup_ensure(ob, vgroup_active);
- }
-
- copy_wpaint_prev(wp, me->dvert, me->totvert);
-
- for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
- unsigned int fidx = mp->totloop - 1;
-
- if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
- continue;
- }
-
- do {
- unsigned int vidx = me->mloop[mp->loopstart + fidx].v;
-
- if (!me->dvert[vidx].flag) {
- if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
- continue;
- }
-
- dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
- if (dw) {
- dw_prev = defvert_verify_index(wp->wpaint_prev + vidx, vgroup_active);
- dw_prev->weight = dw->weight; /* set the undo weight */
- dw->weight = paintweight;
-
- if (me->editflag & ME_EDIT_MIRROR_X) { /* x mirror painting */
- int j = mesh_get_x_mirror_vert(ob, NULL, vidx, topology);
- if (j >= 0) {
- /* copy, not paint again */
- if (vgroup_mirror != -1) {
- dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
- dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_mirror);
- }
- else {
- dw = defvert_verify_index(me->dvert + j, vgroup_active);
- dw_prev = defvert_verify_index(wp->wpaint_prev + j, vgroup_active);
- }
- dw_prev->weight = dw->weight; /* set the undo weight */
- dw->weight = paintweight;
- }
- }
- }
- me->dvert[vidx].flag = 1;
- }
-
- } while (fidx--);
- }
-
- {
- MDeformVert *dv = me->dvert;
- for (index = me->totvert; index != 0; index--, dv++) {
- dv->flag = 0;
- }
- }
-
- copy_wpaint_prev(wp, NULL, 0);
-
- DAG_id_tag_update(&me->id, 0);
-
- return true;
-}
-
-bool ED_vpaint_smooth(Object *ob)
-{
- Mesh *me;
- MPoly *mp;
-
- int i, j;
-
- bool *mlooptag;
- bool selected;
-
- if (((me = BKE_mesh_from_object(ob)) == NULL) ||
- (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
- {
- return false;
- }
-
- selected = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
-
- mlooptag = MEM_callocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
-
- /* simply tag loops of selected faces */
- mp = me->mpoly;
- for (i = 0; i < me->totpoly; i++, mp++) {
- MLoop *ml = me->mloop + mp->loopstart;
- int ml_index = mp->loopstart;
-
- if (selected && !(mp->flag & ME_FACE_SEL))
- continue;
-
- for (j = 0; j < mp->totloop; j++, ml_index++, ml++) {
- mlooptag[ml_index] = true;
- }
- }
-
- /* remove stale me->mcol, will be added later */
- BKE_mesh_tessface_clear(me);
-
- do_shared_vertexcol(me, mlooptag);
-
- MEM_freeN(mlooptag);
-
- DAG_id_tag_update(&me->id, 0);
-
- return true;
-}
-
-/**
- * Apply callback to each vertex of the active vertex color layer.
- */
-bool ED_vpaint_color_transform(
- struct Object *ob,
- VPaintTransform_Callback vpaint_tx_fn,
- const void *user_data)
-{
- Mesh *me;
- const MPoly *mp;
-
- if (((me = BKE_mesh_from_object(ob)) == NULL) ||
- (me->mloopcol == NULL && (make_vertexcol(ob) == false)))
- {
- return false;
- }
-
- const bool do_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
- mp = me->mpoly;
-
- for (int i = 0; i < me->totpoly; i++, mp++) {
- MLoopCol *lcol = &me->mloopcol[mp->loopstart];
-
- if (do_face_sel && !(mp->flag & ME_FACE_SEL)) {
- continue;
- }
-
- for (int j = 0; j < mp->totloop; j++, lcol++) {
- float col[3];
- rgb_uchar_to_float(col, &lcol->r);
-
- vpaint_tx_fn(col, user_data, col);
-
- rgb_float_to_uchar(&lcol->r, col);
- }
- }
-
- /* remove stale me->mcol, will be added later */
- BKE_mesh_tessface_clear(me);
-
- DAG_id_tag_update(&me->id, 0);
-
- return true;
-}
-
-/* XXX: should be re-implemented as a vertex/weight paint 'color correct' operator */
-#if 0
-void vpaint_dogamma(Scene *scene)
-{
- VPaint *vp = scene->toolsettings->vpaint;
- Mesh *me;
- Object *ob;
- float igam, fac;
- int a, temp;
- unsigned char *cp, gamtab[256];
-
- ob = OBACT;
- me = BKE_mesh_from_object(ob);
-
- if (!(ob->mode & OB_MODE_VERTEX_PAINT)) return;
- if (me == 0 || me->mcol == 0 || me->totface == 0) return;
-
- igam = 1.0 / vp->gamma;
- for (a = 0; a < 256; a++) {
-
- fac = ((float)a) / 255.0;
- fac = vp->mul * pow(fac, igam);
-
- temp = 255.9 * fac;
-
- if (temp <= 0) gamtab[a] = 0;
- else if (temp >= 255) gamtab[a] = 255;
- else gamtab[a] = temp;
- }
-
- a = 4 * me->totface;
- cp = (unsigned char *)me->mcol;
- while (a--) {
-
- cp[1] = gamtab[cp[1]];
- cp[2] = gamtab[cp[2]];
- cp[3] = gamtab[cp[3]];
-
- cp += 4;
- }
-}
-#endif
-
-BLI_INLINE unsigned int mcol_blend(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int mfac;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
-
- if (fac >= 255) {
- return col2;
- }
-
- mfac = 255 - fac;
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
- cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
- cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
- cp[3] = 255;
-
- return col;
-}
-
-BLI_INLINE unsigned int mcol_add(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int temp;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- temp = cp1[0] + divide_round_i((fac * cp2[0]), 255);
- cp[0] = (temp > 254) ? 255 : temp;
- temp = cp1[1] + divide_round_i((fac * cp2[1]), 255);
- cp[1] = (temp > 254) ? 255 : temp;
- temp = cp1[2] + divide_round_i((fac * cp2[2]), 255);
- cp[2] = (temp > 254) ? 255 : temp;
- cp[3] = 255;
-
- return col;
-}
-
-BLI_INLINE unsigned int mcol_sub(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int temp;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- temp = cp1[0] - divide_round_i((fac * cp2[0]), 255);
- cp[0] = (temp < 0) ? 0 : temp;
- temp = cp1[1] - divide_round_i((fac * cp2[1]), 255);
- cp[1] = (temp < 0) ? 0 : temp;
- temp = cp1[2] - divide_round_i((fac * cp2[2]), 255);
- cp[2] = (temp < 0) ? 0 : temp;
- cp[3] = 255;
-
- return col;
-}
-
-BLI_INLINE unsigned int mcol_mul(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int mfac;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
-
- mfac = 255 - fac;
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- /* first mul, then blend the fac */
- cp[0] = divide_round_i(mfac * cp1[0] * 255 + fac * cp2[0] * cp1[0], 255 * 255);
- cp[1] = divide_round_i(mfac * cp1[1] * 255 + fac * cp2[1] * cp1[1], 255 * 255);
- cp[2] = divide_round_i(mfac * cp1[2] * 255 + fac * cp2[2] * cp1[2], 255 * 255);
- cp[3] = 255;
-
- return col;
-}
-
-BLI_INLINE unsigned int mcol_lighten(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int mfac;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
- else if (fac >= 255) {
- return col2;
- }
-
- mfac = 255 - fac;
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- /* See if are lighter, if so mix, else don't do anything.
- * if the paint col is darker then the original, then ignore */
- if (IMB_colormanagement_get_luminance_byte(cp1) > IMB_colormanagement_get_luminance_byte(cp2)) {
- return col1;
- }
-
- cp[0] = divide_round_i(mfac * cp1[0] + fac * cp2[0], 255);
- cp[1] = divide_round_i(mfac * cp1[1] + fac * cp2[1], 255);
- cp[2] = divide_round_i(mfac * cp1[2] + fac * cp2[2], 255);
- cp[3] = 255;
-
- return col;
-}
-
-BLI_INLINE unsigned int mcol_darken(unsigned int col1, unsigned int col2, int fac)
-{
- unsigned char *cp1, *cp2, *cp;
- int mfac;
- unsigned int col = 0;
-
- if (fac == 0) {
- return col1;
- }
- else if (fac >= 255) {
- return col2;
- }
-
- mfac = 255 - fac;
-
- cp1 = (unsigned char *)&col1;
- cp2 = (unsigned char *)&col2;
- cp = (unsigned char *)&col;
-
- /* See if were darker, if so mix, else don't do anything.
- * if the paint col is brighter then the original, then ignore */
- if (IMB_colormanagement_get_luminance_byte(cp1) < IMB_colormanagement_get_luminance_byte(cp2)) {
- return col1;
- }
-
- cp[0] = divide_round_i((mfac * cp1[0] + fac * cp2[0]), 255);
- cp[1] = divide_round_i((mfac * cp1[1] + fac * cp2[1]), 255);
- cp[2] = divide_round_i((mfac * cp1[2] + fac * cp2[2]), 255);
- cp[3] = 255;
- return col;
-}
-
-/* wpaint has 'wpaint_blend_tool' */
-static unsigned int vpaint_blend_tool(const int tool, const unsigned int col,
- const unsigned int paintcol, const int alpha_i)
-{
- switch (tool) {
- case PAINT_BLEND_MIX:
- case PAINT_BLEND_BLUR: return mcol_blend(col, paintcol, alpha_i);
- case PAINT_BLEND_ADD: return mcol_add(col, paintcol, alpha_i);
- case PAINT_BLEND_SUB: return mcol_sub(col, paintcol, alpha_i);
- case PAINT_BLEND_MUL: return mcol_mul(col, paintcol, alpha_i);
- case PAINT_BLEND_LIGHTEN: return mcol_lighten(col, paintcol, alpha_i);
- case PAINT_BLEND_DARKEN: return mcol_darken(col, paintcol, alpha_i);
- default:
- BLI_assert(0);
- return 0;
- }
+ return *(uint *)col;
}
/* wpaint has 'wpaint_blend' */
-static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colorig, const
- unsigned int paintcol, const int alpha_i,
- /* pre scaled from [0-1] --> [0-255] */
- const int brush_alpha_value_i)
+static uint vpaint_blend(
+ const VPaint *vp, uint color_curr, uint color_orig,
+ uint color_paint, const int alpha_i,
+ /* pre scaled from [0-1] --> [0-255] */
+ const int brush_alpha_value_i)
{
- Brush *brush = BKE_paint_brush(&vp->paint);
+ const Brush *brush = vp->paint.brush;
const int tool = brush->vertexpaint_tool;
- col = vpaint_blend_tool(tool, col, paintcol, alpha_i);
+ uint color_blend = ED_vpaint_blend_tool(tool, color_curr, color_paint, alpha_i);
- /* if no spray, clip color adding with colorig & orig alpha */
- if ((vp->flag & VP_SPRAY) == 0) {
- unsigned int testcol, a;
+ /* if no accumulate, clip color adding with colorig & orig alpha */
+ if (!brush_use_accumulate(brush)) {
+ uint color_test, a;
char *cp, *ct, *co;
-
- testcol = vpaint_blend_tool(tool, colorig, paintcol, brush_alpha_value_i);
-
- cp = (char *)&col;
- ct = (char *)&testcol;
- co = (char *)&colorig;
-
+
+ color_test = ED_vpaint_blend_tool(tool, color_orig, color_paint, brush_alpha_value_i);
+
+ cp = (char *)&color_blend;
+ ct = (char *)&color_test;
+ co = (char *)&color_orig;
+
for (a = 0; a < 4; a++) {
if (ct[a] < co[a]) {
if (cp[a] < ct[a]) cp[a] = ct[a];
@@ -809,176 +297,51 @@ static unsigned int vpaint_blend(VPaint *vp, unsigned int col, unsigned int colo
}
}
- return col;
-}
-
-
-static int sample_backbuf_area(ViewContext *vc, int *indexar, int totpoly, int x, int y, float size)
-{
- struct ImBuf *ibuf;
- int a, tot = 0, index;
-
- /* brecht: disabled this because it obviously fails for
- * brushes with size > 64, why is this here? */
- /*if (size > 64.0) size = 64.0;*/
-
- ibuf = ED_view3d_backbuf_read(vc, x - size, y - size, x + size, y + size);
- if (ibuf) {
- unsigned int *rt = ibuf->rect;
-
- memset(indexar, 0, sizeof(int) * (totpoly + 1));
-
- size = ibuf->x * ibuf->y;
- while (size--) {
-
- if (*rt) {
- index = *rt;
- if (index > 0 && index <= totpoly) {
- indexar[index] = 1;
- }
- }
-
- rt++;
- }
-
- for (a = 1; a <= totpoly; a++) {
- if (indexar[a]) {
- indexar[tot++] = a;
- }
- }
-
- IMB_freeImBuf(ibuf);
- }
-
- return tot;
-}
-
-/* whats _dl mean? */
-static float calc_vp_strength_col_dl(VPaint *vp, ViewContext *vc, const float co[3],
- const float mval[2], const float brush_size_pressure, float rgba[4])
-{
- float co_ss[2]; /* screenspace */
-
- if (ED_view3d_project_float_object(vc->ar,
- co, co_ss,
- V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ if ((brush->flag & BRUSH_LOCK_ALPHA) &&
+ !ELEM(tool, PAINT_BLEND_ALPHA_SUB, PAINT_BLEND_ALPHA_ADD))
{
- const float dist_sq = len_squared_v2v2(mval, co_ss);
-
- if (dist_sq <= SQUARE(brush_size_pressure)) {
- Brush *brush = BKE_paint_brush(&vp->paint);
- const float dist = sqrtf(dist_sq);
- float factor;
-
- if (brush->mtex.tex && rgba) {
- if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
- BKE_brush_sample_tex_3D(vc->scene, brush, co, rgba, 0, NULL);
- }
- else {
- const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f}; /* we need a 3rd empty value */
- BKE_brush_sample_tex_3D(vc->scene, brush, co_ss_3d, rgba, 0, NULL);
- }
- factor = rgba[3];
- }
- else {
- factor = 1.0f;
- }
- return factor * BKE_brush_curve_strength_clamped(brush, dist, brush_size_pressure);
- }
+ char *cp, *cc;
+ cp = (char *)&color_blend;
+ cc = (char *)&color_curr;
+ cp[3] = cc[3];
}
- if (rgba)
- zero_v4(rgba);
- return 0.0f;
-}
-
-static float calc_vp_alpha_col_dl(VPaint *vp, ViewContext *vc,
- float vpimat[3][3], const DMCoNo *v_co_no,
- const float mval[2],
- const float brush_size_pressure, const float brush_alpha_pressure, float rgba[4])
-{
- float strength = calc_vp_strength_col_dl(vp, vc, v_co_no->co, mval, brush_size_pressure, rgba);
- if (strength > 0.0f) {
- float alpha = brush_alpha_pressure * strength;
-
- if (vp->flag & VP_NORMALS) {
- float dvec[3];
-
- /* transpose ! */
- dvec[2] = dot_v3v3(vpimat[2], v_co_no->no);
- if (dvec[2] > 0.0f) {
- dvec[0] = dot_v3v3(vpimat[0], v_co_no->no);
- dvec[1] = dot_v3v3(vpimat[1], v_co_no->no);
-
- alpha *= dvec[2] / len_v3(dvec);
- }
- else {
- return 0.0f;
- }
- }
-
- return alpha;
- }
-
- return 0.0f;
-}
-
-
-BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
-{
- const float talpha = min_ff(alpha, 1.0f); /* blending with values over 1 doesn't make sense */
- return (paintval * talpha) + (weight * (1.0f - talpha));
-}
-BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
-{
- return weight + (paintval * alpha);
-}
-BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
-{
- return weight - (paintval * alpha);
-}
-BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
-{ /* first mul, then blend the fac */
- return ((1.0f - alpha) + (alpha * paintval)) * weight;
-}
-BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
-{
- return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
-}
-BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
-{
- return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
+ return color_blend;
}
-
-/* vpaint has 'vpaint_blend_tool' */
-/* result is not clamped from [0-1] */
-static float wpaint_blend_tool(const int tool,
- /* dw->weight */
- const float weight,
- const float paintval, const float alpha)
+static void tex_color_alpha(
+ VPaint *vp, const ViewContext *vc, const float co[3],
+ float r_rgba[4])
{
- switch (tool) {
- case PAINT_BLEND_MIX:
- case PAINT_BLEND_BLUR: return wval_blend(weight, paintval, alpha);
- case PAINT_BLEND_ADD: return wval_add(weight, paintval, alpha);
- case PAINT_BLEND_SUB: return wval_sub(weight, paintval, alpha);
- case PAINT_BLEND_MUL: return wval_mul(weight, paintval, alpha);
- case PAINT_BLEND_LIGHTEN: return wval_lighten(weight, paintval, alpha);
- case PAINT_BLEND_DARKEN: return wval_darken(weight, paintval, alpha);
- default:
- BLI_assert(0);
- return 0.0f;
+ const Brush *brush = BKE_paint_brush(&vp->paint);
+ BLI_assert(brush->mtex.tex != NULL);
+ if (brush->mtex.brush_map_mode == MTEX_MAP_MODE_3D) {
+ BKE_brush_sample_tex_3D(vc->scene, brush, co, r_rgba, 0, NULL);
+ }
+ else {
+ float co_ss[2]; /* screenspace */
+ if (ED_view3d_project_float_object(
+ vc->ar,
+ co, co_ss,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ {
+ const float co_ss_3d[3] = {co_ss[0], co_ss[1], 0.0f}; /* we need a 3rd empty value */
+ BKE_brush_sample_tex_3D(vc->scene, brush, co_ss_3d, r_rgba, 0, NULL);
+ }
+ else {
+ zero_v4(r_rgba);
+ }
}
}
/* vpaint has 'vpaint_blend' */
-static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
- const float alpha, float paintval,
- const float brush_alpha_value,
- const short do_flip)
+static float wpaint_blend(
+ const VPaint *wp, float weight,
+ const float alpha, float paintval,
+ const float UNUSED(brush_alpha_value),
+ const short do_flip)
{
- Brush *brush = BKE_paint_brush(&wp->paint);
+ const Brush *brush = wp->paint.brush;
int tool = brush->vertexpaint_tool;
if (do_flip) {
@@ -995,257 +358,30 @@ static float wpaint_blend(VPaint *wp, float weight, float weight_prev,
tool = PAINT_BLEND_LIGHTEN; break;
}
}
-
- weight = wpaint_blend_tool(tool, weight, paintval, alpha);
- CLAMP(weight, 0.0f, 1.0f);
-
- /* if no spray, clip result with orig weight & orig alpha */
- if ((wp->flag & VP_SPRAY) == 0) {
- float testw = wpaint_blend_tool(tool, weight_prev, paintval, brush_alpha_value);
+ weight = ED_wpaint_blend_tool(tool, weight, paintval, alpha);
- CLAMP(testw, 0.0f, 1.0f);
- if (testw < weight_prev) {
- if (weight < testw) weight = testw;
- else if (weight > weight_prev) weight = weight_prev;
- }
- else {
- if (weight > testw) weight = testw;
- else if (weight < weight_prev) weight = weight_prev;
- }
- }
+ CLAMP(weight, 0.0f, 1.0f);
return weight;
}
-/* ----------------------------------------------------- */
-
-
-/* sets wp->weight to the closest weight value to vertex */
-/* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
-static int weight_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+static float wpaint_clamp_monotonic(float oldval, float curval, float newval)
{
- ViewContext vc;
- Mesh *me;
- bool changed = false;
-
- view3d_set_viewcontext(C, &vc);
- me = BKE_mesh_from_object(vc.obact);
-
- if (me && me->dvert && vc.v3d && vc.rv3d && (vc.obact->actdef != 0)) {
- const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
- int v_idx_best = -1;
- unsigned int index;
-
- view3d_operator_needs_opengl(C);
- ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
-
- if (use_vert_sel) {
- if (ED_mesh_pick_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
- v_idx_best = index;
- }
- }
- else {
- if (ED_mesh_pick_face_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
- v_idx_best = index;
- }
- else if (ED_mesh_pick_face(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
- /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
- BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
- }
- }
-
- if (v_idx_best != -1) { /* should always be valid */
- ToolSettings *ts = vc.scene->toolsettings;
- Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
- const int vgroup_active = vc.obact->actdef - 1;
- float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
-
- /* use combined weight in multipaint mode, since that's what is displayed to the user in the colors */
- if (ts->multipaint) {
- int defbase_tot_sel;
- const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
- bool *defbase_sel = BKE_object_defgroup_selected_get(vc.obact, defbase_tot, &defbase_tot_sel);
-
- if (defbase_tot_sel > 1) {
- if (me->editflag & ME_EDIT_MIRROR_X) {
- BKE_object_defgroup_mirror_selection(
- vc.obact, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
- }
-
- vgroup_weight = BKE_defvert_multipaint_collective_weight(
- &me->dvert[v_idx_best], defbase_tot, defbase_sel, defbase_tot_sel, ts->auto_normalize);
-
- /* if autonormalize is enabled, but weights are not normalized, the value can exceed 1 */
- CLAMP(vgroup_weight, 0.0f, 1.0f);
- }
-
- MEM_freeN(defbase_sel);
- }
-
- BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
- changed = true;
- }
- }
-
- if (changed) {
- /* not really correct since the brush didnt change, but redraws the toolbar */
- WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
-
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-void PAINT_OT_weight_sample(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Weight Paint Sample Weight";
- ot->idname = "PAINT_OT_weight_sample";
- ot->description = "Use the mouse to sample a weight in the 3D view";
-
- /* api callbacks */
- ot->invoke = weight_sample_invoke;
- ot->poll = weight_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_UNDO;
-}
-
-/* samples cursor location, and gives menu with vertex groups to activate */
-static bool weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
-{
- /* this func fills in used vgroup's */
- bool found = false;
- int i = dvert->totweight;
- MDeformWeight *dw;
- for (dw = dvert->dw; i > 0; dw++, i--) {
- if (dw->def_nr < defbase_tot) {
- groups[dw->def_nr] = true;
- found = true;
- }
- }
- return found;
-}
-static EnumPropertyItem *weight_paint_sample_enum_itemf(
- bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
-{
- if (C) {
- wmWindow *win = CTX_wm_window(C);
- if (win && win->eventstate) {
- ViewContext vc;
- Mesh *me;
-
- view3d_set_viewcontext(C, &vc);
- me = BKE_mesh_from_object(vc.obact);
-
- if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
- const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
- const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
- int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
- bool found = false;
- unsigned int index;
-
- const int mval[2] = {
- win->eventstate->x - vc.ar->winrct.xmin,
- win->eventstate->y - vc.ar->winrct.ymin,
- };
-
- view3d_operator_needs_opengl(C);
- ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
-
- if (use_vert_sel) {
- if (ED_mesh_pick_vert(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
- MDeformVert *dvert = &me->dvert[index];
- found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
- }
- }
- else {
- if (ED_mesh_pick_face(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
- MPoly *mp = &me->mpoly[index];
- unsigned int fidx = mp->totloop - 1;
-
- do {
- MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
- found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
- } while (fidx--);
- }
- }
-
- if (found == false) {
- MEM_freeN(groups);
- }
- else {
- EnumPropertyItem *item = NULL, item_tmp = {0};
- int totitem = 0;
- int i = 0;
- bDeformGroup *dg;
- for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
- if (groups[i]) {
- item_tmp.identifier = item_tmp.name = dg->name;
- item_tmp.value = i;
- RNA_enum_item_add(&item, &totitem, &item_tmp);
- }
- }
-
- RNA_enum_item_end(&item, &totitem);
- *r_free = true;
-
- MEM_freeN(groups);
- return item;
- }
- }
- }
- }
-
- return DummyRNA_NULL_items;
+ if (newval < oldval)
+ return MIN2(newval, curval);
+ else if (newval > oldval)
+ return MAX2(newval, curval);
+ else
+ return newval;
}
-static int weight_sample_group_exec(bContext *C, wmOperator *op)
-{
- int type = RNA_enum_get(op->ptr, "group");
- ViewContext vc;
- view3d_set_viewcontext(C, &vc);
-
- BLI_assert(type + 1 >= 0);
- vc.obact->actdef = type + 1;
-
- DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
- return OPERATOR_FINISHED;
-}
-
-/* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
-void PAINT_OT_weight_sample_group(wmOperatorType *ot)
-{
- PropertyRNA *prop = NULL;
-
- /* identifiers */
- ot->name = "Weight Paint Sample Group";
- ot->idname = "PAINT_OT_weight_sample_group";
- ot->description = "Select one of the vertex groups available under current mouse position";
-
- /* api callbacks */
- ot->exec = weight_sample_group_exec;
- ot->invoke = WM_menu_invoke;
- ot->poll = weight_paint_mode_poll;
-
- /* flags */
- ot->flag = OPTYPE_UNDO;
-
- /* keyingset to use (dynamic enum) */
- prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
- RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
- RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
- ot->prop = prop;
-}
+/* ----------------------------------------------------- */
static void do_weight_paint_normalize_all(MDeformVert *dvert, const int defbase_tot, const bool *vgroup_validmap)
{
float sum = 0.0f, fac;
- unsigned int i, tot = 0;
+ uint i, tot = 0;
MDeformWeight *dw;
for (i = dvert->totweight, dw = dvert->dw; i != 0; i--, dw++) {
@@ -1291,7 +427,7 @@ static bool do_weight_paint_normalize_all_locked(
float sum = 0.0f, fac;
float sum_unlock = 0.0f;
float lock_weight = 0.0f;
- unsigned int i, tot = 0;
+ uint i, tot = 0;
MDeformWeight *dw;
if (lock_flags == NULL) {
@@ -1391,8 +527,9 @@ static void do_weight_paint_normalize_all_locked_try_active(
}
#if 0 /* UNUSED */
-static bool has_unselected_unlocked_bone_group(int defbase_tot, bool *defbase_sel, int selected,
- const bool *lock_flags, const bool *vgroup_validmap)
+static bool has_unselected_unlocked_bone_group(
+ int defbase_tot, bool *defbase_sel, int selected,
+ const bool *lock_flags, const bool *vgroup_validmap)
{
int i;
if (defbase_tot == selected) {
@@ -1476,7 +613,7 @@ static void multipaint_apply_change(MDeformVert *dvert, const int defbase_tot, f
* Variables stored both for 'active' and 'mirror' sides.
*/
struct WeightPaintGroupData {
- /** index of active group or its mirror
+ /** index of active group or its mirror
*
* - 'active' is always `ob->actdef`.
* - 'mirror' is -1 when 'ME_EDIT_MIRROR_X' flag id disabled,
@@ -1505,13 +642,15 @@ typedef struct WeightPaintInfo {
struct WeightPaintGroupData active, mirror;
- const bool *lock_flags; /* boolean array for locked bones,
- * length of defbase_tot */
- const bool *defbase_sel; /* boolean array for selected bones,
- * length of defbase_tot, cant be const because of how its passed */
-
- const bool *vgroup_validmap; /* same as WeightPaintData.vgroup_validmap,
- * only added here for convenience */
+ /* boolean array for locked bones,
+ * length of defbase_tot */
+ const bool *lock_flags;
+ /* boolean array for selected bones,
+ * length of defbase_tot, cant be const because of how its passed */
+ const bool *defbase_sel;
+ /* same as WeightPaintData.vgroup_validmap,
+ * only added here for convenience */
+ const bool *vgroup_validmap;
bool do_flip;
bool do_multipaint;
@@ -1522,16 +661,16 @@ typedef struct WeightPaintInfo {
static void do_weight_paint_vertex_single(
/* vars which remain the same for every vert */
- VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
+ const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
/* vars which change on each stroke */
- const unsigned int index, float alpha, float paintweight
- )
+ const uint index, float alpha, float paintweight)
{
Mesh *me = ob->data;
MDeformVert *dv = &me->dvert[index];
bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
-
- MDeformWeight *dw, *dw_prev;
+
+ MDeformWeight *dw;
+ float weight_prev;
/* mirror vars */
int index_mirr;
@@ -1540,20 +679,6 @@ static void do_weight_paint_vertex_single(
MDeformVert *dv_mirr;
MDeformWeight *dw_mirr;
- if (wp->flag & VP_ONLYVGROUP) {
- dw = defvert_find_index(dv, wpi->active.index);
- dw_prev = defvert_find_index(wp->wpaint_prev + index, wpi->active.index);
- }
- else {
- dw = defvert_verify_index(dv, wpi->active.index);
- dw_prev = defvert_verify_index(wp->wpaint_prev + index, wpi->active.index);
- }
-
- if (dw == NULL || dw_prev == NULL) {
- return;
- }
-
-
/* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
if (me->editflag & ME_EDIT_MIRROR_X) {
index_mirr = mesh_get_x_mirror_vert(ob, NULL, index, topology);
@@ -1569,11 +694,21 @@ static void do_weight_paint_vertex_single(
index_mirr = vgroup_mirr = -1;
}
+ if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
+ dw = defvert_find_index(dv, wpi->active.index);
+ }
+ else {
+ dw = defvert_verify_index(dv, wpi->active.index);
+ }
+
+ if (dw == NULL) {
+ return;
+ }
/* get the mirror def vars */
if (index_mirr != -1) {
dv_mirr = &me->dvert[index_mirr];
- if (wp->flag & VP_ONLYVGROUP) {
+ if (wp->flag & VP_FLAG_VGROUP_RESTRICT) {
dw_mirr = defvert_find_index(dv_mirr, vgroup_mirr);
if (dw_mirr == NULL) {
@@ -1603,12 +738,28 @@ static void do_weight_paint_vertex_single(
dw_mirr = NULL;
}
+ if (!brush_use_accumulate(wp->paint.brush)) {
+ MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
+ MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
+ if (index_mirr != -1) {
+ defweight_prev_init(dvert_prev, me->dvert, index_mirr);
+ }
+
+ weight_prev = defvert_find_weight(dv_prev, wpi->active.index);
+ }
+ else {
+ weight_prev = dw->weight;
+ }
+
/* If there are no normalize-locks or multipaint,
* then there is no need to run the more complicated checks */
{
- dw->weight = wpaint_blend(wp, dw->weight, dw_prev->weight, alpha, paintweight,
- wpi->brush_alpha_value, wpi->do_flip);
+ float new_weight = wpaint_blend(
+ wp, weight_prev, alpha, paintweight,
+ wpi->brush_alpha_value, wpi->do_flip);
+
+ dw->weight = wpaint_clamp_monotonic(weight_prev, dw->weight, new_weight);
/* WATCH IT: take care of the ordering of applying mirror -> normalize,
* can give wrong results [#26193], least confusing if normalize is done last */
@@ -1667,13 +818,12 @@ static void do_weight_paint_vertex_single(
static void do_weight_paint_vertex_multi(
/* vars which remain the same for every vert */
- VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
+ const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
/* vars which change on each stroke */
- const unsigned int index, float alpha, float paintweight)
+ const uint index, float alpha, float paintweight)
{
Mesh *me = ob->data;
MDeformVert *dv = &me->dvert[index];
- MDeformVert *dv_prev = &wp->wpaint_prev[index];
bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
/* mirror vars */
@@ -1681,7 +831,7 @@ static void do_weight_paint_vertex_multi(
MDeformVert *dv_mirr = NULL;
/* weights */
- float oldw, curw, neww, change, curw_mirr, change_mirr;
+ float curw, oldw, neww, change, curw_mirr, change_mirr;
/* from now on we can check if mirrors enabled if this var is -1 and not bother with the flag */
if (me->editflag & ME_EDIT_MIRROR_X) {
@@ -1690,11 +840,12 @@ static void do_weight_paint_vertex_multi(
if (index_mirr != -1 && index_mirr != index) {
dv_mirr = &me->dvert[index_mirr];
}
+ else {
+ index_mirr = -1;
+ }
}
/* compute weight change by applying the brush to average or sum of group weights */
- oldw = BKE_defvert_multipaint_collective_weight(
- dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
curw = BKE_defvert_multipaint_collective_weight(
dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
@@ -1703,7 +854,22 @@ static void do_weight_paint_vertex_multi(
return;
}
- neww = wpaint_blend(wp, curw, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
+ if (!brush_use_accumulate(wp->paint.brush)) {
+ MDeformVert *dvert_prev = ob->sculpt->mode.wpaint.dvert_prev;
+ MDeformVert *dv_prev = defweight_prev_init(dvert_prev, me->dvert, index);
+ if (index_mirr != -1) {
+ defweight_prev_init(dvert_prev, me->dvert, index_mirr);
+ }
+
+ oldw = BKE_defvert_multipaint_collective_weight(
+ dv_prev, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
+ }
+ else {
+ oldw = curw;
+ }
+
+ neww = wpaint_blend(wp, oldw, alpha, paintweight, wpi->brush_alpha_value, wpi->do_flip);
+ neww = wpaint_clamp_monotonic(oldw, curw, neww);
change = neww / curw;
@@ -1757,9 +923,9 @@ static void do_weight_paint_vertex_multi(
static void do_weight_paint_vertex(
/* vars which remain the same for every vert */
- VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
+ const VPaint *wp, Object *ob, const WeightPaintInfo *wpi,
/* vars which change on each stroke */
- const unsigned int index, float alpha, float paintweight)
+ const uint index, float alpha, float paintweight)
{
if (wpi->do_multipaint) {
do_weight_paint_vertex_multi(wp, ob, wpi, index, alpha, paintweight);
@@ -1769,59 +935,280 @@ static void do_weight_paint_vertex(
}
}
-/* *************** set wpaint operator ****************** */
-/**
- * \note Keep in sync with #vpaint_mode_toggle_exec
- */
-static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
-{
- Object *ob = CTX_data_active_object(C);
- const int mode_flag = OB_MODE_WEIGHT_PAINT;
- const bool is_mode_set = (ob->mode & mode_flag) != 0;
- Scene *scene = CTX_data_scene(C);
- VPaint *wp = scene->toolsettings->wpaint;
- Mesh *me;
+/* Toggle operator for turning vertex paint mode on or off (copied from sculpt.c) */
+static void vertex_paint_init_session(Scene *scene, Object *ob)
+{
+ /* Create persistent sculpt mode data */
+ BKE_sculpt_toolsettings_data_ensure(scene);
- if (!is_mode_set) {
- if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
- return OPERATOR_CANCELLED;
+ if (ob->sculpt == NULL) {
+ ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
+ BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, 0, false);
+ }
+}
+
+static void vertex_paint_init_session_data(const ToolSettings *ts, Object *ob)
+{
+ /* Create maps */
+ struct SculptVertexPaintGeomMap *gmap = NULL;
+ const Brush *brush = NULL;
+ if (ob->mode == OB_MODE_VERTEX_PAINT) {
+ gmap = &ob->sculpt->mode.vpaint.gmap;
+ brush = BKE_paint_brush(&ts->vpaint->paint);
+ ob->sculpt->mode_type = OB_MODE_VERTEX_PAINT;
+ }
+ else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
+ gmap = &ob->sculpt->mode.wpaint.gmap;
+ brush = BKE_paint_brush(&ts->wpaint->paint);
+ ob->sculpt->mode_type = OB_MODE_WEIGHT_PAINT;
+ }
+ else {
+ ob->sculpt->mode_type = 0;
+ BLI_assert(0);
+ return;
+ }
+
+ Mesh *me = ob->data;
+
+ if (gmap->vert_to_loop == NULL) {
+ gmap->vert_map_mem = NULL;
+ gmap->vert_to_loop = NULL;
+ gmap->poly_map_mem = NULL;
+ gmap->vert_to_poly = NULL;
+ BKE_mesh_vert_loop_map_create(
+ &gmap->vert_to_loop,
+ &gmap->vert_map_mem,
+ me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
+ BKE_mesh_vert_poly_map_create(
+ &gmap->vert_to_poly,
+ &gmap->poly_map_mem,
+ me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop);
+ }
+
+ /* Create average brush arrays */
+ if (ob->mode == OB_MODE_VERTEX_PAINT) {
+ if (!brush_use_accumulate(brush)) {
+ if (ob->sculpt->mode.vpaint.previous_color == NULL) {
+ ob->sculpt->mode.vpaint.previous_color =
+ MEM_callocN(me->totloop * sizeof(uint), __func__);
+ }
+ }
+ else {
+ MEM_SAFE_FREE(ob->sculpt->mode.vpaint.previous_color);
+ }
+ }
+ else if (ob->mode == OB_MODE_WEIGHT_PAINT) {
+ if (!brush_use_accumulate(brush)) {
+ if (ob->sculpt->mode.wpaint.alpha_weight == NULL) {
+ ob->sculpt->mode.wpaint.alpha_weight =
+ MEM_callocN(me->totvert * sizeof(float), __func__);
+ }
+ if (ob->sculpt->mode.wpaint.dvert_prev == NULL) {
+ ob->sculpt->mode.wpaint.dvert_prev =
+ MEM_callocN(me->totvert * sizeof(MDeformVert), __func__);
+ MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
+ for (int i = 0; i < me->totvert; i++, dv++) {
+ /* Use to show this isn't initialized, never apply to the mesh data. */
+ dv->flag = 1;
+ }
+ }
+ }
+ else {
+ MEM_SAFE_FREE(ob->sculpt->mode.wpaint.alpha_weight);
+ if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
+ BKE_defvert_array_free_elems(ob->sculpt->mode.wpaint.dvert_prev, me->totvert);
+ MEM_freeN(ob->sculpt->mode.wpaint.dvert_prev);
+ ob->sculpt->mode.wpaint.dvert_prev = NULL;
+ }
}
}
- me = BKE_mesh_from_object(ob);
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Enter Vertex/Weight Paint Mode
+ * \{ */
+
+static void ed_vwpaintmode_enter_generic(
+ wmWindowManager *wm,
+ Scene *scene,
+ Object *ob, const eObjectMode mode_flag)
+{
+ ob->mode |= mode_flag;
+ Mesh *me = BKE_mesh_from_object(ob);
+
+ if (mode_flag == OB_MODE_VERTEX_PAINT) {
+ const ePaintMode paint_mode = ePaintVertex;
+ ED_mesh_color_ensure(me, NULL);
+
+ if (scene->toolsettings->vpaint == NULL) {
+ scene->toolsettings->vpaint = new_vpaint();
+ }
+
+ Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
+ paint_cursor_start_explicit(paint, wm, vertex_paint_poll);
+ BKE_paint_init(scene, paint_mode, PAINT_CURSOR_VERTEX_PAINT);
+ }
+ else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
+ const ePaintMode paint_mode = ePaintWeight;
+
+ if (scene->toolsettings->wpaint == NULL) {
+ scene->toolsettings->wpaint = new_vpaint();
+ }
+
+ Paint *paint = BKE_paint_get_active_from_paintmode(scene, paint_mode);
+ paint_cursor_start_explicit(paint, wm, weight_paint_poll);
+ BKE_paint_init(scene, paint_mode, PAINT_CURSOR_WEIGHT_PAINT);
+
+ /* weight paint specific */
+ ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
+ ED_vgroup_sync_from_pose(ob);
+ }
+ else {
+ BLI_assert(0);
+ }
+
+ /* Create vertex/weight paint mode session data */
+ if (ob->sculpt) {
+ if (ob->sculpt->cache) {
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
+ }
+ BKE_sculptsession_free(ob);
+ }
- if (ob->mode & mode_flag) {
- ob->mode &= ~mode_flag;
+ vertex_paint_init_session(scene, ob);
+}
+
+void ED_object_vpaintmode_enter_ex(
+ wmWindowManager *wm,
+ Scene *scene, Object *ob)
+{
+ ed_vwpaintmode_enter_generic(
+ wm, scene, ob, OB_MODE_VERTEX_PAINT);
+}
+void ED_object_vpaintmode_enter(struct bContext *C)
+{
+ wmWindowManager *wm = CTX_wm_manager(C);
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ ED_object_vpaintmode_enter_ex(wm, scene, ob);
+}
+
+void ED_object_wpaintmode_enter_ex(
+ wmWindowManager *wm,
+ Scene *scene, Object *ob)
+{
+ ed_vwpaintmode_enter_generic(
+ wm, scene, ob, OB_MODE_WEIGHT_PAINT);
+}
+void ED_object_wpaintmode_enter(struct bContext *C)
+{
+ wmWindowManager *wm = CTX_wm_manager(C);
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ ED_object_wpaintmode_enter_ex(wm, scene, ob);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Exit Vertex/Weight Paint Mode
+ * \{ */
+
+static void ed_vwpaintmode_exit_generic(
+ Object *ob, const eObjectMode mode_flag)
+{
+ Mesh *me = BKE_mesh_from_object(ob);
+ ob->mode &= ~mode_flag;
+ if (mode_flag == OB_MODE_VERTEX_PAINT) {
+ if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
+ BKE_mesh_flush_select_from_polys(me);
+ }
+ else if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
+ BKE_mesh_flush_select_from_verts(me);
+ }
+ }
+ else if (mode_flag == OB_MODE_WEIGHT_PAINT) {
if (me->editflag & ME_EDIT_PAINT_VERT_SEL) {
BKE_mesh_flush_select_from_verts(me);
}
else if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
BKE_mesh_flush_select_from_polys(me);
}
+ }
+ else {
+ BLI_assert(0);
+ }
- /* weight paint specific */
+ /* If the cache is not released by a cancel or a done, free it now. */
+ if (ob->sculpt && ob->sculpt->cache) {
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
+ }
+
+ BKE_sculptsession_free(ob);
+
+ paint_cursor_delete_textures();
+
+ if (mode_flag == OB_MODE_WEIGHT_PAINT) {
ED_mesh_mirror_spatial_table(NULL, NULL, NULL, NULL, 'e');
ED_mesh_mirror_topo_table(NULL, NULL, 'e');
-
- paint_cursor_delete_textures();
}
- else {
- ob->mode |= mode_flag;
+}
- if (wp == NULL)
- wp = scene->toolsettings->wpaint = new_vpaint(1);
+void ED_object_vpaintmode_exit_ex(Object *ob)
+{
+ ed_vwpaintmode_exit_generic(ob, OB_MODE_VERTEX_PAINT);
+}
+void ED_object_vpaintmode_exit(struct bContext *C)
+{
+ Object *ob = CTX_data_active_object(C);
+ ED_object_vpaintmode_exit_ex(ob);
+}
- paint_cursor_start(C, weight_paint_poll);
+void ED_object_wpaintmode_exit_ex(Object *ob)
+{
+ ed_vwpaintmode_exit_generic(ob, OB_MODE_WEIGHT_PAINT);
+}
+void ED_object_wpaintmode_exit(struct bContext *C)
+{
+ Object *ob = CTX_data_active_object(C);
+ ED_object_wpaintmode_exit_ex(ob);
+}
- BKE_paint_init(scene, ePaintWeight, PAINT_CURSOR_WEIGHT_PAINT);
+/** \} */
- /* weight paint specific */
- ED_mesh_mirror_spatial_table(ob, NULL, NULL, NULL, 's');
- ED_vgroup_sync_from_pose(ob);
+/* *************** set wpaint operator ****************** */
+
+/**
+ * \note Keep in sync with #vpaint_mode_toggle_exec
+ */
+static int wpaint_mode_toggle_exec(bContext *C, wmOperator *op)
+{
+ Object *ob = CTX_data_active_object(C);
+ const int mode_flag = OB_MODE_WEIGHT_PAINT;
+ const bool is_mode_set = (ob->mode & mode_flag) != 0;
+ Scene *scene = CTX_data_scene(C);
+
+ if (!is_mode_set) {
+ if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
+ return OPERATOR_CANCELLED;
+ }
+ }
+
+ Mesh *me = BKE_mesh_from_object(ob);
+
+ if (is_mode_set) {
+ ED_object_wpaintmode_exit_ex(ob);
+ }
+ else {
+ wmWindowManager *wm = CTX_wm_manager(C);
+ ED_object_wpaintmode_enter_ex(wm, scene, ob);
}
-
+
/* Weightpaint works by overriding colors in mesh,
* so need to make sure we recalc on enter and
* exit (exit needs doing regardless because we
@@ -1840,7 +1227,7 @@ static int paint_poll_test(bContext *C)
Object *ob = CTX_data_active_object(C);
if (ob == NULL || ob->type != OB_MESH)
return 0;
- if (!ob->data || ID_IS_LINKED_DATABLOCK(ob->data))
+ if (!ob->data || ID_IS_LINKED(ob->data))
return 0;
if (CTX_data_edit_object(C))
return 0;
@@ -1849,43 +1236,28 @@ static int paint_poll_test(bContext *C)
void PAINT_OT_weight_paint_toggle(wmOperatorType *ot)
{
-
+
/* identifiers */
ot->name = "Weight Paint Mode";
ot->idname = "PAINT_OT_weight_paint_toggle";
ot->description = "Toggle weight paint mode in 3D view";
-
+
/* api callbacks */
ot->exec = wpaint_mode_toggle_exec;
ot->poll = paint_poll_test;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
}
/* ************ weight paint operator ********** */
-enum eWPaintFlag {
- WPAINT_ENSURE_MIRROR = (1 << 0),
-};
-
-struct WPaintVGroupIndex {
- int active;
- int mirror;
-};
-
struct WPaintData {
ViewContext vc;
- int *indexar;
+ struct NormalAnglePrecalc normal_angle_precalc;
struct WeightPaintGroupData active, mirror;
- void *vp_handle;
- DMCoNo *vertexcosnos;
-
- float wpimat[3][3];
-
/* variables for auto normalize */
const bool *vgroup_validmap; /* stores if vgroups tie to deforming bones or not */
const bool *lock_flags;
@@ -1895,110 +1267,138 @@ struct WPaintData {
int defbase_tot_sel; /* number of selected groups */
bool do_multipaint; /* true if multipaint enabled and multiple groups selected */
- /* variables for blur */
- struct {
- MeshElemMap *vmap;
- int *vmap_mem;
- } blur_data;
-
- BLI_Stack *accumulate_stack; /* for reuse (WPaintDefer) */
-
int defbase_tot;
+
+ /* original weight values for use in blur/smear */
+ float *precomputed_weight;
+ bool precomputed_weight_ready;
};
-/* ensure we have data on wpaint start, add if needed */
-static bool wpaint_ensure_data(
- bContext *C, wmOperator *op,
- enum eWPaintFlag flag, struct WPaintVGroupIndex *vgroup_index)
+/* Initialize the stroke cache invariants from operator properties */
+static void vwpaint_update_cache_invariants(
+ bContext *C, const VPaint *vp, SculptSession *ss, wmOperator *op, const float mouse[2])
{
+ StrokeCache *cache;
Scene *scene = CTX_data_scene(C);
+ UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
+ const Brush *brush = vp->paint.brush;
+ ViewContext *vc = paint_stroke_view_context(op->customdata);
Object *ob = CTX_data_active_object(C);
- Mesh *me = BKE_mesh_from_object(ob);
+ float mat[3][3];
+ float view_dir[3] = {0.0f, 0.0f, 1.0f};
+ int mode;
- if (vgroup_index) {
- vgroup_index->active = -1;
- vgroup_index->mirror = -1;
+ /* VW paint needs to allocate stroke cache before update is called. */
+ if (!ss->cache) {
+ cache = MEM_callocN(sizeof(StrokeCache), "stroke cache");
+ ss->cache = cache;
}
-
- if (scene->obedit) {
- return false;
+ else {
+ cache = ss->cache;
}
- if (me == NULL || me->totpoly == 0) {
- return false;
- }
+ /* Initial mouse location */
+ if (mouse)
+ copy_v2_v2(cache->initial_mouse, mouse);
+ else
+ zero_v2(cache->initial_mouse);
- /* if nothing was added yet, we make dverts and a vertex deform group */
- if (!me->dvert) {
- BKE_object_defgroup_data_create(&me->id);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
- }
+ mode = RNA_enum_get(op->ptr, "mode");
+ cache->invert = mode == BRUSH_STROKE_INVERT;
+ cache->alt_smooth = mode == BRUSH_STROKE_SMOOTH;
+ /* not very nice, but with current events system implementation
+ * we can't handle brush appearance inversion hotkey separately (sergey) */
+ if (cache->invert) ups->draw_inverted = true;
+ else ups->draw_inverted = false;
- /* this happens on a Bone select, when no vgroup existed yet */
- if (ob->actdef <= 0) {
- Object *modob;
- if ((modob = modifiers_isDeformedByArmature(ob))) {
- Bone *actbone = ((bArmature *)modob->data)->act_bone;
- if (actbone) {
- bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
+ copy_v2_v2(cache->mouse, cache->initial_mouse);
+ /* Truly temporary data that isn't stored in properties */
+ cache->vc = vc;
+ cache->brush = brush;
+ cache->first_time = 1;
- if (pchan) {
- bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
- if (dg == NULL) {
- dg = BKE_object_defgroup_add_name(ob, pchan->name); /* sets actdef */
- }
- else {
- int actdef = 1 + BLI_findindex(&ob->defbase, dg);
- BLI_assert(actdef >= 0);
- ob->actdef = actdef;
- }
- }
- }
- }
- }
- if (BLI_listbase_is_empty(&ob->defbase)) {
- BKE_object_defgroup_add(ob);
- }
+ /* cache projection matrix */
+ ED_view3d_ob_project_mat_get(cache->vc->rv3d, ob, cache->projection_mat);
- /* ensure we don't try paint onto an invalid group */
- if (ob->actdef <= 0) {
- BKE_report(op->reports, RPT_WARNING, "No active vertex group for painting, aborting");
- return false;
+ invert_m4_m4(ob->imat, ob->obmat);
+ copy_m3_m4(mat, cache->vc->rv3d->viewinv);
+ mul_m3_v3(mat, view_dir);
+ copy_m3_m4(mat, ob->imat);
+ mul_m3_v3(mat, view_dir);
+ normalize_v3_v3(cache->true_view_normal, view_dir);
+
+ copy_v3_v3(cache->view_normal, cache->true_view_normal);
+ cache->bstrength = BKE_brush_alpha_get(scene, brush);
+ cache->is_last_valid = false;
+}
+
+/* Initialize the stroke cache variants from operator properties */
+static void vwpaint_update_cache_variants(bContext *C, VPaint *vp, Object *ob, PointerRNA *ptr)
+{
+ Scene *scene = CTX_data_scene(C);
+ SculptSession *ss = ob->sculpt;
+ StrokeCache *cache = ss->cache;
+ Brush *brush = BKE_paint_brush(&vp->paint);
+
+ /* This effects the actual brush radius, so things farther away
+ * are compared with a larger radius and vise versa. */
+ if (cache->first_time) {
+ RNA_float_get_array(ptr, "location", cache->true_location);
}
- if (vgroup_index) {
- vgroup_index->active = ob->actdef - 1;
+ RNA_float_get_array(ptr, "mouse", cache->mouse);
+
+ /* XXX: Use pressure value from first brush step for brushes which don't
+ * support strokes (grab, thumb). They depends on initial state and
+ * brush coord/pressure/etc.
+ * It's more an events design issue, which doesn't split coordinate/pressure/angle
+ * changing events. We should avoid this after events system re-design */
+ if (paint_supports_dynamic_size(brush, ePaintSculpt) || cache->first_time) {
+ cache->pressure = RNA_float_get(ptr, "pressure");
}
- if (flag & WPAINT_ENSURE_MIRROR) {
- if (me->editflag & ME_EDIT_MIRROR_X) {
- int mirror = wpaint_mirror_vgroup_ensure(ob, ob->actdef - 1);
- if (vgroup_index) {
- vgroup_index->mirror = mirror;
- }
+ /* Truly temporary data that isn't stored in properties */
+ if (cache->first_time) {
+ if (!BKE_brush_use_locked_size(scene, brush)) {
+ cache->initial_radius = paint_calc_object_space_radius(
+ cache->vc, cache->true_location, BKE_brush_size_get(scene, brush));
+ BKE_brush_unprojected_radius_set(scene, brush, cache->initial_radius);
+ }
+ else {
+ cache->initial_radius = BKE_brush_unprojected_radius_get(scene, brush);
}
}
- return true;
+ if (BKE_brush_use_size_pressure(scene, brush) && paint_supports_dynamic_size(brush, ePaintSculpt)) {
+ cache->radius = cache->initial_radius * cache->pressure;
+ }
+ else {
+ cache->radius = cache->initial_radius;
+ }
+
+ cache->radius_squared = cache->radius * cache->radius;
+
+ if (ss->pbvh) {
+ BKE_pbvh_update(ss->pbvh, PBVH_UpdateRedraw, NULL);
+ BKE_pbvh_update(ss->pbvh, PBVH_UpdateBB, NULL);
+ }
}
-static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UNUSED(mouse[2]))
+static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float mouse[2])
{
Scene *scene = CTX_data_scene(C);
struct PaintStroke *stroke = op->customdata;
ToolSettings *ts = scene->toolsettings;
- VPaint *wp = ts->wpaint;
Object *ob = CTX_data_active_object(C);
Mesh *me = BKE_mesh_from_object(ob);
struct WPaintData *wpd;
struct WPaintVGroupIndex vgroup_index;
int defbase_tot, defbase_tot_sel;
bool *defbase_sel;
- const Brush *brush = BKE_paint_brush(&wp->paint);
-
- float mat[4][4], imat[4][4];
+ SculptSession *ss = ob->sculpt;
+ VPaint *vp = CTX_data_tool_settings(C)->wpaint;
- if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
+ if (ED_wpaint_ensure_data(C, op->reports, WPAINT_ENSURE_MIRROR, &vgroup_index) == false) {
return false;
}
@@ -2048,7 +1448,9 @@ static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UN
/* make mode data storage */
wpd = MEM_callocN(sizeof(struct WPaintData), "WPaintData");
paint_stroke_set_mode_data(stroke, wpd);
- view3d_set_viewcontext(C, &wpd->vc);
+ ED_view3d_viewcontext_init(C, &wpd->vc);
+ view_angle_limits_init(&wpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
+ (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
wpd->active.index = vgroup_index.active;
wpd->mirror.index = vgroup_index.mirror;
@@ -2093,63 +1495,609 @@ static bool wpaint_stroke_test_start(bContext *C, wmOperator *op, const float UN
wpd->mirror.lock = tmpflags;
}
- /* painting on subsurfs should give correct points too, this returns me->totvert amount */
- wpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &wpd->vertexcosnos);
+ if (ELEM(vp->paint.brush->vertexpaint_tool, PAINT_BLEND_SMEAR, PAINT_BLEND_BLUR)) {
+ wpd->precomputed_weight = MEM_mallocN(sizeof(float) * me->totvert, __func__);
+ }
- wpd->indexar = get_indexarray(me);
- copy_wpaint_prev(wp, me->dvert, me->totvert);
+ /* If not previously created, create vertex/weight paint mode session data */
+ vertex_paint_init_session(scene, ob);
+ vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
+ vertex_paint_init_session_data(ts, ob);
- if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
- BKE_mesh_vert_edge_vert_map_create(
- &wpd->blur_data.vmap, &wpd->blur_data.vmap_mem,
- me->medge, me->totvert, me->totedge);
+ if (ob->sculpt->mode.wpaint.dvert_prev != NULL) {
+ MDeformVert *dv = ob->sculpt->mode.wpaint.dvert_prev;
+ for (int i = 0; i < me->totvert; i++, dv++) {
+ /* Use to show this isn't initialized, never apply to the mesh data. */
+ dv->flag = 1;
+ }
+ }
+
+ return true;
+}
+
+static float dot_vf3vs3(const float brushNormal[3], const short vertexNormal[3])
+{
+ float normal[3];
+ normal_short_to_float_v3(normal, vertexNormal);
+ return dot_v3v3(brushNormal, normal);
+}
+
+static void get_brush_alpha_data(
+ const Scene *scene, const SculptSession *ss, const Brush *brush,
+ float *r_brush_size_pressure, float *r_brush_alpha_value, float *r_brush_alpha_pressure)
+{
+ *r_brush_size_pressure =
+ BKE_brush_size_get(scene, brush) *
+ (BKE_brush_use_size_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
+ *r_brush_alpha_value =
+ BKE_brush_alpha_get(scene, brush);
+ *r_brush_alpha_pressure =
+ (BKE_brush_use_alpha_pressure(scene, brush) ? ss->cache->pressure : 1.0f);
+}
+
+static float wpaint_get_active_weight(const MDeformVert *dv, const WeightPaintInfo *wpi)
+{
+ if (wpi->do_multipaint) {
+ float weight = BKE_defvert_multipaint_collective_weight(
+ dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
+
+ CLAMP(weight, 0.0f, 1.0f);
+ return weight;
}
+ else {
+ return defvert_find_weight(dv, wpi->active.index);
+ }
+}
+
+static void do_wpaint_precompute_weight_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ const MDeformVert *dv = &data->me->dvert[n];
- if ((brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
- (brush->flag & BRUSH_ACCUMULATE))
+ data->wpd->precomputed_weight[n] = wpaint_get_active_weight(dv, data->wpi);
+}
+
+static void precompute_weight_values(
+ bContext *C, Object *ob, Brush *brush, struct WPaintData *wpd, WeightPaintInfo *wpi, Mesh *me)
+{
+ if (wpd->precomputed_weight_ready && !brush_use_accumulate(brush))
+ return;
+
+ /* threaded loop over vertices */
+ SculptThreadedTaskData data = {
+ .C = C, .ob = ob, .wpd = wpd, .wpi = wpi, .me = me,
+ };
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ BLI_task_parallel_range(
+ 0, me->totvert,
+ &data,
+ do_wpaint_precompute_weight_cb_ex,
+ &settings);
+
+ wpd->precomputed_weight_ready = true;
+}
+
+static void do_wpaint_brush_blur_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
+
+ const Brush *brush = data->brush;
+ const StrokeCache *cache = ss->cache;
+ Scene *scene = CTX_data_scene(data->C);
+
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- wpd->accumulate_stack = BLI_stack_new(sizeof(struct WPaintDefer), __func__);
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* For grid based pbvh, take the vert whose loop coopresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const char v_flag = data->me->mvert[v_index].flag;
+ /* If the vertex is selected */
+ if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
+ /* Get the average poly weight */
+ int total_hit_loops = 0;
+ float weight_final = 0.0f;
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const MPoly *mp = &data->me->mpoly[p_index];
+
+ total_hit_loops += mp->totloop;
+ for (int k = 0; k < mp->totloop; k++) {
+ const int l_index = mp->loopstart + k;
+ const MLoop *ml = &data->me->mloop[l_index];
+ weight_final += data->wpd->precomputed_weight[ml->v];
+ }
+ }
+
+ /* Apply the weight to the vertex. */
+ if (total_hit_loops != 0) {
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+ const float final_alpha =
+ brush_fade * brush_strength *
+ grid_alpha * brush_alpha_pressure;
+
+ if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
+ if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
+ ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
+ }
+ else {
+ continue;
+ }
+ }
+
+ weight_final /= total_hit_loops;
+ /* Only paint visable verts */
+ do_weight_paint_vertex(
+ data->vp, data->ob, data->wpi,
+ v_index, final_alpha, weight_final);
+ }
+ }
+ }
+ }
+ }
+ BKE_pbvh_vertex_iter_end;
+}
+
+static void do_wpaint_brush_smear_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.wpaint.gmap;
+
+ const Brush *brush = data->brush;
+ const Scene *scene = CTX_data_scene(data->C);
+ const StrokeCache *cache = ss->cache;
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+ float brush_dir[3];
+
+ sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
+ project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
+
+ if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const MVert *mv_curr = &data->me->mvert[v_index];
+
+ /* If the vertex is selected */
+ if (!(use_face_sel || use_vert_sel) || mv_curr->flag & SELECT) {
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ bool do_color = false;
+ /* Minimum dot product between brush direction and current
+ * to neighbor direction is 0.0, meaning orthogonal. */
+ float stroke_dot_max = 0.0f;
+
+ /* Get the color of the loop in the opposite direction of the brush movement
+ * (this callback is specifically for smear.) */
+ float weight_final = 0.0;
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const MPoly *mp = &data->me->mpoly[p_index];
+ const MLoop *ml_other = &data->me->mloop[mp->loopstart];
+ for (int k = 0; k < mp->totloop; k++, ml_other++) {
+ const uint v_other_index = ml_other->v;
+ if (v_other_index != v_index) {
+ const MVert *mv_other = &data->me->mvert[v_other_index];
+
+ /* Get the direction from the selected vert to the neighbor. */
+ float other_dir[3];
+ sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
+ project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
+
+ normalize_v3(other_dir);
+
+ const float stroke_dot = dot_v3v3(other_dir, brush_dir);
+
+ if (stroke_dot > stroke_dot_max) {
+ stroke_dot_max = stroke_dot;
+ weight_final = data->wpd->precomputed_weight[v_other_index];
+ do_color = true;
+ }
+ }
+ }
+ }
+ /* Apply weight to vertex */
+ if (do_color) {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+ const float final_alpha =
+ brush_fade * brush_strength *
+ grid_alpha * brush_alpha_pressure;
+
+ if (final_alpha <= 0.0f)
+ continue;
+
+ do_weight_paint_vertex(
+ data->vp, data->ob, data->wpi,
+ v_index, final_alpha, (float)weight_final);
+ }
+ }
+ }
+ }
+ }
+ BKE_pbvh_vertex_iter_end;
}
+}
- /* imat for normals */
- mul_m4_m4m4(mat, wpd->vc.rv3d->viewmat, ob->obmat);
- invert_m4_m4(imat, mat);
- copy_m3_m4(wpd->wpimat, imat);
+static void do_wpaint_brush_draw_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+ const Scene *scene = CTX_data_scene(data->C);
- return true;
+ const Brush *brush = data->brush;
+ const StrokeCache *cache = ss->cache;
+ /* note: normally `BKE_brush_weight_get(scene, brush)` is used,
+ * however in this case we calculate a new weight each time. */
+ const float paintweight = data->strength;
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* Note: grids are 1:1 with corners (aka loops).
+ * For multires, take the vert whose loop cooresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+
+ const char v_flag = data->me->mvert[v_index].flag;
+ /* If the vertex is selected */
+ if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->wpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+ const float final_alpha = brush_fade * brush_strength * grid_alpha * brush_alpha_pressure;
+
+ if ((brush->flag & BRUSH_ACCUMULATE) == 0) {
+ if (ss->mode.wpaint.alpha_weight[v_index] < final_alpha) {
+ ss->mode.wpaint.alpha_weight[v_index] = final_alpha;
+ }
+ else {
+ continue;
+ }
+ }
+
+ do_weight_paint_vertex(
+ data->vp, data->ob, data->wpi,
+ v_index, final_alpha, paintweight);
+ }
+ }
+ }
+ }
+ BKE_pbvh_vertex_iter_end;
}
-static float wpaint_blur_weight_single(const MDeformVert *dv, const WeightPaintInfo *wpi)
+static void do_wpaint_brush_calc_average_weight_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
- return defvert_find_weight(dv, wpi->active.index);
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ StrokeCache *cache = ss->cache;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const bool use_vert_sel = (data->me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+
+ struct WPaintAverageAccum *accum = (struct WPaintAverageAccum *)data->custom_data + n;
+ accum->len = 0;
+ accum->value = 0.0;
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (angle_cos > 0.0 && BKE_brush_curve_strength(data->brush, sqrtf(test.dist), cache->radius) > 0.0) {
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ // const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const char v_flag = data->me->mvert[v_index].flag;
+
+ /* If the vertex is selected. */
+ if (!(use_face_sel || use_vert_sel) || v_flag & SELECT) {
+ const MDeformVert *dv = &data->me->dvert[v_index];
+ accum->len += 1;
+ accum->value += wpaint_get_active_weight(dv, data->wpi);
+ }
+ }
+ }
+ }
+ BKE_pbvh_vertex_iter_end;
}
-static float wpaint_blur_weight_multi(const MDeformVert *dv, const WeightPaintInfo *wpi)
+static void calculate_average_weight(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
{
- float weight = BKE_defvert_multipaint_collective_weight(
- dv, wpi->defbase_tot, wpi->defbase_sel, wpi->defbase_tot_sel, wpi->do_auto_normalize);
- CLAMP(weight, 0.0f, 1.0f);
- return weight;
+ struct WPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
+ data->custom_data = accum;
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((data->sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ data,
+ do_wpaint_brush_calc_average_weight_cb_ex,
+ &settings);
+
+ uint accum_len = 0;
+ double accum_weight = 0.0;
+ for (int i = 0; i < totnode; i++) {
+ accum_len += accum[i].len;
+ accum_weight += accum[i].value;
+ }
+ if (accum_len != 0) {
+ accum_weight /= accum_len;
+ data->strength = (float)accum_weight;
+ }
+
+ MEM_SAFE_FREE(data->custom_data); /* 'accum' */
}
-static float wpaint_blur_weight_calc_from_connected(
- const MDeformVert *dvert, WeightPaintInfo *wpi, struct WPaintData *wpd, const unsigned int vidx,
- float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *))
+
+static void wpaint_paint_leaves(
+ bContext *C, Object *ob, Sculpt *sd, VPaint *vp, struct WPaintData *wpd, WeightPaintInfo *wpi,
+ Mesh *me, PBVHNode **nodes, int totnode)
{
- const MeshElemMap *map = &wpd->blur_data.vmap[vidx];
- float paintweight;
- if (map->count != 0) {
- paintweight = 0.0f;
- for (int j = 0; j < map->count; j++) {
- paintweight += blur_weight_func(&dvert[map->indices[j]], wpi);
+ Scene *scene = CTX_data_scene(C);
+ const Brush *brush = ob->sculpt->cache->brush;
+
+ /* threaded loop over nodes */
+ SculptThreadedTaskData data = {
+ .sd = sd, .ob = ob, .brush = brush, .nodes = nodes, .vp = vp, .wpd = wpd, .wpi = wpi, .me = me, .C = C,
+ };
+
+ /* Use this so average can modify its weight without touching the brush. */
+ data.strength = BKE_brush_weight_get(scene, brush);
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ /* NOTE: current mirroring code cannot be run in parallel */
+ settings.use_threading = !(me->editflag & ME_EDIT_MIRROR_X);
+
+ switch (brush->vertexpaint_tool) {
+ case PAINT_BLEND_AVERAGE:
+ calculate_average_weight(&data, nodes, totnode);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_wpaint_brush_draw_task_cb_ex,
+ &settings);
+ break;
+ case PAINT_BLEND_SMEAR:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_wpaint_brush_smear_task_cb_ex,
+ &settings);
+ break;
+ case PAINT_BLEND_BLUR:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_wpaint_brush_blur_task_cb_ex,
+ &settings);
+ break;
+ default:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_wpaint_brush_draw_task_cb_ex,
+ &settings);
+ break;
+ }
+}
+
+static PBVHNode **vwpaint_pbvh_gather_generic(
+ Object *ob, VPaint *wp, Sculpt *sd, Brush *brush, int *r_totnode)
+{
+ SculptSession *ss = ob->sculpt;
+ const bool use_normal = vwpaint_use_normal(wp);
+ PBVHNode **nodes = NULL;
+
+ /* Build a list of all nodes that are potentially within the brush's area of influence */
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
+ SculptSearchSphereData data = {
+ .ss = ss,
+ .sd = sd,
+ .radius_squared = ss->cache->radius_squared,
+ .original = true,
+ };
+ BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
+ if (use_normal) {
+ sculpt_pbvh_calc_area_normal(brush, ob, nodes, *r_totnode, true, ss->cache->sculpt_normal_symm);
+ }
+ else {
+ zero_v3(ss->cache->sculpt_normal_symm);
}
- paintweight /= map->count;
}
else {
- paintweight = blur_weight_func(&dvert[vidx], wpi);
+ struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
+ dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
+ SculptSearchCircleData data = {
+ .ss = ss,
+ .sd = sd,
+ .radius_squared = ss->cache->radius_squared,
+ .original = true,
+ .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
+ };
+ BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
+ if (use_normal) {
+ copy_v3_v3(ss->cache->sculpt_normal_symm, ss->cache->view_normal);
+ }
+ else {
+ zero_v3(ss->cache->sculpt_normal_symm);
+ }
+ }
+ return nodes;
+}
+
+static void wpaint_do_paint(
+ bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
+ Mesh *me, Brush *brush, const char symm, const int axis, const int i, const float angle)
+{
+ SculptSession *ss = ob->sculpt;
+ ss->cache->radial_symmetry_pass = i;
+ sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
+
+ int totnode;
+ PBVHNode **nodes = vwpaint_pbvh_gather_generic(ob, wp, sd, brush, &totnode);
+
+ wpaint_paint_leaves(C, ob, sd, wp, wpd, wpi, me, nodes, totnode);
+
+ if (nodes)
+ MEM_freeN(nodes);
+}
+
+static void wpaint_do_radial_symmetry(
+ bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi,
+ Mesh *me, Brush *brush, const char symm, const int axis)
+{
+ for (int i = 1; i < wp->radial_symm[axis - 'X']; i++) {
+ const float angle = (2.0 * M_PI) * i / wp->radial_symm[axis - 'X'];
+ wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, symm, axis, i, angle);
}
+}
- return paintweight;
+/* near duplicate of: sculpt.c's, 'do_symmetrical_brush_actions' and 'vpaint_do_symmetrical_brush_actions'. */
+static void wpaint_do_symmetrical_brush_actions(
+ bContext *C, Object *ob, VPaint *wp, Sculpt *sd, struct WPaintData *wpd, WeightPaintInfo *wpi)
+{
+ Brush *brush = BKE_paint_brush(&wp->paint);
+ Mesh *me = ob->data;
+ SculptSession *ss = ob->sculpt;
+ StrokeCache *cache = ss->cache;
+ const char symm = wp->paint.symmetry_flags & PAINT_SYMM_AXIS_ALL;
+ int i = 0;
+
+ /* initial stroke */
+ wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X', 0, 0);
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'X');
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Y');
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, 0, 'Z');
+
+ cache->symmetry = symm;
+
+ /* symm is a bit combination of XYZ - 1 is mirror X; 2 is Y; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
+ for (i = 1; i <= symm; i++) {
+ if ((symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5)))) {
+ cache->mirror_symmetry_pass = i;
+ cache->radial_symmetry_pass = 0;
+ sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
+
+ if (i & (1 << 0)) {
+ wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X', 0, 0);
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'X');
+ }
+ if (i & (1 << 1)) {
+ wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y', 0, 0);
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Y');
+ }
+ if (i & (1 << 2)) {
+ wpaint_do_paint(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z', 0, 0);
+ wpaint_do_radial_symmetry(C, ob, wp, sd, wpd, wpi, me, brush, i, 'Z');
+ }
+ }
+ }
+ copy_v3_v3(cache->true_last_location, cache->true_location);
+ cache->is_last_valid = true;
}
static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
@@ -2160,24 +2108,17 @@ static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
Brush *brush = BKE_paint_brush(&wp->paint);
struct WPaintData *wpd = paint_stroke_mode_data(stroke);
ViewContext *vc;
- Object *ob;
- Mesh *me;
+ Object *ob = CTX_data_active_object(C);
+
+ SculptSession *ss = ob->sculpt;
+ Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
+
+ vwpaint_update_cache_variants(C, wp, ob, itemptr);
+
float mat[4][4];
- float paintweight;
- int *indexar;
- unsigned int index, totindex;
float mval[2];
- const bool use_blur = (brush->vertexpaint_tool == PAINT_BLEND_BLUR);
- bool use_vert_sel;
- bool use_face_sel;
- bool use_depth;
-
- const float pressure = RNA_float_get(itemptr, "pressure");
- const float brush_size_pressure =
- BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
+
const float brush_alpha_value = BKE_brush_alpha_get(scene, brush);
- const float brush_alpha_pressure =
- brush_alpha_value * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
/* intentionally don't initialize as NULL, make sure we initialize all members below */
WeightPaintInfo wpi;
@@ -2190,21 +2131,15 @@ static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
return;
}
- float (*blur_weight_func)(const MDeformVert *, const WeightPaintInfo *) =
- wpd->do_multipaint ? wpaint_blur_weight_multi : wpaint_blur_weight_single;
-
vc = &wpd->vc;
ob = vc->obact;
- me = ob->data;
- indexar = wpd->indexar;
-
+
view3d_operator_needs_opengl(C);
ED_view3d_init_mats_rv3d(ob, vc->rv3d);
/* load projection matrix */
mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
- RNA_float_get_array(itemptr, "mouse", mval);
/* *** setup WeightPaintInfo - pass onto do_weight_paint_vertex *** */
wpi.defbase_tot = wpd->defbase_tot;
@@ -2222,180 +2157,51 @@ static void wpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
wpi.brush_alpha_value = brush_alpha_value;
/* *** done setting up WeightPaintInfo *** */
-
-
- swap_m4m4(wpd->vc.rv3d->persmat, mat);
-
- use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
- use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
- use_depth = (vc->v3d->flag & V3D_ZBUF_SELECT) != 0;
-
- /* which faces are involved */
- if (use_depth) {
- char editflag_prev = me->editflag;
-
- /* Ugly hack, to avoid drawing vertex index when getting the face index buffer - campbell */
- me->editflag &= ~ME_EDIT_PAINT_VERT_SEL;
- if (use_vert_sel) {
- /* Ugly x2, we need this so hidden faces don't draw */
- me->editflag |= ME_EDIT_PAINT_FACE_SEL;
- }
- totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
- me->editflag = editflag_prev;
-
- if (use_face_sel && me->totpoly) {
- MPoly *mpoly = me->mpoly;
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- MPoly *mp = &mpoly[indexar[index] - 1];
-
- if ((mp->flag & ME_FACE_SEL) == 0) {
- indexar[index] = 0;
- }
- }
- }
- }
- }
- else {
- indexar = NULL;
+ if (wpd->precomputed_weight) {
+ precompute_weight_values(C, ob, brush, wpd, &wpi, ob->data);
}
- /* incase we have modifiers */
- ED_vpaint_proj_handle_update(wpd->vp_handle, vc->ar, mval);
+ wpaint_do_symmetrical_brush_actions(C, ob, wp, sd, wpd, &wpi);
- /* make sure each vertex gets treated only once */
- /* and calculate filter weight */
- paintweight = BKE_brush_weight_get(scene, brush);
+ swap_m4m4(vc->rv3d->persmat, mat);
- if (use_depth) {
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- MPoly *mpoly = me->mpoly + (indexar[index] - 1);
- MLoop *ml = me->mloop + mpoly->loopstart;
- int i;
+ /* calculate pivot for rotation around seletion if needed */
+ /* also needed for "View Selected" on last stroke */
+ paint_last_stroke_update(scene, vc->ar, mval);
- if (use_vert_sel) {
- for (i = 0; i < mpoly->totloop; i++, ml++) {
- me->dvert[ml->v].flag = (me->mvert[ml->v].flag & SELECT);
- }
- }
- else {
- for (i = 0; i < mpoly->totloop; i++, ml++) {
- me->dvert[ml->v].flag = 1;
- }
- }
- }
- }
- }
- else {
- const unsigned int totvert = me->totvert;
- unsigned int i;
+ DAG_id_tag_update(ob->data, 0);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+ swap_m4m4(wpd->vc.rv3d->persmat, mat);
- /* in the case of face selection we need to flush */
- if (use_vert_sel || use_face_sel) {
- for (i = 0; i < totvert; i++) {
- me->dvert[i].flag = me->mvert[i].flag & SELECT;
- }
- }
- else {
- for (i = 0; i < totvert; i++) {
- me->dvert[i].flag = SELECT;
- }
+ rcti r;
+ if (sculpt_get_redraw_rect(vc->ar, CTX_wm_region_view3d(C), ob, &r)) {
+ if (ss->cache) {
+ ss->cache->current_r = r;
}
- }
- /* accumulate means we refer to the previous,
- * which is either the last update, or when we started painting */
- BLI_Stack *accumulate_stack = wpd->accumulate_stack;
- const bool use_accumulate = (accumulate_stack != NULL);
- BLI_assert(accumulate_stack == NULL || BLI_stack_is_empty(accumulate_stack));
-
- const MDeformVert *dvert_prev = use_accumulate ? me->dvert : wp->wpaint_prev;
-
-#define WP_PAINT(v_idx_var) \
- { \
- unsigned int vidx = v_idx_var; \
- if (me->dvert[vidx].flag) { \
- const float alpha = calc_vp_alpha_col_dl( \
- wp, vc, wpd->wpimat, &wpd->vertexcosnos[vidx], \
- mval, brush_size_pressure, brush_alpha_pressure, NULL); \
- if (alpha) { \
- if (use_blur) { \
- paintweight = wpaint_blur_weight_calc_from_connected( \
- dvert_prev, &wpi, wpd, vidx, blur_weight_func); \
- } \
- if (use_accumulate) { \
- struct WPaintDefer *dweight = BLI_stack_push_r(accumulate_stack); \
- dweight->index = vidx; \
- dweight->alpha = alpha; \
- dweight->weight = paintweight; \
- } \
- else { \
- do_weight_paint_vertex(wp, ob, &wpi, vidx, alpha, paintweight); \
- } \
- } \
- me->dvert[vidx].flag = 0; \
- } \
- } (void)0
-
- if (use_depth) {
- for (index = 0; index < totindex; index++) {
-
- if (indexar[index] && indexar[index] <= me->totpoly) {
- MPoly *mpoly = me->mpoly + (indexar[index] - 1);
- MLoop *ml = me->mloop + mpoly->loopstart;
- int i;
-
- for (i = 0; i < mpoly->totloop; i++, ml++) {
- WP_PAINT(ml->v);
- }
- }
+ /* previous is not set in the current cache else
+ * the partial rect will always grow */
+ if (ss->cache) {
+ if (!BLI_rcti_is_empty(&ss->cache->previous_r))
+ BLI_rcti_union(&r, &ss->cache->previous_r);
}
- }
- else {
- const unsigned int totvert = me->totvert;
- unsigned int i;
- for (i = 0; i < totvert; i++) {
- WP_PAINT(i);
- }
- }
-#undef WP_PAINT
+ r.xmin += vc->ar->winrct.xmin - 2;
+ r.xmax += vc->ar->winrct.xmin + 2;
+ r.ymin += vc->ar->winrct.ymin - 2;
+ r.ymax += vc->ar->winrct.ymin + 2;
- if (use_accumulate) {
- unsigned int defer_count = BLI_stack_count(accumulate_stack);
- while (defer_count--) {
- struct WPaintDefer *dweight = BLI_stack_peek(accumulate_stack);
- do_weight_paint_vertex(wp, ob, &wpi, dweight->index, dweight->alpha, dweight->weight);
- BLI_stack_discard(accumulate_stack);
- }
+ ss->partial_redraw = 1;
}
-
-
- /* *** free wpi members */
- /* *** done freeing wpi members */
-
-
- swap_m4m4(vc->rv3d->persmat, mat);
-
- /* calculate pivot for rotation around seletion if needed */
- /* also needed for "View Selected" on last stroke */
- paint_last_stroke_update(scene, vc->ar, mval);
-
- DAG_id_tag_update(ob->data, 0);
- ED_region_tag_redraw(vc->ar);
+ ED_region_tag_redraw_partial(vc->ar, &r);
}
static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
{
- ToolSettings *ts = CTX_data_tool_settings(C);
Object *ob = CTX_data_active_object(C);
struct WPaintData *wpd = paint_stroke_mode_data(stroke);
-
+
if (wpd) {
- ED_vpaint_proj_handle_free(wpd->vp_handle);
- MEM_freeN(wpd->indexar);
-
if (wpd->defbase_sel)
MEM_freeN((void *)wpd->defbase_sel);
if (wpd->vgroup_validmap)
@@ -2406,29 +2212,17 @@ static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
MEM_freeN((void *)wpd->active.lock);
if (wpd->mirror.lock)
MEM_freeN((void *)wpd->mirror.lock);
-
- if (wpd->blur_data.vmap) {
- MEM_freeN(wpd->blur_data.vmap);
- }
- if (wpd->blur_data.vmap_mem) {
- MEM_freeN(wpd->blur_data.vmap_mem);
- }
-
- if (wpd->accumulate_stack) {
- BLI_stack_free(wpd->accumulate_stack);
- }
+ if (wpd->precomputed_weight)
+ MEM_freeN(wpd->precomputed_weight);
MEM_freeN(wpd);
}
-
- /* frees prev buffer */
- copy_wpaint_prev(ts->wpaint, NULL, 0);
-
+
/* and particles too */
if (ob->particlesystem.first) {
ParticleSystem *psys;
int i;
-
+
for (psys = ob->particlesystem.first; psys; psys = psys->next) {
for (i = 0; i < PSYS_TOT_VG; i++) {
if (psys->vgroup[i] == ob->actdef) {
@@ -2442,6 +2236,9 @@ static void wpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
DAG_id_tag_update(ob->data, 0);
WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
}
@@ -2449,10 +2246,11 @@ static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
int retval;
- op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
- wpaint_stroke_update_step, NULL,
- wpaint_stroke_done, event->type);
-
+ op->customdata = paint_stroke_new(
+ C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
+ wpaint_stroke_update_step, NULL,
+ wpaint_stroke_done, event->type);
+
if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
paint_stroke_data_free(op);
return OPERATOR_FINISHED;
@@ -2462,15 +2260,16 @@ static int wpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
OPERATOR_RETVAL_CHECK(retval);
BLI_assert(retval == OPERATOR_RUNNING_MODAL);
-
+
return OPERATOR_RUNNING_MODAL;
}
static int wpaint_exec(bContext *C, wmOperator *op)
{
- op->customdata = paint_stroke_new(C, op, NULL, wpaint_stroke_test_start,
- wpaint_stroke_update_step, NULL,
- wpaint_stroke_done, 0);
+ op->customdata = paint_stroke_new(
+ C, op, sculpt_stroke_get_location, wpaint_stroke_test_start,
+ wpaint_stroke_update_step, NULL,
+ wpaint_stroke_done, 0);
/* frees op->customdata */
paint_stroke_exec(C, op);
@@ -2480,64 +2279,33 @@ static int wpaint_exec(bContext *C, wmOperator *op)
static void wpaint_cancel(bContext *C, wmOperator *op)
{
+ Object *ob = CTX_data_active_object(C);
+ if (ob->sculpt->cache) {
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
+ }
+
paint_stroke_cancel(C, op);
}
void PAINT_OT_weight_paint(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Weight Paint";
ot->idname = "PAINT_OT_weight_paint";
ot->description = "Paint a stroke in the current vertex group's weights";
-
+
/* api callbacks */
ot->invoke = wpaint_invoke;
ot->modal = paint_stroke_modal;
ot->exec = wpaint_exec;
ot->poll = weight_paint_poll;
ot->cancel = wpaint_cancel;
-
+
/* flags */
ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
-
- paint_stroke_operator_properties(ot);
-}
-
-static int weight_paint_set_exec(bContext *C, wmOperator *op)
-{
- struct Scene *scene = CTX_data_scene(C);
- Object *obact = CTX_data_active_object(C);
- ToolSettings *ts = CTX_data_tool_settings(C);
- Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
- float vgroup_weight = BKE_brush_weight_get(scene, brush);
-
- if (wpaint_ensure_data(C, op, WPAINT_ENSURE_MIRROR, NULL) == false) {
- return OPERATOR_CANCELLED;
- }
-
- if (ED_wpaint_fill(scene->toolsettings->wpaint, obact, vgroup_weight)) {
- ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
- return OPERATOR_FINISHED;
- }
- else {
- return OPERATOR_CANCELLED;
- }
-}
-
-void PAINT_OT_weight_set(wmOperatorType *ot)
-{
- /* identifiers */
- ot->name = "Set Weight";
- ot->idname = "PAINT_OT_weight_set";
- ot->description = "Fill the active vertex group with the current paint weight";
-
- /* api callbacks */
- ot->exec = weight_paint_set_exec;
- ot->poll = mask_paint_poll;
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+ paint_stroke_operator_properties(ot);
}
/* ************ set / clear vertex paint mode ********** */
@@ -2546,13 +2314,11 @@ void PAINT_OT_weight_set(wmOperatorType *ot)
* \note Keep in sync with #wpaint_mode_toggle_exec
*/
static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
-{
+{
Object *ob = CTX_data_active_object(C);
const int mode_flag = OB_MODE_VERTEX_PAINT;
const bool is_mode_set = (ob->mode & mode_flag) != 0;
Scene *scene = CTX_data_scene(C);
- VPaint *vp = scene->toolsettings->vpaint;
- Mesh *me;
if (!is_mode_set) {
if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
@@ -2560,53 +2326,36 @@ static int vpaint_mode_toggle_exec(bContext *C, wmOperator *op)
}
}
- me = BKE_mesh_from_object(ob);
-
+ Mesh *me = BKE_mesh_from_object(ob);
+
/* toggle: end vpaint */
if (is_mode_set) {
- ob->mode &= ~mode_flag;
-
- if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
- BKE_mesh_flush_select_from_polys(me);
- }
-
- paint_cursor_delete_textures();
+ ED_object_vpaintmode_exit_ex(ob);
}
else {
- ob->mode |= mode_flag;
-
- if (me->mloopcol == NULL) {
- make_vertexcol(ob);
- }
-
- if (vp == NULL)
- vp = scene->toolsettings->vpaint = new_vpaint(0);
-
- paint_cursor_start(C, vertex_paint_poll);
-
- BKE_paint_init(scene, ePaintVertex, PAINT_CURSOR_VERTEX_PAINT);
+ wmWindowManager *wm = CTX_wm_manager(C);
+ ED_object_vpaintmode_enter_ex(wm, scene, ob);
}
-
+
/* update modifier stack for mapping requirements */
DAG_id_tag_update(&me->id, 0);
-
+
WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
-
+
return OPERATOR_FINISHED;
}
void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Vertex Paint Mode";
ot->idname = "PAINT_OT_vertex_paint_toggle";
ot->description = "Toggle the vertex paint mode in 3D view";
-
+
/* api callbacks */
ot->exec = vpaint_mode_toggle_exec;
ot->poll = paint_poll_test;
-
+
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
@@ -2621,7 +2370,7 @@ void PAINT_OT_vertex_paint_toggle(wmOperatorType *ot)
* - validate context (add mcol)
* - create customdata storage
* - call paint once (mouse click)
- * - add modal handler
+ * - add modal handler
*
* Operator->modal()
* - for every mousemove, apply vertex paint
@@ -2638,15 +2387,14 @@ typedef struct PolyFaceMap {
int facenr;
} PolyFaceMap;
-typedef struct VPaintData {
+struct VPaintData {
ViewContext vc;
- unsigned int paintcol;
- int *indexar;
+ struct NormalAnglePrecalc normal_angle_precalc;
- struct VertProjHandle *vp_handle;
- DMCoNo *vertexcosnos;
+ uint paintcol;
- float vpimat[3][3];
+ struct VertProjHandle *vp_handle;
+ struct DMCoNo *vertexcosnos;
/* modify 'me->mcol' directly, since the derived mesh is drawing from this
* array, otherwise we need to refresh the modifier stack */
@@ -2657,9 +2405,15 @@ typedef struct VPaintData {
bool *mlooptag;
bool is_texbrush;
-} VPaintData;
-static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float UNUSED(mouse[2]))
+ /* Special storage for smear brush, avoid feedback loop - update each step. */
+ struct {
+ uint *color_prev;
+ uint *color_curr;
+ } smear;
+};
+
+static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const float mouse[2])
{
Scene *scene = CTX_data_scene(C);
ToolSettings *ts = scene->toolsettings;
@@ -2669,26 +2423,24 @@ static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const f
struct VPaintData *vpd;
Object *ob = CTX_data_active_object(C);
Mesh *me;
- float mat[4][4], imat[4][4];
+ SculptSession *ss = ob->sculpt;
/* context checks could be a poll() */
me = BKE_mesh_from_object(ob);
if (me == NULL || me->totpoly == 0)
return false;
-
- if (me->mloopcol == NULL)
- make_vertexcol(ob);
+
+ ED_mesh_color_ensure(me, NULL);
if (me->mloopcol == NULL)
return false;
/* make mode data storage */
- vpd = MEM_callocN(sizeof(struct VPaintData), "VPaintData");
+ vpd = MEM_callocN(sizeof(*vpd), "VPaintData");
paint_stroke_set_mode_data(stroke, vpd);
- view3d_set_viewcontext(C, &vpd->vc);
-
- vpd->vp_handle = ED_vpaint_proj_handle_create(vpd->vc.scene, ob, &vpd->vertexcosnos);
+ ED_view3d_viewcontext_init(C, &vpd->vc);
+ view_angle_limits_init(&vpd->normal_angle_precalc, vp->paint.brush->falloff_angle,
+ (vp->paint.brush->flag & BRUSH_FRONTFACE_FALLOFF) != 0);
- vpd->indexar = get_indexarray(me);
vpd->paintcol = vpaint_get_current_col(scene, vp);
vpd->is_texbrush = !(brush->vertexpaint_tool == PAINT_BLEND_BLUR) &&
@@ -2710,84 +2462,586 @@ static bool vpaint_stroke_test_start(bContext *C, struct wmOperator *op, const f
vpd->mlooptag = MEM_mallocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
}
- /* for filtering */
- copy_vpaint_prev(vp, (unsigned int *)me->mloopcol, me->totloop);
-
- /* some old cruft to sort out later */
- mul_m4_m4m4(mat, vpd->vc.rv3d->viewmat, ob->obmat);
- invert_m4_m4(imat, mat);
- copy_m3_m4(vpd->vpimat, imat);
+ if (brush->vertexpaint_tool == PAINT_BLEND_SMEAR) {
+ vpd->smear.color_prev = MEM_mallocN(sizeof(uint) * me->totloop, __func__);
+ memcpy(vpd->smear.color_prev, me->mloopcol, sizeof(uint) * me->totloop);
+ vpd->smear.color_curr = MEM_dupallocN(vpd->smear.color_prev);
+ }
+
+ /* Create projection handle */
+ if (vpd->is_texbrush) {
+ ob->sculpt->building_vp_handle = true;
+ vpd->vp_handle = ED_vpaint_proj_handle_create(scene, ob, &vpd->vertexcosnos);
+ ob->sculpt->building_vp_handle = false;
+ }
+
+ /* If not previously created, create vertex/weight paint mode session data */
+ vertex_paint_init_session(scene, ob);
+ vwpaint_update_cache_invariants(C, vp, ss, op, mouse);
+ vertex_paint_init_session_data(ts, ob);
+
+ if (ob->sculpt->mode.vpaint.previous_color != NULL) {
+ memset(ob->sculpt->mode.vpaint.previous_color, 0, sizeof(uint) * me->totloop);
+ }
return 1;
}
-static void vpaint_paint_poly(VPaint *vp, VPaintData *vpd, Mesh *me,
- const unsigned int index, const float mval[2],
- const float brush_size_pressure, const float brush_alpha_pressure)
+static void do_vpaint_brush_calc_average_color_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
- ViewContext *vc = &vpd->vc;
- Brush *brush = BKE_paint_brush(&vp->paint);
- MPoly *mpoly = &me->mpoly[index];
- MLoop *ml;
- unsigned int *lcol = ((unsigned int *)me->mloopcol) + mpoly->loopstart;
- unsigned int *lcolorig = ((unsigned int *)vp->vpaint_prev) + mpoly->loopstart;
- bool *mlooptag = (vpd->mlooptag) ? vpd->mlooptag + mpoly->loopstart : NULL;
- float alpha;
- int i, j;
- int totloop = mpoly->totloop;
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
- int brush_alpha_pressure_i = (int)(brush_alpha_pressure * 255.0f);
+ StrokeCache *cache = ss->cache;
+ uint *lcol = data->lcol;
+ char *col;
+ const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
- if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
- unsigned int blend[4] = {0};
- unsigned int tcol;
- char *col;
+ struct VPaintAverageAccum *accum = (struct VPaintAverageAccum *)data->custom_data + n;
+ accum->len = 0;
+ memset(accum->value, 0, sizeof(accum->value));
- for (j = 0; j < totloop; j++) {
- col = (char *)(lcol + j);
- blend[0] += col[0];
- blend[1] += col[1];
- blend[2] += col[2];
- blend[3] += col[3];
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ if (BKE_brush_curve_strength(data->brush, 0.0, cache->radius) > 0.0) {
+ /* If the vertex is selected for painting. */
+ const MVert *mv = &data->me->mvert[v_index];
+ if (!use_vert_sel || mv->flag & SELECT) {
+ accum->len += gmap->vert_to_loop[v_index].count;
+ /* if a vertex is within the brush region, then add it's color to the blend. */
+ for (int j = 0; j < gmap->vert_to_loop[v_index].count; j++) {
+ const int l_index = gmap->vert_to_loop[v_index].indices[j];
+ col = (char *)(&lcol[l_index]);
+ /* Color is squared to compensate the sqrt color encoding. */
+ accum->value[0] += col[0] * col[0];
+ accum->value[1] += col[1] * col[1];
+ accum->value[2] += col[2] * col[2];
+ }
+ }
+ }
}
+ }
+ BKE_pbvh_vertex_iter_end;
+}
+
+static float tex_color_alpha_ubyte(
+ SculptThreadedTaskData *data, const float v_co[3],
+ uint *r_color)
+{
+ float rgba[4];
+ float rgba_br[3];
+ tex_color_alpha(data->vp, &data->vpd->vc, v_co, rgba);
+ rgb_uchar_to_float(rgba_br, (const uchar *)&data->vpd->paintcol);
+ mul_v3_v3(rgba_br, rgba);
+ rgb_float_to_uchar((uchar *)r_color, rgba_br);
+ return rgba[3];
+}
+
+static void do_vpaint_brush_draw_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
+
+ const Brush *brush = data->brush;
+ const StrokeCache *cache = ss->cache;
+ uint *lcol = data->lcol;
+ const Scene *scene = CTX_data_scene(data->C);
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
- blend[0] = divide_round_i(blend[0], totloop);
- blend[1] = divide_round_i(blend[1], totloop);
- blend[2] = divide_round_i(blend[2], totloop);
- blend[3] = divide_round_i(blend[3], totloop);
- col = (char *)&tcol;
- col[0] = blend[0];
- col[1] = blend[1];
- col[2] = blend[2];
- col[3] = blend[3];
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
- vpd->paintcol = *((unsigned int *)col);
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* Note: Grids are 1:1 with corners (aka loops).
+ * For grid based pbvh, take the vert whose loop cooresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const MVert *mv = &data->me->mvert[v_index];
+
+ /* If the vertex is selected for painting. */
+ if (!use_vert_sel || mv->flag & SELECT) {
+ /* Calc the dot prod. between ray norm on surf and current vert
+ * (ie splash prevention factor), and only paint front facing verts. */
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+ uint color_final = data->vpd->paintcol;
+
+ /* If we're painting with a texture, sample the texture color and alpha. */
+ float tex_alpha = 1.0;
+ if (data->vpd->is_texbrush) {
+ /* Note: we may want to paint alpha as vertex color alpha. */
+ tex_alpha = tex_color_alpha_ubyte(
+ data, data->vpd->vertexcosnos[v_index].co,
+ &color_final);
+ }
+ /* For each poly owning this vert, paint each loop belonging to this vert. */
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const int l_index = gmap->vert_to_loop[v_index].indices[j];
+ BLI_assert(data->me->mloop[l_index].v == v_index);
+ const MPoly *mp = &data->me->mpoly[p_index];
+ if (!use_face_sel || mp->flag & ME_FACE_SEL) {
+ uint color_orig = 0; /* unused when array is NULL */
+ if (ss->mode.vpaint.previous_color != NULL) {
+ /* Get the previous loop color */
+ if (ss->mode.vpaint.previous_color[l_index] == 0) {
+ ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
+ }
+ color_orig = ss->mode.vpaint.previous_color[l_index];
+ }
+ const float final_alpha =
+ 255 * brush_fade * brush_strength *
+ tex_alpha * brush_alpha_pressure * grid_alpha;
+
+ /* Mix the new color with the original based on final_alpha. */
+ lcol[l_index] = vpaint_blend(
+ data->vp, lcol[l_index], color_orig, color_final,
+ final_alpha, 255 * brush_strength);
+ }
+ }
+ }
+ }
+ }
}
+ BKE_pbvh_vertex_iter_end;
+}
+
+static void do_vpaint_brush_blur_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+
+ Scene *scene = CTX_data_scene(data->C);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
+ const Brush *brush = data->brush;
+ const StrokeCache *cache = ss->cache;
+ uint *lcol = data->lcol;
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
- ml = me->mloop + mpoly->loopstart;
- for (i = 0; i < totloop; i++, ml++) {
- float rgba[4];
- unsigned int paintcol;
- alpha = calc_vp_alpha_col_dl(vp, vc, vpd->vpimat,
- &vpd->vertexcosnos[ml->v], mval,
- brush_size_pressure, brush_alpha_pressure, rgba);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
- if (vpd->is_texbrush) {
- float rgba_br[3];
- rgb_uchar_to_float(rgba_br, (const unsigned char *)&vpd->paintcol);
- mul_v3_v3(rgba_br, rgba);
- rgb_float_to_uchar((unsigned char *)&paintcol, rgba_br);
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const MVert *mv = &data->me->mvert[v_index];
+
+ /* If the vertex is selected for painting. */
+ if (!use_vert_sel || mv->flag & SELECT) {
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+
+ /* Get the average poly color */
+ uint color_final = 0;
+ int total_hit_loops = 0;
+ uint blend[4] = {0};
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const MPoly *mp = &data->me->mpoly[p_index];
+ if (!use_face_sel || mp->flag & ME_FACE_SEL) {
+ total_hit_loops += mp->totloop;
+ for (int k = 0; k < mp->totloop; k++) {
+ const uint l_index = mp->loopstart + k;
+ const char *col = (const char *)(&lcol[l_index]);
+ /* Color is squared to compensate the sqrt color encoding. */
+ blend[0] += (uint)col[0] * (uint)col[0];
+ blend[1] += (uint)col[1] * (uint)col[1];
+ blend[2] += (uint)col[2] * (uint)col[2];
+ blend[3] += (uint)col[3] * (uint)col[3];
+ }
+ }
+ }
+ if (total_hit_loops != 0) {
+ /* Use rgb^2 color averaging. */
+ char *col = (char *)(&color_final);
+ col[0] = round_fl_to_uchar(sqrtf(divide_round_i(blend[0], total_hit_loops)));
+ col[1] = round_fl_to_uchar(sqrtf(divide_round_i(blend[1], total_hit_loops)));
+ col[2] = round_fl_to_uchar(sqrtf(divide_round_i(blend[2], total_hit_loops)));
+ col[3] = round_fl_to_uchar(sqrtf(divide_round_i(blend[3], total_hit_loops)));
+
+ /* For each poly owning this vert, paint each loop belonging to this vert. */
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const int l_index = gmap->vert_to_loop[v_index].indices[j];
+ BLI_assert(data->me->mloop[l_index].v == v_index);
+ const MPoly *mp = &data->me->mpoly[p_index];
+ if (!use_face_sel || mp->flag & ME_FACE_SEL) {
+ uint color_orig = 0; /* unused when array is NULL */
+ if (ss->mode.vpaint.previous_color != NULL) {
+ /* Get the previous loop color */
+ if (ss->mode.vpaint.previous_color[l_index] == 0) {
+ ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
+ }
+ color_orig = ss->mode.vpaint.previous_color[l_index];
+ }
+ const float final_alpha =
+ 255 * brush_fade * brush_strength *
+ brush_alpha_pressure * grid_alpha;
+ /* Mix the new color with the original
+ * based on the brush strength and the curve. */
+ lcol[l_index] = vpaint_blend(
+ data->vp, lcol[l_index], color_orig, *((uint *)col),
+ final_alpha, 255 * brush_strength);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ BKE_pbvh_vertex_iter_end;
+}
+
+static void do_vpaint_brush_smear_task_cb_ex(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SculptThreadedTaskData *data = userdata;
+ SculptSession *ss = data->ob->sculpt;
+ CCGDerivedMesh *ccgdm = BKE_pbvh_get_ccgdm(ss->pbvh);
+
+ Scene *scene = CTX_data_scene(data->C);
+ const struct SculptVertexPaintGeomMap *gmap = &ss->mode.vpaint.gmap;
+ const Brush *brush = data->brush;
+ const StrokeCache *cache = ss->cache;
+ uint *lcol = data->lcol;
+ float brush_size_pressure, brush_alpha_value, brush_alpha_pressure;
+ get_brush_alpha_data(scene, ss, brush, &brush_size_pressure, &brush_alpha_value, &brush_alpha_pressure);
+ float brush_dir[3];
+ const bool use_normal = vwpaint_use_normal(data->vp);
+ const bool use_vert_sel = (data->me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL)) != 0;
+ const bool use_face_sel = (data->me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+
+ sub_v3_v3v3(brush_dir, cache->location, cache->last_location);
+ project_plane_v3_v3v3(brush_dir, brush_dir, cache->view_normal);
+
+ if (cache->is_last_valid && (normalize_v3(brush_dir) != 0.0f)) {
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ const float *sculpt_normal_frontface =
+ sculpt_brush_frontface_normal_from_falloff_shape(ss, data->brush->falloff_shape);
+
+ /* For each vertex */
+ PBVHVertexIter vd;
+ BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
+ {
+ /* Test to see if the vertex coordinates are within the spherical brush region. */
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ /* For grid based pbvh, take the vert whose loop cooresponds to the current grid.
+ * Otherwise, take the current vert. */
+ const int v_index = ccgdm ? data->me->mloop[vd.grid_indices[vd.g]].v : vd.vert_indices[vd.i];
+ const float grid_alpha = ccgdm ? 1.0f / vd.gridsize : 1.0f;
+ const MVert *mv_curr = &data->me->mvert[v_index];
+
+ /* if the vertex is selected for painting. */
+ if (!use_vert_sel || mv_curr->flag & SELECT) {
+ /* Calc the dot prod. between ray norm on surf and current vert
+ * (ie splash prevention factor), and only paint front facing verts. */
+ float brush_strength = cache->bstrength;
+ const float angle_cos = (use_normal && vd.no) ?
+ dot_vf3vs3(sculpt_normal_frontface, vd.no) : 1.0f;
+ if (((brush->flag & BRUSH_FRONTFACE) == 0 ||
+ (angle_cos > 0.0f)) &&
+ ((brush->flag & BRUSH_FRONTFACE_FALLOFF) == 0 ||
+ view_angle_limits_apply_falloff(&data->vpd->normal_angle_precalc, angle_cos, &brush_strength)))
+ {
+ const float brush_fade = BKE_brush_curve_strength(brush, sqrtf(test.dist), cache->radius);
+
+ bool do_color = false;
+ /* Minimum dot product between brush direction and current
+ * to neighbor direction is 0.0, meaning orthogonal. */
+ float stroke_dot_max = 0.0f;
+
+ /* Get the color of the loop in the opposite direction of the brush movement */
+ uint color_final = 0;
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const int l_index = gmap->vert_to_loop[v_index].indices[j];
+ BLI_assert(data->me->mloop[l_index].v == v_index);
+ UNUSED_VARS_NDEBUG(l_index);
+ const MPoly *mp = &data->me->mpoly[p_index];
+ if (!use_face_sel || mp->flag & ME_FACE_SEL) {
+ const MLoop *ml_other = &data->me->mloop[mp->loopstart];
+ for (int k = 0; k < mp->totloop; k++, ml_other++) {
+ const uint v_other_index = ml_other->v;
+ if (v_other_index != v_index) {
+ const MVert *mv_other = &data->me->mvert[v_other_index];
+
+ /* Get the direction from the selected vert to the neighbor. */
+ float other_dir[3];
+ sub_v3_v3v3(other_dir, mv_curr->co, mv_other->co);
+ project_plane_v3_v3v3(other_dir, other_dir, cache->view_normal);
+
+ normalize_v3(other_dir);
+
+ const float stroke_dot = dot_v3v3(other_dir, brush_dir);
+
+ if (stroke_dot > stroke_dot_max) {
+ stroke_dot_max = stroke_dot;
+ color_final = data->vpd->smear.color_prev[mp->loopstart + k];
+ do_color = true;
+ }
+ }
+ }
+ }
+ }
+
+ if (do_color) {
+ const float final_alpha =
+ 255 * brush_fade * brush_strength *
+ brush_alpha_pressure * grid_alpha;
+
+ /* For each poly owning this vert, paint each loop belonging to this vert. */
+ for (int j = 0; j < gmap->vert_to_poly[v_index].count; j++) {
+ const int p_index = gmap->vert_to_poly[v_index].indices[j];
+ const int l_index = gmap->vert_to_loop[v_index].indices[j];
+ BLI_assert(data->me->mloop[l_index].v == v_index);
+ const MPoly *mp = &data->me->mpoly[p_index];
+ if (!use_face_sel || mp->flag & ME_FACE_SEL) {
+ /* Get the previous loop color */
+ uint color_orig = 0; /* unused when array is NULL */
+ if (ss->mode.vpaint.previous_color != NULL) {
+ /* Get the previous loop color */
+ if (ss->mode.vpaint.previous_color[l_index] == 0) {
+ ss->mode.vpaint.previous_color[l_index] = lcol[l_index];
+ }
+ color_orig = ss->mode.vpaint.previous_color[l_index];
+ }
+ /* Mix the new color with the original
+ * based on the brush strength and the curve. */
+ lcol[l_index] = vpaint_blend(
+ data->vp, lcol[l_index], color_orig, color_final,
+ final_alpha, 255 * brush_strength);
+
+ data->vpd->smear.color_curr[l_index] = lcol[l_index];
+ }
+ }
+ }
+ }
+ }
+ }
}
- else
- paintcol = vpd->paintcol;
+ BKE_pbvh_vertex_iter_end;
+ }
+}
+
+static void calculate_average_color(SculptThreadedTaskData *data, PBVHNode **UNUSED(nodes), int totnode)
+{
+ struct VPaintAverageAccum *accum = MEM_mallocN(sizeof(*accum) * totnode, __func__);
+ data->custom_data = accum;
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ BLI_task_parallel_range(
+ 0, totnode,
+ data,
+ do_vpaint_brush_calc_average_color_cb_ex,
+ &settings);
+
+ uint accum_len = 0;
+ uint accum_value[3] = {0};
+ uchar blend[4] = {0};
+ for (int i = 0; i < totnode; i++) {
+ accum_len += accum[i].len;
+ accum_value[0] += accum[i].value[0];
+ accum_value[1] += accum[i].value[1];
+ accum_value[2] += accum[i].value[2];
+ }
+ if (accum_len != 0) {
+ blend[0] = round_fl_to_uchar(sqrtf(divide_round_i(accum_value[0], accum_len)));
+ blend[1] = round_fl_to_uchar(sqrtf(divide_round_i(accum_value[1], accum_len)));
+ blend[2] = round_fl_to_uchar(sqrtf(divide_round_i(accum_value[2], accum_len)));
+ blend[3] = 255;
+ data->vpd->paintcol = *((uint *)blend);
+ }
+
+ MEM_SAFE_FREE(data->custom_data); /* 'accum' */
+}
+
+static void vpaint_paint_leaves(
+ bContext *C, Sculpt *sd, VPaint *vp, struct VPaintData *vpd,
+ Object *ob, Mesh *me, PBVHNode **nodes, int totnode)
+{
+ const Brush *brush = ob->sculpt->cache->brush;
+
+ SculptThreadedTaskData data = {
+ .sd = sd, .ob = ob, .brush = brush, .nodes = nodes, .vp = vp, .vpd = vpd,
+ .lcol = (uint *)me->mloopcol, .me = me, .C = C,
+ };
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ switch (brush->vertexpaint_tool) {
+ case PAINT_BLEND_AVERAGE:
+ calculate_average_color(&data, nodes, totnode);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_vpaint_brush_draw_task_cb_ex,
+ &settings);
+ break;
+ case PAINT_BLEND_BLUR:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_vpaint_brush_blur_task_cb_ex,
+ &settings);
+ break;
+ case PAINT_BLEND_SMEAR:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_vpaint_brush_smear_task_cb_ex,
+ &settings);
+ break;
+ default:
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_vpaint_brush_draw_task_cb_ex,
+ &settings);
+ break;
+ }
+}
+
+static void vpaint_do_paint(
+ bContext *C, Sculpt *sd, VPaint *vp, struct VPaintData *vpd,
+ Object *ob, Mesh *me, Brush *brush, const char symm, const int axis, const int i, const float angle)
+{
+ SculptSession *ss = ob->sculpt;
+ ss->cache->radial_symmetry_pass = i;
+ sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
+
+ int totnode;
+ PBVHNode **nodes = vwpaint_pbvh_gather_generic(ob, vp, sd, brush, &totnode);
+
+ /* Paint those leaves. */
+ vpaint_paint_leaves(C, sd, vp, vpd, ob, me, nodes, totnode);
- if (alpha > 0.0f) {
- const int alpha_i = (int)(alpha * 255.0f);
- lcol[i] = vpaint_blend(vp, lcol[i], lcolorig[i], paintcol, alpha_i, brush_alpha_pressure_i);
+ if (nodes) {
+ MEM_freeN(nodes);
+ }
+}
- if (mlooptag) mlooptag[i] = 1;
+static void vpaint_do_radial_symmetry(
+ bContext *C, Sculpt *sd, VPaint *vp, struct VPaintData *vpd, Object *ob, Mesh *me,
+ Brush *brush, const char symm, const int axis)
+{
+ for (int i = 1; i < vp->radial_symm[axis - 'X']; i++) {
+ const float angle = (2.0 * M_PI) * i / vp->radial_symm[axis - 'X'];
+ vpaint_do_paint(C, sd, vp, vpd, ob, me, brush, symm, axis, i, angle);
+ }
+}
+
+/* near duplicate of: sculpt.c's, 'do_symmetrical_brush_actions' and 'wpaint_do_symmetrical_brush_actions'. */
+static void vpaint_do_symmetrical_brush_actions(
+ bContext *C, Sculpt *sd, VPaint *vp, struct VPaintData *vpd, Object *ob)
+{
+ Brush *brush = BKE_paint_brush(&vp->paint);
+ Mesh *me = ob->data;
+ SculptSession *ss = ob->sculpt;
+ StrokeCache *cache = ss->cache;
+ const char symm = vp->paint.symmetry_flags & PAINT_SYMM_AXIS_ALL;
+ int i = 0;
+
+ /* initial stroke */
+ vpaint_do_paint(C, sd, vp, vpd, ob, me, brush, i, 'X', 0, 0);
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'X');
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'Y');
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'Z');
+
+ cache->symmetry = symm;
+
+ /* symm is a bit combination of XYZ - 1 is mirror X; 2 is Y; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
+ for (i = 1; i <= symm; i++) {
+ if (symm & i && (symm != 5 || i != 3) && (symm != 6 || (i != 3 && i != 5))) {
+ cache->mirror_symmetry_pass = i;
+ cache->radial_symmetry_pass = 0;
+ sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
+
+ if (i & (1 << 0)) {
+ vpaint_do_paint(C, sd, vp, vpd, ob, me, brush, i, 'X', 0, 0);
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'X');
+ }
+ if (i & (1 << 1)) {
+ vpaint_do_paint(C, sd, vp, vpd, ob, me, brush, i, 'Y', 0, 0);
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'Y');
+ }
+ if (i & (1 << 2)) {
+ vpaint_do_paint(C, sd, vp, vpd, ob, me, brush, i, 'Z', 0, 0);
+ vpaint_do_radial_symmetry(C, sd, vp, vpd, ob, me, brush, i, 'Z');
+ }
}
}
+
+ copy_v3_v3(cache->true_last_location, cache->true_location);
+ cache->is_last_valid = true;
}
static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, PointerRNA *itemptr)
@@ -2796,63 +3050,28 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
ToolSettings *ts = CTX_data_tool_settings(C);
struct VPaintData *vpd = paint_stroke_mode_data(stroke);
VPaint *vp = ts->vpaint;
- Brush *brush = BKE_paint_brush(&vp->paint);
ViewContext *vc = &vpd->vc;
Object *ob = vc->obact;
- Mesh *me = ob->data;
- float mat[4][4];
- int *indexar = vpd->indexar;
- int totindex, index;
- float mval[2];
+ Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
- const float pressure = RNA_float_get(itemptr, "pressure");
- const float brush_size_pressure =
- BKE_brush_size_get(scene, brush) * (BKE_brush_use_size_pressure(scene, brush) ? pressure : 1.0f);
- const float brush_alpha_pressure =
- BKE_brush_alpha_get(scene, brush) * (BKE_brush_use_alpha_pressure(scene, brush) ? pressure : 1.0f);
+ vwpaint_update_cache_variants(C, vp, ob, itemptr);
- RNA_float_get_array(itemptr, "mouse", mval);
+ float mat[4][4];
+ float mval[2];
- view3d_operator_needs_opengl(C);
ED_view3d_init_mats_rv3d(ob, vc->rv3d);
/* load projection matrix */
mul_m4_m4m4(mat, vc->rv3d->persmat, ob->obmat);
- /* which faces are involved */
- totindex = sample_backbuf_area(vc, indexar, me->totpoly, mval[0], mval[1], brush_size_pressure);
-
- if ((me->editflag & ME_EDIT_PAINT_FACE_SEL) && me->mpoly) {
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- const MPoly *mpoly = &me->mpoly[indexar[index] - 1];
-
- if ((mpoly->flag & ME_FACE_SEL) == 0)
- indexar[index] = 0;
- }
- }
- }
-
swap_m4m4(vc->rv3d->persmat, mat);
- /* incase we have modifiers */
- ED_vpaint_proj_handle_update(vpd->vp_handle, vc->ar, mval);
-
- /* clear modified tag for blur tool */
- if (vpd->mlooptag)
- memset(vpd->mlooptag, 0, sizeof(bool) * me->totloop);
+ vpaint_do_symmetrical_brush_actions(C, sd, vp, vpd, ob);
- for (index = 0; index < totindex; index++) {
- if (indexar[index] && indexar[index] <= me->totpoly) {
- vpaint_paint_poly(vp, vpd, me, indexar[index] - 1, mval, brush_size_pressure, brush_alpha_pressure);
- }
- }
-
swap_m4m4(vc->rv3d->persmat, mat);
- /* was disabled because it is slow, but necessary for blur */
- if (brush->vertexpaint_tool == PAINT_BLEND_BLUR) {
- do_shared_vertexcol(me, vpd->mlooptag);
+ if (vp->paint.brush->vertexpaint_tool == PAINT_BLEND_SMEAR) {
+ memcpy(vpd->smear.color_prev, vpd->smear.color_curr, sizeof(uint) * ((Mesh *)ob->data)->totloop);
}
/* calculate pivot for rotation around seletion if needed */
@@ -2874,35 +3093,38 @@ static void vpaint_stroke_update_step(bContext *C, struct PaintStroke *stroke, P
static void vpaint_stroke_done(const bContext *C, struct PaintStroke *stroke)
{
- ToolSettings *ts = CTX_data_tool_settings(C);
struct VPaintData *vpd = paint_stroke_mode_data(stroke);
ViewContext *vc = &vpd->vc;
Object *ob = vc->obact;
- Mesh *me = ob->data;
- ED_vpaint_proj_handle_free(vpd->vp_handle);
- MEM_freeN(vpd->indexar);
-
- /* frees prev buffer */
- copy_vpaint_prev(ts->vpaint, NULL, 0);
+ if (vpd->is_texbrush) {
+ ED_vpaint_proj_handle_free(vpd->vp_handle);
+ }
if (vpd->mlooptag)
MEM_freeN(vpd->mlooptag);
+ if (vpd->smear.color_prev)
+ MEM_freeN(vpd->smear.color_prev);
+ if (vpd->smear.color_curr)
+ MEM_freeN(vpd->smear.color_curr);
WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
- DAG_id_tag_update(&me->id, 0);
MEM_freeN(vpd);
+
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
}
static int vpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
int retval;
- op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
- vpaint_stroke_update_step, NULL,
- vpaint_stroke_done, event->type);
-
+ op->customdata = paint_stroke_new(
+ C, op, sculpt_stroke_get_location, vpaint_stroke_test_start,
+ vpaint_stroke_update_step, NULL,
+ vpaint_stroke_done, event->type);
+
if ((retval = op->type->modal(C, op, event)) == OPERATOR_FINISHED) {
paint_stroke_data_free(op);
return OPERATOR_FINISHED;
@@ -2913,15 +3135,16 @@ static int vpaint_invoke(bContext *C, wmOperator *op, const wmEvent *event)
OPERATOR_RETVAL_CHECK(retval);
BLI_assert(retval == OPERATOR_RUNNING_MODAL);
-
+
return OPERATOR_RUNNING_MODAL;
}
static int vpaint_exec(bContext *C, wmOperator *op)
{
- op->customdata = paint_stroke_new(C, op, NULL, vpaint_stroke_test_start,
- vpaint_stroke_update_step, NULL,
- vpaint_stroke_done, 0);
+ op->customdata = paint_stroke_new(
+ C, op, sculpt_stroke_get_location, vpaint_stroke_test_start,
+ vpaint_stroke_update_step, NULL,
+ vpaint_stroke_done, 0);
/* frees op->customdata */
paint_stroke_exec(C, op);
@@ -2931,6 +3154,12 @@ static int vpaint_exec(bContext *C, wmOperator *op)
static void vpaint_cancel(bContext *C, wmOperator *op)
{
+ Object *ob = CTX_data_active_object(C);
+ if (ob->sculpt->cache) {
+ sculpt_cache_free(ob->sculpt->cache);
+ ob->sculpt->cache = NULL;
+ }
+
paint_stroke_cancel(C, op);
}
@@ -2940,382 +3169,17 @@ void PAINT_OT_vertex_paint(wmOperatorType *ot)
ot->name = "Vertex Paint";
ot->idname = "PAINT_OT_vertex_paint";
ot->description = "Paint a stroke in the active vertex color layer";
-
+
/* api callbacks */
ot->invoke = vpaint_invoke;
ot->modal = paint_stroke_modal;
ot->exec = vpaint_exec;
ot->poll = vertex_paint_poll;
ot->cancel = vpaint_cancel;
-
+
/* flags */
ot->flag = OPTYPE_UNDO | OPTYPE_BLOCKING;
paint_stroke_operator_properties(ot);
}
-/* ********************** weight from bones operator ******************* */
-
-static int weight_from_bones_poll(bContext *C)
-{
- Object *ob = CTX_data_active_object(C);
-
- return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
-}
-
-static int weight_from_bones_exec(bContext *C, wmOperator *op)
-{
- Scene *scene = CTX_data_scene(C);
- Object *ob = CTX_data_active_object(C);
- Object *armob = modifiers_isDeformedByArmature(ob);
- Mesh *me = ob->data;
- int type = RNA_enum_get(op->ptr, "type");
-
- create_vgroups_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
-
- DAG_id_tag_update(&me->id, 0);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
-
- return OPERATOR_FINISHED;
-}
-
-void PAINT_OT_weight_from_bones(wmOperatorType *ot)
-{
- static EnumPropertyItem type_items[] = {
- {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
- {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
- {0, NULL, 0, NULL, NULL}};
-
- /* identifiers */
- ot->name = "Weight from Bones";
- ot->idname = "PAINT_OT_weight_from_bones";
- ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
- "using the distance between the vertices and the bones";
-
- /* api callbacks */
- ot->exec = weight_from_bones_exec;
- ot->invoke = WM_menu_invoke;
- ot->poll = weight_from_bones_poll;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- /* properties */
- ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
-}
-
-/* *** VGroups Gradient *** */
-typedef struct DMGradient_vertStore {
- float sco[2];
- float weight_orig;
- enum {
- VGRAD_STORE_NOP = 0,
- VGRAD_STORE_DW_EXIST = (1 << 0)
- } flag;
-} DMGradient_vertStore;
-
-typedef struct DMGradient_userData {
- struct ARegion *ar;
- Scene *scene;
- Mesh *me;
- Brush *brush;
- const float *sco_start; /* [2] */
- const float *sco_end; /* [2] */
- float sco_line_div; /* store (1.0f / len_v2v2(sco_start, sco_end)) */
- int def_nr;
- bool is_init;
- DMGradient_vertStore *vert_cache;
- /* only for init */
- BLI_bitmap *vert_visit;
-
- /* options */
- short use_select;
- short type;
- float weightpaint;
-} DMGradient_userData;
-
-static void gradientVert_update(DMGradient_userData *grad_data, int index)
-{
- Mesh *me = grad_data->me;
- DMGradient_vertStore *vs = &grad_data->vert_cache[index];
- float alpha;
-
- if (grad_data->type == WPAINT_GRADIENT_TYPE_LINEAR) {
- alpha = line_point_factor_v2(vs->sco, grad_data->sco_start, grad_data->sco_end);
- }
- else {
- BLI_assert(grad_data->type == WPAINT_GRADIENT_TYPE_RADIAL);
- alpha = len_v2v2(grad_data->sco_start, vs->sco) * grad_data->sco_line_div;
- }
- /* no need to clamp 'alpha' yet */
-
- /* adjust weight */
- alpha = BKE_brush_curve_strength_clamped(grad_data->brush, alpha, 1.0f);
-
- if (alpha != 0.0f) {
- MDeformVert *dv = &me->dvert[index];
- MDeformWeight *dw = defvert_verify_index(dv, grad_data->def_nr);
- // dw->weight = alpha; // testing
- int tool = grad_data->brush->vertexpaint_tool;
- float testw;
-
- /* init if we just added */
- testw = wpaint_blend_tool(tool, vs->weight_orig, grad_data->weightpaint, alpha * grad_data->brush->alpha);
- CLAMP(testw, 0.0f, 1.0f);
- dw->weight = testw;
- }
- else {
- MDeformVert *dv = &me->dvert[index];
- if (vs->flag & VGRAD_STORE_DW_EXIST) {
- /* normally we NULL check, but in this case we know it exists */
- MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
- dw->weight = vs->weight_orig;
- }
- else {
- /* wasn't originally existing, remove */
- MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
- if (dw) {
- defvert_remove_group(dv, dw);
- }
- }
- }
-}
-
-static void gradientVertUpdate__mapFunc(
- void *userData, int index, const float UNUSED(co[3]),
- const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
-{
- DMGradient_userData *grad_data = userData;
- Mesh *me = grad_data->me;
- if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
- DMGradient_vertStore *vs = &grad_data->vert_cache[index];
- if (vs->sco[0] != FLT_MAX) {
- gradientVert_update(grad_data, index);
- }
- }
-}
-
-static void gradientVertInit__mapFunc(
- void *userData, int index, const float co[3],
- const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
-{
- DMGradient_userData *grad_data = userData;
- Mesh *me = grad_data->me;
-
- if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
- /* run first pass only,
- * the screen coords of the verts need to be cached because
- * updating the mesh may move them about (entering feedback loop) */
-
- if (BLI_BITMAP_TEST(grad_data->vert_visit, index) == 0) {
- DMGradient_vertStore *vs = &grad_data->vert_cache[index];
- if (ED_view3d_project_float_object(grad_data->ar,
- co, vs->sco,
- V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
- {
- /* ok */
- MDeformVert *dv = &me->dvert[index];
- MDeformWeight *dw;
- dw = defvert_find_index(dv, grad_data->def_nr);
- if (dw) {
- vs->weight_orig = dw->weight;
- vs->flag = VGRAD_STORE_DW_EXIST;
- }
- else {
- vs->weight_orig = 0.0f;
- vs->flag = VGRAD_STORE_NOP;
- }
-
- BLI_BITMAP_ENABLE(grad_data->vert_visit, index);
-
- gradientVert_update(grad_data, index);
- }
- else {
- /* no go */
- copy_v2_fl(vs->sco, FLT_MAX);
- }
- }
- }
-}
-
-static int paint_weight_gradient_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- int ret = WM_gesture_straightline_modal(C, op, event);
-
- if (ret & OPERATOR_RUNNING_MODAL) {
- if (event->type == LEFTMOUSE && event->val == KM_RELEASE) { /* XXX, hardcoded */
- /* generally crap! redo! */
- WM_gesture_straightline_cancel(C, op);
- ret &= ~OPERATOR_RUNNING_MODAL;
- ret |= OPERATOR_FINISHED;
- }
- }
-
- if (ret & OPERATOR_CANCELLED) {
- ToolSettings *ts = CTX_data_tool_settings(C);
- VPaint *wp = ts->wpaint;
- Object *ob = CTX_data_active_object(C);
- Mesh *me = ob->data;
- if (wp->wpaint_prev) {
- BKE_defvert_array_free_elems(me->dvert, me->totvert);
- BKE_defvert_array_copy(me->dvert, wp->wpaint_prev, me->totvert);
- free_wpaint_prev(wp);
- }
-
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
- }
- else if (ret & OPERATOR_FINISHED) {
- ToolSettings *ts = CTX_data_tool_settings(C);
- VPaint *wp = ts->wpaint;
- free_wpaint_prev(wp);
- }
-
- return ret;
-}
-
-static int paint_weight_gradient_exec(bContext *C, wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
- DMGradient_vertStore *vert_cache;
- struct ARegion *ar = CTX_wm_region(C);
- Scene *scene = CTX_data_scene(C);
- Object *ob = CTX_data_active_object(C);
- Mesh *me = ob->data;
- int x_start = RNA_int_get(op->ptr, "xstart");
- int y_start = RNA_int_get(op->ptr, "ystart");
- int x_end = RNA_int_get(op->ptr, "xend");
- int y_end = RNA_int_get(op->ptr, "yend");
- float sco_start[2] = {x_start, y_start};
- float sco_end[2] = {x_end, y_end};
- const bool is_interactive = (gesture != NULL);
- DerivedMesh *dm = mesh_get_derived_final(scene, ob, scene->customdata_mask);
-
- DMGradient_userData data = {NULL};
-
- if (is_interactive) {
- if (gesture->userdata == NULL) {
- VPaint *wp = scene->toolsettings->wpaint;
-
- gesture->userdata = MEM_mallocN(sizeof(DMGradient_vertStore) * me->totvert, __func__);
- data.is_init = true;
-
- copy_wpaint_prev(wp, me->dvert, me->totvert);
-
- /* on init only, convert face -> vert sel */
- if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
- BKE_mesh_flush_select_from_polys(me);
- }
- }
-
- vert_cache = gesture->userdata;
- }
- else {
- if (wpaint_ensure_data(C, op, 0, NULL) == false) {
- return OPERATOR_CANCELLED;
- }
-
- data.is_init = true;
- vert_cache = MEM_mallocN(sizeof(DMGradient_vertStore) * me->totvert, __func__);
- }
-
- data.ar = ar;
- data.scene = scene;
- data.me = ob->data;
- data.sco_start = sco_start;
- data.sco_end = sco_end;
- data.sco_line_div = 1.0f / len_v2v2(sco_start, sco_end);
- data.def_nr = ob->actdef - 1;
- data.use_select = (me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL));
- data.vert_cache = vert_cache;
- data.vert_visit = NULL;
- data.type = RNA_enum_get(op->ptr, "type");
-
- {
- ToolSettings *ts = CTX_data_tool_settings(C);
- VPaint *wp = ts->wpaint;
- struct Brush *brush = BKE_paint_brush(&wp->paint);
-
- curvemapping_initialize(brush->curve);
-
- data.brush = brush;
- data.weightpaint = BKE_brush_weight_get(scene, brush);
- }
-
- ED_view3d_init_mats_rv3d(ob, ar->regiondata);
-
- if (data.is_init) {
- data.vert_visit = BLI_BITMAP_NEW(me->totvert, __func__);
-
- dm->foreachMappedVert(dm, gradientVertInit__mapFunc, &data, DM_FOREACH_NOP);
-
- MEM_freeN(data.vert_visit);
- data.vert_visit = NULL;
- }
- else {
- dm->foreachMappedVert(dm, gradientVertUpdate__mapFunc, &data, DM_FOREACH_NOP);
- }
-
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
-
- if (is_interactive == false) {
- MEM_freeN(vert_cache);
- }
-
- return OPERATOR_FINISHED;
-}
-
-static int paint_weight_gradient_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- int ret;
-
- if (wpaint_ensure_data(C, op, 0, NULL) == false) {
- return OPERATOR_CANCELLED;
- }
-
- ret = WM_gesture_straightline_invoke(C, op, event);
- if (ret & OPERATOR_RUNNING_MODAL) {
- struct ARegion *ar = CTX_wm_region(C);
- if (ar->regiontype == RGN_TYPE_WINDOW) {
- /* TODO, hardcoded, extend WM_gesture_straightline_ */
- if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
- wmGesture *gesture = op->customdata;
- gesture->mode = 1;
- }
- }
- }
- return ret;
-}
-
-void PAINT_OT_weight_gradient(wmOperatorType *ot)
-{
- /* defined in DNA_space_types.h */
- static EnumPropertyItem gradient_types[] = {
- {WPAINT_GRADIENT_TYPE_LINEAR, "LINEAR", 0, "Linear", ""},
- {WPAINT_GRADIENT_TYPE_RADIAL, "RADIAL", 0, "Radial", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
- PropertyRNA *prop;
-
- /* identifiers */
- ot->name = "Weight Gradient";
- ot->idname = "PAINT_OT_weight_gradient";
- ot->description = "Draw a line to apply a weight gradient to selected vertices";
-
- /* api callbacks */
- ot->invoke = paint_weight_gradient_invoke;
- ot->modal = paint_weight_gradient_modal;
- ot->exec = paint_weight_gradient_exec;
- ot->poll = weight_paint_poll;
- ot->cancel = WM_gesture_straightline_cancel;
-
- /* flags */
- ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
- prop = RNA_def_enum(ot->srna, "type", gradient_types, 0, "Type", "");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
-
- WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
-}
diff --git a/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c b/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c
new file mode 100644
index 00000000000..b69ca32e5af
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_vertex_color_ops.c
@@ -0,0 +1,574 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_vertex_color_ops.c
+ * \ingroup edsculpt
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BLI_math_base.h"
+#include "BLI_math_color.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_mesh.h"
+#include "BKE_deform.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_mesh.h"
+
+#include "paint_intern.h" /* own include */
+
+
+static int vertex_weight_paint_mode_poll(bContext *C)
+{
+ Object *ob = CTX_data_active_object(C);
+ Mesh *me = BKE_mesh_from_object(ob);
+ return (ob && (ob->mode == OB_MODE_VERTEX_PAINT || ob->mode == OB_MODE_WEIGHT_PAINT)) &&
+ (me && me->totpoly && me->dvert);
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Set Vertex Colors Operator
+ * \{ */
+
+static bool vertex_color_set(Object *ob, uint paintcol)
+{
+ Mesh *me;
+ const MPoly *mp;
+ int i, j;
+
+ if (((me = BKE_mesh_from_object(ob)) == NULL) ||
+ (ED_mesh_color_ensure(me, NULL) == false))
+ {
+ return false;
+ }
+
+ const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+
+ mp = me->mpoly;
+ for (i = 0; i < me->totpoly; i++, mp++) {
+ MLoopCol *lcol = me->mloopcol + mp->loopstart;
+
+ if (use_face_sel && !(mp->flag & ME_FACE_SEL))
+ continue;
+
+ j = 0;
+ do {
+ uint vidx = me->mloop[mp->loopstart + j].v;
+ if (!(use_vert_sel && !(me->mvert[vidx].flag & SELECT))) {
+ *(int *)lcol = paintcol;
+ }
+ lcol++;
+ j++;
+ } while (j < mp->totloop);
+
+ }
+
+ /* remove stale me->mcol, will be added later */
+ BKE_mesh_tessface_clear(me);
+
+ DAG_id_tag_update(&me->id, 0);
+
+ return true;
+}
+
+static int vertex_color_set_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *obact = CTX_data_active_object(C);
+ unsigned int paintcol = vpaint_get_current_col(scene, scene->toolsettings->vpaint);
+
+ if (vertex_color_set(obact, paintcol)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_set(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Set Vertex Colors";
+ ot->idname = "PAINT_OT_vertex_color_set";
+ ot->description = "Fill the active vertex color layer with the current paint color";
+
+ /* api callbacks */
+ ot->exec = vertex_color_set_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Vertex Color from Weight Operator
+ * \{ */
+
+static bool vertex_paint_from_weight(Object *ob)
+{
+ Mesh *me;
+ const MPoly *mp;
+ int vgroup_active;
+
+ if (((me = BKE_mesh_from_object(ob)) == NULL ||
+ (ED_mesh_color_ensure(me, NULL)) == false))
+ {
+ return false;
+ }
+
+ /* TODO: respect selection. */
+ mp = me->mpoly;
+ vgroup_active = ob->actdef - 1;
+ for (int i = 0; i < me->totpoly; i++, mp++) {
+ MLoopCol *lcol = &me->mloopcol[mp->loopstart];
+ uint j = 0;
+ do {
+ uint vidx = me->mloop[mp->loopstart + j].v;
+ const float weight = defvert_find_weight(&me->dvert[vidx], vgroup_active);
+ const uchar grayscale = weight * 255;
+ lcol->r = grayscale;
+ lcol->b = grayscale;
+ lcol->g = grayscale;
+ lcol++;
+ j++;
+ } while (j < mp->totloop);
+ }
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+
+ return true;
+}
+
+static int vertex_paint_from_weight_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Object *obact = CTX_data_active_object(C);
+ if (vertex_paint_from_weight(obact)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_from_weight(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Vertex Color from Weight";
+ ot->idname = "PAINT_OT_vertex_color_from_weight";
+ ot->description = "Convert active weight into gray scale vertex colors";
+
+ /* api callback */
+ ot->exec = vertex_paint_from_weight_exec;
+ ot->poll = vertex_weight_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* TODO: invert, alpha */
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Smooth Vertex Colors Operator
+ * \{ */
+
+static void vertex_color_smooth_looptag(Mesh *me, bool *mlooptag)
+{
+ const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ const MPoly *mp;
+ int (*scol)[4];
+ int i, j;
+ bool has_shared = false;
+
+ /* if no mloopcol: do not do */
+ /* if mtexpoly: only the involved faces, otherwise all */
+
+ if (me->mloopcol == NULL || me->totvert == 0 || me->totpoly == 0) return;
+
+ scol = MEM_callocN(sizeof(int) * me->totvert * 5, "scol");
+
+ for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
+ if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
+ const MLoop *ml = me->mloop + mp->loopstart;
+ MLoopCol *lcol = me->mloopcol + mp->loopstart;
+ for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
+ scol[ml->v][0] += lcol->r;
+ scol[ml->v][1] += lcol->g;
+ scol[ml->v][2] += lcol->b;
+ scol[ml->v][3] += 1;
+ has_shared = 1;
+ }
+ }
+ }
+
+ if (has_shared) {
+ for (i = 0; i < me->totvert; i++) {
+ if (scol[i][3] != 0) {
+ scol[i][0] = divide_round_i(scol[i][0], scol[i][3]);
+ scol[i][1] = divide_round_i(scol[i][1], scol[i][3]);
+ scol[i][2] = divide_round_i(scol[i][2], scol[i][3]);
+ }
+ }
+
+ for (i = 0, mp = me->mpoly; i < me->totpoly; i++, mp++) {
+ if ((use_face_sel == false) || (mp->flag & ME_FACE_SEL)) {
+ const MLoop *ml = me->mloop + mp->loopstart;
+ MLoopCol *lcol = me->mloopcol + mp->loopstart;
+ for (j = 0; j < mp->totloop; j++, ml++, lcol++) {
+ if (mlooptag[mp->loopstart + j]) {
+ lcol->r = scol[ml->v][0];
+ lcol->g = scol[ml->v][1];
+ lcol->b = scol[ml->v][2];
+ }
+ }
+ }
+ }
+ }
+
+ MEM_freeN(scol);
+}
+
+static bool vertex_color_smooth(Object *ob)
+{
+ Mesh *me;
+ const MPoly *mp;
+
+ int i, j;
+
+ bool *mlooptag;
+
+ if (((me = BKE_mesh_from_object(ob)) == NULL) ||
+ (ED_mesh_color_ensure(me, NULL) == false))
+ {
+ return false;
+ }
+
+ const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+
+ mlooptag = MEM_callocN(sizeof(bool) * me->totloop, "VPaintData mlooptag");
+
+ /* simply tag loops of selected faces */
+ mp = me->mpoly;
+ for (i = 0; i < me->totpoly; i++, mp++) {
+ const MLoop *ml = me->mloop + mp->loopstart;
+ int ml_index = mp->loopstart;
+
+ if (use_face_sel && !(mp->flag & ME_FACE_SEL))
+ continue;
+
+ for (j = 0; j < mp->totloop; j++, ml_index++, ml++) {
+ mlooptag[ml_index] = true;
+ }
+ }
+
+ /* remove stale me->mcol, will be added later */
+ BKE_mesh_tessface_clear(me);
+
+ vertex_color_smooth_looptag(me, mlooptag);
+
+ MEM_freeN(mlooptag);
+
+ DAG_id_tag_update(&me->id, 0);
+
+ return true;
+}
+
+
+static int vertex_color_smooth_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Object *obact = CTX_data_active_object(C);
+ if (vertex_color_smooth(obact)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_smooth(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Smooth Vertex Colors";
+ ot->idname = "PAINT_OT_vertex_color_smooth";
+ ot->description = "Smooth colors across vertices";
+
+ /* api callbacks */
+ ot->exec = vertex_color_smooth_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Vertex Color Transformation Operators
+ * \{ */
+
+struct VPaintTx_BrightContrastData {
+ /* pre-calculated */
+ float gain;
+ float offset;
+};
+
+static void vpaint_tx_brightness_contrast(const float col[3], const void *user_data, float r_col[3])
+{
+ const struct VPaintTx_BrightContrastData *data = user_data;
+
+ for (int i = 0; i < 3; i++) {
+ r_col[i] = data->gain * col[i] + data->offset;
+ }
+}
+
+static int vertex_color_brightness_contrast_exec(bContext *C, wmOperator *op)
+{
+ Object *obact = CTX_data_active_object(C);
+
+ float gain, offset;
+ {
+ float brightness = RNA_float_get(op->ptr, "brightness");
+ float contrast = RNA_float_get(op->ptr, "contrast");
+ brightness /= 100.0f;
+ float delta = contrast / 200.0f;
+ gain = 1.0f - delta * 2.0f;
+ /*
+ * The algorithm is by Werner D. Streidt
+ * (http://visca.com/ffactory/archives/5-99/msg00021.html)
+ * Extracted of OpenCV demhist.c
+ */
+ if (contrast > 0) {
+ gain = 1.0f / ((gain != 0.0f) ? gain : FLT_EPSILON);
+ offset = gain * (brightness - delta);
+ }
+ else {
+ delta *= -1;
+ offset = gain * (brightness + delta);
+ }
+ }
+
+ const struct VPaintTx_BrightContrastData user_data = {
+ .gain = gain,
+ .offset = offset,
+ };
+
+ if (ED_vpaint_color_transform(obact, vpaint_tx_brightness_contrast, &user_data)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_brightness_contrast(wmOperatorType *ot)
+{
+ PropertyRNA *prop;
+
+ /* identifiers */
+ ot->name = "Vertex Paint Bright/Contrast";
+ ot->idname = "PAINT_OT_vertex_color_brightness_contrast";
+ ot->description = "Adjust vertex color brightness/contrast";
+
+ /* api callbacks */
+ ot->exec = vertex_color_brightness_contrast_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* params */
+ const float min = -100, max = +100;
+ prop = RNA_def_float(ot->srna, "brightness", 0.0f, min, max, "Brightness", "", min, max);
+ prop = RNA_def_float(ot->srna, "contrast", 0.0f, min, max, "Contrast", "", min, max);
+ RNA_def_property_ui_range(prop, min, max, 1, 1);
+}
+
+struct VPaintTx_HueSatData {
+ float hue;
+ float sat;
+ float val;
+};
+
+static void vpaint_tx_hsv(const float col[3], const void *user_data, float r_col[3])
+{
+ const struct VPaintTx_HueSatData *data = user_data;
+ float hsv[3];
+ rgb_to_hsv_v(col, hsv);
+
+ hsv[0] += (data->hue - 0.5f);
+ if (hsv[0] > 1.0f) {
+ hsv[0] -= 1.0f;
+ }
+ else if (hsv[0] < 0.0f) {
+ hsv[0] += 1.0f;
+ }
+ hsv[1] *= data->sat;
+ hsv[2] *= data->val;
+
+ hsv_to_rgb_v(hsv, r_col);
+}
+
+static int vertex_color_hsv_exec(bContext *C, wmOperator *op)
+{
+ Object *obact = CTX_data_active_object(C);
+
+ const struct VPaintTx_HueSatData user_data = {
+ .hue = RNA_float_get(op->ptr, "h"),
+ .sat = RNA_float_get(op->ptr, "s"),
+ .val = RNA_float_get(op->ptr, "v"),
+ };
+
+ if (ED_vpaint_color_transform(obact, vpaint_tx_hsv, &user_data)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_hsv(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Vertex Paint Hue Saturation Value";
+ ot->idname = "PAINT_OT_vertex_color_hsv";
+ ot->description = "Adjust vertex color HSV values";
+
+ /* api callbacks */
+ ot->exec = vertex_color_hsv_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* params */
+ RNA_def_float(ot->srna, "h", 0.5f, 0.0f, 1.0f, "Hue", "", 0.0f, 1.0f);
+ RNA_def_float(ot->srna, "s", 1.0f, 0.0f, 2.0f, "Saturation", "", 0.0f, 2.0f);
+ RNA_def_float(ot->srna, "v", 1.0f, 0.0f, 2.0f, "Value", "", 0.0f, 2.0f);
+}
+
+static void vpaint_tx_invert(const float col[3], const void *UNUSED(user_data), float r_col[3])
+{
+ for (int i = 0; i < 3; i++) {
+ r_col[i] = 1.0f - col[i];
+ }
+}
+
+static int vertex_color_invert_exec(bContext *C, wmOperator *UNUSED(op))
+{
+ Object *obact = CTX_data_active_object(C);
+
+ if (ED_vpaint_color_transform(obact, vpaint_tx_invert, NULL)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_invert(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Vertex Paint Invert";
+ ot->idname = "PAINT_OT_vertex_color_invert";
+ ot->description = "Invert RGB values";
+
+ /* api callbacks */
+ ot->exec = vertex_color_invert_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+
+struct VPaintTx_LevelsData {
+ float gain;
+ float offset;
+};
+
+static void vpaint_tx_levels(const float col[3], const void *user_data, float r_col[3])
+{
+ const struct VPaintTx_LevelsData *data = user_data;
+ for (int i = 0; i < 3; i++) {
+ r_col[i] = data->gain * (col[i] + data->offset);
+ }
+}
+
+static int vertex_color_levels_exec(bContext *C, wmOperator *op)
+{
+ Object *obact = CTX_data_active_object(C);
+
+ const struct VPaintTx_LevelsData user_data = {
+ .gain = RNA_float_get(op->ptr, "gain"),
+ .offset = RNA_float_get(op->ptr, "offset"),
+ };
+
+ if (ED_vpaint_color_transform(obact, vpaint_tx_levels, &user_data)) {
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, obact);
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_vertex_color_levels(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Vertex Paint Levels";
+ ot->idname = "PAINT_OT_vertex_color_levels";
+ ot->description = "Adjust levels of vertex colors";
+
+ /* api callbacks */
+ ot->exec = vertex_color_levels_exec;
+ ot->poll = vertex_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* params */
+ RNA_def_float(ot->srna, "offset", 0.0f, -1.0f, 1.0f, "Offset", "Value to add to colors", -1.0f, 1.0f);
+ RNA_def_float(ot->srna, "gain", 1.0f, 0.0f, FLT_MAX, "Gain", "Value to multiply colors by", 0.0f, 10.0f);
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/paint_vertex_color_utils.c b/source/blender/editors/sculpt_paint/paint_vertex_color_utils.c
new file mode 100644
index 00000000000..a0bd5ea2a2d
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_vertex_color_utils.c
@@ -0,0 +1,648 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_vertex_color_utils.c
+ * \ingroup edsculpt
+ *
+ * Intended for use by `paint_vertex.c` & `paint_vertex_color_ops.c`.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_brush_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_meshdata_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BLI_math_base.h"
+#include "BLI_math_color.h"
+
+#include "IMB_colormanagement.h"
+
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_mesh.h"
+
+#include "ED_mesh.h"
+
+#include "paint_intern.h" /* own include */
+
+#define EPS_SATURATION 0.0005f
+
+/**
+ * Apply callback to each vertex of the active vertex color layer.
+ */
+bool ED_vpaint_color_transform(
+ struct Object *ob,
+ VPaintTransform_Callback vpaint_tx_fn,
+ const void *user_data)
+{
+ Mesh *me;
+ const MPoly *mp;
+
+ if (((me = BKE_mesh_from_object(ob)) == NULL) ||
+ (ED_mesh_color_ensure(me, NULL) == false))
+ {
+ return false;
+ }
+
+ const bool use_face_sel = (me->editflag & ME_EDIT_PAINT_FACE_SEL) != 0;
+ mp = me->mpoly;
+
+ for (int i = 0; i < me->totpoly; i++, mp++) {
+ MLoopCol *lcol = &me->mloopcol[mp->loopstart];
+
+ if (use_face_sel && !(mp->flag & ME_FACE_SEL)) {
+ continue;
+ }
+
+ for (int j = 0; j < mp->totloop; j++, lcol++) {
+ float col_mix[3];
+ rgb_uchar_to_float(col_mix, &lcol->r);
+
+ vpaint_tx_fn(col_mix, user_data, col_mix);
+
+ rgb_float_to_uchar(&lcol->r, col_mix);
+ }
+ }
+
+ /* remove stale me->mcol, will be added later */
+ BKE_mesh_tessface_clear(me);
+
+ DAG_id_tag_update(&me->id, 0);
+
+ return true;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Color Blending Modes
+ * \{ */
+
+BLI_INLINE uint mcol_blend(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ if (fac >= 255) {
+ return col_dst;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ /* Updated to use the rgb squared color model which blends nicer. */
+ int r1 = cp_src[0] * cp_src[0];
+ int g1 = cp_src[1] * cp_src[1];
+ int b1 = cp_src[2] * cp_src[2];
+ int a1 = cp_src[3] * cp_src[3];
+
+ int r2 = cp_dst[0] * cp_dst[0];
+ int g2 = cp_dst[1] * cp_dst[1];
+ int b2 = cp_dst[2] * cp_dst[2];
+ int a2 = cp_dst[3] * cp_dst[3];
+
+ cp_mix[0] = round_fl_to_uchar(sqrtf(divide_round_i((mfac * r1 + fac * r2), 255)));
+ cp_mix[1] = round_fl_to_uchar(sqrtf(divide_round_i((mfac * g1 + fac * g2), 255)));
+ cp_mix[2] = round_fl_to_uchar(sqrtf(divide_round_i((mfac * b1 + fac * b2), 255)));
+ cp_mix[3] = round_fl_to_uchar(sqrtf(divide_round_i((mfac * a1 + fac * a2), 255)));
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_add(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = cp_src[0] + divide_round_i((fac * cp_dst[0]), 255);
+ cp_mix[0] = (temp > 254) ? 255 : temp;
+ temp = cp_src[1] + divide_round_i((fac * cp_dst[1]), 255);
+ cp_mix[1] = (temp > 254) ? 255 : temp;
+ temp = cp_src[2] + divide_round_i((fac * cp_dst[2]), 255);
+ cp_mix[2] = (temp > 254) ? 255 : temp;
+ temp = cp_src[3] + divide_round_i((fac * cp_dst[3]), 255);
+ cp_mix[3] = (temp > 254) ? 255 : temp;
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_sub(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = cp_src[0] - divide_round_i((fac * cp_dst[0]), 255);
+ cp_mix[0] = (temp < 0) ? 0 : temp;
+ temp = cp_src[1] - divide_round_i((fac * cp_dst[1]), 255);
+ cp_mix[1] = (temp < 0) ? 0 : temp;
+ temp = cp_src[2] - divide_round_i((fac * cp_dst[2]), 255);
+ cp_mix[2] = (temp < 0) ? 0 : temp;
+ temp = cp_src[3] - divide_round_i((fac * cp_dst[3]), 255);
+ cp_mix[3] = (temp < 0) ? 0 : temp;
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_mul(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ /* first mul, then blend the fac */
+ cp_mix[0] = divide_round_i(mfac * cp_src[0] * 255 + fac * cp_dst[0] * cp_src[0], 255 * 255);
+ cp_mix[1] = divide_round_i(mfac * cp_src[1] * 255 + fac * cp_dst[1] * cp_src[1], 255 * 255);
+ cp_mix[2] = divide_round_i(mfac * cp_src[2] * 255 + fac * cp_dst[2] * cp_src[2], 255 * 255);
+ cp_mix[3] = divide_round_i(mfac * cp_src[3] * 255 + fac * cp_dst[3] * cp_src[3], 255 * 255);
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_lighten(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+ else if (fac >= 255) {
+ return col_dst;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ /* See if are lighter, if so mix, else don't do anything.
+ * if the paint color is darker then the original, then ignore */
+ if (IMB_colormanagement_get_luminance_byte(cp_src) > IMB_colormanagement_get_luminance_byte(cp_dst)) {
+ return col_src;
+ }
+
+ cp_mix[0] = divide_round_i(mfac * cp_src[0] + fac * cp_dst[0], 255);
+ cp_mix[1] = divide_round_i(mfac * cp_src[1] + fac * cp_dst[1], 255);
+ cp_mix[2] = divide_round_i(mfac * cp_src[2] + fac * cp_dst[2], 255);
+ cp_mix[3] = divide_round_i(mfac * cp_src[3] + fac * cp_dst[3], 255);
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_darken(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+ else if (fac >= 255) {
+ return col_dst;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ /* See if were darker, if so mix, else don't do anything.
+ * if the paint color is brighter then the original, then ignore */
+ if (IMB_colormanagement_get_luminance_byte(cp_src) < IMB_colormanagement_get_luminance_byte(cp_dst)) {
+ return col_src;
+ }
+
+ cp_mix[0] = divide_round_i((mfac * cp_src[0] + fac * cp_dst[0]), 255);
+ cp_mix[1] = divide_round_i((mfac * cp_src[1] + fac * cp_dst[1]), 255);
+ cp_mix[2] = divide_round_i((mfac * cp_src[2] + fac * cp_dst[2]), 255);
+ cp_mix[3] = divide_round_i((mfac * cp_src[3] + fac * cp_dst[3]), 255);
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_colordodge(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = (cp_dst[0] == 255) ? 255 : min_ii((cp_src[0] * 225) / (255 - cp_dst[0]), 255);
+ cp_mix[0] = (mfac * cp_src[0] + temp * fac) / 255;
+ temp = (cp_dst[1] == 255) ? 255 : min_ii((cp_src[1] * 225) / (255 - cp_dst[1]), 255);
+ cp_mix[1] = (mfac * cp_src[1] + temp * fac) / 255;
+ temp = (cp_dst[2] == 255) ? 255 : min_ii((cp_src[2] * 225) / (255 - cp_dst[2]), 255);
+ cp_mix[2] = (mfac * cp_src[2] + temp * fac) / 255;
+ temp = (cp_dst[3] == 255) ? 255 : min_ii((cp_src[3] * 225) / (255 - cp_dst[3]), 255);
+ cp_mix[3] = (mfac * cp_src[3] + temp * fac) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_difference(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = abs(cp_src[0] - cp_dst[0]);
+ cp_mix[0] = (mfac * cp_src[0] + temp * fac) / 255;
+ temp = abs(cp_src[1] - cp_dst[1]);
+ cp_mix[1] = (mfac * cp_src[1] + temp * fac) / 255;
+ temp = abs(cp_src[2] - cp_dst[2]);
+ cp_mix[2] = (mfac * cp_src[2] + temp * fac) / 255;
+ temp = abs(cp_src[3] - cp_dst[3]);
+ cp_mix[3] = (mfac * cp_src[3] + temp * fac) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_screen(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = max_ii(255 - (((255 - cp_src[0]) * (255 - cp_dst[0])) / 255), 0);
+ cp_mix[0] = (mfac * cp_src[0] + temp * fac) / 255;
+ temp = max_ii(255 - (((255 - cp_src[1]) * (255 - cp_dst[1])) / 255), 0);
+ cp_mix[1] = (mfac * cp_src[1] + temp * fac) / 255;
+ temp = max_ii(255 - (((255 - cp_src[2]) * (255 - cp_dst[2])) / 255), 0);
+ cp_mix[2] = (mfac * cp_src[2] + temp * fac) / 255;
+ temp = max_ii(255 - (((255 - cp_src[3]) * (255 - cp_dst[3])) / 255), 0);
+ cp_mix[3] = (mfac * cp_src[3] + temp * fac) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_hardlight(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ int i = 0;
+
+ for (i = 0; i < 4; i++) {
+ if (cp_dst[i] > 127) {
+ temp = 255 - ((255 - 2 * (cp_dst[i] - 127)) * (255 - cp_src[i]) / 255);
+ }
+ else {
+ temp = (2 * cp_dst[i] * cp_src[i]) >> 8;
+ }
+ cp_mix[i] = min_ii((mfac * cp_src[i] + temp * fac) / 255, 255);
+ }
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_overlay(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ int i = 0;
+
+ for (i = 0; i < 4; i++) {
+ if (cp_src[i] > 127) {
+ temp = 255 - ((255 - 2 * (cp_src[i] - 127)) * (255 - cp_dst[i]) / 255);
+ }
+ else {
+ temp = (2 * cp_dst[i] * cp_src[i]) >> 8;
+ }
+ cp_mix[i] = min_ii((mfac * cp_src[i] + temp * fac) / 255, 255);
+ }
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_softlight(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ int i = 0;
+
+ for (i = 0; i < 4; i++) {
+ if (cp_src[i] < 127) {
+ temp = ((2 * ((cp_dst[i] / 2) + 64)) * cp_src[i]) / 255;
+ }
+ else {
+ temp = 255 - (2 * (255 - ((cp_dst[i] / 2) + 64)) * (255 - cp_src[i]) / 255);
+ }
+ cp_mix[i] = (temp * fac + cp_src[i] * mfac) / 255;
+ }
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_exclusion(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac, temp;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ int i = 0;
+
+ for (i = 0; i < 4; i++) {
+ temp = 127 - ((2 * (cp_src[i] - 127) * (cp_dst[i] - 127)) / 255);
+ cp_mix[i] = (temp * fac + cp_src[i] * mfac) / 255;
+ }
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_luminosity(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ float h1, s1, v1;
+ float h2, s2, v2;
+ float r, g, b;
+ rgb_to_hsv(cp_src[0] / 255.0f, cp_src[1] / 255.0f, cp_src[2] / 255.0f, &h1, &s1, &v1);
+ rgb_to_hsv(cp_dst[0] / 255.0f, cp_dst[1] / 255.0f, cp_dst[2] / 255.0f, &h2, &s2, &v2);
+
+ v1 = v2;
+
+ hsv_to_rgb(h1, s1, v1, &r, &g, &b);
+
+ cp_mix[0] = ((int)(r * 255.0f) * fac + mfac * cp_src[0]) / 255;
+ cp_mix[1] = ((int)(g * 255.0f) * fac + mfac * cp_src[1]) / 255;
+ cp_mix[2] = ((int)(b * 255.0f) * fac + mfac * cp_src[2]) / 255;
+ cp_mix[3] = ((int)(cp_dst[3]) * fac + mfac * cp_src[3]) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_saturation(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ float h1, s1, v1;
+ float h2, s2, v2;
+ float r, g, b;
+ rgb_to_hsv(cp_src[0] / 255.0f, cp_src[1] / 255.0f, cp_src[2] / 255.0f, &h1, &s1, &v1);
+ rgb_to_hsv(cp_dst[0] / 255.0f, cp_dst[1] / 255.0f, cp_dst[2] / 255.0f, &h2, &s2, &v2);
+
+ if (s1 > EPS_SATURATION) {
+ s1 = s2;
+ }
+
+ hsv_to_rgb(h1, s1, v1, &r, &g, &b);
+
+ cp_mix[0] = ((int)(r * 255.0f) * fac + mfac * cp_src[0]) / 255;
+ cp_mix[1] = ((int)(g * 255.0f) * fac + mfac * cp_src[1]) / 255;
+ cp_mix[2] = ((int)(b * 255.0f) * fac + mfac * cp_src[2]) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_hue(uint col_src, uint col_dst, int fac)
+{
+ uchar *cp_src, *cp_dst, *cp_mix;
+ int mfac;
+ uint col_mix = 0;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ mfac = 255 - fac;
+
+ cp_src = (uchar *)&col_src;
+ cp_dst = (uchar *)&col_dst;
+ cp_mix = (uchar *)&col_mix;
+
+ float h1, s1, v1;
+ float h2, s2, v2;
+ float r, g, b;
+ rgb_to_hsv(cp_src[0] / 255.0f, cp_src[1] / 255.0f, cp_src[2] / 255.0f, &h1, &s1, &v1);
+ rgb_to_hsv(cp_dst[0] / 255.0f, cp_dst[1] / 255.0f, cp_dst[2] / 255.0f, &h2, &s2, &v2);
+
+ h1 = h2;
+
+ hsv_to_rgb(h1, s1, v1, &r, &g, &b);
+
+ cp_mix[0] = ((int)(r * 255.0f) * fac + mfac * cp_src[0]) / 255;
+ cp_mix[1] = ((int)(g * 255.0f) * fac + mfac * cp_src[1]) / 255;
+ cp_mix[2] = ((int)(b * 255.0f) * fac + mfac * cp_src[2]) / 255;
+ cp_mix[3] = ((int)(cp_dst[3]) * fac + mfac * cp_src[3]) / 255;
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_alpha_add(uint col_src, int fac)
+{
+ uchar *cp_src, *cp_mix;
+ int temp;
+ uint col_mix = col_src;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ cp_src = (uchar *)&col_src;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = cp_src[3] + fac;
+ cp_mix[3] = (temp > 254) ? 255 : temp;
+
+ return col_mix;
+}
+
+BLI_INLINE uint mcol_alpha_sub(uint col_src, int fac)
+{
+ uchar *cp_src, *cp_mix;
+ int temp;
+ uint col_mix = col_src;
+
+ if (fac == 0) {
+ return col_src;
+ }
+
+ cp_src = (uchar *)&col_src;
+ cp_mix = (uchar *)&col_mix;
+
+ temp = cp_src[3] - fac;
+ cp_mix[3] = temp < 0 ? 0 : temp;
+
+ return col_mix;
+}
+
+/* wpaint has 'ED_wpaint_blend_tool' */
+uint ED_vpaint_blend_tool(
+ const int tool, const uint col,
+ const uint paintcol, const int alpha_i)
+{
+ switch (tool) {
+ case PAINT_BLEND_MIX:
+ case PAINT_BLEND_BLUR: return mcol_blend(col, paintcol, alpha_i);
+ case PAINT_BLEND_AVERAGE: return mcol_blend(col, paintcol, alpha_i);
+ case PAINT_BLEND_SMEAR: return mcol_blend(col, paintcol, alpha_i);
+ case PAINT_BLEND_ADD: return mcol_add(col, paintcol, alpha_i);
+ case PAINT_BLEND_SUB: return mcol_sub(col, paintcol, alpha_i);
+ case PAINT_BLEND_MUL: return mcol_mul(col, paintcol, alpha_i);
+ case PAINT_BLEND_LIGHTEN: return mcol_lighten(col, paintcol, alpha_i);
+ case PAINT_BLEND_DARKEN: return mcol_darken(col, paintcol, alpha_i);
+ case PAINT_BLEND_COLORDODGE: return mcol_colordodge(col, paintcol, alpha_i);
+ case PAINT_BLEND_DIFFERENCE: return mcol_difference(col, paintcol, alpha_i);
+ case PAINT_BLEND_SCREEN: return mcol_screen(col, paintcol, alpha_i);
+ case PAINT_BLEND_HARDLIGHT: return mcol_hardlight(col, paintcol, alpha_i);
+ case PAINT_BLEND_OVERLAY: return mcol_overlay(col, paintcol, alpha_i);
+ case PAINT_BLEND_SOFTLIGHT: return mcol_softlight(col, paintcol, alpha_i);
+ case PAINT_BLEND_EXCLUSION: return mcol_exclusion(col, paintcol, alpha_i);
+ case PAINT_BLEND_LUMINOCITY: return mcol_luminosity(col, paintcol, alpha_i);
+ case PAINT_BLEND_SATURATION: return mcol_saturation(col, paintcol, alpha_i);
+ case PAINT_BLEND_HUE: return mcol_hue(col, paintcol, alpha_i);
+ /* non-color */
+ case PAINT_BLEND_ALPHA_SUB: return mcol_alpha_sub(col, alpha_i);
+ case PAINT_BLEND_ALPHA_ADD: return mcol_alpha_add(col, alpha_i);
+ default:
+ BLI_assert(0);
+ return 0;
+ }
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/paint_vertex_proj.c b/source/blender/editors/sculpt_paint/paint_vertex_proj.c
index c939eb6df35..411a0ca9ec3 100644
--- a/source/blender/editors/sculpt_paint/paint_vertex_proj.c
+++ b/source/blender/editors/sculpt_paint/paint_vertex_proj.c
@@ -76,8 +76,9 @@ struct VertProjUpdate {
/* -------------------------------------------------------------------- */
/* Internal Init */
-static void vpaint_proj_dm_map_cosnos_init__map_cb(void *userData, int index, const float co[3],
- const float no_f[3], const short no_s[3])
+static void vpaint_proj_dm_map_cosnos_init__map_cb(
+ void *userData, int index, const float co[3],
+ const float no_f[3], const short no_s[3])
{
struct VertProjHandle *vp_handle = userData;
DMCoNo *co_no = &vp_handle->vcosnos[index];
@@ -98,8 +99,9 @@ static void vpaint_proj_dm_map_cosnos_init__map_cb(void *userData, int index, co
}
}
-static void vpaint_proj_dm_map_cosnos_init(Scene *scene, Object *ob,
- struct VertProjHandle *vp_handle)
+static void vpaint_proj_dm_map_cosnos_init(
+ Scene *scene, Object *ob,
+ struct VertProjHandle *vp_handle)
{
Mesh *me = ob->data;
DerivedMesh *dm;
@@ -128,8 +130,9 @@ static void vpaint_proj_dm_map_cosnos_init(Scene *scene, Object *ob,
/* Same as init but take mouse location into account */
-static void vpaint_proj_dm_map_cosnos_update__map_cb(void *userData, int index, const float co[3],
- const float no_f[3], const short no_s[3])
+static void vpaint_proj_dm_map_cosnos_update__map_cb(
+ void *userData, int index, const float co[3],
+ const float no_f[3], const short no_s[3])
{
struct VertProjUpdate *vp_update = userData;
struct VertProjHandle *vp_handle = vp_update->vp_handle;
@@ -141,9 +144,10 @@ static void vpaint_proj_dm_map_cosnos_update__map_cb(void *userData, int index,
/* first find distance to this vertex */
float co_ss[2]; /* screenspace */
- if (ED_view3d_project_float_object(vp_update->ar,
- co, co_ss,
- V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ if (ED_view3d_project_float_object(
+ vp_update->ar,
+ co, co_ss,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
{
const float dist_sq = len_squared_v2v2(vp_update->mval_fl, co_ss);
if (dist_sq > vp_handle->dists_sq[index]) {
@@ -169,8 +173,9 @@ static void vpaint_proj_dm_map_cosnos_update__map_cb(void *userData, int index,
}
}
-static void vpaint_proj_dm_map_cosnos_update(struct VertProjHandle *vp_handle,
- ARegion *ar, const float mval_fl[2])
+static void vpaint_proj_dm_map_cosnos_update(
+ struct VertProjHandle *vp_handle,
+ ARegion *ar, const float mval_fl[2])
{
struct VertProjUpdate vp_update = {vp_handle, ar, mval_fl};
@@ -198,8 +203,9 @@ static void vpaint_proj_dm_map_cosnos_update(struct VertProjHandle *vp_handle,
/* -------------------------------------------------------------------- */
/* Public Functions */
-struct VertProjHandle *ED_vpaint_proj_handle_create(Scene *scene, Object *ob,
- DMCoNo **r_vcosnos)
+struct VertProjHandle *ED_vpaint_proj_handle_create(
+ Scene *scene, Object *ob,
+ DMCoNo **r_vcosnos)
{
struct VertProjHandle *vp_handle = MEM_mallocN(sizeof(struct VertProjHandle), __func__);
Mesh *me = ob->data;
@@ -228,8 +234,9 @@ struct VertProjHandle *ED_vpaint_proj_handle_create(Scene *scene, Object *ob,
return vp_handle;
}
-void ED_vpaint_proj_handle_update(struct VertProjHandle *vp_handle,
- ARegion *ar, const float mval_fl[2])
+void ED_vpaint_proj_handle_update(
+ struct VertProjHandle *vp_handle,
+ ARegion *ar, const float mval_fl[2])
{
if (vp_handle->use_update) {
vpaint_proj_dm_map_cosnos_update(vp_handle, ar, mval_fl);
diff --git a/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c b/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c
new file mode 100644
index 00000000000..957cb6a7389
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_vertex_weight_ops.c
@@ -0,0 +1,859 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_vertex_weight_ops.c
+ * \ingroup edsculpt
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_blenlib.h"
+#include "BLI_math.h"
+#include "BLI_array_utils.h"
+#include "BLI_bitmap.h"
+#include "BLI_task.h"
+#include "BLI_string_utils.h"
+
+#include "IMB_imbuf.h"
+#include "IMB_imbuf_types.h"
+#include "IMB_colormanagement.h"
+
+//#include "DNA_armature_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_particle_types.h"
+#include "DNA_brush_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+#include "RNA_enum_types.h"
+
+#include "BKE_DerivedMesh.h"
+#include "BKE_brush.h"
+#include "BKE_context.h"
+#include "BKE_depsgraph.h"
+#include "BKE_deform.h"
+#include "BKE_mesh.h"
+#include "BKE_mesh_mapping.h"
+#include "BKE_modifier.h"
+#include "BKE_object_deform.h"
+#include "BKE_paint.h"
+#include "BKE_report.h"
+#include "BKE_colortools.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_armature.h"
+#include "ED_mesh.h"
+#include "ED_screen.h"
+#include "ED_view3d.h"
+
+#include "paint_intern.h" /* own include */
+
+/* -------------------------------------------------------------------- */
+/** \name Store Previous Weights
+ *
+ * Use to avoid feedback loop w/ mirrored edits.
+ * \{ */
+
+struct WPaintPrev {
+ /* previous vertex weights */
+ struct MDeformVert *wpaint_prev;
+ /* allocation size of prev buffers */
+ int tot;
+};
+
+
+static void wpaint_prev_init(struct WPaintPrev *wpp)
+{
+ wpp->wpaint_prev = NULL;
+ wpp->tot = 0;
+}
+
+static void wpaint_prev_create(struct WPaintPrev *wpp, MDeformVert *dverts, int dcount)
+{
+ wpaint_prev_init(wpp);
+
+ if (dverts && dcount) {
+ wpp->wpaint_prev = MEM_mallocN(sizeof(MDeformVert) * dcount, "wpaint prev");
+ wpp->tot = dcount;
+ BKE_defvert_array_copy(wpp->wpaint_prev, dverts, dcount);
+ }
+}
+
+static void wpaint_prev_destroy(struct WPaintPrev *wpp)
+{
+ if (wpp->wpaint_prev) {
+ BKE_defvert_array_free(wpp->wpaint_prev, wpp->tot);
+ }
+ wpp->wpaint_prev = NULL;
+ wpp->tot = 0;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Weight from Bones Operator
+ * \{ */
+
+static int weight_from_bones_poll(bContext *C)
+{
+ Object *ob = CTX_data_active_object(C);
+
+ return (ob && (ob->mode & OB_MODE_WEIGHT_PAINT) && modifiers_isDeformedByArmature(ob));
+}
+
+static int weight_from_bones_exec(bContext *C, wmOperator *op)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ Object *armob = modifiers_isDeformedByArmature(ob);
+ Mesh *me = ob->data;
+ int type = RNA_enum_get(op->ptr, "type");
+
+ ED_object_vgroup_calc_from_armature(op->reports, scene, ob, armob, type, (me->editflag & ME_EDIT_MIRROR_X));
+
+ DAG_id_tag_update(&me->id, 0);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
+
+ return OPERATOR_FINISHED;
+}
+
+void PAINT_OT_weight_from_bones(wmOperatorType *ot)
+{
+ static const EnumPropertyItem type_items[] = {
+ {ARM_GROUPS_AUTO, "AUTOMATIC", 0, "Automatic", "Automatic weights from bones"},
+ {ARM_GROUPS_ENVELOPE, "ENVELOPES", 0, "From Envelopes", "Weights from envelopes with user defined radius"},
+ {0, NULL, 0, NULL, NULL}};
+
+ /* identifiers */
+ ot->name = "Weight from Bones";
+ ot->idname = "PAINT_OT_weight_from_bones";
+ ot->description = "Set the weights of the groups matching the attached armature's selected bones, "
+ "using the distance between the vertices and the bones";
+
+ /* api callbacks */
+ ot->exec = weight_from_bones_exec;
+ ot->invoke = WM_menu_invoke;
+ ot->poll = weight_from_bones_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ /* properties */
+ ot->prop = RNA_def_enum(ot->srna, "type", type_items, 0, "Type", "Method to use for assigning weights");
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Sample Weight Operator
+ * \{ */
+
+/* sets wp->weight to the closest weight value to vertex */
+/* note: we cant sample frontbuf, weight colors are interpolated too unpredictable */
+static int weight_sample_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ ViewContext vc;
+ Mesh *me;
+ bool changed = false;
+
+ ED_view3d_viewcontext_init(C, &vc);
+ me = BKE_mesh_from_object(vc.obact);
+
+ if (me && me->dvert && vc.v3d && vc.rv3d && (vc.obact->actdef != 0)) {
+ const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+ int v_idx_best = -1;
+ uint index;
+
+ view3d_operator_needs_opengl(C);
+ ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
+
+ if (use_vert_sel) {
+ if (ED_mesh_pick_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
+ v_idx_best = index;
+ }
+ }
+ else {
+ if (ED_mesh_pick_face_vert(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
+ v_idx_best = index;
+ }
+ else if (ED_mesh_pick_face(C, vc.obact, event->mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
+ /* this relies on knowning the internal worksings of ED_mesh_pick_face_vert() */
+ BKE_report(op->reports, RPT_WARNING, "The modifier used does not support deformed locations");
+ }
+ }
+
+ if (v_idx_best != -1) { /* should always be valid */
+ ToolSettings *ts = vc.scene->toolsettings;
+ Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
+ const int vgroup_active = vc.obact->actdef - 1;
+ float vgroup_weight = defvert_find_weight(&me->dvert[v_idx_best], vgroup_active);
+
+ /* use combined weight in multipaint mode, since that's what is displayed to the user in the colors */
+ if (ts->multipaint) {
+ int defbase_tot_sel;
+ const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
+ bool *defbase_sel = BKE_object_defgroup_selected_get(vc.obact, defbase_tot, &defbase_tot_sel);
+
+ if (defbase_tot_sel > 1) {
+ if (me->editflag & ME_EDIT_MIRROR_X) {
+ BKE_object_defgroup_mirror_selection(
+ vc.obact, defbase_tot, defbase_sel, defbase_sel, &defbase_tot_sel);
+ }
+
+ vgroup_weight = BKE_defvert_multipaint_collective_weight(
+ &me->dvert[v_idx_best], defbase_tot, defbase_sel, defbase_tot_sel, ts->auto_normalize);
+
+ /* if autonormalize is enabled, but weights are not normalized, the value can exceed 1 */
+ CLAMP(vgroup_weight, 0.0f, 1.0f);
+ }
+
+ MEM_freeN(defbase_sel);
+ }
+
+ BKE_brush_weight_set(vc.scene, brush, vgroup_weight);
+ changed = true;
+ }
+ }
+
+ if (changed) {
+ /* not really correct since the brush didnt change, but redraws the toolbar */
+ WM_main_add_notifier(NC_BRUSH | NA_EDITED, NULL); /* ts->wpaint->paint.brush */
+
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_weight_sample(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Weight Paint Sample Weight";
+ ot->idname = "PAINT_OT_weight_sample";
+ ot->description = "Use the mouse to sample a weight in the 3D view";
+
+ /* api callbacks */
+ ot->invoke = weight_sample_invoke;
+ ot->poll = weight_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Weight Paint Sample Group Operator
+ * \{ */
+
+/* samples cursor location, and gives menu with vertex groups to activate */
+static bool weight_paint_sample_enum_itemf__helper(const MDeformVert *dvert, const int defbase_tot, int *groups)
+{
+ /* this func fills in used vgroup's */
+ bool found = false;
+ int i = dvert->totweight;
+ MDeformWeight *dw;
+ for (dw = dvert->dw; i > 0; dw++, i--) {
+ if (dw->def_nr < defbase_tot) {
+ groups[dw->def_nr] = true;
+ found = true;
+ }
+ }
+ return found;
+}
+static const EnumPropertyItem *weight_paint_sample_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+{
+ if (C) {
+ wmWindow *win = CTX_wm_window(C);
+ if (win && win->eventstate) {
+ ViewContext vc;
+ Mesh *me;
+
+ ED_view3d_viewcontext_init(C, &vc);
+ me = BKE_mesh_from_object(vc.obact);
+
+ if (me && me->dvert && vc.v3d && vc.rv3d && vc.obact->defbase.first) {
+ const int defbase_tot = BLI_listbase_count(&vc.obact->defbase);
+ const bool use_vert_sel = (me->editflag & ME_EDIT_PAINT_VERT_SEL) != 0;
+ int *groups = MEM_callocN(defbase_tot * sizeof(int), "groups");
+ bool found = false;
+ uint index;
+
+ const int mval[2] = {
+ win->eventstate->x - vc.ar->winrct.xmin,
+ win->eventstate->y - vc.ar->winrct.ymin,
+ };
+
+ view3d_operator_needs_opengl(C);
+ ED_view3d_init_mats_rv3d(vc.obact, vc.rv3d);
+
+ if (use_vert_sel) {
+ if (ED_mesh_pick_vert(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_VERT_SIZE, true)) {
+ MDeformVert *dvert = &me->dvert[index];
+ found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
+ }
+ }
+ else {
+ if (ED_mesh_pick_face(C, vc.obact, mval, &index, ED_MESH_PICK_DEFAULT_FACE_SIZE)) {
+ const MPoly *mp = &me->mpoly[index];
+ uint fidx = mp->totloop - 1;
+
+ do {
+ MDeformVert *dvert = &me->dvert[me->mloop[mp->loopstart + fidx].v];
+ found |= weight_paint_sample_enum_itemf__helper(dvert, defbase_tot, groups);
+ } while (fidx--);
+ }
+ }
+
+ if (found == false) {
+ MEM_freeN(groups);
+ }
+ else {
+ EnumPropertyItem *item = NULL, item_tmp = {0};
+ int totitem = 0;
+ int i = 0;
+ bDeformGroup *dg;
+ for (dg = vc.obact->defbase.first; dg && i < defbase_tot; i++, dg = dg->next) {
+ if (groups[i]) {
+ item_tmp.identifier = item_tmp.name = dg->name;
+ item_tmp.value = i;
+ RNA_enum_item_add(&item, &totitem, &item_tmp);
+ }
+ }
+
+ RNA_enum_item_end(&item, &totitem);
+ *r_free = true;
+
+ MEM_freeN(groups);
+ return item;
+ }
+ }
+ }
+ }
+
+ return DummyRNA_NULL_items;
+}
+
+static int weight_sample_group_exec(bContext *C, wmOperator *op)
+{
+ int type = RNA_enum_get(op->ptr, "group");
+ ViewContext vc;
+ ED_view3d_viewcontext_init(C, &vc);
+
+ BLI_assert(type + 1 >= 0);
+ vc.obact->actdef = type + 1;
+
+ DAG_id_tag_update(&vc.obact->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, vc.obact);
+ return OPERATOR_FINISHED;
+}
+
+/* TODO, we could make this a menu into OBJECT_OT_vertex_group_set_active rather than its own operator */
+void PAINT_OT_weight_sample_group(wmOperatorType *ot)
+{
+ PropertyRNA *prop = NULL;
+
+ /* identifiers */
+ ot->name = "Weight Paint Sample Group";
+ ot->idname = "PAINT_OT_weight_sample_group";
+ ot->description = "Select one of the vertex groups available under current mouse position";
+
+ /* api callbacks */
+ ot->exec = weight_sample_group_exec;
+ ot->invoke = WM_menu_invoke;
+ ot->poll = weight_paint_mode_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
+ /* keyingset to use (dynamic enum) */
+ prop = RNA_def_enum(ot->srna, "group", DummyRNA_DEFAULT_items, 0, "Keying Set", "The Keying Set to use");
+ RNA_def_enum_funcs(prop, weight_paint_sample_enum_itemf);
+ RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
+ ot->prop = prop;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Weight Set Operator
+ * \{ */
+
+/* fills in the selected faces with the current weight and vertex group */
+static bool weight_paint_set(Object *ob, float paintweight)
+{
+ Mesh *me = ob->data;
+ const MPoly *mp;
+ MDeformWeight *dw, *dw_prev;
+ int vgroup_active, vgroup_mirror = -1;
+ uint index;
+ const bool topology = (me->editflag & ME_EDIT_MIRROR_TOPO) != 0;
+
+ /* mutually exclusive, could be made into a */
+ const short paint_selmode = ME_EDIT_PAINT_SEL_MODE(me);
+
+ if (me->totpoly == 0 || me->dvert == NULL || !me->mpoly) {
+ return false;
+ }
+
+ vgroup_active = ob->actdef - 1;
+
+ /* if mirror painting, find the other group */
+ if (me->editflag & ME_EDIT_MIRROR_X) {
+ vgroup_mirror = ED_wpaint_mirror_vgroup_ensure(ob, vgroup_active);
+ }
+
+ struct WPaintPrev wpp;
+ wpaint_prev_create(&wpp, me->dvert, me->totvert);
+
+ for (index = 0, mp = me->mpoly; index < me->totpoly; index++, mp++) {
+ uint fidx = mp->totloop - 1;
+
+ if ((paint_selmode == SCE_SELECT_FACE) && !(mp->flag & ME_FACE_SEL)) {
+ continue;
+ }
+
+ do {
+ uint vidx = me->mloop[mp->loopstart + fidx].v;
+
+ if (!me->dvert[vidx].flag) {
+ if ((paint_selmode == SCE_SELECT_VERTEX) && !(me->mvert[vidx].flag & SELECT)) {
+ continue;
+ }
+
+ dw = defvert_verify_index(&me->dvert[vidx], vgroup_active);
+ if (dw) {
+ dw_prev = defvert_verify_index(wpp.wpaint_prev + vidx, vgroup_active);
+ dw_prev->weight = dw->weight; /* set the undo weight */
+ dw->weight = paintweight;
+
+ if (me->editflag & ME_EDIT_MIRROR_X) { /* x mirror painting */
+ int j = mesh_get_x_mirror_vert(ob, NULL, vidx, topology);
+ if (j >= 0) {
+ /* copy, not paint again */
+ if (vgroup_mirror != -1) {
+ dw = defvert_verify_index(me->dvert + j, vgroup_mirror);
+ dw_prev = defvert_verify_index(wpp.wpaint_prev + j, vgroup_mirror);
+ }
+ else {
+ dw = defvert_verify_index(me->dvert + j, vgroup_active);
+ dw_prev = defvert_verify_index(wpp.wpaint_prev + j, vgroup_active);
+ }
+ dw_prev->weight = dw->weight; /* set the undo weight */
+ dw->weight = paintweight;
+ }
+ }
+ }
+ me->dvert[vidx].flag = 1;
+ }
+
+ } while (fidx--);
+ }
+
+ {
+ MDeformVert *dv = me->dvert;
+ for (index = me->totvert; index != 0; index--, dv++) {
+ dv->flag = 0;
+ }
+ }
+
+ wpaint_prev_destroy(&wpp);
+
+ DAG_id_tag_update(&me->id, 0);
+
+ return true;
+}
+
+
+static int weight_paint_set_exec(bContext *C, wmOperator *op)
+{
+ struct Scene *scene = CTX_data_scene(C);
+ Object *obact = CTX_data_active_object(C);
+ ToolSettings *ts = CTX_data_tool_settings(C);
+ Brush *brush = BKE_paint_brush(&ts->wpaint->paint);
+ float vgroup_weight = BKE_brush_weight_get(scene, brush);
+
+ if (ED_wpaint_ensure_data(C, op->reports, WPAINT_ENSURE_MIRROR, NULL) == false) {
+ return OPERATOR_CANCELLED;
+ }
+
+ if (weight_paint_set(obact, vgroup_weight)) {
+ ED_region_tag_redraw(CTX_wm_region(C)); /* XXX - should redraw all 3D views */
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
+}
+
+void PAINT_OT_weight_set(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Set Weight";
+ ot->idname = "PAINT_OT_weight_set";
+ ot->description = "Fill the active vertex group with the current paint weight";
+
+ /* api callbacks */
+ ot->exec = weight_paint_set_exec;
+ ot->poll = mask_paint_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Interactive Weight Gradient Operator
+ * \{ */
+
+/* *** VGroups Gradient *** */
+typedef struct DMGradient_vertStore {
+ float sco[2];
+ float weight_orig;
+ enum {
+ VGRAD_STORE_NOP = 0,
+ VGRAD_STORE_DW_EXIST = (1 << 0)
+ } flag;
+} DMGradient_vertStore;
+
+typedef struct DMGradient_vertStoreBase {
+ struct WPaintPrev wpp;
+ DMGradient_vertStore elem[0];
+} DMGradient_vertStoreBase;
+
+typedef struct DMGradient_userData {
+ struct ARegion *ar;
+ Scene *scene;
+ Mesh *me;
+ Brush *brush;
+ const float *sco_start; /* [2] */
+ const float *sco_end; /* [2] */
+ float sco_line_div; /* store (1.0f / len_v2v2(sco_start, sco_end)) */
+ int def_nr;
+ bool is_init;
+ DMGradient_vertStoreBase *vert_cache;
+ /* only for init */
+ BLI_bitmap *vert_visit;
+
+ /* options */
+ short use_select;
+ short type;
+ float weightpaint;
+} DMGradient_userData;
+
+static void gradientVert_update(DMGradient_userData *grad_data, int index)
+{
+ Mesh *me = grad_data->me;
+ DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index];
+ float alpha;
+
+ if (grad_data->type == WPAINT_GRADIENT_TYPE_LINEAR) {
+ alpha = line_point_factor_v2(vs->sco, grad_data->sco_start, grad_data->sco_end);
+ }
+ else {
+ BLI_assert(grad_data->type == WPAINT_GRADIENT_TYPE_RADIAL);
+ alpha = len_v2v2(grad_data->sco_start, vs->sco) * grad_data->sco_line_div;
+ }
+ /* no need to clamp 'alpha' yet */
+
+ /* adjust weight */
+ alpha = BKE_brush_curve_strength_clamped(grad_data->brush, alpha, 1.0f);
+
+ if (alpha != 0.0f) {
+ MDeformVert *dv = &me->dvert[index];
+ MDeformWeight *dw = defvert_verify_index(dv, grad_data->def_nr);
+ // dw->weight = alpha; // testing
+ int tool = grad_data->brush->vertexpaint_tool;
+ float testw;
+
+ /* init if we just added */
+ testw = ED_wpaint_blend_tool(tool, vs->weight_orig, grad_data->weightpaint, alpha * grad_data->brush->alpha);
+ CLAMP(testw, 0.0f, 1.0f);
+ dw->weight = testw;
+ }
+ else {
+ MDeformVert *dv = &me->dvert[index];
+ if (vs->flag & VGRAD_STORE_DW_EXIST) {
+ /* normally we NULL check, but in this case we know it exists */
+ MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
+ dw->weight = vs->weight_orig;
+ }
+ else {
+ /* wasn't originally existing, remove */
+ MDeformWeight *dw = defvert_find_index(dv, grad_data->def_nr);
+ if (dw) {
+ defvert_remove_group(dv, dw);
+ }
+ }
+ }
+}
+
+static void gradientVertUpdate__mapFunc(
+ void *userData, int index, const float UNUSED(co[3]),
+ const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
+{
+ DMGradient_userData *grad_data = userData;
+ Mesh *me = grad_data->me;
+ if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
+ DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index];
+ if (vs->sco[0] != FLT_MAX) {
+ gradientVert_update(grad_data, index);
+ }
+ }
+}
+
+static void gradientVertInit__mapFunc(
+ void *userData, int index, const float co[3],
+ const float UNUSED(no_f[3]), const short UNUSED(no_s[3]))
+{
+ DMGradient_userData *grad_data = userData;
+ Mesh *me = grad_data->me;
+
+ if ((grad_data->use_select == false) || (me->mvert[index].flag & SELECT)) {
+ /* run first pass only,
+ * the screen coords of the verts need to be cached because
+ * updating the mesh may move them about (entering feedback loop) */
+
+ if (BLI_BITMAP_TEST(grad_data->vert_visit, index) == 0) {
+ DMGradient_vertStore *vs = &grad_data->vert_cache->elem[index];
+ if (ED_view3d_project_float_object(grad_data->ar,
+ co, vs->sco,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ {
+ /* ok */
+ MDeformVert *dv = &me->dvert[index];
+ const MDeformWeight *dw;
+ dw = defvert_find_index(dv, grad_data->def_nr);
+ if (dw) {
+ vs->weight_orig = dw->weight;
+ vs->flag = VGRAD_STORE_DW_EXIST;
+ }
+ else {
+ vs->weight_orig = 0.0f;
+ vs->flag = VGRAD_STORE_NOP;
+ }
+
+ BLI_BITMAP_ENABLE(grad_data->vert_visit, index);
+
+ gradientVert_update(grad_data, index);
+ }
+ else {
+ /* no go */
+ copy_v2_fl(vs->sco, FLT_MAX);
+ }
+ }
+ }
+}
+
+static int paint_weight_gradient_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ wmGesture *gesture = op->customdata;
+ DMGradient_vertStoreBase *vert_cache = gesture->userdata;
+ int ret = WM_gesture_straightline_modal(C, op, event);
+
+ if (ret & OPERATOR_RUNNING_MODAL) {
+ if (event->type == LEFTMOUSE && event->val == KM_RELEASE) { /* XXX, hardcoded */
+ /* generally crap! redo! */
+ WM_gesture_straightline_cancel(C, op);
+ ret &= ~OPERATOR_RUNNING_MODAL;
+ ret |= OPERATOR_FINISHED;
+ }
+ }
+
+ if (ret & OPERATOR_CANCELLED) {
+ Object *ob = CTX_data_active_object(C);
+ Mesh *me = ob->data;
+ if (vert_cache->wpp.wpaint_prev) {
+ BKE_defvert_array_free_elems(me->dvert, me->totvert);
+ BKE_defvert_array_copy(me->dvert, vert_cache->wpp.wpaint_prev, me->totvert);
+ wpaint_prev_destroy(&vert_cache->wpp);
+ }
+ MEM_freeN(vert_cache);
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+ }
+ else if (ret & OPERATOR_FINISHED) {
+ wpaint_prev_destroy(&vert_cache->wpp);
+ MEM_freeN(vert_cache);
+ }
+
+ return ret;
+}
+
+static int paint_weight_gradient_exec(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+ DMGradient_vertStoreBase *vert_cache;
+ struct ARegion *ar = CTX_wm_region(C);
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ Mesh *me = ob->data;
+ int x_start = RNA_int_get(op->ptr, "xstart");
+ int y_start = RNA_int_get(op->ptr, "ystart");
+ int x_end = RNA_int_get(op->ptr, "xend");
+ int y_end = RNA_int_get(op->ptr, "yend");
+ float sco_start[2] = {x_start, y_start};
+ float sco_end[2] = {x_end, y_end};
+ const bool is_interactive = (gesture != NULL);
+ DerivedMesh *dm = mesh_get_derived_final(scene, ob, scene->customdata_mask);
+
+ DMGradient_userData data = {NULL};
+
+ if (is_interactive) {
+ if (gesture->userdata == NULL) {
+ gesture->userdata = MEM_mallocN(
+ sizeof(DMGradient_vertStoreBase) +
+ (sizeof(DMGradient_vertStore) * me->totvert),
+ __func__);
+ gesture->userdata_free = false;
+ data.is_init = true;
+
+ wpaint_prev_create(&((DMGradient_vertStoreBase *)gesture->userdata)->wpp, me->dvert, me->totvert);
+
+ /* on init only, convert face -> vert sel */
+ if (me->editflag & ME_EDIT_PAINT_FACE_SEL) {
+ BKE_mesh_flush_select_from_polys(me);
+ }
+ }
+
+ vert_cache = gesture->userdata;
+ }
+ else {
+ if (ED_wpaint_ensure_data(C, op->reports, 0, NULL) == false) {
+ return OPERATOR_CANCELLED;
+ }
+
+ data.is_init = true;
+ vert_cache = MEM_mallocN(
+ sizeof(DMGradient_vertStoreBase) +
+ (sizeof(DMGradient_vertStore) * me->totvert),
+ __func__);
+ }
+
+ data.ar = ar;
+ data.scene = scene;
+ data.me = ob->data;
+ data.sco_start = sco_start;
+ data.sco_end = sco_end;
+ data.sco_line_div = 1.0f / len_v2v2(sco_start, sco_end);
+ data.def_nr = ob->actdef - 1;
+ data.use_select = (me->editflag & (ME_EDIT_PAINT_FACE_SEL | ME_EDIT_PAINT_VERT_SEL));
+ data.vert_cache = vert_cache;
+ data.vert_visit = NULL;
+ data.type = RNA_enum_get(op->ptr, "type");
+
+ {
+ ToolSettings *ts = CTX_data_tool_settings(C);
+ VPaint *wp = ts->wpaint;
+ struct Brush *brush = BKE_paint_brush(&wp->paint);
+
+ curvemapping_initialize(brush->curve);
+
+ data.brush = brush;
+ data.weightpaint = BKE_brush_weight_get(scene, brush);
+ }
+
+ ED_view3d_init_mats_rv3d(ob, ar->regiondata);
+
+ if (data.is_init) {
+ data.vert_visit = BLI_BITMAP_NEW(me->totvert, __func__);
+
+ dm->foreachMappedVert(dm, gradientVertInit__mapFunc, &data, DM_FOREACH_NOP);
+
+ MEM_freeN(data.vert_visit);
+ data.vert_visit = NULL;
+ }
+ else {
+ dm->foreachMappedVert(dm, gradientVertUpdate__mapFunc, &data, DM_FOREACH_NOP);
+ }
+
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+
+ if (is_interactive == false) {
+ MEM_freeN(vert_cache);
+ }
+
+ return OPERATOR_FINISHED;
+}
+
+static int paint_weight_gradient_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ int ret;
+
+ if (ED_wpaint_ensure_data(C, op->reports, 0, NULL) == false) {
+ return OPERATOR_CANCELLED;
+ }
+
+ ret = WM_gesture_straightline_invoke(C, op, event);
+ if (ret & OPERATOR_RUNNING_MODAL) {
+ struct ARegion *ar = CTX_wm_region(C);
+ if (ar->regiontype == RGN_TYPE_WINDOW) {
+ /* TODO, hardcoded, extend WM_gesture_straightline_ */
+ if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
+ wmGesture *gesture = op->customdata;
+ gesture->is_active = true;
+ }
+ }
+ }
+ return ret;
+}
+
+void PAINT_OT_weight_gradient(wmOperatorType *ot)
+{
+ /* defined in DNA_space_types.h */
+ static const EnumPropertyItem gradient_types[] = {
+ {WPAINT_GRADIENT_TYPE_LINEAR, "LINEAR", 0, "Linear", ""},
+ {WPAINT_GRADIENT_TYPE_RADIAL, "RADIAL", 0, "Radial", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ PropertyRNA *prop;
+
+ /* identifiers */
+ ot->name = "Weight Gradient";
+ ot->idname = "PAINT_OT_weight_gradient";
+ ot->description = "Draw a line to apply a weight gradient to selected vertices";
+
+ /* api callbacks */
+ ot->invoke = paint_weight_gradient_invoke;
+ ot->modal = paint_weight_gradient_modal;
+ ot->exec = paint_weight_gradient_exec;
+ ot->poll = weight_paint_poll;
+ ot->cancel = WM_gesture_straightline_cancel;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ prop = RNA_def_enum(ot->srna, "type", gradient_types, 0, "Type", "");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+
+ WM_operator_properties_gesture_straightline(ot, CURSOR_EDIT);
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/paint_vertex_weight_utils.c b/source/blender/editors/sculpt_paint/paint_vertex_weight_utils.c
new file mode 100644
index 00000000000..4d70d82d5c6
--- /dev/null
+++ b/source/blender/editors/sculpt_paint/paint_vertex_weight_utils.c
@@ -0,0 +1,311 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/sculpt_paint/paint_vertex_weight_utils.c
+ * \ingroup edsculpt
+ *
+ * Intended for use by `paint_vertex.c` & `paint_vertex_weight_ops.c`.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_listbase.h"
+#include "BLI_math.h"
+#include "BLI_string_utils.h"
+
+#include "DNA_armature_types.h"
+#include "DNA_mesh_types.h"
+#include "DNA_scene_types.h"
+#include "DNA_brush_types.h"
+#include "DNA_object_types.h"
+
+#include "BKE_action.h"
+#include "BKE_context.h"
+#include "BKE_deform.h"
+#include "BKE_mesh.h"
+#include "BKE_modifier.h"
+#include "BKE_object_deform.h"
+#include "BKE_report.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "paint_intern.h" /* own include */
+
+/* -------------------------------------------------------------------- */
+/** \name Weight Paint Sanity Checks
+ * \{ */
+
+/* ensure we have data on wpaint start, add if needed */
+bool ED_wpaint_ensure_data(
+ bContext *C, struct ReportList *reports,
+ enum eWPaintFlag flag, struct WPaintVGroupIndex *vgroup_index)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ Mesh *me = BKE_mesh_from_object(ob);
+
+ if (vgroup_index) {
+ vgroup_index->active = -1;
+ vgroup_index->mirror = -1;
+ }
+
+ if (scene->obedit) {
+ return false;
+ }
+
+ if (me == NULL || me->totpoly == 0) {
+ return false;
+ }
+
+ /* if nothing was added yet, we make dverts and a vertex deform group */
+ if (!me->dvert) {
+ BKE_object_defgroup_data_create(&me->id);
+ WM_event_add_notifier(C, NC_GEOM | ND_DATA, me);
+ }
+
+ /* this happens on a Bone select, when no vgroup existed yet */
+ if (ob->actdef <= 0) {
+ Object *modob;
+ if ((modob = modifiers_isDeformedByArmature(ob))) {
+ Bone *actbone = ((bArmature *)modob->data)->act_bone;
+ if (actbone) {
+ bPoseChannel *pchan = BKE_pose_channel_find_name(modob->pose, actbone->name);
+
+ if (pchan) {
+ bDeformGroup *dg = defgroup_find_name(ob, pchan->name);
+ if (dg == NULL) {
+ dg = BKE_object_defgroup_add_name(ob, pchan->name); /* sets actdef */
+ }
+ else {
+ int actdef = 1 + BLI_findindex(&ob->defbase, dg);
+ BLI_assert(actdef >= 0);
+ ob->actdef = actdef;
+ }
+ }
+ }
+ }
+ }
+ if (BLI_listbase_is_empty(&ob->defbase)) {
+ BKE_object_defgroup_add(ob);
+ }
+
+ /* ensure we don't try paint onto an invalid group */
+ if (ob->actdef <= 0) {
+ BKE_report(reports, RPT_WARNING, "No active vertex group for painting, aborting");
+ return false;
+ }
+
+ if (vgroup_index) {
+ vgroup_index->active = ob->actdef - 1;
+ }
+
+ if (flag & WPAINT_ENSURE_MIRROR) {
+ if (me->editflag & ME_EDIT_MIRROR_X) {
+ int mirror = ED_wpaint_mirror_vgroup_ensure(ob, ob->actdef - 1);
+ if (vgroup_index) {
+ vgroup_index->mirror = mirror;
+ }
+ }
+ }
+
+ return true;
+}
+/** \} */
+
+/* mirror_vgroup is set to -1 when invalid */
+int ED_wpaint_mirror_vgroup_ensure(Object *ob, const int vgroup_active)
+{
+ bDeformGroup *defgroup = BLI_findlink(&ob->defbase, vgroup_active);
+
+ if (defgroup) {
+ int mirrdef;
+ char name_flip[MAXBONENAME];
+
+ BLI_string_flip_side_name(name_flip, defgroup->name, false, sizeof(name_flip));
+ mirrdef = defgroup_name_index(ob, name_flip);
+ if (mirrdef == -1) {
+ if (BKE_defgroup_new(ob, name_flip)) {
+ mirrdef = BLI_listbase_count(&ob->defbase) - 1;
+ }
+ }
+
+ /* curdef should never be NULL unless this is
+ * a lamp and BKE_object_defgroup_add_name fails */
+ return mirrdef;
+ }
+
+ return -1;
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Weight Blending Modes
+ * \{ */
+
+BLI_INLINE float wval_blend(const float weight, const float paintval, const float alpha)
+{
+ const float talpha = min_ff(alpha, 1.0f); /* blending with values over 1 doesn't make sense */
+ return (paintval * talpha) + (weight * (1.0f - talpha));
+}
+BLI_INLINE float wval_add(const float weight, const float paintval, const float alpha)
+{
+ return weight + (paintval * alpha);
+}
+BLI_INLINE float wval_sub(const float weight, const float paintval, const float alpha)
+{
+ return weight - (paintval * alpha);
+}
+BLI_INLINE float wval_mul(const float weight, const float paintval, const float alpha)
+{ /* first mul, then blend the fac */
+ return ((1.0f - alpha) + (alpha * paintval)) * weight;
+}
+BLI_INLINE float wval_lighten(const float weight, const float paintval, const float alpha)
+{
+ return (weight < paintval) ? wval_blend(weight, paintval, alpha) : weight;
+}
+BLI_INLINE float wval_darken(const float weight, const float paintval, const float alpha)
+{
+ return (weight > paintval) ? wval_blend(weight, paintval, alpha) : weight;
+}
+
+/* mainly for color */
+BLI_INLINE float wval_colordodge(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ temp = (paintval == 1.0f) ? 1.0f : min_ff((weight * (225.0f / 255.0f)) / (1.0f - paintval), 1.0f);
+ return mfac * weight + temp * fac;
+}
+BLI_INLINE float wval_difference(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ temp = fabsf(weight - paintval);
+ return mfac * weight + temp * fac;
+}
+BLI_INLINE float wval_screen(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ temp = max_ff(1.0f - (((1.0f - weight) * (1.0f - paintval))), 0);
+ return mfac * weight + temp * fac;
+}
+BLI_INLINE float wval_hardlight(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ if (paintval > 0.5f) {
+ temp = 1.0f - ((1.0f - 2.0f * (paintval - 0.5f)) * (1.0f - weight));
+ }
+ else {
+ temp = (2.0f * paintval * weight);
+ }
+ return mfac * weight + temp * fac;
+}
+BLI_INLINE float wval_overlay(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ if (weight > 0.5f) {
+ temp = 1.0f - ((1.0f - 2.0f * (weight - 0.5f)) * (1.0f - paintval));
+ }
+ else {
+ temp = (2.0f * paintval * weight);
+ }
+ return mfac * weight + temp * fac;
+}
+BLI_INLINE float wval_softlight(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ if (weight < 0.5f) {
+ temp = ((2.0f * ((paintval / 2.0f) + 0.25f)) * weight);
+ }
+ else {
+ temp = 1.0f - (2.0f * (1.0f - ((paintval / 2.0f) + 0.25f)) * (1.0f - weight));
+ }
+ return temp * fac + weight * mfac;
+}
+BLI_INLINE float wval_exclusion(float weight, float paintval, float fac)
+{
+ float mfac, temp;
+ if (fac == 0.0f) {
+ return weight;
+ }
+ mfac = 1.0f - fac;
+ temp = 0.5f - ((2.0f * (weight - 0.5f) * (paintval - 0.5f)));
+ return temp * fac + weight * mfac;
+}
+
+/* vpaint has 'vpaint_blend_tool' */
+/* result is not clamped from [0-1] */
+float ED_wpaint_blend_tool(
+ const int tool,
+ /* dw->weight */
+ const float weight,
+ const float paintval, const float alpha)
+{
+ switch (tool) {
+ case PAINT_BLEND_MIX:
+ case PAINT_BLEND_AVERAGE:
+ case PAINT_BLEND_SMEAR:
+ case PAINT_BLEND_BLUR: return wval_blend(weight, paintval, alpha);
+ case PAINT_BLEND_ADD: return wval_add(weight, paintval, alpha);
+ case PAINT_BLEND_SUB: return wval_sub(weight, paintval, alpha);
+ case PAINT_BLEND_MUL: return wval_mul(weight, paintval, alpha);
+ case PAINT_BLEND_LIGHTEN: return wval_lighten(weight, paintval, alpha);
+ case PAINT_BLEND_DARKEN: return wval_darken(weight, paintval, alpha);
+ /* Mostly make sense for color: support anyway. */
+ case PAINT_BLEND_COLORDODGE: return wval_colordodge(weight, paintval, alpha);
+ case PAINT_BLEND_DIFFERENCE: return wval_difference(weight, paintval, alpha);
+ case PAINT_BLEND_SCREEN: return wval_screen(weight, paintval, alpha);
+ case PAINT_BLEND_HARDLIGHT: return wval_hardlight(weight, paintval, alpha);
+ case PAINT_BLEND_OVERLAY: return wval_overlay(weight, paintval, alpha);
+ case PAINT_BLEND_SOFTLIGHT: return wval_softlight(weight, paintval, alpha);
+ case PAINT_BLEND_EXCLUSION: return wval_exclusion(weight, paintval, alpha);
+ /* Only for color: just use blend. */
+ case PAINT_BLEND_LUMINOCITY:
+ case PAINT_BLEND_SATURATION:
+ case PAINT_BLEND_HUE:
+ case PAINT_BLEND_ALPHA_SUB:
+ case PAINT_BLEND_ALPHA_ADD:
+ default: return wval_blend(weight, paintval, alpha);
+ }
+}
+
+/** \} */ \ No newline at end of file
diff --git a/source/blender/editors/sculpt_paint/sculpt.c b/source/blender/editors/sculpt_paint/sculpt.c
index 84e98181dfb..34e60187a73 100644
--- a/source/blender/editors/sculpt_paint/sculpt.c
+++ b/source/blender/editors/sculpt_paint/sculpt.c
@@ -37,9 +37,8 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
-#include "BLI_dial.h"
+#include "BLI_dial_2d.h"
#include "BLI_task.h"
-#include "BLI_threads.h"
#include "BLI_utildefines.h"
#include "BLI_ghash.h"
@@ -62,6 +61,7 @@
#include "BKE_image.h"
#include "BKE_key.h"
#include "BKE_library.h"
+#include "BKE_main.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
#include "BKE_modifier.h"
@@ -165,111 +165,12 @@ static bool sculpt_brush_needs_rake_rotation(const Brush *brush)
return SCULPT_TOOL_HAS_RAKE(brush->sculpt_tool) && (brush->rake_factor != 0.0f);
}
-/* Factor of brush to have rake point following behind
- * (could be configurable but this is reasonable default). */
-#define SCULPT_RAKE_BRUSH_FACTOR 0.25f
-
-struct SculptRakeData {
- float follow_dist;
- float follow_co[3];
-};
-
typedef enum StrokeFlags {
CLIP_X = 1,
CLIP_Y = 2,
CLIP_Z = 4
} StrokeFlags;
-/* Cache stroke properties. Used because
- * RNA property lookup isn't particularly fast.
- *
- * For descriptions of these settings, check the operator properties.
- */
-typedef struct StrokeCache {
- /* Invariants */
- float initial_radius;
- float scale[3];
- int flag;
- float clip_tolerance[3];
- float initial_mouse[2];
-
- /* Variants */
- float radius;
- float radius_squared;
- float true_location[3];
- float location[3];
-
- bool pen_flip;
- bool invert;
- float pressure;
- float mouse[2];
- float bstrength;
- float normal_weight; /* from brush (with optional override) */
-
- /* The rest is temporary storage that isn't saved as a property */
-
- bool first_time; /* Beginning of stroke may do some things special */
-
- /* from ED_view3d_ob_project_mat_get() */
- float projection_mat[4][4];
-
- /* Clean this up! */
- ViewContext *vc;
- Brush *brush;
-
- float special_rotation;
- float grab_delta[3], grab_delta_symmetry[3];
- float old_grab_location[3], orig_grab_location[3];
-
- /* screen-space rotation defined by mouse motion */
- float rake_rotation[4], rake_rotation_symmetry[4];
- bool is_rake_rotation_valid;
- struct SculptRakeData rake_data;
-
- int symmetry; /* Symmetry index between 0 and 7 bit combo 0 is Brush only;
- * 1 is X mirror; 2 is Y mirror; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
- int mirror_symmetry_pass; /* the symmetry pass we are currently on between 0 and 7*/
- float true_view_normal[3];
- float view_normal[3];
-
- /* sculpt_normal gets calculated by calc_sculpt_normal(), then the
- * sculpt_normal_symm gets updated quickly with the usual symmetry
- * transforms */
- float sculpt_normal[3];
- float sculpt_normal_symm[3];
-
- /* Used for area texture mode, local_mat gets calculated by
- * calc_brush_local_mat() and used in tex_strength(). */
- float brush_local_mat[4][4];
-
- float plane_offset[3]; /* used to shift the plane around when doing tiled strokes */
- int tile_pass;
-
- float last_center[3];
- int radial_symmetry_pass;
- float symm_rot_mat[4][4];
- float symm_rot_mat_inv[4][4];
- bool original;
- float anchored_location[3];
-
- float vertex_rotation; /* amount to rotate the vertices when using rotate brush */
- Dial *dial;
-
- char saved_active_brush_name[MAX_ID_NAME];
- char saved_mask_brush_tool;
- int saved_smooth_size; /* smooth tool copies the size of the current tool */
- bool alt_smooth;
-
- float plane_trim_squared;
-
- bool supports_gravity;
- float true_gravity_direction[3];
- float gravity_direction[3];
-
- rcti previous_r; /* previous redraw rectangle */
- rcti current_r; /* current redraw rectangle */
-} StrokeCache;
-
/************** Access to original unmodified vertex data *************/
typedef struct {
@@ -476,42 +377,10 @@ static bool sculpt_stroke_is_dynamic_topology(
/*** paint mesh ***/
-/* Single struct used by all BLI_task threaded callbacks, let's avoid adding 10's of those... */
-typedef struct SculptThreadedTaskData {
- Sculpt *sd;
- Object *ob;
- Brush *brush;
- PBVHNode **nodes;
- int totnode;
-
- /* Data specific to some callbacks. */
- /* Note: even if only one or two of those are used at a time, keeping them separated, names help figuring out
- * what it is, and memory overhead is ridiculous anyway... */
- float flippedbstrength;
- float angle;
- float strength;
- bool smooth_mask;
- bool has_bm_orco;
-
- SculptProjectVector *spvc;
- float *offset;
- float *grab_delta;
- float *cono;
- float *area_no;
- float *area_no_sp;
- float *area_co;
- float (*mat)[4];
- float (*vertCos)[3];
-
- /* 0=towards view, 1=flipped */
- float (*area_cos)[3];
- float (*area_nos)[3];
- int *count;
-
- ThreadMutex mutex;
-} SculptThreadedTaskData;
-
-static void paint_mesh_restore_co_task_cb(void *userdata, const int n)
+static void paint_mesh_restore_co_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
@@ -573,9 +442,14 @@ static void paint_mesh_restore_co(Sculpt *sd, Object *ob)
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && !ss->bm && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &data, paint_mesh_restore_co_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && !ss->bm && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ paint_mesh_restore_co_task_cb,
+ &settings);
if (nodes)
MEM_freeN(nodes);
@@ -600,7 +474,7 @@ static void sculpt_extend_redraw_rect_previous(Object *ob, rcti *rect)
}
/* Get a screen-space rectangle of the modified area */
-static bool sculpt_get_redraw_rect(ARegion *ar, RegionView3D *rv3d,
+bool sculpt_get_redraw_rect(ARegion *ar, RegionView3D *rv3d,
Object *ob, rcti *rect)
{
PBVH *pbvh = ob->sculpt->pbvh;
@@ -650,17 +524,7 @@ void ED_sculpt_redraw_planes_get(float planes[4][4], ARegion *ar,
/************************ Brush Testing *******************/
-typedef struct SculptBrushTest {
- float radius_squared;
- float location[3];
- float dist;
- int mirror_symmetry_pass;
-
- /* View3d clipping - only set rv3d for clipping */
- RegionView3D *clip_rv3d;
-} SculptBrushTest;
-
-static void sculpt_brush_test_init(SculptSession *ss, SculptBrushTest *test)
+void sculpt_brush_test_init(SculptSession *ss, SculptBrushTest *test)
{
RegionView3D *rv3d = ss->cache->vc->rv3d;
@@ -668,6 +532,10 @@ static void sculpt_brush_test_init(SculptSession *ss, SculptBrushTest *test)
copy_v3_v3(test->location, ss->cache->location);
test->dist = 0.0f; /* just for initialize */
+ /* Only for 2D projection. */
+ zero_v4(test->plane_view);
+ zero_v4(test->plane_tool);
+
test->mirror_symmetry_pass = ss->cache->mirror_symmetry_pass;
if (rv3d->rflag & RV3D_CLIPPING) {
@@ -689,7 +557,7 @@ BLI_INLINE bool sculpt_brush_test_clipping(const SculptBrushTest *test, const fl
return ED_view3d_clipping_test(rv3d, symm_co, true);
}
-static bool sculpt_brush_test(SculptBrushTest *test, const float co[3])
+bool sculpt_brush_test_sphere(SculptBrushTest *test, const float co[3])
{
float distsq = len_squared_v3v3(co, test->location);
@@ -705,7 +573,7 @@ static bool sculpt_brush_test(SculptBrushTest *test, const float co[3])
}
}
-static bool sculpt_brush_test_sq(SculptBrushTest *test, const float co[3])
+bool sculpt_brush_test_sphere_sq(SculptBrushTest *test, const float co[3])
{
float distsq = len_squared_v3v3(co, test->location);
@@ -721,7 +589,7 @@ static bool sculpt_brush_test_sq(SculptBrushTest *test, const float co[3])
}
}
-static bool sculpt_brush_test_fast(const SculptBrushTest *test, const float co[3])
+bool sculpt_brush_test_sphere_fast(const SculptBrushTest *test, const float co[3])
{
if (sculpt_brush_test_clipping(test, co)) {
return 0;
@@ -729,7 +597,25 @@ static bool sculpt_brush_test_fast(const SculptBrushTest *test, const float co[3
return len_squared_v3v3(co, test->location) <= test->radius_squared;
}
-static bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], float local[4][4])
+bool sculpt_brush_test_circle_sq(SculptBrushTest *test, const float co[3])
+{
+ float co_proj[3];
+ closest_to_plane_normalized_v3(co_proj, test->plane_view, co);
+ float distsq = len_squared_v3v3(co_proj, test->location);
+
+ if (distsq <= test->radius_squared) {
+ if (sculpt_brush_test_clipping(test, co)) {
+ return 0;
+ }
+ test->dist = distsq;
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], float local[4][4])
{
float side = M_SQRT1_2;
float local_co[3];
@@ -758,7 +644,36 @@ static bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], flo
}
}
-static float frontface(Brush *br, const float sculpt_normal[3],
+SculptBrushTestFn sculpt_brush_test_init_with_falloff_shape(
+ SculptSession *ss, SculptBrushTest *test, char falloff_shape)
+{
+ sculpt_brush_test_init(ss, test);
+ SculptBrushTestFn sculpt_brush_test_sq_fn;
+ if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
+ sculpt_brush_test_sq_fn = sculpt_brush_test_sphere_sq;
+ }
+ else {
+ /* PAINT_FALLOFF_SHAPE_TUBE */
+ plane_from_point_normal_v3(test->plane_view, test->location, ss->cache->view_normal);
+ sculpt_brush_test_sq_fn = sculpt_brush_test_circle_sq;
+ }
+ return sculpt_brush_test_sq_fn;
+}
+
+const float *sculpt_brush_frontface_normal_from_falloff_shape(
+ SculptSession *ss, char falloff_shape)
+{
+ if (falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
+ return ss->cache->sculpt_normal_symm;
+ }
+ else {
+ /* PAINT_FALLOFF_SHAPE_TUBE */
+ return ss->cache->view_normal;
+ }
+}
+
+
+static float frontface(const Brush *br, const float sculpt_normal[3],
const short no[3], const float fno[3])
{
if (br->flag & BRUSH_FRONTFACE) {
@@ -784,7 +699,7 @@ static float frontface(Brush *br, const float sculpt_normal[3],
static bool sculpt_brush_test_cyl(SculptBrushTest *test, float co[3], float location[3], const float area_no[3])
{
- if (sculpt_brush_test_fast(test, co)) {
+ if (sculpt_brush_test_sphere_fast(test, co)) {
float t1[3], t2[3], t3[3], dist;
sub_v3_v3v3(t1, location, co);
@@ -888,7 +803,10 @@ static float calc_symmetry_feather(Sculpt *sd, StrokeCache *cache)
* \note These are all _very_ similar, when changing one, check others.
* \{ */
-static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
+static void calc_area_normal_and_center_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
@@ -896,18 +814,22 @@ static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
float (*area_cos)[3] = data->area_cos;
PBVHVertexIter vd;
- SculptBrushTest test;
- SculptUndoNode *unode;
+ SculptUndoNode *unode = NULL;
float private_co[2][3] = {{0.0f}};
float private_no[2][3] = {{0.0f}};
int private_count[2] = {0};
- bool use_original;
+ bool use_original = false;
- unode = sculpt_undo_push_node(data->ob, data->nodes[n], SCULPT_UNDO_COORDS);
- sculpt_brush_test_init(ss, &test);
+ if (ss->cache->original) {
+ unode = sculpt_undo_push_node(data->ob, data->nodes[n], SCULPT_UNDO_COORDS);
+ use_original = (unode->co || unode->bm_entry);
+ }
+
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
- use_original = (ss->cache->original && (unode->co || unode->bm_entry));
/* when the mesh is edited we can't rely on original coords
* (original mesh may not even have verts in brush radius) */
@@ -929,7 +851,7 @@ static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
closest_on_tri_to_point_v3(co, test.location, UNPACK3(co_tri));
- if (sculpt_brush_test_fast(&test, co)) {
+ if (sculpt_brush_test_sq_fn(&test, co)) {
float no[3];
int flip_index;
@@ -963,7 +885,7 @@ static void calc_area_normal_and_center_task_cb(void *userdata, const int n)
co = vd.co;
}
- if (sculpt_brush_test_fast(&test, co)) {
+ if (sculpt_brush_test_sq_fn(&test, co)) {
float no_buf[3];
const float *no;
int flip_index;
@@ -1029,15 +951,21 @@ static void calc_area_center(
int count[2] = {0};
+ /* Intentionally set 'sd' to NULL since we share logic with vertex paint. */
SculptThreadedTaskData data = {
- .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
+ .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
.has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = NULL, .count = count,
};
BLI_mutex_init(&data.mutex);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &data, calc_area_normal_and_center_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ calc_area_normal_and_center_task_cb,
+ &settings);
BLI_mutex_end(&data.mutex);
@@ -1053,42 +981,58 @@ static void calc_area_center(
}
}
-
static void calc_area_normal(
Sculpt *sd, Object *ob,
PBVHNode **nodes, int totnode,
float r_area_no[3])
{
const Brush *brush = BKE_paint_brush(&sd->paint);
+ bool use_threading = (sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT;
+ sculpt_pbvh_calc_area_normal(brush, ob, nodes, totnode, use_threading, r_area_no);
+}
+
+/* expose 'calc_area_normal' externally. */
+void sculpt_pbvh_calc_area_normal(
+ const Brush *brush, Object *ob,
+ PBVHNode **nodes, int totnode,
+ bool use_threading,
+ float r_area_no[3])
+{
SculptSession *ss = ob->sculpt;
const bool has_bm_orco = ss->bm && sculpt_stroke_is_dynamic_topology(ss, brush);
- int n;
/* 0=towards view, 1=flipped */
float area_nos[2][3] = {{0.0f}};
int count[2] = {0};
+ /* Intentionally set 'sd' to NULL since this is used for vertex paint too. */
SculptThreadedTaskData data = {
- .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
+ .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
.has_bm_orco = has_bm_orco, .area_cos = NULL, .area_nos = area_nos, .count = count,
};
BLI_mutex_init(&data.mutex);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = use_threading;
BLI_task_parallel_range(
- 0, totnode, &data, calc_area_normal_and_center_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ calc_area_normal_and_center_task_cb,
+ &settings);
BLI_mutex_end(&data.mutex);
/* for area normal */
- for (n = 0; n < ARRAY_SIZE(area_nos); n++) {
- if (normalize_v3_v3(r_area_no, area_nos[n]) != 0.0f) {
+ for (int i = 0; i < ARRAY_SIZE(area_nos); i++) {
+ if (normalize_v3_v3(r_area_no, area_nos[i]) != 0.0f) {
break;
}
}
}
+
/* this calculates flatten center and area normal together,
* amortizing the memory bandwidth and loop overhead to calculate both at the same time */
static void calc_area_normal_and_center(
@@ -1107,15 +1051,21 @@ static void calc_area_normal_and_center(
int count[2] = {0};
+ /* Intentionally set 'sd' to NULL since this is used for vertex paint too. */
SculptThreadedTaskData data = {
- .sd = sd, .ob = ob, .nodes = nodes, .totnode = totnode,
+ .sd = NULL, .ob = ob, .brush = brush, .nodes = nodes, .totnode = totnode,
.has_bm_orco = has_bm_orco, .area_cos = area_cos, .area_nos = area_nos, .count = count,
};
BLI_mutex_init(&data.mutex);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &data, calc_area_normal_and_center_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ calc_area_normal_and_center_task_cb,
+ &settings);
BLI_mutex_end(&data.mutex);
@@ -1237,17 +1187,17 @@ static float brush_strength(
}
/* Return a multiplier for brush strength on a particular vertex. */
-static float tex_strength(SculptSession *ss, Brush *br,
- const float brush_point[3],
- const float len,
- const short vno[3],
- const float fno[3],
- const float mask,
- const int thread_id)
+float tex_strength(SculptSession *ss, const Brush *br,
+ const float brush_point[3],
+ const float len,
+ const short vno[3],
+ const float fno[3],
+ const float mask,
+ const int thread_id)
{
StrokeCache *cache = ss->cache;
const Scene *scene = cache->vc->scene;
- MTex *mtex = &br->mtex;
+ const MTex *mtex = &br->mtex;
float avg = 1;
float rgba[4];
float point[3];
@@ -1316,15 +1266,8 @@ static float tex_strength(SculptSession *ss, Brush *br,
return avg;
}
-typedef struct {
- Sculpt *sd;
- SculptSession *ss;
- float radius_squared;
- bool original;
-} SculptSearchSphereData;
-
/* Test AABB against sphere */
-static bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
+bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
{
SculptSearchSphereData *data = data_v;
float *center = data->ss->cache->location, nearest[3];
@@ -1350,6 +1293,24 @@ static bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v)
return len_squared_v3(t) < data->radius_squared;
}
+/* 2D projection (distance to line). */
+bool sculpt_search_circle_cb(PBVHNode *node, void *data_v)
+{
+ SculptSearchCircleData *data = data_v;
+ float bb_min[3], bb_max[3];
+
+ if (data->original)
+ BKE_pbvh_node_get_original_BB(node, bb_min, bb_max);
+ else
+ BKE_pbvh_node_get_BB(node, bb_min, bb_min);
+
+ float dummy_co[3], dummy_depth;
+ const float dist_sq = dist_squared_ray_to_aabb_v3(
+ data->dist_ray_to_aabb_precalc, bb_min, bb_max, dummy_co, &dummy_depth);
+
+ return dist_sq < data->radius_squared || 1;
+}
+
/* Handles clipping against a mirror modifier and SCULPT_LOCK axis flags */
static void sculpt_clip(Sculpt *sd, SculptSession *ss, float co[3], const float val[3])
{
@@ -1366,6 +1327,37 @@ static void sculpt_clip(Sculpt *sd, SculptSession *ss, float co[3], const float
}
}
+static PBVHNode **sculpt_pbvh_gather_generic(
+ Object *ob, Sculpt *sd, const Brush *brush, bool use_original, float radius_scale, int *r_totnode)
+{
+ SculptSession *ss = ob->sculpt;
+ PBVHNode **nodes = NULL;
+
+ /* Build a list of all nodes that are potentially within the brush's area of influence */
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_SPHERE) {
+ SculptSearchSphereData data = {
+ .ss = ss,
+ .sd = sd,
+ .radius_squared = SQUARE(ss->cache->radius * radius_scale),
+ .original = use_original,
+ };
+ BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, r_totnode);
+ }
+ else {
+ struct DistRayAABB_Precalc dist_ray_to_aabb_precalc;
+ dist_squared_ray_to_aabb_v3_precalc(&dist_ray_to_aabb_precalc, ss->cache->location, ss->cache->view_normal);
+ SculptSearchCircleData data = {
+ .ss = ss,
+ .sd = sd,
+ .radius_squared = SQUARE(ss->cache->radius * radius_scale),
+ .original = use_original,
+ .dist_ray_to_aabb_precalc = &dist_ray_to_aabb_precalc,
+ };
+ BKE_pbvh_search_gather(ss->pbvh, sculpt_search_circle_cb, &data, &nodes, r_totnode);
+ }
+ return nodes;
+}
+
/* Calculate primary direction of movement for many brushes */
static void calc_sculpt_normal(
Sculpt *sd, Object *ob,
@@ -1412,6 +1404,10 @@ static void update_sculpt_normal(Sculpt *sd, Object *ob,
(cache->first_time || !(brush->flag & BRUSH_ORIGINAL_NORMAL)))
{
calc_sculpt_normal(sd, ob, nodes, totnode, cache->sculpt_normal);
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(cache->sculpt_normal, cache->sculpt_normal, cache->view_normal);
+ normalize_v3(cache->sculpt_normal);
+ }
copy_v3_v3(cache->sculpt_normal_symm, cache->sculpt_normal);
}
else {
@@ -1567,7 +1563,7 @@ static float neighbor_average_mask(SculptSession *ss, unsigned vert)
static void bmesh_neighbor_average(float avg[3], BMVert *v)
{
/* logic for 3 or more is identical */
- const int vfcount = BM_vert_face_count_ex(v, 3);
+ const int vfcount = BM_vert_face_count_at_most(v, 3);
/* Don't modify corner vertices */
if (vfcount > 1) {
@@ -1582,7 +1578,7 @@ static void bmesh_neighbor_average(float avg[3], BMVert *v)
for (i = 0; i < ARRAY_SIZE(adj_v); i++) {
const BMVert *v_other = adj_v[i];
- if (vfcount != 2 || BM_vert_face_count_ex(v_other, 2) <= 2) {
+ if (vfcount != 2 || BM_vert_face_count_at_most(v_other, 2) <= 2) {
add_v3_v3(avg, v_other->co);
total++;
}
@@ -1632,30 +1628,56 @@ typedef struct SculptDoBrushSmoothGridDataChunk {
size_t tmpgrid_size;
} SculptDoBrushSmoothGridDataChunk;
+typedef struct {
+ SculptSession *ss;
+ const float *ray_start, *ray_normal;
+ bool hit;
+ float depth;
+ bool original;
+} SculptRaycastData;
+
+typedef struct {
+ const float *ray_start, *ray_normal;
+ bool hit;
+ float depth;
+ float detail;
+} SculptDetailRaycastData;
+
+typedef struct {
+ SculptSession *ss;
+ const float *ray_start, *ray_normal;
+ bool hit;
+ float depth;
+ float dist_sq_to_ray;
+ bool original;
+} SculptFindNearestToRayData;
+
static void do_smooth_brush_mesh_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
Sculpt *sd = data->sd;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const bool smooth_mask = data->smooth_mask;
float bstrength = data->strength;
PBVHVertexIter vd;
- SculptBrushTest test;
CLAMP(bstrength, 0.0f, 1.0f);
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno,
- smooth_mask ? 0.0f : (vd.mask ? *vd.mask : 0.0f),
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, smooth_mask ? 0.0f : (vd.mask ? *vd.mask : 0.0f), tls->thread_id);
if (smooth_mask) {
float val = neighbor_average_mask(ss, vd.vert_indices[vd.i]) - *vd.mask;
val *= fade * bstrength;
@@ -1681,28 +1703,31 @@ static void do_smooth_brush_mesh_task_cb_ex(
}
static void do_smooth_brush_bmesh_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
Sculpt *sd = data->sd;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const bool smooth_mask = data->smooth_mask;
float bstrength = data->strength;
PBVHVertexIter vd;
- SculptBrushTest test;
CLAMP(bstrength, 0.0f, 1.0f);
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, smooth_mask ? 0.0f : *vd.mask,
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, smooth_mask ? 0.0f : *vd.mask, tls->thread_id);
if (smooth_mask) {
float val = bmesh_neighbor_average_mask(vd.bm_vert, vd.cd_vert_mask_offset) - *vd.mask;
val *= fade * bstrength;
@@ -1728,17 +1753,18 @@ static void do_smooth_brush_bmesh_task_cb_ex(
}
static void do_smooth_brush_multires_task_cb_ex(
- void *userdata, void *userdata_chunk, const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
- SculptDoBrushSmoothGridDataChunk *data_chunk = userdata_chunk;
+ SculptDoBrushSmoothGridDataChunk *data_chunk = tls->userdata_chunk;
SculptSession *ss = data->ob->sculpt;
Sculpt *sd = data->sd;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const bool smooth_mask = data->smooth_mask;
float bstrength = data->strength;
- SculptBrushTest test;
CCGElem **griddata, *gddata;
CCGKey key;
@@ -1751,7 +1777,9 @@ static void do_smooth_brush_multires_task_cb_ex(
int *grid_indices, totgrid, gridsize;
int i, x, y;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
CLAMP(bstrength, 0.0f, 1.0f);
@@ -1838,10 +1866,11 @@ static void do_smooth_brush_multires_task_cb_ex(
fno = CCG_elem_offset_no(&key, gddata, index);
mask = CCG_elem_offset_mask(&key, gddata, index);
- if (sculpt_brush_test(&test, co)) {
+ if (sculpt_brush_test_sq_fn(&test, co)) {
const float strength_mask = (smooth_mask ? 0.0f : *mask);
const float fade = bstrength * tex_strength(
- ss, brush, co, test.dist, NULL, fno, strength_mask, thread_id);
+ ss, brush, co, sqrtf(test.dist),
+ NULL, fno, strength_mask, tls->thread_id);
float f = 1.0f / 16.0f;
if (x == 0 || x == gridsize - 1)
@@ -1899,6 +1928,10 @@ static void smooth(
.smooth_mask = smooth_mask, .strength = strength,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+
switch (type) {
case PBVH_GRIDS:
{
@@ -1913,22 +1946,30 @@ static void smooth(
data_chunk->tmpgrid_size = size;
size += sizeof(*data_chunk);
- BLI_task_parallel_range_ex(
- 0, totnode, &data, data_chunk, size, do_smooth_brush_multires_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ settings.userdata_chunk = data_chunk;
+ settings.userdata_chunk_size = size;
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_smooth_brush_multires_task_cb_ex,
+ &settings);
MEM_freeN(data_chunk);
break;
}
case PBVH_FACES:
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_smooth_brush_mesh_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_smooth_brush_mesh_task_cb_ex,
+ &settings);
break;
case PBVH_BMESH:
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_smooth_brush_bmesh_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_smooth_brush_bmesh_task_cb_ex,
+ &settings);
break;
}
@@ -1944,22 +1985,27 @@ static void do_smooth_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
}
static void do_mask_brush_draw_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float bstrength = ss->cache->bstrength;
PBVHVertexIter vd;
- SculptBrushTest test;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
- const float fade = tex_strength(ss, brush, vd.co, test.dist, vd.no, vd.fno, 0.0f, thread_id);
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ const float fade = tex_strength(
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, 0.0f, tls->thread_id);
(*vd.mask) += fade * bstrength;
CLAMP(*vd.mask, 0, 1);
@@ -1980,9 +2026,14 @@ static void do_mask_brush_draw(Sculpt *sd, Object *ob, PBVHNode **nodes, int tot
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_mask_brush_draw_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_mask_brush_draw_task_cb_ex,
+ &settings);
}
static void do_mask_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
@@ -2001,27 +2052,31 @@ static void do_mask_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
}
static void do_draw_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *offset = data->offset;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
/* offset vertex */
const float fade = tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], offset, fade);
@@ -2050,40 +2105,56 @@ static void do_draw_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
.offset = offset,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_draw_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_draw_brush_task_cb_ex,
+ &settings);
}
+/**
+ * Used for 'SCULPT_TOOL_CREASE' and 'SCULPT_TOOL_BLOB'
+ */
static void do_crease_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
SculptProjectVector *spvc = data->spvc;
const float flippedbstrength = data->flippedbstrength;
const float *offset = data->offset;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
/* offset vertex */
const float fade = tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
float val1[3];
float val2[3];
/* first we pinch */
sub_v3_v3v3(val1, test.location, vd.co);
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(val1, val1, ss->cache->view_normal);
+ }
+
mul_v3_fl(val1, fade * flippedbstrength);
sculpt_project_v3(spvc, val1, val1);
@@ -2138,35 +2209,47 @@ static void do_crease_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
.spvc = &spvc, .offset = offset, .flippedbstrength = flippedbstrength,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_crease_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_crease_brush_task_cb_ex,
+ &settings);
}
static void do_pinch_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
float val[3];
sub_v3_v3v3(val, test.location, vd.co);
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(val, val, ss->cache->view_normal);
+ }
mul_v3_v3fl(proxy[vd.i], val, fade);
if (vd.mvert)
@@ -2184,21 +2267,27 @@ static void do_pinch_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_pinch_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_pinch_brush_task_cb_ex,
+ &settings);
}
static void do_grab_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *grab_delta = data->grab_delta;
PBVHVertexIter vd;
- SculptBrushTest test;
SculptOrigVertData orig_data;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
@@ -2207,16 +2296,18 @@ static void do_grab_brush_task_cb_ex(
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
sculpt_orig_vert_data_update(&orig_data, &vd);
- if (sculpt_brush_test(&test, orig_data.co)) {
+ if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, orig_data.co, sqrtf(test.dist),
+ orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
@@ -2244,33 +2335,42 @@ static void do_grab_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
.grab_delta = grab_delta,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_grab_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_grab_brush_task_cb_ex,
+ &settings);
}
static void do_nudge_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *cono = data->cono;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], cono, fade);
@@ -2298,22 +2398,28 @@ static void do_nudge_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
.cono = cono,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_nudge_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_nudge_brush_task_cb_ex,
+ &settings);
}
static void do_snake_hook_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
SculptProjectVector *spvc = data->spvc;
const float *grab_delta = data->grab_delta;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
const bool do_rake_rotation = ss->cache->is_rake_rotation_valid;
@@ -2323,13 +2429,16 @@ static void do_snake_hook_brush_task_cb_ex(
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], grab_delta, fade);
@@ -2338,6 +2447,9 @@ static void do_snake_hook_brush_task_cb_ex(
float delta_pinch_init[3], delta_pinch[3];
sub_v3_v3v3(delta_pinch, vd.co, test.location);
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(delta_pinch, delta_pinch, ss->cache->true_view_normal);
+ }
/* important to calculate based on the grabbed location (intentionally ignore fade here). */
add_v3_v3(delta_pinch, grab_delta);
@@ -2399,21 +2511,27 @@ static void do_snake_hook_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int to
.spvc = &spvc, .grab_delta = grab_delta,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_snake_hook_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_snake_hook_brush_task_cb_ex,
+ &settings);
}
static void do_thumb_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *cono = data->cono;
PBVHVertexIter vd;
- SculptBrushTest test;
SculptOrigVertData orig_data;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
@@ -2422,16 +2540,18 @@ static void do_thumb_brush_task_cb_ex(
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
sculpt_orig_vert_data_update(&orig_data, &vd);
- if (sculpt_brush_test(&test, orig_data.co)) {
+ if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, orig_data.co, sqrtf(test.dist),
+ orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], cono, fade);
@@ -2459,21 +2579,27 @@ static void do_thumb_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
.cono = cono,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_thumb_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_thumb_brush_task_cb_ex,
+ &settings);
}
static void do_rotate_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float angle = data->angle;
PBVHVertexIter vd;
- SculptBrushTest test;
SculptOrigVertData orig_data;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
@@ -2482,17 +2608,19 @@ static void do_rotate_brush_task_cb_ex(
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
sculpt_orig_vert_data_update(&orig_data, &vd);
- if (sculpt_brush_test(&test, orig_data.co)) {
+ if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
float vec[3], rot[3][3];
const float fade = bstrength * tex_strength(
- ss, brush, orig_data.co, test.dist, orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, orig_data.co, sqrtf(test.dist),
+ orig_data.no, NULL, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
sub_v3_v3v3(vec, orig_data.co, ss->cache->location);
axis_angle_normalized_to_mat3(rot, ss->cache->sculpt_normal_symm, angle * fade);
@@ -2520,22 +2648,28 @@ static void do_rotate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
.angle = angle,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_rotate_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_rotate_brush_task_cb_ex,
+ &settings);
}
static void do_layer_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
Sculpt *sd = data->sd;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *offset = data->offset;
PBVHVertexIter vd;
- SculptBrushTest test;
SculptOrigVertData orig_data;
float *layer_disp;
const float bstrength = ss->cache->bstrength;
@@ -2550,15 +2684,18 @@ static void do_layer_brush_task_cb_ex(
layer_disp = BKE_pbvh_node_layer_disp_get(ss->pbvh, data->nodes[n]);
BLI_mutex_unlock(&data->mutex);
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
sculpt_orig_vert_data_update(&orig_data, &vd);
- if (sculpt_brush_test(&test, orig_data.co)) {
+ if (sculpt_brush_test_sq_fn(&test, orig_data.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
float *disp = &layer_disp[vd.i];
float val[3];
@@ -2603,34 +2740,43 @@ static void do_layer_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode
};
BLI_mutex_init(&data.mutex);
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_layer_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_layer_brush_task_cb_ex,
+ &settings);
BLI_mutex_end(&data.mutex);
}
static void do_inflate_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, test.dist, vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
float val[3];
if (vd.fno)
@@ -2656,9 +2802,14 @@ static void do_inflate_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totno
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_inflate_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_inflate_brush_task_cb_ex,
+ &settings);
}
static void calc_sculpt_plane(
@@ -2693,6 +2844,10 @@ static void calc_sculpt_plane(
case SCULPT_DISP_DIR_AREA:
calc_area_normal_and_center(sd, ob, nodes, totnode, r_area_no, r_area_co);
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(r_area_no, r_area_no, ss->cache->view_normal);
+ normalize_v3(r_area_no);
+ }
break;
default:
@@ -2734,16 +2889,6 @@ static void calc_sculpt_plane(
}
}
-/* Projects a point onto a plane along the plane's normal */
-static void point_plane_project(
- float intr[3],
- const float co[3], const float plane_normal[3], const float plane_center[3])
-{
- sub_v3_v3v3(intr, co, plane_center);
- mul_v3_v3fl(intr, plane_normal, dot_v3v3(plane_normal, intr));
- sub_v3_v3v3(intr, co, intr);
-}
-
static int plane_trim(const StrokeCache *cache, const Brush *brush, const float val[3])
{
return (!(brush->flag & BRUSH_PLANE_TRIM) ||
@@ -2751,26 +2896,18 @@ static int plane_trim(const StrokeCache *cache, const Brush *brush, const float
}
static bool plane_point_side_flip(
- const float co[3], const float plane_normal[3], const float plane_center[3],
+ const float co[3], const float plane[4],
const bool flip)
{
- float delta[3];
- float d;
-
- sub_v3_v3v3(delta, co, plane_center);
- d = dot_v3v3(plane_normal, delta);
-
+ float d = plane_point_side_v3(plane, co);
if (flip) d = -d;
-
return d <= 0.0f;
}
-static int plane_point_side(const float co[3], const float plane_normal[3], const float plane_center[3])
+static int plane_point_side(const float co[3], const float plane[4])
{
- float delta[3];
-
- sub_v3_v3v3(delta, co, plane_center);
- return dot_v3v3(plane_normal, delta) <= 0.0f;
+ float d = plane_point_side_v3(plane, co);
+ return d <= 0.0f;
}
static float get_offset(Sculpt *sd, SculptSession *ss)
@@ -2787,37 +2924,42 @@ static float get_offset(Sculpt *sd, SculptSession *ss)
}
static void do_flatten_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *area_no = data->area_no;
const float *area_co = data->area_co;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+
+ plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test_sq(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
float intr[3];
float val[3];
- point_plane_project(intr, vd.co, area_no, area_co);
+ closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
sub_v3_v3v3(val, intr, vd.co);
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2856,38 +2998,48 @@ static void do_flatten_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totno
.area_no = area_no, .area_co = area_co,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_flatten_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_flatten_brush_task_cb_ex,
+ &settings);
}
static void do_clay_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *area_no = data->area_no;
const float *area_co = data->area_co;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const bool flip = (ss->cache->bstrength < 0);
const float bstrength = flip ? -ss->cache->bstrength : ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+
+ plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test_sq(&test, vd.co)) {
- if (plane_point_side_flip(vd.co, area_no, area_co, flip)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ if (plane_point_side_flip(vd.co, test.plane_tool, flip)) {
float intr[3];
float val[3];
- point_plane_project(intr, vd.co, area_no, area_co);
+ closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
sub_v3_v3v3(val, intr, vd.co);
@@ -2895,8 +3047,8 @@ static void do_clay_brush_task_cb_ex(
/* note, the normal from the vertices is ignored,
* causes glitch with planes, see: T44390 */
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -2939,17 +3091,24 @@ static void do_clay_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
.area_no = area_no, .area_co = area_co,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_clay_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_clay_brush_task_cb_ex,
+ &settings);
}
static void do_clay_strips_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
float (*mat)[4] = data->mat;
const float *area_no_sp = data->area_no_sp;
const float *area_co = data->area_co;
@@ -2963,15 +3122,16 @@ static void do_clay_strips_brush_task_cb_ex(
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
sculpt_brush_test_init(ss, &test);
+ plane_from_point_normal_v3(test.plane_tool, area_co, area_no_sp);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
if (sculpt_brush_test_cube(&test, vd.co, mat)) {
- if (plane_point_side_flip(vd.co, area_no_sp, area_co, flip)) {
+ if (plane_point_side_flip(vd.co, test.plane_tool, flip)) {
float intr[3];
float val[3];
- point_plane_project(intr, vd.co, area_no_sp, area_co);
+ closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
sub_v3_v3v3(val, intr, vd.co);
@@ -2979,8 +3139,8 @@ static void do_clay_strips_brush_task_cb_ex(
/* note, the normal from the vertices is ignored,
* causes glitch with planes, see: T44390 */
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, ss->cache->radius * test.dist,
- vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, ss->cache->radius * test.dist,
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -3048,44 +3208,54 @@ static void do_clay_strips_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int t
.area_no_sp = area_no_sp, .area_co = area_co, .mat = mat,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_clay_strips_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_clay_strips_brush_task_cb_ex,
+ &settings);
}
static void do_fill_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *area_no = data->area_no;
const float *area_co = data->area_co;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+
+ plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test_sq(&test, vd.co)) {
- if (plane_point_side(vd.co, area_no, area_co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ if (plane_point_side(vd.co, test.plane_tool)) {
float intr[3];
float val[3];
- point_plane_project(intr, vd.co, area_no, area_co);
+ closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
sub_v3_v3v3(val, intr, vd.co);
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, sqrtf(test.dist),
- vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -3126,44 +3296,53 @@ static void do_fill_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode)
.area_no = area_no, .area_co = area_co,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_fill_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_fill_brush_task_cb_ex,
+ &settings);
}
static void do_scrape_brush_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
const float *area_no = data->area_no;
const float *area_co = data->area_co;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
const float bstrength = ss->cache->bstrength;
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
+ plane_from_point_normal_v3(test.plane_tool, area_co, area_no);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE)
{
- if (sculpt_brush_test_sq(&test, vd.co)) {
- if (!plane_point_side(vd.co, area_no, area_co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
+ if (!plane_point_side(vd.co, test.plane_tool)) {
float intr[3];
float val[3];
- point_plane_project(intr, vd.co, area_no, area_co);
+ closest_to_plane_normalized_v3(intr, test.plane_tool, vd.co);
sub_v3_v3v3(val, intr, vd.co);
if (plane_trim(ss->cache, brush, val)) {
const float fade = bstrength * tex_strength(
- ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], val, fade);
@@ -3204,32 +3383,40 @@ static void do_scrape_brush(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnod
.area_no = area_no, .area_co = area_co,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_scrape_brush_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_scrape_brush_task_cb_ex,
+ &settings);
}
static void do_gravity_task_cb_ex(
- void *userdata, void *UNUSED(userdata_chunk), const int n, const int thread_id)
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict tls)
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
- Brush *brush = data->brush;
+ const Brush *brush = data->brush;
float *offset = data->offset;
PBVHVertexIter vd;
- SculptBrushTest test;
float (*proxy)[3];
proxy = BKE_pbvh_node_add_proxy(ss->pbvh, data->nodes[n])->co;
- sculpt_brush_test_init(ss, &test);
+ SculptBrushTest test;
+ SculptBrushTestFn sculpt_brush_test_sq_fn =
+ sculpt_brush_test_init_with_falloff_shape(ss, &test, data->brush->falloff_shape);
BKE_pbvh_vertex_iter_begin(ss->pbvh, data->nodes[n], vd, PBVH_ITER_UNIQUE) {
- if (sculpt_brush_test_sq(&test, vd.co)) {
+ if (sculpt_brush_test_sq_fn(&test, vd.co)) {
const float fade = tex_strength(
- ss, brush, vd.co, sqrtf(test.dist), vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f,
- thread_id);
+ ss, brush, vd.co, sqrtf(test.dist),
+ vd.no, vd.fno, vd.mask ? *vd.mask : 0.0f, tls->thread_id);
mul_v3_v3fl(proxy[vd.i], offset, fade);
@@ -3260,9 +3447,14 @@ static void do_gravity(Sculpt *sd, Object *ob, PBVHNode **nodes, int totnode, fl
.offset = offset,
};
- BLI_task_parallel_range_ex(
- 0, totnode, &data, NULL, 0, do_gravity_task_cb_ex,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT), false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
+ BLI_task_parallel_range(
+ 0, totnode,
+ &data,
+ do_gravity_task_cb_ex,
+ &settings);
}
@@ -3313,22 +3505,12 @@ void sculpt_vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3])
static void sculpt_topology_update(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSettings *UNUSED(ups))
{
SculptSession *ss = ob->sculpt;
- SculptSearchSphereData data;
- PBVHNode **nodes = NULL;
- float radius;
- int n, totnode;
-
- /* Build a list of all nodes that are potentially within the
- * brush's area of influence */
- data.ss = ss;
- data.sd = sd;
- radius = ss->cache->radius * 1.25f;
-
- data.radius_squared = radius * radius;
- data.original = sculpt_tool_needs_original(brush->sculpt_tool) ? true : ss->cache->original;
-
- BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, &totnode);
+ int n, totnode;
+ /* Build a list of all nodes that are potentially within the brush's area of influence */
+ const bool use_original = sculpt_tool_needs_original(brush->sculpt_tool) ? true : ss->cache->original;
+ const float radius_scale = 1.25f;
+ PBVHNode **nodes = sculpt_pbvh_gather_generic(ob, sd, brush, use_original, radius_scale, &totnode);
/* Only act if some verts are inside the brush area */
if (totnode) {
@@ -3360,8 +3542,10 @@ static void sculpt_topology_update(Sculpt *sd, Object *ob, Brush *brush, Unified
BKE_pbvh_bmesh_update_topology(
ss->pbvh, mode,
ss->cache->location,
- (brush->flag & BRUSH_FRONTFACE) ? ss->cache->view_normal : NULL,
- ss->cache->radius);
+ ss->cache->view_normal,
+ ss->cache->radius,
+ (brush->flag & BRUSH_FRONTFACE) != 0,
+ (brush->falloff_shape != PAINT_FALLOFF_SHAPE_SPHERE));
}
MEM_freeN(nodes);
@@ -3372,7 +3556,10 @@ static void sculpt_topology_update(Sculpt *sd, Object *ob, Brush *brush, Unified
}
}
-static void do_brush_action_task_cb(void *userdata, const int n)
+static void do_brush_action_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SculptThreadedTaskData *data = userdata;
@@ -3384,16 +3571,12 @@ static void do_brush_action_task_cb(void *userdata, const int n)
static void do_brush_action(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSettings *ups)
{
SculptSession *ss = ob->sculpt;
- SculptSearchSphereData data;
- PBVHNode **nodes = NULL;
int totnode;
/* Build a list of all nodes that are potentially within the brush's area of influence */
- data.ss = ss;
- data.sd = sd;
- data.radius_squared = ss->cache->radius_squared;
- data.original = sculpt_tool_needs_original(brush->sculpt_tool) ? true : ss->cache->original;
- BKE_pbvh_search_gather(ss->pbvh, sculpt_search_sphere_cb, &data, &nodes, &totnode);
+ const bool use_original = sculpt_tool_needs_original(brush->sculpt_tool) ? true : ss->cache->original;
+ const float radius_scale = 1.0f;
+ PBVHNode **nodes = sculpt_pbvh_gather_generic(ob, sd, brush, use_original, radius_scale, &totnode);
/* Only act if some verts are inside the brush area */
if (totnode) {
@@ -3403,9 +3586,14 @@ static void do_brush_action(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSe
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &task_data, do_brush_action_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &task_data,
+ do_brush_action_task_cb,
+ &settings);
if (sculpt_brush_needs_normal(brush, ss->cache->normal_weight))
update_sculpt_normal(sd, ob, nodes, totnode);
@@ -3517,7 +3705,10 @@ static void sculpt_flush_pbvhvert_deform(Object *ob, PBVHVertexIter *vd)
copy_v3_v3(me->mvert[index].co, newco);
}
-static void sculpt_combine_proxies_task_cb(void *userdata, const int n)
+static void sculpt_combine_proxies_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
@@ -3584,9 +3775,14 @@ static void sculpt_combine_proxies(Sculpt *sd, Object *ob)
.sd = sd, .ob = ob, .brush = brush, .nodes = nodes,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &data, sculpt_combine_proxies_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ sculpt_combine_proxies_task_cb,
+ &settings);
}
if (nodes)
@@ -3612,7 +3808,10 @@ static void sculpt_update_keyblock(Object *ob)
}
}
-static void sculpt_flush_stroke_deform_task_cb(void *userdata, const int n)
+static void sculpt_flush_stroke_deform_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SculptThreadedTaskData *data = userdata;
SculptSession *ss = data->ob->sculpt;
@@ -3665,9 +3864,14 @@ static void sculpt_flush_stroke_deform(Sculpt *sd, Object *ob)
.vertCos = vertCos,
};
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, &data, sculpt_flush_stroke_deform_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ &data,
+ sculpt_flush_stroke_deform_task_cb,
+ &settings);
if (vertCos) {
sculpt_vertcos_to_key(ob, ss->kb, vertCos);
@@ -3688,13 +3892,12 @@ static void sculpt_flush_stroke_deform(Sculpt *sd, Object *ob)
/* Flip all the editdata across the axis/axes specified by symm. Used to
* calculate multiple modifications to the mesh when symmetry is enabled. */
-static void calc_brushdata_symm(Sculpt *sd, StrokeCache *cache, const char symm,
- const char axis, const float angle,
- const float UNUSED(feather))
+void sculpt_cache_calc_brushdata_symm(
+ StrokeCache *cache, const char symm,
+ const char axis, const float angle)
{
- (void)sd; /* unused */
-
flip_v3_v3(cache->location, cache->true_location, symm);
+ flip_v3_v3(cache->last_location, cache->true_last_location, symm);
flip_v3_v3(cache->grab_delta_symmetry, cache->grab_delta, symm);
flip_v3_v3(cache->view_normal, cache->true_view_normal, symm);
@@ -3791,7 +3994,7 @@ static void do_tiled(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSettings
static void do_radial_symmetry(Sculpt *sd, Object *ob, Brush *brush, UnifiedPaintSettings *ups,
BrushActionFunc action,
const char symm, const int axis,
- const float feather)
+ const float UNUSED(feather))
{
SculptSession *ss = ob->sculpt;
int i;
@@ -3799,7 +4002,7 @@ static void do_radial_symmetry(Sculpt *sd, Object *ob, Brush *brush, UnifiedPain
for (i = 1; i < sd->radial_symm[axis - 'X']; ++i) {
const float angle = 2 * M_PI * i / sd->radial_symm[axis - 'X'];
ss->cache->radial_symmetry_pass = i;
- calc_brushdata_symm(sd, ss->cache, symm, axis, angle, feather);
+ sculpt_cache_calc_brushdata_symm(ss->cache, symm, axis, angle);
do_tiled(sd, ob, brush, ups, action);
}
}
@@ -3817,8 +4020,9 @@ static void sculpt_fix_noise_tear(Sculpt *sd, Object *ob)
multires_stitch_grids(ob);
}
-static void do_symmetrical_brush_actions(Sculpt *sd, Object *ob,
- BrushActionFunc action, UnifiedPaintSettings *ups)
+static void do_symmetrical_brush_actions(
+ Sculpt *sd, Object *ob,
+ BrushActionFunc action, UnifiedPaintSettings *ups)
{
Brush *brush = BKE_paint_brush(&sd->paint);
SculptSession *ss = ob->sculpt;
@@ -3837,7 +4041,7 @@ static void do_symmetrical_brush_actions(Sculpt *sd, Object *ob,
cache->mirror_symmetry_pass = i;
cache->radial_symmetry_pass = 0;
- calc_brushdata_symm(sd, cache, i, 0, 0, feather);
+ sculpt_cache_calc_brushdata_symm(cache, i, 0, 0);
do_tiled(sd, ob, brush, ups, action);
do_radial_symmetry(sd, ob, brush, ups, action, i, 'X', feather);
@@ -3900,7 +4104,7 @@ static const char *sculpt_tool_name(Sculpt *sd)
{
Brush *brush = BKE_paint_brush(&sd->paint);
- switch ((BrushSculptTool)brush->sculpt_tool) {
+ switch ((eBrushSculptTool)brush->sculpt_tool) {
case SCULPT_TOOL_DRAW:
return "Draw Brush";
case SCULPT_TOOL_SMOOTH:
@@ -3948,7 +4152,7 @@ static const char *sculpt_tool_name(Sculpt *sd)
* Operator for applying a stroke (various attributes including mouse path)
* using the current brush. */
-static void sculpt_cache_free(StrokeCache *cache)
+void sculpt_cache_free(StrokeCache *cache)
{
if (cache->dial)
MEM_freeN(cache->dial);
@@ -4211,7 +4415,6 @@ static void sculpt_update_brush_delta(UnifiedPaintSettings *ups, Object *ob, Bru
sub_v3_v3v3(cache->grab_delta, grab_location,
cache->old_grab_location);
}
-
invert_m4_m4(imat, ob->obmat);
mul_mat3_m4_v3(imat, cache->grab_delta);
break;
@@ -4221,6 +4424,10 @@ static void sculpt_update_brush_delta(UnifiedPaintSettings *ups, Object *ob, Bru
zero_v3(cache->grab_delta);
}
+ if (brush->falloff_shape == PAINT_FALLOFF_SHAPE_TUBE) {
+ project_plane_v3_v3v3(cache->grab_delta, cache->grab_delta, ss->cache->true_view_normal);
+ }
+
copy_v3_v3(cache->old_grab_location, grab_location);
if (tool == SCULPT_TOOL_GRAB)
@@ -4385,34 +4592,18 @@ static bool sculpt_any_smooth_mode(const Brush *brush,
(brush->mask_tool == BRUSH_MASK_SMOOTH)));
}
-static void sculpt_stroke_modifiers_check(const bContext *C, Object *ob)
+static void sculpt_stroke_modifiers_check(const bContext *C, Object *ob, const Brush *brush)
{
SculptSession *ss = ob->sculpt;
if (ss->kb || ss->modifiers_active) {
- Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
- Brush *brush = BKE_paint_brush(&sd->paint);
-
- BKE_sculpt_update_mesh_elements(CTX_data_scene(C), sd, ob,
- sculpt_any_smooth_mode(brush, ss->cache, 0), false);
+ Scene *scene = CTX_data_scene(C);
+ Sculpt *sd = scene->toolsettings->sculpt;
+ bool need_pmap = sculpt_any_smooth_mode(brush, ss->cache, 0);
+ BKE_sculpt_update_mesh_elements(scene, sd, ob, need_pmap, false);
}
}
-typedef struct {
- SculptSession *ss;
- const float *ray_start, *ray_normal;
- bool hit;
- float dist;
- bool original;
-} SculptRaycastData;
-
-typedef struct {
- const float *ray_start, *ray_normal;
- bool hit;
- float dist;
- float detail;
-} SculptDetailRaycastData;
-
static void sculpt_raycast_cb(PBVHNode *node, void *data_v, float *tmin)
{
if (BKE_pbvh_node_get_tmin(node) < *tmin) {
@@ -4433,10 +4624,40 @@ static void sculpt_raycast_cb(PBVHNode *node, void *data_v, float *tmin)
}
if (BKE_pbvh_node_raycast(srd->ss->pbvh, node, origco, use_origco,
- srd->ray_start, srd->ray_normal, &srd->dist))
+ srd->ray_start, srd->ray_normal, &srd->depth))
+ {
+ srd->hit = 1;
+ *tmin = srd->depth;
+ }
+ }
+}
+
+static void sculpt_find_nearest_to_ray_cb(PBVHNode *node, void *data_v, float *tmin)
+{
+ if (BKE_pbvh_node_get_tmin(node) < *tmin) {
+ SculptFindNearestToRayData *srd = data_v;
+ float (*origco)[3] = NULL;
+ bool use_origco = false;
+
+ if (srd->original && srd->ss->cache) {
+ if (BKE_pbvh_type(srd->ss->pbvh) == PBVH_BMESH) {
+ use_origco = true;
+ }
+ else {
+ /* intersect with coordinates from before we started stroke */
+ SculptUndoNode *unode = sculpt_undo_get_node(node);
+ origco = (unode) ? unode->co : NULL;
+ use_origco = origco ? true : false;
+ }
+ }
+
+ if (BKE_pbvh_node_find_nearest_to_ray(
+ srd->ss->pbvh, node, origco, use_origco,
+ srd->ray_start, srd->ray_normal,
+ &srd->depth, &srd->dist_sq_to_ray))
{
srd->hit = 1;
- *tmin = srd->dist;
+ *tmin = srd->dist_sq_to_ray;
}
}
}
@@ -4446,10 +4667,10 @@ static void sculpt_raycast_detail_cb(PBVHNode *node, void *data_v, float *tmin)
if (BKE_pbvh_node_get_tmin(node) < *tmin) {
SculptDetailRaycastData *srd = data_v;
if (BKE_pbvh_bmesh_node_raycast_detail(node, srd->ray_start, srd->ray_normal,
- &srd->dist, &srd->detail))
+ &srd->depth, &srd->detail))
{
srd->hit = 1;
- *tmin = srd->dist;
+ *tmin = srd->depth;
}
}
}
@@ -4496,12 +4717,11 @@ bool sculpt_stroke_get_location(bContext *C, float out[3], const float mouse[2])
Object *ob;
SculptSession *ss;
StrokeCache *cache;
- float ray_start[3], ray_end[3], ray_normal[3], dist;
- SculptRaycastData srd;
+ float ray_start[3], ray_end[3], ray_normal[3], depth;
bool original;
ViewContext vc;
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
ob = vc.obact;
@@ -4509,25 +4729,61 @@ bool sculpt_stroke_get_location(bContext *C, float out[3], const float mouse[2])
cache = ss->cache;
original = (cache) ? cache->original : 0;
- sculpt_stroke_modifiers_check(C, ob);
+ const Brush *brush = BKE_paint_brush(BKE_paint_get_active_from_context(C));
- dist = sculpt_raycast_init(&vc, mouse, ray_start, ray_end, ray_normal, original);
+ sculpt_stroke_modifiers_check(C, ob, brush);
- srd.original = original;
- srd.ss = ob->sculpt;
- srd.hit = 0;
- srd.ray_start = ray_start;
- srd.ray_normal = ray_normal;
- srd.dist = dist;
+ depth = sculpt_raycast_init(&vc, mouse, ray_start, ray_end, ray_normal, original);
+
+ bool hit = false;
+ {
+ SculptRaycastData srd = {
+ .original = original,
+ .ss = ob->sculpt,
+ .hit = 0,
+ .ray_start = ray_start,
+ .ray_normal = ray_normal,
+ .depth = depth,
+ };
+ BKE_pbvh_raycast(
+ ss->pbvh, sculpt_raycast_cb, &srd,
+ ray_start, ray_normal, srd.original);
+ if (srd.hit) {
+ hit = true;
+ copy_v3_v3(out, ray_normal);
+ mul_v3_fl(out, srd.depth);
+ add_v3_v3(out, ray_start);
+ }
+ }
- BKE_pbvh_raycast(ss->pbvh, sculpt_raycast_cb, &srd,
- ray_start, ray_normal, srd.original);
+ if (hit == false) {
+ if (ELEM(brush->falloff_shape, PAINT_FALLOFF_SHAPE_TUBE)) {
+ SculptFindNearestToRayData srd = {
+ .original = original,
+ .ss = ob->sculpt,
+ .hit = 0,
+ .ray_start = ray_start,
+ .ray_normal = ray_normal,
+ .depth = FLT_MAX,
+ .dist_sq_to_ray = FLT_MAX,
+ };
+ BKE_pbvh_find_nearest_to_ray(
+ ss->pbvh, sculpt_find_nearest_to_ray_cb, &srd,
+ ray_start, ray_normal, srd.original);
+ if (srd.hit) {
+ hit = true;
+ copy_v3_v3(out, ray_normal);
+ mul_v3_fl(out, srd.depth);
+ add_v3_v3(out, ray_start);
+ }
+ }
+ }
- copy_v3_v3(out, ray_normal);
- mul_v3_fl(out, srd.dist);
- add_v3_v3(out, ray_start);
+ if (cache && hit) {
+ copy_v3_v3(cache->true_location, out);
+ }
- return srd.hit;
+ return hit;
}
static void sculpt_brush_init_tex(const Scene *scene, Sculpt *sd, SculptSession *ss)
@@ -4656,8 +4912,11 @@ static bool sculpt_stroke_test_start(bContext *C, struct wmOperator *op,
const float mouse[2])
{
/* Don't start the stroke until mouse goes over the mesh.
- * note: mouse will only be null when re-executing the saved stroke. */
- if (!mouse || over_mesh(C, op, mouse[0], mouse[1])) {
+ * note: mouse will only be null when re-executing the saved stroke.
+ * We have exception for 'exec' strokes since they may not set 'mouse', only 'location', see: T52195. */
+ if (((op->flag & OP_IS_INVOKE) == 0) ||
+ (mouse == NULL) || over_mesh(C, op, mouse[0], mouse[1]))
+ {
Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
@@ -4682,7 +4941,7 @@ static void sculpt_stroke_update_step(bContext *C, struct PaintStroke *UNUSED(st
SculptSession *ss = ob->sculpt;
const Brush *brush = BKE_paint_brush(&sd->paint);
- sculpt_stroke_modifiers_check(C, ob);
+ sculpt_stroke_modifiers_check(C, ob, brush);
sculpt_update_cache_variants(C, sd, ob, itemptr);
sculpt_restore_mesh(sd, ob);
@@ -4754,9 +5013,10 @@ static void sculpt_stroke_done(const bContext *C, struct PaintStroke *UNUSED(str
if (ss->cache) {
UnifiedPaintSettings *ups = &CTX_data_tool_settings(C)->unified_paint_settings;
Brush *brush = BKE_paint_brush(&sd->paint);
+ BLI_assert(brush == ss->cache->brush); /* const, so we shouldn't change. */
ups->draw_inverted = false;
- sculpt_stroke_modifiers_check(C, ob);
+ sculpt_stroke_modifiers_check(C, ob, brush);
/* Alt-Smooth */
if (ss->cache->alt_smooth) {
@@ -4764,11 +5024,10 @@ static void sculpt_stroke_done(const bContext *C, struct PaintStroke *UNUSED(str
brush->mask_tool = ss->cache->saved_mask_brush_tool;
}
else {
- Paint *p = &sd->paint;
- BKE_brush_size_set(scene, ss->cache->brush, ss->cache->saved_smooth_size);
+ BKE_brush_size_set(scene, brush, ss->cache->saved_smooth_size);
brush = (Brush *)BKE_libblock_find_name(ID_BR, ss->cache->saved_active_brush_name);
if (brush) {
- BKE_paint_brush_set(p, brush);
+ BKE_paint_brush_set(&sd->paint, brush);
}
}
}
@@ -4776,7 +5035,7 @@ static void sculpt_stroke_done(const bContext *C, struct PaintStroke *UNUSED(str
sculpt_cache_free(ss->cache);
ss->cache = NULL;
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
BKE_pbvh_update(ss->pbvh, PBVH_UpdateOriginalBB, NULL);
@@ -4984,21 +5243,19 @@ void sculpt_dyntopo_node_layers_add(SculptSession *ss)
}
-void sculpt_update_after_dynamic_topology_toggle(bContext *C)
+void sculpt_update_after_dynamic_topology_toggle(
+ Scene *scene, Object *ob)
{
- Scene *scene = CTX_data_scene(C);
- Object *ob = CTX_data_active_object(C);
Sculpt *sd = scene->toolsettings->sculpt;
/* Create the PBVH */
BKE_sculpt_update_mesh_elements(scene, sd, ob, false, false);
- WM_event_add_notifier(C, NC_OBJECT | ND_DRAW, ob);
+ WM_main_add_notifier(NC_OBJECT | ND_DRAW, ob);
}
-void sculpt_dynamic_topology_enable(bContext *C)
+void sculpt_dynamic_topology_enable_ex(
+ Scene *scene, Object *ob)
{
- Scene *scene = CTX_data_scene(C);
- Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
Mesh *me = ob->data;
const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_ME(me);
@@ -5034,17 +5291,16 @@ void sculpt_dynamic_topology_enable(bContext *C)
ss->bm_log = BM_log_create(ss->bm);
/* Refresh */
- sculpt_update_after_dynamic_topology_toggle(C);
+ sculpt_update_after_dynamic_topology_toggle(scene, ob);
}
/* Free the sculpt BMesh and BMLog
*
* If 'unode' is given, the BMesh's data is copied out to the unode
* before the BMesh is deleted so that it can be restored from */
-void sculpt_dynamic_topology_disable(bContext *C,
- SculptUndoNode *unode)
+void sculpt_dynamic_topology_disable_ex(
+ Scene *scene, Object *ob, SculptUndoNode *unode)
{
- Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
Mesh *me = ob->data;
@@ -5093,28 +5349,54 @@ void sculpt_dynamic_topology_disable(bContext *C,
}
/* Refresh */
- sculpt_update_after_dynamic_topology_toggle(C);
+ sculpt_update_after_dynamic_topology_toggle(scene, ob);
}
+void sculpt_dynamic_topology_disable(bContext *C, SculptUndoNode *unode)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ sculpt_dynamic_topology_disable_ex(scene, ob, unode);
+}
+
+static void sculpt_dynamic_topology_disable_with_undo(
+ Scene *scene, Object *ob)
+{
+ SculptSession *ss = ob->sculpt;
+ if (ss->bm) {
+ sculpt_undo_push_begin("Dynamic topology disable");
+ sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_END);
+ sculpt_dynamic_topology_disable_ex(scene, ob, NULL);
+ sculpt_undo_push_end();
+ }
+}
+
+static void sculpt_dynamic_topology_enable_with_undo(
+ Scene *scene, Object *ob)
+{
+ SculptSession *ss = ob->sculpt;
+ if (ss->bm == NULL) {
+ sculpt_undo_push_begin("Dynamic topology enable");
+ sculpt_dynamic_topology_enable_ex(scene, ob);
+ sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
+ sculpt_undo_push_end();
+ }
+}
static int sculpt_dynamic_topology_toggle_exec(bContext *C, wmOperator *UNUSED(op))
{
+ Scene *scene = CTX_data_scene(C);
Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
WM_cursor_wait(1);
if (ss->bm) {
- sculpt_undo_push_begin("Dynamic topology disable");
- sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_END);
- sculpt_dynamic_topology_disable(C, NULL);
+ sculpt_dynamic_topology_disable_with_undo(scene, ob);
}
else {
- sculpt_undo_push_begin("Dynamic topology enable");
- sculpt_dynamic_topology_enable(C);
- sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
+ sculpt_dynamic_topology_enable_with_undo(scene, ob);
}
- sculpt_undo_push_end(C);
WM_cursor_wait(0);
@@ -5150,20 +5432,18 @@ static int dyntopo_warning_popup(bContext *C, wmOperatorType *ot, enum eDynTopoW
uiItemS(layout);
}
- uiItemFullO_ptr(layout, ot, IFACE_("OK"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0);
+ uiItemFullO_ptr(layout, ot, IFACE_("OK"), ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, NULL);
UI_popup_menu_end(C, pup);
return OPERATOR_INTERFACE;
}
-static enum eDynTopoWarnFlag sculpt_dynamic_topology_check(bContext *C)
+static enum eDynTopoWarnFlag sculpt_dynamic_topology_check(Scene *scene, Object *ob)
{
- Object *ob = CTX_data_active_object(C);
Mesh *me = ob->data;
SculptSession *ss = ob->sculpt;
- Scene *scene = CTX_data_scene(C);
enum eDynTopoWarnFlag flag = 0;
BLI_assert(ss->bm == NULL);
@@ -5208,7 +5488,8 @@ static int sculpt_dynamic_topology_toggle_invoke(bContext *C, wmOperator *op, co
SculptSession *ss = ob->sculpt;
if (!ss->bm) {
- enum eDynTopoWarnFlag flag = sculpt_dynamic_topology_check(C);
+ Scene *scene = CTX_data_scene(C);
+ enum eDynTopoWarnFlag flag = sculpt_dynamic_topology_check(scene, ob);
if (flag) {
/* The mesh has customdata that will be lost, let the user confirm this is OK */
@@ -5302,7 +5583,7 @@ static int sculpt_symmetrize_exec(bContext *C, wmOperator *UNUSED(op))
/* Finish undo */
BM_log_all_added(ss->bm, ss->bm_log);
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
/* Redraw */
sculpt_pbvh_clear(ob);
@@ -5327,167 +5608,201 @@ static void SCULPT_OT_symmetrize(wmOperatorType *ot)
static void sculpt_init_session(Scene *scene, Object *ob)
{
- ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
+ /* Create persistent sculpt mode data */
+ BKE_sculpt_toolsettings_data_ensure(scene);
+ ob->sculpt = MEM_callocN(sizeof(SculptSession), "sculpt session");
BKE_sculpt_update_mesh_elements(scene, scene->toolsettings->sculpt, ob, 0, false);
}
-
-static int sculpt_mode_toggle_exec(bContext *C, wmOperator *op)
+static int ed_object_sculptmode_flush_recalc_flag(Scene *scene, Object *ob, MultiresModifierData *mmd)
{
- Scene *scene = CTX_data_scene(C);
- ToolSettings *ts = CTX_data_tool_settings(C);
- Object *ob = CTX_data_active_object(C);
- const int mode_flag = OB_MODE_SCULPT;
- const bool is_mode_set = (ob->mode & mode_flag) != 0;
- Mesh *me;
- MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
int flush_recalc = 0;
-
- if (!is_mode_set) {
- if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
- return OPERATOR_CANCELLED;
- }
- }
-
- me = BKE_mesh_from_object(ob);
-
/* multires in sculpt mode could have different from object mode subdivision level */
flush_recalc |= mmd && mmd->sculptlvl != mmd->lvl;
/* if object has got active modifiers, it's dm could be different in sculpt mode */
flush_recalc |= sculpt_has_active_modifiers(scene, ob);
+ return flush_recalc;
+}
- if (is_mode_set) {
- if (mmd)
- multires_force_update(ob);
+void ED_object_sculptmode_enter_ex(
+ Scene *scene, Object *ob,
+ ReportList *reports)
+{
+ const int mode_flag = OB_MODE_SCULPT;
+ Mesh *me = BKE_mesh_from_object(ob);
- if (flush_recalc || (ob->sculpt && ob->sculpt->bm))
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ /* Enter sculptmode */
+ ob->mode |= mode_flag;
- if (me->flag & ME_SCULPT_DYNAMIC_TOPOLOGY) {
- /* Dynamic topology must be disabled before exiting sculpt
- * mode to ensure the undo stack stays in a consistent
- * state */
- sculpt_dynamic_topology_toggle_exec(C, NULL);
- /* store so we know to re-enable when entering sculpt mode */
- me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
- }
+ MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
- /* Leave sculptmode */
- ob->mode &= ~mode_flag;
+ const int flush_recalc = ed_object_sculptmode_flush_recalc_flag(scene, ob, mmd);
+
+ if (flush_recalc) {
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
+ /* Create sculpt mode session data */
+ if (ob->sculpt) {
BKE_sculptsession_free(ob);
+ }
+
+ sculpt_init_session(scene, ob);
- paint_cursor_delete_textures();
+ /* Mask layer is required */
+ if (mmd) {
+ /* XXX, we could attempt to support adding mask data mid-sculpt mode (with multi-res)
+ * but this ends up being quite tricky (and slow) */
+ BKE_sculpt_mask_layers_ensure(ob, mmd);
}
- else {
- /* Enter sculptmode */
- ob->mode |= mode_flag;
- if (flush_recalc)
- DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ if (!(fabsf(ob->size[0] - ob->size[1]) < 1e-4f && fabsf(ob->size[1] - ob->size[2]) < 1e-4f)) {
+ BKE_report(reports, RPT_WARNING,
+ "Object has non-uniform scale, sculpting may be unpredictable");
+ }
+ else if (is_negative_m4(ob->obmat)) {
+ BKE_report(reports, RPT_WARNING,
+ "Object has negative scale, sculpting may be unpredictable");
+ }
- /* Create persistent sculpt mode data */
- if (!ts->sculpt) {
- ts->sculpt = MEM_callocN(sizeof(Sculpt), "sculpt mode data");
+ Paint *paint = BKE_paint_get_active_from_paintmode(scene, ePaintSculpt);
+ BKE_paint_init(scene, ePaintSculpt, PAINT_CURSOR_SCULPT);
- /* Turn on X plane mirror symmetry by default */
- ts->sculpt->paint.symmetry_flags |= PAINT_SYMM_X;
- ts->sculpt->paint.flags |= PAINT_SHOW_BRUSH;
+ paint_cursor_start_explicit(paint, G.main->wm.first, sculpt_poll_view3d);
- /* Make sure at least dyntopo subdivision is enabled */
- ts->sculpt->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE;
+ /* Check dynamic-topology flag; re-enter dynamic-topology mode when changing modes,
+ * As long as no data was added that is not supported. */
+ if (me->flag & ME_SCULPT_DYNAMIC_TOPOLOGY) {
+ const char *message_unsupported = NULL;
+ if (me->totloop != me->totpoly * 3) {
+ message_unsupported = TIP_("non-triangle face");
+ }
+ else if (mmd != NULL) {
+ message_unsupported = TIP_("multi-res modifier");
+ }
+ else {
+ enum eDynTopoWarnFlag flag = sculpt_dynamic_topology_check(scene, ob);
+ if (flag == 0) {
+ /* pass */
+ }
+ else if (flag & DYNTOPO_WARN_VDATA) {
+ message_unsupported = TIP_("vertex data");
+ }
+ else if (flag & DYNTOPO_WARN_EDATA) {
+ message_unsupported = TIP_("edge data");
+ }
+ else if (flag & DYNTOPO_WARN_LDATA) {
+ message_unsupported = TIP_("face data");
+ }
+ else if (flag & DYNTOPO_WARN_MODIFIER) {
+ message_unsupported = TIP_("constructive modifier");
+ }
+ else {
+ BLI_assert(0);
+ }
}
- if (!ts->sculpt->detail_size)
- ts->sculpt->detail_size = 12;
- if (!ts->sculpt->detail_percent)
- ts->sculpt->detail_percent = 25;
- if (ts->sculpt->constant_detail == 0.0f)
- ts->sculpt->constant_detail = 3.0f;
+ if (message_unsupported == NULL) {
+ /* undo push is needed to prevent memory leak */
+ sculpt_undo_push_begin("Dynamic topology enable");
+ sculpt_dynamic_topology_enable_ex(scene, ob);
+ sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
+ }
+ else {
+ BKE_reportf(reports, RPT_WARNING,
+ "Dynamic Topology found: %s, disabled",
+ message_unsupported);
+ me->flag &= ~ME_SCULPT_DYNAMIC_TOPOLOGY;
+ }
+ }
- /* Set sane default tiling offsets */
- if (!ts->sculpt->paint.tile_offset[0]) ts->sculpt->paint.tile_offset[0] = 1.0f;
- if (!ts->sculpt->paint.tile_offset[1]) ts->sculpt->paint.tile_offset[1] = 1.0f;
- if (!ts->sculpt->paint.tile_offset[2]) ts->sculpt->paint.tile_offset[2] = 1.0f;
+ /* VBO no longer valid */
+ if (ob->derivedFinal) {
+ GPU_drawobject_free(ob->derivedFinal);
+ }
+}
+void ED_object_sculptmode_enter(struct bContext *C, ReportList *reports)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ ED_object_sculptmode_enter_ex(scene, ob, reports);
+}
- /* Create sculpt mode session data */
- if (ob->sculpt)
- BKE_sculptsession_free(ob);
+void ED_object_sculptmode_exit_ex(
+ Scene *scene, Object *ob)
+{
+ const int mode_flag = OB_MODE_SCULPT;
+ Mesh *me = BKE_mesh_from_object(ob);
- sculpt_init_session(scene, ob);
+ MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob);
+ if (mmd) {
+ multires_force_update(ob);
+ }
+
+ /* Not needed for now. */
+#if 0
+ const int flush_recalc = ed_object_sculptmode_flush_recalc_flag(scene, ob, mmd);
+#endif
- /* Mask layer is required */
- if (mmd) {
- /* XXX, we could attempt to support adding mask data mid-sculpt mode (with multi-res)
- * but this ends up being quite tricky (and slow) */
- BKE_sculpt_mask_layers_ensure(ob, mmd);
- }
+ /* Always for now, so leaving sculpt mode always ensures scene is in
+ * a consistent state.
+ */
+ if (true || /* flush_recalc || */ (ob->sculpt && ob->sculpt->bm)) {
+ DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ }
- if (!(fabsf(ob->size[0] - ob->size[1]) < 1e-4f && fabsf(ob->size[1] - ob->size[2]) < 1e-4f)) {
- BKE_report(op->reports, RPT_WARNING,
- "Object has non-uniform scale, sculpting may be unpredictable");
- }
- else if (is_negative_m4(ob->obmat)) {
- BKE_report(op->reports, RPT_WARNING,
- "Object has negative scale, sculpting may be unpredictable");
- }
+ if (me->flag & ME_SCULPT_DYNAMIC_TOPOLOGY) {
+ /* Dynamic topology must be disabled before exiting sculpt
+ * mode to ensure the undo stack stays in a consistent
+ * state */
+ sculpt_dynamic_topology_disable_with_undo(scene, ob);
- BKE_paint_init(scene, ePaintSculpt, PAINT_CURSOR_SCULPT);
+ /* store so we know to re-enable when entering sculpt mode */
+ me->flag |= ME_SCULPT_DYNAMIC_TOPOLOGY;
+ }
- paint_cursor_start(C, sculpt_poll_view3d);
+ /* Leave sculptmode */
+ ob->mode &= ~mode_flag;
- /* Check dynamic-topology flag; re-enter dynamic-topology mode when changing modes,
- * As long as no data was added that is not supported. */
- if (me->flag & ME_SCULPT_DYNAMIC_TOPOLOGY) {
- const char *message_unsupported = NULL;
- if (me->totloop != me->totpoly * 3) {
- message_unsupported = TIP_("non-triangle face");
- }
- else if (mmd != NULL) {
- message_unsupported = TIP_("multi-res modifier");
- }
- else {
- enum eDynTopoWarnFlag flag = sculpt_dynamic_topology_check(C);
- if (flag == 0) {
- /* pass */
- }
- else if (flag & DYNTOPO_WARN_VDATA) {
- message_unsupported = TIP_("vertex data");
- }
- else if (flag & DYNTOPO_WARN_EDATA) {
- message_unsupported = TIP_("edge data");
- }
- else if (flag & DYNTOPO_WARN_LDATA) {
- message_unsupported = TIP_("face data");
- }
- else if (flag & DYNTOPO_WARN_MODIFIER) {
- message_unsupported = TIP_("constructive modifier");
- }
- else {
- BLI_assert(0);
- }
- }
+ BKE_sculptsession_free(ob);
- if (message_unsupported == NULL) {
- /* undo push is needed to prevent memory leak */
- sculpt_undo_push_begin("Dynamic topology enable");
- sculpt_dynamic_topology_enable(C);
- sculpt_undo_push_node(ob, NULL, SCULPT_UNDO_DYNTOPO_BEGIN);
- }
- else {
- BKE_reportf(op->reports, RPT_WARNING,
- "Dynamic Topology found: %s, disabled",
- message_unsupported);
- me->flag &= ~ME_SCULPT_DYNAMIC_TOPOLOGY;
- }
+ paint_cursor_delete_textures();
+
+ /* VBO no longer valid */
+ if (ob->derivedFinal) {
+ GPU_drawobject_free(ob->derivedFinal);
+ }
+}
+
+void ED_object_sculptmode_exit(bContext *C)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ ED_object_sculptmode_exit_ex(scene, ob);
+}
+
+static int sculpt_mode_toggle_exec(bContext *C, wmOperator *op)
+{
+ Scene *scene = CTX_data_scene(C);
+ Object *ob = CTX_data_active_object(C);
+ const int mode_flag = OB_MODE_SCULPT;
+ const bool is_mode_set = (ob->mode & mode_flag) != 0;
+
+ if (!is_mode_set) {
+ if (!ED_object_mode_compat_set(C, ob, mode_flag, op->reports)) {
+ return OPERATOR_CANCELLED;
}
}
- if (ob->derivedFinal) /* VBO no longer valid */
- GPU_drawobject_free(ob->derivedFinal);
+ if (is_mode_set) {
+ ED_object_sculptmode_exit_ex(scene, ob);
+ }
+ else {
+ ED_object_sculptmode_enter_ex(scene, ob, op->reports);
+ }
WM_event_add_notifier(C, NC_SCENE | ND_MODE, scene);
@@ -5523,7 +5838,7 @@ static int sculpt_detail_flood_fill_exec(bContext *C, wmOperator *UNUSED(op))
Object *ob = CTX_data_active_object(C);
SculptSession *ss = ob->sculpt;
float size;
- float bb_min[3], bb_max[3];
+ float bb_min[3], bb_max[3], center[3], dim[3];
int i, totnodes;
PBVHNode **nodes;
@@ -5535,11 +5850,12 @@ static int sculpt_detail_flood_fill_exec(bContext *C, wmOperator *UNUSED(op))
for (i = 0; i < totnodes; i++) {
BKE_pbvh_node_mark_topology_update(nodes[i]);
}
- /* get the bounding box, store the size to bb_max and center (zero) to bb_min */
+ /* get the bounding box, it's center and size */
BKE_pbvh_bounding_box(ob->sculpt->pbvh, bb_min, bb_max);
- sub_v3_v3(bb_max, bb_min);
- zero_v3(bb_min);
- size = max_fff(bb_max[0], bb_max[1], bb_max[2]);
+ add_v3_v3v3(center, bb_min, bb_max);
+ mul_v3_fl(center, 0.5f);
+ sub_v3_v3v3(dim, bb_max, bb_min);
+ size = max_fff(dim[0], dim[1], dim[2]);
/* update topology size */
BKE_pbvh_bmesh_detail_size_set(ss->pbvh, 1.0f / sd->constant_detail);
@@ -5549,14 +5865,14 @@ static int sculpt_detail_flood_fill_exec(bContext *C, wmOperator *UNUSED(op))
while (BKE_pbvh_bmesh_update_topology(
ss->pbvh, PBVH_Collapse | PBVH_Subdivide,
- bb_min, NULL, size))
+ center, NULL, size, false, false))
{
for (i = 0; i < totnodes; i++)
BKE_pbvh_node_mark_topology_update(nodes[i]);
}
MEM_freeN(nodes);
- sculpt_undo_push_end(C);
+ sculpt_undo_push_end();
/* force rebuild of pbvh for better BB placement */
sculpt_pbvh_clear(ob);
@@ -5585,22 +5901,24 @@ static void sample_detail(bContext *C, int ss_co[2])
ViewContext vc;
Object *ob;
Sculpt *sd;
- float ray_start[3], ray_end[3], ray_normal[3], dist;
+ float ray_start[3], ray_end[3], ray_normal[3], depth;
SculptDetailRaycastData srd;
float mouse[2] = {ss_co[0], ss_co[1]};
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
sd = CTX_data_tool_settings(C)->sculpt;
ob = vc.obact;
- sculpt_stroke_modifiers_check(C, ob);
+ Brush *brush = BKE_paint_brush(&sd->paint);
+
+ sculpt_stroke_modifiers_check(C, ob, brush);
- dist = sculpt_raycast_init(&vc, mouse, ray_start, ray_end, ray_normal, false);
+ depth = sculpt_raycast_init(&vc, mouse, ray_start, ray_end, ray_normal, false);
srd.hit = 0;
srd.ray_start = ray_start;
srd.ray_normal = ray_normal;
- srd.dist = dist;
+ srd.depth = depth;
srd.detail = sd->constant_detail;
BKE_pbvh_raycast(ob->sculpt->pbvh, sculpt_raycast_detail_cb, &srd,
diff --git a/source/blender/editors/sculpt_paint/sculpt_intern.h b/source/blender/editors/sculpt_paint/sculpt_intern.h
index 108fe3532e3..e46760258e1 100644
--- a/source/blender/editors/sculpt_paint/sculpt_intern.h
+++ b/source/blender/editors/sculpt_paint/sculpt_intern.h
@@ -38,12 +38,15 @@
#include "DNA_key_types.h"
#include "BLI_bitmap.h"
+#include "BLI_threads.h"
+
#include "BKE_pbvh.h"
struct bContext;
struct KeyBlock;
struct Object;
struct SculptUndoNode;
+struct SculptOrigVertData;
int sculpt_mode_poll(struct bContext *C);
int sculpt_mode_poll_view3d(struct bContext *C);
@@ -52,15 +55,21 @@ int sculpt_poll(struct bContext *C);
int sculpt_poll_view3d(struct bContext *C);
/* Stroke */
-bool sculpt_stroke_get_location(bContext *C, float out[3], const float mouse[2]);
+bool sculpt_stroke_get_location(struct bContext *C, float out[3], const float mouse[2]);
/* Dynamic topology */
void sculpt_pbvh_clear(Object *ob);
void sculpt_dyntopo_node_layers_add(struct SculptSession *ss);
-void sculpt_update_after_dynamic_topology_toggle(bContext *C);
-void sculpt_dynamic_topology_enable(struct bContext *C);
-void sculpt_dynamic_topology_disable(struct bContext *C,
- struct SculptUndoNode *unode);
+void sculpt_update_after_dynamic_topology_toggle(
+ struct Scene *scene, struct Object *ob);
+void sculpt_dynamic_topology_enable_ex(
+ struct Scene *scene, struct Object *ob);
+void sculpt_dynamic_topology_enable(bContext *C);
+
+void sculpt_dynamic_topology_disable_ex(
+ struct Scene *scene, struct Object *ob,
+ struct SculptUndoNode *unode);
+void sculpt_dynamic_topology_disable(bContext *C, struct SculptUndoNode *unode);
/* Undo */
@@ -113,17 +122,242 @@ typedef struct SculptUndoNode {
/* shape keys */
char shapeName[sizeof(((KeyBlock *)0))->name];
+
+ size_t undo_size;
} SculptUndoNode;
+/* Factor of brush to have rake point following behind
+ * (could be configurable but this is reasonable default). */
+#define SCULPT_RAKE_BRUSH_FACTOR 0.25f
+
+struct SculptRakeData {
+ float follow_dist;
+ float follow_co[3];
+};
+
+/* Single struct used by all BLI_task threaded callbacks, let's avoid adding 10's of those... */
+typedef struct SculptThreadedTaskData {
+ struct bContext *C;
+ struct Sculpt *sd;
+ struct Object *ob;
+ const struct Brush *brush;
+ struct PBVHNode **nodes;
+ int totnode;
+
+ struct VPaint *vp;
+ struct VPaintData *vpd;
+ struct WPaintData *wpd;
+ struct WeightPaintInfo *wpi;
+ unsigned int *lcol;
+ struct Mesh *me;
+ /* For passing generic params. */
+ void *custom_data;
+
+
+ /* Data specific to some callbacks. */
+ /* Note: even if only one or two of those are used at a time, keeping them separated, names help figuring out
+ * what it is, and memory overhead is ridiculous anyway... */
+ float flippedbstrength;
+ float angle;
+ float strength;
+ bool smooth_mask;
+ bool has_bm_orco;
+
+ struct SculptProjectVector *spvc;
+ float *offset;
+ float *grab_delta;
+ float *cono;
+ float *area_no;
+ float *area_no_sp;
+ float *area_co;
+ float(*mat)[4];
+ float(*vertCos)[3];
+
+ /* 0=towards view, 1=flipped */
+ float(*area_cos)[3];
+ float(*area_nos)[3];
+ int *count;
+
+ ThreadMutex mutex;
+
+} SculptThreadedTaskData;
+
+/*************** Brush testing declarations ****************/
+typedef struct SculptBrushTest {
+ float radius_squared;
+ float location[3];
+ float dist;
+ int mirror_symmetry_pass;
+
+ /* For circle (not sphere) projection. */
+ float plane_view[4];
+
+ /* Some tool code uses a plane for it's calculateions. */
+ float plane_tool[4];
+
+ /* View3d clipping - only set rv3d for clipping */
+ struct RegionView3D *clip_rv3d;
+} SculptBrushTest;
+
+typedef bool (*SculptBrushTestFn)(SculptBrushTest *test, const float co[3]);
+
+typedef struct {
+ struct Sculpt *sd;
+ struct SculptSession *ss;
+ float radius_squared;
+ bool original;
+} SculptSearchSphereData;
+
+typedef struct {
+ struct Sculpt *sd;
+ struct SculptSession *ss;
+ float radius_squared;
+ bool original;
+ struct DistRayAABB_Precalc *dist_ray_to_aabb_precalc;
+} SculptSearchCircleData;
+
+void sculpt_brush_test_init(struct SculptSession *ss, SculptBrushTest *test);
+bool sculpt_brush_test_sphere(SculptBrushTest *test, const float co[3]);
+bool sculpt_brush_test_sphere_sq(SculptBrushTest *test, const float co[3]);
+bool sculpt_brush_test_sphere_fast(const SculptBrushTest *test, const float co[3]);
+bool sculpt_brush_test_cube(SculptBrushTest *test, const float co[3], float local[4][4]);
+bool sculpt_brush_test_circle_sq(SculptBrushTest *test, const float co[3]);
+bool sculpt_search_sphere_cb(PBVHNode *node, void *data_v);
+bool sculpt_search_circle_cb(PBVHNode *node, void *data_v);
+
+SculptBrushTestFn sculpt_brush_test_init_with_falloff_shape(
+ SculptSession *ss, SculptBrushTest *test, char falloff_shape);
+const float *sculpt_brush_frontface_normal_from_falloff_shape(
+ SculptSession *ss, char falloff_shape);
+
+float tex_strength(
+ struct SculptSession *ss, const struct Brush *br,
+ const float point[3],
+ const float len,
+ const short vno[3],
+ const float fno[3],
+ const float mask,
+ const int thread_id);
+
+/* just for vertex paint. */
+void sculpt_pbvh_calc_area_normal(
+ const struct Brush *brush, Object *ob,
+ PBVHNode **nodes, int totnode,
+ bool use_threading,
+ float r_area_no[3]);
+
+/* Cache stroke properties. Used because
+ * RNA property lookup isn't particularly fast.
+ *
+ * For descriptions of these settings, check the operator properties.
+ */
+
+typedef struct StrokeCache {
+ /* Invariants */
+ float initial_radius;
+ float scale[3];
+ int flag;
+ float clip_tolerance[3];
+ float initial_mouse[2];
+
+ /* Variants */
+ float radius;
+ float radius_squared;
+ float true_location[3];
+ float true_last_location[3];
+ float location[3];
+ float last_location[3];
+ bool is_last_valid;
+
+ bool pen_flip;
+ bool invert;
+ float pressure;
+ float mouse[2];
+ float bstrength;
+ float normal_weight; /* from brush (with optional override) */
+
+ /* The rest is temporary storage that isn't saved as a property */
+
+ bool first_time; /* Beginning of stroke may do some things special */
+
+ /* from ED_view3d_ob_project_mat_get() */
+ float projection_mat[4][4];
+
+ /* Clean this up! */
+ struct ViewContext *vc;
+ const struct Brush *brush;
+
+ float special_rotation;
+ float grab_delta[3], grab_delta_symmetry[3];
+ float old_grab_location[3], orig_grab_location[3];
+
+ /* screen-space rotation defined by mouse motion */
+ float rake_rotation[4], rake_rotation_symmetry[4];
+ bool is_rake_rotation_valid;
+ struct SculptRakeData rake_data;
+
+ /* Symmetry index between 0 and 7 bit combo 0 is Brush only;
+ * 1 is X mirror; 2 is Y mirror; 3 is XY; 4 is Z; 5 is XZ; 6 is YZ; 7 is XYZ */
+ int symmetry;
+ int mirror_symmetry_pass; /* the symmetry pass we are currently on between 0 and 7*/
+ float true_view_normal[3];
+ float view_normal[3];
+
+ /* sculpt_normal gets calculated by calc_sculpt_normal(), then the
+ * sculpt_normal_symm gets updated quickly with the usual symmetry
+ * transforms */
+ float sculpt_normal[3];
+ float sculpt_normal_symm[3];
+
+ /* Used for area texture mode, local_mat gets calculated by
+ * calc_brush_local_mat() and used in tex_strength(). */
+ float brush_local_mat[4][4];
+
+ float plane_offset[3]; /* used to shift the plane around when doing tiled strokes */
+ int tile_pass;
+
+ float last_center[3];
+ int radial_symmetry_pass;
+ float symm_rot_mat[4][4];
+ float symm_rot_mat_inv[4][4];
+ bool original;
+ float anchored_location[3];
+
+ float vertex_rotation; /* amount to rotate the vertices when using rotate brush */
+ struct Dial *dial;
+
+ char saved_active_brush_name[MAX_ID_NAME];
+ char saved_mask_brush_tool;
+ int saved_smooth_size; /* smooth tool copies the size of the current tool */
+ bool alt_smooth;
+
+ float plane_trim_squared;
+
+ bool supports_gravity;
+ float true_gravity_direction[3];
+ float gravity_direction[3];
+
+ rcti previous_r; /* previous redraw rectangle */
+ rcti current_r; /* current redraw rectangle */
+
+} StrokeCache;
+
+void sculpt_cache_calc_brushdata_symm(
+ StrokeCache *cache, const char symm,
+ const char axis, const float angle);
+void sculpt_cache_free(StrokeCache *cache);
+
SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node, SculptUndoType type);
SculptUndoNode *sculpt_undo_get_node(PBVHNode *node);
void sculpt_undo_push_begin(const char *name);
-void sculpt_undo_push_end(const struct bContext *C);
+void sculpt_undo_push_end(void);
void sculpt_vertcos_to_key(Object *ob, KeyBlock *kb, float (*vertCos)[3]);
void sculpt_update_object_bounding_box(struct Object *ob);
+bool sculpt_get_redraw_rect(struct ARegion *ar, struct RegionView3D *rv3d, Object *ob, rcti *rect);
+
#define SCULPT_THREADED_LIMIT 4
#endif
diff --git a/source/blender/editors/sculpt_paint/sculpt_undo.c b/source/blender/editors/sculpt_paint/sculpt_undo.c
index 44bd872d107..e90d2b58c0c 100644
--- a/source/blender/editors/sculpt_paint/sculpt_undo.c
+++ b/source/blender/editors/sculpt_paint/sculpt_undo.c
@@ -48,6 +48,8 @@
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_mesh_types.h"
+#include "DNA_screen_types.h"
+#include "DNA_space_types.h"
#include "BKE_ccg.h"
#include "BKE_context.h"
@@ -57,6 +59,7 @@
#include "BKE_key.h"
#include "BKE_mesh.h"
#include "BKE_subsurf.h"
+#include "BKE_undo_system.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -64,12 +67,22 @@
#include "GPU_buffers.h"
#include "ED_paint.h"
+#include "ED_object.h"
+#include "ED_sculpt.h"
+#include "ED_undo.h"
#include "bmesh.h"
#include "paint_intern.h"
#include "sculpt_intern.h"
-/************************** Undo *************************/
+
+typedef struct UndoSculpt {
+ ListBase nodes;
+
+ size_t undo_size;
+} UndoSculpt;
+
+static UndoSculpt *sculpt_undo_get_nodes(void);
static void update_cb(PBVHNode *node, void *rebuild)
{
@@ -316,7 +329,10 @@ static bool sculpt_undo_restore_mask(bContext *C, DerivedMesh *dm, SculptUndoNod
return 1;
}
-static void sculpt_undo_bmesh_restore_generic_task_cb(void *userdata, const int n)
+static void sculpt_undo_bmesh_restore_generic_task_cb(
+ void *__restrict userdata,
+ const int n,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
PBVHNode **nodes = userdata;
@@ -344,9 +360,14 @@ static void sculpt_undo_bmesh_restore_generic(bContext *C,
BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT);
BLI_task_parallel_range(
- 0, totnode, nodes, sculpt_undo_bmesh_restore_generic_task_cb,
- ((sd->flags & SCULPT_USE_OPENMP) && totnode > SCULPT_THREADED_LIMIT));
+ 0, totnode,
+ nodes,
+ sculpt_undo_bmesh_restore_generic_task_cb,
+ &settings);
if (nodes)
MEM_freeN(nodes);
@@ -446,7 +467,7 @@ static int sculpt_undo_bmesh_restore(bContext *C,
return false;
}
-static void sculpt_undo_restore(bContext *C, ListBase *lb)
+static void sculpt_undo_restore_list(bContext *C, ListBase *lb)
{
Scene *scene = CTX_data_scene(C);
Sculpt *sd = CTX_data_tool_settings(C)->sculpt;
@@ -566,7 +587,7 @@ static void sculpt_undo_restore(bContext *C, ListBase *lb)
}
}
-static void sculpt_undo_free(ListBase *lb)
+static void sculpt_undo_free_list(ListBase *lb)
{
SculptUndoNode *unode;
int i;
@@ -609,6 +630,8 @@ static void sculpt_undo_free(ListBase *lb)
}
}
+/* Most likely we don't need this. */
+#if 0
static bool sculpt_undo_cleanup(bContext *C, ListBase *lb)
{
Object *ob = CTX_data_active_object(C);
@@ -625,16 +648,17 @@ static bool sculpt_undo_cleanup(bContext *C, ListBase *lb)
return false;
}
+#endif
SculptUndoNode *sculpt_undo_get_node(PBVHNode *node)
{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
+ UndoSculpt *usculpt = sculpt_undo_get_nodes();
- if (!lb) {
+ if (usculpt == NULL) {
return NULL;
}
- return BLI_findptr(lb, node, offsetof(SculptUndoNode, node));
+ return BLI_findptr(&usculpt->nodes, node, offsetof(SculptUndoNode, node));
}
static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
@@ -660,10 +684,11 @@ static void sculpt_undo_alloc_and_store_hidden(PBVH *pbvh,
}
}
-static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
- SculptUndoType type)
+static SculptUndoNode *sculpt_undo_alloc_node(
+ Object *ob, PBVHNode *node,
+ SculptUndoType type)
{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
+ UndoSculpt *usculpt = sculpt_undo_get_nodes();
SculptUndoNode *unode;
SculptSession *ss = ob->sculpt;
int totvert, allvert, totgrid, maxgrid, gridsize, *grids;
@@ -688,23 +713,23 @@ static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
/* general TODO, fix count_alloc */
switch (type) {
case SCULPT_UNDO_COORDS:
- unode->co = MEM_mapallocN(sizeof(float) * 3 * allvert, "SculptUndoNode.co");
- unode->no = MEM_mapallocN(sizeof(short) * 3 * allvert, "SculptUndoNode.no");
- undo_paint_push_count_alloc(UNDO_PAINT_MESH,
- (sizeof(float) * 3 +
- sizeof(short) * 3 +
- sizeof(int)) * allvert);
+ unode->co = MEM_mapallocN(sizeof(float[3]) * allvert, "SculptUndoNode.co");
+ unode->no = MEM_mapallocN(sizeof(short[3]) * allvert, "SculptUndoNode.no");
+
+ usculpt->undo_size = (sizeof(float[3]) + sizeof(short[3]) + sizeof(int)) * allvert;
break;
case SCULPT_UNDO_HIDDEN:
if (maxgrid)
sculpt_undo_alloc_and_store_hidden(ss->pbvh, unode);
else
unode->vert_hidden = BLI_BITMAP_NEW(allvert, "SculptUndoNode.vert_hidden");
-
+
break;
case SCULPT_UNDO_MASK:
unode->mask = MEM_mapallocN(sizeof(float) * allvert, "SculptUndoNode.mask");
- undo_paint_push_count_alloc(UNDO_PAINT_MESH, (sizeof(float) * sizeof(int)) * allvert);
+
+ usculpt->undo_size += (sizeof(float) * sizeof(int)) * allvert;
+
break;
case SCULPT_UNDO_DYNTOPO_BEGIN:
case SCULPT_UNDO_DYNTOPO_END:
@@ -713,7 +738,7 @@ static SculptUndoNode *sculpt_undo_alloc_node(Object *ob, PBVHNode *node,
break;
}
- BLI_addtail(lb, unode);
+ BLI_addtail(&usculpt->nodes, unode);
if (maxgrid) {
/* multires */
@@ -790,12 +815,13 @@ static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
PBVHNode *node,
SculptUndoType type)
{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
- SculptUndoNode *unode = lb->first;
+ UndoSculpt *usculpt = sculpt_undo_get_nodes();
SculptSession *ss = ob->sculpt;
PBVHVertexIter vd;
- if (!lb->first) {
+ SculptUndoNode *unode = usculpt->nodes.first;
+
+ if (unode == NULL) {
unode = MEM_callocN(sizeof(*unode), __func__);
BLI_strncpy(unode->idname, ob->id.name, sizeof(unode->idname));
@@ -834,7 +860,7 @@ static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
unode->bm_entry = BM_log_entry_add(ss->bm_log);
}
- BLI_addtail(lb, unode);
+ BLI_addtail(&usculpt->nodes, unode);
}
if (node) {
@@ -875,14 +901,15 @@ static SculptUndoNode *sculpt_undo_bmesh_push(Object *ob,
return unode;
}
-SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
- SculptUndoType type)
+SculptUndoNode *sculpt_undo_push_node(
+ Object *ob, PBVHNode *node,
+ SculptUndoType type)
{
SculptSession *ss = ob->sculpt;
SculptUndoNode *unode;
/* list is manipulated by multiple threads, so we lock */
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
if (ss->bm ||
ELEM(type,
@@ -892,17 +919,17 @@ SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
/* Dynamic topology stores only one undo node per stroke,
* regardless of the number of PBVH nodes modified */
unode = sculpt_undo_bmesh_push(ob, node, type);
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return unode;
}
else if ((unode = sculpt_undo_get_node(node))) {
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return unode;
}
unode = sculpt_undo_alloc_node(ob, node, type);
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
/* copy threaded, hopefully this is the performance critical part */
@@ -946,17 +973,18 @@ SculptUndoNode *sculpt_undo_push_node(Object *ob, PBVHNode *node,
void sculpt_undo_push_begin(const char *name)
{
- ED_undo_paint_push_begin(UNDO_PAINT_MESH, name,
- sculpt_undo_restore, sculpt_undo_free, sculpt_undo_cleanup);
+ UndoStack *ustack = ED_undo_stack_get();
+ bContext *C = NULL; /* special case, we never read from this. */
+ BKE_undosys_step_push_init_with_type(ustack, C, name, BKE_UNDOSYS_TYPE_SCULPT);
}
-void sculpt_undo_push_end(const bContext *C)
+void sculpt_undo_push_end(void)
{
- ListBase *lb = undo_paint_push_get_list(UNDO_PAINT_MESH);
+ UndoSculpt *usculpt = sculpt_undo_get_nodes();
SculptUndoNode *unode;
/* we don't need normals in the undo stack */
- for (unode = lb->first; unode; unode = unode->next) {
+ for (unode = usculpt->nodes.first; unode; unode = unode->next) {
if (unode->no) {
MEM_freeN(unode->no);
unode->no = NULL;
@@ -966,7 +994,97 @@ void sculpt_undo_push_end(const bContext *C)
BKE_pbvh_node_layer_disp_free(unode->node);
}
- ED_undo_paint_push_end(UNDO_PAINT_MESH);
+ UndoStack *ustack = ED_undo_stack_get();
+ BKE_undosys_step_push(ustack, NULL, NULL);
+}
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct SculptUndoStep {
+ UndoStep step;
+ /* note: will split out into list for multi-object-sculpt-mode. */
+ UndoSculpt data;
+} SculptUndoStep;
+
+static bool sculpt_undosys_poll(bContext *C)
+{
+ ScrArea *sa = CTX_wm_area(C);
+ if (sa && (sa->spacetype == SPACE_VIEW3D)) {
+ Object *obact = CTX_data_active_object(C);
+ if (obact && (obact->mode & OB_MODE_SCULPT)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static void sculpt_undosys_step_encode_init(struct bContext *UNUSED(C), UndoStep *us_p)
+{
+ SculptUndoStep *us = (SculptUndoStep *)us_p;
+ /* dummy, memory is cleared anyway. */
+ BLI_listbase_clear(&us->data.nodes);
+}
+
+static bool sculpt_undosys_step_encode(struct bContext *UNUSED(C), UndoStep *us_p)
+{
+ /* dummy, encoding is done along the way by adding tiles
+ * to the current 'SculptUndoStep' added by encode_init. */
+ SculptUndoStep *us = (SculptUndoStep *)us_p;
+ us->step.data_size = us->data.undo_size;
+ return true;
+}
+
+static void sculpt_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* TODO(campbell): undo_system: use low-level API to set mode. */
+ ED_object_mode_set(C, OB_MODE_SCULPT);
+ BLI_assert(sculpt_undosys_poll(C));
+
+ SculptUndoStep *us = (SculptUndoStep *)us_p;
+ sculpt_undo_restore_list(C, &us->data.nodes);
+}
- WM_file_tag_modified(C);
+static void sculpt_undosys_step_free(UndoStep *us_p)
+{
+ SculptUndoStep *us = (SculptUndoStep *)us_p;
+ sculpt_undo_free_list(&us->data.nodes);
}
+
+/* Export for ED_undo_sys. */
+void ED_sculpt_undosys_type(UndoType *ut)
+{
+ ut->name = "Sculpt";
+ ut->poll = sculpt_undosys_poll;
+ ut->step_encode_init = sculpt_undosys_step_encode_init;
+ ut->step_encode = sculpt_undosys_step_encode;
+ ut->step_decode = sculpt_undosys_step_decode;
+ ut->step_free = sculpt_undosys_step_free;
+
+ ut->mode = BKE_UNDOTYPE_MODE_ACCUMULATE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(SculptUndoStep);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+static UndoSculpt *sculpt_undosys_step_get_nodes(UndoStep *us_p)
+{
+ SculptUndoStep *us = (SculptUndoStep *)us_p;
+ return &us->data;
+}
+
+static UndoSculpt *sculpt_undo_get_nodes(void)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ UndoStep *us = BKE_undosys_stack_init_or_active_with_type(ustack, BKE_UNDOSYS_TYPE_SCULPT);
+ return sculpt_undosys_step_get_nodes(us);
+}
+
+/** \} */
diff --git a/source/blender/editors/sculpt_paint/sculpt_uv.c b/source/blender/editors/sculpt_paint/sculpt_uv.c
index fd2a0b15cb9..e39750227c0 100644
--- a/source/blender/editors/sculpt_paint/sculpt_uv.c
+++ b/source/blender/editors/sculpt_paint/sculpt_uv.c
@@ -173,7 +173,7 @@ static int uv_sculpt_brush_poll_do(bContext *C, const bool check_region)
}
em = BKE_editmesh_from_object(obedit);
- ret = EDBM_mtexpoly_check(em);
+ ret = EDBM_uv_check(em);
if (ret) {
ARegion *ar = CTX_wm_region(C);
@@ -650,9 +650,9 @@ static UvSculptData *uv_sculpt_stroke_init(bContext *C, wmOperator *op, const wm
/* we need to find the active island here */
if (do_island_optimization) {
UvElement *element;
- NearestHit hit;
+ UvNearestHit hit = UV_NEAREST_HIT_INIT;
Image *ima = CTX_data_edit_image(C);
- uv_find_nearest_vert(scene, ima, em, co, NULL, &hit);
+ uv_find_nearest_vert(scene, ima, em, co, 0.0f, &hit);
element = BM_uv_element_get(data->elementMap, hit.efa, hit.l);
island_index = element->island;
@@ -759,7 +759,7 @@ static UvSculptData *uv_sculpt_stroke_init(bContext *C, wmOperator *op, const wm
MEM_freeN(uniqueUv);
/* Allocate connectivity data, we allocate edges once */
- data->uvedges = MEM_mallocN(sizeof(*data->uvedges) * BLI_ghash_size(edgeHash), "uv_brush_edge_connectivity_data");
+ data->uvedges = MEM_mallocN(sizeof(*data->uvedges) * BLI_ghash_len(edgeHash), "uv_brush_edge_connectivity_data");
if (!data->uvedges) {
BLI_ghash_free(edgeHash, NULL, NULL);
MEM_freeN(edges);
@@ -772,7 +772,7 @@ static UvSculptData *uv_sculpt_stroke_init(bContext *C, wmOperator *op, const wm
GHASH_ITER (gh_iter, edgeHash) {
data->uvedges[i++] = *((UvEdge *)BLI_ghashIterator_getKey(&gh_iter));
}
- data->totalUvEdges = BLI_ghash_size(edgeHash);
+ data->totalUvEdges = BLI_ghash_len(edgeHash);
/* cleanup temporary stuff */
BLI_ghash_free(edgeHash, NULL, NULL);
@@ -905,7 +905,7 @@ static int uv_sculpt_stroke_modal(bContext *C, wmOperator *op, const wmEvent *ev
void SCULPT_OT_uv_sculpt_stroke(wmOperatorType *ot)
{
- static EnumPropertyItem stroke_mode_items[] = {
+ static const EnumPropertyItem stroke_mode_items[] = {
{BRUSH_STROKE_NORMAL, "NORMAL", 0, "Normal", "Apply brush normally"},
{BRUSH_STROKE_INVERT, "INVERT", 0, "Invert", "Invert action of brush for duration of stroke"},
{BRUSH_STROKE_SMOOTH, "RELAX", 0, "Relax", "Switch brush to relax mode for duration of stroke"},
diff --git a/source/blender/editors/sound/sound_ops.c b/source/blender/editors/sound/sound_ops.c
index c2c52f58181..0c349e6433e 100644
--- a/source/blender/editors/sound/sound_ops.c
+++ b/source/blender/editors/sound/sound_ops.c
@@ -397,7 +397,7 @@ static int sound_mixdown_exec(bContext *C, wmOperator *op)
}
#ifdef WITH_AUDASPACE
-static EnumPropertyItem container_items[] = {
+static const EnumPropertyItem container_items[] = {
#ifdef WITH_FFMPEG
{AUD_CONTAINER_AC3, "AC3", 0, "ac3", "Dolby Digital ATRAC 3"},
#endif
@@ -429,7 +429,7 @@ static bool sound_mixdown_check(bContext *UNUSED(C), wmOperator *op)
const char *extension = NULL;
- EnumPropertyItem *item = container_items;
+ const EnumPropertyItem *item = container_items;
while (item->identifier != NULL) {
if (item->value == container) {
const char **ext = snd_ext_sound;
@@ -491,7 +491,7 @@ static bool sound_mixdown_draw_check_prop(PointerRNA *UNUSED(ptr), PropertyRNA *
static void sound_mixdown_draw(bContext *C, wmOperator *op)
{
- static EnumPropertyItem pcm_format_items[] = {
+ static const EnumPropertyItem pcm_format_items[] = {
{AUD_FORMAT_U8, "U8", 0, "U8", "8 bit unsigned"},
{AUD_FORMAT_S16, "S16", 0, "S16", "16 bit signed"},
#ifdef WITH_SNDFILE
@@ -503,21 +503,21 @@ static void sound_mixdown_draw(bContext *C, wmOperator *op)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem mp3_format_items[] = {
+ static const EnumPropertyItem mp3_format_items[] = {
{AUD_FORMAT_S16, "S16", 0, "S16", "16 bit signed"},
{AUD_FORMAT_S32, "S32", 0, "S32", "32 bit signed"},
{0, NULL, 0, NULL, NULL}
};
#ifdef WITH_SNDFILE
- static EnumPropertyItem flac_format_items[] = {
+ static const EnumPropertyItem flac_format_items[] = {
{AUD_FORMAT_S16, "S16", 0, "S16", "16 bit signed"},
{AUD_FORMAT_S24, "S24", 0, "S24", "24 bit signed"},
{0, NULL, 0, NULL, NULL}
};
#endif
- static EnumPropertyItem all_codec_items[] = {
+ static const EnumPropertyItem all_codec_items[] = {
{AUD_CODEC_AAC, "AAC", 0, "AAC", "Advanced Audio Coding"},
{AUD_CODEC_AC3, "AC3", 0, "AC3", "Dolby Digital ATRAC 3"},
{AUD_CODEC_FLAC, "FLAC", 0, "FLAC", "Free Lossless Audio Codec"},
@@ -528,7 +528,7 @@ static void sound_mixdown_draw(bContext *C, wmOperator *op)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ogg_codec_items[] = {
+ static const EnumPropertyItem ogg_codec_items[] = {
{AUD_CODEC_FLAC, "FLAC", 0, "FLAC", "Free Lossless Audio Codec"},
{AUD_CODEC_VORBIS, "VORBIS", 0, "Vorbis", "Xiph.Org Vorbis Codec"},
{0, NULL, 0, NULL, NULL}
@@ -641,7 +641,7 @@ static void sound_mixdown_draw(bContext *C, wmOperator *op)
static void SOUND_OT_mixdown(wmOperatorType *ot)
{
#ifdef WITH_AUDASPACE
- static EnumPropertyItem format_items[] = {
+ static const EnumPropertyItem format_items[] = {
{AUD_FORMAT_U8, "U8", 0, "U8", "8 bit unsigned"},
{AUD_FORMAT_S16, "S16", 0, "S16", "16 bit signed"},
{AUD_FORMAT_S24, "S24", 0, "S24", "24 bit signed"},
@@ -651,7 +651,7 @@ static void SOUND_OT_mixdown(wmOperatorType *ot)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem codec_items[] = {
+ static const EnumPropertyItem codec_items[] = {
#ifdef WITH_FFMPEG
{AUD_CODEC_AAC, "AAC", 0, "AAC", "Advanced Audio Coding"},
{AUD_CODEC_AC3, "AC3", 0, "AC3", "Dolby Digital ATRAC 3"},
@@ -670,7 +670,7 @@ static void SOUND_OT_mixdown(wmOperatorType *ot)
/* identifiers */
ot->name = "Mixdown";
- ot->description = "Mixes the scene's audio to a sound file";
+ ot->description = "Mix the scene's audio to a sound file";
ot->idname = "SOUND_OT_mixdown";
/* api callbacks */
diff --git a/source/blender/editors/space_action/action_buttons.c b/source/blender/editors/space_action/action_buttons.c
index bfc808f6d83..ba6cef38acd 100644
--- a/source/blender/editors/space_action/action_buttons.c
+++ b/source/blender/editors/space_action/action_buttons.c
@@ -50,8 +50,6 @@
#include "BKE_curve.h"
#include "BKE_depsgraph.h"
#include "BKE_fcurve.h"
-#include "BKE_main.h"
-#include "BKE_global.h"
#include "BKE_screen.h"
#include "BKE_unit.h"
diff --git a/source/blender/editors/space_action/action_data.c b/source/blender/editors/space_action/action_data.c
index fdf2dfe8371..f1153b5bed0 100644
--- a/source/blender/editors/space_action/action_data.c
+++ b/source/blender/editors/space_action/action_data.c
@@ -54,10 +54,8 @@
#include "BKE_animsys.h"
#include "BKE_action.h"
#include "BKE_fcurve.h"
-#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_key.h"
-#include "BKE_main.h"
#include "BKE_nla.h"
#include "BKE_scene.h"
#include "BKE_context.h"
@@ -125,7 +123,7 @@ static bAction *action_create_new(bContext *C, bAction *oldact)
}
else {
/* just make a new (empty) action */
- action = add_empty_action(CTX_data_main(C), "Action");
+ action = BKE_action_add(CTX_data_main(C), "Action");
}
/* when creating new ID blocks, there is already 1 user (as for all new datablocks),
@@ -568,11 +566,11 @@ void ED_animedit_unlink_action(bContext *C, ID *id, AnimData *adt, bAction *act,
if (strip->act == act) {
/* Remove this strip, and the track too if it doesn't have anything else */
- free_nlastrip(&nlt->strips, strip);
+ BKE_nlastrip_free(&nlt->strips, strip);
if (nlt->strips.first == NULL) {
BLI_assert(nstrip == NULL);
- free_nlatrack(&adt->nla_tracks, nlt);
+ BKE_nlatrack_free(&adt->nla_tracks, nlt);
}
}
}
diff --git a/source/blender/editors/space_action/action_edit.c b/source/blender/editors/space_action/action_edit.c
index f8db35e2311..1c15a7c5950 100644
--- a/source/blender/editors/space_action/action_edit.c
+++ b/source/blender/editors/space_action/action_edit.c
@@ -59,7 +59,6 @@
#include "BKE_global.h"
#include "BKE_library.h"
#include "BKE_key.h"
-#include "BKE_main.h"
#include "BKE_nla.h"
#include "BKE_context.h"
#include "BKE_report.h"
@@ -660,7 +659,7 @@ void ACTION_OT_paste(wmOperatorType *ot)
/* ******************** Insert Keyframes Operator ************************* */
/* defines for insert keyframes tool */
-static EnumPropertyItem prop_actkeys_insertkey_types[] = {
+static const EnumPropertyItem prop_actkeys_insertkey_types[] = {
{1, "ALL", 0, "All Channels", ""},
{2, "SEL", 0, "Only Selected Channels", ""},
{3, "GROUP", 0, "In Active Group", ""}, /* XXX not in all cases */
@@ -1110,7 +1109,7 @@ void ACTION_OT_sample(wmOperatorType *ot)
#define CLEAR_CYCLIC_EXPO -2
/* defines for set extrapolation-type for selected keyframes tool */
-static EnumPropertyItem prop_actkeys_expo_types[] = {
+static const EnumPropertyItem prop_actkeys_expo_types[] = {
{FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", "Values on endpoint keyframes are held"},
{FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", "Straight-line slope of end segments are extended past the endpoint keyframes"},
@@ -1146,7 +1145,7 @@ static void setexpo_action_keys(bAnimContext *ac, short mode)
/* only add if one doesn't exist */
if (list_has_suitable_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, -1) == 0) {
/* TODO: add some more preset versions which set different extrapolation options? */
- add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES);
+ add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, fcu);
}
}
else if (mode == CLEAR_CYCLIC_EXPO) {
@@ -1522,7 +1521,7 @@ static int actkeys_framejump_exec(bContext *C, wmOperator *UNUSED(op))
/* set the new current frame value, based on the average time */
if (ked.i1) {
Scene *scene = ac.scene;
- CFRA = iroundf(ked.f1 / ked.i1);
+ CFRA = round_fl_to_int(ked.f1 / ked.i1);
SUBFRA = 0.f;
}
@@ -1550,7 +1549,7 @@ void ACTION_OT_frame_jump(wmOperatorType *ot)
/* ******************** Snap Keyframes Operator *********************** */
/* defines for snap keyframes tool */
-static EnumPropertyItem prop_actkeys_snap_types[] = {
+static const EnumPropertyItem prop_actkeys_snap_types[] = {
{ACTKEYS_SNAP_CFRA, "CFRA", 0, "Current frame",
"Snap selected keyframes to the current frame"},
{ACTKEYS_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame",
@@ -1659,7 +1658,7 @@ void ACTION_OT_snap(wmOperatorType *ot)
/* ******************** Mirror Keyframes Operator *********************** */
/* defines for mirror keyframes tool */
-static EnumPropertyItem prop_actkeys_mirror_types[] = {
+static const EnumPropertyItem prop_actkeys_mirror_types[] = {
{ACTKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current frame",
"Flip times of selected keyframes using the current frame as the mirror line"},
{ACTKEYS_MIRROR_XAXIS, "XAXIS", 0, "By Values over Value=0",
diff --git a/source/blender/editors/space_action/action_select.c b/source/blender/editors/space_action/action_select.c
index 553be0ad290..2b974ac73d7 100644
--- a/source/blender/editors/space_action/action_select.c
+++ b/source/blender/editors/space_action/action_select.c
@@ -36,7 +36,7 @@
#include "BLI_blenlib.h"
#include "BLI_dlrbTree.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_utildefines.h"
#include "DNA_anim_types.h"
@@ -220,7 +220,7 @@ static void borderselect_action(bAnimContext *ac, const rcti rect, short mode, s
UI_view2d_region_to_view(v2d, rect.xmax, rect.ymax - 2, &rectf.xmax, &rectf.ymax);
/* filter data */
- filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_LIST_CHANNELS | ANIMFILTER_NODUPLIS);
+ filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_LIST_CHANNELS);
ANIM_animdata_filter(ac, &anim_data, filter, ac->data, ac->datatype);
/* get beztriple editing/validation funcs */
@@ -262,6 +262,7 @@ static void borderselect_action(bAnimContext *ac, const rcti rect, short mode, s
{
/* loop over data selecting */
switch (ale->type) {
+#if 0 /* XXX: Keyframes are not currently shown here */
case ANIMTYPE_GPDATABLOCK:
{
bGPdata *gpd = ale->data;
@@ -271,6 +272,7 @@ static void borderselect_action(bAnimContext *ac, const rcti rect, short mode, s
}
break;
}
+#endif
case ANIMTYPE_GPLAYER:
ED_gplayer_frames_select_border(ale->data, rectf.xmin, rectf.xmax, selectmode);
break;
@@ -307,26 +309,27 @@ static int actkeys_borderselect_exec(bContext *C, wmOperator *op)
bAnimContext ac;
rcti rect;
short mode = 0, selectmode = 0;
- int gesture_mode;
- bool extend;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* get editor data */
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
/* clear all selection if not extending selection */
- extend = RNA_boolean_get(op->ptr, "extend");
- if (!extend)
+ if (!extend) {
deselect_action_keys(&ac, 1, SELECT_SUBTRACT);
+ }
/* get settings from operator */
WM_operator_properties_border_to_rcti(op, &rect);
-
- gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- if (gesture_mode == GESTURE_MODAL_SELECT)
+
+ if (select) {
selectmode = SELECT_ADD;
- else
+ }
+ else {
selectmode = SELECT_SUBTRACT;
+ }
/* selection 'mode' depends on whether borderselect region only matters on one axis */
if (RNA_boolean_get(op->ptr, "axis_range")) {
@@ -360,10 +363,10 @@ void ACTION_OT_select_border(wmOperatorType *ot)
ot->description = "Select all keyframes within the specified region";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = actkeys_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_action_active;
@@ -371,7 +374,7 @@ void ACTION_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
ot->prop = RNA_def_boolean(ot->srna, "axis_range", 0, "Axis Range", "");
}
@@ -398,7 +401,7 @@ static void region_select_action_keys(bAnimContext *ac, const rctf *rectf_view,
UI_view2d_region_to_view_rctf(v2d, rectf_view, &rectf);
/* filter data */
- filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_LIST_CHANNELS | ANIMFILTER_NODUPLIS);
+ filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_LIST_VISIBLE | ANIMFILTER_LIST_CHANNELS);
ANIM_animdata_filter(ac, &anim_data, filter, ac->data, ac->datatype);
/* get beztriple editing/validation funcs */
@@ -463,6 +466,7 @@ static void region_select_action_keys(bAnimContext *ac, const rctf *rectf_view,
{
/* loop over data selecting */
switch (ale->type) {
+#if 0 /* XXX: Keyframes are not currently shown here */
case ANIMTYPE_GPDATABLOCK:
{
bGPdata *gpd = ale->data;
@@ -472,6 +476,7 @@ static void region_select_action_keys(bAnimContext *ac, const rctf *rectf_view,
}
break;
}
+#endif
case ANIMTYPE_GPLAYER:
{
ED_gplayer_frames_select_region(&ked, ale->data, mode, selectmode);
@@ -570,9 +575,7 @@ void ACTION_OT_select_lasso(wmOperatorType *ot)
ot->flag = OPTYPE_UNDO;
/* properties */
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend selection instead of deselecting everything first");
+ WM_operator_properties_gesture_lasso_select(ot);
}
/* ------------------- */
@@ -580,8 +583,8 @@ void ACTION_OT_select_lasso(wmOperatorType *ot)
static int action_circle_select_exec(bContext *C, wmOperator *op)
{
bAnimContext ac;
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const short selectmode = (gesture_mode == GESTURE_MODAL_SELECT) ? SELECT_ADD : SELECT_SUBTRACT;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const short selectmode = select ? SELECT_ADD : SELECT_SUBTRACT;
KeyframeEdit_CircleData data = {0};
rctf rect_fl;
@@ -627,11 +630,9 @@ void ACTION_OT_select_circle(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
-
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Event Type", "", INT_MIN, INT_MAX);
+
+ /* properties */
+ WM_operator_properties_gesture_circle_select(ot);
}
/* ******************** Column Select Operator **************************** */
@@ -643,7 +644,7 @@ void ACTION_OT_select_circle(wmOperatorType *ot)
*/
/* defines for column-select mode */
-static EnumPropertyItem prop_column_select_types[] = {
+static const EnumPropertyItem prop_column_select_types[] = {
{ACTKEYS_COLUMNSEL_KEYS, "KEYS", 0, "On Selected Keyframes", ""},
{ACTKEYS_COLUMNSEL_CFRA, "CFRA", 0, "On Current Frame", ""},
{ACTKEYS_COLUMNSEL_MARKERS_COLUMN, "MARKERS_COLUMN", 0, "On Selected Markers", ""},
@@ -719,8 +720,6 @@ static void columnselect_action_keys(bAnimContext *ac, short mode)
KeyframeEditFunc select_cb, ok_cb;
KeyframeEditData ked = {{NULL}};
- /* initialize keyframe editing data */
-
/* build list of columns */
switch (mode) {
case ACTKEYS_COLUMNSEL_KEYS: /* list of selected keys */
@@ -1011,7 +1010,7 @@ void ACTION_OT_select_less(wmOperatorType *ot)
/* Select keyframes left/right of the current frame indicator */
/* defines for left-right select tool */
-static EnumPropertyItem prop_actkeys_leftright_select_types[] = {
+static const EnumPropertyItem prop_actkeys_leftright_select_types[] = {
{ACTKEYS_LRSEL_TEST, "CHECK", 0, "Check if Select Left or Right", ""},
{ACTKEYS_LRSEL_LEFT, "LEFT", 0, "Before current frame", ""},
{ACTKEYS_LRSEL_RIGHT, "RIGHT", 0, "After current frame", ""},
@@ -1128,7 +1127,8 @@ static int actkeys_select_leftright_exec(bContext *C, wmOperator *op)
actkeys_select_leftright(&ac, leftright, selectmode);
/* set notifier that keyframe selection (and channels too) have changed */
- WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | ND_ANIMCHAN | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
return OPERATOR_FINISHED;
}
@@ -1578,7 +1578,8 @@ static int actkeys_clickselect_invoke(bContext *C, wmOperator *op, const wmEvent
mouse_action_keys(&ac, event->mval, selectmode, column, channel);
/* set notifier that keyframe selection (and channels too) have changed */
- WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | ND_ANIMCHAN | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
/* for tweak grab to work */
return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
diff --git a/source/blender/editors/space_action/space_action.c b/source/blender/editors/space_action/space_action.c
index 83655a2ba9e..5cde224b7dc 100644
--- a/source/blender/editors/space_action/space_action.c
+++ b/source/blender/editors/space_action/space_action.c
@@ -624,13 +624,17 @@ static void action_id_remap(ScrArea *UNUSED(sa), SpaceLink *slink, ID *old_id, I
{
SpaceAction *sact = (SpaceAction *)slink;
- if (!ELEM(GS(old_id->name), ID_GR)) {
- return;
+ if ((ID *)sact->action == old_id) {
+ sact->action = (bAction *)new_id;
}
if ((ID *)sact->ads.filter_grp == old_id) {
sact->ads.filter_grp = (Group *)new_id;
}
+ if ((ID *)sact->ads.source == old_id) {
+ sact->ads.source = new_id;
+ }
+
}
/* only called once, from space/spacetypes.c */
diff --git a/source/blender/editors/space_api/spacetypes.c b/source/blender/editors/space_api/spacetypes.c
index ac6e3123e4e..9247cdb1ae7 100644
--- a/source/blender/editors/space_api/spacetypes.c
+++ b/source/blender/editors/space_api/spacetypes.c
@@ -60,6 +60,7 @@
#include "ED_space_api.h"
#include "ED_sound.h"
#include "ED_uvedit.h"
+#include "ED_lattice.h"
#include "ED_mball.h"
#include "ED_logic.h"
#include "ED_clip.h"
@@ -104,6 +105,7 @@ void ED_spacetypes_init(void)
ED_operatortypes_animchannels();
ED_operatortypes_gpencil();
ED_operatortypes_object();
+ ED_operatortypes_lattice();
ED_operatortypes_mesh();
ED_operatortypes_sculpt();
ED_operatortypes_uvedit();
@@ -176,7 +178,8 @@ void ED_spacetypes_keymap(wmKeyConfig *keyconf)
ED_keymap_anim(keyconf);
ED_keymap_animchannels(keyconf);
ED_keymap_gpencil(keyconf);
- ED_keymap_object(keyconf); /* defines lattice also */
+ ED_keymap_object(keyconf);
+ ED_keymap_lattice(keyconf);
ED_keymap_mesh(keyconf);
ED_keymap_uvedit(keyconf);
ED_keymap_curve(keyconf);
diff --git a/source/blender/editors/space_buttons/buttons_ops.c b/source/blender/editors/space_buttons/buttons_ops.c
index fc1b6877f5e..2a703ebb46c 100644
--- a/source/blender/editors/space_buttons/buttons_ops.c
+++ b/source/blender/editors/space_buttons/buttons_ops.c
@@ -51,7 +51,7 @@
#include "WM_types.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "RNA_access.h"
diff --git a/source/blender/editors/space_buttons/buttons_texture.c b/source/blender/editors/space_buttons/buttons_texture.c
index 72de7e5c81c..49bd0794a51 100644
--- a/source/blender/editors/space_buttons/buttons_texture.c
+++ b/source/blender/editors/space_buttons/buttons_texture.c
@@ -45,7 +45,7 @@
#include "DNA_material_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_screen_types.h"
@@ -350,7 +350,7 @@ static void buttons_texture_users_from_context(ListBase *users, const bContext *
if (!scene)
scene = CTX_data_scene(C);
- if (!(pinid || pinid == &scene->id)) {
+ if (!pinid || GS(pinid->name) == ID_SCE) {
ob = (scene->basact) ? scene->basact->object : NULL;
wrld = scene->world;
brush = BKE_paint_brush(BKE_paint_get_active_from_context(C));
@@ -470,7 +470,7 @@ void buttons_texture_context_compute(const bContext *C, SpaceButs *sbuts)
}
else {
/* set one user as active based on active index */
- if (ct->index == BLI_listbase_count_ex(&ct->users, ct->index + 1))
+ if (ct->index >= BLI_listbase_count_at_most(&ct->users, ct->index + 1))
ct->index = 0;
ct->user = BLI_findlink(&ct->users, ct->index);
diff --git a/source/blender/editors/space_clip/clip_buttons.c b/source/blender/editors/space_clip/clip_buttons.c
index 0378c68d12c..ec8e4a881e1 100644
--- a/source/blender/editors/space_clip/clip_buttons.c
+++ b/source/blender/editors/space_clip/clip_buttons.c
@@ -106,7 +106,7 @@ void uiTemplateMovieClip(uiLayout *layout, bContext *C, PointerRNA *ptr, const c
uiLayoutSetContextPointer(layout, "edit_movieclip", &clipptr);
if (!compact)
- uiTemplateID(layout, C, ptr, propname, NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, propname, NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (clip) {
uiLayout *col;
diff --git a/source/blender/editors/space_clip/clip_draw.c b/source/blender/editors/space_clip/clip_draw.c
index 695d04d3850..a71b2baa96f 100644
--- a/source/blender/editors/space_clip/clip_draw.c
+++ b/source/blender/editors/space_clip/clip_draw.c
@@ -365,9 +365,11 @@ static void draw_stabilization_border(SpaceClip *sc, ARegion *ar, int width, int
static void draw_track_path(SpaceClip *sc, MovieClip *UNUSED(clip), MovieTrackingTrack *track)
{
+#define MAX_STATIC_PATH 64
int count = sc->path_length;
int i, a, b, curindex = -1;
- float path[102][2];
+ float path_static[(MAX_STATIC_PATH + 1) * 2][2];
+ float (*path)[2];
int tiny = sc->flag & SC_SHOW_TINY_MARKER, framenr, start_frame;
MovieTrackingMarker *marker;
@@ -380,6 +382,13 @@ static void draw_track_path(SpaceClip *sc, MovieClip *UNUSED(clip), MovieTrackin
if (marker->framenr != framenr || marker->flag & MARKER_DISABLED)
return;
+ if (count < MAX_STATIC_PATH) {
+ path = path_static;
+ }
+ else {
+ path = MEM_mallocN(sizeof(*path) * (count + 1) * 2, "path");
+ }
+
a = count;
i = framenr - 1;
while (i >= framenr - count) {
@@ -470,6 +479,11 @@ static void draw_track_path(SpaceClip *sc, MovieClip *UNUSED(clip), MovieTrackin
glVertex2f(path[i][0], path[i][1]);
}
glEnd();
+
+ if (path != path_static) {
+ MEM_freeN(path);
+ }
+#undef MAX_STATIC_PATH
}
static void draw_marker_outline(SpaceClip *sc, MovieTrackingTrack *track, MovieTrackingMarker *marker,
diff --git a/source/blender/editors/space_clip/clip_editor.c b/source/blender/editors/space_clip/clip_editor.c
index 14d0f909d23..59dd755173f 100644
--- a/source/blender/editors/space_clip/clip_editor.c
+++ b/source/blender/editors/space_clip/clip_editor.c
@@ -259,11 +259,9 @@ ImBuf *ED_space_clip_get_stable_buffer(SpaceClip *sc, float loc[2], float *scale
return NULL;
}
-/* Returns color in the display space, matching ED_space_image_color_sample(). */
-bool ED_space_clip_color_sample(Scene *scene, SpaceClip *sc, ARegion *ar, int mval[2], float r_col[3])
+/* Returns color in linear space, matching ED_space_image_color_sample(). */
+bool ED_space_clip_color_sample(SpaceClip *sc, ARegion *ar, int mval[2], float r_col[3])
{
- const char *display_device = scene->display_settings.display_device;
- struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
ImBuf *ibuf;
float fx, fy, co[2];
bool ret = false;
@@ -299,11 +297,7 @@ bool ED_space_clip_color_sample(Scene *scene, SpaceClip *sc, ARegion *ar, int mv
ret = true;
}
}
-
- if (ret) {
- IMB_colormanagement_scene_linear_to_display_v3(r_col, display);
- }
-
+
IMB_freeImBuf(ibuf);
return ret;
diff --git a/source/blender/editors/space_clip/clip_graph_ops.c b/source/blender/editors/space_clip/clip_graph_ops.c
index e781d199d35..9ad4fd4642a 100644
--- a/source/blender/editors/space_clip/clip_graph_ops.c
+++ b/source/blender/editors/space_clip/clip_graph_ops.c
@@ -331,8 +331,7 @@ void CLIP_OT_graph_select(wmOperatorType *ot)
typedef struct BorderSelectuserData {
rctf rect;
- int mode;
- bool changed, extend;
+ bool select, extend, changed;
} BorderSelectuserData;
static void border_select_cb(void *userdata, MovieTrackingTrack *UNUSED(track),
@@ -348,11 +347,12 @@ static void border_select_cb(void *userdata, MovieTrackingTrack *UNUSED(track),
else
flag = MARKER_GRAPH_SEL_Y;
- if (data->mode == GESTURE_MODAL_SELECT)
+ if (data->select) {
marker->flag |= flag;
- else
+ }
+ else {
marker->flag &= ~flag;
-
+ }
data->changed = true;
}
else if (!data->extend) {
@@ -380,7 +380,7 @@ static int border_select_graph_exec(bContext *C, wmOperator *op)
UI_view2d_region_to_view_rctf(&ar->v2d, &rect, &userdata.rect);
userdata.changed = false;
- userdata.mode = RNA_int_get(op->ptr, "gesture_mode");
+ userdata.select = !RNA_boolean_get(op->ptr, "deselect");
userdata.extend = RNA_boolean_get(op->ptr, "extend");
clip_graph_tracking_values_iterate_track(sc, act_track, &userdata, border_select_cb, NULL, NULL);
@@ -402,16 +402,16 @@ void CLIP_OT_graph_select_border(wmOperatorType *ot)
ot->idname = "CLIP_OT_graph_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = border_select_graph_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = clip_graph_knots_poll;
/* flags */
ot->flag = OPTYPE_UNDO;
/* properties */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/********************** select all operator *********************/
@@ -700,7 +700,7 @@ static int graph_disable_markers_exec(bContext *C, wmOperator *op)
void CLIP_OT_graph_disable_markers(wmOperatorType *ot)
{
- static EnumPropertyItem actions_items[] = {
+ static const EnumPropertyItem actions_items[] = {
{0, "DISABLE", 0, "Disable", "Disable selected markers"},
{1, "ENABLE", 0, "Enable", "Enable selected markers"},
{2, "TOGGLE", 0, "Toggle", "Toggle disabled flag for selected markers"},
diff --git a/source/blender/editors/space_clip/clip_intern.h b/source/blender/editors/space_clip/clip_intern.h
index 14393c6968b..ae15834a1d9 100644
--- a/source/blender/editors/space_clip/clip_intern.h
+++ b/source/blender/editors/space_clip/clip_intern.h
@@ -139,6 +139,8 @@ void clip_graph_tracking_iterate(struct SpaceClip *sc, bool selected_only, bool
void clip_delete_track(struct bContext *C, struct MovieClip *clip, struct MovieTrackingTrack *track);
void clip_delete_marker(struct bContext *C, struct MovieClip *clip, struct MovieTrackingTrack *track, struct MovieTrackingMarker *marker);
+void clip_delete_plane_track(struct bContext *C, struct MovieClip *clip, struct MovieTrackingPlaneTrack *plane_track);
+
void clip_view_center_to_point(SpaceClip *sc, float x, float y);
void clip_draw_cfra(struct SpaceClip *sc, struct ARegion *ar, struct Scene *scene);
diff --git a/source/blender/editors/space_clip/clip_ops.c b/source/blender/editors/space_clip/clip_ops.c
index 9430ee626ba..7d8dd629562 100644
--- a/source/blender/editors/space_clip/clip_ops.c
+++ b/source/blender/editors/space_clip/clip_ops.c
@@ -56,6 +56,7 @@
#include "BKE_context.h"
#include "BKE_global.h"
+#include "BKE_depsgraph.h"
#include "BKE_report.h"
#include "BKE_library.h"
#include "BKE_main.h"
@@ -247,6 +248,7 @@ static int open_exec(bContext *C, wmOperator *op)
WM_event_add_notifier(C, NC_MOVIECLIP | NA_ADDED, clip);
+ DAG_relations_tag_update(bmain);
MEM_freeN(op->customdata);
return OPERATOR_FINISHED;
@@ -941,7 +943,7 @@ static int frame_from_event(bContext *C, const wmEvent *event)
UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &viewx, &viewy);
- framenr = iroundf(viewx);
+ framenr = round_fl_to_int(viewx);
}
return framenr;
diff --git a/source/blender/editors/space_clip/clip_toolbar.c b/source/blender/editors/space_clip/clip_toolbar.c
index b042bbe8fea..d2a7244eded 100644
--- a/source/blender/editors/space_clip/clip_toolbar.c
+++ b/source/blender/editors/space_clip/clip_toolbar.c
@@ -49,7 +49,7 @@
#include "WM_api.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "UI_interface.h"
#include "UI_resources.h"
@@ -193,7 +193,7 @@ void CLIP_OT_tools(wmOperatorType *ot)
static void clip_panel_operator_redo_buts(const bContext *C, Panel *pa, wmOperator *op)
{
- uiLayoutOperatorButs(C, pa->layout, op, NULL, 'V', 0);
+ uiTemplateOperatorPropertyButs(C, pa->layout, op, NULL, 'V', 0);
}
static void clip_panel_operator_redo_header(const bContext *C, Panel *pa)
diff --git a/source/blender/editors/space_clip/clip_utils.c b/source/blender/editors/space_clip/clip_utils.c
index 547c2fba66f..e7853cb2a0c 100644
--- a/source/blender/editors/space_clip/clip_utils.c
+++ b/source/blender/editors/space_clip/clip_utils.c
@@ -72,7 +72,7 @@ void clip_graph_tracking_values_iterate_track(
BKE_movieclip_get_size(clip, &sc->user, &width, &height);
for (coord = 0; coord < 2; coord++) {
- int i, prevfra = 0;
+ int i, prevfra = track->markers[0].framenr;
bool open = false;
float prevval = 0.0f;
@@ -178,36 +178,37 @@ void clip_delete_track(bContext *C, MovieClip *clip, MovieTrackingTrack *track)
MovieTrackingTrack *act_track = BKE_tracking_track_get_active(tracking);
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
bool has_bundle = false;
- char track_name_escaped[MAX_NAME], prefix[MAX_NAME * 2];
-
- if (track == act_track)
+ const bool used_for_stabilization =
+ (track->flag & (TRACK_USE_2D_STAB | TRACK_USE_2D_STAB_ROT)) != 0;
+ if (track == act_track) {
tracking->act_track = NULL;
-
- /* handle reconstruction display in 3d viewport */
- if (track->flag & TRACK_HAS_BUNDLE)
+ }
+ /* Handle reconstruction display in 3d viewport. */
+ if (track->flag & TRACK_HAS_BUNDLE) {
has_bundle = true;
-
+ }
/* Make sure no plane will use freed track */
BKE_tracking_plane_tracks_remove_point_track(tracking, track);
-
/* Delete f-curves associated with the track (such as weight, i.e.) */
- BLI_strescape(track_name_escaped, track->name, sizeof(track_name_escaped));
- BLI_snprintf(prefix, sizeof(prefix), "tracks[\"%s\"]", track_name_escaped);
- BKE_animdata_fix_paths_remove(&clip->id, prefix);
-
+ /* Escaped object name, escaped track name, rest of the path. */
+ char rna_path[MAX_NAME * 4 + 64];
+ BKE_tracking_get_rna_path_for_track(tracking,
+ track,
+ rna_path, sizeof(rna_path));
+ BKE_animdata_fix_paths_remove(&clip->id, rna_path);
+ /* Delete track itself. */
BKE_tracking_track_free(track);
BLI_freelinkN(tracksbase, track);
-
+ /* Send notifiers. */
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
-
- if (track->flag & (TRACK_USE_2D_STAB | TRACK_USE_2D_STAB_ROT)) {
+ if (used_for_stabilization) {
WM_event_add_notifier(C, NC_MOVIECLIP | ND_DISPLAY, clip);
}
-
- DAG_id_tag_update(&clip->id, 0);
-
- if (has_bundle)
+ if (has_bundle) {
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ }
+ /* Inform dependency graph. */
+ DAG_id_tag_update(&clip->id, 0);
}
void clip_delete_marker(bContext *C, MovieClip *clip, MovieTrackingTrack *track,
@@ -223,6 +224,28 @@ void clip_delete_marker(bContext *C, MovieClip *clip, MovieTrackingTrack *track,
}
}
+void clip_delete_plane_track(bContext *C,
+ MovieClip *clip,
+ MovieTrackingPlaneTrack *plane_track)
+{
+ MovieTracking *tracking = &clip->tracking;
+ ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
+ /* Delete f-curves associated with the track (such as weight, i.e.) */
+ /* Escaped object name, escaped track name, rest of the path. */
+ char rna_path[MAX_NAME * 4 + 64];
+ BKE_tracking_get_rna_path_for_plane_track(tracking,
+ plane_track,
+ rna_path, sizeof(rna_path));
+ BKE_animdata_fix_paths_remove(&clip->id, rna_path);
+ /* Delete the plane track itself. */
+ BKE_tracking_plane_track_free(plane_track);
+ BLI_freelinkN(plane_tracks_base, plane_track);
+ /* TODO(sergey): Any notifiers to be sent here? */
+ (void) C;
+ /* Inform dependency graph. */
+ DAG_id_tag_update(&clip->id, 0);
+}
+
void clip_view_center_to_point(SpaceClip *sc, float x, float y)
{
int width, height;
diff --git a/source/blender/editors/space_clip/space_clip.c b/source/blender/editors/space_clip/space_clip.c
index 05e69968e35..58930fa2cf2 100644
--- a/source/blender/editors/space_clip/space_clip.c
+++ b/source/blender/editors/space_clip/space_clip.c
@@ -337,7 +337,7 @@ static void clip_listener(bScreen *UNUSED(sc), ScrArea *sa, wmNotifier *wmn)
switch (wmn->data) {
case ND_FRAME:
clip_scopes_tag_refresh(sa);
- /* fall-through */
+ ATTR_FALLTHROUGH;
case ND_FRAME_RANGE:
ED_area_tag_redraw(sa);
@@ -821,6 +821,7 @@ static void clip_keymap(struct wmKeyConfig *keyconf)
#endif
}
+/* DO NOT make this static, this hides the symbol and breaks API generation script. */
const char *clip_context_dir[] = {"edit_movieclip", "edit_mask", NULL};
static int clip_context(const bContext *C, const char *member, bContextDataResult *result)
diff --git a/source/blender/editors/space_clip/tracking_ops.c b/source/blender/editors/space_clip/tracking_ops.c
index d28cbe5fb1d..50f21c8891c 100644
--- a/source/blender/editors/space_clip/tracking_ops.c
+++ b/source/blender/editors/space_clip/tracking_ops.c
@@ -226,7 +226,6 @@ static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
MovieClip *clip = ED_space_clip_get_clip(sc);
MovieTracking *tracking = &clip->tracking;
bool changed = false;
-
/* Delete selected plane tracks. */
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first,
@@ -235,14 +234,11 @@ static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
plane_track = next_plane_track)
{
next_plane_track = plane_track->next;
-
if (PLANE_TRACK_VIEW_SELECTED(plane_track)) {
- BKE_tracking_plane_track_free(plane_track);
- BLI_freelinkN(plane_tracks_base, plane_track);
+ clip_delete_plane_track(C, clip, plane_track);
changed = true;
}
}
-
/* Remove selected point tracks (they'll also be removed from planes which
* uses them).
*/
@@ -257,14 +253,11 @@ static int delete_track_exec(bContext *C, wmOperator *UNUSED(op))
changed = true;
}
}
-
/* Nothing selected now, unlock view so it can be scrolled nice again. */
sc->flag &= ~SC_LOCK_SELECTION;
-
if (changed) {
WM_event_add_notifier(C, NC_MOVIECLIP | NA_EDITED, clip);
}
-
return OPERATOR_FINISHED;
}
@@ -875,8 +868,7 @@ static int slide_marker_modal(bContext *C, wmOperator *op, const wmEvent *event)
if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY)) {
data->accurate = event->val == KM_PRESS;
}
-
- /* fall-through */
+ ATTR_FALLTHROUGH;
case MOUSEMOVE:
mdelta[0] = event->mval[0] - data->mval[0];
mdelta[1] = event->mval[1] - data->mval[1];
@@ -1138,7 +1130,7 @@ static int clear_track_path_exec(bContext *C, wmOperator *op)
void CLIP_OT_clear_track_path(wmOperatorType *ot)
{
- static EnumPropertyItem clear_path_actions[] = {
+ static const EnumPropertyItem clear_path_actions[] = {
{TRACK_CLEAR_UPTO, "UPTO", 0, "Clear up-to", "Clear path up to current frame"},
{TRACK_CLEAR_REMAINED, "REMAINED", 0, "Clear remained", "Clear path at remaining frames (after current)"},
{TRACK_CLEAR_ALL, "ALL", 0, "Clear all", "Clear the whole path"},
@@ -1210,7 +1202,7 @@ static int disable_markers_exec(bContext *C, wmOperator *op)
void CLIP_OT_disable_markers(wmOperatorType *ot)
{
- static EnumPropertyItem actions_items[] = {
+ static const EnumPropertyItem actions_items[] = {
{MARKER_OP_DISABLE, "DISABLE", 0, "Disable",
"Disable selected markers"},
{MARKER_OP_ENABLE, "ENABLE", 0, "Enable",
@@ -1477,7 +1469,7 @@ static int frame_jump_exec(bContext *C, wmOperator *op)
void CLIP_OT_frame_jump(wmOperatorType *ot)
{
- static EnumPropertyItem position_items[] = {
+ static const EnumPropertyItem position_items[] = {
{0, "PATHSTART", 0, "Path Start", "Jump to start of current path"},
{1, "PATHEND", 0, "Path End", "Jump to end of current path"},
{2, "FAILEDPREV", 0, "Previous Failed", "Jump to previous failed frame"},
@@ -1534,7 +1526,8 @@ static int join_tracks_exec(bContext *C, wmOperator *op)
update_stabilization = true;
if ((act_track->flag & TRACK_USE_2D_STAB) == 0) {
act_track->flag |= TRACK_USE_2D_STAB;
- } else {
+ }
+ else {
stab->tot_track--;
}
BLI_assert(0 <= stab->tot_track);
@@ -1543,7 +1536,8 @@ static int join_tracks_exec(bContext *C, wmOperator *op)
update_stabilization = true;
if ((act_track->flag & TRACK_USE_2D_STAB_ROT) == 0) {
act_track->flag |= TRACK_USE_2D_STAB_ROT;
- } else {
+ }
+ else {
stab->tot_rot_track--;
}
BLI_assert(0 <= stab->tot_rot_track);
@@ -1643,7 +1637,7 @@ static int lock_tracks_exec(bContext *C, wmOperator *op)
void CLIP_OT_lock_tracks(wmOperatorType *ot)
{
- static EnumPropertyItem actions_items[] = {
+ static const EnumPropertyItem actions_items[] = {
{TRACK_ACTION_LOCK, "LOCK", 0, "Lock", "Lock selected tracks"},
{TRACK_ACTION_UNLOCK, "UNLOCK", 0, "Unlock", "Unlock selected tracks"},
{TRACK_ACTION_TOGGLE, "TOGGLE", 0, "Toggle",
@@ -1699,7 +1693,7 @@ static int set_solver_keyframe_exec(bContext *C, wmOperator *op)
void CLIP_OT_set_solver_keyframe(wmOperatorType *ot)
{
- static EnumPropertyItem keyframe_items[] = {
+ static const EnumPropertyItem keyframe_items[] = {
{SOLVER_KEYFRAME_A, "KEYFRAME_A", 0, "Keyframe A", ""},
{SOLVER_KEYFRAME_B, "KEYFRAME_B", 0, "Keyframe B", ""},
{0, NULL, 0, NULL, NULL}
@@ -1864,6 +1858,10 @@ static bool is_track_clean(MovieTrackingTrack *track, int frames, int del)
}
}
+ if (del && count == 0) {
+ ok = 0;
+ }
+
if (del) {
MEM_freeN(track->markers);
@@ -1970,7 +1968,7 @@ static int clean_tracks_invoke(bContext *C,
void CLIP_OT_clean_tracks(wmOperatorType *ot)
{
- static EnumPropertyItem actions_items[] = {
+ static const EnumPropertyItem actions_items[] = {
{TRACKING_CLEAN_SELECT, "SELECT", 0, "Select",
"Select unclean tracks"},
{TRACKING_CLEAN_DELETE_TRACK, "DELETE_TRACK", 0, "Delete Track",
diff --git a/source/blender/editors/space_clip/tracking_ops_detect.c b/source/blender/editors/space_clip/tracking_ops_detect.c
index 992c347a630..0ee06b305da 100644
--- a/source/blender/editors/space_clip/tracking_ops_detect.c
+++ b/source/blender/editors/space_clip/tracking_ops_detect.c
@@ -128,7 +128,7 @@ static int detect_features_exec(bContext *C, wmOperator *op)
void CLIP_OT_detect_features(wmOperatorType *ot)
{
- static EnumPropertyItem placement_items[] = {
+ static const EnumPropertyItem placement_items[] = {
{0, "FRAME", 0, "Whole Frame",
"Place markers across the whole frame"},
{1, "INSIDE_GPENCIL", 0, "Inside grease pencil",
diff --git a/source/blender/editors/space_clip/tracking_ops_orient.c b/source/blender/editors/space_clip/tracking_ops_orient.c
index f81180d65a9..8c5be7c9d04 100644
--- a/source/blender/editors/space_clip/tracking_ops_orient.c
+++ b/source/blender/editors/space_clip/tracking_ops_orient.c
@@ -42,7 +42,6 @@
#include "BKE_context.h"
#include "BKE_constraint.h"
#include "BKE_tracking.h"
-#include "BKE_global.h"
#include "BKE_depsgraph.h"
#include "BKE_object.h"
#include "BKE_report.h"
@@ -504,7 +503,7 @@ static int set_plane_exec(bContext *C, wmOperator *op)
void CLIP_OT_set_plane(wmOperatorType *ot)
{
- static EnumPropertyItem plane_items[] = {
+ static const EnumPropertyItem plane_items[] = {
{0, "FLOOR", 0, "Floor", "Set floor plane"},
{1, "WALL", 0, "Wall", "Set wall plane"},
{0, NULL, 0, NULL, NULL}
@@ -578,7 +577,7 @@ static int set_axis_exec(bContext *C, wmOperator *op)
void CLIP_OT_set_axis(wmOperatorType *ot)
{
- static EnumPropertyItem axis_actions[] = {
+ static const EnumPropertyItem axis_actions[] = {
{0, "X", 0, "X", "Align bundle align X axis"},
{1, "Y", 0, "Y", "Align bundle align Y axis"},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/space_clip/tracking_ops_plane.c b/source/blender/editors/space_clip/tracking_ops_plane.c
index 4332f3ea765..aa8518befaa 100644
--- a/source/blender/editors/space_clip/tracking_ops_plane.c
+++ b/source/blender/editors/space_clip/tracking_ops_plane.c
@@ -301,8 +301,7 @@ static int slide_plane_marker_modal(bContext *C,
if (ELEM(event->type, LEFTSHIFTKEY, RIGHTSHIFTKEY)) {
data->accurate = event->val == KM_PRESS;
}
-
- /* fall-through */
+ ATTR_FALLTHROUGH;
case MOUSEMOVE:
mdelta[0] = event->mval[0] - data->previous_mval[0];
mdelta[1] = event->mval[1] - data->previous_mval[1];
diff --git a/source/blender/editors/space_clip/tracking_ops_track.c b/source/blender/editors/space_clip/tracking_ops_track.c
index 368cbeaf955..0dd0ee8c7d4 100644
--- a/source/blender/editors/space_clip/tracking_ops_track.c
+++ b/source/blender/editors/space_clip/tracking_ops_track.c
@@ -165,7 +165,7 @@ static int track_markers_initjob(bContext *C,
track_init_markers(sc, clip, framenr, &frames_limit);
- tmj->sfra = ED_space_clip_get_clip_frame_number(sc);
+ tmj->sfra = framenr;
tmj->clip = clip;
tmj->backwards = backwards;
@@ -176,6 +176,7 @@ static int track_markers_initjob(bContext *C,
else {
tmj->efra = EFRA;
}
+ tmj->efra = BKE_movieclip_remap_scene_to_clip_frame(clip, tmj->efra);
}
else {
if (backwards) {
@@ -196,8 +197,6 @@ static int track_markers_initjob(bContext *C,
}
}
- tmj->efra = BKE_movieclip_remap_scene_to_clip_frame(clip, tmj->efra);
-
if (settings->speed != TRACKING_SPEED_FASTEST) {
tmj->delay = 1.0f / scene->r.frs_sec * 1000.0f;
@@ -212,7 +211,7 @@ static int track_markers_initjob(bContext *C,
}
}
- tmj->context = BKE_autotrack_context_new(clip, &sc->user, backwards, 1);
+ tmj->context = BKE_autotrack_context_new(clip, &sc->user, backwards, true);
clip->tracking_context = tmj->context;
@@ -310,6 +309,7 @@ static void track_markers_endjob(void *tmv)
static void track_markers_freejob(void *tmv)
{
TrackMarkersJob *tmj = (TrackMarkersJob *)tmv;
+ tmj->clip->tracking_context = NULL;
BKE_autotrack_context_free(tmj->context);
MEM_freeN(tmj);
}
diff --git a/source/blender/editors/space_clip/tracking_select.c b/source/blender/editors/space_clip/tracking_select.c
index e970b1b9743..ecbc1f5ae1e 100644
--- a/source/blender/editors/space_clip/tracking_select.c
+++ b/source/blender/editors/space_clip/tracking_select.c
@@ -37,7 +37,7 @@
#include "BLI_utildefines.h"
#include "BLI_math.h"
#include "BLI_rect.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BKE_context.h"
#include "BKE_tracking.h"
@@ -438,7 +438,6 @@ static int border_select_exec(bContext *C, wmOperator *op)
rcti rect;
rctf rectf;
bool changed = false;
- int mode, extend;
int framenr = ED_space_clip_get_clip_frame_number(sc);
/* get rectangle from operator */
@@ -447,8 +446,8 @@ static int border_select_exec(bContext *C, wmOperator *op)
ED_clip_point_stable_pos(sc, ar, rect.xmin, rect.ymin, &rectf.xmin, &rectf.ymin);
ED_clip_point_stable_pos(sc, ar, rect.xmax, rect.ymax, &rectf.xmax, &rectf.ymax);
- mode = RNA_int_get(op->ptr, "gesture_mode");
- extend = RNA_boolean_get(op->ptr, "extend");
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* do actual selection */
track = tracksbase->first;
@@ -458,10 +457,12 @@ static int border_select_exec(bContext *C, wmOperator *op)
if (MARKER_VISIBLE(sc, track, marker)) {
if (BLI_rctf_isect_pt_v(&rectf, marker->pos)) {
- if (mode == GESTURE_MODAL_SELECT)
+ if (select) {
BKE_tracking_track_flag_set(track, TRACK_AREA_ALL, SELECT);
- else
+ }
+ else {
BKE_tracking_track_flag_clear(track, TRACK_AREA_ALL, SELECT);
+ }
}
else if (!extend) {
BKE_tracking_track_flag_clear(track, TRACK_AREA_ALL, SELECT);
@@ -485,7 +486,7 @@ static int border_select_exec(bContext *C, wmOperator *op)
for (i = 0; i < 4; i++) {
if (BLI_rctf_isect_pt_v(&rectf, plane_marker->corners[i])) {
- if (mode == GESTURE_MODAL_SELECT) {
+ if (select) {
plane_track->flag |= SELECT;
}
else {
@@ -520,16 +521,16 @@ void CLIP_OT_select_border(wmOperatorType *ot)
ot->idname = "CLIP_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = border_select_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
ot->flag = OPTYPE_UNDO;
/* properties */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/********************** lasso select operator *********************/
@@ -656,9 +657,7 @@ void CLIP_OT_select_lasso(wmOperatorType *ot)
ot->flag = OPTYPE_UNDO;
/* properties */
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
+ WM_operator_properties_gesture_lasso_select(ot);
}
/********************** circle select operator *********************/
@@ -690,17 +689,17 @@ static int circle_select_exec(bContext *C, wmOperator *op)
MovieTrackingPlaneTrack *plane_track;
ListBase *tracksbase = BKE_tracking_get_active_tracks(tracking);
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(tracking);
- int x, y, radius, width, height, mode;
+ int width, height;
bool changed = false;
float zoomx, zoomy, offset[2], ellipse[2];
int framenr = ED_space_clip_get_clip_frame_number(sc);
/* get operator properties */
- x = RNA_int_get(op->ptr, "x");
- y = RNA_int_get(op->ptr, "y");
- radius = RNA_int_get(op->ptr, "radius");
+ const int x = RNA_int_get(op->ptr, "x");
+ const int y = RNA_int_get(op->ptr, "y");
+ const int radius = RNA_int_get(op->ptr, "radius");
- mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
/* compute ellipse and position in unified coordinates */
ED_space_clip_get_size(sc, &width, &height);
@@ -718,11 +717,12 @@ static int circle_select_exec(bContext *C, wmOperator *op)
MovieTrackingMarker *marker = BKE_tracking_marker_get(track, framenr);
if (MARKER_VISIBLE(sc, track, marker) && marker_inside_ellipse(marker, offset, ellipse)) {
- if (mode == GESTURE_MODAL_SELECT)
+ if (select) {
BKE_tracking_track_flag_set(track, TRACK_AREA_ALL, SELECT);
- else
+ }
+ else {
BKE_tracking_track_flag_clear(track, TRACK_AREA_ALL, SELECT);
-
+ }
changed = true;
}
}
@@ -741,7 +741,7 @@ static int circle_select_exec(bContext *C, wmOperator *op)
for (i = 0; i < 4; i++) {
if (point_inside_ellipse(plane_marker->corners[i], offset, ellipse)) {
- if (mode == GESTURE_MODAL_SELECT) {
+ if (select) {
plane_track->flag |= SELECT;
}
else {
@@ -782,10 +782,7 @@ void CLIP_OT_select_circle(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
+ WM_operator_properties_gesture_circle_select(ot);
}
/********************** select all operator *********************/
@@ -909,7 +906,7 @@ void CLIP_OT_select_all(wmOperatorType *ot)
/********************** select grouped operator *********************/
-static int select_groped_exec(bContext *C, wmOperator *op)
+static int select_grouped_exec(bContext *C, wmOperator *op)
{
SpaceClip *sc = CTX_wm_space_clip(C);
MovieClip *clip = ED_space_clip_get_clip(sc);
@@ -975,7 +972,7 @@ static int select_groped_exec(bContext *C, wmOperator *op)
void CLIP_OT_select_grouped(wmOperatorType *ot)
{
- static EnumPropertyItem select_group_items[] = {
+ static const EnumPropertyItem select_group_items[] = {
{0, "KEYFRAMED", 0, "Keyframed tracks", "Select all keyframed tracks"},
{1, "ESTIMATED", 0, "Estimated tracks", "Select all estimated tracks"},
{2, "TRACKED", 0, "Tracked tracks", "Select all tracked tracks"},
@@ -992,7 +989,7 @@ void CLIP_OT_select_grouped(wmOperatorType *ot)
ot->idname = "CLIP_OT_select_grouped";
/* api callbacks */
- ot->exec = select_groped_exec;
+ ot->exec = select_grouped_exec;
ot->poll = ED_space_clip_tracking_poll;
/* flags */
diff --git a/source/blender/editors/space_console/console_intern.h b/source/blender/editors/space_console/console_intern.h
index 5b016b77e9f..f523cf0d476 100644
--- a/source/blender/editors/space_console/console_intern.h
+++ b/source/blender/editors/space_console/console_intern.h
@@ -70,6 +70,6 @@ void CONSOLE_OT_select_set(struct wmOperatorType *ot);
void CONSOLE_OT_select_word(struct wmOperatorType *ot);
enum { LINE_BEGIN, LINE_END, PREV_CHAR, NEXT_CHAR, PREV_WORD, NEXT_WORD };
-enum { DEL_ALL, DEL_NEXT_CHAR, DEL_PREV_CHAR, DEL_NEXT_WORD, DEL_PREV_WORD, DEL_SELECTION, DEL_NEXT_SEL, DEL_PREV_SEL };
+enum { DEL_NEXT_CHAR, DEL_PREV_CHAR, DEL_NEXT_WORD, DEL_PREV_WORD, DEL_SELECTION, DEL_NEXT_SEL, DEL_PREV_SEL };
#endif /* __CONSOLE_INTERN_H__ */
diff --git a/source/blender/editors/space_console/console_ops.c b/source/blender/editors/space_console/console_ops.c
index 2b99c4dfa3d..b740ff4b397 100644
--- a/source/blender/editors/space_console/console_ops.c
+++ b/source/blender/editors/space_console/console_ops.c
@@ -299,7 +299,7 @@ static bool console_line_column_from_index(
/* static funcs for text editing */
/* similar to the text editor, with some not used. keep compatible */
-static EnumPropertyItem console_move_type_items[] = {
+static const EnumPropertyItem console_move_type_items[] = {
{LINE_BEGIN, "LINE_BEGIN", 0, "Line Begin", ""},
{LINE_END, "LINE_END", 0, "Line End", ""},
{PREV_CHAR, "PREVIOUS_CHARACTER", 0, "Previous Character", ""},
@@ -570,7 +570,7 @@ void CONSOLE_OT_unindent(wmOperatorType *ot)
ot->poll = ED_operator_console_active;
}
-static EnumPropertyItem console_delete_type_items[] = {
+static const EnumPropertyItem console_delete_type_items[] = {
{DEL_NEXT_CHAR, "NEXT_CHARACTER", 0, "Next Character", ""},
{DEL_PREV_CHAR, "PREVIOUS_CHARACTER", 0, "Previous Character", ""},
{DEL_NEXT_WORD, "NEXT_WORD", 0, "Next Word", ""},
@@ -895,7 +895,7 @@ static int console_scrollback_append_exec(bContext *C, wmOperator *op)
void CONSOLE_OT_scrollback_append(wmOperatorType *ot)
{
/* defined in DNA_space_types.h */
- static EnumPropertyItem console_line_type_items[] = {
+ static const EnumPropertyItem console_line_type_items[] = {
{CONSOLE_LINE_OUTPUT, "OUTPUT", 0, "Output", ""},
{CONSOLE_LINE_INPUT, "INPUT", 0, "Input", ""},
{CONSOLE_LINE_INFO, "INFO", 0, "Information", ""},
diff --git a/source/blender/editors/space_file/file_draw.c b/source/blender/editors/space_file/file_draw.c
index 52d01063175..396f3cf32f4 100644
--- a/source/blender/editors/space_file/file_draw.c
+++ b/source/blender/editors/space_file/file_draw.c
@@ -597,7 +597,7 @@ void file_draw_list(const bContext *C, ARegion *ar)
int colorid = (file_selflag & FILE_SEL_SELECTED) ? TH_HILITE : TH_BACK;
int shade = (params->highlight_file == i) || (file_selflag & FILE_SEL_HIGHLIGHTED) ? 35 : 0;
- BLI_assert(i > 0 || FILENAME_IS_CURRPAR(file->relpath));
+ BLI_assert(i == 0 || !FILENAME_IS_CURRPAR(file->relpath));
draw_tile(sx, sy - 1, layout->tile_w + 4, sfile->layout->tile_h + layout->tile_border_y, colorid, shade);
}
diff --git a/source/blender/editors/space_file/file_ops.c b/source/blender/editors/space_file/file_ops.c
index b7228f634bf..217ce8f1d9a 100644
--- a/source/blender/editors/space_file/file_ops.c
+++ b/source/blender/editors/space_file/file_ops.c
@@ -105,7 +105,7 @@ static void file_deselect_all(SpaceFile *sfile, unsigned int flag)
filelist_entries_select_index_range_set(sfile->files, &sel, FILE_SEL_REMOVE, flag, CHECK_ALL);
}
-typedef enum FileSelect {
+typedef enum FileSelect {
FILE_SELECT_NOTHING = 0,
FILE_SELECT_DIR = 1,
FILE_SELECT_FILE = 2
@@ -151,15 +151,25 @@ static FileSelection file_selection_get(bContext *C, const rcti *rect, bool fill
/* if desired, fill the selection up from the last selected file to the current one */
if (fill && (sel.last >= 0) && (sel.last < numfiles) ) {
- int f = sel.last;
- while (f >= 0) {
+ int f;
+ /* Try to find a smaller-index selected item. */
+ for (f = sel.last; f >= 0; f--) {
if (filelist_entry_select_index_get(sfile->files, f, CHECK_ALL) )
break;
- f--;
}
if (f >= 0) {
sel.first = f + 1;
}
+ /* If none found, try to find a higher-index selected item. */
+ else {
+ for (f = sel.first; f < numfiles; f++) {
+ if (filelist_entry_select_index_get(sfile->files, f, CHECK_ALL) )
+ break;
+ }
+ if (f < numfiles) {
+ sel.last = f - 1;
+ }
+ }
}
return sel;
}
@@ -370,7 +380,7 @@ static int file_border_select_modal(bContext *C, wmOperator *op, const wmEvent *
int result;
- result = WM_border_select_modal(C, op, event);
+ result = WM_gesture_border_modal(C, op, event);
if (result == OPERATOR_RUNNING_MODAL) {
WM_operator_properties_border_to_rcti(op, &rect);
@@ -419,7 +429,7 @@ static int file_border_select_exec(bContext *C, wmOperator *op)
SpaceFile *sfile = CTX_wm_space_file(C);
rcti rect;
FileSelect ret;
- const bool select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
const bool extend = RNA_boolean_get(op->ptr, "extend");
WM_operator_properties_border_to_rcti(op, &rect);
@@ -452,14 +462,14 @@ void FILE_OT_select_border(wmOperatorType *ot)
ot->idname = "FILE_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = file_border_select_exec;
ot->modal = file_border_select_modal;
ot->poll = ED_operator_file_active;
- ot->cancel = WM_border_select_cancel;
+ ot->cancel = WM_gesture_border_cancel;
/* properties */
- WM_operator_properties_gesture_border(ot, 1);
+ WM_operator_properties_gesture_border_select(ot);
}
static int file_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
@@ -730,7 +740,7 @@ static int file_walk_select_invoke(bContext *C, wmOperator *op, const wmEvent *U
void FILE_OT_select_walk(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{FILE_SELECT_WALK_UP, "UP", 0, "Prev", ""},
{FILE_SELECT_WALK_DOWN, "DOWN", 0, "Next", ""},
{FILE_SELECT_WALK_LEFT, "LEFT", 0, "Left", ""},
@@ -1041,7 +1051,7 @@ static int bookmark_move_exec(bContext *C, wmOperator *op)
void FILE_OT_bookmark_move(wmOperatorType *ot)
{
- static EnumPropertyItem slot_move[] = {
+ static const EnumPropertyItem slot_move[] = {
{FILE_BOOKMARK_MOVE_TOP, "TOP", 0, "Top", "Top of the list"},
{FILE_BOOKMARK_MOVE_UP, "UP", 0, "Up", ""},
{FILE_BOOKMARK_MOVE_DOWN, "DOWN", 0, "Down", ""},
@@ -1302,7 +1312,6 @@ void file_sfile_filepath_set(SpaceFile *sfile, const char *filepath)
if (BLI_is_dir(filepath)) {
BLI_strncpy(sfile->params->dir, filepath, sizeof(sfile->params->dir));
- sfile->params->file[0] = '\0';
}
else {
if ((sfile->params->flag & FILE_DIRSEL_ONLY) == 0) {
@@ -2204,7 +2213,7 @@ static int file_rename_poll(bContext *C)
poll = false;
}
else {
- char dir[FILE_MAX];
+ char dir[FILE_MAX_LIBEXTRA];
if (filelist_islibrary(sfile->files, dir, NULL)) {
poll = false;
}
@@ -2236,7 +2245,7 @@ static int file_delete_poll(bContext *C)
SpaceFile *sfile = CTX_wm_space_file(C);
if (sfile && sfile->params) {
- char dir[FILE_MAX];
+ char dir[FILE_MAX_LIBEXTRA];
int numfiles = filelist_files_ensure(sfile->files);
int i;
int num_selected = 0;
diff --git a/source/blender/editors/space_file/file_panels.c b/source/blender/editors/space_file/file_panels.c
index 7acf2564fb2..1839e861518 100644
--- a/source/blender/editors/space_file/file_panels.c
+++ b/source/blender/editors/space_file/file_panels.c
@@ -88,7 +88,7 @@ static void file_panel_operator(const bContext *C, Panel *pa)
UI_block_func_set(uiLayoutGetBlock(pa->layout), file_draw_check_cb, NULL, NULL);
- uiLayoutOperatorButs(C, pa->layout, op, file_panel_check_prop, '\0', UI_LAYOUT_OP_SHOW_EMPTY);
+ uiTemplateOperatorPropertyButs(C, pa->layout, op, file_panel_check_prop, '\0', UI_TEMPLATE_OP_PROPS_SHOW_EMPTY);
UI_block_func_set(uiLayoutGetBlock(pa->layout), NULL, NULL, NULL);
}
diff --git a/source/blender/editors/space_file/filelist.c b/source/blender/editors/space_file/filelist.c
index 83469a48165..d670af59bc9 100644
--- a/source/blender/editors/space_file/filelist.c
+++ b/source/blender/editors/space_file/filelist.c
@@ -277,9 +277,10 @@ typedef struct FileListFilter {
/* FileListFilter.flags */
enum {
- FLF_HIDE_DOT = 1 << 0,
- FLF_HIDE_PARENT = 1 << 1,
- FLF_HIDE_LIB_DIR = 1 << 2,
+ FLF_DO_FILTER = 1 << 0,
+ FLF_HIDE_DOT = 1 << 1,
+ FLF_HIDE_PARENT = 1 << 2,
+ FLF_HIDE_LIB_DIR = 1 << 3,
};
typedef struct FileList {
@@ -594,24 +595,27 @@ static bool is_filtered_file(FileListInternEntry *file, const char *UNUSED(root)
{
bool is_filtered = !is_hidden_file(file->relpath, filter);
- if (is_filtered && filter->filter && !FILENAME_IS_CURRPAR(file->relpath)) {
- if (file->typeflag & FILE_TYPE_DIR) {
- if (file->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {
- if (!(filter->filter & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {
- is_filtered = false;
+ if (is_filtered && (filter->flags & FLF_DO_FILTER) && !FILENAME_IS_CURRPAR(file->relpath)) {
+ /* We only check for types if some type are enabled in filtering. */
+ if (filter->filter) {
+ if (file->typeflag & FILE_TYPE_DIR) {
+ if (file->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {
+ if (!(filter->filter & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {
+ is_filtered = false;
+ }
+ }
+ else {
+ if (!(filter->filter & FILE_TYPE_FOLDER)) {
+ is_filtered = false;
+ }
}
}
else {
- if (!(filter->filter & FILE_TYPE_FOLDER)) {
+ if (!(file->typeflag & filter->filter)) {
is_filtered = false;
}
}
}
- else {
- if (!(file->typeflag & filter->filter)) {
- is_filtered = false;
- }
- }
if (is_filtered && (filter->filter_search[0] != '\0')) {
if (fnmatch(filter->filter_search, file->relpath, FNM_CASEFOLD) != 0) {
is_filtered = false;
@@ -631,28 +635,31 @@ static bool is_filtered_lib(FileListInternEntry *file, const char *root, FileLis
if (BLO_library_path_explode(path, dir, &group, &name)) {
is_filtered = !is_hidden_file(file->relpath, filter);
- if (is_filtered && filter->filter && !FILENAME_IS_CURRPAR(file->relpath)) {
- if (file->typeflag & FILE_TYPE_DIR) {
- if (file->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {
- if (!(filter->filter & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {
- is_filtered = false;
+ if (is_filtered && (filter->flags & FLF_DO_FILTER) && !FILENAME_IS_CURRPAR(file->relpath)) {
+ /* We only check for types if some type are enabled in filtering. */
+ if (filter->filter || filter->filter_id) {
+ if (file->typeflag & FILE_TYPE_DIR) {
+ if (file->typeflag & (FILE_TYPE_BLENDERLIB | FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP)) {
+ if (!(filter->filter & (FILE_TYPE_BLENDER | FILE_TYPE_BLENDER_BACKUP))) {
+ is_filtered = false;
+ }
}
- }
- else {
- if (!(filter->filter & FILE_TYPE_FOLDER)) {
- is_filtered = false;
+ else {
+ if (!(filter->filter & FILE_TYPE_FOLDER)) {
+ is_filtered = false;
+ }
}
}
- }
- if (is_filtered && group) {
- if (!name && (filter->flags & FLF_HIDE_LIB_DIR)) {
- is_filtered = false;
- }
- else {
- unsigned int filter_id = groupname_to_filter_id(group);
- if (!(filter_id & filter->filter_id)) {
+ if (is_filtered && group) {
+ if (!name && (filter->flags & FLF_HIDE_LIB_DIR)) {
is_filtered = false;
}
+ else {
+ unsigned int filter_id = groupname_to_filter_id(group);
+ if (!(filter_id & filter->filter_id)) {
+ is_filtered = false;
+ }
+ }
}
}
if (is_filtered && (filter->filter_search[0] != '\0')) {
@@ -729,12 +736,17 @@ void filelist_filter(FileList *filelist)
MEM_freeN(filtered_tmp);
}
-void filelist_setfilter_options(FileList *filelist, const bool hide_dot, const bool hide_parent,
+void filelist_setfilter_options(FileList *filelist, const bool do_filter,
+ const bool hide_dot, const bool hide_parent,
const unsigned int filter, const unsigned int filter_id,
const char *filter_glob, const char *filter_search)
{
bool update = false;
+ if (((filelist->filter_data.flags & FLF_DO_FILTER) != 0) != (do_filter != 0)) {
+ filelist->filter_data.flags ^= FLF_DO_FILTER;
+ update = true;
+ }
if (((filelist->filter_data.flags & FLF_HIDE_DOT) != 0) != (hide_dot != 0)) {
filelist->filter_data.flags ^= FLF_HIDE_DOT;
update = true;
@@ -1104,7 +1116,10 @@ static void filelist_cache_preview_runf(TaskPool *__restrict pool, void *taskdat
preview->img = IMB_thumb_manage(preview->path, THB_LARGE, source);
IMB_thumb_path_unlock(preview->path);
- preview->flags = 0; /* Used to tell free func to not free anything! */
+ /* Used to tell free func to not free anything.
+ * Note that we do not care about cas result here,
+ * we only want value attribution itself to be atomic (and memory barier).*/
+ atomic_cas_uint32(&preview->flags, preview->flags, 0);
BLI_thread_queue_push(cache->previews_done, preview);
// printf("%s: End (%d)...\n", __func__, threadid);
@@ -1964,7 +1979,7 @@ int ED_path_extension_type(const char *path)
else if (BLI_testextensie(path, ".py")) {
return FILE_TYPE_PYSCRIPT;
}
- else if (BLI_testextensie_n(path, ".txt", ".glsl", ".osl", ".data", NULL)) {
+ else if (BLI_testextensie_n(path, ".txt", ".glsl", ".osl", ".data", ".pov", ".ini", ".mcr", ".inc", NULL)) {
return FILE_TYPE_TEXT;
}
else if (BLI_testextensie_n(path, ".ttf", ".ttc", ".pfb", ".otf", ".otc", NULL)) {
@@ -1979,9 +1994,7 @@ int ED_path_extension_type(const char *path)
else if (BLI_testextensie(path, ".abc")) {
return FILE_TYPE_ALEMBIC;
}
- else if (BLI_testextensie_array(path, imb_ext_image) ||
- (G.have_quicktime && BLI_testextensie_array(path, imb_ext_image_qt)))
- {
+ else if (BLI_testextensie_array(path, imb_ext_image)) {
return FILE_TYPE_IMAGE;
}
else if (BLI_testextensie(path, ".ogg")) {
diff --git a/source/blender/editors/space_file/filelist.h b/source/blender/editors/space_file/filelist.h
index f4304681780..4e9c1e0dd1d 100644
--- a/source/blender/editors/space_file/filelist.h
+++ b/source/blender/editors/space_file/filelist.h
@@ -68,7 +68,8 @@ int folderlist_clear_next(struct SpaceFile *sfile);
void filelist_setsorting(struct FileList *filelist, const short sort);
void filelist_sort(struct FileList *filelist);
-void filelist_setfilter_options(struct FileList *filelist, const bool hide_dot, const bool hide_parent,
+void filelist_setfilter_options(struct FileList *filelist, const bool do_filter,
+ const bool hide_dot, const bool hide_parent,
const unsigned int filter, const unsigned int filter_id,
const char *filter_glob, const char *filter_search);
void filelist_filter(struct FileList *filelist);
diff --git a/source/blender/editors/space_file/fsmenu.c b/source/blender/editors/space_file/fsmenu.c
index 631ff06a77a..ee0ec3fda39 100644
--- a/source/blender/editors/space_file/fsmenu.c
+++ b/source/blender/editors/space_file/fsmenu.c
@@ -48,9 +48,6 @@
#ifdef WIN32
# include <windows.h> /* need to include windows.h so _WIN32_IE is defined */
-# ifndef _WIN32_IE
-# define _WIN32_IE 0x0400 /* minimal requirements for SHGetSpecialFolderPath on MINGW MSVC has this defined already */
-# endif
# include <shlobj.h> /* for SHGetSpecialFolderPath, has to be done before BLI_winstuff
* because 'near' is disabled through BLI_windstuff */
# include "BLI_winstuff.h"
@@ -169,12 +166,15 @@ void ED_fsmenu_entry_set_path(struct FSMenuEntry *fsentry, const char *path)
static void fsmenu_entry_generate_name(struct FSMenuEntry *fsentry, char *name, size_t name_size)
{
- char temp[FILE_MAX];
+ int offset = 0;
+ int len = name_size;
- BLI_strncpy(temp, fsentry->path, FILE_MAX);
- BLI_add_slash(temp);
- BLI_getlastdir(temp, name, name_size);
- BLI_del_slash(name);
+ if (BLI_path_name_at_index(fsentry->path, -1, &offset, &len)) {
+ /* use as size */
+ len += 1;
+ }
+
+ BLI_strncpy(name, &fsentry->path[offset], MIN2(len, name_size));
if (!name[0]) {
name[0] = '/';
name[1] = '\0';
@@ -537,28 +537,22 @@ void fsmenu_read_system(struct FSMenu *fsmenu, int read_bookmarks)
/* Finally get user favorite places */
if (read_bookmarks) {
UInt32 seed;
- OSErr err = noErr;
- CFArrayRef pathesArray;
- LSSharedFileListRef list;
- LSSharedFileListItemRef itemRef;
- CFIndex i, pathesCount;
- CFURLRef cfURL = NULL;
- CFStringRef pathString = NULL;
- list = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
- pathesArray = LSSharedFileListCopySnapshot(list, &seed);
- pathesCount = CFArrayGetCount(pathesArray);
+ LSSharedFileListRef list = LSSharedFileListCreate(NULL, kLSSharedFileListFavoriteItems, NULL);
+ CFArrayRef pathesArray = LSSharedFileListCopySnapshot(list, &seed);
+ CFIndex pathesCount = CFArrayGetCount(pathesArray);
- for (i = 0; i < pathesCount; i++) {
- itemRef = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(pathesArray, i);
+ for (CFIndex i = 0; i < pathesCount; i++) {
+ LSSharedFileListItemRef itemRef = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(pathesArray, i);
- err = LSSharedFileListItemResolve(itemRef,
- kLSSharedFileListNoUserInteraction |
- kLSSharedFileListDoNotMountVolumes,
- &cfURL, NULL);
- if (err != noErr)
+ CFURLRef cfURL = NULL;
+ OSErr err = LSSharedFileListItemResolve(itemRef,
+ kLSSharedFileListNoUserInteraction |
+ kLSSharedFileListDoNotMountVolumes,
+ &cfURL, NULL);
+ if (err != noErr || !cfURL)
continue;
- pathString = CFURLCopyFileSystemPath(cfURL, kCFURLPOSIXPathStyle);
+ CFStringRef pathString = CFURLCopyFileSystemPath(cfURL, kCFURLPOSIXPathStyle);
if (pathString == NULL || !CFStringGetCString(pathString, line, sizeof(line), kCFStringEncodingUTF8))
continue;
diff --git a/source/blender/editors/space_file/space_file.c b/source/blender/editors/space_file/space_file.c
index 374db92297d..1623712786c 100644
--- a/source/blender/editors/space_file/space_file.c
+++ b/source/blender/editors/space_file/space_file.c
@@ -188,6 +188,9 @@ static SpaceLink *file_duplicate(SpaceLink *sl)
/* clear or remove stuff from old */
sfilen->op = NULL; /* file window doesn't own operators */
+ sfilen->previews_timer = NULL;
+ sfilen->smoothscroll_timer = NULL;
+
if (sfileo->params) {
sfilen->files = filelist_new(sfileo->params->type);
sfilen->params = MEM_dupallocN(sfileo->params);
@@ -223,9 +226,10 @@ static void file_refresh(const bContext *C, ScrArea *sa)
filelist_setdir(sfile->files, params->dir);
filelist_setrecursion(sfile->files, params->recursion_level);
filelist_setsorting(sfile->files, params->sort);
- filelist_setfilter_options(sfile->files, (params->flag & FILE_HIDE_DOT) != 0,
+ filelist_setfilter_options(sfile->files, (params->flag & FILE_FILTER) != 0,
+ (params->flag & FILE_HIDE_DOT) != 0,
false, /* TODO hide_parent, should be controllable? */
- (params->flag & FILE_FILTER) ? params->filter : 0,
+ params->filter,
params->filter_id,
params->filter_glob,
params->filter_search);
@@ -602,7 +606,7 @@ static void file_tools_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa),
#if 0
/* context changes */
switch (wmn->category) {
-
+ /* pass */
}
#endif
}
diff --git a/source/blender/editors/space_graph/graph_buttons.c b/source/blender/editors/space_graph/graph_buttons.c
index 516814b63b4..1ada5538fe3 100644
--- a/source/blender/editors/space_graph/graph_buttons.c
+++ b/source/blender/editors/space_graph/graph_buttons.c
@@ -64,6 +64,7 @@
#include "ED_anim_api.h"
#include "ED_keyframing.h"
#include "ED_screen.h"
+#include "ED_undo.h"
#include "UI_interface.h"
#include "UI_resources.h"
@@ -208,7 +209,12 @@ static void graph_panel_properties(const bContext *C, Panel *pa)
sub = uiLayoutRow(row, true);
uiLayoutSetEnabled(sub, (fcu->color_mode == FCURVE_COLOR_CUSTOM));
uiItemR(sub, &fcu_ptr, "color", 0, "", ICON_NONE);
-
+
+ /* smoothing setting */
+ col = uiLayoutColumn(layout, true);
+ uiItemL(col, IFACE_("Auto Handle Smoothing:"), ICON_NONE);
+ uiItemR(col, &fcu_ptr, "auto_smoothing", 0, "", ICON_NONE);
+
MEM_freeN(ale);
}
@@ -498,25 +504,28 @@ static void driver_remove_cb(bContext *C, void *ale_v, void *UNUSED(arg))
/* call API method to remove this driver */
ANIM_remove_driver(reports, id, fcu->rna_path, fcu->array_index, 0);
+ ED_undo_push(C, "Remove Driver");
}
/* callback to add a target variable to the active driver */
-static void driver_add_var_cb(bContext *UNUSED(C), void *driver_v, void *UNUSED(arg))
+static void driver_add_var_cb(bContext *C, void *driver_v, void *UNUSED(arg))
{
ChannelDriver *driver = (ChannelDriver *)driver_v;
/* add a new variable */
driver_add_new_variable(driver);
+ ED_undo_push(C, "Add Driver Variable");
}
/* callback to remove target variable from active driver */
-static void driver_delete_var_cb(bContext *UNUSED(C), void *driver_v, void *dvar_v)
+static void driver_delete_var_cb(bContext *C, void *driver_v, void *dvar_v)
{
ChannelDriver *driver = (ChannelDriver *)driver_v;
DriverVar *dvar = (DriverVar *)dvar_v;
/* remove the active variable */
driver_free_variable_ex(driver, dvar);
+ ED_undo_push(C, "Delete Driver Variable");
}
/* callback to report why a driver variable is invalid */
@@ -616,30 +625,31 @@ static void graph_panel_driverVar__rotDiff(uiLayout *layout, ID *id, DriverVar *
Object *ob2 = (Object *)dtar2->id;
PointerRNA dtar_ptr, dtar2_ptr;
uiLayout *col;
-
+
/* initialize RNA pointer to the target */
- RNA_pointer_create(id, &RNA_DriverTarget, dtar, &dtar_ptr);
- RNA_pointer_create(id, &RNA_DriverTarget, dtar2, &dtar2_ptr);
-
- /* Bone 1 */
+ RNA_pointer_create(id, &RNA_DriverTarget, dtar, &dtar_ptr);
+ RNA_pointer_create(id, &RNA_DriverTarget, dtar2, &dtar2_ptr);
+
+ /* Object 1 */
col = uiLayoutColumn(layout, true);
uiLayoutSetRedAlert(col, (dtar->flag & DTAR_FLAG_INVALID)); /* XXX: per field... */
- uiItemR(col, &dtar_ptr, "id", 0, IFACE_("Bone 1"), ICON_NONE);
-
+ uiItemR(col, &dtar_ptr, "id", 0, IFACE_("Object 1"), ICON_NONE);
+
if (dtar->id && GS(dtar->id->name) == ID_OB && ob1->pose) {
PointerRNA tar_ptr;
-
+
RNA_pointer_create(dtar->id, &RNA_Pose, ob1->pose, &tar_ptr);
uiItemPointerR(col, &dtar_ptr, "bone_target", &tar_ptr, "bones", "", ICON_BONE_DATA);
}
-
+
+ /* Object 2 */
col = uiLayoutColumn(layout, true);
uiLayoutSetRedAlert(col, (dtar2->flag & DTAR_FLAG_INVALID)); /* XXX: per field... */
- uiItemR(col, &dtar2_ptr, "id", 0, IFACE_("Bone 2"), ICON_NONE);
-
+ uiItemR(col, &dtar2_ptr, "id", 0, IFACE_("Object 2"), ICON_NONE);
+
if (dtar2->id && GS(dtar2->id->name) == ID_OB && ob2->pose) {
PointerRNA tar_ptr;
-
+
RNA_pointer_create(dtar2->id, &RNA_Pose, ob2->pose, &tar_ptr);
uiItemPointerR(col, &dtar2_ptr, "bone_target", &tar_ptr, "bones", "", ICON_BONE_DATA);
}
@@ -658,8 +668,8 @@ static void graph_panel_driverVar__locDiff(uiLayout *layout, ID *id, DriverVar *
/* initialize RNA pointer to the target */
RNA_pointer_create(id, &RNA_DriverTarget, dtar, &dtar_ptr);
RNA_pointer_create(id, &RNA_DriverTarget, dtar2, &dtar2_ptr);
-
- /* Bone 1 */
+
+ /* Object 1 */
col = uiLayoutColumn(layout, true);
uiLayoutSetRedAlert(col, (dtar->flag & DTAR_FLAG_INVALID)); /* XXX: per field... */
uiItemR(col, &dtar_ptr, "id", 0, IFACE_("Object 1"), ICON_NONE);
@@ -673,7 +683,8 @@ static void graph_panel_driverVar__locDiff(uiLayout *layout, ID *id, DriverVar *
uiLayoutSetRedAlert(col, false); /* we can clear it again now - it's only needed when creating the ID/Bone fields */
uiItemR(col, &dtar_ptr, "transform_space", 0, NULL, ICON_NONE);
-
+
+ /* Object 2 */
col = uiLayoutColumn(layout, true);
uiLayoutSetRedAlert(col, (dtar2->flag & DTAR_FLAG_INVALID)); /* XXX: per field... */
uiItemR(col, &dtar2_ptr, "id", 0, IFACE_("Object 2"), ICON_NONE);
diff --git a/source/blender/editors/space_graph/graph_edit.c b/source/blender/editors/space_graph/graph_edit.c
index f38d36853d7..12d24502ad6 100644
--- a/source/blender/editors/space_graph/graph_edit.c
+++ b/source/blender/editors/space_graph/graph_edit.c
@@ -195,8 +195,8 @@ static int graphkeys_previewrange_exec(bContext *C, wmOperator *UNUSED(op))
/* set the range directly */
get_graph_keyframe_extents(&ac, &min, &max, NULL, NULL, false, false);
scene->r.flag |= SCER_PRV_RANGE;
- scene->r.psfra = iroundf(min);
- scene->r.pefra = iroundf(max);
+ scene->r.psfra = round_fl_to_int(min);
+ scene->r.pefra = round_fl_to_int(max);
/* set notifier that things have changed */
// XXX err... there's nothing for frame ranges yet, but this should do fine too
@@ -502,7 +502,7 @@ typedef enum eGraphKeys_InsertKey_Types {
} eGraphKeys_InsertKey_Types;
/* RNA mode types for insert keyframes tool */
-static EnumPropertyItem prop_graphkeys_insertkey_types[] = {
+static const EnumPropertyItem prop_graphkeys_insertkey_types[] = {
{GRAPHKEYS_INSERTKEY_ALL, "ALL", 0, "All Channels",
"Insert a keyframe on all visible and editable F-Curves using each curve's current value"},
{GRAPHKEYS_INSERTKEY_SEL, "SEL", 0, "Only Selected Channels",
@@ -1466,7 +1466,7 @@ void GRAPH_OT_sample(wmOperatorType *ot)
#define CLEAR_CYCLIC_EXPO -2
/* defines for set extrapolation-type for selected keyframes tool */
-static EnumPropertyItem prop_graphkeys_expo_types[] = {
+static const EnumPropertyItem prop_graphkeys_expo_types[] = {
{FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant Extrapolation", "Values on endpoint keyframes are held"},
{FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear Extrapolation", "Straight-line slope of end segments are extended past the endpoint keyframes"},
@@ -1504,7 +1504,7 @@ static void setexpo_graph_keys(bAnimContext *ac, short mode)
/* only add if one doesn't exist */
if (list_has_suitable_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, -1) == 0) {
// TODO: add some more preset versions which set different extrapolation options?
- add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES);
+ add_fmodifier(&fcu->modifiers, FMODIFIER_TYPE_CYCLES, fcu);
}
}
else if (mode == CLEAR_CYCLIC_EXPO) {
@@ -2036,7 +2036,7 @@ static int graphkeys_framejump_exec(bContext *C, wmOperator *UNUSED(op))
}
else {
/* Animation Mode - Affects current frame (int) */
- CFRA = iroundf(ked.f1 / ked.i1);
+ CFRA = round_fl_to_int(ked.f1 / ked.i1);
SUBFRA = 0.f;
sipo->cursorVal = ked.f2 / (float)ked.i1;
}
@@ -2066,7 +2066,7 @@ void GRAPH_OT_frame_jump(wmOperatorType *ot)
/* ******************** Snap Keyframes Operator *********************** */
/* defines for snap keyframes tool */
-static EnumPropertyItem prop_graphkeys_snap_types[] = {
+static const EnumPropertyItem prop_graphkeys_snap_types[] = {
{GRAPHKEYS_SNAP_CFRA, "CFRA", 0, "Current Frame",
"Snap selected keyframes to the current frame"},
{GRAPHKEYS_SNAP_VALUE, "VALUE", 0, "Cursor Value",
@@ -2195,7 +2195,7 @@ void GRAPH_OT_snap(wmOperatorType *ot)
/* ******************** Mirror Keyframes Operator *********************** */
/* defines for mirror keyframes tool */
-static EnumPropertyItem prop_graphkeys_mirror_types[] = {
+static const EnumPropertyItem prop_graphkeys_mirror_types[] = {
{GRAPHKEYS_MIRROR_CFRA, "CFRA", 0, "By Times over Current Frame",
"Flip times of selected keyframes using the current frame as the mirror line"},
{GRAPHKEYS_MIRROR_VALUE, "VALUE", 0, "By Values over Cursor Value",
@@ -2386,7 +2386,7 @@ void GRAPH_OT_smooth(wmOperatorType *ot)
/* ******************** Add F-Modifier Operator *********************** */
-static EnumPropertyItem *graph_fmodifier_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *graph_fmodifier_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
int totitem = 0;
@@ -2446,7 +2446,7 @@ static int graph_fmodifier_add_exec(bContext *C, wmOperator *op)
FModifier *fcm;
/* add F-Modifier of specified type to active F-Curve, and make it the active one */
- fcm = add_fmodifier(&fcu->modifiers, type);
+ fcm = add_fmodifier(&fcu->modifiers, type, fcu);
if (fcm) {
set_active_fmodifier(&fcu->modifiers, fcm);
}
@@ -2582,7 +2582,7 @@ static int graph_fmodifier_paste_exec(bContext *C, wmOperator *op)
FCurve *fcu = (FCurve *)ale->data;
int tot;
- tot = ANIM_fmodifiers_paste_from_buf(&fcu->modifiers, replace);
+ tot = ANIM_fmodifiers_paste_from_buf(&fcu->modifiers, replace, fcu);
if (tot) {
ale->update |= ANIM_UPDATE_DEPS;
@@ -2746,3 +2746,89 @@ void GRAPH_OT_driver_variables_paste(wmOperatorType *ot)
}
/* ************************************************************************** */
+
+static int graph_driver_delete_invalid_exec(bContext *C, wmOperator *op)
+{
+ bAnimContext ac;
+ ListBase anim_data = {NULL, NULL};
+ bAnimListElem *ale;
+ int filter;
+ bool ok = false;
+ unsigned int deleted = 0;
+
+ /* get editor data */
+ if (ANIM_animdata_get_context(C, &ac) == 0)
+ return OPERATOR_CANCELLED;
+
+ /* NOTE: we might need a scene update to evaluate the driver flags */
+
+ /* filter data */
+ filter = (ANIMFILTER_DATA_VISIBLE | ANIMFILTER_CURVE_VISIBLE | ANIMFILTER_NODUPLIS);
+ ANIM_animdata_filter(&ac, &anim_data, filter, ac.data, ac.datatype);
+
+ /* find invalid drivers */
+ for (ale = anim_data.first; ale; ale = ale->next) {
+ FCurve *fcu = (FCurve *)ale->data;
+ if (ELEM(NULL, fcu, fcu->driver)) {
+ continue;
+ }
+ if (!(fcu->driver->flag & DRIVER_FLAG_INVALID)) {
+ continue;
+ }
+
+ ok |= ANIM_remove_driver(op->reports, ale->id, fcu->rna_path, fcu->array_index, 0);
+ if (!ok) {
+ break;
+ }
+ deleted += 1;
+ }
+
+ /* cleanup */
+ ANIM_animdata_freelist(&anim_data);
+
+ if (deleted > 0) {
+ /* notify the world of any changes */
+ DAG_relations_tag_update(CTX_data_main(C));
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_REMOVED, NULL);
+ WM_reportf(RPT_INFO, "Deleted %u drivers", deleted);
+ }
+ else {
+ WM_report(RPT_INFO, "No drivers deleted");
+ }
+
+ /* successful or not? */
+ if (!ok) {
+ return OPERATOR_CANCELLED;
+ }
+
+ return OPERATOR_FINISHED;
+}
+
+static int graph_driver_delete_invalid_poll(bContext *C)
+{
+ bAnimContext ac;
+ ScrArea *sa = CTX_wm_area(C);
+
+ /* firstly, check if in Graph Editor */
+ if ((sa == NULL) || (sa->spacetype != SPACE_IPO))
+ return 0;
+
+ /* try to init Anim-Context stuff ourselves and check */
+ return ANIM_animdata_get_context(C, &ac) != 0;
+}
+
+
+void GRAPH_OT_driver_delete_invalid(wmOperatorType *ot)
+{
+ /* identifiers */
+ ot->name = "Delete Invalid Drivers";
+ ot->idname = "GRAPH_OT_driver_delete_invalid";
+ ot->description = "Delete all visible drivers considered invalid";
+
+ /* api callbacks */
+ ot->exec = graph_driver_delete_invalid_exec;
+ ot->poll = graph_driver_delete_invalid_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+}
diff --git a/source/blender/editors/space_graph/graph_intern.h b/source/blender/editors/space_graph/graph_intern.h
index 534b712fd5e..6c375b23352 100644
--- a/source/blender/editors/space_graph/graph_intern.h
+++ b/source/blender/editors/space_graph/graph_intern.h
@@ -152,6 +152,7 @@ void GRAPH_OT_fmodifier_paste(struct wmOperatorType *ot);
void GRAPH_OT_driver_variables_copy(struct wmOperatorType *ot);
void GRAPH_OT_driver_variables_paste(struct wmOperatorType *ot);
+void GRAPH_OT_driver_delete_invalid(struct wmOperatorType *ot);
/* ----------- */
diff --git a/source/blender/editors/space_graph/graph_ops.c b/source/blender/editors/space_graph/graph_ops.c
index 75f0da83e77..57d8f45905d 100644
--- a/source/blender/editors/space_graph/graph_ops.c
+++ b/source/blender/editors/space_graph/graph_ops.c
@@ -94,7 +94,7 @@ static void graphview_cursor_apply(bContext *C, wmOperator *op)
* NOTE: sync this part of the code with ANIM_OT_change_frame
*/
/* 1) frame is rounded to the nearest int, since frames are ints */
- CFRA = iroundf(frame);
+ CFRA = round_fl_to_int(frame);
if (scene->r.flag & SCER_LOCK_FRAME_SELECTION) {
/* Clip to preview range
@@ -333,13 +333,14 @@ static void GRAPH_OT_hide(wmOperatorType *ot)
/* ........ */
-static int graphview_curves_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int graphview_curves_reveal_exec(bContext *C, wmOperator *op)
{
bAnimContext ac;
ListBase anim_data = {NULL, NULL};
ListBase all_data = {NULL, NULL};
bAnimListElem *ale;
int filter;
+ const bool select = RNA_boolean_get(op->ptr, "select");
/* get editor data */
if (ANIM_animdata_get_context(C, &ac) == 0)
@@ -364,8 +365,11 @@ static int graphview_curves_reveal_exec(bContext *C, wmOperator *UNUSED(op))
continue;
/* select if it is not visible */
- if (ANIM_channel_setting_get(&ac, ale, ACHANNEL_SETTING_VISIBLE) == 0)
- ANIM_channel_setting_set(&ac, ale, ACHANNEL_SETTING_SELECT, ACHANNEL_SETFLAG_ADD);
+ if (ANIM_channel_setting_get(&ac, ale, ACHANNEL_SETTING_VISIBLE) == 0) {
+ ANIM_channel_setting_set(
+ &ac, ale, ACHANNEL_SETTING_SELECT,
+ select ? ACHANNEL_SETFLAG_ADD : ACHANNEL_SETFLAG_CLEAR);
+ }
/* change the visibility setting */
ANIM_channel_setting_set(&ac, ale, ACHANNEL_SETTING_VISIBLE, ACHANNEL_SETFLAG_ADD);
@@ -397,6 +401,8 @@ static void GRAPH_OT_reveal(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
/* ************************** registration - operator types **********************************/
@@ -462,6 +468,7 @@ void graphedit_operatortypes(void)
/* Drivers */
WM_operatortype_append(GRAPH_OT_driver_variables_copy);
WM_operatortype_append(GRAPH_OT_driver_variables_paste);
+ WM_operatortype_append(GRAPH_OT_driver_delete_invalid);
}
void ED_operatormacros_graph(void)
diff --git a/source/blender/editors/space_graph/graph_select.c b/source/blender/editors/space_graph/graph_select.c
index 67b960bfa53..0b7ce7d7310 100644
--- a/source/blender/editors/space_graph/graph_select.c
+++ b/source/blender/editors/space_graph/graph_select.c
@@ -37,7 +37,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "DNA_anim_types.h"
#include "DNA_screen_types.h"
@@ -332,25 +332,27 @@ static int graphkeys_borderselect_exec(bContext *C, wmOperator *op)
rctf rect_fl;
short mode = 0, selectmode = 0;
bool incl_handles;
- bool extend;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* get editor data */
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
/* clear all selection if not extending selection */
- extend = RNA_boolean_get(op->ptr, "extend");
+
if (!extend)
deselect_graph_keys(&ac, 1, SELECT_SUBTRACT, true);
/* get select mode
- * - 'gesture_mode' from the operator specifies how to select
* - 'include_handles' from the operator specifies whether to include handles in the selection
*/
- if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT)
+ if (select) {
selectmode = SELECT_ADD;
- else
+ }
+ else {
selectmode = SELECT_SUBTRACT;
+ }
incl_handles = RNA_boolean_get(op->ptr, "include_handles");
@@ -391,10 +393,10 @@ void GRAPH_OT_select_border(wmOperatorType *ot)
ot->description = "Select all keyframes within the specified region";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = graphkeys_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = graphop_visible_keyframes_poll;
@@ -402,7 +404,7 @@ void GRAPH_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
ot->prop = RNA_def_boolean(ot->srna, "axis_range", 0, "Axis Range", "");
RNA_def_boolean(ot->srna, "include_handles", 0, "Include Handles", "Are handles tested individually against the selection criteria");
@@ -486,9 +488,7 @@ void GRAPH_OT_select_lasso(wmOperatorType *ot)
ot->flag = OPTYPE_UNDO;
/* properties */
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend selection instead of deselecting everything first");
+ WM_operator_properties_gesture_lasso_select(ot);
}
/* ------------------- */
@@ -496,8 +496,8 @@ void GRAPH_OT_select_lasso(wmOperatorType *ot)
static int graph_circle_select_exec(bContext *C, wmOperator *op)
{
bAnimContext ac;
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const short selectmode = (gesture_mode == GESTURE_MODAL_SELECT) ? SELECT_ADD : SELECT_SUBTRACT;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const short selectmode = select ? SELECT_ADD : SELECT_SUBTRACT;
bool incl_handles = false;
KeyframeEdit_CircleData data = {0};
@@ -555,11 +555,9 @@ void GRAPH_OT_select_circle(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
-
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Event Type", "", INT_MIN, INT_MAX);
+
+ /* properties */
+ WM_operator_properties_gesture_circle_select(ot);
}
/* ******************** Column Select Operator **************************** */
@@ -571,7 +569,7 @@ void GRAPH_OT_select_circle(wmOperatorType *ot)
*/
/* defines for column-select mode */
-static EnumPropertyItem prop_column_select_types[] = {
+static const EnumPropertyItem prop_column_select_types[] = {
{GRAPHKEYS_COLUMNSEL_KEYS, "KEYS", 0, "On Selected Keyframes", ""},
{GRAPHKEYS_COLUMNSEL_CFRA, "CFRA", 0, "On Current Frame", ""},
{GRAPHKEYS_COLUMNSEL_MARKERS_COLUMN, "MARKERS_COLUMN", 0, "On Selected Markers", ""},
@@ -916,7 +914,7 @@ void GRAPH_OT_select_less(wmOperatorType *ot)
/* Select keyframes left/right of the current frame indicator */
/* defines for left-right select tool */
-static EnumPropertyItem prop_graphkeys_leftright_select_types[] = {
+static const EnumPropertyItem prop_graphkeys_leftright_select_types[] = {
{GRAPHKEYS_LRSEL_TEST, "CHECK", 0, "Check if Select Left or Right", ""},
{GRAPHKEYS_LRSEL_LEFT, "LEFT", 0, "Before current frame", ""},
{GRAPHKEYS_LRSEL_RIGHT, "RIGHT", 0, "After current frame", ""},
@@ -1005,7 +1003,8 @@ static int graphkeys_select_leftright_exec(bContext *C, wmOperator *op)
graphkeys_select_leftright(&ac, leftright, selectmode);
/* set notifier that keyframe selection (and channels too) have changed */
- WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | ND_ANIMCHAN | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
return OPERATOR_FINISHED;
}
@@ -1087,6 +1086,8 @@ typedef struct tNearestVertInfo {
int dist; /* distance from mouse to vert */
eAnim_ChannelType ctype; /* type of animation channel this FCurve comes from */
+
+ float frame; /* frame that point was on when it matched (global time) */
} tNearestVertInfo;
/* Tags for the type of graph vert that we have */
@@ -1153,6 +1154,8 @@ static void nearest_fcurve_vert_store(
nvi->hpoint = hpoint;
nvi->dist = dist;
+ nvi->frame = bezt->vec[1][0]; /* currently in global time... */
+
nvi->sel = BEZT_ISSEL_ANY(bezt); // XXX... should this use the individual verts instead?
/* add to list of matches if appropriate... */
@@ -1437,10 +1440,7 @@ static void graphkeys_mselect_column(bAnimContext *ac, const int mval[2], short
/* get frame number on which elements should be selected */
// TODO: should we restrict to integer frames only?
- if (nvi->bezt)
- selx = nvi->bezt->vec[1][0];
- else if (nvi->fpt)
- selx = nvi->fpt->vec[0];
+ selx = nvi->frame;
/* if select mode is replace, deselect all keyframes first */
if (select_mode == SELECT_REPLACE) {
@@ -1518,7 +1518,8 @@ static int graphkeys_clickselect_invoke(bContext *C, wmOperator *op, const wmEve
}
/* set notifier that keyframe selection (and also channel selection in some cases) has changed */
- WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | ND_ANIMCHAN | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
/* for tweak grab to work */
return OPERATOR_FINISHED | OPERATOR_PASS_THROUGH;
diff --git a/source/blender/editors/space_graph/graph_utils.c b/source/blender/editors/space_graph/graph_utils.c
index 0e56dc817e4..907f346c931 100644
--- a/source/blender/editors/space_graph/graph_utils.c
+++ b/source/blender/editors/space_graph/graph_utils.c
@@ -171,8 +171,8 @@ int graphop_editable_keyframes_poll(bContext *C)
/* editable curves must fulfill the following criteria:
* - it has bezier keyframes
- * - it must not be protected from editing (this is already checked for with the foredit flag
- * - F-Curve modifiers do not interfere with the result too much
+ * - it must not be protected from editing (this is already checked for with the edit flag
+ * - F-Curve modifiers do not interfere with the result too much
* (i.e. the modifier-control drawing check returns false)
*/
if (fcu->bezt == NULL)
diff --git a/source/blender/editors/space_graph/space_graph.c b/source/blender/editors/space_graph/space_graph.c
index f12db310856..362bd284105 100644
--- a/source/blender/editors/space_graph/space_graph.c
+++ b/source/blender/editors/space_graph/space_graph.c
@@ -682,13 +682,14 @@ static void graph_refresh(const bContext *C, ScrArea *sa)
static void graph_id_remap(ScrArea *UNUSED(sa), SpaceLink *slink, ID *old_id, ID *new_id)
{
SpaceIpo *sgraph = (SpaceIpo *)slink;
-
- if (!ELEM(GS(old_id->name), ID_GR)) {
- return;
- }
-
- if (sgraph->ads && (ID *)sgraph->ads->filter_grp == old_id) {
- sgraph->ads->filter_grp = (Group *)new_id;
+
+ if (sgraph->ads) {
+ if ((ID *)sgraph->ads->filter_grp == old_id) {
+ sgraph->ads->filter_grp = (Group *)new_id;
+ }
+ if ((ID *)sgraph->ads->source == old_id) {
+ sgraph->ads->source = new_id;
+ }
}
}
diff --git a/source/blender/editors/space_image/image_buttons.c b/source/blender/editors/space_image/image_buttons.c
index b9d98dfe794..c105f40f1d6 100644
--- a/source/blender/editors/space_image/image_buttons.c
+++ b/source/blender/editors/space_image/image_buttons.c
@@ -403,16 +403,6 @@ final:
BKE_image_release_renderresult(scene, image);
}
-static const char *ui_imageuser_pass_fake_name(RenderLayer *rl)
-{
- if (rl == NULL) {
- return IFACE_("Combined");
- }
- else {
- return NULL;
- }
-}
-
static void ui_imageuser_pass_menu(bContext *UNUSED(C), uiLayout *layout, void *rnd_pt)
{
struct ImageUI_Data *rnd_data = rnd_pt;
@@ -424,11 +414,8 @@ static void ui_imageuser_pass_menu(bContext *UNUSED(C), uiLayout *layout, void *
Scene *scene = iuser->scene;
RenderResult *rr;
RenderLayer *rl;
- RenderPass rpass_fake = {NULL};
RenderPass *rpass;
- const char *fake_name;
int nr;
- int passflag = 0;
/* may have been freed since drawing */
rr = BKE_image_acquire_renderresult(scene, image);
@@ -446,35 +433,25 @@ static void ui_imageuser_pass_menu(bContext *UNUSED(C), uiLayout *layout, void *
uiItemS(layout);
- nr = 0;
- fake_name = ui_imageuser_pass_fake_name(rl);
+ nr = (rl == NULL) ? 1 : 0;
- if (fake_name) {
- BLI_strncpy(rpass_fake.internal_name, fake_name, sizeof(rpass_fake.internal_name));
- nr += 1;
- }
+ ListBase added_passes;
+ BLI_listbase_clear(&added_passes);
/* rendered results don't have a Combined pass */
/* multiview: the ordering must be ascending, so the left-most pass is always the one picked */
for (rpass = rl ? rl->passes.first : NULL; rpass; rpass = rpass->next, nr++) {
-
/* just show one pass of each kind */
- if (passflag & rpass->passtype)
+ if (BLI_findstring_ptr(&added_passes, rpass->name, offsetof(LinkData, data))) {
continue;
+ }
+ BLI_addtail(&added_passes, BLI_genericNodeN(rpass->name));
- passflag |= rpass->passtype;
-
-final:
- uiDefButS(block, UI_BTYPE_BUT_MENU, B_NOP, IFACE_(rpass->internal_name), 0, 0,
+ uiDefButS(block, UI_BTYPE_BUT_MENU, B_NOP, IFACE_(rpass->name), 0, 0,
UI_UNIT_X * 5, UI_UNIT_X, &iuser->pass, (float) nr, 0.0, 0, -1, "");
}
- if (fake_name) {
- fake_name = NULL;
- rpass = &rpass_fake;
- nr = 0;
- goto final;
- }
+ BLI_freelistN(&added_passes);
BKE_image_release_renderresult(scene, image);
}
@@ -571,7 +548,7 @@ static bool ui_imageuser_layer_menu_step(bContext *C, int direction, void *rnd_p
else if (direction == 1) {
int tot = BLI_listbase_count(&rr->layers);
- if (RE_HasFakeLayer(rr))
+ if (RE_HasCombinedLayer(rr))
tot++; /* fake compo/sequencer layer */
if (iuser->layer < tot - 1) {
@@ -611,7 +588,7 @@ static bool ui_imageuser_pass_menu_step(bContext *C, int direction, void *rnd_pt
return false;
}
- if (RE_HasFakeLayer(rr)) {
+ if (RE_HasCombinedLayer(rr)) {
layer -= 1;
}
@@ -633,7 +610,7 @@ static bool ui_imageuser_pass_menu_step(bContext *C, int direction, void *rnd_pt
int rp_index = iuser->pass + 1;
for (rp = rpass->next; rp; rp = rp->next, rp_index++) {
- if (rp->passtype != rpass->passtype) {
+ if (!STREQ(rp->name, rpass->name)) {
iuser->pass = rp_index;
changed = true;
break;
@@ -650,7 +627,7 @@ static bool ui_imageuser_pass_menu_step(bContext *C, int direction, void *rnd_pt
}
for (rp = rl->passes.first; rp; rp = rp->next, rp_index++) {
- if (rp->passtype == rpass->passtype) {
+ if (STREQ(rp->name, rpass->name)) {
iuser->pass = rp_index - 1;
changed = true;
break;
@@ -712,6 +689,10 @@ static void uiblock_layer_pass_buttons(
const char *display_name = "";
const bool show_stereo = (iuser->flag & IMA_SHOW_STEREO) != 0;
+ if (iuser->scene == NULL) {
+ return;
+ }
+
uiLayoutRow(layout, true);
/* layer menu is 1/3 larger than pass */
@@ -766,21 +747,22 @@ static void uiblock_layer_pass_buttons(
}
/* pass */
- fake_name = ui_imageuser_pass_fake_name(rl);
- rpass = (rl ? BLI_findlink(&rl->passes, iuser->pass - (fake_name ? 1 : 0)) : NULL);
+ rpass = (rl ? BLI_findlink(&rl->passes, iuser->pass) : NULL);
- display_name = rpass ? rpass->internal_name : (fake_name ? fake_name : "");
- rnd_pt = ui_imageuser_data_copy(&rnd_pt_local);
- but = uiDefMenuBut(
- block, ui_imageuser_pass_menu, rnd_pt, IFACE_(display_name),
- 0, 0, wmenu3, UI_UNIT_Y, TIP_("Select Pass"));
- UI_but_func_menu_step_set(but, ui_imageuser_pass_menu_step);
- UI_but_funcN_set(but, image_multi_cb, rnd_pt, rr);
- UI_but_type_set_menu_from_pulldown(but);
- rnd_pt = NULL;
+ if (rpass && RE_passes_have_name(rl)) {
+ display_name = rpass->name;
+ rnd_pt = ui_imageuser_data_copy(&rnd_pt_local);
+ but = uiDefMenuBut(
+ block, ui_imageuser_pass_menu, rnd_pt, IFACE_(display_name),
+ 0, 0, wmenu3, UI_UNIT_Y, TIP_("Select Pass"));
+ UI_but_func_menu_step_set(but, ui_imageuser_pass_menu_step);
+ UI_but_funcN_set(but, image_multi_cb, rnd_pt, rr);
+ UI_but_type_set_menu_from_pulldown(but);
+ rnd_pt = NULL;
+ }
/* view */
- if (BLI_listbase_count_ex(&rr->views, 2) > 1 &&
+ if (BLI_listbase_count_at_most(&rr->views, 2) > 1 &&
((!show_stereo) || (!RE_RenderResult_is_stereo(rr))))
{
rview = BLI_findlink(&rr->views, iuser->view);
@@ -889,8 +871,11 @@ void uiTemplateImage(uiLayout *layout, bContext *C, PointerRNA *ptr, const char
uiLayoutSetContextPointer(layout, "edit_image", &imaptr);
uiLayoutSetContextPointer(layout, "edit_image_user", userptr);
- if (!compact)
- uiTemplateID(layout, C, ptr, propname, ima ? NULL : "IMAGE_OT_new", "IMAGE_OT_open", NULL);
+ if (!compact) {
+ uiTemplateID(
+ layout, C, ptr, propname,
+ ima ? NULL : "IMAGE_OT_new", "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
+ }
if (ima) {
UI_block_funcN_set(block, rna_update_cb, MEM_dupallocN(cb), NULL);
@@ -1130,7 +1115,7 @@ void uiTemplateImageSettings(uiLayout *layout, PointerRNA *imfptr, int color_man
uiItemR(row, imfptr, "use_zbuffer", 0, NULL, ICON_NONE);
}
- if (is_render_out && (imf->imtype == R_IMF_IMTYPE_OPENEXR)) {
+ if (is_render_out && ELEM(imf->imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER)) {
show_preview = true;
uiItemR(row, imfptr, "use_preview", 0, NULL, ICON_NONE);
}
@@ -1204,7 +1189,7 @@ void uiTemplateImageStereo3d(uiLayout *layout, PointerRNA *stereo3d_format_ptr)
case S3D_DISPLAY_SIDEBYSIDE:
{
uiItemR(col, stereo3d_format_ptr, "use_sidebyside_crosseyed", 0, NULL, ICON_NONE);
- /* fall-through */
+ ATTR_FALLTHROUGH;
}
case S3D_DISPLAY_TOPBOTTOM:
{
diff --git a/source/blender/editors/space_image/image_draw.c b/source/blender/editors/space_image/image_draw.c
index e810f4db7dd..594938b82aa 100644
--- a/source/blender/editors/space_image/image_draw.c
+++ b/source/blender/editors/space_image/image_draw.c
@@ -88,7 +88,7 @@ static void draw_render_info(const bContext *C,
float zoomy)
{
RenderResult *rr;
- Render *re = RE_GetRender(scene->id.name);
+ Render *re = RE_GetSceneRender(scene);
RenderData *rd = RE_engine_get_render_data(re);
Scene *stats_scene = ED_render_job_get_scene(C);
if (stats_scene == NULL) {
@@ -360,11 +360,11 @@ void ED_image_draw_info(Scene *scene, ARegion *ar, bool color_manage, bool use_d
if (channels == 1) {
if (fp) {
rgb_to_hsv(fp[0], fp[0], fp[0], &hue, &sat, &val);
- rgb_to_yuv(fp[0], fp[0], fp[0], &lum, &u, &v);
+ rgb_to_yuv(fp[0], fp[0], fp[0], &lum, &u, &v, BLI_YUV_ITU_BT709);
}
else if (cp) {
rgb_to_hsv((float)cp[0] / 255.0f, (float)cp[0] / 255.0f, (float)cp[0] / 255.0f, &hue, &sat, &val);
- rgb_to_yuv((float)cp[0] / 255.0f, (float)cp[0] / 255.0f, (float)cp[0] / 255.0f, &lum, &u, &v);
+ rgb_to_yuv((float)cp[0] / 255.0f, (float)cp[0] / 255.0f, (float)cp[0] / 255.0f, &lum, &u, &v, BLI_YUV_ITU_BT709);
}
BLI_snprintf(str, sizeof(str), "V:%-.4f", val);
@@ -379,7 +379,7 @@ void ED_image_draw_info(Scene *scene, ARegion *ar, bool color_manage, bool use_d
}
else if (channels >= 3) {
rgb_to_hsv(finalcol[0], finalcol[1], finalcol[2], &hue, &sat, &val);
- rgb_to_yuv(finalcol[0], finalcol[1], finalcol[2], &lum, &u, &v);
+ rgb_to_yuv(finalcol[0], finalcol[1], finalcol[2], &lum, &u, &v, BLI_YUV_ITU_BT709);
BLI_snprintf(str, sizeof(str), "H:%-.4f", hue);
BLF_position(blf_mono_font, dx, dy, 0);
@@ -881,7 +881,7 @@ void draw_image_main(const bContext *C, ARegion *ar)
* other images are not modifying in such a way so they does not require
* lock (sergey)
*/
- BLI_lock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_lock(LOCK_DRAW_IMAGE);
}
if (show_stereo3d) {
@@ -942,7 +942,7 @@ void draw_image_main(const bContext *C, ARegion *ar)
#endif
if (show_viewer) {
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
}
/* render info */
diff --git a/source/blender/editors/space_image/image_edit.c b/source/blender/editors/space_image/image_edit.c
index 8f2f6595408..9d7944a25d3 100644
--- a/source/blender/editors/space_image/image_edit.c
+++ b/source/blender/editors/space_image/image_edit.c
@@ -365,7 +365,7 @@ bool ED_space_image_show_uvedit(SpaceImage *sima, Object *obedit)
struct BMEditMesh *em = BKE_editmesh_from_object(obedit);
bool ret;
- ret = EDBM_mtexpoly_check(em);
+ ret = EDBM_uv_check(em);
return ret;
}
diff --git a/source/blender/editors/space_image/image_ops.c b/source/blender/editors/space_image/image_ops.c
index 324a3cb13b7..e14e7820403 100644
--- a/source/blender/editors/space_image/image_ops.c
+++ b/source/blender/editors/space_image/image_ops.c
@@ -1000,7 +1000,7 @@ static int image_view_zoom_border_exec(bContext *C, wmOperator *op)
SpaceImage *sima = CTX_wm_space_image(C);
ARegion *ar = CTX_wm_region(C);
rctf bounds;
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool zoom_in = !RNA_boolean_get(op->ptr, "zoom_out");
WM_operator_properties_border_to_rctf(op, &bounds);
@@ -1019,7 +1019,7 @@ static int image_view_zoom_border_exec(bContext *C, wmOperator *op)
sima_zoom_set_from_bounds(sima, ar, &bounds);
/* zoom out */
- if (gesture_mode == GESTURE_MODAL_OUT) {
+ if (!zoom_in) {
sima->xof = sima_view_prev.xof + (sima->xof - sima_view_prev.xof);
sima->yof = sima_view_prev.yof + (sima->yof - sima_view_prev.yof);
sima->zoom = sima_view_prev.zoom * (sima_view_prev.zoom / sima->zoom);
@@ -1038,15 +1038,15 @@ void IMAGE_OT_view_zoom_border(wmOperatorType *ot)
ot->idname = "IMAGE_OT_view_zoom_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = image_view_zoom_border_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = space_image_main_region_poll;
/* rna */
- WM_operator_properties_gesture_border(ot, false);
+ WM_operator_properties_gesture_border_zoom(ot);
}
/**************** load/replace/save callbacks ******************/
@@ -1067,6 +1067,7 @@ typedef struct ImageOpenData {
typedef struct ImageFrameRange {
struct ImageFrameRange *next, *prev;
ListBase frames;
+ /** The full path of the first file in the list of image files */
char filepath[FILE_MAX];
} ImageFrameRange;
@@ -1092,12 +1093,12 @@ static void image_open_cancel(bContext *UNUSED(C), wmOperator *op)
/**
* \brief Get a list of frames from the list of image files matching the first file name sequence pattern
* \param ptr [in] the RNA pointer containing the "directory" entry and "files" collection
- * \param frames [out] the list of frame numbers found in the files matching the first one by name
- * \param path [out] the full path of the first file in the list of image files
+ * \param frames_all [out] the list of frame numbers found in the files matching the first one by name
*/
static void image_sequence_get_frame_ranges(PointerRNA *ptr, ListBase *frames_all)
{
char dir[FILE_MAXDIR];
+ const bool do_frame_range = RNA_boolean_get(ptr, "use_sequence_detection");
ImageFrameRange *frame_range = NULL;
RNA_string_get(ptr, "directory", dir);
@@ -1113,7 +1114,8 @@ static void image_sequence_get_frame_ranges(PointerRNA *ptr, ListBase *frames_al
frame->framenr = BLI_stringdec(filename, head, tail, &digits);
/* still in the same sequence */
- if ((frame_range != NULL) &&
+ if (do_frame_range &&
+ (frame_range != NULL) &&
(STREQLEN(base_head, head, FILE_MAX)) &&
(STREQLEN(base_tail, tail, FILE_MAX)))
{
@@ -1146,9 +1148,10 @@ static int image_cmp_frame(const void *a, const void *b)
}
/**
- * \brief Return the start (offset) and the length of the sequence of continuous frames in the list of frames
- * \param frames [in] the list of frame numbers, as a side-effect the list is sorted
- * \param ofs [out] offest, the first frame number in the sequence
+ * Return the start (offset) and the length of the sequence of continuous frames in the list of frames
+ *
+ * \param frames: [in] the list of frame numbers, as a side-effect the list is sorted.
+ * \param ofs: [out] offset the first frame number in the sequence.
* \return the number of contiguous frames in the sequence
*/
static int image_sequence_get_len(ListBase *frames, int *ofs)
@@ -1167,6 +1170,7 @@ static int image_sequence_get_len(ListBase *frames, int *ofs)
}
return frame_curr - (*ofs);
}
+ *ofs = 0;
return 0;
}
@@ -1298,12 +1302,12 @@ static int image_open_exec(bContext *C, wmOperator *op)
if (iod->iuser) {
iuser = iod->iuser;
}
- else if (sa->spacetype == SPACE_IMAGE) {
+ else if (sa && sa->spacetype == SPACE_IMAGE) {
SpaceImage *sima = sa->spacedata.first;
ED_space_image_set(sima, scene, obedit, ima);
iuser = &sima->iuser;
}
- else if (sa->spacetype == SPACE_VIEW3D) {
+ else if (sa && sa->spacetype == SPACE_VIEW3D) {
View3D *v3d = sa->spacedata.first;
for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
@@ -1325,7 +1329,12 @@ static int image_open_exec(bContext *C, wmOperator *op)
iuser->frames = frame_seq_len;
iuser->sfra = 1;
iuser->framenr = 1;
- iuser->offset = frame_ofs - 1;
+ if (ima->source == IMA_SRC_MOVIE) {
+ iuser->offset = 0;
+ }
+ else {
+ iuser->offset = frame_ofs - 1;
+ }
iuser->fie_ima = 2;
iuser->scene = scene;
BKE_image_init_imageuser(ima, iuser);
@@ -1448,6 +1457,9 @@ void IMAGE_OT_open(wmOperatorType *ot)
ot, FILE_TYPE_FOLDER | FILE_TYPE_IMAGE | FILE_TYPE_MOVIE, FILE_SPECIAL, FILE_OPENFILE,
WM_FILESEL_FILEPATH | WM_FILESEL_DIRECTORY | WM_FILESEL_FILES | WM_FILESEL_RELPATH,
FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
+
+ RNA_def_boolean(ot->srna, "use_sequence_detection", true, "Detect Sequences",
+ "Automatically detect animated sequences in selected images (based on file names)");
}
/******************** Match movie length operator ********************/
@@ -1813,9 +1825,6 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
const bool save_as_render = (RNA_struct_find_property(op->ptr, "save_as_render") && RNA_boolean_get(op->ptr, "save_as_render"));
ImageFormatData *imf = &simopts->im_format;
- const bool is_multilayer = imf->imtype == R_IMF_IMTYPE_MULTILAYER;
- bool is_mono;
-
/* old global to ensure a 2nd save goes to same dir */
BLI_strncpy(G.ima, simopts->filepath, sizeof(G.ima));
@@ -1842,7 +1851,8 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
/* we need renderresult for exr and rendered multiview */
scene = CTX_data_scene(C);
rr = BKE_image_acquire_renderresult(scene, ima);
- is_mono = rr ? BLI_listbase_count_ex(&rr->views, 2) < 2 : BLI_listbase_count_ex(&ima->views, 2) < 2;
+ bool is_mono = rr ? BLI_listbase_count_at_most(&rr->views, 2) < 2 : BLI_listbase_count_at_most(&ima->views, 2) < 2;
+ bool is_exr_rr = rr && ELEM(imf->imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) && RE_HasFloatPixels(rr);
/* error handling */
if (!rr) {
@@ -1872,29 +1882,23 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
}
/* fancy multiview OpenEXR */
- if ((imf->imtype == R_IMF_IMTYPE_MULTILAYER) && (imf->views_format == R_IMF_VIEWS_MULTIVIEW)) {
- ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, true, NULL);
+ if (imf->views_format == R_IMF_VIEWS_MULTIVIEW && is_exr_rr) {
+ /* save render result */
+ ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, NULL, sima->iuser.layer);
save_image_post(op, ibuf, ima, ok, true, relbase, relative, do_newpath, simopts->filepath);
ED_space_image_release_buffer(sima, ibuf, lock);
}
- else if ((imf->imtype == R_IMF_IMTYPE_OPENEXR) && (imf->views_format == R_IMF_VIEWS_MULTIVIEW)) {
- /* treat special Openexr case separetely (this is the singlelayer multiview OpenEXR */
- BKE_imbuf_write_prepare(ibuf, imf);
- ok = BKE_image_save_openexr_multiview(ima, ibuf, simopts->filepath, (IB_rect | IB_zbuf | IB_zbuffloat | IB_multiview));
- ED_space_image_release_buffer(sima, ibuf, lock);
- }
/* regular mono pipeline */
else if (is_mono) {
- if (is_multilayer) {
- ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, false, NULL);
+ if (is_exr_rr) {
+ ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, NULL, -1);
}
else {
colormanaged_ibuf = IMB_colormanagement_imbuf_for_write(ibuf, save_as_render, true, &imf->view_settings, &imf->display_settings, imf);
- IMB_metadata_copy(colormanaged_ibuf, ibuf);
ok = BKE_imbuf_write_as(colormanaged_ibuf, simopts->filepath, imf, save_copy);
save_imbuf_post(ibuf, colormanaged_ibuf);
}
- save_image_post(op, ibuf, ima, ok, (is_multilayer ? true : save_copy), relbase, relative, do_newpath, simopts->filepath);
+ save_image_post(op, ibuf, ima, ok, (is_exr_rr ? true : save_copy), relbase, relative, do_newpath, simopts->filepath);
ED_space_image_release_buffer(sima, ibuf, lock);
}
/* individual multiview images */
@@ -1903,7 +1907,7 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
unsigned char planes = ibuf->planes;
const int totviews = (rr ? BLI_listbase_count(&rr->views) : BLI_listbase_count(&ima->views));
- if (!is_multilayer) {
+ if (!is_exr_rr) {
ED_space_image_release_buffer(sima, ibuf, lock);
}
@@ -1913,9 +1917,9 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
const char *view = rr ? ((RenderView *) BLI_findlink(&rr->views, i))->name :
((ImageView *) BLI_findlink(&ima->views, i))->name;
- if (is_multilayer) {
+ if (is_exr_rr) {
BKE_scene_multiview_view_filepath_get(&scene->r, simopts->filepath, view, filepath);
- ok_view = RE_WriteRenderResult(op->reports, rr, filepath, imf, false, view);
+ ok_view = RE_WriteRenderResult(op->reports, rr, filepath, imf, view, -1);
save_image_post(op, ibuf, ima, ok_view, true, relbase, relative, do_newpath, filepath);
}
else {
@@ -1943,14 +1947,14 @@ static bool save_image_doit(bContext *C, SpaceImage *sima, wmOperator *op, SaveI
ok &= ok_view;
}
- if (is_multilayer) {
+ if (is_exr_rr) {
ED_space_image_release_buffer(sima, ibuf, lock);
}
}
/* stereo (multiview) images */
else if (simopts->im_format.views_format == R_IMF_VIEWS_STEREO_3D) {
if (imf->imtype == R_IMF_IMTYPE_MULTILAYER) {
- ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, false, NULL);
+ ok = RE_WriteRenderResult(op->reports, rr, simopts->filepath, imf, NULL, -1);
save_image_post(op, ibuf, ima, ok, true, relbase, relative, do_newpath, simopts->filepath);
ED_space_image_release_buffer(sima, ibuf, lock);
}
@@ -2376,8 +2380,8 @@ static int image_new_exec(bContext *C, wmOperator *op)
Main *bmain;
PointerRNA ptr, idptr;
PropertyRNA *prop;
- char _name[MAX_ID_NAME - 2];
- char *name = _name;
+ char name_buffer[MAX_ID_NAME - 2];
+ const char *name;
float color[4];
int width, height, floatbuf, gen_type, alpha;
int gen_context;
@@ -2390,10 +2394,13 @@ static int image_new_exec(bContext *C, wmOperator *op)
bmain = CTX_data_main(C);
prop = RNA_struct_find_property(op->ptr, "name");
- RNA_property_string_get(op->ptr, prop, name);
+ RNA_property_string_get(op->ptr, prop, name_buffer);
if (!RNA_property_is_set(op->ptr, prop)) {
/* Default value, we can translate! */
- name = (char *)DATA_(name);
+ name = DATA_(name_buffer);
+ }
+ else {
+ name = name_buffer;
}
width = RNA_int_get(op->ptr, "width");
height = RNA_int_get(op->ptr, "height");
@@ -2540,7 +2547,7 @@ void IMAGE_OT_new(wmOperatorType *ot)
PropertyRNA *prop;
static float default_color[4] = {0.0f, 0.0f, 0.0f, 1.0f};
- static EnumPropertyItem gen_context_items[] = {
+ static const EnumPropertyItem gen_context_items[] = {
{GEN_CONTEXT_NONE, "NONE", 0, "None", ""},
{GEN_CONTEXT_PAINT_CANVAS, "PAINT_CANVAS", 0, "Paint Canvas", ""},
{GEN_CONTEXT_PAINT_STENCIL, "PAINT_STENCIL", 0, "Paint Stencil", ""},
@@ -2610,8 +2617,7 @@ static int image_invert_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
if (support_undo) {
- ED_undo_paint_push_begin(UNDO_PAINT_IMAGE, op->type->name,
- ED_image_undo_restore, ED_image_undo_free, NULL);
+ ED_image_undo_push_begin(op->type->name);
/* not strictly needed, because we only imapaint_dirty_region to invalidate all tiles
* but better do this right in case someone copies this for a tool that uses partial redraw better */
ED_imapaint_clear_partial_redraw();
@@ -2652,8 +2658,9 @@ static int image_invert_exec(bContext *C, wmOperator *op)
if (ibuf->mipmap[0])
ibuf->userflags |= IB_MIPMAP_INVALID;
- if (support_undo)
- ED_undo_paint_push_end(UNDO_PAINT_IMAGE);
+ if (support_undo) {
+ ED_image_undo_push_end();
+ }
/* force GPU reupload, all image is invalid */
GPU_free_image(ima);
@@ -2900,11 +2907,9 @@ static void image_sample_draw(const bContext *C, ARegion *ar, void *arg_info)
}
}
-/* Returns color in the display space, matching ED_space_node_color_sample(). */
-bool ED_space_image_color_sample(Scene *scene, SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
+/* Returns color in linear space, matching ED_space_node_color_sample(). */
+bool ED_space_image_color_sample(SpaceImage *sima, ARegion *ar, int mval[2], float r_col[3])
{
- const char *display_device = scene->display_settings.display_device;
- struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
void *lock;
ImBuf *ibuf = ED_space_image_acquire_buffer(sima, &lock);
float fx, fy;
@@ -2938,10 +2943,6 @@ bool ED_space_image_color_sample(Scene *scene, SpaceImage *sima, ARegion *ar, in
}
}
- if (ret) {
- IMB_colormanagement_scene_linear_to_display_v3(r_col, display);
- }
-
ED_space_image_release_buffer(sima, ibuf, lock);
return ret;
}
@@ -3253,7 +3254,7 @@ void IMAGE_OT_sample_line(wmOperatorType *ot)
void IMAGE_OT_curves_point_set(wmOperatorType *ot)
{
- static EnumPropertyItem point_items[] = {
+ static const EnumPropertyItem point_items[] = {
{0, "BLACK_POINT", 0, "Black Point", ""},
{1, "WHITE_POINT", 0, "White Point", ""},
{0, NULL, 0, NULL, NULL}
@@ -3523,7 +3524,7 @@ static int frame_from_event(bContext *C, const wmEvent *event)
UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &viewx, &viewy);
- framenr = iroundf(viewx);
+ framenr = round_fl_to_int(viewx);
}
return framenr;
@@ -3629,7 +3630,7 @@ static int render_border_exec(bContext *C, wmOperator *op)
{
ARegion *ar = CTX_wm_region(C);
Scene *scene = CTX_data_scene(C);
- Render *re = RE_GetRender(scene->id.name);
+ Render *re = RE_GetSceneRender(scene);
RenderData *rd;
rctf border;
@@ -3681,10 +3682,10 @@ void IMAGE_OT_render_border(wmOperatorType *ot)
ot->idname = "IMAGE_OT_render_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = render_border_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = image_cycle_render_slot_poll;
/* flags */
diff --git a/source/blender/editors/space_image/space_image.c b/source/blender/editors/space_image/space_image.c
index 6ddf78290aa..bac3b9f8df7 100644
--- a/source/blender/editors/space_image/space_image.c
+++ b/source/blender/editors/space_image/space_image.c
@@ -89,6 +89,18 @@ static void image_scopes_tag_refresh(ScrArea *sa)
sima->scopes.ok = 0;
}
+static void image_user_refresh_scene(const bContext *C, SpaceImage *sima)
+{
+ if (sima->image && sima->image->type == IMA_TYPE_R_RESULT) {
+ /* for render result, try to use the currently rendering scene */
+ Scene *render_scene = ED_render_job_get_current_scene(C);
+ if (render_scene) {
+ sima->iuser.scene = render_scene;
+ return;
+ }
+ }
+ sima->iuser.scene = CTX_data_scene(C);
+}
/* ******************** manage regions ********************* */
@@ -422,12 +434,9 @@ static void image_refresh(const bContext *C, ScrArea *sa)
}
else {
/* old shading system, we set texface */
- MTexPoly *tf;
-
- if (em && EDBM_mtexpoly_check(em)) {
- tf = EDBM_mtexpoly_active_get(em, NULL, sloppy, selected);
-
- if (tf) {
+ if (em && EDBM_uv_check(em)) {
+ MTexPoly *tf;
+ if (EDBM_uv_active_face_get(em, sloppy, selected, &tf)) {
/* don't need to check for pin here, see above */
sima->image = tf->tpage;
@@ -699,17 +708,7 @@ static void image_main_region_draw(const bContext *C, ARegion *ar)
glClearColor(col[0], col[1], col[2], 0.0);
glClear(GL_COLOR_BUFFER_BIT);
- /* put scene context variable in iuser */
- if (sima->image && sima->image->type == IMA_TYPE_R_RESULT) {
- /* for render result, try to use the currently rendering scene */
- Scene *render_scene = ED_render_job_get_current_scene(C);
- if (render_scene)
- sima->iuser.scene = render_scene;
- else
- sima->iuser.scene = scene;
- }
- else
- sima->iuser.scene = scene;
+ image_user_refresh_scene(C, sima);
/* we set view2d from own zoom and offset each time */
image_main_region_set_view2d(sima, ar);
@@ -763,14 +762,14 @@ static void image_main_region_draw(const bContext *C, ARegion *ar)
/* ED_space_image_get* will acquire image buffer which requires
* lock here by the same reason why lock is needed in draw_image_main
*/
- BLI_lock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_lock(LOCK_DRAW_IMAGE);
}
ED_space_image_get_size(sima, &width, &height);
ED_space_image_get_aspect(sima, &aspx, &aspy);
if (show_viewer)
- BLI_unlock_thread(LOCK_DRAW_IMAGE);
+ BLI_thread_unlock(LOCK_DRAW_IMAGE);
ED_mask_draw_region(mask, ar,
sima->mask_info.draw_flag,
@@ -961,6 +960,11 @@ static void image_header_region_init(wmWindowManager *UNUSED(wm), ARegion *ar)
static void image_header_region_draw(const bContext *C, ARegion *ar)
{
+ ScrArea *sa = CTX_wm_area(C);
+ SpaceImage *sima = sa->spacedata.first;
+
+ image_user_refresh_scene(C, sima);
+
ED_region_header(C, ar);
}
diff --git a/source/blender/editors/space_info/info_ops.c b/source/blender/editors/space_info/info_ops.c
index 0e427623840..b87a0de23b9 100644
--- a/source/blender/editors/space_info/info_ops.c
+++ b/source/blender/editors/space_info/info_ops.c
@@ -162,7 +162,6 @@ static int pack_all_exec(bContext *C, wmOperator *op)
Main *bmain = CTX_data_main(C);
packAll(bmain, op->reports, true);
- G.fileflags |= G_AUTOPACK;
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/space_info/info_report.c b/source/blender/editors/space_info/info_report.c
index 0cc01646e82..31df9b199ea 100644
--- a/source/blender/editors/space_info/info_report.c
+++ b/source/blender/editors/space_info/info_report.c
@@ -230,7 +230,7 @@ static int borderselect_exec(bContext *C, wmOperator *op)
rcti rect;
//rctf rectf, rq;
- const bool select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
//int mval[2];
WM_operator_properties_border_to_rcti(op, &rect);
@@ -298,10 +298,10 @@ void INFO_OT_select_border(wmOperatorType *ot)
ot->idname = "INFO_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_info_active;
@@ -309,7 +309,7 @@ void INFO_OT_select_border(wmOperatorType *ot)
/* ot->flag = OPTYPE_REGISTER; */
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
diff --git a/source/blender/editors/space_logic/logic_buttons.c b/source/blender/editors/space_logic/logic_buttons.c
index e5eee21ed08..54e6e217b77 100644
--- a/source/blender/editors/space_logic/logic_buttons.c
+++ b/source/blender/editors/space_logic/logic_buttons.c
@@ -142,8 +142,6 @@ static int cut_links_exec(bContext *C, wmOperator *op)
void LOGIC_OT_links_cut(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
ot->name = "Cut Links";
ot->idname = "LOGIC_OT_links_cut";
ot->description = "Remove logic brick connections";
@@ -158,8 +156,10 @@ void LOGIC_OT_links_cut(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
+ /* properties */
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
/* internal */
RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
}
diff --git a/source/blender/editors/space_logic/logic_ops.c b/source/blender/editors/space_logic/logic_ops.c
index 1559515221e..7b9a8634490 100644
--- a/source/blender/editors/space_logic/logic_ops.c
+++ b/source/blender/editors/space_logic/logic_ops.c
@@ -66,7 +66,7 @@ static int edit_sensor_poll(bContext *C)
{
PointerRNA ptr = CTX_data_pointer_get_type(C, "sensor", &RNA_Sensor);
- if (ptr.data && ID_IS_LINKED_DATABLOCK(ptr.id.data)) return 0;
+ if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0;
return 1;
}
@@ -74,7 +74,7 @@ static int edit_controller_poll(bContext *C)
{
PointerRNA ptr = CTX_data_pointer_get_type(C, "controller", &RNA_Controller);
- if (ptr.data && ID_IS_LINKED_DATABLOCK(ptr.id.data)) return 0;
+ if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0;
return 1;
}
@@ -82,7 +82,7 @@ static int edit_actuator_poll(bContext *C)
{
PointerRNA ptr = CTX_data_pointer_get_type(C, "actuator", &RNA_Actuator);
- if (ptr.data && ID_IS_LINKED_DATABLOCK(ptr.id.data)) return 0;
+ if (ptr.data && ID_IS_LINKED(ptr.id.data)) return 0;
return 1;
}
@@ -562,7 +562,7 @@ static void LOGIC_OT_actuator_add(wmOperatorType *ot)
}
/* ************* Move Logic Bricks Operator ************* */
-static EnumPropertyItem logicbricks_move_direction[] = {
+static const EnumPropertyItem logicbricks_move_direction[] = {
{1, "UP", 0, "Move Up", ""},
{2, "DOWN", 0, "Move Down", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/space_logic/logic_window.c b/source/blender/editors/space_logic/logic_window.c
index 3de44174d6a..4dd3f369204 100644
--- a/source/blender/editors/space_logic/logic_window.c
+++ b/source/blender/editors/space_logic/logic_window.c
@@ -56,7 +56,7 @@
#include "BKE_main.h"
#include "BKE_sca.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "BLT_translation.h"
@@ -2018,7 +2018,7 @@ static void draw_actuator_sound(uiLayout *layout, PointerRNA *ptr, bContext *C)
{
uiLayout *row, *col;
- uiTemplateID(layout, C, ptr, "sound", NULL, "SOUND_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "sound", NULL, "SOUND_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!RNA_pointer_get(ptr, "sound").data) {
uiItemL(layout, IFACE_("Select a sound from the list or load a new one"), ICON_NONE);
return;
diff --git a/source/blender/editors/space_nla/nla_buttons.c b/source/blender/editors/space_nla/nla_buttons.c
index 5355b8012db..9551a1cf362 100644
--- a/source/blender/editors/space_nla/nla_buttons.c
+++ b/source/blender/editors/space_nla/nla_buttons.c
@@ -72,7 +72,7 @@ static void do_nla_region_buttons(bContext *C, void *UNUSED(arg), int UNUSED(eve
//Scene *scene = CTX_data_scene(C);
#if 0
switch (event) {
-
+ /* pass */
}
#endif
/* default for now */
@@ -285,7 +285,9 @@ static void nla_panel_animdata(const bContext *C, Panel *pa)
/* Active Action Properties ------------------------------------- */
/* action */
row = uiLayoutRow(layout, true);
- uiTemplateID(row, (bContext *)C, &adt_ptr, "action", "ACTION_OT_new", NULL, "NLA_OT_action_unlink");
+ uiTemplateID(
+ row, (bContext *)C, &adt_ptr, "action",
+ "ACTION_OT_new", NULL, "NLA_OT_action_unlink", UI_TEMPLATE_ID_FILTER_ALL);
/* extrapolation */
row = uiLayoutRow(layout, true);
@@ -552,7 +554,7 @@ void nla_buttons_register(ARegionType *art)
pt = MEM_callocN(sizeof(PanelType), "spacetype nla panel modifiers");
strcpy(pt->idname, "NLA_PT_modifiers");
strcpy(pt->label, N_("Modifiers"));
- strcpy(pt->category, "Modifiers");
+ strcpy(pt->category, "Modifiers");
strcpy(pt->translation_context, BLT_I18NCONTEXT_DEFAULT_BPYRNA);
pt->draw = nla_panel_modifiers;
pt->poll = nla_strip_eval_panel_poll;
diff --git a/source/blender/editors/space_nla/nla_channels.c b/source/blender/editors/space_nla/nla_channels.c
index e9c46e9d04b..27f275c15dd 100644
--- a/source/blender/editors/space_nla/nla_channels.c
+++ b/source/blender/editors/space_nla/nla_channels.c
@@ -129,7 +129,7 @@ static int mouse_nla_channels(bContext *C, bAnimContext *ac, float x, int channe
Object *ob = base->object;
AnimData *adt = ob->adt;
- if (nlaedit_is_tweakmode_on(ac) == 0) {
+ if (nlaedit_is_tweakmode_on(ac) == 0 && (ob->restrictflag & OB_RESTRICT_SELECT) == 0) {
/* set selection status */
if (selectmode == SELECT_INVERT) {
/* swap select */
@@ -596,12 +596,12 @@ bool nlaedit_add_tracks_existing(bAnimContext *ac, bool above_sel)
*/
if (above_sel) {
/* just add a new one above this one */
- add_nlatrack(adt, nlt);
+ BKE_nlatrack_add(adt, nlt);
added = true;
}
else if ((lastAdt == NULL) || (adt != lastAdt)) {
/* add one track to the top of the owning AnimData's stack, then don't add anymore to this stack */
- add_nlatrack(adt, NULL);
+ BKE_nlatrack_add(adt, NULL);
lastAdt = adt;
added = true;
}
@@ -636,7 +636,7 @@ bool nlaedit_add_tracks_empty(bAnimContext *ac)
/* ensure it is empty */
if (BLI_listbase_is_empty(&adt->nla_tracks)) {
/* add new track to this AnimData block then */
- add_nlatrack(adt, NULL);
+ BKE_nlatrack_add(adt, NULL);
added = true;
}
}
@@ -731,7 +731,7 @@ static int nlaedit_delete_tracks_exec(bContext *C, wmOperator *UNUSED(op))
adt->flag &= ~ADT_NLA_SOLO_TRACK;
/* call delete on this track - deletes all strips too */
- free_nlatrack(&adt->nla_tracks, nlt);
+ BKE_nlatrack_free(&adt->nla_tracks, nlt);
}
}
diff --git a/source/blender/editors/space_nla/nla_draw.c b/source/blender/editors/space_nla/nla_draw.c
index 5b3c062e16d..d33b84f76c0 100644
--- a/source/blender/editors/space_nla/nla_draw.c
+++ b/source/blender/editors/space_nla/nla_draw.c
@@ -285,15 +285,20 @@ static void nla_draw_strip_curves(NlaStrip *strip, float yminc, float ymaxc)
float cfra;
/* plot the curve (over the strip's main region) */
- glBegin(GL_LINE_STRIP);
- /* sample at 1 frame intervals, and draw
- * - min y-val is yminc, max is y-maxc, so clamp in those regions
- */
- for (cfra = strip->start; cfra <= strip->end; cfra += 1.0f) {
- float y = evaluate_fcurve(fcu, cfra); // assume this to be in 0-1 range
- glVertex2f(cfra, ((y * yheight) + yminc));
+ if (fcu) {
+ glBegin(GL_LINE_STRIP);
+
+ /* sample at 1 frame intervals, and draw
+ * - min y-val is yminc, max is y-maxc, so clamp in those regions
+ */
+ for (cfra = strip->start; cfra <= strip->end; cfra += 1.0f) {
+ float y = evaluate_fcurve(fcu, cfra);
+ CLAMP(y, 0.0f, 1.0f);
+ glVertex2f(cfra, ((y * yheight) + yminc));
+ }
+
+ glEnd(); // GL_LINE_STRIP
}
- glEnd(); // GL_LINE_STRIP
}
else {
/* use blend in/out values only if both aren't zero */
@@ -361,7 +366,7 @@ static void nla_draw_strip(SpaceNla *snla, AnimData *adt, NlaTrack *nlt, NlaStri
glVertex2f(strip->start, yminc);
glEnd();
}
- /* fall-through */
+ ATTR_FALLTHROUGH;
/* this only draws after the strip */
case NLASTRIP_EXTEND_HOLD_FORWARD:
diff --git a/source/blender/editors/space_nla/nla_edit.c b/source/blender/editors/space_nla/nla_edit.c
index 1f298373a80..c86e9872c0a 100644
--- a/source/blender/editors/space_nla/nla_edit.c
+++ b/source/blender/editors/space_nla/nla_edit.c
@@ -365,8 +365,8 @@ static int nlaedit_previewrange_exec(bContext *C, wmOperator *UNUSED(op))
/* set the range directly */
get_nlastrip_extents(&ac, &min, &max, true);
scene->r.flag |= SCER_PRV_RANGE;
- scene->r.psfra = iroundf(min);
- scene->r.pefra = iroundf(max);
+ scene->r.psfra = round_fl_to_int(min);
+ scene->r.pefra = round_fl_to_int(max);
/* set notifier that things have changed */
// XXX err... there's nothing for frame ranges yet, but this should do fine too
@@ -645,7 +645,7 @@ static int nlaedit_add_actionclip_exec(bContext *C, wmOperator *op)
}
/* create a new strip, and offset it to start on the current frame */
- strip = add_nlastrip(act);
+ strip = BKE_nlastrip_new(act);
strip->end += (cfra - strip->start);
strip->start = cfra;
@@ -655,7 +655,7 @@ static int nlaedit_add_actionclip_exec(bContext *C, wmOperator *op)
/* trying to add to the current failed (no space),
* so add a new track to the stack, and add to that...
*/
- nlt = add_nlatrack(adt, NULL);
+ nlt = BKE_nlatrack_add(adt, NULL);
BKE_nlatrack_add_strip(nlt, strip);
}
@@ -858,7 +858,7 @@ static int nlaedit_add_sound_exec(bContext *C, wmOperator *UNUSED(op))
continue;
/* create a new strip, and offset it to start on the current frame */
- strip = add_nla_soundstrip(ac.scene, ob->data);
+ strip = BKE_nla_add_soundstrip(ac.scene, ob->data);
strip->start += cfra;
strip->end += cfra;
@@ -868,7 +868,7 @@ static int nlaedit_add_sound_exec(bContext *C, wmOperator *UNUSED(op))
/* trying to add to the current failed (no space),
* so add a new track to the stack, and add to that...
*/
- nlt = add_nlatrack(adt, NULL);
+ nlt = BKE_nlatrack_add(adt, NULL);
BKE_nlatrack_add_strip(nlt, strip);
}
@@ -1057,7 +1057,7 @@ static int nlaedit_duplicate_exec(bContext *C, wmOperator *op)
/* if selected, split the strip at its midpoint */
if (strip->flag & NLASTRIP_FLAG_SELECT) {
/* make a copy (assume that this is possible) */
- nstrip = copy_nlastrip(strip, linked);
+ nstrip = BKE_nlastrip_copy(strip, linked);
/* in case there's no space in the track above, or we haven't got a reference to it yet, try adding */
if (BKE_nlatrack_add_strip(nlt->next, nstrip) == 0) {
@@ -1065,7 +1065,7 @@ static int nlaedit_duplicate_exec(bContext *C, wmOperator *op)
* - if the current one is the last one, nlt->next will be NULL, which defaults to adding
* at the top of the stack anyway...
*/
- track = add_nlatrack(adt, nlt->next);
+ track = BKE_nlatrack_add(adt, nlt->next);
BKE_nlatrack_add_strip(track, nstrip);
}
@@ -1160,14 +1160,14 @@ static int nlaedit_delete_exec(bContext *C, wmOperator *UNUSED(op))
if (strip->flag & NLASTRIP_FLAG_SELECT) {
/* if a strip either side of this was a transition, delete those too */
if ((strip->prev) && (strip->prev->type == NLASTRIP_TYPE_TRANSITION))
- free_nlastrip(&nlt->strips, strip->prev);
+ BKE_nlastrip_free(&nlt->strips, strip->prev);
if ((nstrip) && (nstrip->type == NLASTRIP_TYPE_TRANSITION)) {
nstrip = nstrip->next;
- free_nlastrip(&nlt->strips, strip->next);
+ BKE_nlastrip_free(&nlt->strips, strip->next);
}
/* finally, delete this strip */
- free_nlastrip(&nlt->strips, strip);
+ BKE_nlastrip_free(&nlt->strips, strip);
}
}
}
@@ -1242,7 +1242,7 @@ static void nlaedit_split_strip_actclip(AnimData *adt, NlaTrack *nlt, NlaStrip *
/* make a copy (assume that this is possible) and append
* it immediately after the current strip
*/
- nstrip = copy_nlastrip(strip, true);
+ nstrip = BKE_nlastrip_copy(strip, true);
BLI_insertlinkafter(&nlt->strips, strip, nstrip);
/* set the endpoint of the first strip and the start of the new strip
@@ -1501,7 +1501,7 @@ static int nlaedit_swap_exec(bContext *C, wmOperator *op)
NlaStrip *mstrip = (NlaStrip *)nlt->strips.first;
if ((mstrip->flag & NLASTRIP_FLAG_TEMP_META) &&
- (BLI_listbase_count_ex(&mstrip->strips, 3) == 2))
+ (BLI_listbase_count_at_most(&mstrip->strips, 3) == 2))
{
/* remove this temp meta, so that we can see the strips inside */
BKE_nlastrips_clear_metas(&nlt->strips, 0, 1);
@@ -2089,7 +2089,7 @@ void NLA_OT_clear_scale(wmOperatorType *ot)
/* Moves the start-point of the selected strips to the specified places */
/* defines for snap keyframes tool */
-static EnumPropertyItem prop_nlaedit_snap_types[] = {
+static const EnumPropertyItem prop_nlaedit_snap_types[] = {
{NLAEDIT_SNAP_CFRA, "CFRA", 0, "Current Frame", ""},
{NLAEDIT_SNAP_NEAREST_FRAME, "NEAREST_FRAME", 0, "Nearest Frame", ""}, // XXX as single entry?
{NLAEDIT_SNAP_NEAREST_SECOND, "NEAREST_SECOND", 0, "Nearest Second", ""}, // XXX as single entry?
@@ -2186,7 +2186,7 @@ static int nlaedit_snap_exec(bContext *C, wmOperator *op)
/* in case there's no space in the current track, try adding */
if (BKE_nlatrack_add_strip(nlt, strip) == 0) {
/* need to add a new track above the current one */
- track = add_nlatrack(adt, nlt);
+ track = BKE_nlatrack_add(adt, nlt);
BKE_nlatrack_add_strip(track, strip);
/* clear temp meta-strips on this new track, as we may not be able to get back to it */
@@ -2239,7 +2239,7 @@ void NLA_OT_snap(wmOperatorType *ot)
/* ******************** Add F-Modifier Operator *********************** */
-static EnumPropertyItem *nla_fmodifier_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *nla_fmodifier_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
int totitem = 0;
@@ -2316,7 +2316,7 @@ static int nla_fmodifier_add_exec(bContext *C, wmOperator *op)
continue;
/* add F-Modifier of specified type to selected, and make it the active one */
- fcm = add_fmodifier(&strip->modifiers, type);
+ fcm = add_fmodifier(&strip->modifiers, type, NULL);
if (fcm) {
set_active_fmodifier(&strip->modifiers, fcm);
@@ -2470,7 +2470,7 @@ static int nla_fmodifier_paste_exec(bContext *C, wmOperator *op)
}
/* paste FModifiers from buffer */
- ok += ANIM_fmodifiers_paste_from_buf(&strip->modifiers, replace);
+ ok += ANIM_fmodifiers_paste_from_buf(&strip->modifiers, replace, NULL);
ale->update |= ANIM_UPDATE_DEPS;
}
}
diff --git a/source/blender/editors/space_nla/nla_select.c b/source/blender/editors/space_nla/nla_select.c
index 8261397c940..e09e4417d5d 100644
--- a/source/blender/editors/space_nla/nla_select.c
+++ b/source/blender/editors/space_nla/nla_select.c
@@ -278,25 +278,28 @@ static int nlaedit_borderselect_exec(bContext *C, wmOperator *op)
bAnimContext ac;
rcti rect;
short mode = 0, selectmode = 0;
- int extend;
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
+ const bool extend = RNA_boolean_get(op->ptr, "extend");
/* get editor data */
if (ANIM_animdata_get_context(C, &ac) == 0)
return OPERATOR_CANCELLED;
/* clear all selection if not extending selection */
- extend = RNA_boolean_get(op->ptr, "extend");
- if (!extend)
+ if (!extend) {
deselect_nla_strips(&ac, DESELECT_STRIPS_TEST, SELECT_SUBTRACT);
+ }
/* get settings from operator */
WM_operator_properties_border_to_rcti(op, &rect);
-
- if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT)
+
+ if (select) {
selectmode = SELECT_ADD;
- else
+ }
+ else {
selectmode = SELECT_SUBTRACT;
-
+ }
+
/* selection 'mode' depends on whether borderselect region only matters on one axis */
if (RNA_boolean_get(op->ptr, "axis_range")) {
/* mode depends on which axis of the range is larger to determine which axis to use
@@ -329,10 +332,10 @@ void NLA_OT_select_border(wmOperatorType *ot)
ot->description = "Use box selection to grab NLA-Strips";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = nlaedit_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = nlaop_poll_tweakmode_off;
@@ -340,7 +343,7 @@ void NLA_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, 1);
+ WM_operator_properties_gesture_border_select(ot);
RNA_def_boolean(ot->srna, "axis_range", 0, "Axis Range", "");
}
@@ -349,7 +352,7 @@ void NLA_OT_select_border(wmOperatorType *ot)
/* Select keyframes left/right of the current frame indicator */
/* defines for left-right select tool */
-static EnumPropertyItem prop_nlaedit_leftright_select_types[] = {
+static const EnumPropertyItem prop_nlaedit_leftright_select_types[] = {
{NLAEDIT_LRSEL_TEST, "CHECK", 0, "Check if Select Left or Right", ""},
{NLAEDIT_LRSEL_LEFT, "LEFT", 0, "Before current frame", ""},
{NLAEDIT_LRSEL_RIGHT, "RIGHT", 0, "After current frame", ""},
@@ -441,7 +444,8 @@ static int nlaedit_select_leftright_exec(bContext *C, wmOperator *op)
nlaedit_select_leftright(C, &ac, leftright, selectmode);
/* set notifier that keyframe selection (and channels too) have changed */
- WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | ND_ANIMCHAN | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_KEYFRAME | NA_SELECTED, NULL);
+ WM_event_add_notifier(C, NC_ANIMATION | ND_ANIMCHAN | NA_SELECTED, NULL);
return OPERATOR_FINISHED;
}
diff --git a/source/blender/editors/space_nla/space_nla.c b/source/blender/editors/space_nla/space_nla.c
index 3b5604087b9..f1e8b655673 100644
--- a/source/blender/editors/space_nla/space_nla.c
+++ b/source/blender/editors/space_nla/space_nla.c
@@ -505,13 +505,14 @@ static void nla_listener(bScreen *UNUSED(sc), ScrArea *sa, wmNotifier *wmn)
static void nla_id_remap(ScrArea *UNUSED(sa), SpaceLink *slink, ID *old_id, ID *new_id)
{
SpaceNla *snla = (SpaceNla *)slink;
-
- if (!ELEM(GS(old_id->name), ID_GR)) {
- return;
- }
-
- if ((ID *)snla->ads->filter_grp == old_id) {
- snla->ads->filter_grp = (Group *)new_id;
+
+ if (snla->ads) {
+ if ((ID *)snla->ads->filter_grp == old_id) {
+ snla->ads->filter_grp = (Group *)new_id;
+ }
+ if ((ID *)snla->ads->source == old_id) {
+ snla->ads->source = new_id;
+ }
}
}
diff --git a/source/blender/editors/space_node/drawnode.c b/source/blender/editors/space_node/drawnode.c
index d31a475e45e..5665a5cff2d 100644
--- a/source/blender/editors/space_node/drawnode.c
+++ b/source/blender/editors/space_node/drawnode.c
@@ -323,7 +323,7 @@ static int node_resize_area_default(bNode *node, int x, int y)
static void node_draw_buttons_group(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
- uiTemplateIDBrowse(layout, C, ptr, "node_tree", NULL, NULL, NULL);
+ uiTemplateIDBrowse(layout, C, ptr, "node_tree", NULL, NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
}
/* XXX Does a bounding box update by iterating over all children.
@@ -638,7 +638,7 @@ static void node_draw_reroute(const bContext *C, ARegion *ar, SpaceNode *UNUSED(
* highlight also if node itself is selected, since we don't display the node body separately!
*/
for (sock = node->inputs.first; sock; sock = sock->next) {
- node_socket_circle_draw(C, ntree, node, sock, socket_size, (sock->flag & SELECT) || (node->flag & SELECT));
+ node_socket_draw(C, ntree, node, sock, socket_size, (sock->flag & SELECT) || (node->flag & SELECT));
}
UI_block_end(C, node->block);
@@ -683,7 +683,8 @@ static void node_common_set_butfunc(bNodeType *ntype)
/* ****************** BUTTON CALLBACKS FOR SHADER NODES ***************** */
static void node_buts_image_user(uiLayout *layout, bContext *C, PointerRNA *ptr,
- PointerRNA *imaptr, PointerRNA *iuserptr)
+ PointerRNA *imaptr, PointerRNA *iuserptr,
+ bool compositor)
{
uiLayout *col;
int source;
@@ -718,7 +719,8 @@ static void node_buts_image_user(uiLayout *layout, bContext *C, PointerRNA *ptr,
uiItemR(col, ptr, "use_auto_refresh", 0, NULL, ICON_NONE);
}
- if (RNA_enum_get(imaptr, "type") == IMA_TYPE_MULTILAYER &&
+ if (compositor &&
+ RNA_enum_get(imaptr, "type") == IMA_TYPE_MULTILAYER &&
RNA_boolean_get(ptr, "has_layers"))
{
col = uiLayoutColumn(layout, false);
@@ -731,7 +733,7 @@ static void node_shader_buts_material(uiLayout *layout, bContext *C, PointerRNA
bNode *node = ptr->data;
uiLayout *col;
- uiTemplateID(layout, C, ptr, "material", "MATERIAL_OT_new", NULL, NULL);
+ uiTemplateID(layout, C, ptr, "material", "MATERIAL_OT_new", NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id) return;
@@ -828,7 +830,7 @@ static void node_shader_buts_tex_image(uiLayout *layout, bContext *C, PointerRNA
PointerRNA iuserptr = RNA_pointer_get(ptr, "image_user");
uiLayoutSetContextPointer(layout, "image_user", &iuserptr);
- uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
uiItemR(layout, ptr, "color_space", 0, "", ICON_NONE);
uiItemR(layout, ptr, "interpolation", 0, "", ICON_NONE);
uiItemR(layout, ptr, "projection", 0, "", ICON_NONE);
@@ -842,7 +844,7 @@ static void node_shader_buts_tex_image(uiLayout *layout, bContext *C, PointerRNA
/* note: image user properties used directly here, unlike compositor image node,
* which redefines them in the node struct RNA to get proper updates.
*/
- node_buts_image_user(layout, C, &iuserptr, &imaptr, &iuserptr);
+ node_buts_image_user(layout, C, &iuserptr, &imaptr, &iuserptr, false);
}
static void node_shader_buts_tex_image_ex(uiLayout *layout, bContext *C, PointerRNA *ptr)
@@ -857,9 +859,11 @@ static void node_shader_buts_tex_environment(uiLayout *layout, bContext *C, Poin
PointerRNA iuserptr = RNA_pointer_get(ptr, "image_user");
uiLayoutSetContextPointer(layout, "image_user", &iuserptr);
- uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL);
+ uiTemplateID(
+ layout, C, ptr, "image",
+ NULL, "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
- node_buts_image_user(layout, C, &iuserptr, &imaptr, &iuserptr);
+ node_buts_image_user(layout, C, &iuserptr, &imaptr, &iuserptr, false);
uiItemR(layout, ptr, "color_space", 0, "", ICON_NONE);
uiItemR(layout, ptr, "interpolation", 0, "", ICON_NONE);
@@ -873,7 +877,9 @@ static void node_shader_buts_tex_environment_ex(uiLayout *layout, bContext *C, P
Image *ima = imaptr.data;
uiLayoutSetContextPointer(layout, "image_user", &iuserptr);
- uiTemplateID(layout, C, ptr, "image", ima ? NULL : "IMAGE_OT_new", "IMAGE_OT_open", NULL);
+ uiTemplateID(
+ layout, C, ptr, "image",
+ ima ? NULL : "IMAGE_OT_new", "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!ima)
return;
@@ -1030,7 +1036,7 @@ static void node_shader_buts_normal_map(uiLayout *layout, bContext *C, PointerRN
{
uiItemR(layout, ptr, "space", 0, "", 0);
- if (RNA_enum_get(ptr, "space") == SHD_NORMAL_MAP_TANGENT) {
+ if (RNA_enum_get(ptr, "space") == SHD_SPACE_TANGENT) {
PointerRNA obptr = CTX_data_pointer_get(C, "active_object");
if (obptr.data && RNA_enum_get(&obptr, "type") == OB_MESH) {
@@ -1042,6 +1048,11 @@ static void node_shader_buts_normal_map(uiLayout *layout, bContext *C, PointerRN
}
}
+static void node_shader_buts_displacement(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiItemR(layout, ptr, "space", 0, "", 0);
+}
+
static void node_shader_buts_tangent(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
uiLayout *split, *row;
@@ -1071,6 +1082,12 @@ static void node_shader_buts_glossy(uiLayout *layout, bContext *UNUSED(C), Point
uiItemR(layout, ptr, "distribution", 0, "", ICON_NONE);
}
+static void node_shader_buts_principled(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiItemR(layout, ptr, "distribution", 0, "", ICON_NONE);
+ uiItemR(layout, ptr, "subsurface_method", 0, "", ICON_NONE);
+}
+
static void node_shader_buts_anisotropic(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
{
uiItemR(layout, ptr, "distribution", 0, "", ICON_NONE);
@@ -1131,6 +1148,11 @@ static void node_buts_output_linestyle(uiLayout *layout, bContext *UNUSED(C), Po
uiItemR(col, ptr, "use_clamp", 0, NULL, ICON_NONE);
}
+static void node_shader_buts_bevel(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiItemR(layout, ptr, "samples", 0, NULL, ICON_NONE);
+}
+
/* only once called */
static void node_shader_set_butfunc(bNodeType *ntype)
{
@@ -1228,6 +1250,10 @@ static void node_shader_set_butfunc(bNodeType *ntype)
case SH_NODE_NORMAL_MAP:
ntype->draw_buttons = node_shader_buts_normal_map;
break;
+ case SH_NODE_DISPLACEMENT:
+ case SH_NODE_VECTOR_DISPLACEMENT:
+ ntype->draw_buttons = node_shader_buts_displacement;
+ break;
case SH_NODE_TANGENT:
ntype->draw_buttons = node_shader_buts_tangent;
break;
@@ -1236,6 +1262,9 @@ static void node_shader_set_butfunc(bNodeType *ntype)
case SH_NODE_BSDF_REFRACTION:
ntype->draw_buttons = node_shader_buts_glossy;
break;
+ case SH_NODE_BSDF_PRINCIPLED:
+ ntype->draw_buttons = node_shader_buts_principled;
+ break;
case SH_NODE_BSDF_ANISOTROPIC:
ntype->draw_buttons = node_shader_buts_anisotropic;
break;
@@ -1261,6 +1290,9 @@ static void node_shader_set_butfunc(bNodeType *ntype)
case SH_NODE_OUTPUT_LINESTYLE:
ntype->draw_buttons = node_buts_output_linestyle;
break;
+ case SH_NODE_BEVEL:
+ ntype->draw_buttons = node_shader_buts_bevel;
+ break;
}
}
@@ -1291,12 +1323,14 @@ static void node_composit_buts_image(uiLayout *layout, bContext *C, PointerRNA *
RNA_pointer_create((ID *)ptr->id.data, &RNA_ImageUser, node->storage, &iuserptr);
uiLayoutSetContextPointer(layout, "image_user", &iuserptr);
- uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL);
+ uiTemplateID(
+ layout, C, ptr, "image",
+ NULL, "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id) return;
imaptr = RNA_pointer_get(ptr, "image");
- node_buts_image_user(layout, C, ptr, &imaptr, &iuserptr);
+ node_buts_image_user(layout, C, ptr, &imaptr, &iuserptr, true);
node_buts_image_views(layout, C, ptr, &imaptr);
}
@@ -1320,11 +1354,8 @@ static void node_composit_buts_renderlayers(uiLayout *layout, bContext *C, Point
PropertyRNA *prop;
const char *layer_name;
char scene_name[MAX_ID_NAME - 2];
- wmOperatorType *ot = WM_operatortype_find("RENDER_OT_render", 1);
-
- BLI_assert(ot != 0);
- uiTemplateID(layout, C, ptr, "scene", NULL, NULL, NULL);
+ uiTemplateID(layout, C, ptr, "scene", NULL, NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id) return;
@@ -1339,11 +1370,9 @@ static void node_composit_buts_renderlayers(uiLayout *layout, bContext *C, Point
scn_ptr = RNA_pointer_get(ptr, "scene");
RNA_string_get(&scn_ptr, "name", scene_name);
- WM_operator_properties_create_ptr(&op_ptr, ot);
+ uiItemFullO(row, "RENDER_OT_render", "", ICON_RENDER_STILL, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
RNA_string_set(&op_ptr, "layer", layer_name);
RNA_string_set(&op_ptr, "scene", scene_name);
- uiItemFullO_ptr(row, ot, "", ICON_RENDER_STILL, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
-
}
@@ -1440,7 +1469,7 @@ static void node_composit_buts_defocus(uiLayout *layout, bContext *C, PointerRNA
col = uiLayoutColumn(layout, false);
uiItemR(col, ptr, "use_preview", 0, NULL, ICON_NONE);
- uiTemplateID(layout, C, ptr, "scene", NULL, NULL, NULL);
+ uiTemplateID(layout, C, ptr, "scene", NULL, NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
col = uiLayoutColumn(layout, false);
uiItemR(col, ptr, "use_zbuffer", 0, NULL, ICON_NONE);
@@ -1792,6 +1821,7 @@ static void node_composit_buts_file_output_ex(uiLayout *layout, bContext *C, Poi
Scene *scene = CTX_data_scene(C);
PointerRNA imfptr = RNA_pointer_get(ptr, "format");
PointerRNA active_input_ptr, op_ptr;
+ wmOperatorType *ot;
uiLayout *row, *col;
int active_index;
const bool multilayer = RNA_enum_get(&imfptr, "file_format") == R_IMF_IMTYPE_MULTILAYER;
@@ -1830,11 +1860,10 @@ static void node_composit_buts_file_output_ex(uiLayout *layout, bContext *C, Poi
active_input_ptr.id.data = ptr->id.data;
col = uiLayoutColumn(row, true);
- op_ptr = uiItemFullO(col, "NODE_OT_output_file_move_active_socket", "",
- ICON_TRIA_UP, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ ot = WM_operatortype_find("NODE_OT_output_file_move_active_socket", false);
+ uiItemFullO_ptr(col, ot, "", ICON_TRIA_UP, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
RNA_enum_set(&op_ptr, "direction", 1);
- op_ptr = uiItemFullO(col, "NODE_OT_output_file_move_active_socket", "",
- ICON_TRIA_DOWN, NULL, WM_OP_INVOKE_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(col, ot, "", ICON_TRIA_DOWN, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
RNA_enum_set(&op_ptr, "direction", 2);
if (active_input_ptr.data) {
@@ -1845,7 +1874,7 @@ static void node_composit_buts_file_output_ex(uiLayout *layout, bContext *C, Poi
row = uiLayoutRow(col, false);
uiItemR(row, &active_input_ptr, "name", 0, "", ICON_NONE);
uiItemFullO(row, "NODE_OT_output_file_remove_active_socket", "",
- ICON_X, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_R_ICON_ONLY);
+ ICON_X, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_R_ICON_ONLY, NULL);
}
else {
col = uiLayoutColumn(layout, true);
@@ -1854,7 +1883,7 @@ static void node_composit_buts_file_output_ex(uiLayout *layout, bContext *C, Poi
row = uiLayoutRow(col, false);
uiItemR(row, &active_input_ptr, "path", 0, "", ICON_NONE);
uiItemFullO(row, "NODE_OT_output_file_remove_active_socket", "",
- ICON_X, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_R_ICON_ONLY);
+ ICON_X, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_R_ICON_ONLY, NULL);
/* format details for individual files */
imfptr = RNA_pointer_get(&active_input_ptr, "format");
@@ -2007,7 +2036,7 @@ static void node_composit_buts_ycc(uiLayout *layout, bContext *UNUSED(C), Pointe
static void node_composit_buts_movieclip(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
}
static void node_composit_buts_movieclip_ex(uiLayout *layout, bContext *C, PointerRNA *ptr)
@@ -2015,7 +2044,7 @@ static void node_composit_buts_movieclip_ex(uiLayout *layout, bContext *C, Point
bNode *node = ptr->data;
PointerRNA clipptr;
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id)
return;
@@ -2029,7 +2058,7 @@ static void node_composit_buts_stabilize2d(uiLayout *layout, bContext *C, Pointe
{
bNode *node = ptr->data;
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id)
return;
@@ -2053,7 +2082,7 @@ static void node_composit_buts_moviedistortion(uiLayout *layout, bContext *C, Po
{
bNode *node = ptr->data;
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (!node->id)
return;
@@ -2166,14 +2195,9 @@ static void node_composit_buts_switch(uiLayout *layout, bContext *UNUSED(C), Poi
static void node_composit_buts_switch_view_ex(uiLayout *layout, bContext *UNUSED(C), PointerRNA *UNUSED(ptr))
{
- PointerRNA op_ptr;
- wmOperatorType *ot = WM_operatortype_find("NODE_OT_switch_view_update", 1);
-
- BLI_assert(ot != 0);
-
- WM_operator_properties_create_ptr(&op_ptr, ot);
-
- uiItemFullO_ptr(layout, ot, "Update Views", ICON_FILE_REFRESH, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(
+ layout, "NODE_OT_switch_view_update",
+ "Update Views", ICON_FILE_REFRESH, NULL, WM_OP_INVOKE_DEFAULT, 0, NULL);
}
static void node_composit_buts_boxmask(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
@@ -2215,16 +2239,17 @@ static void node_composit_backdrop_viewer(SpaceNode *snode, ImBuf *backdrop, bNo
if (node->custom1 == 0) {
const float backdropWidth = backdrop->x;
const float backdropHeight = backdrop->y;
- const float cx = x + snode->zoom * backdropWidth * node->custom3;
+ const float cx = x + snode->zoom * backdropWidth * node->custom3;
const float cy = y + snode->zoom * backdropHeight * node->custom4;
+ const float cross_size = 12 * U.pixelsize;
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
- glVertex2f(cx - 25, cy - 25);
- glVertex2f(cx + 25, cy + 25);
- glVertex2f(cx + 25, cy - 25);
- glVertex2f(cx - 25, cy + 25);
+ glVertex2f(cx - cross_size, cy - cross_size);
+ glVertex2f(cx + cross_size, cy + cross_size);
+ glVertex2f(cx + cross_size, cy - cross_size);
+ glVertex2f(cx - cross_size, cy + cross_size);
glEnd();
}
}
@@ -2347,7 +2372,7 @@ static void node_composit_buts_mask(uiLayout *layout, bContext *C, PointerRNA *p
{
bNode *node = ptr->data;
- uiTemplateID(layout, C, ptr, "mask", NULL, NULL, NULL);
+ uiTemplateID(layout, C, ptr, "mask", NULL, NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
uiItemR(layout, ptr, "use_antialiasing", 0, NULL, ICON_NONE);
uiItemR(layout, ptr, "use_feather", 0, NULL, ICON_NONE);
@@ -2369,7 +2394,7 @@ static void node_composit_buts_keyingscreen(uiLayout *layout, bContext *C, Point
{
bNode *node = ptr->data;
- uiTemplateID(layout, C, ptr, "clip", NULL, NULL, NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, NULL, NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (node->id) {
MovieClip *clip = (MovieClip *) node->id;
@@ -2405,7 +2430,7 @@ static void node_composit_buts_trackpos(uiLayout *layout, bContext *C, PointerRN
{
bNode *node = ptr->data;
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (node->id) {
MovieClip *clip = (MovieClip *) node->id;
@@ -2445,7 +2470,7 @@ static void node_composit_buts_planetrackdeform(uiLayout *layout, bContext *C, P
bNode *node = ptr->data;
NodePlaneTrackDeformData *data = node->storage;
- uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "clip", NULL, "CLIP_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
if (node->id) {
MovieClip *clip = (MovieClip *) node->id;
@@ -2489,6 +2514,11 @@ static void node_composit_buts_sunbeams(uiLayout *layout, bContext *UNUSED(C), P
uiItemR(layout, ptr, "ray_length", UI_ITEM_R_SLIDER, NULL, ICON_NONE);
}
+static void node_composit_buts_brightcontrast(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr)
+{
+ uiItemR(layout, ptr, "use_premultiply", 0, NULL, ICON_NONE);
+}
+
/* only once called */
static void node_composit_set_butfunc(bNodeType *ntype)
{
@@ -2716,6 +2746,8 @@ static void node_composit_set_butfunc(bNodeType *ntype)
case CMP_NODE_SUNBEAMS:
ntype->draw_buttons = node_composit_buts_sunbeams;
break;
+ case CMP_NODE_BRIGHTCONTRAST:
+ ntype->draw_buttons = node_composit_buts_brightcontrast;
}
}
@@ -2816,7 +2848,7 @@ static void node_texture_buts_proc(uiLayout *layout, bContext *UNUSED(C), Pointe
static void node_texture_buts_image(uiLayout *layout, bContext *C, PointerRNA *ptr)
{
- uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL);
+ uiTemplateID(layout, C, ptr, "image", NULL, "IMAGE_OT_open", NULL, UI_TEMPLATE_ID_FILTER_ALL);
}
static void node_texture_buts_image_ex(uiLayout *layout, bContext *C, PointerRNA *ptr)
@@ -3016,7 +3048,7 @@ static const float std_node_socket_colors[][4] = {
{0.70, 0.65, 0.19, 1.0}, /* SOCK_BOOLEAN */
{0.0, 0.0, 0.0, 1.0}, /*__SOCK_MESH (deprecated) */
{0.06, 0.52, 0.15, 1.0}, /* SOCK_INT */
- {1.0, 1.0, 1.0, 1.0}, /* SOCK_STRING */
+ {0.39, 0.39, 0.39, 1.0}, /* SOCK_STRING */
};
/* common color callbacks for standard types */
@@ -3087,7 +3119,7 @@ static void std_node_socket_draw(bContext *C, uiLayout *layout, PointerRNA *ptr,
node_file_output_socket_draw(C, layout, ptr, node_ptr);
return;
}
-
+
if ((sock->in_out == SOCK_OUT) || (sock->flag & SOCK_IN_USE) || (sock->flag & SOCK_HIDE_VALUE)) {
node_socket_button_label(C, layout, ptr, node_ptr, text);
return;
@@ -3103,20 +3135,11 @@ static void std_node_socket_draw(bContext *C, uiLayout *layout, PointerRNA *ptr,
uiTemplateComponentMenu(layout, ptr, "default_value", text);
break;
case SOCK_RGBA:
- {
- uiLayout *row = uiLayoutRow(layout, false);
- uiLayoutSetAlignment(row, UI_LAYOUT_ALIGN_LEFT);
- /* draw the socket name right of the actual button */
- uiItemR(row, ptr, "default_value", 0, "", 0);
- uiItemL(row, text, 0);
- break;
- }
case SOCK_STRING:
{
- uiLayout *row = uiLayoutRow(layout, true);
- /* draw the socket name right of the actual button */
- uiItemR(row, ptr, "default_value", 0, "", 0);
+ uiLayout *row = uiLayoutSplit(layout, 0.5f, false);
uiItemL(row, text, 0);
+ uiItemR(row, ptr, "default_value", 0, "", 0);
break;
}
default:
@@ -3150,11 +3173,6 @@ static void std_node_socket_interface_draw(bContext *UNUSED(C), uiLayout *layout
uiItemR(row, ptr, "max_value", 0, IFACE_("Max"), 0);
break;
}
- case SOCK_BOOLEAN:
- {
- uiItemR(layout, ptr, "default_value", 0, NULL, 0);
- break;
- }
case SOCK_VECTOR:
{
uiLayout *row;
@@ -3164,11 +3182,8 @@ static void std_node_socket_interface_draw(bContext *UNUSED(C), uiLayout *layout
uiItemR(row, ptr, "max_value", 0, IFACE_("Max"), 0);
break;
}
+ case SOCK_BOOLEAN:
case SOCK_RGBA:
- {
- uiItemR(layout, ptr, "default_value", 0, NULL, 0);
- break;
- }
case SOCK_STRING:
{
uiItemR(layout, ptr, "default_value", 0, NULL, 0);
@@ -3436,7 +3451,6 @@ void node_draw_link_bezier(View2D *v2d, SpaceNode *snode, bNodeLink *link,
/* store current linewidth */
float linew;
float arrow[2], arrow1[2], arrow2[2];
- const float px_fac = UI_DPI_WINDOW_FAC;
glGetFloatv(GL_LINE_WIDTH, &linew);
/* we can reuse the dist variable here to increment the GL curve eval amount*/
@@ -3463,7 +3477,7 @@ void node_draw_link_bezier(View2D *v2d, SpaceNode *snode, bNodeLink *link,
}
if (do_triple) {
UI_ThemeColorShadeAlpha(th_col3, -80, -120);
- glLineWidth(4.0f * px_fac);
+ glLineWidth(4.0f);
glBegin(GL_LINE_STRIP);
for (i = 0; i <= LINK_RESOL; i++) {
@@ -3483,7 +3497,7 @@ void node_draw_link_bezier(View2D *v2d, SpaceNode *snode, bNodeLink *link,
* for Intel hardware, this breaks with GL_LINE_STRIP and
* changing color in begin/end blocks.
*/
- glLineWidth(1.5f * px_fac);
+ glLineWidth(1.5f);
if (do_shaded) {
glBegin(GL_LINES);
for (i = 0; i < LINK_RESOL; i++) {
@@ -3618,7 +3632,7 @@ void node_draw_link(View2D *v2d, SpaceNode *snode, bNodeLink *link)
return;
if (link->fromsock->flag & SOCK_UNAVAIL)
return;
-
+
if (link->flag & NODE_LINK_VALID) {
/* special indicated link, on drop-node */
if (link->flag & NODE_LINKFLAG_HILITE) {
@@ -3638,7 +3652,7 @@ void node_draw_link(View2D *v2d, SpaceNode *snode, bNodeLink *link)
th_col1 = TH_REDALERT;
}
}
-
+
node_draw_link_bezier(v2d, snode, link, th_col1, do_shaded, th_col2, do_triple, th_col3);
// node_draw_link_straight(v2d, snode, link, th_col1, do_shaded, th_col2, do_triple, th_col3);
}
diff --git a/source/blender/editors/space_node/node_add.c b/source/blender/editors/space_node/node_add.c
index d49df2afbd4..ec35727d176 100644
--- a/source/blender/editors/space_node/node_add.c
+++ b/source/blender/editors/space_node/node_add.c
@@ -44,6 +44,8 @@
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_report.h"
+#include "BKE_scene.h"
+#include "BKE_texture.h"
#include "ED_node.h" /* own include */
#include "ED_screen.h"
@@ -105,13 +107,15 @@ static bool add_reroute_intersect_check(bNodeLink *link, float mcoords[][2], int
if (node_link_bezier_points(NULL, NULL, link, coord_array, NODE_LINK_RESOL)) {
- for (i = 0; i < tot - 1; i++)
- for (b = 0; b < NODE_LINK_RESOL; b++)
+ for (i = 0; i < tot - 1; i++) {
+ for (b = 0; b < NODE_LINK_RESOL; b++) {
if (isect_seg_seg_v2(mcoords[i], mcoords[i + 1], coord_array[b], coord_array[b + 1]) > 0) {
result[0] = (mcoords[i][0] + mcoords[i + 1][0]) / 2.0f;
result[1] = (mcoords[i][1] + mcoords[i + 1][1]) / 2.0f;
return 1;
}
+ }
+ }
}
return 0;
}
@@ -273,8 +277,6 @@ static int add_reroute_exec(bContext *C, wmOperator *op)
void NODE_OT_add_reroute(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
ot->name = "Add Reroute";
ot->idname = "NODE_OT_add_reroute";
ot->description = "Add a reroute node";
@@ -289,8 +291,10 @@ void NODE_OT_add_reroute(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
+ /* properties */
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
/* internal */
RNA_def_int(ot->srna, "cursor", BC_CROSSCURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
}
@@ -312,7 +316,10 @@ static int node_add_file_exec(bContext *C, wmOperator *op)
switch (snode->nodetree->type) {
case NTREE_SHADER:
- type = SH_NODE_TEX_IMAGE;
+ if (BKE_scene_use_new_shading_nodes(CTX_data_scene(C)))
+ type = SH_NODE_TEX_IMAGE;
+ else
+ type = SH_NODE_TEXTURE;
break;
case NTREE_TEXTURE:
type = TEX_NODE_IMAGE;
@@ -333,7 +340,14 @@ static int node_add_file_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- node->id = (ID *)ima;
+ if (type == SH_NODE_TEXTURE) {
+ Tex *tex = BKE_texture_add(CTX_data_main(C), DATA_(ima->id.name));
+ tex->ima = ima;
+ node->id = (ID *)tex;
+ WM_event_add_notifier(C, NC_TEXTURE | NA_ADDED, node->id);
+ }
+ else
+ node->id = (ID *)ima;
/* When adding new image file via drag-drop we need to load imbuf in order
* to get proper image source.
@@ -503,7 +517,7 @@ static int new_node_tree_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-static EnumPropertyItem *new_node_tree_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *new_node_tree_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
return rna_node_tree_type_itemf(NULL, NULL, r_free);
}
diff --git a/source/blender/editors/space_node/node_buttons.c b/source/blender/editors/space_node/node_buttons.c
index f0567924edd..e8b4e6ec990 100644
--- a/source/blender/editors/space_node/node_buttons.c
+++ b/source/blender/editors/space_node/node_buttons.c
@@ -133,6 +133,7 @@ static void node_tree_interface_panel(const bContext *C, Panel *pa)
int in_out;
uiLayout *layout = pa->layout, *row, *split, *col;
PointerRNA ptr, sockptr, opptr;
+ wmOperatorType *ot;
if (!ntree)
return;
@@ -146,23 +147,25 @@ static void node_tree_interface_panel(const bContext *C, Panel *pa)
split = uiLayoutRow(row, true);
col = uiLayoutColumn(split, true);
+ ot = WM_operatortype_find("NODE_OT_tree_socket_add", false);
uiItemL(col, IFACE_("Inputs:"), ICON_NONE);
uiTemplateList(col, (bContext *)C, "NODE_UL_interface_sockets", "inputs", &ptr, "inputs", &ptr, "active_input",
NULL, 0, 0, 0, 0);
- opptr = uiItemFullO(col, "NODE_OT_tree_socket_add", "", ICON_PLUS, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(col, ot, "", ICON_PLUS, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "in_out", SOCK_IN);
col = uiLayoutColumn(split, true);
uiItemL(col, IFACE_("Outputs:"), ICON_NONE);
uiTemplateList(col, (bContext *)C, "NODE_UL_interface_sockets", "outputs", &ptr, "outputs", &ptr, "active_output",
NULL, 0, 0, 0, 0);
- opptr = uiItemFullO(col, "NODE_OT_tree_socket_add", "", ICON_PLUS, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(col, ot, "", ICON_PLUS, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "in_out", SOCK_OUT);
+ ot = WM_operatortype_find("NODE_OT_tree_socket_move", false);
col = uiLayoutColumn(row, true);
- opptr = uiItemFullO(col, "NODE_OT_tree_socket_move", "", ICON_TRIA_UP, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(col, ot, "", ICON_TRIA_UP, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "direction", 1);
- opptr = uiItemFullO(col, "NODE_OT_tree_socket_move", "", ICON_TRIA_DOWN, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(col, ot, "", ICON_TRIA_DOWN, NULL, WM_OP_EXEC_DEFAULT, 0, &opptr);
RNA_enum_set(&opptr, "direction", 2);
if (sock) {
diff --git a/source/blender/editors/space_node/node_draw.c b/source/blender/editors/space_node/node_draw.c
index ab40c55b59d..e56a3a549fc 100644
--- a/source/blender/editors/space_node/node_draw.c
+++ b/source/blender/editors/space_node/node_draw.c
@@ -354,6 +354,8 @@ static void node_update_basis(const bContext *C, bNodeTree *ntree, bNode *node)
dy -= NODE_DYS / 2;
/* output sockets */
+ bool add_output_space = false;
+
for (nsock = node->outputs.first; nsock; nsock = nsock->next) {
if (nodeSocketIsHidden(nsock))
continue;
@@ -386,6 +388,12 @@ static void node_update_basis(const bContext *C, bNodeTree *ntree, bNode *node)
dy = buty;
if (nsock->next)
dy -= NODE_SOCKDY;
+
+ add_output_space = true;
+ }
+
+ if (add_output_space) {
+ dy -= NODE_DY / 4;
}
node->prvr.xmin = locx + NODE_DYS;
@@ -617,34 +625,22 @@ static void node_draw_mute_line(View2D *v2d, SpaceNode *snode, bNode *node)
glDisable(GL_LINE_SMOOTH);
}
-/* this might have some more generic use */
-static void node_circle_draw(float x, float y, float size, const float col[4], int highlight)
+static void node_socket_shape_draw(
+ float x, float y, float size, const float col[4], bool highlight,
+ const float coords[][2], int coords_len)
{
- /* 16 values of sin function */
- static const float si[16] = {
- 0.00000000f, 0.39435585f, 0.72479278f, 0.93775213f,
- 0.99871650f, 0.89780453f, 0.65137248f, 0.29936312f,
- -0.10116832f, -0.48530196f, -0.79077573f, -0.96807711f,
- -0.98846832f, -0.84864425f, -0.57126821f, -0.20129852f
- };
- /* 16 values of cos function */
- static const float co[16] = {
- 1.00000000f, 0.91895781f, 0.68896691f, 0.34730525f,
- -0.05064916f, -0.44039415f, -0.75875812f, -0.95413925f,
- -0.99486932f, -0.87434661f, -0.61210598f, -0.25065253f,
- 0.15142777f, 0.52896401f, 0.82076344f, 0.97952994f,
- };
int a;
-
+
glColor4fv(col);
-
+
glEnable(GL_BLEND);
glBegin(GL_POLYGON);
- for (a = 0; a < 16; a++)
- glVertex2f(x + size * si[a], y + size * co[a]);
+ for (a = 0; a < coords_len; a++) {
+ glVertex2f(x + size * coords[a][0], y + size * coords[a][1]);
+ }
glEnd();
glDisable(GL_BLEND);
-
+
if (highlight) {
UI_ThemeColor(TH_TEXT_HI);
glLineWidth(1.5f);
@@ -655,14 +651,16 @@ static void node_circle_draw(float x, float y, float size, const float col[4], i
glEnable(GL_BLEND);
glEnable(GL_LINE_SMOOTH);
glBegin(GL_LINE_LOOP);
- for (a = 0; a < 16; a++)
- glVertex2f(x + size * si[a], y + size * co[a]);
+ for (a = 0; a < coords_len; a++) {
+ glVertex2f(x + size * coords[a][0], y + size * coords[a][1]);
+ }
glEnd();
glDisable(GL_LINE_SMOOTH);
glDisable(GL_BLEND);
}
-void node_socket_circle_draw(const bContext *C, bNodeTree *ntree, bNode *node, bNodeSocket *sock, float size, int highlight)
+
+void node_socket_draw(const bContext *C, bNodeTree *ntree, bNode *node, bNodeSocket *sock, float size, bool highlight)
{
PointerRNA ptr, node_ptr;
float color[4];
@@ -670,7 +668,60 @@ void node_socket_circle_draw(const bContext *C, bNodeTree *ntree, bNode *node, b
RNA_pointer_create((ID *)ntree, &RNA_NodeSocket, sock, &ptr);
RNA_pointer_create((ID *)ntree, &RNA_Node, node, &node_ptr);
sock->typeinfo->draw_color((bContext *)C, &ptr, &node_ptr, color);
- node_circle_draw(sock->locx, sock->locy, size, color, highlight);
+
+ /* 16 values of {sin, cos} function */
+ const float shape_circle[16][2] = {
+ {0.00000000f, 1.00000000f},
+ {0.39435585f, 0.91895781f},
+ {0.72479278f, 0.68896691f},
+ {0.93775213f, 0.34730525f},
+ {0.99871650f, -0.05064916f},
+ {0.89780453f, -0.44039415f},
+ {0.65137248f, -0.75875812f},
+ {0.29936312f, -0.95413925f},
+ {-0.10116832f, -0.99486932f},
+ {-0.48530196f, -0.87434661f},
+ {-0.79077573f, -0.61210598f},
+ {-0.96807711f, -0.25065253f},
+ {-0.98846832f, 0.15142777f},
+ {-0.84864425f, 0.52896401f},
+ {-0.57126821f, 0.82076344f},
+ {-0.20129852f, 0.97952994f }
+ };
+
+ const float shape_diamond[4][2] = {
+ {0.0f, 1.2f},
+ {1.2f, 0.0f},
+ {0.0f, -1.2f},
+ {-1.2f, 0.0f},
+ };
+
+ const float shape_square[4][2] = {
+ {-0.9f, 0.9f},
+ {0.9f, 0.9f},
+ {0.9f, -0.9f},
+ {-0.9f, -0.9f},
+ };
+
+ const float (*shape)[2];
+ int shape_len;
+ switch (sock->draw_shape) {
+ default:
+ case SOCK_DRAW_SHAPE_CIRCLE:
+ shape = shape_circle;
+ shape_len = ARRAY_SIZE(shape_circle);
+ break;
+ case SOCK_DRAW_SHAPE_DIAMOND:
+ shape = shape_diamond;
+ shape_len = ARRAY_SIZE(shape_diamond);
+ break;
+ case SOCK_DRAW_SHAPE_SQUARE:
+ shape = shape_square;
+ shape_len = ARRAY_SIZE(shape_square);
+ break;
+ }
+
+ node_socket_shape_draw(sock->locx, sock->locy, size, color, highlight, shape, shape_len);
}
/* ************** Socket callbacks *********** */
@@ -820,14 +871,6 @@ static void node_draw_basis(const bContext *C, ARegion *ar, SpaceNode *snode, bN
UI_ThemeColorBlend(color_id, TH_REDALERT, 0.5f);
-#ifdef WITH_COMPOSITOR
- if (ntree->type == NTREE_COMPOSIT && (snode->flag & SNODE_SHOW_HIGHLIGHT)) {
- if (COM_isHighlightedbNode(node)) {
- UI_ThemeColorBlend(color_id, TH_ACTIVE, 0.5f);
- }
- }
-#endif
-
glLineWidth(1.0f);
UI_draw_roundbox_corner_set(UI_CNR_TOP_LEFT | UI_CNR_TOP_RIGHT);
@@ -943,7 +986,7 @@ static void node_draw_basis(const bContext *C, ARegion *ar, SpaceNode *snode, bN
if (nodeSocketIsHidden(sock))
continue;
- node_socket_circle_draw(C, ntree, node, sock, NODE_SOCKSIZE, sock->flag & SELECT);
+ node_socket_draw(C, ntree, node, sock, NODE_SOCKSIZE, sock->flag & SELECT);
}
/* socket outputs */
@@ -951,7 +994,7 @@ static void node_draw_basis(const bContext *C, ARegion *ar, SpaceNode *snode, bN
if (nodeSocketIsHidden(sock))
continue;
- node_socket_circle_draw(C, ntree, node, sock, NODE_SOCKSIZE, sock->flag & SELECT);
+ node_socket_draw(C, ntree, node, sock, NODE_SOCKSIZE, sock->flag & SELECT);
}
/* preview */
@@ -989,16 +1032,6 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
if (node->flag & NODE_MUTED)
UI_ThemeColorBlend(color_id, TH_REDALERT, 0.5f);
-#ifdef WITH_COMPOSITOR
- if (ntree->type == NTREE_COMPOSIT && (snode->flag & SNODE_SHOW_HIGHLIGHT)) {
- if (COM_isHighlightedbNode(node)) {
- UI_ThemeColorBlend(color_id, TH_ACTIVE, 0.5f);
- }
- }
-#else
- (void)ntree;
-#endif
-
UI_draw_roundbox(rct->xmin, rct->ymin, rct->xmax, rct->ymax, hiddenrad);
/* outline active and selected emphasis */
@@ -1066,7 +1099,7 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
// BLI_snprintf(showname, sizeof(showname), "[%s]", showname); /* XXX - don't print into self! */
uiDefBut(node->block, UI_BTYPE_LABEL, 0, showname,
- iroundf(rct->xmin + NODE_MARGIN_X), iroundf(centy - NODE_DY * 0.5f),
+ round_fl_to_int(rct->xmin + NODE_MARGIN_X), round_fl_to_int(centy - NODE_DY * 0.5f),
(short)(BLI_rctf_size_x(rct) - 18.0f - 12.0f), (short)NODE_DY,
NULL, 0, 0, 0, 0, "");
}
@@ -1084,13 +1117,15 @@ static void node_draw_hidden(const bContext *C, ARegion *ar, SpaceNode *snode, b
/* sockets */
for (sock = node->inputs.first; sock; sock = sock->next) {
- if (!nodeSocketIsHidden(sock))
- node_socket_circle_draw(C, ntree, node, sock, socket_size, sock->flag & SELECT);
+ if (!nodeSocketIsHidden(sock)) {
+ node_socket_draw(C, ntree, node, sock, socket_size, sock->flag & SELECT);
+ }
}
for (sock = node->outputs.first; sock; sock = sock->next) {
- if (!nodeSocketIsHidden(sock))
- node_socket_circle_draw(C, ntree, node, sock, socket_size, sock->flag & SELECT);
+ if (!nodeSocketIsHidden(sock)) {
+ node_socket_draw(C, ntree, node, sock, socket_size, sock->flag & SELECT);
+ }
}
UI_block_end(C, node->block);
@@ -1253,15 +1288,9 @@ static void snode_setup_v2d(SpaceNode *snode, ARegion *ar, const float center[2]
static void draw_nodetree(const bContext *C, ARegion *ar, bNodeTree *ntree, bNodeInstanceKey parent_key)
{
SpaceNode *snode = CTX_wm_space_node(C);
-
+
node_uiblocks_init(C, ntree);
-
-#ifdef WITH_COMPOSITOR
- if (ntree->type == NTREE_COMPOSIT) {
- COM_startReadHighlights();
- }
-#endif
-
+
node_update_nodetree(C, ntree);
node_draw_nodetree(C, ar, snode, ntree, parent_key);
}
diff --git a/source/blender/editors/space_node/node_edit.c b/source/blender/editors/space_node/node_edit.c
index 8a61857675c..e38b48d4bb8 100644
--- a/source/blender/editors/space_node/node_edit.c
+++ b/source/blender/editors/space_node/node_edit.c
@@ -505,8 +505,6 @@ void ED_node_composit_default(const bContext *C, struct Scene *sce)
nodeAddLink(sce->nodetree, in, fromsock, out, tosock);
ntreeUpdateTree(CTX_data_main(C), sce->nodetree);
-
- // XXX ntreeCompositForceHidden(sce->nodetree);
}
/* assumes nothing being done in ntree yet, sets the default in/out node */
@@ -582,17 +580,11 @@ void snode_set_context(const bContext *C)
}
}
- if (snode->nodetree != ntree || snode->id != id || snode->from != from || snode->treepath.last == NULL) {
+ if (snode->nodetree != ntree || snode->id != id || snode->from != from ||
+ (snode->treepath.last == NULL && ntree))
+ {
ED_node_tree_start(snode, ntree, id, from);
}
-
- /* XXX Legacy hack to update render layer node outputs.
- * This should be handled by the depsgraph eventually ...
- */
- if (ED_node_is_compositor(snode) && snode->nodetree) {
- /* update output sockets based on available layers */
- ntreeCompositForceHidden(snode->nodetree);
- }
}
void snode_update(SpaceNode *snode, bNode *node)
@@ -1069,12 +1061,9 @@ int node_find_indicated_socket(SpaceNode *snode, bNode **nodep, bNodeSocket **so
/* check if we click in a socket */
for (node = snode->edittree->nodes.first; node; node = node->next) {
-
- rect.xmin = cursor[0] - (NODE_SOCKSIZE + 4);
- rect.ymin = cursor[1] - (NODE_SOCKSIZE + 4);
- rect.xmax = cursor[0] + (NODE_SOCKSIZE + 4);
- rect.ymax = cursor[1] + (NODE_SOCKSIZE + 4);
-
+
+ BLI_rctf_init_pt_radius(&rect, cursor, NODE_SOCKSIZE + 4);
+
if (!(node->flag & NODE_HIDDEN)) {
/* extra padding inside and out - allow dragging on the text areas too */
if (in_out == SOCK_IN) {
@@ -1332,7 +1321,7 @@ static int node_read_fullsamplelayers_exec(bContext *C, wmOperator *UNUSED(op))
Main *bmain = CTX_data_main(C);
SpaceNode *snode = CTX_wm_space_node(C);
Scene *curscene = CTX_data_scene(C);
- Render *re = RE_NewRender(curscene->id.name);
+ Render *re = RE_NewSceneRender(curscene);
WM_cursor_wait(1);
RE_MergeFullSample(re, bmain, curscene, snode->nodetree);
@@ -1916,7 +1905,7 @@ static int node_output_file_move_active_socket_exec(bContext *C, wmOperator *op)
void NODE_OT_output_file_move_active_socket(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{1, "UP", 0, "Up", ""},
{2, "DOWN", 0, "Down", ""},
{ 0, NULL, 0, NULL, NULL }
@@ -2097,7 +2086,7 @@ static int node_clipboard_paste_exec(bContext *C, wmOperator *op)
/* make sure all clipboard nodes would be valid in the target tree */
all_nodes_valid = true;
for (node = clipboard_nodes_lb->first; node; node = node->next) {
- if (!node->typeinfo->poll_instance(node, ntree)) {
+ if (!node->typeinfo->poll_instance || !node->typeinfo->poll_instance(node, ntree)) {
all_nodes_valid = false;
BKE_reportf(op->reports, RPT_ERROR, "Cannot add node %s into node tree %s", node->name, ntree->id.name + 2);
}
@@ -2284,7 +2273,7 @@ void NODE_OT_tree_socket_remove(wmOperatorType *ot)
/********************** Move interface socket operator *********************/
-static EnumPropertyItem move_direction_items[] = {
+static const EnumPropertyItem move_direction_items[] = {
{ 1, "UP", 0, "Up", "" },
{ 2, "DOWN", 0, "Down", "" },
{ 0, NULL, 0, NULL, NULL },
@@ -2574,17 +2563,17 @@ void NODE_OT_viewer_border(wmOperatorType *ot)
ot->idname = "NODE_OT_viewer_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = viewer_border_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = composite_node_active;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* properties */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
static int clear_viewer_border_exec(bContext *C, wmOperator *UNUSED(op))
diff --git a/source/blender/editors/space_node/node_group.c b/source/blender/editors/space_node/node_group.c
index 26eeaa91dd0..7eaf35c6c4f 100644
--- a/source/blender/editors/space_node/node_group.c
+++ b/source/blender/editors/space_node/node_group.c
@@ -37,6 +37,7 @@
#include "DNA_anim_types.h"
#include "BLI_listbase.h"
+#include "BLI_linklist.h"
#include "BLI_math.h"
#include "BLT_translation.h"
@@ -92,9 +93,9 @@ static int node_group_operator_editable(bContext *C)
* Disabled otherwise to allow pynodes define their own operators
* with same keymap.
*/
- if (STREQ(snode->tree_idname, "ShaderNodeTree") ||
- STREQ(snode->tree_idname, "CompositorNodeTree") ||
- STREQ(snode->tree_idname, "TextureNodeTree"))
+ if (ED_node_is_shader(snode) ||
+ ED_node_is_compositor(snode) ||
+ ED_node_is_texture(snode))
{
return true;
}
@@ -112,11 +113,11 @@ static const char *group_node_idname(bContext *C)
{
SpaceNode *snode = CTX_wm_space_node(C);
- if (STREQ(snode->tree_idname, "ShaderNodeTree"))
+ if (ED_node_is_shader(snode))
return "ShaderNodeGroup";
- else if (STREQ(snode->tree_idname, "CompositorNodeTree"))
+ else if (ED_node_is_compositor(snode))
return "CompositorNodeGroup";
- else if (STREQ(snode->tree_idname, "TextureNodeTree"))
+ else if (ED_node_is_texture(snode))
return "TextureNodeGroup";
return "";
@@ -186,6 +187,7 @@ static int node_group_ungroup(bNodeTree *ntree, bNode *gnode)
bNode *node, *nextnode;
bNodeTree *ngroup, *wgroup;
ListBase anim_basepaths = {NULL, NULL};
+ LinkNode *nodes_delayed_free = NULL;
ngroup = (bNodeTree *)gnode->id;
@@ -208,8 +210,8 @@ static int node_group_ungroup(bNodeTree *ntree, bNode *gnode)
* This also removes remaining links to and from interface nodes.
*/
if (ELEM(node->type, NODE_GROUP_INPUT, NODE_GROUP_OUTPUT)) {
- nodeFreeNode(wgroup, node);
- continue;
+ /* We must delay removal since sockets will reference this node. see: T52092 */
+ BLI_linklist_prepend(&nodes_delayed_free, node);
}
/* keep track of this node's RNA "base" path (the part of the path identifying the node)
@@ -336,6 +338,11 @@ static int node_group_ungroup(bNodeTree *ntree, bNode *gnode)
}
}
+ while (nodes_delayed_free) {
+ node = BLI_linklist_pop(&nodes_delayed_free);
+ nodeFreeNode(ntree, node);
+ }
+
/* delete the group instance */
nodeFreeNode(ntree, gnode);
@@ -508,7 +515,7 @@ typedef enum eNodeGroupSeparateType {
} eNodeGroupSeparateType;
/* Operator Property */
-static EnumPropertyItem node_group_separate_types[] = {
+static const EnumPropertyItem node_group_separate_types[] = {
{NODE_GS_COPY, "COPY", 0, "Copy", "Copy to parent node tree, keep group intact"},
{NODE_GS_MOVE, "MOVE", 0, "Move", "Move to parent node tree, remove from group"},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/space_node/node_intern.h b/source/blender/editors/space_node/node_intern.h
index 6b8fa0b88fe..352f9e51012 100644
--- a/source/blender/editors/space_node/node_intern.h
+++ b/source/blender/editors/space_node/node_intern.h
@@ -67,8 +67,9 @@ void snode_group_offset(struct SpaceNode *snode, float *x, float *y); /* transfo
/* node_draw.c */
int node_get_colorid(struct bNode *node);
-void node_socket_circle_draw(const struct bContext *C, struct bNodeTree *ntree, struct bNode *node,
- struct bNodeSocket *sock, float size, int highlight);
+void node_socket_draw(
+ const struct bContext *C, struct bNodeTree *ntree, struct bNode *node,
+ struct bNodeSocket *sock, float size, bool highlight);
int node_get_resize_cursor(int directions);
void node_draw_shadow(struct SpaceNode *snode, struct bNode *node, float radius, float alpha);
void node_draw_default(const struct bContext *C, struct ARegion *ar, struct SpaceNode *snode,
diff --git a/source/blender/editors/space_node/node_relationships.c b/source/blender/editors/space_node/node_relationships.c
index 5f592431558..70f7553cf41 100644
--- a/source/blender/editors/space_node/node_relationships.c
+++ b/source/blender/editors/space_node/node_relationships.c
@@ -31,12 +31,14 @@
#include "MEM_guardedalloc.h"
+#include "DNA_anim_types.h"
#include "DNA_node_types.h"
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_easing.h"
+#include "BKE_animsys.h"
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_library.h"
@@ -63,6 +65,15 @@
/* ****************** Relations helpers *********************** */
+static bool ntree_has_drivers(bNodeTree *ntree)
+{
+ AnimData *adt = BKE_animdata_from_id(&ntree->id);
+ if (adt == NULL) {
+ return false;
+ }
+ return !BLI_listbase_is_empty(&adt->drivers);
+}
+
static bool ntree_check_nodes_connected_dfs(bNodeTree *ntree,
bNode *from,
bNode *to)
@@ -134,6 +145,14 @@ static bool node_group_has_output(bNode *node)
bool node_connected_to_output(bNodeTree *ntree, bNode *node)
{
+ /* Special case for drivers: if node tree has any drivers we assume it is
+ * always to be tagged for update when node changes. Otherwise we will be
+ * doomed to do some deep and nasty deep search of indirect dependencies,
+ * which will be too complicated without real benefit.
+ */
+ if (ntree_has_drivers(ntree)) {
+ return true;
+ }
for (bNode *current_node = ntree->nodes.first;
current_node != NULL;
current_node = current_node->next)
@@ -144,11 +163,17 @@ bool node_connected_to_output(bNodeTree *ntree, bNode *node)
* We could make check more grained here by taking which socket the node
* is connected to and so eventually.
*/
- if (current_node->type == NODE_GROUP &&
- ntree_check_nodes_connected(ntree, node, current_node) &&
- node_group_has_output(current_node))
- {
- return true;
+ if (current_node->type == NODE_GROUP) {
+ if (current_node->id != NULL &&
+ ntree_has_drivers((bNodeTree *)current_node->id))
+ {
+ return true;
+ }
+ if (ntree_check_nodes_connected(ntree, node, current_node) &&
+ node_group_has_output(current_node))
+ {
+ return true;
+ }
}
if (current_node->flag & NODE_DO_OUTPUT) {
if (ntree_check_nodes_connected(ntree, node, current_node)) {
@@ -567,7 +592,13 @@ static void node_link_exit(bContext *C, wmOperator *op, bool apply_links)
ntree->is_updating = true;
for (linkdata = nldrag->links.first; linkdata; linkdata = linkdata->next) {
bNodeLink *link = linkdata->data;
-
+
+ /* See note below, but basically TEST flag means that the link
+ * was connected to output (or to a node which affects the
+ * output).
+ */
+ do_tag_update |= (link->flag & NODE_LINK_TEST) != 0;
+
if (apply_links && link->tosock && link->fromsock) {
/* before actually adding the link,
* let nodes perform special link insertion handling
@@ -593,11 +624,6 @@ static void node_link_exit(bContext *C, wmOperator *op, bool apply_links)
}
}
else {
- /* See note below, but basically TEST flag means that the link
- * was connected to output (or to a node which affects the
- * output).
- */
- do_tag_update |= (link->flag & NODE_LINK_TEST) != 0;
nodeRemLink(ntree, link);
}
}
@@ -1006,8 +1032,6 @@ static int cut_links_exec(bContext *C, wmOperator *op)
void NODE_OT_links_cut(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
ot->name = "Cut Links";
ot->idname = "NODE_OT_links_cut";
ot->description = "Use the mouse to cut (remove) some links";
@@ -1022,8 +1046,11 @@ void NODE_OT_links_cut(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
+ /* properties */
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
/* internal */
RNA_def_int(ot->srna, "cursor", BC_KNIFECURSOR, 0, INT_MAX, "Cursor", "", 0, INT_MAX);
}
diff --git a/source/blender/editors/space_node/node_select.c b/source/blender/editors/space_node/node_select.c
index 7195d2a9838..4b4add0e698 100644
--- a/source/blender/editors/space_node/node_select.c
+++ b/source/blender/editors/space_node/node_select.c
@@ -34,7 +34,7 @@
#include "BLI_utildefines.h"
#include "BLI_rect.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_math.h"
#include "BLI_string.h"
#include "BLI_string_utf8.h"
@@ -333,7 +333,7 @@ static int node_select_grouped_exec(bContext *C, wmOperator *op)
void NODE_OT_select_grouped(wmOperatorType *ot)
{
- static EnumPropertyItem prop_select_grouped_types[] = {
+ static const EnumPropertyItem prop_select_grouped_types[] = {
{NODE_SELECT_GROUPED_TYPE, "TYPE", 0, "Type", ""},
{NODE_SELECT_GROUPED_COLOR, "COLOR", 0, "Color", ""},
{NODE_SELECT_GROUPED_PREFIX, "PREFIX", 0, "Prefix", ""},
@@ -524,23 +524,23 @@ static int node_borderselect_exec(bContext *C, wmOperator *op)
ARegion *ar = CTX_wm_region(C);
bNode *node;
rctf rectf;
- int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
const bool extend = RNA_boolean_get(op->ptr, "extend");
WM_operator_properties_border_to_rctf(op, &rectf);
UI_view2d_region_to_view_rctf(&ar->v2d, &rectf, &rectf);
for (node = snode->edittree->nodes.first; node; node = node->next) {
- bool select;
+ bool is_inside;
if (node->type == NODE_FRAME) {
- select = BLI_rctf_inside_rctf(&rectf, &node->totr);
+ is_inside = BLI_rctf_inside_rctf(&rectf, &node->totr);
}
else {
- select = BLI_rctf_isect(&rectf, &node->totr, NULL);
+ is_inside = BLI_rctf_isect(&rectf, &node->totr, NULL);
}
- if (select) {
- nodeSetSelected(node, (gesture_mode == GESTURE_MODAL_SELECT));
+ if (is_inside) {
+ nodeSetSelected(node, select);
}
else if (!extend) {
nodeSetSelected(node, false);
@@ -571,7 +571,7 @@ static int node_border_select_invoke(bContext *C, wmOperator *op, const wmEvent
return OPERATOR_CANCELLED | OPERATOR_PASS_THROUGH;
}
- return WM_border_select_invoke(C, op, event);
+ return WM_gesture_border_invoke(C, op, event);
}
void NODE_OT_select_border(wmOperatorType *ot)
@@ -584,8 +584,8 @@ void NODE_OT_select_border(wmOperatorType *ot)
/* api callbacks */
ot->invoke = node_border_select_invoke;
ot->exec = node_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_node_active;
@@ -593,7 +593,7 @@ void NODE_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
RNA_def_boolean(ot->srna, "tweak", 0, "Tweak", "Only activate when mouse is not over a node - useful for tweak gesture");
}
@@ -605,12 +605,12 @@ static int node_circleselect_exec(bContext *C, wmOperator *op)
ARegion *ar = CTX_wm_region(C);
bNode *node;
- int x, y, radius, gesture_mode;
+ int x, y, radius;
float offset[2];
float zoom = (float)(BLI_rcti_size_x(&ar->winrct)) / (float)(BLI_rctf_size_x(&ar->v2d.cur));
- gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
/* get operator properties */
x = RNA_int_get(op->ptr, "x");
@@ -621,7 +621,7 @@ static int node_circleselect_exec(bContext *C, wmOperator *op)
for (node = snode->edittree->nodes.first; node; node = node->next) {
if (BLI_rctf_isect_circle(&node->totr, offset, radius / zoom)) {
- nodeSetSelected(node, (gesture_mode == GESTURE_MODAL_SELECT));
+ nodeSetSelected(node, select);
}
}
@@ -647,11 +647,8 @@ void NODE_OT_select_circle(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- /* rna */
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
+ /* properties */
+ WM_operator_properties_gesture_circle_select(ot);
}
/* ****** Lasso Select ****** */
@@ -728,9 +725,7 @@ void NODE_OT_select_lasso(wmOperatorType *ot)
ot->flag = OPTYPE_UNDO;
/* properties */
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
+ WM_operator_properties_gesture_lasso_select(ot);
}
/* ****** Select/Deselect All ****** */
diff --git a/source/blender/editors/space_node/node_templates.c b/source/blender/editors/space_node/node_templates.c
index ec525e684b0..173c919e38c 100644
--- a/source/blender/editors/space_node/node_templates.c
+++ b/source/blender/editors/space_node/node_templates.c
@@ -53,7 +53,7 @@
#include "ED_node.h" /* own include */
-#include "ED_util.h"
+#include "ED_undo.h"
/************************* Node Socket Manipulation **************************/
@@ -482,10 +482,10 @@ static void ui_node_menu_column(NodeLinkArg *arg, int nclass, const char *cname)
}
NODE_TYPES_END
- qsort(sorted_ntypes, BLI_array_count(sorted_ntypes), sizeof(bNodeType *), ui_node_item_name_compare);
+ qsort(sorted_ntypes, BLI_array_len(sorted_ntypes), sizeof(bNodeType *), ui_node_item_name_compare);
/* generate UI */
- for (int j = 0; j < BLI_array_count(sorted_ntypes); j++) {
+ for (int j = 0; j < BLI_array_len(sorted_ntypes); j++) {
bNodeType *ntype = sorted_ntypes[j];
NodeLinkItem *items;
int totitems;
@@ -683,10 +683,11 @@ static void ui_node_draw_input(uiLayout *layout, bContext *C, bNodeTree *ntree,
RNA_pointer_create(&ntree->id, &RNA_Node, node, &nodeptr);
/* indented label */
- for (i = 0; i < indent; i++)
+ for (i = 0; i < indent; i++) {
label[i] = ' ';
+ }
label[indent] = '\0';
- BLI_snprintf(label, UI_MAX_NAME_STR, "%s%s:", label, IFACE_(input->name));
+ BLI_snprintf(label + indent, UI_MAX_NAME_STR - indent, "%s:", IFACE_(input->name));
/* split in label and value */
split = uiLayoutSplit(layout, 0.35f, false);
diff --git a/source/blender/editors/space_node/node_view.c b/source/blender/editors/space_node/node_view.c
index 8c5d2d82468..f497a06cb12 100644
--- a/source/blender/editors/space_node/node_view.c
+++ b/source/blender/editors/space_node/node_view.c
@@ -345,7 +345,7 @@ static int backimage_fit_exec(bContext *C, wmOperator *UNUSED(op))
ima = BKE_image_verify_viewer(IMA_TYPE_COMPOSITE, "Viewer Node");
ibuf = BKE_image_acquire_ibuf(ima, NULL, &lock);
- if (ibuf == NULL) {
+ if ((ibuf == NULL) || (ibuf->x == 0) || (ibuf->y == 0)) {
BKE_image_release_ibuf(ima, ibuf, lock);
return OPERATOR_CANCELLED;
}
@@ -417,20 +417,18 @@ static void sample_draw(const bContext *C, ARegion *ar, void *arg_info)
}
}
-/* Returns color in the display space, matching ED_space_image_color_sample().
+/* Returns color in linear space, matching ED_space_image_color_sample().
* And here we've got recursion in the comments tips...
*/
-bool ED_space_node_color_sample(Scene *scene, SpaceNode *snode, ARegion *ar, int mval[2], float r_col[3])
+bool ED_space_node_color_sample(SpaceNode *snode, ARegion *ar, int mval[2], float r_col[3])
{
- const char *display_device = scene->display_settings.display_device;
- struct ColorManagedDisplay *display = IMB_colormanagement_display_get_named(display_device);
void *lock;
Image *ima;
ImBuf *ibuf;
float fx, fy, bufx, bufy;
bool ret = false;
- if (STREQ(snode->tree_idname, ntreeType_Composite->idname) || (snode->flag & SNODE_BACKDRAW) == 0) {
+ if (!ED_node_is_compositor(snode) || (snode->flag & SNODE_BACKDRAW) == 0) {
/* use viewer image for color sampling only if we're in compositor tree
* with backdrop enabled
*/
@@ -471,10 +469,6 @@ bool ED_space_node_color_sample(Scene *scene, SpaceNode *snode, ARegion *ar, int
}
}
- if (ret) {
- IMB_colormanagement_scene_linear_to_display_v3(r_col, display);
- }
-
BKE_image_release_ibuf(ima, ibuf, lock);
return ret;
diff --git a/source/blender/editors/space_node/space_node.c b/source/blender/editors/space_node/space_node.c
index bbdf6feef01..2267316d257 100644
--- a/source/blender/editors/space_node/space_node.c
+++ b/source/blender/editors/space_node/space_node.c
@@ -753,6 +753,10 @@ static void node_region_listener(bScreen *UNUSED(sc), ScrArea *UNUSED(sa), ARegi
break;
}
break;
+ case NC_WM:
+ if (wmn->data == ND_JOB)
+ ED_region_tag_redraw(ar);
+ break;
case NC_SCENE:
case NC_MATERIAL:
case NC_TEXTURE:
diff --git a/source/blender/editors/space_outliner/outliner_draw.c b/source/blender/editors/space_outliner/outliner_draw.c
index 99242fd12f9..d8d6b09ac6b 100644
--- a/source/blender/editors/space_outliner/outliner_draw.c
+++ b/source/blender/editors/space_outliner/outliner_draw.c
@@ -401,7 +401,7 @@ void restrictbutton_gr_restrict_flag(void *poin, void *poin2, int flag)
if (group_restrict_flag(gr, flag)) {
for (gob = gr->gobject.first; gob; gob = gob->next) {
- if (ID_IS_LINKED_DATABLOCK(gob->ob))
+ if (ID_IS_LINKED(gob->ob))
continue;
gob->ob->restrictflag &= ~flag;
@@ -413,7 +413,7 @@ void restrictbutton_gr_restrict_flag(void *poin, void *poin2, int flag)
}
else {
for (gob = gr->gobject.first; gob; gob = gob->next) {
- if (ID_IS_LINKED_DATABLOCK(gob->ob))
+ if (ID_IS_LINKED(gob->ob))
continue;
/* not in editmode */
@@ -654,7 +654,7 @@ static void outliner_draw_restrictbuts(uiBlock *block, Scene *scene, ARegion *ar
int but_flag = UI_BUT_DRAG_LOCK;
gr = (Group *)tselem->id;
- if (ID_IS_LINKED_DATABLOCK(gr))
+ if (ID_IS_LINKED(gr))
but_flag |= UI_BUT_DISABLED;
UI_block_emboss_set(block, UI_EMBOSS_NONE);
@@ -827,7 +827,7 @@ static void outliner_draw_userbuts(uiBlock *block, ARegion *ar, SpaceOops *soops
char buf[16] = "";
int but_flag = UI_BUT_DRAG_LOCK;
- if (ID_IS_LINKED_DATABLOCK(id))
+ if (ID_IS_LINKED(id))
but_flag |= UI_BUT_DISABLED;
UI_block_emboss_set(block, UI_EMBOSS_NONE);
@@ -993,7 +993,7 @@ static void tselem_draw_icon_uibut(struct DrawIconArg *arg, int icon)
else {
uiBut *but = uiDefIconBut(arg->block, UI_BTYPE_LABEL, 0, icon, arg->xb, arg->yb, UI_UNIT_X, UI_UNIT_Y, NULL,
0.0, 0.0, 1.0, arg->alpha,
- (arg->id && ID_IS_LINKED_DATABLOCK(arg->id)) ? arg->id->lib->name : "");
+ (arg->id && ID_IS_LINKED(arg->id)) ? arg->id->lib->name : "");
if (arg->id)
UI_but_drag_set_id(but, arg->id);
@@ -1040,9 +1040,6 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
struct DrawIconArg arg;
float aspect;
- /* icons tiny bit away from text */
- x -= 0.15f * UI_UNIT_Y;
-
/* make function calls a bit compacter */
arg.block = block;
arg.id = tselem->id;
@@ -1053,8 +1050,10 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
/* placement of icons, copied from interface_widgets.c */
aspect = (0.8f * UI_UNIT_Y) / ICON_DEFAULT_HEIGHT;
- arg.x = x = x + 4.0f * aspect;
- arg.y = y = y + 0.1f * UI_UNIT_Y;
+ x += 2.0f * aspect;
+ y += 2.0f * aspect;
+ arg.x = x;
+ arg.y = y;
if (tselem->type) {
switch (tselem->type) {
@@ -1126,6 +1125,7 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
case eModifierType_Cast:
UI_icon_draw(x, y, ICON_MOD_CAST); break;
case eModifierType_MeshDeform:
+ case eModifierType_SurfaceDeform:
UI_icon_draw(x, y, ICON_MOD_MESHDEFORM); break;
case eModifierType_Bevel:
UI_icon_draw(x, y, ICON_MOD_BEVEL); break;
@@ -1273,7 +1273,10 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
}
}
else {
- switch (GS(tselem->id->name)) {
+ /* TODO(sergey): Casting to short here just to handle ID_NLA which is
+ * NOT inside of IDType enum.
+ */
+ switch ((short)GS(tselem->id->name)) {
case ID_SCE:
tselem_draw_icon_uibut(&arg, ICON_SCENE_DATA); break;
case ID_ME:
@@ -1343,6 +1346,8 @@ static void tselem_draw_icon(uiBlock *block, int xmax, float x, float y, TreeSto
tselem_draw_icon_uibut(&arg, ICON_LINE_DATA); break;
case ID_GD:
tselem_draw_icon_uibut(&arg, ICON_GREASEPENCIL); break;
+ default:
+ break;
}
}
}
@@ -1388,9 +1393,9 @@ static void outliner_draw_iconrow(bContext *C, uiBlock *block, Scene *scene, Spa
UI_draw_roundbox_corner_set(UI_CNR_ALL);
glColor4ub(255, 255, 255, 100);
UI_draw_roundbox(
- (float) *offsx - 1.0f * ufac,
+ (float) *offsx + 1.0f * ufac,
(float)ys + 1.0f * ufac,
- (float)*offsx + UI_UNIT_X - 2.0f * ufac,
+ (float)*offsx + UI_UNIT_X - 1.0f * ufac,
(float)ys + UI_UNIT_Y - ufac,
(float)UI_UNIT_Y / 2.0f - ufac);
glEnable(GL_BLEND); /* roundbox disables */
@@ -1535,9 +1540,9 @@ static void outliner_draw_tree_element(
if (active != OL_DRAWSEL_NONE) {
UI_draw_roundbox_corner_set(UI_CNR_ALL);
UI_draw_roundbox(
- (float)startx + UI_UNIT_X,
+ (float)startx + UI_UNIT_X + 1.0f * ufac,
(float)*starty + 1.0f * ufac,
- (float)startx + 2.0f * UI_UNIT_X - 2.0f * ufac,
+ (float)startx + 2.0f * UI_UNIT_X - 1.0f * ufac,
(float)*starty + UI_UNIT_Y - 1.0f * ufac,
UI_UNIT_Y / 2.0f - 1.0f * ufac);
glEnable(GL_BLEND); /* roundbox disables it */
@@ -1548,16 +1553,13 @@ static void outliner_draw_tree_element(
/* open/close icon, only when sublevels, except for scene */
if (te->subtree.first || (tselem->type == 0 && te->idcode == ID_SCE) || (te->flag & TE_LAZY_CLOSED)) {
int icon_x;
- if (tselem->type == 0 && ELEM(te->idcode, ID_OB, ID_SCE))
- icon_x = startx;
- else
- icon_x = startx + 5 * ufac;
+ icon_x = startx;
// icons a bit higher
if (TSELEM_OPEN(tselem, soops))
- UI_icon_draw((float)icon_x, (float)*starty + 2 * ufac, ICON_DISCLOSURE_TRI_DOWN);
+ UI_icon_draw((float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_DOWN);
else
- UI_icon_draw((float)icon_x, (float)*starty + 2 * ufac, ICON_DISCLOSURE_TRI_RIGHT);
+ UI_icon_draw((float)icon_x + 2 * ufac, (float)*starty + 1 * ufac, ICON_DISCLOSURE_TRI_RIGHT);
}
offsx += UI_UNIT_X;
@@ -1567,24 +1569,24 @@ static void outliner_draw_tree_element(
tselem_draw_icon(block, xmax, (float)startx + offsx, (float)*starty, tselem, te, 1.0f);
- offsx += UI_UNIT_X;
+ offsx += UI_UNIT_X + 2 * ufac;
}
else
offsx += 2 * ufac;
- if (tselem->type == 0 && ID_IS_LINKED_DATABLOCK(tselem->id)) {
+ if (tselem->type == 0 && ID_IS_LINKED(tselem->id)) {
glPixelTransferf(GL_ALPHA_SCALE, 0.5f);
if (tselem->id->tag & LIB_TAG_MISSING) {
- UI_icon_draw((float)startx + offsx, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_BROKEN);
+ UI_icon_draw((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_BROKEN);
}
else if (tselem->id->tag & LIB_TAG_INDIRECT) {
- UI_icon_draw((float)startx + offsx, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_INDIRECT);
+ UI_icon_draw((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_INDIRECT);
}
else {
- UI_icon_draw((float)startx + offsx, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_DIRECT);
+ UI_icon_draw((float)startx + offsx + 2 * ufac, (float)*starty + 2 * ufac, ICON_LIBRARY_DATA_DIRECT);
}
glPixelTransferf(GL_ALPHA_SCALE, 1.0f);
- offsx += UI_UNIT_X;
+ offsx += UI_UNIT_X + 2 * ufac;
}
glDisable(GL_BLEND);
@@ -1756,7 +1758,7 @@ static void outliner_draw_tree(bContext *C, uiBlock *block, Scene *scene, ARegio
// gray hierarchy lines
UI_ThemeColorBlend(TH_BACK, TH_TEXT, 0.4f);
starty = (int)ar->v2d.tot.ymax - UI_UNIT_Y / 2 - OL_Y_OFFSET;
- startx = 6;
+ startx = UI_UNIT_X / 2 - 1.0f;
outliner_draw_hierarchy(soops, &soops->tree, startx, &starty);
// items themselves
diff --git a/source/blender/editors/space_outliner/outliner_edit.c b/source/blender/editors/space_outliner/outliner_edit.c
index 345ac353c11..71edd855cf0 100644
--- a/source/blender/editors/space_outliner/outliner_edit.c
+++ b/source/blender/editors/space_outliner/outliner_edit.c
@@ -52,7 +52,6 @@
#include "BKE_animsys.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
-#include "BKE_global.h"
#include "BKE_idcode.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
@@ -230,7 +229,7 @@ static void do_item_rename(ARegion *ar, TreeElement *te, TreeStoreElem *tselem,
else if (ELEM(tselem->type, TSE_SEQUENCE, TSE_SEQ_STRIP, TSE_SEQUENCE_DUP)) {
BKE_report(reports, RPT_WARNING, "Cannot edit sequence name");
}
- else if (ID_IS_LINKED_DATABLOCK(tselem->id)) {
+ else if (ID_IS_LINKED(tselem->id)) {
BKE_report(reports, RPT_WARNING, "Cannot edit external libdata");
}
else if (te->idcode == ID_LI && ((Library *)tselem->id)->parent) {
@@ -309,9 +308,12 @@ static void id_delete(bContext *C, ReportList *reports, TreeElement *te, TreeSto
ID *id = tselem->id;
BLI_assert(te->idcode != 0 && id != NULL);
- BLI_assert(te->idcode != ID_LI || ((Library *)id)->parent == NULL);
UNUSED_VARS_NDEBUG(te);
+ if (te->idcode == ID_LI && ((Library *)id)->parent != NULL) {
+ BKE_reportf(reports, RPT_WARNING, "Cannot delete indirectly linked library '%s'", id->name);
+ return;
+ }
if (id->tag & LIB_TAG_INDIRECT) {
BKE_reportf(reports, RPT_WARNING, "Cannot delete indirectly linked id '%s'", id->name);
return;
@@ -418,7 +420,7 @@ static int outliner_id_remap_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- if (ID_IS_LINKED_DATABLOCK(old_id)) {
+ if (ID_IS_LINKED(old_id)) {
BKE_reportf(op->reports, RPT_WARNING,
"Old ID '%s' is linked from a library, indirect usages of this data-block will not be remapped",
old_id->name);
@@ -479,7 +481,7 @@ static int outliner_id_remap_invoke(bContext *C, wmOperator *op, const wmEvent *
return WM_operator_props_dialog_popup(C, op, 200, 100);
}
-static EnumPropertyItem *outliner_id_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *outliner_id_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem item_tmp = {0}, *item = NULL;
int totitem = 0;
@@ -516,7 +518,8 @@ void OUTLINER_OT_id_remap(wmOperatorType *ot)
ot->flag = 0;
- RNA_def_enum(ot->srna, "id_type", rna_enum_id_type_items, ID_OB, "ID Type", "");
+ prop = RNA_def_enum(ot->srna, "id_type", rna_enum_id_type_items, ID_OB, "ID Type", "");
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_ID);
prop = RNA_def_enum(ot->srna, "old_id", DummyRNA_NULL_items, 0, "Old ID", "Old ID to replace");
RNA_def_property_enum_funcs_runtime(prop, NULL, NULL, outliner_id_itemf);
@@ -789,7 +792,7 @@ void object_toggle_visibility_cb(
Base *base = (Base *)te->directdata;
Object *ob = (Object *)tselem->id;
- if (ID_IS_LINKED_DATABLOCK(tselem->id)) {
+ if (ID_IS_LINKED(tselem->id)) {
BKE_report(reports, RPT_WARNING, "Cannot edit external libdata");
return;
}
@@ -850,7 +853,7 @@ void object_toggle_selectability_cb(
{
Base *base = (Base *)te->directdata;
- if (ID_IS_LINKED_DATABLOCK(tselem->id)) {
+ if (ID_IS_LINKED(tselem->id)) {
BKE_report(reports, RPT_WARNING, "Cannot edit external libdata");
return;
}
@@ -905,7 +908,7 @@ void object_toggle_renderability_cb(
{
Base *base = (Base *)te->directdata;
- if (ID_IS_LINKED_DATABLOCK(tselem->id)) {
+ if (ID_IS_LINKED(tselem->id)) {
BKE_report(reports, RPT_WARNING, "Cannot edit external libdata");
return;
}
@@ -1088,7 +1091,7 @@ static int outliner_show_active_exec(bContext *C, wmOperator *UNUSED(op))
te = outliner_find_id(so, &so->tree, &obact->id);
- if (obact->type == OB_ARMATURE) {
+ if (te != NULL && obact->type == OB_ARMATURE) {
/* traverse down the bone hierarchy in case of armature */
TreeElement *te_obact = te;
@@ -1940,7 +1943,7 @@ static int outliner_orphans_purge_invoke(bContext *C, wmOperator *op, const wmEv
{
/* present a prompt to informing users that this change is irreversible */
return WM_operator_confirm_message(C, op,
- "Purging unused data-blocks cannot be undone. "
+ "Purging unused data-blocks cannot be undone and saves to current .blend file. "
"Click here to proceed...");
}
@@ -1962,7 +1965,8 @@ void OUTLINER_OT_orphans_purge(wmOperatorType *ot)
/* identifiers */
ot->idname = "OUTLINER_OT_orphans_purge";
ot->name = "Purge All";
- ot->description = "Clear all orphaned data-blocks without any users from the file (cannot be undone)";
+ ot->description = "Clear all orphaned data-blocks without any users from the file "
+ "(cannot be undone, saves to current .blend file)";
/* callbacks */
ot->invoke = outliner_orphans_purge_invoke;
@@ -1992,7 +1996,7 @@ static int parent_drop_exec(bContext *C, wmOperator *op)
RNA_string_get(op->ptr, "child", childname);
ob = (Object *)BKE_libblock_find_name(ID_OB, childname);
- if (ID_IS_LINKED_DATABLOCK(ob)) {
+ if (ID_IS_LINKED(ob)) {
BKE_report(op->reports, RPT_INFO, "Can't edit library linked object");
return OPERATOR_CANCELLED;
}
@@ -2040,7 +2044,7 @@ static int parent_drop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
if (ob == par) {
return OPERATOR_CANCELLED;
}
- if (ID_IS_LINKED_DATABLOCK(ob)) {
+ if (ID_IS_LINKED(ob)) {
BKE_report(op->reports, RPT_INFO, "Can't edit library linked object");
return OPERATOR_CANCELLED;
}
@@ -2068,74 +2072,62 @@ static int parent_drop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
wmOperatorType *ot = WM_operatortype_find("OUTLINER_OT_parent_drop", false);
uiPopupMenu *pup = UI_popup_menu_begin(C, IFACE_("Set Parent To"), ICON_NONE);
uiLayout *layout = UI_popup_menu_layout(pup);
-
PointerRNA ptr;
- WM_operator_properties_create_ptr(&ptr, ot);
+ /* Cannot use uiItemEnumO()... have multiple properties to set. */
+ uiItemFullO_ptr(layout, ot, IFACE_("Object"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_OBJECT);
- /* Cannot use uiItemEnumO()... have multiple properties to set. */
- uiItemFullO_ptr(layout, ot, IFACE_("Object"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
+
/* par becomes parent, make the associated menus */
if (par->type == OB_ARMATURE) {
- WM_operator_properties_create_ptr(&ptr, ot);
+ uiItemFullO_ptr(layout, ot, IFACE_("Armature Deform"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_ARMATURE);
- uiItemFullO_ptr(layout, ot, IFACE_("Armature Deform"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_(" With Empty Groups"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_ARMATURE_NAME);
- uiItemFullO_ptr(layout, ot, IFACE_(" With Empty Groups"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_(" With Envelope Weights"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_ARMATURE_ENVELOPE);
- uiItemFullO_ptr(layout, ot, IFACE_(" With Envelope Weights"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_(" With Automatic Weights"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_ARMATURE_AUTO);
- uiItemFullO_ptr(layout, ot, IFACE_(" With Automatic Weights"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_("Bone"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_BONE);
- uiItemFullO_ptr(layout, ot, IFACE_("Bone"),
- 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
}
else if (par->type == OB_CURVE) {
- WM_operator_properties_create_ptr(&ptr, ot);
+ uiItemFullO_ptr(layout, ot, IFACE_("Curve Deform"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_CURVE);
- uiItemFullO_ptr(layout, ot, IFACE_("Curve Deform"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_("Follow Path"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_FOLLOW);
- uiItemFullO_ptr(layout, ot, IFACE_("Follow Path"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
-
- WM_operator_properties_create_ptr(&ptr, ot);
+
+ uiItemFullO_ptr(layout, ot, IFACE_("Path Constraint"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_PATH_CONST);
- uiItemFullO_ptr(layout, ot, IFACE_("Path Constraint"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
}
else if (par->type == OB_LATTICE) {
- WM_operator_properties_create_ptr(&ptr, ot);
+ uiItemFullO_ptr(layout, ot, IFACE_("Lattice Deform"), 0, NULL, WM_OP_EXEC_DEFAULT, 0, &ptr);
RNA_string_set(&ptr, "parent", parname);
RNA_string_set(&ptr, "child", childname);
RNA_enum_set(&ptr, "type", PAR_LATTICE);
- uiItemFullO_ptr(layout, ot, IFACE_("Lattice Deform"), 0, ptr.data, WM_OP_EXEC_DEFAULT, 0);
}
UI_popup_menu_end(C, pup);
@@ -2249,7 +2241,7 @@ static int scene_drop_invoke(bContext *C, wmOperator *op, const wmEvent *event)
RNA_string_get(op->ptr, "object", obname);
ob = (Object *)BKE_libblock_find_name(ID_OB, obname);
- if (ELEM(NULL, ob, scene) || ID_IS_LINKED_DATABLOCK(scene)) {
+ if (ELEM(NULL, ob, scene) || ID_IS_LINKED(scene)) {
return OPERATOR_CANCELLED;
}
diff --git a/source/blender/editors/space_outliner/outliner_intern.h b/source/blender/editors/space_outliner/outliner_intern.h
index ccc52f2dba8..ca7dbe4f73c 100644
--- a/source/blender/editors/space_outliner/outliner_intern.h
+++ b/source/blender/editors/space_outliner/outliner_intern.h
@@ -150,7 +150,13 @@ eOLDrawState tree_element_type_active(
TreeElement *te, TreeStoreElem *tselem, const eOLSetState set, bool recursive);
eOLDrawState tree_element_active(struct bContext *C, struct Scene *scene, SpaceOops *soops,
TreeElement *te, const eOLSetState set, const bool handle_all_types);
-int outliner_item_do_activate(struct bContext *C, int x, int y, bool extend, bool recursive);
+
+void outliner_item_do_activate_from_tree_element(
+ struct bContext *C, TreeElement *te, TreeStoreElem *tselem,
+ bool extend, bool recursive);
+int outliner_item_do_activate_from_cursor(
+ struct bContext *C, const int mval[2],
+ bool extend, bool recursive);
/* outliner_edit.c ---------------------------------------------- */
typedef void (*outliner_operation_cb)(
diff --git a/source/blender/editors/space_outliner/outliner_select.c b/source/blender/editors/space_outliner/outliner_select.c
index 89df471990a..0b8724b4e28 100644
--- a/source/blender/editors/space_outliner/outliner_select.c
+++ b/source/blender/editors/space_outliner/outliner_select.c
@@ -54,7 +54,7 @@
#include "ED_object.h"
#include "ED_screen.h"
#include "ED_sequencer.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -143,8 +143,8 @@ static eOLDrawState tree_element_active_renderlayer(
/**
* Select object tree:
- * CTRL+LMB: Select/Deselect object and all cildren
- * CTRL+SHIFT+LMB: Add/Remove object and all children
+ * CTRL+LMB: Select/Deselect object and all children.
+ * CTRL+SHIFT+LMB: Add/Remove object and all children.
*/
static void do_outliner_object_select_recursive(Scene *scene, Object *ob_parent, bool select)
{
@@ -241,7 +241,7 @@ static eOLDrawState tree_element_set_active_object(
}
if (ob != scene->obedit)
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO);
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
return OL_DRAWSEL_NORMAL;
}
@@ -470,10 +470,11 @@ static eOLDrawState tree_element_active_defgroup(
WM_event_add_notifier(C, NC_OBJECT | ND_TRANSFORM, ob);
}
else {
- if (ob == OBACT)
+ if (ob == OBACT) {
if (ob->actdef == te->index + 1) {
return OL_DRAWSEL_NORMAL;
}
+ }
}
return OL_DRAWSEL_NONE;
}
@@ -621,7 +622,7 @@ static eOLDrawState tree_element_active_ebone(
if (set != OL_SETSEL_NONE) {
if (set == OL_SETSEL_NORMAL) {
if (!(ebone->flag & BONE_HIDDEN_A)) {
- ED_armature_deselect_all(scene->obedit);
+ ED_armature_edit_deselect_all(scene->obedit);
tree_element_active_ebone__sel(C, scene, arm, ebone, true);
status = OL_DRAWSEL_NORMAL;
}
@@ -706,15 +707,23 @@ static eOLDrawState tree_element_active_pose(
{
Object *ob = (Object *)tselem->id;
Base *base = BKE_scene_base_find(scene, ob);
-
+
+ if (base == NULL) {
+ /* Armature not instantiated in current scene (e.g. inside an appended group...). */
+ return OL_DRAWSEL_NONE;
+ }
+
if (set != OL_SETSEL_NONE) {
- if (scene->obedit)
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO);
+ if (scene->obedit) {
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
+ }
- if (ob->mode & OB_MODE_POSE)
- ED_armature_exit_posemode(C, base);
- else
- ED_armature_enter_posemode(C, base);
+ if (ob->mode & OB_MODE_POSE) {
+ ED_object_posemode_exit(C, ob);
+ }
+ else {
+ ED_object_posemode_enter(C, ob);
+ }
}
else {
if (ob->mode & OB_MODE_POSE) {
@@ -810,7 +819,7 @@ eOLDrawState tree_element_active(bContext *C, Scene *scene, SpaceOops *soops, Tr
{
switch (te->idcode) {
/* Note: ID_OB only if handle_all_type is true, else objects are handled specially to allow multiple
- * selection. See do_outliner_item_activate. */
+ * selection. See do_outliner_item_activate_from_cursor. */
case ID_OB:
if (handle_all_types) {
return tree_element_set_active_object(C, scene, soops, te, set, false);
@@ -886,10 +895,85 @@ eOLDrawState tree_element_type_active(
/* ================================================ */
-static bool do_outliner_item_activate(bContext *C, Scene *scene, ARegion *ar, SpaceOops *soops,
- TreeElement *te, bool extend, bool recursive, const float mval[2])
+/**
+ * Action when clicking to activate an item (typically under the mouse cursor),
+ * but don't do any cursor intersection checks.
+ *
+ * Needed to run from operators accessed from a menu.
+ */
+static void do_outliner_item_activate_tree_element(
+ bContext *C, Scene *scene, SpaceOops *soops,
+ TreeElement *te, TreeStoreElem *tselem,
+ bool extend, bool recursive)
+{
+ /* always makes active object, except for some specific types.
+ * Note about TSE_EBONE: In case of a same ID_AR datablock shared among several objects, we do not want
+ * to switch out of edit mode (see T48328 for details). */
+ if (!ELEM(tselem->type, TSE_SEQUENCE, TSE_SEQ_STRIP, TSE_SEQUENCE_DUP, TSE_EBONE)) {
+ tree_element_set_active_object(
+ C, scene, soops, te,
+ (extend && tselem->type == 0) ? OL_SETSEL_EXTEND : OL_SETSEL_NORMAL,
+ recursive && tselem->type == 0);
+ }
+
+ if (tselem->type == 0) { // the lib blocks
+ /* editmode? */
+ if (te->idcode == ID_SCE) {
+ if (scene != (Scene *)tselem->id) {
+ ED_screen_set_scene(C, CTX_wm_screen(C), (Scene *)tselem->id);
+ }
+ }
+ else if (te->idcode == ID_GR) {
+ Group *gr = (Group *)tselem->id;
+ GroupObject *gob;
+
+ if (extend) {
+ int sel = BA_SELECT;
+ for (gob = gr->gobject.first; gob; gob = gob->next) {
+ if (gob->ob->flag & SELECT) {
+ sel = BA_DESELECT;
+ break;
+ }
+ }
+
+ for (gob = gr->gobject.first; gob; gob = gob->next) {
+ ED_base_object_select(BKE_scene_base_find(scene, gob->ob), sel);
+ }
+ }
+ else {
+ BKE_scene_base_deselect_all(scene);
+
+ for (gob = gr->gobject.first; gob; gob = gob->next) {
+ if ((gob->ob->flag & SELECT) == 0)
+ ED_base_object_select(BKE_scene_base_find(scene, gob->ob), BA_SELECT);
+ }
+ }
+
+ WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
+ }
+ else if (ELEM(te->idcode, ID_ME, ID_CU, ID_MB, ID_LT, ID_AR)) {
+ WM_operator_name_call(C, "OBJECT_OT_editmode_toggle", WM_OP_INVOKE_REGION_WIN, NULL);
+ }
+ else { // rest of types
+ tree_element_active(C, scene, soops, te, OL_SETSEL_NORMAL, false);
+ }
+
+ }
+ else {
+ tree_element_type_active(
+ C, scene, soops, te, tselem,
+ extend ? OL_SETSEL_EXTEND : OL_SETSEL_NORMAL,
+ recursive);
+ }
+}
+
+/**
+ * Activates tree items, also handles clicking on arrows.
+ */
+static bool do_outliner_item_activate_from_cursor(
+ bContext *C, Scene *scene, ARegion *ar, SpaceOops *soops,
+ TreeElement *te, bool extend, bool recursive, const float mval[2])
{
-
if (mval[1] > te->ys && mval[1] < te->ys + UI_UNIT_Y) {
TreeStoreElem *tselem = TREESTORE(te);
bool openclose = false;
@@ -916,78 +1000,49 @@ static bool do_outliner_item_activate(bContext *C, Scene *scene, ARegion *ar, Sp
}
/* name and first icon */
else if (mval[0] > te->xs + UI_UNIT_X && mval[0] < te->xend) {
-
- /* always makes active object, except for some specific types.
- * Note about TSE_EBONE: In case of a same ID_AR datablock shared among several objects, we do not want
- * to switch out of edit mode (see T48328 for details). */
- if (!ELEM(tselem->type, TSE_SEQUENCE, TSE_SEQ_STRIP, TSE_SEQUENCE_DUP, TSE_EBONE)) {
- tree_element_set_active_object(C, scene, soops, te,
- (extend && tselem->type == 0) ? OL_SETSEL_EXTEND : OL_SETSEL_NORMAL,
- recursive && tselem->type == 0);
- }
-
- if (tselem->type == 0) { // the lib blocks
- /* editmode? */
- if (te->idcode == ID_SCE) {
- if (scene != (Scene *)tselem->id) {
- ED_screen_set_scene(C, CTX_wm_screen(C), (Scene *)tselem->id);
- }
- }
- else if (te->idcode == ID_GR) {
- Group *gr = (Group *)tselem->id;
- GroupObject *gob;
-
- if (extend) {
- int sel = BA_SELECT;
- for (gob = gr->gobject.first; gob; gob = gob->next) {
- if (gob->ob->flag & SELECT) {
- sel = BA_DESELECT;
- break;
- }
- }
-
- for (gob = gr->gobject.first; gob; gob = gob->next) {
- ED_base_object_select(BKE_scene_base_find(scene, gob->ob), sel);
- }
- }
- else {
- BKE_scene_base_deselect_all(scene);
-
- for (gob = gr->gobject.first; gob; gob = gob->next) {
- if ((gob->ob->flag & SELECT) == 0)
- ED_base_object_select(BKE_scene_base_find(scene, gob->ob), BA_SELECT);
- }
- }
-
- WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
- }
- else if (ELEM(te->idcode, ID_ME, ID_CU, ID_MB, ID_LT, ID_AR)) {
- WM_operator_name_call(C, "OBJECT_OT_editmode_toggle", WM_OP_INVOKE_REGION_WIN, NULL);
- }
- else { // rest of types
- tree_element_active(C, scene, soops, te, OL_SETSEL_NORMAL, false);
- }
-
- }
- else {
- tree_element_type_active(C, scene, soops, te, tselem,
- extend ? OL_SETSEL_EXTEND : OL_SETSEL_NORMAL,
- recursive);
- }
-
+ do_outliner_item_activate_tree_element(
+ C, scene, soops,
+ te, tselem,
+ extend, recursive);
return true;
}
}
for (te = te->subtree.first; te; te = te->next) {
- if (do_outliner_item_activate(C, scene, ar, soops, te, extend, recursive, mval)) {
+ if (do_outliner_item_activate_from_cursor(C, scene, ar, soops, te, extend, recursive, mval)) {
return true;
}
}
return false;
}
-int outliner_item_do_activate(bContext *C, int x, int y, bool extend, bool recursive)
+/**
+ * A version of #outliner_item_do_acticate_from_cursor that takes the tree element directly.
+ * and doesn't depend on the pointer position.
+ *
+ * This allows us to simulate clicking on an item without dealing with the mouse cursor.
+ */
+void outliner_item_do_activate_from_tree_element(
+ bContext *C, TreeElement *te, TreeStoreElem *tselem,
+ bool extend, bool recursive)
+{
+ Scene *scene = CTX_data_scene(C);
+ SpaceOops *soops = CTX_wm_space_outliner(C);
+
+ do_outliner_item_activate_tree_element(
+ C, scene, soops,
+ te, tselem,
+ extend, recursive);
+}
+
+/**
+ * Action to run when clicking in the outliner,
+ *
+ * May expend/collapse branches or activate items.
+ * */
+int outliner_item_do_activate_from_cursor(
+ bContext *C, const int mval[2],
+ bool extend, bool recursive)
{
Scene *scene = CTX_data_scene(C);
ARegion *ar = CTX_wm_region(C);
@@ -995,7 +1050,7 @@ int outliner_item_do_activate(bContext *C, int x, int y, bool extend, bool recur
TreeElement *te;
float fmval[2];
- UI_view2d_region_to_view(&ar->v2d, x, y, &fmval[0], &fmval[1]);
+ UI_view2d_region_to_view(&ar->v2d, mval[0], mval[1], &fmval[0], &fmval[1]);
if (!ELEM(soops->outlinevis, SO_DATABLOCKS, SO_USERDEF) &&
!(soops->flag & SO_HIDE_RESTRICTCOLS) &&
@@ -1005,7 +1060,9 @@ int outliner_item_do_activate(bContext *C, int x, int y, bool extend, bool recur
}
for (te = soops->tree.first; te; te = te->next) {
- if (do_outliner_item_activate(C, scene, ar, soops, te, extend, recursive, fmval)) break;
+ if (do_outliner_item_activate_from_cursor(C, scene, ar, soops, te, extend, recursive, fmval)) {
+ break;
+ }
}
if (te) {
@@ -1040,9 +1097,7 @@ static int outliner_item_activate(bContext *C, wmOperator *op, const wmEvent *ev
{
bool extend = RNA_boolean_get(op->ptr, "extend");
bool recursive = RNA_boolean_get(op->ptr, "recursive");
- int x = event->mval[0];
- int y = event->mval[1];
- return outliner_item_do_activate(C, x, y, extend, recursive);
+ return outliner_item_do_activate_from_cursor(C, event->mval, extend, recursive);
}
void OUTLINER_OT_item_activate(wmOperatorType *ot)
@@ -1062,12 +1117,12 @@ void OUTLINER_OT_item_activate(wmOperatorType *ot)
/* ****************************************************** */
/* **************** Border Select Tool ****************** */
-static void outliner_item_border_select(Scene *scene, rctf *rectf, TreeElement *te, int gesture_mode)
+static void outliner_item_border_select(Scene *scene, rctf *rectf, TreeElement *te, bool select)
{
TreeStoreElem *tselem = TREESTORE(te);
if (te->ys <= rectf->ymax && te->ys + UI_UNIT_Y >= rectf->ymin) {
- if (gesture_mode == GESTURE_MODAL_SELECT) {
+ if (select) {
tselem->flag |= TSE_SELECTED;
}
else {
@@ -1078,7 +1133,7 @@ static void outliner_item_border_select(Scene *scene, rctf *rectf, TreeElement *
/* Look at its children. */
if ((tselem->flag & TSE_CLOSED) == 0) {
for (te = te->subtree.first; te; te = te->next) {
- outliner_item_border_select(scene, rectf, te, gesture_mode);
+ outliner_item_border_select(scene, rectf, te, select);
}
}
}
@@ -1090,13 +1145,13 @@ static int outliner_border_select_exec(bContext *C, wmOperator *op)
ARegion *ar = CTX_wm_region(C);
TreeElement *te;
rctf rectf;
- int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ bool select = !RNA_boolean_get(op->ptr, "deselect");
WM_operator_properties_border_to_rctf(op, &rectf);
UI_view2d_region_to_view_rctf(&ar->v2d, &rectf, &rectf);
for (te = soops->tree.first; te; te = te->next) {
- outliner_item_border_select(scene, &rectf, te, gesture_mode);
+ outliner_item_border_select(scene, &rectf, te, select);
}
WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
@@ -1113,10 +1168,10 @@ void OUTLINER_OT_select_border(wmOperatorType *ot)
ot->description = "Use box selection to select tree elements";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = outliner_border_select_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_outliner_active;
@@ -1124,7 +1179,7 @@ void OUTLINER_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, false);
+ WM_operator_properties_gesture_border_ex(ot, true, false);
}
/* ****************************************************** */
diff --git a/source/blender/editors/space_outliner/outliner_tools.c b/source/blender/editors/space_outliner/outliner_tools.c
index 4eda7977622..e8275d597a6 100644
--- a/source/blender/editors/space_outliner/outliner_tools.c
+++ b/source/blender/editors/space_outliner/outliner_tools.c
@@ -68,7 +68,7 @@
#include "ED_object.h"
#include "ED_screen.h"
#include "ED_sequencer.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -235,8 +235,7 @@ static void unlink_group_cb(
}
else {
Main *bmain = CTX_data_main(C);
- BKE_libblock_unlink(bmain, group, false, false);
- BKE_libblock_free(bmain, group);
+ BKE_libblock_delete(bmain, group);
}
}
@@ -279,7 +278,7 @@ typedef enum eOutliner_PropSceneOps {
OL_SCENE_OP_DELETE = 1
} eOutliner_PropSceneOps;
-static EnumPropertyItem prop_scene_op_types[] = {
+static const EnumPropertyItem prop_scene_op_types[] = {
{OL_SCENE_OP_DELETE, "DELETE", ICON_X, "Delete", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -373,17 +372,14 @@ static void object_select_cb(
}
static void object_select_hierarchy_cb(
- bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te),
- TreeStoreElem *UNUSED(tsep), TreeStoreElem *UNUSED(tselem), void *UNUSED(user_data))
+ bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *te,
+ TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data))
{
- /* From where do i get the x,y coordinate of the mouse event ? */
- wmWindow *win = CTX_wm_window(C);
- int x = win->eventstate->mval[0];
- int y = win->eventstate->mval[1];
- outliner_item_do_activate(C, x, y, true, true);
+ /* Don't extend because this toggles, which is nice for Ctrl-Click but not for a menu item.
+ * it's especially confusing when multiple items are selected since some toggle on/off. */
+ outliner_item_do_activate_from_tree_element(C, te, tselem, false, true);
}
-
static void object_deselect_cb(
bContext *UNUSED(C), ReportList *UNUSED(reports), Scene *scene, TreeElement *te,
TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data))
@@ -399,7 +395,7 @@ static void object_deselect_cb(
static void object_delete_cb(
bContext *C, ReportList *reports, Scene *scene, TreeElement *te,
- TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data))
+ TreeStoreElem *tsep, TreeStoreElem *tselem, void *user_data)
{
Base *base = (Base *)te->directdata;
@@ -422,7 +418,7 @@ static void object_delete_cb(
// check also library later
if (scene->obedit == base->object)
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO);
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
ED_base_object_free_and_unlink(CTX_data_main(C), scene, base);
/* leave for ED_outliner_id_unref to handle */
@@ -431,13 +427,20 @@ static void object_delete_cb(
tselem->id = NULL;
#endif
}
+ else {
+ /* No base, means object is no more instantiated in any scene.
+ * Should not happen ideally, but does happens, see T51625.
+ * Rather than twisting in all kind of ways to address all possible cases leading to that situation, simpler
+ * to allow deleting such object as a mere generic data-block. */
+ id_delete_cb(C, reports, scene, te, tsep, tselem, user_data);
+ }
}
static void id_local_cb(
bContext *C, ReportList *UNUSED(reports), Scene *UNUSED(scene), TreeElement *UNUSED(te),
TreeStoreElem *UNUSED(tsep), TreeStoreElem *tselem, void *UNUSED(user_data))
{
- if (ID_IS_LINKED_DATABLOCK(tselem->id) && (tselem->id->tag & LIB_TAG_EXTERN)) {
+ if (ID_IS_LINKED(tselem->id) && (tselem->id->tag & LIB_TAG_EXTERN)) {
Main *bmain = CTX_data_main(C);
/* if the ID type has no special local function,
* just clear the lib */
@@ -870,7 +873,7 @@ static void object_delete_hierarchy_cb(
/* Check also library later. */
for (; obedit && (obedit != base->object); obedit = obedit->parent);
if (obedit == base->object) {
- ED_object_editmode_exit(C, EM_FREEDATA | EM_FREEUNDO | EM_WAITCURSOR | EM_DO_UNDO);
+ ED_object_editmode_exit(C, EM_FREEDATA | EM_WAITCURSOR | EM_DO_UNDO);
}
outline_delete_hierarchy(C, reports, scene, base);
@@ -900,7 +903,7 @@ enum {
OL_OP_RENAME,
};
-static EnumPropertyItem prop_object_op_types[] = {
+static const EnumPropertyItem prop_object_op_types[] = {
{OL_OP_SELECT, "SELECT", 0, "Select", ""},
{OL_OP_DESELECT, "DESELECT", 0, "Deselect", ""},
{OL_OP_SELECT_HIERARCHY, "SELECT_HIERARCHY", 0, "Select Hierarchy", ""},
@@ -1047,11 +1050,11 @@ typedef enum eOutliner_PropGroupOps {
OL_GROUPOP_RENAME,
} eOutliner_PropGroupOps;
-static EnumPropertyItem prop_group_op_types[] = {
+static const EnumPropertyItem prop_group_op_types[] = {
{OL_GROUPOP_UNLINK, "UNLINK", 0, "Unlink Group", ""},
{OL_GROUPOP_LOCAL, "LOCAL", 0, "Make Local Group", ""},
{OL_GROUPOP_LINK, "LINK", 0, "Link Group Objects to Scene", ""},
- {OL_GROUPOP_DELETE, "DELETE", 0, "Delete Group", "WARNING: no undo"},
+ {OL_GROUPOP_DELETE, "DELETE", 0, "Delete Group", ""},
{OL_GROUPOP_REMAP, "REMAP", 0, "Remap Users",
"Make all users of selected data-blocks to use instead current (clicked) one"},
{OL_GROUPOP_INSTANCE, "INSTANCE", 0, "Instance Groups in Scene", ""},
@@ -1090,7 +1093,7 @@ static int outliner_group_operation_exec(bContext *C, wmOperator *op)
DAG_relations_tag_update(CTX_data_main(C));
break;
case OL_GROUPOP_DELETE:
- WM_operator_name_call(C, "OUTLINER_OT_id_delete", WM_OP_INVOKE_REGION_WIN, NULL);
+ outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, id_delete_cb, NULL);
break;
case OL_GROUPOP_REMAP:
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, id_remap_cb, NULL);
@@ -1154,7 +1157,7 @@ typedef enum eOutlinerIdOpTypes {
} eOutlinerIdOpTypes;
// TODO: implement support for changing the ID-block used
-static EnumPropertyItem prop_id_op_types[] = {
+static const EnumPropertyItem prop_id_op_types[] = {
{OUTLINER_IDOP_UNLINK, "UNLINK", 0, "Unlink", ""},
{OUTLINER_IDOP_LOCAL, "LOCAL", 0, "Make Local", ""},
{OUTLINER_IDOP_SINGLE, "SINGLE", 0, "Make Single User", ""},
@@ -1254,6 +1257,7 @@ static int outliner_id_operation_exec(bContext *C, wmOperator *op)
{
if (idlevel > 0) {
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, id_delete_cb, NULL);
+ ED_undo_push(C, "Delete");
}
break;
}
@@ -1261,6 +1265,7 @@ static int outliner_id_operation_exec(bContext *C, wmOperator *op)
{
if (idlevel > 0) {
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, id_remap_cb, NULL);
+ ED_undo_push(C, "Remap");
}
break;
}
@@ -1339,7 +1344,7 @@ typedef enum eOutlinerLibOpTypes {
OL_LIB_RELOAD,
} eOutlinerLibOpTypes;
-static EnumPropertyItem outliner_lib_op_type_items[] = {
+static const EnumPropertyItem outliner_lib_op_type_items[] = {
{OL_LIB_RENAME, "RENAME", 0, "Rename", ""},
{OL_LIB_DELETE, "DELETE", 0, "Delete", "Delete this library and all its item from Blender - WARNING: no undo"},
{OL_LIB_RELOCATE, "RELOCATE", 0, "Relocate", "Select a new path for this library, and reload all its data"},
@@ -1369,18 +1374,20 @@ static int outliner_lib_operation_exec(bContext *C, wmOperator *op)
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, item_rename_cb, NULL);
WM_event_add_notifier(C, NC_ID | NA_EDITED, NULL);
- ED_undo_push(C, "Rename");
+ ED_undo_push(C, "Rename Library");
break;
}
case OL_LIB_DELETE:
{
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, id_delete_cb, NULL);
+ ED_undo_push(C, "Delete Library");
break;
}
case OL_LIB_RELOCATE:
{
/* rename */
outliner_do_libdata_operation(C, op->reports, scene, soops, &soops->tree, lib_relocate_cb, NULL);
+ ED_undo_push(C, "Relocate Library");
break;
}
case OL_LIB_RELOAD:
@@ -1547,7 +1554,7 @@ typedef enum eOutliner_AnimDataOps {
//OUTLINER_ANIMOP_PASTE_DRIVERS
} eOutliner_AnimDataOps;
-static EnumPropertyItem prop_animdata_op_types[] = {
+static const EnumPropertyItem prop_animdata_op_types[] = {
{OUTLINER_ANIMOP_CLEAR_ADT, "CLEAR_ANIMDATA", 0, "Clear Animation Data", "Remove this animation data container"},
{OUTLINER_ANIMOP_SET_ACT, "SET_ACT", 0, "Set Action", ""},
{OUTLINER_ANIMOP_CLEAR_ACT, "CLEAR_ACT", 0, "Unlink Action", ""},
@@ -1647,7 +1654,7 @@ void OUTLINER_OT_animdata_operation(wmOperatorType *ot)
/* **************************************** */
-static EnumPropertyItem prop_constraint_op_types[] = {
+static const EnumPropertyItem prop_constraint_op_types[] = {
{OL_CONSTRAINTOP_ENABLE, "ENABLE", ICON_RESTRICT_VIEW_OFF, "Enable", ""},
{OL_CONSTRAINTOP_DISABLE, "DISABLE", ICON_RESTRICT_VIEW_ON, "Disable", ""},
{OL_CONSTRAINTOP_DELETE, "DELETE", ICON_X, "Delete", ""},
@@ -1693,7 +1700,7 @@ void OUTLINER_OT_constraint_operation(wmOperatorType *ot)
/* ******************** */
-static EnumPropertyItem prop_modifier_op_types[] = {
+static const EnumPropertyItem prop_modifier_op_types[] = {
{OL_MODIFIER_OP_TOGVIS, "TOGVIS", ICON_RESTRICT_VIEW_OFF, "Toggle viewport use", ""},
{OL_MODIFIER_OP_TOGREN, "TOGREN", ICON_RESTRICT_RENDER_OFF, "Toggle render use", ""},
{OL_MODIFIER_OP_DELETE, "DELETE", ICON_X, "Delete", ""},
@@ -1740,7 +1747,7 @@ void OUTLINER_OT_modifier_operation(wmOperatorType *ot)
/* ******************** */
// XXX: select linked is for RNA structs only
-static EnumPropertyItem prop_data_op_types[] = {
+static const EnumPropertyItem prop_data_op_types[] = {
{OL_DOP_SELECT, "SELECT", 0, "Select", ""},
{OL_DOP_DESELECT, "DESELECT", 0, "Deselect", ""},
{OL_DOP_HIDE, "HIDE", 0, "Hide", ""},
diff --git a/source/blender/editors/space_outliner/outliner_tree.c b/source/blender/editors/space_outliner/outliner_tree.c
index ec46c5df9a0..051605b1079 100644
--- a/source/blender/editors/space_outliner/outliner_tree.c
+++ b/source/blender/editors/space_outliner/outliner_tree.c
@@ -113,7 +113,7 @@ static void outliner_storage_cleanup(SpaceOops *soops)
}
if (unused) {
- if (BLI_mempool_count(ts) == unused) {
+ if (BLI_mempool_len(ts) == unused) {
BLI_mempool_destroy(ts);
soops->treestore = NULL;
if (soops->treehash) {
@@ -123,7 +123,7 @@ static void outliner_storage_cleanup(SpaceOops *soops)
}
else {
TreeStoreElem *tsenew;
- BLI_mempool *new_ts = BLI_mempool_create(sizeof(TreeStoreElem), BLI_mempool_count(ts) - unused,
+ BLI_mempool *new_ts = BLI_mempool_create(sizeof(TreeStoreElem), BLI_mempool_len(ts) - unused,
512, BLI_MEMPOOL_ALLOW_ITER);
BLI_mempool_iternew(ts, &iter);
while ((tselem = BLI_mempool_iterstep(&iter))) {
@@ -491,7 +491,7 @@ static void outliner_add_object_contents(SpaceOops *soops, TreeElement *te, Tree
outliner_add_element(soops, &te->subtree, ob->poselib, te, 0, 0); // XXX FIXME.. add a special type for this
- if (ob->proxy && !ID_IS_LINKED_DATABLOCK(ob))
+ if (ob->proxy && !ID_IS_LINKED(ob))
outliner_add_element(soops, &te->subtree, ob->proxy, te, TSE_PROXY, 0);
outliner_add_element(soops, &te->subtree, ob->gpd, te, 0, 0);
@@ -882,6 +882,8 @@ static void outliner_add_id_contents(SpaceOops *soops, TreeElement *te, TreeStor
}
break;
}
+ default:
+ break;
}
}
@@ -1080,6 +1082,12 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
PointerRNA pptr, propptr, *ptr = (PointerRNA *)idv;
PropertyRNA *prop, *iterprop;
PropertyType proptype;
+
+ /* Don't display arrays larger, weak but index is stored as a short,
+ * also the outliner isn't intended for editing such large data-sets. */
+ BLI_STATIC_ASSERT(sizeof(te->index) == 2, "Index is no longer short!");
+ const int tot_limit = SHRT_MAX;
+
int a, tot;
/* we do lazy build, for speed and to avoid infinite recusion */
@@ -1101,6 +1109,7 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
iterprop = RNA_struct_iterator_property(ptr->type);
tot = RNA_property_collection_length(ptr, iterprop);
+ CLAMP_MAX(tot, tot_limit);
/* auto open these cases */
if (!parent || (RNA_property_type(parent->directdata)) == PROP_POINTER)
@@ -1147,6 +1156,7 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
}
else if (proptype == PROP_COLLECTION) {
tot = RNA_property_collection_length(ptr, prop);
+ CLAMP_MAX(tot, tot_limit);
if (TSELEM_OPEN(tselem, soops)) {
for (a = 0; a < tot; a++) {
@@ -1159,6 +1169,7 @@ static TreeElement *outliner_add_element(SpaceOops *soops, ListBase *lb, void *i
}
else if (ELEM(proptype, PROP_BOOLEAN, PROP_INT, PROP_FLOAT)) {
tot = RNA_property_array_length(ptr, prop);
+ CLAMP_MAX(tot, tot_limit);
if (TSELEM_OPEN(tselem, soops)) {
for (a = 0; a < tot; a++)
@@ -1316,7 +1327,7 @@ static void outliner_add_library_contents(Main *mainvar, SpaceOops *soops, TreeE
ten = outliner_add_element(soops, &te->subtree, lbarray[a], NULL, TSE_ID_BASE, 0);
ten->directdata = lbarray[a];
- ten->name = (char *)BKE_idcode_to_name_plural(GS(id->name));
+ ten->name = BKE_idcode_to_name_plural(GS(id->name));
if (ten->name == NULL)
ten->name = "UNKNOWN";
@@ -1356,7 +1367,7 @@ static void outliner_add_orphaned_datablocks(Main *mainvar, SpaceOops *soops)
ten = outliner_add_element(soops, &soops->tree, lbarray[a], NULL, TSE_ID_BASE, 0);
ten->directdata = lbarray[a];
- ten->name = (char *)BKE_idcode_to_name_plural(GS(id->name));
+ ten->name = BKE_idcode_to_name_plural(GS(id->name));
if (ten->name == NULL)
ten->name = "UNKNOWN";
@@ -1624,7 +1635,7 @@ void outliner_build_tree(Main *mainvar, Scene *scene, SpaceOops *soops)
Base *base;
TreeElement *te = NULL, *ten;
TreeStoreElem *tselem;
- int show_opened = !soops->treestore || !BLI_mempool_count(soops->treestore); /* on first view, we open scenes */
+ int show_opened = !soops->treestore || !BLI_mempool_len(soops->treestore); /* on first view, we open scenes */
/* Are we looking for something - we want to tag parents to filter child matches
* - NOT in datablocks view - searching all datablocks takes way too long to be useful
diff --git a/source/blender/editors/space_sequencer/sequencer_add.c b/source/blender/editors/space_sequencer/sequencer_add.c
index ede6b7ce469..258cbdfaffd 100644
--- a/source/blender/editors/space_sequencer/sequencer_add.c
+++ b/source/blender/editors/space_sequencer/sequencer_add.c
@@ -38,6 +38,8 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
+#include "BLT_translation.h"
+
#include "DNA_scene_types.h"
#include "DNA_mask_types.h"
@@ -359,7 +361,7 @@ void SEQUENCER_OT_scene_strip_add(struct wmOperatorType *ot)
sequencer_generic_props__internal(ot, SEQPROP_STARTFRAME);
prop = RNA_def_enum(ot->srna, "scene", DummyRNA_NULL_items, 0, "Scene", "");
- RNA_def_enum_funcs(prop, RNA_scene_itemf);
+ RNA_def_enum_funcs(prop, RNA_scene_without_active_itemf);
RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
ot->prop = prop;
}
@@ -445,6 +447,7 @@ void SEQUENCER_OT_movieclip_strip_add(struct wmOperatorType *ot)
sequencer_generic_props__internal(ot, SEQPROP_STARTFRAME);
prop = RNA_def_enum(ot->srna, "clip", DummyRNA_NULL_items, 0, "Clip", "");
RNA_def_enum_funcs(prop, RNA_movieclip_itemf);
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_MOVIECLIP);
RNA_def_property_flag(prop, PROP_ENUM_NO_TRANSLATE);
ot->prop = prop;
}
diff --git a/source/blender/editors/space_sequencer/sequencer_draw.c b/source/blender/editors/space_sequencer/sequencer_draw.c
index e1768e4aedc..c3a27dad538 100644
--- a/source/blender/editors/space_sequencer/sequencer_draw.c
+++ b/source/blender/editors/space_sequencer/sequencer_draw.c
@@ -40,6 +40,7 @@
#include "DNA_scene_types.h"
#include "DNA_mask_types.h"
+#include "DNA_object_types.h"
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
#include "DNA_userdef_types.h"
@@ -59,6 +60,7 @@
#include "BIF_glutil.h"
#include "GPU_basic_shader.h"
+#include "GPU_compositing.h"
#include "ED_anim_api.h"
#include "ED_gpencil.h"
@@ -154,6 +156,7 @@ void color3ubv_from_seq(Scene *curscene, Sequence *seq, unsigned char col[3])
case SEQ_TYPE_MULTICAM:
case SEQ_TYPE_ADJUSTMENT:
case SEQ_TYPE_GAUSSIAN_BLUR:
+ case SEQ_TYPE_COLORMIX:
UI_GetThemeColor3ubv(TH_SEQ_EFFECT, col);
/* slightly offset hue to distinguish different effects */
@@ -168,6 +171,7 @@ void color3ubv_from_seq(Scene *curscene, Sequence *seq, unsigned char col[3])
else if (seq->type == SEQ_TYPE_MULTICAM) rgb_byte_set_hue_float_offset(col, 0.32);
else if (seq->type == SEQ_TYPE_ADJUSTMENT) rgb_byte_set_hue_float_offset(col, 0.40);
else if (seq->type == SEQ_TYPE_GAUSSIAN_BLUR) rgb_byte_set_hue_float_offset(col, 0.42);
+ else if (seq->type == SEQ_TYPE_COLORMIX) rgb_byte_set_hue_float_offset(col, 0.46);
break;
case SEQ_TYPE_COLOR:
@@ -545,7 +549,8 @@ static void draw_seq_text(View2D *v2d, SpaceSeq *sseq, Sequence *seq, float x1,
if ((sseq->flag & SEQ_ALL_WAVEFORMS) || (seq->flag & SEQ_AUDIO_DRAW_WAVEFORM)) {
str[0] = 0;
str_len = 0;
- } else if (seq->sound) {
+ }
+ else if (seq->sound) {
str_len = BLI_snprintf(str, sizeof(str), "%s: %s | %d",
name, seq->sound->name, seq->len);
}
@@ -906,7 +911,7 @@ void ED_sequencer_special_preview_clear(void)
ImBuf *sequencer_ibuf_get(struct Main *bmain, Scene *scene, SpaceSeq *sseq, int cfra, int frame_ofs, const char *viewname)
{
- SeqRenderData context;
+ SeqRenderData context = {0};
ImBuf *ibuf;
int rectx, recty;
float render_size;
@@ -933,6 +938,12 @@ ImBuf *sequencer_ibuf_get(struct Main *bmain, Scene *scene, SpaceSeq *sseq, int
rectx, recty, proxy_size,
&context);
context.view_id = BKE_scene_multiview_view_id_get(&scene->r, viewname);
+ if (scene->r.seq_flag & R_SEQ_CAMERA_DOF) {
+ if (sseq->compositor == NULL) {
+ sseq->compositor = GPU_fx_compositor_create();
+ }
+ context.gpu_fx = sseq->compositor;
+ }
/* sequencer could start rendering, in this case we need to be sure it wouldn't be canceled
* by Esc pressed somewhere in the past
@@ -1115,18 +1126,16 @@ void draw_image_seq(const bContext *C, Scene *scene, ARegion *ar, SpaceSeq *sseq
const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
bool draw_metadata = false;
- if (G.is_rendering == false && (scene->r.seq_flag & R_SEQ_GL_PREV) == 0) {
+ if (G.is_rendering == false && (scene->r.seq_prev_type) == OB_RENDER) {
/* stop all running jobs, except screen one. currently previews frustrate Render
* needed to make so sequencer's rendering doesn't conflict with compositor
*/
WM_jobs_kill_type(CTX_wm_manager(C), NULL, WM_JOB_TYPE_COMPOSITE);
- if ((scene->r.seq_flag & R_SEQ_GL_PREV) == 0) {
- /* in case of final rendering used for preview, kill all previews,
- * otherwise threading conflict will happen in rendering module
- */
- WM_jobs_kill_type(CTX_wm_manager(C), NULL, WM_JOB_TYPE_RENDER_PREVIEW);
- }
+ /* in case of final rendering used for preview, kill all previews,
+ * otherwise threading conflict will happen in rendering module
+ */
+ WM_jobs_kill_type(CTX_wm_manager(C), NULL, WM_JOB_TYPE_RENDER_PREVIEW);
}
if ((!draw_overlay || sseq->overlay_type == SEQ_DRAW_OVERLAY_REFERENCE) && !draw_backdrop) {
@@ -1420,7 +1429,7 @@ void draw_image_seq(const bContext *C, Scene *scene, ARegion *ar, SpaceSeq *sseq
/* NOTE: sequencer mask editing isnt finished, the draw code is working but editing not,
* for now just disable drawing since the strip frame will likely be offset */
- //if (sc->mode == SC_MODE_MASKEDIT) {
+ // if (sc->mode == SC_MODE_MASKEDIT)
if (0 && sseq->mainb == SEQ_DRAW_IMG_IMBUF) {
Mask *mask = BKE_sequencer_mask_get(scene);
@@ -1630,9 +1639,8 @@ void draw_timeline_seq(const bContext *C, ARegion *ar)
/* draw backdrop */
draw_seq_backdrop(v2d);
- /* regular grid-pattern over the rest of the view (i.e. 25-frame grid lines) */
- // NOTE: the gridlines are currently spaced every 25 frames, which is only fine for 25 fps, but maybe not for 30...
- UI_view2d_constant_grid_draw(v2d);
+ /* regular grid-pattern over the rest of the view (i.e. 1-second grid lines) */
+ UI_view2d_constant_grid_draw(v2d, FPS);
/* Only draw backdrop in pure sequence view. */
if (sseq->view == SEQ_VIEW_SEQUENCE && sseq->draw_flag & SEQ_DRAW_BACKDROP) {
diff --git a/source/blender/editors/space_sequencer/sequencer_edit.c b/source/blender/editors/space_sequencer/sequencer_edit.c
index 8ae89941bdb..0895d28fba7 100644
--- a/source/blender/editors/space_sequencer/sequencer_edit.c
+++ b/source/blender/editors/space_sequencer/sequencer_edit.c
@@ -95,6 +95,7 @@ EnumPropertyItem sequencer_prop_effect_types[] = {
{SEQ_TYPE_ADJUSTMENT, "ADJUSTMENT", 0, "Adjustment Layer", ""},
{SEQ_TYPE_GAUSSIAN_BLUR, "GAUSSIAN_BLUR", 0, "Gaussian Blur", ""},
{SEQ_TYPE_TEXT, "TEXT", 0, "Text", ""},
+ {SEQ_TYPE_COLORMIX, "COLORMIX", 0, "Color Mix", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -107,7 +108,7 @@ EnumPropertyItem prop_side_types[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_side_lr_types[] = {
+static const EnumPropertyItem prop_side_lr_types[] = {
{SEQ_SIDE_LEFT, "LEFT", 0, "Left", ""},
{SEQ_SIDE_RIGHT, "RIGHT", 0, "Right", ""},
{0, NULL, 0, NULL, NULL}
@@ -562,7 +563,7 @@ int seq_effect_find_selected(Scene *scene, Sequence *activeseq, int type, Sequen
}
if (seq1 == NULL) seq1 = seq2;
if (seq3 == NULL) seq3 = seq2;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case 2:
if (seq1 == NULL || seq2 == NULL) {
*error_str = N_("2 selected sequence strips are needed");
@@ -670,6 +671,9 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
Sequence *seqn = NULL;
bool skip_dup = false;
+ /* Unlike soft-cut, it's important to use the same value for both strips. */
+ const bool is_end_exact = ((seq->start + seq->len) == cutframe);
+
/* backup values */
ts.start = seq->start;
ts.machine = seq->machine;
@@ -682,7 +686,7 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
ts.anim_startofs = seq->anim_startofs;
ts.anim_endofs = seq->anim_endofs;
ts.len = seq->len;
-
+
/* First Strip! */
/* strips with extended stillfames before */
@@ -694,7 +698,9 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
BKE_sequence_calc(scene, seq);
}
- if ((seq->startstill) && (cutframe < seq->start)) {
+ /* Important to offset the start when 'cutframe == seq->start'
+ * because we need at least one frame of content after start/end still have clipped it. */
+ if ((seq->startstill) && (cutframe <= seq->start)) {
/* don't do funny things with METAs ... */
if (seq->type == SEQ_TYPE_META) {
skip_dup = true;
@@ -708,13 +714,17 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
}
}
/* normal strip */
- else if ((cutframe >= seq->start) && (cutframe <= (seq->start + seq->len))) {
+ else if ((is_end_exact == false) &&
+ ((cutframe >= seq->start) && (cutframe <= (seq->start + seq->len))))
+ {
seq->endofs = 0;
seq->endstill = 0;
seq->anim_endofs += (seq->start + seq->len) - cutframe;
}
/* strips with extended stillframes after */
- else if (((seq->start + seq->len) < cutframe) && (seq->endstill)) {
+ else if ((is_end_exact == true) ||
+ (((seq->start + seq->len) < cutframe) && (seq->endstill)))
+ {
seq->endstill -= seq->enddisp - cutframe;
/* don't do funny things with METAs ... */
if (seq->type == SEQ_TYPE_META) {
@@ -727,12 +737,16 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
if (!skip_dup) {
/* Duplicate AFTER the first change */
- seqn = BKE_sequence_dupli_recursive(scene, NULL, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
+ seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
}
if (seqn) {
seqn->flag |= SELECT;
-
+
+ /* Important not to re-assign this (unlike soft-cut) */
+#if 0
+ is_end_exact = ((seqn->start + seqn->len) == cutframe);
+#endif
/* Second Strip! */
/* strips with extended stillframes before */
if ((seqn->startstill) && (cutframe == seqn->start + 1)) {
@@ -741,9 +755,11 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
seqn->anim_endofs = ts.anim_endofs;
seqn->endstill = ts.endstill;
}
-
+
/* normal strip */
- else if ((cutframe >= seqn->start) && (cutframe <= (seqn->start + seqn->len))) {
+ else if ((is_end_exact == false) &&
+ ((cutframe >= seqn->start) && (cutframe <= (seqn->start + seqn->len))))
+ {
seqn->start = cutframe;
seqn->startstill = 0;
seqn->startofs = 0;
@@ -752,16 +768,18 @@ static Sequence *cut_seq_hard(Scene *scene, Sequence *seq, int cutframe)
seqn->anim_endofs = ts.anim_endofs;
seqn->endstill = ts.endstill;
}
-
+
/* strips with extended stillframes after */
- else if (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)) {
+ else if ((is_end_exact == true) ||
+ (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)))
+ {
seqn->start = cutframe;
seqn->startofs = 0;
seqn->anim_startofs += ts.len - 1;
seqn->endstill = ts.enddisp - cutframe - 1;
seqn->startstill = 0;
}
-
+
BKE_sequence_reload_new_file(scene, seqn, false);
BKE_sequence_calc(scene, seqn);
}
@@ -774,6 +792,8 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
Sequence *seqn = NULL;
bool skip_dup = false;
+ bool is_end_exact = ((seq->start + seq->len) == cutframe);
+
/* backup values */
ts.start = seq->start;
ts.machine = seq->machine;
@@ -786,11 +806,13 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
ts.anim_startofs = seq->anim_startofs;
ts.anim_endofs = seq->anim_endofs;
ts.len = seq->len;
-
+
/* First Strip! */
/* strips with extended stillfames before */
-
- if ((seq->startstill) && (cutframe < seq->start)) {
+
+ /* Important to offset the start when 'cutframe == seq->start'
+ * because we need at least one frame of content after start/end still have clipped it. */
+ if ((seq->startstill) && (cutframe <= seq->start)) {
/* don't do funny things with METAs ... */
if (seq->type == SEQ_TYPE_META) {
skip_dup = true;
@@ -804,11 +826,15 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
}
}
/* normal strip */
- else if ((cutframe >= seq->start) && (cutframe <= (seq->start + seq->len))) {
+ else if ((is_end_exact == false) &&
+ (cutframe >= seq->start) && (cutframe <= (seq->start + seq->len)))
+ {
seq->endofs = (seq->start + seq->len) - cutframe;
}
/* strips with extended stillframes after */
- else if (((seq->start + seq->len) < cutframe) && (seq->endstill)) {
+ else if ((is_end_exact == true) ||
+ (((seq->start + seq->len) < cutframe) && (seq->endstill)))
+ {
seq->endstill -= seq->enddisp - cutframe;
/* don't do funny things with METAs ... */
if (seq->type == SEQ_TYPE_META) {
@@ -820,12 +846,14 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
if (!skip_dup) {
/* Duplicate AFTER the first change */
- seqn = BKE_sequence_dupli_recursive(scene, NULL, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
+ seqn = BKE_sequence_dupli_recursive(scene, scene, seq, SEQ_DUPE_UNIQUE_NAME | SEQ_DUPE_ANIM);
}
if (seqn) {
seqn->flag |= SELECT;
-
+
+ is_end_exact = ((seqn->start + seqn->len) == cutframe);
+
/* Second Strip! */
/* strips with extended stillframes before */
if ((seqn->startstill) && (cutframe == seqn->start + 1)) {
@@ -834,23 +862,27 @@ static Sequence *cut_seq_soft(Scene *scene, Sequence *seq, int cutframe)
seqn->endofs = ts.endofs;
seqn->endstill = ts.endstill;
}
-
+
/* normal strip */
- else if ((cutframe >= seqn->start) && (cutframe <= (seqn->start + seqn->len))) {
+ else if ((is_end_exact == false) &&
+ (cutframe >= seqn->start) && (cutframe <= (seqn->start + seqn->len)))
+ {
seqn->startstill = 0;
seqn->startofs = cutframe - ts.start;
seqn->endofs = ts.endofs;
seqn->endstill = ts.endstill;
}
-
+
/* strips with extended stillframes after */
- else if (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)) {
+ else if ((is_end_exact == true) ||
+ (((seqn->start + seqn->len) < cutframe) && (seqn->endstill)))
+ {
seqn->start = cutframe - ts.len + 1;
seqn->startofs = ts.len - 1;
seqn->endstill = ts.enddisp - cutframe - 1;
seqn->startstill = 0;
}
-
+
BKE_sequence_calc(scene, seqn);
}
return seqn;
@@ -1232,7 +1264,7 @@ static int sequencer_snap_invoke(bContext *C, wmOperator *op, const wmEvent *UNU
void SEQUENCER_OT_snap(struct wmOperatorType *ot)
{
/* identifiers */
- ot->name = "Snap Strips";
+ ot->name = "Snap Strips to Frame";
ot->idname = "SEQUENCER_OT_snap";
ot->description = "Frame where selected strips will be snapped";
@@ -2033,7 +2065,7 @@ void SEQUENCER_OT_swap_inputs(struct wmOperatorType *ot)
/* cut operator */
-static EnumPropertyItem prop_cut_types[] = {
+static const EnumPropertyItem prop_cut_types[] = {
{SEQ_CUT_SOFT, "SOFT", 0, "Soft", ""},
{SEQ_CUT_HARD, "HARD", 0, "Hard", ""},
{0, NULL, 0, NULL, NULL}
@@ -2162,7 +2194,7 @@ static int sequencer_add_duplicate_exec(bContext *C, wmOperator *UNUSED(op))
if (ed == NULL)
return OPERATOR_CANCELLED;
- BKE_sequence_base_dupli_recursive(scene, NULL, &nseqbase, ed->seqbasep, SEQ_DUPE_CONTEXT);
+ BKE_sequence_base_dupli_recursive(scene, scene, &nseqbase, ed->seqbasep, SEQ_DUPE_CONTEXT, 0);
if (nseqbase.first) {
Sequence *seq = nseqbase.first;
@@ -2204,23 +2236,24 @@ static int sequencer_delete_exec(bContext *C, wmOperator *UNUSED(op))
Editing *ed = BKE_sequencer_editing_get(scene, false);
Sequence *seq;
MetaStack *ms;
- bool nothingSelected = true;
+ bool nothing_selected = true;
seq = BKE_sequencer_active_get(scene);
if (seq && seq->flag & SELECT) { /* avoid a loop since this is likely to be selected */
- nothingSelected = false;
+ nothing_selected = false;
}
else {
for (seq = ed->seqbasep->first; seq; seq = seq->next) {
if (seq->flag & SELECT) {
- nothingSelected = false;
+ nothing_selected = false;
break;
}
}
}
- if (nothingSelected)
+ if (nothing_selected) {
return OPERATOR_FINISHED;
+ }
/* for effects and modifiers, try to find a replacement input */
for (seq = ed->seqbasep->first; seq; seq = seq->next) {
@@ -2798,7 +2831,7 @@ static int sequencer_view_zoom_ratio_exec(bContext *C, wmOperator *op)
float facx = BLI_rcti_size_x(&v2d->mask) / winx;
float facy = BLI_rcti_size_y(&v2d->mask) / winy;
- BLI_rctf_resize(&v2d->cur, floorf(winx * facx / ratio + 0.5f), floorf(winy * facy / ratio + 0.5f));
+ BLI_rctf_resize(&v2d->cur, ceilf(winx * facx / ratio + 0.5f), ceilf(winy * facy / ratio + 0.5f));
ED_region_tag_redraw(CTX_wm_region(C));
@@ -2823,7 +2856,7 @@ void SEQUENCER_OT_view_zoom_ratio(wmOperatorType *ot)
#if 0
-static EnumPropertyItem view_type_items[] = {
+static const EnumPropertyItem view_type_items[] = {
{SEQ_VIEW_SEQUENCE, "SEQUENCER", ICON_SEQ_SEQUENCER, "Sequencer", ""},
{SEQ_VIEW_PREVIEW, "PREVIEW", ICON_SEQ_PREVIEW, "Image Preview", ""},
{SEQ_VIEW_SEQUENCE_PREVIEW, "SEQUENCER_PREVIEW", ICON_SEQ_SEQUENCER, "Sequencer and Image Preview", ""},
@@ -3200,7 +3233,7 @@ static int sequencer_copy_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- BKE_sequence_base_dupli_recursive(scene, NULL, &nseqbase, ed->seqbasep, SEQ_DUPE_UNIQUE_NAME);
+ BKE_sequence_base_dupli_recursive(scene, scene, &nseqbase, ed->seqbasep, SEQ_DUPE_UNIQUE_NAME, 0);
/* To make sure the copied strips have unique names between each other add
* them temporarily to the end of the original seqbase. (bug 25932)
@@ -3267,7 +3300,7 @@ static int sequencer_paste_exec(bContext *C, wmOperator *UNUSED(op))
ED_sequencer_deselect_all(scene);
ofs = scene->r.cfra - seqbase_clipboard_frame;
- BKE_sequence_base_dupli_recursive(scene, NULL, &nseqbase, &seqbase_clipboard, SEQ_DUPE_UNIQUE_NAME);
+ BKE_sequence_base_dupli_recursive(scene, scene, &nseqbase, &seqbase_clipboard, SEQ_DUPE_UNIQUE_NAME, 0);
/* transform pasted strips before adding */
if (ofs) {
@@ -3352,6 +3385,9 @@ static int sequencer_swap_data_exec(bContext *C, wmOperator *op)
if (seq_act->sound) BKE_sound_add_scene_sound_defaults(scene, seq_act);
if (seq_other->sound) BKE_sound_add_scene_sound_defaults(scene, seq_other);
+ BKE_sequence_invalidate_cache(scene, seq_act);
+ BKE_sequence_invalidate_cache(scene, seq_other);
+
WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER, scene);
return OPERATOR_FINISHED;
@@ -3418,17 +3454,17 @@ void SEQUENCER_OT_view_ghost_border(wmOperatorType *ot)
ot->description = "Set the boundaries of the border used for offset-view";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = view_ghost_border_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = sequencer_view_preview_poll;
- ot->cancel = WM_border_select_cancel;
+ ot->cancel = WM_gesture_border_cancel;
/* flags */
ot->flag = 0;
/* rna */
- WM_operator_properties_gesture_border(ot, false);
+ WM_operator_properties_gesture_border(ot);
}
/* rebuild_proxy operator */
@@ -3509,7 +3545,7 @@ static int sequencer_enable_proxies_exec(bContext *C, wmOperator *op)
bool proxy_50 = RNA_boolean_get(op->ptr, "proxy_50");
bool proxy_75 = RNA_boolean_get(op->ptr, "proxy_75");
bool proxy_100 = RNA_boolean_get(op->ptr, "proxy_100");
- bool override = RNA_boolean_get(op->ptr, "override");
+ bool overwrite = RNA_boolean_get(op->ptr, "overwrite");
bool turnon = true;
if (ed == NULL || !(proxy_25 || proxy_50 || proxy_75 || proxy_100)) {
@@ -3545,7 +3581,7 @@ static int sequencer_enable_proxies_exec(bContext *C, wmOperator *op)
else
seq->strip->proxy->build_size_flags &= ~SEQ_PROXY_IMAGE_SIZE_100;
- if (!override)
+ if (!overwrite)
seq->strip->proxy->build_flags |= SEQ_PROXY_SKIP_EXISTING;
else
seq->strip->proxy->build_flags &= ~SEQ_PROXY_SKIP_EXISTING;
@@ -3577,12 +3613,12 @@ void SEQUENCER_OT_enable_proxies(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "proxy_50", false, "50%", "");
RNA_def_boolean(ot->srna, "proxy_75", false, "75%", "");
RNA_def_boolean(ot->srna, "proxy_100", false, "100%", "");
- RNA_def_boolean(ot->srna, "override", false, "Override", "");
+ RNA_def_boolean(ot->srna, "overwrite", false, "Overwrite", "");
}
/* change ops */
-static EnumPropertyItem prop_change_effect_input_types[] = {
+static const EnumPropertyItem prop_change_effect_input_types[] = {
{0, "A_B", 0, "A -> B", ""},
{1, "B_C", 0, "B -> C", ""},
{2, "A_C", 0, "A -> C", ""},
diff --git a/source/blender/editors/space_sequencer/sequencer_modifier.c b/source/blender/editors/space_sequencer/sequencer_modifier.c
index 1b3d458bb69..7ab9308f9a6 100644
--- a/source/blender/editors/space_sequencer/sequencer_modifier.c
+++ b/source/blender/editors/space_sequencer/sequencer_modifier.c
@@ -185,7 +185,7 @@ static int strip_modifier_move_exec(bContext *C, wmOperator *op)
void SEQUENCER_OT_strip_modifier_move(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{SEQ_MODIFIER_MOVE_UP, "UP", 0, "Up", "Move modifier up in the stack"},
{SEQ_MODIFIER_MOVE_DOWN, "DOWN", 0, "Down", "Move modifier down in the stack"},
{0, NULL, 0, NULL, NULL}
@@ -258,7 +258,7 @@ static int strip_modifier_copy_exec(bContext *C, wmOperator *op)
void SEQUENCER_OT_strip_modifier_copy(wmOperatorType *ot)
{
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{SEQ_MODIFIER_COPY_REPLACE, "REPLACE", 0, "Replace",
"Replace modifiers in destination"},
{SEQ_MODIFIER_COPY_APPEND, "APPEND", 0, "Append",
diff --git a/source/blender/editors/space_sequencer/sequencer_scopes.c b/source/blender/editors/space_sequencer/sequencer_scopes.c
index 80cb42c0b3d..c5d6edadb53 100644
--- a/source/blender/editors/space_sequencer/sequencer_scopes.c
+++ b/source/blender/editors/space_sequencer/sequencer_scopes.c
@@ -459,13 +459,15 @@ typedef struct MakeHistogramViewData {
} MakeHistogramViewData;
static void make_histogram_view_from_ibuf_byte_cb_ex(
- void *userdata, void *userdata_chunk, const int y, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict tls)
{
MakeHistogramViewData *data = userdata;
const ImBuf *ibuf = data->ibuf;
const unsigned char *src = (unsigned char *)ibuf->rect;
- uint32_t (*cur_bins)[HIS_STEPS] = userdata_chunk;
+ uint32_t (*cur_bins)[HIS_STEPS] = tls->userdata_chunk;
for (int x = 0; x < ibuf->x; x++) {
const unsigned char *pixel = src + (y * ibuf->x + x) * 4;
@@ -476,7 +478,8 @@ static void make_histogram_view_from_ibuf_byte_cb_ex(
}
}
-static void make_histogram_view_from_ibuf_finalize(void *userdata, void *userdata_chunk)
+static void make_histogram_view_from_ibuf_finalize(void *__restrict userdata,
+ void *__restrict userdata_chunk)
{
MakeHistogramViewData *data = userdata;
uint32_t (*bins)[HIS_STEPS] = data->bins;
@@ -501,9 +504,17 @@ static ImBuf *make_histogram_view_from_ibuf_byte(ImBuf *ibuf)
memset(bins, 0, sizeof(bins));
MakeHistogramViewData data = {.ibuf = ibuf, .bins = bins};
- BLI_task_parallel_range_finalize(
- 0, ibuf->y, &data, bins, sizeof(bins), make_histogram_view_from_ibuf_byte_cb_ex,
- make_histogram_view_from_ibuf_finalize, ibuf->y >= 256, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (ibuf->y >= 256);
+ settings.userdata_chunk = bins;
+ settings.userdata_chunk_size = sizeof(bins);
+ settings.func_finalize = make_histogram_view_from_ibuf_finalize;
+ BLI_task_parallel_range(
+ 0, ibuf->y,
+ &data,
+ make_histogram_view_from_ibuf_byte_cb_ex,
+ &settings);
nr = nb = ng = 0;
for (x = 0; x < HIS_STEPS; x++) {
@@ -548,13 +559,15 @@ BLI_INLINE int get_bin_float(float f)
}
static void make_histogram_view_from_ibuf_float_cb_ex(
- void *userdata, void *userdata_chunk, const int y, const int UNUSED(threadid))
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict tls)
{
const MakeHistogramViewData *data = userdata;
const ImBuf *ibuf = data->ibuf;
const float *src = ibuf->rect_float;
- uint32_t (*cur_bins)[HIS_STEPS] = userdata_chunk;
+ uint32_t (*cur_bins)[HIS_STEPS] = tls->userdata_chunk;
for (int x = 0; x < ibuf->x; x++) {
const float *pixel = src + (y * ibuf->x + x) * 4;
@@ -576,9 +589,17 @@ static ImBuf *make_histogram_view_from_ibuf_float(ImBuf *ibuf)
memset(bins, 0, sizeof(bins));
MakeHistogramViewData data = {.ibuf = ibuf, .bins = bins};
- BLI_task_parallel_range_finalize(
- 0, ibuf->y, &data, bins, sizeof(bins), make_histogram_view_from_ibuf_float_cb_ex,
- make_histogram_view_from_ibuf_finalize, ibuf->y >= 256, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (ibuf->y >= 256);
+ settings.userdata_chunk = bins;
+ settings.userdata_chunk_size = sizeof(bins);
+ settings.func_finalize = make_histogram_view_from_ibuf_finalize;
+ BLI_task_parallel_range(
+ 0, ibuf->y,
+ &data,
+ make_histogram_view_from_ibuf_float_cb_ex,
+ &settings);
nr = nb = ng = 0;
for (x = 0; x < HIS_STEPS; x++) {
diff --git a/source/blender/editors/space_sequencer/sequencer_select.c b/source/blender/editors/space_sequencer/sequencer_select.c
index 48c49f36471..90a369760ac 100644
--- a/source/blender/editors/space_sequencer/sequencer_select.c
+++ b/source/blender/editors/space_sequencer/sequencer_select.c
@@ -548,7 +548,7 @@ static int sequencer_select_invoke(bContext *C, wmOperator *op, const wmEvent *e
void SEQUENCER_OT_select(wmOperatorType *ot)
{
- static EnumPropertyItem sequencer_select_left_right_types[] = {
+ static const EnumPropertyItem sequencer_select_left_right_types[] = {
{SEQ_SELECT_LR_NONE, "NONE", 0, "None", "Don't do left-right selection"},
{SEQ_SELECT_LR_MOUSE, "MOUSE", 0, "Mouse", "Use mouse position for selection"},
{SEQ_SELECT_LR_LEFT, "LEFT", 0, "Left", "Select left"},
@@ -683,7 +683,7 @@ static int sequencer_select_less_exec(bContext *C, wmOperator *UNUSED(op))
if (!select_more_less_seq__internal(scene, false, false))
return OPERATOR_CANCELLED;
-
+
WM_event_add_notifier(C, NC_SCENE | ND_SEQUENCER | NA_SELECTED, scene);
return OPERATOR_FINISHED;
@@ -889,7 +889,7 @@ static int sequencer_borderselect_exec(bContext *C, wmOperator *op)
Sequence *seq;
rctf rectf, rq;
- const bool select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
const bool extend = RNA_boolean_get(op->ptr, "extend");
if (ed == NULL)
@@ -927,10 +927,10 @@ void SEQUENCER_OT_select_border(wmOperatorType *ot)
ot->description = "Select strips using border selection";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = sequencer_borderselect_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_sequencer_active;
@@ -938,7 +938,7 @@ void SEQUENCER_OT_select_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
/* ****** Selected Grouped ****** */
@@ -953,7 +953,7 @@ enum {
SEQ_SELECT_GROUP_OVERLAP,
};
-static EnumPropertyItem sequencer_prop_select_grouped_types[] = {
+static const EnumPropertyItem sequencer_prop_select_grouped_types[] = {
{SEQ_SELECT_GROUP_TYPE, "TYPE", 0, "Type", "Shared strip type"},
{SEQ_SELECT_GROUP_TYPE_BASIC, "TYPE_BASIC", 0, "Global Type", "All strips of same basic type (Graphical or Sound)"},
{SEQ_SELECT_GROUP_TYPE_EFFECT, "TYPE_EFFECT", 0, "Effect Type",
diff --git a/source/blender/editors/space_sequencer/space_sequencer.c b/source/blender/editors/space_sequencer/space_sequencer.c
index a2a80297041..6b50d3fecdf 100644
--- a/source/blender/editors/space_sequencer/space_sequencer.c
+++ b/source/blender/editors/space_sequencer/space_sequencer.c
@@ -60,6 +60,8 @@
#include "IMB_imbuf.h"
+#include "GPU_compositing.h"
+
#include "sequencer_intern.h" // own include
/**************************** common state *****************************/
@@ -218,6 +220,11 @@ static void sequencer_free(SpaceLink *sl)
if (scopes->histogram_ibuf)
IMB_freeImBuf(scopes->histogram_ibuf);
+
+ if (sseq->compositor != NULL) {
+ GPU_fx_compositor_destroy(sseq->compositor);
+ sseq->compositor = NULL;
+ }
}
@@ -435,6 +442,7 @@ static void sequencer_dropboxes(void)
/* ************* end drop *********** */
+/* DO NOT make this static, this hides the symbol and breaks API generation script. */
const char *sequencer_context_dir[] = {"edit_mask", NULL};
static int sequencer_context(const bContext *C, const char *member, bContextDataResult *result)
diff --git a/source/blender/editors/space_text/CMakeLists.txt b/source/blender/editors/space_text/CMakeLists.txt
index de85ddc40ab..91420a5d63a 100644
--- a/source/blender/editors/space_text/CMakeLists.txt
+++ b/source/blender/editors/space_text/CMakeLists.txt
@@ -43,9 +43,12 @@ set(SRC
text_format.c
text_format_lua.c
text_format_osl.c
+ text_format_pov.c
+ text_format_pov_ini.c
text_format_py.c
text_header.c
text_ops.c
+ text_undo.c
text_format.h
text_intern.h
diff --git a/source/blender/editors/space_text/space_text.c b/source/blender/editors/space_text/space_text.c
index 686a10fc785..fcb46ced750 100644
--- a/source/blender/editors/space_text/space_text.c
+++ b/source/blender/editors/space_text/space_text.c
@@ -158,7 +158,7 @@ static void text_listener(bScreen *UNUSED(sc), ScrArea *sa, wmNotifier *wmn)
}
ED_area_tag_redraw(sa);
- /* fall-through */ /* fall down to tag redraw */
+ ATTR_FALLTHROUGH; /* fall down to tag redraw */
case NA_ADDED:
case NA_REMOVED:
ED_area_tag_redraw(sa);
@@ -636,5 +636,7 @@ void ED_spacetype_text(void)
ED_text_format_register_py();
ED_text_format_register_osl();
ED_text_format_register_lua();
+ ED_text_format_register_pov();
+ ED_text_format_register_pov_ini();
}
diff --git a/source/blender/editors/space_text/text_autocomplete.c b/source/blender/editors/space_text/text_autocomplete.c
index c38c57b9528..9163831c333 100644
--- a/source/blender/editors/space_text/text_autocomplete.c
+++ b/source/blender/editors/space_text/text_autocomplete.c
@@ -241,7 +241,7 @@ static void get_suggest_prefix(Text *text, int offset)
texttool_suggest_prefix(line + i, len);
}
-static void confirm_suggestion(Text *text)
+static void confirm_suggestion(Text *text, TextUndoBuf *utxt)
{
SuggItem *sel;
int i, over = 0;
@@ -260,7 +260,7 @@ static void confirm_suggestion(Text *text)
// for (i = 0; i < skipleft; i++)
// txt_move_left(text, 0);
BLI_assert(memcmp(sel->name, &line[i], over) == 0);
- txt_insert_buf(text, sel->name + over);
+ txt_insert_buf(text, utxt, sel->name + over);
// for (i = 0; i < skipleft; i++)
// txt_move_right(text, 0);
@@ -284,7 +284,8 @@ static int text_autocomplete_invoke(bContext *C, wmOperator *op, const wmEvent *
ED_area_tag_redraw(CTX_wm_area(C));
if (texttool_suggest_first() == texttool_suggest_last()) {
- confirm_suggestion(st->text);
+ TextUndoBuf *utxt = NULL; // FIXME
+ confirm_suggestion(st->text, utxt);
text_update_line_edited(st->text->curl);
text_autocomplete_free(C, op);
return OPERATOR_FINISHED;
@@ -314,6 +315,8 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
(void)text;
+ TextUndoBuf *utxt = NULL; // FIXME
+
if (st->doplugins && texttool_text_is_active(st->text)) {
if (texttool_suggest_first()) tools |= TOOL_SUGG_LIST;
if (texttool_docs_get()) tools |= TOOL_DOCUMENT;
@@ -328,7 +331,7 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
if (tools & TOOL_SUGG_LIST) {
texttool_suggest_clear();
}
- if (tools & TOOL_DOCUMENT) {
+ if (tools & TOOL_DOCUMENT) {
texttool_docs_clear();
doc_scroll = 0;
}
@@ -340,7 +343,7 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
case MIDDLEMOUSE:
if (event->val == KM_PRESS) {
if (text_do_suggest_select(st, ar)) {
- confirm_suggestion(st->text);
+ confirm_suggestion(st->text, utxt);
text_update_line_edited(st->text->curl);
swallow = 1;
}
@@ -375,7 +378,7 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
case PADENTER:
if (event->val == KM_PRESS) {
if (tools & TOOL_SUGG_LIST) {
- confirm_suggestion(st->text);
+ confirm_suggestion(st->text, utxt);
text_update_line_edited(st->text->curl);
swallow = 1;
draw = 1;
@@ -455,7 +458,7 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
break;
case PAGEDOWNKEY:
scroll = SUGG_LIST_SIZE - 1;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case WHEELDOWNMOUSE:
case DOWNARROWKEY:
if (event->val == KM_PRESS) {
@@ -489,7 +492,7 @@ static int text_autocomplete_modal(bContext *C, wmOperator *op, const wmEvent *e
break;
case PAGEUPKEY:
scroll = SUGG_LIST_SIZE - 1;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case WHEELUPMOUSE:
case UPARROWKEY:
if (event->val == KM_PRESS) {
diff --git a/source/blender/editors/space_text/text_draw.c b/source/blender/editors/space_text/text_draw.c
index 81605a80f69..4eb66811c7d 100644
--- a/source/blender/editors/space_text/text_draw.c
+++ b/source/blender/editors/space_text/text_draw.c
@@ -594,7 +594,7 @@ static void text_update_drawcache(SpaceText *st, ARegion *ar)
drawcache->total_lines = 0;
if (st->showlinenrs)
- st->linenrs_tot = (int)floor(log10((float)nlines)) + 1;
+ st->linenrs_tot = integer_digits_i(nlines);
while (line) {
if (drawcache->valid_head) { /* we're inside valid head lines */
@@ -628,7 +628,7 @@ static void text_update_drawcache(SpaceText *st, ARegion *ar)
nlines = BLI_listbase_count(&txt->lines);
if (st->showlinenrs)
- st->linenrs_tot = (int)floor(log10((float)nlines)) + 1;
+ st->linenrs_tot = integer_digits_i(nlines);
}
drawcache->total_lines = nlines;
@@ -926,6 +926,7 @@ static void draw_textscroll(const SpaceText *st, rcti *scroll, rcti *back)
/*********************** draw documentation *******************************/
+#if 0
static void draw_documentation(const SpaceText *st, ARegion *ar)
{
TextDrawContext tdc = {0};
@@ -1014,6 +1015,7 @@ static void draw_documentation(const SpaceText *st, ARegion *ar)
draw_documentation(st, ar);
}
}
+#endif
/*********************** draw suggestion list *******************************/
@@ -1487,7 +1489,7 @@ void draw_text_main(SpaceText *st, ARegion *ar)
/* draw other stuff */
draw_brackets(st, &tdc, ar);
draw_textscroll(st, &scroll, &back);
- draw_documentation(st, ar);
+ /* draw_documentation(st, ar); - No longer supported */
draw_suggestion_list(st, &tdc, ar);
text_font_end(&tdc);
diff --git a/source/blender/editors/space_text/text_format.h b/source/blender/editors/space_text/text_format.h
index b901ec83a9c..d7cf31d0b41 100644
--- a/source/blender/editors/space_text/text_format.h
+++ b/source/blender/editors/space_text/text_format.h
@@ -102,6 +102,8 @@ void ED_text_format_register(TextFormatType *tft);
void ED_text_format_register_py(void);
void ED_text_format_register_osl(void);
void ED_text_format_register_lua(void);
+void ED_text_format_register_pov(void);
+void ED_text_format_register_pov_ini(void);
#define STR_LITERAL_STARTSWITH(str, str_literal, len_var) \
(strncmp(str, str_literal, len_var = (sizeof(str_literal) - 1)) == 0)
diff --git a/source/blender/editors/space_text/text_format_pov.c b/source/blender/editors/space_text/text_format_pov.c
new file mode 100644
index 00000000000..4c9abecedd6
--- /dev/null
+++ b/source/blender/editors/space_text/text_format_pov.c
@@ -0,0 +1,903 @@
+/*
+ * ***** 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
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/space_text/text_format_pov.c
+ * \ingroup sptext
+ */
+
+#include <string.h>
+
+#include "BLI_blenlib.h"
+
+#include "DNA_text_types.h"
+#include "DNA_space_types.h"
+
+#include "BKE_text.h"
+
+#include "text_format.h"
+
+/* *** POV Keywords (for format_line) *** */
+
+/* Checks the specified source string for a POV keyword (minus boolean & 'nil').
+ * This name must start at the beginning of the source string and must be
+ * followed by a non-identifier (see text_check_identifier(char)) or null char.
+ *
+ * If a keyword is found, the length of the matching word is returned.
+ * Otherwise, -1 is returned.
+ *
+ * See:
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+
+static int txtfmt_pov_find_keyword(const char *string)
+{
+ int i, len;
+ /* Language Directives */
+ if (STR_LITERAL_STARTSWITH(string, "deprecated", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "persistent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "statistics", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "version", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "warning", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "declare", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "default", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "include", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "append", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "elseif", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "debug", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "break", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "else", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "error", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fclose", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fopen", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ifndef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ifdef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "patch", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "local", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "macro", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "range", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "read", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "render", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "switch", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "undef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "while", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "write", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "case", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "end", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "for", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "if", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+static int txtfmt_pov_find_reserved_keywords(const char *string)
+{
+ int i, len;
+ /* POV-Ray Built-in Variables
+ * list is from...
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+
+ /* Float Functions */
+ if (STR_LITERAL_STARTSWITH(string, "conserve_energy", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_intersections", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "dimension_size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bitwise_and", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bitwise_or", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bitwise_xor", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "file_exists", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "precompute", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "dimensions", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clipped_by", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "shadowless", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "turb_depth", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "reciprocal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quaternion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "phong_size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tesselate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "save_file", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "load_file", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_trace", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "transform", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "translate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "direction", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "roughness", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "metallic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gts_load", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gts_save", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "location", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "altitude", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "function", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "evaluate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inverse", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "collect", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "target", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "albedo", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rotate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "matrix", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "look_at", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "jitter", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "angle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "right", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "scale", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "child", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "crand", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "blink", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "defined", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "degrees", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inside", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "radians", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vlength", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "select", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "floor", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "strcmp", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "strlen", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tessel", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sturm", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "abs", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "acosh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "prod", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "with", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "acos", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "asc", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "asinh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "asin", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "atan2", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "atand", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "atanh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "atan", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ceil", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "warp", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cosh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "log", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "min", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mod", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pow", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rand", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "seed", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "form", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sinh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sqrt", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tanh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vdot", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sin", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sqr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sum", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pwr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tan", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "val", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cos", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "div", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "exp", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "int", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sky", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "up", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ln", len)) i = len;
+ /* Color Identifiers */
+ else if (STR_LITERAL_STARTSWITH(string, "transmit", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "filter", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "srgbft", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "srgbf", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "srgbt", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rgbft", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gamma", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "green", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "blue", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gray", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "srgb", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sRGB", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SRGB", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rgbf", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rgbt", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rgb", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "red", len)) i = len;
+ /* Color Spaces */
+ else if (STR_LITERAL_STARTSWITH(string, "pov", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hsl", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hsv", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "xyl", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "xyv", len)) i = len;
+ /* Vector Functions */
+ else if (STR_LITERAL_STARTSWITH(string, "vaxis_rotate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vturbulence", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "min_extent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vnormalize", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_extent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vrotate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vcross", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "trace", len)) i = len;
+ /* String Functions */
+ else if (STR_LITERAL_STARTSWITH(string, "file_time", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "datetime", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "concat", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "strlwr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "strupr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "substr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vstr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "chr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "str", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+
+static int txtfmt_pov_find_reserved_builtins(const char *string)
+{
+ int i, len;
+
+ /* POV-Ray Built-in Variables
+ * list is from...
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+ /* Language Keywords */
+ if (STR_LITERAL_STARTSWITH(string, "reflection_exponent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "area_illumination", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "all_intersections", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cutaway_textures", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "smooth_triangle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lommel_seeliger", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "falloff_angle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "aa_threshold", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hypercomplex", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "major_radius", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_distance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_iteration", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "colour_space", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "color_space", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "iridescence", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "subsurface", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "scattering", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "absorption", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "water_level", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "reflection", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_extent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "oren_nayar", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "refraction", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hierarchy", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "radiosity", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tolerance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "interior", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "toroidal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "emission", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "material", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "internal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "photons", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "arc_angle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "minnaert", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "texture", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "array", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "black_hole", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "component", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "composite", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "coords", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cube", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "dist_exp", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "exterior", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "file_gamma", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "flatness", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "planet", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "screw", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "keep", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "flip", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "move", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "roll", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "look_at", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "metric", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "offset", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "orientation", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pattern", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "precision", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "repeat", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bend", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "alpha", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "slice", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "smooth", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "solid", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "all", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "now", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pot", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "type", len)) i = len;
+ /* Animation Options */
+ else if (STR_LITERAL_STARTSWITH(string, "global_settings", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "input_file_name", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "initial_clock", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "initial_frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "frame_number", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_height", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "final_clock", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "final_frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock_delta", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock_on", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock", len)) i = len;
+ /* Spline Identifiers */
+ else if (STR_LITERAL_STARTSWITH(string, "extended_x_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "general_x_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quadratic_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "basic_x_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "natural_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "linear_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bezier_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "akima_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sor_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tcb_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "linear_sweep", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "conic_sweep", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "b_spline", len)) i = len;
+ /* Patterns */
+ else if (STR_LITERAL_STARTSWITH(string, "pigment_pattern", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_pattern", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "density_file", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cylindrical", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "proportion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "triangular", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "proximity", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spherical", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bump_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "wrinkles", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "average", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "voronoi", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "masonry", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "binary", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "boxed", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bozo", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "brick", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bumps", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cells", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "checker", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "crackle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "dents", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "facets", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gradient", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "granite", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hexagon", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "julia", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "leopard", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "magnet", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mandel", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "marble", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "onion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pavement", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "planar", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quilted", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "radial", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ripples", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "slope", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spiral1", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spiral2", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spotted", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "square", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tile2", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tiling", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tiles", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "waves", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "wood", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "agate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "aoi", len)) i = len;
+ /* Objects */
+ else if (STR_LITERAL_STARTSWITH(string, "superellipsoid", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bicubic_patch", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "julia_fractal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "height_field", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic_spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sphere_sweep", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "light_group", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "light_source", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "intersection", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "isosurface", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "background", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sky_sphere", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cylinder", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "difference", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "brilliance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "parametric", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "interunion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "intermerge", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "polynomial", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "displace", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "specular", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ambient", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "diffuse", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "polygon", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quadric", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quartic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "rainbow", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sphere", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spline", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "prism", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "galley", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "phong", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cone", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "blob", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "box", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "disc", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fog", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lathe", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "merge", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mesh2", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mesh", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "object", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ovus", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lemon", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "plane", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "poly", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "irid", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sor", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "text", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "torus", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "triangle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "union", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "colour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "color", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "media", len)) i = len;
+ /* Built-in Vectors */
+ else if (STR_LITERAL_STARTSWITH(string, "t", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "u", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "v", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "x", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "y", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "z", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+
+/* Checks the specified source string for a POV modifiers. This
+ * name must start at the beginning of the source string and must be followed
+ * by a non-identifier (see text_check_identifier(char)) or null character.
+ *
+ * If a special name is found, the length of the matching name is returned.
+ * Otherwise, -1 is returned.
+ *
+ * See:
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+
+static int txtfmt_pov_find_specialvar(const char *string)
+{
+ int i, len;
+ /* Modifiers */
+ if (STR_LITERAL_STARTSWITH(string, "dispersion_samples", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "projected_through", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "double_illuminate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "expand_thresholds", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "media_interaction", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "media_attenuation", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "low_error_factor", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "recursion_limit", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "interior_texture", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_trace_level", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gray_threshold", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pretrace_start", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "normal_indices", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "normal_vectors", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "vertex_vectors", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "noise_generator", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "irid_wavelength", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "number_of_waves", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ambient_light", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inside_vector", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "face_indices", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "texture_list", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_gradient", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uv_indices", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uv_vectors", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fade_distance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "global_lights", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_bump_scale", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pretrace_end", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_radiosity", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_reflection", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "assumed_gamma", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "scallop_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "triangle_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "nearest_count", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "maximum_reuse", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "minimum_reuse", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "always_sample", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "translucency", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "eccentricity", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "contained_by", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inside_point", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "adc_bailout", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "density_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "split_union", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mm_per_unit", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "agate_turb", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bounded_by", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "brick_size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hf_gray_16", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "dispersion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "extinction", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "thickness", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "color_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "colour_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fade_colour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fade_power", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fade_color", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "normal_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pigment_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quick_color", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "quick_colour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "material_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pass_through", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "interpolate", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "texture_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "error_bound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "brightness", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "use_color", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "use_alpha", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "use_colour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "use_index", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uv_mapping", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "importance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "max_sample", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "intervals", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sine_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "slope_map", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "poly_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_shadow", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ramp_wave", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "precision", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "original", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "accuracy", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "map_type", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_image", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "distance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "autostop", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "caustics", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "octaves", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "aa_level", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "frequency", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fog_offset", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "modulation", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "outbound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no_cache", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pigment", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "charset", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inbound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "outside", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "inner", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "turbulence", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "threshold", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "accuracy", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "polarity", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bump_size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "circular", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "control0", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "control1", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "maximal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "minimal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fog_type", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fog_alt", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "samples", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "origin", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "amount", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "adaptive", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "exponent", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "strength", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "density", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fresnel", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "albinos", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "finish", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "method", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "omega", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fixed", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spacing", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "u_steps", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "v_steps", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "offset", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hollow", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gather", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lambda", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mortar", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "cubic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "count", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "once", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "orient", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "normal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "phase", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ratio", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "open", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ior", len)) i = len;
+ /* Light Types and options*/
+ else if (STR_LITERAL_STARTSWITH(string, "area_light", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "looks_like", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fade_power", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tightness", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "spotlight", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "parallel", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "point_at", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "falloff", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "radius", len)) i = len;
+ /* Camera Types and options*/
+ else if (STR_LITERAL_STARTSWITH(string, "omni_directional_stereo", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lambert_cylindrical", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "miller_cylindrical", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "lambert_azimuthal", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ultra_wide_angle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera_direction", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera_location ", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "van_der_grinten", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "aitoff_hammer", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "smyth_craster", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "orthographic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera_right", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "blur_samples", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "plate_carree", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera_type", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "perspective", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mesh_camera", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "focal_point", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "balthasart", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "confidence", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "parallaxe", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hobo_dyer", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "camera_up", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "panoramic", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "eckert_vi", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "eckert_iv", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mollweide", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "aperture", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "behrmann", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "variance", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "stereo", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "icosa", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tetra", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "octa", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "mercator", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "omnimax", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fisheye", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "edwards", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "peters", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gall", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+static int txtfmt_pov_find_bool(const char *string)
+{
+ int i, len;
+ /*Built-in Constants*/
+ if (STR_LITERAL_STARTSWITH(string, "unofficial", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "false", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "off", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "true", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "yes", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "on", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pi", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tau", len)) i = len;
+ /* Encodings */
+ else if (STR_LITERAL_STARTSWITH(string, "sint16be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint16le", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint32be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint32le", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint16be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint16le", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bt2020", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "bt709", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint8", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint8", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ascii", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "utf8", len)) i = len;
+ /* Filetypes */
+ else if (STR_LITERAL_STARTSWITH(string, "tiff", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "df3", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "exr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gif", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hdr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "iff", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "jpeg", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pgm", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "png", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ppm", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sys", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tga", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ttf", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "Nonetheless") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+static char txtfmt_pov_format_identifier(const char *str)
+{
+ char fmt;
+ if ((txtfmt_pov_find_specialvar(str)) != -1) fmt = FMT_TYPE_SPECIAL;
+ else if ((txtfmt_pov_find_keyword(str)) != -1) fmt = FMT_TYPE_KEYWORD;
+ else if ((txtfmt_pov_find_reserved_keywords(str)) != -1) fmt = FMT_TYPE_RESERVED;
+ else if ((txtfmt_pov_find_reserved_builtins(str)) != -1) fmt = FMT_TYPE_DIRECTIVE;
+ else fmt = FMT_TYPE_DEFAULT;
+ return fmt;
+}
+
+static void txtfmt_pov_format_line(SpaceText *st, TextLine *line, const bool do_next)
+{
+ FlattenString fs;
+ const char *str;
+ char *fmt;
+ char cont_orig, cont, find, prev = ' ';
+ int len, i;
+
+ /* Get continuation from previous line */
+ if (line->prev && line->prev->format != NULL) {
+ fmt = line->prev->format;
+ cont = fmt[strlen(fmt) + 1]; /* Just after the null-terminator */
+ BLI_assert((FMT_CONT_ALL & cont) == cont);
+ }
+ else {
+ cont = FMT_CONT_NOP;
+ }
+
+ /* Get original continuation from this line */
+ if (line->format != NULL) {
+ fmt = line->format;
+ cont_orig = fmt[strlen(fmt) + 1]; /* Just after the null-terminator */
+ BLI_assert((FMT_CONT_ALL & cont_orig) == cont_orig);
+ }
+ else {
+ cont_orig = 0xFF;
+ }
+
+ len = flatten_string(st, &fs, line->line);
+ str = fs.buf;
+ if (!text_check_format_len(line, len)) {
+ flatten_string_free(&fs);
+ return;
+ }
+ fmt = line->format;
+
+ while (*str) {
+ /* Handle escape sequences by skipping both \ and next char */
+ if (*str == '\\') {
+ *fmt = prev; fmt++; str++;
+ if (*str == '\0') break;
+ *fmt = prev; fmt++; str += BLI_str_utf8_size_safe(str);
+ continue;
+ }
+ /* Handle continuations */
+ else if (cont) {
+ /* C-Style comments */
+ if (cont & FMT_CONT_COMMENT_C) {
+ if (*str == '*' && *(str + 1) == '/') {
+ *fmt = FMT_TYPE_COMMENT; fmt++; str++;
+ *fmt = FMT_TYPE_COMMENT;
+ cont = FMT_CONT_NOP;
+ }
+ else {
+ *fmt = FMT_TYPE_COMMENT;
+ }
+ /* Handle other comments */
+ }
+ else {
+ find = (cont & FMT_CONT_QUOTEDOUBLE) ? '"' : '\'';
+ if (*str == find) cont = 0;
+ *fmt = FMT_TYPE_STRING;
+ }
+
+ str += BLI_str_utf8_size_safe(str) - 1;
+ }
+ /* Not in a string... */
+ else {
+ /* C-Style (multi-line) comments */
+ if (*str == '/' && *(str + 1) == '*') {
+ cont = FMT_CONT_COMMENT_C;
+ *fmt = FMT_TYPE_COMMENT; fmt++; str++;
+ *fmt = FMT_TYPE_COMMENT;
+ }
+ /* Single line comment */
+ else if (*str == '/' && *(str + 1) == '/') {
+ text_format_fill(&str, &fmt, FMT_TYPE_COMMENT, len - (int)(fmt - line->format));
+ }
+ else if (*str == '"' || *str == '\'') {
+ /* Strings */
+ find = *str;
+ cont = (*str == '"') ? FMT_CONT_QUOTEDOUBLE : FMT_CONT_QUOTESINGLE;
+ *fmt = FMT_TYPE_STRING;
+ }
+ /* Whitespace (all ws. has been converted to spaces) */
+ else if (*str == ' ') {
+ *fmt = FMT_TYPE_WHITESPACE;
+ }
+ /* Numbers (digits not part of an identifier and periods followed by digits) */
+ else if ((prev != FMT_TYPE_DEFAULT && text_check_digit(*str)) ||
+ (*str == '.' && text_check_digit(*(str + 1))))
+ {
+ *fmt = FMT_TYPE_NUMERAL;
+ }
+ /* Booleans */
+ else if (prev != FMT_TYPE_DEFAULT && (i = txtfmt_pov_find_bool(str)) != -1) {
+ if (i > 0) {
+ text_format_fill_ascii(&str, &fmt, FMT_TYPE_NUMERAL, i);
+ }
+ else {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ }
+ /* Punctuation */
+ else if (text_check_delim(*str)) {
+ *fmt = FMT_TYPE_SYMBOL;
+ }
+ /* Identifiers and other text (no previous ws. or delims. so text continues) */
+ else if (prev == FMT_TYPE_DEFAULT) {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ /* Not ws, a digit, punct, or continuing text. Must be new, check for special words */
+ else {
+ /* Special vars(v) or built-in keywords(b) */
+ /* keep in sync with 'txtfmt_pov_format_identifier()' */
+ if ((i = txtfmt_pov_find_specialvar(str)) != -1) prev = FMT_TYPE_SPECIAL;
+ else if ((i = txtfmt_pov_find_keyword(str)) != -1) prev = FMT_TYPE_KEYWORD;
+ else if ((i = txtfmt_pov_find_reserved_keywords(str)) != -1) prev = FMT_TYPE_RESERVED;
+ else if ((i = txtfmt_pov_find_reserved_builtins(str)) != -1) prev = FMT_TYPE_DIRECTIVE;
+
+ if (i > 0) {
+ text_format_fill_ascii(&str, &fmt, prev, i);
+ }
+ else {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ }
+ }
+ prev = *fmt; fmt++; str++;
+ }
+
+ /* Terminate and add continuation char */
+ *fmt = '\0'; fmt++;
+ *fmt = cont;
+
+ /* If continuation has changed and we're allowed, process the next line */
+ if (cont != cont_orig && do_next && line->next) {
+ txtfmt_pov_format_line(st, line->next, do_next);
+ }
+
+ flatten_string_free(&fs);
+}
+
+void ED_text_format_register_pov(void)
+{
+ static TextFormatType tft = {NULL};
+ static const char *ext[] = {"pov", "inc", "mcr", "mac", NULL};
+
+ tft.format_identifier = txtfmt_pov_format_identifier;
+ tft.format_line = txtfmt_pov_format_line;
+ tft.ext = ext;
+
+ ED_text_format_register(&tft);
+}
diff --git a/source/blender/editors/space_text/text_format_pov_ini.c b/source/blender/editors/space_text/text_format_pov_ini.c
new file mode 100644
index 00000000000..453dd1d748c
--- /dev/null
+++ b/source/blender/editors/space_text/text_format_pov_ini.c
@@ -0,0 +1,491 @@
+/*
+ * ***** 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
+ * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/space_text/text_format_pov_ini.c
+ * \ingroup sptext
+ */
+
+#include <string.h>
+
+#include "BLI_blenlib.h"
+
+#include "DNA_text_types.h"
+#include "DNA_space_types.h"
+
+#include "BKE_text.h"
+
+#include "text_format.h"
+
+/* *** POV INI Keywords (for format_line) *** */
+
+/* Checks the specified source string for a POV INI keyword (minus boolean & 'nil').
+ * This name must start at the beginning of the source string and must be
+ * followed by a non-identifier (see text_check_identifier(char)) or null char.
+ *
+ * If a keyword is found, the length of the matching word is returned.
+ * Otherwise, -1 is returned.
+ *
+ * See:
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+
+static int txtfmt_ini_find_keyword(const char *string)
+{
+ int i, len;
+ /* Language Directives */
+ if (STR_LITERAL_STARTSWITH(string, "deprecated", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "statistics", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "declare", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "default", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "version", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "warning", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "include", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fclose", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ifndef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "append", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "elseif", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "debug", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "error", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "fopen", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ifdef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "local", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "macro", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "range", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "render", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "break", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "switch", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "undef", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "while", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "write", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "case", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "else", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "read", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "end", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "for", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "if", len)) i = len;
+
+ else if (STR_LITERAL_STARTSWITH(string, "I", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "S", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "A", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Q", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "U", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "F", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "C", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "N", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "P", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "T", len)) i = len;
+
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+static int txtfmt_ini_find_reserved(const char *string)
+{
+ int i, len;
+ /* POV-Ray Built-in INI Variables
+ * list is from...
+ * http://www.povray.org/documentation/view/3.7.0/212/
+ */
+ if (STR_LITERAL_STARTSWITH(string, "RenderCompleteSoundEnabled", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Create_Continue_Trace_Log", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ParseErrorSoundEnabled", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "RenderErrorSoundEnabled", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "HideWhenMainMinimized", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias_Confidence", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "RenderCompleteSound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ParseErrorSound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "RenderErrorSound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "UseExtensions", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ReadWriteSourceDir", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionLeft", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionTop", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionRight", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionBottom", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Pre_Scene_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Pre_Frame_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Post_Scene_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Post_Frame_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "User_Abort_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Fatal_Error_Command", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionX", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NormalPositionY", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Pre_Scene_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Pre_Frame_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Post_Scene_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Post_Frame_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "User_Abort_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Fatal_Error_Return", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias_Threshold", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias_Gamma", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias_Depth", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "input_file_name", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Subset_Start_Frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Subset_End_Frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "UseToolbar", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "UseTooltips", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Frame_Step", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Cyclic_Animation", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Field_Render", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Odd_Field", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "final_clock", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "final_frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "frame_number", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "initial_clock", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "initial_frame", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_height", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "image_width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Start_Column", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Start_Row", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "End_Column", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "End_Row", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Test_Abort_Count", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Test_Abort", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Continue_Trace", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Bounding_Method", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Create_Ini", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Display_Gamma", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Display", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Version", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Pause_When_Done", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Verbose", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Preview_Start_Size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Preview_End_Size", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Output_to_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Input_File_Name", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Output_File_Name", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Output_File_Type", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Output_Alpha", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Bits_Per_Color", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Compression", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Dither_Method", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Include_Header", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Library_Path", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Debug_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Fatal_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Render_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Statistic_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Warning_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Warning_Level", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "All_Console", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Debug_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Fatal_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Render_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Statistic_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Warning_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "All_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Quality", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Bounding_Threshold", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Bounding", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Light_Buffer", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Vista_Buffer", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Remove_Bounds", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Split_Unions", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Glare_Desaturation", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Sampling_Method", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Stochastic_Seed", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Jitter_Amount", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Jitter", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Antialias_Depth", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "CheckNewVersion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "RunCount", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "CommandLine", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "TextColour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "WarningColour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ErrorColour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "BackgroundColour", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "DropToEditor", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastRenderName", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastRenderPath", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastQueuePath", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SecondaryINISection", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "BetaVersionNo64", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastBitmapName", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastBitmapPath", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastINIPath", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SecondaryINIFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "BackgroundFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SaveSettingsOnExit", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "TileBackground", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "HideNewUserHelp", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SendSystemInfo", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ItsAboutTime", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "LastPath", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Band0Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Band1Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Band2Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Band3Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Band4Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ShowCmd", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Transparency", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Use8BitMode", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "MakeActive", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "KeepAboveMain", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "AutoClose", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "PreserveBitmap", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "FontSize", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "FontWeight", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "KeepMessages", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "AlertSound", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Completion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Priority", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "DutyCycle", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "AlertOnCompletion", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "AutoRender", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "PreventSleep", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NoShelloutWait", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SystemNoActive", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "NoShellOuts", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "VideoSource", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SceneFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "OutputFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "IniOutputFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "CurrentDirectory", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "SourceFile", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Rendering", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "RenderwinClose", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Append_File", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Warning Level", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock_delta", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock_on", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "clock", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Height", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Width", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Dither", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Flags", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "Font", len)) i = len;
+ /* Filetypes */
+ else if (STR_LITERAL_STARTSWITH(string, "df3", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "exr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "gif", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "hdr", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "iff", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "jpeg", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pgm", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "png", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "ppm", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sys", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tga", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tiff", len)) i = len;
+ /* Encodings */
+ else if (STR_LITERAL_STARTSWITH(string, "ascii", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "utf8", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint8", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint16be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "uint16le", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint8", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint16be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint16le", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint32be", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "sint32le", len)) i = len;
+
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "definate") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+
+
+
+static int txtfmt_ini_find_bool(const char *string)
+{
+ int i, len;
+ /* Built-in Constants */
+ if (STR_LITERAL_STARTSWITH(string, "false", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "no", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "off", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "true", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "yes", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "on", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "pi", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "tau", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%o", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%s", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%n", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%k", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%h", len)) i = len;
+ else if (STR_LITERAL_STARTSWITH(string, "%w", len)) i = len;
+ else i = 0;
+
+ /* If next source char is an identifier (eg. 'i' in "Nonetheless") no match */
+ return (i == 0 || text_check_identifier(string[i])) ? -1 : i;
+}
+
+static char txtfmt_pov_ini_format_identifier(const char *str)
+{
+ char fmt;
+ if ((txtfmt_ini_find_keyword(str)) != -1) fmt = FMT_TYPE_KEYWORD;
+ else if ((txtfmt_ini_find_reserved(str)) != -1) fmt = FMT_TYPE_RESERVED;
+ else fmt = FMT_TYPE_DEFAULT;
+ return fmt;
+}
+
+static void txtfmt_pov_ini_format_line(SpaceText *st, TextLine *line, const bool do_next)
+{
+ FlattenString fs;
+ const char *str;
+ char *fmt;
+ char cont_orig, cont, find, prev = ' ';
+ int len, i;
+
+ /* Get continuation from previous line */
+ if (line->prev && line->prev->format != NULL) {
+ fmt = line->prev->format;
+ cont = fmt[strlen(fmt) + 1]; /* Just after the null-terminator */
+ BLI_assert((FMT_CONT_ALL & cont) == cont);
+ }
+ else {
+ cont = FMT_CONT_NOP;
+ }
+
+ /* Get original continuation from this line */
+ if (line->format != NULL) {
+ fmt = line->format;
+ cont_orig = fmt[strlen(fmt) + 1]; /* Just after the null-terminator */
+ BLI_assert((FMT_CONT_ALL & cont_orig) == cont_orig);
+ }
+ else {
+ cont_orig = 0xFF;
+ }
+
+ len = flatten_string(st, &fs, line->line);
+ str = fs.buf;
+ if (!text_check_format_len(line, len)) {
+ flatten_string_free(&fs);
+ return;
+ }
+ fmt = line->format;
+
+ while (*str) {
+ /* Handle escape sequences by skipping both \ and next char */
+ if (*str == '\\') {
+ *fmt = prev; fmt++; str++;
+ if (*str == '\0') break;
+ *fmt = prev; fmt++; str += BLI_str_utf8_size_safe(str);
+ continue;
+ }
+ /* Handle continuations */
+ else if (cont) {
+ /* Multi-line comments */
+ if (cont & FMT_CONT_COMMENT_C) {
+ if (*str == ']' && *(str + 1) == ']') {
+ *fmt = FMT_TYPE_COMMENT; fmt++; str++;
+ *fmt = FMT_TYPE_COMMENT;
+ cont = FMT_CONT_NOP;
+ }
+ else {
+ *fmt = FMT_TYPE_COMMENT;
+ }
+ /* Handle other comments */
+ }
+ else {
+ find = (cont & FMT_CONT_QUOTEDOUBLE) ? '"' : '\'';
+ if (*str == find) cont = 0;
+ *fmt = FMT_TYPE_STRING;
+ }
+
+ str += BLI_str_utf8_size_safe(str) - 1;
+ }
+ /* Not in a string... */
+ else {
+ /* Multi-line comments not supported */
+ /* Single line comment */
+ if (*str == ';') {
+ text_format_fill(&str, &fmt, FMT_TYPE_COMMENT, len - (int)(fmt - line->format));
+ }
+ else if (*str == '"' || *str == '\'') {
+ /* Strings */
+ find = *str;
+ cont = (*str == '"') ? FMT_CONT_QUOTEDOUBLE : FMT_CONT_QUOTESINGLE;
+ *fmt = FMT_TYPE_STRING;
+ }
+ /* Whitespace (all ws. has been converted to spaces) */
+ else if (*str == ' ') {
+ *fmt = FMT_TYPE_WHITESPACE;
+ }
+ /* Numbers (digits not part of an identifier and periods followed by digits) */
+ else if ((prev != FMT_TYPE_DEFAULT && text_check_digit(*str)) ||
+ (*str == '.' && text_check_digit(*(str + 1))))
+ {
+ *fmt = FMT_TYPE_NUMERAL;
+ }
+ /* Booleans */
+ else if (prev != FMT_TYPE_DEFAULT && (i = txtfmt_ini_find_bool(str)) != -1) {
+ if (i > 0) {
+ text_format_fill_ascii(&str, &fmt, FMT_TYPE_NUMERAL, i);
+ }
+ else {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ }
+ /* Punctuation */
+ else if ((*str != '#') && text_check_delim(*str)) {
+ *fmt = FMT_TYPE_SYMBOL;
+ }
+ /* Identifiers and other text (no previous ws. or delims. so text continues) */
+ else if (prev == FMT_TYPE_DEFAULT) {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ /* Not ws, a digit, punct, or continuing text. Must be new, check for special words */
+ else {
+ /* Special vars(v) or built-in keywords(b) */
+ /* keep in sync with 'txtfmt_ini_format_identifier()' */
+ if ((i = txtfmt_ini_find_keyword(str)) != -1) prev = FMT_TYPE_KEYWORD;
+ else if ((i = txtfmt_ini_find_reserved(str)) != -1) prev = FMT_TYPE_RESERVED;
+
+ if (i > 0) {
+ text_format_fill_ascii(&str, &fmt, prev, i);
+ }
+ else {
+ str += BLI_str_utf8_size_safe(str) - 1;
+ *fmt = FMT_TYPE_DEFAULT;
+ }
+ }
+ }
+ prev = *fmt; fmt++; str++;
+ }
+
+ /* Terminate and add continuation char */
+ *fmt = '\0'; fmt++;
+ *fmt = cont;
+
+ /* If continuation has changed and we're allowed, process the next line */
+ if (cont != cont_orig && do_next && line->next) {
+ txtfmt_pov_ini_format_line(st, line->next, do_next);
+ }
+
+ flatten_string_free(&fs);
+}
+
+void ED_text_format_register_pov_ini(void)
+{
+ static TextFormatType tft = {NULL};
+ static const char *ext[] = {"ini", NULL};
+
+ tft.format_identifier = txtfmt_pov_ini_format_identifier;
+ tft.format_line = txtfmt_pov_ini_format_line;
+ tft.ext = ext;
+
+ ED_text_format_register(&tft);
+}
diff --git a/source/blender/editors/space_text/text_ops.c b/source/blender/editors/space_text/text_ops.c
index f603fa1b0f1..68338bf2337 100644
--- a/source/blender/editors/space_text/text_ops.c
+++ b/source/blender/editors/space_text/text_ops.c
@@ -92,7 +92,7 @@ static int text_edit_poll(bContext *C)
if (!text)
return 0;
- if (ID_IS_LINKED_DATABLOCK(text)) {
+ if (ID_IS_LINKED(text)) {
// BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -108,7 +108,7 @@ int text_space_edit_poll(bContext *C)
if (!st || !text)
return 0;
- if (ID_IS_LINKED_DATABLOCK(text)) {
+ if (ID_IS_LINKED(text)) {
// BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -128,7 +128,7 @@ static int text_region_edit_poll(bContext *C)
if (!ar || ar->regiontype != RGN_TYPE_WINDOW)
return 0;
- if (ID_IS_LINKED_DATABLOCK(text)) {
+ if (ID_IS_LINKED(text)) {
// BKE_report(op->reports, RPT_ERROR, "Cannot edit external libdata");
return 0;
}
@@ -731,7 +731,8 @@ static int text_paste_exec(bContext *C, wmOperator *op)
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
- txt_insert_buf(text, buf);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+ txt_insert_buf(text, utxt, buf);
text_update_edited(text);
MEM_freeN(buf);
@@ -756,7 +757,10 @@ void TEXT_OT_paste(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_paste_exec;
ot->poll = text_edit_poll;
-
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
/* properties */
RNA_def_boolean(ot->srna, "selection", 0, "Selection", "Paste text selected elsewhere rather than copied (X11 only)");
}
@@ -766,9 +770,11 @@ void TEXT_OT_paste(wmOperatorType *ot)
static int text_duplicate_line_exec(bContext *C, wmOperator *UNUSED(op))
{
Text *text = CTX_data_edit_text(C);
-
- txt_duplicate_line(text);
-
+
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
+ txt_duplicate_line(text, utxt);
+
WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
/* run the script while editing, evil but useful */
@@ -785,10 +791,13 @@ void TEXT_OT_duplicate_line(wmOperatorType *ot)
ot->name = "Duplicate Line";
ot->idname = "TEXT_OT_duplicate_line";
ot->description = "Duplicate the current line";
-
+
/* api callbacks */
ot->exec = text_duplicate_line_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* copy operator *********************/
@@ -838,7 +847,9 @@ static int text_cut_exec(bContext *C, wmOperator *UNUSED(op))
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
txt_copy_clipboard(text);
- txt_delete_selected(text);
+
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+ txt_delete_selected(text, utxt);
text_update_cursor_moved(C);
WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
@@ -860,6 +871,9 @@ void TEXT_OT_cut(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_cut_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* indent operator *********************/
@@ -870,12 +884,15 @@ static int text_indent_exec(bContext *C, wmOperator *UNUSED(op))
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
if (txt_has_sel(text)) {
txt_order_cursors(text, false);
- txt_indent(text);
+ txt_indent(text, utxt);
+ }
+ else {
+ txt_add_char(text, utxt, '\t');
}
- else
- txt_add_char(text, '\t');
text_update_edited(text);
@@ -895,6 +912,9 @@ void TEXT_OT_indent(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_indent_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* unindent operator *********************/
@@ -905,8 +925,10 @@ static int text_unindent_exec(bContext *C, wmOperator *UNUSED(op))
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
txt_order_cursors(text, false);
- txt_unindent(text);
+ txt_unindent(text, utxt);
text_update_edited(text);
@@ -926,6 +948,9 @@ void TEXT_OT_unindent(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_unindent_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* line break operator *********************/
@@ -941,14 +966,15 @@ static int text_line_break_exec(bContext *C, wmOperator *UNUSED(op))
// double check tabs/spaces before splitting the line
curts = txt_setcurr_tab_spaces(text, space);
- txt_split_curline(text);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+ txt_split_curline(text, utxt);
for (a = 0; a < curts; a++) {
if (text->flags & TXT_TABSTOSPACES) {
- txt_add_char(text, ' ');
+ txt_add_char(text, utxt, ' ');
}
else {
- txt_add_char(text, '\t');
+ txt_add_char(text, utxt, '\t');
}
}
@@ -961,7 +987,7 @@ static int text_line_break_exec(bContext *C, wmOperator *UNUSED(op))
text_update_cursor_moved(C);
WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
- return OPERATOR_CANCELLED;
+ return OPERATOR_FINISHED;
}
void TEXT_OT_line_break(wmOperatorType *ot)
@@ -970,10 +996,13 @@ void TEXT_OT_line_break(wmOperatorType *ot)
ot->name = "Line Break";
ot->idname = "TEXT_OT_line_break";
ot->description = "Insert line break at cursor position";
-
+
/* api callbacks */
ot->exec = text_line_break_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* comment operator *********************/
@@ -985,8 +1014,10 @@ static int text_comment_exec(bContext *C, wmOperator *UNUSED(op))
if (txt_has_sel(text)) {
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
txt_order_cursors(text, false);
- txt_comment(text);
+ txt_comment(text, utxt);
text_update_edited(text);
text_update_cursor_moved(C);
@@ -1003,10 +1034,13 @@ void TEXT_OT_comment(wmOperatorType *ot)
ot->name = "Comment";
ot->idname = "TEXT_OT_comment";
ot->description = "Convert selected text to comment";
-
+
/* api callbacks */
ot->exec = text_comment_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* uncomment operator *********************/
@@ -1018,8 +1052,10 @@ static int text_uncomment_exec(bContext *C, wmOperator *UNUSED(op))
if (txt_has_sel(text)) {
text_drawcache_tag_update(CTX_wm_space_text(C), 0);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
txt_order_cursors(text, false);
- txt_uncomment(text);
+ txt_uncomment(text, utxt);
text_update_edited(text);
text_update_cursor_moved(C);
@@ -1041,12 +1077,15 @@ void TEXT_OT_uncomment(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_uncomment_exec;
ot->poll = text_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* convert whitespace operator *********************/
enum { TO_SPACES, TO_TABS };
-static EnumPropertyItem whitespace_type_items[] = {
+static const EnumPropertyItem whitespace_type_items[] = {
{TO_SPACES, "SPACES", 0, "To Spaces", NULL},
{TO_TABS, "TABS", 0, "To Tabs", NULL},
{0, NULL, 0, NULL, NULL}};
@@ -1174,6 +1213,9 @@ void TEXT_OT_convert_whitespace(wmOperatorType *ot)
ot->exec = text_convert_whitespace_exec;
ot->poll = text_edit_poll;
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
/* properties */
RNA_def_enum(ot->srna, "type", whitespace_type_items, TO_SPACES, "Type", "Type of whitespace to convert to");
}
@@ -1265,8 +1307,10 @@ static int move_lines_exec(bContext *C, wmOperator *op)
{
Text *text = CTX_data_edit_text(C);
const int direction = RNA_enum_get(op->ptr, "direction");
-
- txt_move_lines(text, direction);
+
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
+ txt_move_lines(text, utxt, direction);
text_update_cursor_moved(C);
WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
@@ -1280,7 +1324,7 @@ static int move_lines_exec(bContext *C, wmOperator *op)
void TEXT_OT_move_lines(wmOperatorType *ot)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{TXT_MOVE_LINE_UP, "UP", 0, "Up", ""},
{TXT_MOVE_LINE_DOWN, "DOWN", 0, "Down", ""},
{0, NULL, 0, NULL, NULL}
@@ -1295,13 +1339,16 @@ void TEXT_OT_move_lines(wmOperatorType *ot)
ot->exec = move_lines_exec;
ot->poll = text_edit_poll;
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
/* properties */
RNA_def_enum(ot->srna, "direction", direction_items, 1, "Direction", "");
}
/************************ move operator ************************/
-static EnumPropertyItem move_type_items[] = {
+static const EnumPropertyItem move_type_items[] = {
{LINE_BEGIN, "LINE_BEGIN", 0, "Line Begin", ""},
{LINE_END, "LINE_END", 0, "Line End", ""},
{FILE_TOP, "FILE_TOP", 0, "File Top", ""},
@@ -1923,7 +1970,7 @@ void TEXT_OT_jump(wmOperatorType *ot)
/******************* delete operator **********************/
-static EnumPropertyItem delete_type_items[] = {
+static const EnumPropertyItem delete_type_items[] = {
{DEL_NEXT_CHAR, "NEXT_CHARACTER", 0, "Next Character", ""},
{DEL_PREV_CHAR, "PREVIOUS_CHARACTER", 0, "Previous Character", ""},
{DEL_NEXT_WORD, "NEXT_WORD", 0, "Next Word", ""},
@@ -1936,6 +1983,7 @@ static int text_delete_exec(bContext *C, wmOperator *op)
Text *text = CTX_data_edit_text(C);
int type = RNA_enum_get(op->ptr, "type");
+
text_drawcache_tag_update(st, 0);
/* behavior could be changed here,
@@ -1945,11 +1993,13 @@ static int text_delete_exec(bContext *C, wmOperator *op)
else if (type == DEL_NEXT_WORD) type = DEL_NEXT_CHAR;
}
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
if (type == DEL_PREV_WORD) {
if (txt_cursor_is_line_start(text)) {
- txt_backspace_char(text);
+ txt_backspace_char(text, utxt);
}
- txt_backspace_word(text);
+ txt_backspace_word(text, utxt);
}
else if (type == DEL_PREV_CHAR) {
@@ -1965,13 +2015,13 @@ static int text_delete_exec(bContext *C, wmOperator *op)
}
}
- txt_backspace_char(text);
+ txt_backspace_char(text, utxt);
}
else if (type == DEL_NEXT_WORD) {
if (txt_cursor_is_line_end(text)) {
- txt_delete_char(text);
+ txt_delete_char(text, utxt);
}
- txt_delete_word(text);
+ txt_delete_word(text, utxt);
}
else if (type == DEL_NEXT_CHAR) {
@@ -1987,7 +2037,7 @@ static int text_delete_exec(bContext *C, wmOperator *op)
}
}
- txt_delete_char(text);
+ txt_delete_char(text, utxt);
}
text_update_line_edited(text->curl);
@@ -2013,6 +2063,9 @@ void TEXT_OT_delete(wmOperatorType *ot)
ot->exec = text_delete_exec;
ot->poll = text_edit_poll;
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
/* properties */
RNA_def_enum(ot->srna, "type", delete_type_items, DEL_NEXT_CHAR, "Type", "Which part of the text to delete");
}
@@ -2840,16 +2893,18 @@ static int text_insert_exec(bContext *C, wmOperator *op)
str = RNA_string_get_alloc(op->ptr, "text", NULL, 0);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+
if (st && st->overwrite) {
while (str[i]) {
code = BLI_str_utf8_as_unicode_step(str, &i);
- done |= txt_replace_char(text, code);
+ done |= txt_replace_char(text, utxt, code);
}
}
else {
while (str[i]) {
code = BLI_str_utf8_as_unicode_step(str, &i);
- done |= txt_add_char(text, code);
+ done |= txt_add_char(text, utxt, code);
}
}
@@ -2919,6 +2974,9 @@ void TEXT_OT_insert(wmOperatorType *ot)
ot->invoke = text_insert_invoke;
ot->poll = text_edit_poll;
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
+
/* properties */
prop = RNA_def_string(ot->srna, "text", NULL, 0, "Text", "Text to insert at the cursor position");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
@@ -2955,7 +3013,8 @@ static int text_find_and_replace(bContext *C, wmOperator *op, short mode)
if (found) {
if (mode == TEXT_REPLACE) {
- txt_insert_buf(text, st->replacestr);
+ TextUndoBuf *utxt = ED_text_undo_push_init(C);
+ txt_insert_buf(text, utxt, st->replacestr);
if (text->curl && text->curl->format) {
MEM_freeN(text->curl->format);
text->curl->format = NULL;
@@ -3024,6 +3083,9 @@ void TEXT_OT_replace(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_replace_exec;
ot->poll = text_space_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/******************* find set selected *********************/
@@ -3081,12 +3143,15 @@ void TEXT_OT_replace_set_selected(wmOperatorType *ot)
/* api callbacks */
ot->exec = text_replace_set_selected_exec;
ot->poll = text_space_edit_poll;
+
+ /* flags */
+ ot->flag = OPTYPE_UNDO;
}
/****************** resolve conflict operator ******************/
enum { RESOLVE_IGNORE, RESOLVE_RELOAD, RESOLVE_SAVE, RESOLVE_MAKE_INTERNAL };
-static EnumPropertyItem resolution_items[] = {
+static const EnumPropertyItem resolution_items[] = {
{RESOLVE_IGNORE, "IGNORE", 0, "Ignore", ""},
{RESOLVE_RELOAD, "RELOAD", 0, "Reload", ""},
{RESOLVE_SAVE, "SAVE", 0, "Save", ""},
@@ -3201,26 +3266,3 @@ void TEXT_OT_to_3d_object(wmOperatorType *ot)
/* properties */
RNA_def_boolean(ot->srna, "split_lines", 0, "Split Lines", "Create one object per line in the text");
}
-
-
-/************************ undo ******************************/
-
-void ED_text_undo_step(bContext *C, int step)
-{
- Text *text = CTX_data_edit_text(C);
-
- if (!text)
- return;
-
- if (step == 1)
- txt_do_undo(text);
- else if (step == -1)
- txt_do_redo(text);
-
- text_update_edited(text);
-
- text_update_cursor_moved(C);
- text_drawcache_tag_update(CTX_wm_space_text(C), 1);
- WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
-}
-
diff --git a/source/blender/editors/space_text/text_undo.c b/source/blender/editors/space_text/text_undo.c
new file mode 100644
index 00000000000..729522cc8f4
--- /dev/null
+++ b/source/blender/editors/space_text/text_undo.c
@@ -0,0 +1,185 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/space_text/text_undo.c
+ * \ingroup sptext
+ */
+
+#include <string.h>
+#include <errno.h>
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_text_types.h"
+
+#include "BLI_listbase.h"
+#include "BLI_array_utils.h"
+
+#include "BLT_translation.h"
+
+#include "PIL_time.h"
+
+#include "BKE_context.h"
+#include "BKE_library.h"
+#include "BKE_report.h"
+#include "BKE_text.h"
+#include "BKE_undo_system.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_text.h"
+#include "ED_curve.h"
+#include "ED_screen.h"
+#include "ED_undo.h"
+
+#include "UI_interface.h"
+#include "UI_resources.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+
+#include "text_intern.h"
+#include "text_format.h"
+
+/* TODO(campbell): undo_system: move text undo out of text block. */
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct TextUndoStep {
+ UndoStep step;
+ UndoRefID_Text text_ref;
+ TextUndoBuf data;
+} TextUndoStep;
+
+static bool text_undosys_poll(bContext *C)
+{
+ Text *text = CTX_data_edit_text(C);
+ if (text == NULL) {
+ return false;
+ }
+ if (ID_IS_LINKED(text)) {
+ return false;
+ }
+ return true;
+}
+
+static void text_undosys_step_encode_init(struct bContext *C, UndoStep *us_p)
+{
+ TextUndoStep *us = (TextUndoStep *)us_p;
+ BLI_assert(BLI_array_is_zeroed(&us->data, 1));
+
+ UNUSED_VARS(C);
+ /* XXX, use to set the undo type only. */
+
+ us->data.buf = NULL;
+ us->data.len = 0;
+ us->data.pos = -1;
+}
+
+static bool text_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ TextUndoStep *us = (TextUndoStep *)us_p;
+
+ Text *text = CTX_data_edit_text(C);
+
+ /* No undo data was generated. Hint, use global undo here. */
+ if ((us->data.pos == -1) || (us->data.buf == NULL)) {
+ return false;
+ }
+
+ us->text_ref.ptr = text;
+
+ us->step.data_size = us->data.len;
+
+ return true;
+}
+
+static void text_undosys_step_decode(struct bContext *C, UndoStep *us_p, int dir)
+{
+ TextUndoStep *us = (TextUndoStep *)us_p;
+ Text *text = us->text_ref.ptr;
+
+ if (dir < 0) {
+ TextUndoBuf data = us->data;
+ txt_do_undo(text, &data);
+ }
+ else {
+ TextUndoBuf data = us->data;
+ data.pos = -1;
+ txt_do_redo(text, &data);
+ }
+
+ text_update_edited(text);
+ text_update_cursor_moved(C);
+ text_drawcache_tag_update(CTX_wm_space_text(C), 1);
+ WM_event_add_notifier(C, NC_TEXT | NA_EDITED, text);
+}
+
+static void text_undosys_step_free(UndoStep *us_p)
+{
+ TextUndoStep *us = (TextUndoStep *)us_p;
+ MEM_SAFE_FREE(us->data.buf);
+}
+
+static void text_undosys_foreach_ID_ref(
+ UndoStep *us_p, UndoTypeForEachIDRefFn foreach_ID_ref_fn, void *user_data)
+{
+ TextUndoStep *us = (TextUndoStep *)us_p;
+ foreach_ID_ref_fn(user_data, ((UndoRefID *)&us->text_ref));
+}
+
+/* Export for ED_undo_sys. */
+
+void ED_text_undosys_type(UndoType *ut)
+{
+ ut->name = "Text";
+ ut->poll = text_undosys_poll;
+ ut->step_encode_init = text_undosys_step_encode_init;
+ ut->step_encode = text_undosys_step_encode;
+ ut->step_decode = text_undosys_step_decode;
+ ut->step_free = text_undosys_step_free;
+
+ ut->step_foreach_ID_ref = text_undosys_foreach_ID_ref;
+
+ ut->mode = BKE_UNDOTYPE_MODE_ACCUMULATE;
+ ut->use_context = false;
+
+ ut->step_size = sizeof(TextUndoStep);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+/* Use operator system to finish the undo step. */
+TextUndoBuf *ED_text_undo_push_init(bContext *C)
+{
+ UndoStack *ustack = ED_undo_stack_get();
+ UndoStep *us_p = BKE_undosys_step_push_init_with_type(ustack, C, NULL, BKE_UNDOSYS_TYPE_TEXT);
+ TextUndoStep *us = (TextUndoStep *)us_p;
+ return &us->data;
+}
+
+/** \} */
diff --git a/source/blender/editors/space_time/space_time.c b/source/blender/editors/space_time/space_time.c
index 15eb154c757..f29d2b30ffe 100644
--- a/source/blender/editors/space_time/space_time.c
+++ b/source/blender/editors/space_time/space_time.c
@@ -329,6 +329,8 @@ static void time_draw_idblock_keyframes(View2D *v2d, ID *id, short onlysel)
case ID_CF:
cachefile_to_keylist(&ads, (CacheFile *)id, &keys, NULL);
break;
+ default:
+ break;
}
/* build linked-list for searching */
diff --git a/source/blender/editors/space_view3d/CMakeLists.txt b/source/blender/editors/space_view3d/CMakeLists.txt
index a5c60248bf1..e25a9c04f15 100644
--- a/source/blender/editors/space_view3d/CMakeLists.txt
+++ b/source/blender/editors/space_view3d/CMakeLists.txt
@@ -63,6 +63,7 @@ set(SRC
view3d_select.c
view3d_snap.c
view3d_toolbar.c
+ view3d_utils.c
view3d_view.c
view3d_intern.h
diff --git a/source/blender/editors/space_view3d/drawanimviz.c b/source/blender/editors/space_view3d/drawanimviz.c
index f0e65f84205..a99ac0d46a5 100644
--- a/source/blender/editors/space_view3d/drawanimviz.c
+++ b/source/blender/editors/space_view3d/drawanimviz.c
@@ -76,15 +76,15 @@ void draw_motion_paths_init(View3D *v3d, ARegion *ar)
}
/* set color
-* - more intense for active/selected bones, less intense for unselected bones
-* - black for before current frame, green for current frame, blue for after current frame
-* - intensity decreases as distance from current frame increases
-*
-* If the user select custom color, the color is replaced for the color selected in UI panel
-* - 75% Darker color is used for previous frames
-* - 50% Darker color for current frame
-* - User selected color for next frames
-*/
+ * - more intense for active/selected bones, less intense for unselected bones
+ * - black for before current frame, green for current frame, blue for after current frame
+ * - intensity decreases as distance from current frame increases
+ *
+ * If the user select custom color, the color is replaced for the color selected in UI panel
+ * - 75% Darker color is used for previous frames
+ * - 50% Darker color for current frame
+ * - User selected color for next frames
+ */
static void set_motion_path_color(Scene *scene, bMotionPath *mpath, int i, short sel, int sfra, int efra,
float prev_color[3], float frame_color[3], float next_color[3])
{
diff --git a/source/blender/editors/space_view3d/drawarmature.c b/source/blender/editors/space_view3d/drawarmature.c
index 149144d969a..5208013b6fe 100644
--- a/source/blender/editors/space_view3d/drawarmature.c
+++ b/source/blender/editors/space_view3d/drawarmature.c
@@ -1265,7 +1265,7 @@ static void draw_b_bone(const short dt, int armflag, int boneflag, short constfl
else {
/* wire */
if (armflag & ARM_POSEMODE) {
- if (constflag) {
+ if (constflag && ((G.f & G_PICKSEL) == 0)) {
/* set constraint colors */
if (set_pchan_glColor(PCHAN_COLOR_CONSTS, boneflag, constflag)) {
glEnable(GL_BLEND);
@@ -1406,7 +1406,7 @@ static void draw_bone(const short dt, int armflag, int boneflag, short constflag
set_ebone_glColor(boneflag);
}
else if (armflag & ARM_POSEMODE) {
- if (constflag) {
+ if (constflag && ((G.f & G_PICKSEL) == 0)) {
/* draw constraint colors */
if (set_pchan_glColor(PCHAN_COLOR_CONSTS, boneflag, constflag)) {
glEnable(GL_BLEND);
@@ -1903,6 +1903,11 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
}
}
+ /* custom bone may draw outline double-width */
+ if (arm->flag & ARM_POSEMODE) {
+ glLineWidth(1.0f);
+ }
+
/* draw custom bone shapes as wireframes */
if (!(arm->flag & ARM_NO_CUSTOM) &&
(draw_wire || (dt <= OB_WIRE)) )
@@ -1968,11 +1973,6 @@ static void draw_pose_bones(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
index = -1;
}
}
-
- /* custom bone may draw outline double-width */
- if (arm->flag & ARM_POSEMODE) {
- glLineWidth(1.0f);
- }
/* wire draw over solid only in posemode */
if ((dt <= OB_WIRE) || (arm->flag & ARM_POSEMODE) || ELEM(arm->drawtype, ARM_LINE, ARM_WIRE)) {
@@ -2360,7 +2360,6 @@ static void draw_ebones(View3D *v3d, ARegion *ar, Object *ob, const short dt)
/* Draw name */
if (arm->flag & ARM_DRAWNAMES) {
mid_v3_v3v3(vec, eBone->head, eBone->tail);
- glRasterPos3fv(vec);
view3d_cached_text_draw_add(vec, eBone->name, strlen(eBone->name), 10, 0, col);
}
/* Draw additional axes */
diff --git a/source/blender/editors/space_view3d/drawmesh.c b/source/blender/editors/space_view3d/drawmesh.c
index ecbfd5c7c85..b6bcc592cc8 100644
--- a/source/blender/editors/space_view3d/drawmesh.c
+++ b/source/blender/editors/space_view3d/drawmesh.c
@@ -678,6 +678,7 @@ static void update_tface_color_layer(DerivedMesh *dm, bool use_mcol)
finalCol[loop_index].r = 255;
finalCol[loop_index].g = 0;
finalCol[loop_index].b = 255;
+ finalCol[loop_index].a = 255;
}
copy_mode = COPY_PREV;
}
@@ -685,6 +686,7 @@ static void update_tface_color_layer(DerivedMesh *dm, bool use_mcol)
int loop_index = mp->loopstart;
for (j = 0; j < mp->totloop; j++, loop_index++) {
copy_v3_v3_uchar(&finalCol[loop_index].r, Gtexdraw.obcol);
+ finalCol[loop_index].a = 255;
}
copy_mode = COPY_PREV;
}
@@ -1113,6 +1115,7 @@ static void tex_mat_set_texture_cb(void *userData, int mat_nr, void *attribs)
gattribs->layer[0].type = CD_MTFACE;
gattribs->layer[0].name[0] = '\0';
gattribs->layer[0].gltexco = 1;
+ gattribs->layer[0].glinfoindoex = -1;
gattribs->totlayer = 1;
/* bind material */
@@ -1297,6 +1300,13 @@ void draw_mesh_paint_vcolor_faces(DerivedMesh *dm, const bool use_light,
flags |= DM_DRAW_NEED_NORMALS;
}
+ /* Don't show alpha in wire mode. */
+ const bool show_alpha = use_light;
+ if (show_alpha) {
+ glEnable(GL_BLEND);
+ glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
+ }
+
if (me->mloopcol) {
dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data,
DM_DRAW_USE_COLORS | flags);
@@ -1306,6 +1316,10 @@ void draw_mesh_paint_vcolor_faces(DerivedMesh *dm, const bool use_light,
dm->drawMappedFaces(dm, facemask_cb, setMaterial, NULL, user_data, flags);
}
+ if (show_alpha) {
+ glDisable(GL_BLEND);
+ }
+
if (use_light) {
draw_mesh_paint_light_end();
}
diff --git a/source/blender/editors/space_view3d/drawobject.c b/source/blender/editors/space_view3d/drawobject.c
index 90d33dc5995..c3823627009 100644
--- a/source/blender/editors/space_view3d/drawobject.c
+++ b/source/blender/editors/space_view3d/drawobject.c
@@ -631,7 +631,7 @@ void drawaxes(const float viewmat_local[4][4], float size, char drawtype)
/* Function to draw an Image on an empty Object */
-static void draw_empty_image(Object *ob, const short dflag, const unsigned char ob_wire_col[4], StereoViews sview)
+static void draw_empty_image(Object *ob, const short dflag, const unsigned char ob_wire_col[4], eStereoViews sview)
{
Image *ima = ob->data;
ImBuf *ibuf;
@@ -867,7 +867,7 @@ void view3d_cached_text_draw_add(const float co[3],
memcpy(vos->str, str, alloc_len);
}
-void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write, float mat[4][4])
+void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write)
{
RegionView3D *rv3d = ar->regiondata;
ViewCachedString *vos;
@@ -877,9 +877,6 @@ void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write, flo
/* project first and test */
for (vos = g_v3d_strings[g_v3d_string_level]; vos; vos = vos->next) {
- if (mat && !(vos->flag & V3D_CACHE_TEXT_WORLDSPACE))
- mul_m4_v3(mat, vos->vec);
-
if (ED_view3d_project_short_ex(ar,
(vos->flag & V3D_CACHE_TEXT_GLOBALSPACE) ? rv3d->persmat : rv3d->persmatob,
(vos->flag & V3D_CACHE_TEXT_LOCALCLIP) != 0,
@@ -929,14 +926,12 @@ void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write, flo
col_pack_prev = vos->col.pack;
}
- ((vos->flag & V3D_CACHE_TEXT_ASCII) ?
- BLF_draw_default_ascii :
- BLF_draw_default
- )((float)(vos->sco[0] + vos->xoffs),
- (float)(vos->sco[1]),
- (depth_write) ? 0.0f : 2.0f,
- vos->str,
- vos->str_len);
+ ((vos->flag & V3D_CACHE_TEXT_ASCII) ? BLF_draw_default_ascii : BLF_draw_default)(
+ (float)(vos->sco[0] + vos->xoffs),
+ (float)(vos->sco[1]),
+ (depth_write) ? 0.0f : 2.0f,
+ vos->str,
+ vos->str_len);
}
}
@@ -987,7 +982,7 @@ static void drawcube_size(float size)
{ size, size, size}
};
- const GLubyte indices[24] = {0,1,1,3,3,2,2,0,0,4,4,5,5,7,7,6,6,4,1,5,3,7,2,6};
+ const GLubyte indices[24] = {0, 1, 1, 3, 3, 2, 2, 0, 0, 4, 4, 5, 5, 7, 7, 6, 6, 4, 1, 5, 3, 7, 2, 6};
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, pos);
@@ -1824,16 +1819,16 @@ static void drawcamera_volume(float near_plane[4][3], float far_plane[4][3], con
glBegin(mode);
glVertex3fv(near_plane[2]);
- glVertex3fv(near_plane[1]);
- glVertex3fv(far_plane[1]);
glVertex3fv(far_plane[2]);
+ glVertex3fv(far_plane[3]);
+ glVertex3fv(near_plane[3]);
glEnd();
glBegin(mode);
- glVertex3fv(far_plane[0]);
- glVertex3fv(near_plane[0]);
- glVertex3fv(near_plane[3]);
glVertex3fv(far_plane[3]);
+ glVertex3fv(near_plane[3]);
+ glVertex3fv(near_plane[0]);
+ glVertex3fv(far_plane[0]);
glEnd();
}
@@ -4212,7 +4207,6 @@ static void draw_mesh_fancy(Scene *scene, ARegion *ar, View3D *v3d, RegionView3D
if (is_obact && BKE_paint_select_vert_test(ob)) {
const bool use_depth = (v3d->flag & V3D_ZBUF_SELECT) != 0;
- glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(UI_GetThemeValuef(TH_VERTEX_SIZE));
if (!use_depth) glDisable(GL_DEPTH_TEST);
@@ -5050,6 +5044,8 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
curvemapping_changed_all(psys->part->clumpcurve);
if ((psys->part->child_flag & PART_CHILD_USE_ROUGH_CURVE) && psys->part->roughcurve)
curvemapping_changed_all(psys->part->roughcurve);
+ if ((psys->part->child_flag & PART_CHILD_USE_TWIST_CURVE) && psys->part->twistcurve)
+ curvemapping_changed_all(psys->part->twistcurve);
/* 2. */
sim.scene = scene;
@@ -5124,7 +5120,7 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
copy_m4_m4(imat, rv3d->viewinv);
normalize_v3(imat[0]);
normalize_v3(imat[1]);
- /* fall-through */
+ ATTR_FALLTHROUGH;
case PART_DRAW_CROSS:
case PART_DRAW_AXIS:
/* lets calculate the scale: */
@@ -5194,46 +5190,46 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
/* 4. */
if (draw_as && ELEM(draw_as, PART_DRAW_PATH, PART_DRAW_CIRC) == 0) {
- int tot_vec_size = (totpart + totchild) * 3 * sizeof(float);
+ int partsize = 3 * sizeof(float);
int create_ndata = 0;
if (!pdd)
pdd = psys->pdd = MEM_callocN(sizeof(ParticleDrawData), "ParticleDrawData");
if (part->draw_as == PART_DRAW_REND && part->trail_count > 1) {
- tot_vec_size *= part->trail_count;
+ partsize *= part->trail_count;
psys_make_temp_pointcache(ob, psys);
}
switch (draw_as) {
case PART_DRAW_AXIS:
case PART_DRAW_CROSS:
- tot_vec_size *= 6;
+ partsize *= 6;
if (draw_as != PART_DRAW_CROSS)
create_cdata = 1;
break;
case PART_DRAW_LINE:
- tot_vec_size *= 2;
+ partsize *= 2;
break;
case PART_DRAW_BB:
- tot_vec_size *= 4;
+ partsize *= 4;
create_ndata = 1;
break;
}
- if (pdd->tot_vec_size != tot_vec_size)
+ if (pdd->totpart != totpart + totchild || pdd->partsize != partsize)
psys_free_pdd(psys);
if (!pdd->vdata)
- pdd->vdata = MEM_callocN(tot_vec_size, "particle_vdata");
+ pdd->vdata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_vdata");
if (create_cdata && !pdd->cdata)
- pdd->cdata = MEM_callocN(tot_vec_size, "particle_cdata");
+ pdd->cdata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_cdata");
if (create_ndata && !pdd->ndata)
- pdd->ndata = MEM_callocN(tot_vec_size, "particle_ndata");
+ pdd->ndata = MEM_calloc_arrayN(totpart + totchild, partsize, "particle_ndata");
if (part->draw & PART_DRAW_VEL && draw_as != PART_DRAW_LINE) {
if (!pdd->vedata)
- pdd->vedata = MEM_callocN(2 * (totpart + totchild) * 3 * sizeof(float), "particle_vedata");
+ pdd->vedata = MEM_calloc_arrayN(totpart + totchild, 2 * 3 * sizeof(float), "particle_vedata");
need_v = 1;
}
@@ -5247,7 +5243,8 @@ static void draw_new_particle_system(Scene *scene, View3D *v3d, RegionView3D *rv
pdd->ved = pdd->vedata;
pdd->cd = pdd->cdata;
pdd->nd = pdd->ndata;
- pdd->tot_vec_size = tot_vec_size;
+ pdd->totpart = totpart + totchild;
+ pdd->partsize = partsize;
}
else if (psys->pdd) {
psys_free_pdd(psys);
@@ -5768,7 +5765,7 @@ static void draw_ptcache_edit(Scene *scene, View3D *v3d, PTCacheEdit *edit)
totkeys = (*edit->pathcache)->segments + 1;
glEnable(GL_BLEND);
- pathcol = MEM_callocN(totkeys * 4 * sizeof(float), "particle path color data");
+ pathcol = MEM_calloc_arrayN(totkeys, 4 * sizeof(float), "particle path color data");
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
@@ -5821,8 +5818,8 @@ static void draw_ptcache_edit(Scene *scene, View3D *v3d, PTCacheEdit *edit)
if (totkeys_visible) {
if (edit->points && !(edit->points->keys->flag & PEK_USE_WCO))
- pd = pdata = MEM_callocN(totkeys_visible * 3 * sizeof(float), "particle edit point data");
- cd = cdata = MEM_callocN(totkeys_visible * (timed ? 4 : 3) * sizeof(float), "particle edit color data");
+ pd = pdata = MEM_calloc_arrayN(totkeys_visible, 3 * sizeof(float), "particle edit point data");
+ cd = cdata = MEM_calloc_arrayN(totkeys_visible, (timed ? 4 : 3) * sizeof(float), "particle edit color data");
}
for (i = 0, point = edit->points; i < totpoint; i++, point++) {
@@ -6420,19 +6417,16 @@ static void draw_editnurb(
vec_a[0] = fac;
vec_a[1] = 0.0f;
vec_a[2] = 0.0f;
-
- vec_b[0] = -fac;
- vec_b[1] = 0.0f;
- vec_b[2] = 0.0f;
mul_qt_v3(bevp->quat, vec_a);
- mul_qt_v3(bevp->quat, vec_b);
+ madd_v3_v3fl(vec_a, bevp->dir, -fac);
+
+ reflect_v3_v3v3(vec_b, vec_a, bevp->dir);
+ negate_v3(vec_b);
+
add_v3_v3(vec_a, bevp->vec);
add_v3_v3(vec_b, bevp->vec);
- madd_v3_v3fl(vec_a, bevp->dir, -fac);
- madd_v3_v3fl(vec_b, bevp->dir, -fac);
-
glBegin(GL_LINE_STRIP);
glVertex3fv(vec_a);
glVertex3fv(bevp->vec);
@@ -6476,7 +6470,6 @@ static void draw_editfont(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *b
Curve *cu = ob->data;
EditFont *ef = cu->editfont;
float vec1[3], vec2[3];
- int selstart, selend;
draw_editfont_textcurs(rv3d, ef->textcurs);
@@ -6529,17 +6522,16 @@ static void draw_editfont(Scene *scene, View3D *v3d, RegionView3D *rv3d, Base *b
setlinestyle(0);
- if (BKE_vfont_select_get(ob, &selstart, &selend) && ef->selboxes) {
- const int seltot = selend - selstart;
+ if (ef->selboxes && ef->selboxes_len) {
float selboxw;
cpack(0xffffff);
set_inverted_drawing(1);
- for (int i = 0; i <= seltot; i++) {
+ for (int i = 0; i < ef->selboxes_len; i++) {
EditFontSelBox *sb = &ef->selboxes[i];
float tvec[3];
- if (i != seltot) {
+ if (i + 1 != ef->selboxes_len) {
if (ef->selboxes[i + 1].y == sb->y)
selboxw = ef->selboxes[i + 1].x - sb->x;
else
@@ -7016,11 +7008,11 @@ static void draw_box(const float vec[8][3], bool solid)
glVertexPointer(3, GL_FLOAT, 0, vec);
if (solid) {
- const GLubyte indices[24] = {0,1,2,3,7,6,5,4,4,5,1,0,3,2,6,7,3,7,4,0,1,5,6,2};
+ const GLubyte indices[24] = {0, 1, 2, 3, 7, 6, 5, 4, 4, 5, 1, 0, 3, 2, 6, 7, 3, 7, 4, 0, 1, 5, 6, 2};
glDrawRangeElements(GL_QUADS, 0, 7, 24, GL_UNSIGNED_BYTE, indices);
}
else {
- const GLubyte indices[24] = {0,1,1,2,2,3,3,0,0,4,4,5,5,6,6,7,7,4,1,5,2,6,3,7};
+ const GLubyte indices[24] = {0, 1, 1, 2, 2, 3, 3, 0, 0, 4, 4, 5, 5, 6, 6, 7, 7, 4, 1, 5, 2, 6, 3, 7};
glDrawRangeElements(GL_LINES, 0, 7, 24, GL_UNSIGNED_BYTE, indices);
}
@@ -7171,8 +7163,9 @@ static void drawtexspace(Object *ob)
}
/* draws wire outline */
-static void drawObjectSelect(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
- const unsigned char ob_wire_col[4])
+static void draw_object_selected_outline(
+ Scene *scene, View3D *v3d, ARegion *ar, Base *base,
+ const unsigned char ob_wire_col[4])
{
RegionView3D *rv3d = ar->regiondata;
Object *ob = base->object;
@@ -7344,7 +7337,7 @@ static void draw_object_wire_color(Scene *scene, Base *base, unsigned char r_ob_
}
else {
/* Sets the 'colindex' */
- if (ID_IS_LINKED_DATABLOCK(ob)) {
+ if (ID_IS_LINKED(ob)) {
colindex = (base->flag & (SELECT + BA_WAS_SEL)) ? 2 : 1;
}
/* Sets the 'theme_id' or fallback to wire */
@@ -7355,7 +7348,7 @@ static void draw_object_wire_color(Scene *scene, Base *base, unsigned char r_ob_
theme_id = TH_GROUP_ACTIVE;
if (scene->basact != base) {
- theme_shade = -16;
+ theme_shade = -32;
}
}
else {
@@ -7645,7 +7638,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
if ((v3d->flag & V3D_SELECT_OUTLINE) && !render_override && ob->type != OB_MESH) {
if (dt > OB_WIRE && (ob->mode & OB_MODE_EDIT) == 0 && (dflag & DRAW_SCENESET) == 0) {
if (!(ob->dtx & OB_DRAWWIRE) && (ob->flag & SELECT) && !(dflag & (DRAW_PICKING | DRAW_CONSTCOLOR))) {
- drawObjectSelect(scene, v3d, ar, base, ob_wire_col);
+ draw_object_selected_outline(scene, v3d, ar, base, ob_wire_col);
}
}
}
@@ -7831,7 +7824,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
draw_new_particle_system(scene, v3d, rv3d, base, psys, dt, dflag);
}
invert_m4_m4(ob->imat, ob->obmat);
- view3d_cached_text_draw_end(v3d, ar, 0, NULL);
+ view3d_cached_text_draw_end(v3d, ar, 0);
glMultMatrixf(ob->obmat);
@@ -8006,7 +7999,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
/* return warning, this is cached text draw */
invert_m4_m4(ob->imat, ob->obmat);
- view3d_cached_text_draw_end(v3d, ar, 1, NULL);
+ view3d_cached_text_draw_end(v3d, ar, 1);
/* return warning, clear temp flag */
v3d->flag2 &= ~V3D_SHOW_SOLID_MATCAP;
@@ -8054,7 +8047,7 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
!(G.f & G_RENDER_OGL))
{
/* check > 0 otherwise grease pencil can draw into the circle select which is annoying. */
- drawcentercircle(v3d, rv3d, ob->obmat[3], do_draw_center, ID_IS_LINKED_DATABLOCK(ob) || ob->id.us > 1);
+ drawcentercircle(v3d, rv3d, ob->obmat[3], do_draw_center, ID_IS_LINKED(ob) || ob->id.us > 1);
}
}
}
@@ -8174,6 +8167,50 @@ void draw_object(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short
ED_view3d_clear_mats_rv3d(rv3d);
}
+
+/**
+ * Drawing for selection picking,
+ * caller must have called 'GPU_select_load_id(base->selcode)' first.
+ */
+void draw_object_select(Scene *scene, ARegion *ar, View3D *v3d, Base *base, const short dflag)
+{
+ BLI_assert(dflag & DRAW_PICKING && dflag & DRAW_CONSTCOLOR);
+ draw_object(scene, ar, v3d, base, dflag);
+
+ /* we draw duplicators for selection too */
+ if ((base->object->transflag & OB_DUPLI)) {
+ ListBase *lb;
+ DupliObject *dob;
+ Base tbase;
+
+ tbase.flag = OB_FROMDUPLI;
+ lb = object_duplilist(G.main->eval_ctx, scene, base->object);
+
+ for (dob = lb->first; dob; dob = dob->next) {
+ float omat[4][4];
+ char dt;
+ short dtx;
+
+ tbase.object = dob->ob;
+ copy_m4_m4(omat, dob->ob->obmat);
+ copy_m4_m4(dob->ob->obmat, dob->mat);
+
+ /* extra service: draw the duplicator in drawtype of parent */
+ /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
+ dt = tbase.object->dt; tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
+ dtx = tbase.object->dtx; tbase.object->dtx = base->object->dtx;
+
+ draw_object(scene, ar, v3d, &tbase, dflag);
+
+ tbase.object->dt = dt;
+ tbase.object->dtx = dtx;
+
+ copy_m4_m4(dob->ob->obmat, omat);
+ }
+ free_object_duplilist(lb);
+ }
+}
+
/* ***************** BACKBUF SEL (BBS) ********* */
static void bbs_obmode_mesh_verts__mapFunc(void *userData, int index, const float co[3],
@@ -8237,6 +8274,7 @@ static DMDrawOption bbs_mesh_wire__setDrawOptions(void *userData, int index)
static void bbs_mesh_wire(BMEditMesh *em, DerivedMesh *dm, int offset)
{
drawBMOffset_userData data = {em->bm, offset};
+ glLineWidth(1);
dm->drawMappedEdges(dm, bbs_mesh_wire__setDrawOptions, &data);
}
@@ -8342,9 +8380,13 @@ static void bbs_mesh_solid_verts(Scene *scene, Object *ob)
DM_update_materials(dm, ob);
- dm->drawMappedFaces(dm, bbs_mesh_solid_hide2__setDrawOpts, GPU_object_material_bind, NULL, me, DM_DRAW_SKIP_HIDDEN);
+ /* Only draw faces to mask out verts, we don't want their selection ID's. */
+ const int G_f_orig = G.f;
+ G.f &= ~G_BACKBUFSEL;
- GPU_object_material_unbind();
+ dm->drawMappedFaces(dm, bbs_mesh_solid_hide2__setDrawOpts, NULL, NULL, me, DM_DRAW_SKIP_HIDDEN);
+
+ G.f |= (G_f_orig & G_BACKBUFSEL);
bbs_obmode_mesh_verts(ob, dm, 1);
bm_vertoffs = me->totvert + 1;
@@ -8392,17 +8434,24 @@ void draw_object_backbufsel(Scene *scene, View3D *v3d, RegionView3D *rv3d, Objec
bbs_mesh_solid_EM(em, scene, v3d, ob, dm, (ts->selectmode & SCE_SELECT_FACE) != 0);
if (ts->selectmode & SCE_SELECT_FACE)
bm_solidoffs = 1 + em->bm->totface;
- else
+ else {
bm_solidoffs = 1;
+ }
ED_view3d_polygon_offset(rv3d, 1.0);
- /* we draw edges always, for loop (select) tools */
- bbs_mesh_wire(em, dm, bm_solidoffs);
- bm_wireoffs = bm_solidoffs + em->bm->totedge;
+ /* we draw edges if edge select mode */
+ if (ts->selectmode & SCE_SELECT_EDGE) {
+ bbs_mesh_wire(em, dm, bm_solidoffs);
+ bm_wireoffs = bm_solidoffs + em->bm->totedge;
+ }
+ else {
+ /* `bm_vertoffs` is calculated from `bm_wireoffs`. (otherwise see T53512) */
+ bm_wireoffs = bm_solidoffs;
+ }
- /* we draw verts if vert select mode or if in transform (for snap). */
- if ((ts->selectmode & SCE_SELECT_VERTEX) || (G.moving & G_TRANSFORM_EDIT)) {
+ /* we draw verts if vert select mode. */
+ if (ts->selectmode & SCE_SELECT_VERTEX) {
bbs_mesh_verts(em, dm, bm_wireoffs);
bm_vertoffs = bm_wireoffs + em->bm->totvert;
}
@@ -8417,8 +8466,8 @@ void draw_object_backbufsel(Scene *scene, View3D *v3d, RegionView3D *rv3d, Objec
else {
Mesh *me = ob->data;
if ((me->editflag & ME_EDIT_PAINT_VERT_SEL) &&
- /* currently vertex select only supports weight paint */
- (ob->mode & OB_MODE_WEIGHT_PAINT))
+ /* currently vertex select supports weight paint and vertex paint*/
+ ((ob->mode & OB_MODE_WEIGHT_PAINT) || (ob->mode & OB_MODE_VERTEX_PAINT)))
{
bbs_mesh_solid_verts(scene, ob);
}
diff --git a/source/blender/editors/space_view3d/drawsimdebug.c b/source/blender/editors/space_view3d/drawsimdebug.c
index 9414d39467d..3f23d4aa09a 100644
--- a/source/blender/editors/space_view3d/drawsimdebug.c
+++ b/source/blender/editors/space_view3d/drawsimdebug.c
@@ -171,7 +171,7 @@ void draw_sim_debug_data(Scene *UNUSED(scene), View3D *v3d, ARegion *ar)
view3d_cached_text_draw_begin();
draw_sim_debug_elements(_sim_debug_data, imat);
- view3d_cached_text_draw_end(v3d, ar, false, NULL);
+ view3d_cached_text_draw_end(v3d, ar, false);
glPopMatrix();
diff --git a/source/blender/editors/space_view3d/drawvolume.c b/source/blender/editors/space_view3d/drawvolume.c
index 27ecbf83db5..cf118404183 100644
--- a/source/blender/editors/space_view3d/drawvolume.c
+++ b/source/blender/editors/space_view3d/drawvolume.c
@@ -41,7 +41,7 @@
#include "BLI_math.h"
#include "BKE_DerivedMesh.h"
-#include "BKE_texture.h"
+#include "BKE_colorband.h"
#include "BKE_particle.h"
#include "smoke_API.h"
@@ -112,7 +112,7 @@ static void create_flame_spectrum_texture(float *data)
static void create_color_ramp(const ColorBand *coba, float *data)
{
for (int i = 0; i < TFUNC_WIDTH; i++) {
- do_colorband(coba, (float)i / TFUNC_WIDTH, &data[i * 4]);
+ BKE_colorband_evaluate(coba, (float)i / TFUNC_WIDTH, &data[i * 4]);
}
}
@@ -737,7 +737,7 @@ static void add_streamline(float (*verts)[3], float(*colors)[3], float center[3]
copy_v3_v3(verts[(*offset)++], center);
}
-typedef void (*vector_draw_func)(float(*)[3], float(*)[3], float*, float*, float, float, int*);
+typedef void (*vector_draw_func)(float(*)[3], float(*)[3], float *, float *, float, float, int *);
#endif /* WITH_SMOKE */
void draw_smoke_velocity(SmokeDomainSettings *domain, float viewnormal[3])
@@ -774,8 +774,8 @@ void draw_smoke_velocity(SmokeDomainSettings *domain, float viewnormal[3])
float min[3] = {
domain->p0[0] - domain->cell_size[0] * domain->adapt_res,
- domain->p0[1] - domain->cell_size[1] * domain->adapt_res,
- domain->p0[2] - domain->cell_size[2] * domain->adapt_res,
+ domain->p0[1] - domain->cell_size[1] * domain->adapt_res,
+ domain->p0[2] - domain->cell_size[2] * domain->adapt_res,
};
int num_points_v[3] = {
diff --git a/source/blender/editors/space_view3d/space_view3d.c b/source/blender/editors/space_view3d/space_view3d.c
index e73cc507f3e..a36b698a04e 100644
--- a/source/blender/editors/space_view3d/space_view3d.c
+++ b/source/blender/editors/space_view3d/space_view3d.c
@@ -290,7 +290,7 @@ void ED_view3d_stop_render_preview(wmWindowManager *wm, ARegion *ar)
}
}
-void ED_view3d_shade_update(Main *bmain, Scene *scene, View3D *v3d, ScrArea *sa)
+void ED_view3d_shade_update(Main *bmain, View3D *v3d, ScrArea *sa)
{
wmWindowManager *wm = bmain->wm.first;
@@ -302,10 +302,6 @@ void ED_view3d_shade_update(Main *bmain, Scene *scene, View3D *v3d, ScrArea *sa)
ED_view3d_stop_render_preview(wm, ar);
}
}
- else if (scene->obedit != NULL && scene->obedit->type == OB_MESH) {
- /* Tag mesh to load edit data. */
- DAG_id_tag_update(scene->obedit->data, 0);
- }
}
/* ******************** default callbacks for view3d space ***************** */
@@ -869,6 +865,7 @@ static void view3d_main_region_listener(bScreen *sc, ScrArea *sa, ARegion *ar, w
case ND_CONSTRAINT:
case ND_KEYS:
case ND_PARTICLE:
+ case ND_POINTCACHE:
case ND_LOD:
ED_region_tag_redraw(ar);
break;
@@ -1411,33 +1408,31 @@ static void view3d_id_remap(ScrArea *sa, SpaceLink *slink, ID *old_id, ID *new_i
}
}
}
- if ((ID *)v3d->ob_centre == old_id) {
- v3d->ob_centre = (Object *)new_id;
- if (new_id == NULL) { /* Otherwise, bonename may remain valid... We could be smart and check this, too? */
- v3d->ob_centre_bone[0] = '\0';
- }
- }
- if ((ID *)v3d->defmaterial == old_id) {
- v3d->defmaterial = (Material *)new_id;
- }
-#if 0 /* XXX Deprecated? */
- if ((ID *)v3d->gpd == old_id) {
- v3d->gpd = (bGPData *)new_id;
- }
-#endif
+ /* Values in local-view aren't used, see: T52663 */
+ if (is_local == false) {
+ /* Skip 'v3d->defmaterial', it's not library data. */
- if (ELEM(GS(old_id->name), ID_IM, ID_MC)) {
- for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
- if ((ID *)bgpic->ima == old_id) {
- bgpic->ima = (Image *)new_id;
- id_us_min(old_id);
- id_us_plus(new_id);
+ if ((ID *)v3d->ob_centre == old_id) {
+ v3d->ob_centre = (Object *)new_id;
+ /* Otherwise, bonename may remain valid... We could be smart and check this, too? */
+ if (new_id == NULL) {
+ v3d->ob_centre_bone[0] = '\0';
}
- if ((ID *)bgpic->clip == old_id) {
- bgpic->clip = (MovieClip *)new_id;
- id_us_min(old_id);
- id_us_plus(new_id);
+ }
+
+ if (ELEM(GS(old_id->name), ID_IM, ID_MC)) {
+ for (BGpic *bgpic = v3d->bgpicbase.first; bgpic; bgpic = bgpic->next) {
+ if ((ID *)bgpic->ima == old_id) {
+ bgpic->ima = (Image *)new_id;
+ id_us_min(old_id);
+ id_us_plus(new_id);
+ }
+ if ((ID *)bgpic->clip == old_id) {
+ bgpic->clip = (MovieClip *)new_id;
+ id_us_min(old_id);
+ id_us_plus(new_id);
+ }
}
}
}
diff --git a/source/blender/editors/space_view3d/view3d_buttons.c b/source/blender/editors/space_view3d/view3d_buttons.c
index 351c7ccec15..0c67776693d 100644
--- a/source/blender/editors/space_view3d/view3d_buttons.c
+++ b/source/blender/editors/space_view3d/view3d_buttons.c
@@ -814,10 +814,6 @@ static void view3d_panel_vgroup(const bContext *C, Panel *pa)
if (dv && dv->totweight) {
ToolSettings *ts = scene->toolsettings;
- wmOperatorType *ot_weight_set_active = WM_operatortype_find("OBJECT_OT_vertex_weight_set_active", true);
- wmOperatorType *ot_weight_paste = WM_operatortype_find("OBJECT_OT_vertex_weight_paste", true);
- wmOperatorType *ot_weight_delete = WM_operatortype_find("OBJECT_OT_vertex_weight_delete", true);
-
wmOperatorType *ot;
PointerRNA op_ptr, tools_ptr;
PointerRNA *but_ptr;
@@ -856,7 +852,7 @@ static void view3d_panel_vgroup(const bContext *C, Panel *pa)
/* The Weight Group Name */
- ot = ot_weight_set_active;
+ ot = WM_operatortype_find("OBJECT_OT_vertex_weight_set_active", true);
but = uiDefButO_ptr(block, UI_BTYPE_BUT, ot, WM_OP_EXEC_DEFAULT, dg->name,
xco, yco, (x = UI_UNIT_X * 5), UI_UNIT_Y, "");
but_ptr = UI_but_operator_ptr_get(but);
@@ -882,23 +878,16 @@ static void view3d_panel_vgroup(const bContext *C, Panel *pa)
xco += x;
/* The weight group paste function */
-
- ot = ot_weight_paste;
- WM_operator_properties_create_ptr(&op_ptr, ot);
- RNA_int_set(&op_ptr, "weight_group", i);
icon = (locked) ? ICON_BLANK1 : ICON_PASTEDOWN;
- uiItemFullO_ptr(row, ot, "", icon, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(row, "OBJECT_OT_vertex_weight_paste", "", icon, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
+ RNA_int_set(&op_ptr, "weight_group", i);
/* The weight entry delete function */
-
- ot = ot_weight_delete;
- WM_operator_properties_create_ptr(&op_ptr, ot);
- RNA_int_set(&op_ptr, "weight_group", i);
icon = (locked) ? ICON_LOCKED : ICON_X;
- uiItemFullO_ptr(row, ot, "", icon, op_ptr.data, WM_OP_INVOKE_DEFAULT, 0);
+ uiItemFullO(row, "OBJECT_OT_vertex_weight_delete", "", icon, NULL, WM_OP_INVOKE_DEFAULT, 0, &op_ptr);
+ RNA_int_set(&op_ptr, "weight_group", i);
yco -= UI_UNIT_Y;
-
}
}
}
diff --git a/source/blender/editors/space_view3d/view3d_camera_control.c b/source/blender/editors/space_view3d/view3d_camera_control.c
index f717f1c0a43..e27b3fe13f9 100644
--- a/source/blender/editors/space_view3d/view3d_camera_control.c
+++ b/source/blender/editors/space_view3d/view3d_camera_control.c
@@ -31,10 +31,10 @@
*
* Typical view-control usage:
*
- * - acquire a view-control (#ED_view3d_control_acquire).
+ * - acquire a view-control (#ED_view3d_cameracontrol_acquire).
* - modify ``rv3d->ofs``, ``rv3d->viewquat``.
- * - update the view data (#ED_view3d_control_acquire) - within a loop which draws the viewport.
- * - finish and release the view-control (#ED_view3d_control_release),
+ * - update the view data (#ED_view3d_cameracontrol_acquire) - within a loop which draws the viewport.
+ * - finish and release the view-control (#ED_view3d_cameracontrol_release),
* either keeping the current view or restoring the initial view.
*
* Notes:
diff --git a/source/blender/editors/space_view3d/view3d_draw.c b/source/blender/editors/space_view3d/view3d_draw.c
index f23e587e55d..cc046eebc68 100644
--- a/source/blender/editors/space_view3d/view3d_draw.c
+++ b/source/blender/editors/space_view3d/view3d_draw.c
@@ -48,7 +48,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_utildefines.h"
#include "BLI_endian_switch.h"
#include "BLI_threads.h"
@@ -100,11 +100,13 @@
#include "GPU_material.h"
#include "GPU_compositing.h"
#include "GPU_extensions.h"
+#include "GPU_select.h"
#include "view3d_intern.h" /* own include */
/* prototypes */
-static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar);
+static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d);
+static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect);
static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *ar,
float winmat[4][4], const char *viewname);
@@ -859,7 +861,7 @@ static void draw_viewport_name(ARegion *ar, View3D *v3d, rcti *rect)
* framenum, object name, bone name (if available), marker name (if available)
*/
-static void draw_selected_name(Scene *scene, Object *ob, rcti *rect)
+static void draw_selected_name(Scene *scene, Object *ob, const rcti *rect)
{
const int cfra = CFRA;
const char *msg_pin = " (Pinned)";
@@ -1316,31 +1318,30 @@ static void drawviewborder(Scene *scene, ARegion *ar, View3D *v3d)
/* *********************** backdraw for selection *************** */
-static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d)
+static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d, Object *obact, Object *obedit)
{
RegionView3D *rv3d = ar->regiondata;
- struct Base *base = scene->basact;
int multisample_enabled;
BLI_assert(ar->regiontype == RGN_TYPE_WINDOW);
- if (base && (base->object->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
- BKE_paint_select_face_test(base->object)))
+ if (obact && (obact->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT) ||
+ BKE_paint_select_face_test(obact)))
{
/* do nothing */
}
/* texture paint mode sampling */
- else if (base && (base->object->mode & OB_MODE_TEXTURE_PAINT) &&
+ else if (obact && (obact->mode & OB_MODE_TEXTURE_PAINT) &&
(v3d->drawtype > OB_WIRE))
{
/* do nothing */
}
- else if ((base && (base->object->mode & OB_MODE_PARTICLE_EDIT)) &&
+ else if ((obact && (obact->mode & OB_MODE_PARTICLE_EDIT)) &&
V3D_IS_ZBUF(v3d))
{
/* do nothing */
}
- else if (scene->obedit &&
+ else if (obedit &&
V3D_IS_ZBUF(v3d))
{
/* do nothing */
@@ -1415,10 +1416,11 @@ static void backdrawview3d(Scene *scene, wmWindow *win, ARegion *ar, View3D *v3d
ED_view3d_clipping_set(rv3d);
G.f |= G_BACKBUFSEL;
-
- if (base && (base->lay & v3d->lay))
- draw_object_backbufsel(scene, v3d, rv3d, base->object);
-
+
+ if (obact && (obact->lay & v3d->lay)) {
+ draw_object_backbufsel(scene, v3d, rv3d, obact);
+ }
+
if (rv3d->gpuoffscreen)
GPU_offscreen_unbind(rv3d->gpuoffscreen, true);
else
@@ -1461,8 +1463,9 @@ static void view3d_opengl_read_Z_pixels(ARegion *ar, int x, int y, int w, int h,
void ED_view3d_backbuf_validate(ViewContext *vc)
{
- if (vc->v3d->flag & V3D_INVALID_BACKBUF)
- backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d);
+ if (vc->v3d->flag & V3D_INVALID_BACKBUF) {
+ backdrawview3d(vc->scene, vc->win, vc->ar, vc->v3d, vc->obact, vc->obedit);
+ }
}
/**
@@ -1553,8 +1556,10 @@ ImBuf *ED_view3d_backbuf_read(ViewContext *vc, int xmin, int ymin, int xmax, int
}
}
-/* smart function to sample a rect spiralling outside, nice for backbuf selection */
-unsigned int ED_view3d_backbuf_sample_rect(
+/**
+ * Smart function to sample a rectangle spiral ling outside, nice for backbuf selection
+ */
+uint ED_view3d_backbuf_sample_rect(
ViewContext *vc, const int mval[2], int size,
unsigned int min, unsigned int max, float *r_dist)
{
@@ -2023,6 +2028,35 @@ static void view3d_draw_xraytransp(Scene *scene, ARegion *ar, View3D *v3d, const
glDepthMask(GL_TRUE);
}
+/* clears zbuffer and draws it over,
+ * note that in the select version we don't care about transparent flag as with regular drawing */
+static void view3d_draw_xray_select(Scene *scene, ARegion *ar, View3D *v3d, bool *clear)
+{
+ /* Not ideal, but we need to read from the previous depths before clearing
+ * otherwise we could have a function to load the depths after drawing.
+ *
+ * Clearing the depth buffer isn't all that common between drawing objects so accept this for now.
+ */
+ if (U.gpu_select_pick_deph) {
+ GPU_select_load_id(-1);
+ }
+
+ View3DAfter *v3da;
+ if (*clear && v3d->zbuf) {
+ glClear(GL_DEPTH_BUFFER_BIT);
+ *clear = false;
+ }
+
+ v3d->xray = true;
+ while ((v3da = BLI_pophead(&v3d->afterdraw_xray))) {
+ if (GPU_select_load_id(v3da->base->selcol)) {
+ draw_object_select(scene, ar, v3d, v3da->base, v3da->dflag);
+ }
+ MEM_freeN(v3da);
+ }
+ v3d->xray = false;
+}
+
/* *********************** */
/*
@@ -2341,17 +2375,11 @@ void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
short zbuf = v3d->zbuf;
RegionView3D *rv3d = ar->regiondata;
- view3d_winmatrix_set(ar, v3d, NULL);
- view3d_viewmatrix_set(scene, v3d, rv3d); /* note: calls BKE_object_where_is_calc for camera... */
-
- mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
- invert_m4_m4(rv3d->persinv, rv3d->persmat);
- invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
+ /* Setup view matrix. */
+ ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
glClear(GL_DEPTH_BUFFER_BIT);
- glLoadMatrixf(rv3d->viewmat);
-
v3d->zbuf = true;
glEnable(GL_DEPTH_TEST);
@@ -2360,46 +2388,15 @@ void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d)
}
v3d->zbuf = zbuf;
-
}
-void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaoverride)
+static void view3d_draw_depth_loop(Scene *scene, ARegion *ar, View3D *v3d)
{
- RegionView3D *rv3d = ar->regiondata;
Base *base;
- short zbuf = v3d->zbuf;
- short flag = v3d->flag;
- float glalphaclip = U.glalphaclip;
- int obcenter_dia = U.obcenter_dia;
+
/* no need for color when drawing depth buffer */
const short dflag_depth = DRAW_CONSTCOLOR;
- /* temp set drawtype to solid */
-
- /* Setting these temporarily is not nice */
- v3d->flag &= ~V3D_SELECT_OUTLINE;
- U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
- U.obcenter_dia = 0;
-
- view3d_winmatrix_set(ar, v3d, NULL);
- view3d_viewmatrix_set(scene, v3d, rv3d); /* note: calls BKE_object_where_is_calc for camera... */
-
- mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
- invert_m4_m4(rv3d->persinv, rv3d->persmat);
- invert_m4_m4(rv3d->viewinv, rv3d->viewmat);
-
- glClear(GL_DEPTH_BUFFER_BIT);
-
- glLoadMatrixf(rv3d->viewmat);
-
- if (rv3d->rflag & RV3D_CLIPPING) {
- ED_view3d_clipping_set(rv3d);
- }
- /* get surface depth without bias */
- rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
- v3d->zbuf = true;
- glEnable(GL_DEPTH_TEST);
-
/* draw set first */
if (scene->set) {
Scene *sce_iter;
@@ -2473,8 +2470,44 @@ void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaover
glDepthMask(mask_orig);
}
+}
+
+void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaoverride)
+{
+ struct bThemeState theme_state;
+ RegionView3D *rv3d = ar->regiondata;
+ short zbuf = v3d->zbuf;
+ short flag = v3d->flag;
+ float glalphaclip = U.glalphaclip;
+ int obcenter_dia = U.obcenter_dia;
+ /* temp set drawtype to solid */
+
+ /* Setting these temporarily is not nice */
+ v3d->flag &= ~V3D_SELECT_OUTLINE;
+ U.glalphaclip = alphaoverride ? 0.5f : glalphaclip; /* not that nice but means we wont zoom into billboards */
+ U.obcenter_dia = 0;
+
+ /* Tools may request depth outside of regular drawing code. */
+ UI_Theme_Store(&theme_state);
+ UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
+
+ /* Setup view matrix. */
+ ED_view3d_draw_setup_view(NULL, scene, ar, v3d, rv3d->viewmat, rv3d->winmat, NULL);
+
+ glClear(GL_DEPTH_BUFFER_BIT);
if (rv3d->rflag & RV3D_CLIPPING) {
+ ED_view3d_clipping_set(rv3d);
+ }
+ /* get surface depth without bias */
+ rv3d->rflag |= RV3D_ZOFFSET_DISABLED;
+
+ v3d->zbuf = true;
+ glEnable(GL_DEPTH_TEST);
+
+ view3d_draw_depth_loop(scene, ar, v3d);
+
+ if (rv3d->rflag & RV3D_CLIPPING) {
ED_view3d_clipping_disable();
}
rv3d->rflag &= ~RV3D_ZOFFSET_DISABLED;
@@ -2485,6 +2518,60 @@ void ED_view3d_draw_depth(Scene *scene, ARegion *ar, View3D *v3d, bool alphaover
U.glalphaclip = glalphaclip;
v3d->flag = flag;
U.obcenter_dia = obcenter_dia;
+
+ UI_Theme_Restore(&theme_state);
+}
+
+void ED_view3d_draw_select_loop(
+ ViewContext *vc, Scene *scene, View3D *v3d, ARegion *ar,
+ bool use_obedit_skip, bool use_nearest)
+{
+ short code = 1;
+ const short dflag = DRAW_PICKING | DRAW_CONSTCOLOR;
+
+ if (vc->obedit && vc->obedit->type == OB_MBALL) {
+ draw_object(scene, ar, v3d, BASACT, dflag);
+ }
+ else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
+ /* if not drawing sketch, draw bones */
+ if (!BDR_drawSketchNames(vc)) {
+ draw_object(scene, ar, v3d, BASACT, dflag);
+ }
+ }
+ else {
+ Base *base;
+
+ for (base = scene->base.first; base; base = base->next) {
+ if (base->lay & v3d->lay) {
+
+ if ((base->object->restrictflag & OB_RESTRICT_SELECT) ||
+ (use_obedit_skip && (scene->obedit->data == base->object->data)))
+ {
+ base->selcol = 0;
+ }
+ else {
+ base->selcol = code;
+
+ if (use_nearest && (base->object->dtx & OB_DRAWXRAY)) {
+ ED_view3d_after_add(&v3d->afterdraw_xray, base, dflag);
+ }
+ else {
+ if (GPU_select_load_id(code)) {
+ draw_object_select(scene, ar, v3d, base, dflag);
+ }
+ }
+ code++;
+ }
+ }
+ }
+
+ if (use_nearest) {
+ bool xrayclear = true;
+ if (v3d->afterdraw_xray.first) {
+ view3d_draw_xray_select(scene, ar, v3d, &xrayclear);
+ }
+ }
+ }
}
typedef struct View3DShadow {
@@ -2515,7 +2602,7 @@ static void gpu_render_lamp_update(Scene *scene, View3D *v3d,
if (layers &&
GPU_lamp_has_shadow_buffer(lamp) &&
/* keep last, may do string lookup */
- GPU_lamp_override_visible(lamp, srl, NULL))
+ GPU_lamp_visible(lamp, srl, NULL))
{
shadow = MEM_callocN(sizeof(View3DShadow), "View3DShadow");
shadow->lamp = lamp;
@@ -2655,7 +2742,8 @@ CustomDataMask ED_view3d_screen_datamask(const bScreen *screen)
/**
* \note keep this synced with #ED_view3d_mats_rv3d_backup/#ED_view3d_mats_rv3d_restore
*/
-void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
+void ED_view3d_update_viewmat(
+ Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
{
RegionView3D *rv3d = ar->regiondata;
@@ -2663,13 +2751,20 @@ void ED_view3d_update_viewmat(Scene *scene, View3D *v3d, ARegion *ar, float view
if (winmat)
copy_m4_m4(rv3d->winmat, winmat);
else
- view3d_winmatrix_set(ar, v3d, NULL);
+ view3d_winmatrix_set(ar, v3d, rect);
/* setup view matrix */
- if (viewmat)
+ if (viewmat) {
copy_m4_m4(rv3d->viewmat, viewmat);
- else
- view3d_viewmatrix_set(scene, v3d, rv3d); /* note: calls BKE_object_where_is_calc for camera... */
+ }
+ else {
+ float rect_scale[2];
+ if (rect) {
+ rect_scale[0] = (float)BLI_rcti_size_x(rect) / (float)ar->winx;
+ rect_scale[1] = (float)BLI_rcti_size_y(rect) / (float)ar->winy;
+ }
+ view3d_viewmatrix_set(scene, v3d, rv3d, rect ? rect_scale : NULL); /* note: calls BKE_object_where_is_calc for camera... */
+ }
/* update utility matrices */
mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
@@ -2926,11 +3021,12 @@ static void view3d_draw_objects(
}
}
-static void view3d_main_region_setup_view(Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4])
+static void view3d_main_region_setup_view(
+ Scene *scene, View3D *v3d, ARegion *ar, float viewmat[4][4], float winmat[4][4], const rcti *rect)
{
RegionView3D *rv3d = ar->regiondata;
- ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat);
+ ED_view3d_update_viewmat(scene, v3d, ar, viewmat, winmat, rect);
/* set for opengl */
glMatrixMode(GL_PROJECTION);
@@ -2955,7 +3051,7 @@ struct RV3DMatrixStore {
float pixsize;
};
-void *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
+struct RV3DMatrixStore *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
{
struct RV3DMatrixStore *rv3dmat = MEM_mallocN(sizeof(*rv3dmat), __func__);
copy_m4_m4(rv3dmat->winmat, rv3d->winmat);
@@ -2968,9 +3064,8 @@ void *ED_view3d_mats_rv3d_backup(struct RegionView3D *rv3d)
return (void *)rv3dmat;
}
-void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, void *rv3dmat_pt)
+void ED_view3d_mats_rv3d_restore(struct RegionView3D *rv3d, struct RV3DMatrixStore *rv3dmat)
{
- struct RV3DMatrixStore *rv3dmat = rv3dmat_pt;
copy_m4_m4(rv3d->winmat, rv3dmat->winmat);
copy_m4_m4(rv3d->viewmat, rv3dmat->viewmat);
copy_m4_m4(rv3d->persmat, rv3dmat->persmat);
@@ -3114,7 +3209,7 @@ void ED_view3d_draw_offscreen(
if ((viewname != NULL && viewname[0] != '\0') && (viewmat == NULL) && rv3d->persp == RV3D_CAMOB && v3d->camera)
view3d_stereo3d_setup_offscreen(scene, v3d, ar, winmat, viewname);
else
- view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
/* framebuffer fx needed, we need to draw offscreen first */
if (v3d->fx_settings.fx_flag && fx) {
@@ -3177,6 +3272,23 @@ void ED_view3d_draw_offscreen(
}
/**
+ * Set the correct matrices
+ */
+void ED_view3d_draw_setup_view(
+ wmWindow *win, Scene *scene, ARegion *ar, View3D *v3d, float viewmat[4][4], float winmat[4][4], const rcti *rect)
+{
+ RegionView3D *rv3d = ar->regiondata;
+
+ /* Setup the view matrix. */
+ if (view3d_stereo3d_active(win, scene, v3d, rv3d)) {
+ view3d_stereo3d_setup(scene, v3d, ar, rect);
+ }
+ else {
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, rect);
+ }
+}
+
+/**
* Utility func for ED_view3d_draw_offscreen
*
* \param ofs: Optional off-screen buffer, can be NULL.
@@ -3184,14 +3296,16 @@ void ED_view3d_draw_offscreen(
*/
ImBuf *ED_view3d_draw_offscreen_imbuf(
Scene *scene, View3D *v3d, ARegion *ar, int sizex, int sizey,
- unsigned int flag, bool draw_background,
- int alpha_mode, int samples, bool full_samples, const char *viewname,
+ unsigned int flag, unsigned int draw_flags,
+ int alpha_mode, int samples, const char *viewname,
/* output vars */
GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
{
RegionView3D *rv3d = ar->regiondata;
ImBuf *ibuf;
const bool draw_sky = (alpha_mode == R_ADDSKY);
+ const bool draw_background = (draw_flags & V3D_OFSDRAW_USE_BACKGROUND);
+ const bool use_full_sample = (draw_flags & V3D_OFSDRAW_USE_FULL_SAMPLE);
/* view state */
GPUFXSettings fx_settings = v3d->fx_settings;
@@ -3207,7 +3321,7 @@ ImBuf *ED_view3d_draw_offscreen_imbuf(
if (own_ofs) {
/* bind */
- ofs = GPU_offscreen_create(sizex, sizey, full_samples ? 0 : samples, err_out);
+ ofs = GPU_offscreen_create(sizex, sizey, use_full_sample ? 0 : samples, err_out);
if (ofs == NULL) {
return NULL;
}
@@ -3252,7 +3366,7 @@ ImBuf *ED_view3d_draw_offscreen_imbuf(
}
}
- if ((samples && full_samples) == 0) {
+ if ((samples && use_full_sample) == 0) {
/* Single-pass render, common case */
ED_view3d_draw_offscreen(
scene, v3d, ar, sizex, sizey, NULL, winmat,
@@ -3352,8 +3466,8 @@ ImBuf *ED_view3d_draw_offscreen_imbuf(
*/
ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
Scene *scene, Object *camera, int width, int height,
- unsigned int flag, int drawtype, bool use_solid_tex, bool use_gpencil, bool draw_background,
- int alpha_mode, int samples, bool full_samples, const char *viewname,
+ unsigned int flag, unsigned int draw_flags, int drawtype,
+ int alpha_mode, int samples, const char *viewname,
GPUFX *fx, GPUOffScreen *ofs, char err_out[256])
{
View3D v3d = {NULL};
@@ -3369,15 +3483,22 @@ ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
v3d.lay = scene->lay;
v3d.drawtype = drawtype;
v3d.flag2 = V3D_RENDER_OVERRIDE;
-
- if (use_gpencil)
- v3d.flag2 |= V3D_SHOW_GPENCIL;
- if (use_solid_tex)
+ if (draw_flags & V3D_OFSDRAW_USE_GPENCIL) {
+ v3d.flag2 |= V3D_SHOW_GPENCIL;
+ }
+ if (draw_flags & V3D_OFSDRAW_USE_SOLID_TEX) {
v3d.flag2 |= V3D_SOLID_TEX;
-
- if (draw_background)
+ }
+ if (draw_flags & V3D_OFSDRAW_USE_BACKGROUND) {
v3d.flag3 |= V3D_SHOW_WORLD;
+ }
+ if (draw_flags & V3D_OFSDRAW_USE_CAMERA_DOF) {
+ if (camera->type == OB_CAMERA) {
+ v3d.fx_settings.dof = &((Camera *)camera->data)->gpu_dof;
+ v3d.fx_settings.fx_flag |= GPU_FX_FLAG_DOF;
+ }
+ }
rv3d.persp = RV3D_CAMOB;
@@ -3405,9 +3526,8 @@ ImBuf *ED_view3d_draw_offscreen_imbuf_simple(
invert_m4_m4(rv3d.persinv, rv3d.viewinv);
return ED_view3d_draw_offscreen_imbuf(
- scene, &v3d, &ar, width, height, flag,
- draw_background, alpha_mode, samples, full_samples, viewname,
- fx, ofs, err_out);
+ scene, &v3d, &ar, width, height, flag, draw_flags,
+ alpha_mode, samples, viewname, fx, ofs, err_out);
}
@@ -3467,14 +3587,16 @@ void ED_scene_draw_fps(Scene *scene, const rcti *rect)
#endif
}
-static bool view3d_main_region_do_render_draw(Scene *scene)
+static bool view3d_main_region_do_render_draw(const Scene *scene)
{
RenderEngineType *type = RE_engines_find(scene->r.engine);
return (type && type->view_update && type->view_draw);
}
-bool ED_view3d_calc_render_border(Scene *scene, View3D *v3d, ARegion *ar, rcti *rect)
+bool ED_view3d_calc_render_border(
+ const Scene *scene, const View3D *v3d, const ARegion *ar,
+ rcti *rect)
{
RegionView3D *rv3d = ar->regiondata;
rctf viewborder;
@@ -3543,7 +3665,7 @@ static bool view3d_main_region_draw_engine(const bContext *C, Scene *scene,
}
/* setup view matrices */
- view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
+ view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL, NULL);
/* background draw */
ED_region_pixelspace(ar);
@@ -3610,26 +3732,37 @@ static void view3d_main_region_draw_engine_info(View3D *v3d, RegionView3D *rv3d,
ED_region_info_draw(ar, rv3d->render_engine->text, fill_color, true);
}
-static bool view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d, RegionView3D *rv3d)
+static bool view3d_stereo3d_active(wmWindow *win, Scene *scene, View3D *v3d, RegionView3D *rv3d)
{
- wmWindow *win = CTX_wm_window(C);
-
- if ((scene->r.scemode & R_MULTIVIEW) == 0)
- return false;
-
- if (WM_stereo3d_enabled(win, true) == false)
+ if ((scene->r.scemode & R_MULTIVIEW) == 0) {
return false;
+ }
- if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB)
+ if ((v3d->camera == NULL) || (v3d->camera->type != OB_CAMERA) || rv3d->persp != RV3D_CAMOB) {
return false;
+ }
- if (scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) {
- if (v3d->stereo3d_camera == STEREO_MONO_ID)
+ switch (v3d->stereo3d_camera) {
+ case STEREO_MONO_ID:
return false;
-
- return BKE_scene_multiview_is_stereo3d(&scene->r);
+ break;
+ case STEREO_3D_ID:
+ /* win will be NULL when calling this from the selection or draw loop. */
+ if ((win == NULL) || (WM_stereo3d_enabled(win, true) == false)) {
+ return false;
+ }
+ if (((scene->r.views_format & SCE_VIEWS_FORMAT_MULTIVIEW) != 0) &&
+ !BKE_scene_multiview_is_stereo3d(&scene->r))
+ {
+ return false;
+ }
+ break;
+ /* We always need the stereo calculation for left and right cameras. */
+ case STEREO_LEFT_ID:
+ case STEREO_RIGHT_ID:
+ default:
+ break;
}
-
return true;
}
@@ -3641,7 +3774,7 @@ static bool view3d_stereo3d_active(const bContext *C, Scene *scene, View3D *v3d,
* we do a small hack to replace it temporarily so we don't need to change the
* view3d)main_region_setup_view() code to account for that.
*/
-static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
+static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar, const rcti *rect)
{
bool is_left;
const char *names[2] = {STEREO_LEFT_NAME, STEREO_RIGHT_NAME};
@@ -3663,28 +3796,28 @@ static void view3d_stereo3d_setup(Scene *scene, View3D *v3d, ARegion *ar)
data = (Camera *)v3d->camera->data;
shiftx = data->shiftx;
- BLI_lock_thread(LOCK_VIEW3D);
+ BLI_thread_lock(LOCK_VIEW3D);
data->shiftx = BKE_camera_multiview_shift_x(&scene->r, v3d->camera, viewname);
BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
- view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL, rect);
data->shiftx = shiftx;
- BLI_unlock_thread(LOCK_VIEW3D);
+ BLI_thread_unlock(LOCK_VIEW3D);
}
else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
float viewmat[4][4];
Object *view_ob = v3d->camera;
Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
- BLI_lock_thread(LOCK_VIEW3D);
+ BLI_thread_lock(LOCK_VIEW3D);
v3d->camera = camera;
BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
- view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL);
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, NULL, rect);
v3d->camera = view_ob;
- BLI_unlock_thread(LOCK_VIEW3D);
+ BLI_thread_unlock(LOCK_VIEW3D);
}
}
@@ -3697,14 +3830,14 @@ static void view3d_stereo3d_setup_offscreen(Scene *scene, View3D *v3d, ARegion *
const bool is_left = STREQ(viewname, STEREO_LEFT_NAME);
BKE_camera_multiview_view_matrix(&scene->r, v3d->camera, is_left, viewmat);
- view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
}
else { /* SCE_VIEWS_FORMAT_MULTIVIEW */
float viewmat[4][4];
Object *camera = BKE_camera_multiview_render(scene, v3d->camera, viewname);
BKE_camera_multiview_view_matrix(&scene->r, camera, false, viewmat);
- view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat);
+ view3d_main_region_setup_view(scene, v3d, ar, viewmat, winmat, NULL);
}
}
@@ -3742,11 +3875,8 @@ static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, Vie
GPU_default_lights();
}
- /* setup the view matrix */
- if (view3d_stereo3d_active(C, scene, v3d, rv3d))
- view3d_stereo3d_setup(scene, v3d, ar);
- else
- view3d_main_region_setup_view(scene, v3d, ar, NULL, NULL);
+ /* Setup the view matrix. */
+ ED_view3d_draw_setup_view(CTX_wm_window(C), scene, ar, v3d, NULL, NULL, NULL);
rv3d->rflag &= ~RV3D_IS_GAME_ENGINE;
#ifdef WITH_GAMEENGINE
@@ -3816,6 +3946,10 @@ static void view3d_main_region_draw_objects(const bContext *C, Scene *scene, Vie
static bool is_cursor_visible(Scene *scene)
{
+ if (U.app_flag & USER_APP_VIEW3D_HIDE_CURSOR) {
+ return false;
+ }
+
Object *ob = OBACT;
/* don't draw cursor in paint modes, but with a few exceptions */
diff --git a/source/blender/editors/space_view3d/view3d_edit.c b/source/blender/editors/space_view3d/view3d_edit.c
index 5e13b3f27fc..199800df539 100644
--- a/source/blender/editors/space_view3d/view3d_edit.c
+++ b/source/blender/editors/space_view3d/view3d_edit.c
@@ -26,6 +26,8 @@
/** \file blender/editors/space_view3d/view3d_edit.c
* \ingroup spview3d
+ *
+ * 3D view manipulation/operators.
*/
#include <string.h>
@@ -41,14 +43,11 @@
#include "MEM_guardedalloc.h"
-#include "BLI_bitmap_draw_2d.h"
#include "BLI_blenlib.h"
-#include "BLI_kdopbvh.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
#include "BKE_armature.h"
-#include "BKE_camera.h"
#include "BKE_context.h"
#include "BKE_font.h"
#include "BKE_library.h"
@@ -58,7 +57,6 @@
#include "BKE_scene.h"
#include "BKE_screen.h"
#include "BKE_action.h"
-#include "BKE_depsgraph.h" /* for ED_view3d_camera_lock_sync */
#include "BIF_gl.h"
@@ -72,7 +70,6 @@
#include "ED_armature.h"
#include "ED_particle.h"
-#include "ED_keyframing.h"
#include "ED_screen.h"
#include "ED_transform.h"
#include "ED_mesh.h"
@@ -81,486 +78,120 @@
#include "UI_resources.h"
-#include "PIL_time.h" /* smoothview */
+#include "PIL_time.h"
#include "view3d_intern.h" /* own include */
-bool ED_view3d_offset_lock_check(const View3D *v3d, const RegionView3D *rv3d)
-{
- return (rv3d->persp != RV3D_CAMOB) && (v3d->ob_centre_cursor || v3d->ob_centre);
-}
-
-/* ********************** view3d_edit: view manipulations ********************* */
-
-/**
- * \return true when the view-port is locked to its camera.
- */
-bool ED_view3d_camera_lock_check(const View3D *v3d, const RegionView3D *rv3d)
-{
- return ((v3d->camera) &&
- (!ID_IS_LINKED_DATABLOCK(v3d->camera)) &&
- (v3d->flag2 & V3D_LOCK_CAMERA) &&
- (rv3d->persp == RV3D_CAMOB));
-}
-
-/**
- * Apply the camera object transformation to the view-port.
- * (needed so we can use regular view-port manipulation operators, that sync back to the camera).
- */
-void ED_view3d_camera_lock_init_ex(View3D *v3d, RegionView3D *rv3d, const bool calc_dist)
-{
- if (ED_view3d_camera_lock_check(v3d, rv3d)) {
- if (calc_dist) {
- /* using a fallback dist is OK here since ED_view3d_from_object() compensates for it */
- rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
- }
- ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
- }
-}
-
-void ED_view3d_camera_lock_init(View3D *v3d, RegionView3D *rv3d)
-{
- ED_view3d_camera_lock_init_ex(v3d, rv3d, true);
-}
-
-/**
- * Apply the view-port transformation back to the camera object.
- *
- * \return true if the camera is moved.
- */
-bool ED_view3d_camera_lock_sync(View3D *v3d, RegionView3D *rv3d)
-{
- if (ED_view3d_camera_lock_check(v3d, rv3d)) {
- ObjectTfmProtectedChannels obtfm;
- Object *root_parent;
-
- if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
- Object *ob_update;
- float tmat[4][4];
- float imat[4][4];
- float view_mat[4][4];
- float diff_mat[4][4];
- float parent_mat[4][4];
-
- while (root_parent->parent) {
- root_parent = root_parent->parent;
- }
-
- ED_view3d_to_m4(view_mat, rv3d->ofs, rv3d->viewquat, rv3d->dist);
-
- normalize_m4_m4(tmat, v3d->camera->obmat);
-
- invert_m4_m4(imat, tmat);
- mul_m4_m4m4(diff_mat, view_mat, imat);
-
- mul_m4_m4m4(parent_mat, diff_mat, root_parent->obmat);
-
- BKE_object_tfm_protected_backup(root_parent, &obtfm);
- BKE_object_apply_mat4(root_parent, parent_mat, true, false);
- BKE_object_tfm_protected_restore(root_parent, &obtfm, root_parent->protectflag);
-
- ob_update = v3d->camera;
- while (ob_update) {
- DAG_id_tag_update(&ob_update->id, OB_RECALC_OB);
- WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, ob_update);
- ob_update = ob_update->parent;
- }
- }
- else {
- /* always maintain the same scale */
- const short protect_scale_all = (OB_LOCK_SCALEX | OB_LOCK_SCALEY | OB_LOCK_SCALEZ);
- BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
- ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
- BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag | protect_scale_all);
-
- DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
- WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, v3d->camera);
- }
-
- return true;
- }
- else {
- return false;
- }
-}
-
-bool ED_view3d_camera_autokey(
- Scene *scene, ID *id_key,
- struct bContext *C, const bool do_rotate, const bool do_translate)
-{
- if (autokeyframe_cfra_can_key(scene, id_key)) {
- const float cfra = (float)CFRA;
- ListBase dsources = {NULL, NULL};
-
- /* add data-source override for the camera object */
- ANIM_relative_keyingset_add_source(&dsources, id_key, NULL, NULL);
-
- /* insert keyframes
- * 1) on the first frame
- * 2) on each subsequent frame
- * TODO: need to check in future that frame changed before doing this
- */
- if (do_rotate) {
- struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_ROTATION_ID);
- ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
- }
- if (do_translate) {
- struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_LOCATION_ID);
- ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
- }
-
- /* free temp data */
- BLI_freelistN(&dsources);
-
- return true;
- }
- else {
- return false;
- }
-}
-
-/**
- * Call after modifying a locked view.
- *
- * \note Not every view edit currently auto-keys (numpad for eg),
- * this is complicated because of smoothview.
- */
-bool ED_view3d_camera_lock_autokey(
- View3D *v3d, RegionView3D *rv3d,
- struct bContext *C, const bool do_rotate, const bool do_translate)
-{
- /* similar to ED_view3d_cameracontrol_update */
- if (ED_view3d_camera_lock_check(v3d, rv3d)) {
- Scene *scene = CTX_data_scene(C);
- ID *id_key;
- Object *root_parent;
- if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
- while (root_parent->parent) {
- root_parent = root_parent->parent;
- }
- id_key = &root_parent->id;
- }
- else {
- id_key = &v3d->camera->id;
- }
-
- return ED_view3d_camera_autokey(scene, id_key, C, do_rotate, do_translate);
- }
- else {
- return false;
- }
-}
-
-/**
- * For viewport operators that exit camera persp.
- *
- * \note This differs from simply setting ``rv3d->persp = persp`` because it
- * sets the ``ofs`` and ``dist`` values of the viewport so it matches the camera,
- * otherwise switching out of camera view may jump to a different part of the scene.
- */
-static void view3d_persp_switch_from_camera(View3D *v3d, RegionView3D *rv3d, const char persp)
-{
- BLI_assert(rv3d->persp == RV3D_CAMOB);
- BLI_assert(persp != RV3D_CAMOB);
-
- if (v3d->camera) {
- rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
- ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
- }
-
- if (!ED_view3d_camera_lock_check(v3d, rv3d)) {
- rv3d->persp = persp;
- }
-}
-
-/* ********************* box view support ***************** */
-
-static void view3d_boxview_clip(ScrArea *sa)
-{
- ARegion *ar;
- BoundBox *bb = MEM_callocN(sizeof(BoundBox), "clipbb");
- float clip[6][4];
- float x1 = 0.0f, y1 = 0.0f, z1 = 0.0f, ofs[3] = {0.0f, 0.0f, 0.0f};
- int val;
-
- /* create bounding box */
- for (ar = sa->regionbase.first; ar; ar = ar->next) {
- if (ar->regiontype == RGN_TYPE_WINDOW) {
- RegionView3D *rv3d = ar->regiondata;
-
- if (rv3d->viewlock & RV3D_BOXCLIP) {
- if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) {
- if (ar->winx > ar->winy) x1 = rv3d->dist;
- else x1 = ar->winx * rv3d->dist / ar->winy;
-
- if (ar->winx > ar->winy) y1 = ar->winy * rv3d->dist / ar->winx;
- else y1 = rv3d->dist;
- copy_v2_v2(ofs, rv3d->ofs);
- }
- else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) {
- ofs[2] = rv3d->ofs[2];
-
- if (ar->winx > ar->winy) z1 = ar->winy * rv3d->dist / ar->winx;
- else z1 = rv3d->dist;
- }
- }
- }
- }
-
- for (val = 0; val < 8; val++) {
- if (ELEM(val, 0, 3, 4, 7))
- bb->vec[val][0] = -x1 - ofs[0];
- else
- bb->vec[val][0] = x1 - ofs[0];
-
- if (ELEM(val, 0, 1, 4, 5))
- bb->vec[val][1] = -y1 - ofs[1];
- else
- bb->vec[val][1] = y1 - ofs[1];
-
- if (val > 3)
- bb->vec[val][2] = -z1 - ofs[2];
- else
- bb->vec[val][2] = z1 - ofs[2];
- }
-
- /* normals for plane equations */
- normal_tri_v3(clip[0], bb->vec[0], bb->vec[1], bb->vec[4]);
- normal_tri_v3(clip[1], bb->vec[1], bb->vec[2], bb->vec[5]);
- normal_tri_v3(clip[2], bb->vec[2], bb->vec[3], bb->vec[6]);
- normal_tri_v3(clip[3], bb->vec[3], bb->vec[0], bb->vec[7]);
- normal_tri_v3(clip[4], bb->vec[4], bb->vec[5], bb->vec[6]);
- normal_tri_v3(clip[5], bb->vec[0], bb->vec[2], bb->vec[1]);
-
- /* then plane equations */
- for (val = 0; val < 6; val++) {
- clip[val][3] = -dot_v3v3(clip[val], bb->vec[val % 5]);
- }
-
- /* create bounding box */
- for (ar = sa->regionbase.first; ar; ar = ar->next) {
- if (ar->regiontype == RGN_TYPE_WINDOW) {
- RegionView3D *rv3d = ar->regiondata;
-
- if (rv3d->viewlock & RV3D_BOXCLIP) {
- rv3d->rflag |= RV3D_CLIPPING;
- memcpy(rv3d->clip, clip, sizeof(clip));
- if (rv3d->clipbb) MEM_freeN(rv3d->clipbb);
- rv3d->clipbb = MEM_dupallocN(bb);
- }
- }
- }
- MEM_freeN(bb);
-}
-
-/**
- * Find which axis values are shared between both views and copy to \a rv3d_dst
- * taking axis flipping into account.
- */
-static void view3d_boxview_sync_axis(RegionView3D *rv3d_dst, RegionView3D *rv3d_src)
-{
- /* absolute axis values above this are considered to be set (will be ~1.0f) */
- const float axis_eps = 0.5f;
- float viewinv[4];
-
- /* use the view rotation to identify which axis to sync on */
- float view_axis_all[4][3] = {
- {1.0f, 0.0f, 0.0f},
- {0.0f, 1.0f, 0.0f},
- {1.0f, 0.0f, 0.0f},
- {0.0f, 1.0f, 0.0f}};
-
- float *view_src_x = &view_axis_all[0][0];
- float *view_src_y = &view_axis_all[1][0];
-
- float *view_dst_x = &view_axis_all[2][0];
- float *view_dst_y = &view_axis_all[3][0];
- int i;
-
-
- /* we could use rv3d->viewinv, but better not depend on view matrix being updated */
- if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_src->view, viewinv) == false)) {
- return;
- }
- invert_qt_normalized(viewinv);
- mul_qt_v3(viewinv, view_src_x);
- mul_qt_v3(viewinv, view_src_y);
-
- if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_dst->view, viewinv) == false)) {
- return;
- }
- invert_qt_normalized(viewinv);
- mul_qt_v3(viewinv, view_dst_x);
- mul_qt_v3(viewinv, view_dst_y);
+/* -------------------------------------------------------------------- */
+/** \name Generic View Operator Properties
+ * \{ */
- /* check source and dest have a matching axis */
- for (i = 0; i < 3; i++) {
- if (((fabsf(view_src_x[i]) > axis_eps) || (fabsf(view_src_y[i]) > axis_eps)) &&
- ((fabsf(view_dst_x[i]) > axis_eps) || (fabsf(view_dst_y[i]) > axis_eps)))
- {
- rv3d_dst->ofs[i] = rv3d_src->ofs[i];
- }
- }
-}
+enum eV3D_OpPropFlag {
+ V3D_OP_PROP_MOUSE_CO = (1 << 0),
+ V3D_OP_PROP_DELTA = (1 << 1),
+ V3D_OP_PROP_USE_ALL_REGIONS = (1 << 2),
+ V3D_OP_PROP_USE_MOUSE_INIT = (1 << 3),
+};
-/* sync center/zoom view of region to others, for view transforms */
-static void view3d_boxview_sync(ScrArea *sa, ARegion *ar)
+static void view3d_operator_properties_common(wmOperatorType *ot, const enum eV3D_OpPropFlag flag)
{
- ARegion *artest;
- RegionView3D *rv3d = ar->regiondata;
- short clip = 0;
-
- for (artest = sa->regionbase.first; artest; artest = artest->next) {
- if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
- RegionView3D *rv3dtest = artest->regiondata;
-
- if (rv3dtest->viewlock & RV3D_LOCKED) {
- rv3dtest->dist = rv3d->dist;
- view3d_boxview_sync_axis(rv3dtest, rv3d);
- clip |= rv3dtest->viewlock & RV3D_BOXCLIP;
-
- ED_region_tag_redraw(artest);
- }
- }
+ if (flag & V3D_OP_PROP_MOUSE_CO) {
+ PropertyRNA *prop;
+ prop = RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Region Position X", "", 0, INT_MAX);
+ RNA_def_property_flag(prop, PROP_HIDDEN);
+ prop = RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Region Position Y", "", 0, INT_MAX);
+ RNA_def_property_flag(prop, PROP_HIDDEN);
}
-
- if (clip) {
- view3d_boxview_clip(sa);
+ if (flag & V3D_OP_PROP_DELTA) {
+ RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
}
-}
-
-/* for home, center etc */
-void view3d_boxview_copy(ScrArea *sa, ARegion *ar)
-{
- ARegion *artest;
- RegionView3D *rv3d = ar->regiondata;
- bool clip = false;
-
- for (artest = sa->regionbase.first; artest; artest = artest->next) {
- if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
- RegionView3D *rv3dtest = artest->regiondata;
-
- if (rv3dtest->viewlock) {
- rv3dtest->dist = rv3d->dist;
- copy_v3_v3(rv3dtest->ofs, rv3d->ofs);
- ED_region_tag_redraw(artest);
-
- clip |= ((rv3dtest->viewlock & RV3D_BOXCLIP) != 0);
- }
- }
+ if (flag & V3D_OP_PROP_USE_ALL_REGIONS) {
+ PropertyRNA *prop;
+ prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-
- if (clip) {
- view3d_boxview_clip(sa);
+ if (flag & V3D_OP_PROP_USE_MOUSE_INIT) {
+ /* Disable when view operators are initialized from buttons. */
+ PropertyRNA *prop;
+ prop = RNA_def_boolean(ot->srna, "use_mouse_init", true, "Mouse Init", "Use initial mouse position");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
}
}
-/* 'clip' is used to know if our clip setting has changed */
-void ED_view3d_quadview_update(ScrArea *sa, ARegion *ar, bool do_clip)
-{
- ARegion *ar_sync = NULL;
- RegionView3D *rv3d = ar->regiondata;
- short viewlock;
- /* this function copies flags from the first of the 3 other quadview
- * regions to the 2 other, so it assumes this is the region whose
- * properties are always being edited, weak */
- viewlock = rv3d->viewlock;
-
- if ((viewlock & RV3D_LOCKED) == 0) {
- do_clip = (viewlock & RV3D_BOXCLIP) != 0;
- viewlock = 0;
- }
- else if ((viewlock & RV3D_BOXVIEW) == 0 && (viewlock & RV3D_BOXCLIP) != 0) {
- do_clip = true;
- viewlock &= ~RV3D_BOXCLIP;
- }
-
- for (; ar; ar = ar->prev) {
- if (ar->alignment == RGN_ALIGN_QSPLIT) {
- rv3d = ar->regiondata;
- rv3d->viewlock = viewlock;
-
- if (do_clip && (viewlock & RV3D_BOXCLIP) == 0) {
- rv3d->rflag &= ~RV3D_BOXCLIP;
- }
-
- /* use ar_sync so we sync with one of the aligned views below
- * else the view jumps on changing view settings like 'clip'
- * since it copies from the perspective view */
- ar_sync = ar;
- }
- }
-
- if (rv3d->viewlock & RV3D_BOXVIEW) {
- view3d_boxview_sync(sa, ar_sync ? ar_sync : sa->regionbase.last);
- }
-
- /* ensure locked regions have an axis, locked user views don't make much sense */
- if (viewlock & RV3D_LOCKED) {
- int index_qsplit = 0;
- for (ar = sa->regionbase.first; ar; ar = ar->next) {
- if (ar->alignment == RGN_ALIGN_QSPLIT) {
- rv3d = ar->regiondata;
- if (rv3d->viewlock) {
- if (!RV3D_VIEW_IS_AXIS(rv3d->view)) {
- rv3d->view = ED_view3d_lock_view_from_index(index_qsplit);
- rv3d->persp = RV3D_ORTHO;
- ED_view3d_lock(rv3d);
- }
- }
- index_qsplit++;
- }
- }
- }
-
- ED_area_tag_redraw(sa);
-}
+/** \} */
-/* ************************** init for view ops **********************************/
+/* -------------------------------------------------------------------- */
+/** \name Generic View Operator Custom-Data
+ * \{ */
typedef struct ViewOpsData {
- /* context pointers (assigned by viewops_data_alloc) */
+ /** Context pointers (assigned by #viewops_data_alloc). */
Scene *scene;
ScrArea *sa;
ARegion *ar;
View3D *v3d;
RegionView3D *rv3d;
- /* needed for continuous zoom */
+ /** Needed for continuous zoom. */
wmTimer *timer;
- double timer_lastdraw;
- float oldquat[4];
- float viewquat[4]; /* working copy of rv3d->viewquat */
- float trackvec[3];
- float mousevec[3]; /* dolly only */
+ /** Viewport state on initialization, don't change afterwards. */
+ struct {
+ float dist;
+ float camzoom;
+ float quat[4];
+ /** #wmEvent.x, y. */
+ int event_xy[2];
+ /** Offset to use when #VIEWOPS_FLAG_USE_MOUSE_INIT is not set.
+ * so we can simulate pressing in the middle of the screen. */
+ int event_xy_offset[2];
+ /** #wmEvent.type that triggered the operator. */
+ int event_type;
+ float ofs[3];
+ /** Initial distance to 'ofs'. */
+ float zfac;
+
+ /** Trackball rotation only. */
+ float trackvec[3];
+ /** Dolly only. */
+ float mousevec[3];
+ } init;
+
+ /** Previous state (previous modal event handled). */
+ struct {
+ int event_xy[2];
+ /** For operators that use time-steps (continuous zoom). */
+ double time;
+ } prev;
+
+ /** Current state. */
+ struct {
+ /** Working copy of #RegionView3D.viewquat, needed for rotation calculation
+ * so we can apply snap to the view-port while keeping the unsnapped rotation
+ * here to use when snap is disabled and for continued calculation. */
+ float viewquat[4];
+ } curr;
+
float reverse;
- float dist_prev, camzoom_prev;
- float grid, far;
bool axis_snap; /* view rotate only */
- float zfac;
- /* use for orbit selection and auto-dist */
- float ofs[3], dyn_ofs[3];
+ /** Use for orbit selection and auto-dist. */
+ float dyn_ofs[3];
bool use_dyn_ofs;
-
- int origx, origy, oldx, oldy;
- int origkey; /* the key that triggered the operator */
-
} ViewOpsData;
#define TRACKBALLSIZE (1.1f)
-static void calctrackballvec(const rcti *rect, int mx, int my, float vec[3])
+static void calctrackballvec(const rcti *rect, const int event_xy[2], float vec[3])
{
const float radius = TRACKBALLSIZE;
const float t = radius / (float)M_SQRT2;
float x, y, z, d;
/* normalize x and y */
- x = BLI_rcti_cent_x(rect) - mx;
+ x = BLI_rcti_cent_x(rect) - event_xy[0];
x /= (float)(BLI_rcti_size_x(rect) / 4);
- y = BLI_rcti_cent_y(rect) - my;
+ y = BLI_rcti_cent_y(rect) - event_xy[1];
y /= (float)(BLI_rcti_size_y(rect) / 2);
d = sqrtf(x * x + y * y);
if (d < t) { /* Inside sphere */
@@ -575,13 +206,6 @@ static void calctrackballvec(const rcti *rect, int mx, int my, float vec[3])
vec[2] = -z; /* yah yah! */
}
-
-/* -------------------------------------------------------------------- */
-/* ViewOpsData */
-
-/** \name Generic View Operator Custom-Data.
- * \{ */
-
/**
* Allocate and fill in context pointers for #ViewOpsData
*/
@@ -599,7 +223,7 @@ static void viewops_data_alloc(bContext *C, wmOperator *op)
}
void view3d_orbit_apply_dyn_ofs(
- float r_ofs[3], const float ofs_old[3], const float viewquat_old[4],
+ float r_ofs[3], const float ofs_init[3], const float viewquat_old[4],
const float viewquat_new[4], const float dyn_ofs[3])
{
float q[4];
@@ -608,7 +232,7 @@ void view3d_orbit_apply_dyn_ofs(
invert_qt_normalized(q);
- sub_v3_v3v3(r_ofs, ofs_old, dyn_ofs);
+ sub_v3_v3v3(r_ofs, ofs_init, dyn_ofs);
mul_qt_v3(q, r_ofs);
add_v3_v3(r_ofs, dyn_ofs);
}
@@ -697,49 +321,118 @@ static bool view3d_orbit_calc_center(bContext *C, float r_dyn_ofs[3])
return is_set;
}
+enum eViewOpsFlag {
+ /** When enabled, rotate around the selection. */
+ VIEWOPS_FLAG_ORBIT_SELECT = (1 << 0),
+ /** When enabled, use the depth under the cursor for navigation. */
+ VIEWOPS_FLAG_DEPTH_NAVIGATE = (1 << 1),
+ /**
+ * When enabled run #ED_view3d_persp_ensure this may switch out of
+ * camera view when orbiting or switch from ortho to perspective when auto-persp is enabled.
+ * Some operations don't require this (view zoom/pan or ndof where subtle rotation is common
+ * so we don't want it to trigger auto-perspective). */
+ VIEWOPS_FLAG_PERSP_ENSURE = (1 << 2),
+ /** When set, ignore any options that depend on initial cursor location. */
+ VIEWOPS_FLAG_USE_MOUSE_INIT = (1 << 3),
+};
+
+static enum eViewOpsFlag viewops_flag_from_args(bool use_select, bool use_depth)
+{
+ enum eViewOpsFlag flag = 0;
+ if (use_select) {
+ flag |= VIEWOPS_FLAG_ORBIT_SELECT;
+ }
+ if (use_depth) {
+ flag |= VIEWOPS_FLAG_DEPTH_NAVIGATE;
+ }
+
+ return flag;
+}
+
+static enum eViewOpsFlag viewops_flag_from_prefs(void)
+{
+ return viewops_flag_from_args(
+ (U.uiflag & USER_ORBIT_SELECTION) != 0,
+ (U.uiflag & USER_DEPTH_NAVIGATE) != 0);
+}
+
/**
* Calculate the values for #ViewOpsData
*/
-static void viewops_data_create_ex(bContext *C, wmOperator *op, const wmEvent *event,
- const bool use_orbit_select,
- const bool use_orbit_zbuf)
+static void viewops_data_create(
+ bContext *C, wmOperator *op, const wmEvent *event,
+ enum eViewOpsFlag viewops_flag)
{
ViewOpsData *vod = op->customdata;
RegionView3D *rv3d = vod->rv3d;
+ /* Could do this more nicely. */
+ if ((viewops_flag & VIEWOPS_FLAG_USE_MOUSE_INIT) == 0) {
+ viewops_flag &= ~VIEWOPS_FLAG_DEPTH_NAVIGATE;
+ }
+
+ /* we need the depth info before changing any viewport options */
+ if (viewops_flag & VIEWOPS_FLAG_DEPTH_NAVIGATE) {
+ float fallback_depth_pt[3];
+
+ view3d_operator_needs_opengl(C); /* needed for zbuf drawing */
+
+ negate_v3_v3(fallback_depth_pt, rv3d->ofs);
+
+ vod->use_dyn_ofs = ED_view3d_autodist(
+ vod->scene, vod->ar, vod->v3d,
+ event->mval, vod->dyn_ofs, true, fallback_depth_pt);
+ }
+ else {
+ vod->use_dyn_ofs = false;
+ }
+
+ if (viewops_flag & VIEWOPS_FLAG_PERSP_ENSURE) {
+ if (ED_view3d_persp_ensure(vod->v3d, vod->ar)) {
+ /* If we're switching from camera view to the perspective one,
+ * need to tag viewport update, so camera vuew and borders
+ * are properly updated.
+ */
+ ED_region_tag_redraw(vod->ar);
+ }
+ }
+
/* set the view from the camera, if view locking is enabled.
* we may want to make this optional but for now its needed always */
ED_view3d_camera_lock_init(vod->v3d, vod->rv3d);
- vod->dist_prev = rv3d->dist;
- vod->camzoom_prev = rv3d->camzoom;
- copy_qt_qt(vod->viewquat, rv3d->viewquat);
- copy_qt_qt(vod->oldquat, rv3d->viewquat);
- vod->origx = vod->oldx = event->x;
- vod->origy = vod->oldy = event->y;
- vod->origkey = event->type; /* the key that triggered the operator. */
- vod->use_dyn_ofs = false;
- copy_v3_v3(vod->ofs, rv3d->ofs);
+ vod->init.dist = rv3d->dist;
+ vod->init.camzoom = rv3d->camzoom;
+ copy_qt_qt(vod->init.quat, rv3d->viewquat);
+ vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
+ vod->init.event_xy[1] = vod->prev.event_xy[1] = event->y;
- if (use_orbit_select) {
+ if (viewops_flag & VIEWOPS_FLAG_USE_MOUSE_INIT) {
+ vod->init.event_xy_offset[0] = 0;
+ vod->init.event_xy_offset[1] = 0;
+ }
+ else {
+ /* Simulate the event starting in the middle of the region. */
+ vod->init.event_xy_offset[0] = BLI_rcti_cent_x(&vod->ar->winrct) - event->x;
+ vod->init.event_xy_offset[1] = BLI_rcti_cent_y(&vod->ar->winrct) - event->y;
+ }
- vod->use_dyn_ofs = true;
+ vod->init.event_type = event->type;
+ copy_v3_v3(vod->init.ofs, rv3d->ofs);
- view3d_orbit_calc_center(C, vod->dyn_ofs);
+ copy_qt_qt(vod->curr.viewquat, rv3d->viewquat);
- negate_v3(vod->dyn_ofs);
+ if (viewops_flag & VIEWOPS_FLAG_ORBIT_SELECT) {
+ float ofs[3];
+ if (view3d_orbit_calc_center(C, ofs) || (vod->use_dyn_ofs == false)) {
+ vod->use_dyn_ofs = true;
+ negate_v3_v3(vod->dyn_ofs, ofs);
+ viewops_flag &= ~VIEWOPS_FLAG_DEPTH_NAVIGATE;
+ }
}
- else if (use_orbit_zbuf) {
- Scene *scene = CTX_data_scene(C);
- float fallback_depth_pt[3];
- view3d_operator_needs_opengl(C); /* needed for zbuf drawing */
-
- negate_v3_v3(fallback_depth_pt, rv3d->ofs);
-
- if ((vod->use_dyn_ofs = ED_view3d_autodist(scene, vod->ar, vod->v3d,
- event->mval, vod->dyn_ofs, true, fallback_depth_pt)))
- {
+ if (viewops_flag & VIEWOPS_FLAG_DEPTH_NAVIGATE) {
+ if (vod->use_dyn_ofs) {
if (rv3d->is_persp) {
float my_origin[3]; /* original G.vd->ofs */
float my_pivot[3]; /* view */
@@ -765,7 +458,7 @@ static void viewops_data_create_ex(bContext *C, wmOperator *op, const wmEvent *e
/* find a new ofs value that is along the view axis (rather than the mouse location) */
closest_to_line_v3(dvec, vod->dyn_ofs, my_pivot, my_origin);
- vod->dist_prev = rv3d->dist = len_v3v3(my_pivot, dvec);
+ vod->init.dist = rv3d->dist = len_v3v3(my_pivot, dvec);
negate_v3_v3(rv3d->ofs, dvec);
}
@@ -778,27 +471,26 @@ static void viewops_data_create_ex(bContext *C, wmOperator *op, const wmEvent *e
negate_v3(rv3d->ofs);
}
negate_v3(vod->dyn_ofs);
- copy_v3_v3(vod->ofs, rv3d->ofs);
+ copy_v3_v3(vod->init.ofs, rv3d->ofs);
}
}
+ /* For dolly */
+ ED_view3d_win_to_vector(vod->ar, (const float[2]){UNPACK2(event->mval)}, vod->init.mousevec);
+
{
- /* for dolly */
- const float mval_f[2] = {(float)event->mval[0],
- (float)event->mval[1]};
- ED_view3d_win_to_vector(vod->ar, mval_f, vod->mousevec);
+ const int event_xy_offset[2] = {
+ event->x + vod->init.event_xy_offset[0],
+ event->y + vod->init.event_xy_offset[1],
+ };
+ /* For rotation with trackball rotation. */
+ calctrackballvec(&vod->ar->winrct, event_xy_offset, vod->init.trackvec);
}
- /* lookup, we don't pass on v3d to prevent confusement */
- vod->grid = vod->v3d->grid;
- vod->far = vod->v3d->far;
-
- calctrackballvec(&vod->ar->winrct, event->x, event->y, vod->trackvec);
-
{
float tvec[3];
negate_v3_v3(tvec, rv3d->ofs);
- vod->zfac = ED_view3d_calc_zfac(rv3d, tvec, NULL);
+ vod->init.zfac = ED_view3d_calc_zfac(rv3d, tvec, NULL);
}
vod->reverse = 1.0f;
@@ -808,14 +500,6 @@ static void viewops_data_create_ex(bContext *C, wmOperator *op, const wmEvent *e
rv3d->rflag |= RV3D_NAVIGATING;
}
-static void viewops_data_create(bContext *C, wmOperator *op, const wmEvent *event)
-{
- viewops_data_create_ex(
- C, op, event,
- (U.uiflag & USER_ORBIT_SELECTION) != 0,
- (U.uiflag & USER_ZBUF_ORBIT) != 0);
-}
-
static void viewops_data_free(bContext *C, wmOperator *op)
{
ARegion *ar;
@@ -839,10 +523,12 @@ static void viewops_data_free(bContext *C, wmOperator *op)
if (p && (p->flags & PAINT_FAST_NAVIGATE))
ED_region_tag_redraw(ar);
}
-/** \} */
+/** \} */
-/* ************************** viewrotate **********************************/
+/* -------------------------------------------------------------------- */
+/** \name View Rotate Operator
+ * \{ */
enum {
VIEW_PASS = 0,
@@ -851,22 +537,24 @@ enum {
};
/* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
-#define VIEW_MODAL_CONFIRM 1 /* used for all view operations */
-#define VIEWROT_MODAL_AXIS_SNAP_ENABLE 2
-#define VIEWROT_MODAL_AXIS_SNAP_DISABLE 3
-#define VIEWROT_MODAL_SWITCH_ZOOM 4
-#define VIEWROT_MODAL_SWITCH_MOVE 5
-#define VIEWROT_MODAL_SWITCH_ROTATE 6
+enum {
+ VIEW_MODAL_CONFIRM = 1, /* used for all view operations */
+ VIEWROT_MODAL_AXIS_SNAP_ENABLE = 2,
+ VIEWROT_MODAL_AXIS_SNAP_DISABLE = 3,
+ VIEWROT_MODAL_SWITCH_ZOOM = 4,
+ VIEWROT_MODAL_SWITCH_MOVE = 5,
+ VIEWROT_MODAL_SWITCH_ROTATE = 6,
+};
/* called in transform_ops.c, on each regeneration of keymaps */
void viewrotate_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
{VIEWROT_MODAL_AXIS_SNAP_ENABLE, "AXIS_SNAP_ENABLE", 0, "Enable Axis Snap", ""},
{VIEWROT_MODAL_AXIS_SNAP_DISABLE, "AXIS_SNAP_DISABLE", 0, "Disable Axis Snap", ""},
-
+
{VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
{VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
@@ -893,17 +581,16 @@ void viewrotate_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
#endif
-
+
/* assign map to operators */
WM_modalkeymap_assign(keymap, "VIEW3D_OT_rotate");
-
}
static void viewrotate_apply_dyn_ofs(ViewOpsData *vod, const float viewquat_new[4])
{
if (vod->use_dyn_ofs) {
RegionView3D *rv3d = vod->rv3d;
- view3d_orbit_apply_dyn_ofs(rv3d->ofs, vod->ofs, vod->oldquat, viewquat_new, vod->dyn_ofs);
+ view3d_orbit_apply_dyn_ofs(rv3d->ofs, vod->init.ofs, vod->init.quat, viewquat_new, vod->dyn_ofs);
}
}
@@ -919,7 +606,7 @@ static void viewrotate_apply_snap(ViewOpsData *vod)
int x, y, z;
bool found = false;
- invert_qt_qt_normalized(viewquat_inv, vod->viewquat);
+ invert_qt_qt_normalized(viewquat_inv, vod->curr.viewquat);
mul_qt_v3(viewquat_inv, zaxis);
normalize_v3(zaxis);
@@ -955,7 +642,7 @@ static void viewrotate_apply_snap(ViewOpsData *vod)
* for testing roll */
rotation_between_vecs_to_quat(viewquat_align, zaxis_best, zaxis);
normalize_qt(viewquat_align);
- mul_qt_qtqt(viewquat_align, vod->viewquat, viewquat_align);
+ mul_qt_qtqt(viewquat_align, vod->curr.viewquat, viewquat_align);
normalize_qt(viewquat_align);
invert_qt_qt_normalized(viewquat_align_inv, viewquat_align);
@@ -1009,7 +696,7 @@ static void viewrotate_apply_snap(ViewOpsData *vod)
}
}
-static void viewrotate_apply(ViewOpsData *vod, int x, int y)
+static void viewrotate_apply(ViewOpsData *vod, const int event_xy[2])
{
RegionView3D *rv3d = vod->rv3d;
@@ -1019,9 +706,15 @@ static void viewrotate_apply(ViewOpsData *vod, int x, int y)
float axis[3], q1[4], dvec[3], newvec[3];
float angle;
- calctrackballvec(&vod->ar->winrct, x, y, newvec);
+ {
+ const int event_xy_offset[2] = {
+ event_xy[0] + vod->init.event_xy_offset[0],
+ event_xy[1] + vod->init.event_xy_offset[1],
+ };
+ calctrackballvec(&vod->ar->winrct, event_xy_offset, newvec);
+ }
- sub_v3_v3v3(dvec, newvec, vod->trackvec);
+ sub_v3_v3v3(dvec, newvec, vod->init.trackvec);
angle = (len_v3(dvec) / (2.0f * TRACKBALLSIZE)) * (float)M_PI;
@@ -1032,12 +725,12 @@ static void viewrotate_apply(ViewOpsData *vod, int x, int y)
* so that the angle of rotation is linearly proportional to
* the distance that the mouse is dragged. */
- cross_v3_v3v3(axis, vod->trackvec, newvec);
+ cross_v3_v3v3(axis, vod->init.trackvec, newvec);
axis_angle_to_quat(q1, axis, angle);
- mul_qt_qtqt(vod->viewquat, q1, vod->oldquat);
+ mul_qt_qtqt(vod->curr.viewquat, q1, vod->init.quat);
- viewrotate_apply_dyn_ofs(vod, vod->viewquat);
+ viewrotate_apply_dyn_ofs(vod, vod->curr.viewquat);
}
else {
/* New turntable view code by John Aughey */
@@ -1054,7 +747,7 @@ static void viewrotate_apply(ViewOpsData *vod, int x, int y)
const float sensitivity = 0.007f;
/* Get the 3x3 matrix and its inverse from the quaternion */
- quat_to_mat3(m, vod->viewquat);
+ quat_to_mat3(m, vod->curr.viewquat);
invert_m3_m3(m_inv, m);
/* avoid gimble lock */
@@ -1081,30 +774,30 @@ static void viewrotate_apply(ViewOpsData *vod, int x, int y)
/* This can likely be computed directly from the quaternion. */
/* Perform the up/down rotation */
- axis_angle_to_quat(quat_local_x, xaxis, sensitivity * -(y - vod->oldy));
- mul_qt_qtqt(quat_local_x, vod->viewquat, quat_local_x);
+ axis_angle_to_quat(quat_local_x, xaxis, sensitivity * -(event_xy[1] - vod->prev.event_xy[1]));
+ mul_qt_qtqt(quat_local_x, vod->curr.viewquat, quat_local_x);
/* Perform the orbital rotation */
- axis_angle_to_quat_single(quat_global_z, 'Z', sensitivity * vod->reverse * (x - vod->oldx));
- mul_qt_qtqt(vod->viewquat, quat_local_x, quat_global_z);
+ axis_angle_to_quat_single(quat_global_z, 'Z', sensitivity * vod->reverse * (event_xy[0] - vod->prev.event_xy[0]));
+ mul_qt_qtqt(vod->curr.viewquat, quat_local_x, quat_global_z);
- viewrotate_apply_dyn_ofs(vod, vod->viewquat);
+ viewrotate_apply_dyn_ofs(vod, vod->curr.viewquat);
}
/* avoid precision loss over time */
- normalize_qt(vod->viewquat);
+ normalize_qt(vod->curr.viewquat);
/* use a working copy so view rotation locking doesnt overwrite the locked
* rotation back into the view we calculate with */
- copy_qt_qt(rv3d->viewquat, vod->viewquat);
+ copy_qt_qt(rv3d->viewquat, vod->curr.viewquat);
/* check for view snap,
* note: don't apply snap to vod->viewquat so the view wont jam up */
if (vod->axis_snap) {
viewrotate_apply_snap(vod);
}
- vod->oldx = x;
- vod->oldy = y;
+ vod->prev.event_xy[0] = event_xy[0];
+ vod->prev.event_xy[1] = event_xy[1];
ED_view3d_camera_lock_sync(vod->v3d, rv3d);
@@ -1145,12 +838,12 @@ static int viewrotate_modal(bContext *C, wmOperator *op, const wmEvent *event)
break;
}
}
- else if (event->type == vod->origkey && event->val == KM_RELEASE) {
+ else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
event_code = VIEW_CONFIRM;
}
if (event_code == VIEW_APPLY) {
- viewrotate_apply(vod, event->x, event->y);
+ viewrotate_apply(vod, &event->x);
if (ED_screen_animation_playing(CTX_wm_manager(C))) {
use_autokey = true;
}
@@ -1172,41 +865,12 @@ static int viewrotate_modal(bContext *C, wmOperator *op, const wmEvent *event)
return ret;
}
-/**
- * Action to take when rotating the view,
- * handle auto-persp and logic for switching out of views.
- *
- * shared with NDOF.
- */
-static bool view3d_ensure_persp(struct View3D *v3d, ARegion *ar)
-{
- RegionView3D *rv3d = ar->regiondata;
- const bool autopersp = (U.uiflag & USER_AUTOPERSP) != 0;
-
- BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
-
- if (ED_view3d_camera_lock_check(v3d, rv3d))
- return false;
-
- if (rv3d->persp != RV3D_PERSP) {
- if (rv3d->persp == RV3D_CAMOB) {
- /* If autopersp and previous view was an axis one, switch back to PERSP mode, else reuse previous mode. */
- char persp = (autopersp && RV3D_VIEW_IS_AXIS(rv3d->lview)) ? RV3D_PERSP : rv3d->lpersp;
- view3d_persp_switch_from_camera(v3d, rv3d, persp);
- }
- else if (autopersp && RV3D_VIEW_IS_AXIS(rv3d->view)) {
- rv3d->persp = RV3D_PERSP;
- }
- return true;
- }
-
- return false;
-}
-
static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
ViewOpsData *vod;
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+
/* makes op->customdata */
viewops_data_alloc(C, op);
vod = op->customdata;
@@ -1219,38 +883,33 @@ static int viewrotate_invoke(bContext *C, wmOperator *op, const wmEvent *event)
ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
- /* switch from camera view when: */
- if (view3d_ensure_persp(vod->v3d, vod->ar)) {
- /* If we're switching from camera view to the perspective one,
- * need to tag viewport update, so camera vuew and borders
- * are properly updated.
- */
- ED_region_tag_redraw(vod->ar);
- }
-
- viewops_data_create(C, op, event);
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_prefs() |
+ VIEWOPS_FLAG_PERSP_ENSURE |
+ (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
if (ELEM(event->type, MOUSEPAN, MOUSEROTATE)) {
/* Rotate direction we keep always same */
- int x, y;
+ int event_xy[2];
if (event->type == MOUSEPAN) {
if (U.uiflag2 & USER_TRACKPAD_NATURAL) {
- x = 2 * event->x - event->prevx;
- y = 2 * event->y - event->prevy;
+ event_xy[0] = 2 * event->x - event->prevx;
+ event_xy[1] = 2 * event->y - event->prevy;
}
else {
- x = event->prevx;
- y = event->prevy;
+ event_xy[0] = event->prevx;
+ event_xy[1] = event->prevy;
}
}
else {
/* MOUSEROTATE performs orbital rotation, so y axis delta is set to 0 */
- x = event->prevx;
- y = event->y;
+ event_xy[0] = event->prevx;
+ event_xy[1] = event->y;
}
- viewrotate_apply(vod, x, y);
+ viewrotate_apply(vod, event_xy);
ED_view3d_depth_tag_update(vod->rv3d);
viewops_data_free(C, op);
@@ -1313,13 +972,17 @@ void VIEW3D_OT_rotate(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
+
+ view3d_operator_properties_common(ot, V3D_OP_PROP_USE_MOUSE_INIT);
}
-#ifdef WITH_INPUT_NDOF
+/** \} */
+/* -------------------------------------------------------------------- */
/** \name NDOF Utility Functions
* \{ */
+#ifdef WITH_INPUT_NDOF
#define NDOF_HAS_TRANSLATE ((!ED_view3d_offset_lock_check(v3d, rv3d)) && !is_zero_v3(ndof->tvec))
#define NDOF_HAS_ROTATE (((rv3d->viewlock & RV3D_LOCKED) == 0) && !is_zero_v3(ndof->rvec))
@@ -1369,8 +1032,9 @@ static float view3d_ndof_pan_speed_calc(RegionView3D *rv3d)
*
* \param has_zoom zoom, otherwise dolly, often `!rv3d->is_persp` since it doesnt make sense to dolly in ortho.
*/
-static void view3d_ndof_pan_zoom(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
- const bool has_translate, const bool has_zoom)
+static void view3d_ndof_pan_zoom(
+ const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
+ const bool has_translate, const bool has_zoom)
{
RegionView3D *rv3d = ar->regiondata;
float view_inv[4];
@@ -1431,9 +1095,10 @@ static void view3d_ndof_pan_zoom(const struct wmNDOFMotionData *ndof, ScrArea *s
}
-static void view3d_ndof_orbit(const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
- /* optional, can be NULL*/
- ViewOpsData *vod)
+static void view3d_ndof_orbit(
+ const struct wmNDOFMotionData *ndof, ScrArea *sa, ARegion *ar,
+ /* optional, can be NULL*/
+ ViewOpsData *vod)
{
View3D *v3d = sa->spacedata.first;
RegionView3D *rv3d = ar->regiondata;
@@ -1442,7 +1107,7 @@ static void view3d_ndof_orbit(const struct wmNDOFMotionData *ndof, ScrArea *sa,
BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
- view3d_ensure_persp(v3d, ar);
+ ED_view3d_persp_ensure(v3d, ar);
rv3d->view = RV3D_VIEW_USER;
@@ -1477,7 +1142,6 @@ static void view3d_ndof_orbit(const struct wmNDOFMotionData *ndof, ScrArea *sa,
axis_angle_to_quat_single(quat, 'Z', angle);
mul_qt_qtqt(rv3d->viewquat, rv3d->viewquat, quat);
-
}
else {
float quat[4];
@@ -1618,14 +1282,16 @@ void view3d_ndof_fly(
/** \} */
+/* -------------------------------------------------------------------- */
+/** \name NDOF Operators
+ *
+ * - "orbit" navigation (trackball/turntable)
+ * - zooming
+ * - panning in rotationally-locked views
+ * \{ */
-/* -- "orbit" navigation (trackball/turntable)
- * -- zooming
- * -- panning in rotationally-locked views
- */
static int ndof_orbit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
-
if (event->type != NDOF_MOTION) {
return OPERATOR_CANCELLED;
}
@@ -1637,8 +1303,9 @@ static int ndof_orbit_invoke(bContext *C, wmOperator *op, const wmEvent *event)
const wmNDOFMotionData *ndof = event->customdata;
viewops_data_alloc(C, op);
- viewops_data_create_ex(C, op, event,
- (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_args((U.uiflag & USER_ORBIT_SELECTION) != 0, false));
vod = op->customdata;
ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
@@ -1693,7 +1360,6 @@ void VIEW3D_OT_ndof_orbit(struct wmOperatorType *ot)
static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
-
if (event->type != NDOF_MOTION) {
return OPERATOR_CANCELLED;
}
@@ -1705,8 +1371,9 @@ static int ndof_orbit_zoom_invoke(bContext *C, wmOperator *op, const wmEvent *ev
const wmNDOFMotionData *ndof = event->customdata;
viewops_data_alloc(C, op);
- viewops_data_create_ex(C, op, event,
- (U.uiflag & USER_ORBIT_SELECTION) != 0, false);
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_args((U.uiflag & USER_ORBIT_SELECTION) != 0, false));
vod = op->customdata;
@@ -1884,17 +1551,20 @@ void VIEW3D_OT_ndof_all(struct wmOperatorType *ot)
#endif /* WITH_INPUT_NDOF */
-/* ************************ viewmove ******************************** */
+/** \} */
+/* -------------------------------------------------------------------- */
+/** \name View Move (Pan) Operator
+ * \{ */
/* NOTE: these defines are saved in keymap files, do not change values but just add new ones */
/* called in transform_ops.c, on each regeneration of keymaps */
void viewmove_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
-
+
{VIEWROT_MODAL_SWITCH_ZOOM, "SWITCH_TO_ZOOM", 0, "Switch to Zoom"},
{VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
@@ -1918,7 +1588,7 @@ void viewmove_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ZOOM);
WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
#endif
-
+
/* assign map to operators */
WM_modalkeymap_assign(keymap, "VIEW3D_OT_move");
}
@@ -1927,13 +1597,13 @@ void viewmove_modal_keymap(wmKeyConfig *keyconf)
static void viewmove_apply(ViewOpsData *vod, int x, int y)
{
if (ED_view3d_offset_lock_check(vod->v3d, vod->rv3d)) {
- vod->rv3d->ofs_lock[0] -= ((vod->oldx - x) * 2.0f) / (float)vod->ar->winx;
- vod->rv3d->ofs_lock[1] -= ((vod->oldy - y) * 2.0f) / (float)vod->ar->winy;
+ vod->rv3d->ofs_lock[0] -= ((vod->prev.event_xy[0] - x) * 2.0f) / (float)vod->ar->winx;
+ vod->rv3d->ofs_lock[1] -= ((vod->prev.event_xy[1] - y) * 2.0f) / (float)vod->ar->winy;
}
else if ((vod->rv3d->persp == RV3D_CAMOB) && !ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) {
const float zoomfac = BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
- vod->rv3d->camdx += (vod->oldx - x) / (vod->ar->winx * zoomfac);
- vod->rv3d->camdy += (vod->oldy - y) / (vod->ar->winy * zoomfac);
+ vod->rv3d->camdx += (vod->prev.event_xy[0] - x) / (vod->ar->winx * zoomfac);
+ vod->rv3d->camdy += (vod->prev.event_xy[1] - y) / (vod->ar->winy * zoomfac);
CLAMP(vod->rv3d->camdx, -1.0f, 1.0f);
CLAMP(vod->rv3d->camdy, -1.0f, 1.0f);
}
@@ -1941,18 +1611,19 @@ static void viewmove_apply(ViewOpsData *vod, int x, int y)
float dvec[3];
float mval_f[2];
- mval_f[0] = x - vod->oldx;
- mval_f[1] = y - vod->oldy;
- ED_view3d_win_to_delta(vod->ar, mval_f, dvec, vod->zfac);
+ mval_f[0] = x - vod->prev.event_xy[0];
+ mval_f[1] = y - vod->prev.event_xy[1];
+ ED_view3d_win_to_delta(vod->ar, mval_f, dvec, vod->init.zfac);
add_v3_v3(vod->rv3d->ofs, dvec);
- if (vod->rv3d->viewlock & RV3D_BOXVIEW)
+ if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(vod->sa, vod->ar);
+ }
}
- vod->oldx = x;
- vod->oldy = y;
+ vod->prev.event_xy[0] = x;
+ vod->prev.event_xy[1] = y;
ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
@@ -1987,7 +1658,7 @@ static int viewmove_modal(bContext *C, wmOperator *op, const wmEvent *event)
break;
}
}
- else if (event->type == vod->origkey && event->val == KM_RELEASE) {
+ else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
event_code = VIEW_CONFIRM;
}
@@ -2018,9 +1689,14 @@ static int viewmove_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
ViewOpsData *vod;
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+
/* makes op->customdata */
viewops_data_alloc(C, op);
- viewops_data_create(C, op, event);
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_prefs() |
+ (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
vod = op->customdata;
ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
@@ -2029,9 +1705,9 @@ static int viewmove_invoke(bContext *C, wmOperator *op, const wmEvent *event)
/* invert it, trackpad scroll follows same principle as 2d windows this way */
viewmove_apply(vod, 2 * event->x - event->prevx, 2 * event->y - event->prevy);
ED_view3d_depth_tag_update(vod->rv3d);
-
+
viewops_data_free(C, op);
-
+
return OPERATOR_FINISHED;
}
else {
@@ -2063,17 +1739,24 @@ void VIEW3D_OT_move(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
+
+ /* properties */
+ view3d_operator_properties_common(ot, V3D_OP_PROP_USE_MOUSE_INIT);
}
-/* ************************ viewzoom ******************************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Zoom Operator
+ * \{ */
/* viewdolly_modal_keymap has an exact copy of this, apply fixes to both */
/* called in transform_ops.c, on each regeneration of keymaps */
void viewzoom_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
-
+
{VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
{VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
@@ -2097,14 +1780,17 @@ void viewzoom_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
#endif
-
+
/* assign map to operators */
WM_modalkeymap_assign(keymap, "VIEW3D_OT_zoom");
}
-static void view_zoom_mouseloc_camera(
+/**
+ * \param zoom_xy: Optionally zoom to window location (coords compatible w/ #wmEvent.x, y). Use when not NULL.
+ */
+static void view_zoom_to_window_xy_camera(
Scene *scene, View3D *v3d,
- ARegion *ar, float dfac, int mx, int my)
+ ARegion *ar, float dfac, const int zoom_xy[2])
{
RegionView3D *rv3d = ar->regiondata;
const float zoomfac = BKE_screen_view3d_zoom_to_fac(rv3d->camzoom);
@@ -2112,12 +1798,12 @@ static void view_zoom_mouseloc_camera(
const float camzoom_new = BKE_screen_view3d_zoom_from_fac(zoomfac_new);
- if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
+ if (zoom_xy != NULL) {
float zoomfac_px;
rctf camera_frame_old;
rctf camera_frame_new;
- const float pt_src[2] = {mx, my};
+ const float pt_src[2] = {zoom_xy[0], zoom_xy[1]};
float pt_dst[2];
float delta_px[2];
@@ -2148,12 +1834,15 @@ static void view_zoom_mouseloc_camera(
}
}
-static void view_zoom_mouseloc_3d(ARegion *ar, float dfac, int mx, int my)
+/**
+ * \param zoom_xy: Optionally zoom to window location (coords compatible w/ #wmEvent.x, y). Use when not NULL.
+ */
+static void view_zoom_to_window_xy_3d(ARegion *ar, float dfac, const int zoom_xy[2])
{
RegionView3D *rv3d = ar->regiondata;
const float dist_new = rv3d->dist * dfac;
- if (U.uiflag & USER_ZOOM_TO_MOUSEPOS) {
+ if (zoom_xy != NULL) {
float dvec[3];
float tvec[3];
float tpos[3];
@@ -2163,8 +1852,8 @@ static void view_zoom_mouseloc_3d(ARegion *ar, float dfac, int mx, int my)
negate_v3_v3(tpos, rv3d->ofs);
- mval_f[0] = (float)(((mx - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
- mval_f[1] = (float)(((my - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
+ mval_f[0] = (float)(((zoom_xy[0] - ar->winrct.xmin) * 2) - ar->winx) / 2.0f;
+ mval_f[1] = (float)(((zoom_xy[1] - ar->winrct.ymin) * 2) - ar->winy) / 2.0f;
/* Project cursor position into 3D space */
zfac = ED_view3d_calc_zfac(rv3d, tpos, NULL);
@@ -2190,7 +1879,7 @@ static float viewzoom_scale_value(
const rcti *winrct,
const short viewzoom,
const bool zoom_invert, const bool zoom_invert_force,
- const int xy[2], const int xy_orig[2],
+ const int xy_curr[2], const int xy_init[2],
const float val, const float val_orig,
double *r_timer_lastdraw)
{
@@ -2202,10 +1891,10 @@ static float viewzoom_scale_value(
float fac;
if (U.uiflag & USER_ZOOM_HORIZ) {
- fac = (float)(xy_orig[0] - xy[0]);
+ fac = (float)(xy_init[0] - xy_curr[0]);
}
else {
- fac = (float)(xy_orig[1] - xy[1]);
+ fac = (float)(xy_init[1] - xy_curr[1]);
}
if (zoom_invert != zoom_invert_force) {
@@ -2223,8 +1912,8 @@ static float viewzoom_scale_value(
BLI_rcti_cent_x(winrct),
BLI_rcti_cent_y(winrct),
};
- float len_new = 5 + len_v2v2_int(ctr, xy);
- float len_old = 5 + len_v2v2_int(ctr, xy_orig);
+ float len_new = 5 + len_v2v2_int(ctr, xy_curr);
+ float len_old = 5 + len_v2v2_int(ctr, xy_init);
/* intentionally ignore 'zoom_invert' for scale */
if (zoom_invert_force) {
@@ -2238,12 +1927,12 @@ static float viewzoom_scale_value(
float len_old = 5;
if (U.uiflag & USER_ZOOM_HORIZ) {
- len_new += (winrct->xmax - xy[0]);
- len_old += (winrct->xmax - xy_orig[0]);
+ len_new += (winrct->xmax - (xy_curr[0]));
+ len_old += (winrct->xmax - (xy_init[0]));
}
else {
- len_new += (winrct->ymax - xy[1]);
- len_old += (winrct->ymax - xy_orig[1]);
+ len_new += (winrct->ymax - (xy_curr[1]));
+ len_old += (winrct->ymax - (xy_init[1]));
}
if (zoom_invert != zoom_invert_force) {
@@ -2257,25 +1946,48 @@ static float viewzoom_scale_value(
return zfac;
}
+static float viewzoom_scale_value_offset(
+ const rcti *winrct,
+ const short viewzoom,
+ const bool zoom_invert, const bool zoom_invert_force,
+ const int xy_curr[2], const int xy_init[2], const int xy_offset[2],
+ const float val, const float val_orig,
+ double *r_timer_lastdraw)
+{
+ const int xy_curr_offset[2] = {
+ xy_curr[0] + xy_offset[0],
+ xy_curr[1] + xy_offset[1],
+ };
+ const int xy_init_offset[2] = {
+ xy_init[0] + xy_offset[0],
+ xy_init[1] + xy_offset[1],
+ };
+ return viewzoom_scale_value(
+ winrct, viewzoom, zoom_invert, zoom_invert_force,
+ xy_curr_offset, xy_init_offset,
+ val, val_orig, r_timer_lastdraw);
+}
+
static void viewzoom_apply_camera(
ViewOpsData *vod, const int xy[2],
- const short viewzoom, const bool zoom_invert)
+ const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
{
float zfac;
- float zoomfac_prev = BKE_screen_view3d_zoom_to_fac(vod->camzoom_prev) * 2.0f;
+ float zoomfac_prev = BKE_screen_view3d_zoom_to_fac(vod->init.camzoom) * 2.0f;
float zoomfac = BKE_screen_view3d_zoom_to_fac(vod->rv3d->camzoom) * 2.0f;
- zfac = viewzoom_scale_value(
- &vod->ar->winrct, viewzoom, zoom_invert, true, xy, &vod->origx,
+ zfac = viewzoom_scale_value_offset(
+ &vod->ar->winrct, viewzoom, zoom_invert, true,
+ xy, vod->init.event_xy, vod->init.event_xy_offset,
zoomfac, zoomfac_prev,
- &vod->timer_lastdraw);
+ &vod->prev.time);
if (zfac != 1.0f && zfac != 0.0f) {
/* calculate inverted, then invert again (needed because of camera zoom scaling) */
zfac = 1.0f / zfac;
- view_zoom_mouseloc_camera(
+ view_zoom_to_window_xy_camera(
vod->scene, vod->v3d,
- vod->ar, zfac, vod->oldx, vod->oldy);
+ vod->ar, zfac, zoom_to_pos ? vod->prev.event_xy : NULL);
}
ED_region_tag_redraw(vod->ar);
@@ -2283,32 +1995,34 @@ static void viewzoom_apply_camera(
static void viewzoom_apply_3d(
ViewOpsData *vod, const int xy[2],
- const short viewzoom, const bool zoom_invert)
+ const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
{
float zfac;
float dist_range[2];
ED_view3d_dist_range_get(vod->v3d, dist_range);
- zfac = viewzoom_scale_value(
- &vod->ar->winrct, viewzoom, zoom_invert, false, xy, &vod->origx,
- vod->rv3d->dist, vod->dist_prev,
- &vod->timer_lastdraw);
+ zfac = viewzoom_scale_value_offset(
+ &vod->ar->winrct, viewzoom, zoom_invert, false,
+ xy, vod->init.event_xy, vod->init.event_xy_offset,
+ vod->rv3d->dist, vod->init.dist,
+ &vod->prev.time);
if (zfac != 1.0f) {
const float zfac_min = dist_range[0] / vod->rv3d->dist;
const float zfac_max = dist_range[1] / vod->rv3d->dist;
CLAMP(zfac, zfac_min, zfac_max);
- view_zoom_mouseloc_3d(
- vod->ar, zfac, vod->oldx, vod->oldy);
+ view_zoom_to_window_xy_3d(
+ vod->ar, zfac, zoom_to_pos ? vod->prev.event_xy : NULL);
}
/* these limits were in old code too */
CLAMP(vod->rv3d->dist, dist_range[0], dist_range[1]);
- if (vod->rv3d->viewlock & RV3D_BOXVIEW)
+ if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(vod->sa, vod->ar);
+ }
ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
@@ -2317,15 +2031,15 @@ static void viewzoom_apply_3d(
static void viewzoom_apply(
ViewOpsData *vod, const int xy[2],
- const short viewzoom, const bool zoom_invert)
+ const short viewzoom, const bool zoom_invert, const bool zoom_to_pos)
{
if ((vod->rv3d->persp == RV3D_CAMOB) &&
(vod->rv3d->is_persp && ED_view3d_camera_lock_check(vod->v3d, vod->rv3d)) == 0)
{
- viewzoom_apply_camera(vod, xy, viewzoom, zoom_invert);
+ viewzoom_apply_camera(vod, xy, viewzoom, zoom_invert, zoom_to_pos);
}
else {
- viewzoom_apply_3d(vod, xy, viewzoom, zoom_invert);
+ viewzoom_apply_3d(vod, xy, viewzoom, zoom_invert, zoom_to_pos);
}
}
@@ -2359,12 +2073,16 @@ static int viewzoom_modal(bContext *C, wmOperator *op, const wmEvent *event)
break;
}
}
- else if (event->type == vod->origkey && event->val == KM_RELEASE) {
+ else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
event_code = VIEW_CONFIRM;
}
if (event_code == VIEW_APPLY) {
- viewzoom_apply(vod, &event->x, U.viewzoom, (U.uiflag & USER_ZOOM_INVERT) != 0);
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+ viewzoom_apply(
+ vod, &event->x, U.viewzoom,
+ (U.uiflag & USER_ZOOM_INVERT) != 0,
+ (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)));
if (ED_screen_animation_playing(CTX_wm_manager(C))) {
use_autokey = true;
}
@@ -2397,7 +2115,7 @@ static int viewzoom_exec(bContext *C, wmOperator *op)
float dist_range[2];
const int delta = RNA_int_get(op->ptr, "delta");
- int mx, my;
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
if (op->customdata) {
ViewOpsData *vod = op->customdata;
@@ -2413,39 +2131,46 @@ static int viewzoom_exec(bContext *C, wmOperator *op)
v3d = sa->spacedata.first;
rv3d = ar->regiondata;
- mx = RNA_struct_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
- my = RNA_struct_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
use_cam_zoom = (rv3d->persp == RV3D_CAMOB) && !(rv3d->is_persp && ED_view3d_camera_lock_check(v3d, rv3d));
+ int zoom_xy_buf[2];
+ const int *zoom_xy = NULL;
+ if (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) {
+ zoom_xy_buf[0] = RNA_struct_property_is_set(op->ptr, "mx") ? RNA_int_get(op->ptr, "mx") : ar->winx / 2;
+ zoom_xy_buf[1] = RNA_struct_property_is_set(op->ptr, "my") ? RNA_int_get(op->ptr, "my") : ar->winy / 2;
+ zoom_xy = zoom_xy_buf;
+ }
+
ED_view3d_dist_range_get(v3d, dist_range);
if (delta < 0) {
const float step = 1.2f;
/* this min and max is also in viewmove() */
if (use_cam_zoom) {
- view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
+ view_zoom_to_window_xy_camera(scene, v3d, ar, step, zoom_xy);
}
else {
if (rv3d->dist < dist_range[1]) {
- view_zoom_mouseloc_3d(ar, step, mx, my);
+ view_zoom_to_window_xy_3d(ar, step, zoom_xy);
}
}
}
else {
const float step = 1.0f / 1.2f;
if (use_cam_zoom) {
- view_zoom_mouseloc_camera(scene, v3d, ar, step, mx, my);
+ view_zoom_to_window_xy_camera(scene, v3d, ar, step, zoom_xy);
}
else {
if (rv3d->dist > dist_range[0]) {
- view_zoom_mouseloc_3d(ar, step, mx, my);
+ view_zoom_to_window_xy_3d(ar, step, zoom_xy);
}
}
}
- if (rv3d->viewlock & RV3D_BOXVIEW)
+ if (rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(sa, ar);
+ }
ED_view3d_depth_tag_update(rv3d);
@@ -2459,49 +2184,19 @@ static int viewzoom_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
}
-/* this is an exact copy of viewzoom_modal_keymap */
-/* called in transform_ops.c, on each regeneration of keymaps */
-void viewdolly_modal_keymap(wmKeyConfig *keyconf)
-{
- static EnumPropertyItem modal_items[] = {
- {VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
-
- {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
- {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
-
- {0, NULL, 0, NULL, NULL}
- };
-
- wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
-
- /* this function is called for each spacetype, only needs to add map once */
- if (keymap && keymap->modal_items) return;
-
- keymap = WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
-
- /* items for modal map */
- WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
- WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
-
- /* disabled mode switching for now, can re-implement better, later on */
-#if 0
- WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
- WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
- WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
-#endif
-
- /* assign map to operators */
- WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
-}
-
/* viewdolly_invoke() copied this function, changes here may apply there */
static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
ViewOpsData *vod;
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+
/* makes op->customdata */
viewops_data_alloc(C, op);
- viewops_data_create(C, op, event);
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_prefs() |
+ (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
vod = op->customdata;
ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
@@ -2519,14 +2214,16 @@ static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
if (event->type == MOUSEZOOM || event->type == MOUSEPAN) {
if (U.uiflag & USER_ZOOM_HORIZ) {
- vod->origx = vod->oldx = event->x;
- viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
+ vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
}
else {
/* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
- vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
- viewzoom_apply(vod, &event->prevx, USER_ZOOM_DOLLY, (U.uiflag & USER_ZOOM_INVERT) != 0);
+ vod->init.event_xy[1] = vod->prev.event_xy[1] = vod->init.event_xy[1] + event->x - event->prevx;
}
+ viewzoom_apply(
+ vod, &event->prevx, USER_ZOOM_DOLLY,
+ (U.uiflag & USER_ZOOM_INVERT) != 0,
+ (use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)));
ED_view3d_camera_lock_autokey(vod->v3d, vod->rv3d, C, false, true);
ED_view3d_depth_tag_update(vod->rv3d);
@@ -2538,7 +2235,7 @@ static int viewzoom_invoke(bContext *C, wmOperator *op, const wmEvent *event)
if (U.viewzoom == USER_ZOOM_CONT) {
/* needs a timer to continue redrawing */
vod->timer = WM_event_add_timer(CTX_wm_manager(C), CTX_wm_window(C), TIMER, 0.01f);
- vod->timer_lastdraw = PIL_check_seconds_timer();
+ vod->prev.time = PIL_check_seconds_timer();
}
/* add temp handler */
@@ -2557,8 +2254,6 @@ static void viewzoom_cancel(bContext *C, wmOperator *op)
void VIEW3D_OT_zoom(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
/* identifiers */
ot->name = "Zoom View";
ot->description = "Zoom in/out in the view";
@@ -2574,15 +2269,56 @@ void VIEW3D_OT_zoom(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
- RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
- prop = RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
- RNA_def_property_flag(prop, PROP_HIDDEN);
- prop = RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
- RNA_def_property_flag(prop, PROP_HIDDEN);
+ /* properties */
+ view3d_operator_properties_common(
+ ot,
+ V3D_OP_PROP_DELTA | V3D_OP_PROP_MOUSE_CO | V3D_OP_PROP_USE_MOUSE_INIT);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Dolly Operator
+ *
+ * Like zoom but translates the view offset along the view direction
+ * which avoids #RegionView3D.dist approaching zero.
+ * \{ */
+
+/* this is an exact copy of viewzoom_modal_keymap */
+/* called in transform_ops.c, on each regeneration of keymaps */
+void viewdolly_modal_keymap(wmKeyConfig *keyconf)
+{
+ static const EnumPropertyItem modal_items[] = {
+ {VIEW_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
+
+ {VIEWROT_MODAL_SWITCH_ROTATE, "SWITCH_TO_ROTATE", 0, "Switch to Rotate"},
+ {VIEWROT_MODAL_SWITCH_MOVE, "SWITCH_TO_MOVE", 0, "Switch to Move"},
+
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ wmKeyMap *keymap = WM_modalkeymap_get(keyconf, "View3D Dolly Modal");
+
+ /* this function is called for each spacetype, only needs to add map once */
+ if (keymap && keymap->modal_items) return;
+
+ keymap = WM_modalkeymap_add(keyconf, "View3D Dolly Modal", modal_items);
+
+ /* items for modal map */
+ WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, VIEW_MODAL_CONFIRM);
+ WM_modalkeymap_add_item(keymap, ESCKEY, KM_PRESS, KM_ANY, 0, VIEW_MODAL_CONFIRM);
+
+ /* disabled mode switching for now, can re-implement better, later on */
+#if 0
+ WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
+ WM_modalkeymap_add_item(keymap, LEFTCTRLKEY, KM_RELEASE, KM_ANY, 0, VIEWROT_MODAL_SWITCH_ROTATE);
+ WM_modalkeymap_add_item(keymap, LEFTSHIFTKEY, KM_PRESS, KM_ANY, 0, VIEWROT_MODAL_SWITCH_MOVE);
+#endif
+
+ /* assign map to operators */
+ WM_modalkeymap_assign(keymap, "VIEW3D_OT_dolly");
+}
-/* ************************ viewdolly ******************************** */
static bool viewdolly_offset_lock_check(bContext *C, wmOperator *op)
{
View3D *v3d = CTX_wm_view3d(C);
@@ -2596,13 +2332,13 @@ static bool viewdolly_offset_lock_check(bContext *C, wmOperator *op)
}
}
-static void view_dolly_mouseloc(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
+static void view_dolly_to_vector_3d(ARegion *ar, float orig_ofs[3], float dvec[3], float dfac)
{
RegionView3D *rv3d = ar->regiondata;
madd_v3_v3v3fl(rv3d->ofs, orig_ofs, dvec, -(1.0f - dfac));
}
-static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_invert)
+static void viewdolly_apply(ViewOpsData *vod, const int xy[2], const short zoom_invert)
{
float zfac = 1.0;
@@ -2610,24 +2346,27 @@ static void viewdolly_apply(ViewOpsData *vod, int x, int y, const short zoom_inv
float len1, len2;
if (U.uiflag & USER_ZOOM_HORIZ) {
- len1 = (vod->ar->winrct.xmax - x) + 5;
- len2 = (vod->ar->winrct.xmax - vod->origx) + 5;
+ len1 = (vod->ar->winrct.xmax - xy[0]) + 5;
+ len2 = (vod->ar->winrct.xmax - vod->init.event_xy[0]) + 5;
}
else {
- len1 = (vod->ar->winrct.ymax - y) + 5;
- len2 = (vod->ar->winrct.ymax - vod->origy) + 5;
+ len1 = (vod->ar->winrct.ymax - xy[1]) + 5;
+ len2 = (vod->ar->winrct.ymax - vod->init.event_xy[1]) + 5;
}
- if (zoom_invert)
+ if (zoom_invert) {
SWAP(float, len1, len2);
+ }
zfac = 1.0f + ((len1 - len2) * 0.01f * vod->rv3d->dist);
}
- if (zfac != 1.0f)
- view_dolly_mouseloc(vod->ar, vod->ofs, vod->mousevec, zfac);
+ if (zfac != 1.0f) {
+ view_dolly_to_vector_3d(vod->ar, vod->init.ofs, vod->init.mousevec, zfac);
+ }
- if (vod->rv3d->viewlock & RV3D_BOXVIEW)
+ if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(vod->sa, vod->ar);
+ }
ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
@@ -2661,12 +2400,12 @@ static int viewdolly_modal(bContext *C, wmOperator *op, const wmEvent *event)
break;
}
}
- else if (event->type == vod->origkey && event->val == KM_RELEASE) {
+ else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
event_code = VIEW_CONFIRM;
}
if (event_code == VIEW_APPLY) {
- viewdolly_apply(vod, event->x, event->y, (U.uiflag & USER_ZOOM_INVERT) != 0);
+ viewdolly_apply(vod, &event->x, (U.uiflag & USER_ZOOM_INVERT) != 0);
if (ED_screen_animation_playing(CTX_wm_manager(C))) {
use_autokey = true;
}
@@ -2703,7 +2442,7 @@ static int viewdolly_exec(bContext *C, wmOperator *op)
sa = vod->sa;
ar = vod->ar;
- copy_v3_v3(mousevec, vod->mousevec);
+ copy_v3_v3(mousevec, vod->init.mousevec);
}
else {
sa = CTX_wm_area(C);
@@ -2715,20 +2454,18 @@ static int viewdolly_exec(bContext *C, wmOperator *op)
v3d = sa->spacedata.first;
rv3d = ar->regiondata;
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+
/* overwrite the mouse vector with the view direction (zoom into the center) */
- if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
+ if ((use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) == 0) {
normalize_v3_v3(mousevec, rv3d->viewinv[2]);
}
- if (delta < 0) {
- view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 0.2f);
- }
- else {
- view_dolly_mouseloc(ar, rv3d->ofs, mousevec, 1.8f);
- }
+ view_dolly_to_vector_3d(ar, rv3d->ofs, mousevec, delta < 0 ? 0.2f : 1.8f);
- if (rv3d->viewlock & RV3D_BOXVIEW)
+ if (rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(sa, ar);
+ }
ED_view3d_depth_tag_update(rv3d);
@@ -2766,7 +2503,7 @@ static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
if (vod->rv3d->persp != RV3D_PERSP) {
if (vod->rv3d->persp == RV3D_CAMOB) {
/* ignore rv3d->lpersp because dolly only makes sense in perspective mode */
- view3d_persp_switch_from_camera(vod->v3d, vod->rv3d, RV3D_PERSP);
+ ED_view3d_persp_switch_from_camera(vod->v3d, vod->rv3d, RV3D_PERSP);
}
else {
vod->rv3d->persp = RV3D_PERSP;
@@ -2774,7 +2511,12 @@ static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
ED_region_tag_redraw(vod->ar);
}
- viewops_data_create(C, op, event);
+ const bool use_mouse_init = RNA_boolean_get(op->ptr, "use_mouse_init");
+
+ viewops_data_create(
+ C, op, event,
+ viewops_flag_from_prefs() |
+ (use_mouse_init ? VIEWOPS_FLAG_USE_MOUSE_INIT : 0));
/* if one or the other zoom position aren't set, set from event */
@@ -2788,24 +2530,22 @@ static int viewdolly_invoke(bContext *C, wmOperator *op, const wmEvent *event)
}
else {
/* overwrite the mouse vector with the view direction (zoom into the center) */
- if ((U.uiflag & USER_ZOOM_TO_MOUSEPOS) == 0) {
- negate_v3_v3(vod->mousevec, vod->rv3d->viewinv[2]);
- normalize_v3(vod->mousevec);
+ if ((use_mouse_init && (U.uiflag & USER_ZOOM_TO_MOUSEPOS)) == 0) {
+ negate_v3_v3(vod->init.mousevec, vod->rv3d->viewinv[2]);
+ normalize_v3(vod->init.mousevec);
}
if (event->type == MOUSEZOOM) {
/* Bypass Zoom invert flag for track pads (pass false always) */
if (U.uiflag & USER_ZOOM_HORIZ) {
- vod->origx = vod->oldx = event->x;
- viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
+ vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
}
else {
-
/* Set y move = x move as MOUSEZOOM uses only x axis to pass magnification value */
- vod->origy = vod->oldy = vod->origy + event->x - event->prevx;
- viewdolly_apply(vod, event->prevx, event->prevy, (U.uiflag & USER_ZOOM_INVERT) == 0);
+ vod->init.event_xy[1] = vod->prev.event_xy[1] = vod->init.event_xy[1] + event->x - event->prevx;
}
+ viewdolly_apply(vod, &event->prevx, (U.uiflag & USER_ZOOM_INVERT) == 0);
ED_view3d_depth_tag_update(vod->rv3d);
viewops_data_free(C, op);
@@ -2843,14 +2583,23 @@ void VIEW3D_OT_dolly(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_BLOCKING | OPTYPE_GRAB_CURSOR;
- RNA_def_int(ot->srna, "delta", 0, INT_MIN, INT_MAX, "Delta", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "mx", 0, 0, INT_MAX, "Zoom Position X", "", 0, INT_MAX);
- RNA_def_int(ot->srna, "my", 0, 0, INT_MAX, "Zoom Position Y", "", 0, INT_MAX);
+ /* properties */
+ view3d_operator_properties_common(
+ ot, V3D_OP_PROP_DELTA | V3D_OP_PROP_MOUSE_CO | V3D_OP_PROP_USE_MOUSE_INIT);
}
-static void view3d_from_minmax(bContext *C, View3D *v3d, ARegion *ar,
- const float min[3], const float max[3],
- bool ok_dist, const int smooth_viewtx)
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View All Operator
+ *
+ * Move & Zoom the view to fit all of it's contents.
+ * \{ */
+
+static void view3d_from_minmax(
+ bContext *C, View3D *v3d, ARegion *ar,
+ const float min[3], const float max[3],
+ bool ok_dist, const int smooth_viewtx)
{
RegionView3D *rv3d = ar->regiondata;
float afm[3];
@@ -2916,10 +2665,13 @@ static void view3d_from_minmax(bContext *C, View3D *v3d, ARegion *ar,
/* smooth view does viewlock RV3D_BOXVIEW copy */
}
-/* same as view3d_from_minmax but for all regions (except cameras) */
-static void view3d_from_minmax_multi(bContext *C, View3D *v3d,
- const float min[3], const float max[3],
- const bool ok_dist, const int smooth_viewtx)
+/**
+ * Same as #view3d_from_minmax but for all regions (except cameras).
+ */
+static void view3d_from_minmax_multi(
+ bContext *C, View3D *v3d,
+ const float min[3], const float max[3],
+ const bool ok_dist, const int smooth_viewtx)
{
ScrArea *sa = CTX_wm_area(C);
ARegion *ar;
@@ -2935,7 +2687,7 @@ static void view3d_from_minmax_multi(bContext *C, View3D *v3d,
}
}
-static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in 2.4x */
+static int view3d_all_exec(bContext *C, wmOperator *op)
{
ARegion *ar = CTX_wm_region(C);
View3D *v3d = CTX_wm_view3d(C);
@@ -2999,8 +2751,6 @@ static int view3d_all_exec(bContext *C, wmOperator *op) /* was view3d_home() in
void VIEW3D_OT_view_all(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
/* identifiers */
ot->name = "View All";
ot->description = "View all objects in scene";
@@ -3013,11 +2763,19 @@ void VIEW3D_OT_view_all(wmOperatorType *ot)
/* flags */
ot->flag = 0;
- prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ /* properties */
+ view3d_operator_properties_common(ot, V3D_OP_PROP_USE_ALL_REGIONS);
RNA_def_boolean(ot->srna, "center", 0, "Center", "");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Selected Operator
+ *
+ * Move & Zoom the view to fit selected contents.
+ * \{ */
+
/* like a localview without local!, was centerview() in 2.4x */
static int viewselected_exec(bContext *C, wmOperator *op)
{
@@ -3124,8 +2882,6 @@ static int viewselected_exec(bContext *C, wmOperator *op)
void VIEW3D_OT_view_selected(wmOperatorType *ot)
{
- PropertyRNA *prop;
-
/* identifiers */
ot->name = "View Selected";
ot->description = "Move the view to the selection center";
@@ -3138,17 +2894,22 @@ void VIEW3D_OT_view_selected(wmOperatorType *ot)
/* flags */
ot->flag = 0;
- /* rna later */
- prop = RNA_def_boolean(ot->srna, "use_all_regions", 0, "All Regions", "View selected for all regions");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ /* properties */
+ view3d_operator_properties_common(ot, V3D_OP_PROP_USE_ALL_REGIONS);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Lock Clear Operator
+ * \{ */
+
static int view_lock_clear_exec(bContext *C, wmOperator *UNUSED(op))
{
View3D *v3d = CTX_wm_view3d(C);
if (v3d) {
- ED_view3D_lock_clear(v3d);
+ ED_view3d_lock_clear(v3d);
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
@@ -3175,6 +2936,12 @@ void VIEW3D_OT_view_lock_clear(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Lock to Active Operator
+ * \{ */
+
static int view_lock_to_active_exec(bContext *C, wmOperator *UNUSED(op))
{
View3D *v3d = CTX_wm_view3d(C);
@@ -3182,7 +2949,7 @@ static int view_lock_to_active_exec(bContext *C, wmOperator *UNUSED(op))
if (v3d) {
- ED_view3D_lock_clear(v3d);
+ ED_view3d_lock_clear(v3d);
v3d->ob_centre = obact; /* can be NULL */
@@ -3226,12 +2993,18 @@ void VIEW3D_OT_view_lock_to_active(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Center Cursor Operator
+ * \{ */
+
static int viewcenter_cursor_exec(bContext *C, wmOperator *op)
{
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
Scene *scene = CTX_data_scene(C);
-
+
if (rv3d) {
ARegion *ar = CTX_wm_region(C);
const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
@@ -3247,7 +3020,7 @@ static int viewcenter_cursor_exec(bContext *C, wmOperator *op)
/* smooth view does viewlock RV3D_BOXVIEW copy */
}
-
+
return OPERATOR_FINISHED;
}
@@ -3257,15 +3030,21 @@ void VIEW3D_OT_view_center_cursor(wmOperatorType *ot)
ot->name = "Center View to Cursor";
ot->description = "Center the view so that the cursor is in the middle of the view";
ot->idname = "VIEW3D_OT_view_center_cursor";
-
+
/* api callbacks */
ot->exec = viewcenter_cursor_exec;
ot->poll = ED_operator_view3d_active;
-
+
/* flags */
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Center Pick Operator
+ * \{ */
+
static int viewcenter_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
View3D *v3d = CTX_wm_view3d(C);
@@ -3313,6 +3092,12 @@ void VIEW3D_OT_view_center_pick(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Camera Center Operator
+ * \{ */
+
static int view3d_center_camera_exec(bContext *C, wmOperator *UNUSED(op)) /* was view3d_home() in 2.4x */
{
Scene *scene = CTX_data_scene(C);
@@ -3358,6 +3143,12 @@ void VIEW3D_OT_view_center_camera(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Lock Center Operator
+ * \{ */
+
static int view3d_center_lock_exec(bContext *C, wmOperator *UNUSED(op)) /* was view3d_home() in 2.4x */
{
RegionView3D *rv3d = CTX_wm_region_view3d(C);
@@ -3384,7 +3175,11 @@ void VIEW3D_OT_view_center_lock(wmOperatorType *ot)
ot->flag = 0;
}
-/* ********************* Set render border operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Render Border Operator
+ * \{ */
static int render_border_exec(bContext *C, wmOperator *op)
{
@@ -3454,7 +3249,6 @@ static int render_border_exec(bContext *C, wmOperator *op)
}
return OPERATOR_FINISHED;
-
}
void VIEW3D_OT_render_border(wmOperatorType *ot)
@@ -3467,17 +3261,17 @@ void VIEW3D_OT_render_border(wmOperatorType *ot)
ot->idname = "VIEW3D_OT_render_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = render_border_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_view3d_active;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
- /* rna */
+ /* properties */
WM_operator_properties_border(ot);
prop = RNA_def_boolean(ot->srna, "camera_only", false, "Camera Only",
@@ -3485,7 +3279,11 @@ void VIEW3D_OT_render_border(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_HIDDEN);
}
-/* ********************* Clear render border operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Clear Render Border Operator
+ * \{ */
static int clear_render_border_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -3514,7 +3312,6 @@ static int clear_render_border_exec(bContext *C, wmOperator *UNUSED(op))
border->ymax = 1.0f;
return OPERATOR_FINISHED;
-
}
void VIEW3D_OT_clear_render_border(wmOperatorType *ot)
@@ -3532,7 +3329,11 @@ void VIEW3D_OT_clear_render_border(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/* ********************* Border Zoom operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Border Zoom Operator
+ * \{ */
static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
{
@@ -3540,7 +3341,6 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
Scene *scene = CTX_data_scene(C);
- int gesture_mode;
const int smooth_viewtx = WM_operator_smooth_viewtx_get(op);
/* Zooms in on a border drawn by the user */
@@ -3564,24 +3364,24 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
WM_operator_properties_border_to_rcti(op, &rect);
/* check if zooming in/out view */
- gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
+ const bool zoom_in = !RNA_boolean_get(op->ptr, "zoom_out");
ED_view3d_dist_range_get(v3d, dist_range);
/* Get Z Depths, needed for perspective, nice for ortho */
bgl_get_mats(&mats);
ED_view3d_draw_depth(scene, ar, v3d, true);
-
+
{
/* avoid allocating the whole depth buffer */
ViewDepths depth_temp = {0};
/* avoid view3d_update_depths() for speed. */
view3d_update_depths_rect(ar, &depth_temp, &rect);
-
+
/* find the closest Z pixel */
depth_close = view3d_depth_near(&depth_temp);
-
+
MEM_SAFE_FREE(depth_temp.depths);
}
@@ -3662,7 +3462,7 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
new_dist *= max_ff(xscale, yscale);
}
- if (gesture_mode == GESTURE_MODAL_OUT) {
+ if (!zoom_in) {
sub_v3_v3v3(dvec, new_ofs, rv3d->ofs);
new_dist = rv3d->dist * (rv3d->dist / new_dist);
add_v3_v3v3(new_ofs, rv3d->ofs, dvec);
@@ -3675,8 +3475,9 @@ static int view3d_zoom_border_exec(bContext *C, wmOperator *op)
C, v3d, ar, smooth_viewtx,
&(const V3D_SmoothParams) {.ofs = new_ofs, .dist = &new_dist});
- if (rv3d->viewlock & RV3D_BOXVIEW)
+ if (rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(CTX_wm_area(C), ar);
+ }
return OPERATOR_FINISHED;
}
@@ -3688,7 +3489,7 @@ static int view3d_zoom_border_invoke(bContext *C, wmOperator *op, const wmEvent
/* if in camera view do not exec the operator so we do not conflict with set render border*/
if ((rv3d->persp != RV3D_CAMOB) || ED_view3d_camera_lock_check(v3d, rv3d))
- return WM_border_select_invoke(C, op, event);
+ return WM_gesture_border_invoke(C, op, event);
else
return OPERATOR_PASS_THROUGH;
}
@@ -3703,25 +3504,32 @@ void VIEW3D_OT_zoom_border(wmOperatorType *ot)
/* api callbacks */
ot->invoke = view3d_zoom_border_invoke;
ot->exec = view3d_zoom_border_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_region_view3d_active;
/* flags */
ot->flag = 0;
- /* rna */
- WM_operator_properties_gesture_border(ot, false);
+ /* properties */
+ WM_operator_properties_gesture_border_zoom(ot);
}
-/* sets the view to 1:1 camera/render-pixel */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Camera Zoom 1:1 Operator
+ *
+ * Sets the view to 1:1 camera/render-pixel.
+ * \{ */
+
static void view3d_set_1_to_1_viewborder(Scene *scene, ARegion *ar, View3D *v3d)
{
RegionView3D *rv3d = ar->regiondata;
float size[2];
int im_width = (scene->r.size * scene->r.xsch) / 100;
-
+
ED_view3d_calc_camera_border_size(scene, ar, v3d, rv3d, size);
rv3d->camzoom = BKE_screen_view3d_zoom_from_fac((float)im_width / size[0]);
@@ -3760,9 +3568,13 @@ void VIEW3D_OT_zoom_camera_1_to_1(wmOperatorType *ot)
ot->flag = 0;
}
-/* ********************* Changing view operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Axis/Type Operator
+ * \{ */
-static EnumPropertyItem prop_view_items[] = {
+static const EnumPropertyItem prop_view_items[] = {
{RV3D_VIEW_LEFT, "LEFT", ICON_TRIA_LEFT, "Left", "View From the Left"},
{RV3D_VIEW_RIGHT, "RIGHT", ICON_TRIA_RIGHT, "Right", "View From the Right"},
{RV3D_VIEW_BOTTOM, "BOTTOM", ICON_TRIA_DOWN, "Bottom", "View From the Bottom"},
@@ -3776,10 +3588,11 @@ static EnumPropertyItem prop_view_items[] = {
/* would like to make this a generic function - outside of transform */
-static void axis_set_view(bContext *C, View3D *v3d, ARegion *ar,
- const float quat_[4],
- short view, int perspo, bool align_active,
- const int smooth_viewtx)
+static void axis_set_view(
+ bContext *C, View3D *v3d, ARegion *ar,
+ const float quat_[4],
+ short view, int perspo, bool align_active,
+ const int smooth_viewtx)
{
RegionView3D *rv3d = ar->regiondata; /* no NULL check is needed, poll checks */
float quat[4];
@@ -3957,7 +3770,6 @@ static int viewnumpad_exec(bContext *C, wmOperator *op)
&(const V3D_SmoothParams) {
.camera = v3d->camera, .ofs = rv3d->ofs, .quat = rv3d->viewquat,
.dist = &rv3d->dist, .lens = &v3d->lens});
-
}
else {
/* return to settings of last view */
@@ -3998,7 +3810,15 @@ void VIEW3D_OT_viewnumpad(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-static EnumPropertyItem prop_view_orbit_items[] = {
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Orbit Operator
+ *
+ * Rotate (orbit) in incremental steps. For interactive orbit see #VIEW3D_OT_rotate.
+ * \{ */
+
+static const EnumPropertyItem prop_view_orbit_items[] = {
{V3D_VIEW_STEPLEFT, "ORBITLEFT", 0, "Orbit Left", "Orbit the view around to the Left"},
{V3D_VIEW_STEPRIGHT, "ORBITRIGHT", 0, "Orbit Right", "Orbit the view around to the Right"},
{V3D_VIEW_STEPUP, "ORBITUP", 0, "Orbit Up", "Orbit the view Up"},
@@ -4041,7 +3861,7 @@ static int vieworbit_exec(bContext *C, wmOperator *op)
float quat_new[4];
if (view_opposite == RV3D_VIEW_USER) {
- view3d_ensure_persp(v3d, ar);
+ ED_view3d_persp_ensure(v3d, ar);
}
if (ELEM(orbitdir, V3D_VIEW_STEPLEFT, V3D_VIEW_STEPRIGHT)) {
@@ -4112,17 +3932,19 @@ void VIEW3D_OT_view_orbit(wmOperatorType *ot)
/* flags */
ot->flag = 0;
-
+
/* properties */
prop = RNA_def_float(ot->srna, "angle", 0, -FLT_MAX, FLT_MAX, "Roll", "", -FLT_MAX, FLT_MAX);
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
ot->prop = RNA_def_enum(ot->srna, "type", prop_view_orbit_items, 0, "Orbit", "Direction of View Orbit");
-
}
+/** \} */
-/* ************************ viewroll ******************************** */
+/* -------------------------------------------------------------------- */
+/** \name View Roll Operator
+ * \{ */
static void view_roll_angle(ARegion *ar, float quat[4], const float orig_quat[4], const float dvec[3], float angle)
{
@@ -4149,19 +3971,20 @@ static void viewroll_apply(ViewOpsData *vod, int x, int UNUSED(y))
tot = vod->ar->winrct.xmax - vod->ar->winrct.xmin;
len1 = (vod->ar->winrct.xmax - x) / tot;
- len2 = (vod->ar->winrct.xmax - vod->origx) / tot;
+ len2 = (vod->ar->winrct.xmax - vod->init.event_xy[0]) / tot;
angle = (len1 - len2) * (float)M_PI * 4.0f;
}
if (angle != 0.0f)
- view_roll_angle(vod->ar, vod->rv3d->viewquat, vod->oldquat, vod->mousevec, angle);
+ view_roll_angle(vod->ar, vod->rv3d->viewquat, vod->init.quat, vod->init.mousevec, angle);
if (vod->use_dyn_ofs) {
- view3d_orbit_apply_dyn_ofs(vod->rv3d->ofs, vod->ofs, vod->oldquat, vod->rv3d->viewquat, vod->dyn_ofs);
+ view3d_orbit_apply_dyn_ofs(vod->rv3d->ofs, vod->init.ofs, vod->init.quat, vod->rv3d->viewquat, vod->dyn_ofs);
}
- if (vod->rv3d->viewlock & RV3D_BOXVIEW)
+ if (vod->rv3d->viewlock & RV3D_BOXVIEW) {
view3d_boxview_sync(vod->sa, vod->ar);
+ }
ED_view3d_camera_lock_sync(vod->v3d, vod->rv3d);
@@ -4194,7 +4017,7 @@ static int viewroll_modal(bContext *C, wmOperator *op, const wmEvent *event)
break;
}
}
- else if (event->type == vod->origkey && event->val == KM_RELEASE) {
+ else if (event->type == vod->init.event_type && event->val == KM_RELEASE) {
event_code = VIEW_CONFIRM;
}
@@ -4221,7 +4044,7 @@ static int viewroll_modal(bContext *C, wmOperator *op, const wmEvent *event)
return ret;
}
-static EnumPropertyItem prop_view_roll_items[] = {
+static const EnumPropertyItem prop_view_roll_items[] = {
{0, "ANGLE", 0, "Roll Angle", "Roll the view using an angle value"},
{V3D_VIEW_STEPLEFT, "LEFT", 0, "Roll Left", "Roll the view around to the Left"},
{V3D_VIEW_STEPRIGHT, "RIGHT", 0, "Roll Right", "Roll the view around to the Right"},
@@ -4298,17 +4121,17 @@ static int viewroll_invoke(bContext *C, wmOperator *op, const wmEvent *event)
else {
/* makes op->customdata */
viewops_data_alloc(C, op);
- viewops_data_create(C, op, event);
+ viewops_data_create(C, op, event, viewops_flag_from_prefs());
vod = op->customdata;
ED_view3d_smooth_view_force_finish(C, vod->v3d, vod->ar);
/* overwrite the mouse vector with the view direction */
- normalize_v3_v3(vod->mousevec, vod->rv3d->viewinv[2]);
- negate_v3(vod->mousevec);
+ normalize_v3_v3(vod->init.mousevec, vod->rv3d->viewinv[2]);
+ negate_v3(vod->init.mousevec);
if (event->type == MOUSEROTATE) {
- vod->origx = vod->oldx = event->x;
+ vod->init.event_xy[0] = vod->prev.event_xy[0] = event->x;
viewroll_apply(vod, event->prevx, event->prevy);
ED_view3d_depth_tag_update(vod->rv3d);
@@ -4356,7 +4179,7 @@ void VIEW3D_OT_view_roll(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-static EnumPropertyItem prop_view_pan_items[] = {
+static const EnumPropertyItem prop_view_pan_items[] = {
{V3D_VIEW_PANLEFT, "PANLEFT", 0, "Pan Left", "Pan the view to the Left"},
{V3D_VIEW_PANRIGHT, "PANRIGHT", 0, "Pan Right", "Pan the view to the Right"},
{V3D_VIEW_PANUP, "PANUP", 0, "Pan Up", "Pan the view Up"},
@@ -4364,6 +4187,14 @@ static EnumPropertyItem prop_view_pan_items[] = {
{0, NULL, 0, NULL, NULL}
};
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Pan Operator
+ *
+ * Move (pan) in incremental steps. For interactive pan see #VIEW3D_OT_move.
+ * \{ */
+
static int viewpan_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
int x = 0, y = 0;
@@ -4375,10 +4206,10 @@ static int viewpan_invoke(bContext *C, wmOperator *op, const wmEvent *event)
else if (pandir == V3D_VIEW_PANDOWN) { y = 25; }
viewops_data_alloc(C, op);
- viewops_data_create(C, op, event);
+ viewops_data_create(C, op, event, viewops_flag_from_prefs());
ViewOpsData *vod = op->customdata;
- viewmove_apply(vod, vod->oldx + x, vod->oldy + y);
+ viewmove_apply(vod, vod->prev.event_xy[0] + x, vod->prev.event_xy[1] + y);
ED_view3d_depth_tag_update(vod->rv3d);
viewops_data_free(C, op);
@@ -4399,11 +4230,17 @@ void VIEW3D_OT_view_pan(wmOperatorType *ot)
/* flags */
ot->flag = 0;
-
+
/* Properties */
ot->prop = RNA_def_enum(ot->srna, "type", prop_view_pan_items, 0, "Pan", "Direction of View Pan");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Toggle Perspective/Orthographic Operator
+ * \{ */
+
static int viewpersportho_exec(bContext *C, wmOperator *UNUSED(op))
{
View3D *v3d_dummy;
@@ -4422,7 +4259,6 @@ static int viewpersportho_exec(bContext *C, wmOperator *UNUSED(op))
}
return OPERATOR_FINISHED;
-
}
void VIEW3D_OT_view_persportho(wmOperatorType *ot)
@@ -4440,6 +4276,14 @@ void VIEW3D_OT_view_persportho(wmOperatorType *ot)
ot->flag = 0;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Navigate Operator
+ *
+ * Wraps walk/fly modes.
+ * \{ */
+
static int view3d_navigate_invoke(bContext *C, wmOperator *UNUSED(op), const wmEvent *UNUSED(event))
{
eViewNavigation_Method mode = U.navigation_mode;
@@ -4469,14 +4313,17 @@ void VIEW3D_OT_navigate(wmOperatorType *ot)
ot->poll = ED_operator_view3d_active;
}
+/** \} */
-/* ******************** add background image operator **************** */
+/* -------------------------------------------------------------------- */
+/** \name Background Image Add Operator
+ * \{ */
static BGpic *background_image_add(bContext *C)
{
View3D *v3d = CTX_wm_view3d(C);
- return ED_view3D_background_image_new(v3d);
+ return ED_view3d_background_image_new(v3d);
}
static int background_image_add_exec(bContext *C, wmOperator *UNUSED(op))
@@ -4491,7 +4338,7 @@ static int background_image_add_invoke(bContext *C, wmOperator *op, const wmEven
View3D *v3d = CTX_wm_view3d(C);
Image *ima;
BGpic *bgpic;
-
+
ima = (Image *)WM_operator_drop_load_path(C, op, ID_IM);
/* may be NULL, continue anyway */
@@ -4499,9 +4346,9 @@ static int background_image_add_invoke(bContext *C, wmOperator *op, const wmEven
bgpic->ima = ima;
v3d->flag |= V3D_DISPBGPICS;
-
+
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
-
+
return OPERATOR_FINISHED;
}
@@ -4521,7 +4368,7 @@ void VIEW3D_OT_background_image_add(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
-
+
/* properties */
RNA_def_string(ot->srna, "name", "Image", MAX_ID_NAME - 2, "Name", "Image name to assign");
WM_operator_properties_filesel(
@@ -4529,8 +4376,12 @@ void VIEW3D_OT_background_image_add(wmOperatorType *ot)
WM_FILESEL_FILEPATH | WM_FILESEL_RELPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Background Image Remove Operator
+ * \{ */
-/* ***** remove image operator ******* */
static int background_image_remove_exec(bContext *C, wmOperator *op)
{
View3D *v3d = CTX_wm_view3d(C);
@@ -4545,7 +4396,7 @@ static int background_image_remove_exec(bContext *C, wmOperator *op)
id_us_min((ID *)bgpic_rem->clip);
}
- ED_view3D_background_image_remove(v3d, bgpic_rem);
+ ED_view3d_background_image_remove(v3d, bgpic_rem);
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
return OPERATOR_FINISHED;
@@ -4553,7 +4404,6 @@ static int background_image_remove_exec(bContext *C, wmOperator *op)
else {
return OPERATOR_CANCELLED;
}
-
}
void VIEW3D_OT_background_image_remove(wmOperatorType *ot)
@@ -4569,12 +4419,18 @@ void VIEW3D_OT_background_image_remove(wmOperatorType *ot)
/* flags */
ot->flag = 0;
-
+
/* properties */
RNA_def_int(ot->srna, "index", 0, 0, INT_MAX, "Index", "Background image index to remove", 0, INT_MAX);
}
-/* ********************* set clipping operator ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Clipping Planes Operator
+ *
+ * Draw border or toggle off.
+ * \{ */
static void calc_local_clipping(float clip_local[6][4], BoundBox *clipbb, float mat[4][4])
{
@@ -4612,7 +4468,7 @@ static int view3d_clipping_exec(bContext *C, wmOperator *op)
/* note; otherwise opengl won't work */
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
view3d_get_transformation(vc.ar, vc.rv3d, NULL, &mats); /* NULL because we don't want it in object space */
ED_view3d_clipping_calc(rv3d->clipbb, rv3d->clip, &mats, &rect);
@@ -4632,11 +4488,10 @@ static int view3d_clipping_invoke(bContext *C, wmOperator *op, const wmEvent *ev
return OPERATOR_FINISHED;
}
else {
- return WM_border_select_invoke(C, op, event);
+ return WM_gesture_border_invoke(C, op, event);
}
}
-/* toggles */
void VIEW3D_OT_clip_border(wmOperatorType *ot)
{
@@ -4648,19 +4503,23 @@ void VIEW3D_OT_clip_border(wmOperatorType *ot)
/* api callbacks */
ot->invoke = view3d_clipping_invoke;
ot->exec = view3d_clipping_exec;
- ot->modal = WM_border_select_modal;
- ot->cancel = WM_border_select_cancel;
+ ot->modal = WM_gesture_border_modal;
+ ot->cancel = WM_gesture_border_cancel;
ot->poll = ED_operator_region_view3d_active;
/* flags */
ot->flag = 0;
- /* rna */
+ /* properties */
WM_operator_properties_border(ot);
}
-/* ***************** 3d cursor cursor op ******************* */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Cursor Operator
+ * \{ */
/* cursor position in vec, result in vec, mval in region coords */
/* note: cannot use event->mval here (called by object_add() */
@@ -4672,14 +4531,14 @@ void ED_view3d_cursor3d_position(bContext *C, float fp[3], const int mval[2])
RegionView3D *rv3d = ar->regiondata;
bool flip;
bool depth_used = false;
-
+
/* normally the caller should ensure this,
* but this is called from areas that aren't already dealing with the viewport */
if (rv3d == NULL)
return;
ED_view3d_calc_zfac(rv3d, fp, &flip);
-
+
/* reset the depth based on the view offset (we _know_ the offset is infront of us) */
if (flip) {
negate_v3_v3(fp, rv3d->ofs);
@@ -4687,7 +4546,7 @@ void ED_view3d_cursor3d_position(bContext *C, float fp[3], const int mval[2])
ED_view3d_calc_zfac(rv3d, fp, NULL /* &flip */ );
}
- if (U.uiflag & USER_ZBUF_CURSOR) { /* maybe this should be accessed some other way */
+ if (U.uiflag & USER_DEPTH_CURSOR) { /* maybe this should be accessed some other way */
view3d_operator_needs_opengl(C);
if (ED_view3d_autodist(scene, ar, v3d, mval, fp, true, NULL))
depth_used = true;
@@ -4717,13 +4576,20 @@ void ED_view3d_cursor3d_update(bContext *C, const int mval[2])
ARegion *ar = CTX_wm_region(C);
RegionView3D *rv3d = ar->regiondata;
- float co_curr[2], co_prev[2];
+ if (U.uiflag & USER_LOCK_CURSOR_ADJUST) {
- if ((ED_view3d_project_float_global(ar, fp_prev, co_prev, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
- (ED_view3d_project_float_global(ar, fp_curr, co_curr, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
- {
- rv3d->ofs_lock[0] += (co_curr[0] - co_prev[0]) / (ar->winx * 0.5f);
- rv3d->ofs_lock[1] += (co_curr[1] - co_prev[1]) / (ar->winy * 0.5f);
+ float co_curr[2], co_prev[2];
+
+ if ((ED_view3d_project_float_global(ar, fp_prev, co_prev, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK) &&
+ (ED_view3d_project_float_global(ar, fp_curr, co_curr, V3D_PROJ_TEST_NOP) == V3D_PROJ_RET_OK))
+ {
+ rv3d->ofs_lock[0] += (co_curr[0] - co_prev[0]) / (ar->winx * 0.5f);
+ rv3d->ofs_lock[1] += (co_curr[1] - co_prev[1]) / (ar->winy * 0.5f);
+ }
+ }
+ else {
+ /* Cursor may be outside of the view, prevent it getting 'lost', see: T40353 & T45301 */
+ zero_v2(rv3d->ofs_lock);
}
}
@@ -4755,13 +4621,13 @@ void VIEW3D_OT_cursor3d(wmOperatorType *ot)
/* flags */
// ot->flag = OPTYPE_REGISTER|OPTYPE_UNDO;
-
- /* rna later */
-
}
-/* ***************** manipulator op ******************* */
+/** \} */
+/* -------------------------------------------------------------------- */
+/** \name Transform Manipulator Operator
+ * \{ */
static int manipulator_invoke(bContext *C, wmOperator *op, const wmEvent *event)
{
@@ -4781,6 +4647,7 @@ static int manipulator_invoke(bContext *C, wmOperator *op, const wmEvent *event)
void VIEW3D_OT_manipulator(wmOperatorType *ot)
{
+ PropertyRNA *prop;
/* identifiers */
ot->name = "3D Manipulator";
@@ -4795,23 +4662,30 @@ void VIEW3D_OT_manipulator(wmOperatorType *ot)
/* properties to pass to transform */
Transform_Properties(ot, P_CONSTRAINT);
- RNA_def_boolean(ot->srna, "use_planar_constraint", false, "Planar Constraint", "Limit the transformation to the "
- "two axes that have not been clicked (translate/scale only)");
+ prop = RNA_def_boolean(ot->srna, "use_planar_constraint", false, "Planar Constraint", "Limit the transformation to the "
+ "two axes that have not been clicked (translate/scale only)");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE | PROP_HIDDEN);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Enable Transform Manipulator Operator
+ * \{ */
+
static int enable_manipulator_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
View3D *v3d = CTX_wm_view3d(C);
v3d->twtype = 0;
-
+
if (RNA_boolean_get(op->ptr, "translate"))
v3d->twtype |= V3D_MANIP_TRANSLATE;
if (RNA_boolean_get(op->ptr, "rotate"))
v3d->twtype |= V3D_MANIP_ROTATE;
if (RNA_boolean_get(op->ptr, "scale"))
v3d->twtype |= V3D_MANIP_SCALE;
-
+
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
return OPERATOR_FINISHED;
@@ -4825,12 +4699,12 @@ void VIEW3D_OT_enable_manipulator(wmOperatorType *ot)
ot->name = "Enable 3D Manipulator";
ot->description = "Enable the transform manipulator for use";
ot->idname = "VIEW3D_OT_enable_manipulator";
-
+
/* api callbacks */
ot->invoke = enable_manipulator_invoke;
ot->poll = ED_operator_view3d_active;
-
- /* rna later */
+
+ /* properties */
prop = RNA_def_boolean(ot->srna, "translate", 0, "Translate", "Enable the translate manipulator");
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
prop = RNA_def_boolean(ot->srna, "rotate", 0, "Rotate", "Enable the rotate manipulator");
@@ -4839,7 +4713,11 @@ void VIEW3D_OT_enable_manipulator(wmOperatorType *ot)
RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
-/* ************************* Toggle rendered shading *********************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Toggle Render Shading Operator
+ * \{ */
static int toggle_render_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -4851,7 +4729,7 @@ static int toggle_render_exec(bContext *C, wmOperator *UNUSED(op))
v3d->prev_drawtype = v3d->drawtype;
v3d->drawtype = OB_RENDER;
}
- ED_view3d_shade_update(CTX_data_main(C), CTX_data_scene(C), v3d, CTX_wm_area(C));
+ ED_view3d_shade_update(CTX_data_main(C), v3d, CTX_wm_area(C));
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_VIEW3D, v3d);
return OPERATOR_FINISHED;
}
@@ -4868,374 +4746,4 @@ void VIEW3D_OT_toggle_render(wmOperatorType *ot)
ot->poll = ED_operator_view3d_active;
}
-/* ************************* below the line! *********************** */
-
-
-static float view_autodist_depth_margin(ARegion *ar, const int mval[2], int margin)
-{
- ViewDepths depth_temp = {0};
- rcti rect;
- float depth_close;
-
- if (margin == 0) {
- /* Get Z Depths, needed for perspective, nice for ortho */
- rect.xmin = mval[0];
- rect.ymin = mval[1];
- rect.xmax = mval[0] + 1;
- rect.ymax = mval[1] + 1;
- }
- else {
- rect.xmax = mval[0] + margin;
- rect.ymax = mval[1] + margin;
-
- rect.xmin = mval[0] - margin;
- rect.ymin = mval[1] - margin;
- }
-
- view3d_update_depths_rect(ar, &depth_temp, &rect);
- depth_close = view3d_depth_near(&depth_temp);
- MEM_SAFE_FREE(depth_temp.depths);
- return depth_close;
-}
-
-/**
- * Get the world-space 3d location from a screen-space 2d point.
- *
- * \param mval: Input screen-space pixel location.
- * \param mouse_worldloc: Output world-space location.
- * \param fallback_depth_pt: Use this points depth when no depth can be found.
- */
-bool ED_view3d_autodist(
- Scene *scene, ARegion *ar, View3D *v3d,
- const int mval[2], float mouse_worldloc[3],
- const bool alphaoverride, const float fallback_depth_pt[3])
-{
- bglMats mats; /* ZBuffer depth vars */
- float depth_close;
- double cent[2], p[3];
- int margin_arr[] = {0, 2, 4};
- int i;
- bool depth_ok = false;
-
- /* Get Z Depths, needed for perspective, nice for ortho */
- ED_view3d_draw_depth(scene, ar, v3d, alphaoverride);
-
- /* call after in case settings have been modified since last drawing, see: T47089 */
- bgl_get_mats(&mats);
-
- /* Attempt with low margin's first */
- i = 0;
- do {
- depth_close = view_autodist_depth_margin(ar, mval, margin_arr[i++] * U.pixelsize);
- depth_ok = (depth_close != FLT_MAX);
- } while ((depth_ok == false) && (i < ARRAY_SIZE(margin_arr)));
-
- if (depth_ok) {
- cent[0] = (double)mval[0] + 0.5;
- cent[1] = (double)mval[1] + 0.5;
-
- if (gluUnProject(cent[0], cent[1], depth_close,
- mats.modelview, mats.projection, (GLint *)mats.viewport, &p[0], &p[1], &p[2]))
- {
- mouse_worldloc[0] = (float)p[0];
- mouse_worldloc[1] = (float)p[1];
- mouse_worldloc[2] = (float)p[2];
- return true;
- }
- }
-
- if (fallback_depth_pt) {
- ED_view3d_win_to_3d_int(v3d, ar, fallback_depth_pt, mval, mouse_worldloc);
- return true;
- }
- else {
- return false;
- }
-}
-
-void ED_view3d_autodist_init(Scene *scene, ARegion *ar, View3D *v3d, int mode)
-{
- /* Get Z Depths, needed for perspective, nice for ortho */
- switch (mode) {
- case 0:
- ED_view3d_draw_depth(scene, ar, v3d, true);
- break;
- case 1:
- ED_view3d_draw_depth_gpencil(scene, ar, v3d);
- break;
- }
-}
-
-/* no 4x4 sampling, run #ED_view3d_autodist_init first */
-bool ED_view3d_autodist_simple(ARegion *ar, const int mval[2], float mouse_worldloc[3],
- int margin, float *force_depth)
-{
- bglMats mats; /* ZBuffer depth vars, could cache? */
- float depth;
- double cent[2], p[3];
-
- /* Get Z Depths, needed for perspective, nice for ortho */
- if (force_depth)
- depth = *force_depth;
- else
- depth = view_autodist_depth_margin(ar, mval, margin);
-
- if (depth == FLT_MAX)
- return false;
-
- cent[0] = (double)mval[0] + 0.5;
- cent[1] = (double)mval[1] + 0.5;
-
- bgl_get_mats(&mats);
-
- if (!gluUnProject(cent[0], cent[1], depth,
- mats.modelview, mats.projection, (GLint *)mats.viewport, &p[0], &p[1], &p[2]))
- {
- return false;
- }
-
- mouse_worldloc[0] = (float)p[0];
- mouse_worldloc[1] = (float)p[1];
- mouse_worldloc[2] = (float)p[2];
- return true;
-}
-
-bool ED_view3d_autodist_depth(ARegion *ar, const int mval[2], int margin, float *depth)
-{
- *depth = view_autodist_depth_margin(ar, mval, margin);
-
- return (*depth != FLT_MAX);
-}
-
-static bool depth_segment_cb(int x, int y, void *userData)
-{
- struct { ARegion *ar; int margin; float depth; } *data = userData;
- int mval[2];
- float depth;
-
- mval[0] = x;
- mval[1] = y;
-
- depth = view_autodist_depth_margin(data->ar, mval, data->margin);
-
- if (depth != FLT_MAX) {
- data->depth = depth;
- return 0;
- }
- else {
- return 1;
- }
-}
-
-bool ED_view3d_autodist_depth_seg(ARegion *ar, const int mval_sta[2], const int mval_end[2],
- int margin, float *depth)
-{
- struct { ARegion *ar; int margin; float depth; } data = {NULL};
- int p1[2];
- int p2[2];
-
- data.ar = ar;
- data.margin = margin;
- data.depth = FLT_MAX;
-
- copy_v2_v2_int(p1, mval_sta);
- copy_v2_v2_int(p2, mval_end);
-
- BLI_bitmap_draw_2d_line_v2v2i(p1, p2, depth_segment_cb, &data);
-
- *depth = data.depth;
-
- return (*depth != FLT_MAX);
-}
-
-/* problem - ofs[3] can be on same location as camera itself.
- * Blender needs proper dist value for zoom.
- * use fallback_dist to override small values
- */
-float ED_view3d_offset_distance(float mat[4][4], const float ofs[3], const float fallback_dist)
-{
- float pos[4] = {0.0f, 0.0f, 0.0f, 1.0f};
- float dir[4] = {0.0f, 0.0f, 1.0f, 0.0f};
- float dist;
-
- mul_m4_v4(mat, pos);
- add_v3_v3(pos, ofs);
- mul_m4_v4(mat, dir);
- normalize_v3(dir);
-
- dist = dot_v3v3(pos, dir);
-
- if ((dist < FLT_EPSILON) && (fallback_dist != 0.0f)) {
- dist = fallback_dist;
- }
-
- return dist;
-}
-
-/**
- * Set the dist without moving the view (compensate with #RegionView3D.ofs)
- *
- * \note take care that viewinv is up to date, #ED_view3d_update_viewmat first.
- */
-void ED_view3d_distance_set(RegionView3D *rv3d, const float dist)
-{
- float viewinv[4];
- float tvec[3];
-
- BLI_assert(dist >= 0.0f);
-
- copy_v3_fl3(tvec, 0.0f, 0.0f, rv3d->dist - dist);
- /* rv3d->viewinv isn't always valid */
-#if 0
- mul_mat3_m4_v3(rv3d->viewinv, tvec);
-#else
- invert_qt_qt_normalized(viewinv, rv3d->viewquat);
- mul_qt_v3(viewinv, tvec);
-#endif
- sub_v3_v3(rv3d->ofs, tvec);
-
- rv3d->dist = dist;
-}
-
-/**
- * Set the view transformation from a 4x4 matrix.
- *
- * \param mat The view 4x4 transformation matrix to assign.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
-void ED_view3d_from_m4(float mat[4][4], float ofs[3], float quat[4], float *dist)
-{
- float nmat[3][3];
-
- /* dist depends on offset */
- BLI_assert(dist == NULL || ofs != NULL);
-
- copy_m3_m4(nmat, mat);
- normalize_m3(nmat);
-
- /* Offset */
- if (ofs)
- negate_v3_v3(ofs, mat[3]);
-
- /* Quat */
- if (quat) {
- mat3_normalized_to_quat(quat, nmat);
- invert_qt_normalized(quat);
- }
-
- if (ofs && dist) {
- madd_v3_v3fl(ofs, nmat[2], *dist);
- }
-}
-
-/**
- * Calculate the view transformation matrix from RegionView3D input.
- * The resulting matrix is equivalent to RegionView3D.viewinv
- * \param mat The view 4x4 transformation matrix to calculate.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
-void ED_view3d_to_m4(float mat[4][4], const float ofs[3], const float quat[4], const float dist)
-{
- float iviewquat[4] = {-quat[0], quat[1], quat[2], quat[3]};
- float dvec[3] = {0.0f, 0.0f, dist};
-
- quat_to_mat4(mat, iviewquat);
- mul_mat3_m4_v3(mat, dvec);
- sub_v3_v3v3(mat[3], dvec, ofs);
-}
-
-/**
- * Set the RegionView3D members from an objects transformation and optionally lens.
- * \param ob The object to set the view to.
- * \param ofs The view offset to be set, normally from RegionView3D.ofs.
- * \param quat The view rotation to be set, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs to be set, normally from RegionView3D.dist.
- * \param lens The view lens angle set for cameras and lamps, normally from View3D.lens.
- */
-void ED_view3d_from_object(Object *ob, float ofs[3], float quat[4], float *dist, float *lens)
-{
- ED_view3d_from_m4(ob->obmat, ofs, quat, dist);
-
- if (lens) {
- CameraParams params;
-
- BKE_camera_params_init(&params);
- BKE_camera_params_from_object(&params, ob);
- *lens = params.lens;
- }
-}
-
-/**
- * Set the object transformation from RegionView3D members.
- * \param ob The object which has the transformation assigned.
- * \param ofs The view offset, normally from RegionView3D.ofs.
- * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
- * \param dist The view distance from ofs, normally from RegionView3D.dist.
- */
-void ED_view3d_to_object(Object *ob, const float ofs[3], const float quat[4], const float dist)
-{
- float mat[4][4];
- ED_view3d_to_m4(mat, ofs, quat, dist);
- BKE_object_apply_mat4(ob, mat, true, true);
-}
-
-/**
- * Use to store the last view, before entering camera view.
- */
-void ED_view3d_lastview_store(RegionView3D *rv3d)
-{
- copy_qt_qt(rv3d->lviewquat, rv3d->viewquat);
- rv3d->lview = rv3d->view;
- if (rv3d->persp != RV3D_CAMOB) {
- rv3d->lpersp = rv3d->persp;
- }
-}
-
-BGpic *ED_view3D_background_image_new(View3D *v3d)
-{
- BGpic *bgpic = MEM_callocN(sizeof(BGpic), "Background Image");
-
- bgpic->rotation = 0.0f;
- bgpic->size = 5.0f;
- bgpic->blend = 0.5f;
- bgpic->iuser.fie_ima = 2;
- bgpic->iuser.ok = 1;
- bgpic->view = 0; /* 0 for all */
- bgpic->flag |= V3D_BGPIC_EXPANDED;
-
- BLI_addtail(&v3d->bgpicbase, bgpic);
-
- return bgpic;
-}
-
-void ED_view3D_background_image_remove(View3D *v3d, BGpic *bgpic)
-{
- BLI_remlink(&v3d->bgpicbase, bgpic);
-
- MEM_freeN(bgpic);
-}
-
-void ED_view3D_background_image_clear(View3D *v3d)
-{
- BGpic *bgpic = v3d->bgpicbase.first;
-
- while (bgpic) {
- BGpic *next_bgpic = bgpic->next;
-
- ED_view3D_background_image_remove(v3d, bgpic);
-
- bgpic = next_bgpic;
- }
-}
-
-void ED_view3D_lock_clear(View3D *v3d)
-{
- v3d->ob_centre = NULL;
- v3d->ob_centre_bone[0] = '\0';
- v3d->ob_centre_cursor = false;
- v3d->flag2 &= ~V3D_LOCK_CAMERA;
-}
+/** \} */
diff --git a/source/blender/editors/space_view3d/view3d_fly.c b/source/blender/editors/space_view3d/view3d_fly.c
index 04a6aa215f4..eda780d01a7 100644
--- a/source/blender/editors/space_view3d/view3d_fly.c
+++ b/source/blender/editors/space_view3d/view3d_fly.c
@@ -97,7 +97,7 @@ typedef enum eFlyPanState {
/* called in transform_ops.c, on each regeneration of keymaps */
void fly_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{FLY_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{FLY_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
{FLY_MODAL_ACCELERATE, "ACCELERATE", 0, "Accelerate", ""},
@@ -351,7 +351,7 @@ static bool initFlyInfo(bContext *C, FlyInfo *fly, wmOperator *op, const wmEvent
fly->rv3d->persp = RV3D_PERSP;
}
- if (fly->rv3d->persp == RV3D_CAMOB && ID_IS_LINKED_DATABLOCK(fly->v3d->camera)) {
+ if (fly->rv3d->persp == RV3D_CAMOB && ID_IS_LINKED(fly->v3d->camera)) {
BKE_report(op->reports, RPT_ERROR, "Cannot fly a camera from an external library");
return false;
}
diff --git a/source/blender/editors/space_view3d/view3d_header.c b/source/blender/editors/space_view3d/view3d_header.c
index bf1bdf68619..d80ef486663 100644
--- a/source/blender/editors/space_view3d/view3d_header.c
+++ b/source/blender/editors/space_view3d/view3d_header.c
@@ -54,7 +54,7 @@
#include "WM_types.h"
#include "ED_mesh.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_screen.h"
#include "UI_interface.h"
@@ -318,7 +318,7 @@ void uiTemplateHeader3D(uiLayout *layout, struct bContext *C)
row = uiLayoutRow(layout, false);
{
- EnumPropertyItem *item = rna_enum_object_mode_items;
+ const EnumPropertyItem *item = rna_enum_object_mode_items;
const char *name = "";
int icon = ICON_OBJECT_DATAMODE;
@@ -350,7 +350,7 @@ void uiTemplateHeader3D(uiLayout *layout, struct bContext *C)
PointerRNA meshptr;
RNA_pointer_create(ob->data, &RNA_Mesh, ob->data, &meshptr);
- if (ob->mode & (OB_MODE_TEXTURE_PAINT | OB_MODE_VERTEX_PAINT)) {
+ if (ob->mode & (OB_MODE_TEXTURE_PAINT)) {
uiItemR(layout, &meshptr, "use_paint_mask", UI_ITEM_R_ICON_ONLY, "", ICON_NONE);
}
else {
diff --git a/source/blender/editors/space_view3d/view3d_intern.h b/source/blender/editors/space_view3d/view3d_intern.h
index b11f42bcfef..6237bfe6693 100644
--- a/source/blender/editors/space_view3d/view3d_intern.h
+++ b/source/blender/editors/space_view3d/view3d_intern.h
@@ -107,6 +107,7 @@ void VIEW3D_OT_zoom_border(struct wmOperatorType *ot);
void VIEW3D_OT_toggle_render(struct wmOperatorType *ot);
void view3d_boxview_copy(ScrArea *sa, ARegion *ar);
+void view3d_boxview_sync(ScrArea *sa, ARegion *ar);
void view3d_orbit_apply_dyn_ofs(
float r_ofs[3], const float ofs_old[3], const float viewquat_old[4],
@@ -142,7 +143,13 @@ void draw_motion_paths_cleanup(View3D *v3d);
/* drawobject.c */
-void draw_object(Scene *scene, struct ARegion *ar, View3D *v3d, Base *base, const short dflag);
+void draw_object(
+ Scene *scene, struct ARegion *ar, View3D *v3d,
+ Base *base, const short dflag);
+void draw_object_select(
+ Scene *scene, ARegion *ar, View3D *v3d,
+ Base *base, const short dflag);
+
bool draw_glsl_material(Scene *scene, struct Object *ob, View3D *v3d, const char dt);
void draw_object_instance(Scene *scene, View3D *v3d, RegionView3D *rv3d, struct Object *ob, const char dt, int outline);
void draw_object_backbufsel(Scene *scene, View3D *v3d, RegionView3D *rv3d, struct Object *ob);
@@ -152,7 +159,7 @@ void view3d_cached_text_draw_begin(void);
void view3d_cached_text_draw_add(const float co[3],
const char *str, const size_t str_len,
short xoffs, short flag, const unsigned char col[4]);
-void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write, float mat[4][4]);
+void view3d_cached_text_draw_end(View3D *v3d, ARegion *ar, bool depth_write);
bool check_object_draw_texture(struct Scene *scene, struct View3D *v3d, const char drawtype);
@@ -167,9 +174,10 @@ enum {
int view3d_effective_drawtype(const struct View3D *v3d);
/* drawarmature.c */
-bool draw_armature(Scene *scene, View3D *v3d, ARegion *ar, Base *base,
- const short dt, const short dflag, const unsigned char ob_wire_col[4],
- const bool is_outline);
+bool draw_armature(
+ Scene *scene, View3D *v3d, ARegion *ar, Base *base,
+ const short dt, const short dflag, const unsigned char ob_wire_col[4],
+ const bool is_outline);
/* drawmesh.c */
void draw_mesh_textured(Scene *scene, View3D *v3d, RegionView3D *rv3d,
@@ -193,9 +201,16 @@ void draw_sim_debug_data(Scene *scene, View3D *v3d, ARegion *ar);
/* view3d_draw.c */
void view3d_main_region_draw(const struct bContext *C, struct ARegion *ar);
-void ED_view3d_draw_depth(Scene *scene, struct ARegion *ar, View3D *v3d, bool alphaoverride);
+
+void ED_view3d_draw_depth(
+ Scene *scene,
+ struct ARegion *ar, View3D *v3d, bool alphaoverride);
void ED_view3d_draw_depth_gpencil(Scene *scene, ARegion *ar, View3D *v3d);
-void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag);
+void ED_view3d_draw_select_loop(
+ ViewContext *vc, Scene *scene, View3D *v3d, ARegion *ar,
+ bool use_obedit_skip, bool use_nearest);
+
+void ED_view3d_after_add(ListBase *lb, Base *base, const short dflag);\
void circf(float x, float y, float rad);
void circ(float x, float y, float rad);
@@ -241,8 +256,11 @@ void ED_view3d_smooth_view_force_finish(
struct bContext *C,
struct View3D *v3d, struct ARegion *ar);
-void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rctf *rect);
-void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d);
+void view3d_winmatrix_set(
+ ARegion *ar, const View3D *v3d, const rcti *rect);
+void view3d_viewmatrix_set(
+ Scene *scene,
+ const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2]);
void fly_modal_keymap(struct wmKeyConfig *keyconf);
void walk_modal_keymap(struct wmKeyConfig *keyconf);
diff --git a/source/blender/editors/space_view3d/view3d_iterators.c b/source/blender/editors/space_view3d/view3d_iterators.c
index ce4b7f7deeb..ef7b01f7a21 100644
--- a/source/blender/editors/space_view3d/view3d_iterators.c
+++ b/source/blender/editors/space_view3d/view3d_iterators.c
@@ -119,7 +119,7 @@ void meshobject_foreachScreenVert(
data.clip_flag = clip_flag;
if (clip_flag & V3D_PROJ_TEST_CLIP_BB) {
- ED_view3d_clipping_local(vc->rv3d, vc->obedit->obmat); /* for local clipping lookups */
+ ED_view3d_clipping_local(vc->rv3d, vc->obact->obmat);
}
dm->foreachMappedVert(dm, meshobject_foreachScreenVert__mapFunc, &data, DM_FOREACH_NOP);
diff --git a/source/blender/editors/space_view3d/view3d_ops.c b/source/blender/editors/space_view3d/view3d_ops.c
index 0fa6841fe27..d71639c35d2 100644
--- a/source/blender/editors/space_view3d/view3d_ops.c
+++ b/source/blender/editors/space_view3d/view3d_ops.c
@@ -241,13 +241,21 @@ void view3d_keymap(wmKeyConfig *keyconf)
keymap = WM_keymap_find(keyconf, "3D View", SPACE_VIEW3D, 0);
/* Shift+LMB behavior first, so it has priority over KM_ANY item below. */
- kmi = WM_keymap_verify_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
RNA_boolean_set(kmi->ptr, "release_confirm", true);
RNA_boolean_set(kmi->ptr, "use_planar_constraint", true);
+ RNA_boolean_set(kmi->ptr, "use_accurate", false);
+
+ kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "release_confirm", true);
+ RNA_boolean_set(kmi->ptr, "use_planar_constraint", false);
+ RNA_boolean_set(kmi->ptr, "use_accurate", true);
+
/* Using KM_ANY here to allow holding modifiers before starting to transform. */
kmi = WM_keymap_add_item(keymap, "VIEW3D_OT_manipulator", LEFTMOUSE, KM_PRESS, KM_ANY, 0);
RNA_boolean_set(kmi->ptr, "release_confirm", true);
RNA_boolean_set(kmi->ptr, "use_planar_constraint", false);
+ RNA_boolean_set(kmi->ptr, "use_accurate", false);
WM_keymap_verify_item(keymap, "VIEW3D_OT_cursor3d", ACTIONMOUSE, KM_PRESS, 0, 0);
diff --git a/source/blender/editors/space_view3d/view3d_project.c b/source/blender/editors/space_view3d/view3d_project.c
index 65a6dee2f6c..2e876bc48b3 100644
--- a/source/blender/editors/space_view3d/view3d_project.c
+++ b/source/blender/editors/space_view3d/view3d_project.c
@@ -278,6 +278,11 @@ eV3DProjStatus ED_view3d_project_float_object(const ARegion *ar, const float co[
/* More Generic Window/Ray/Vector projection functions
* *************************************************** */
+float ED_view3d_pixel_size(const RegionView3D *rv3d, const float co[3])
+{
+ return mul_project_m4_v3_zfac((float(*)[4])rv3d->persmat, co) * rv3d->pixsize * U.pixelsize;
+}
+
/**
* Calculate a depth value from \a co, use with #ED_view3d_win_to_delta
*/
diff --git a/source/blender/editors/space_view3d/view3d_ruler.c b/source/blender/editors/space_view3d/view3d_ruler.c
index aefe30bbe32..f2c87953302 100644
--- a/source/blender/editors/space_view3d/view3d_ruler.c
+++ b/source/blender/editors/space_view3d/view3d_ruler.c
@@ -48,7 +48,6 @@
#include "ED_screen.h"
#include "ED_view3d.h"
-#include "ED_transform.h"
#include "ED_transform_snap_object_context.h"
#include "ED_space_api.h"
@@ -1009,9 +1008,12 @@ static int view3d_ruler_modal(bContext *C, wmOperator *op, const wmEvent *event)
}
case RETKEY:
{
- view3d_ruler_to_gpencil(C, ruler_info);
- do_draw = true;
- exit_code = OPERATOR_FINISHED;
+ /* Enter may be used to invoke from search. */
+ if (event->val == KM_PRESS) {
+ view3d_ruler_to_gpencil(C, ruler_info);
+ do_draw = true;
+ exit_code = OPERATOR_FINISHED;
+ }
break;
}
case DELKEY:
diff --git a/source/blender/editors/space_view3d/view3d_select.c b/source/blender/editors/space_view3d/view3d_select.c
index 3239d07553f..d184081b03a 100644
--- a/source/blender/editors/space_view3d/view3d_select.c
+++ b/source/blender/editors/space_view3d/view3d_select.c
@@ -48,7 +48,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_math.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_rect.h"
#include "BLI_linklist.h"
#include "BLI_listbase.h"
@@ -70,8 +70,6 @@
#include "BKE_paint.h"
#include "BKE_editmesh.h"
#include "BKE_tracking.h"
-#include "BKE_utildefines.h"
-
#include "BIF_gl.h"
#include "BIF_glutil.h"
@@ -85,6 +83,7 @@
#include "ED_armature.h"
#include "ED_curve.h"
+#include "ED_lattice.h"
#include "ED_particle.h"
#include "ED_mesh.h"
#include "ED_object.h"
@@ -98,13 +97,15 @@
#include "view3d_intern.h" /* own include */
+// #include "PIL_time_utildefines.h"
+
float ED_view3d_select_dist_px(void)
{
return 75.0f * U.pixelsize;
}
/* TODO: should return whether there is valid context to continue */
-void view3d_set_viewcontext(bContext *C, ViewContext *vc)
+void ED_view3d_viewcontext_init(bContext *C, ViewContext *vc)
{
memset(vc, 0, sizeof(ViewContext));
vc->ar = CTX_wm_region(C);
@@ -246,9 +247,10 @@ typedef struct LassoSelectUserData {
bool is_changed;
} LassoSelectUserData;
-static void view3d_userdata_lassoselect_init(LassoSelectUserData *r_data,
- ViewContext *vc, const rcti *rect, const int (*mcords)[2],
- const int moves, const bool select)
+static void view3d_userdata_lassoselect_init(
+ LassoSelectUserData *r_data,
+ ViewContext *vc, const rcti *rect, const int (*mcords)[2],
+ const int moves, const bool select)
{
r_data->vc = vc;
@@ -323,7 +325,8 @@ static bool edge_inside_rect(const rctf *rect, const float v1[2], const float v2
return 1;
}
-static void do_lasso_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
+static void do_lasso_select_pose__doSelectBone(
+ void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
{
LassoSelectUserData *data = userData;
bArmature *arm = data->vc->obact->data;
@@ -410,8 +413,9 @@ static void object_deselect_all_visible(Scene *scene, View3D *v3d)
}
}
-static void do_lasso_select_objects(ViewContext *vc, const int mcords[][2], const short moves,
- const bool extend, const bool select)
+static void do_lasso_select_objects(
+ ViewContext *vc, const int mcords[][2], const short moves,
+ const bool extend, const bool select)
{
Base *base;
@@ -444,7 +448,8 @@ static void do_lasso_select_mesh__doSelectVert(void *userData, BMVert *eve, cons
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void do_lasso_select_mesh__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
+static void do_lasso_select_mesh__doSelectEdge(
+ void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
{
LassoSelectUserData *data = userData;
@@ -536,7 +541,8 @@ static void do_lasso_select_mesh(ViewContext *vc, const int mcords[][2], short m
EDBM_selectmode_flush(vc->em);
}
-static void do_lasso_select_curve__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
+static void do_lasso_select_curve__doSelect(
+ void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
LassoSelectUserData *data = userData;
Object *obedit = data->vc->obedit;
@@ -611,7 +617,8 @@ static void do_lasso_select_lattice(ViewContext *vc, const int mcords[][2], shor
lattice_foreachScreenVert(vc, do_lasso_select_lattice__doSelect, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
-static void do_lasso_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
+static void do_lasso_select_armature__doSelectBone(
+ void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
{
LassoSelectUserData *data = userData;
bArmature *arm = data->vc->obedit->data;
@@ -674,14 +681,14 @@ static void do_lasso_select_armature(ViewContext *vc, const int mcords[][2], sho
ED_view3d_init_mats_rv3d(vc->obedit, vc->rv3d);
if (extend == false && select)
- ED_armature_deselect_all_visible(vc->obedit);
+ ED_armature_edit_deselect_all_visible(vc->obedit);
armature_foreachScreenBone(vc, do_lasso_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
if (data.is_changed) {
bArmature *arm = vc->obedit->data;
- ED_armature_sync_selection(arm->edbo);
- ED_armature_validate_active(arm);
+ ED_armature_edit_sync_selection(arm->edbo);
+ ED_armature_edit_validate_active(arm);
WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
}
}
@@ -717,14 +724,15 @@ static void do_lasso_select_meta(ViewContext *vc, const int mcords[][2], short m
mball_foreachScreenElem(vc, do_lasso_select_mball__doSelectElem, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
}
-static void do_lasso_select_meshobject__doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
+static void do_lasso_select_meshobject__doSelectVert(
+ void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
{
LassoSelectUserData *data = userData;
if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co) &&
BLI_lasso_is_point_inside(data->mcords, data->moves, screen_co[0], screen_co[1], IS_CLIPPED))
{
- BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
+ SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
}
}
static void do_lasso_select_paintvert(ViewContext *vc, const int mcords[][2], short moves, bool extend, bool select)
@@ -822,9 +830,10 @@ static void do_lasso_select_node(int mcords[][2], short moves, const bool select
}
#endif
-static void view3d_lasso_select(bContext *C, ViewContext *vc,
- const int mcords[][2], short moves,
- bool extend, bool select)
+static void view3d_lasso_select(
+ bContext *C, ViewContext *vc,
+ const int mcords[][2], short moves,
+ bool extend, bool select)
{
Object *ob = CTX_data_active_object(C);
@@ -884,7 +893,7 @@ static int view3d_lasso_select_exec(bContext *C, wmOperator *op)
view3d_operator_needs_opengl(C);
/* setup view context for argument to callbacks */
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
extend = RNA_boolean_get(op->ptr, "extend");
select = !RNA_boolean_get(op->ptr, "deselect");
@@ -912,66 +921,12 @@ void VIEW3D_OT_select_lasso(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
-}
-
-
-/* ************************************************* */
-
-#if 0
-/* smart function to sample a rect spiralling outside, nice for backbuf selection */
-static unsigned int samplerect(unsigned int *buf, int size, unsigned int dontdo)
-{
- Base *base;
- unsigned int *bufmin, *bufmax;
- int a, b, rc, tel, len, dirvec[4][2], maxob;
- unsigned int retval = 0;
-
- base = LASTBASE;
- if (base == 0) return 0;
- maxob = base->selcol;
-
- len = (size - 1) / 2;
- rc = 0;
-
- dirvec[0][0] = 1;
- dirvec[0][1] = 0;
- dirvec[1][0] = 0;
- dirvec[1][1] = -size;
- dirvec[2][0] = -1;
- dirvec[2][1] = 0;
- dirvec[3][0] = 0;
- dirvec[3][1] = size;
-
- bufmin = buf;
- bufmax = buf + size * size;
- buf += len * size + len;
-
- for (tel = 1; tel <= size; tel++) {
-
- for (a = 0; a < 2; a++) {
- for (b = 0; b < tel; b++) {
-
- if (*buf && *buf <= maxob && *buf != dontdo) return *buf;
- if (*buf == dontdo) retval = dontdo; /* if only color dontdo is available, still return dontdo */
-
- buf += (dirvec[rc][0] + dirvec[rc][1]);
-
- if (buf < bufmin || buf >= bufmax) return retval;
- }
- rc++;
- rc &= 3;
- }
- }
- return retval;
+ /* properties */
+ WM_operator_properties_gesture_lasso_select(ot);
}
-#endif
/* ************************** mouse select ************************* */
-
/* The max number of menu items in an object select menu */
typedef struct SelMenuItemF {
char idname[MAX_ID_NAME - 2];
@@ -982,7 +937,8 @@ typedef struct SelMenuItemF {
static SelMenuItemF object_mouse_select_menu_data[SEL_MENU_SIZE];
/* special (crappy) operator only for menu select */
-static EnumPropertyItem *object_select_menu_enum_itemf(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *object_select_menu_enum_itemf(
+ bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL, item_tmp = {0};
int totitem = 0;
@@ -1087,7 +1043,9 @@ static void deselectall_except(Scene *scene, Base *b) /* deselect all except b
}
}
-static Base *object_mouse_select_menu(bContext *C, ViewContext *vc, unsigned int *buffer, int hits, const int mval[2], short toggle)
+static Base *object_mouse_select_menu(
+ bContext *C, ViewContext *vc, unsigned int *buffer, int hits,
+ const int mval[2], bool toggle)
{
short baseCount = 0;
bool ok;
@@ -1166,7 +1124,7 @@ static Base *object_mouse_select_menu(bContext *C, ViewContext *vc, unsigned int
}
}
-static bool selectbuffer_has_bones(const unsigned int *buffer, const unsigned int hits)
+static bool selectbuffer_has_bones(const uint *buffer, const uint hits)
{
unsigned int i;
for (i = 0; i < hits; i++) {
@@ -1178,19 +1136,19 @@ static bool selectbuffer_has_bones(const unsigned int *buffer, const unsigned in
}
/* utility function for mixed_bones_object_selectbuffer */
-static short selectbuffer_ret_hits_15(unsigned int *UNUSED(buffer), const short hits15)
+static int selectbuffer_ret_hits_15(unsigned int *UNUSED(buffer), const int hits15)
{
return hits15;
}
-static short selectbuffer_ret_hits_9(unsigned int *buffer, const short hits15, const short hits9)
+static int selectbuffer_ret_hits_9(unsigned int *buffer, const int hits15, const int hits9)
{
const int offs = 4 * hits15;
memcpy(buffer, buffer + offs, 4 * hits9 * sizeof(unsigned int));
return hits9;
}
-static short selectbuffer_ret_hits_5(unsigned int *buffer, const short hits15, const short hits9, const short hits5)
+static int selectbuffer_ret_hits_5(unsigned int *buffer, const int hits15, const int hits9, const int hits5)
{
const int offs = 4 * hits15 + 4 * hits9;
memcpy(buffer, buffer + offs, 4 * hits5 * sizeof(unsigned int));
@@ -1199,14 +1157,13 @@ static short selectbuffer_ret_hits_5(unsigned int *buffer, const short hits15, c
/* we want a select buffer with bones, if there are... */
/* so check three selection levels and compare */
-static short mixed_bones_object_selectbuffer(
+static int mixed_bones_object_selectbuffer(
ViewContext *vc, unsigned int *buffer, const int mval[2],
bool use_cycle, bool enumerate,
bool *r_do_nearest)
{
rcti rect;
- int offs;
- short hits15, hits9 = 0, hits5 = 0;
+ int hits15, hits9 = 0, hits5 = 0;
bool has_bones15 = false, has_bones9 = false, has_bones5 = false;
static int last_mval[2] = {-100, -100};
bool do_nearest = false;
@@ -1234,49 +1191,63 @@ static short mixed_bones_object_selectbuffer(
do_nearest = do_nearest && !enumerate;
- BLI_rcti_init(&rect, mval[0] - 14, mval[0] + 14, mval[1] - 14, mval[1] + 14);
- hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, do_nearest);
+ const int select_mode = (do_nearest ? VIEW3D_SELECT_PICK_NEAREST : VIEW3D_SELECT_PICK_ALL);
+ int hits = 0;
+
+ /* we _must_ end cache before return, use 'goto finally' */
+ view3d_opengl_select_cache_begin();
+
+ BLI_rcti_init_pt_radius(&rect, mval, 14);
+ hits15 = view3d_opengl_select(vc, buffer, MAXPICKBUF, &rect, select_mode);
if (hits15 == 1) {
- return selectbuffer_ret_hits_15(buffer, hits15);
+ hits = selectbuffer_ret_hits_15(buffer, hits15);
+ goto finally;
}
else if (hits15 > 0) {
+ int offs;
has_bones15 = selectbuffer_has_bones(buffer, hits15);
offs = 4 * hits15;
- BLI_rcti_init(&rect, mval[0] - 9, mval[0] + 9, mval[1] - 9, mval[1] + 9);
- hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, do_nearest);
+ BLI_rcti_init_pt_radius(&rect, mval, 9);
+ hits9 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode);
if (hits9 == 1) {
- return selectbuffer_ret_hits_9(buffer, hits15, hits9);
+ hits = selectbuffer_ret_hits_9(buffer, hits15, hits9);
+ goto finally;
}
else if (hits9 > 0) {
has_bones9 = selectbuffer_has_bones(buffer + offs, hits9);
offs += 4 * hits9;
- BLI_rcti_init(&rect, mval[0] - 5, mval[0] + 5, mval[1] - 5, mval[1] + 5);
- hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, do_nearest);
+ BLI_rcti_init_pt_radius(&rect, mval, 5);
+ hits5 = view3d_opengl_select(vc, buffer + offs, MAXPICKBUF - offs, &rect, select_mode);
if (hits5 == 1) {
- return selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
+ hits = selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
+ goto finally;
}
else if (hits5 > 0) {
has_bones5 = selectbuffer_has_bones(buffer + offs, hits5);
}
}
- if (has_bones5) return selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
- else if (has_bones9) return selectbuffer_ret_hits_9(buffer, hits15, hits9);
- else if (has_bones15) return selectbuffer_ret_hits_15(buffer, hits15);
-
- if (hits5 > 0) return selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5);
- else if (hits9 > 0) return selectbuffer_ret_hits_9(buffer, hits15, hits9);
- else return selectbuffer_ret_hits_15(buffer, hits15);
+ if (has_bones5) { hits = selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5); goto finally; }
+ else if (has_bones9) { hits = selectbuffer_ret_hits_9(buffer, hits15, hits9); goto finally; }
+ else if (has_bones15) { hits = selectbuffer_ret_hits_15(buffer, hits15); goto finally; }
+
+ if (hits5 > 0) { hits = selectbuffer_ret_hits_5(buffer, hits15, hits9, hits5); goto finally; }
+ else if (hits9 > 0) { hits = selectbuffer_ret_hits_9(buffer, hits15, hits9); goto finally; }
+ else { hits = selectbuffer_ret_hits_15(buffer, hits15); goto finally; }
}
-
- return 0;
+
+finally:
+ view3d_opengl_select_cache_end();
+
+ return hits;
}
/* returns basact */
-static Base *mouse_select_eval_buffer(ViewContext *vc, unsigned int *buffer, int hits,
- Base *startbase, bool has_bones, bool do_nearest)
+static Base *mouse_select_eval_buffer(
+ ViewContext *vc, const uint *buffer, int hits,
+ Base *startbase, bool has_bones, bool do_nearest)
{
Scene *scene = vc->scene;
View3D *v3d = vc->v3d;
@@ -1368,7 +1339,7 @@ Base *ED_view3d_give_base_under_cursor(bContext *C, const int mval[2])
/* setup view context for argument to callbacks */
view3d_operator_needs_opengl(C);
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, false, false, &do_nearest);
@@ -1412,12 +1383,12 @@ static bool ed_object_select_pick(
bool is_obedit;
float dist = ED_view3d_select_dist_px() * 1.3333f;
bool retval = false;
- short hits;
+ int hits;
const float mval_fl[2] = {(float)mval[0], (float)mval[1]};
/* setup view context for argument to callbacks */
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
is_obedit = (vc.obedit != NULL);
if (object) {
@@ -1442,8 +1413,9 @@ static bool ed_object_select_pick(
while (base) {
if (BASE_SELECTABLE(v3d, base)) {
float screen_co[2];
- if (ED_view3d_project_float_global(ar, base->object->obmat[3], screen_co,
- V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ if (ED_view3d_project_float_global(
+ ar, base->object->obmat[3], screen_co,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
{
float dist_temp = len_manhattan_v2v2(mval_fl, screen_co);
if (base == BASACT) dist_temp += 10.0f;
@@ -1464,10 +1436,13 @@ static bool ed_object_select_pick(
unsigned int buffer[MAXPICKBUF];
bool do_nearest;
+ // TIMEIT_START(select_time);
+
/* if objects have posemode set, the bones are in the same selection buffer */
-
hits = mixed_bones_object_selectbuffer(&vc, buffer, mval, true, enumerate, &do_nearest);
-
+
+ // TIMEIT_END(select_time);
+
if (hits > 0) {
/* note: bundles are handling in the same way as bones */
const bool has_bones = selectbuffer_has_bones(buffer, hits);
@@ -1539,7 +1514,9 @@ static bool ed_object_select_pick(
}
}
}
- else if (ED_do_pose_selectbuffer(scene, basact, buffer, hits, extend, deselect, toggle, do_nearest)) {
+ else if (ED_armature_pose_select_pick_with_buffer(
+ scene, basact, buffer, hits, extend, deselect, toggle, do_nearest))
+ {
/* then bone is found */
/* we make the armature selected:
@@ -1626,8 +1603,9 @@ typedef struct BoxSelectUserData {
bool is_changed;
} BoxSelectUserData;
-static void view3d_userdata_boxselect_init(BoxSelectUserData *r_data,
- ViewContext *vc, const rcti *rect, const bool select)
+static void view3d_userdata_boxselect_init(
+ BoxSelectUserData *r_data,
+ ViewContext *vc, const rcti *rect, const bool select)
{
r_data->vc = vc;
@@ -1654,7 +1632,7 @@ static void do_paintvert_box_select__doSelectVert(void *userData, MVert *mv, con
BoxSelectUserData *data = userData;
if (BLI_rctf_isect_pt_v(data->rect_fl, screen_co)) {
- BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
+ SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
}
}
static int do_paintvert_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
@@ -1740,7 +1718,8 @@ static int do_paintvert_box_select(ViewContext *vc, rcti *rect, bool select, boo
return OPERATOR_FINISHED;
}
-static void do_nurbs_box_select__doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
+static void do_nurbs_box_select__doSelect(
+ void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
BoxSelectUserData *data = userData;
Object *obedit = data->vc->obedit;
@@ -1818,7 +1797,8 @@ static void do_mesh_box_select__doSelectVert(void *userData, BMVert *eve, const
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void do_mesh_box_select__doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
+static void do_mesh_box_select__doSelectEdge(
+ void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int index)
{
BoxSelectUserData *data = userData;
@@ -1904,9 +1884,9 @@ static int do_meta_box_select(ViewContext *vc, rcti *rect, bool select, bool ext
int a;
unsigned int buffer[MAXPICKBUF];
- short hits;
+ int hits;
- hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, false);
+ hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL);
if (extend == false && select)
BKE_mball_deselect_all(mb);
@@ -1934,36 +1914,35 @@ static int do_meta_box_select(ViewContext *vc, rcti *rect, bool select, bool ext
static int do_armature_box_select(ViewContext *vc, rcti *rect, bool select, bool extend)
{
bArmature *arm = vc->obedit->data;
- EditBone *ebone;
int a;
unsigned int buffer[MAXPICKBUF];
- short hits;
+ int hits;
- hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, false);
+ hits = view3d_opengl_select(vc, buffer, MAXPICKBUF, rect, VIEW3D_SELECT_ALL);
/* clear flag we use to detect point was affected */
- for (ebone = arm->edbo->first; ebone; ebone = ebone->next)
+ for (EditBone *ebone = arm->edbo->first; ebone; ebone = ebone->next)
ebone->flag &= ~BONE_DONE;
if (extend == false && select)
- ED_armature_deselect_all_visible(vc->obedit);
+ ED_armature_edit_deselect_all_visible(vc->obedit);
/* first we only check points inside the border */
for (a = 0; a < hits; a++) {
int index = buffer[(4 * a) + 3];
if (index != -1) {
- ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
if ((index & 0xFFFF0000) == 0) {
continue;
}
+ EditBone *ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
if (index & BONESEL_TIP) {
ebone->flag |= BONE_DONE;
if (select) ebone->flag |= BONE_TIPSEL;
else ebone->flag &= ~BONE_TIPSEL;
}
-
+
if (index & BONESEL_ROOT) {
ebone->flag |= BONE_DONE;
if (select) ebone->flag |= BONE_ROOTSEL;
@@ -1972,34 +1951,37 @@ static int do_armature_box_select(ViewContext *vc, rcti *rect, bool select, bool
}
}
}
-
+
/* now we have to flush tag from parents... */
- for (ebone = arm->edbo->first; ebone; ebone = ebone->next) {
+ for (EditBone *ebone = arm->edbo->first; ebone; ebone = ebone->next) {
if (ebone->parent && (ebone->flag & BONE_CONNECTED)) {
- if (ebone->parent->flag & BONE_DONE)
+ if (ebone->parent->flag & BONE_DONE) {
ebone->flag |= BONE_DONE;
+ }
}
}
-
+
/* only select/deselect entire bones when no points where in the rect */
for (a = 0; a < hits; a++) {
int index = buffer[(4 * a) + 3];
if (index != -1) {
- ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
if (index & BONESEL_BONE) {
+ EditBone *ebone = BLI_findlink(arm->edbo, index & ~(BONESEL_ANY));
if ((select == false) || ((ebone->flag & BONE_UNSELECTABLE) == 0)) {
if (!(ebone->flag & BONE_DONE)) {
- if (select)
+ if (select) {
ebone->flag |= (BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
- else
+ }
+ else {
ebone->flag &= ~(BONE_ROOTSEL | BONE_TIPSEL | BONE_SELECTED);
+ }
}
}
}
}
}
- ED_armature_sync_selection(arm->edbo);
+ ED_armature_edit_sync_selection(arm->edbo);
return hits > 0 ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
@@ -2008,12 +1990,12 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, b
{
Bone *bone;
Object *ob = vc->obact;
- unsigned int *vbuffer = NULL; /* selection buffer */
- unsigned int *col; /* color in buffer */
+ unsigned int *vbuffer = NULL; /* selection buffer */
+ unsigned int *col; /* color in buffer */
int bone_only;
int bone_selected = 0;
int totobj = MAXPICKBUF; /* XXX solve later */
- short hits;
+ int hits;
if ((ob) && (ob->mode & OB_MODE_POSE))
bone_only = 1;
@@ -2037,7 +2019,7 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, b
/* selection buffer now has bones potentially too, so we add MAXPICKBUF */
vbuffer = MEM_mallocN(4 * (totobj + MAXPICKELEMS) * sizeof(unsigned int), "selection buffer");
- hits = view3d_opengl_select(vc, vbuffer, 4 * (totobj + MAXPICKELEMS), rect, false);
+ hits = view3d_opengl_select(vc, vbuffer, 4 * (totobj + MAXPICKELEMS), rect, VIEW3D_SELECT_ALL);
/*
* LOGIC NOTES (theeth):
* The buffer and ListBase have the same relative order, which makes the selection
@@ -2058,7 +2040,7 @@ static int do_object_pose_box_select(bContext *C, ViewContext *vc, rcti *rect, b
if (BASE_SELECTABLE(vc->v3d, base)) {
while (base->selcol == (*col & 0xFFFF)) { /* we got an object */
if (*col & 0xFFFF0000) { /* we got a bone */
- bone = get_indexed_bone(base->object, *col & ~(BONESEL_ANY));
+ bone = ED_armature_bone_find_index(base->object, *col & ~(BONESEL_ANY));
if (bone) {
if (select) {
if ((bone->flag & BONE_UNSELECTABLE) == 0) {
@@ -2117,11 +2099,11 @@ static int view3d_borderselect_exec(bContext *C, wmOperator *op)
view3d_operator_needs_opengl(C);
/* setup view context for argument to callbacks */
- view3d_set_viewcontext(C, &vc);
+ ED_view3d_viewcontext_init(C, &vc);
- select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
- WM_operator_properties_border_to_rcti(op, &rect);
+ select = !RNA_boolean_get(op->ptr, "deselect");
extend = RNA_boolean_get(op->ptr, "extend");
+ WM_operator_properties_border_to_rcti(op, &rect);
if (vc.obedit) {
switch (vc.obedit->type) {
@@ -2196,17 +2178,17 @@ void VIEW3D_OT_select_border(wmOperatorType *ot)
ot->idname = "VIEW3D_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = view3d_borderselect_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = view3d_selectable_data;
- ot->cancel = WM_border_select_cancel;
+ ot->cancel = WM_gesture_border_cancel;
/* flags */
ot->flag = OPTYPE_UNDO;
/* rna */
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
@@ -2295,7 +2277,7 @@ static int view3d_select_exec(bContext *C, wmOperator *op)
if (obedit->type == OB_MESH)
retval = EDBM_select_pick(C, location, extend, deselect, toggle);
else if (obedit->type == OB_ARMATURE)
- retval = ED_armature_select_pick(C, location, extend, deselect, toggle);
+ retval = ED_armature_edit_select_pick(C, location, extend, deselect, toggle);
else if (obedit->type == OB_LATTICE)
retval = ED_lattice_select_pick(C, location, extend, deselect, toggle);
else if (ELEM(obedit->type, OB_CURVE, OB_SURF))
@@ -2374,8 +2356,9 @@ typedef struct CircleSelectUserData {
bool is_changed;
} CircleSelectUserData;
-static void view3d_userdata_circleselect_init(CircleSelectUserData *r_data,
- ViewContext *vc, const bool select, const int mval[2], const float rad)
+static void view3d_userdata_circleselect_init(
+ CircleSelectUserData *r_data,
+ ViewContext *vc, const bool select, const int mval[2], const float rad)
{
r_data->vc = vc;
r_data->select = select;
@@ -2398,7 +2381,8 @@ static void mesh_circle_doSelectVert(void *userData, BMVert *eve, const float sc
BM_vert_select_set(data->vc->em->bm, eve, data->select);
}
}
-static void mesh_circle_doSelectEdge(void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
+static void mesh_circle_doSelectEdge(
+ void *userData, BMEdge *eed, const float screen_co_a[2], const float screen_co_b[2], int UNUSED(index))
{
CircleSelectUserData *data = userData;
@@ -2475,12 +2459,13 @@ static void paint_facesel_circle_select(ViewContext *vc, const bool select, cons
}
}
-static void paint_vertsel_circle_select_doSelectVert(void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
+static void paint_vertsel_circle_select_doSelectVert(
+ void *userData, MVert *mv, const float screen_co[2], int UNUSED(index))
{
CircleSelectUserData *data = userData;
if (len_squared_v2v2(data->mval_fl, screen_co) <= data->radius_squared) {
- BKE_BIT_TEST_SET(mv->flag, data->select, SELECT);
+ SET_FLAG_FROM_TEST(mv->flag, data->select, SELECT);
}
}
static void paint_vertsel_circle_select(ViewContext *vc, const bool select, const int mval[2], float rad)
@@ -2516,7 +2501,8 @@ static void paint_vertsel_circle_select(ViewContext *vc, const bool select, cons
}
-static void nurbscurve_circle_doSelect(void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
+static void nurbscurve_circle_doSelect(
+ void *userData, Nurb *UNUSED(nu), BPoint *bp, BezTriple *bezt, int beztindex, const float screen_co[2])
{
CircleSelectUserData *data = userData;
Object *obedit = data->vc->obedit;
@@ -2577,7 +2563,7 @@ static void lattice_circle_select(ViewContext *vc, const bool select, const int
/* NOTE: pose-bone case is copied from editbone case... */
-static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, const float screen_co[2])
+static bool pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, const float screen_co[2])
{
CircleSelectUserData *data = userData;
@@ -2590,7 +2576,8 @@ static short pchan_circle_doSelectJoint(void *userData, bPoseChannel *pchan, con
}
return 0;
}
-static void do_circle_select_pose__doSelectBone(void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
+static void do_circle_select_pose__doSelectBone(
+ void *userData, struct bPoseChannel *pchan, const float screen_co_a[2], const float screen_co_b[2])
{
CircleSelectUserData *data = userData;
bArmature *arm = data->vc->obact->data;
@@ -2655,7 +2642,7 @@ static void pose_circle_select(ViewContext *vc, const bool select, const int mva
}
}
-static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, const float screen_co[2], short head)
+static bool armature_circle_doSelectJoint(void *userData, EditBone *ebone, const float screen_co[2], bool head)
{
CircleSelectUserData *data = userData;
@@ -2676,7 +2663,8 @@ static short armature_circle_doSelectJoint(void *userData, EditBone *ebone, cons
}
return 0;
}
-static void do_circle_select_armature__doSelectBone(void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
+static void do_circle_select_armature__doSelectBone(
+ void *userData, struct EditBone *ebone, const float screen_co_a[2], const float screen_co_b[2])
{
CircleSelectUserData *data = userData;
bArmature *arm = data->vc->obedit->data;
@@ -2731,8 +2719,8 @@ static void armature_circle_select(ViewContext *vc, const bool select, const int
armature_foreachScreenBone(vc, do_circle_select_armature__doSelectBone, &data, V3D_PROJ_TEST_CLIP_DEFAULT);
if (data.is_changed) {
- ED_armature_sync_selection(arm->edbo);
- ED_armature_validate_active(arm);
+ ED_armature_edit_sync_selection(arm->edbo);
+ ED_armature_edit_validate_active(arm);
WM_main_add_notifier(NC_OBJECT | ND_BONE_SELECT, vc->obedit);
}
}
@@ -2797,8 +2785,9 @@ static bool object_circle_select(ViewContext *vc, const bool select, const int m
for (base = FIRSTBASE; base; base = base->next) {
if (BASE_SELECTABLE(vc->v3d, base) && ((base->flag & SELECT) != select_flag)) {
float screen_co[2];
- if (ED_view3d_project_float_global(vc->ar, base->object->obmat[3], screen_co,
- V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
+ if (ED_view3d_project_float_global(
+ vc->ar, base->object->obmat[3], screen_co,
+ V3D_PROJ_TEST_CLIP_BB | V3D_PROJ_TEST_CLIP_WIN | V3D_PROJ_TEST_CLIP_NEAR) == V3D_PROJ_RET_OK)
{
if (len_squared_v2v2(mval_fl, screen_co) <= radius_squared) {
ED_base_object_select(base, select ? BA_SELECT : BA_DESELECT);
@@ -2814,22 +2803,19 @@ static bool object_circle_select(ViewContext *vc, const bool select, const int m
/* not a real operator, only for circle test */
static int view3d_circle_select_exec(bContext *C, wmOperator *op)
{
- Scene *scene = CTX_data_scene(C);
- Object *obact = CTX_data_active_object(C);
+ ViewContext vc;
+ ED_view3d_viewcontext_init(C, &vc);
+ Object *obact = vc.obact;
+ Object *obedit = vc.obedit;
const int radius = RNA_int_get(op->ptr, "radius");
- const int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
const int mval[2] = {RNA_int_get(op->ptr, "x"),
RNA_int_get(op->ptr, "y")};
- if (CTX_data_edit_object(C) || BKE_paint_select_elem_test(obact) ||
+ if (obedit || BKE_paint_select_elem_test(obact) ||
(obact && (obact->mode & (OB_MODE_PARTICLE_EDIT | OB_MODE_POSE))) )
{
- ViewContext vc;
-
view3d_operator_needs_opengl(C);
-
- view3d_set_viewcontext(C, &vc);
if (CTX_data_edit_object(C)) {
obedit_circle_select(&vc, select, mval, (float)radius);
@@ -2843,23 +2829,22 @@ static int view3d_circle_select_exec(bContext *C, wmOperator *op)
paint_vertsel_circle_select(&vc, select, mval, (float)radius);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obact->data);
}
- else if (obact->mode & OB_MODE_POSE)
+ else if (obact->mode & OB_MODE_POSE) {
pose_circle_select(&vc, select, mval, (float)radius);
- else
+ }
+ else {
return PE_circle_select(C, select, mval, (float)radius);
+ }
}
else if (obact && obact->mode & OB_MODE_SCULPT) {
return OPERATOR_CANCELLED;
}
else {
- ViewContext vc;
- view3d_set_viewcontext(C, &vc);
-
if (object_circle_select(&vc, select, mval, (float)radius)) {
- WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, scene);
+ WM_event_add_notifier(C, NC_SCENE | ND_OB_SELECT, vc.scene);
}
}
-
+
return OPERATOR_FINISHED;
}
@@ -2877,9 +2862,7 @@ void VIEW3D_OT_select_circle(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
-
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Event Type", "", INT_MIN, INT_MAX);
+
+ /* properties */
+ WM_operator_properties_gesture_circle_select(ot);
}
diff --git a/source/blender/editors/space_view3d/view3d_toolbar.c b/source/blender/editors/space_view3d/view3d_toolbar.c
index 62f605ab99c..dfa64bd2015 100644
--- a/source/blender/editors/space_view3d/view3d_toolbar.c
+++ b/source/blender/editors/space_view3d/view3d_toolbar.c
@@ -55,7 +55,7 @@
#include "RNA_access.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "UI_interface.h"
#include "UI_resources.h"
@@ -67,7 +67,7 @@
static void view3d_panel_operator_redo_buts(const bContext *C, Panel *pa, wmOperator *op)
{
- uiLayoutOperatorButs(C, pa->layout, op, NULL, 'V', 0);
+ uiTemplateOperatorPropertyButs(C, pa->layout, op, NULL, 'V', 0);
}
static void view3d_panel_operator_redo_header(const bContext *C, Panel *pa)
@@ -218,7 +218,7 @@ static void view3d_panel_tool_shelf(const bContext *C, Panel *pa)
for (ct = st->toolshelf.first; ct; ct = ct->next) {
if (STREQLEN(context, ct->context, OP_MAX_TYPENAME)) {
col = uiLayoutColumn(pa->layout, true);
- uiItemFullO(col, ct->opname, NULL, ICON_NONE, NULL, WM_OP_INVOKE_REGION_WIN, 0);
+ uiItemFullO(col, ct->opname, NULL, ICON_NONE, NULL, WM_OP_INVOKE_REGION_WIN, 0, NULL);
}
}
}
diff --git a/source/blender/editors/space_view3d/view3d_utils.c b/source/blender/editors/space_view3d/view3d_utils.c
new file mode 100644
index 00000000000..e06ae89fa89
--- /dev/null
+++ b/source/blender/editors/space_view3d/view3d_utils.c
@@ -0,0 +1,1506 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2008 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/space_view3d/view3d_utils.c
+ * \ingroup spview3d
+ *
+ * 3D View checks and manipulation (no operators).
+ */
+
+#include <string.h>
+#include <stdio.h>
+#include <math.h>
+#include <float.h>
+
+#include "DNA_camera_types.h"
+#include "DNA_curve_types.h"
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_bitmap_draw_2d.h"
+#include "BLI_blenlib.h"
+#include "BLI_math.h"
+#include "BLI_utildefines.h"
+
+#include "BKE_camera.h"
+#include "BKE_context.h"
+#include "BKE_object.h"
+#include "BKE_screen.h"
+#include "BKE_depsgraph.h" /* for ED_view3d_camera_lock_sync */
+
+#include "BIF_gl.h"
+#include "BIF_glutil.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_keyframing.h"
+#include "ED_screen.h"
+#include "ED_view3d.h"
+
+#include "view3d_intern.h" /* own include */
+
+/* -------------------------------------------------------------------- */
+/** \name View Data Access Utilities
+ *
+ * \{ */
+
+float *ED_view3d_cursor3d_get(Scene *scene, View3D *v3d)
+{
+ if (v3d && v3d->localvd) return v3d->cursor;
+ else return scene->cursor;
+}
+
+Camera *ED_view3d_camera_data_get(View3D *v3d, RegionView3D *rv3d)
+{
+ /* establish the camera object, so we can default to view mapping if anything is wrong with it */
+ if ((rv3d->persp == RV3D_CAMOB) && v3d->camera && (v3d->camera->type == OB_CAMERA)) {
+ return v3d->camera->data;
+ }
+ else {
+ return NULL;
+ }
+}
+
+void ED_view3d_dist_range_get(
+ const View3D *v3d,
+ float r_dist_range[2])
+{
+ r_dist_range[0] = v3d->grid * 0.001f;
+ r_dist_range[1] = v3d->far * 10.0f;
+}
+
+/**
+ * \note copies logic of #ED_view3d_viewplane_get(), keep in sync.
+ */
+bool ED_view3d_clip_range_get(
+ const View3D *v3d, const RegionView3D *rv3d,
+ float *r_clipsta, float *r_clipend,
+ const bool use_ortho_factor)
+{
+ CameraParams params;
+
+ BKE_camera_params_init(&params);
+ BKE_camera_params_from_view3d(&params, v3d, rv3d);
+
+ if (use_ortho_factor && params.is_ortho) {
+ const float fac = 2.0f / (params.clipend - params.clipsta);
+ params.clipsta *= fac;
+ params.clipend *= fac;
+ }
+
+ if (r_clipsta) *r_clipsta = params.clipsta;
+ if (r_clipend) *r_clipend = params.clipend;
+
+ return params.is_ortho;
+}
+
+bool ED_view3d_viewplane_get(
+ const View3D *v3d, const RegionView3D *rv3d, int winx, int winy,
+ rctf *r_viewplane, float *r_clipsta, float *r_clipend, float *r_pixsize)
+{
+ CameraParams params;
+
+ BKE_camera_params_init(&params);
+ BKE_camera_params_from_view3d(&params, v3d, rv3d);
+ BKE_camera_params_compute_viewplane(&params, winx, winy, 1.0f, 1.0f);
+
+ if (r_viewplane) *r_viewplane = params.viewplane;
+ if (r_clipsta) *r_clipsta = params.clipsta;
+ if (r_clipend) *r_clipend = params.clipend;
+ if (r_pixsize) *r_pixsize = params.viewdx;
+
+ return params.is_ortho;
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name View State/Context Utilities
+ *
+ * \{ */
+
+/**
+ * Use this call when executing an operator,
+ * event system doesn't set for each event the OpenGL drawing context.
+ */
+void view3d_operator_needs_opengl(const bContext *C)
+{
+ wmWindow *win = CTX_wm_window(C);
+ ARegion *ar = CTX_wm_region(C);
+
+ view3d_region_operator_needs_opengl(win, ar);
+}
+
+void view3d_region_operator_needs_opengl(wmWindow *win, ARegion *ar)
+{
+ /* for debugging purpose, context should always be OK */
+ if ((ar == NULL) || (ar->regiontype != RGN_TYPE_WINDOW)) {
+ printf("view3d_region_operator_needs_opengl error, wrong region\n");
+ }
+ else {
+ RegionView3D *rv3d = ar->regiondata;
+
+ wmSubWindowSet(win, ar->swinid);
+ glMatrixMode(GL_PROJECTION);
+ glLoadMatrixf(rv3d->winmat);
+ glMatrixMode(GL_MODELVIEW);
+ glLoadMatrixf(rv3d->viewmat);
+ }
+}
+
+/**
+ * Use instead of: ``bglPolygonOffset(rv3d->dist, ...)`` see bug [#37727]
+ */
+void ED_view3d_polygon_offset(const RegionView3D *rv3d, const float dist)
+{
+ float viewdist;
+
+ if (rv3d->rflag & RV3D_ZOFFSET_DISABLED) {
+ return;
+ }
+
+ viewdist = rv3d->dist;
+
+ /* special exception for ortho camera (viewdist isnt used for perspective cameras) */
+ if (dist != 0.0f) {
+ if (rv3d->persp == RV3D_CAMOB) {
+ if (rv3d->is_persp == false) {
+ viewdist = 1.0f / max_ff(fabsf(rv3d->winmat[0][0]), fabsf(rv3d->winmat[1][1]));
+ }
+ }
+ }
+
+ bglPolygonOffset(viewdist, dist);
+}
+
+bool ED_view3d_context_activate(bContext *C)
+{
+ bScreen *sc = CTX_wm_screen(C);
+ ScrArea *sa = CTX_wm_area(C);
+ ARegion *ar;
+
+ /* sa can be NULL when called from python */
+ if (sa == NULL || sa->spacetype != SPACE_VIEW3D) {
+ sa = BKE_screen_find_big_area(sc, SPACE_VIEW3D, 0);
+ }
+
+ if (sa == NULL) {
+ return false;
+ }
+
+ ar = BKE_area_find_region_active_win(sa);
+ if (ar == NULL) {
+ return false;
+ }
+
+ /* bad context switch .. */
+ CTX_wm_area_set(C, sa);
+ CTX_wm_region_set(C, ar);
+
+ return true;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Clipping Utilities
+ *
+ * \{ */
+void ED_view3d_clipping_calc_from_boundbox(float clip[4][4], const BoundBox *bb, const bool is_flip)
+{
+ int val;
+
+ for (val = 0; val < 4; val++) {
+ normal_tri_v3(clip[val], bb->vec[val], bb->vec[val == 3 ? 0 : val + 1], bb->vec[val + 4]);
+ if (UNLIKELY(is_flip)) {
+ negate_v3(clip[val]);
+ }
+
+ clip[val][3] = -dot_v3v3(clip[val], bb->vec[val]);
+ }
+}
+
+void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
+{
+ float modelview[4][4];
+ double xs, ys, p[3];
+ int val, flip_sign, a;
+
+ /* near zero floating point values can give issues with gluUnProject
+ * in side view on some implementations */
+ if (fabs(mats->modelview[0]) < 1e-6) mats->modelview[0] = 0.0;
+ if (fabs(mats->modelview[5]) < 1e-6) mats->modelview[5] = 0.0;
+
+ /* Set up viewport so that gluUnProject will give correct values */
+ mats->viewport[0] = 0;
+ mats->viewport[1] = 0;
+
+ /* four clipping planes and bounding volume */
+ /* first do the bounding volume */
+ for (val = 0; val < 4; val++) {
+ xs = (val == 0 || val == 3) ? rect->xmin : rect->xmax;
+ ys = (val == 0 || val == 1) ? rect->ymin : rect->ymax;
+
+ gluUnProject(xs, ys, 0.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
+ copy_v3fl_v3db(bb->vec[val], p);
+
+ gluUnProject(xs, ys, 1.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
+ copy_v3fl_v3db(bb->vec[4 + val], p);
+ }
+
+ /* verify if we have negative scale. doing the transform before cross
+ * product flips the sign of the vector compared to doing cross product
+ * before transform then, so we correct for that. */
+ for (a = 0; a < 16; a++)
+ ((float *)modelview)[a] = mats->modelview[a];
+ flip_sign = is_negative_m4(modelview);
+
+ ED_view3d_clipping_calc_from_boundbox(planes, bb, flip_sign);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Bound-Box Utilities
+ *
+ * \{ */
+
+static bool view3d_boundbox_clip_m4(const BoundBox *bb, float persmatob[4][4])
+{
+ int a, flag = -1, fl;
+
+ for (a = 0; a < 8; a++) {
+ float vec[4], min, max;
+ copy_v3_v3(vec, bb->vec[a]);
+ vec[3] = 1.0;
+ mul_m4_v4(persmatob, vec);
+ max = vec[3];
+ min = -vec[3];
+
+ fl = 0;
+ if (vec[0] < min) fl += 1;
+ if (vec[0] > max) fl += 2;
+ if (vec[1] < min) fl += 4;
+ if (vec[1] > max) fl += 8;
+ if (vec[2] < min) fl += 16;
+ if (vec[2] > max) fl += 32;
+
+ flag &= fl;
+ if (flag == 0) return true;
+ }
+
+ return false;
+}
+
+bool ED_view3d_boundbox_clip_ex(const RegionView3D *rv3d, const BoundBox *bb, float obmat[4][4])
+{
+ /* return 1: draw */
+
+ float persmatob[4][4];
+
+ if (bb == NULL) return true;
+ if (bb->flag & BOUNDBOX_DISABLED) return true;
+
+ mul_m4_m4m4(persmatob, (float(*)[4])rv3d->persmat, obmat);
+
+ return view3d_boundbox_clip_m4(bb, persmatob);
+}
+
+bool ED_view3d_boundbox_clip(RegionView3D *rv3d, const BoundBox *bb)
+{
+ if (bb == NULL) return true;
+ if (bb->flag & BOUNDBOX_DISABLED) return true;
+
+ return view3d_boundbox_clip_m4(bb, rv3d->persmatob);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Perspective & Mode Switching
+ *
+ * Misc view utility functions.
+ * \{ */
+
+bool ED_view3d_offset_lock_check(const View3D *v3d, const RegionView3D *rv3d)
+{
+ return (rv3d->persp != RV3D_CAMOB) && (v3d->ob_centre_cursor || v3d->ob_centre);
+}
+
+/**
+ * Use to store the last view, before entering camera view.
+ */
+void ED_view3d_lastview_store(RegionView3D *rv3d)
+{
+ copy_qt_qt(rv3d->lviewquat, rv3d->viewquat);
+ rv3d->lview = rv3d->view;
+ if (rv3d->persp != RV3D_CAMOB) {
+ rv3d->lpersp = rv3d->persp;
+ }
+}
+
+void ED_view3d_lock_clear(View3D *v3d)
+{
+ v3d->ob_centre = NULL;
+ v3d->ob_centre_bone[0] = '\0';
+ v3d->ob_centre_cursor = false;
+ v3d->flag2 &= ~V3D_LOCK_CAMERA;
+}
+
+/**
+ * For viewport operators that exit camera perspective.
+ *
+ * \note This differs from simply setting ``rv3d->persp = persp`` because it
+ * sets the ``ofs`` and ``dist`` values of the viewport so it matches the camera,
+ * otherwise switching out of camera view may jump to a different part of the scene.
+ */
+void ED_view3d_persp_switch_from_camera(View3D *v3d, RegionView3D *rv3d, const char persp)
+{
+ BLI_assert(rv3d->persp == RV3D_CAMOB);
+ BLI_assert(persp != RV3D_CAMOB);
+
+ if (v3d->camera) {
+ rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
+ ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
+ }
+
+ if (!ED_view3d_camera_lock_check(v3d, rv3d)) {
+ rv3d->persp = persp;
+ }
+}
+/**
+ * Action to take when rotating the view,
+ * handle auto-persp and logic for switching out of views.
+ *
+ * shared with NDOF.
+ */
+bool ED_view3d_persp_ensure(struct View3D *v3d, ARegion *ar)
+{
+ RegionView3D *rv3d = ar->regiondata;
+ const bool autopersp = (U.uiflag & USER_AUTOPERSP) != 0;
+
+ BLI_assert((rv3d->viewlock & RV3D_LOCKED) == 0);
+
+ if (ED_view3d_camera_lock_check(v3d, rv3d))
+ return false;
+
+ if (rv3d->persp != RV3D_PERSP) {
+ if (rv3d->persp == RV3D_CAMOB) {
+ /* If autopersp and previous view was an axis one, switch back to PERSP mode, else reuse previous mode. */
+ char persp = (autopersp && RV3D_VIEW_IS_AXIS(rv3d->lview)) ? RV3D_PERSP : rv3d->lpersp;
+ ED_view3d_persp_switch_from_camera(v3d, rv3d, persp);
+ }
+ else if (autopersp && RV3D_VIEW_IS_AXIS(rv3d->view)) {
+ rv3d->persp = RV3D_PERSP;
+ }
+ return true;
+ }
+
+ return false;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Camera Lock API
+ *
+ * Lock the camera to the view-port, allowing view manipulation to transform the camera.
+ * \{ */
+
+/**
+ * \return true when the view-port is locked to its camera.
+ */
+bool ED_view3d_camera_lock_check(const View3D *v3d, const RegionView3D *rv3d)
+{
+ return ((v3d->camera) &&
+ (!ID_IS_LINKED(v3d->camera)) &&
+ (v3d->flag2 & V3D_LOCK_CAMERA) &&
+ (rv3d->persp == RV3D_CAMOB));
+}
+
+/**
+ * Apply the camera object transformation to the view-port.
+ * (needed so we can use regular view-port manipulation operators, that sync back to the camera).
+ */
+void ED_view3d_camera_lock_init_ex(View3D *v3d, RegionView3D *rv3d, const bool calc_dist)
+{
+ if (ED_view3d_camera_lock_check(v3d, rv3d)) {
+ if (calc_dist) {
+ /* using a fallback dist is OK here since ED_view3d_from_object() compensates for it */
+ rv3d->dist = ED_view3d_offset_distance(v3d->camera->obmat, rv3d->ofs, VIEW3D_DIST_FALLBACK);
+ }
+ ED_view3d_from_object(v3d->camera, rv3d->ofs, rv3d->viewquat, &rv3d->dist, NULL);
+ }
+}
+
+void ED_view3d_camera_lock_init(View3D *v3d, RegionView3D *rv3d)
+{
+ ED_view3d_camera_lock_init_ex(v3d, rv3d, true);
+}
+
+/**
+ * Apply the view-port transformation back to the camera object.
+ *
+ * \return true if the camera is moved.
+ */
+bool ED_view3d_camera_lock_sync(View3D *v3d, RegionView3D *rv3d)
+{
+ if (ED_view3d_camera_lock_check(v3d, rv3d)) {
+ ObjectTfmProtectedChannels obtfm;
+ Object *root_parent;
+
+ if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
+ Object *ob_update;
+ float tmat[4][4];
+ float imat[4][4];
+ float view_mat[4][4];
+ float diff_mat[4][4];
+ float parent_mat[4][4];
+
+ while (root_parent->parent) {
+ root_parent = root_parent->parent;
+ }
+
+ ED_view3d_to_m4(view_mat, rv3d->ofs, rv3d->viewquat, rv3d->dist);
+
+ normalize_m4_m4(tmat, v3d->camera->obmat);
+
+ invert_m4_m4(imat, tmat);
+ mul_m4_m4m4(diff_mat, view_mat, imat);
+
+ mul_m4_m4m4(parent_mat, diff_mat, root_parent->obmat);
+
+ BKE_object_tfm_protected_backup(root_parent, &obtfm);
+ BKE_object_apply_mat4(root_parent, parent_mat, true, false);
+ BKE_object_tfm_protected_restore(root_parent, &obtfm, root_parent->protectflag);
+
+ ob_update = v3d->camera;
+ while (ob_update) {
+ DAG_id_tag_update(&ob_update->id, OB_RECALC_OB);
+ WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, ob_update);
+ ob_update = ob_update->parent;
+ }
+ }
+ else {
+ /* always maintain the same scale */
+ const short protect_scale_all = (OB_LOCK_SCALEX | OB_LOCK_SCALEY | OB_LOCK_SCALEZ);
+ BKE_object_tfm_protected_backup(v3d->camera, &obtfm);
+ ED_view3d_to_object(v3d->camera, rv3d->ofs, rv3d->viewquat, rv3d->dist);
+ BKE_object_tfm_protected_restore(v3d->camera, &obtfm, v3d->camera->protectflag | protect_scale_all);
+
+ DAG_id_tag_update(&v3d->camera->id, OB_RECALC_OB);
+ WM_main_add_notifier(NC_OBJECT | ND_TRANSFORM, v3d->camera);
+ }
+
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+bool ED_view3d_camera_autokey(
+ Scene *scene, ID *id_key,
+ struct bContext *C, const bool do_rotate, const bool do_translate)
+{
+ if (autokeyframe_cfra_can_key(scene, id_key)) {
+ const float cfra = (float)CFRA;
+ ListBase dsources = {NULL, NULL};
+
+ /* add data-source override for the camera object */
+ ANIM_relative_keyingset_add_source(&dsources, id_key, NULL, NULL);
+
+ /* insert keyframes
+ * 1) on the first frame
+ * 2) on each subsequent frame
+ * TODO: need to check in future that frame changed before doing this
+ */
+ if (do_rotate) {
+ struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_ROTATION_ID);
+ ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
+ }
+ if (do_translate) {
+ struct KeyingSet *ks = ANIM_get_keyingset_for_autokeying(scene, ANIM_KS_LOCATION_ID);
+ ANIM_apply_keyingset(C, &dsources, NULL, ks, MODIFYKEY_MODE_INSERT, cfra);
+ }
+
+ /* free temp data */
+ BLI_freelistN(&dsources);
+
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+/**
+ * Call after modifying a locked view.
+ *
+ * \note Not every view edit currently auto-keys (numpad for eg),
+ * this is complicated because of smoothview.
+ */
+bool ED_view3d_camera_lock_autokey(
+ View3D *v3d, RegionView3D *rv3d,
+ struct bContext *C, const bool do_rotate, const bool do_translate)
+{
+ /* similar to ED_view3d_cameracontrol_update */
+ if (ED_view3d_camera_lock_check(v3d, rv3d)) {
+ Scene *scene = CTX_data_scene(C);
+ ID *id_key;
+ Object *root_parent;
+ if ((U.uiflag & USER_CAM_LOCK_NO_PARENT) == 0 && (root_parent = v3d->camera->parent)) {
+ while (root_parent->parent) {
+ root_parent = root_parent->parent;
+ }
+ id_key = &root_parent->id;
+ }
+ else {
+ id_key = &v3d->camera->id;
+ }
+
+ return ED_view3d_camera_autokey(scene, id_key, C, do_rotate, do_translate);
+ }
+ else {
+ return false;
+ }
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Box View Support
+ *
+ * Use with quad-split so each view is clipped by the bounds of each view axis.
+ * \{ */
+
+static void view3d_boxview_clip(ScrArea *sa)
+{
+ ARegion *ar;
+ BoundBox *bb = MEM_callocN(sizeof(BoundBox), "clipbb");
+ float clip[6][4];
+ float x1 = 0.0f, y1 = 0.0f, z1 = 0.0f, ofs[3] = {0.0f, 0.0f, 0.0f};
+ int val;
+
+ /* create bounding box */
+ for (ar = sa->regionbase.first; ar; ar = ar->next) {
+ if (ar->regiontype == RGN_TYPE_WINDOW) {
+ RegionView3D *rv3d = ar->regiondata;
+
+ if (rv3d->viewlock & RV3D_BOXCLIP) {
+ if (ELEM(rv3d->view, RV3D_VIEW_TOP, RV3D_VIEW_BOTTOM)) {
+ if (ar->winx > ar->winy) x1 = rv3d->dist;
+ else x1 = ar->winx * rv3d->dist / ar->winy;
+
+ if (ar->winx > ar->winy) y1 = ar->winy * rv3d->dist / ar->winx;
+ else y1 = rv3d->dist;
+ copy_v2_v2(ofs, rv3d->ofs);
+ }
+ else if (ELEM(rv3d->view, RV3D_VIEW_FRONT, RV3D_VIEW_BACK)) {
+ ofs[2] = rv3d->ofs[2];
+
+ if (ar->winx > ar->winy) z1 = ar->winy * rv3d->dist / ar->winx;
+ else z1 = rv3d->dist;
+ }
+ }
+ }
+ }
+
+ for (val = 0; val < 8; val++) {
+ if (ELEM(val, 0, 3, 4, 7))
+ bb->vec[val][0] = -x1 - ofs[0];
+ else
+ bb->vec[val][0] = x1 - ofs[0];
+
+ if (ELEM(val, 0, 1, 4, 5))
+ bb->vec[val][1] = -y1 - ofs[1];
+ else
+ bb->vec[val][1] = y1 - ofs[1];
+
+ if (val > 3)
+ bb->vec[val][2] = -z1 - ofs[2];
+ else
+ bb->vec[val][2] = z1 - ofs[2];
+ }
+
+ /* normals for plane equations */
+ normal_tri_v3(clip[0], bb->vec[0], bb->vec[1], bb->vec[4]);
+ normal_tri_v3(clip[1], bb->vec[1], bb->vec[2], bb->vec[5]);
+ normal_tri_v3(clip[2], bb->vec[2], bb->vec[3], bb->vec[6]);
+ normal_tri_v3(clip[3], bb->vec[3], bb->vec[0], bb->vec[7]);
+ normal_tri_v3(clip[4], bb->vec[4], bb->vec[5], bb->vec[6]);
+ normal_tri_v3(clip[5], bb->vec[0], bb->vec[2], bb->vec[1]);
+
+ /* then plane equations */
+ for (val = 0; val < 6; val++) {
+ clip[val][3] = -dot_v3v3(clip[val], bb->vec[val % 5]);
+ }
+
+ /* create bounding box */
+ for (ar = sa->regionbase.first; ar; ar = ar->next) {
+ if (ar->regiontype == RGN_TYPE_WINDOW) {
+ RegionView3D *rv3d = ar->regiondata;
+
+ if (rv3d->viewlock & RV3D_BOXCLIP) {
+ rv3d->rflag |= RV3D_CLIPPING;
+ memcpy(rv3d->clip, clip, sizeof(clip));
+ if (rv3d->clipbb) MEM_freeN(rv3d->clipbb);
+ rv3d->clipbb = MEM_dupallocN(bb);
+ }
+ }
+ }
+ MEM_freeN(bb);
+}
+
+/**
+ * Find which axis values are shared between both views and copy to \a rv3d_dst
+ * taking axis flipping into account.
+ */
+static void view3d_boxview_sync_axis(RegionView3D *rv3d_dst, RegionView3D *rv3d_src)
+{
+ /* absolute axis values above this are considered to be set (will be ~1.0f) */
+ const float axis_eps = 0.5f;
+ float viewinv[4];
+
+ /* use the view rotation to identify which axis to sync on */
+ float view_axis_all[4][3] = {
+ {1.0f, 0.0f, 0.0f},
+ {0.0f, 1.0f, 0.0f},
+ {1.0f, 0.0f, 0.0f},
+ {0.0f, 1.0f, 0.0f}};
+
+ float *view_src_x = &view_axis_all[0][0];
+ float *view_src_y = &view_axis_all[1][0];
+
+ float *view_dst_x = &view_axis_all[2][0];
+ float *view_dst_y = &view_axis_all[3][0];
+ int i;
+
+
+ /* we could use rv3d->viewinv, but better not depend on view matrix being updated */
+ if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_src->view, viewinv) == false)) {
+ return;
+ }
+ invert_qt_normalized(viewinv);
+ mul_qt_v3(viewinv, view_src_x);
+ mul_qt_v3(viewinv, view_src_y);
+
+ if (UNLIKELY(ED_view3d_quat_from_axis_view(rv3d_dst->view, viewinv) == false)) {
+ return;
+ }
+ invert_qt_normalized(viewinv);
+ mul_qt_v3(viewinv, view_dst_x);
+ mul_qt_v3(viewinv, view_dst_y);
+
+ /* check source and dest have a matching axis */
+ for (i = 0; i < 3; i++) {
+ if (((fabsf(view_src_x[i]) > axis_eps) || (fabsf(view_src_y[i]) > axis_eps)) &&
+ ((fabsf(view_dst_x[i]) > axis_eps) || (fabsf(view_dst_y[i]) > axis_eps)))
+ {
+ rv3d_dst->ofs[i] = rv3d_src->ofs[i];
+ }
+ }
+}
+
+/* sync center/zoom view of region to others, for view transforms */
+void view3d_boxview_sync(ScrArea *sa, ARegion *ar)
+{
+ ARegion *artest;
+ RegionView3D *rv3d = ar->regiondata;
+ short clip = 0;
+
+ for (artest = sa->regionbase.first; artest; artest = artest->next) {
+ if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
+ RegionView3D *rv3dtest = artest->regiondata;
+
+ if (rv3dtest->viewlock & RV3D_LOCKED) {
+ rv3dtest->dist = rv3d->dist;
+ view3d_boxview_sync_axis(rv3dtest, rv3d);
+ clip |= rv3dtest->viewlock & RV3D_BOXCLIP;
+
+ ED_region_tag_redraw(artest);
+ }
+ }
+ }
+
+ if (clip) {
+ view3d_boxview_clip(sa);
+ }
+}
+
+/* for home, center etc */
+void view3d_boxview_copy(ScrArea *sa, ARegion *ar)
+{
+ ARegion *artest;
+ RegionView3D *rv3d = ar->regiondata;
+ bool clip = false;
+
+ for (artest = sa->regionbase.first; artest; artest = artest->next) {
+ if (artest != ar && artest->regiontype == RGN_TYPE_WINDOW) {
+ RegionView3D *rv3dtest = artest->regiondata;
+
+ if (rv3dtest->viewlock) {
+ rv3dtest->dist = rv3d->dist;
+ copy_v3_v3(rv3dtest->ofs, rv3d->ofs);
+ ED_region_tag_redraw(artest);
+
+ clip |= ((rv3dtest->viewlock & RV3D_BOXCLIP) != 0);
+ }
+ }
+ }
+
+ if (clip) {
+ view3d_boxview_clip(sa);
+ }
+}
+
+/* 'clip' is used to know if our clip setting has changed */
+void ED_view3d_quadview_update(ScrArea *sa, ARegion *ar, bool do_clip)
+{
+ ARegion *ar_sync = NULL;
+ RegionView3D *rv3d = ar->regiondata;
+ short viewlock;
+ /* this function copies flags from the first of the 3 other quadview
+ * regions to the 2 other, so it assumes this is the region whose
+ * properties are always being edited, weak */
+ viewlock = rv3d->viewlock;
+
+ if ((viewlock & RV3D_LOCKED) == 0) {
+ do_clip = (viewlock & RV3D_BOXCLIP) != 0;
+ viewlock = 0;
+ }
+ else if ((viewlock & RV3D_BOXVIEW) == 0 && (viewlock & RV3D_BOXCLIP) != 0) {
+ do_clip = true;
+ viewlock &= ~RV3D_BOXCLIP;
+ }
+
+ for (; ar; ar = ar->prev) {
+ if (ar->alignment == RGN_ALIGN_QSPLIT) {
+ rv3d = ar->regiondata;
+ rv3d->viewlock = viewlock;
+
+ if (do_clip && (viewlock & RV3D_BOXCLIP) == 0) {
+ rv3d->rflag &= ~RV3D_BOXCLIP;
+ }
+
+ /* use ar_sync so we sync with one of the aligned views below
+ * else the view jumps on changing view settings like 'clip'
+ * since it copies from the perspective view */
+ ar_sync = ar;
+ }
+ }
+
+ if (rv3d->viewlock & RV3D_BOXVIEW) {
+ view3d_boxview_sync(sa, ar_sync ? ar_sync : sa->regionbase.last);
+ }
+
+ /* ensure locked regions have an axis, locked user views don't make much sense */
+ if (viewlock & RV3D_LOCKED) {
+ int index_qsplit = 0;
+ for (ar = sa->regionbase.first; ar; ar = ar->next) {
+ if (ar->alignment == RGN_ALIGN_QSPLIT) {
+ rv3d = ar->regiondata;
+ if (rv3d->viewlock) {
+ if (!RV3D_VIEW_IS_AXIS(rv3d->view)) {
+ rv3d->view = ED_view3d_lock_view_from_index(index_qsplit);
+ rv3d->persp = RV3D_ORTHO;
+ ED_view3d_lock(rv3d);
+ }
+ }
+ index_qsplit++;
+ }
+ }
+ }
+
+ ED_area_tag_redraw(sa);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Auto-Depth Utilities
+ * \{ */
+
+static float view_autodist_depth_margin(ARegion *ar, const int mval[2], int margin)
+{
+ ViewDepths depth_temp = {0};
+ rcti rect;
+ float depth_close;
+
+ if (margin == 0) {
+ /* Get Z Depths, needed for perspective, nice for ortho */
+ rect.xmin = mval[0];
+ rect.ymin = mval[1];
+ rect.xmax = mval[0] + 1;
+ rect.ymax = mval[1] + 1;
+ }
+ else {
+ BLI_rcti_init_pt_radius(&rect, mval, margin);
+ }
+
+ view3d_update_depths_rect(ar, &depth_temp, &rect);
+ depth_close = view3d_depth_near(&depth_temp);
+ MEM_SAFE_FREE(depth_temp.depths);
+ return depth_close;
+}
+
+/**
+ * Get the world-space 3d location from a screen-space 2d point.
+ *
+ * \param mval: Input screen-space pixel location.
+ * \param mouse_worldloc: Output world-space location.
+ * \param fallback_depth_pt: Use this points depth when no depth can be found.
+ */
+bool ED_view3d_autodist(
+ Scene *scene, ARegion *ar, View3D *v3d,
+ const int mval[2], float mouse_worldloc[3],
+ const bool alphaoverride, const float fallback_depth_pt[3])
+{
+ bglMats mats; /* ZBuffer depth vars */
+ float depth_close;
+ double cent[2], p[3];
+ int margin_arr[] = {0, 2, 4};
+ int i;
+ bool depth_ok = false;
+
+ /* Get Z Depths, needed for perspective, nice for ortho */
+ ED_view3d_draw_depth(scene, ar, v3d, alphaoverride);
+
+ /* call after in case settings have been modified since last drawing, see: T47089 */
+ bgl_get_mats(&mats);
+
+ /* Attempt with low margin's first */
+ i = 0;
+ do {
+ depth_close = view_autodist_depth_margin(ar, mval, margin_arr[i++] * U.pixelsize);
+ depth_ok = (depth_close != FLT_MAX);
+ } while ((depth_ok == false) && (i < ARRAY_SIZE(margin_arr)));
+
+ if (depth_ok) {
+ cent[0] = (double)mval[0] + 0.5;
+ cent[1] = (double)mval[1] + 0.5;
+
+ if (gluUnProject(cent[0], cent[1], depth_close,
+ mats.modelview, mats.projection, (GLint *)mats.viewport, &p[0], &p[1], &p[2]))
+ {
+ mouse_worldloc[0] = (float)p[0];
+ mouse_worldloc[1] = (float)p[1];
+ mouse_worldloc[2] = (float)p[2];
+ return true;
+ }
+ }
+
+ if (fallback_depth_pt) {
+ ED_view3d_win_to_3d_int(v3d, ar, fallback_depth_pt, mval, mouse_worldloc);
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+void ED_view3d_autodist_init(Scene *scene, ARegion *ar, View3D *v3d, int mode)
+{
+ /* Get Z Depths, needed for perspective, nice for ortho */
+ switch (mode) {
+ case 0:
+ ED_view3d_draw_depth(scene, ar, v3d, true);
+ break;
+ case 1:
+ ED_view3d_draw_depth_gpencil(scene, ar, v3d);
+ break;
+ }
+}
+
+/* no 4x4 sampling, run #ED_view3d_autodist_init first */
+bool ED_view3d_autodist_simple(
+ ARegion *ar, const int mval[2], float mouse_worldloc[3],
+ int margin, float *force_depth)
+{
+ bglMats mats; /* ZBuffer depth vars, could cache? */
+ float depth;
+ double cent[2], p[3];
+
+ /* Get Z Depths, needed for perspective, nice for ortho */
+ if (force_depth)
+ depth = *force_depth;
+ else
+ depth = view_autodist_depth_margin(ar, mval, margin);
+
+ if (depth == FLT_MAX)
+ return false;
+
+ cent[0] = (double)mval[0] + 0.5;
+ cent[1] = (double)mval[1] + 0.5;
+
+ bgl_get_mats(&mats);
+
+ if (!gluUnProject(cent[0], cent[1], depth,
+ mats.modelview, mats.projection, (GLint *)mats.viewport, &p[0], &p[1], &p[2]))
+ {
+ return false;
+ }
+
+ mouse_worldloc[0] = (float)p[0];
+ mouse_worldloc[1] = (float)p[1];
+ mouse_worldloc[2] = (float)p[2];
+ return true;
+}
+
+bool ED_view3d_autodist_depth(ARegion *ar, const int mval[2], int margin, float *depth)
+{
+ *depth = view_autodist_depth_margin(ar, mval, margin);
+
+ return (*depth != FLT_MAX);
+}
+
+static bool depth_segment_cb(int x, int y, void *userData)
+{
+ struct { ARegion *ar; int margin; float depth; } *data = userData;
+ int mval[2];
+ float depth;
+
+ mval[0] = x;
+ mval[1] = y;
+
+ depth = view_autodist_depth_margin(data->ar, mval, data->margin);
+
+ if (depth != FLT_MAX) {
+ data->depth = depth;
+ return 0;
+ }
+ else {
+ return 1;
+ }
+}
+
+bool ED_view3d_autodist_depth_seg(
+ ARegion *ar, const int mval_sta[2], const int mval_end[2],
+ int margin, float *depth)
+{
+ struct { ARegion *ar; int margin; float depth; } data = {NULL};
+ int p1[2];
+ int p2[2];
+
+ data.ar = ar;
+ data.margin = margin;
+ data.depth = FLT_MAX;
+
+ copy_v2_v2_int(p1, mval_sta);
+ copy_v2_v2_int(p2, mval_end);
+
+ BLI_bitmap_draw_2d_line_v2v2i(p1, p2, depth_segment_cb, &data);
+
+ *depth = data.depth;
+
+ return (*depth != FLT_MAX);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Radius/Distance Utilities
+ *
+ * Use to calculate a distance to a point based on it's radius.
+ * \{ */
+
+float ED_view3d_radius_to_dist_persp(const float angle, const float radius)
+{
+ return radius * (1.0f / tanf(angle / 2.0f));
+}
+
+float ED_view3d_radius_to_dist_ortho(const float lens, const float radius)
+{
+ return radius / (DEFAULT_SENSOR_WIDTH / lens);
+}
+
+/**
+ * Return a new RegionView3D.dist value to fit the \a radius.
+ *
+ * \note Depth isn't taken into account, this will fit a flat plane exactly,
+ * but points towards the view (with a perspective projection),
+ * may be within the radius but outside the view. eg:
+ *
+ * <pre>
+ * +
+ * pt --> + /^ radius
+ * / |
+ * / |
+ * view + +
+ * \ |
+ * \ |
+ * \|
+ * +
+ * </pre>
+ *
+ * \param ar Can be NULL if \a use_aspect is false.
+ * \param persp Allow the caller to tell what kind of perspective to use (ortho/view/camera)
+ * \param use_aspect Increase the distance to account for non 1:1 view aspect.
+ * \param radius The radius will be fitted exactly, typically pre-scaled by a margin (#VIEW3D_MARGIN).
+ */
+float ED_view3d_radius_to_dist(
+ const View3D *v3d, const ARegion *ar,
+ const char persp, const bool use_aspect,
+ const float radius)
+{
+ float dist;
+
+ BLI_assert(ELEM(persp, RV3D_ORTHO, RV3D_PERSP, RV3D_CAMOB));
+ BLI_assert((persp != RV3D_CAMOB) || v3d->camera);
+
+ if (persp == RV3D_ORTHO) {
+ dist = ED_view3d_radius_to_dist_ortho(v3d->lens, radius);
+ }
+ else {
+ float lens, sensor_size, zoom;
+ float angle;
+
+ if (persp == RV3D_CAMOB) {
+ CameraParams params;
+ BKE_camera_params_init(&params);
+ params.clipsta = v3d->near;
+ params.clipend = v3d->far;
+ BKE_camera_params_from_object(&params, v3d->camera);
+
+ lens = params.lens;
+ sensor_size = BKE_camera_sensor_size(params.sensor_fit, params.sensor_x, params.sensor_y);
+
+ /* ignore 'rv3d->camzoom' because we want to fit to the cameras frame */
+ zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB;
+ }
+ else {
+ lens = v3d->lens;
+ sensor_size = DEFAULT_SENSOR_WIDTH;
+ zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
+ }
+
+ angle = focallength_to_fov(lens, sensor_size);
+
+ /* zoom influences lens, correct this by scaling the angle as a distance (by the zoom-level) */
+ angle = atanf(tanf(angle / 2.0f) * zoom) * 2.0f;
+
+ dist = ED_view3d_radius_to_dist_persp(angle, radius);
+ }
+
+ if (use_aspect) {
+ const RegionView3D *rv3d = ar->regiondata;
+
+ float winx, winy;
+
+ if (persp == RV3D_CAMOB) {
+ /* camera frame x/y in pixels */
+ winx = ar->winx / rv3d->viewcamtexcofac[0];
+ winy = ar->winy / rv3d->viewcamtexcofac[1];
+ }
+ else {
+ winx = ar->winx;
+ winy = ar->winy;
+ }
+
+ if (winx && winy) {
+ float aspect = winx / winy;
+ if (aspect < 1.0f) {
+ aspect = 1.0f / aspect;
+ }
+ dist *= aspect;
+ }
+ }
+
+ return dist;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Distance Utilities
+ * \{ */
+
+/* problem - ofs[3] can be on same location as camera itself.
+ * Blender needs proper dist value for zoom.
+ * use fallback_dist to override small values
+ */
+float ED_view3d_offset_distance(float mat[4][4], const float ofs[3], const float fallback_dist)
+{
+ float pos[4] = {0.0f, 0.0f, 0.0f, 1.0f};
+ float dir[4] = {0.0f, 0.0f, 1.0f, 0.0f};
+ float dist;
+
+ mul_m4_v4(mat, pos);
+ add_v3_v3(pos, ofs);
+ mul_m4_v4(mat, dir);
+ normalize_v3(dir);
+
+ dist = dot_v3v3(pos, dir);
+
+ if ((dist < FLT_EPSILON) && (fallback_dist != 0.0f)) {
+ dist = fallback_dist;
+ }
+
+ return dist;
+}
+
+/**
+ * Set the dist without moving the view (compensate with #RegionView3D.ofs)
+ *
+ * \note take care that viewinv is up to date, #ED_view3d_update_viewmat first.
+ */
+void ED_view3d_distance_set(RegionView3D *rv3d, const float dist)
+{
+ float viewinv[4];
+ float tvec[3];
+
+ BLI_assert(dist >= 0.0f);
+
+ copy_v3_fl3(tvec, 0.0f, 0.0f, rv3d->dist - dist);
+ /* rv3d->viewinv isn't always valid */
+#if 0
+ mul_mat3_m4_v3(rv3d->viewinv, tvec);
+#else
+ invert_qt_qt_normalized(viewinv, rv3d->viewquat);
+ mul_qt_v3(viewinv, tvec);
+#endif
+ sub_v3_v3(rv3d->ofs, tvec);
+
+ rv3d->dist = dist;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Axis Utilities
+ * \{ */
+static float view3d_quat_axis[6][4] = {
+ {M_SQRT1_2, -M_SQRT1_2, 0.0f, 0.0f}, /* RV3D_VIEW_FRONT */
+ {0.0f, 0.0f, -M_SQRT1_2, -M_SQRT1_2}, /* RV3D_VIEW_BACK */
+ {0.5f, -0.5f, 0.5f, 0.5f}, /* RV3D_VIEW_LEFT */
+ {0.5f, -0.5f, -0.5f, -0.5f}, /* RV3D_VIEW_RIGHT */
+ {1.0f, 0.0f, 0.0f, 0.0f}, /* RV3D_VIEW_TOP */
+ {0.0f, -1.0f, 0.0f, 0.0f}, /* RV3D_VIEW_BOTTOM */
+};
+
+
+bool ED_view3d_quat_from_axis_view(const char view, float quat[4])
+{
+ if (RV3D_VIEW_IS_AXIS(view)) {
+ copy_qt_qt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]);
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+char ED_view3d_quat_to_axis_view(const float quat[4], const float epsilon)
+{
+ /* quat values are all unit length */
+
+ char view;
+
+ for (view = RV3D_VIEW_FRONT; view <= RV3D_VIEW_BOTTOM; view++) {
+ if (fabsf(angle_signed_qtqt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT])) < epsilon) {
+ return view;
+ }
+ }
+
+ return RV3D_VIEW_USER;
+}
+
+char ED_view3d_lock_view_from_index(int index)
+{
+ switch (index) {
+ case 0: return RV3D_VIEW_FRONT;
+ case 1: return RV3D_VIEW_TOP;
+ case 2: return RV3D_VIEW_RIGHT;
+ default: return RV3D_VIEW_USER;
+ }
+
+}
+
+char ED_view3d_axis_view_opposite(char view)
+{
+ switch (view) {
+ case RV3D_VIEW_FRONT: return RV3D_VIEW_BACK;
+ case RV3D_VIEW_BACK: return RV3D_VIEW_FRONT;
+ case RV3D_VIEW_LEFT: return RV3D_VIEW_RIGHT;
+ case RV3D_VIEW_RIGHT: return RV3D_VIEW_LEFT;
+ case RV3D_VIEW_TOP: return RV3D_VIEW_BOTTOM;
+ case RV3D_VIEW_BOTTOM: return RV3D_VIEW_TOP;
+ }
+
+ return RV3D_VIEW_USER;
+}
+
+
+bool ED_view3d_lock(RegionView3D *rv3d)
+{
+ return ED_view3d_quat_from_axis_view(rv3d->view, rv3d->viewquat);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name View Transform Utilities
+ * \{ */
+
+/**
+ * Set the view transformation from a 4x4 matrix.
+ *
+ * \param mat The view 4x4 transformation matrix to assign.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
+ */
+void ED_view3d_from_m4(float mat[4][4], float ofs[3], float quat[4], float *dist)
+{
+ float nmat[3][3];
+
+ /* dist depends on offset */
+ BLI_assert(dist == NULL || ofs != NULL);
+
+ copy_m3_m4(nmat, mat);
+ normalize_m3(nmat);
+
+ /* Offset */
+ if (ofs)
+ negate_v3_v3(ofs, mat[3]);
+
+ /* Quat */
+ if (quat) {
+ mat3_normalized_to_quat(quat, nmat);
+ invert_qt_normalized(quat);
+ }
+
+ if (ofs && dist) {
+ madd_v3_v3fl(ofs, nmat[2], *dist);
+ }
+}
+
+/**
+ * Calculate the view transformation matrix from RegionView3D input.
+ * The resulting matrix is equivalent to RegionView3D.viewinv
+ * \param mat The view 4x4 transformation matrix to calculate.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
+ */
+void ED_view3d_to_m4(float mat[4][4], const float ofs[3], const float quat[4], const float dist)
+{
+ float iviewquat[4] = {-quat[0], quat[1], quat[2], quat[3]};
+ float dvec[3] = {0.0f, 0.0f, dist};
+
+ quat_to_mat4(mat, iviewquat);
+ mul_mat3_m4_v3(mat, dvec);
+ sub_v3_v3v3(mat[3], dvec, ofs);
+}
+
+/**
+ * Set the RegionView3D members from an objects transformation and optionally lens.
+ * \param ob The object to set the view to.
+ * \param ofs The view offset to be set, normally from RegionView3D.ofs.
+ * \param quat The view rotation to be set, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs to be set, normally from RegionView3D.dist.
+ * \param lens The view lens angle set for cameras and lamps, normally from View3D.lens.
+ */
+void ED_view3d_from_object(Object *ob, float ofs[3], float quat[4], float *dist, float *lens)
+{
+ ED_view3d_from_m4(ob->obmat, ofs, quat, dist);
+
+ if (lens) {
+ CameraParams params;
+
+ BKE_camera_params_init(&params);
+ BKE_camera_params_from_object(&params, ob);
+ *lens = params.lens;
+ }
+}
+
+/**
+ * Set the object transformation from RegionView3D members.
+ * \param ob The object which has the transformation assigned.
+ * \param ofs The view offset, normally from RegionView3D.ofs.
+ * \param quat The view rotation, quaternion normally from RegionView3D.viewquat.
+ * \param dist The view distance from ofs, normally from RegionView3D.dist.
+ */
+void ED_view3d_to_object(Object *ob, const float ofs[3], const float quat[4], const float dist)
+{
+ float mat[4][4];
+ ED_view3d_to_m4(mat, ofs, quat, dist);
+ BKE_object_apply_mat4(ob, mat, true, true);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Depth Buffer Utilities
+ * \{ */
+
+float ED_view3d_depth_read_cached(const ViewContext *vc, const int mval[2])
+{
+ ViewDepths *vd = vc->rv3d->depths;
+
+ int x = mval[0];
+ int y = mval[1];
+
+ if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h) {
+ return vd->depths[y * vd->w + x];
+ }
+ else {
+ BLI_assert(1.0 <= vd->depth_range[1]);
+ return 1.0f;
+ }
+}
+
+bool ED_view3d_depth_read_cached_normal(
+ const ViewContext *vc, const bglMats *mats, const int mval[2],
+ float r_normal[3])
+{
+ /* Note: we could support passing in a radius.
+ * For now just read 9 pixels. */
+
+ /* pixels surrounding */
+ bool depths_valid[9] = {false};
+ float coords[9][3] = {{0}};
+
+ ARegion *ar = vc->ar;
+ const ViewDepths *depths = vc->rv3d->depths;
+
+ for (int x = 0, i = 0; x < 2; x++) {
+ for (int y = 0; y < 2; y++) {
+ const int mval_ofs[2] = {mval[0] + (x - 1), mval[1] + (y - 1)};
+
+ const double depth = (double)ED_view3d_depth_read_cached(vc, mval_ofs);
+ if ((depth > depths->depth_range[0]) && (depth < depths->depth_range[1])) {
+ if (ED_view3d_depth_unproject(ar, mats, mval_ofs, depth, coords[i])) {
+ depths_valid[i] = true;
+ }
+ }
+ i++;
+ }
+ }
+
+ const int edges[2][6][2] = {
+ /* x edges */
+ {{0, 1}, {1, 2},
+ {3, 4}, {4, 5},
+ {6, 7}, {7, 8}},
+ /* y edges */
+ {{0, 3}, {3, 6},
+ {1, 4}, {4, 7},
+ {2, 5}, {5, 8}},
+ };
+
+ float cross[2][3] = {{0.0f}};
+
+ for (int i = 0; i < 6; i++) {
+ for (int axis = 0; axis < 2; axis++) {
+ if (depths_valid[edges[axis][i][0]] && depths_valid[edges[axis][i][1]]) {
+ float delta[3];
+ sub_v3_v3v3(delta, coords[edges[axis][i][0]], coords[edges[axis][i][1]]);
+ add_v3_v3(cross[axis], delta);
+ }
+ }
+ }
+
+ cross_v3_v3v3(r_normal, cross[0], cross[1]);
+
+ if (normalize_v3(r_normal) != 0.0f) {
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+bool ED_view3d_depth_unproject(
+ const ARegion *ar, const bglMats *mats,
+ const int mval[2], const double depth,
+ float r_location_world[3])
+{
+ double p[3];
+ if (gluUnProject(
+ (double)ar->winrct.xmin + mval[0] + 0.5,
+ (double)ar->winrct.ymin + mval[1] + 0.5,
+ depth, mats->modelview, mats->projection, (const GLint *)mats->viewport,
+ &p[0], &p[1], &p[2]))
+ {
+ copy_v3fl_v3db(r_location_world, p);
+ return true;
+ }
+ return false;
+}
+
+void ED_view3d_depth_tag_update(RegionView3D *rv3d)
+{
+ if (rv3d->depths)
+ rv3d->depths->damaged = true;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Background Image Utilities
+ * \{ */
+
+BGpic *ED_view3d_background_image_new(View3D *v3d)
+{
+ BGpic *bgpic = MEM_callocN(sizeof(BGpic), "Background Image");
+
+ bgpic->rotation = 0.0f;
+ bgpic->size = 5.0f;
+ bgpic->blend = 0.5f;
+ bgpic->iuser.fie_ima = 2;
+ bgpic->iuser.ok = 1;
+ bgpic->view = 0; /* 0 for all */
+ bgpic->flag |= V3D_BGPIC_EXPANDED;
+
+ BLI_addtail(&v3d->bgpicbase, bgpic);
+
+ return bgpic;
+}
+
+void ED_view3d_background_image_remove(View3D *v3d, BGpic *bgpic)
+{
+ BLI_remlink(&v3d->bgpicbase, bgpic);
+
+ MEM_freeN(bgpic);
+}
+
+void ED_view3d_background_image_clear(View3D *v3d)
+{
+ BGpic *bgpic = v3d->bgpicbase.first;
+
+ while (bgpic) {
+ BGpic *next_bgpic = bgpic->next;
+
+ ED_view3d_background_image_remove(v3d, bgpic);
+
+ bgpic = next_bgpic;
+ }
+}
+
+/** \} */
diff --git a/source/blender/editors/space_view3d/view3d_view.c b/source/blender/editors/space_view3d/view3d_view.c
index 8582952d1a0..56f0e39aca0 100644
--- a/source/blender/editors/space_view3d/view3d_view.c
+++ b/source/blender/editors/space_view3d/view3d_view.c
@@ -28,7 +28,6 @@
* \ingroup spview3d
*/
-
#include "DNA_camera_types.h"
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
@@ -39,7 +38,6 @@
#include "BLI_rect.h"
#include "BLI_utildefines.h"
-#include "BKE_anim.h"
#include "BKE_action.h"
#include "BKE_camera.h"
#include "BKE_context.h"
@@ -49,10 +47,10 @@
#include "BKE_main.h"
#include "BKE_report.h"
#include "BKE_scene.h"
-#include "BKE_screen.h"
#include "BIF_gl.h"
-#include "BIF_glutil.h"
+
+#include "UI_resources.h"
#include "GPU_select.h"
@@ -60,8 +58,6 @@
#include "WM_types.h"
#include "ED_screen.h"
-#include "ED_armature.h"
-
#ifdef WITH_GAMEENGINE
# include "BLI_listbase.h"
@@ -72,55 +68,14 @@
# include "BL_System.h"
#endif
-
#include "view3d_intern.h" /* own include */
-/* use this call when executing an operator,
- * event system doesn't set for each event the
- * opengl drawing context */
-void view3d_operator_needs_opengl(const bContext *C)
-{
- wmWindow *win = CTX_wm_window(C);
- ARegion *ar = CTX_wm_region(C);
-
- view3d_region_operator_needs_opengl(win, ar);
-}
-
-void view3d_region_operator_needs_opengl(wmWindow *win, ARegion *ar)
-{
- /* for debugging purpose, context should always be OK */
- if ((ar == NULL) || (ar->regiontype != RGN_TYPE_WINDOW)) {
- printf("view3d_region_operator_needs_opengl error, wrong region\n");
- }
- else {
- RegionView3D *rv3d = ar->regiondata;
-
- wmSubWindowSet(win, ar->swinid);
- glMatrixMode(GL_PROJECTION);
- glLoadMatrixf(rv3d->winmat);
- glMatrixMode(GL_MODELVIEW);
- glLoadMatrixf(rv3d->viewmat);
- }
-}
-
-float *ED_view3d_cursor3d_get(Scene *scene, View3D *v3d)
-{
- if (v3d && v3d->localvd) return v3d->cursor;
- else return scene->cursor;
-}
-
-Camera *ED_view3d_camera_data_get(View3D *v3d, RegionView3D *rv3d)
-{
- /* establish the camera object, so we can default to view mapping if anything is wrong with it */
- if ((rv3d->persp == RV3D_CAMOB) && v3d->camera && (v3d->camera->type == OB_CAMERA)) {
- return v3d->camera->data;
- }
- else {
- return NULL;
- }
-}
+/* -------------------------------------------------------------------- */
+/** \name Smooth View Operator & Utilities
+ *
+ * Use for view transitions to have smooth (animated) transitions.
+ * \{ */
-/* ****************** smooth view operator ****************** */
/* This operator is one of the 'timer refresh' ones like animation playback */
struct SmoothView3DState {
@@ -269,7 +224,7 @@ void ED_view3d_smooth_view_ex(
* this means small rotations wont lag */
if (sview->quat && !sview->ofs && !sview->dist) {
/* scale the time allowed by the rotation */
- sms.time_allowed *= (double)angle_normalized_qtqt(sms.dst.quat, sms.src.quat) / M_PI; /* 180deg == 1.0 */
+ sms.time_allowed *= (double)fabsf(angle_signed_normalized_qtqt(sms.dst.quat, sms.src.quat)) / M_PI; /* 180deg == 1.0 */
}
/* ensure it shows correct */
@@ -397,6 +352,8 @@ static void view3d_smoothview_apply(bContext *C, View3D *v3d, ARegion *ar, bool
ED_view3d_camera_lock_autokey(v3d, rv3d, C, true, true);
}
+ /* Event handling won't know if a UI item has been moved under the pointer. */
+ WM_event_add_mousemove(C);
}
if (sync_boxview && (rv3d->viewlock & RV3D_BOXVIEW)) {
@@ -449,28 +406,31 @@ void ED_view3d_smooth_view_force_finish(
/* force update of view matrix so tools that run immediately after
* can use them without redrawing first */
Scene *scene = CTX_data_scene(C);
- ED_view3d_update_viewmat(scene, v3d, ar, NULL, NULL);
+ ED_view3d_update_viewmat(scene, v3d, ar, NULL, NULL, NULL);
}
}
void VIEW3D_OT_smoothview(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Smooth View";
ot->description = "";
ot->idname = "VIEW3D_OT_smoothview";
-
+
/* api callbacks */
ot->invoke = view3d_smoothview_invoke;
-
+
/* flags */
ot->flag = OPTYPE_INTERNAL;
ot->poll = ED_operator_view3d_active;
}
-/* ****************** change view operators ****************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Camera to View Operator
+ * \{ */
static int view3d_camera_to_view_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -507,7 +467,7 @@ static int view3d_camera_to_view_poll(bContext *C)
if (ED_view3d_context_user_region(C, &v3d, &ar)) {
RegionView3D *rv3d = ar->regiondata;
- if (v3d && v3d->camera && !ID_IS_LINKED_DATABLOCK(v3d->camera)) {
+ if (v3d && v3d->camera && !ID_IS_LINKED(v3d->camera)) {
if (rv3d && (rv3d->viewlock & RV3D_LOCKED) == 0) {
if (rv3d->persp != RV3D_CAMOB) {
return 1;
@@ -534,6 +494,12 @@ void VIEW3D_OT_camera_to_view(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Camera Fit Frame to Selected Operator
+ * \{ */
+
/* unlike VIEW3D_OT_view_selected this is for framing a render and not
* meant to take into account vertex/bone selection for eg. */
static int view3d_camera_to_view_selected_exec(bContext *C, wmOperator *op)
@@ -592,6 +558,12 @@ void VIEW3D_OT_camera_to_view_selected(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Object as Camera Operator
+ * \{ */
+
static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob, const int smooth_viewtx)
{
Main *bmain = CTX_data_main(C);
@@ -642,7 +614,7 @@ static void sync_viewport_camera_smoothview(bContext *C, View3D *v3d, Object *ob
}
static int view3d_setobjectascamera_exec(bContext *C, wmOperator *op)
-{
+{
View3D *v3d;
ARegion *ar;
RegionView3D *rv3d;
@@ -695,7 +667,6 @@ int ED_operator_rv3d_user_region_poll(bContext *C)
void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Set Active Object as Camera";
ot->description = "Set the active object as the active camera for this view or scene";
@@ -709,206 +680,16 @@ void VIEW3D_OT_object_as_camera(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
}
-/* ********************************** */
-
-void ED_view3d_clipping_calc_from_boundbox(float clip[4][4], const BoundBox *bb, const bool is_flip)
-{
- int val;
-
- for (val = 0; val < 4; val++) {
- normal_tri_v3(clip[val], bb->vec[val], bb->vec[val == 3 ? 0 : val + 1], bb->vec[val + 4]);
- if (UNLIKELY(is_flip)) {
- negate_v3(clip[val]);
- }
-
- clip[val][3] = -dot_v3v3(clip[val], bb->vec[val]);
- }
-}
-
-void ED_view3d_clipping_calc(BoundBox *bb, float planes[4][4], bglMats *mats, const rcti *rect)
-{
- float modelview[4][4];
- double xs, ys, p[3];
- int val, flip_sign, a;
-
- /* near zero floating point values can give issues with gluUnProject
- * in side view on some implementations */
- if (fabs(mats->modelview[0]) < 1e-6) mats->modelview[0] = 0.0;
- if (fabs(mats->modelview[5]) < 1e-6) mats->modelview[5] = 0.0;
-
- /* Set up viewport so that gluUnProject will give correct values */
- mats->viewport[0] = 0;
- mats->viewport[1] = 0;
-
- /* four clipping planes and bounding volume */
- /* first do the bounding volume */
- for (val = 0; val < 4; val++) {
- xs = (val == 0 || val == 3) ? rect->xmin : rect->xmax;
- ys = (val == 0 || val == 1) ? rect->ymin : rect->ymax;
-
- gluUnProject(xs, ys, 0.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
- copy_v3fl_v3db(bb->vec[val], p);
-
- gluUnProject(xs, ys, 1.0, mats->modelview, mats->projection, mats->viewport, &p[0], &p[1], &p[2]);
- copy_v3fl_v3db(bb->vec[4 + val], p);
- }
-
- /* verify if we have negative scale. doing the transform before cross
- * product flips the sign of the vector compared to doing cross product
- * before transform then, so we correct for that. */
- for (a = 0; a < 16; a++)
- ((float *)modelview)[a] = mats->modelview[a];
- flip_sign = is_negative_m4(modelview);
-
- ED_view3d_clipping_calc_from_boundbox(planes, bb, flip_sign);
-}
-
-static bool view3d_boundbox_clip_m4(const BoundBox *bb, float persmatob[4][4])
-{
- int a, flag = -1, fl;
-
- for (a = 0; a < 8; a++) {
- float vec[4], min, max;
- copy_v3_v3(vec, bb->vec[a]);
- vec[3] = 1.0;
- mul_m4_v4(persmatob, vec);
- max = vec[3];
- min = -vec[3];
-
- fl = 0;
- if (vec[0] < min) fl += 1;
- if (vec[0] > max) fl += 2;
- if (vec[1] < min) fl += 4;
- if (vec[1] > max) fl += 8;
- if (vec[2] < min) fl += 16;
- if (vec[2] > max) fl += 32;
-
- flag &= fl;
- if (flag == 0) return true;
- }
-
- return false;
-}
-
-bool ED_view3d_boundbox_clip_ex(const RegionView3D *rv3d, const BoundBox *bb, float obmat[4][4])
-{
- /* return 1: draw */
-
- float persmatob[4][4];
-
- if (bb == NULL) return true;
- if (bb->flag & BOUNDBOX_DISABLED) return true;
-
- mul_m4_m4m4(persmatob, (float(*)[4])rv3d->persmat, obmat);
-
- return view3d_boundbox_clip_m4(bb, persmatob);
-}
-
-bool ED_view3d_boundbox_clip(RegionView3D *rv3d, const BoundBox *bb)
-{
- if (bb == NULL) return true;
- if (bb->flag & BOUNDBOX_DISABLED) return true;
-
- return view3d_boundbox_clip_m4(bb, rv3d->persmatob);
-}
-
-float ED_view3d_depth_read_cached(const ViewContext *vc, int x, int y)
-{
- ViewDepths *vd = vc->rv3d->depths;
-
- x -= vc->ar->winrct.xmin;
- y -= vc->ar->winrct.ymin;
-
- if (vd && vd->depths && x > 0 && y > 0 && x < vd->w && y < vd->h)
- return vd->depths[y * vd->w + x];
- else
- return 1;
-}
-
-void ED_view3d_depth_tag_update(RegionView3D *rv3d)
-{
- if (rv3d->depths)
- rv3d->depths->damaged = true;
-}
-
-void ED_view3d_dist_range_get(
- const View3D *v3d,
- float r_dist_range[2])
-{
- r_dist_range[0] = v3d->grid * 0.001f;
- r_dist_range[1] = v3d->far * 10.0f;
-}
-
-/* copies logic of get_view3d_viewplane(), keep in sync */
-bool ED_view3d_clip_range_get(
- const View3D *v3d, const RegionView3D *rv3d,
- float *r_clipsta, float *r_clipend,
- const bool use_ortho_factor)
-{
- CameraParams params;
-
- BKE_camera_params_init(&params);
- BKE_camera_params_from_view3d(&params, v3d, rv3d);
-
- if (use_ortho_factor && params.is_ortho) {
- const float fac = 2.0f / (params.clipend - params.clipsta);
- params.clipsta *= fac;
- params.clipend *= fac;
- }
-
- if (r_clipsta) *r_clipsta = params.clipsta;
- if (r_clipend) *r_clipend = params.clipend;
-
- return params.is_ortho;
-}
+/** \} */
-bool ED_view3d_viewplane_get(
- const View3D *v3d, const RegionView3D *rv3d, int winx, int winy,
- rctf *r_viewplane, float *r_clipsta, float *r_clipend, float *r_pixsize)
-{
- CameraParams params;
-
- BKE_camera_params_init(&params);
- BKE_camera_params_from_view3d(&params, v3d, rv3d);
- BKE_camera_params_compute_viewplane(&params, winx, winy, 1.0f, 1.0f);
-
- if (r_viewplane) *r_viewplane = params.viewplane;
- if (r_clipsta) *r_clipsta = params.clipsta;
- if (r_clipend) *r_clipend = params.clipend;
- if (r_pixsize) *r_pixsize = params.viewdx;
-
- return params.is_ortho;
-}
-
-/**
- * Use instead of: ``bglPolygonOffset(rv3d->dist, ...)`` see bug [#37727]
- */
-void ED_view3d_polygon_offset(const RegionView3D *rv3d, const float dist)
-{
- float viewdist;
-
- if (rv3d->rflag & RV3D_ZOFFSET_DISABLED) {
- return;
- }
-
- viewdist = rv3d->dist;
-
- /* special exception for ortho camera (viewdist isnt used for perspective cameras) */
- if (dist != 0.0f) {
- if (rv3d->persp == RV3D_CAMOB) {
- if (rv3d->is_persp == false) {
- viewdist = 1.0f / max_ff(fabsf(rv3d->winmat[0][0]), fabsf(rv3d->winmat[1][1]));
- }
- }
- }
-
- bglPolygonOffset(viewdist, dist);
-}
+/* -------------------------------------------------------------------- */
+/** \name Window and View Matrix Calculation
+ * \{ */
/**
* \param rect optional for picking (can be NULL).
*/
-void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rctf *rect)
+void view3d_winmatrix_set(ARegion *ar, const View3D *v3d, const rcti *rect)
{
RegionView3D *rv3d = ar->regiondata;
rctf viewplane;
@@ -957,75 +738,20 @@ static void obmat_to_viewmat(RegionView3D *rv3d, Object *ob)
mat4_normalized_to_quat(rv3d->viewquat, rv3d->viewmat);
}
-static float view3d_quat_axis[6][4] = {
- {M_SQRT1_2, -M_SQRT1_2, 0.0f, 0.0f}, /* RV3D_VIEW_FRONT */
- {0.0f, 0.0f, -M_SQRT1_2, -M_SQRT1_2}, /* RV3D_VIEW_BACK */
- {0.5f, -0.5f, 0.5f, 0.5f}, /* RV3D_VIEW_LEFT */
- {0.5f, -0.5f, -0.5f, -0.5f}, /* RV3D_VIEW_RIGHT */
- {1.0f, 0.0f, 0.0f, 0.0f}, /* RV3D_VIEW_TOP */
- {0.0f, -1.0f, 0.0f, 0.0f}, /* RV3D_VIEW_BOTTOM */
-};
-
-
-bool ED_view3d_quat_from_axis_view(const char view, float quat[4])
-{
- if (RV3D_VIEW_IS_AXIS(view)) {
- copy_qt_qt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]);
- return true;
- }
- else {
- return false;
- }
-}
-
-char ED_view3d_quat_to_axis_view(const float quat[4], const float epsilon)
-{
- /* quat values are all unit length */
-
- char view;
-
- for (view = RV3D_VIEW_FRONT; view <= RV3D_VIEW_BOTTOM; view++) {
- if (angle_qtqt(quat, view3d_quat_axis[view - RV3D_VIEW_FRONT]) < epsilon) {
- return view;
- }
- }
-
- return RV3D_VIEW_USER;
-}
-
-char ED_view3d_lock_view_from_index(int index)
-{
- switch (index) {
- case 0: return RV3D_VIEW_FRONT;
- case 1: return RV3D_VIEW_TOP;
- case 2: return RV3D_VIEW_RIGHT;
- default: return RV3D_VIEW_USER;
- }
-
-}
-
-char ED_view3d_axis_view_opposite(char view)
-{
- switch (view) {
- case RV3D_VIEW_FRONT: return RV3D_VIEW_BACK;
- case RV3D_VIEW_BACK: return RV3D_VIEW_FRONT;
- case RV3D_VIEW_LEFT: return RV3D_VIEW_RIGHT;
- case RV3D_VIEW_RIGHT: return RV3D_VIEW_LEFT;
- case RV3D_VIEW_TOP: return RV3D_VIEW_BOTTOM;
- case RV3D_VIEW_BOTTOM: return RV3D_VIEW_TOP;
- }
-
- return RV3D_VIEW_USER;
-}
-
-
-bool ED_view3d_lock(RegionView3D *rv3d)
-{
- return ED_view3d_quat_from_axis_view(rv3d->view, rv3d->viewquat);
-}
-
-/* don't set windows active in here, is used by renderwin too */
-void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d)
+/**
+ * Sets #RegionView3D.viewmat
+ *
+ * \param scene: Scene for camera and cursor location.
+ * \param v3d: View 3D space data.
+ * \param rv3d: 3D region which stores the final matrices.
+ * \param rect_scale: Optional 2D scale argument,
+ * Use when displaying a sub-region, eg: when #view3d_winmatrix_set takes a 'rect' argument.
+ *
+ * \note don't set windows active in here, is used by renderwin too.
+ */
+void view3d_viewmatrix_set(
+ Scene *scene,
+ const View3D *v3d, RegionView3D *rv3d, const float rect_scale[2])
{
if (rv3d->persp == RV3D_CAMOB) { /* obs/camera */
if (v3d->camera) {
@@ -1084,6 +810,17 @@ void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d)
mul_v2_v2fl(vec, rv3d->ofs_lock, rv3d->is_persp ? rv3d->dist : 1.0f);
vec[2] = 0.0f;
+
+ if (rect_scale) {
+ /* Since 'RegionView3D.winmat' has been calculated and this function doesn't take the 'ARegion'
+ * we don't know about the region size.
+ * Use 'rect_scale' when drawing a sub-region to apply 2D offset,
+ * scaled by the difference between the sub-region and the region size.
+ */
+ vec[0] /= rect_scale[0];
+ vec[1] /= rect_scale[1];
+ }
+
mul_mat3_m4_v3(persinv, vec);
translate_m4(rv3d->viewmat, vec[0], vec[1], vec[2]);
}
@@ -1091,76 +828,25 @@ void view3d_viewmatrix_set(Scene *scene, const View3D *v3d, RegionView3D *rv3d)
}
}
-static void view3d_select_loop(ViewContext *vc, Scene *scene, View3D *v3d, ARegion *ar, bool use_obedit_skip)
-{
- short code = 1;
- char dt;
- short dtx;
-
- if (vc->obedit && vc->obedit->type == OB_MBALL) {
- draw_object(scene, ar, v3d, BASACT, DRAW_PICKING | DRAW_CONSTCOLOR);
- }
- else if ((vc->obedit && vc->obedit->type == OB_ARMATURE)) {
- /* if not drawing sketch, draw bones */
- if (!BDR_drawSketchNames(vc)) {
- draw_object(scene, ar, v3d, BASACT, DRAW_PICKING | DRAW_CONSTCOLOR);
- }
- }
- else {
- Base *base;
-
- v3d->xray = true; /* otherwise it postpones drawing */
- for (base = scene->base.first; base; base = base->next) {
- if (base->lay & v3d->lay) {
-
- if ((base->object->restrictflag & OB_RESTRICT_SELECT) ||
- (use_obedit_skip && (scene->obedit->data == base->object->data)))
- {
- base->selcol = 0;
- }
- else {
- base->selcol = code;
-
- if (GPU_select_load_id(code)) {
- draw_object(scene, ar, v3d, base, DRAW_PICKING | DRAW_CONSTCOLOR);
+/** \} */
- /* we draw duplicators for selection too */
- if ((base->object->transflag & OB_DUPLI)) {
- ListBase *lb;
- DupliObject *dob;
- Base tbase;
+/* -------------------------------------------------------------------- */
+/** \name OpenGL Select Utilities
+ * \{ */
- tbase.flag = OB_FROMDUPLI;
- lb = object_duplilist(G.main->eval_ctx, scene, base->object);
-
- for (dob = lb->first; dob; dob = dob->next) {
- float omat[4][4];
-
- tbase.object = dob->ob;
- copy_m4_m4(omat, dob->ob->obmat);
- copy_m4_m4(dob->ob->obmat, dob->mat);
-
- /* extra service: draw the duplicator in drawtype of parent */
- /* MIN2 for the drawtype to allow bounding box objects in groups for lods */
- dt = tbase.object->dt; tbase.object->dt = MIN2(tbase.object->dt, base->object->dt);
- dtx = tbase.object->dtx; tbase.object->dtx = base->object->dtx;
-
- draw_object(scene, ar, v3d, &tbase, DRAW_PICKING | DRAW_CONSTCOLOR);
-
- tbase.object->dt = dt;
- tbase.object->dtx = dtx;
+/**
+ * Optionally cache data for multiple calls to #view3d_opengl_select
+ *
+ * just avoid GPU_select headers outside this file
+ */
+void view3d_opengl_select_cache_begin(void)
+{
+ GPU_select_cache_begin();
+}
- copy_m4_m4(dob->ob->obmat, omat);
- }
- free_object_duplilist(lb);
- }
- }
- code++;
- }
- }
- }
- v3d->xray = false; /* restore */
- }
+void view3d_opengl_select_cache_end(void)
+{
+ GPU_select_cache_end();
}
/**
@@ -1170,32 +856,74 @@ static void view3d_select_loop(ViewContext *vc, Scene *scene, View3D *v3d, ARegi
*
* \note (vc->obedit == NULL) can be set to explicitly skip edit-object selection.
*/
-short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input, bool do_nearest)
+int view3d_opengl_select(
+ ViewContext *vc, unsigned int *buffer, unsigned int bufsize, const rcti *input,
+ eV3DSelectMode select_mode)
{
+ struct bThemeState theme_state;
Scene *scene = vc->scene;
View3D *v3d = vc->v3d;
ARegion *ar = vc->ar;
- rctf rect;
- short hits;
+ rcti rect;
+ int hits;
const bool use_obedit_skip = (scene->obedit != NULL) && (vc->obedit == NULL);
- const bool do_passes = do_nearest && GPU_select_query_check_active();
+ const bool is_pick_select = (U.gpu_select_pick_deph != 0);
+ const bool do_passes = (
+ (is_pick_select == false) &&
+ (select_mode == VIEW3D_SELECT_PICK_NEAREST) &&
+ GPU_select_query_check_active());
+ const bool use_nearest = (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST);
+
+ char gpu_select_mode;
- G.f |= G_PICKSEL;
-
/* case not a border select */
if (input->xmin == input->xmax) {
- rect.xmin = input->xmin - 12; /* seems to be default value for bones only now */
- rect.xmax = input->xmin + 12;
- rect.ymin = input->ymin - 12;
- rect.ymax = input->ymin + 12;
+ /* seems to be default value for bones only now */
+ BLI_rcti_init_pt_radius(&rect, (const int[2]){input->xmin, input->ymin}, 12);
}
else {
- BLI_rctf_rcti_copy(&rect, input);
+ rect = *input;
}
-
- view3d_winmatrix_set(ar, v3d, &rect);
- mul_m4_m4m4(vc->rv3d->persmat, vc->rv3d->winmat, vc->rv3d->viewmat);
-
+
+ if (is_pick_select) {
+ if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_NEAREST) {
+ gpu_select_mode = GPU_SELECT_PICK_NEAREST;
+ }
+ else if (is_pick_select && select_mode == VIEW3D_SELECT_PICK_ALL) {
+ gpu_select_mode = GPU_SELECT_PICK_ALL;
+ }
+ else {
+ gpu_select_mode = GPU_SELECT_ALL;
+ }
+ }
+ else {
+ if (do_passes) {
+ gpu_select_mode = GPU_SELECT_NEAREST_FIRST_PASS;
+ }
+ else {
+ gpu_select_mode = GPU_SELECT_ALL;
+ }
+ }
+
+ /* Tools may request depth outside of regular drawing code. */
+ UI_Theme_Store(&theme_state);
+ UI_SetTheme(SPACE_VIEW3D, RGN_TYPE_WINDOW);
+
+ /* Re-use cache (rect must be smaller then the cached)
+ * other context is assumed to be unchanged */
+ if (GPU_select_is_cached()) {
+ GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
+ GPU_select_cache_load_id();
+ hits = GPU_select_end();
+ goto finally;
+ }
+
+ G.f |= G_PICKSEL;
+
+ /* Important we use the 'viewmat' and don't re-calculate since
+ * the object & bone view locking takes 'rect' into account, see: T51629. */
+ ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, &rect);
+
if (v3d->drawtype > OB_WIRE) {
v3d->zbuf = true;
glEnable(GL_DEPTH_TEST);
@@ -1204,27 +932,23 @@ short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int b
if (vc->rv3d->rflag & RV3D_CLIPPING)
ED_view3d_clipping_set(vc->rv3d);
- if (do_passes)
- GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_FIRST_PASS, 0);
- else
- GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_ALL, 0);
+ GPU_select_begin(buffer, bufsize, &rect, gpu_select_mode, 0);
- view3d_select_loop(vc, scene, v3d, ar, use_obedit_skip);
+ ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
hits = GPU_select_end();
/* second pass, to get the closest object to camera */
- if (do_passes) {
+ if (do_passes && (hits > 0)) {
GPU_select_begin(buffer, bufsize, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
- view3d_select_loop(vc, scene, v3d, ar, use_obedit_skip);
+ ED_view3d_draw_select_loop(vc, scene, v3d, ar, use_obedit_skip, use_nearest);
GPU_select_end();
}
G.f &= ~G_PICKSEL;
- view3d_winmatrix_set(ar, v3d, NULL);
- mul_m4_m4m4(vc->rv3d->persmat, vc->rv3d->winmat, vc->rv3d->viewmat);
+ ED_view3d_draw_setup_view(vc->win, scene, ar, v3d, vc->rv3d->viewmat, NULL, NULL);
if (v3d->drawtype > OB_WIRE) {
v3d->zbuf = 0;
@@ -1233,13 +957,20 @@ short view3d_opengl_select(ViewContext *vc, unsigned int *buffer, unsigned int b
if (vc->rv3d->rflag & RV3D_CLIPPING)
ED_view3d_clipping_disable();
-
+
+finally:
if (hits < 0) printf("Too many objects in select buffer\n"); /* XXX make error message */
+ UI_Theme_Restore(&theme_state);
+
return hits;
}
-/* ********************** local view operator ******************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Local View Operators
+ * \{ */
static unsigned int free_localbit(Main *bmain)
{
@@ -1428,10 +1159,12 @@ static bool view3d_localview_init(
}
}
+ DAG_on_visible_update(bmain, false);
+
return ok;
}
-static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmain, Scene *scene, ScrArea *sa, const int smooth_viewtx)
+static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmain, ScrArea *sa, const int smooth_viewtx)
{
const bool free = true;
ARegion *ar;
@@ -1443,8 +1176,6 @@ static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmai
camera_old = v3d->camera;
camera_new = v3d->localvd->camera;
- v3d->near = v3d->localvd->near;
- v3d->far = v3d->localvd->far;
v3d->lay = v3d->localvd->lay;
v3d->layact = v3d->localvd->layact;
v3d->drawtype = v3d->localvd->drawtype;
@@ -1483,7 +1214,7 @@ static void restore_localviewdata(wmWindowManager *wm, wmWindow *win, Main *bmai
}
}
- ED_view3d_shade_update(bmain, scene, v3d, sa);
+ ED_view3d_shade_update(bmain, v3d, sa);
}
}
}
@@ -1500,7 +1231,7 @@ static bool view3d_localview_exit(
locallay = v3d->lay & 0xFF000000;
- restore_localviewdata(wm, win, bmain, scene, sa, smooth_viewtx);
+ restore_localviewdata(wm, win, bmain, sa, smooth_viewtx);
/* for when in other window the layers have changed */
if (v3d->scenelock) v3d->lay = scene->lay;
@@ -1574,43 +1305,43 @@ void VIEW3D_OT_localview(wmOperatorType *ot)
ot->poll = ED_operator_view3d_active;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Game Engine Operator
+ *
+ * Start the game engine (handles context switching).
+ * \{ */
+
#ifdef WITH_GAMEENGINE
static ListBase queue_back;
-static void SaveState(bContext *C, wmWindow *win)
+static void game_engine_save_state(bContext *C, wmWindow *win)
{
Object *obact = CTX_data_active_object(C);
-
+
glPushAttrib(GL_ALL_ATTRIB_BITS);
if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
GPU_paint_set_mipmap(1);
-
+
queue_back = win->queue;
-
+
BLI_listbase_clear(&win->queue);
-
- //XXX waitcursor(1);
}
-static void RestoreState(bContext *C, wmWindow *win)
+static void game_engine_restore_state(bContext *C, wmWindow *win)
{
Object *obact = CTX_data_active_object(C);
-
+
if (obact && obact->mode & OB_MODE_TEXTURE_PAINT)
GPU_paint_set_mipmap(0);
- //XXX curarea->win_swap = 0;
- //XXX curarea->head_swap = 0;
- //XXX allqueue(REDRAWVIEW3D, 1);
- //XXX allqueue(REDRAWBUTSALL, 0);
- //XXX reset_slowparents();
- //XXX waitcursor(0);
- //XXX G.qual = 0;
-
- if (win) /* check because closing win can set to NULL */
+ /* check because closing win can set to NULL */
+ if (win) {
win->queue = queue_back;
-
+ }
+
GPU_state_init();
GPU_set_tpage(NULL, 0, 0);
@@ -1684,33 +1415,6 @@ static int game_engine_poll(bContext *C)
return 1;
}
-bool ED_view3d_context_activate(bContext *C)
-{
- bScreen *sc = CTX_wm_screen(C);
- ScrArea *sa = CTX_wm_area(C);
- ARegion *ar;
-
- /* sa can be NULL when called from python */
- if (sa == NULL || sa->spacetype != SPACE_VIEW3D) {
- sa = BKE_screen_find_big_area(sc, SPACE_VIEW3D, 0);
- }
-
- if (sa == NULL) {
- return false;
- }
-
- ar = BKE_area_find_region_active_win(sa);
- if (ar == NULL) {
- return false;
- }
-
- /* bad context switch .. */
- CTX_wm_area_set(C, sa);
- CTX_wm_region_set(C, ar);
-
- return true;
-}
-
static int game_engine_exec(bContext *C, wmOperator *op)
{
#ifdef WITH_GAMEENGINE
@@ -1722,12 +1426,12 @@ static int game_engine_exec(bContext *C, wmOperator *op)
RegionView3D *rv3d;
rcti cam_frame;
- (void)op; /* unused */
-
+ UNUSED_VARS(op);
+
/* bad context switch .. */
if (!ED_view3d_context_activate(C))
return OPERATOR_CANCELLED;
-
+
/* redraw to hide any menus/popups, we don't go back to
* the window manager until after this operator exits */
WM_redraw_windows(C);
@@ -1739,7 +1443,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
ar = CTX_wm_region(C);
view3d_operator_needs_opengl(C);
-
+
game_set_commmandline_options(&startscene->gm);
if ((rv3d->persp == RV3D_CAMOB) &&
@@ -1763,7 +1467,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
}
- SaveState(C, prevwin);
+ game_engine_save_state(C, prevwin);
StartKetsjiShell(C, ar, &cam_frame, 1);
@@ -1772,7 +1476,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
prevwin = NULL;
CTX_wm_window_set(C, NULL);
}
-
+
ED_area_tag_redraw(CTX_wm_area(C));
if (prevwin) {
@@ -1783,7 +1487,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
CTX_wm_area_set(C, prevsa);
}
- RestoreState(C, prevwin);
+ game_engine_restore_state(C, prevwin);
//XXX restore_all_scene_cfra(scene_cfra_store);
BKE_scene_set_background(CTX_data_main(C), startscene);
@@ -1793,7 +1497,7 @@ static int game_engine_exec(bContext *C, wmOperator *op)
return OPERATOR_FINISHED;
#else
- (void)C; /* unused */
+ UNUSED_VARS(C);
BKE_report(op->reports, RPT_ERROR, "Game engine is disabled in this build");
return OPERATOR_CANCELLED;
#endif
@@ -1801,168 +1505,15 @@ static int game_engine_exec(bContext *C, wmOperator *op)
void VIEW3D_OT_game_start(wmOperatorType *ot)
{
-
/* identifiers */
ot->name = "Start Game Engine";
ot->description = "Start game engine";
ot->idname = "VIEW3D_OT_game_start";
-
+
/* api callbacks */
ot->exec = game_engine_exec;
-
- ot->poll = game_engine_poll;
-}
-
-/* ************************************** */
-
-float ED_view3d_pixel_size(const RegionView3D *rv3d, const float co[3])
-{
- return mul_project_m4_v3_zfac((float(*)[4])rv3d->persmat, co) * rv3d->pixsize * U.pixelsize;
-}
-
-float ED_view3d_radius_to_dist_persp(const float angle, const float radius)
-{
- return radius * (1.0f / tanf(angle / 2.0f));
-}
-
-float ED_view3d_radius_to_dist_ortho(const float lens, const float radius)
-{
- return radius / (DEFAULT_SENSOR_WIDTH / lens);
-}
-
-/**
- * Return a new RegionView3D.dist value to fit the \a radius.
- *
- * \note Depth isn't taken into account, this will fit a flat plane exactly,
- * but points towards the view (with a perspective projection),
- * may be within the radius but outside the view. eg:
- *
- * <pre>
- * +
- * pt --> + /^ radius
- * / |
- * / |
- * view + +
- * \ |
- * \ |
- * \|
- * +
- * </pre>
- *
- * \param ar Can be NULL if \a use_aspect is false.
- * \param persp Allow the caller to tell what kind of perspective to use (ortho/view/camera)
- * \param use_aspect Increase the distance to account for non 1:1 view aspect.
- * \param radius The radius will be fitted exactly, typically pre-scaled by a margin (#VIEW3D_MARGIN).
- */
-float ED_view3d_radius_to_dist(
- const View3D *v3d, const ARegion *ar,
- const char persp, const bool use_aspect,
- const float radius)
-{
- float dist;
-
- BLI_assert(ELEM(persp, RV3D_ORTHO, RV3D_PERSP, RV3D_CAMOB));
- BLI_assert((persp != RV3D_CAMOB) || v3d->camera);
-
- if (persp == RV3D_ORTHO) {
- dist = ED_view3d_radius_to_dist_ortho(v3d->lens, radius);
- }
- else {
- float lens, sensor_size, zoom;
- float angle;
-
- if (persp == RV3D_CAMOB) {
- CameraParams params;
- BKE_camera_params_init(&params);
- params.clipsta = v3d->near;
- params.clipend = v3d->far;
- BKE_camera_params_from_object(&params, v3d->camera);
-
- lens = params.lens;
- sensor_size = BKE_camera_sensor_size(params.sensor_fit, params.sensor_x, params.sensor_y);
- /* ignore 'rv3d->camzoom' because we want to fit to the cameras frame */
- zoom = CAMERA_PARAM_ZOOM_INIT_CAMOB;
- }
- else {
- lens = v3d->lens;
- sensor_size = DEFAULT_SENSOR_WIDTH;
- zoom = CAMERA_PARAM_ZOOM_INIT_PERSP;
- }
-
- angle = focallength_to_fov(lens, sensor_size);
-
- /* zoom influences lens, correct this by scaling the angle as a distance (by the zoom-level) */
- angle = atanf(tanf(angle / 2.0f) * zoom) * 2.0f;
-
- dist = ED_view3d_radius_to_dist_persp(angle, radius);
- }
-
- if (use_aspect) {
- const RegionView3D *rv3d = ar->regiondata;
-
- float winx, winy;
-
- if (persp == RV3D_CAMOB) {
- /* camera frame x/y in pixels */
- winx = ar->winx / rv3d->viewcamtexcofac[0];
- winy = ar->winy / rv3d->viewcamtexcofac[1];
- }
- else {
- winx = ar->winx;
- winy = ar->winy;
- }
-
- if (winx && winy) {
- float aspect = winx / winy;
- if (aspect < 1.0f) {
- aspect = 1.0f / aspect;
- }
- dist *= aspect;
- }
- }
-
- return dist;
-}
-
-/* view matrix properties utilities */
-
-/* unused */
-#if 0
-void ED_view3d_operator_properties_viewmat(wmOperatorType *ot)
-{
- PropertyRNA *prop;
-
- prop = RNA_def_int(ot->srna, "region_width", 0, 0, INT_MAX, "Region Width", "", 0, INT_MAX);
- RNA_def_property_flag(prop, PROP_HIDDEN);
-
- prop = RNA_def_int(ot->srna, "region_height", 0, 0, INT_MAX, "Region height", "", 0, INT_MAX);
- RNA_def_property_flag(prop, PROP_HIDDEN);
-
- prop = RNA_def_float_matrix(ot->srna, "perspective_matrix", 4, 4, NULL, 0.0f, 0.0f, "", "Perspective Matrix", 0.0f, 0.0f);
- RNA_def_property_flag(prop, PROP_HIDDEN);
-}
-
-void ED_view3d_operator_properties_viewmat_set(bContext *C, wmOperator *op)
-{
- ARegion *ar = CTX_wm_region(C);
- RegionView3D *rv3d = ED_view3d_context_rv3d(C);
-
- if (!RNA_struct_property_is_set(op->ptr, "region_width"))
- RNA_int_set(op->ptr, "region_width", ar->winx);
-
- if (!RNA_struct_property_is_set(op->ptr, "region_height"))
- RNA_int_set(op->ptr, "region_height", ar->winy);
-
- if (!RNA_struct_property_is_set(op->ptr, "perspective_matrix"))
- RNA_float_set_array(op->ptr, "perspective_matrix", (float *)rv3d->persmat);
+ ot->poll = game_engine_poll;
}
-void ED_view3d_operator_properties_viewmat_get(wmOperator *op, int *winx, int *winy, float persmat[4][4])
-{
- *winx = RNA_int_get(op->ptr, "region_width");
- *winy = RNA_int_get(op->ptr, "region_height");
-
- RNA_float_get_array(op->ptr, "perspective_matrix", (float *)persmat);
-}
-#endif
+/** \} */
diff --git a/source/blender/editors/space_view3d/view3d_walk.c b/source/blender/editors/space_view3d/view3d_walk.c
index 542dc410bc3..f780ca35f30 100644
--- a/source/blender/editors/space_view3d/view3d_walk.c
+++ b/source/blender/editors/space_view3d/view3d_walk.c
@@ -49,7 +49,6 @@
#include "ED_screen.h"
#include "ED_space_api.h"
-#include "ED_transform.h"
#include "ED_transform_snap_object_context.h"
#include "PIL_time.h" /* smoothview */
@@ -129,7 +128,7 @@ typedef enum eWalkGravityState {
/* called in transform_ops.c, on each regeneration of keymaps */
void walk_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{WALK_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{WALK_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
@@ -510,7 +509,7 @@ static bool initWalkInfo(bContext *C, WalkInfo *walk, wmOperator *op)
walk->rv3d->persp = RV3D_PERSP;
}
- if (walk->rv3d->persp == RV3D_CAMOB && ID_IS_LINKED_DATABLOCK(walk->v3d->camera)) {
+ if (walk->rv3d->persp == RV3D_CAMOB && ID_IS_LINKED(walk->v3d->camera)) {
BKE_report(op->reports, RPT_ERROR, "Cannot navigate a camera from an external library");
return false;
}
@@ -674,16 +673,6 @@ static int walkEnd(bContext *C, WalkInfo *walk)
return OPERATOR_CANCELLED;
}
-static bool wm_event_is_last_mousemove(const wmEvent *event)
-{
- while ((event = event->next)) {
- if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
- return false;
- }
- }
- return true;
-}
-
static void walkEvent(bContext *C, wmOperator *op, WalkInfo *walk, const wmEvent *event)
{
if (event->type == TIMER && event->customdata == walk->timer) {
@@ -710,7 +699,7 @@ static void walkEvent(bContext *C, wmOperator *op, WalkInfo *walk, const wmEvent
return;
}
- if ((walk->is_cursor_absolute == false) && WM_event_is_absolute(event)) {
+ if ((walk->is_cursor_absolute == false) && event->is_motion_absolute) {
walk->is_cursor_absolute = true;
copy_v2_v2_int(walk->prev_mval, event->mval);
copy_v2_v2_int(walk->center_mval, event->mval);
@@ -736,7 +725,7 @@ static void walkEvent(bContext *C, wmOperator *op, WalkInfo *walk, const wmEvent
}
else
#endif
- if (wm_event_is_last_mousemove(event)) {
+ if (WM_event_is_last_mousemove(event)) {
wmWindow *win = CTX_wm_window(C);
#ifdef __APPLE__
diff --git a/source/blender/editors/transform/transform.c b/source/blender/editors/transform/transform.c
index 1916f9b4dab..4a8bd5287df 100644
--- a/source/blender/editors/transform/transform.c
+++ b/source/blender/editors/transform/transform.c
@@ -51,7 +51,7 @@
#include "BLI_listbase.h"
#include "BLI_string.h"
#include "BLI_ghash.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_memarena.h"
#include "BKE_nla.h"
@@ -801,7 +801,7 @@ enum {
/* called in transform_ops.c, on each regeneration of keymaps */
wmKeyMap *transform_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{TFM_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{TFM_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
{TFM_MODAL_TRANSLATE, "TRANSLATE", 0, "Translate", ""},
@@ -1605,7 +1605,7 @@ static void drawArrow(ArrowDirection d, short offset, short length, short size)
offset = -offset;
length = -length;
size = -size;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case RIGHT:
glBegin(GL_LINES);
glVertex2s(offset, 0);
@@ -1621,7 +1621,7 @@ static void drawArrow(ArrowDirection d, short offset, short length, short size)
offset = -offset;
length = -length;
size = -size;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case UP:
glBegin(GL_LINES);
glVertex2s(0, offset);
@@ -1640,7 +1640,7 @@ static void drawArrowHead(ArrowDirection d, short size)
switch (d) {
case LEFT:
size = -size;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case RIGHT:
glBegin(GL_LINES);
glVertex2s(0, 0);
@@ -1652,7 +1652,7 @@ static void drawArrowHead(ArrowDirection d, short size)
case DOWN:
size = -size;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case UP:
glBegin(GL_LINES);
glVertex2s(0, 0);
@@ -1694,23 +1694,13 @@ static void drawHelpline(bContext *UNUSED(C), int x, int y, void *customdata)
TransInfo *t = (TransInfo *)customdata;
if (t->helpline != HLP_NONE && !(t->flag & T_USES_MANIPULATOR)) {
- float vecrot[3], cent[2];
+ float cent[2];
int mval[2];
mval[0] = x;
mval[1] = y;
- copy_v3_v3(vecrot, t->center);
- if (t->flag & T_EDIT) {
- Object *ob = t->obedit;
- if (ob) mul_m4_v3(ob->obmat, vecrot);
- }
- else if (t->flag & T_POSE) {
- Object *ob = t->poseobj;
- if (ob) mul_m4_v3(ob->obmat, vecrot);
- }
-
- projectFloatViewEx(t, vecrot, cent, V3D_PROJ_TEST_CLIP_ZERO);
+ projectFloatViewEx(t, t->center_global, cent, V3D_PROJ_TEST_CLIP_ZERO);
glPushMatrix();
@@ -1936,7 +1926,7 @@ void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
}
// If modal, save settings back in scene if not set as operator argument
- if (t->flag & T_MODAL) {
+ if ((t->flag & T_MODAL) || (op->flag & OP_IS_REPEAT)) {
/* save settings if not set in operator */
/* skip saving proportional edit if it was not actually used */
@@ -1956,10 +1946,9 @@ void saveTransform(bContext *C, TransInfo *t, wmOperator *op)
ts->proportional_objects = (proportional != PROP_EDIT_OFF);
}
- if ((prop = RNA_struct_find_property(op->ptr, "proportional_size")) &&
- !RNA_property_is_set(op->ptr, prop))
- {
- ts->proportional_size = t->prop_size;
+ if ((prop = RNA_struct_find_property(op->ptr, "proportional_size"))) {
+ ts->proportional_size =
+ RNA_property_is_set(op->ptr, prop) ? RNA_property_float_get(op->ptr, prop) : t->prop_size;
}
if ((prop = RNA_struct_find_property(op->ptr, "proportional_edit_falloff")) &&
@@ -2176,7 +2165,14 @@ bool initTransform(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve
calculateCenter(t);
if (event) {
- initMouseInput(t, &t->mouse, t->center2d, event->mval, event->shift);
+ /* Initialize accurate transform to settings requested by keymap. */
+ bool use_accurate = false;
+ if ((prop = RNA_struct_find_property(op->ptr, "use_accurate")) && RNA_property_is_set(op->ptr, prop)) {
+ if (RNA_property_boolean_get(op->ptr, prop)) {
+ use_accurate = true;
+ }
+ }
+ initMouseInput(t, &t->mouse, t->center2d, event->mval, use_accurate);
}
switch (mode) {
@@ -2871,7 +2867,9 @@ static void initBend(TransInfo *t)
t->flag |= T_NO_CONSTRAINT;
//copy_v3_v3(t->center, ED_view3d_cursor3d_get(t->scene, t->view));
- calculateCenterCursor(t, t->center);
+ if ((t->flag & T_OVERRIDE_CENTER) == 0) {
+ calculateCenterCursor(t, t->center);
+ }
calculateCenterGlobal(t, t->center, t->center_global);
t->val = 0.0f;
@@ -3044,19 +3042,13 @@ static void Bend(TransInfo *t, const int UNUSED(mval[2]))
/** \name Transform Shear
* \{ */
-static void postInputShear(TransInfo *UNUSED(t), float values[3])
-{
- mul_v3_fl(values, 0.05f);
-}
-
static void initShear(TransInfo *t)
{
t->mode = TFM_SHEAR;
t->transform = applyShear;
t->handleEvent = handleEventShear;
-
- setInputPostFct(&t->mouse, postInputShear);
- initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
+
+ initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
t->idx_max = 0;
t->num.idx_max = 0;
@@ -3078,24 +3070,24 @@ static eRedrawFlag handleEventShear(TransInfo *t, const wmEvent *event)
if (event->type == MIDDLEMOUSE && event->val == KM_PRESS) {
/* Use custom.mode.data pointer to signal Shear direction */
if (t->custom.mode.data == NULL) {
- initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
+ initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_RATIO);
t->custom.mode.data = (void *)1;
}
else {
- initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
+ initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
t->custom.mode.data = NULL;
}
status = TREDRAW_HARD;
}
else if (event->type == XKEY && event->val == KM_PRESS) {
- initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_ABSOLUTE);
+ initMouseInputMode(t, &t->mouse, INPUT_HORIZONTAL_RATIO);
t->custom.mode.data = NULL;
status = TREDRAW_HARD;
}
else if (event->type == YKEY && event->val == KM_PRESS) {
- initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_ABSOLUTE);
+ initMouseInputMode(t, &t->mouse, INPUT_VERTICAL_RATIO);
t->custom.mode.data = (void *)1;
status = TREDRAW_HARD;
@@ -4066,13 +4058,15 @@ static void initTrackball(TransInfo *t)
static void applyTrackballValue(TransInfo *t, const float axis1[3], const float axis2[3], float angles[2])
{
TransData *td = t->data;
- float mat[3][3], smat[3][3], totmat[3][3];
+ float mat[3][3];
+ float axis[3];
+ float angle;
int i;
- axis_angle_normalized_to_mat3(smat, axis1, angles[0]);
- axis_angle_normalized_to_mat3(totmat, axis2, angles[1]);
-
- mul_m3_m3m3(mat, smat, totmat);
+ mul_v3_v3fl(axis, axis1, angles[0]);
+ madd_v3_v3fl(axis, axis2, angles[1]);
+ angle = normalize_v3(axis);
+ axis_angle_normalized_to_mat3(mat, axis, angle);
for (i = 0; i < t->total; i++, td++) {
if (td->flag & TD_NOACTION)
@@ -4082,10 +4076,7 @@ static void applyTrackballValue(TransInfo *t, const float axis1[3], const float
continue;
if (t->flag & T_PROP_EDIT) {
- axis_angle_normalized_to_mat3(smat, axis1, td->factor * angles[0]);
- axis_angle_normalized_to_mat3(totmat, axis2, td->factor * angles[1]);
-
- mul_m3_m3m3(mat, smat, totmat);
+ axis_angle_normalized_to_mat3(mat, axis, td->factor * angle);
}
ElementRotation(t, td, mat, t->around);
@@ -4271,7 +4262,7 @@ static void headerTranslation(TransInfo *t, const float vec[3], char str[UI_MAX_
bUnit_AsString(distvec, sizeof(distvec), dist * t->scene->unit.scale_length, 4, t->scene->unit.system,
B_UNIT_LENGTH, do_split, false);
}
- else if (dist > 1e10f || dist < -1e10f) {
+ else if (dist > 1e10f || dist < -1e10f) {
/* prevent string buffer overflow */
BLI_snprintf(distvec, NUM_STR_REP_LEN, "%.4e", dist);
}
@@ -4331,7 +4322,7 @@ static void headerTranslation(TransInfo *t, const float vec[3], char str[UI_MAX_
const char *str_dir = (snode->insert_ofs_dir == SNODE_INSERTOFS_DIR_RIGHT) ? IFACE_("right") : IFACE_("left");
char str_km[64];
- WM_modalkeymap_items_to_string(t->keymap, TFM_MODAL_INSERTOFS_TOGGLE_DIR, true, sizeof(str_km), str_km);
+ WM_modalkeymap_items_to_string(t->keymap, TFM_MODAL_INSERTOFS_TOGGLE_DIR, true, str_km, sizeof(str_km));
ofs += BLI_snprintf(str, UI_MAX_DRAW_STR, IFACE_("Auto-offset set to %s - press %s to toggle direction | %s"),
str_dir, str_km, str_old);
@@ -4547,7 +4538,7 @@ static void applyShrinkFatten(TransInfo *t, const int UNUSED(mval[2]))
if (t->keymap) {
wmKeyMapItem *kmi = WM_modalkeymap_find_propvalue(t->keymap, TFM_MODAL_RESIZE);
if (kmi) {
- ofs += WM_keymap_item_to_string(kmi, false, sizeof(str) - ofs, str + ofs);
+ ofs += WM_keymap_item_to_string(kmi, false, str + ofs, sizeof(str) - ofs);
}
}
BLI_snprintf(str + ofs, sizeof(str) - ofs, IFACE_(" or Alt) Even Thickness %s"),
@@ -4941,7 +4932,7 @@ static void initPushPull(TransInfo *t)
static void applyPushPull(TransInfo *t, const int UNUSED(mval[2]))
{
- float vec[3], axis[3];
+ float vec[3], axis_global[3];
float distance;
int i;
char str[UI_MAX_DRAW_STR];
@@ -4969,7 +4960,7 @@ static void applyPushPull(TransInfo *t, const int UNUSED(mval[2]))
}
if (t->con.applyRot && t->con.mode & CON_APPLY) {
- t->con.applyRot(t, NULL, axis, NULL);
+ t->con.applyRot(t, NULL, axis_global, NULL);
}
for (i = 0; i < t->total; i++, td++) {
@@ -4981,7 +4972,11 @@ static void applyPushPull(TransInfo *t, const int UNUSED(mval[2]))
sub_v3_v3v3(vec, t->center, td->center);
if (t->con.applyRot && t->con.mode & CON_APPLY) {
+ float axis[3];
+ copy_v3_v3(axis, axis_global);
t->con.applyRot(t, td, axis, NULL);
+
+ mul_m3_v3(td->smtx, axis);
if (isLockConstraint(t)) {
float dvec[3];
project_v3_v3v3(dvec, vec, axis);
@@ -5554,10 +5549,10 @@ static void slide_origdata_interp_data_vert(
float v_proj[3][3];
if (do_loop_weight || do_loop_mdisps) {
- project_plane_v3_v3v3(v_proj[1], sv->co_orig_3d, v_proj_axis);
+ project_plane_normalized_v3_v3v3(v_proj[1], sv->co_orig_3d, v_proj_axis);
}
- // BM_ITER_ELEM (l, &liter, sv->v, BM_LOOPS_OF_VERT) {
+ // BM_ITER_ELEM (l, &liter, sv->v, BM_LOOPS_OF_VERT)
BM_iter_init(&liter, bm, BM_LOOPS_OF_VERT, sv->v);
l_num = liter.count;
loop_weights = do_loop_weight ? BLI_array_alloca(loop_weights, l_num) : NULL;
@@ -5588,19 +5583,19 @@ static void slide_origdata_interp_data_vert(
/* In the unlikely case that we're next to a zero length edge - walk around the to the next.
* Since we only need to check if the vertex is in this corner,
* its not important _which_ loop - as long as its not overlapping 'sv->co_orig_3d', see: T45096. */
- project_plane_v3_v3v3(v_proj[0], co_prev, v_proj_axis);
+ project_plane_normalized_v3_v3v3(v_proj[0], co_prev, v_proj_axis);
while (UNLIKELY(((co_prev_ok = (len_squared_v3v3(v_proj[1], v_proj[0]) > eps)) == false) &&
((l_prev = l_prev->prev) != l->next)))
{
co_prev = slide_origdata_orig_vert_co(sod, l_prev->v);
- project_plane_v3_v3v3(v_proj[0], co_prev, v_proj_axis);
+ project_plane_normalized_v3_v3v3(v_proj[0], co_prev, v_proj_axis);
}
- project_plane_v3_v3v3(v_proj[2], co_next, v_proj_axis);
+ project_plane_normalized_v3_v3v3(v_proj[2], co_next, v_proj_axis);
while (UNLIKELY(((co_next_ok = (len_squared_v3v3(v_proj[1], v_proj[2]) > eps)) == false) &&
((l_next = l_next->next) != l->prev)))
{
co_next = slide_origdata_orig_vert_co(sod, l_next->v);
- project_plane_v3_v3v3(v_proj[2], co_next, v_proj_axis);
+ project_plane_normalized_v3_v3v3(v_proj[2], co_next, v_proj_axis);
}
if (co_prev_ok && co_next_ok) {
@@ -5620,12 +5615,12 @@ static void slide_origdata_interp_data_vert(
if (sod->layer_math_map_num) {
if (do_loop_weight) {
for (j = 0; j < sod->layer_math_map_num; j++) {
- BM_vert_loop_groups_data_layer_merge_weights(bm, sv->cd_loop_groups[j], sod->layer_math_map[j], loop_weights);
+ BM_vert_loop_groups_data_layer_merge_weights(bm, sv->cd_loop_groups[j], sod->layer_math_map[j], loop_weights);
}
}
else {
for (j = 0; j < sod->layer_math_map_num; j++) {
- BM_vert_loop_groups_data_layer_merge(bm, sv->cd_loop_groups[j], sod->layer_math_map[j]);
+ BM_vert_loop_groups_data_layer_merge(bm, sv->cd_loop_groups[j], sod->layer_math_map[j]);
}
}
}
@@ -7985,7 +7980,7 @@ static void headerSeqSlide(TransInfo *t, const float val[2], char str[UI_MAX_DRA
if (t->keymap) {
wmKeyMapItem *kmi = WM_modalkeymap_find_propvalue(t->keymap, TFM_MODAL_TRANSLATE);
if (kmi) {
- ofs += WM_keymap_item_to_string(kmi, false, UI_MAX_DRAW_STR - ofs, str + ofs);
+ ofs += WM_keymap_item_to_string(kmi, false, str + ofs, UI_MAX_DRAW_STR - ofs);
}
}
ofs += BLI_snprintf(str + ofs, UI_MAX_DRAW_STR - ofs, IFACE_(" or Alt) Expand to fit %s"),
@@ -8356,8 +8351,15 @@ static void initTimeSlide(TransInfo *t)
TransData *td = t->data;
for (i = 0; i < t->total; i++, td++) {
- if (min > *(td->val)) min = *(td->val);
- if (max < *(td->val)) max = *(td->val);
+ AnimData *adt = (t->spacetype != SPACE_NLA) ? td->extra : NULL;
+ float val = *(td->val);
+
+ /* strip/action time to global (mapped) time */
+ if (adt)
+ val = BKE_nla_tweakedit_remap(adt, val, NLATIME_CONVERT_MAP);
+
+ if (min > val) min = val;
+ if (max < val) max = val;
}
if (min == max) {
@@ -8432,25 +8434,38 @@ static void applyTimeSlideValue(TransInfo *t, float sval)
*/
AnimData *adt = (t->spacetype != SPACE_NLA) ? td->extra : NULL;
float cval = t->values[0];
-
- /* apply NLA-mapping to necessary values */
- if (adt)
- cval = BKE_nla_tweakedit_remap(adt, cval, NLATIME_CONVERT_UNMAP);
-
+
/* only apply to data if in range */
if ((sval > minx) && (sval < maxx)) {
float cvalc = CLAMPIS(cval, minx, maxx);
+ float ival = td->ival;
float timefac;
-
+
+ /* NLA mapping magic here works as follows:
+ * - "ival" goes from strip time to global time
+ * - calculation is performed into td->val in global time
+ * (since sval and min/max are all in global time)
+ * - "td->val" then gets put back into strip time
+ */
+ if (adt) {
+ /* strip to global */
+ ival = BKE_nla_tweakedit_remap(adt, ival, NLATIME_CONVERT_MAP);
+ }
+
/* left half? */
- if (td->ival < sval) {
- timefac = (sval - td->ival) / (sval - minx);
+ if (ival < sval) {
+ timefac = (sval - ival) / (sval - minx);
*(td->val) = cvalc - timefac * (cvalc - minx);
}
else {
- timefac = (td->ival - sval) / (maxx - sval);
+ timefac = (ival - sval) / (maxx - sval);
*(td->val) = cvalc + timefac * (maxx - cvalc);
}
+
+ if (adt) {
+ /* global to strip */
+ *(td->val) = BKE_nla_tweakedit_remap(adt, *(td->val), NLATIME_CONVERT_UNMAP);
+ }
}
}
}
@@ -8509,9 +8524,11 @@ static void initTimeScale(TransInfo *t)
/* recalculate center2d to use CFRA and mouse Y, since that's
* what is used in time scale */
- t->center[0] = t->scene->r.cfra;
- projectFloatView(t, t->center, center);
- center[1] = t->mouse.imval[1];
+ if ((t->flag & T_OVERRIDE_CENTER) == 0) {
+ t->center[0] = t->scene->r.cfra;
+ projectFloatView(t, t->center, center);
+ center[1] = t->mouse.imval[1];
+ }
/* force a reinit with the center2d used here */
initMouseInput(t, &t->mouse, center, t->mouse.imval, false);
diff --git a/source/blender/editors/transform/transform.h b/source/blender/editors/transform/transform.h
index d60eb2f0778..06a60456cdb 100644
--- a/source/blender/editors/transform/transform.h
+++ b/source/blender/editors/transform/transform.h
@@ -533,6 +533,9 @@ typedef struct TransInfo {
/* alternative transformation. used to add offset to tracking markers */
#define T_ALT_TRANSFORM (1 << 24)
+ /** #TransInfo.center has been set, don't change it. */
+#define T_OVERRIDE_CENTER (1 << 25)
+
/* TransInfo->modifiers */
#define MOD_CONSTRAINT_SELECT 0x01
#define MOD_PRECISION 0x02
diff --git a/source/blender/editors/transform/transform_constraints.c b/source/blender/editors/transform/transform_constraints.c
index d7b670b6476..08bd36fe95c 100644
--- a/source/blender/editors/transform/transform_constraints.c
+++ b/source/blender/editors/transform/transform_constraints.c
@@ -831,6 +831,13 @@ static void drawObjectConstraint(TransInfo *t)
}
}
+ if (t->options & CTX_GPENCIL_STROKES) {
+ /* only draw a constraint line for one point, otherwise we can't see anything */
+ if ((options & DRAWLIGHT) == 0) {
+ break;
+ }
+ }
+
if (t->flag & T_OBJECT) {
copy_v3_v3(co, td->ob->obmat[3]);
axismtx = td->axismtx;
@@ -972,7 +979,7 @@ static void setNearestAxis3d(TransInfo *t)
* of two 2D points 30 pixels apart (that's the last factor in the formula) after
* projecting them with ED_view3d_win_to_delta and then get the length of that vector.
*/
- zfac = mul_project_m4_v3_zfac(t->persmat, t->center);
+ zfac = mul_project_m4_v3_zfac(t->persmat, t->center_global);
zfac = len_v3(t->persinv[0]) * 2.0f / t->ar->winx * zfac * 30.0f;
for (i = 0; i < 3; i++) {
diff --git a/source/blender/editors/transform/transform_conversions.c b/source/blender/editors/transform/transform_conversions.c
index 091a5773cf0..60092a28e36 100644
--- a/source/blender/editors/transform/transform_conversions.c
+++ b/source/blender/editors/transform/transform_conversions.c
@@ -771,29 +771,37 @@ int count_set_pose_transflags(int *out_mode, short around, Object *ob)
/* -------- Auto-IK ---------- */
/* adjust pose-channel's auto-ik chainlen */
-static void pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
+static bool pchan_autoik_adjust(bPoseChannel *pchan, short chainlen)
{
bConstraint *con;
+ bool changed = false;
/* don't bother to search if no valid constraints */
- if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0)
- return;
+ if ((pchan->constflag & (PCHAN_HAS_IK | PCHAN_HAS_TARGET)) == 0) {
+ return changed;
+ }
/* check if pchan has ik-constraint */
for (con = pchan->constraints.first; con; con = con->next) {
if (con->type == CONSTRAINT_TYPE_KINEMATIC && (con->enforce != 0.0f)) {
bKinematicConstraint *data = con->data;
-
+
/* only accept if a temporary one (for auto-ik) */
if (data->flag & CONSTRAINT_IK_TEMP) {
/* chainlen is new chainlen, but is limited by maximum chainlen */
- if ((chainlen == 0) || (chainlen > data->max_rootbone))
+ const int old_rootbone = data->rootbone;
+ if ((chainlen == 0) || (chainlen > data->max_rootbone)) {
data->rootbone = data->max_rootbone;
- else
+ }
+ else {
data->rootbone = chainlen;
+ }
+ changed |= (data->rootbone != old_rootbone);
}
}
}
+
+ return changed;
}
/* change the chain-length of auto-ik */
@@ -809,7 +817,13 @@ void transform_autoik_update(TransInfo *t, short mode)
}
else if (mode == -1) {
/* mode==-1 is from WHEELMOUSEUP... decreases len */
- if (*chainlen > 0) (*chainlen)--;
+ if (*chainlen > 0) {
+ (*chainlen)--;
+ }
+ else {
+ /* IK length did not change, skip updates. */
+ return;
+ }
}
/* sanity checks (don't assume t->poseobj is set, or that it is an armature) */
@@ -817,8 +831,19 @@ void transform_autoik_update(TransInfo *t, short mode)
return;
/* apply to all pose-channels */
+ bool changed = false;
for (pchan = t->poseobj->pose->chanbase.first; pchan; pchan = pchan->next) {
- pchan_autoik_adjust(pchan, *chainlen);
+ changed |= pchan_autoik_adjust(pchan, *chainlen);
+ }
+
+#ifdef WITH_LEGACY_DEPSGRAPH
+ if (!DEG_depsgraph_use_legacy())
+#endif
+ {
+ if (changed) {
+ /* TODO(sergey): Consider doing partial update only. */
+ DAG_relations_tag_update(G.main);
+ }
}
}
@@ -828,7 +853,9 @@ static void pose_grab_with_ik_clear(Object *ob)
bKinematicConstraint *data;
bPoseChannel *pchan;
bConstraint *con, *next;
+#ifdef WITH_LEGACY_DEPSGRAPH
bool need_dependency_update = false;
+#endif
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
/* clear all temporary lock flags */
@@ -843,7 +870,9 @@ static void pose_grab_with_ik_clear(Object *ob)
data = con->data;
if (data->flag & CONSTRAINT_IK_TEMP) {
/* iTaSC needs clear for removed constraints */
+#ifdef WITH_LEGACY_DEPSGRAPH
need_dependency_update = true;
+#endif
BIK_clear_data(ob->pose);
BLI_remlink(&pchan->constraints, con);
@@ -1171,7 +1200,7 @@ static void createTransArmatureVerts(TransInfo *t)
}
if (mirror && (oldtot < t->total)) {
- eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
+ eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebo);
if (eboflip)
total_mirrored++;
}
@@ -1341,7 +1370,7 @@ static void createTransArmatureVerts(TransInfo *t)
}
if (mirror && (td_old != td)) {
- eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebo);
+ eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebo);
if (eboflip) {
bid[i].bone = eboflip;
bid[i].dist = eboflip->dist;
@@ -1496,6 +1525,48 @@ static TransDataCurveHandleFlags *initTransDataCurveHandles(TransData *td, struc
return hdata;
}
+/**
+ * For the purpose of transform code we need to behave as if handles are selected,
+ * even when they aren't (see special case below).
+ */
+static int bezt_select_to_transform_triple_flag(
+ const BezTriple *bezt, const bool hide_handles)
+{
+ int flag = 0;
+
+ if (hide_handles) {
+ if (bezt->f2 & SELECT) {
+ flag = (1 << 0) | (1 << 1) | (1 << 2);
+ }
+ }
+ else {
+ flag = (
+ ((bezt->f1 & SELECT) ? (1 << 0) : 0) |
+ ((bezt->f2 & SELECT) ? (1 << 1) : 0) |
+ ((bezt->f3 & SELECT) ? (1 << 2) : 0)
+ );
+ }
+
+ /* Special case for auto & aligned handles:
+ * When a center point is being moved without the handles,
+ * leaving the handles stationary makes no sense and only causes strange behavior,
+ * where one handle is arbitrarily anchored, the other one is aligned and lengthened
+ * based on where the center point is moved. Also a bug when cancelling, see: T52007.
+ *
+ * A more 'correct' solution could be to store handle locations in 'TransDataCurveHandleFlags'.
+ * However that doesn't resolve odd behavior, so best transform the handles in this case.
+ */
+ if ((flag != ((1 << 0) | (1 << 1) | (1 << 2))) && (flag & (1 << 1))) {
+ if (ELEM(bezt->h1, HD_AUTO, HD_ALIGN) &&
+ ELEM(bezt->h2, HD_AUTO, HD_ALIGN))
+ {
+ flag = (1 << 0) | (1 << 1) | (1 << 2);
+ }
+ }
+
+ return flag;
+}
+
static void createTransCurveVerts(TransInfo *t)
{
Curve *cu = t->obedit->data;
@@ -1513,22 +1584,22 @@ static void createTransCurveVerts(TransInfo *t)
/* to be sure */
if (cu->editnurb == NULL) return;
+#define SEL_F1 (1 << 0)
+#define SEL_F2 (1 << 1)
+#define SEL_F3 (1 << 2)
+
/* count total of vertices, check identical as in 2nd loop for making transdata! */
nurbs = BKE_curve_editNurbs_get(cu);
for (nu = nurbs->first; nu; nu = nu->next) {
if (nu->type == CU_BEZIER) {
for (a = 0, bezt = nu->bezt; a < nu->pntsu; a++, bezt++) {
if (bezt->hide == 0) {
- if (hide_handles) {
- if (bezt->f2 & SELECT) countsel += 3;
- if (is_prop_edit) count += 3;
- }
- else {
- if (bezt->f1 & SELECT) countsel++;
- if (bezt->f2 & SELECT) countsel++;
- if (bezt->f3 & SELECT) countsel++;
- if (is_prop_edit) count += 3;
- }
+ const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
+ if (bezt_tx & SEL_F1) { countsel++; }
+ if (bezt_tx & SEL_F2) { countsel++; }
+ if (bezt_tx & SEL_F3) { countsel++; }
+ if (is_prop_edit) count += 3;
+
}
}
}
@@ -1579,10 +1650,10 @@ static void createTransCurveVerts(TransInfo *t)
}
}
- if (is_prop_edit ||
- ((bezt->f2 & SELECT) && hide_handles) ||
- ((bezt->f1 & SELECT) && hide_handles == 0))
- {
+ /* Elements that will be transform (not always a match to selection). */
+ const int bezt_tx = bezt_select_to_transform_triple_flag(bezt, hide_handles);
+
+ if (is_prop_edit || bezt_tx & SEL_F1) {
copy_v3_v3(td->iloc, bezt->vec[0]);
td->loc = bezt->vec[0];
copy_v3_v3(td->center, bezt->vec[(hide_handles ||
@@ -1613,7 +1684,7 @@ static void createTransCurveVerts(TransInfo *t)
}
/* This is the Curve Point, the other two are handles */
- if (is_prop_edit || (bezt->f2 & SELECT)) {
+ if (is_prop_edit || bezt_tx & SEL_F2) {
copy_v3_v3(td->iloc, bezt->vec[1]);
td->loc = bezt->vec[1];
copy_v3_v3(td->center, td->loc);
@@ -1639,7 +1710,7 @@ static void createTransCurveVerts(TransInfo *t)
copy_m3_m3(td->axismtx, axismtx);
}
- if ((bezt->f1 & SELECT) == 0 && (bezt->f3 & SELECT) == 0)
+ if ((bezt_tx & SEL_F1) == 0 && (bezt_tx & SEL_F3) == 0)
/* If the middle is selected but the sides arnt, this is needed */
if (hdata == NULL) { /* if the handle was not saved by the previous handle */
hdata = initTransDataCurveHandles(td, bezt);
@@ -1649,10 +1720,7 @@ static void createTransCurveVerts(TransInfo *t)
count++;
tail++;
}
- if (is_prop_edit ||
- ((bezt->f2 & SELECT) && hide_handles) ||
- ((bezt->f3 & SELECT) && hide_handles == 0))
- {
+ if (is_prop_edit || bezt_tx & SEL_F3) {
copy_v3_v3(td->iloc, bezt->vec[2]);
td->loc = bezt->vec[2];
copy_v3_v3(td->center, bezt->vec[(hide_handles ||
@@ -1707,6 +1775,26 @@ static void createTransCurveVerts(TransInfo *t)
for (a = nu->pntsu * nu->pntsv, bp = nu->bp; a > 0; a--, bp++) {
if (bp->hide == 0) {
if (is_prop_edit || (bp->f1 & SELECT)) {
+ float axismtx[3][3];
+
+ if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
+ if (nu->pntsv == 1) {
+ float normal[3], plane[3];
+
+ BKE_nurb_bpoint_calc_normal(nu, bp, normal);
+ BKE_nurb_bpoint_calc_plane(nu, bp, plane);
+
+ if (createSpaceNormalTangent(axismtx, normal, plane)) {
+ /* pass */
+ }
+ else {
+ normalize_v3(normal);
+ axis_dominant_v3_to_m3(axismtx, normal);
+ invert_m3(axismtx);
+ }
+ }
+ }
+
copy_v3_v3(td->iloc, bp->vec);
td->loc = bp->vec;
copy_v3_v3(td->center, td->loc);
@@ -1725,6 +1813,11 @@ static void createTransCurveVerts(TransInfo *t)
copy_m3_m3(td->smtx, smtx);
copy_m3_m3(td->mtx, mtx);
+ if (t->around == V3D_AROUND_LOCAL_ORIGINS) {
+ if (nu->pntsv == 1) {
+ copy_m3_m3(td->axismtx, axismtx);
+ }
+ }
td++;
count++;
@@ -1740,6 +1833,10 @@ static void createTransCurveVerts(TransInfo *t)
calc_distanceCurveVerts(head, tail - 1);
}
}
+
+#undef SEL_F1
+#undef SEL_F2
+#undef SEL_F3
}
/* ********************* lattice *************** */
@@ -1808,7 +1905,6 @@ static void createTransParticleVerts(bContext *C, TransInfo *t)
{
TransData *td = NULL;
TransDataExtension *tx;
- Base *base = CTX_data_active_base(C);
Object *ob = CTX_data_active_object(C);
ParticleEditSettings *pset = PE_settings(t->scene);
PTCacheEdit *edit = PE_get_current(t->scene, ob);
@@ -1828,8 +1924,6 @@ static void createTransParticleVerts(bContext *C, TransInfo *t)
if (psys)
psmd = psys_get_modifier(ob, psys);
- base->flag |= BA_HAS_RECALC_DATA;
-
for (i = 0, point = edit->points; i < edit->totpoint; i++, point++) {
point->flag &= ~PEP_TRANSFORM;
transformparticle = 0;
@@ -1973,9 +2067,12 @@ void flushTransParticles(TransInfo *t)
/* ********************* mesh ****************** */
-static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
- float *dists, const float *dists_prev,
- float mtx[3][3])
+static bool bmesh_test_dist_add(
+ BMVert *v, BMVert *v_other,
+ float *dists, const float *dists_prev,
+ /* optionally track original index */
+ int *index, const int *index_prev,
+ float mtx[3][3])
{
if ((BM_elem_flag_test(v_other, BM_ELEM_SELECT) == 0) &&
(BM_elem_flag_test(v_other, BM_ELEM_HIDDEN) == 0))
@@ -1990,6 +2087,9 @@ static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
dist_other = dists_prev[i] + len_v3(vec);
if (dist_other < dists[i_other]) {
dists[i_other] = dist_other;
+ if (index != NULL) {
+ index[i_other] = index_prev[i];
+ }
return true;
}
}
@@ -1997,11 +2097,13 @@ static bool bmesh_test_dist_add(BMVert *v, BMVert *v_other,
return false;
}
-static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists)
+/**
+ * \param mtx: Measure disatnce in this space.
+ * \param dists: Store the closest connected distance to selected vertices.
+ * \param index: Optionally store the original index we're measuring the distance to (can be NULL).
+ */
+static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float *dists, int *index)
{
- /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
- float *dists_prev = MEM_mallocN(bm->totvert * sizeof(float), __func__);
-
BLI_LINKSTACK_DECLARE(queue, BMVert *);
/* any BM_ELEM_TAG'd vertex is in 'queue_next', so we don't add in twice */
@@ -2022,17 +2124,27 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
if (BM_elem_flag_test(v, BM_ELEM_SELECT) == 0 || BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
dist = FLT_MAX;
+ if (index != NULL) {
+ index[i] = i;
+ }
}
else {
BLI_LINKSTACK_PUSH(queue, v);
dist = 0.0f;
+ if (index != NULL) {
+ index[i] = i;
+ }
}
- dists[i] = dists_prev[i] = dist;
+ dists[i] = dist;
}
bm->elem_index_dirty &= ~BM_VERT;
}
+ /* need to be very careful of feedback loops here, store previous dist's to avoid feedback */
+ float *dists_prev = MEM_dupallocN(dists);
+ int *index_prev = MEM_dupallocN(index); /* may be NULL */
+
do {
BMVert *v;
LinkNode *lnk;
@@ -2061,7 +2173,7 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
/* edge distance */
{
BMVert *v_other = BM_edge_other_vert(e_iter, v);
- if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
+ if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
BM_elem_flag_enable(v_other, BM_ELEM_TAG);
BLI_LINKSTACK_PUSH(queue_next, v_other);
@@ -2086,7 +2198,7 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
(BM_elem_flag_test(l_iter_radial->f, BM_ELEM_HIDDEN) == 0))
{
BMVert *v_other = l_iter_radial->next->next->v;
- if (bmesh_test_dist_add(v, v_other, dists, dists_prev, mtx)) {
+ if (bmesh_test_dist_add(v, v_other, dists, dists_prev, index, index_prev, mtx)) {
if (BM_elem_flag_test(v_other, BM_ELEM_TAG) == 0) {
BM_elem_flag_enable(v_other, BM_ELEM_TAG);
BLI_LINKSTACK_PUSH(queue_next, v_other);
@@ -2110,6 +2222,9 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
/* keep in sync, avoid having to do full memcpy each iteration */
dists_prev[i] = dists[i];
+ if (index != NULL) {
+ index_prev[i] = index[i];
+ }
}
BLI_LINKSTACK_SWAP(queue, queue_next);
@@ -2123,9 +2238,14 @@ static void editmesh_set_connectivity_distance(BMesh *bm, float mtx[3][3], float
BLI_LINKSTACK_FREE(queue_next);
MEM_freeN(dists_prev);
+ if (index_prev != NULL) {
+ MEM_freeN(index_prev);
+ }
}
-static struct TransIslandData *editmesh_islands_info_calc(BMEditMesh *em, int *r_island_tot, int **r_island_vert_map)
+static struct TransIslandData *editmesh_islands_info_calc(
+ BMEditMesh *em, int *r_island_tot, int **r_island_vert_map,
+ bool calc_single_islands)
{
BMesh *bm = em->bm;
struct TransIslandData *trans_islands;
@@ -2237,6 +2357,42 @@ static struct TransIslandData *editmesh_islands_info_calc(BMEditMesh *em, int *r
MEM_freeN(groups_array);
MEM_freeN(group_index);
+ /* for PET we need islands of 1 so connected vertices can use it with V3D_AROUND_LOCAL_ORIGINS */
+ if (calc_single_islands) {
+ BMIter viter;
+ BMVert *v;
+ int group_tot_single = 0;
+
+ BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
+ if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
+ group_tot_single += 1;
+ }
+ }
+
+ if (group_tot_single != 0) {
+ trans_islands = MEM_reallocN(trans_islands, sizeof(*trans_islands) * (group_tot + group_tot_single));
+
+ BM_ITER_MESH_INDEX (v, &viter, bm, BM_VERTS_OF_MESH, i) {
+ if (BM_elem_flag_test(v, BM_ELEM_SELECT) && (vert_map[i] == -1)) {
+ struct TransIslandData *v_island = &trans_islands[group_tot];
+ vert_map[i] = group_tot;
+
+ copy_v3_v3(v_island->co, v->co);
+
+ if (is_zero_v3(v->no) != 0.0f) {
+ axis_dominant_v3_to_m3(v_island->axismtx, v->no);
+ invert_m3(v_island->axismtx);
+ }
+ else {
+ unit_m3(v_island->axismtx);
+ }
+
+ group_tot += 1;
+ }
+ }
+ }
+ }
+
*r_island_tot = group_tot;
*r_island_vert_map = vert_map;
@@ -2336,6 +2492,12 @@ static void createTransEditVerts(TransInfo *t)
int island_info_tot;
int *island_vert_map = NULL;
+ /* Even for translation this is needed because of island-orientation, see: T51651. */
+ const bool is_island_center = (t->around == V3D_AROUND_LOCAL_ORIGINS);
+ /* Original index of our connected vertex when connected distances are calculated.
+ * Optional, allocate if needed. */
+ int *dists_index = NULL;
+
if (t->flag & T_MIRROR) {
EDBM_verts_mirror_cache_begin(em, 0, false, (t->flag & T_PROP_EDIT) == 0, use_topology);
mirror = 1;
@@ -2367,8 +2529,12 @@ static void createTransEditVerts(TransInfo *t)
t->total = count;
/* allocating scratch arrays */
- if (prop_mode & T_PROP_CONNECTED)
- dists = MEM_mallocN(em->bm->totvert * sizeof(float), "scratch nears");
+ if (prop_mode & T_PROP_CONNECTED) {
+ dists = MEM_mallocN(em->bm->totvert * sizeof(float), __func__);
+ if (is_island_center) {
+ dists_index = MEM_mallocN(em->bm->totvert * sizeof(int), __func__);
+ }
+ }
}
else {
t->total = bm->totvertsel;
@@ -2390,16 +2556,17 @@ static void createTransEditVerts(TransInfo *t)
pseudoinverse_m3_m3(smtx, mtx, PSEUDOINVERSE_EPSILON);
if (prop_mode & T_PROP_CONNECTED) {
- editmesh_set_connectivity_distance(em->bm, mtx, dists);
+ editmesh_set_connectivity_distance(em->bm, mtx, dists, dists_index);
}
- /* Only in case of rotation and resize, we want the elements of the edited
- * object to behave as groups whose pivot are the individual origins
- *
- * TODO: use island_info to detect the closest point when the "Snap Target"
- * in Blender UI is "Closest" */
- if ((t->around == V3D_AROUND_LOCAL_ORIGINS) && (t->mode != TFM_TRANSLATION)) {
- island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map);
+ if (is_island_center) {
+ /* In this specific case, near-by vertices will need to know the island of the nearest connected vertex. */
+ const bool calc_single_islands = (
+ (prop_mode & T_PROP_CONNECTED) &&
+ (t->around == V3D_AROUND_LOCAL_ORIGINS) &&
+ (em->selectmode & SCE_SELECT_VERTEX));
+
+ island_info = editmesh_islands_info_calc(em, &island_info_tot, &island_vert_map, calc_single_islands);
}
/* detect CrazySpace [tm] */
@@ -2449,10 +2616,16 @@ static void createTransEditVerts(TransInfo *t)
BM_ITER_MESH_INDEX (eve, &iter, bm, BM_VERTS_OF_MESH, a) {
if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
if (prop_mode || BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
- struct TransIslandData *v_island = (island_info && island_vert_map[a] != -1) ?
- &island_info[island_vert_map[a]] : NULL;
+ struct TransIslandData *v_island = NULL;
float *bweight = (cd_vert_bweight_offset != -1) ? BM_ELEM_CD_GET_VOID_P(eve, cd_vert_bweight_offset) : NULL;
+ if (island_info) {
+ const int connected_index = (dists_index && dists_index[a] != -1) ? dists_index[a] : a;
+ v_island = (island_vert_map[connected_index] != -1) ?
+ &island_info[island_vert_map[connected_index]] : NULL;
+ }
+
+
VertsToTransData(t, tob, tx, em, eve, bweight, v_island);
if (tx)
tx++;
@@ -2531,6 +2704,8 @@ cleanup:
MEM_freeN(defmats);
if (dists)
MEM_freeN(dists);
+ if (dists_index)
+ MEM_freeN(dists_index);
if (t->flag & T_MIRROR) {
EDBM_verts_mirror_cache_end(em);
@@ -2623,7 +2798,7 @@ void flushTransSeq(TransInfo *t)
tdsq = (TransDataSeq *)td->extra;
seq = tdsq->seq;
old_start = seq->start;
- new_frame = iroundf(td2d->loc[0]);
+ new_frame = round_fl_to_int(td2d->loc[0]);
switch (tdsq->sel_flag) {
case SELECT:
@@ -2635,7 +2810,7 @@ void flushTransSeq(TransInfo *t)
seq->start = new_frame - tdsq->start_offset;
#endif
if (seq->depth == 0) {
- seq->machine = iroundf(td2d->loc[1]);
+ seq->machine = round_fl_to_int(td2d->loc[1]);
CLAMP(seq->machine, 1, MAXSEQ);
}
break;
@@ -3337,67 +3512,136 @@ static void posttrans_mask_clean(Mask *mask)
}
}
+/* Time + Average value */
+typedef struct tRetainedKeyframe {
+ struct tRetainedKeyframe *next, *prev;
+ float frame; /* frame to cluster around */
+ float val; /* average value */
+
+ size_t tot_count; /* number of keyframes that have been averaged */
+ size_t del_count; /* number of keyframes of this sort that have been deleted so far */
+} tRetainedKeyframe;
+
/* Called during special_aftertrans_update to make sure selected keyframes replace
* any other keyframes which may reside on that frame (that is not selected).
*/
static void posttrans_fcurve_clean(FCurve *fcu, const bool use_handle)
{
- float *selcache; /* cache for frame numbers of selected frames (fcu->totvert*sizeof(float)) */
- int len, index, i; /* number of frames in cache, item index */
-
- /* allocate memory for the cache */
- // TODO: investigate using BezTriple columns instead?
- if (fcu->totvert == 0 || fcu->bezt == NULL)
+ /* NOTE: We assume that all keys are sorted */
+ ListBase retained_keys = {NULL, NULL};
+ const bool can_average_points = ((fcu->flag & (FCURVE_INT_VALUES | FCURVE_DISCRETE_VALUES)) == 0);
+
+ /* sanity checks */
+ if ((fcu->totvert == 0) || (fcu->bezt == NULL))
return;
- selcache = MEM_callocN(sizeof(float) * fcu->totvert, "FCurveSelFrameNums");
- len = 0;
- index = 0;
-
- /* We do 2 loops, 1 for marking keyframes for deletion, one for deleting
- * as there is no guarantee what order the keyframes are exactly, even though
- * they have been sorted by time.
+
+ /* 1) Identify selected keyframes, and average the values on those
+ * in case there are collisions due to multiple keys getting scaled
+ * to all end up on the same frame
*/
-
- /* Loop 1: find selected keyframes */
- for (i = 0; i < fcu->totvert; i++) {
+ for (int i = 0; i < fcu->totvert; i++) {
BezTriple *bezt = &fcu->bezt[i];
if (BEZT_ISSEL_ANY(bezt)) {
- selcache[index] = bezt->vec[1][0];
- index++;
- len++;
+ bool found = false;
+
+ /* If there's another selected frame here, merge it */
+ for (tRetainedKeyframe *rk = retained_keys.last; rk; rk = rk->prev) {
+ if (IS_EQT(rk->frame, bezt->vec[1][0], BEZT_BINARYSEARCH_THRESH)) {
+ rk->val += bezt->vec[1][1];
+ rk->tot_count++;
+
+ found = true;
+ break;
+ }
+ else if (rk->frame < bezt->vec[1][0]) {
+ /* Terminate early if have passed the supposed insertion point? */
+ break;
+ }
+ }
+
+ /* If nothing found yet, create a new one */
+ if (found == false) {
+ tRetainedKeyframe *rk = MEM_callocN(sizeof(tRetainedKeyframe), "tRetainedKeyframe");
+
+ rk->frame = bezt->vec[1][0];
+ rk->val = bezt->vec[1][1];
+ rk->tot_count = 1;
+
+ BLI_addtail(&retained_keys, rk);
+ }
}
}
-
- /* Loop 2: delete unselected keyframes on the same frames
- * (if any keyframes were found, or the whole curve wasn't affected)
+
+ if (BLI_listbase_is_empty(&retained_keys)) {
+ /* This may happen if none of the points were selected... */
+ if (G.debug & G_DEBUG) {
+ printf("%s: nothing to do for FCurve %p (rna_path = '%s')\n", __func__, fcu, fcu->rna_path);
+ }
+ return;
+ }
+ else {
+ /* Compute the average values for each retained keyframe */
+ for (tRetainedKeyframe *rk = retained_keys.first; rk; rk = rk->next) {
+ rk->val = rk->val / (float)rk->tot_count;
+ }
+ }
+
+ /* 2) Delete all keyframes duplicating the "retained keys" found above
+ * - Most of these will be unselected keyframes
+ * - Some will be selected keyframes though. For those, we only keep the last one
+ * (or else everything is gone), and replace its value with the averaged value.
*/
- if ((len) && (len != fcu->totvert)) {
- for (i = fcu->totvert - 1; i >= 0; i--) {
- BezTriple *bezt = &fcu->bezt[i];
-
- if (BEZT_ISSEL_ANY(bezt) == 0) {
- /* check beztriple should be removed according to cache */
- for (index = 0; index < len; index++) {
- if (IS_EQF(bezt->vec[1][0], selcache[index])) {
+ for (int i = fcu->totvert - 1; i >= 0; i--) {
+ BezTriple *bezt = &fcu->bezt[i];
+
+ /* Is this keyframe a candidate for deletion? */
+ /* TODO: Replace loop with an O(1) lookup instead */
+ for (tRetainedKeyframe *rk = retained_keys.last; rk; rk = rk->prev) {
+ if (IS_EQT(bezt->vec[1][0], rk->frame, BEZT_BINARYSEARCH_THRESH)) {
+ /* Selected keys are treated with greater care than unselected ones... */
+ if (BEZT_ISSEL_ANY(bezt)) {
+ /* - If this is the last selected key left (based on rk->del_count) ==> UPDATE IT
+ * (or else we wouldn't have any keyframe left here)
+ * - Otherwise, there are still other selected keyframes on this frame
+ * to be merged down still ==> DELETE IT
+ */
+ if (rk->del_count == rk->tot_count - 1) {
+ /* Update keyframe... */
+ if (can_average_points) {
+ /* TODO: update handles too? */
+ bezt->vec[1][1] = rk->val;
+ }
+ }
+ else {
+ /* Delete Keyframe */
delete_fcurve_key(fcu, i, 0);
- break;
}
- else if (bezt->vec[1][0] < selcache[index])
- break;
+
+ /* Update count of how many we've deleted
+ * - It should only matter that we're doing this for all but the last one
+ */
+ rk->del_count++;
+ }
+ else {
+ /* Always delete - Unselected keys don't matter */
+ delete_fcurve_key(fcu, i, 0);
}
+
+ /* Stop the RK search... we've found our match now */
+ break;
}
}
-
- testhandles_fcurve(fcu, use_handle);
}
-
- /* free cache */
- MEM_freeN(selcache);
+
+ /* 3) Recalculate handles */
+ testhandles_fcurve(fcu, use_handle);
+
+ /* cleanup */
+ BLI_freelistN(&retained_keys);
}
-
/* Called by special_aftertrans_update to make sure selected keyframes replace
* any other keyframes which may reside on that frame (that is not selected).
* remake_action_ipos should have already been called
@@ -3583,7 +3827,7 @@ void flushTransIntFrameActionData(TransInfo *t)
/* flush data! */
for (i = 0; i < t->total; i++, tfd++) {
- *(tfd->sdata) = iroundf(tfd->val);
+ *(tfd->sdata) = round_fl_to_int(tfd->val);
}
}
@@ -4611,7 +4855,7 @@ void flushTransGraphData(TransInfo *t)
/* if int-values only, truncate to integers */
if (td->flag & TD_INTVALUES)
- td2d->loc2d[1] = floorf(td2d->loc[1] + 0.5f);
+ td2d->loc2d[1] = floorf(td2d->loc[1] * inv_unit_scale - tdg->offset + 0.5f);
else
td2d->loc2d[1] = td2d->loc[1] * inv_unit_scale - tdg->offset;
@@ -5264,7 +5508,8 @@ static void ObjectToTransData(TransInfo *t, TransData *td, Object *ob)
}
/* update object's loc/rot to get current rigid body transform */
mat4_to_loc_rot_size(ob->loc, rot, scale, ob->obmat);
- BKE_object_mat3_to_rot(ob, rot, false);
+ sub_v3_v3(ob->loc, ob->dloc);
+ BKE_object_mat3_to_rot(ob, rot, false); /* drot is already corrected here */
}
}
@@ -5427,17 +5672,14 @@ static void set_trans_object_base_flags(TransInfo *t)
}
/* all recalc flags get flushed to all layers, so a layer flip later on works fine */
-#ifdef WITH_LEGACY_DEPSGRAPH
DAG_scene_flush_update(G.main, t->scene, -1, 0);
-#endif
/* and we store them temporal in base (only used for transform code) */
/* this because after doing updates, the object->recalc is cleared */
for (base = scene->base.first; base; base = base->next) {
- if (base->object->recalc & OB_RECALC_OB)
- base->flag |= BA_HAS_RECALC_OB;
- if (base->object->recalc & OB_RECALC_DATA)
- base->flag |= BA_HAS_RECALC_DATA;
+ if (base->object->recalc & (OB_RECALC_OB | OB_RECALC_DATA)) {
+ base->flag |= BA_SNAP_FIX_DEPS_FIASCO;
+ }
}
}
@@ -5508,17 +5750,14 @@ static int count_proportional_objects(TransInfo *t)
/* all recalc flags get flushed to all layers, so a layer flip later on works fine */
DAG_scene_relations_update(G.main, t->scene);
-#ifdef WITH_LEGACY_DEPSGRAPH
DAG_scene_flush_update(G.main, t->scene, -1, 0);
-#endif
/* and we store them temporal in base (only used for transform code) */
/* this because after doing updates, the object->recalc is cleared */
for (base = scene->base.first; base; base = base->next) {
- if (base->object->recalc & OB_RECALC_OB)
- base->flag |= BA_HAS_RECALC_OB;
- if (base->object->recalc & OB_RECALC_DATA)
- base->flag |= BA_HAS_RECALC_DATA;
+ if (base->object->recalc & (OB_RECALC_OB | OB_RECALC_DATA)) {
+ base->flag |= BA_SNAP_FIX_DEPS_FIASCO;
+ }
}
return total;
@@ -5533,7 +5772,7 @@ static void clear_trans_object_base_flags(TransInfo *t)
if (base->flag & BA_WAS_SEL)
base->flag |= SELECT;
- base->flag &= ~(BA_WAS_SEL | BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA | BA_TEMP_TAG | BA_TRANSFORM_CHILD | BA_TRANSFORM_PARENT);
+ base->flag &= ~(BA_WAS_SEL | BA_SNAP_FIX_DEPS_FIASCO | BA_TEMP_TAG | BA_TRANSFORM_CHILD | BA_TRANSFORM_PARENT);
}
}
@@ -5797,27 +6036,23 @@ static void special_aftertrans_update__movieclip(bContext *C, TransInfo *t)
{
SpaceClip *sc = t->sa->spacedata.first;
MovieClip *clip = ED_space_clip_get_clip(sc);
- MovieTrackingPlaneTrack *plane_track;
ListBase *plane_tracks_base = BKE_tracking_get_active_plane_tracks(&clip->tracking);
- int framenr = ED_space_clip_get_clip_frame_number(sc);
-
- for (plane_track = plane_tracks_base->first;
+ const int framenr = ED_space_clip_get_clip_frame_number(sc);
+ /* Update coordinates of modified plane tracks. */
+ for (MovieTrackingPlaneTrack *plane_track = plane_tracks_base->first;
plane_track;
plane_track = plane_track->next)
{
bool do_update = false;
-
if (plane_track->flag & PLANE_TRACK_HIDDEN) {
continue;
}
-
do_update |= PLANE_TRACK_VIEW_SELECTED(plane_track) != 0;
if (do_update == false) {
if ((plane_track->flag & PLANE_TRACK_AUTOKEY) == 0) {
int i;
for (i = 0; i < plane_track->point_tracksnr; i++) {
MovieTrackingTrack *track = plane_track->point_tracks[i];
-
if (TRACK_VIEW_SELECTED(sc, track)) {
do_update = true;
break;
@@ -5825,15 +6060,14 @@ static void special_aftertrans_update__movieclip(bContext *C, TransInfo *t)
}
}
}
-
if (do_update) {
BKE_tracking_track_plane_from_existing_motion(plane_track, framenr);
}
}
-
- if (t->scene->nodetree) {
- /* tracks can be used for stabilization nodes,
- * flush update for such nodes */
+ if (t->scene->nodetree != NULL) {
+ /* Tracks can be used for stabilization nodes,
+ * flush update for such nodes.
+ */
nodeUpdateID(t->scene->nodetree, &clip->id);
WM_event_add_notifier(C, NC_SCENE | ND_NODES, NULL);
}
@@ -6438,7 +6672,7 @@ static void createTransObject(bContext *C, TransInfo *t)
}
/* select linked objects, but skip them later */
- if (ID_IS_LINKED_DATABLOCK(ob)) {
+ if (ID_IS_LINKED(ob)) {
td->flag |= TD_SKIP;
}
@@ -7661,7 +7895,7 @@ static void createTransGPencil(bContext *C, TransInfo *t)
float mtx[3][3], smtx[3][3];
const Scene *scene = CTX_data_scene(C);
- const int cfra = CFRA;
+ const int cfra_scene = CFRA;
const bool is_prop_edit = (t->flag & T_PROP_EDIT) != 0;
const bool is_prop_edit_connected = (t->flag & T_PROP_CONNECTED) != 0;
@@ -7686,7 +7920,7 @@ static void createTransGPencil(bContext *C, TransInfo *t)
if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
bGPDframe *gpf = gpl->actframe;
bGPDstroke *gps;
-
+
for (gps = gpf->strokes.first; gps; gps = gps->next) {
/* skip strokes that are invalid for current view */
if (ED_gpencil_stroke_can_use(C, gps) == false) {
@@ -7742,6 +7976,7 @@ static void createTransGPencil(bContext *C, TransInfo *t)
for (gpl = gpd->layers.first; gpl; gpl = gpl->next) {
/* only editable and visible layers are considered */
if (gpencil_layer_is_editable(gpl) && (gpl->actframe != NULL)) {
+ const int cfra = (gpl->flag & GP_LAYER_FRAMELOCK) ? gpl->actframe->framenum : cfra_scene;
bGPDframe *gpf = gpl->actframe;
bGPDstroke *gps;
float diff_mat[4][4];
@@ -7758,7 +7993,6 @@ static void createTransGPencil(bContext *C, TransInfo *t)
* - This is useful when animating as it saves that "uh-oh" moment when you realize you've
* spent too much time editing the wrong frame...
*/
- // XXX: should this be allowed when framelock is enabled?
if (gpf->framenum != cfra) {
gpf = BKE_gpencil_frame_addcopy(gpl, cfra);
/* in some weird situations (framelock enabled) return NULL */
@@ -8038,7 +8272,12 @@ void createTransData(bContext *C, TransInfo *t)
if (t->data && t->flag & T_PROP_EDIT) {
if (ELEM(t->obedit->type, OB_CURVE, OB_MESH)) {
sort_trans_data(t); // makes selected become first in array
- set_prop_dist(t, 0);
+ if ((t->obedit->type == OB_MESH) && (t->flag & T_PROP_CONNECTED)) {
+ /* already calculated by editmesh_set_connectivity_distance */
+ }
+ else {
+ set_prop_dist(t, 0);
+ }
sort_trans_data_dist(t);
}
else {
diff --git a/source/blender/editors/transform/transform_generics.c b/source/blender/editors/transform/transform_generics.c
index f78a23be7b8..1ff602e075e 100644
--- a/source/blender/editors/transform/transform_generics.c
+++ b/source/blender/editors/transform/transform_generics.c
@@ -82,7 +82,6 @@
#include "BKE_editmesh.h"
#include "BKE_tracking.h"
#include "BKE_mask.h"
-#include "BKE_utildefines.h"
#include "ED_anim_api.h"
#include "ED_armature.h"
@@ -267,6 +266,7 @@ static void animrecord_check_state(Scene *scene, ID *id, wmTimer *animtimer)
/* if playback has just looped around, we need to add a new NLA track+strip to allow a clean pass to occur */
if ((sad) && (sad->flag & ANIMPLAY_FLAG_JUMPED)) {
AnimData *adt = BKE_animdata_from_id(id);
+ const bool is_first = (adt) && (adt->nla_tracks.first == NULL);
/* perform push-down manually with some differences
* NOTE: BKE_nla_action_pushdown() sync warning...
@@ -277,7 +277,7 @@ static void animrecord_check_state(Scene *scene, ID *id, wmTimer *animtimer)
/* only push down if action is more than 1-2 frames long */
calc_action_range(adt->action, &astart, &aend, 1);
if (aend > astart + 2.0f) {
- NlaStrip *strip = add_nlastrip_to_stack(adt, adt->action);
+ NlaStrip *strip = BKE_nlastack_add_strip(adt, adt->action);
/* clear reference to action now that we've pushed it onto the stack */
id_us_min(&adt->action->id);
@@ -287,6 +287,29 @@ static void animrecord_check_state(Scene *scene, ID *id, wmTimer *animtimer)
strip->extendmode = NLASTRIP_EXTEND_NOTHING;
strip->flag &= ~(NLASTRIP_FLAG_AUTO_BLENDS | NLASTRIP_FLAG_SELECT | NLASTRIP_FLAG_ACTIVE);
+ /* copy current "action blending" settings from adt to the strip,
+ * as it was keyframed with these settings, so omitting them will
+ * change the effect [T54766]
+ */
+ if (is_first == false) {
+ strip->blendmode = adt->act_blendmode;
+ strip->influence = adt->act_influence;
+
+ if (adt->act_influence < 1.0f) {
+ /* enable "user-controlled" influence (which will insert a default keyframe)
+ * so that the influence doesn't get lost on the new update
+ *
+ * NOTE: An alternative way would have been to instead hack the influence
+ * to not get always get reset to full strength if NLASTRIP_FLAG_USR_INFLUENCE
+ * is disabled but auto-blending isn't being used. However, that approach
+ * is a bit hacky/hard to discover, and may cause backwards compatability issues,
+ * so it's better to just do it this way.
+ */
+ strip->flag |= NLASTRIP_FLAG_USR_INFLUENCE;
+ BKE_nlastrip_validate_fcurves(strip);
+ }
+ }
+
/* also, adjust the AnimData's action extend mode to be on
* 'nothing' so that previous result still play
*/
@@ -848,7 +871,7 @@ static void recalcData_objects(TransInfo *t)
mul_qt_v3(qrot, up_axis);
/* roll has a tendency to flip in certain orientations - [#34283], [#33974] */
- roll = ED_rollBoneToVector(ebo, up_axis, false);
+ roll = ED_armature_ebone_roll_to_vector(ebo, up_axis, false);
ebo->roll = angle_compat_rad(roll, td->ival);
}
}
@@ -857,7 +880,7 @@ static void recalcData_objects(TransInfo *t)
if (arm->flag & ARM_MIRROR_EDIT) {
if (t->state != TRANS_CANCEL)
- transform_armature_mirror_update(t->obedit);
+ ED_armature_edit_transform_mirror_update(t->obedit);
else
restoreBones(t);
}
@@ -971,7 +994,7 @@ static void recalcData_sequencer(TransInfo *t)
/* force recalculation of triangles during transformation */
static void recalcData_gpencil_strokes(TransInfo *t)
- {
+{
TransData *td = t->data;
for (int i = 0; i < t->total; i++, td++) {
bGPDstroke *gps = td->extra;
@@ -1208,7 +1231,7 @@ void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve
if (prop_id && (prop = RNA_struct_find_property(op->ptr, prop_id)) &&
RNA_property_is_set(op->ptr, prop))
{
- BKE_BIT_TEST_SET(t->flag, RNA_property_boolean_get(op->ptr, prop), T_ALT_TRANSFORM);
+ SET_FLAG_FROM_TEST(t->flag, RNA_property_boolean_get(op->ptr, prop), T_ALT_TRANSFORM);
}
}
@@ -1331,7 +1354,7 @@ void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve
t->current_orientation = V3D_MANIP_GLOBAL;
}
}
-
+
if (op && ((prop = RNA_struct_find_property(op->ptr, "release_confirm")) &&
RNA_property_is_set(op->ptr, prop)))
{
@@ -1435,6 +1458,13 @@ void initTransInfo(bContext *C, TransInfo *t, wmOperator *op, const wmEvent *eve
#endif
setTransformViewAspect(t, t->aspect);
+
+ if (op && (prop = RNA_struct_find_property(op->ptr, "center_override")) && RNA_property_is_set(op->ptr, prop)) {
+ RNA_property_float_get_array(op->ptr, prop, t->center);
+ mul_v3_v3(t->center, t->aspect);
+ t->flag |= T_OVERRIDE_CENTER;
+ }
+
setTransformViewMatrices(t);
initNumInput(&t->num);
}
@@ -1835,7 +1865,9 @@ static void calculateCenter_FromAround(TransInfo *t, int around, float r_center[
void calculateCenter(TransInfo *t)
{
- calculateCenter_FromAround(t, t->around, t->center);
+ if ((t->flag & T_OVERRIDE_CENTER) == 0) {
+ calculateCenter_FromAround(t, t->around, t->center);
+ }
calculateCenterGlobal(t, t->center, t->center_global);
/* avoid calculating again */
@@ -1849,7 +1881,7 @@ void calculateCenter(TransInfo *t)
calculateCenter2D(t);
/* for panning from cameraview */
- if (t->flag & T_OBJECT) {
+ if ((t->flag & T_OBJECT) && (t->flag & T_OVERRIDE_CENTER) == 0) {
if (t->spacetype == SPACE_VIEW3D && t->ar && t->ar->regiontype == RGN_TYPE_WINDOW) {
if (t->flag & T_CAMERA) {
@@ -1876,14 +1908,6 @@ void calculateCenter(TransInfo *t)
if (t->spacetype == SPACE_VIEW3D) {
/* ED_view3d_calc_zfac() defines a factor for perspective depth correction, used in ED_view3d_win_to_delta() */
- float vec[3];
- if (t->flag & (T_EDIT | T_POSE)) {
- Object *ob = t->obedit ? t->obedit : t->poseobj;
- mul_v3_m4v3(vec, ob->obmat, t->center);
- }
- else {
- copy_v3_v3(vec, t->center);
- }
/* zfac is only used convertViewVec only in cases operator was invoked in RGN_TYPE_WINDOW
* and never used in other cases.
@@ -1892,7 +1916,7 @@ void calculateCenter(TransInfo *t)
* for a region different from RGN_TYPE_WINDOW.
*/
if (t->ar->regiontype == RGN_TYPE_WINDOW) {
- t->zfac = ED_view3d_calc_zfac(t->ar->regiondata, vec, NULL);
+ t->zfac = ED_view3d_calc_zfac(t->ar->regiondata, t->center_global, NULL);
}
else {
t->zfac = 0.0f;
diff --git a/source/blender/editors/transform/transform_input.c b/source/blender/editors/transform/transform_input.c
index 42cc918ec8c..5f2e5a99090 100644
--- a/source/blender/editors/transform/transform_input.c
+++ b/source/blender/editors/transform/transform_input.c
@@ -86,12 +86,11 @@ static void InputTrackBall(TransInfo *UNUSED(t), MouseInput *mi, const double mv
output[1] *= mi->factor;
}
-static void InputHorizontalRatio(TransInfo *t, MouseInput *UNUSED(mi), const double mval[2], float output[3])
+static void InputHorizontalRatio(TransInfo *t, MouseInput *mi, const double mval[2], float output[3])
{
const int winx = t->ar ? t->ar->winx : 1;
- const double pad = winx / 10;
- output[0] = (mval[0] - pad) / (winx - 2 * pad);
+ output[0] = ((mval[0] - mi->imval[0]) / winx) * 2.0f;
}
static void InputHorizontalAbsolute(TransInfo *t, MouseInput *mi, const double mval[2], float output[3])
@@ -104,12 +103,11 @@ static void InputHorizontalAbsolute(TransInfo *t, MouseInput *mi, const double m
output[0] = dot_v3v3(t->viewinv[0], vec) * 2.0f;
}
-static void InputVerticalRatio(TransInfo *t, MouseInput *UNUSED(mi), const double mval[2], float output[3])
+static void InputVerticalRatio(TransInfo *t, MouseInput *mi, const double mval[2], float output[3])
{
const int winy = t->ar ? t->ar->winy : 1;
- const double pad = winy / 10;
- output[0] = (mval[1] - pad) / (winy - 2 * pad);
+ output[0] = ((mval[1] - mi->imval[1]) / winy) * 2.0f;
}
static void InputVerticalAbsolute(TransInfo *t, MouseInput *mi, const double mval[2], float output[3])
@@ -187,7 +185,7 @@ static void InputAngle(TransInfo *UNUSED(t), MouseInput *mi, const double mval[2
/* use doubles here, to make sure a "1.0" (no rotation) doesn't become 9.999999e-01, which gives 0.02 for acos */
double deler = (((dx1 * dx1 + dy1 * dy1) +
(dx2 * dx2 + dy2 * dy2) -
- (dx3 * dx3 + dy3 * dy3)) / (2.0 * ((A * B) ? (A * B) : 1.0)));
+ (dx3 * dx3 + dy3 * dy3)) / (2.0 * (((A * B) != 0.0) ? (A * B) : 1.0)));
/* ((A * B) ? (A * B) : 1.0) this takes care of potential divide by zero errors */
float dphi;
@@ -314,7 +312,6 @@ void initMouseInputMode(TransInfo *t, MouseInput *mi, MouseInputMode mode)
t->helpline = HLP_TRACKBALL;
break;
case INPUT_HORIZONTAL_RATIO:
- mi->factor = (float)(mi->center[0] - mi->imval[0]);
mi->apply = InputHorizontalRatio;
t->helpline = HLP_HARROW;
break;
diff --git a/source/blender/editors/transform/transform_manipulator.c b/source/blender/editors/transform/transform_manipulator.c
index e141724f2df..193a29928ef 100644
--- a/source/blender/editors/transform/transform_manipulator.c
+++ b/source/blender/editors/transform/transform_manipulator.c
@@ -107,15 +107,16 @@
#define TW_AXIS_DOT_MIN 0.02f
#define TW_AXIS_DOT_MAX 0.1f
+struct TransformBounds {
+ float center[3]; /* Center for transform widget. */
+ float min[3], max[3]; /* Boundbox of selection for transform widget. */
+};
+
/* transform widget center calc helper for below */
-static void calc_tw_center(Scene *scene, const float co[3])
+static void calc_tw_center(struct TransformBounds *tbounds, const float co[3])
{
- float *twcent = scene->twcent;
- float *min = scene->twmin;
- float *max = scene->twmax;
-
- minmax_v3v3_v3(min, max, co);
- add_v3_v3(twcent, co);
+ minmax_v3v3_v3(tbounds->min, tbounds->max, co);
+ add_v3_v3(tbounds->center, co);
}
static void protectflag_to_drawflags(short protectflag, short *drawflags)
@@ -143,21 +144,17 @@ static void protectflag_to_drawflags(short protectflag, short *drawflags)
}
/* for pose mode */
-static void stats_pose(Scene *scene, RegionView3D *rv3d, bPoseChannel *pchan)
+static void protectflag_to_drawflags_pchan(RegionView3D *rv3d, const bPoseChannel *pchan)
{
- Bone *bone = pchan->bone;
-
- if (bone) {
- calc_tw_center(scene, pchan->pose_head);
- protectflag_to_drawflags(pchan->protectflag, &rv3d->twdrawflag);
- }
+ protectflag_to_drawflags(pchan->protectflag, &rv3d->twdrawflag);
}
/* for editmode*/
-static void stats_editbone(RegionView3D *rv3d, EditBone *ebo)
+static void protectflag_to_drawflags_ebone(RegionView3D *rv3d, const EditBone *ebo)
{
- if (ebo->flag & BONE_EDITMODE_LOCKED)
+ if (ebo->flag & BONE_EDITMODE_LOCKED) {
protectflag_to_drawflags(OB_LOCK_LOC | OB_LOCK_ROT | OB_LOCK_SCALE, &rv3d->twdrawflag);
+ }
}
/* could move into BLI_math however this is only useful for display/editing purposes */
@@ -192,73 +189,71 @@ static void axis_angle_to_gimbal_axis(float gmat[3][3], const float axis[3], con
}
-static int test_rotmode_euler(short rotmode)
+static bool test_rotmode_euler(short rotmode)
{
return (ELEM(rotmode, ROT_MODE_AXISANGLE, ROT_MODE_QUAT)) ? 0 : 1;
}
bool gimbal_axis(Object *ob, float gmat[3][3])
{
- if (ob) {
- if (ob->mode & OB_MODE_POSE) {
- bPoseChannel *pchan = BKE_pose_channel_active(ob);
-
- if (pchan) {
- float mat[3][3], tmat[3][3], obmat[3][3];
- if (test_rotmode_euler(pchan->rotmode)) {
- eulO_to_gimbal_axis(mat, pchan->eul, pchan->rotmode);
- }
- else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
- axis_angle_to_gimbal_axis(mat, pchan->rotAxis, pchan->rotAngle);
- }
- else { /* quat */
- return 0;
- }
-
-
- /* apply bone transformation */
- mul_m3_m3m3(tmat, pchan->bone->bone_mat, mat);
-
- if (pchan->parent) {
- float parent_mat[3][3];
+ if (ob->mode & OB_MODE_POSE) {
+ bPoseChannel *pchan = BKE_pose_channel_active(ob);
- copy_m3_m4(parent_mat, pchan->parent->pose_mat);
- mul_m3_m3m3(mat, parent_mat, tmat);
-
- /* needed if object transformation isn't identity */
- copy_m3_m4(obmat, ob->obmat);
- mul_m3_m3m3(gmat, obmat, mat);
- }
- else {
- /* needed if object transformation isn't identity */
- copy_m3_m4(obmat, ob->obmat);
- mul_m3_m3m3(gmat, obmat, tmat);
- }
-
- normalize_m3(gmat);
- return 1;
+ if (pchan) {
+ float mat[3][3], tmat[3][3], obmat[3][3];
+ if (test_rotmode_euler(pchan->rotmode)) {
+ eulO_to_gimbal_axis(mat, pchan->eul, pchan->rotmode);
}
- }
- else {
- if (test_rotmode_euler(ob->rotmode)) {
- eulO_to_gimbal_axis(gmat, ob->rot, ob->rotmode);
- }
- else if (ob->rotmode == ROT_MODE_AXISANGLE) {
- axis_angle_to_gimbal_axis(gmat, ob->rotAxis, ob->rotAngle);
+ else if (pchan->rotmode == ROT_MODE_AXISANGLE) {
+ axis_angle_to_gimbal_axis(mat, pchan->rotAxis, pchan->rotAngle);
}
else { /* quat */
return 0;
}
- if (ob->parent) {
+
+ /* apply bone transformation */
+ mul_m3_m3m3(tmat, pchan->bone->bone_mat, mat);
+
+ if (pchan->parent) {
float parent_mat[3][3];
- copy_m3_m4(parent_mat, ob->parent->obmat);
- normalize_m3(parent_mat);
- mul_m3_m3m3(gmat, parent_mat, gmat);
+
+ copy_m3_m4(parent_mat, pchan->parent->pose_mat);
+ mul_m3_m3m3(mat, parent_mat, tmat);
+
+ /* needed if object transformation isn't identity */
+ copy_m3_m4(obmat, ob->obmat);
+ mul_m3_m3m3(gmat, obmat, mat);
+ }
+ else {
+ /* needed if object transformation isn't identity */
+ copy_m3_m4(obmat, ob->obmat);
+ mul_m3_m3m3(gmat, obmat, tmat);
}
+
+ normalize_m3(gmat);
return 1;
}
}
+ else {
+ if (test_rotmode_euler(ob->rotmode)) {
+ eulO_to_gimbal_axis(gmat, ob->rot, ob->rotmode);
+ }
+ else if (ob->rotmode == ROT_MODE_AXISANGLE) {
+ axis_angle_to_gimbal_axis(gmat, ob->rotAxis, ob->rotAngle);
+ }
+ else { /* quat */
+ return 0;
+ }
+
+ if (ob->parent) {
+ float parent_mat[3][3];
+ copy_m3_m4(parent_mat, ob->parent->obmat);
+ normalize_m3(parent_mat);
+ mul_m3_m3m3(gmat, parent_mat, gmat);
+ }
+ return 1;
+ }
return 0;
}
@@ -266,7 +261,7 @@ bool gimbal_axis(Object *ob, float gmat[3][3])
/* centroid, boundbox, of selection */
/* returns total items selected */
-static int calc_manipulator_stats(const bContext *C)
+static int calc_manipulator_stats(const bContext *C, struct TransformBounds *tbounds)
{
ScrArea *sa = CTX_wm_area(C);
ARegion *ar = CTX_wm_region(C);
@@ -286,9 +281,9 @@ static int calc_manipulator_stats(const bContext *C)
rv3d->twdrawflag = 0xFFFF;
/* transform widget centroid/center */
- INIT_MINMAX(scene->twmin, scene->twmax);
- zero_v3(scene->twcent);
-
+ INIT_MINMAX(tbounds->min, tbounds->max);
+ zero_v3(tbounds->center);
+
if (is_gp_edit) {
float diff_mat[4][4];
float fpt[3];
@@ -317,12 +312,12 @@ static int calc_manipulator_stats(const bContext *C)
for (i = 0, pt = gps->points; i < gps->totpoints; i++, pt++) {
if (pt->flag & GP_SPOINT_SELECT) {
if (gpl->parent == NULL) {
- calc_tw_center(scene, &pt->x);
+ calc_tw_center(tbounds, &pt->x);
totsel++;
}
else {
mul_v3_m4v3(fpt, diff_mat, &pt->x);
- calc_tw_center(scene, fpt);
+ calc_tw_center(tbounds, fpt);
totsel++;
}
}
@@ -335,7 +330,7 @@ static int calc_manipulator_stats(const bContext *C)
/* selection center */
if (totsel) {
- mul_v3_fl(scene->twcent, 1.0f / (float)totsel); /* centroid! */
+ mul_v3_fl(tbounds->center, 1.0f / (float)totsel);
}
}
else if (obedit) {
@@ -350,7 +345,7 @@ static int calc_manipulator_stats(const bContext *C)
/* USE LAST SELECTE WITH ACTIVE */
if ((v3d->around == V3D_AROUND_ACTIVE) && BM_select_history_active_get(em->bm, &ese)) {
BM_editselection_center(&ese, vec);
- calc_tw_center(scene, vec);
+ calc_tw_center(tbounds, vec);
totsel = 1;
}
else {
@@ -363,7 +358,7 @@ static int calc_manipulator_stats(const bContext *C)
if (!BM_elem_flag_test(eve, BM_ELEM_HIDDEN)) {
if (BM_elem_flag_test(eve, BM_ELEM_SELECT)) {
totsel++;
- calc_tw_center(scene, eve->co);
+ calc_tw_center(tbounds, eve->co);
}
}
}
@@ -376,22 +371,22 @@ static int calc_manipulator_stats(const bContext *C)
if ((v3d->around == V3D_AROUND_ACTIVE) && (ebo = arm->act_edbone)) {
/* doesn't check selection or visibility intentionally */
if (ebo->flag & BONE_TIPSEL) {
- calc_tw_center(scene, ebo->tail);
+ calc_tw_center(tbounds, ebo->tail);
totsel++;
}
if ((ebo->flag & BONE_ROOTSEL) ||
((ebo->flag & BONE_TIPSEL) == false)) /* ensure we get at least one point */
{
- calc_tw_center(scene, ebo->head);
+ calc_tw_center(tbounds, ebo->head);
totsel++;
}
- stats_editbone(rv3d, ebo);
+ protectflag_to_drawflags_ebone(rv3d, ebo);
}
else {
for (ebo = arm->edbo->first; ebo; ebo = ebo->next) {
if (EBONE_VISIBLE(arm, ebo)) {
if (ebo->flag & BONE_TIPSEL) {
- calc_tw_center(scene, ebo->tail);
+ calc_tw_center(tbounds, ebo->tail);
totsel++;
}
if ((ebo->flag & BONE_ROOTSEL) &&
@@ -401,11 +396,11 @@ static int calc_manipulator_stats(const bContext *C)
(ebo->parent->flag & BONE_TIPSEL) &&
EBONE_VISIBLE(arm, ebo->parent)) == 0)
{
- calc_tw_center(scene, ebo->head);
+ calc_tw_center(tbounds, ebo->head);
totsel++;
}
if (ebo->flag & BONE_SELECTED) {
- stats_editbone(rv3d, ebo);
+ protectflag_to_drawflags_ebone(rv3d, ebo);
}
}
}
@@ -416,7 +411,7 @@ static int calc_manipulator_stats(const bContext *C)
float center[3];
if (v3d->around == V3D_AROUND_ACTIVE && ED_curve_active_center(cu, center)) {
- calc_tw_center(scene, center);
+ calc_tw_center(tbounds, center);
totsel++;
}
else {
@@ -437,21 +432,25 @@ static int calc_manipulator_stats(const bContext *C)
*/
if (cu->drawflag & CU_HIDE_HANDLES) {
if (bezt->f2 & SELECT) {
- calc_tw_center(scene, bezt->vec[1]);
+ calc_tw_center(tbounds, bezt->vec[1]);
totsel++;
}
}
else if (bezt->f2 & SELECT) {
- calc_tw_center(scene, bezt->vec[1]);
+ calc_tw_center(tbounds, bezt->vec[1]);
totsel++;
}
else {
if (bezt->f1 & SELECT) {
- calc_tw_center(scene, bezt->vec[(v3d->around == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 0]);
+ calc_tw_center(
+ tbounds,
+ bezt->vec[(v3d->around == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 0]);
totsel++;
}
if (bezt->f3 & SELECT) {
- calc_tw_center(scene, bezt->vec[(v3d->around == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 2]);
+ calc_tw_center(
+ tbounds,
+ bezt->vec[(v3d->around == V3D_AROUND_LOCAL_ORIGINS) ? 1 : 2]);
totsel++;
}
}
@@ -463,7 +462,7 @@ static int calc_manipulator_stats(const bContext *C)
a = nu->pntsu * nu->pntsv;
while (a--) {
if (bp->f1 & SELECT) {
- calc_tw_center(scene, bp->vec);
+ calc_tw_center(tbounds, bp->vec);
totsel++;
}
bp++;
@@ -478,13 +477,13 @@ static int calc_manipulator_stats(const bContext *C)
MetaElem *ml;
if ((v3d->around == V3D_AROUND_ACTIVE) && (ml = mb->lastelem)) {
- calc_tw_center(scene, &ml->x);
+ calc_tw_center(tbounds, &ml->x);
totsel++;
}
else {
for (ml = mb->editelems->first; ml; ml = ml->next) {
if (ml->flag & SELECT) {
- calc_tw_center(scene, &ml->x);
+ calc_tw_center(tbounds, &ml->x);
totsel++;
}
}
@@ -495,7 +494,7 @@ static int calc_manipulator_stats(const bContext *C)
BPoint *bp;
if ((v3d->around == V3D_AROUND_ACTIVE) && (bp = BKE_lattice_active_point_get(lt))) {
- calc_tw_center(scene, bp->vec);
+ calc_tw_center(tbounds, bp->vec);
totsel++;
}
else {
@@ -503,7 +502,7 @@ static int calc_manipulator_stats(const bContext *C)
a = lt->pntsu * lt->pntsv * lt->pntsw;
while (a--) {
if (bp->f1 & SELECT) {
- calc_tw_center(scene, bp->vec);
+ calc_tw_center(tbounds, bp->vec);
totsel++;
}
bp++;
@@ -513,10 +512,10 @@ static int calc_manipulator_stats(const bContext *C)
/* selection center */
if (totsel) {
- mul_v3_fl(scene->twcent, 1.0f / (float)totsel); // centroid!
- mul_m4_v3(obedit->obmat, scene->twcent);
- mul_m4_v3(obedit->obmat, scene->twmin);
- mul_m4_v3(obedit->obmat, scene->twmax);
+ mul_v3_fl(tbounds->center, 1.0f / (float)totsel);
+ mul_m4_v3(obedit->obmat, tbounds->center);
+ mul_m4_v3(obedit->obmat, tbounds->min);
+ mul_m4_v3(obedit->obmat, tbounds->max);
}
}
else if (ob && (ob->mode & OB_MODE_POSE)) {
@@ -530,7 +529,8 @@ static int calc_manipulator_stats(const bContext *C)
/* doesn't check selection or visibility intentionally */
Bone *bone = pchan->bone;
if (bone) {
- stats_pose(scene, rv3d, pchan);
+ calc_tw_center(tbounds, pchan->pose_head);
+ protectflag_to_drawflags_pchan(rv3d, pchan);
totsel = 1;
ok = true;
}
@@ -543,7 +543,8 @@ static int calc_manipulator_stats(const bContext *C)
for (pchan = ob->pose->chanbase.first; pchan; pchan = pchan->next) {
Bone *bone = pchan->bone;
if (bone && (bone->flag & BONE_TRANSFORM)) {
- stats_pose(scene, rv3d, pchan);
+ calc_tw_center(tbounds, pchan->pose_head);
+ protectflag_to_drawflags_pchan(rv3d, pchan);
}
}
ok = true;
@@ -551,10 +552,10 @@ static int calc_manipulator_stats(const bContext *C)
}
if (ok) {
- mul_v3_fl(scene->twcent, 1.0f / (float)totsel); // centroid!
- mul_m4_v3(ob->obmat, scene->twcent);
- mul_m4_v3(ob->obmat, scene->twmin);
- mul_m4_v3(ob->obmat, scene->twmax);
+ mul_v3_fl(tbounds->center, 1.0f / (float)totsel);
+ mul_m4_v3(ob->obmat, tbounds->center);
+ mul_m4_v3(ob->obmat, tbounds->min);
+ mul_m4_v3(ob->obmat, tbounds->max);
}
}
else if (ob && (ob->mode & OB_MODE_ALL_PAINT)) {
@@ -573,7 +574,7 @@ static int calc_manipulator_stats(const bContext *C)
for (k = 0, ek = point->keys; k < point->totkey; k++, ek++) {
if (ek->flag & PEK_SELECT) {
- calc_tw_center(scene, (ek->flag & PEK_USE_WCO) ? ek->world_co : ek->co);
+ calc_tw_center(tbounds, (ek->flag & PEK_USE_WCO) ? ek->world_co : ek->co);
totsel++;
}
}
@@ -581,7 +582,7 @@ static int calc_manipulator_stats(const bContext *C)
/* selection center */
if (totsel)
- mul_v3_fl(scene->twcent, 1.0f / (float)totsel); // centroid!
+ mul_v3_fl(tbounds->center, 1.0f / (float)totsel);
}
}
else {
@@ -594,7 +595,7 @@ static int calc_manipulator_stats(const bContext *C)
if (TESTBASELIB(v3d, base)) {
if (ob == NULL)
ob = base->object;
- calc_tw_center(scene, base->object->obmat[3]);
+ calc_tw_center(tbounds, base->object->obmat[3]);
protectflag_to_drawflags(base->object->protectflag, &rv3d->twdrawflag);
totsel++;
}
@@ -602,7 +603,7 @@ static int calc_manipulator_stats(const bContext *C)
/* selection center */
if (totsel) {
- mul_v3_fl(scene->twcent, 1.0f / (float)totsel); // centroid!
+ mul_v3_fl(tbounds->center, 1.0f / (float)totsel);
}
}
@@ -623,7 +624,7 @@ static int calc_manipulator_stats(const bContext *C)
break;
}
/* if not gimbal, fall through to normal */
- /* fall-through */
+ ATTR_FALLTHROUGH;
}
case V3D_MANIP_NORMAL:
{
@@ -634,7 +635,7 @@ static int calc_manipulator_stats(const bContext *C)
break;
}
/* no break we define 'normal' as 'local' in Object mode */
- /* fall-through */
+ ATTR_FALLTHROUGH;
}
case V3D_MANIP_LOCAL:
{
@@ -713,12 +714,13 @@ static float screen_aligned(RegionView3D *rv3d, float mat[4][4])
}
-/* radring = radius of doughnut rings
- * radhole = radius hole
- * start = starting segment (based on nrings)
- * end = end segment
- * nsides = amount of points in ring
- * nrigns = amount of rings
+/**
+ * \param radring: Radius of doughnut rings.
+ * \param radhole: Radius hole.
+ * \param start: Starting segment (based on \a nrings).
+ * \param end: End segment.
+ * \param nsides: Number of points in ring.
+ * \param nrings: Number of rings.
*/
static void partial_doughnut(float radring, float radhole, int start, int end, int nsides, int nrings)
{
@@ -1647,9 +1649,10 @@ void BIF_draw_manipulator(const bContext *C)
if ((v3d->twtype & (V3D_MANIP_TRANSLATE | V3D_MANIP_ROTATE | V3D_MANIP_SCALE)) == 0) return;
{
+ struct TransformBounds tbounds;
v3d->twflag &= ~V3D_DRAW_MANIPULATOR;
- totsel = calc_manipulator_stats(C);
+ totsel = calc_manipulator_stats(C, &tbounds);
if (totsel == 0) return;
v3d->twflag |= V3D_DRAW_MANIPULATOR;
@@ -1669,13 +1672,13 @@ void BIF_draw_manipulator(const bContext *C)
copy_v3_v3(rv3d->twmat[3], ob->obmat[3]);
}
else {
- mid_v3_v3v3(rv3d->twmat[3], scene->twmin, scene->twmax);
+ mid_v3_v3v3(rv3d->twmat[3], tbounds.min, tbounds.max);
}
break;
}
case V3D_AROUND_LOCAL_ORIGINS:
case V3D_AROUND_CENTER_MEAN:
- copy_v3_v3(rv3d->twmat[3], scene->twcent);
+ copy_v3_v3(rv3d->twmat[3], tbounds.center);
break;
case V3D_AROUND_CURSOR:
copy_v3_v3(rv3d->twmat[3], ED_view3d_cursor3d_get(scene, v3d));
@@ -1720,19 +1723,16 @@ void BIF_draw_manipulator(const bContext *C)
}
}
-static int manipulator_selectbuf(ScrArea *sa, ARegion *ar, const int mval[2], float hotspot)
+static int manipulator_selectbuf(Scene *scene, ScrArea *sa, ARegion *ar, const int mval[2], float hotspot)
{
View3D *v3d = sa->spacedata.first;
RegionView3D *rv3d = ar->regiondata;
- rctf rect, selrect;
+ rcti rect;
GLuint buffer[64]; // max 4 items per select, so large enuf
short hits;
const bool is_picksel = true;
const bool do_passes = GPU_select_query_check_active();
- /* XXX check a bit later on this... (ton) */
- extern void view3d_winmatrix_set(ARegion *ar, View3D *v3d, rctf *rect);
-
/* when looking through a selected camera, the manipulator can be at the
* exact same position as the view, skip so we don't break selection */
if (fabsf(mat4_to_scale(rv3d->twmat)) < 1e-7f)
@@ -1743,15 +1743,12 @@ static int manipulator_selectbuf(ScrArea *sa, ARegion *ar, const int mval[2], fl
rect.ymin = mval[1] - hotspot;
rect.ymax = mval[1] + hotspot;
- selrect = rect;
-
- view3d_winmatrix_set(ar, v3d, &rect);
- mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
+ ED_view3d_draw_setup_view(NULL, scene, ar, v3d, NULL, NULL, &rect);
if (do_passes)
- GPU_select_begin(buffer, 64, &selrect, GPU_SELECT_NEAREST_FIRST_PASS, 0);
+ GPU_select_begin(buffer, 64, &rect, GPU_SELECT_NEAREST_FIRST_PASS, 0);
else
- GPU_select_begin(buffer, 64, &selrect, GPU_SELECT_ALL, 0);
+ GPU_select_begin(buffer, 64, &rect, GPU_SELECT_ALL, 0);
/* do the drawing */
if (v3d->twtype & V3D_MANIP_ROTATE) {
@@ -1765,8 +1762,8 @@ static int manipulator_selectbuf(ScrArea *sa, ARegion *ar, const int mval[2], fl
hits = GPU_select_end();
- if (do_passes) {
- GPU_select_begin(buffer, 64, &selrect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
+ if (do_passes && (hits > 0)) {
+ GPU_select_begin(buffer, 64, &rect, GPU_SELECT_NEAREST_SECOND_PASS, hits);
/* do the drawing */
if (v3d->twtype & V3D_MANIP_ROTATE) {
@@ -1781,8 +1778,7 @@ static int manipulator_selectbuf(ScrArea *sa, ARegion *ar, const int mval[2], fl
GPU_select_end();
}
- view3d_winmatrix_set(ar, v3d, NULL);
- mul_m4_m4m4(rv3d->persmat, rv3d->winmat, rv3d->viewmat);
+ ED_view3d_draw_setup_view(NULL, scene, ar, v3d, NULL, NULL, NULL);
if (hits == 1) return buffer[3];
else if (hits > 1) {
@@ -1826,10 +1822,28 @@ static int manipulator_selectbuf(ScrArea *sa, ARegion *ar, const int mval[2], fl
return 0;
}
+static const char *manipulator_get_operator_name(int man_val)
+{
+ if (man_val & MAN_TRANS_C) {
+ return "TRANSFORM_OT_translate";
+ }
+ else if (man_val == MAN_ROT_T) {
+ return "TRANSFORM_OT_trackball";
+ }
+ else if (man_val & MAN_ROT_C) {
+ return "TRANSFORM_OT_rotate";
+ }
+ else if (man_val & MAN_SCALE_C) {
+ return "TRANSFORM_OT_resize";
+ }
+
+ return NULL;
+}
/* return 0; nothing happened */
int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op)
{
+ Scene *scene = CTX_data_scene(C);
ScrArea *sa = CTX_wm_area(C);
View3D *v3d = sa->spacedata.first;
ARegion *ar = CTX_wm_region(C);
@@ -1844,13 +1858,26 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op)
RNA_enum_set(op->ptr, "constraint_orientation", v3d->twmode);
// find the hotspots first test narrow hotspot
- val = manipulator_selectbuf(sa, ar, event->mval, 0.5f * (float)U.tw_hotspot);
+ val = manipulator_selectbuf(scene, sa, ar, event->mval, 0.5f * (float)U.tw_hotspot);
if (val) {
+ wmOperatorType *ot;
+ PointerRNA props_ptr;
+ PropertyRNA *prop;
+ const char *opname;
// drawflags still global, for drawing call above
- drawflags = manipulator_selectbuf(sa, ar, event->mval, 0.2f * (float)U.tw_hotspot);
+ drawflags = manipulator_selectbuf(scene, sa, ar, event->mval, 0.2f * (float)U.tw_hotspot);
if (drawflags == 0) drawflags = val;
+ /* Planar constraint doesn't make sense for rotation, give other keymaps a chance */
+ if ((drawflags & MAN_ROT_C) && use_planar) {
+ return 0;
+ }
+
+ opname = manipulator_get_operator_name(drawflags);
+ ot = WM_operatortype_find(opname, true);
+ WM_operator_properties_create_ptr(&props_ptr, ot);
+
if (drawflags & MAN_TRANS_C) {
switch (drawflags) {
case MAN_TRANS_C:
@@ -1880,8 +1907,7 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op)
constraint_axis[2] = 1;
break;
}
- RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
- WM_operator_name_call(C, "TRANSFORM_OT_translate", WM_OP_INVOKE_DEFAULT, op->ptr);
+ RNA_boolean_set_array(&props_ptr, "constraint_axis", constraint_axis);
}
else if (drawflags & MAN_SCALE_C) {
switch (drawflags) {
@@ -1910,22 +1936,10 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op)
constraint_axis[2] = 1;
break;
}
- RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
- WM_operator_name_call(C, "TRANSFORM_OT_resize", WM_OP_INVOKE_DEFAULT, op->ptr);
+ RNA_boolean_set_array(&props_ptr, "constraint_axis", constraint_axis);
}
- else if (drawflags == MAN_ROT_T) { /* trackball need special case, init is different */
- /* Do not pass op->ptr!!! trackball has no "constraint" properties!
- * See [#34621], it's a miracle it did not cause more problems!!! */
- /* However, we need to copy the "release_confirm" property, but only if defined, see T41112. */
- PointerRNA props_ptr;
- PropertyRNA *prop;
- wmOperatorType *ot = WM_operatortype_find("TRANSFORM_OT_trackball", true);
- WM_operator_properties_create_ptr(&props_ptr, ot);
- if ((prop = RNA_struct_find_property(op->ptr, "release_confirm")) && RNA_property_is_set(op->ptr, prop)) {
- RNA_property_boolean_set(&props_ptr, prop, RNA_property_boolean_get(op->ptr, prop));
- }
- WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr);
- WM_operator_properties_free(&props_ptr);
+ else if (drawflags == MAN_ROT_T) {
+ /* pass */
}
else if (drawflags & MAN_ROT_C) {
switch (drawflags) {
@@ -1939,9 +1953,25 @@ int BIF_do_manipulator(bContext *C, const struct wmEvent *event, wmOperator *op)
constraint_axis[2] = 1;
break;
}
- RNA_boolean_set_array(op->ptr, "constraint_axis", constraint_axis);
- WM_operator_name_call(C, "TRANSFORM_OT_rotate", WM_OP_INVOKE_DEFAULT, op->ptr);
+ RNA_boolean_set_array(&props_ptr, "constraint_axis", constraint_axis);
+ }
+
+ /* pass operator properties on to transform operators */
+ prop = RNA_struct_find_property(op->ptr, "use_accurate");
+ if (RNA_property_is_set(op->ptr, prop)) {
+ RNA_property_boolean_set(&props_ptr, prop, RNA_property_boolean_get(op->ptr, prop));
}
+ prop = RNA_struct_find_property(op->ptr, "release_confirm");
+ if (RNA_property_is_set(op->ptr, prop)) {
+ RNA_property_boolean_set(&props_ptr, prop, RNA_property_boolean_get(op->ptr, prop));
+ }
+ prop = RNA_struct_find_property(op->ptr, "constraint_orientation");
+ if (RNA_property_is_set(op->ptr, prop)) {
+ RNA_property_enum_set(&props_ptr, prop, RNA_property_enum_get(op->ptr, prop));
+ }
+
+ WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr);
+ WM_operator_properties_free(&props_ptr);
}
/* after transform, restore drawflags */
drawflags = 0xFFFF;
diff --git a/source/blender/editors/transform/transform_ops.c b/source/blender/editors/transform/transform_ops.c
index cbe58ddf586..46bd83b5d35 100644
--- a/source/blender/editors/transform/transform_ops.c
+++ b/source/blender/editors/transform/transform_ops.c
@@ -122,7 +122,7 @@ static TransformModeItem transform_modes[] =
{NULL, 0}
};
-EnumPropertyItem rna_enum_transform_mode_types[] =
+const EnumPropertyItem rna_enum_transform_mode_types[] =
{
{TFM_INIT, "INIT", 0, "Init", ""},
{TFM_DUMMY, "DUMMY", 0, "Dummy", ""},
@@ -565,10 +565,20 @@ void Transform_Properties(struct wmOperatorType *ot, int flags)
RNA_def_boolean(ot->srna, "correct_uv", 0, "Correct UVs", "Correct UV coordinates when transforming");
}
+ if (flags & P_CENTER) {
+ /* For manipulators that define their own center. */
+ prop = RNA_def_property(ot->srna, "center_override", PROP_FLOAT, PROP_XYZ);
+ RNA_def_property_array(prop, 3);
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+ RNA_def_property_ui_text(prop, "Center Override", "Force using this center value (when set)");
+ }
+
if ((flags & P_NO_DEFAULTS) == 0) {
- // Add confirm method all the time. At the end because it's not really that important and should be hidden only in log, not in keymap edit
- /*prop =*/ RNA_def_boolean(ot->srna, "release_confirm", 0, "Confirm on Release", "Always confirm operation when releasing button");
- //RNA_def_property_flag(prop, PROP_HIDDEN);
+ prop = RNA_def_boolean(ot->srna, "release_confirm", 0, "Confirm on Release", "Always confirm operation when releasing button");
+ RNA_def_property_flag(prop, PROP_HIDDEN);
+
+ prop = RNA_def_boolean(ot->srna, "use_accurate", 0, "Accurate", "Use accurate transformation");
+ RNA_def_property_flag(prop, PROP_HIDDEN);
}
}
@@ -609,7 +619,8 @@ static void TRANSFORM_OT_resize(struct wmOperatorType *ot)
RNA_def_float_vector(ot->srna, "value", 3, VecOne, -FLT_MAX, FLT_MAX, "Vector", "", -FLT_MAX, FLT_MAX);
- Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_OPTIONS | P_GPENCIL_EDIT);
+ Transform_Properties(
+ ot, P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_OPTIONS | P_GPENCIL_EDIT | P_CENTER);
}
static int skin_resize_poll(bContext *C)
@@ -660,7 +671,7 @@ static void TRANSFORM_OT_trackball(struct wmOperatorType *ot)
/* Maybe we could use float_vector_xyz here too? */
RNA_def_float_rotation(ot->srna, "value", 2, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -FLT_MAX, FLT_MAX);
- Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT);
+ Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT | P_CENTER);
}
static void TRANSFORM_OT_rotate(struct wmOperatorType *ot)
@@ -680,7 +691,8 @@ static void TRANSFORM_OT_rotate(struct wmOperatorType *ot)
RNA_def_float_rotation(ot->srna, "value", 0, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
- Transform_Properties(ot, P_AXIS | P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_GPENCIL_EDIT);
+ Transform_Properties(
+ ot, P_AXIS | P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_GEO_SNAP | P_GPENCIL_EDIT | P_CENTER);
}
static void TRANSFORM_OT_tilt(struct wmOperatorType *ot)
@@ -723,7 +735,7 @@ static void TRANSFORM_OT_bend(struct wmOperatorType *ot)
RNA_def_float_rotation(ot->srna, "value", 1, NULL, -FLT_MAX, FLT_MAX, "Angle", "", -M_PI * 2, M_PI * 2);
- Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT);
+ Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT | P_CENTER);
}
static void TRANSFORM_OT_shear(struct wmOperatorType *ot)
@@ -764,7 +776,7 @@ static void TRANSFORM_OT_push_pull(struct wmOperatorType *ot)
RNA_def_float(ot->srna, "value", 0, -FLT_MAX, FLT_MAX, "Distance", "", -FLT_MAX, FLT_MAX);
- Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP);
+ Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_CENTER);
}
static void TRANSFORM_OT_shrink_fatten(struct wmOperatorType *ot)
@@ -807,7 +819,7 @@ static void TRANSFORM_OT_tosphere(struct wmOperatorType *ot)
RNA_def_float_factor(ot->srna, "value", 0, 0, 1, "Factor", "", 0, 1);
- Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT);
+ Transform_Properties(ot, P_PROPORTIONAL | P_MIRROR | P_SNAP | P_GPENCIL_EDIT | P_CENTER);
}
static void TRANSFORM_OT_mirror(struct wmOperatorType *ot)
@@ -825,7 +837,7 @@ static void TRANSFORM_OT_mirror(struct wmOperatorType *ot)
ot->cancel = transform_cancel;
ot->poll = ED_operator_screenactive;
- Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_GPENCIL_EDIT);
+ Transform_Properties(ot, P_CONSTRAINT | P_PROPORTIONAL | P_GPENCIL_EDIT | P_CENTER);
}
static void TRANSFORM_OT_edge_slide(struct wmOperatorType *ot)
@@ -988,7 +1000,8 @@ static void TRANSFORM_OT_transform(struct wmOperatorType *ot)
RNA_def_float_vector(ot->srna, "value", 4, NULL, -FLT_MAX, FLT_MAX, "Values", "", -FLT_MAX, FLT_MAX);
- Transform_Properties(ot, P_AXIS | P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_ALIGN_SNAP | P_GPENCIL_EDIT);
+ Transform_Properties(
+ ot, P_AXIS | P_CONSTRAINT | P_PROPORTIONAL | P_MIRROR | P_ALIGN_SNAP | P_GPENCIL_EDIT | P_CENTER);
}
void transform_operatortypes(void)
diff --git a/source/blender/editors/transform/transform_orientations.c b/source/blender/editors/transform/transform_orientations.c
index 058af768885..18b5e952a3d 100644
--- a/source/blender/editors/transform/transform_orientations.c
+++ b/source/blender/editors/transform/transform_orientations.c
@@ -70,7 +70,7 @@ void BIF_clearTransformOrientation(bContext *C)
// Need to loop over all view3d
if (v3d && v3d->twmode >= V3D_MANIP_CUSTOM) {
- v3d->twmode = V3D_MANIP_GLOBAL; /* fallback to global */
+ v3d->twmode = V3D_MANIP_GLOBAL; /* fallback to global */
}
}
@@ -451,18 +451,18 @@ void initTransformOrientation(bContext *C, TransInfo *t)
case V3D_MANIP_GIMBAL:
unit_m3(t->spacemtx);
- if (gimbal_axis(ob, t->spacemtx)) {
+ if (ob && gimbal_axis(ob, t->spacemtx)) {
BLI_strncpy(t->spacename, IFACE_("gimbal"), sizeof(t->spacename));
break;
}
- /* fall-through */ /* no gimbal fallthrough to normal */
+ ATTR_FALLTHROUGH; /* no gimbal fallthrough to normal */
case V3D_MANIP_NORMAL:
if (obedit || (ob && ob->mode & OB_MODE_POSE)) {
BLI_strncpy(t->spacename, IFACE_("normal"), sizeof(t->spacename));
ED_getTransformOrientationMatrix(C, t->spacemtx, t->around);
break;
}
- /* fall-through */ /* we define 'normal' as 'local' in Object mode */
+ ATTR_FALLTHROUGH; /* we define 'normal' as 'local' in Object mode */
case V3D_MANIP_LOCAL:
BLI_strncpy(t->spacename, IFACE_("local"), sizeof(t->spacename));
@@ -743,10 +743,19 @@ int getTransformOrientation_ex(const bContext *C, float normal[3], float plane[3
SWAP(BMVert *, v_pair[0], v_pair[1]);
}
- add_v3_v3v3(normal, v_pair[0]->no, v_pair[1]->no);
- sub_v3_v3v3(plane, v_pair[0]->co, v_pair[1]->co);
- /* flip the plane normal so we point outwards */
- negate_v3(plane);
+ add_v3_v3v3(normal, v_pair[1]->no, v_pair[0]->no);
+ sub_v3_v3v3(plane, v_pair[1]->co, v_pair[0]->co);
+
+ if (normalize_v3(plane) != 0.0f) {
+ /* For edges it'd important the resulting matrix can rotate around the edge,
+ * project onto the plane so we can use a fallback value. */
+ project_plane_normalized_v3_v3v3(normal, normal, plane);
+ if (UNLIKELY(normalize_v3(normal) == 0.0f)) {
+ /* in the case the normal and plane are aligned,
+ * use a fallback normal which is orthogonal to the plane. */
+ ortho_v3_v3(normal, plane);
+ }
+ }
}
result = ORIENTATION_EDGE;
@@ -817,15 +826,21 @@ int getTransformOrientation_ex(const bContext *C, float normal[3], float plane[3
else if (ELEM(obedit->type, OB_CURVE, OB_SURF)) {
Curve *cu = obedit->data;
Nurb *nu = NULL;
- BezTriple *bezt = NULL;
int a;
ListBase *nurbs = BKE_curve_editNurbs_get(cu);
- if (activeOnly && BKE_curve_nurb_vert_active_get(cu, &nu, (void *)&bezt)) {
+ void *vert_act = NULL;
+ if (activeOnly && BKE_curve_nurb_vert_active_get(cu, &nu, &vert_act)) {
if (nu->type == CU_BEZIER) {
+ BezTriple *bezt = vert_act;
BKE_nurb_bezt_calc_normal(nu, bezt, normal);
BKE_nurb_bezt_calc_plane(nu, bezt, plane);
}
+ else {
+ BPoint *bp = vert_act;
+ BKE_nurb_bpoint_calc_normal(nu, bp, normal);
+ BKE_nurb_bpoint_calc_plane(nu, bp, plane);
+ }
}
else {
const bool use_handle = (cu->drawflag & CU_HIDE_HANDLES) == 0;
@@ -833,7 +848,7 @@ int getTransformOrientation_ex(const bContext *C, float normal[3], float plane[3
for (nu = nurbs->first; nu; nu = nu->next) {
/* only bezier has a normal */
if (nu->type == CU_BEZIER) {
- bezt = nu->bezt;
+ BezTriple *bezt = nu->bezt;
a = nu->pntsu;
while (a--) {
short flag = 0;
@@ -885,6 +900,36 @@ int getTransformOrientation_ex(const bContext *C, float normal[3], float plane[3
bezt++;
}
}
+ else if (nu->bp && (nu->pntsv == 1)) {
+ BPoint *bp = nu->bp;
+ a = nu->pntsu;
+ while (a--) {
+ if (bp->f1 & SELECT) {
+ float tvec[3];
+
+ BPoint *bp_prev = BKE_nurb_bpoint_get_prev(nu, bp);
+ BPoint *bp_next = BKE_nurb_bpoint_get_next(nu, bp);
+
+ const bool is_prev_sel = bp_prev && (bp_prev->f1 & SELECT);
+ const bool is_next_sel = bp_next && (bp_next->f1 & SELECT);
+ if (is_prev_sel == false && is_next_sel == false) {
+ /* Isolated, add based on surrounding */
+ BKE_nurb_bpoint_calc_normal(nu, bp, tvec);
+ add_v3_v3(normal, tvec);
+ }
+ else if (is_next_sel) {
+ /* A segment, add the edge normal */
+ sub_v3_v3v3(tvec, bp->vec, bp_next->vec);
+ normalize_v3(tvec);
+ add_v3_v3(normal, tvec);
+ }
+
+ BKE_nurb_bpoint_calc_plane(nu, bp, tvec);
+ add_v3_v3(plane, tvec);
+ }
+ bp++;
+ }
+ }
}
}
diff --git a/source/blender/editors/transform/transform_snap.c b/source/blender/editors/transform/transform_snap.c
index 318d2718969..5750224de3d 100644
--- a/source/blender/editors/transform/transform_snap.c
+++ b/source/blender/editors/transform/transform_snap.c
@@ -105,7 +105,7 @@ static float ResizeBetween(TransInfo *t, const float p1[3], const float p2[3]);
/****************** IMPLEMENTATIONS *********************/
-static bool snapNodeTest(View2D *v2d, bNode *node, SnapSelect snap_select);
+static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select);
static NodeBorder snapNodeBorder(int snap_node_mode);
#if 0
@@ -316,9 +316,7 @@ void applyProject(TransInfo *t)
mul_m4_v3(ob->obmat, iloc);
}
else if (t->flag & T_OBJECT) {
- /* TODO(sergey): Ideally force update is not needed here. */
- td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
- BKE_object_handle_update(G.main->eval_ctx, t->scene, td->ob);
+ BKE_object_eval_transform_all(G.main->eval_ctx, t->scene, td->ob);
copy_v3_v3(iloc, td->ob->obmat[3]);
}
@@ -407,8 +405,7 @@ void applyGridAbsolute(TransInfo *t)
mul_m4_v3(obmat, iloc);
}
else if (t->flag & T_OBJECT) {
- td->ob->recalc |= OB_RECALC_OB | OB_RECALC_DATA | OB_RECALC_TIME;
- BKE_object_handle_update(G.main->eval_ctx, t->scene, td->ob);
+ BKE_object_eval_transform_all(G.main->eval_ctx, t->scene, td->ob);
copy_v3_v3(iloc, td->ob->obmat[3]);
}
@@ -1017,7 +1014,7 @@ static void CalcSnapGeometry(TransInfo *t, float *UNUSED(vec))
float dist_px = SNAP_MIN_DISTANCE; // Use a user defined value here
char node_border;
- if (snapNodesTransform(t, t->mval, t->tsnap.modeSelect, loc, &dist_px, &node_border)) {
+ if (snapNodesTransform(t, t->mval, loc, &dist_px, &node_border)) {
copy_v2_v2(t->tsnap.snapPoint, loc);
t->tsnap.snapNodeBorder = node_border;
@@ -1315,7 +1312,7 @@ bool peelObjectsTransform(
/******************** NODES ***********************************/
-static bool snapNodeTest(View2D *v2d, bNode *node, SnapSelect snap_select)
+static bool snapNodeTest(View2D *v2d, bNode *node, eSnapSelect snap_select)
{
/* node is use for snapping only if a) snap mode matches and b) node is inside the view */
return ((snap_select == SNAP_NOT_SELECTED && !(node->flag & NODE_SELECT)) ||
@@ -1394,7 +1391,7 @@ static bool snapNode(
static bool snapNodes(
ToolSettings *ts, SpaceNode *snode, ARegion *ar,
- const int mval[2], SnapSelect snap_select,
+ const int mval[2], eSnapSelect snap_select,
float r_loc[2], float *r_dist_px, char *r_node_border)
{
bNodeTree *ntree = snode->edittree;
@@ -1413,22 +1410,11 @@ static bool snapNodes(
}
bool snapNodesTransform(
- TransInfo *t, const int mval[2], SnapSelect snap_select,
+ TransInfo *t, const int mval[2],
float r_loc[2], float *r_dist_px, char *r_node_border)
{
return snapNodes(
- t->settings, t->sa->spacedata.first, t->ar, mval, snap_select,
- r_loc, r_dist_px, r_node_border);
-}
-
-bool snapNodesContext(
- bContext *C, const int mval[2], SnapSelect snap_select,
- float r_loc[2], float *r_dist_px, char *r_node_border)
-{
- Scene *scene = CTX_data_scene(C);
- ARegion *ar = CTX_wm_region(C);
- return snapNodes(
- scene->toolsettings, CTX_wm_space_node(C), ar, mval, snap_select,
+ t->settings, t->sa->spacedata.first, t->ar, mval, t->tsnap.modeSelect,
r_loc, r_dist_px, r_node_border);
}
@@ -1478,7 +1464,7 @@ void snapSequenceBounds(TransInfo *t, const int mval[2])
/* convert to frame range */
UI_view2d_region_to_view(&t->ar->v2d, mval[0], mval[1], &xmouse, &ymouse);
- mframe = iroundf(xmouse);
+ mframe = round_fl_to_int(xmouse);
/* now find the closest sequence */
frame = BKE_sequencer_find_next_prev_edit(t->scene, mframe, SEQ_SIDE_BOTH, true, false, true);
diff --git a/source/blender/editors/transform/transform_snap_object.c b/source/blender/editors/transform/transform_snap_object.c
index 53f6b37c22e..d248d0df4e3 100644
--- a/source/blender/editors/transform/transform_snap_object.c
+++ b/source/blender/editors/transform/transform_snap_object.c
@@ -59,6 +59,10 @@
#include "transform.h"
+/* -------------------------------------------------------------------- */
+/** Internal Data Types
+ * \{ */
+
enum eViewProj {
VIEW_PROJ_NONE = -1,
VIEW_PROJ_ORTHO = 0,
@@ -87,6 +91,8 @@ typedef struct SnapObjectData {
typedef struct SnapObjectData_Mesh {
SnapObjectData sd;
BVHTreeFromMesh *bvh_trees[3];
+ MPoly *mpoly;
+ bool poly_allocated;
} SnapObjectData_Mesh;
@@ -128,18 +134,137 @@ struct SnapObjectContext {
};
-static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt);
-
+/** \} */
/* -------------------------------------------------------------------- */
+/** Common Utilities
+ * \{ */
+
+
+typedef void(*IterSnapObjsCallback)(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data);
+
+/**
+ * Walks through all objects in the scene to create the list of objets to snap.
+ *
+ * \param sctx: Snap context to store data.
+ * \param snap_select : from enum eSnapSelect.
+ * \param obedit : Object Edited to use its coordinates of BMesh(if any) to do the snapping.
+ */
+static void iter_snap_objects(
+ SnapObjectContext *sctx,
+ const eSnapSelect snap_select,
+ Object *obedit,
+ IterSnapObjsCallback sob_callback,
+ void *data)
+{
+ Base *base_act = sctx->scene->basact;
+ for (Base *base = sctx->scene->base.first; base != NULL; base = base->next) {
+ if ((BASE_VISIBLE_BGMODE(sctx->v3d_data.v3d, sctx->scene, base)) &&
+ (base->flag & BA_SNAP_FIX_DEPS_FIASCO) == 0 &&
+ !((snap_select == SNAP_NOT_SELECTED && (base->flag & (SELECT | BA_WAS_SEL))) ||
+ (snap_select == SNAP_NOT_ACTIVE && base == base_act)))
+ {
+ bool use_obedit;
+ Object *obj = base->object;
+ if (obj->transflag & OB_DUPLI) {
+ DupliObject *dupli_ob;
+ ListBase *lb = object_duplilist(sctx->bmain->eval_ctx, sctx->scene, obj);
+ for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
+ use_obedit = obedit && dupli_ob->ob->data == obedit->data;
+ sob_callback(sctx, use_obedit, use_obedit ? obedit : dupli_ob->ob, dupli_ob->mat, data);
+ }
+ free_object_duplilist(lb);
+ }
+
+ use_obedit = obedit && obj->data == obedit->data;
+ sob_callback(sctx, use_obedit, use_obedit ? obedit : obj, obj->obmat, data);
+ }
+ }
+}
-/** \name Support for storing all depths, not just the first (raycast 'all')
+
+/**
+ * Generates a struct with the immutable parameters that will be used on all objects.
*
- * This uses a list of #SnapObjectHitDepth structs.
+ * \param snap_to: Element to snap, Vertice, Edge or Face.
+ * \param view_proj: ORTHO or PERSP.
+ * Currently only works one at a time, but can eventually operate as flag.
*
+ * \param mval: Mouse coords.
+ * (When NULL, ray-casting is handled without any projection matrix correction.)
+ * \param ray_origin: ray_start before being moved toward the ray_normal at the distance from vew3d clip_min.
+ * \param ray_start: ray_origin moved for the start clipping plane (clip_min).
+ * \param ray_direction: Unit length direction of the ray.
+ * \param depth_range: distances of clipe plane min and clip plane max;
+ */
+static void snap_data_set(
+ SnapData *snapdata,
+ const ARegion *ar, const unsigned short snap_to, const enum eViewProj view_proj,
+ const float mval[2], const float ray_origin[3], const float ray_start[3],
+ const float ray_direction[3], const float depth_range[2])
+{
+ copy_m4_m4(snapdata->pmat, ((RegionView3D *)ar->regiondata)->persmat);
+ snapdata->win_half[0] = ar->winx / 2;
+ snapdata->win_half[1] = ar->winy / 2;
+ copy_v2_v2(snapdata->mval, mval);
+ snapdata->snap_to = snap_to;
+ copy_v3_v3(snapdata->ray_origin, ray_origin);
+ copy_v3_v3(snapdata->ray_start, ray_start);
+ copy_v3_v3(snapdata->ray_dir, ray_direction);
+ snapdata->view_proj = view_proj;
+ copy_v2_v2(snapdata->depth_range, depth_range);
+}
+
+
+MINLINE float depth_get(const float co[3], const float ray_start[3], const float ray_dir[3])
+{
+ float dvec[3];
+ sub_v3_v3v3(dvec, co, ray_start);
+ return dot_v3v3(dvec, ray_dir);
+}
+
+
+static bool walk_parent_bvhroot_cb(const BVHTreeAxisRange *bounds, void *userdata)
+{
+ BVHTreeRay *ray = userdata;
+ const float bbmin[3] = {bounds[0].min, bounds[1].min, bounds[2].min};
+ const float bbmax[3] = {bounds[0].max, bounds[1].max, bounds[2].max};
+ if (!isect_ray_aabb_v3_simple(ray->origin, ray->direction, bbmin, bbmax, &ray->radius, NULL)) {
+ ray->radius = -1;
+ }
+ return false;
+}
+
+
+static bool isect_ray_bvhroot_v3(struct BVHTree *tree, const float ray_start[3], const float ray_dir[3], float *depth)
+{
+ BVHTreeRay ray;
+ copy_v3_v3(ray.origin, ray_start);
+ copy_v3_v3(ray.direction, ray_dir);
+
+ BLI_bvhtree_walk_dfs(tree, walk_parent_bvhroot_cb, NULL, NULL, &ray);
+
+ if (ray.radius > 0) {
+ *depth = ray.radius;
+ return true;
+ }
+ else {
+ return false;
+ }
+}
+
+
+static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt);
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Ray Cast Funcs
* \{ */
-/* Store all ray-hits */
+/* Store all ray-hits
+ * Support for storing all depths, not just the first (raycast 'all') */
+
struct RayCastAll_Data {
void *bvhdata;
@@ -160,6 +285,7 @@ struct RayCastAll_Data {
bool retval;
};
+
static struct SnapObjectHitDepth *hit_depth_create(
const float depth, const float co[3], const float no[3], int index,
Object *ob, const float obmat[4][4], unsigned int ob_uuid)
@@ -227,57 +353,498 @@ static void raycast_all_cb(void *userdata, int index, const BVHTreeRay *ray, BVH
}
}
-/** \} */
+static bool raycastDerivedMesh(
+ SnapObjectContext *sctx,
+ const float ray_start[3], const float ray_dir[3],
+ Object *ob, DerivedMesh *dm, float obmat[4][4], const unsigned int ob_index,
+ /* read/write args */
+ float *ray_depth,
+ /* return args */
+ float r_loc[3], float r_no[3], int *r_index,
+ ListBase *r_hit_list)
+{
+ bool retval = false;
-/* -------------------------------------------------------------------- */
+ if (dm->getNumPolys(dm) == 0) {
+ return retval;
+ }
+
+ float imat[4][4];
+ float timat[3][3]; /* transpose inverse matrix for normals */
+ float ray_start_local[3], ray_normal_local[3];
+ float local_scale, local_depth, len_diff = 0.0f;
+
+ invert_m4_m4(imat, obmat);
+ transpose_m3_m4(timat, imat);
+
+ copy_v3_v3(ray_start_local, ray_start);
+ copy_v3_v3(ray_normal_local, ray_dir);
+
+ mul_m4_v3(imat, ray_start_local);
+ mul_mat3_m4_v3(imat, ray_normal_local);
+
+ /* local scale in normal direction */
+ local_scale = normalize_v3(ray_normal_local);
+ local_depth = *ray_depth;
+ if (local_depth != BVH_RAYCAST_DIST_MAX) {
+ local_depth *= local_scale;
+ }
+
+ /* Test BoundBox */
+ BoundBox *bb = BKE_object_boundbox_get(ob);
+ if (bb) {
+ /* was BKE_boundbox_ray_hit_check, see: cf6ca226fa58 */
+ if (!isect_ray_aabb_v3_simple(
+ ray_start_local, ray_normal_local, bb->vec[0], bb->vec[6], &len_diff, NULL))
+ {
+ return retval;
+ }
+ }
+
+ SnapObjectData_Mesh *sod = NULL;
+ BVHTreeFromMesh *treedata;
+
+ void **sod_p;
+ if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
+ sod = *sod_p;
+ }
+ else {
+ sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
+ sod->sd.type = SNAP_MESH;
+ }
+
+ if (sod->bvh_trees[2] == NULL) {
+ sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
+ }
+
+ treedata = sod->bvh_trees[2];
+
+ if (treedata) {
+ /* the tree is owned by the DM and may have been freed since we last used! */
+ if (treedata->tree) {
+ if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
+ free_bvhtree_from_mesh(treedata);
+ }
+ else {
+ if (treedata->vert == NULL) {
+ treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
+ }
+ if (treedata->loop == NULL) {
+ treedata->loop = DM_get_loop_array(dm, &treedata->loop_allocated);
+ }
+ if (treedata->looptri == NULL) {
+ if (sod->mpoly == NULL) {
+ sod->mpoly = DM_get_poly_array(dm, &sod->poly_allocated);
+ }
+ treedata->looptri = dm->getLoopTriArray(dm);
+ treedata->looptri_allocated = false;
+ }
+ }
+ }
+
+ if (treedata->tree == NULL) {
+ bvhtree_from_mesh_looptri(treedata, dm, 0.0f, 4, 6);
+
+ if (treedata->tree == NULL) {
+ return retval;
+ }
+ }
+ }
+ else {
+ return retval;
+ }
+
+ /* Only use closer ray_start in case of ortho view! In perspective one, ray_start may already
+ * been *inside* boundbox, leading to snap failures (see T38409).
+ * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
+ */
+ if (len_diff == 0.0f) { /* do_ray_start_correction */
+ /* We *need* a reasonably valid len_diff in this case.
+ * Get the distance to bvhtree root */
+ if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
+ return retval;
+ }
+ }
+ /* You need to make sure that ray_start is really far away,
+ * because even in the Orthografic view, in some cases,
+ * the ray can start inside the object (see T50486) */
+ if (len_diff > 400.0f) {
+ /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
+ * very far away ray_start values (as returned in case of ortho view3d), see T38358.
+ */
+ len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
+ madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
+ local_depth -= len_diff;
+ }
+ else {
+ len_diff = 0.0f;
+ }
+ if (r_hit_list) {
+ struct RayCastAll_Data data;
+
+ data.bvhdata = treedata;
+ data.raycast_callback = treedata->raycast_callback;
+ data.obmat = obmat;
+ data.timat = timat;
+ data.len_diff = len_diff;
+ data.local_scale = local_scale;
+ data.ob = ob;
+ data.ob_uuid = ob_index;
+ data.hit_list = r_hit_list;
+ data.retval = retval;
+
+ BLI_bvhtree_ray_cast_all(
+ treedata->tree, ray_start_local, ray_normal_local, 0.0f,
+ *ray_depth, raycast_all_cb, &data);
+
+ retval = data.retval;
+ }
+ else {
+ BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
+
+ if (BLI_bvhtree_ray_cast(
+ treedata->tree, ray_start_local, ray_normal_local, 0.0f,
+ &hit, treedata->raycast_callback, treedata) != -1)
+ {
+ hit.dist += len_diff;
+ hit.dist /= local_scale;
+ if (hit.dist <= *ray_depth) {
+ *ray_depth = hit.dist;
+ copy_v3_v3(r_loc, hit.co);
+
+ /* back to worldspace */
+ mul_m4_v3(obmat, r_loc);
+
+ if (r_no) {
+ copy_v3_v3(r_no, hit.no);
+ mul_m3_v3(timat, r_no);
+ normalize_v3(r_no);
+ }
+
+ retval = true;
+
+ if (r_index) {
+ *r_index = dm_looptri_to_poly_index(dm, &treedata->looptri[hit.index]);
+ }
+ }
+ }
+ }
+
+ return retval;
+}
+
+static bool raycastEditMesh(
+ SnapObjectContext *sctx,
+ const float ray_start[3], const float ray_dir[3],
+ Object *ob, BMEditMesh *em, float obmat[4][4], const unsigned int ob_index,
+ /* read/write args */
+ float *ray_depth,
+ /* return args */
+ float r_loc[3], float r_no[3], int *r_index,
+ ListBase *r_hit_list)
+{
+ bool retval = false;
+ if (em->bm->totface == 0) {
+ return retval;
+ }
+
+ SnapObjectData_EditMesh *sod = NULL;
+ BVHTreeFromEditMesh *treedata = NULL;
+
+ void **sod_p;
+ if (BLI_ghash_ensure_p(sctx->cache.object_map, ob, &sod_p)) {
+ sod = *sod_p;
+ }
+ else {
+ sod = *sod_p = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*sod));
+ sod->sd.type = SNAP_EDIT_MESH;
+ }
+
+ if (sod->bvh_trees[2] == NULL) {
+ sod->bvh_trees[2] = BLI_memarena_calloc(sctx->cache.mem_arena, sizeof(*treedata));
+ }
+ treedata = sod->bvh_trees[2];
+
+ if (treedata) {
+ if (treedata->tree == NULL) {
+ BLI_bitmap *elem_mask = NULL;
+ int looptri_num_active = -1;
+
+ if (sctx->callbacks.edit_mesh.test_face_fn) {
+ elem_mask = BLI_BITMAP_NEW(em->tottri, __func__);
+ looptri_num_active = BM_iter_mesh_bitmap_from_filter_tessface(
+ em->bm, elem_mask,
+ sctx->callbacks.edit_mesh.test_face_fn, sctx->callbacks.edit_mesh.user_data);
+ }
+ bvhtree_from_editmesh_looptri_ex(treedata, em, elem_mask, looptri_num_active, 0.0f, 4, 6, NULL);
+
+ if (elem_mask) {
+ MEM_freeN(elem_mask);
+ }
+ }
+ if (treedata->tree == NULL) {
+ return retval;
+ }
+ }
+ else {
+ return retval;
+ }
+
+ float imat[4][4];
+ float timat[3][3]; /* transpose inverse matrix for normals */
+ float ray_normal_local[3], ray_start_local[3], len_diff = 0.0f;
+
+ invert_m4_m4(imat, obmat);
+ transpose_m3_m4(timat, imat);
+
+ copy_v3_v3(ray_normal_local, ray_dir);
+ mul_mat3_m4_v3(imat, ray_normal_local);
+
+ copy_v3_v3(ray_start_local, ray_start);
+ mul_m4_v3(imat, ray_start_local);
+
+ /* local scale in normal direction */
+ float local_scale = normalize_v3(ray_normal_local);
+ float local_depth = *ray_depth;
+ if (local_depth != BVH_RAYCAST_DIST_MAX) {
+ local_depth *= local_scale;
+ }
+
+ /* Only use closer ray_start in case of ortho view! In perspective one, ray_start
+ * may already been *inside* boundbox, leading to snap failures (see T38409).
+ * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
+ */
+ if (sctx->use_v3d && !((RegionView3D *)sctx->v3d_data.ar->regiondata)->is_persp) { /* do_ray_start_correction */
+ /* We *need* a reasonably valid len_diff in this case.
+ * Get the distance to bvhtree root */
+ if (!isect_ray_bvhroot_v3(treedata->tree, ray_start_local, ray_normal_local, &len_diff)) {
+ return retval;
+ }
+ /* You need to make sure that ray_start is really far away,
+ * because even in the Orthografic view, in some cases,
+ * the ray can start inside the object (see T50486) */
+ if (len_diff > 400.0f) {
+ /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
+ * very far away ray_start values (as returned in case of ortho view3d), see T38358.
+ */
+ len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
+ madd_v3_v3fl(ray_start_local, ray_normal_local, len_diff);
+ local_depth -= len_diff;
+ }
+ else len_diff = 0.0f;
+ }
+ if (r_hit_list) {
+ struct RayCastAll_Data data;
+
+ data.bvhdata = treedata;
+ data.raycast_callback = treedata->raycast_callback;
+ data.obmat = obmat;
+ data.timat = timat;
+ data.len_diff = len_diff;
+ data.local_scale = local_scale;
+ data.ob = ob;
+ data.ob_uuid = ob_index;
+ data.hit_list = r_hit_list;
+ data.retval = retval;
+
+ BLI_bvhtree_ray_cast_all(
+ treedata->tree, ray_start_local, ray_normal_local, 0.0f,
+ *ray_depth, raycast_all_cb, &data);
+
+ retval = data.retval;
+ }
+ else {
+ BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
+
+ if (BLI_bvhtree_ray_cast(
+ treedata->tree, ray_start_local, ray_normal_local, 0.0f,
+ &hit, treedata->raycast_callback, treedata) != -1)
+ {
+ hit.dist += len_diff;
+ hit.dist /= local_scale;
+ if (hit.dist <= *ray_depth) {
+ *ray_depth = hit.dist;
+ copy_v3_v3(r_loc, hit.co);
+
+ /* back to worldspace */
+ mul_m4_v3(obmat, r_loc);
+
+ if (r_no) {
+ copy_v3_v3(r_no, hit.no);
+ mul_m3_v3(timat, r_no);
+ normalize_v3(r_no);
+ }
+
+ retval = true;
+
+ if (r_index) {
+ *r_index = hit.index;
+ }
+ }
+ }
+ }
+
+ return retval;
+}
-/** \Common utilities
- * \{ */
/**
- * Generates a struct with the immutable parameters that will be used on all objects.
- *
- * \param snap_to: Element to snap, Vertice, Edge or Face.
- * \param view_proj: ORTHO or PERSP.
- * Currently only works one at a time, but can eventually operate as flag.
+ * \param use_obedit: Uses the coordinates of BMesh (if any) to do the snapping;
*
- * \param mval: Mouse coords.
- * (When NULL, ray-casting is handled without any projection matrix correction.)
- * \param ray_origin: ray_start before being moved toward the ray_normal at the distance from vew3d clip_min.
- * \param ray_start: ray_origin moved for the start clipping plane (clip_min).
- * \param ray_direction: Unit length direction of the ray.
- * \param depth_range: distances of clipe plane min and clip plane max;
+ * \note Duplicate args here are documented at #snapObjectsRay
*/
-static void snap_data_set(
- SnapData *snapdata,
- const ARegion *ar, const unsigned short snap_to, const enum eViewProj view_proj,
- const float mval[2], const float ray_origin[3], const float ray_start[3],
- const float ray_direction[3], const float depth_range[2])
+static bool raycastObj(
+ SnapObjectContext *sctx,
+ const float ray_start[3], const float ray_dir[3],
+ Object *ob, float obmat[4][4], const unsigned int ob_index,
+ bool use_obedit,
+ /* read/write args */
+ float *ray_depth,
+ /* return args */
+ float r_loc[3], float r_no[3], int *r_index,
+ Object **r_ob, float r_obmat[4][4],
+ ListBase *r_hit_list)
{
- if (ar) {
- copy_m4_m4(snapdata->pmat, ((RegionView3D *)ar->regiondata)->persmat);
- snapdata->win_half[0] = ar->winx / 2;
- snapdata->win_half[1] = ar->winy / 2;
+ bool retval = false;
+
+ if (ob->type == OB_MESH) {
+ BMEditMesh *em;
+
+ if (use_obedit) {
+ em = BKE_editmesh_from_object(ob);
+ retval = raycastEditMesh(
+ sctx,
+ ray_start, ray_dir,
+ ob, em, obmat, ob_index,
+ ray_depth, r_loc, r_no, r_index, r_hit_list);
+ }
+ else {
+ /* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
+ * still set the 'em' to NULL, since we only want the 'dm'. */
+ DerivedMesh *dm;
+ em = BKE_editmesh_from_object(ob);
+ if (em) {
+ editbmesh_get_derived_cage_and_final(sctx->scene, ob, em, CD_MASK_BAREMESH, &dm);
+ }
+ else {
+ dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
+ }
+ retval = raycastDerivedMesh(
+ sctx,
+ ray_start, ray_dir,
+ ob, dm, obmat, ob_index,
+ ray_depth, r_loc, r_no, r_index, r_hit_list);
+ }
}
- if (mval) {
- copy_v2_v2(snapdata->mval, mval);
+
+ if (retval) {
+ if (r_ob) {
+ *r_ob = ob;
+ copy_m4_m4(r_obmat, obmat);
+ }
}
- snapdata->snap_to = snap_to;
- copy_v3_v3(snapdata->ray_origin, ray_origin);
- copy_v3_v3(snapdata->ray_start, ray_start);
- copy_v3_v3(snapdata->ray_dir, ray_direction);
- snapdata->view_proj = view_proj;
- copy_v2_v2(snapdata->depth_range, depth_range);
+
+ return retval;
}
-MINLINE float depth_get(const float co[3], const float ray_start[3], const float ray_dir[3])
+
+struct RaycastObjUserData {
+ const float *ray_start;
+ const float *ray_dir;
+ unsigned int ob_index;
+ /* read/write args */
+ float *ray_depth;
+ /* return args */
+ float *r_loc;
+ float *r_no;
+ int *r_index;
+ Object **r_ob;
+ float (*r_obmat)[4];
+ ListBase *r_hit_list;
+ bool ret;
+};
+
+static void raycast_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
{
- float dvec[3];
- sub_v3_v3v3(dvec, co, ray_start);
- return dot_v3v3(dvec, ray_dir);
+ struct RaycastObjUserData *dt = data;
+ dt->ret |= raycastObj(
+ sctx,
+ dt->ray_start, dt->ray_dir,
+ ob, obmat, dt->ob_index++, is_obedit,
+ dt->ray_depth,
+ dt->r_loc, dt->r_no, dt->r_index,
+ dt->r_ob, dt->r_obmat,
+ dt->r_hit_list);
}
+/**
+ * Main RayCast Function
+ * ======================
+ *
+ * Walks through all objects in the scene to find the `hit` on object surface.
+ *
+ * \param sctx: Snap context to store data.
+ * \param snap_select : from enum eSnapSelect.
+ * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
+ * \param obj_list: List with objects to snap (created in `create_object_list`).
+ *
+ * Read/Write Args
+ * ---------------
+ *
+ * \param ray_depth: maximum depth allowed for r_co, elements deeper than this value will be ignored.
+ *
+ * Output Args
+ * -----------
+ *
+ * \param r_loc: Hit location.
+ * \param r_no: Hit normal (optional).
+ * \param r_index: Hit index or -1 when no valid index is found.
+ * (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
+ * \param r_ob: Hit object.
+ * \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
+ * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
+ *
+ */
+static bool raycastObjects(
+ SnapObjectContext *sctx,
+ const float ray_start[3], const float ray_dir[3],
+ const eSnapSelect snap_select, const bool use_object_edit_cage,
+ /* read/write args */
+ float *ray_depth,
+ /* return args */
+ float r_loc[3], float r_no[3], int *r_index,
+ Object **r_ob, float r_obmat[4][4],
+ ListBase *r_hit_list)
+{
+ Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
+
+ struct RaycastObjUserData data = {
+ .ray_start = ray_start,
+ .ray_dir = ray_dir,
+ .ob_index = 0,
+ .ray_depth = ray_depth,
+ .r_loc = r_loc,
+ .r_no = r_no,
+ .r_index = r_index,
+ .r_ob = r_ob,
+ .r_obmat = r_obmat,
+ .r_hit_list = r_hit_list,
+ .ret = false,
+ };
+
+ iter_snap_objects(sctx, snap_select, obedit, raycast_obj_cb, &data);
+
+ return data.ret;
+}
+
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** Snap Nearest utilities
+ * \{ */
+
static void copy_dm_vert_no(const int index, float r_no[3], const BVHTreeFromMesh *data)
{
const MVert *vert = data->vert + index;
@@ -486,36 +1053,20 @@ static float dist_squared_to_projected_aabb(
main_axis += 3;
}
- /* if rtmin < rtmax, ray intersect `AABB` */
- if (rtmin <= rtmax) {
#define IGNORE_BEHIND_RAY
#ifdef IGNORE_BEHIND_RAY
- /* `if rtmax < depth_min`, the hit is behind us */
- if (rtmax < data->ray_min_dist) {
- /* Test if the entire AABB is behind us */
- float depth = depth_get(
- local_bvmax, data->ray_origin_local, data->ray_direction_local);
- if (depth < (data->ray_min_dist)) {
- return FLT_MAX;
- }
- }
-#endif
- const float proj = rtmin * data->ray_direction_local[main_axis];
- r_axis_closest[main_axis] = (proj - va[main_axis]) < (vb[main_axis] - proj);
- return 0.0f;
- }
-#ifdef IGNORE_BEHIND_RAY
- /* `if rtmin < depth_min`, the hit is behing us */
- else if (rtmin < data->ray_min_dist) {
- /* Test if the entire AABB is behind us */
- float depth = depth_get(
- local_bvmax, data->ray_origin_local, data->ray_direction_local);
- if (depth < (data->ray_min_dist)) {
- return FLT_MAX;
- }
+ float depth_max = depth_get(local_bvmax, data->ray_origin_local, data->ray_direction_local);
+ if (depth_max < data->ray_min_dist) {
+ return FLT_MAX;
}
#endif
#undef IGNORE_BEHIND_RAY
+
+ /* if rtmin <= rtmax, ray intersect `AABB` */
+ if (rtmin <= rtmax) {
+ return 0;
+ }
+
if (data->sign[main_axis]) {
va[main_axis] = local_bvmax[main_axis];
vb[main_axis] = local_bvmin[main_axis];
@@ -556,15 +1107,12 @@ static float dist_squared_to_projected_aabb(
vb2d[0] *= data->win_half[0];
vb2d[1] *= data->win_half[1];
- //float dvec[2], edge[2], rdist;
- //sub_v2_v2v2(dvec, data->mval, va2d);
- //sub_v2_v2v2(edge, vb2d, va2d);
- float rdist;
- short dvec[2] = {data->mval[0] - va2d[0], data->mval[1] - va2d[1]};
- short edge[2] = {vb2d[0] - va2d[0], vb2d[1] - va2d[1]};
- float lambda = dvec[0] * edge[0] + dvec[1] * edge[1];
+ float dvec[2], edge[2], lambda, rdist;
+ sub_v2_v2v2(dvec, data->mval, va2d);
+ sub_v2_v2v2(edge, vb2d, va2d);
+ lambda = dot_v2v2(dvec, edge);
if (lambda != 0.0f) {
- lambda /= edge[0] * edge[0] + edge[1] * edge[1];
+ lambda /= len_squared_v2(edge);
if (lambda <= 0.0f) {
rdist = len_squared_v2v2(data->mval, va2d);
r_axis_closest[main_axis] = true;
@@ -601,24 +1149,10 @@ static float dist_squared_to_projected_aabb_simple(
return dist_squared_to_projected_aabb(&data, bbmin, bbmax, dummy);
}
-static float dist_aabb_to_plane(
- const float bbmin[3], const float bbmax[3],
- const float plane_co[3], const float plane_no[3])
-{
- const float local_bvmin[3] = {
- (plane_no[0] < 0) ? bbmax[0] : bbmin[0],
- (plane_no[1] < 0) ? bbmax[1] : bbmin[1],
- (plane_no[2] < 0) ? bbmax[2] : bbmin[2],
- };
- return depth_get(local_bvmin, plane_co, plane_no);
-}
-
/** \} */
-
/* -------------------------------------------------------------------- */
-
-/** \Walk DFS
+/** Walk DFS
* \{ */
typedef void (*Nearest2DGetEdgeVertsCallback)(const int index, const float *v_pair[2], void *data);
@@ -713,7 +1247,6 @@ static bool cb_nearest_walk_order(const BVHTreeAxisRange *UNUSED(bounds), char a
/** \} */
/* -------------------------------------------------------------------- */
-
/** \name Internal Object Snapping API
* \{ */
@@ -934,9 +1467,10 @@ static bool snapEmpty(
float tmp_co[3];
copy_v3_v3(tmp_co, obmat[3]);
if (test_projected_vert_dist(
- snapdata->depth_range, snapdata->mval, tmp_co,
- snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
- r_loc)) {
+ snapdata->depth_range, snapdata->mval, tmp_co,
+ snapdata->pmat, snapdata->win_half, is_persp, &dist_px_sq,
+ r_loc))
+ {
*dist_px = sqrtf(dist_px_sq);
*ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
retval = true;
@@ -1050,21 +1584,15 @@ static int dm_looptri_to_poly_index(DerivedMesh *dm, const MLoopTri *lt)
static bool snapDerivedMesh(
SnapObjectContext *sctx, SnapData *snapdata,
- Object *ob, DerivedMesh *dm, float obmat[4][4], const unsigned int ob_index,
+ Object *ob, DerivedMesh *dm, float obmat[4][4],
/* read/write args */
float *ray_depth, float *dist_px,
/* return args */
- float r_loc[3], float r_no[3], int *r_index,
- ListBase *r_hit_list)
+ float r_loc[3], float r_no[3])
{
bool retval = false;
- if (snapdata->snap_to == SCE_SNAP_MODE_FACE) {
- if (dm->getNumPolys(dm) == 0) {
- return retval;
- }
- }
- else if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
+ if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
if (dm->getNumEdges(dm) == 0) {
return retval;
}
@@ -1075,38 +1603,27 @@ static bool snapDerivedMesh(
}
}
- bool need_ray_start_correction_init =
- (snapdata->snap_to == SCE_SNAP_MODE_FACE) &&
- (snapdata->view_proj == VIEW_PROJ_ORTHO);
-
float imat[4][4];
float timat[3][3]; /* transpose inverse matrix for normals */
- float ray_start_local[3], ray_normal_local[3];
- float local_scale, local_depth, len_diff;
+ float ray_normal_local[3];
+ float local_scale;
invert_m4_m4(imat, obmat);
transpose_m3_m4(timat, imat);
- copy_v3_v3(ray_start_local, snapdata->ray_start);
copy_v3_v3(ray_normal_local, snapdata->ray_dir);
- mul_m4_v3(imat, ray_start_local);
mul_mat3_m4_v3(imat, ray_normal_local);
/* local scale in normal direction */
local_scale = normalize_v3(ray_normal_local);
- local_depth = *ray_depth;
- if (local_depth != BVH_RAYCAST_DIST_MAX) {
- local_depth *= local_scale;
- }
float lpmat[4][4];
float ray_org_local[3];
float ray_min_dist;
- if (ELEM(snapdata->snap_to, SCE_SNAP_MODE_VERTEX, SCE_SNAP_MODE_EDGE)) {
- mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
- ray_min_dist = snapdata->depth_range[0] * local_scale;
- }
+
+ mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
+ ray_min_dist = snapdata->depth_range[0] * local_scale;
copy_v3_v3(ray_org_local, snapdata->ray_origin);
mul_m4_v3(imat, ray_org_local);
@@ -1115,27 +1632,12 @@ static bool snapDerivedMesh(
BoundBox *bb = BKE_object_boundbox_get(ob);
if (bb) {
/* In vertex and edges you need to get the pixel distance from ray to BoundBox, see: T46099, T46816 */
- if (ELEM(snapdata->snap_to, SCE_SNAP_MODE_VERTEX, SCE_SNAP_MODE_EDGE)) {
- float dist_px_sq = dist_squared_to_projected_aabb_simple(
- lpmat, snapdata->win_half, ray_min_dist, snapdata->mval,
- ray_org_local, ray_normal_local, bb->vec[0], bb->vec[6]);
- if (dist_px_sq > SQUARE(*dist_px))
- {
- return retval;
- }
- }
- else {
- /* was BKE_boundbox_ray_hit_check, see: cf6ca226fa58 */
- if (!isect_ray_aabb_v3_simple(
- ray_start_local, ray_normal_local, bb->vec[0], bb->vec[6], NULL, NULL))
- {
- return retval;
- }
+ float dist_px_sq = dist_squared_to_projected_aabb_simple(
+ lpmat, snapdata->win_half, ray_min_dist, snapdata->mval,
+ ray_org_local, ray_normal_local, bb->vec[0], bb->vec[6]);
+ if (dist_px_sq > SQUARE(*dist_px)) {
+ return retval;
}
- /* was local_depth, see: T47838 */
- len_diff = dist_aabb_to_plane(bb->vec[0], bb->vec[6], ray_start_local, ray_normal_local);
- if (len_diff < 0) len_diff = 0.0f;
- need_ray_start_correction_init = false;
}
SnapObjectData_Mesh *sod = NULL;
@@ -1152,9 +1654,6 @@ static bool snapDerivedMesh(
int tree_index = -1;
switch (snapdata->snap_to) {
- case SCE_SNAP_MODE_FACE:
- tree_index = 2;
- break;
case SCE_SNAP_MODE_EDGE:
tree_index = 1;
break;
@@ -1173,161 +1672,76 @@ static bool snapDerivedMesh(
if (treedata->cached && !bvhcache_has_tree(dm->bvhCache, treedata->tree)) {
free_bvhtree_from_mesh(treedata);
}
+ else {
+ if (treedata->vert == NULL) {
+ treedata->vert = DM_get_vert_array(dm, &treedata->vert_allocated);
+ }
+ if ((tree_index == 1) && (treedata->edge == NULL)) {
+ treedata->edge = DM_get_edge_array(dm, &treedata->edge_allocated);
+ }
+ }
}
}
- if (treedata && treedata->tree == NULL) {
- switch (snapdata->snap_to) {
- case SCE_SNAP_MODE_FACE:
- bvhtree_from_mesh_looptri(treedata, dm, 0.0f, 4, 6);
- break;
- case SCE_SNAP_MODE_EDGE:
- bvhtree_from_mesh_edges(treedata, dm, 0.0f, 2, 6);
- break;
- case SCE_SNAP_MODE_VERTEX:
- bvhtree_from_mesh_verts(treedata, dm, 0.0f, 2, 6);
- break;
+ if (treedata) {
+ if (treedata->tree == NULL) {
+ switch (snapdata->snap_to) {
+ case SCE_SNAP_MODE_EDGE:
+ bvhtree_from_mesh_edges(treedata, dm, 0.0f, 2, 6);
+ break;
+ case SCE_SNAP_MODE_VERTEX:
+ bvhtree_from_mesh_verts(treedata, dm, 0.0f, 2, 6);
+ break;
+ }
+ }
+ if (treedata->tree == NULL) {
+ return retval;
}
}
- if (!treedata || !treedata->tree) {
+ else {
return retval;
}
- if (snapdata->snap_to == SCE_SNAP_MODE_FACE) {
- /* Only use closer ray_start in case of ortho view! In perspective one, ray_start may already
- * been *inside* boundbox, leading to snap failures (see T38409).
- * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
- */
- if (snapdata->view_proj == VIEW_PROJ_ORTHO) { /* do_ray_start_correction */
- if (need_ray_start_correction_init) {
- /* We *need* a reasonably valid len_diff in this case.
- * Use BHVTree to find the closest face from ray_start_local.
- */
- BVHTreeNearest nearest;
- nearest.index = -1;
- nearest.dist_sq = FLT_MAX;
- /* Compute and store result. */
- BLI_bvhtree_find_nearest(
- treedata->tree, ray_start_local, &nearest, treedata->nearest_callback, treedata);
- if (nearest.index != -1) {
- float dvec[3];
- sub_v3_v3v3(dvec, nearest.co, ray_start_local);
- len_diff = dot_v3v3(dvec, ray_normal_local);
- }
- }
- /* You need to make sure that ray_start is really far away,
- * because even in the Orthografic view, in some cases,
- * the ray can start inside the object (see T50486) */
- if (len_diff > 400.0f) {
- /* We pass a temp ray_start, set from object's boundbox, to avoid precision issues with
- * very far away ray_start values (as returned in case of ortho view3d), see T38358.
- */
- len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
- madd_v3_v3v3fl(
- ray_start_local, ray_org_local, ray_normal_local,
- len_diff + snapdata->depth_range[0] * local_scale);
- local_depth -= len_diff;
- }
- else len_diff = 0.0f;
- }
- else {
- len_diff = 0.0f;
- }
- if (r_hit_list) {
- struct RayCastAll_Data data;
-
- data.bvhdata = treedata;
- data.raycast_callback = treedata->raycast_callback;
- data.obmat = obmat;
- data.timat = timat;
- data.len_diff = len_diff;
- data.local_scale = local_scale;
- data.ob = ob;
- data.ob_uuid = ob_index;
- data.hit_list = r_hit_list;
- data.retval = retval;
-
- BLI_bvhtree_ray_cast_all(
- treedata->tree, ray_start_local, ray_normal_local, 0.0f,
- *ray_depth, raycast_all_cb, &data);
-
- retval = data.retval;
- }
- else {
- BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
+ /* Warning: the depth_max is currently being used only in perspective view.
+ * It is not correct to limit the maximum depth for elements obtained with nearest
+ * since this limitation depends on the normal and the size of the occlusion face.
+ * And more... ray_depth is being confused with Z-depth here... (varies only the precision) */
+ const float ray_depth_max_global = *ray_depth + snapdata->depth_range[0];
- if (BLI_bvhtree_ray_cast(
- treedata->tree, ray_start_local, ray_normal_local, 0.0f,
- &hit, treedata->raycast_callback, treedata) != -1)
- {
- hit.dist += len_diff;
- hit.dist /= local_scale;
- if (hit.dist <= *ray_depth) {
- *ray_depth = hit.dist;
- copy_v3_v3(r_loc, hit.co);
-
- /* back to worldspace */
- mul_m4_v3(obmat, r_loc);
-
- if (r_no) {
- copy_v3_v3(r_no, hit.no);
- mul_m3_v3(timat, r_no);
- normalize_v3(r_no);
- }
+ Nearest2dUserData neasrest2d = {
+ .dist_px_sq = SQUARE(*dist_px),
+ .r_axis_closest = {1.0f, 1.0f, 1.0f},
+ .depth_range = {snapdata->depth_range[0], ray_depth_max_global},
+ .userdata = treedata,
+ .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_dm_edge_verts,
+ .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_dm_vert_no,
+ .index = -1};
- retval = true;
+ dist_squared_to_projected_aabb_precalc(
+ &neasrest2d.data_precalc, lpmat,
+ snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
+ ray_min_dist, snapdata->mval, ray_org_local, ray_normal_local);
- if (r_index) {
- *r_index = dm_looptri_to_poly_index(dm, &treedata->looptri[hit.index]);
- }
- }
- }
- }
- }
- /* SCE_SNAP_MODE_VERTEX or SCE_SNAP_MODE_EDGE */
- else {
+ BVHTree_WalkLeafCallback cb_walk_leaf =
+ (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
+ cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
- /* Warning: the depth_max is currently being used only in perspective view.
- * It is not correct to limit the maximum depth for elements obtained with nearest
- * since this limitation depends on the normal and the size of the occlusion face.
- * And more... ray_depth is being confused with Z-depth here... (varies only the precision) */
- const float ray_depth_max_global = *ray_depth + snapdata->depth_range[0];
-
- Nearest2dUserData neasrest2d = {
- .dist_px_sq = SQUARE(*dist_px),
- .r_axis_closest = {1.0f, 1.0f, 1.0f},
- .depth_range = {snapdata->depth_range[0], ray_depth_max_global},
- .userdata = treedata,
- .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_dm_edge_verts,
- .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_dm_vert_no,
- .index = -1};
-
- dist_squared_to_projected_aabb_precalc(
- &neasrest2d.data_precalc, lpmat,
- snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
- ray_min_dist, snapdata->mval, ray_org_local, ray_normal_local);
-
- BVHTree_WalkLeafCallback cb_walk_leaf =
- (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
- cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
-
- BLI_bvhtree_walk_dfs(
- treedata->tree,
- cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
-
- if (neasrest2d.index != -1) {
- copy_v3_v3(r_loc, neasrest2d.co);
- mul_m4_v3(obmat, r_loc);
- if (r_no) {
- copy_v3_v3(r_no, neasrest2d.no);
- mul_m3_v3(timat, r_no);
- normalize_v3(r_no);
- }
- *dist_px = sqrtf(neasrest2d.dist_px_sq);
- *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
+ BLI_bvhtree_walk_dfs(
+ treedata->tree,
+ cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
- retval = true;
+ if (neasrest2d.index != -1) {
+ copy_v3_v3(r_loc, neasrest2d.co);
+ mul_m4_v3(obmat, r_loc);
+ if (r_no) {
+ copy_v3_v3(r_no, neasrest2d.no);
+ mul_m3_v3(timat, r_no);
+ normalize_v3(r_no);
}
+ *dist_px = sqrtf(neasrest2d.dist_px_sq);
+ *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
+
+ retval = true;
}
return retval;
@@ -1335,20 +1749,14 @@ static bool snapDerivedMesh(
static bool snapEditMesh(
SnapObjectContext *sctx, SnapData *snapdata,
- Object *ob, BMEditMesh *em, float obmat[4][4], const unsigned int ob_index,
+ Object *ob, BMEditMesh *em, float obmat[4][4],
/* read/write args */
float *ray_depth, float *dist_px,
/* return args */
- float r_loc[3], float r_no[3], int *r_index,
- ListBase *r_hit_list)
+ float r_loc[3], float r_no[3])
{
bool retval = false;
- if (snapdata->snap_to == SCE_SNAP_MODE_FACE) {
- if (em->bm->totface == 0) {
- return retval;
- }
- }
if (snapdata->snap_to == SCE_SNAP_MODE_EDGE) {
if (em->bm->totedge == 0) {
return retval;
@@ -1373,13 +1781,8 @@ static bool snapEditMesh(
/* local scale in normal direction */
float local_scale = normalize_v3(ray_normal_local);
- float local_depth = *ray_depth;
- if (local_depth != BVH_RAYCAST_DIST_MAX) {
- local_depth *= local_scale;
- }
SnapObjectData_EditMesh *sod = NULL;
-
BVHTreeFromEditMesh *treedata = NULL;
void **sod_p;
@@ -1393,9 +1796,6 @@ static bool snapEditMesh(
int tree_index = -1;
switch (snapdata->snap_to) {
- case SCE_SNAP_MODE_FACE:
- tree_index = 2;
- break;
case SCE_SNAP_MODE_EDGE:
tree_index = 1;
break;
@@ -1410,197 +1810,90 @@ static bool snapEditMesh(
treedata = sod->bvh_trees[tree_index];
}
- if (treedata && treedata->tree == NULL) {
- BLI_bitmap *elem_mask = NULL;
- switch (snapdata->snap_to) {
- case SCE_SNAP_MODE_FACE:
- {
- int looptri_num_active = -1;
- if (sctx->callbacks.edit_mesh.test_face_fn) {
- elem_mask = BLI_BITMAP_NEW(em->tottri, __func__);
- looptri_num_active = BM_iter_mesh_bitmap_from_filter_tessface(
- em->bm, elem_mask,
- sctx->callbacks.edit_mesh.test_face_fn, sctx->callbacks.edit_mesh.user_data);
+ if (treedata) {
+ if (treedata->tree == NULL) {
+ BLI_bitmap *elem_mask = NULL;
+ switch (snapdata->snap_to) {
+ case SCE_SNAP_MODE_EDGE:
+ {
+ int edges_num_active = -1;
+ if (sctx->callbacks.edit_mesh.test_edge_fn) {
+ elem_mask = BLI_BITMAP_NEW(em->bm->totedge, __func__);
+ edges_num_active = BM_iter_mesh_bitmap_from_filter(
+ BM_EDGES_OF_MESH, em->bm, elem_mask,
+ (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_edge_fn,
+ sctx->callbacks.edit_mesh.user_data);
+ }
+ bvhtree_from_editmesh_edges_ex(treedata, em, elem_mask, edges_num_active, 0.0f, 2, 6);
+ break;
}
- bvhtree_from_editmesh_looptri_ex(treedata, em, elem_mask, looptri_num_active, 0.0f, 4, 6, NULL);
- break;
- }
- case SCE_SNAP_MODE_EDGE:
- {
- int edges_num_active = -1;
- if (sctx->callbacks.edit_mesh.test_edge_fn) {
- elem_mask = BLI_BITMAP_NEW(em->bm->totedge, __func__);
- edges_num_active = BM_iter_mesh_bitmap_from_filter(
- BM_EDGES_OF_MESH, em->bm, elem_mask,
- (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_edge_fn,
- sctx->callbacks.edit_mesh.user_data);
+ case SCE_SNAP_MODE_VERTEX:
+ {
+ int verts_num_active = -1;
+ if (sctx->callbacks.edit_mesh.test_vert_fn) {
+ elem_mask = BLI_BITMAP_NEW(em->bm->totvert, __func__);
+ verts_num_active = BM_iter_mesh_bitmap_from_filter(
+ BM_VERTS_OF_MESH, em->bm, elem_mask,
+ (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_vert_fn,
+ sctx->callbacks.edit_mesh.user_data);
+ }
+ bvhtree_from_editmesh_verts_ex(treedata, em, elem_mask, verts_num_active, 0.0f, 2, 6);
+ break;
}
- bvhtree_from_editmesh_edges_ex(treedata, em, elem_mask, edges_num_active, 0.0f, 2, 6);
- break;
}
- case SCE_SNAP_MODE_VERTEX:
- {
- int verts_num_active = -1;
- if (sctx->callbacks.edit_mesh.test_vert_fn) {
- elem_mask = BLI_BITMAP_NEW(em->bm->totvert, __func__);
- verts_num_active = BM_iter_mesh_bitmap_from_filter(
- BM_VERTS_OF_MESH, em->bm, elem_mask,
- (bool (*)(BMElem *, void *))sctx->callbacks.edit_mesh.test_vert_fn,
- sctx->callbacks.edit_mesh.user_data);
- }
- bvhtree_from_editmesh_verts_ex(treedata, em, elem_mask, verts_num_active, 0.0f, 2, 6);
- break;
+ if (elem_mask) {
+ MEM_freeN(elem_mask);
}
}
- if (elem_mask) {
- MEM_freeN(elem_mask);
+ if (treedata->tree == NULL) {
+ return retval;
}
}
-
- if (!treedata || !treedata->tree) {
+ else {
return retval;
}
- if (snapdata->snap_to == SCE_SNAP_MODE_FACE) {
- float ray_start_local[3];
- copy_v3_v3(ray_start_local, snapdata->ray_start);
- mul_m4_v3(imat, ray_start_local);
+ float ray_org_local[3];
+ copy_v3_v3(ray_org_local, snapdata->ray_origin);
+ mul_m4_v3(imat, ray_org_local);
- /* Only use closer ray_start in case of ortho view! In perspective one, ray_start
- * may already been *inside* boundbox, leading to snap failures (see T38409).
- * Note also ar might be null (see T38435), in this case we assume ray_start is ok!
- */
- float len_diff = 0.0f;
- if (snapdata->view_proj == VIEW_PROJ_ORTHO) { /* do_ray_start_correction */
- /* We *need* a reasonably valid len_diff in this case.
- * Use BHVTree to find the closest face from ray_start_local.
- */
- BVHTreeNearest nearest;
- nearest.index = -1;
- nearest.dist_sq = FLT_MAX;
- /* Compute and store result. */
- if (BLI_bvhtree_find_nearest(
- treedata->tree, ray_start_local, &nearest, NULL, NULL) != -1)
- {
- float dvec[3];
- sub_v3_v3v3(dvec, nearest.co, ray_start_local);
- len_diff = dot_v3v3(dvec, ray_normal_local);
- /* You need to make sure that ray_start is really far away,
- * because even in the Orthografic view, in some cases,
- * the ray can start inside the object (see T50486) */
- if (len_diff > 400.0f) {
- float ray_org_local[3];
-
- copy_v3_v3(ray_org_local, snapdata->ray_origin);
- mul_m4_v3(imat, ray_org_local);
-
- /* We pass a temp ray_start, set from object's boundbox,
- * to avoid precision issues with very far away ray_start values
- * (as returned in case of ortho view3d), see T38358.
- */
- len_diff -= local_scale; /* make temp start point a bit away from bbox hit point. */
- madd_v3_v3v3fl(
- ray_start_local, ray_org_local, ray_normal_local,
- len_diff + snapdata->depth_range[0] * local_scale);
- local_depth -= len_diff;
- }
- else len_diff = 0.0f;
- }
- }
- if (r_hit_list) {
- struct RayCastAll_Data data;
-
- data.bvhdata = treedata;
- data.raycast_callback = treedata->raycast_callback;
- data.obmat = obmat;
- data.timat = timat;
- data.len_diff = len_diff;
- data.local_scale = local_scale;
- data.ob = ob;
- data.ob_uuid = ob_index;
- data.hit_list = r_hit_list;
- data.retval = retval;
-
- BLI_bvhtree_ray_cast_all(
- treedata->tree, ray_start_local, ray_normal_local, 0.0f,
- *ray_depth, raycast_all_cb, &data);
-
- retval = data.retval;
- }
- else {
- BVHTreeRayHit hit = {.index = -1, .dist = local_depth};
+ Nearest2dUserData neasrest2d = {
+ .dist_px_sq = SQUARE(*dist_px),
+ .r_axis_closest = {1.0f, 1.0f, 1.0f},
+ .depth_range = {snapdata->depth_range[0], *ray_depth + snapdata->depth_range[0]},
+ .userdata = treedata,
+ .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_bedge_verts,
+ .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_bvert_no,
+ .index = -1};
- if (BLI_bvhtree_ray_cast(
- treedata->tree, ray_start_local, ray_normal_local, 0.0f,
- &hit, treedata->raycast_callback, treedata) != -1)
- {
- hit.dist += len_diff;
- hit.dist /= local_scale;
- if (hit.dist <= *ray_depth) {
- *ray_depth = hit.dist;
- copy_v3_v3(r_loc, hit.co);
-
- /* back to worldspace */
- mul_m4_v3(obmat, r_loc);
-
- if (r_no) {
- copy_v3_v3(r_no, hit.no);
- mul_m3_v3(timat, r_no);
- normalize_v3(r_no);
- }
+ float lpmat[4][4];
+ mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
+ dist_squared_to_projected_aabb_precalc(
+ &neasrest2d.data_precalc, lpmat,
+ snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
+ (snapdata->depth_range[0] * local_scale), snapdata->mval,
+ ray_org_local, ray_normal_local);
- retval = true;
+ BVHTree_WalkLeafCallback cb_walk_leaf =
+ (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
+ cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
- if (r_index) {
- *r_index = hit.index;
- }
- }
- }
- }
- }
- else {
- float ray_org_local[3];
- copy_v3_v3(ray_org_local, snapdata->ray_origin);
- mul_m4_v3(imat, ray_org_local);
-
- Nearest2dUserData neasrest2d = {
- .dist_px_sq = SQUARE(*dist_px),
- .r_axis_closest = {1.0f, 1.0f, 1.0f},
- .depth_range = {snapdata->depth_range[0], *ray_depth + snapdata->depth_range[0]},
- .userdata = treedata,
- .get_edge_verts = (Nearest2DGetEdgeVertsCallback)get_bedge_verts,
- .copy_vert_no = (Nearest2DCopyVertNoCallback)copy_bvert_no,
- .index = -1};
-
- float lpmat[4][4];
- mul_m4_m4m4(lpmat, snapdata->pmat, obmat);
- dist_squared_to_projected_aabb_precalc(
- &neasrest2d.data_precalc, lpmat,
- snapdata->view_proj == VIEW_PROJ_PERSP, snapdata->win_half,
- (snapdata->depth_range[0] * local_scale), snapdata->mval,
- ray_org_local, ray_normal_local);
-
- BVHTree_WalkLeafCallback cb_walk_leaf =
- (snapdata->snap_to == SCE_SNAP_MODE_VERTEX) ?
- cb_walk_leaf_snap_vert : cb_walk_leaf_snap_edge;
-
- BLI_bvhtree_walk_dfs(
- treedata->tree,
- cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
-
- if (neasrest2d.index != -1) {
- copy_v3_v3(r_loc, neasrest2d.co);
- mul_m4_v3(obmat, r_loc);
- if (r_no) {
- copy_v3_v3(r_no, neasrest2d.no);
- mul_m3_v3(timat, r_no);
- normalize_v3(r_no);
- }
- *dist_px = sqrtf(neasrest2d.dist_px_sq);
- *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
+ BLI_bvhtree_walk_dfs(
+ treedata->tree,
+ cb_walk_parent_snap_project, cb_walk_leaf, cb_nearest_walk_order, &neasrest2d);
- retval = true;
+ if (neasrest2d.index != -1) {
+ copy_v3_v3(r_loc, neasrest2d.co);
+ mul_m4_v3(obmat, r_loc);
+ if (r_no) {
+ copy_v3_v3(r_no, neasrest2d.no);
+ mul_m3_v3(timat, r_no);
+ normalize_v3(r_no);
}
+ *dist_px = sqrtf(neasrest2d.dist_px_sq);
+ *ray_depth = depth_get(r_loc, snapdata->ray_start, snapdata->ray_dir);
+
+ retval = true;
}
return retval;
@@ -1613,14 +1906,13 @@ static bool snapEditMesh(
*/
static bool snapObject(
SnapObjectContext *sctx, SnapData *snapdata,
- Object *ob, float obmat[4][4], const unsigned int ob_index,
+ Object *ob, float obmat[4][4],
bool use_obedit,
/* read/write args */
float *ray_depth, float *dist_px,
/* return args */
- float r_loc[3], float r_no[3], int *r_index,
- Object **r_ob, float r_obmat[4][4],
- ListBase *r_hit_list)
+ float r_loc[3], float r_no[3],
+ Object **r_ob, float r_obmat[4][4])
{
bool retval = false;
@@ -1630,10 +1922,9 @@ static bool snapObject(
if (use_obedit) {
em = BKE_editmesh_from_object(ob);
retval = snapEditMesh(
- sctx, snapdata, ob, em, obmat, ob_index,
+ sctx, snapdata, ob, em, obmat,
ray_depth, dist_px,
- r_loc, r_no, r_index,
- r_hit_list);
+ r_loc, r_no);
}
else {
/* in this case we want the mesh from the editmesh, avoids stale data. see: T45978.
@@ -1647,10 +1938,9 @@ static bool snapObject(
dm = mesh_get_derived_final(sctx->scene, ob, CD_MASK_BAREMESH);
}
retval = snapDerivedMesh(
- sctx, snapdata, ob, dm, obmat, ob_index,
+ sctx, snapdata, ob, dm, obmat,
ray_depth, dist_px,
- r_loc, r_no,
- r_index, r_hit_list);
+ r_loc, r_no);
dm->release(dm);
}
@@ -1695,6 +1985,34 @@ static bool snapObject(
return retval;
}
+
+struct SnapObjUserData {
+ SnapData *snapdata;
+ /* read/write args */
+ float *ray_depth;
+ float *dist_px;
+ /* return args */
+ float *r_loc;
+ float *r_no;
+ Object **r_ob;
+ float (*r_obmat)[4];
+ bool ret;
+};
+
+static void sanp_obj_cb(SnapObjectContext *sctx, bool is_obedit, Object *ob, float obmat[4][4], void *data)
+{
+ struct SnapObjUserData *dt = data;
+ dt->ret |= snapObject(
+ sctx, dt->snapdata,
+ ob, obmat, is_obedit,
+ /* read/write args */
+ dt->ray_depth, dt->dist_px,
+ /* return args */
+ dt->r_loc, dt->r_no,
+ dt->r_ob, dt->r_obmat);
+}
+
+
/**
* Main Snapping Function
* ======================
@@ -1703,8 +2021,8 @@ static bool snapObject(
*
* \param sctx: Snap context to store data.
* \param snapdata: struct generated in `get_snapdata`.
- * \param snap_select: from enum SnapSelect.
- * \param use_object_edit_cage: Uses the coordinates of BMesh (if any) to do the snapping.
+ * \param snap_select : from enum eSnapSelect.
+ * \param use_object_edit_cage : Uses the coordinates of BMesh(if any) to do the snapping.
*
* Read/Write Args
* ---------------
@@ -1721,96 +2039,38 @@ static bool snapObject(
* (currently only set to the polygon index when when using ``snap_to == SCE_SNAP_MODE_FACE``).
* \param r_ob: Hit object.
* \param r_obmat: Object matrix (may not be #Object.obmat with dupli-instances).
- * \param r_hit_list: List of #SnapObjectHitDepth (caller must free).
*
*/
static bool snapObjectsRay(
SnapObjectContext *sctx, SnapData *snapdata,
- const SnapSelect snap_select,
- const bool use_object_edit_cage,
+ const eSnapSelect snap_select, const bool use_object_edit_cage,
/* read/write args */
float *ray_depth, float *dist_px,
/* return args */
- float r_loc[3], float r_no[3], int *r_index,
- Object **r_ob, float r_obmat[4][4],
- ListBase *r_hit_list)
+ float r_loc[3], float r_no[3],
+ Object **r_ob, float r_obmat[4][4])
{
- bool retval = false;
-
- unsigned int ob_index = 0;
Object *obedit = use_object_edit_cage ? sctx->scene->obedit : NULL;
- /* Need an exception for particle edit because the base is flagged with BA_HAS_RECALC_DATA
- * which makes the loop skip it, even the derived mesh will never change
- *
- * To solve that problem, we do it first as an exception.
- * */
- Base *base_act = sctx->scene->basact;
- if (base_act && base_act->object && base_act->object->mode & OB_MODE_PARTICLE_EDIT) {
- Object *ob = base_act->object;
-
- retval |= snapObject(
- sctx, snapdata, ob, ob->obmat, ob_index++, false,
- ray_depth, dist_px,
- r_loc, r_no, r_index, r_ob, r_obmat, r_hit_list);
- }
-
- bool ignore_object_selected = false, ignore_object_active = false;
- switch (snap_select) {
- case SNAP_ALL:
- break;
- case SNAP_NOT_SELECTED:
- ignore_object_selected = true;
- break;
- case SNAP_NOT_ACTIVE:
- ignore_object_active = true;
- break;
- }
- for (Base *base = sctx->scene->base.first; base != NULL; base = base->next) {
- if ((BASE_VISIBLE_BGMODE(sctx->v3d_data.v3d, sctx->scene, base)) &&
- (base->flag & (BA_HAS_RECALC_OB | BA_HAS_RECALC_DATA)) == 0 &&
-
- !((ignore_object_selected && (base->flag & (SELECT | BA_WAS_SEL))) ||
- (ignore_object_active && base == base_act)))
- {
- Object *ob = base->object;
-
- if (ob->transflag & OB_DUPLI) {
- DupliObject *dupli_ob;
- ListBase *lb = object_duplilist(sctx->bmain->eval_ctx, sctx->scene, ob);
-
- for (dupli_ob = lb->first; dupli_ob; dupli_ob = dupli_ob->next) {
- bool use_obedit_dupli = (obedit && dupli_ob->ob->data == obedit->data);
- Object *dupli_snap = (use_obedit_dupli) ? obedit : dupli_ob->ob;
-
- retval |= snapObject(
- sctx, snapdata, dupli_snap, dupli_ob->mat,
- ob_index++, use_obedit_dupli,
- ray_depth, dist_px,
- r_loc, r_no, r_index, r_ob, r_obmat, r_hit_list);
- }
-
- free_object_duplilist(lb);
- }
+ struct SnapObjUserData data = {
+ .snapdata = snapdata,
+ .ray_depth = ray_depth,
+ .dist_px = dist_px,
+ .r_loc = r_loc,
+ .r_no = r_no,
+ .r_ob = r_ob,
+ .r_obmat = r_obmat,
+ .ret = false,
+ };
- bool use_obedit = (obedit != NULL) && (ob->data == obedit->data);
- Object *ob_snap = use_obedit ? obedit : ob;
+ iter_snap_objects(sctx, snap_select, obedit, sanp_obj_cb, &data);
- retval |= snapObject(
- sctx, snapdata, ob_snap, ob->obmat, ob_index++, use_obedit,
- ray_depth, dist_px,
- r_loc, r_no, r_index, r_ob, r_obmat, r_hit_list);
- }
- }
-
- return retval;
+ return data.ret;
}
/** \} */
-
/* -------------------------------------------------------------------- */
-
/** \name Public Object Snapping API
* \{ */
@@ -1855,6 +2115,9 @@ static void snap_object_data_free(void *sod_v)
free_bvhtree_from_mesh(sod->bvh_trees[i]);
}
}
+ if (sod->poly_allocated) {
+ MEM_freeN(sod->mpoly);
+ }
break;
}
case SNAP_EDIT_MESH:
@@ -1894,25 +2157,17 @@ void ED_transform_snap_object_context_set_editmesh_callbacks(
bool ED_transform_snap_object_project_ray_ex(
SnapObjectContext *sctx,
- const unsigned short snap_to,
const struct SnapObjectParams *params,
const float ray_start[3], const float ray_normal[3],
float *ray_depth,
float r_loc[3], float r_no[3], int *r_index,
Object **r_ob, float r_obmat[4][4])
{
- const float depth_range[2] = {0.0f, FLT_MAX};
-
- SnapData snapdata;
- snap_data_set(
- &snapdata, sctx->v3d_data.ar, snap_to, VIEW_PROJ_NONE,
- NULL, ray_start, ray_start, ray_normal, depth_range);
-
- return snapObjectsRay(
- sctx, &snapdata,
+ return raycastObjects(
+ sctx,
+ ray_start, ray_normal,
params->snap_select, params->use_object_edit_cage,
- ray_depth, NULL,
- r_loc, r_no, r_index, r_ob, r_obmat, NULL);
+ ray_depth, r_loc, r_no, r_index, r_ob, r_obmat, NULL);
}
/**
@@ -1924,13 +2179,11 @@ bool ED_transform_snap_object_project_ray_ex(
*/
bool ED_transform_snap_object_project_ray_all(
SnapObjectContext *sctx,
- const unsigned short snap_to,
const struct SnapObjectParams *params,
const float ray_start[3], const float ray_normal[3],
float ray_depth, bool sort,
ListBase *r_hit_list)
{
- const float depth_range[2] = {0.0f, FLT_MAX};
if (ray_depth == -1.0f) {
ray_depth = BVH_RAYCAST_DIST_MAX;
}
@@ -1939,15 +2192,11 @@ bool ED_transform_snap_object_project_ray_all(
float ray_depth_prev = ray_depth;
#endif
- SnapData snapdata;
- snap_data_set(&snapdata, sctx->v3d_data.ar, snap_to, VIEW_PROJ_NONE, NULL,
- ray_start, ray_start, ray_normal, depth_range);
-
- bool retval = snapObjectsRay(
- sctx, &snapdata,
+ bool retval = raycastObjects(
+ sctx,
+ ray_start, ray_normal,
params->snap_select, params->use_object_edit_cage,
- &ray_depth, NULL,
- NULL, NULL, NULL, NULL, NULL,
+ &ray_depth, NULL, NULL, NULL, NULL, NULL,
r_hit_list);
/* meant to be readonly for 'all' hits, ensure it is */
@@ -1980,7 +2229,6 @@ static bool transform_snap_context_project_ray_impl(
/* try snap edge, then face if it fails */
ret = ED_transform_snap_object_project_ray_ex(
sctx,
- SCE_SNAP_MODE_FACE,
params,
ray_start, ray_normal, ray_depth,
r_co, r_no, NULL,
@@ -2050,10 +2298,10 @@ static bool transform_snap_context_project_view3d_mixed_impl(
for (int i = 0; i < 3; i++) {
if (snap_to_flag & (1 << i)) {
if (ED_transform_snap_object_project_view3d(
- sctx,
- elem_type[i], params,
- mval, dist_px, &ray_depth,
- r_co, r_no))
+ sctx,
+ elem_type[i], params,
+ mval, dist_px, &ray_depth,
+ r_co, r_no))
{
is_hit = true;
break;
@@ -2126,16 +2374,24 @@ bool ED_transform_snap_object_project_view3d_ex(
ray_depth = &ray_depth_fallback;
}
- SnapData snapdata;
- const enum eViewProj view_proj = ((RegionView3D *)ar->regiondata)->is_persp ? VIEW_PROJ_PERSP : VIEW_PROJ_ORTHO;
- snap_data_set(&snapdata, ar, snap_to, view_proj, mval,
- ray_origin, ray_start, ray_normal, depth_range);
+ if (snap_to == SCE_SNAP_MODE_FACE) {
+ return raycastObjects(
+ sctx,
+ ray_start, ray_normal,
+ params->snap_select, params->use_object_edit_cage,
+ ray_depth, r_loc, r_no, r_index, NULL, NULL, NULL);
+ }
+ else {
+ SnapData snapdata;
+ const enum eViewProj view_proj = ((RegionView3D *)ar->regiondata)->is_persp ? VIEW_PROJ_PERSP : VIEW_PROJ_ORTHO;
+ snap_data_set(&snapdata, ar, snap_to, view_proj, mval,
+ ray_origin, ray_start, ray_normal, depth_range);
- return snapObjectsRay(
- sctx, &snapdata,
- params->snap_select, params->use_object_edit_cage,
- ray_depth, dist_px,
- r_loc, r_no, r_index, NULL, NULL, NULL);
+ return snapObjectsRay(
+ sctx, &snapdata,
+ params->snap_select, params->use_object_edit_cage,
+ ray_depth, dist_px, r_loc, r_no, NULL, NULL);
+ }
}
bool ED_transform_snap_object_project_view3d(
@@ -2176,7 +2432,6 @@ bool ED_transform_snap_object_project_all_view3d_ex(
return ED_transform_snap_object_project_ray_all(
sctx,
- SCE_SNAP_MODE_FACE,
params,
ray_start, ray_normal, ray_depth, sort,
r_hit_list);
diff --git a/source/blender/editors/undo/CMakeLists.txt b/source/blender/editors/undo/CMakeLists.txt
new file mode 100644
index 00000000000..89832604ed8
--- /dev/null
+++ b/source/blender/editors/undo/CMakeLists.txt
@@ -0,0 +1,45 @@
+# ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#
+# Contributor(s): Jacques Beaurain.
+#
+# ***** END GPL LICENSE BLOCK *****
+
+set(INC
+ ../include
+ ../../blenkernel
+ ../../blenlib
+ ../../blentranslation
+ ../../makesdna
+ ../../makesrna
+ ../../windowmanager
+ ../../../../intern/guardedalloc
+ ../../../../intern/clog
+)
+
+set(SRC
+ ed_undo.c
+ memfile_undo.c
+ undo_system_types.c
+
+ undo_intern.h
+)
+
+if(WITH_INTERNATIONAL)
+ add_definitions(-DWITH_INTERNATIONAL)
+endif()
+
+blender_add_lib(bf_editor_undo "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/editors/util/undo.c b/source/blender/editors/undo/ed_undo.c
index fab5b7e821f..d8b194e3336 100644
--- a/source/blender/editors/util/undo.c
+++ b/source/blender/editors/undo/ed_undo.c
@@ -25,17 +25,16 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/editors/util/undo.c
- * \ingroup edutil
+/** \file blender/editors/undo/ed_undo.c
+ * \ingroup edundo
*/
-#include <stdlib.h>
#include <string.h>
-#include <math.h>
#include "MEM_guardedalloc.h"
-#include "DNA_object_types.h"
+#include "CLG_log.h"
+
#include "DNA_scene_types.h"
#include "BLI_utildefines.h"
@@ -47,19 +46,12 @@
#include "BKE_global.h"
#include "BKE_main.h"
#include "BKE_screen.h"
+#include "BKE_undo_system.h"
-#include "ED_armature.h"
-#include "ED_particle.h"
-#include "ED_curve.h"
#include "ED_gpencil.h"
-#include "ED_mball.h"
-#include "ED_mesh.h"
-#include "ED_object.h"
#include "ED_render.h"
#include "ED_screen.h"
-#include "ED_paint.h"
-#include "ED_util.h"
-#include "ED_text.h"
+#include "ED_undo.h"
#include "WM_api.h"
#include "WM_types.h"
@@ -70,59 +62,50 @@
#include "UI_interface.h"
#include "UI_resources.h"
-#include "util_intern.h"
+/** We only need this locally. */
+static CLG_LogRef LOG = {"ed.undo"};
-/* ***************** generic undo system ********************* */
+/* -------------------------------------------------------------------- */
+/** \name Generic Undo System Access
+ *
+ * Non-operator undo editor functions.
+ * \{ */
void ED_undo_push(bContext *C, const char *str)
{
- Object *obedit = CTX_data_edit_object(C);
- Object *obact = CTX_data_active_object(C);
-
- if (G.debug & G_DEBUG)
- printf("%s: %s\n", __func__, str);
-
- if (obedit) {
- if (U.undosteps == 0) return;
-
- if (obedit->type == OB_MESH)
- undo_push_mesh(C, str);
- else if (ELEM(obedit->type, OB_CURVE, OB_SURF))
- undo_push_curve(C, str);
- else if (obedit->type == OB_FONT)
- undo_push_font(C, str);
- else if (obedit->type == OB_MBALL)
- undo_push_mball(C, str);
- else if (obedit->type == OB_LATTICE)
- undo_push_lattice(C, str);
- else if (obedit->type == OB_ARMATURE)
- undo_push_armature(C, str);
- }
- else if (obact && obact->mode & OB_MODE_PARTICLE_EDIT) {
- if (U.undosteps == 0) return;
+ CLOG_INFO(&LOG, 1, "name='%s'", str);
+
+ const int steps = U.undosteps;
- PE_undo_push(CTX_data_scene(C), str);
+ if (steps <= 0) {
+ return;
}
- else if (obact && obact->mode & OB_MODE_SCULPT) {
- /* do nothing for now */
+
+ wmWindowManager *wm = CTX_wm_manager(C);
+
+ /* Only apply limit if this is the last undo step. */
+ if (wm->undo_stack->step_active && (wm->undo_stack->step_active->next == NULL)) {
+ BKE_undosys_stack_limit_steps_and_memory(wm->undo_stack, steps - 1, 0);
}
- else {
- BKE_undo_write(C, str);
+
+ BKE_undosys_step_push(wm->undo_stack, C, str);
+
+ if (U.undomemory != 0) {
+ const size_t memory_limit = (size_t)U.undomemory * 1024 * 1024;
+ BKE_undosys_stack_limit_steps_and_memory(wm->undo_stack, 0, memory_limit);
}
- WM_file_tag_modified(C);
+ WM_file_tag_modified();
}
/* note: also check undo_history_exec() in bottom if you change notifiers */
static int ed_undo_step(bContext *C, int step, const char *undoname)
{
+ CLOG_INFO(&LOG, 1, "name='%s', step=%d", undoname, step);
wmWindowManager *wm = CTX_wm_manager(C);
wmWindow *win = CTX_wm_window(C);
- Main *bmain = CTX_data_main(C);
+ // Main *bmain = CTX_data_main(C);
Scene *scene = CTX_data_scene(C);
- Object *obedit = CTX_data_edit_object(C);
- Object *obact = CTX_data_active_object(C);
- ScrArea *sa = CTX_wm_area(C);
/* undo during jobs are running can easily lead to freeing data using by jobs,
* or they can just lead to freezing job in some other cases */
@@ -130,100 +113,45 @@ static int ed_undo_step(bContext *C, int step, const char *undoname)
return OPERATOR_CANCELLED;
}
+ /* TODO(campbell): undo_system: use undo system */
/* grease pencil can be can be used in plenty of spaces, so check it first */
if (ED_gpencil_session_active()) {
return ED_undo_gpencil_step(C, step, undoname);
}
- if (sa && (sa->spacetype == SPACE_IMAGE)) {
- SpaceImage *sima = (SpaceImage *)sa->spacedata.first;
-
- if ((obact && (obact->mode & OB_MODE_TEXTURE_PAINT)) || (sima->mode == SI_MODE_PAINT)) {
- if (!ED_undo_paint_step(C, UNDO_PAINT_IMAGE, step, undoname) && undoname) {
- if (U.uiflag & USER_GLOBALUNDO) {
- ED_viewport_render_kill_jobs(wm, bmain, true);
- BKE_undo_name(C, undoname);
- }
- }
-
- WM_event_add_notifier(C, NC_WINDOW, NULL);
- return OPERATOR_FINISHED;
+ /* Undo System */
+ {
+ if (undoname) {
+ UndoStep *step_data = BKE_undosys_step_find_by_name(wm->undo_stack, undoname);
+ BKE_undosys_step_undo_with_data(wm->undo_stack, C, step_data);
}
- }
-
- if (sa && (sa->spacetype == SPACE_TEXT)) {
- ED_text_undo_step(C, step);
- }
- else if (obedit) {
- if (OB_TYPE_SUPPORT_EDITMODE(obedit->type)) {
- if (undoname)
- undo_editmode_name(C, undoname);
- else
- undo_editmode_step(C, step);
-
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
- }
- }
- else {
- /* Note: we used to do a fall-through here where if the
- * mode-specific undo system had no more steps to undo (or
- * redo), the global undo would run.
- *
- * That was inconsistent with editmode, and also makes for
- * unecessarily tricky interaction with the other undo
- * systems. */
- if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) {
- ED_undo_paint_step(C, UNDO_PAINT_IMAGE, step, undoname);
- }
- else if (obact && obact->mode & OB_MODE_SCULPT) {
- ED_undo_paint_step(C, UNDO_PAINT_MESH, step, undoname);
- }
- else if (obact && obact->mode & OB_MODE_PARTICLE_EDIT) {
- if (step == 1)
- PE_undo(scene);
- else
- PE_redo(scene);
- }
- else if (U.uiflag & USER_GLOBALUNDO) {
- // note python defines not valid here anymore.
- //#ifdef WITH_PYTHON
- // XXX BPY_scripts_clear_pyobjects();
- //#endif
-
- /* for global undo/redo we should just clear the editmode stack */
- /* for example, texface stores image pointers */
- undo_editmode_clear();
-
- ED_viewport_render_kill_jobs(wm, bmain, true);
-
- if (undoname)
- BKE_undo_name(C, undoname);
- else
- BKE_undo_step(C, step);
-
- scene = CTX_data_scene(C);
-
- WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, scene);
+ else {
+ BKE_undosys_step_undo_compat_only(wm->undo_stack, C, step);
}
}
-
+
WM_event_add_notifier(C, NC_WINDOW, NULL);
WM_event_add_notifier(C, NC_WM | ND_UNDO, NULL);
if (win) {
win->addmousemove = true;
}
-
+
return OPERATOR_FINISHED;
}
void ED_undo_grouped_push(bContext *C, const char *str)
{
/* do nothing if previous undo task is the same as this one (or from the same undo group) */
- const char *last_undo = BKE_undo_get_name_last();
+ {
+ wmWindowManager *wm = CTX_wm_manager(C);
+ if (wm->undo_stack->steps.last) {
+ const UndoStep *us = wm->undo_stack->steps.last;
+ if (STREQ(str, us->name)) {
+ return;
+ }
+ }
- if (last_undo && STREQ(str, last_undo)) {
- return;
}
/* push as usual */
@@ -264,49 +192,29 @@ void ED_undo_pop_op(bContext *C, wmOperator *op)
/* name optionally, function used to check for operator redo panel */
bool ED_undo_is_valid(const bContext *C, const char *undoname)
{
- Object *obedit = CTX_data_edit_object(C);
- Object *obact = CTX_data_active_object(C);
- ScrArea *sa = CTX_wm_area(C);
-
- if (sa && sa->spacetype == SPACE_IMAGE) {
- SpaceImage *sima = (SpaceImage *)sa->spacedata.first;
-
- if ((obact && (obact->mode & OB_MODE_TEXTURE_PAINT)) || (sima->mode == SI_MODE_PAINT)) {
- return 1;
- }
- }
-
- if (sa && (sa->spacetype == SPACE_TEXT)) {
- return 1;
- }
- else if (obedit) {
- if (OB_TYPE_SUPPORT_EDITMODE(obedit->type)) {
- return undo_editmode_is_valid(undoname);
- }
- }
- else {
-
- /* if below tests fail, global undo gets executed */
-
- if (obact && obact->mode & OB_MODE_TEXTURE_PAINT) {
- if (ED_undo_paint_is_valid(UNDO_PAINT_IMAGE, undoname))
- return 1;
- }
- else if (obact && obact->mode & OB_MODE_SCULPT) {
- if (ED_undo_paint_is_valid(UNDO_PAINT_MESH, undoname))
- return 1;
- }
- else if (obact && obact->mode & OB_MODE_PARTICLE_EDIT) {
- return PE_undo_is_valid(CTX_data_scene(C));
- }
-
- if (U.uiflag & USER_GLOBALUNDO) {
- return BKE_undo_is_valid(undoname);
- }
- }
- return 0;
+ wmWindowManager *wm = CTX_wm_manager(C);
+ return BKE_undosys_stack_has_undo(wm->undo_stack, undoname);
}
+/**
+ * Ideally we wont access the stack directly,
+ * this is needed for modes which handle undo themselves (bypassing #ED_undo_push).
+ *
+ * Using global isn't great, this just avoids doing inline,
+ * causing 'BKE_global.h' & 'BKE_main.h' includes.
+ */
+UndoStack *ED_undo_stack_get(void)
+{
+ wmWindowManager *wm = G.main->wm.first;
+ return wm->undo_stack;
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Undo, Undo Push & Redo Operators
+ * \{ */
+
static int ed_undo_exec(bContext *C, wmOperator *UNUSED(op))
{
/* "last operator" should disappear, later we can tie this with undo stack nicer */
@@ -334,8 +242,12 @@ static int ed_undo_redo_exec(bContext *C, wmOperator *UNUSED(op))
return ret ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
-
-/* ********************** */
+static int ed_undo_redo_poll(bContext *C)
+{
+ wmOperator *last_op = WM_operator_last_redo(C);
+ return last_op && ED_operator_screenactive(C) &&
+ WM_operator_check_ui_enabled(C, last_op->type->name);
+}
void ED_OT_undo(wmOperatorType *ot)
{
@@ -343,7 +255,7 @@ void ED_OT_undo(wmOperatorType *ot)
ot->name = "Undo";
ot->description = "Undo previous action";
ot->idname = "ED_OT_undo";
-
+
/* api callbacks */
ot->exec = ed_undo_exec;
ot->poll = ED_operator_screenactive;
@@ -355,7 +267,7 @@ void ED_OT_undo_push(wmOperatorType *ot)
ot->name = "Undo Push";
ot->description = "Add an undo state (internal use only)";
ot->idname = "ED_OT_undo_push";
-
+
/* api callbacks */
ot->exec = ed_undo_push_exec;
@@ -370,7 +282,7 @@ void ED_OT_redo(wmOperatorType *ot)
ot->name = "Redo";
ot->description = "Redo previous action";
ot->idname = "ED_OT_redo";
-
+
/* api callbacks */
ot->exec = ed_redo_exec;
ot->poll = ED_operator_screenactive;
@@ -382,18 +294,25 @@ void ED_OT_undo_redo(wmOperatorType *ot)
ot->name = "Undo and Redo";
ot->description = "Undo and redo previous action";
ot->idname = "ED_OT_undo_redo";
-
+
/* api callbacks */
ot->exec = ed_undo_redo_exec;
- ot->poll = ED_operator_screenactive;
+ ot->poll = ed_undo_redo_poll;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Operator Repeat
+ * \{ */
+
/* ui callbacks should call this rather than calling WM_operator_repeat() themselves */
int ED_undo_operator_repeat(bContext *C, struct wmOperator *op)
{
int ret = 0;
if (op) {
+ CLOG_INFO(&LOG, 1, "idname='%s'", op->type->idname);
wmWindowManager *wm = CTX_wm_manager(C);
struct Scene *scene = CTX_data_scene(C);
@@ -419,6 +338,9 @@ int ED_undo_operator_repeat(bContext *C, struct wmOperator *op)
if (G.debug & G_DEBUG)
printf("redo_cb: operator redo %s\n", op->type->name);
+
+ WM_operator_free_all_after(wm, op);
+
ED_undo_pop_op(C, op);
if (op->type->check) {
@@ -451,9 +373,7 @@ int ED_undo_operator_repeat(bContext *C, struct wmOperator *op)
CTX_wm_region_set(C, ar);
}
else {
- if (G.debug & G_DEBUG) {
- printf("redo_cb: ED_undo_operator_repeat called with NULL 'op'\n");
- }
+ CLOG_WARN(&LOG, "called with NULL 'op'");
}
return ret;
@@ -470,114 +390,50 @@ void ED_undo_operator_repeat_cb_evt(bContext *C, void *arg_op, int UNUSED(arg_ev
ED_undo_operator_repeat(C, (wmOperator *)arg_op);
}
+/** \} */
-/* ************************** */
-
-enum {
- UNDOSYSTEM_GLOBAL = 1,
- UNDOSYSTEM_EDITMODE = 2,
- UNDOSYSTEM_PARTICLE = 3,
- UNDOSYSTEM_IMAPAINT = 4,
- UNDOSYSTEM_SCULPT = 5,
-};
-
-static int get_undo_system(bContext *C)
-{
- Object *obact = CTX_data_active_object(C);
- Object *obedit = CTX_data_edit_object(C);
- ScrArea *sa = CTX_wm_area(C);
-
- /* first check for editor undo */
- if (sa && (sa->spacetype == SPACE_IMAGE)) {
- SpaceImage *sima = (SpaceImage *)sa->spacedata.first;
-
- if ((obact && (obact->mode & OB_MODE_TEXTURE_PAINT)) || (sima->mode == SI_MODE_PAINT)) {
- if (!ED_undo_paint_empty(UNDO_PAINT_IMAGE))
- return UNDOSYSTEM_IMAPAINT;
- }
- }
- /* find out which undo system */
- if (obedit) {
- if (OB_TYPE_SUPPORT_EDITMODE(obedit->type)) {
- return UNDOSYSTEM_EDITMODE;
- }
- }
- else {
- if (obact) {
- if (obact->mode & OB_MODE_PARTICLE_EDIT)
- return UNDOSYSTEM_PARTICLE;
- else if (obact->mode & OB_MODE_TEXTURE_PAINT) {
- if (!ED_undo_paint_empty(UNDO_PAINT_IMAGE))
- return UNDOSYSTEM_IMAPAINT;
- }
- else if (obact->mode & OB_MODE_SCULPT) {
- if (!ED_undo_paint_empty(UNDO_PAINT_MESH))
- return UNDOSYSTEM_SCULPT;
- }
- }
- if (U.uiflag & USER_GLOBALUNDO)
- return UNDOSYSTEM_GLOBAL;
- }
-
- return 0;
-}
+/* -------------------------------------------------------------------- */
+/** \name Undo History Operator
+ * \{ */
/* create enum based on undo items */
-static EnumPropertyItem *rna_undo_itemf(bContext *C, int undosys, int *totitem)
+static const EnumPropertyItem *rna_undo_itemf(bContext *C, int *totitem)
{
EnumPropertyItem item_tmp = {0}, *item = NULL;
int i = 0;
- bool active;
-
- while (true) {
- const char *name = NULL;
-
- if (undosys == UNDOSYSTEM_PARTICLE) {
- name = PE_undo_get_name(CTX_data_scene(C), i, &active);
- }
- else if (undosys == UNDOSYSTEM_EDITMODE) {
- name = undo_editmode_get_name(C, i, &active);
- }
- else if (undosys == UNDOSYSTEM_IMAPAINT) {
- name = ED_undo_paint_get_name(C, UNDO_PAINT_IMAGE, i, &active);
- }
- else if (undosys == UNDOSYSTEM_SCULPT) {
- name = ED_undo_paint_get_name(C, UNDO_PAINT_MESH, i, &active);
- }
- else {
- name = BKE_undo_get_name(i, &active);
- }
-
- if (name) {
- item_tmp.identifier = name;
- /* XXX This won't work with non-default contexts (e.g. operators) :/ */
- item_tmp.name = IFACE_(name);
- if (active)
+
+ wmWindowManager *wm = CTX_wm_manager(C);
+ if (wm->undo_stack == NULL) {
+ return NULL;
+ }
+
+ for (UndoStep *us = wm->undo_stack->steps.first; us; us = us->next, i++) {
+ if (us->skip == false) {
+ item_tmp.identifier = us->name;
+ item_tmp.name = IFACE_(us->name);
+ if (us == wm->undo_stack->step_active) {
item_tmp.icon = ICON_RESTRICT_VIEW_OFF;
- else
+ }
+ else {
item_tmp.icon = ICON_NONE;
- item_tmp.value = i++;
+ }
+ item_tmp.value = i;
RNA_enum_item_add(&item, totitem, &item_tmp);
}
- else
- break;
}
-
RNA_enum_item_end(&item, totitem);
-
+
return item;
}
static int undo_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
- int undosys, totitem = 0;
-
- undosys = get_undo_system(C);
-
- if (undosys) {
- EnumPropertyItem *item = rna_undo_itemf(C, undosys, &totitem);
-
+ int totitem = 0;
+
+ {
+ const EnumPropertyItem *item = rna_undo_itemf(C, &totitem);
+
if (totitem > 0) {
uiPopupMenu *pup = UI_popup_menu_begin(C, RNA_struct_ui_name(op->type->srna), ICON_NONE);
uiLayout *layout = UI_popup_menu_layout(pup);
@@ -586,7 +442,7 @@ static int undo_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSE
const int col_size = 20 + totitem / 12;
int i, c;
bool add_col = true;
-
+
for (c = 0, i = totitem; i--;) {
if (add_col && !(c % col_size)) {
column = uiLayoutColumn(split, false);
@@ -598,12 +454,12 @@ static int undo_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSE
add_col = true;
}
}
-
- MEM_freeN(item);
-
+
+ MEM_freeN((void *)item);
+
UI_popup_menu_end(C, pup);
}
-
+
}
return OPERATOR_CANCELLED;
}
@@ -611,30 +467,12 @@ static int undo_history_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSE
/* note: also check ed_undo_step() in top if you change notifiers */
static int undo_history_exec(bContext *C, wmOperator *op)
{
- if (RNA_struct_property_is_set(op->ptr, "item")) {
- int undosys = get_undo_system(C);
- int item = RNA_int_get(op->ptr, "item");
-
- if (undosys == UNDOSYSTEM_PARTICLE) {
- PE_undo_number(CTX_data_scene(C), item);
- }
- else if (undosys == UNDOSYSTEM_EDITMODE) {
- undo_editmode_number(C, item + 1);
- WM_event_add_notifier(C, NC_GEOM | ND_DATA, NULL);
- }
- else if (undosys == UNDOSYSTEM_IMAPAINT) {
- ED_undo_paint_step_num(C, UNDO_PAINT_IMAGE, item);
- }
- else if (undosys == UNDOSYSTEM_SCULPT) {
- ED_undo_paint_step_num(C, UNDO_PAINT_MESH, item);
- }
- else {
- ED_viewport_render_kill_jobs(CTX_wm_manager(C), CTX_data_main(C), true);
- BKE_undo_number(C, item);
- WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, CTX_data_scene(C));
- }
+ PropertyRNA *prop = RNA_struct_find_property(op->ptr, "item");
+ if (RNA_property_is_set(op->ptr, prop)) {
+ int item = RNA_property_int_get(op->ptr, prop);
+ wmWindowManager *wm = CTX_wm_manager(C);
+ BKE_undosys_step_undo_from_index(wm->undo_stack, C, item);
WM_event_add_notifier(C, NC_WINDOW, NULL);
-
return OPERATOR_FINISHED;
}
return OPERATOR_CANCELLED;
@@ -646,14 +484,14 @@ void ED_OT_undo_history(wmOperatorType *ot)
ot->name = "Undo History";
ot->description = "Redo specific action in history";
ot->idname = "ED_OT_undo_history";
-
+
/* api callbacks */
ot->invoke = undo_history_invoke;
ot->exec = undo_history_exec;
ot->poll = ED_operator_screenactive;
-
+
RNA_def_int(ot->srna, "item", 0, 0, INT_MAX, "Item", "", 0, INT_MAX);
}
-
+/** \} */
diff --git a/source/blender/editors/undo/memfile_undo.c b/source/blender/editors/undo/memfile_undo.c
new file mode 100644
index 00000000000..bb81da74f88
--- /dev/null
+++ b/source/blender/editors/undo/memfile_undo.c
@@ -0,0 +1,150 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/undo/memfile_undo.c
+ * \ingroup edundo
+ *
+ * Wrapper between 'ED_undo.h' and 'BKE_undo_system.h' API's.
+ */
+
+#include "BLI_utildefines.h"
+#include "BLI_sys_types.h"
+
+#include "DNA_object_enums.h"
+
+#include "BKE_blender_undo.h"
+#include "BKE_context.h"
+#include "BKE_undo_system.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+#include "ED_object.h"
+#include "ED_undo.h"
+#include "ED_render.h"
+
+
+#include "../blenloader/BLO_undofile.h"
+
+#include "undo_intern.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Implements ED Undo System
+ * \{ */
+
+typedef struct MemFileUndoStep {
+ UndoStep step;
+ MemFileUndoData *data;
+} MemFileUndoStep;
+
+static bool memfile_undosys_poll(bContext *UNUSED(C))
+{
+ /* other poll functions must run first, this is a catch-all. */
+
+ if ((U.uiflag & USER_GLOBALUNDO) == 0) {
+ return false;
+ }
+ return true;
+}
+
+static bool memfile_undosys_step_encode(struct bContext *C, UndoStep *us_p)
+{
+ MemFileUndoStep *us = (MemFileUndoStep *)us_p;
+
+ /* Important we only use 'main' from the context (see: BKE_undosys_stack_init_from_main). */
+ struct Main *bmain = CTX_data_main(C);
+ UndoStack *ustack = ED_undo_stack_get();
+
+ /* can be NULL, use when set. */
+ MemFileUndoStep *us_prev = (MemFileUndoStep *)BKE_undosys_step_find_by_type(ustack, BKE_UNDOSYS_TYPE_MEMFILE);
+ us->data = BKE_memfile_undo_encode(bmain, us_prev ? us_prev->data : NULL);
+ us->step.data_size = us->data->undo_size;
+ return true;
+}
+
+static void memfile_undosys_step_decode(struct bContext *C, UndoStep *us_p, int UNUSED(dir))
+{
+ /* Loading the content will correctly switch into compatible non-object modes. */
+ ED_object_mode_set(C, OB_MODE_OBJECT);
+
+ /* This is needed so undoing/redoing doesn't crash with threaded previews going */
+ ED_viewport_render_kill_jobs(CTX_wm_manager(C), CTX_data_main(C), true);
+ MemFileUndoStep *us = (MemFileUndoStep *)us_p;
+ BKE_memfile_undo_decode(us->data, C);
+
+ WM_event_add_notifier(C, NC_SCENE | ND_LAYER_CONTENT, CTX_data_scene(C));
+}
+
+static void memfile_undosys_step_free(UndoStep *us_p)
+{
+ /* To avoid unnecessary slow down, free backwards (so we don't need to merge when clearing all). */
+ MemFileUndoStep *us = (MemFileUndoStep *)us_p;
+ if (us_p->next != NULL) {
+ UndoStep *us_next_p = BKE_undosys_step_same_type_next(us_p);
+ if (us_next_p != NULL) {
+ MemFileUndoStep *us_next = (MemFileUndoStep *)us_next_p;
+ BLO_memfile_merge(&us->data->memfile, &us_next->data->memfile);
+ }
+ }
+
+ BKE_memfile_undo_free(us->data);
+}
+
+/* Export for ED_undo_sys. */
+void ED_memfile_undosys_type(UndoType *ut)
+{
+ ut->name = "Global Undo";
+ ut->poll = memfile_undosys_poll;
+ ut->step_encode = memfile_undosys_step_encode;
+ ut->step_decode = memfile_undosys_step_decode;
+ ut->step_free = memfile_undosys_step_free;
+
+ ut->mode = BKE_UNDOTYPE_MODE_STORE;
+ ut->use_context = true;
+
+ ut->step_size = sizeof(MemFileUndoStep);
+}
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Utilities
+ * \{ */
+
+/**
+ * Ideally we wouldn't need to export global undo internals, there are some cases where it's needed though.
+ */
+static struct MemFile *ed_undosys_step_get_memfile(UndoStep *us_p)
+{
+ MemFileUndoStep *us = (MemFileUndoStep *)us_p;
+ return &us->data->memfile;
+}
+
+struct MemFile *ED_undosys_stack_memfile_get_active(UndoStack *ustack)
+{
+ UndoStep *us = BKE_undosys_stack_active_with_type(ustack, BKE_UNDOSYS_TYPE_MEMFILE);
+ if (us) {
+ return ed_undosys_step_get_memfile(us);
+ }
+ return NULL;
+}
+
+
+/** \} */
diff --git a/source/blender/editors/undo/undo_intern.h b/source/blender/editors/undo/undo_intern.h
new file mode 100644
index 00000000000..671f9637d65
--- /dev/null
+++ b/source/blender/editors/undo/undo_intern.h
@@ -0,0 +1,35 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/undo/undo_intern.h
+ * \ingroup edundo
+ */
+
+#ifndef __UNDO_INTERN_H__
+#define __UNDO_INTERN_H__
+
+/* internal exports only */
+
+struct UndoType;
+
+/* memfile_undo.c */
+void ED_memfile_undosys_type(struct UndoType *ut);
+
+#endif /* __UNDO_INTERN_H__ */
diff --git a/source/blender/editors/undo/undo_system_types.c b/source/blender/editors/undo/undo_system_types.c
new file mode 100644
index 00000000000..75c3d2cc1b7
--- /dev/null
+++ b/source/blender/editors/undo/undo_system_types.c
@@ -0,0 +1,74 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/editors/undo/undo_system_types.c
+ * \ingroup edundo
+ */
+
+#include <string.h>
+
+#include "BLI_utildefines.h"
+
+
+#include "ED_armature.h"
+#include "ED_curve.h"
+#include "ED_lattice.h"
+#include "ED_mball.h"
+#include "ED_mesh.h"
+#include "ED_paint.h"
+#include "ED_particle.h"
+#include "ED_sculpt.h"
+#include "ED_text.h"
+#include "ED_undo.h"
+#include "undo_intern.h"
+
+/* Keep last */
+#include "BKE_undo_system.h"
+
+void ED_undosys_type_init(void)
+{
+ /* Edit Modes */
+ BKE_undosys_type_append(ED_armature_undosys_type);
+ BKE_undosys_type_append(ED_curve_undosys_type);
+ BKE_undosys_type_append(ED_font_undosys_type);
+ BKE_undosys_type_append(ED_lattice_undosys_type);
+ BKE_undosys_type_append(ED_mball_undosys_type);
+ BKE_undosys_type_append(ED_mesh_undosys_type);
+
+ /* Paint Modes */
+ BKE_UNDOSYS_TYPE_IMAGE = BKE_undosys_type_append(ED_image_undosys_type);
+
+ BKE_UNDOSYS_TYPE_SCULPT = BKE_undosys_type_append(ED_sculpt_undosys_type);
+
+ BKE_UNDOSYS_TYPE_PARTICLE = BKE_undosys_type_append(ED_particle_undosys_type);
+
+ BKE_UNDOSYS_TYPE_PAINTCURVE = BKE_undosys_type_append(ED_paintcurve_undosys_type);
+
+ /* Text editor */
+ BKE_UNDOSYS_TYPE_TEXT = BKE_undosys_type_append(ED_text_undosys_type);
+
+ /* Keep global undo last (as a fallback). */
+ BKE_UNDOSYS_TYPE_MEMFILE = BKE_undosys_type_append(ED_memfile_undosys_type);
+}
+
+void ED_undosys_type_free(void)
+{
+ BKE_undosys_type_free_all();
+}
diff --git a/source/blender/editors/util/CMakeLists.txt b/source/blender/editors/util/CMakeLists.txt
index c0b30f93939..8657c876d47 100644
--- a/source/blender/editors/util/CMakeLists.txt
+++ b/source/blender/editors/util/CMakeLists.txt
@@ -30,6 +30,7 @@ set(INC
../../makesrna
../../windowmanager
../../../../intern/guardedalloc
+ ../../../../intern/clog
../../../../intern/glew-mx
)
@@ -40,11 +41,8 @@ set(INC_SYS
set(SRC
ed_transverts.c
ed_util.c
- editmode_undo.c
numinput.c
- undo.c
- util_intern.h
# general includes
../include/BIF_gl.h
../include/BIF_glutil.h
diff --git a/source/blender/editors/util/ed_transverts.c b/source/blender/editors/util/ed_transverts.c
index b0970cdfd48..c3fb653979c 100644
--- a/source/blender/editors/util/ed_transverts.c
+++ b/source/blender/editors/util/ed_transverts.c
@@ -153,7 +153,7 @@ void ED_transverts_update_obedit(TransVertStore *tvs, Object *obedit)
}
}
if (arm->flag & ARM_MIRROR_EDIT)
- transform_armature_mirror_update(obedit);
+ ED_armature_edit_transform_mirror_update(obedit);
}
else if (obedit->type == OB_LATTICE) {
Lattice *lt = obedit->data;
diff --git a/source/blender/editors/util/ed_util.c b/source/blender/editors/util/ed_util.c
index 1f1a778cac7..03d0b4a8d48 100644
--- a/source/blender/editors/util/ed_util.c
+++ b/source/blender/editors/util/ed_util.c
@@ -58,6 +58,7 @@
#include "BKE_packedFile.h"
#include "BKE_paint.h"
#include "BKE_screen.h"
+#include "BKE_undo_system.h"
#include "ED_armature.h"
#include "ED_buttons.h"
@@ -89,6 +90,10 @@ void ED_editors_init(bContext *C)
Object *ob, *obact = (sce && sce->basact) ? sce->basact->object : NULL;
ID *data;
+ if (wm->undo_stack == NULL) {
+ wm->undo_stack = BKE_undosys_stack_create();
+ }
+
/* This is called during initialization, so we don't want to store any reports */
ReportList *reports = CTX_wm_reports(C);
int reports_flag_prev = reports->flag & ~RPT_STORE;
@@ -105,8 +110,8 @@ void ED_editors_init(bContext *C)
ob->mode = OB_MODE_OBJECT;
data = ob->data;
- if (ob == obact && !ID_IS_LINKED_DATABLOCK(ob) && !(data && ID_IS_LINKED_DATABLOCK(data)))
- ED_object_toggle_modes(C, mode);
+ if (ob == obact && !ID_IS_LINKED(ob) && !(data && ID_IS_LINKED(data)))
+ ED_object_mode_toggle(C, mode);
}
}
@@ -128,9 +133,15 @@ void ED_editors_exit(bContext *C)
return;
/* frees all editmode undos */
- undo_editmode_clear();
- ED_undo_paint_free();
-
+ if (G.main->wm.first) {
+ wmWindowManager *wm = G.main->wm.first;
+ /* normally we don't check for NULL undo stack, do here since it may run in different context. */
+ if (wm->undo_stack) {
+ BKE_undosys_stack_destroy(wm->undo_stack);
+ wm->undo_stack = NULL;
+ }
+ }
+
for (sce = bmain->scene.first; sce; sce = sce->id.next) {
if (sce->obedit) {
Object *ob = sce->obedit;
@@ -169,18 +180,22 @@ bool ED_editors_flush_edits(const bContext *C, bool for_render)
* objects can exist at the same time */
for (ob = bmain->object.first; ob; ob = ob->id.next) {
if (ob->mode & OB_MODE_SCULPT) {
- /* flush multires changes (for sculpt) */
- multires_force_update(ob);
- has_edited = true;
-
- if (for_render) {
- /* flush changes from dynamic topology sculpt */
- BKE_sculptsession_bm_to_me_for_render(ob);
- }
- else {
- /* Set reorder=false so that saving the file doesn't reorder
- * the BMesh's elements */
- BKE_sculptsession_bm_to_me(ob, false);
+ /* Don't allow flushing while in the middle of a stroke (frees data in use).
+ * Auto-save prevents this from happening but scripts may cause a flush on saving: T53986. */
+ if ((ob->sculpt && ob->sculpt->cache) == 0) {
+ /* flush multires changes (for sculpt) */
+ multires_force_update(ob);
+ has_edited = true;
+
+ if (for_render) {
+ /* flush changes from dynamic topology sculpt */
+ BKE_sculptsession_bm_to_me_for_render(ob);
+ }
+ else {
+ /* Set reorder=false so that saving the file doesn't reorder
+ * the BMesh's elements */
+ BKE_sculptsession_bm_to_me(ob, false);
+ }
}
}
else if (ob->mode & OB_MODE_EDIT) {
@@ -226,8 +241,9 @@ void unpack_menu(bContext *C, const char *opname, const char *id_name, const cha
pup = UI_popup_menu_begin(C, IFACE_("Unpack File"), ICON_NONE);
layout = UI_popup_menu_layout(pup);
- props_ptr = uiItemFullO_ptr(layout, ot, IFACE_("Remove Pack"), ICON_NONE,
- NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(
+ layout, ot, IFACE_("Remove Pack"), ICON_NONE,
+ NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_REMOVE);
RNA_string_set(&props_ptr, "id", id_name);
@@ -240,7 +256,7 @@ void unpack_menu(bContext *C, const char *opname, const char *id_name, const cha
switch (checkPackedFile(local_name, pf)) {
case PF_NOFILE:
BLI_snprintf(line, sizeof(line), IFACE_("Create %s"), local_name);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_WRITE_LOCAL);
RNA_string_set(&props_ptr, "id", id_name);
@@ -248,7 +264,7 @@ void unpack_menu(bContext *C, const char *opname, const char *id_name, const cha
case PF_EQUAL:
BLI_snprintf(line, sizeof(line), IFACE_("Use %s (identical)"), local_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_USE_LOCAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_USE_LOCAL);
RNA_string_set(&props_ptr, "id", id_name);
@@ -256,13 +272,13 @@ void unpack_menu(bContext *C, const char *opname, const char *id_name, const cha
case PF_DIFFERS:
BLI_snprintf(line, sizeof(line), IFACE_("Use %s (differs)"), local_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_USE_LOCAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_USE_LOCAL);
RNA_string_set(&props_ptr, "id", id_name);
BLI_snprintf(line, sizeof(line), IFACE_("Overwrite %s"), local_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_WRITE_LOCAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_WRITE_LOCAL);
RNA_string_set(&props_ptr, "id", id_name);
break;
@@ -274,27 +290,27 @@ void unpack_menu(bContext *C, const char *opname, const char *id_name, const cha
case PF_NOFILE:
BLI_snprintf(line, sizeof(line), IFACE_("Create %s"), abs_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_WRITE_ORIGINAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_WRITE_ORIGINAL);
RNA_string_set(&props_ptr, "id", id_name);
break;
case PF_EQUAL:
BLI_snprintf(line, sizeof(line), IFACE_("Use %s (identical)"), abs_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_USE_ORIGINAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_USE_ORIGINAL);
RNA_string_set(&props_ptr, "id", id_name);
break;
case PF_DIFFERS:
BLI_snprintf(line, sizeof(line), IFACE_("Use %s (differs)"), abs_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_USE_ORIGINAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_USE_ORIGINAL);
RNA_string_set(&props_ptr, "id", id_name);
BLI_snprintf(line, sizeof(line), IFACE_("Overwrite %s"), abs_name);
//uiItemEnumO_ptr(layout, ot, line, 0, "method", PF_WRITE_ORIGINAL);
- props_ptr = uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, UI_ITEM_O_RETURN_PROPS);
+ uiItemFullO_ptr(layout, ot, line, ICON_NONE, NULL, WM_OP_EXEC_DEFAULT, 0, &props_ptr);
RNA_enum_set(&props_ptr, "method", PF_WRITE_ORIGINAL);
RNA_string_set(&props_ptr, "id", id_name);
break;
diff --git a/source/blender/editors/util/editmode_undo.c b/source/blender/editors/util/editmode_undo.c
deleted file mode 100644
index 441fd446cd6..00000000000
--- a/source/blender/editors/util/editmode_undo.c
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2004 Blender Foundation
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/editors/util/editmode_undo.c
- * \ingroup edutil
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-
-#include "MEM_guardedalloc.h"
-
-#include "DNA_object_types.h"
-
-#include "BLI_blenlib.h"
-#include "BLI_utildefines.h"
-
-#include "BKE_blender_undo.h"
-#include "BKE_context.h"
-#include "BKE_depsgraph.h"
-#include "BKE_global.h"
-
-#include "ED_util.h"
-#include "ED_mesh.h"
-
-
-#include "util_intern.h"
-
-/* ***************** generic editmode undo system ********************* */
-/*
- * Add this in your local code:
- *
- * void undo_editmode_push(bContext *C, const char *name,
- * void * (*getdata)(bContext *C), // use context to retrieve current editdata
- * void (*freedata)(void *), // pointer to function freeing data
- * void (*to_editmode)(void *, void *), // data to editmode conversion
- * void * (*from_editmode)(void *)) // editmode to data conversion
- * int (*validate_undo)(void *, void *)) // check if undo data is still valid
- *
- *
- * Further exported for UI is:
- *
- * void undo_editmode_step(bContext *C, int step); // undo and redo
- * void undo_editmode_clear(void) // free & clear all data
- * void undo_editmode_menu(void) // history menu
- */
-
-/* ********************************************************************* */
-
-/* ****** XXX ***** */
-static void error(const char *UNUSED(arg)) {}
-/* ****** XXX ***** */
-
-typedef struct UndoElem {
- struct UndoElem *next, *prev;
- ID id; // copy of editmode object ID
- Object *ob; // pointer to edited object
- int type; // type of edited object
- void *undodata;
- uintptr_t undosize;
- char name[BKE_UNDO_STR_MAX];
- void * (*getdata)(bContext * C);
- void (*freedata)(void *);
- void (*to_editmode)(void *, void *, void *);
- void * (*from_editmode)(void *, void *);
- int (*validate_undo)(void *, void *);
-} UndoElem;
-
-static ListBase undobase = {NULL, NULL};
-static UndoElem *curundo = NULL;
-
-
-/* ********************* xtern api calls ************* */
-
-static void undo_restore(UndoElem *undo, void *editdata, void *obdata)
-{
- if (undo) {
- undo->to_editmode(undo->undodata, editdata, obdata);
- }
-}
-
-/* name can be a dynamic string */
-void undo_editmode_push(bContext *C, const char *name,
- void * (*getdata)(bContext * C),
- void (*freedata)(void *),
- void (*to_editmode)(void *, void *, void *),
- void *(*from_editmode)(void *, void *),
- int (*validate_undo)(void *, void *))
-{
- UndoElem *uel;
- Object *obedit = CTX_data_edit_object(C);
- void *editdata;
- int nr;
- uintptr_t memused, totmem, maxmem;
-
- /* at first here was code to prevent an "original" key to be inserted twice
- * this was giving conflicts for example when mesh changed due to keys or apply */
-
- /* remove all undos after (also when curundo == NULL) */
- while (undobase.last != curundo) {
- uel = undobase.last;
- uel->freedata(uel->undodata);
- BLI_freelinkN(&undobase, uel);
- }
-
- /* make new */
- curundo = uel = MEM_callocN(sizeof(UndoElem), "undo editmode");
- BLI_strncpy(uel->name, name, sizeof(uel->name));
- BLI_addtail(&undobase, uel);
-
- uel->getdata = getdata;
- uel->freedata = freedata;
- uel->to_editmode = to_editmode;
- uel->from_editmode = from_editmode;
- uel->validate_undo = validate_undo;
-
- /* limit amount to the maximum amount*/
- nr = 0;
- uel = undobase.last;
- while (uel) {
- nr++;
- if (nr == U.undosteps) break;
- uel = uel->prev;
- }
- if (uel) {
- while (undobase.first != uel) {
- UndoElem *first = undobase.first;
- first->freedata(first->undodata);
- BLI_freelinkN(&undobase, first);
- }
- }
-
- /* copy */
- memused = MEM_get_memory_in_use();
- editdata = getdata(C);
- curundo->undodata = curundo->from_editmode(editdata, obedit->data);
- curundo->undosize = MEM_get_memory_in_use() - memused;
- curundo->ob = obedit;
- curundo->id = obedit->id;
- curundo->type = obedit->type;
-
- if (U.undomemory != 0) {
- /* limit to maximum memory (afterwards, we can't know in advance) */
- totmem = 0;
- maxmem = ((uintptr_t)U.undomemory) * 1024 * 1024;
-
- 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;
- first->freedata(first->undodata);
- BLI_freelinkN(&undobase, first);
- }
- }
- }
-}
-
-/* helper to remove clean other objects from undo stack */
-static void undo_clean_stack(bContext *C)
-{
- UndoElem *uel, *next;
- Object *obedit = CTX_data_edit_object(C);
-
- /* global undo changes pointers, so we also allow identical names */
- /* side effect: when deleting/renaming object and start editing new one with same name */
-
- uel = undobase.first;
- while (uel) {
- void *editdata = uel->getdata(C);
- bool is_valid = false;
- next = uel->next;
-
- /* for when objects are converted, renamed, or global undo changes pointers... */
- if (uel->type == obedit->type) {
- if (STREQ(uel->id.name, obedit->id.name)) {
- if (uel->validate_undo == NULL)
- is_valid = true;
- else if (uel->validate_undo(uel->undodata, editdata))
- is_valid = true;
- }
- }
- if (is_valid)
- uel->ob = obedit;
- else {
- if (uel == curundo)
- curundo = NULL;
-
- uel->freedata(uel->undodata);
- BLI_freelinkN(&undobase, uel);
- }
-
- uel = next;
- }
-
- if (curundo == NULL) curundo = undobase.last;
-}
-
-/* 1 = an undo, -1 is a redo. we have to make sure 'curundo' remains at current situation */
-void undo_editmode_step(bContext *C, int step)
-{
- Object *obedit = CTX_data_edit_object(C);
-
- /* prevent undo to happen on wrong object, stack can be a mix */
- undo_clean_stack(C);
-
- if (step == 0) {
- undo_restore(curundo, curundo->getdata(C), obedit->data);
- }
- else if (step == 1) {
-
- if (curundo == NULL || curundo->prev == NULL) {
- error("No more steps to undo");
- }
- else {
- if (G.debug & G_DEBUG) printf("undo %s\n", curundo->name);
- curundo = curundo->prev;
- undo_restore(curundo, curundo->getdata(C), obedit->data);
- }
- }
- else {
- /* curundo has to remain current situation! */
-
- if (curundo == NULL || curundo->next == NULL) {
- error("No more steps to redo");
- }
- else {
- undo_restore(curundo->next, curundo->getdata(C), obedit->data);
- curundo = curundo->next;
- if (G.debug & G_DEBUG) printf("redo %s\n", curundo->name);
- }
- }
-
- /* special case for editmesh, mode must be copied back to the scene */
- if (obedit->type == OB_MESH) {
- EDBM_selectmode_to_scene(C);
- }
-
- DAG_id_tag_update(&obedit->id, OB_RECALC_DATA);
-
- /* XXX notifiers */
-}
-
-void undo_editmode_clear(void)
-{
- UndoElem *uel;
-
- uel = undobase.first;
- while (uel) {
- uel->freedata(uel->undodata);
- uel = uel->next;
- }
- BLI_freelistN(&undobase);
- curundo = NULL;
-}
-
-/* based on index nr it does a restore */
-void undo_editmode_number(bContext *C, int nr)
-{
- UndoElem *uel;
- int a = 1;
-
- for (uel = undobase.first; uel; uel = uel->next, a++) {
- if (a == nr) break;
- }
- curundo = uel;
- undo_editmode_step(C, 0);
-}
-
-void undo_editmode_name(bContext *C, const char *undoname)
-{
- UndoElem *uel;
-
- for (uel = undobase.last; uel; uel = uel->prev) {
- if (STREQ(undoname, uel->name))
- break;
- }
- if (uel && uel->prev) {
- curundo = uel->prev;
- undo_editmode_step(C, 0);
- }
-}
-
-/* undoname optionally, if NULL it just checks for existing undo steps */
-bool undo_editmode_is_valid(const char *undoname)
-{
- if (undoname) {
- UndoElem *uel;
-
- for (uel = undobase.last; uel; uel = uel->prev) {
- if (STREQ(undoname, uel->name))
- break;
- }
- return uel != NULL;
- }
- return undobase.last != undobase.first;
-}
-
-
-/* get name of undo item, return null if no item with this index */
-/* if active pointer, set it to 1 if true */
-const char *undo_editmode_get_name(bContext *C, int nr, bool *r_active)
-{
- UndoElem *uel;
-
- /* prevent wrong numbers to be returned */
- undo_clean_stack(C);
-
- if (r_active) *r_active = false;
-
- uel = BLI_findlink(&undobase, nr);
- if (uel) {
- if (r_active && (uel == curundo)) {
- *r_active = true;
- }
- return uel->name;
- }
- return NULL;
-}
-
-
-void *undo_editmode_get_prev(Object *ob)
-{
- UndoElem *ue = undobase.last;
- if (ue && ue->prev && ue->prev->ob == ob) return ue->prev->undodata;
- return NULL;
-}
diff --git a/source/blender/editors/util/numinput.c b/source/blender/editors/util/numinput.c
index e07831358d6..a139f0e3c87 100644
--- a/source/blender/editors/util/numinput.c
+++ b/source/blender/editors/util/numinput.c
@@ -296,7 +296,7 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
}
/* Else, common behavior with DELKEY, only difference is remove char(s) before/after the cursor. */
dir = STRCUR_DIR_PREV;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case DELKEY:
if ((n->val_flag[idx] & NUM_EDITED) && n->str[0]) {
int t_cur = cur = n->str_cur;
@@ -322,7 +322,7 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
break;
case LEFTARROWKEY:
dir = STRCUR_DIR_PREV;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case RIGHTARROWKEY:
cur = n->str_cur;
if (event->ctrl) {
@@ -478,9 +478,9 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
/* At this point, our value has changed, try to interpret it with python (if str is not empty!). */
if (n->str[0]) {
const float val_prev = n->val[idx];
+ double val;
#ifdef WITH_PYTHON
Scene *sce = CTX_data_scene(C);
- double val;
char str_unit_convert[NUM_STR_REP_LEN * 6]; /* Should be more than enough! */
const char *default_unit = NULL;
@@ -488,8 +488,9 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
const float fac = (float)BKE_scene_unit_scale(&sce->unit, n->unit_type[idx], 1.0);
/* Make radian default unit when needed. */
- if (n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION)
+ if (n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION) {
default_unit = "r";
+ }
BLI_strncpy(str_unit_convert, n->str, sizeof(str_unit_convert));
@@ -497,7 +498,7 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
n->unit_sys, n->unit_type[idx]);
/* Note: with angles, we always get values as radians here... */
- if (BPY_execute_string_as_number(C, str_unit_convert, &val, false)) {
+ if (BPY_execute_string_as_number(C, str_unit_convert, false, &val)) {
n->val[idx] = (float)val;
n->val_flag[idx] &= ~NUM_INVALID;
}
@@ -505,15 +506,25 @@ bool handleNumInput(bContext *C, NumInput *n, const wmEvent *event)
n->val_flag[idx] |= NUM_INVALID;
}
#else /* Very unlikely, but does not harm... */
- n->val[idx] = (float)atof(n->str);
- (void)C;
+ val = atof(n->str);
+ n->val[idx] = (float)val;
+ UNUSED_VARS(C);
#endif /* WITH_PYTHON */
if (n->val_flag[idx] & NUM_NEGATE) {
n->val[idx] = -n->val[idx];
}
if (n->val_flag[idx] & NUM_INVERSE) {
- n->val[idx] = 1.0f / n->val[idx];
+ val = n->val[idx];
+ /* If we invert on radians when user is in degrees, you get unexpected results... See T53463. */
+ if (!n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION) {
+ val = RAD2DEG(val);
+ }
+ val = 1.0 / val;
+ if (!n->unit_use_radians && n->unit_type[idx] == B_UNIT_ROTATION) {
+ val = DEG2RAD(val);
+ }
+ n->val[idx] = (float)val;
}
if (UNLIKELY(!isfinite(n->val[idx]))) {
diff --git a/source/blender/editors/uvedit/uvedit_draw.c b/source/blender/editors/uvedit/uvedit_draw.c
index 5c5e84ee5f0..7b793697077 100644
--- a/source/blender/editors/uvedit/uvedit_draw.c
+++ b/source/blender/editors/uvedit/uvedit_draw.c
@@ -201,7 +201,7 @@ static void draw_uvs_stretch(SpaceImage *sima, Scene *scene, BMEditMesh *em, MTe
uv_poly_copy_aspect(tf_uvorig, tf_uv, aspx, aspy, efa->len);
totarea += BM_face_calc_area(efa);
- totuvarea += area_poly_v2((const float (*)[2])tf_uv, efa->len);
+ totuvarea += area_poly_v2(tf_uv, efa->len);
if (uvedit_face_visible_test(scene, ima, efa, tf)) {
BM_elem_flag_enable(efa, BM_ELEM_TAG);
@@ -244,7 +244,7 @@ static void draw_uvs_stretch(SpaceImage *sima, Scene *scene, BMEditMesh *em, MTe
uv_poly_copy_aspect(tf_uvorig, tf_uv, aspx, aspy, efa->len);
- uvarea = area_poly_v2((const float (*)[2])tf_uv, efa->len) / totuvarea;
+ uvarea = area_poly_v2(tf_uv, efa->len) / totuvarea;
if (area < FLT_EPSILON || uvarea < FLT_EPSILON)
areadiff = 1.0f;
@@ -502,7 +502,7 @@ static void draw_uvs_texpaint(SpaceImage *sima, Scene *scene, Object *ob)
ma = give_current_material(ob, ob->actcol);
- if (me->mtpoly) {
+ if (me->mloopuv) {
MPoly *mpoly = me->mpoly;
MLoopUV *mloopuv, *mloopuv_base;
int a, b;
@@ -570,7 +570,7 @@ static void draw_uvs(SpaceImage *sima, Scene *scene, Object *obedit)
const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
const int cd_poly_tex_offset = CustomData_get_offset(&bm->pdata, CD_MTEXPOLY);
- activetf = EDBM_mtexpoly_active_get(em, &efa_act, false, false); /* will be set to NULL if hidden */
+ efa_act = EDBM_uv_active_face_get(em, false, false, &activetf); /* will be set to NULL if hidden */
#ifndef USE_EDBM_LOOPTRIS
activef = BM_mesh_active_face_get(bm, false, false);
#endif
@@ -967,7 +967,7 @@ static void draw_uv_shadows_get(SpaceImage *sima, Object *ob, Object *obedit, bo
if ((sima->mode == SI_MODE_PAINT) && obedit && obedit->type == OB_MESH) {
struct BMEditMesh *em = BKE_editmesh_from_object(obedit);
- *show_shadow = EDBM_mtexpoly_check(em);
+ *show_shadow = EDBM_uv_check(em);
}
*show_texpaint = (ob && ob->type == OB_MESH && ob->mode == OB_MODE_TEXTURE_PAINT);
diff --git a/source/blender/editors/uvedit/uvedit_intern.h b/source/blender/editors/uvedit/uvedit_intern.h
index e028c08091c..b5ff46e9219 100644
--- a/source/blender/editors/uvedit/uvedit_intern.h
+++ b/source/blender/editors/uvedit/uvedit_intern.h
@@ -51,18 +51,31 @@ void uv_poly_center(struct BMFace *f, float r_cent[2], const int cd_loop_uv_off
/* find nearest */
-typedef struct NearestHit {
+typedef struct UvNearestHit {
+ /** Always set if we have a hit. */
struct BMFace *efa;
struct MTexPoly *tf;
struct BMLoop *l;
struct MLoopUV *luv, *luv_next;
- int lindex; /* index of loop within face */
-} NearestHit;
+ /** Index of loop within face. */
+ int lindex;
+ /** Needs to be set before calling nearest functions. */
+ float dist_sq;
+} UvNearestHit;
-void uv_find_nearest_vert(struct Scene *scene, struct Image *ima, struct BMEditMesh *em,
- const float co[2], const float penalty[2], struct NearestHit *hit);
-void uv_find_nearest_edge(struct Scene *scene, struct Image *ima, struct BMEditMesh *em,
- const float co[2], struct NearestHit *hit);
+#define UV_NEAREST_HIT_INIT { .dist_sq = FLT_MAX, }
+
+bool uv_find_nearest_vert(
+ struct Scene *scene, struct Image *ima, struct BMEditMesh *em,
+ const float co[2], const float penalty_dist, struct UvNearestHit *hit_final);
+
+bool uv_find_nearest_edge(
+ struct Scene *scene, struct Image *ima, struct BMEditMesh *em,
+ const float co[2], struct UvNearestHit *hit_final);
+
+bool uv_find_nearest_face(
+ struct Scene *scene, struct Image *ima, struct BMEditMesh *em,
+ const float co[2], struct UvNearestHit *hit_final);
/* utility tool functions */
diff --git a/source/blender/editors/uvedit/uvedit_ops.c b/source/blender/editors/uvedit/uvedit_ops.c
index c7b292d1458..1df410c5878 100644
--- a/source/blender/editors/uvedit/uvedit_ops.c
+++ b/source/blender/editors/uvedit/uvedit_ops.c
@@ -29,7 +29,6 @@
* \ingroup eduv
*/
-
#include <stdlib.h>
#include <string.h>
#include <math.h>
@@ -49,7 +48,7 @@
#include "BLI_utildefines.h"
#include "BLI_alloca.h"
#include "BLI_math.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BLI_blenlib.h"
#include "BLI_array.h"
@@ -92,7 +91,9 @@ static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int
static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object *obedit, const bool select);
-/************************* state testing ************************/
+/* -------------------------------------------------------------------- */
+/** \name State Testing
+ * \{ */
bool ED_uvedit_test(Object *obedit)
{
@@ -106,7 +107,7 @@ bool ED_uvedit_test(Object *obedit)
return 0;
em = BKE_editmesh_from_object(obedit);
- ret = EDBM_mtexpoly_check(em);
+ ret = EDBM_uv_check(em);
return ret;
}
@@ -133,15 +134,21 @@ static int UNUSED_FUNCTION(ED_operator_uvmap_mesh) (bContext *C)
return 0;
}
-/**************************** object active image *****************************/
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Object Active Image
+ * \{ */
static bool is_image_texture_node(bNode *node)
{
return ELEM(node->type, SH_NODE_TEX_IMAGE, SH_NODE_TEX_ENVIRONMENT);
}
-bool ED_object_get_active_image(Object *ob, int mat_nr,
- Image **r_ima, ImageUser **r_iuser, bNode **r_node, bNodeTree **r_ntree)
+bool ED_object_get_active_image(
+ Object *ob, int mat_nr,
+ Image **r_ima, ImageUser **r_iuser, bNode **r_node, bNodeTree **r_ntree)
{
Material *ma = give_current_material(ob, mat_nr);
bNodeTree *ntree = (ma && ma->use_nodes) ? ma->nodetree : NULL;
@@ -174,7 +181,11 @@ void ED_object_assign_active_image(Main *bmain, Object *ob, int mat_nr, Image *i
}
}
-/************************* assign image ************************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Assign Image
+ * \{ */
//#define USE_SWITCH_ASPECT
@@ -225,7 +236,7 @@ void ED_uvedit_assign_image(Main *UNUSED(bmain), Scene *scene, Object *obedit, I
BM_data_layer_add(em->bm, &em->bm->pdata, CD_MTEXPOLY);
BM_data_layer_add(em->bm, &em->bm->ldata, CD_MLOOPUV);
/* make UVs all nice 0-1 */
- ED_mesh_uv_loop_reset_ex(obedit->data, CustomData_get_active_layer_index(&em->bm->pdata, CD_MTEXPOLY));
+ ED_mesh_uv_loop_reset_ex(obedit->data, CustomData_get_active_layer(&em->bm->pdata, CD_MTEXPOLY));
update = true;
}
@@ -316,7 +327,11 @@ static bool uvedit_set_tile(Object *obedit, Image *ima, int curtile)
return true;
}
-/*********************** space conversion *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Space Conversion
+ * \{ */
static void uvedit_pixel_to_float(SpaceImage *sima, float *dist, float pixeldist)
{
@@ -334,7 +349,26 @@ static void uvedit_pixel_to_float(SpaceImage *sima, float *dist, float pixeldist
dist[1] = pixeldist / height;
}
-/*************** visibility and selection utilities **************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Visibility and Selection Utilities
+ * \{ */
+
+static void uvedit_vertex_select_tagged(BMEditMesh *em, Scene *scene, bool select, int cd_loop_uv_offset)
+{
+ BMFace *efa;
+ BMLoop *l;
+ BMIter iter, liter;
+
+ BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
+ BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
+ if (BM_elem_flag_test(l->v, BM_ELEM_TAG)) {
+ uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
+ }
+ }
+ }
+}
bool uvedit_face_visible_nolocal(Scene *scene, BMFace *efa)
{
@@ -356,8 +390,9 @@ bool uvedit_face_visible_test(Scene *scene, Image *ima, BMFace *efa, MTexPoly *t
return uvedit_face_visible_nolocal(scene, efa);
}
-bool uvedit_face_select_test(Scene *scene, BMFace *efa,
- const int cd_loop_uv_offset)
+bool uvedit_face_select_test(
+ Scene *scene, BMFace *efa,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
if (ts->uv_flag & UV_SYNC_SELECTION) {
@@ -378,8 +413,9 @@ bool uvedit_face_select_test(Scene *scene, BMFace *efa,
}
}
-bool uvedit_face_select_set(struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
- const bool do_history, const int cd_loop_uv_offset)
+bool uvedit_face_select_set(
+ struct Scene *scene, struct BMEditMesh *em, struct BMFace *efa, const bool select,
+ const bool do_history, const int cd_loop_uv_offset)
{
if (select) {
return uvedit_face_select_enable(scene, em, efa, do_history, cd_loop_uv_offset);
@@ -389,8 +425,9 @@ bool uvedit_face_select_set(struct Scene *scene, struct BMEditMesh *em, struct B
}
}
-bool uvedit_face_select_enable(Scene *scene, BMEditMesh *em, BMFace *efa, const bool do_history,
- const int cd_loop_uv_offset)
+bool uvedit_face_select_enable(
+ Scene *scene, BMEditMesh *em, BMFace *efa, const bool do_history,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -416,8 +453,9 @@ bool uvedit_face_select_enable(Scene *scene, BMEditMesh *em, BMFace *efa, const
return false;
}
-bool uvedit_face_select_disable(Scene *scene, BMEditMesh *em, BMFace *efa,
- const int cd_loop_uv_offset)
+bool uvedit_face_select_disable(
+ Scene *scene, BMEditMesh *em, BMFace *efa,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -440,8 +478,9 @@ bool uvedit_face_select_disable(Scene *scene, BMEditMesh *em, BMFace *efa,
return false;
}
-bool uvedit_edge_select_test(Scene *scene, BMLoop *l,
- const int cd_loop_uv_offset)
+bool uvedit_edge_select_test(
+ Scene *scene, BMLoop *l,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -467,8 +506,9 @@ bool uvedit_edge_select_test(Scene *scene, BMLoop *l,
}
}
-void uvedit_edge_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
- const bool do_history, const int cd_loop_uv_offset)
+void uvedit_edge_select_set(
+ BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
+ const bool do_history, const int cd_loop_uv_offset)
{
if (select) {
@@ -479,8 +519,9 @@ void uvedit_edge_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool
}
}
-void uvedit_edge_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l, const bool do_history,
- const int cd_loop_uv_offset)
+void uvedit_edge_select_enable(
+ BMEditMesh *em, Scene *scene, BMLoop *l, const bool do_history,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -510,8 +551,9 @@ void uvedit_edge_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l, const bo
}
}
-void uvedit_edge_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
- const int cd_loop_uv_offset)
+void uvedit_edge_select_disable(
+ BMEditMesh *em, Scene *scene, BMLoop *l,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -537,8 +579,9 @@ void uvedit_edge_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
}
}
-bool uvedit_uv_select_test(Scene *scene, BMLoop *l,
- const int cd_loop_uv_offset)
+bool uvedit_uv_select_test(
+ Scene *scene, BMLoop *l,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -554,8 +597,9 @@ bool uvedit_uv_select_test(Scene *scene, BMLoop *l,
}
}
-void uvedit_uv_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
- const bool do_history, const int cd_loop_uv_offset)
+void uvedit_uv_select_set(
+ BMEditMesh *em, Scene *scene, BMLoop *l, const bool select,
+ const bool do_history, const int cd_loop_uv_offset)
{
if (select) {
uvedit_uv_select_enable(em, scene, l, do_history, cd_loop_uv_offset);
@@ -565,8 +609,9 @@ void uvedit_uv_select_set(BMEditMesh *em, Scene *scene, BMLoop *l, const bool se
}
}
-void uvedit_uv_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l,
- const bool do_history, const int cd_loop_uv_offset)
+void uvedit_uv_select_enable(
+ BMEditMesh *em, Scene *scene, BMLoop *l,
+ const bool do_history, const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -586,8 +631,9 @@ void uvedit_uv_select_enable(BMEditMesh *em, Scene *scene, BMLoop *l,
}
}
-void uvedit_uv_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
- const int cd_loop_uv_offset)
+void uvedit_uv_select_disable(
+ BMEditMesh *em, Scene *scene, BMLoop *l,
+ const int cd_loop_uv_offset)
{
ToolSettings *ts = scene->toolsettings;
@@ -603,7 +649,11 @@ void uvedit_uv_select_disable(BMEditMesh *em, Scene *scene, BMLoop *l,
}
}
-/*********************** live unwrap utilities ***********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Live Unwrap Utilities
+ * \{ */
void uvedit_live_unwrap_update(SpaceImage *sima, Scene *scene, Object *obedit)
{
@@ -614,7 +664,12 @@ void uvedit_live_unwrap_update(SpaceImage *sima, Scene *scene, Object *obedit)
}
}
-/*********************** geometric utilities ***********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Geometric Utilities
+ * \{ */
+
void uv_poly_center(BMFace *f, float r_cent[2], const int cd_loop_uv_offset)
{
BMLoop *l;
@@ -743,89 +798,104 @@ static bool uvedit_center(Scene *scene, Image *ima, Object *obedit, float cent[2
return changed;
}
-/************************** find nearest ****************************/
+/** \} */
-void uv_find_nearest_edge(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
+/* -------------------------------------------------------------------- */
+/** \name Find Nearest Elements
+ * \{ */
+
+bool uv_find_nearest_edge(
+ Scene *scene, Image *ima, BMEditMesh *em, const float co[2],
+ UvNearestHit *hit)
{
MTexPoly *tf;
BMFace *efa;
BMLoop *l;
BMIter iter, liter;
MLoopUV *luv, *luv_next;
- float mindist_squared, dist_squared;
int i;
+ bool found = false;
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
- mindist_squared = 1e10f;
- memset(hit, 0, sizeof(*hit));
-
BM_mesh_elem_index_ensure(em->bm, BM_VERT);
-
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
- if (!uvedit_face_visible_test(scene, ima, efa, tf))
+ if (!uvedit_face_visible_test(scene, ima, efa, tf)) {
continue;
-
+ }
BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
- dist_squared = dist_squared_to_line_segment_v2(co, luv->uv, luv_next->uv);
+ const float dist_test_sq = dist_squared_to_line_segment_v2(co, luv->uv, luv_next->uv);
- if (dist_squared < mindist_squared) {
+ if (dist_test_sq < hit->dist_sq) {
hit->tf = tf;
hit->efa = efa;
-
+
hit->l = l;
hit->luv = luv;
hit->luv_next = luv_next;
hit->lindex = i;
- mindist_squared = dist_squared;
+ hit->dist_sq = dist_test_sq;
+ found = true;
}
}
}
+ return found;
}
-static void uv_find_nearest_face(Scene *scene, Image *ima, BMEditMesh *em, const float co[2], NearestHit *hit)
+bool uv_find_nearest_face(
+ Scene *scene, Image *ima, BMEditMesh *em, const float co[2],
+ UvNearestHit *hit_final)
{
- MTexPoly *tf;
- BMFace *efa;
- BMIter iter;
- float mindist, dist, cent[2];
+ bool found = false;
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
- mindist = 1e10f;
- memset(hit, 0, sizeof(*hit));
+ /* this will fill in hit.vert1 and hit.vert2 */
+ float dist_sq_init = hit_final->dist_sq;
+ UvNearestHit hit = *hit_final;
+ if (uv_find_nearest_edge(scene, ima, em, co, &hit)) {
+ hit.dist_sq = dist_sq_init;
+ hit.l = NULL;
+ hit.luv = hit.luv_next = NULL;
- /*this will fill in hit.vert1 and hit.vert2*/
- uv_find_nearest_edge(scene, ima, em, co, hit);
- hit->l = NULL;
- hit->luv = hit->luv_next = NULL;
+ BMIter iter;
+ BMFace *efa;
- BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
- tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
- if (!uvedit_face_visible_test(scene, ima, efa, tf))
- continue;
+ BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
+ MTexPoly *tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
+ if (!uvedit_face_visible_test(scene, ima, efa, tf)) {
+ continue;
+ }
- uv_poly_center(efa, cent, cd_loop_uv_offset);
+ float cent[2];
+ uv_poly_center(efa, cent, cd_loop_uv_offset);
- dist = len_manhattan_v2v2(co, cent);
+ const float dist_test_sq = len_squared_v2v2(co, cent);
- if (dist < mindist) {
- hit->tf = tf;
- hit->efa = efa;
- mindist = dist;
+ if (dist_test_sq < hit.dist_sq) {
+ hit.efa = efa;
+ hit.dist_sq = dist_test_sq;
+ found = true;
+ }
}
}
+ if (found) {
+ *hit_final = hit;
+ }
+ return found;
}
-static bool uv_nearest_between(const BMLoop *l, const float co[2],
- const int cd_loop_uv_offset)
+static bool uv_nearest_between(
+ const BMLoop *l, const float co[2],
+ const int cd_loop_uv_offset)
{
const float *uv_prev = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l->prev, cd_loop_uv_offset))->uv;
const float *uv_curr = ((MLoopUV *)BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset))->uv;
@@ -835,60 +905,74 @@ static bool uv_nearest_between(const BMLoop *l, const float co[2],
(line_point_side_v2(uv_next, uv_curr, co) <= 0.0f));
}
-void uv_find_nearest_vert(Scene *scene, Image *ima, BMEditMesh *em,
- float const co[2], const float penalty[2], NearestHit *hit)
+bool uv_find_nearest_vert(
+ Scene *scene, Image *ima, BMEditMesh *em,
+ float const co[2], const float penalty_dist, UvNearestHit *hit_final)
{
- BMFace *efa;
- BMLoop *l;
- BMIter iter, liter;
- MTexPoly *tf;
- MLoopUV *luv;
- float mindist, dist;
- int i;
+ bool found = false;
- const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
- const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
+ /* this will fill in hit.vert1 and hit.vert2 */
+ float dist_sq_init = hit_final->dist_sq;
+ UvNearestHit hit = *hit_final;
+ if (uv_find_nearest_edge(scene, ima, em, co, &hit)) {
+ hit.dist_sq = dist_sq_init;
- /*this will fill in hit.vert1 and hit.vert2*/
- uv_find_nearest_edge(scene, ima, em, co, hit);
- hit->l = NULL;
- hit->luv = hit->luv_next = NULL;
+ hit.l = NULL;
+ hit.luv = hit.luv_next = NULL;
- mindist = 1e10f;
- memset(hit, 0, sizeof(*hit));
-
- BM_mesh_elem_index_ensure(em->bm, BM_VERT);
+ BMFace *efa;
+ BMIter iter;
- BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
- tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
- if (!uvedit_face_visible_test(scene, ima, efa, tf))
- continue;
+ BM_mesh_elem_index_ensure(em->bm, BM_VERT);
- BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
- luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- if (penalty && uvedit_uv_select_test(scene, l, cd_loop_uv_offset))
- dist = len_manhattan_v2v2(co, luv->uv) + len_manhattan_v2(penalty);
- else
- dist = len_manhattan_v2v2(co, luv->uv);
+ const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
+ const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
- if (dist <= mindist) {
- if (dist == mindist) {
- if (!uv_nearest_between(l, co, cd_loop_uv_offset)) {
- continue;
- }
+ BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
+ MTexPoly *tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
+ if (!uvedit_face_visible_test(scene, ima, efa, tf)) {
+ continue;
+ }
+
+ BMIter liter;
+ BMLoop *l;
+ int i;
+ BM_ITER_ELEM_INDEX (l, &liter, efa, BM_LOOPS_OF_FACE, i) {
+ float dist_test_sq;
+ MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
+ if (penalty_dist != 0.0f && uvedit_uv_select_test(scene, l, cd_loop_uv_offset)) {
+ dist_test_sq = len_v2v2(co, luv->uv) + penalty_dist;
+ dist_test_sq = SQUARE(dist_test_sq);
+ }
+ else {
+ dist_test_sq = len_squared_v2v2(co, luv->uv);
}
- mindist = dist;
+ if (dist_test_sq <= hit.dist_sq) {
+ if (dist_test_sq == hit.dist_sq) {
+ if (!uv_nearest_between(l, co, cd_loop_uv_offset)) {
+ continue;
+ }
+ }
- hit->l = l;
- hit->luv = luv;
- hit->luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
- hit->tf = tf;
- hit->efa = efa;
- hit->lindex = i;
+ hit.dist_sq = dist_test_sq;
+
+ hit.l = l;
+ hit.luv = luv;
+ hit.luv_next = BM_ELEM_CD_GET_VOID_P(l->next, cd_loop_uv_offset);
+ hit.efa = efa;
+ hit.lindex = i;
+ found = true;
+ }
}
}
}
+
+ if (found) {
+ *hit_final = hit;
+ }
+
+ return found;
}
bool ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, const float co[2], float r_uv[2])
@@ -929,7 +1013,11 @@ bool ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, const float
return found;
}
-/*********************** loop select ***********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Loop Select
+ * \{ */
static void uv_select_edgeloop_vertex_loop_flag(UvMapVert *first)
{
@@ -1014,8 +1102,9 @@ static bool uv_select_edgeloop_edge_tag_faces(BMEditMesh *em, UvMapVert *first1,
return true;
}
-static int uv_select_edgeloop(Scene *scene, Image *ima, BMEditMesh *em, NearestHit *hit,
- const float limit[2], const bool extend)
+static int uv_select_edgeloop(
+ Scene *scene, Image *ima, BMEditMesh *em, UvNearestHit *hit,
+ const float limit[2], const bool extend)
{
BMFace *efa;
BMIter iter, liter;
@@ -1116,14 +1205,19 @@ static int uv_select_edgeloop(Scene *scene, Image *ima, BMEditMesh *em, NearestH
return (select) ? 1 : -1;
}
-/*********************** linked select ***********************/
+/** \} */
-static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const float limit[2], NearestHit *hit, bool extend, bool select_faces)
+/* -------------------------------------------------------------------- */
+/** \name Select Linked
+ * \{ */
+
+static void uv_select_linked(
+ Scene *scene, Image *ima, BMEditMesh *em, const float limit[2], UvNearestHit *hit_final,
+ bool extend, bool deselect, bool toggle, bool select_faces)
{
BMFace *efa;
BMLoop *l;
BMIter iter, liter;
- MTexPoly *tf;
MLoopUV *luv;
UvVertMap *vmap;
UvMapVert *vlist, *iterv, *startv;
@@ -1136,8 +1230,13 @@ static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const flo
BM_mesh_elem_table_ensure(em->bm, BM_FACE); /* we can use this too */
- /* use winding so we don't consider overlapping islands as connected, see T44320 */
- vmap = BM_uv_vert_map_create(em->bm, limit, !select_faces, true);
+ /* Note, we had 'use winding' so we don't consider overlapping islands as connected, see T44320
+ * this made *every* projection split the island into front/back islands.
+ * Keep 'use_winding' to false, see: T50970.
+ *
+ * Better solve this by having a delimit option for select-linked operator,
+ * keeping island-select working as is. */
+ vmap = BM_uv_vert_map_create(em->bm, limit, !select_faces, false);
if (vmap == NULL)
return;
@@ -1145,9 +1244,10 @@ static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const flo
stack = MEM_mallocN(sizeof(*stack) * (em->bm->totface + 1), "UvLinkStack");
flag = MEM_callocN(sizeof(*flag) * em->bm->totface, "UvLinkFlag");
- if (!hit) {
+ if (hit_final == NULL) {
+ /* Use existing selection */
BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
- tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
+ MTexPoly *tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
if (uvedit_face_visible_test(scene, ima, efa, tf)) {
if (select_faces) {
@@ -1175,7 +1275,7 @@ static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const flo
}
else {
BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
- if (efa == hit->efa) {
+ if (efa == hit_final->efa) {
stack[stacksize] = a;
stacksize++;
flag[a] = 1;
@@ -1217,89 +1317,65 @@ static void uv_select_linked(Scene *scene, Image *ima, BMEditMesh *em, const flo
}
}
- if (!extend) {
- BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
- if (select_faces) {
- if (flag[a])
- BM_face_select_set(em->bm, efa, true);
- else
- BM_face_select_set(em->bm, efa, false);
- }
- else {
- BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
-
- if (flag[a])
- luv->flag |= MLOOPUV_VERTSEL;
- else
- luv->flag &= ~MLOOPUV_VERTSEL;
- }
- }
- }
- }
- else {
+ /* Toggling - if any of the linked vertices is selected (and visible), we deselect. */
+ if ((toggle == true) && (extend == false) && (deselect == false)) {
BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
+ bool found_selected = false;
if (!flag[a]) {
continue;
}
if (select_faces) {
- if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN))
- break;
+ if (BM_elem_flag_test(efa, BM_ELEM_SELECT) && !BM_elem_flag_test(efa, BM_ELEM_HIDDEN)) {
+ found_selected = true;
+ }
}
else {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
if (luv->flag & MLOOPUV_VERTSEL) {
- break;
+ found_selected = true;
}
}
- if (l) {
+ if (found_selected) {
+ deselect = true;
break;
}
}
}
+ }
- if (efa) {
- BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
- if (!flag[a]) {
- continue;
- }
-
- if (select_faces) {
- BM_face_select_set(em->bm, efa, false);
- }
- else {
- BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
-
- luv->flag &= ~MLOOPUV_VERTSEL;
- }
- }
+#define SET_SELECTION(value) \
+ if (select_faces) { \
+ BM_face_select_set(em->bm, efa, value); \
+ } \
+ else { \
+ BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) { \
+ luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset); \
+ luv->flag = (value) ? (luv->flag | MLOOPUV_VERTSEL) : (luv->flag & ~MLOOPUV_VERTSEL); \
+ } \
+ } (void)0
+
+ BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
+ if (!flag[a]) {
+ if (!extend && !deselect && !toggle) {
+ SET_SELECTION(false);
}
+ continue;
}
- else {
- BM_ITER_MESH_INDEX (efa, &iter, em->bm, BM_FACES_OF_MESH, a) {
- if (!flag[a]) {
- continue;
- }
-
- if (select_faces) {
- BM_face_select_set(em->bm, efa, true);
- }
- else {
- BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
- }
- }
- }
+ if (!deselect) {
+ SET_SELECTION(true);
+ }
+ else {
+ SET_SELECTION(false);
}
}
-
+
+#undef SET_SELECTION
+
MEM_freeN(stack);
MEM_freeN(flag);
BM_uv_vert_map_free(vmap);
@@ -1330,6 +1406,12 @@ static float *uv_sel_co_from_eve(Scene *scene, Image *ima, BMEditMesh *em, BMVer
return NULL;
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select More/Less Operator
+ * \{ */
+
static int uv_select_more_less(bContext *C, const bool select)
{
Scene *scene = CTX_data_scene(C);
@@ -1361,9 +1443,7 @@ static int uv_select_more_less(bContext *C, const bool select)
if (ts->uv_selectmode == UV_SELECT_FACE) {
/* clear tags */
- BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
- BM_elem_flag_disable(efa, BM_ELEM_TAG);
- }
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_FACE, BM_ELEM_TAG, false);
/* mark loops to be selected */
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
@@ -1472,7 +1552,11 @@ static void UV_OT_select_less(wmOperatorType *ot)
ot->poll = ED_operator_uvedit_space_image;
}
-/* ******************** align operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Weld Align Operator
+ * \{ */
static void uv_weld_align(bContext *C, int tool)
{
@@ -1565,9 +1649,7 @@ static void uv_weld_align(bContext *C, int tool)
BMIter iter, liter, eiter;
/* clear tag */
- BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
- BM_elem_flag_disable(eve, BM_ELEM_TAG);
- }
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
/* tag verts with a selected UV */
BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
@@ -1586,8 +1668,10 @@ static void uv_weld_align(bContext *C, int tool)
/* flush vertex tags to edges */
BM_ITER_MESH (eed, &iter, em->bm, BM_EDGES_OF_MESH) {
- BM_elem_flag_set(eed, BM_ELEM_TAG, (BM_elem_flag_test(eed->v1, BM_ELEM_TAG) &&
- BM_elem_flag_test(eed->v2, BM_ELEM_TAG)));
+ BM_elem_flag_set(
+ eed, BM_ELEM_TAG,
+ (BM_elem_flag_test(eed->v1, BM_ELEM_TAG) &&
+ BM_elem_flag_test(eed->v2, BM_ELEM_TAG)));
}
/* find a vertex with only one tagged edge */
@@ -1638,11 +1722,11 @@ static void uv_weld_align(bContext *C, int tool)
}
/* now we have all verts, make into a line */
- if (BLI_array_count(eve_line) > 2) {
+ if (BLI_array_len(eve_line) > 2) {
/* we know the returns from these must be valid */
const float *uv_start = uv_sel_co_from_eve(scene, ima, em, eve_line[0]);
- const float *uv_end = uv_sel_co_from_eve(scene, ima, em, eve_line[BLI_array_count(eve_line) - 1]);
+ const float *uv_end = uv_sel_co_from_eve(scene, ima, em, eve_line[BLI_array_len(eve_line) - 1]);
/* For t & u modes */
float a = 0.0f;
@@ -1660,7 +1744,7 @@ static void uv_weld_align(bContext *C, int tool)
}
/* go over all verts except for endpoints */
- for (i = 0; i < BLI_array_count(eve_line); i++) {
+ for (i = 0; i < BLI_array_len(eve_line); i++) {
BM_ITER_ELEM (l, &liter, eve_line[i], BM_LOOPS_OF_VERT) {
tf = BM_ELEM_CD_GET_VOID_P(l->f, cd_poly_tex_offset);
@@ -1711,7 +1795,7 @@ static int uv_align_exec(bContext *C, wmOperator *op)
static void UV_OT_align(wmOperatorType *ot)
{
- static EnumPropertyItem axis_items[] = {
+ static const EnumPropertyItem axis_items[] = {
{'s', "ALIGN_S", 0, "Straighten", "Align UVs along the line defined by the endpoints"},
{'t', "ALIGN_T", 0, "Straighten X", "Align UVs along the line defined by the endpoints along the X axis"},
{'u', "ALIGN_U", 0, "Straighten Y", "Align UVs along the line defined by the endpoints along the Y axis"},
@@ -1733,7 +1817,12 @@ static void UV_OT_align(wmOperatorType *ot)
/* properties */
RNA_def_enum(ot->srna, "axis", axis_items, 'a', "Axis", "Axis to align UV locations on");
}
-/* ******************** weld near operator **************** */
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Remove Doubles Operator
+ * \{ */
typedef struct UVvert {
MLoopUV *uv_loop;
@@ -1773,7 +1862,7 @@ static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
MLoopUV **loop_arr = NULL;
BLI_array_declare(loop_arr);
- /* TODO, use qsort as with MESH_OT_remove_doubles, this isn't optimal */
+ /* TODO, use kd-tree as with MESH_OT_remove_doubles, this isn't optimal */
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
if (!uvedit_face_visible_test(scene, ima, efa, tf))
@@ -1791,12 +1880,12 @@ static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
}
}
- for (uv_a_index = 0; uv_a_index < BLI_array_count(vert_arr); uv_a_index++) {
+ for (uv_a_index = 0; uv_a_index < BLI_array_len(vert_arr); uv_a_index++) {
if (vert_arr[uv_a_index].weld == false) {
float uv_min[2];
float uv_max[2];
- BLI_array_empty(loop_arr);
+ BLI_array_clear(loop_arr);
BLI_array_append(loop_arr, vert_arr[uv_a_index].uv_loop);
uv_a = vert_arr[uv_a_index].uv_loop->uv;
@@ -1805,7 +1894,7 @@ static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
copy_v2_v2(uv_min, uv_a);
vert_arr[uv_a_index].weld = true;
- for (uv_b_index = uv_a_index + 1; uv_b_index < BLI_array_count(vert_arr); uv_b_index++) {
+ for (uv_b_index = uv_a_index + 1; uv_b_index < BLI_array_len(vert_arr); uv_b_index++) {
uv_b = vert_arr[uv_b_index].uv_loop->uv;
if ((vert_arr[uv_b_index].weld == false) &&
(len_manhattan_v2v2(uv_a, uv_b) < threshold))
@@ -1815,10 +1904,10 @@ static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
vert_arr[uv_b_index].weld = true;
}
}
- if (BLI_array_count(loop_arr)) {
+ if (BLI_array_len(loop_arr)) {
float uv_mid[2];
mid_v2_v2v2(uv_mid, uv_min, uv_max);
- for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr); uv_b_index++) {
+ for (uv_b_index = 0; uv_b_index < BLI_array_len(loop_arr); uv_b_index++) {
copy_v2_v2(loop_arr[uv_b_index]->uv, uv_mid);
}
}
@@ -1853,12 +1942,12 @@ static int uv_remove_doubles_exec(bContext *C, wmOperator *op)
}
}
- for (uv_a_index = 0; uv_a_index < BLI_array_count(loop_arr); uv_a_index++) {
+ for (uv_a_index = 0; uv_a_index < BLI_array_len(loop_arr); uv_a_index++) {
float dist_best = FLT_MAX, dist;
const float *uv_best = NULL;
uv_a = loop_arr[uv_a_index]->uv;
- for (uv_b_index = 0; uv_b_index < BLI_array_count(loop_arr_unselected); uv_b_index++) {
+ for (uv_b_index = 0; uv_b_index < BLI_array_len(loop_arr_unselected); uv_b_index++) {
uv_b = loop_arr_unselected[uv_b_index]->uv;
dist = len_manhattan_v2v2(uv_a, uv_b);
if ((dist < threshold) && (dist < dist_best)) {
@@ -1898,7 +1987,12 @@ static void UV_OT_remove_doubles(wmOperatorType *ot)
"Merge Distance", "Maximum distance between welded vertices", 0.0f, 1.0f);
RNA_def_boolean(ot->srna, "use_unselected", 0, "Unselected", "Merge selected to other unselected vertices");
}
-/* ******************** weld operator **************** */
+
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Weld Near Operator
+ * \{ */
static int uv_weld_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -1920,8 +2014,11 @@ static void UV_OT_weld(wmOperatorType *ot)
ot->poll = ED_operator_uvedit;
}
+/** \} */
-/* ******************** (de)select all operator **************** */
+/* -------------------------------------------------------------------- */
+/** \name (De)Select All Operator
+ * \{ */
static void uv_select_all_perform(Scene *scene, Image *ima, BMEditMesh *em, int action)
{
@@ -2030,9 +2127,13 @@ static void UV_OT_select_all(wmOperatorType *ot)
WM_operator_properties_select_all(ot);
}
-/* ******************** mouse select operator **************** */
+/** \} */
-static bool uv_sticky_select(float *limit, int hitv[4], int v, float *hituv[4], float *uv, int sticky, int hitlen)
+/* -------------------------------------------------------------------- */
+/** \name Mouse Select Operator
+ * \{ */
+
+static bool uv_sticky_select(float *limit, int hitv[], int v, float *hituv[], float *uv, int sticky, int hitlen)
{
int i;
@@ -2068,12 +2169,11 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
BMIter iter, liter;
MTexPoly *tf;
MLoopUV *luv;
- NearestHit hit;
+ UvNearestHit hit = UV_NEAREST_HIT_INIT;
int i, selectmode, sticky, sync, *hitv = NULL;
bool select = true;
int flush = 0, hitlen = 0; /* 0 == don't flush, 1 == sel, -1 == desel; only use when selection sync is enabled */
float limit[2], **hituv = NULL;
- float penalty[2];
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
@@ -2084,8 +2184,13 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
* shift-selecting can consider an adjacent point close enough to add to
* the selection rather than de-selecting the closest. */
- uvedit_pixel_to_float(sima, limit, 0.05f);
- uvedit_pixel_to_float(sima, penalty, 5.0f / (sima ? sima->zoom : 1.0f));
+ float penalty_dist;
+ {
+ float penalty[2];
+ uvedit_pixel_to_float(sima, limit, 0.05f);
+ uvedit_pixel_to_float(sima, penalty, 5.0f / (sima ? sima->zoom : 1.0f));
+ penalty_dist = len_v2(penalty);
+ }
/* retrieve operation mode */
if (ts->uv_flag & UV_SYNC_SELECTION) {
@@ -2109,8 +2214,7 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
/* find nearest element */
if (loop) {
/* find edge */
- uv_find_nearest_edge(scene, ima, em, co, &hit);
- if (hit.efa == NULL) {
+ if (!uv_find_nearest_edge(scene, ima, em, co, &hit)) {
return OPERATOR_CANCELLED;
}
@@ -2118,8 +2222,7 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
}
else if (selectmode == UV_SELECT_VERTEX) {
/* find vertex */
- uv_find_nearest_vert(scene, ima, em, co, penalty, &hit);
- if (hit.efa == NULL) {
+ if (!uv_find_nearest_vert(scene, ima, em, co, penalty_dist, &hit)) {
return OPERATOR_CANCELLED;
}
@@ -2135,8 +2238,7 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
}
else if (selectmode == UV_SELECT_EDGE) {
/* find edge */
- uv_find_nearest_edge(scene, ima, em, co, &hit);
- if (hit.efa == NULL) {
+ if (!uv_find_nearest_edge(scene, ima, em, co, &hit)) {
return OPERATOR_CANCELLED;
}
@@ -2154,11 +2256,10 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
}
else if (selectmode == UV_SELECT_FACE) {
/* find face */
- uv_find_nearest_face(scene, ima, em, co, &hit);
- if (hit.efa == NULL) {
+ if (!uv_find_nearest_face(scene, ima, em, co, &hit)) {
return OPERATOR_CANCELLED;
}
-
+
/* make active */
BM_mesh_active_face_set(em->bm, hit.efa);
@@ -2175,9 +2276,7 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
hitlen = hit.efa->len;
}
else if (selectmode == UV_SELECT_ISLAND) {
- uv_find_nearest_edge(scene, ima, em, co, &hit);
-
- if (hit.efa == NULL) {
+ if (!uv_find_nearest_edge(scene, ima, em, co, &hit)) {
return OPERATOR_CANCELLED;
}
@@ -2193,7 +2292,8 @@ static int uv_mouse_select(bContext *C, const float co[2], bool extend, bool loo
flush = uv_select_edgeloop(scene, ima, em, &hit, limit, extend);
}
else if (selectmode == UV_SELECT_ISLAND) {
- uv_select_linked(scene, ima, em, limit, &hit, extend, false);
+ /* Current behavior of 'extend' is actually toggling, so pass extend flag as 'toggle' here */
+ uv_select_linked(scene, ima, em, limit, &hit, false, false, extend, false);
}
else if (extend) {
if (selectmode == UV_SELECT_VERTEX) {
@@ -2357,7 +2457,11 @@ static void UV_OT_select(wmOperatorType *ot)
"Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
}
-/* ******************** loop select operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Loop Select Operator
+ * \{ */
static int uv_select_loop_exec(bContext *C, wmOperator *op)
{
@@ -2402,7 +2506,11 @@ static void UV_OT_select_loop(wmOperatorType *ot)
"Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
}
-/* ******************** linked select operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Linked Operator
+ * \{ */
static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent *event, int pick)
{
@@ -2413,10 +2521,10 @@ static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent
Image *ima = CTX_data_edit_image(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
float limit[2];
- int extend;
+ int extend, deselect;
bool select_faces = (ts->uv_flag & UV_SYNC_SELECTION) && (ts->selectmode & SCE_SELECT_FACE);
- NearestHit hit, *hit_p = NULL;
+ UvNearestHit hit = UV_NEAREST_HIT_INIT;
if ((ts->uv_flag & UV_SYNC_SELECTION) && !(ts->selectmode & SCE_SELECT_FACE)) {
BKE_report(op->reports, RPT_ERROR, "Select linked only works in face select mode when sync selection is enabled");
@@ -2424,6 +2532,7 @@ static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent
}
extend = RNA_boolean_get(op->ptr, "extend");
+ deselect = RNA_boolean_get(op->ptr, "deselect");
uvedit_pixel_to_float(sima, limit, 0.05f);
if (pick) {
@@ -2441,11 +2550,12 @@ static int uv_select_linked_internal(bContext *C, wmOperator *op, const wmEvent
RNA_float_get_array(op->ptr, "location", co);
}
- uv_find_nearest_edge(scene, ima, em, co, &hit);
- hit_p = &hit;
+ if (!uv_find_nearest_edge(scene, ima, em, co, &hit)) {
+ return OPERATOR_CANCELLED;
+ }
}
- uv_select_linked(scene, ima, em, limit, hit_p, extend, select_faces);
+ uv_select_linked(scene, ima, em, limit, pick ? &hit : NULL, extend, deselect, false, select_faces);
DAG_id_tag_update(obedit->data, 0);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
@@ -2473,6 +2583,7 @@ static void UV_OT_select_linked(wmOperatorType *ot)
/* properties */
RNA_def_boolean(ot->srna, "extend", 0,
"Extend", "Extend selection rather than clearing the existing selection");
+ RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked UV vertices rather than selecting them");
}
static int uv_select_linked_pick_invoke(bContext *C, wmOperator *op, const wmEvent *event)
@@ -2501,7 +2612,7 @@ static void UV_OT_select_linked_pick(wmOperatorType *ot)
/* properties */
RNA_def_boolean(ot->srna, "extend", 0,
"Extend", "Extend selection rather than clearing the existing selection");
-
+ RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect linked UV vertices rather than selecting them");
RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX,
"Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f);
}
@@ -2612,17 +2723,21 @@ static void uv_select_sync_flush(ToolSettings *ts, BMEditMesh *em, const short s
}
}
-
+/** \} */
/* -------------------------------------------------------------------- */
-/* Utility functions to flush the uv-selection from tags */
+/** \name Select/Tag Flushing Utils
+ *
+ * Utility functions to flush the uv-selection from tags.
+ * \{ */
/**
* helper function for #uv_select_flush_from_tag_loop and uv_select_flush_from_tag_face
*/
-static void uv_select_flush_from_tag_sticky_loc_internal(Scene *scene, BMEditMesh *em, UvVertMap *vmap,
- const unsigned int efa_index, BMLoop *l,
- const bool select, const int cd_loop_uv_offset)
+static void uv_select_flush_from_tag_sticky_loc_internal(
+ Scene *scene, BMEditMesh *em, UvVertMap *vmap,
+ const unsigned int efa_index, BMLoop *l,
+ const bool select, const int cd_loop_uv_offset)
{
UvMapVert *start_vlist = NULL, *vlist_iter;
BMFace *efa_vlist;
@@ -2687,12 +2802,8 @@ static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object
if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
/* Tag all verts as untouched, then touch the ones that have a face center
* in the loop and select all MLoopUV's that use a touched vert. */
- BMVert *eve;
-
- BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
- BM_elem_flag_disable(eve, BM_ELEM_TAG);
- }
-
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
if (BM_elem_flag_test(efa, BM_ELEM_TAG)) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
@@ -2730,8 +2841,9 @@ static void uv_select_flush_from_tag_face(SpaceImage *sima, Scene *scene, Object
/* tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset); */ /* UNUSED */
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
- select, cd_loop_uv_offset);
+ uv_select_flush_from_tag_sticky_loc_internal(
+ scene, em, vmap, efa_index, l,
+ select, cd_loop_uv_offset);
}
}
}
@@ -2778,11 +2890,7 @@ static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object
if ((ts->uv_flag & UV_SYNC_SELECTION) == 0 && sima->sticky == SI_STICKY_VERTEX) {
/* Tag all verts as untouched, then touch the ones that have a face center
* in the loop and select all MLoopUV's that use a touched vert. */
- BMVert *eve;
-
- BM_ITER_MESH (eve, &iter, em->bm, BM_VERTS_OF_MESH) {
- BM_elem_flag_disable(eve, BM_ELEM_TAG);
- }
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
@@ -2821,8 +2929,9 @@ static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (BM_elem_flag_test(l, BM_ELEM_TAG)) {
- uv_select_flush_from_tag_sticky_loc_internal(scene, em, vmap, efa_index, l,
- select, cd_loop_uv_offset);
+ uv_select_flush_from_tag_sticky_loc_internal(
+ scene, em, vmap, efa_index, l,
+ select, cd_loop_uv_offset);
}
}
}
@@ -2840,7 +2949,11 @@ static void uv_select_flush_from_tag_loop(SpaceImage *sima, Scene *scene, Object
}
}
-/* ******************** border select operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Border Select Operator
+ * \{ */
static int uv_border_select_exec(bContext *C, wmOperator *op)
{
@@ -2858,9 +2971,10 @@ static int uv_border_select_exec(bContext *C, wmOperator *op)
MLoopUV *luv;
rctf rectf;
bool changed, pinned, select, extend;
- const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
- (ts->selectmode == SCE_SELECT_FACE) :
- (ts->uv_selectmode == UV_SELECT_FACE);
+ const bool use_face_center = (
+ (ts->uv_flag & UV_SYNC_SELECTION) ?
+ (ts->selectmode == SCE_SELECT_FACE) :
+ (ts->uv_selectmode == UV_SELECT_FACE));
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
const int cd_poly_tex_offset = CustomData_get_offset(&em->bm->pdata, CD_MTEXPOLY);
@@ -2870,9 +2984,9 @@ static int uv_border_select_exec(bContext *C, wmOperator *op)
UI_view2d_region_to_view_rctf(&ar->v2d, &rectf, &rectf);
/* figure out what to select/deselect */
- select = (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT);
- pinned = RNA_boolean_get(op->ptr, "pinned");
+ select = !RNA_boolean_get(op->ptr, "deselect");
extend = RNA_boolean_get(op->ptr, "extend");
+ pinned = RNA_boolean_get(op->ptr, "pinned");
if (!extend)
uv_select_all_perform(scene, ima, em, SEL_DESELECT);
@@ -2906,7 +3020,8 @@ static int uv_border_select_exec(bContext *C, wmOperator *op)
else {
/* other selection modes */
changed = true;
-
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
if (!uvedit_face_visible_test(scene, ima, efa, tf))
@@ -2919,15 +3034,21 @@ static int uv_border_select_exec(bContext *C, wmOperator *op)
/* UV_SYNC_SELECTION - can't do pinned selection */
if (BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
+ BM_elem_flag_enable(l->v, BM_ELEM_TAG);
}
}
else if (pinned) {
if ((luv->flag & MLOOPUV_PINNED) && BLI_rctf_isect_pt_v(&rectf, luv->uv)) {
uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
+ BM_elem_flag_enable(l->v, BM_ELEM_TAG);
}
}
}
}
+
+ if (sima->sticky == SI_STICKY_VERTEX) {
+ uvedit_vertex_select_tagged(em, scene, select, cd_loop_uv_offset);
+ }
}
if (changed) {
@@ -2951,11 +3072,11 @@ static void UV_OT_select_border(wmOperatorType *ot)
ot->idname = "UV_OT_select_border";
/* api callbacks */
- ot->invoke = WM_border_select_invoke;
+ ot->invoke = WM_gesture_border_invoke;
ot->exec = uv_border_select_exec;
- ot->modal = WM_border_select_modal;
+ ot->modal = WM_gesture_border_modal;
ot->poll = ED_operator_uvedit_space_image; /* requires space image */;
- ot->cancel = WM_border_select_cancel;
+ ot->cancel = WM_gesture_border_cancel;
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
@@ -2963,10 +3084,14 @@ static void UV_OT_select_border(wmOperatorType *ot)
/* properties */
RNA_def_boolean(ot->srna, "pinned", 0, "Pinned", "Border select pinned UVs only");
- WM_operator_properties_gesture_border(ot, true);
+ WM_operator_properties_gesture_border_select(ot);
}
-/* ******************** circle select operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Circle Select Operator
+ * \{ */
static int uv_inside_circle(const float uv[2], const float offset[2], const float ellipse[2])
{
@@ -2977,19 +3102,6 @@ static int uv_inside_circle(const float uv[2], const float offset[2], const floa
return ((x * x + y * y) < 1.0f);
}
-static bool uv_select_inside_ellipse(BMEditMesh *em, Scene *scene, const bool select,
- const float offset[2], const float ellipse[2], BMLoop *l, MLoopUV *luv,
- const int cd_loop_uv_offset)
-{
- if (uv_inside_circle(luv->uv, offset, ellipse)) {
- uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
- return true;
- }
- else {
- return false;
- }
-}
-
static int uv_circle_select_exec(bContext *C, wmOperator *op)
{
SpaceImage *sima = CTX_wm_space_image(C);
@@ -3004,12 +3116,12 @@ static int uv_circle_select_exec(bContext *C, wmOperator *op)
MLoopUV *luv;
int x, y, radius, width, height;
float zoomx, zoomy, offset[2], ellipse[2];
- int gesture_mode = RNA_int_get(op->ptr, "gesture_mode");
- const bool select = (gesture_mode == GESTURE_MODAL_SELECT);
+ const bool select = !RNA_boolean_get(op->ptr, "deselect");
bool changed = false;
- const bool use_face_center = (ts->uv_flag & UV_SYNC_SELECTION) ?
- (ts->selectmode == SCE_SELECT_FACE) :
- (ts->uv_selectmode == UV_SELECT_FACE);
+ const bool use_face_center = (
+ (ts->uv_flag & UV_SYNC_SELECTION) ?
+ (ts->selectmode == SCE_SELECT_FACE) :
+ (ts->uv_selectmode == UV_SELECT_FACE));
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
@@ -3050,12 +3162,22 @@ static int uv_circle_select_exec(bContext *C, wmOperator *op)
}
}
else {
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- changed |= uv_select_inside_ellipse(em, scene, select, offset, ellipse, l, luv, cd_loop_uv_offset);
+ if (uv_inside_circle(luv->uv, offset, ellipse)) {
+ changed = true;
+ uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
+ BM_elem_flag_enable(l->v, BM_ELEM_TAG);
+ }
}
}
+
+ if (sima->sticky == SI_STICKY_VERTEX) {
+ uvedit_vertex_select_tagged(em, scene, select, cd_loop_uv_offset);
+ }
}
if (changed) {
@@ -3083,19 +3205,20 @@ static void UV_OT_circle_select(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;
-
+
/* properties */
- RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
- RNA_def_int(ot->srna, "radius", 1, 1, INT_MAX, "Radius", "", 1, INT_MAX);
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
+ WM_operator_properties_gesture_circle_select(ot);
}
+/** \} */
-/* ******************** lasso select operator **************** */
+/* -------------------------------------------------------------------- */
+/** \name Lasso Select Operator
+ * \{ */
-static bool do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short moves,
- const bool select, const bool extend)
+static bool do_lasso_select_mesh_uv(
+ bContext *C, const int mcords[][2], short moves,
+ const bool select, const bool extend)
{
SpaceImage *sima = CTX_wm_space_image(C);
Image *ima = CTX_data_edit_image(C);
@@ -3151,25 +3274,33 @@ static bool do_lasso_select_mesh_uv(bContext *C, const int mcords[][2], short mo
}
}
else { /* Vert Sel */
+ BM_mesh_elem_hflag_disable_all(em->bm, BM_VERT, BM_ELEM_TAG, false);
+
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
tf = BM_ELEM_CD_GET_VOID_P(efa, cd_poly_tex_offset);
if (uvedit_face_visible_test(scene, ima, efa, tf)) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if ((select) != (uvedit_uv_select_test(scene, l, cd_loop_uv_offset))) {
MLoopUV *luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- if (UI_view2d_view_to_region_clip(&ar->v2d,
- luv->uv[0], luv->uv[1],
- &screen_uv[0], &screen_uv[1]) &&
+ if (UI_view2d_view_to_region_clip(
+ &ar->v2d,
+ luv->uv[0], luv->uv[1],
+ &screen_uv[0], &screen_uv[1]) &&
BLI_rcti_isect_pt_v(&rect, screen_uv) &&
BLI_lasso_is_point_inside(mcords, moves, screen_uv[0], screen_uv[1], V2D_IS_CLIPPED))
{
uvedit_uv_select_set(em, scene, l, select, false, cd_loop_uv_offset);
changed = true;
+ BM_elem_flag_enable(l->v, BM_ELEM_TAG);
}
}
}
}
}
+
+ if (sima->sticky == SI_STICKY_VERTEX) {
+ uvedit_vertex_select_tagged(em, scene, select, cd_loop_uv_offset);
+ }
}
if (changed) {
@@ -3219,14 +3350,15 @@ static void UV_OT_select_lasso(wmOperatorType *ot)
/* flags */
ot->flag = OPTYPE_UNDO;
- RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
- RNA_def_boolean(ot->srna, "deselect", 0, "Deselect", "Deselect rather than select items");
- RNA_def_boolean(ot->srna, "extend", 1, "Extend", "Extend selection instead of deselecting everything first");
+ /* properties */
+ WM_operator_properties_gesture_lasso_select(ot);
}
+/** \} */
-
-/* ******************** snap cursor operator **************** */
+/* -------------------------------------------------------------------- */
+/** \name Snap Cursor Operator
+ * \{ */
static void uv_snap_to_pixel(float uvco[2], float w, float h)
{
@@ -3275,7 +3407,7 @@ static int uv_snap_cursor_exec(bContext *C, wmOperator *op)
static void UV_OT_snap_cursor(wmOperatorType *ot)
{
- static EnumPropertyItem target_items[] = {
+ static const EnumPropertyItem target_items[] = {
{0, "PIXELS", 0, "Pixels", ""},
{1, "SELECTED", 0, "Selected", ""},
{0, NULL, 0, NULL, NULL}};
@@ -3294,7 +3426,11 @@ static void UV_OT_snap_cursor(wmOperatorType *ot)
RNA_def_enum(ot->srna, "target", target_items, 0, "Target", "Target to snap the selected UVs to");
}
-/* ******************** snap selection operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Snap Selection Operator
+ * \{ */
static bool uv_snap_uvs_to_cursor(Scene *scene, Image *ima, Object *obedit, const float cursor[2])
{
@@ -3494,7 +3630,7 @@ static int uv_snap_selection_exec(bContext *C, wmOperator *op)
static void UV_OT_snap_selected(wmOperatorType *ot)
{
- static EnumPropertyItem target_items[] = {
+ static const EnumPropertyItem target_items[] = {
{0, "PIXELS", 0, "Pixels", ""},
{1, "CURSOR", 0, "Cursor", ""},
{2, "CURSOR_OFFSET", 0, "Cursor (Offset)", ""},
@@ -3515,7 +3651,11 @@ static void UV_OT_snap_selected(wmOperatorType *ot)
RNA_def_enum(ot->srna, "target", target_items, 0, "Target", "Target to snap the selected UVs to");
}
-/* ******************** pin operator **************** */
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Pin UV's Operator
+ * \{ */
static int uv_pin_exec(bContext *C, wmOperator *op)
{
@@ -3573,7 +3713,11 @@ static void UV_OT_pin(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "clear", 0, "Clear", "Clear pinning for the selection instead of setting it");
}
-/******************* select pinned operator ***************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Select Pinned UV's Operator
+ * \{ */
static int uv_select_pinned_exec(bContext *C, wmOperator *UNUSED(op))
{
@@ -3621,15 +3765,20 @@ static void UV_OT_select_pinned(wmOperatorType *ot)
ot->poll = ED_operator_uvedit;
}
-/********************** hide operator *********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Hide Operator
+ * \{ */
/* check if we are selected or unselected based on 'bool_test' arg,
* needed for select swap support */
#define UV_SEL_TEST(luv, bool_test) ((((luv)->flag & MLOOPUV_VERTSEL) == MLOOPUV_VERTSEL) == bool_test)
/* is every UV vert selected or unselected depending on bool_test */
-static bool bm_face_is_all_uv_sel(BMFace *f, bool select_test,
- const int cd_loop_uv_offset)
+static bool bm_face_is_all_uv_sel(
+ BMFace *f, bool select_test,
+ const int cd_loop_uv_offset)
{
BMLoop *l_iter;
BMLoop *l_first;
@@ -3759,9 +3908,13 @@ static void UV_OT_hide(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected");
}
-/****************** reveal operator ******************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Reveal Operator
+ * \{ */
-static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
+static int uv_reveal_exec(bContext *C, wmOperator *op)
{
SpaceImage *sima = CTX_wm_space_image(C);
Object *obedit = CTX_data_edit_object(C);
@@ -3777,12 +3930,14 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
const int cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
+ const bool select = RNA_boolean_get(op->ptr, "select");
+
/* note on tagging, selecting faces needs to be delayed so it doesn't select the verts and
* confuse our checks on selected verts. */
/* call the mesh function if we are in mesh sync sel */
if (ts->uv_flag & UV_SYNC_SELECTION) {
- EDBM_mesh_reveal(em);
+ EDBM_mesh_reveal(em, select);
WM_event_add_notifier(C, NC_GEOM | ND_SELECT, obedit->data);
return OPERATOR_FINISHED;
@@ -3794,7 +3949,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && !BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
+ SET_FLAG_FROM_TEST(luv->flag, select, MLOOPUV_VERTSEL);
}
/* BM_face_select_set(em->bm, efa, true); */
BM_elem_flag_enable(efa, BM_ELEM_TAG);
@@ -3815,7 +3970,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
if (!totsel) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
+ SET_FLAG_FROM_TEST(luv->flag, select, MLOOPUV_VERTSEL);
}
/* BM_face_select_set(em->bm, efa, true); */
BM_elem_flag_enable(efa, BM_ELEM_TAG);
@@ -3830,7 +3985,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (BM_elem_flag_test(l->v, BM_ELEM_SELECT) == 0) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
+ SET_FLAG_FROM_TEST(luv->flag, select, MLOOPUV_VERTSEL);
}
}
/* BM_face_select_set(em->bm, efa, true); */
@@ -3846,7 +4001,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
if (!BM_elem_flag_test(efa, BM_ELEM_HIDDEN) && !BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
+ SET_FLAG_FROM_TEST(luv->flag, select, MLOOPUV_VERTSEL);
}
/* BM_face_select_set(em->bm, efa, true); */
BM_elem_flag_enable(efa, BM_ELEM_TAG);
@@ -3860,7 +4015,7 @@ static int uv_reveal_exec(bContext *C, wmOperator *UNUSED(op))
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
if (BM_elem_flag_test(l->v, BM_ELEM_SELECT) == 0) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
- luv->flag |= MLOOPUV_VERTSEL;
+ SET_FLAG_FROM_TEST(luv->flag, select, MLOOPUV_VERTSEL);
}
}
/* BM_face_select_set(em->bm, efa, true); */
@@ -3888,9 +4043,15 @@ static void UV_OT_reveal(wmOperatorType *ot)
/* api callbacks */
ot->exec = uv_reveal_exec;
ot->poll = ED_operator_uvedit;
+
+ RNA_def_boolean(ot->srna, "select", true, "Select", "");
}
-/******************** set 3d cursor operator ********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set 2D Cursor Operator
+ * \{ */
static int uv_set_2d_cursor_poll(bContext *C)
{
@@ -3953,7 +4114,11 @@ static void UV_OT_cursor_set(wmOperatorType *ot)
"Cursor location in normalized (0.0-1.0) coordinates", -10.0f, 10.0f);
}
-/********************** set tile operator **********************/
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Set Tile Operator
+ * \{ */
static int set_tile_exec(bContext *C, wmOperator *op)
{
@@ -4019,6 +4184,11 @@ static void UV_OT_tile_set(wmOperatorType *ot)
RNA_def_int_vector(ot->srna, "tile", 2, NULL, 0, INT_MAX, "Tile", "Tile coordinate", 0, 10);
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Seam from UV Islands Operator
+ * \{ */
static int uv_seams_from_islands_exec(bContext *C, wmOperator *op)
{
@@ -4037,7 +4207,7 @@ static int uv_seams_from_islands_exec(bContext *C, wmOperator *op)
em = me->edit_btmesh;
bm = em->bm;
- if (!EDBM_mtexpoly_check(em)) {
+ if (!EDBM_uv_check(em)) {
return OPERATOR_CANCELLED;
}
@@ -4154,6 +4324,12 @@ static void UV_OT_seams_from_islands(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "mark_sharp", 0, "Mark Sharp", "Mark boundary edges as sharp");
}
+/** \} */
+
+/* -------------------------------------------------------------------- */
+/** \name Mark Seam Operator
+ * \{ */
+
static int uv_mark_seam_exec(bContext *C, wmOperator *op)
{
Object *ob = CTX_data_edit_object(C);
@@ -4164,17 +4340,14 @@ static int uv_mark_seam_exec(bContext *C, wmOperator *op)
BMFace *efa;
BMLoop *loop;
BMIter iter, liter;
- bool clear = RNA_boolean_get(op->ptr, "clear");
+ bool flag_set = !RNA_boolean_get(op->ptr, "clear");
const int cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
BM_ITER_ELEM (loop, &liter, efa, BM_LOOPS_OF_FACE) {
if (uvedit_edge_select_test(scene, loop, cd_loop_uv_offset)) {
- if (clear)
- BM_elem_flag_disable(loop->e, BM_ELEM_SEAM);
- else
- BM_elem_flag_enable(loop->e, BM_ELEM_SEAM);
+ BM_elem_flag_set(loop->e, BM_ELEM_SEAM, flag_set);
}
}
}
@@ -4229,8 +4402,11 @@ static void UV_OT_mark_seam(wmOperatorType *ot)
RNA_def_boolean(ot->srna, "clear", false, "Clear Seams", "Clear instead of marking seams");
}
+/** \} */
-/* ************************** registration **********************************/
+/* -------------------------------------------------------------------- */
+/** \name Operator Registration & Keymap
+ * \{ */
void ED_operatortypes_uvedit(void)
{
@@ -4313,10 +4489,18 @@ void ED_keymap_uvedit(wmKeyConfig *keyconf)
RNA_boolean_set(kmi->ptr, "deselect", true);
/* selection manipulation */
- RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL, 0)->ptr, "extend", false);
- RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, 0, 0)->ptr, "extend", false);
- RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL | KM_SHIFT, 0)->ptr, "extend", true);
- RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "extend", true);
+ kmi = WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL, 0);
+ RNA_boolean_set(kmi->ptr, "extend", true);
+ RNA_boolean_set(kmi->ptr, "deselect", false);
+ kmi = WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, 0, 0);
+ RNA_boolean_set(kmi->ptr, "extend", true);
+ RNA_boolean_set(kmi->ptr, "deselect", false);
+ kmi = WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL | KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "extend", false);
+ RNA_boolean_set(kmi->ptr, "deselect", true);
+ kmi = WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, KM_SHIFT, 0);
+ RNA_boolean_set(kmi->ptr, "extend", false);
+ RNA_boolean_set(kmi->ptr, "deselect", true);
/* select more/less */
WM_keymap_add_item(keymap, "UV_OT_select_more", PADPLUSKEY, KM_PRESS, KM_CTRL, 0);
@@ -4366,3 +4550,4 @@ void ED_keymap_uvedit(wmKeyConfig *keyconf)
transform_keymap_for_space(keyconf, keymap, SPACE_IMAGE);
}
+/** \} */
diff --git a/source/blender/editors/uvedit/uvedit_parametrizer.c b/source/blender/editors/uvedit/uvedit_parametrizer.c
index 15891555398..e05e449efb6 100644
--- a/source/blender/editors/uvedit/uvedit_parametrizer.c
+++ b/source/blender/editors/uvedit/uvedit_parametrizer.c
@@ -32,8 +32,8 @@
#include "BLI_math.h"
#include "BLI_rand.h"
#include "BLI_heap.h"
-#include "BLI_boxpack2d.h"
-#include "BLI_convexhull2d.h"
+#include "BLI_boxpack_2d.h"
+#include "BLI_convexhull_2d.h"
#include "uvedit_parametrizer.h"
@@ -1306,7 +1306,7 @@ static void p_chart_fill_boundary(PChart *chart, PEdge *be, int nedges)
while (nedges > 2) {
PEdge *ne, *ne1, *ne2;
- e = (PEdge *)BLI_heap_popmin(heap);
+ e = (PEdge *)BLI_heap_pop_min(heap);
e1 = p_boundary_edge_prev(e);
e2 = p_boundary_edge_next(e);
@@ -2200,12 +2200,12 @@ static void p_chart_simplify_compute(PChart *chart)
e->u.nextcollapse = NULL;
/* pop edge collapse out of heap one by one */
- while (!BLI_heap_empty(heap)) {
+ while (!BLI_heap_is_empty(heap)) {
if (ncollapsed == NCOLLAPSE)
break;
HeapNode *link = BLI_heap_top(heap);
- PEdge *edge = (PEdge *)BLI_heap_popmin(heap), *pair = edge->pair;
+ PEdge *edge = (PEdge *)BLI_heap_pop_min(heap), *pair = edge->pair;
PVert *oldv, *keepv;
PEdge *wheele, *nexte;
@@ -2874,7 +2874,7 @@ static PBool p_chart_symmetry_pins(PChart *chart, PEdge *outer, PVert **pin1, PV
PEdge *cure = NULL, *firste1 = NULL, *firste2 = NULL, *nextbe;
float maxlen = 0.0f, curlen = 0.0f, totlen = 0.0f, firstlen = 0.0f;
float len1, len2;
-
+
/* find longest series of verts split in the chart itself, these are
* marked during construction */
be = outer;
@@ -4291,7 +4291,7 @@ static void param_pack_rotate(ParamHandle *handle)
p_chart_uv_to_array(chart, points);
- angle = BLI_convexhull_aabb_fit_points_2d((const float (*)[2])points, chart->nverts);
+ angle = BLI_convexhull_aabb_fit_points_2d(points, chart->nverts);
MEM_freeN(points);
diff --git a/source/blender/editors/uvedit/uvedit_smart_stitch.c b/source/blender/editors/uvedit/uvedit_smart_stitch.c
index 50aec737c8e..057417b898f 100644
--- a/source/blender/editors/uvedit/uvedit_smart_stitch.c
+++ b/source/blender/editors/uvedit/uvedit_smart_stitch.c
@@ -1782,7 +1782,7 @@ static int stitch_init(bContext *C, wmOperator *op)
}
}
- total_edges = BLI_ghash_size(edge_hash);
+ total_edges = BLI_ghash_len(edge_hash);
state->edges = edges = MEM_mallocN(sizeof(*edges) * total_edges, "stitch_edges");
/* I assume any system will be able to at least allocate an iterator :p */
@@ -2058,16 +2058,16 @@ static void stitch_select(bContext *C, Scene *scene, const wmEvent *event, Stitc
{
/* add uv under mouse to processed uv's */
float co[2];
- NearestHit hit;
+ UvNearestHit hit = UV_NEAREST_HIT_INIT;
ARegion *ar = CTX_wm_region(C);
Image *ima = CTX_data_edit_image(C);
UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]);
if (state->mode == STITCH_VERT) {
- uv_find_nearest_vert(scene, ima, state->em, co, NULL, &hit);
-
- if (hit.efa) {
+ if (uv_find_nearest_vert(
+ scene, ima, state->em, co, 0.0f, &hit))
+ {
/* Add vertex to selection, deselect all common uv's of vert other
* than selected and update the preview. This behavior was decided so that
* you can do stuff like deselect the opposite stitchable vertex and the initial still gets deselected */
@@ -2079,9 +2079,9 @@ static void stitch_select(bContext *C, Scene *scene, const wmEvent *event, Stitc
}
}
else {
- uv_find_nearest_edge(scene, ima, state->em, co, &hit);
-
- if (hit.efa) {
+ if (uv_find_nearest_edge(
+ scene, ima, state->em, co, &hit))
+ {
UvEdge *edge = uv_edge_get(hit.l, state);
stitch_select_edge(edge, state, false);
}
@@ -2116,6 +2116,7 @@ static int stitch_modal(bContext *C, wmOperator *op, const wmEvent *event)
}
break;
}
+ ATTR_FALLTHROUGH;
case PADENTER:
case RETKEY:
if (event->val == KM_PRESS) {
@@ -2253,7 +2254,7 @@ void UV_OT_stitch(wmOperatorType *ot)
{
PropertyRNA *prop;
- static EnumPropertyItem stitch_modes[] = {
+ static const EnumPropertyItem stitch_modes[] = {
{STITCH_VERT, "VERTEX", 0, "Vertex", ""},
{STITCH_EDGE, "EDGE", 0, "Edge", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/editors/uvedit/uvedit_unwrap_ops.c b/source/blender/editors/uvedit/uvedit_unwrap_ops.c
index 08f1b00a3d7..f039d709ffe 100644
--- a/source/blender/editors/uvedit/uvedit_unwrap_ops.c
+++ b/source/blender/editors/uvedit/uvedit_unwrap_ops.c
@@ -947,46 +947,89 @@ void ED_uvedit_live_unwrap(Scene *scene, Object *obedit)
#define POLAR_ZX 0
#define POLAR_ZY 1
-static void uv_map_transform_center(Scene *scene, View3D *v3d, float *result,
- Object *ob, BMEditMesh *em)
+static void uv_map_transform_calc_bounds(BMEditMesh *em, float r_min[3], float r_max[3])
{
- const int around = (v3d) ? v3d->around : V3D_AROUND_CENTER_BOUNDS;
+ BMFace *efa;
+ BMIter iter;
+ INIT_MINMAX(r_min, r_max);
+ BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
+ if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
+ BM_face_calc_bounds_expand(efa, r_min, r_max);
+ }
+ }
+}
+
+static void uv_map_transform_calc_center_median(BMEditMesh *em, float r_center[3])
+{
+ BMFace *efa;
+ BMIter iter;
+ uint center_accum_num = 0;
+ zero_v3(r_center);
+ BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
+ if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
+ float center[3];
+ BM_face_calc_center_mean(efa, center);
+ add_v3_v3(r_center, center);
+ center_accum_num += 1;
+ }
+ }
+ mul_v3_fl(r_center, 1.0f / (float)center_accum_num);
+}
+static void uv_map_transform_center(
+ Scene *scene, View3D *v3d, Object *ob, BMEditMesh *em,
+ float r_center[3],
+ float r_bounds[2][3])
+{
/* only operates on the edit object - this is all that's needed now */
+ const int around = (v3d) ? v3d->around : V3D_AROUND_CENTER_BOUNDS;
+
+ float bounds[2][3];
+ INIT_MINMAX(bounds[0], bounds[1]);
+ bool is_minmax_set = false;
switch (around) {
case V3D_AROUND_CENTER_BOUNDS: /* bounding box center */
{
- BMFace *efa;
- BMLoop *l;
- BMIter iter, liter;
- float min[3], max[3];
-
- INIT_MINMAX(min, max);
-
- BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
- if (BM_elem_flag_test(efa, BM_ELEM_SELECT)) {
- BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
- minmax_v3v3_v3(min, max, l->v->co);
- }
- }
- }
- mid_v3_v3v3(result, min, max);
+ uv_map_transform_calc_bounds(em, bounds[0], bounds[1]);
+ is_minmax_set = true;
+ mid_v3_v3v3(r_center, bounds[0], bounds[1]);
+ break;
+ }
+ case V3D_AROUND_CENTER_MEAN:
+ {
+ uv_map_transform_calc_center_median(em, r_center);
break;
}
case V3D_AROUND_CURSOR: /* cursor center */
{
- const float *curs = ED_view3d_cursor3d_get(scene, v3d);
- /* shift to objects world */
- sub_v3_v3v3(result, curs, ob->obmat[3]);
+ invert_m4_m4(ob->imat, ob->obmat);
+ mul_v3_m4v3(r_center, ob->imat, ED_view3d_cursor3d_get(scene, v3d));
break;
}
+ case V3D_AROUND_ACTIVE:
+ {
+ BMEditSelection ese;
+ if (BM_select_history_active_get(em->bm, &ese)) {
+ BM_editselection_center(&ese, r_center);
+ break;
+ }
+ ATTR_FALLTHROUGH;
+ }
case V3D_AROUND_LOCAL_ORIGINS: /* object center */
- case V3D_AROUND_CENTER_MEAN: /* multiple objects centers, only one object here*/
default:
- zero_v3(result);
+ zero_v3(r_center);
break;
}
+
+ /* if this is passed, always set! */
+ if (r_bounds) {
+ if (!is_minmax_set) {
+ uv_map_transform_calc_bounds(em, bounds[0], bounds[1]);
+ }
+ copy_v3_v3(r_bounds[0], bounds[0]);
+ copy_v3_v3(r_bounds[1], bounds[1]);
+ }
}
static void uv_map_rotation_matrix(float result[4][4], RegionView3D *rv3d, Object *ob,
@@ -1037,13 +1080,10 @@ static void uv_map_rotation_matrix(float result[4][4], RegionView3D *rv3d, Objec
mul_m4_series(result, rotup, rotside, viewmatrix, rotobj);
}
-static void uv_map_transform(bContext *C, wmOperator *op, float center[3], float rotmat[4][4])
+static void uv_map_transform(bContext *C, wmOperator *op, float rotmat[4][4])
{
/* context checks are messy here, making it work in both 3d view and uv editor */
- Scene *scene = CTX_data_scene(C);
Object *obedit = CTX_data_edit_object(C);
- BMEditMesh *em = BKE_editmesh_from_object(obedit);
- View3D *v3d = CTX_wm_view3d(C);
RegionView3D *rv3d = CTX_wm_region_view3d(C);
/* common operator properties */
int align = RNA_enum_get(op->ptr, "align");
@@ -1051,8 +1091,6 @@ static void uv_map_transform(bContext *C, wmOperator *op, float center[3], float
float radius = RNA_struct_find_property(op->ptr, "radius") ? RNA_float_get(op->ptr, "radius") : 1.0f;
float upangledeg, sideangledeg;
- uv_map_transform_center(scene, v3d, center, obedit, em);
-
if (direction == VIEW_ON_EQUATOR) {
upangledeg = 90.0f;
sideangledeg = 0.0f;
@@ -1073,13 +1111,13 @@ static void uv_map_transform(bContext *C, wmOperator *op, float center[3], float
static void uv_transform_properties(wmOperatorType *ot, int radius)
{
- static EnumPropertyItem direction_items[] = {
+ static const EnumPropertyItem direction_items[] = {
{VIEW_ON_EQUATOR, "VIEW_ON_EQUATOR", 0, "View on Equator", "3D view is on the equator"},
{VIEW_ON_POLES, "VIEW_ON_POLES", 0, "View on Poles", "3D view is on the poles"},
{ALIGN_TO_OBJECT, "ALIGN_TO_OBJECT", 0, "Align to Object", "Align according to object transform"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem align_items[] = {
+ static const EnumPropertyItem align_items[] = {
{POLAR_ZX, "POLAR_ZX", 0, "Polar ZX", "Polar 0 is X"},
{POLAR_ZY, "POLAR_ZY", 0, "Polar ZY", "Polar 0 is Y"},
{0, NULL, 0, NULL, NULL}
@@ -1327,7 +1365,7 @@ static void unwrap_draw(bContext *UNUSED(C), wmOperator *op)
void UV_OT_unwrap(wmOperatorType *ot)
{
- static EnumPropertyItem method_items[] = {
+ static const EnumPropertyItem method_items[] = {
{0, "ANGLE_BASED", 0, "Angle Based", ""},
{1, "CONFORMAL", 0, "Conformal", ""},
{2, "SLIM", 0, "SLIM", "" },
@@ -1593,6 +1631,7 @@ static int sphere_project_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
Object *obedit = CTX_data_edit_object(C);
+ View3D *v3d = CTX_wm_view3d(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
BMFace *efa;
BMLoop *l;
@@ -1610,7 +1649,8 @@ static int sphere_project_exec(bContext *C, wmOperator *op)
cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
- uv_map_transform(C, op, center, rotmat);
+ uv_map_transform(C, op, rotmat);
+ uv_map_transform_center(scene, v3d, obedit, em, center, NULL);
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
if (!BM_elem_flag_test(efa, BM_ELEM_SELECT))
@@ -1672,6 +1712,7 @@ static int cylinder_project_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
Object *obedit = CTX_data_edit_object(C);
+ View3D *v3d = CTX_wm_view3d(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
BMFace *efa;
BMLoop *l;
@@ -1689,12 +1730,13 @@ static int cylinder_project_exec(bContext *C, wmOperator *op)
cd_loop_uv_offset = CustomData_get_offset(&em->bm->ldata, CD_MLOOPUV);
- uv_map_transform(C, op, center, rotmat);
+ uv_map_transform(C, op, rotmat);
+ uv_map_transform_center(scene, v3d, obedit, em, center, NULL);
BM_ITER_MESH (efa, &iter, em->bm, BM_FACES_OF_MESH) {
if (!BM_elem_flag_test(efa, BM_ELEM_SELECT))
continue;
-
+
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
@@ -1733,68 +1775,79 @@ void UV_OT_cylinder_project(wmOperatorType *ot)
/******************* Cube Project operator ****************/
-void ED_uvedit_unwrap_cube_project(Object *ob, BMesh *bm, float cube_size, bool use_select)
+void ED_uvedit_unwrap_cube_project(BMesh *bm, float cube_size, bool use_select, const float center[3])
{
BMFace *efa;
BMLoop *l;
BMIter iter, liter;
/* MTexPoly *tf; */ /* UNUSED */
MLoopUV *luv;
- float *loc, dx, dy;
+ float loc[3];
int cox, coy;
int cd_loop_uv_offset;
cd_loop_uv_offset = CustomData_get_offset(&bm->ldata, CD_MLOOPUV);
- loc = ob->obmat[3];
+ if (center) {
+ copy_v3_v3(loc, center);
+ }
+ else {
+ zero_v3(loc);
+ }
/* choose x,y,z axis for projection depending on the largest normal
* component, but clusters all together around the center of map. */
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
- int first = 1;
-
/* tf = CustomData_bmesh_get(&em->bm->pdata, efa->head.data, CD_MTEXPOLY); */ /* UNUSED */
if (use_select && !BM_elem_flag_test(efa, BM_ELEM_SELECT))
continue;
axis_dominant_v3(&cox, &coy, efa->no);
- dx = dy = 0;
BM_ITER_ELEM (l, &liter, efa, BM_LOOPS_OF_FACE) {
luv = BM_ELEM_CD_GET_VOID_P(l, cd_loop_uv_offset);
-
- luv->uv[0] = 0.5f + 0.5f * cube_size * (loc[cox] + l->v->co[cox]);
- luv->uv[1] = 0.5f + 0.5f * cube_size * (loc[coy] + l->v->co[coy]);
-
- if (first) {
- dx = floor(luv->uv[0]);
- dy = floor(luv->uv[1]);
- first = 0;
- }
-
-
- luv->uv[0] -= dx;
- luv->uv[1] -= dy;
+ luv->uv[0] = 0.5f + 0.5f * cube_size * (l->v->co[cox] - loc[cox]);
+ luv->uv[1] = 0.5f + 0.5f * cube_size * (l->v->co[coy] - loc[coy]);
}
}
-
}
static int cube_project_exec(bContext *C, wmOperator *op)
{
Scene *scene = CTX_data_scene(C);
+ View3D *v3d = CTX_wm_view3d(C);
Object *obedit = CTX_data_edit_object(C);
BMEditMesh *em = BKE_editmesh_from_object(obedit);
- float cube_size = RNA_float_get(op->ptr, "cube_size");
+ PropertyRNA *prop_cube_size = RNA_struct_find_property(op->ptr, "cube_size");
+ float cube_size = RNA_property_float_get(op->ptr, prop_cube_size);
+ float center[3];
+ float bounds[2][3];
+ float (*bounds_buf)[3] = NULL;
/* add uvs if they don't exist yet */
if (!ED_uvedit_ensure_uvs(C, scene, obedit)) {
return OPERATOR_CANCELLED;
}
- ED_uvedit_unwrap_cube_project(obedit, em->bm, cube_size, true);
+ if (!RNA_property_is_set(op->ptr, prop_cube_size)) {
+ bounds_buf = bounds;
+ }
+
+ uv_map_transform_center(scene, v3d, obedit, em, center, bounds_buf);
+
+ /* calculate based on bounds */
+ if (bounds_buf) {
+ float dims[3];
+ sub_v3_v3v3(dims, bounds[1], bounds[0]);
+ cube_size = max_fff(UNPACK3(dims));
+ cube_size = cube_size ? 2.0f / cube_size : 1.0f;
+ RNA_property_float_set(op->ptr, prop_cube_size, cube_size);
+ }
+
+ ED_uvedit_unwrap_cube_project(em->bm, cube_size, true, center);
+
uv_map_clip_correct(scene, obedit, em, op);
DAG_id_tag_update(obedit->data, 0);
diff --git a/source/blender/freestyle/intern/application/AppView.cpp b/source/blender/freestyle/intern/application/AppView.cpp
index c331d1de9c9..9b1b02c8ee2 100644
--- a/source/blender/freestyle/intern/application/AppView.cpp
+++ b/source/blender/freestyle/intern/application/AppView.cpp
@@ -22,12 +22,6 @@
* \ingroup freestyle
*/
-/* This header file needs to be included first, in order to avoid a
- compilation with MinGW (see the commit log of revision 28253) */
-extern "C" {
-#include "BLI_jitter.h"
-}
-
#include <iostream>
#include "Controller.h"
diff --git a/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp b/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp
index f63cf771120..9c478c203e7 100644
--- a/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp
+++ b/source/blender/freestyle/intern/blender_interface/BlenderStrokeRenderer.cpp
@@ -524,7 +524,7 @@ void BlenderStrokeRenderer::RenderStrokeRepBasic(StrokeRep *iStrokeRep) const
// We'll generate both with tips and without tips
// coordinates, on two different UV layers.
- if (ma->mtex[a]->texflag & MTEX_TIPS) {
+ if (ma->mtex[a]->texflag & MTEX_TIPS) {
BLI_strncpy(ma->mtex[a]->uvname, uvNames[1], sizeof(ma->mtex[a]->uvname));
}
else {
@@ -957,7 +957,7 @@ Render *BlenderStrokeRenderer::RenderScene(Render * /*re*/, bool render)
}
#endif
- Render *freestyle_render = RE_NewRender(freestyle_scene->id.name);
+ Render *freestyle_render = RE_NewSceneRender(freestyle_scene);
RE_RenderFreestyleStrokes(freestyle_render, freestyle_bmain, freestyle_scene,
render && get_stroke_count() > 0);
diff --git a/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp b/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp
index 223bc607e21..ea22633c50e 100644
--- a/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp
+++ b/source/blender/freestyle/intern/blender_interface/FRS_freestyle.cpp
@@ -448,15 +448,13 @@ static void prepare(Render *re, SceneRenderLayer *srl)
RenderLayer *rl = RE_GetRenderLayer(re->result, srl->name);
bool diffuse = false, z = false;
for (RenderPass *rpass = (RenderPass *)rl->passes.first; rpass; rpass = rpass->next) {
- switch (rpass->passtype) {
- case SCE_PASS_DIFFUSE:
+ if (STREQ(rpass->name, RE_PASSNAME_DIFFUSE)) {
controller->setPassDiffuse(rpass->rect, rpass->rectx, rpass->recty);
diffuse = true;
- break;
- case SCE_PASS_Z:
+ }
+ if (STREQ(rpass->name, RE_PASSNAME_Z)) {
controller->setPassZ(rpass->rect, rpass->rectx, rpass->recty);
z = true;
- break;
}
}
if (G.debug & G_DEBUG_FREESTYLE) {
@@ -492,7 +490,7 @@ void FRS_composite_result(Render *re, SceneRenderLayer *srl, Render *freestyle_r
return;
}
- src = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, freestyle_render->viewname);
+ src = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, freestyle_render->viewname);
if (!src) {
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "No source result image to composite" << endl;
@@ -512,7 +510,7 @@ void FRS_composite_result(Render *re, SceneRenderLayer *srl, Render *freestyle_r
}
return;
}
- dest = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, re->viewname);
+ dest = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, re->viewname);
if (!dest) {
if (G.debug & G_DEBUG_FREESTYLE) {
cout << "No destination result image to composite to" << endl;
diff --git a/source/blender/freestyle/intern/geometry/matrix_util.h b/source/blender/freestyle/intern/geometry/matrix_util.h
index d65b0ea803b..444fd7c4785 100644
--- a/source/blender/freestyle/intern/geometry/matrix_util.h
+++ b/source/blender/freestyle/intern/geometry/matrix_util.h
@@ -50,15 +50,15 @@ namespace MatrixUtil {
/**
* computes the eigen values and eigen vectors of a semi definite symmetric matrix
*
- * @param matrix is stored in column symmetric storage, i.e.
+ * \param mat: The matrix stored in column symmetric storage, i.e.
* matrix = { m11, m12, m22, m13, m23, m33, m14, m24, m34, m44 ... }
* size = n(n+1)/2
*
- * @param eigen_vectors (return) = { v1, v2, v3, ..., vn }
+ * \param eigen_vec: (return) = { v1, v2, v3, ..., vn }
* where vk = vk0, vk1, ..., vkn
* size = n^2, must be allocated by caller
*
- * @param eigen_values (return) are in decreasing order
+ * \param eigen_val: (return) are in decreasing order
* size = n, must be allocated by caller
*/
void semi_definite_symmetric_eigen(const double *mat, int n, double *eigen_vec, double *eigen_val);
diff --git a/source/blender/freestyle/intern/python/BPy_Freestyle.cpp b/source/blender/freestyle/intern/python/BPy_Freestyle.cpp
index f8aef2a08ae..0b09a3c2442 100644
--- a/source/blender/freestyle/intern/python/BPy_Freestyle.cpp
+++ b/source/blender/freestyle/intern/python/BPy_Freestyle.cpp
@@ -157,7 +157,7 @@ static PyObject *Freestyle_blendRamp(PyObject * /*self*/, PyObject *args)
return Vector_CreatePyObject(a, 3, NULL);
}
-#include "BKE_texture.h" /* do_colorband() */
+#include "BKE_colorband.h" /* BKE_colorband_evaluate() */
static char Freestyle_evaluateColorRamp___doc__[] =
".. function:: evaluateColorRamp(ramp, in)\n"
@@ -184,7 +184,7 @@ static PyObject *Freestyle_evaluateColorRamp(PyObject * /*self*/, PyObject *args
return NULL;
}
coba = (ColorBand *)py_srna->ptr.data;
- if (!do_colorband(coba, in, out)) {
+ if (!BKE_colorband_evaluate(coba, in, out)) {
PyErr_SetString(PyExc_ValueError, "failed to evaluate the color ramp");
return NULL;
}
diff --git a/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h b/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h
index 956842580c5..4142117c361 100644
--- a/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h
+++ b/source/blender/freestyle/intern/stroke/CurveAdvancedIterators.h
@@ -275,7 +275,7 @@ protected:
{
if (_Point != 0) {
delete _Point;
- _Point = 0;
+ _Point = 0;
}
if ((_currentn == _n - 1) && (_t == 1.0f)) {
// we're setting the iterator to end
diff --git a/source/blender/freestyle/intern/system/PythonInterpreter.h b/source/blender/freestyle/intern/system/PythonInterpreter.h
index 0e08af1bac8..79ba9421cda 100644
--- a/source/blender/freestyle/intern/system/PythonInterpreter.h
+++ b/source/blender/freestyle/intern/system/PythonInterpreter.h
@@ -52,7 +52,7 @@ extern "C" {
#include "BPY_extern.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
}
namespace Freestyle {
diff --git a/source/blender/freestyle/intern/system/StringUtils.h b/source/blender/freestyle/intern/system/StringUtils.h
index e11798762e4..10748c45c19 100644
--- a/source/blender/freestyle/intern/system/StringUtils.h
+++ b/source/blender/freestyle/intern/system/StringUtils.h
@@ -35,7 +35,6 @@
#include <vector>
extern "C" {
-#include "BKE_utildefines.h"
#include "BLI_string.h"
#include "BLI_path_util.h"
}
diff --git a/source/blender/freestyle/intern/view_map/ViewMapAdvancedIterators.h b/source/blender/freestyle/intern/view_map/ViewMapAdvancedIterators.h
index 8e98cabd75b..a3a0b5cbaeb 100644
--- a/source/blender/freestyle/intern/view_map/ViewMapAdvancedIterators.h
+++ b/source/blender/freestyle/intern/view_map/ViewMapAdvancedIterators.h
@@ -555,9 +555,9 @@ public:
// operators
// operator corresponding to ++i.
inline Self& operator++()
- {
- increment();
- return *this;
+ {
+ increment();
+ return *this;
}
// operator corresponding to i++, i.e. which returns the value *and then* increments it.
diff --git a/source/blender/freestyle/intern/winged_edge/WingedEdgeBuilder.h b/source/blender/freestyle/intern/winged_edge/WingedEdgeBuilder.h
index 5683b39fd28..601c208b137 100644
--- a/source/blender/freestyle/intern/winged_edge/WingedEdgeBuilder.h
+++ b/source/blender/freestyle/intern/winged_edge/WingedEdgeBuilder.h
@@ -113,7 +113,7 @@ public:
#endif
inline void setRenderMonitor(RenderMonitor *iRenderMonitor) {
- _pRenderMonitor = iRenderMonitor;
+ _pRenderMonitor = iRenderMonitor;
}
protected:
diff --git a/source/blender/gpu/CMakeLists.txt b/source/blender/gpu/CMakeLists.txt
index 8885209ce01..885ff2ff159 100644
--- a/source/blender/gpu/CMakeLists.txt
+++ b/source/blender/gpu/CMakeLists.txt
@@ -57,6 +57,8 @@ set(SRC
intern/gpu_init_exit.c
intern/gpu_material.c
intern/gpu_select.c
+ intern/gpu_select_pick.c
+ intern/gpu_select_sample_query.c
intern/gpu_shader.c
intern/gpu_texture.c
@@ -97,6 +99,7 @@ set(SRC
GPU_texture.h
intern/gpu_codegen.h
intern/gpu_private.h
+ intern/gpu_select_private.h
)
data_to_c_simple(shaders/gpu_shader_geometry.glsl SRC)
diff --git a/source/blender/gpu/GPU_buffers.h b/source/blender/gpu/GPU_buffers.h
index b693d473bd8..6ffaa29ead6 100644
--- a/source/blender/gpu/GPU_buffers.h
+++ b/source/blender/gpu/GPU_buffers.h
@@ -222,50 +222,60 @@ void GPU_interleaved_attrib_unbind(void);
typedef struct GPU_PBVH_Buffers GPU_PBVH_Buffers;
/* build */
-GPU_PBVH_Buffers *GPU_build_mesh_pbvh_buffers(
+GPU_PBVH_Buffers *GPU_pbvh_mesh_buffers_build(
const int (*face_vert_indices)[3],
const struct MPoly *mpoly, const struct MLoop *mloop, const struct MLoopTri *looptri,
const struct MVert *verts,
const int *face_indices,
const int face_indices_len);
-GPU_PBVH_Buffers *GPU_build_grid_pbvh_buffers(
+GPU_PBVH_Buffers *GPU_pbvh_grid_buffers_build(
int *grid_indices, int totgrid, unsigned int **grid_hidden, int gridsize, const struct CCGKey *key,
struct GridCommonGPUBuffer **grid_common_gpu_buffer);
-GPU_PBVH_Buffers *GPU_build_bmesh_pbvh_buffers(bool smooth_shading);
+GPU_PBVH_Buffers *GPU_pbvh_bmesh_buffers_build(bool smooth_shading);
/* update */
-void GPU_update_mesh_pbvh_buffers(
+enum {
+ GPU_PBVH_BUFFERS_SHOW_DIFFUSE_COLOR = (1 << 0),
+ GPU_PBVH_BUFFERS_SHOW_MASK = (1 << 1),
+};
+
+void GPU_pbvh_mesh_buffers_update(
GPU_PBVH_Buffers *buffers, const struct MVert *mvert,
const int *vert_indices, int totvert, const float *vmask,
- const int (*face_vert_indices)[3], bool show_diffuse_color);
-
-void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
- struct BMesh *bm,
- struct GSet *bm_faces,
- struct GSet *bm_unique_verts,
- struct GSet *bm_other_verts,
- bool show_diffuse_color);
-
-void GPU_update_grid_pbvh_buffers(GPU_PBVH_Buffers *buffers, struct CCGElem **grids,
- const struct DMFlagMat *grid_flag_mats,
- int *grid_indices, int totgrid, const struct CCGKey *key,
- bool show_diffuse_color);
+ const int (*face_vert_indices)[3],
+ const int update_flags);
+
+void GPU_pbvh_bmesh_buffers_update(
+ GPU_PBVH_Buffers *buffers,
+ struct BMesh *bm,
+ struct GSet *bm_faces,
+ struct GSet *bm_unique_verts,
+ struct GSet *bm_other_verts,
+ const int update_flags);
+
+void GPU_pbvh_grid_buffers_update(
+ GPU_PBVH_Buffers *buffers, struct CCGElem **grids,
+ const struct DMFlagMat *grid_flag_mats,
+ int *grid_indices, int totgrid, const struct CCGKey *key,
+ const int update_flags);
/* draw */
-void GPU_draw_pbvh_buffers(GPU_PBVH_Buffers *buffers, DMSetMaterial setMaterial,
- bool wireframe, bool fast);
+void GPU_pbvh_buffers_draw(
+ GPU_PBVH_Buffers *buffers, DMSetMaterial setMaterial,
+ bool wireframe, bool fast);
/* debug PBVH draw*/
-void GPU_draw_pbvh_BB(float min[3], float max[3], bool leaf);
-void GPU_end_draw_pbvh_BB(void);
-void GPU_init_draw_pbvh_BB(void);
+void GPU_pbvh_BB_draw(float min[3], float max[3], bool leaf);
+void GPU_pbvh_BB_draw_init(void);
+void GPU_pbvh_BB_draw_end(void);
bool GPU_pbvh_buffers_diffuse_changed(GPU_PBVH_Buffers *buffers, struct GSet *bm_faces, bool show_diffuse_color);
+bool GPU_pbvh_buffers_mask_changed(GPU_PBVH_Buffers *buffers, bool show_mask);
-void GPU_free_pbvh_buffers(GPU_PBVH_Buffers *buffers);
-void GPU_free_pbvh_buffer_multires(struct GridCommonGPUBuffer **grid_common_gpu_buffer);
+void GPU_pbvh_buffers_free(GPU_PBVH_Buffers *buffers);
+void GPU_pbvh_multires_buffers_free(struct GridCommonGPUBuffer **grid_common_gpu_buffer);
#endif
diff --git a/source/blender/gpu/GPU_material.h b/source/blender/gpu/GPU_material.h
index 0d92d22a173..e229afd3323 100644
--- a/source/blender/gpu/GPU_material.h
+++ b/source/blender/gpu/GPU_material.h
@@ -98,6 +98,7 @@ typedef enum GPUBuiltin {
GPU_PARTICLE_ANG_VELOCITY = (1 << 12),
GPU_LOC_TO_VIEW_MATRIX = (1 << 13),
GPU_INVERSE_LOC_TO_VIEW_MATRIX = (1 << 14),
+ GPU_OBJECT_INFO = (1 << 15)
} GPUBuiltin;
typedef enum GPUOpenGLBuiltin {
@@ -213,6 +214,7 @@ bool GPU_stack_link(GPUMaterial *mat, const char *name, GPUNodeStack *in, GPUNod
void GPU_material_output_link(GPUMaterial *material, GPUNodeLink *link);
void GPU_material_enable_alpha(GPUMaterial *material);
+GPUBuiltin GPU_get_material_builtins(GPUMaterial *material);
GPUBlendMode GPU_material_alpha_blend(GPUMaterial *material, float obcol[4]);
/* High level functions to create and use GPU materials */
@@ -224,13 +226,13 @@ void GPU_material_free(struct ListBase *gpumaterial);
void GPU_materials_free(void);
-bool GPU_lamp_override_visible(GPULamp *lamp, struct SceneRenderLayer *srl, struct Material *ma);
+bool GPU_lamp_visible(GPULamp *lamp, struct SceneRenderLayer *srl, struct Material *ma);
void GPU_material_bind(
GPUMaterial *material, int oblay, int viewlay, double time, int mipmap,
float viewmat[4][4], float viewinv[4][4], float cameraborder[4], bool scenelock);
void GPU_material_bind_uniforms(
GPUMaterial *material, float obmat[4][4], float viewmat[4][4], float obcol[4],
- float autobumpscale, GPUParticleInfo *pi);
+ float autobumpscale, GPUParticleInfo *pi, float object_info[3]);
void GPU_material_unbind(GPUMaterial *material);
bool GPU_material_bound(GPUMaterial *material);
struct Scene *GPU_material_scene(GPUMaterial *material);
@@ -342,7 +344,7 @@ void GPU_zenith_update_color(float color[3]);
struct GPUParticleInfo
{
float scalprops[4];
- float location[3];
+ float location[4];
float velocity[3];
float angular_velocity[3];
};
diff --git a/source/blender/gpu/GPU_select.h b/source/blender/gpu/GPU_select.h
index 6a16b5b7456..53f480bccd7 100644
--- a/source/blender/gpu/GPU_select.h
+++ b/source/blender/gpu/GPU_select.h
@@ -30,19 +30,31 @@
#ifndef __GPU_SELECT_H__
#define __GPU_SELECT_H__
-#include "DNA_vec_types.h" /* rcft */
#include "BLI_sys_types.h"
+struct rcti;
+
/* flags for mode of operation */
enum {
GPU_SELECT_ALL = 1,
+ /* gpu_select_query */
GPU_SELECT_NEAREST_FIRST_PASS = 2,
GPU_SELECT_NEAREST_SECOND_PASS = 3,
+ /* gpu_select_pick */
+ GPU_SELECT_PICK_ALL = 4,
+ GPU_SELECT_PICK_NEAREST = 5,
};
-void GPU_select_begin(unsigned int *buffer, unsigned int bufsize, rctf *input, char mode, int oldhits);
+void GPU_select_begin(unsigned int *buffer, unsigned int bufsize, const struct rcti *input, char mode, int oldhits);
bool GPU_select_load_id(unsigned int id);
+void GPU_select_finalize(void);
unsigned int GPU_select_end(void);
bool GPU_select_query_check_active(void);
+/* cache selection region */
+bool GPU_select_is_cached(void);
+void GPU_select_cache_begin(void);
+void GPU_select_cache_load_id(void);
+void GPU_select_cache_end(void);
+
#endif
diff --git a/source/blender/gpu/intern/gpu_basic_shader.c b/source/blender/gpu/intern/gpu_basic_shader.c
index a2b89239344..8505bd847a0 100644
--- a/source/blender/gpu/intern/gpu_basic_shader.c
+++ b/source/blender/gpu/intern/gpu_basic_shader.c
@@ -407,7 +407,7 @@ static GPUShader *gpu_basic_shader(int options)
return shader;
}
-static void GPU_basic_shader_uniform_autoset(GPUShader *shader, int options)
+static void gpu_basic_shader_uniform_autoset(GPUShader *shader, int options)
{
if (options & GPU_SHADER_LINE) {
glGetIntegerv(GL_VIEWPORT, &GPU_MATERIAL_STATE.viewport[0]);
@@ -443,7 +443,7 @@ void GPU_basic_shader_bind(int options)
if (shader) {
GPU_shader_bind(shader);
- GPU_basic_shader_uniform_autoset(shader, options);
+ gpu_basic_shader_uniform_autoset(shader, options);
}
}
else {
diff --git a/source/blender/gpu/intern/gpu_buffers.c b/source/blender/gpu/intern/gpu_buffers.c
index 370841327aa..85543ca29b2 100644
--- a/source/blender/gpu/intern/gpu_buffers.c
+++ b/source/blender/gpu/intern/gpu_buffers.c
@@ -76,13 +76,13 @@ typedef struct {
static size_t gpu_buffer_size_from_type(DerivedMesh *dm, GPUBufferType type);
-const GPUBufferTypeSettings gpu_buffer_type_settings[] = {
+static const GPUBufferTypeSettings gpu_buffer_type_settings[] = {
/* vertex */
{GL_ARRAY_BUFFER, 3},
/* normal */
{GL_ARRAY_BUFFER, 4}, /* we copy 3 shorts per normal but we add a fourth for alignment */
/* mcol */
- {GL_ARRAY_BUFFER, 3},
+ {GL_ARRAY_BUFFER, 4},
/* uv */
{GL_ARRAY_BUFFER, 2},
/* uv for texpaint */
@@ -690,7 +690,7 @@ void GPU_color_setup(DerivedMesh *dm, int colType)
glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, dm->drawObject->colors->id);
- glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0);
+ glColorPointer(4, GL_UNSIGNED_BYTE, 0, 0);
GLStates |= GPU_BUFFER_COLOR_STATE;
}
@@ -743,7 +743,7 @@ void GPU_triangle_setup(struct DerivedMesh *dm)
GLStates |= GPU_BUFFER_ELEMENT_STATE;
}
-static int GPU_typesize(int type)
+static int gpu_typesize(int type)
{
switch (type) {
case GL_FLOAT:
@@ -766,7 +766,7 @@ int GPU_attrib_element_size(GPUAttrib data[], int numdata)
int i, elementsize = 0;
for (i = 0; i < numdata; i++) {
- int typesize = GPU_typesize(data[i].type);
+ int typesize = gpu_typesize(data[i].type);
if (typesize != 0)
elementsize += typesize * data[i].size;
}
@@ -803,7 +803,7 @@ void GPU_interleaved_attrib_setup(GPUBuffer *buffer, GPUAttrib data[], int numda
glVertexAttribPointer(data[i].index, data[i].size, data[i].type,
GL_TRUE, elementsize, BUFFER_OFFSET(offset));
- offset += data[i].size * GPU_typesize(data[i].type);
+ offset += data[i].size * gpu_typesize(data[i].type);
attribData[i].index = data[i].index;
attribData[i].size = data[i].size;
@@ -993,6 +993,8 @@ struct GPU_PBVH_Buffers {
bool smooth;
bool show_diffuse_color;
+ bool show_mask;
+
bool use_matcaps;
float diffuse_color[4];
};
@@ -1030,16 +1032,20 @@ static void gpu_color_from_mask_quad_copy(const CCGKey *key,
out[2] = diffuse_color[2] * mask_color;
}
-void GPU_update_mesh_pbvh_buffers(
+void GPU_pbvh_mesh_buffers_update(
GPU_PBVH_Buffers *buffers, const MVert *mvert,
const int *vert_indices, int totvert, const float *vmask,
- const int (*face_vert_indices)[3], bool show_diffuse_color)
+ const int (*face_vert_indices)[3],
+ const int update_flags)
{
+ const bool show_diffuse_color = (update_flags & GPU_PBVH_BUFFERS_SHOW_DIFFUSE_COLOR) != 0;
+ const bool show_mask = (update_flags & GPU_PBVH_BUFFERS_SHOW_MASK) != 0;
VertexBufferFormat *vert_data;
- int i, j;
+ int i;
buffers->vmask = vmask;
buffers->show_diffuse_color = show_diffuse_color;
+ buffers->show_mask = show_mask;
buffers->use_matcaps = GPU_material_use_matcaps_get();
{
@@ -1057,6 +1063,9 @@ void GPU_update_mesh_pbvh_buffers(
copy_v4_v4(buffers->diffuse_color, diffuse_color);
+ uchar diffuse_color_ub[4];
+ rgba_float_to_uchar(diffuse_color_ub, diffuse_color);
+
/* Build VBO */
if (buffers->vert_buf)
GPU_buffer_free(buffers->vert_buf);
@@ -1076,28 +1085,20 @@ void GPU_update_mesh_pbvh_buffers(
memcpy(out->no, v->no, sizeof(short) * 3);
}
-#define UPDATE_VERTEX(face, vertex, index, diffuse_color) \
- { \
- VertexBufferFormat *out = vert_data + face_vert_indices[face][index]; \
- if (vmask) \
- gpu_color_from_mask_copy(vmask[vertex], diffuse_color, out->color); \
- else \
- rgb_float_to_uchar(out->color, diffuse_color); \
- } (void)0
-
for (i = 0; i < buffers->face_indices_len; i++) {
const MLoopTri *lt = &buffers->looptri[buffers->face_indices[i]];
- const unsigned int vtri[3] = {
- buffers->mloop[lt->tri[0]].v,
- buffers->mloop[lt->tri[1]].v,
- buffers->mloop[lt->tri[2]].v,
- };
+ for (uint j = 0; j < 3; j++) {
+ VertexBufferFormat *out = vert_data + face_vert_indices[i][j];
- UPDATE_VERTEX(i, vtri[0], 0, diffuse_color);
- UPDATE_VERTEX(i, vtri[1], 1, diffuse_color);
- UPDATE_VERTEX(i, vtri[2], 2, diffuse_color);
+ if (vmask && show_mask) {
+ uint v_index = buffers->mloop[lt->tri[j]].v;
+ gpu_color_from_mask_copy(vmask[v_index], diffuse_color, out->color);
+ }
+ else {
+ copy_v3_v3_uchar(out->color, diffuse_color_ub);
+ }
+ }
}
-#undef UPDATE_VERTEX
}
else {
/* calculate normal for each polygon only once */
@@ -1112,8 +1113,6 @@ void GPU_update_mesh_pbvh_buffers(
buffers->mloop[lt->tri[2]].v,
};
- float fmask;
-
if (paint_is_face_hidden(lt, mvert, buffers->mloop))
continue;
@@ -1126,23 +1125,22 @@ void GPU_update_mesh_pbvh_buffers(
mpoly_prev = lt->poly;
}
- if (vmask) {
- fmask = (vmask[vtri[0]] +
- vmask[vtri[1]] +
- vmask[vtri[2]]) / 3.0f;
+ uchar color_ub[3];
+ if (vmask && show_mask) {
+ float fmask = (vmask[vtri[0]] + vmask[vtri[1]] + vmask[vtri[2]]) / 3.0f;
+ gpu_color_from_mask_copy(fmask, diffuse_color, color_ub);
+ }
+ else {
+ copy_v3_v3_uchar(color_ub, diffuse_color_ub);
}
- for (j = 0; j < 3; j++) {
+ for (uint j = 0; j < 3; j++) {
const MVert *v = &mvert[vtri[j]];
VertexBufferFormat *out = vert_data;
copy_v3_v3(out->co, v->co);
copy_v3_v3_short(out->no, no);
-
- if (vmask)
- gpu_color_from_mask_copy(fmask, diffuse_color, out->color);
- else
- rgb_float_to_uchar(out->color, diffuse_color);
+ copy_v3_v3_uchar(out->color, color_ub);
vert_data++;
}
@@ -1160,7 +1158,7 @@ void GPU_update_mesh_pbvh_buffers(
buffers->mvert = mvert;
}
-GPU_PBVH_Buffers *GPU_build_mesh_pbvh_buffers(
+GPU_PBVH_Buffers *GPU_pbvh_mesh_buffers_build(
const int (*face_vert_indices)[3],
const MPoly *mpoly, const MLoop *mloop, const MLoopTri *looptri,
const MVert *mvert,
@@ -1176,6 +1174,7 @@ GPU_PBVH_Buffers *GPU_build_mesh_pbvh_buffers(
buffers->smooth = mpoly[looptri[face_indices[0]].poly].flag & ME_SMOOTH;
buffers->show_diffuse_color = false;
+ buffers->show_mask = true;
buffers->use_matcaps = false;
/* Count the number of visible triangles */
@@ -1244,14 +1243,19 @@ GPU_PBVH_Buffers *GPU_build_mesh_pbvh_buffers(
return buffers;
}
-void GPU_update_grid_pbvh_buffers(GPU_PBVH_Buffers *buffers, CCGElem **grids,
- const DMFlagMat *grid_flag_mats, int *grid_indices,
- int totgrid, const CCGKey *key, bool show_diffuse_color)
+void GPU_pbvh_grid_buffers_update(
+ GPU_PBVH_Buffers *buffers, CCGElem **grids,
+ const DMFlagMat *grid_flag_mats, int *grid_indices,
+ int totgrid, const CCGKey *key,
+ const int update_flags)
{
+ const bool show_diffuse_color = (update_flags & GPU_PBVH_BUFFERS_SHOW_DIFFUSE_COLOR) != 0;
+ const bool show_mask = (update_flags & GPU_PBVH_BUFFERS_SHOW_MASK) != 0;
VertexBufferFormat *vert_data;
int i, j, k, x, y;
buffers->show_diffuse_color = show_diffuse_color;
+ buffers->show_mask = show_mask;
buffers->use_matcaps = GPU_material_use_matcaps_get();
buffers->smooth = grid_flag_mats[grid_indices[0]].flag & ME_SMOOTH;
@@ -1285,8 +1289,13 @@ void GPU_update_grid_pbvh_buffers(GPU_PBVH_Buffers *buffers, CCGElem **grids,
normal_float_to_short_v3(vd->no, CCG_elem_no(key, elem));
if (has_mask) {
- gpu_color_from_mask_copy(*CCG_elem_mask(key, elem),
- diffuse_color, vd->color);
+ if (show_mask) {
+ gpu_color_from_mask_copy(*CCG_elem_mask(key, elem),
+ diffuse_color, vd->color);
+ }
+ else {
+ F3TOCHAR3(diffuse_color, vd->color);
+ }
}
}
vd++;
@@ -1317,13 +1326,18 @@ void GPU_update_grid_pbvh_buffers(GPU_PBVH_Buffers *buffers, CCGElem **grids,
normal_float_to_short_v3(vd->no, fno);
if (has_mask) {
- gpu_color_from_mask_quad_copy(key,
- elems[0],
- elems[1],
- elems[2],
- elems[3],
- diffuse_color,
- vd->color);
+ if (show_mask) {
+ gpu_color_from_mask_quad_copy(key,
+ elems[0],
+ elems[1],
+ elems[2],
+ elems[3],
+ diffuse_color,
+ vd->color);
+ }
+ else {
+ F3TOCHAR3(diffuse_color, vd->color);
+ }
}
}
}
@@ -1466,7 +1480,7 @@ static GPUBuffer *gpu_get_grid_buffer(
} \
} (void)0
-GPU_PBVH_Buffers *GPU_build_grid_pbvh_buffers(
+GPU_PBVH_Buffers *GPU_pbvh_grid_buffers_build(
int *grid_indices, int totgrid, BLI_bitmap **grid_hidden, int gridsize, const CCGKey *key,
GridCommonGPUBuffer **grid_common_gpu_buffer)
{
@@ -1479,6 +1493,7 @@ GPU_PBVH_Buffers *GPU_build_grid_pbvh_buffers(
buffers->totgrid = totgrid;
buffers->show_diffuse_color = false;
+ buffers->show_mask = true;
buffers->use_matcaps = false;
/* Count the number of quads */
@@ -1550,7 +1565,8 @@ static void gpu_bmesh_vert_to_buffer_copy(BMVert *v,
const float fno[3],
const float *fmask,
const int cd_vert_mask_offset,
- const float diffuse_color[4])
+ const float diffuse_color[4],
+ const bool show_mask)
{
if (!BM_elem_flag_test(v, BM_ELEM_HIDDEN)) {
VertexBufferFormat *vd = &vert_data[*v_index];
@@ -1559,11 +1575,16 @@ static void gpu_bmesh_vert_to_buffer_copy(BMVert *v,
copy_v3_v3(vd->co, v->co);
normal_float_to_short_v3(vd->no, fno ? fno : v->no);
- gpu_color_from_mask_copy(
- fmask ? *fmask :
- BM_ELEM_CD_GET_FLOAT(v, cd_vert_mask_offset),
- diffuse_color,
- vd->color);
+ float effective_mask;
+ if (show_mask) {
+ effective_mask = fmask ? *fmask
+ : BM_ELEM_CD_GET_FLOAT(v, cd_vert_mask_offset);
+ }
+ else {
+ effective_mask = 0.0f;
+ }
+
+ gpu_color_from_mask_copy(effective_mask, diffuse_color, vd->color);
/* Assign index for use in the triangle index buffer */
/* note: caller must set: bm->elem_index_dirty |= BM_VERT; */
@@ -1612,13 +1633,16 @@ static int gpu_bmesh_face_visible_count(GSet *bm_faces)
/* Creates a vertex buffer (coordinate, normal, color) and, if smooth
* shading, an element index buffer. */
-void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
- BMesh *bm,
- GSet *bm_faces,
- GSet *bm_unique_verts,
- GSet *bm_other_verts,
- bool show_diffuse_color)
+void GPU_pbvh_bmesh_buffers_update(
+ GPU_PBVH_Buffers *buffers,
+ BMesh *bm,
+ GSet *bm_faces,
+ GSet *bm_unique_verts,
+ GSet *bm_other_verts,
+ const int update_flags)
{
+ const bool show_diffuse_color = (update_flags & GPU_PBVH_BUFFERS_SHOW_DIFFUSE_COLOR) != 0;
+ const bool show_mask = (update_flags & GPU_PBVH_BUFFERS_SHOW_MASK) != 0;
VertexBufferFormat *vert_data;
void *tri_data;
int tottri, totvert, maxvert = 0;
@@ -1628,6 +1652,7 @@ void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
const int cd_vert_mask_offset = CustomData_get_offset(&bm->vdata, CD_PAINT_MASK);
buffers->show_diffuse_color = show_diffuse_color;
+ buffers->show_mask = show_mask;
buffers->use_matcaps = GPU_material_use_matcaps_get();
/* Count visible triangles */
@@ -1678,13 +1703,15 @@ void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
GSET_ITER (gs_iter, bm_unique_verts) {
gpu_bmesh_vert_to_buffer_copy(BLI_gsetIterator_getKey(&gs_iter),
vert_data, &v_index, NULL, NULL,
- cd_vert_mask_offset, diffuse_color);
+ cd_vert_mask_offset, diffuse_color,
+ show_mask);
}
GSET_ITER (gs_iter, bm_other_verts) {
gpu_bmesh_vert_to_buffer_copy(BLI_gsetIterator_getKey(&gs_iter),
vert_data, &v_index, NULL, NULL,
- cd_vert_mask_offset, diffuse_color);
+ cd_vert_mask_offset, diffuse_color,
+ show_mask);
}
maxvert = v_index;
@@ -1703,7 +1730,7 @@ void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
int i;
#if 0
- BM_iter_as_array(bm, BM_VERTS_OF_FACE, f, (void**)v, 3);
+ BM_iter_as_array(bm, BM_VERTS_OF_FACE, f, (void **)v, 3);
#endif
BM_face_as_array_vert_tri(f, v);
@@ -1716,7 +1743,8 @@ void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
for (i = 0; i < 3; i++) {
gpu_bmesh_vert_to_buffer_copy(v[i], vert_data,
&v_index, f->no, &fmask,
- cd_vert_mask_offset, diffuse_color);
+ cd_vert_mask_offset, diffuse_color,
+ show_mask);
}
}
}
@@ -1803,7 +1831,7 @@ void GPU_update_bmesh_pbvh_buffers(GPU_PBVH_Buffers *buffers,
}
}
-GPU_PBVH_Buffers *GPU_build_bmesh_pbvh_buffers(bool smooth_shading)
+GPU_PBVH_Buffers *GPU_pbvh_bmesh_buffers_build(bool smooth_shading)
{
GPU_PBVH_Buffers *buffers;
@@ -1811,13 +1839,15 @@ GPU_PBVH_Buffers *GPU_build_bmesh_pbvh_buffers(bool smooth_shading)
buffers->use_bmesh = true;
buffers->smooth = smooth_shading;
buffers->show_diffuse_color = false;
+ buffers->show_mask = true;
buffers->use_matcaps = false;
return buffers;
}
-void GPU_draw_pbvh_buffers(GPU_PBVH_Buffers *buffers, DMSetMaterial setMaterial,
- bool wireframe, bool fast)
+void GPU_pbvh_buffers_draw(
+ GPU_PBVH_Buffers *buffers, DMSetMaterial setMaterial,
+ bool wireframe, bool fast)
{
bool do_fast = fast && buffers->index_buf_fast;
/* sets material from the first face, to solve properly face would need to
@@ -1956,7 +1986,8 @@ void GPU_draw_pbvh_buffers(GPU_PBVH_Buffers *buffers, DMSetMaterial setMaterial,
}
}
-bool GPU_pbvh_buffers_diffuse_changed(GPU_PBVH_Buffers *buffers, GSet *bm_faces, bool show_diffuse_color)
+bool GPU_pbvh_buffers_diffuse_changed(
+ GPU_PBVH_Buffers *buffers, GSet *bm_faces, bool show_diffuse_color)
{
float diffuse_color[4];
bool use_matcaps = GPU_material_use_matcaps_get();
@@ -1978,7 +2009,7 @@ bool GPU_pbvh_buffers_diffuse_changed(GPU_PBVH_Buffers *buffers, GSet *bm_faces,
}
else if (buffers->use_bmesh) {
/* due to dynamic nature of dyntopo, only get first material */
- if (BLI_gset_size(bm_faces) > 0) {
+ if (BLI_gset_len(bm_faces) > 0) {
GSetIterator gs_iter;
BMFace *f;
@@ -1999,7 +2030,12 @@ bool GPU_pbvh_buffers_diffuse_changed(GPU_PBVH_Buffers *buffers, GSet *bm_faces,
return !equals_v3v3(diffuse_color, buffers->diffuse_color);
}
-void GPU_free_pbvh_buffers(GPU_PBVH_Buffers *buffers)
+bool GPU_pbvh_buffers_mask_changed(GPU_PBVH_Buffers *buffers, bool show_mask)
+{
+ return (buffers->show_mask != show_mask);
+}
+
+void GPU_pbvh_buffers_free(GPU_PBVH_Buffers *buffers)
{
if (buffers) {
if (buffers->vert_buf)
@@ -2017,7 +2053,7 @@ void GPU_free_pbvh_buffers(GPU_PBVH_Buffers *buffers)
}
}
-void GPU_free_pbvh_buffer_multires(GridCommonGPUBuffer **grid_common_gpu_buffer)
+void GPU_pbvh_multires_buffers_free(GridCommonGPUBuffer **grid_common_gpu_buffer)
{
GridCommonGPUBuffer *gridbuff = *grid_common_gpu_buffer;
@@ -2033,7 +2069,7 @@ void GPU_free_pbvh_buffer_multires(GridCommonGPUBuffer **grid_common_gpu_buffer)
}
/* debug function, draws the pbvh BB */
-void GPU_draw_pbvh_BB(float min[3], float max[3], bool leaf)
+void GPU_pbvh_BB_draw(float min[3], float max[3], bool leaf)
{
const float quads[4][4][3] = {
{
@@ -2074,7 +2110,7 @@ void GPU_draw_pbvh_BB(float min[3], float max[3], bool leaf)
glDrawArrays(GL_QUADS, 0, 16);
}
-void GPU_init_draw_pbvh_BB(void)
+void GPU_pbvh_BB_draw_init(void)
{
glPushAttrib(GL_ENABLE_BIT);
glDisable(GL_CULL_FACE);
@@ -2084,7 +2120,7 @@ void GPU_init_draw_pbvh_BB(void)
glEnable(GL_BLEND);
}
-void GPU_end_draw_pbvh_BB(void)
+void GPU_pbvh_BB_draw_end(void)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glPopAttrib();
diff --git a/source/blender/gpu/intern/gpu_codegen.c b/source/blender/gpu/intern/gpu_codegen.c
index 211394e7932..b5512aa108d 100644
--- a/source/blender/gpu/intern/gpu_codegen.c
+++ b/source/blender/gpu/intern/gpu_codegen.c
@@ -360,7 +360,7 @@ static void codegen_print_datatype(DynStr *ds, const GPUType type, float *data)
BLI_dynstr_appendf(ds, "%s(", GPU_DATATYPE_STR[type]);
for (i = 0; i < type; i++) {
- BLI_dynstr_appendf(ds, "%f", data[i]);
+ BLI_dynstr_appendf(ds, "%.12f", data[i]);
if (i == type - 1)
BLI_dynstr_append(ds, ")");
else
@@ -410,6 +410,8 @@ const char *GPU_builtin_name(GPUBuiltin builtin)
return "unfparticlevel";
else if (builtin == GPU_PARTICLE_ANG_VELOCITY)
return "unfparticleangvel";
+ else if (builtin == GPU_OBJECT_INFO)
+ return "unfobjectinfo";
else
return "";
}
diff --git a/source/blender/gpu/intern/gpu_compositing.c b/source/blender/gpu/intern/gpu_compositing.c
index 964c2b5051e..2f2a16f9e1d 100644
--- a/source/blender/gpu/intern/gpu_compositing.c
+++ b/source/blender/gpu/intern/gpu_compositing.c
@@ -798,7 +798,9 @@ bool GPU_fx_do_composite_pass(
ssao_shader = GPU_shader_get_builtin_fx_shader(GPU_SHADER_FX_SSAO, is_persp);
if (ssao_shader) {
const GPUSSAOSettings *fx_ssao = fx->settings.ssao;
- float ssao_params[4] = {fx_ssao->distance_max, fx_ssao->factor, fx_ssao->attenuation, 0.0f};
+ /* adjust attenuation to be scale invariant */
+ float attenuation = fx_ssao->attenuation / (fx_ssao->distance_max * fx_ssao->distance_max);
+ float ssao_params[4] = {fx_ssao->distance_max, fx_ssao->factor, attenuation, 0.0f};
float sample_params[3];
sample_params[0] = fx->ssao_sample_count_cache;
diff --git a/source/blender/gpu/intern/gpu_debug.c b/source/blender/gpu/intern/gpu_debug.c
index d632e767ca9..859aab9565f 100644
--- a/source/blender/gpu/intern/gpu_debug.c
+++ b/source/blender/gpu/intern/gpu_debug.c
@@ -29,6 +29,7 @@
* \ingroup gpu
*/
+#include "BLI_compiler_attrs.h"
#include "BLI_utildefines.h"
#include "BLI_sys_types.h"
#include "BLI_system.h"
@@ -161,7 +162,7 @@ const char *gpuErrorString(GLenum err)
#endif
-static const char* source_name(GLenum source)
+static const char *source_name(GLenum source)
{
switch (source) {
case GL_DEBUG_SOURCE_API: return "API";
@@ -174,7 +175,7 @@ static const char* source_name(GLenum source)
}
}
-static const char* message_type_name(GLenum message)
+static const char *message_type_name(GLenum message)
{
switch (message) {
case GL_DEBUG_TYPE_ERROR: return "error";
@@ -188,7 +189,7 @@ static const char* message_type_name(GLenum message)
}
}
-static const char* category_name_amd(GLenum category)
+static const char *category_name_amd(GLenum category)
{
switch (category) {
case GL_DEBUG_CATEGORY_API_ERROR_AMD: return "API error";
@@ -219,7 +220,7 @@ static void APIENTRY gpu_debug_proc(
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH:
backtrace = true;
- /* fall through */
+ ATTR_FALLTHROUGH;
case GL_DEBUG_SEVERITY_MEDIUM:
case GL_DEBUG_SEVERITY_LOW:
case GL_DEBUG_SEVERITY_NOTIFICATION: /* KHR has this, ARB does not */
@@ -249,7 +250,7 @@ static void APIENTRY gpu_debug_proc_amd(
switch (severity) {
case GL_DEBUG_SEVERITY_HIGH:
backtrace = true;
- /* fall through */
+ ATTR_FALLTHROUGH;
case GL_DEBUG_SEVERITY_MEDIUM:
case GL_DEBUG_SEVERITY_LOW:
fprintf(stderr, "GL %s: %s\n", category_name_amd(category), message);
@@ -424,9 +425,11 @@ void GPU_assert_no_gl_errors(const char *file, int line, const char *str)
static void gpu_state_print_fl_ex(const char *name, GLenum type)
{
+#define MAX_ARRAY_SIZE 64
+
const unsigned char err_mark[4] = {0xff, 0xff, 0xff, 0xff};
- float value[32];
+ float value[MAX_ARRAY_SIZE];
int a;
memset(value, 0xff, sizeof(value));
@@ -434,7 +437,7 @@ static void gpu_state_print_fl_ex(const char *name, GLenum type)
if (glGetError() == GL_NO_ERROR) {
printf("%s: ", name);
- for (a = 0; a < 32; a++) {
+ for (a = 0; a < MAX_ARRAY_SIZE; a++) {
if (memcmp(&value[a], err_mark, sizeof(value[a])) == 0) {
break;
}
@@ -442,6 +445,8 @@ static void gpu_state_print_fl_ex(const char *name, GLenum type)
}
printf("\n");
}
+
+#undef MAX_ARRAY_SIZE
}
#define gpu_state_print_fl(val) gpu_state_print_fl_ex(#val, val)
@@ -497,6 +502,7 @@ void GPU_state_print(void)
gpu_state_print_fl(GL_COLOR_SUM);
gpu_state_print_fl(GL_COLOR_TABLE);
gpu_state_print_fl(GL_COLOR_WRITEMASK);
+ gpu_state_print_fl(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
gpu_state_print_fl(GL_COMPRESSED_TEXTURE_FORMATS);
gpu_state_print_fl(GL_CONVOLUTION_1D);
gpu_state_print_fl(GL_CONVOLUTION_2D);
diff --git a/source/blender/gpu/intern/gpu_draw.c b/source/blender/gpu/intern/gpu_draw.c
index 7936811ab4d..514f2f71bd7 100644
--- a/source/blender/gpu/intern/gpu_draw.c
+++ b/source/blender/gpu/intern/gpu_draw.c
@@ -41,6 +41,7 @@
#include "GPU_glew.h"
#include "BLI_blenlib.h"
+#include "BLI_hash.h"
#include "BLI_linklist.h"
#include "BLI_math.h"
#include "BLI_threads.h"
@@ -681,10 +682,10 @@ int GPU_verify_image(
if (do_color_management) {
srgb_frect = MEM_mallocN(ibuf->x * ibuf->y * sizeof(float) * 4, "floar_buf_col_cor");
gpu_verify_high_bit_srgb_buffer(srgb_frect, ibuf);
- frect = srgb_frect + texwinsy * ibuf->x + texwinsx;
+ frect = srgb_frect + (4 * (texwinsy * ibuf->x + texwinsx));
}
else {
- frect = ibuf->rect_float + texwinsy * ibuf->x + texwinsx;
+ frect = ibuf->rect_float + (ibuf->channels * (texwinsy * ibuf->x + texwinsx));
}
}
else {
@@ -1203,7 +1204,7 @@ void GPU_paint_set_mipmap(bool mipmap)
/* check if image has been downscaled and do scaled partial update */
-static bool GPU_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, int y, int w, int h)
+static bool gpu_check_scaled_image(ImBuf *ibuf, Image *ima, float *frect, int x, int y, int w, int h)
{
if ((!GPU_full_non_power_of_two_support() && !is_power_of_2_resolution(ibuf->x, ibuf->y)) ||
is_over_resolution_limit(GL_TEXTURE_2D, ibuf->x, ibuf->y))
@@ -1296,7 +1297,7 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i
bool is_data = (ima->tpageflag & IMA_GLBIND_IS_DATA) != 0;
IMB_partial_rect_from_float(ibuf, buffer, x, y, w, h, is_data);
- if (GPU_check_scaled_image(ibuf, ima, buffer, x, y, w, h)) {
+ if (gpu_check_scaled_image(ibuf, ima, buffer, x, y, w, h)) {
MEM_freeN(buffer);
BKE_image_release_ibuf(ima, ibuf, NULL);
return;
@@ -1320,7 +1321,7 @@ void GPU_paint_update_image(Image *ima, ImageUser *iuser, int x, int y, int w, i
return;
}
- if (GPU_check_scaled_image(ibuf, ima, NULL, x, y, w, h)) {
+ if (gpu_check_scaled_image(ibuf, ima, NULL, x, y, w, h)) {
BKE_image_release_ibuf(ima, ibuf, NULL);
return;
}
@@ -1474,9 +1475,9 @@ static LinkNode *image_free_queue = NULL;
static void gpu_queue_image_for_free(Image *ima)
{
- BLI_lock_thread(LOCK_OPENGL);
+ BLI_thread_lock(LOCK_OPENGL);
BLI_linklist_prepend(&image_free_queue, ima);
- BLI_unlock_thread(LOCK_OPENGL);
+ BLI_thread_unlock(LOCK_OPENGL);
}
void GPU_free_unused_buffers(void)
@@ -1484,7 +1485,7 @@ void GPU_free_unused_buffers(void)
if (!BLI_thread_is_main())
return;
- BLI_lock_thread(LOCK_OPENGL);
+ BLI_thread_lock(LOCK_OPENGL);
/* images */
for (LinkNode *node = image_free_queue; node; node = node->next) {
@@ -1501,7 +1502,7 @@ void GPU_free_unused_buffers(void)
/* vbo buffers */
GPU_global_buffer_pool_free_unused();
- BLI_unlock_thread(LOCK_OPENGL);
+ BLI_thread_unlock(LOCK_OPENGL);
}
void GPU_free_image(Image *ima)
@@ -1870,7 +1871,7 @@ void GPU_begin_object_materials(
GPU_object_material_unbind();
}
-static int GPU_get_particle_info(GPUParticleInfo *pi)
+static int gpu_get_particle_info(GPUParticleInfo *pi)
{
DupliObject *dob = GMS.dob;
if (dob->particle_system) {
@@ -1889,6 +1890,8 @@ static int GPU_get_particle_info(GPUParticleInfo *pi)
pi->scalprops[3] = p->size;
copy_v3_v3(pi->location, p->state.co);
+ pi->location[3] = BLI_hash_int_01(ind);
+
copy_v3_v3(pi->velocity, p->state.vel);
copy_v3_v3(pi->angular_velocity, p->state.ave);
return 1;
@@ -1899,6 +1902,21 @@ static int GPU_get_particle_info(GPUParticleInfo *pi)
return 0;
}
+static void GPU_get_object_info(float oi[3], Material *mat)
+{
+ Object *ob = GMS.gob;
+ oi[0] = ob->index;
+ oi[1] = mat->index;
+ unsigned int random;
+ if (GMS.dob) {
+ random = GMS.dob->random_id;
+ }
+ else {
+ random = BLI_hash_int_2d(BLI_hash_string(GMS.gob->id.name + 2), 0);
+ }
+ oi[2] = random * (1.0f / (float)0xFFFFFFFF);
+}
+
int GPU_object_material_bind(int nr, void *attribs)
{
GPUVertexAttribs *gattribs = attribs;
@@ -1958,21 +1976,27 @@ int GPU_object_material_bind(int nr, void *attribs)
/* bind glsl material and get attributes */
Material *mat = GMS.gmatbuf[nr];
GPUParticleInfo partile_info;
+ float object_info[3] = {0};
float auto_bump_scale;
GPUMaterial *gpumat = GPU_material_from_blender(GMS.gscene, mat, GMS.is_opensubdiv);
GPU_material_vertex_attributes(gpumat, gattribs);
- if (GMS.dob)
- GPU_get_particle_info(&partile_info);
+ if (GMS.dob) {
+ gpu_get_particle_info(&partile_info);
+ }
+
+ if (GPU_get_material_builtins(gpumat) & GPU_OBJECT_INFO) {
+ GPU_get_object_info(object_info, mat);
+ }
GPU_material_bind(
gpumat, GMS.gob->lay, GMS.glay, 1.0, !(GMS.gob->mode & OB_MODE_TEXTURE_PAINT),
GMS.gviewmat, GMS.gviewinv, GMS.gviewcamtexcofac, GMS.gscenelock);
auto_bump_scale = GMS.gob->derivedFinal != NULL ? GMS.gob->derivedFinal->auto_bump_scale : 1.0f;
- GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gob->col, auto_bump_scale, &partile_info);
+ GPU_material_bind_uniforms(gpumat, GMS.gob->obmat, GMS.gviewmat, GMS.gob->col, auto_bump_scale, &partile_info, object_info);
GMS.gboundmat = mat;
/* for glsl use alpha blend mode, unless it's set to solid and
@@ -2177,7 +2201,7 @@ int GPU_scene_object_lights(Scene *scene, Object *ob, int lay, float viewmat[4][
GPU_basic_shader_light_set(count, NULL);
/* view direction for specular is not computed correct by default in
- * opengl, so we set the settings ourselfs */
+ * opengl, so we set the settings ourselves */
GPU_basic_shader_light_set_viewer(!ortho);
int count = 0;
diff --git a/source/blender/gpu/intern/gpu_framebuffer.c b/source/blender/gpu/intern/gpu_framebuffer.c
index f62ef677434..e7a8beae5cc 100644
--- a/source/blender/gpu/intern/gpu_framebuffer.c
+++ b/source/blender/gpu/intern/gpu_framebuffer.c
@@ -52,7 +52,7 @@ struct GPUFrameBuffer {
GPUTexture *depthtex;
};
-static void GPU_print_framebuffer_error(GLenum status, char err_out[256])
+static void gpu_print_framebuffer_error(GLenum status, char err_out[256])
{
const char *err = "unknown";
@@ -164,7 +164,7 @@ int GPU_framebuffer_texture_attach(GPUFrameBuffer *fb, GPUTexture *tex, int slot
if (error == GL_INVALID_OPERATION) {
GPU_framebuffer_restore();
- GPU_print_framebuffer_error(error, err_out);
+ gpu_print_framebuffer_error(error, err_out);
return 0;
}
@@ -331,7 +331,7 @@ bool GPU_framebuffer_check_valid(GPUFrameBuffer *fb, char err_out[256])
if (status != GL_FRAMEBUFFER_COMPLETE_EXT) {
GPU_framebuffer_restore();
- GPU_print_framebuffer_error(status, err_out);
+ gpu_print_framebuffer_error(status, err_out);
return false;
}
diff --git a/source/blender/gpu/intern/gpu_material.c b/source/blender/gpu/intern/gpu_material.c
index 4e2043471b6..edb6c9a29f9 100644
--- a/source/blender/gpu/intern/gpu_material.c
+++ b/source/blender/gpu/intern/gpu_material.c
@@ -47,13 +47,13 @@
#include "BLI_utildefines.h"
#include "BKE_anim.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_global.h"
#include "BKE_image.h"
#include "BKE_main.h"
#include "BKE_node.h"
#include "BKE_scene.h"
-#include "BKE_texture.h"
#include "BKE_group.h"
#include "IMB_imbuf_types.h"
@@ -122,6 +122,8 @@ struct GPUMaterial {
int partvel;
int partangvel;
+ int objectinfoloc;
+
ListBase lamps;
bool bound;
@@ -225,7 +227,7 @@ static void gpu_material_set_attrib_id(GPUMaterial *material)
attribs->totlayer = b;
}
-static int GPU_material_construct_end(GPUMaterial *material, const char *passname)
+static int gpu_material_construct_end(GPUMaterial *material, const char *passname)
{
if (material->outlink) {
GPUNodeLink *outlink = material->outlink;
@@ -268,6 +270,8 @@ static int GPU_material_construct_end(GPUMaterial *material, const char *passnam
material->partvel = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_PARTICLE_VELOCITY));
if (material->builtins & GPU_PARTICLE_ANG_VELOCITY)
material->partangvel = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_PARTICLE_ANG_VELOCITY));
+ if (material->builtins & GPU_OBJECT_INFO)
+ material->objectinfoloc = GPU_shader_get_uniform(shader, GPU_builtin_name(GPU_OBJECT_INFO));
return 1;
}
else {
@@ -308,9 +312,11 @@ void GPU_material_free(ListBase *gpumaterial)
BLI_freelistN(gpumaterial);
}
-bool GPU_lamp_override_visible(GPULamp *lamp, SceneRenderLayer *srl, Material *ma)
+bool GPU_lamp_visible(GPULamp *lamp, SceneRenderLayer *srl, Material *ma)
{
- if (srl && srl->light_override)
+ if (lamp->hide)
+ return false;
+ else if (srl && srl->light_override)
return BKE_group_object_exists(srl->light_override, lamp->ob);
else if (ma && ma->group)
return BKE_group_object_exists(ma->group, lamp->ob);
@@ -334,8 +340,8 @@ void GPU_material_bind(
for (LinkData *nlink = material->lamps.first; nlink; nlink = nlink->next) {
GPULamp *lamp = nlink->data;
- if (!lamp->hide && (lamp->lay & viewlay) && (!(lamp->mode & LA_LAYER) || (lamp->lay & oblay)) &&
- GPU_lamp_override_visible(lamp, srl, material->ma))
+ if ((lamp->lay & viewlay) && (!(lamp->mode & LA_LAYER) || (lamp->lay & oblay)) &&
+ GPU_lamp_visible(lamp, srl, material->ma))
{
lamp->dynenergy = lamp->energy;
copy_v3_v3(lamp->dyncol, lamp->col);
@@ -398,9 +404,14 @@ void GPU_material_bind(
}
}
+GPUBuiltin GPU_get_material_builtins(GPUMaterial *material)
+{
+ return material->builtins;
+}
+
void GPU_material_bind_uniforms(
GPUMaterial *material, float obmat[4][4], float viewmat[4][4], float obcol[4],
- float autobumpscale, GPUParticleInfo *pi)
+ float autobumpscale, GPUParticleInfo *pi, float object_info[3])
{
if (material->pass) {
GPUShader *shader = GPU_pass_shader(material->pass);
@@ -441,7 +452,7 @@ void GPU_material_bind_uniforms(
GPU_shader_uniform_vector(shader, material->partscalarpropsloc, 4, 1, pi->scalprops);
}
if (material->builtins & GPU_PARTICLE_LOCATION) {
- GPU_shader_uniform_vector(shader, material->partcoloc, 3, 1, pi->location);
+ GPU_shader_uniform_vector(shader, material->partcoloc, 4, 1, pi->location);
}
if (material->builtins & GPU_PARTICLE_VELOCITY) {
GPU_shader_uniform_vector(shader, material->partvel, 3, 1, pi->velocity);
@@ -449,6 +460,9 @@ void GPU_material_bind_uniforms(
if (material->builtins & GPU_PARTICLE_ANG_VELOCITY) {
GPU_shader_uniform_vector(shader, material->partangvel, 3, 1, pi->angular_velocity);
}
+ if (material->builtins & GPU_OBJECT_INFO) {
+ GPU_shader_uniform_vector(shader, material->objectinfoloc, 3, 1, object_info);
+ }
}
}
@@ -665,7 +679,7 @@ static void ramp_blend(
GPU_link(mat, names[type], fac, col1, col2, r_col);
}
-static void do_colorband_blend(
+static void BKE_colorband_eval_blend(
GPUMaterial *mat, ColorBand *coba, GPUNodeLink *fac, float rampfac, int type,
GPUNodeLink *incol, GPUNodeLink **r_col)
{
@@ -674,7 +688,7 @@ static void do_colorband_blend(
int size;
/* do colorband */
- colorband_table_RGBA(coba, &array, &size);
+ BKE_colorband_evaluate_table_rgba(coba, &array, &size);
GPU_link(mat, "valtorgb", fac, GPU_texture(size, array), &col, &tmp);
/* use alpha in fac */
@@ -697,7 +711,7 @@ static void ramp_diffuse_result(GPUShadeInput *shi, GPUNodeLink **diff)
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);
+ BKE_colorband_eval_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, *diff, diff);
}
}
}
@@ -734,7 +748,7 @@ static void add_to_diffuse(
}
/* colorband + blend */
- do_colorband_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol);
+ BKE_colorband_eval_blend(mat, ma->ramp_col, fac, ma->rampfac_col, ma->rampblend_col, shi->rgb, &addcol);
}
}
else
@@ -756,7 +770,7 @@ static void ramp_spec_result(GPUShadeInput *shi, GPUNodeLink **spec)
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);
+ BKE_colorband_eval_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
}
}
@@ -788,7 +802,7 @@ static void do_specular_ramp(GPUShadeInput *shi, GPUNodeLink *is, GPUNodeLink *t
}
/* colorband + blend */
- do_colorband_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
+ BKE_colorband_eval_blend(mat, ma->ramp_spec, fac, ma->rampfac_spec, ma->rampblend_spec, *spec, spec);
}
}
@@ -1891,7 +1905,7 @@ GPUMaterial *GPU_material_matcap(Scene *scene, Material *ma, bool use_opensubdiv
GPU_material_output_link(mat, outlink);
- GPU_material_construct_end(mat, "matcap_pass");
+ gpu_material_construct_end(mat, "matcap_pass");
/* note that even if building the shader fails in some way, we still keep
* it to avoid trying to compile again and again, and simple do not use
@@ -2044,7 +2058,7 @@ static void do_world_tex(GPUShadeInput *shi, struct World *wo, GPUNodeLink **hor
}
}
-static void GPU_material_old_world(struct GPUMaterial *mat, struct World *wo)
+static void gpu_material_old_world(struct GPUMaterial *mat, struct World *wo)
{
GPUShadeInput shi;
GPUShadeResult shr;
@@ -2112,17 +2126,18 @@ GPUMaterial *GPU_material_world(struct Scene *scene, struct World *wo)
mat->type = GPU_MATERIAL_TYPE_WORLD;
/* create nodes */
- if (BKE_scene_use_new_shading_nodes(scene) && wo->nodetree && wo->use_nodes)
+ if (BKE_scene_use_new_shading_nodes(scene) && wo->nodetree && wo->use_nodes) {
ntreeGPUMaterialNodes(wo->nodetree, mat, NODE_NEW_SHADING);
+ }
else {
- GPU_material_old_world(mat, wo);
+ gpu_material_old_world(mat, wo);
}
if (GPU_material_do_color_management(mat))
if (mat->outlink)
GPU_link(mat, "linearrgb_to_srgb", mat->outlink, &mat->outlink);
- GPU_material_construct_end(mat, wo->id.name);
+ gpu_material_construct_end(mat, wo->id.name);
/* note that even if building the shader fails in some way, we still keep
* it to avoid trying to compile again and again, and simple do not use
@@ -2188,7 +2203,7 @@ GPUMaterial *GPU_material_from_blender(Scene *scene, Material *ma, bool use_open
if (mat->outlink)
GPU_link(mat, "linearrgb_to_srgb", mat->outlink, &mat->outlink);
- GPU_material_construct_end(mat, ma->id.name);
+ gpu_material_construct_end(mat, ma->id.name);
/* note that even if building the shader fails in some way, we still keep
* it to avoid trying to compile again and again, and simple do not use
diff --git a/source/blender/gpu/intern/gpu_select.c b/source/blender/gpu/intern/gpu_select.c
index 58582232cd5..291a552a041 100644
--- a/source/blender/gpu/intern/gpu_select.c
+++ b/source/blender/gpu/intern/gpu_select.c
@@ -29,109 +29,92 @@
* Interface for accessing gpu-related methods for selection. The semantics will be
* similar to glRenderMode(GL_SELECT) since the goal is to maintain compatibility.
*/
+#include <stdlib.h>
+
#include "GPU_select.h"
#include "GPU_extensions.h"
#include "GPU_glew.h"
-
+
#include "MEM_guardedalloc.h"
#include "DNA_userdef_types.h"
#include "BLI_utildefines.h"
-/* Ad hoc number of queries to allocate to skip doing many glGenQueries */
-#define ALLOC_QUERIES 200
-
-typedef struct GPUQueryState {
+#include "gpu_select_private.h"
+
+/* Internal algorithm used */
+enum {
+ /** GL_SELECT, legacy OpenGL selection */
+ ALGO_GL_LEGACY = 1,
+ /** glBegin/EndQuery(GL_SAMPLES_PASSED... ), `gpu_select_query.c`
+ * Only sets 4th component (ID) correctly. */
+ ALGO_GL_QUERY = 2,
+ /** Read depth buffer for every drawing pass and extract depths, `gpu_select_pick.c`
+ * Only sets 4th component (ID) correctly. */
+ ALGO_GL_PICK = 3,
+};
+
+typedef struct GPUSelectState {
/* To ignore selection id calls when not initialized */
bool select_is_active;
- /* Tracks whether a query has been issued so that gpu_load_id can end the previous one */
- bool query_issued;
- /* array holding the OpenGL query identifiers */
- unsigned int *queries;
- /* array holding the id corresponding to each query */
- unsigned int *id;
- /* number of queries in *queries and *id */
- unsigned int num_of_queries;
- /* index to the next query to start */
- unsigned int active_query;
/* flag to cache user preference for occlusion based selection */
bool use_gpu_select;
- /* cache on initialization */
- unsigned int *buffer;
- /* buffer size (stores number of integers, for actual size multiply by sizeof integer)*/
- unsigned int bufsize;
/* mode of operation */
char mode;
- unsigned int index;
- int oldhits;
-} GPUQueryState;
+ /* internal algorithm for selection */
+ char algorithm;
+ /* allow GPU_select_begin/end without drawing */
+ bool use_cache;
+} GPUSelectState;
-static GPUQueryState g_query_state = {0};
+static GPUSelectState g_select_state = {0};
/**
* initialize and provide buffer for results
*/
-void GPU_select_begin(unsigned int *buffer, unsigned int bufsize, rctf *input, char mode, int oldhits)
+void GPU_select_begin(uint *buffer, uint bufsize, const rcti *input, char mode, int oldhits)
{
- g_query_state.select_is_active = true;
- g_query_state.query_issued = false;
- g_query_state.active_query = 0;
- g_query_state.use_gpu_select = GPU_select_query_check_active();
- g_query_state.num_of_queries = 0;
- g_query_state.bufsize = bufsize;
- g_query_state.buffer = buffer;
- g_query_state.mode = mode;
- g_query_state.index = 0;
- g_query_state.oldhits = oldhits;
-
- if (!g_query_state.use_gpu_select) {
- glSelectBuffer(bufsize, (GLuint *)buffer);
- glRenderMode(GL_SELECT);
- glInitNames();
- glPushName(-1);
+ if (mode == GPU_SELECT_NEAREST_SECOND_PASS) {
+ /* In the case hits was '-1', don't start the second pass since it's not going to give useful results.
+ * As well as buffer overflow in 'gpu_select_query_load_id'. */
+ BLI_assert(oldhits != -1);
}
- else {
- float viewport[4];
-
- g_query_state.num_of_queries = ALLOC_QUERIES;
- g_query_state.queries = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.queries), "gpu selection queries");
- g_query_state.id = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.id), "gpu selection ids");
- glGenQueries(g_query_state.num_of_queries, g_query_state.queries);
+ g_select_state.select_is_active = true;
+ g_select_state.use_gpu_select = GPU_select_query_check_active();
+ g_select_state.mode = mode;
- glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT);
- /* disable writing to the framebuffer */
- glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
-
- /* In order to save some fill rate we minimize the viewport using rect.
- * We need to get the region of the scissor so that our geometry doesn't
- * get rejected before the depth test. Should probably cull rect against
- * scissor for viewport but this is a rare case I think */
- glGetFloatv(GL_SCISSOR_BOX, viewport);
- if (!input || input->xmin == input->xmax) {
- glViewport(viewport[0], viewport[1], 24, 24);
- }
- else {
- glViewport(viewport[0], viewport[1], (int)(input->xmax - input->xmin), (int)(input->ymax - input->ymin));
- }
+ if (ELEM(g_select_state.mode, GPU_SELECT_PICK_ALL, GPU_SELECT_PICK_NEAREST)) {
+ g_select_state.algorithm = ALGO_GL_PICK;
+ }
+ else if (!g_select_state.use_gpu_select) {
+ g_select_state.algorithm = ALGO_GL_LEGACY;
+ }
+ else {
+ g_select_state.algorithm = ALGO_GL_QUERY;
+ }
- /* occlusion queries operates on fragments that pass tests and since we are interested on all
- * objects in the view frustum independently of their order, we need to disable the depth test */
- if (mode == GPU_SELECT_ALL) {
- glDisable(GL_DEPTH_TEST);
- glDepthMask(GL_FALSE);
+ switch (g_select_state.algorithm) {
+ case ALGO_GL_LEGACY:
+ {
+ g_select_state.use_cache = false;
+ glSelectBuffer(bufsize, (GLuint *)buffer);
+ glRenderMode(GL_SELECT);
+ glInitNames();
+ glPushName(-1);
+ break;
}
- else if (mode == GPU_SELECT_NEAREST_FIRST_PASS) {
- glClear(GL_DEPTH_BUFFER_BIT);
- glEnable(GL_DEPTH_TEST);
- glDepthMask(GL_TRUE);
- glDepthFunc(GL_LEQUAL);
+ case ALGO_GL_QUERY:
+ {
+ g_select_state.use_cache = false;
+ gpu_select_query_begin((uint (*)[4])buffer, bufsize / 4, input, mode, oldhits);
+ break;
}
- else if (mode == GPU_SELECT_NEAREST_SECOND_PASS) {
- glEnable(GL_DEPTH_TEST);
- glDepthMask(GL_FALSE);
- glDepthFunc(GL_EQUAL);
+ default: /* ALGO_GL_PICK */
+ {
+ gpu_select_pick_begin((uint (*)[4])buffer, bufsize / 4, input, mode);
+ break;
}
}
}
@@ -143,44 +126,27 @@ void GPU_select_begin(unsigned int *buffer, unsigned int bufsize, rctf *input, c
*
* \warning We rely on the order of object rendering on passes to be the same for this to work.
*/
-bool GPU_select_load_id(unsigned int id)
+bool GPU_select_load_id(uint id)
{
/* if no selection mode active, ignore */
- if (!g_query_state.select_is_active)
+ if (!g_select_state.select_is_active)
return true;
- if (!g_query_state.use_gpu_select) {
- glLoadName(id);
- }
- else {
- if (g_query_state.query_issued) {
- glEndQuery(GL_SAMPLES_PASSED);
+ switch (g_select_state.algorithm) {
+ case ALGO_GL_LEGACY:
+ {
+ glLoadName(id);
+ return true;
}
- /* if required, allocate extra queries */
- if (g_query_state.active_query == g_query_state.num_of_queries) {
- g_query_state.num_of_queries += ALLOC_QUERIES;
- g_query_state.queries = MEM_reallocN(g_query_state.queries, g_query_state.num_of_queries * sizeof(*g_query_state.queries));
- g_query_state.id = MEM_reallocN(g_query_state.id, g_query_state.num_of_queries * sizeof(*g_query_state.id));
- glGenQueries(ALLOC_QUERIES, &g_query_state.queries[g_query_state.active_query]);
+ case ALGO_GL_QUERY:
+ {
+ return gpu_select_query_load_id(id);
}
-
- glBeginQuery(GL_SAMPLES_PASSED, g_query_state.queries[g_query_state.active_query]);
- g_query_state.id[g_query_state.active_query] = id;
- g_query_state.active_query++;
- g_query_state.query_issued = true;
-
- if (g_query_state.mode == GPU_SELECT_NEAREST_SECOND_PASS && g_query_state.index < g_query_state.oldhits) {
- if (g_query_state.buffer[g_query_state.index * 4 + 3] == id) {
- g_query_state.index++;
- return true;
- }
- else {
- return false;
- }
+ default: /* ALGO_GL_PICK */
+ {
+ return gpu_select_pick_load_id(id);
}
}
-
- return true;
}
/**
@@ -188,62 +154,30 @@ bool GPU_select_load_id(unsigned int id)
* Return number of hits and hits in buffer.
* if \a dopass is true, we will do a second pass with occlusion queries to get the closest hit.
*/
-unsigned int GPU_select_end(void)
+uint GPU_select_end(void)
{
- unsigned int hits = 0;
- if (!g_query_state.use_gpu_select) {
- glPopName();
- hits = glRenderMode(GL_RENDER);
- }
- else {
- int i;
-
- if (g_query_state.query_issued) {
- glEndQuery(GL_SAMPLES_PASSED);
+ uint hits = 0;
+
+ switch (g_select_state.algorithm) {
+ case ALGO_GL_LEGACY:
+ {
+ glPopName();
+ hits = glRenderMode(GL_RENDER);
+ break;
}
-
- for (i = 0; i < g_query_state.active_query; i++) {
- unsigned int result;
- glGetQueryObjectuiv(g_query_state.queries[i], GL_QUERY_RESULT, &result);
- if (result > 0) {
- if (g_query_state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
- int maxhits = g_query_state.bufsize / 4;
-
- if (hits < maxhits) {
- g_query_state.buffer[hits * 4] = 1;
- g_query_state.buffer[hits * 4 + 1] = 0xFFFF;
- g_query_state.buffer[hits * 4 + 2] = 0xFFFF;
- g_query_state.buffer[hits * 4 + 3] = g_query_state.id[i];
-
- hits++;
- }
- else {
- hits = -1;
- break;
- }
- }
- else {
- int j;
- /* search in buffer and make selected object first */
- for (j = 0; j < g_query_state.oldhits; j++) {
- if (g_query_state.buffer[j * 4 + 3] == g_query_state.id[i]) {
- g_query_state.buffer[j * 4 + 1] = 0;
- g_query_state.buffer[j * 4 + 2] = 0;
- }
- }
- break;
- }
- }
+ case ALGO_GL_QUERY:
+ {
+ hits = gpu_select_query_end();
+ break;
+ }
+ default: /* ALGO_GL_PICK */
+ {
+ hits = gpu_select_pick_end();
+ break;
}
-
- glDeleteQueries(g_query_state.num_of_queries, g_query_state.queries);
- MEM_freeN(g_query_state.queries);
- MEM_freeN(g_query_state.id);
- glPopAttrib();
- glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
- g_query_state.select_is_active = false;
+ g_select_state.select_is_active = false;
return hits;
}
@@ -260,3 +194,41 @@ bool GPU_select_query_check_active(void)
GPU_type_matches(GPU_DEVICE_NVIDIA, GPU_OS_UNIX, GPU_DRIVER_OPENSOURCE))));
}
+
+/* ----------------------------------------------------------------------------
+ * Caching
+ *
+ * Support multiple begin/end's as long as they are within the initial region.
+ * Currently only used by ALGO_GL_PICK.
+ */
+
+void GPU_select_cache_begin(void)
+{
+ /* validate on GPU_select_begin, clear if not supported */
+ BLI_assert(g_select_state.use_cache == false);
+ g_select_state.use_cache = true;
+ if (g_select_state.algorithm == ALGO_GL_PICK) {
+ gpu_select_pick_cache_begin();
+ }
+}
+
+void GPU_select_cache_load_id(void)
+{
+ BLI_assert(g_select_state.use_cache == true);
+ if (g_select_state.algorithm == ALGO_GL_PICK) {
+ gpu_select_pick_cache_load_id();
+ }
+}
+
+void GPU_select_cache_end(void)
+{
+ if (g_select_state.algorithm == ALGO_GL_PICK) {
+ gpu_select_pick_cache_end();
+ }
+ g_select_state.use_cache = false;
+}
+
+bool GPU_select_is_cached(void)
+{
+ return g_select_state.use_cache && gpu_select_pick_is_cached();
+}
diff --git a/source/blender/gpu/intern/gpu_select_pick.c b/source/blender/gpu/intern/gpu_select_pick.c
new file mode 100644
index 00000000000..3e65e2987e6
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_select_pick.c
@@ -0,0 +1,746 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2017 Blender Foundation.
+ * All rights reserved.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/gpu/intern/gpu_select_pick.c
+ * \ingroup gpu
+ *
+ * Custom select code for picking small regions (not efficient for large regions).
+ * `gpu_select_pick_*` API.
+ */
+#include <string.h>
+#include <stdlib.h>
+#include <float.h>
+
+#include "GPU_select.h"
+#include "GPU_extensions.h"
+#include "GPU_glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_rect.h"
+#include "BLI_listbase.h"
+#include "BLI_math_vector.h"
+#include "BLI_utildefines.h"
+
+#include "gpu_select_private.h"
+
+#include "BLI_strict_flags.h"
+
+/* #define DEBUG_PRINT */
+
+/* Alloc number for depths */
+#define ALLOC_DEPTHS 200
+
+/* Z-depth of cleared depth buffer */
+#define DEPTH_MAX 0xffffffff
+
+/* ----------------------------------------------------------------------------
+ * SubRectStride
+ */
+
+/* For looping over a sub-region of a rect, could be moved into 'rct.c'*/
+typedef struct SubRectStride {
+ uint start; /* start here */
+ uint span; /* read these */
+ uint span_len; /* len times (read span 'len' times). */
+ uint skip; /* skip those */
+} SubRectStride;
+
+/* we may want to change back to float if uint isn't well supported */
+typedef uint depth_t;
+
+/**
+ * Calculate values needed for looping over a sub-region (smaller buffer within a larger buffer).
+ *
+ * 'src' must be bigger than 'dst'.
+ */
+static void rect_subregion_stride_calc(const rcti *src, const rcti *dst, SubRectStride *r_sub)
+{
+ const int src_x = BLI_rcti_size_x(src);
+ // const int src_y = BLI_rcti_size_y(src);
+ const int dst_x = BLI_rcti_size_x(dst);
+ const int dst_y = BLI_rcti_size_y(dst);
+ const int x = dst->xmin - src->xmin;
+ const int y = dst->ymin - src->ymin;
+
+ BLI_assert(src->xmin <= dst->xmin && src->ymin <= dst->ymin &&
+ src->ymax >= dst->ymax && src->ymax >= dst->ymax);
+ BLI_assert(x >= 0 && y >= 0);
+
+ r_sub->start = (uint)((src_x * y) + x);
+ r_sub->span = (uint)dst_x;
+ r_sub->span_len = (uint)dst_y;
+ r_sub->skip = (uint)(src_x - dst_x);
+}
+
+/**
+ * Ignore depth clearing as a change,
+ * only check if its been changed _and_ filled in (ignore clearing since XRAY does this).
+ */
+BLI_INLINE bool depth_is_filled(const depth_t *prev, const depth_t *curr)
+{
+ return (*prev != *curr) && (*curr != DEPTH_MAX);
+}
+
+/* ----------------------------------------------------------------------------
+ * DepthBufCache
+ *
+ * Result of reading glReadPixels,
+ * use for both cache and non-cached storage.
+ */
+
+/* store result of glReadPixels */
+typedef struct DepthBufCache {
+ struct DepthBufCache *next, *prev;
+ uint id;
+ depth_t buf[0];
+} DepthBufCache;
+
+static DepthBufCache *depth_buf_malloc(uint rect_len)
+{
+ DepthBufCache *rect = MEM_mallocN(sizeof(DepthBufCache) + sizeof(depth_t) * rect_len, __func__);
+ rect->id = SELECT_ID_NONE;
+ return rect;
+}
+
+static bool depth_buf_rect_depth_any(
+ const DepthBufCache *rect_depth,
+ uint rect_len)
+{
+ const depth_t *curr = rect_depth->buf;
+ for (uint i = 0; i < rect_len; i++, curr++) {
+ if (*curr != DEPTH_MAX) {
+ return true;
+ }
+ }
+ return false;
+}
+
+static bool depth_buf_subrect_depth_any(
+ const DepthBufCache *rect_depth,
+ const SubRectStride *sub_rect)
+{
+ const depth_t *curr = rect_depth->buf + sub_rect->start;
+ for (uint i = 0; i < sub_rect->span_len; i++) {
+ const depth_t *curr_end = curr + sub_rect->span;
+ for (; curr < curr_end; curr++, curr++) {
+ if (*curr != DEPTH_MAX) {
+ return true;
+ }
+ }
+ curr += sub_rect->skip;
+ }
+ return false;
+}
+
+static bool depth_buf_rect_depth_any_filled(
+ const DepthBufCache *rect_prev, const DepthBufCache *rect_curr,
+ uint rect_len)
+{
+#if 0
+ return memcmp(rect_depth_a->buf, rect_depth_b->buf, rect_len * sizeof(depth_t)) != 0;
+#else
+ const depth_t *prev = rect_prev->buf;
+ const depth_t *curr = rect_curr->buf;
+ for (uint i = 0; i < rect_len; i++, curr++, prev++) {
+ if (depth_is_filled(prev, curr)) {
+ return true;
+ }
+ }
+ return false;
+#endif
+}
+
+/**
+ * Both buffers are the same size, just check if the sub-rect contains any differences.
+ */
+static bool depth_buf_subrect_depth_any_filled(
+ const DepthBufCache *rect_src, const DepthBufCache *rect_dst,
+ const SubRectStride *sub_rect)
+{
+ /* same as above but different rect sizes */
+ const depth_t *prev = rect_src->buf + sub_rect->start;
+ const depth_t *curr = rect_dst->buf + sub_rect->start;
+ for (uint i = 0; i < sub_rect->span_len; i++) {
+ const depth_t *curr_end = curr + sub_rect->span;
+ for (; curr < curr_end; prev++, curr++) {
+ if (depth_is_filled(prev, curr)) {
+ return true;
+ }
+ }
+ prev += sub_rect->skip;
+ curr += sub_rect->skip;
+ }
+ return false;
+}
+
+/* ----------------------------------------------------------------------------
+ * DepthID
+ *
+ * Internal structure for storing hits.
+ */
+
+typedef struct DepthID {
+ uint id;
+ depth_t depth;
+} DepthID;
+
+static int depth_id_cmp(const void *v1, const void *v2)
+{
+ const DepthID *d1 = v1, *d2 = v2;
+ if (d1->id < d2->id) {
+ return -1;
+ }
+ else if (d1->id > d2->id) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+static int depth_cmp(const void *v1, const void *v2)
+{
+ const DepthID *d1 = v1, *d2 = v2;
+ if (d1->depth < d2->depth) {
+ return -1;
+ }
+ else if (d1->depth > d2->depth) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+/* depth sorting */
+typedef struct GPUPickState {
+ /* cache on initialization */
+ uint (*buffer)[4];
+
+ /* buffer size (stores number of integers, for actual size multiply by sizeof integer)*/
+ uint bufsize;
+ /* mode of operation */
+ char mode;
+
+ /* OpenGL drawing, never use when (is_cached == true). */
+ struct {
+ /* The current depth, accumulated as we draw */
+ DepthBufCache *rect_depth;
+ /* Scratch buffer, avoid allocs every time (when not caching) */
+ DepthBufCache *rect_depth_test;
+
+ /* Pass to glReadPixels (x, y, w, h) */
+ int clip_readpixels[4];
+
+ /* Set after first draw */
+ bool is_init;
+ uint prev_id;
+ } gl;
+
+ /* src: data stored in 'cache' and 'gl',
+ * dst: use when cached region is smaller (where src -> dst isn't 1:1) */
+ struct {
+ rcti clip_rect;
+ uint rect_len;
+ } src, dst;
+
+ /* Store cache between `GPU_select_cache_begin/end` */
+ bool use_cache;
+ bool is_cached;
+ struct {
+ /* Cleanup used for iterating over both source and destination buffers:
+ * src.clip_rect -> dst.clip_rect */
+ SubRectStride sub_rect;
+
+ /* List of DepthBufCache, sized of 'src.clip_rect' */
+ ListBase bufs;
+ } cache;
+
+ /* Pickign methods */
+ union {
+ /* GPU_SELECT_PICK_ALL */
+ struct {
+ DepthID *hits;
+ uint hits_len;
+ uint hits_len_alloc;
+ } all;
+
+ /* GPU_SELECT_PICK_NEAREST */
+ struct {
+ uint *rect_id;
+ } nearest;
+ };
+} GPUPickState;
+
+
+static GPUPickState g_pick_state = {0};
+
+void gpu_select_pick_begin(
+ uint (*buffer)[4], uint bufsize,
+ const rcti *input, char mode)
+{
+ GPUPickState *ps = &g_pick_state;
+
+#ifdef DEBUG_PRINT
+ printf("%s: mode=%d, use_cache=%d, is_cache=%d\n", __func__, mode, ps->use_cache, ps->is_cached);
+#endif
+
+ ps->bufsize = bufsize;
+ ps->buffer = buffer;
+ ps->mode = mode;
+
+ const uint rect_len = (uint)(BLI_rcti_size_x(input) * BLI_rcti_size_y(input));
+ ps->dst.clip_rect = *input;
+ ps->dst.rect_len = rect_len;
+
+ /* Restrict OpenGL operations for when we don't have cache */
+ if (ps->is_cached == false) {
+
+ glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT);
+ /* disable writing to the framebuffer */
+ glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+
+ glEnable(GL_DEPTH_TEST);
+ glDepthMask(GL_TRUE);
+
+ if (mode == GPU_SELECT_PICK_ALL) {
+ /* Note that other depth settings (such as #GL_LEQUAL) work too,
+ * since the depth is always cleared.
+ * Noting this for cases when depth picking is used where drawing calls change depth settings. */
+ glDepthFunc(GL_ALWAYS);
+ }
+ else {
+ glDepthFunc(GL_LEQUAL);
+ }
+
+ /* set just in case */
+ glPixelTransferf(GL_DEPTH_BIAS, 0.0);
+ glPixelTransferf(GL_DEPTH_SCALE, 1.0);
+
+ float viewport[4];
+ glGetFloatv(GL_SCISSOR_BOX, viewport);
+
+ ps->src.clip_rect = *input;
+ ps->src.rect_len = rect_len;
+
+ ps->gl.clip_readpixels[0] = (int)viewport[0];
+ ps->gl.clip_readpixels[1] = (int)viewport[1];
+ ps->gl.clip_readpixels[2] = BLI_rcti_size_x(&ps->src.clip_rect);
+ ps->gl.clip_readpixels[3] = BLI_rcti_size_y(&ps->src.clip_rect);
+
+ glViewport(UNPACK4(ps->gl.clip_readpixels));
+
+ /* It's possible we don't want to clear depth buffer,
+ * so existing elements are masked by current z-buffer. */
+ glClear(GL_DEPTH_BUFFER_BIT);
+
+ /* scratch buffer (read new values here) */
+ ps->gl.rect_depth_test = depth_buf_malloc(rect_len);
+ ps->gl.rect_depth = depth_buf_malloc(rect_len);
+
+ /* set initial 'far' value */
+#if 0
+ glReadPixels(UNPACK4(ps->gl.clip_readpixels), GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, ps->gl.rect_depth->buf);
+#else
+ for (uint i = 0; i < rect_len; i++) {
+ ps->gl.rect_depth->buf[i] = DEPTH_MAX;
+ }
+#endif
+
+ ps->gl.is_init = false;
+ ps->gl.prev_id = 0;
+ }
+ else {
+ /* Using cache (ps->is_cached == true) */
+ /* src.clip_rect -> dst.clip_rect */
+ rect_subregion_stride_calc(&ps->src.clip_rect, &ps->dst.clip_rect, &ps->cache.sub_rect);
+ BLI_assert(ps->gl.rect_depth == NULL);
+ BLI_assert(ps->gl.rect_depth_test == NULL);
+ }
+
+ if (mode == GPU_SELECT_PICK_ALL) {
+ ps->all.hits = MEM_mallocN(sizeof(*ps->all.hits) * ALLOC_DEPTHS, __func__);
+ ps->all.hits_len = 0;
+ ps->all.hits_len_alloc = ALLOC_DEPTHS;
+ }
+ else {
+ /* Set to 0xff for SELECT_ID_NONE */
+ ps->nearest.rect_id = MEM_mallocN(sizeof(uint) * ps->dst.rect_len, __func__);
+ memset(ps->nearest.rect_id, 0xff, sizeof(uint) * ps->dst.rect_len);
+ }
+}
+
+/**
+ * Given 2x depths, we know are different - update the depth information
+ * use for both cached/uncached depth buffers.
+ */
+static void gpu_select_load_id_pass_all(const DepthBufCache *rect_curr)
+{
+ GPUPickState *ps = &g_pick_state;
+ const uint id = rect_curr->id;
+ /* find the best depth for this pass and store in 'all.hits' */
+ depth_t depth_best = DEPTH_MAX;
+
+#define EVAL_TEST() \
+ if (depth_best > *curr) { \
+ depth_best = *curr; \
+ } ((void)0)
+
+ if (ps->is_cached == false) {
+ const depth_t *curr = rect_curr->buf;
+ BLI_assert(ps->src.rect_len == ps->dst.rect_len);
+ const uint rect_len = ps->src.rect_len;
+ for (uint i = 0; i < rect_len; i++, curr++) {
+ EVAL_TEST();
+ }
+ }
+ else {
+ /* same as above but different rect sizes */
+ const depth_t *curr = rect_curr->buf + ps->cache.sub_rect.start;
+ for (uint i = 0; i < ps->cache.sub_rect.span_len; i++) {
+ const depth_t *curr_end = curr + ps->cache.sub_rect.span;
+ for (; curr < curr_end; curr++) {
+ EVAL_TEST();
+ }
+ curr += ps->cache.sub_rect.skip;
+ }
+ }
+
+#undef EVAL_TEST
+
+ /* ensure enough space */
+ if (UNLIKELY(ps->all.hits_len == ps->all.hits_len_alloc)) {
+ ps->all.hits_len_alloc += ALLOC_DEPTHS;
+ ps->all.hits = MEM_reallocN(ps->all.hits, ps->all.hits_len_alloc * sizeof(*ps->all.hits));
+ }
+ DepthID *d = &ps->all.hits[ps->all.hits_len++];
+ d->id = id;
+ d->depth = depth_best;
+}
+
+static void gpu_select_load_id_pass_nearest(const DepthBufCache *rect_prev, const DepthBufCache *rect_curr)
+{
+ GPUPickState *ps = &g_pick_state;
+ const uint id = rect_curr->id;
+ /* keep track each pixels ID in 'nearest.rect_id' */
+ if (id != SELECT_ID_NONE) {
+ uint *id_ptr = ps->nearest.rect_id;
+
+ /* Check against DEPTH_MAX because XRAY will clear the buffer,
+ * so previously set values will become unset.
+ * In this case just leave those id's left as-is. */
+#define EVAL_TEST() \
+ if (depth_is_filled(prev, curr)) { \
+ *id_ptr = id; \
+ } ((void)0)
+
+ if (ps->is_cached == false) {
+ const depth_t *prev = rect_prev->buf;
+ const depth_t *curr = rect_curr->buf;
+ BLI_assert(ps->src.rect_len == ps->dst.rect_len);
+ const uint rect_len = ps->src.rect_len;
+ for (uint i = 0; i < rect_len; i++, curr++, prev++, id_ptr++) {
+ EVAL_TEST();
+ }
+ }
+ else {
+ /* same as above but different rect sizes */
+ const depth_t *prev = rect_prev->buf + ps->cache.sub_rect.start;
+ const depth_t *curr = rect_curr->buf + ps->cache.sub_rect.start;
+ for (uint i = 0; i < ps->cache.sub_rect.span_len; i++) {
+ const depth_t *curr_end = curr + ps->cache.sub_rect.span;
+ for (; curr < curr_end; prev++, curr++, id_ptr++) {
+ EVAL_TEST();
+ }
+ prev += ps->cache.sub_rect.skip;
+ curr += ps->cache.sub_rect.skip;
+ }
+ }
+
+#undef EVAL_TEST
+ }
+}
+
+
+bool gpu_select_pick_load_id(uint id)
+{
+ GPUPickState *ps = &g_pick_state;
+ if (ps->gl.is_init) {
+ const uint rect_len = ps->src.rect_len;
+ glReadPixels(UNPACK4(ps->gl.clip_readpixels), GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, ps->gl.rect_depth_test->buf);
+ /* perform initial check since most cases the array remains unchanged */
+
+ bool do_pass = false;
+ if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
+ if (depth_buf_rect_depth_any(ps->gl.rect_depth_test, rect_len)) {
+ ps->gl.rect_depth_test->id = ps->gl.prev_id;
+ gpu_select_load_id_pass_all(ps->gl.rect_depth_test);
+ do_pass = true;
+ }
+ }
+ else {
+ if (depth_buf_rect_depth_any_filled(ps->gl.rect_depth, ps->gl.rect_depth_test, rect_len)) {
+ ps->gl.rect_depth_test->id = ps->gl.prev_id;
+ gpu_select_load_id_pass_nearest(ps->gl.rect_depth, ps->gl.rect_depth_test);
+ do_pass = true;
+ }
+ }
+
+ if (do_pass) {
+ /* Store depth in cache */
+ if (ps->use_cache) {
+ BLI_addtail(&ps->cache.bufs, ps->gl.rect_depth);
+ ps->gl.rect_depth = depth_buf_malloc(ps->src.rect_len);
+ }
+
+ SWAP(DepthBufCache *, ps->gl.rect_depth, ps->gl.rect_depth_test);
+
+ if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
+ /* we want new depths every time */
+ glClear(GL_DEPTH_BUFFER_BIT);
+ }
+ }
+ }
+
+ ps->gl.is_init = true;
+ ps->gl.prev_id = id;
+
+ return true;
+}
+
+uint gpu_select_pick_end(void)
+{
+ GPUPickState *ps = &g_pick_state;
+
+#ifdef DEBUG_PRINT
+ printf("%s\n", __func__);
+#endif
+
+ if (ps->is_cached == false) {
+ if (ps->gl.is_init) {
+ /* force finishing last pass */
+ gpu_select_pick_load_id(ps->gl.prev_id);
+ }
+ glPopAttrib();
+ glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+ }
+
+ /* assign but never free directly since it may be in cache */
+ DepthBufCache *rect_depth_final;
+
+ /* Store depth in cache */
+ if (ps->use_cache && !ps->is_cached) {
+ BLI_addtail(&ps->cache.bufs, ps->gl.rect_depth);
+ ps->gl.rect_depth = NULL;
+ rect_depth_final = ps->cache.bufs.last;
+ }
+ else if (ps->is_cached) {
+ rect_depth_final = ps->cache.bufs.last;
+ }
+ else {
+ /* common case, no cache */
+ rect_depth_final = ps->gl.rect_depth;
+ }
+
+ uint maxhits = g_pick_state.bufsize;
+ DepthID *depth_data;
+ uint depth_data_len = 0;
+
+ if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
+ depth_data = ps->all.hits;
+ depth_data_len = ps->all.hits_len;
+ /* move ownership */
+ ps->all.hits = NULL;
+ ps->all.hits_len = 0;
+ ps->all.hits_len_alloc = 0;
+ }
+ else {
+ /* GPU_SELECT_PICK_NEAREST */
+
+ /* Over alloc (unlikely we have as many depths as pixels) */
+ uint depth_data_len_first_pass = 0;
+ depth_data = MEM_mallocN(ps->dst.rect_len * sizeof(*depth_data), __func__);
+
+ /* Partially de-duplicating copy,
+ * when contiguous ID's are found - update their closest depth.
+ * This isn't essential but means there is less data to sort. */
+
+#define EVAL_TEST(i_src, i_dst) \
+ { \
+ const uint id = ps->nearest.rect_id[i_dst]; \
+ if (id != SELECT_ID_NONE) { \
+ const depth_t depth = rect_depth_final->buf[i_src]; \
+ if (depth_last == NULL || depth_last->id != id) { \
+ DepthID *d = &depth_data[depth_data_len_first_pass++]; \
+ d->id = id; \
+ d->depth = depth; \
+ } \
+ else if (depth_last->depth > depth) { \
+ depth_last->depth = depth; \
+ } \
+ } \
+ } ((void)0)
+
+ {
+ DepthID *depth_last = NULL;
+ if (ps->is_cached == false) {
+ for (uint i = 0; i < ps->src.rect_len; i++) {
+ EVAL_TEST(i, i);
+ }
+ }
+ else {
+ /* same as above but different rect sizes */
+ uint i_src = ps->cache.sub_rect.start, i_dst = 0;
+ for (uint j = 0; j < ps->cache.sub_rect.span_len; j++) {
+ const uint i_src_end = i_src + ps->cache.sub_rect.span;
+ for (; i_src < i_src_end; i_src++, i_dst++) {
+ EVAL_TEST(i_src, i_dst);
+ }
+ i_src += ps->cache.sub_rect.skip;
+ }
+ }
+ }
+
+#undef EVAL_TEST
+
+ qsort(depth_data, depth_data_len_first_pass, sizeof(DepthID), depth_id_cmp);
+
+ /* Sort by ID's then keep the best depth for each ID */
+ depth_data_len = 0;
+ {
+ DepthID *depth_last = NULL;
+ for (uint i = 0; i < depth_data_len_first_pass; i++) {
+ if (depth_last == NULL || depth_last->id != depth_data[i].id) {
+ depth_last = &depth_data[depth_data_len++];
+ *depth_last = depth_data[i];
+ }
+ else if (depth_last->depth > depth_data[i].depth) {
+ depth_last->depth = depth_data[i].depth;
+ }
+ }
+ }
+ }
+
+ /* Finally sort each unique (id, depth) pair by depth
+ * so the final hit-list is sorted by depth (nearest first) */
+ uint hits = 0;
+
+ if (depth_data_len > maxhits) {
+ hits = (uint)-1;
+ }
+ else {
+ /* leave sorting up to the caller */
+ qsort(depth_data, depth_data_len, sizeof(DepthID), depth_cmp);
+
+ for (uint i = 0; i < depth_data_len; i++) {
+#ifdef DEBUG_PRINT
+ printf(" hit: %u: depth %u\n", depth_data[i].id, depth_data[i].depth);
+#endif
+ /* first 3 are dummy values */
+ g_pick_state.buffer[hits][0] = 1;
+ g_pick_state.buffer[hits][1] = 0x0; /* depth_data[i].depth; */ /* unused */
+ g_pick_state.buffer[hits][2] = 0x0; /* z-far is currently never used. */
+ g_pick_state.buffer[hits][3] = depth_data[i].id;
+ hits++;
+ }
+ BLI_assert(hits < maxhits);
+ }
+
+ MEM_freeN(depth_data);
+
+ MEM_SAFE_FREE(ps->gl.rect_depth);
+ MEM_SAFE_FREE(ps->gl.rect_depth_test);
+
+ if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
+ /* 'hits' already freed as 'depth_data' */
+ }
+ else {
+ MEM_freeN(ps->nearest.rect_id);
+ ps->nearest.rect_id = NULL;
+ }
+
+ if (ps->use_cache) {
+ ps->is_cached = true;
+ }
+
+ return hits;
+}
+
+/* ----------------------------------------------------------------------------
+ * Caching
+ *
+ * Support multiple begin/end's reusing depth buffers.
+ */
+
+void gpu_select_pick_cache_begin(void)
+{
+ BLI_assert(g_pick_state.use_cache == false);
+#ifdef DEBUG_PRINT
+ printf("%s\n", __func__);
+#endif
+ g_pick_state.use_cache = true;
+ g_pick_state.is_cached = false;
+}
+
+void gpu_select_pick_cache_end(void)
+{
+#ifdef DEBUG_PRINT
+ printf("%s: with %d buffers\n", __func__, BLI_listbase_count(&g_pick_state.cache.bufs));
+#endif
+ g_pick_state.use_cache = false;
+ g_pick_state.is_cached = false;
+
+ BLI_freelistN(&g_pick_state.cache.bufs);
+}
+
+/* is drawing needed? */
+bool gpu_select_pick_is_cached(void)
+{
+ return g_pick_state.is_cached;
+}
+
+void gpu_select_pick_cache_load_id(void)
+{
+ BLI_assert(g_pick_state.is_cached == true);
+ GPUPickState *ps = &g_pick_state;
+#ifdef DEBUG_PRINT
+ printf("%s (building depth from cache)\n", __func__);
+#endif
+ for (DepthBufCache *rect_depth = ps->cache.bufs.first; rect_depth; rect_depth = rect_depth->next) {
+ if (rect_depth->next != NULL) {
+ /* we know the buffers differ, but this sub-region may not.
+ * double check before adding an id-pass */
+ if (g_pick_state.mode == GPU_SELECT_PICK_ALL) {
+ if (depth_buf_subrect_depth_any(rect_depth->next, &ps->cache.sub_rect)) {
+ gpu_select_load_id_pass_all(rect_depth->next);
+ }
+ }
+ else {
+ if (depth_buf_subrect_depth_any_filled(rect_depth, rect_depth->next, &ps->cache.sub_rect)) {
+ gpu_select_load_id_pass_nearest(rect_depth, rect_depth->next);
+ }
+ }
+ }
+ }
+}
diff --git a/source/blender/gpu/intern/gpu_select_private.h b/source/blender/gpu/intern/gpu_select_private.h
new file mode 100644
index 00000000000..8935bd7b253
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_select_private.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2014 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Antony Riakiotakis.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/gpu/intern/gpu_select_private.h
+ * \ingroup gpu
+ *
+ * Selection implementations.
+ */
+
+#ifndef __GPU_SELECT_PRIVATE_H__
+#define __GPU_SELECT_PRIVATE_H__
+
+/* gpu_select_pick */
+void gpu_select_pick_begin(unsigned int (*buffer)[4], unsigned int bufsize, const rcti *input, char mode);
+bool gpu_select_pick_load_id(unsigned int id);
+unsigned int gpu_select_pick_end(void);
+
+void gpu_select_pick_cache_begin(void);
+void gpu_select_pick_cache_end(void);
+bool gpu_select_pick_is_cached(void);
+void gpu_select_pick_cache_load_id(void);
+
+/* gpu_select_sample_query */
+void gpu_select_query_begin(unsigned int (*buffer)[4], unsigned int bufsize, const rcti *input, char mode, int oldhits);
+bool gpu_select_query_load_id(unsigned int id);
+unsigned int gpu_select_query_end(void);
+
+
+#define SELECT_ID_NONE ((unsigned int)0xffffffff)
+
+#endif /* __GPU_SELECT_PRIVATE_H__ */
diff --git a/source/blender/gpu/intern/gpu_select_sample_query.c b/source/blender/gpu/intern/gpu_select_sample_query.c
new file mode 100644
index 00000000000..9bb96ea67a2
--- /dev/null
+++ b/source/blender/gpu/intern/gpu_select_sample_query.c
@@ -0,0 +1,213 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2014 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Antony Riakiotakis.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/gpu/intern/gpu_select_sample_query.c
+ * \ingroup gpu
+ *
+ * Interface for accessing gpu-related methods for selection. The semantics will be
+ * similar to glRenderMode(GL_SELECT) since the goal is to maintain compatibility.
+ */
+
+#include <stdlib.h>
+
+#include "GPU_select.h"
+#include "GPU_extensions.h"
+#include "GPU_glew.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_rect.h"
+
+#include "BLI_utildefines.h"
+
+#include "gpu_select_private.h"
+
+
+/* Ad hoc number of queries to allocate to skip doing many glGenQueries */
+#define ALLOC_QUERIES 200
+
+typedef struct GPUQueryState {
+ /* Tracks whether a query has been issued so that gpu_load_id can end the previous one */
+ bool query_issued;
+ /* array holding the OpenGL query identifiers */
+ uint *queries;
+ /* array holding the id corresponding to each query */
+ uint *id;
+ /* number of queries in *queries and *id */
+ uint num_of_queries;
+ /* index to the next query to start */
+ uint active_query;
+ /* cache on initialization */
+ uint (*buffer)[4];
+ /* buffer size (stores number of integers, for actual size multiply by sizeof integer)*/
+ uint bufsize;
+ /* mode of operation */
+ char mode;
+ uint index;
+ int oldhits;
+} GPUQueryState;
+
+static GPUQueryState g_query_state = {0};
+
+
+void gpu_select_query_begin(
+ uint (*buffer)[4], uint bufsize,
+ const rcti *input, char mode,
+ int oldhits)
+{
+ float viewport[4];
+
+ g_query_state.query_issued = false;
+ g_query_state.active_query = 0;
+ g_query_state.num_of_queries = 0;
+ g_query_state.bufsize = bufsize;
+ g_query_state.buffer = buffer;
+ g_query_state.mode = mode;
+ g_query_state.index = 0;
+ g_query_state.oldhits = oldhits;
+
+ g_query_state.num_of_queries = ALLOC_QUERIES;
+
+ g_query_state.queries = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.queries), "gpu selection queries");
+ g_query_state.id = MEM_mallocN(g_query_state.num_of_queries * sizeof(*g_query_state.id), "gpu selection ids");
+ glGenQueries(g_query_state.num_of_queries, g_query_state.queries);
+
+ glPushAttrib(GL_DEPTH_BUFFER_BIT | GL_VIEWPORT_BIT);
+ /* disable writing to the framebuffer */
+ glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
+
+ /* In order to save some fill rate we minimize the viewport using rect.
+ * We need to get the region of the scissor so that our geometry doesn't
+ * get rejected before the depth test. Should probably cull rect against
+ * scissor for viewport but this is a rare case I think */
+ glGetFloatv(GL_SCISSOR_BOX, viewport);
+ glViewport(viewport[0], viewport[1], BLI_rcti_size_x(input), BLI_rcti_size_y(input));
+
+ /* occlusion queries operates on fragments that pass tests and since we are interested on all
+ * objects in the view frustum independently of their order, we need to disable the depth test */
+ if (mode == GPU_SELECT_ALL) {
+ glDisable(GL_DEPTH_TEST);
+ glDepthMask(GL_FALSE);
+ }
+ else if (mode == GPU_SELECT_NEAREST_FIRST_PASS) {
+ glClear(GL_DEPTH_BUFFER_BIT);
+ glEnable(GL_DEPTH_TEST);
+ glDepthMask(GL_TRUE);
+ glDepthFunc(GL_LEQUAL);
+ }
+ else if (mode == GPU_SELECT_NEAREST_SECOND_PASS) {
+ glEnable(GL_DEPTH_TEST);
+ glDepthMask(GL_FALSE);
+ glDepthFunc(GL_EQUAL);
+ }
+}
+
+bool gpu_select_query_load_id(uint id)
+{
+ if (g_query_state.query_issued) {
+ glEndQuery(GL_SAMPLES_PASSED);
+ }
+ /* if required, allocate extra queries */
+ if (g_query_state.active_query == g_query_state.num_of_queries) {
+ g_query_state.num_of_queries += ALLOC_QUERIES;
+ g_query_state.queries = MEM_reallocN(g_query_state.queries, g_query_state.num_of_queries * sizeof(*g_query_state.queries));
+ g_query_state.id = MEM_reallocN(g_query_state.id, g_query_state.num_of_queries * sizeof(*g_query_state.id));
+ glGenQueries(ALLOC_QUERIES, &g_query_state.queries[g_query_state.active_query]);
+ }
+
+ glBeginQuery(GL_SAMPLES_PASSED, g_query_state.queries[g_query_state.active_query]);
+ g_query_state.id[g_query_state.active_query] = id;
+ g_query_state.active_query++;
+ g_query_state.query_issued = true;
+
+ if (g_query_state.mode == GPU_SELECT_NEAREST_SECOND_PASS) {
+ /* Second pass should never run if first pass fails, can read past 'bufsize' in this case. */
+ BLI_assert(g_query_state.oldhits != -1);
+ if (g_query_state.index < g_query_state.oldhits) {
+ if (g_query_state.buffer[g_query_state.index][3] == id) {
+ g_query_state.index++;
+ return true;
+ }
+ else {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+uint gpu_select_query_end(void)
+{
+ int i;
+
+ uint hits = 0;
+ const uint maxhits = g_query_state.bufsize;
+
+ if (g_query_state.query_issued) {
+ glEndQuery(GL_SAMPLES_PASSED);
+ }
+
+ for (i = 0; i < g_query_state.active_query; i++) {
+ uint result;
+ glGetQueryObjectuiv(g_query_state.queries[i], GL_QUERY_RESULT, &result);
+ if (result > 0) {
+ if (g_query_state.mode != GPU_SELECT_NEAREST_SECOND_PASS) {
+
+ if (hits < maxhits) {
+ g_query_state.buffer[hits][0] = 1;
+ g_query_state.buffer[hits][1] = 0xFFFF;
+ g_query_state.buffer[hits][2] = 0xFFFF;
+ g_query_state.buffer[hits][3] = g_query_state.id[i];
+
+ hits++;
+ }
+ else {
+ hits = -1;
+ break;
+ }
+ }
+ else {
+ int j;
+ /* search in buffer and make selected object first */
+ for (j = 0; j < g_query_state.oldhits; j++) {
+ if (g_query_state.buffer[j][3] == g_query_state.id[i]) {
+ g_query_state.buffer[j][1] = 0;
+ g_query_state.buffer[j][2] = 0;
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ glDeleteQueries(g_query_state.num_of_queries, g_query_state.queries);
+ MEM_freeN(g_query_state.queries);
+ MEM_freeN(g_query_state.id);
+ glPopAttrib();
+ glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+
+ return hits;
+}
diff --git a/source/blender/gpu/intern/gpu_shader.c b/source/blender/gpu/intern/gpu_shader.c
index 14f2764b009..b579f87698c 100644
--- a/source/blender/gpu/intern/gpu_shader.c
+++ b/source/blender/gpu/intern/gpu_shader.c
@@ -39,6 +39,7 @@
#include "GPU_glew.h"
#include "GPU_shader.h"
#include "GPU_texture.h"
+#include "GPU_material.h"
/* TODO(sergey): Find better default values for this constants. */
#define MAX_DEFINE_LENGTH 1024
diff --git a/source/blender/gpu/intern/gpu_texture.c b/source/blender/gpu/intern/gpu_texture.c
index 54f0003c086..1c97c2ce811 100644
--- a/source/blender/gpu/intern/gpu_texture.c
+++ b/source/blender/gpu/intern/gpu_texture.c
@@ -79,7 +79,7 @@ static unsigned char *GPU_texture_convert_pixels(int length, const float *fpixel
return pixels;
}
-static void GPU_glTexSubImageEmpty(GLenum target, GLenum format, int x, int y, int w, int h)
+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");
@@ -193,7 +193,7 @@ static GPUTexture *GPU_texture_create_nD(
pixels ? pixels : fpixels);
if (tex->w > w) {
- GPU_glTexSubImageEmpty(tex->target, format, w, 0, tex->w - w, 1);
+ gpu_glTexSubImageEmpty(tex->target, format, w, 0, tex->w - w, 1);
}
}
}
@@ -210,10 +210,12 @@ static GPUTexture *GPU_texture_create_nD(
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 (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);
+ }
}
}
diff --git a/source/blender/gpu/shaders/gpu_shader_fx_ssao_frag.glsl b/source/blender/gpu/shaders/gpu_shader_fx_ssao_frag.glsl
index 50c8e255162..f19ff4ec65a 100644
--- a/source/blender/gpu/shaders/gpu_shader_fx_ssao_frag.glsl
+++ b/source/blender/gpu/shaders/gpu_shader_fx_ssao_frag.glsl
@@ -75,7 +75,7 @@ float calculate_ssao_factor(float depth)
float f = dot(dir, normal);
/* use minor bias here to avoid self shadowing */
- if (f > 0.05 * len + 0.0001)
+ if (f > 0.05 * len)
factor += f * 1.0 / (len * (1.0 + len * len * ssao_params.z));
}
}
diff --git a/source/blender/gpu/shaders/gpu_shader_material.glsl b/source/blender/gpu/shaders/gpu_shader_material.glsl
index 0f3ffa8244b..a0ca719e207 100644
--- a/source/blender/gpu/shaders/gpu_shader_material.glsl
+++ b/source/blender/gpu/shaders/gpu_shader_material.glsl
@@ -189,16 +189,18 @@ void geom(
}
void particle_info(
- vec4 sprops, vec3 loc, vec3 vel, vec3 avel,
- out float index, out float age, out float life_time, out vec3 location,
+ vec4 sprops, vec4 loc, vec3 vel, vec3 avel,
+ out float index, out float random, out float age,
+ out float life_time, out vec3 location,
out float size, out vec3 velocity, out vec3 angular_velocity)
{
index = sprops.x;
+ random = loc.w;
age = sprops.y;
life_time = sprops.z;
size = sprops.w;
- location = loc;
+ location = loc.xyz;
velocity = vel;
angular_velocity = avel;
}
@@ -403,7 +405,7 @@ void math_modulo(float val1, float val2, out float outval)
/* change sign to match C convention, mod in GLSL will take absolute for negative numbers,
* see https://www.opengl.org/sdk/docs/man/html/mod.xhtml */
- outval = (val1 > 0.0) ? outval : -outval;
+ outval = (val1 > 0.0) ? outval : outval - val2;
}
void math_abs(float val1, out float outval)
@@ -954,8 +956,8 @@ void texco_orco(vec3 attorco, out vec3 orco)
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); */
+ /* 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);
}
@@ -2378,11 +2380,19 @@ void shade_alpha_obcolor(vec4 col, vec4 obcol, out vec4 outcol)
/*********** NEW SHADER UTILITIES **************/
-float fresnel_dielectric(vec3 Incoming, vec3 Normal, float eta)
+float fresnel_dielectric_0(float eta)
+{
+ /* compute fresnel reflactance at normal incidence => cosi = 1.0 */
+ float A = (eta - 1.0) / (eta + 1.0);
+
+ return A * A;
+}
+
+float fresnel_dielectric_cos(float cosi, float eta)
{
/* compute fresnel reflectance without explicitly computing
* the refracted direction */
- float c = abs(dot(Incoming, Normal));
+ float c = abs(cosi);
float g = eta * eta - 1.0 + c * c;
float result;
@@ -2399,6 +2409,13 @@ float fresnel_dielectric(vec3 Incoming, vec3 Normal, float eta)
return result;
}
+float fresnel_dielectric(vec3 Incoming, vec3 Normal, float eta)
+{
+ /* compute fresnel reflectance without explicitly computing
+ * the refracted direction */
+ return fresnel_dielectric_cos(dot(Incoming, Normal), eta);
+}
+
float hypot(float x, float y)
{
return sqrt(x * x + y * y);
@@ -2463,8 +2480,7 @@ uint hash(int kx, int ky, int kz)
float bits_to_01(uint bits)
{
- float x = float(bits) * (1.0 / float(0xffffffffu));
- return x;
+ return (float(bits) / 4294967295.0);
}
float cellnoise(vec3 p)
@@ -2492,6 +2508,61 @@ float floorfrac(float x, out int i)
return x - i;
}
+
+/* Principled BSDF operations */
+
+float sqr(float a)
+{
+ return a*a;
+}
+
+float schlick_fresnel(float u)
+{
+ float m = clamp(1.0 - u, 0.0, 1.0);
+ float m2 = m * m;
+ return m2 * m2 * m; // pow(m,5)
+}
+
+float GTR1(float NdotH, float a)
+{
+ if (a >= 1.0) {
+ return M_1_PI;
+ }
+
+ a = max(a, 0.001);
+ float a2 = a*a;
+ float t = 1.0 + (a2 - 1.0) * NdotH*NdotH;
+ return (a2 - 1.0) / (M_PI * log(a2) * t);
+}
+
+float GTR2(float NdotH, float a)
+{
+ float a2 = a*a;
+ float t = 1.0 + (a2 - 1.0) * NdotH*NdotH;
+ return a2 / (M_PI * t*t);
+}
+
+float GTR2_aniso(float NdotH, float HdotX, float HdotY, float ax, float ay)
+{
+ return 1.0 / (M_PI * ax*ay * sqr(sqr(HdotX / ax) + sqr(HdotY / ay) + NdotH*NdotH));
+}
+
+float smithG_GGX(float NdotV, float alphaG)
+{
+ float a = alphaG*alphaG;
+ float b = NdotV*NdotV;
+ return 1.0 / (NdotV + sqrt(a + b - a * b));
+}
+
+vec3 rotate_vector(vec3 p, vec3 n, float theta) {
+ return (
+ p * cos(theta) + cross(n, p) *
+ sin(theta) + n * dot(p, n) *
+ (1.0 - cos(theta))
+ );
+}
+
+
/*********** NEW SHADER NODES ***************/
#define NUM_LIGHTS 3
@@ -2528,7 +2599,8 @@ void node_bsdf_glossy(vec4 color, float roughness, vec3 N, out vec4 result)
vec3 light_specular = gl_LightSource[i].specular.rgb;
/* we mix in some diffuse so low roughness still shows up */
- float bsdf = 0.5 * pow(max(dot(N, H), 0.0), 1.0 / roughness);
+ float r2 = roughness * roughness;
+ float bsdf = 0.5 * pow(max(dot(N, H), 0.0), 1.0 / r2);
bsdf += 0.5 * max(dot(N, light_position), 0.0);
L += light_specular * bsdf;
}
@@ -2553,6 +2625,125 @@ void node_bsdf_toon(vec4 color, float size, float tsmooth, vec3 N, out vec4 resu
node_bsdf_diffuse(color, 0.0, N, result);
}
+void node_bsdf_principled(vec4 base_color, float subsurface, vec3 subsurface_radius, vec4 subsurface_color, float metallic, float specular,
+ float specular_tint, float roughness, float anisotropic, float anisotropic_rotation, float sheen, float sheen_tint, float clearcoat,
+ float clearcoat_roughness, float ior, float transmission, float transmission_roughness, vec3 N, vec3 CN, vec3 T, vec3 I, out vec4 result)
+{
+ /* ambient light */
+ // TODO: set ambient light to an appropriate value
+ vec3 L = mix(0.1, 0.03, metallic) * mix(base_color.rgb, subsurface_color.rgb, subsurface * (1.0 - metallic));
+
+ float eta = (2.0 / (1.0 - sqrt(0.08 * specular))) - 1.0;
+
+ /* set the viewing vector */
+ vec3 V = (gl_ProjectionMatrix[3][3] == 0.0) ? -normalize(I) : vec3(0.0, 0.0, 1.0);
+
+ /* get the tangent */
+ vec3 Tangent = T;
+ if (T == vec3(0.0)) {
+ // if no tangent is set, use a default tangent
+ if(N.x != N.y || N.x != N.z) {
+ Tangent = vec3(N.z-N.y, N.x-N.z, N.y-N.x); // (1,1,1) x N
+ }
+ else {
+ Tangent = vec3(N.z-N.y, N.x+N.z, -N.y-N.x); // (-1,1,1) x N
+ }
+ }
+
+ /* rotate tangent */
+ if (anisotropic_rotation != 0.0) {
+ Tangent = rotate_vector(Tangent, N, anisotropic_rotation * 2.0 * M_PI);
+ }
+
+ /* calculate the tangent and bitangent */
+ vec3 Y = normalize(cross(N, Tangent));
+ vec3 X = cross(Y, N);
+
+ /* fresnel normalization parameters */
+ float F0 = fresnel_dielectric_0(eta);
+ float F0_norm = 1.0 / (1.0 - F0);
+
+ /* directional lights */
+ for (int i = 0; i < NUM_LIGHTS; i++) {
+ vec3 light_position_world = gl_LightSource[i].position.xyz;
+ vec3 light_position = normalize(light_position_world);
+
+ vec3 H = normalize(light_position + V);
+
+ vec3 light_diffuse = gl_LightSource[i].diffuse.rgb;
+ vec3 light_specular = gl_LightSource[i].specular.rgb;
+
+ float NdotL = dot(N, light_position);
+ float NdotV = dot(N, V);
+ float LdotH = dot(light_position, H);
+
+ vec3 diffuse_and_specular_bsdf = vec3(0.0);
+ if (NdotL >= 0.0 && NdotV >= 0.0) {
+ float NdotH = dot(N, H);
+
+ float Cdlum = 0.3 * base_color.r + 0.6 * base_color.g + 0.1 * base_color.b; // luminance approx.
+
+ vec3 Ctint = Cdlum > 0 ? base_color.rgb / Cdlum : vec3(1.0); // normalize lum. to isolate hue+sat
+ vec3 Cspec0 = mix(specular * 0.08 * mix(vec3(1.0), Ctint, specular_tint), base_color.rgb, metallic);
+ vec3 Csheen = mix(vec3(1.0), Ctint, sheen_tint);
+
+ // Diffuse fresnel - go from 1 at normal incidence to .5 at grazing
+ // and mix in diffuse retro-reflection based on roughness
+
+ float FL = schlick_fresnel(NdotL), FV = schlick_fresnel(NdotV);
+ float Fd90 = 0.5 + 2.0 * LdotH*LdotH * roughness;
+ float Fd = mix(1.0, Fd90, FL) * mix(1.0, Fd90, FV);
+
+ // Based on Hanrahan-Krueger brdf approximation of isotropic bssrdf
+ // 1.25 scale is used to (roughly) preserve albedo
+ // Fss90 used to "flatten" retroreflection based on roughness
+ float Fss90 = LdotH*LdotH * roughness;
+ float Fss = mix(1.0, Fss90, FL) * mix(1.0, Fss90, FV);
+ float ss = 1.25 * (Fss * (1.0 / (NdotL + NdotV) - 0.5) + 0.5);
+
+ // specular
+ float aspect = sqrt(1.0 - anisotropic * 0.9);
+ float a = sqr(roughness);
+ float ax = max(0.001, a / aspect);
+ float ay = max(0.001, a * aspect);
+ float Ds = GTR2_aniso(NdotH, dot(H, X), dot(H, Y), ax, ay); //GTR2(NdotH, a);
+ float FH = (fresnel_dielectric_cos(LdotH, eta) - F0) * F0_norm;
+ vec3 Fs = mix(Cspec0, vec3(1.0), FH);
+ float roughg = sqr(roughness * 0.5 + 0.5);
+ float Gs = smithG_GGX(NdotL, roughg) * smithG_GGX(NdotV, roughg);
+
+ // sheen
+ vec3 Fsheen = schlick_fresnel(LdotH) * sheen * Csheen;
+
+ vec3 diffuse_bsdf = (mix(Fd * base_color.rgb, ss * subsurface_color.rgb, subsurface) + Fsheen) * light_diffuse;
+ vec3 specular_bsdf = Gs * Fs * Ds * light_specular;
+ diffuse_and_specular_bsdf = diffuse_bsdf * (1.0 - metallic) + specular_bsdf;
+ }
+ diffuse_and_specular_bsdf *= max(NdotL, 0.0);
+
+ float CNdotL = dot(CN, light_position);
+ float CNdotV = dot(CN, V);
+
+ vec3 clearcoat_bsdf = vec3(0.0);
+ if (CNdotL >= 0.0 && CNdotV >= 0.0 && clearcoat > 0.0) {
+ float CNdotH = dot(CN, H);
+ //float FH = schlick_fresnel(LdotH);
+
+ // clearcoat (ior = 1.5 -> F0 = 0.04)
+ float Dr = GTR1(CNdotH, sqr(clearcoat_roughness));
+ float Fr = fresnel_dielectric_cos(LdotH, 1.5); //mix(0.04, 1.0, FH);
+ float Gr = smithG_GGX(CNdotL, 0.25) * smithG_GGX(CNdotV, 0.25);
+
+ clearcoat_bsdf = clearcoat * Gr * Fr * Dr * vec3(0.25) * light_specular;
+ }
+ clearcoat_bsdf *= max(CNdotL, 0.0);
+
+ L += diffuse_and_specular_bsdf + clearcoat_bsdf;
+ }
+
+ result = vec4(L, 1.0);
+}
+
void node_bsdf_translucent(vec4 color, vec3 N, out vec4 result)
{
node_bsdf_diffuse(color, 0.0, N, result);
@@ -2782,7 +2973,10 @@ float calc_gradient(vec3 p, int gradient_type)
return atan(y, x) / (M_PI * 2) + 0.5;
}
else {
- float r = max(1.0 - sqrt(x * x + y * y + z * z), 0.0);
+ /* Bias a little bit for the case where p is a unit length vector,
+ * to get exactly zero instead of a small random value depending
+ * on float precision. */
+ float r = max(0.999999 - sqrt(x * x + y * y + z * z), 0.0);
if (gradient_type == 5) { /* quadratic sphere */
return r * r;
}
@@ -2846,10 +3040,10 @@ vec2 calc_brick_texture(vec3 p, float mortar_size, float mortar_smooth, float bi
float tint = clamp((integer_noise((rownum << 16) + (bricknum & 0xFFFF)) + bias), 0.0, 1.0);
float min_dist = min(min(x, y), min(brick_width - x, row_height - y));
- if(min_dist >= mortar_size) {
+ if (min_dist >= mortar_size) {
return vec2(tint, 0.0);
}
- else if(mortar_smooth == 0.0) {
+ else if (mortar_smooth == 0.0) {
return vec2(tint, 1.0);
}
else {
@@ -2931,15 +3125,17 @@ void node_tex_image(vec3 co, sampler2D ima, out vec4 color, out float alpha)
}
void node_tex_image_box(vec3 texco,
- vec3 nob,
+ vec3 N,
sampler2D ima,
float blend,
out vec4 color,
out float alpha)
{
+ vec3 signed_N = N;
+
/* project from direction vector to barycentric coordinates in triangles */
- nob = vec3(abs(nob.x), abs(nob.y), abs(nob.z));
- nob /= (nob.x + nob.y + nob.z);
+ N = vec3(abs(N.x), abs(N.y), abs(N.z));
+ N /= (N.x + N.y + N.z);
/* basic idea is to think of this as a triangle, each corner representing
* one of the 3 faces of the cube. in the corners we have single textures,
@@ -2955,37 +3151,37 @@ void node_tex_image_box(vec3 texco,
float limit = 0.5 * (1.0 + blend);
/* first test for corners with single texture */
- if (nob.x > limit * (nob.x + nob.y) && nob.x > limit * (nob.x + nob.z)) {
+ if (N.x > limit * (N.x + N.y) && N.x > limit * (N.x + N.z)) {
weight.x = 1.0;
}
- else if (nob.y > limit * (nob.x + nob.y) && nob.y > limit * (nob.y + nob.z)) {
+ else if (N.y > limit * (N.x + N.y) && N.y > limit * (N.y + N.z)) {
weight.y = 1.0;
}
- else if (nob.z > limit * (nob.x + nob.z) && nob.z > limit * (nob.y + nob.z)) {
+ else if (N.z > limit * (N.x + N.z) && N.z > limit * (N.y + N.z)) {
weight.z = 1.0;
}
else if (blend > 0.0) {
/* in case of blending, test for mixes between two textures */
- if (nob.z < (1.0 - limit) * (nob.y + nob.x)) {
- weight.x = nob.x / (nob.x + nob.y);
+ if (N.z < (1.0 - limit) * (N.y + N.x)) {
+ weight.x = N.x / (N.x + N.y);
weight.x = clamp((weight.x - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
weight.y = 1.0 - weight.x;
}
- else if (nob.x < (1.0 - limit) * (nob.y + nob.z)) {
- weight.y = nob.y / (nob.y + nob.z);
+ else if (N.x < (1.0 - limit) * (N.y + N.z)) {
+ weight.y = N.y / (N.y + N.z);
weight.y = clamp((weight.y - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
weight.z = 1.0 - weight.y;
}
- else if (nob.y < (1.0 - limit) * (nob.x + nob.z)) {
- weight.x = nob.x / (nob.x + nob.z);
+ else if (N.y < (1.0 - limit) * (N.x + N.z)) {
+ weight.x = N.x / (N.x + N.z);
weight.x = clamp((weight.x - 0.5 * (1.0 - blend)) / blend, 0.0, 1.0);
weight.z = 1.0 - weight.x;
}
else {
/* last case, we have a mix between three */
- weight.x = ((2.0 - limit) * nob.x + (limit - 1.0)) / (2.0 * limit - 1.0);
- weight.y = ((2.0 - limit) * nob.y + (limit - 1.0)) / (2.0 * limit - 1.0);
- weight.z = ((2.0 - limit) * nob.z + (limit - 1.0)) / (2.0 * limit - 1.0);
+ weight.x = ((2.0 - limit) * N.x + (limit - 1.0)) / (2.0 * limit - 1.0);
+ weight.y = ((2.0 - limit) * N.y + (limit - 1.0)) / (2.0 * limit - 1.0);
+ weight.z = ((2.0 - limit) * N.z + (limit - 1.0)) / (2.0 * limit - 1.0);
}
}
else {
@@ -2994,13 +3190,25 @@ void node_tex_image_box(vec3 texco,
}
color = vec4(0);
if (weight.x > 0.0) {
- color += weight.x * texture2D(ima, texco.yz);
+ vec2 uv = texco.yz;
+ if(signed_N.x < 0.0) {
+ uv.x = 1.0 - uv.x;
+ }
+ color += weight.x * texture2D(ima, uv);
}
if (weight.y > 0.0) {
- color += weight.y * texture2D(ima, texco.xz);
+ vec2 uv = texco.xz;
+ if(signed_N.y > 0.0) {
+ uv.x = 1.0 - uv.x;
+ }
+ color += weight.y * texture2D(ima, uv);
}
if (weight.z > 0.0) {
- color += weight.z * texture2D(ima, texco.yx);
+ vec2 uv = texco.yx;
+ if(signed_N.z > 0.0) {
+ uv.x = 1.0 - uv.x;
+ }
+ color += weight.z * texture2D(ima, uv);
}
alpha = color.a;
@@ -3108,17 +3316,29 @@ float noise_perlin(float x, float y, float z)
float v = noise_fade(fy);
float w = noise_fade(fz);
- float result;
+ float noise_u[2], noise_v[2];
+
+ noise_u[0] = noise_nerp(u,
+ noise_grad(hash(X, Y, Z), fx, fy, fz),
+ noise_grad(hash(X + 1, Y, Z), fx - 1.0, fy, fz));
- result = noise_nerp(w, noise_nerp(v, noise_nerp(u, noise_grad(hash(X, Y, Z), fx, fy, fz),
- noise_grad(hash(X + 1, Y, Z), fx - 1.0, fy, fz)),
- noise_nerp(u, noise_grad(hash(X, Y + 1, Z), fx, fy - 1.0, fz),
- noise_grad(hash(X + 1, Y + 1, Z), fx - 1.0, fy - 1.0, fz))),
- noise_nerp(v, noise_nerp(u, noise_grad(hash(X, Y, Z + 1), fx, fy, fz - 1.0),
- noise_grad(hash(X + 1, Y, Z + 1), fx - 1.0, fy, fz - 1.0)),
- noise_nerp(u, noise_grad(hash(X, Y + 1, Z + 1), fx, fy - 1.0, fz - 1.0),
- noise_grad(hash(X + 1, Y + 1, Z + 1), fx - 1.0, fy - 1.0, fz - 1.0))));
- return noise_scale3(result);
+ noise_u[1] = noise_nerp(u,
+ noise_grad(hash(X, Y + 1, Z), fx, fy - 1.0, fz),
+ noise_grad(hash(X + 1, Y + 1, Z), fx - 1.0, fy - 1.0, fz));
+
+ noise_v[0] = noise_nerp(v, noise_u[0], noise_u[1]);
+
+ noise_u[0] = noise_nerp(u,
+ noise_grad(hash(X, Y, Z + 1), fx, fy, fz - 1.0),
+ noise_grad(hash(X + 1, Y, Z + 1), fx - 1.0, fy, fz - 1.0));
+
+ noise_u[1] = noise_nerp(u,
+ noise_grad(hash(X, Y + 1, Z + 1), fx, fy - 1.0, fz - 1.0),
+ noise_grad(hash(X + 1, Y + 1, Z + 1), fx - 1.0, fy - 1.0, fz - 1.0));
+
+ noise_v[1] = noise_nerp(v, noise_u[0], noise_u[1]);
+
+ return noise_scale3(noise_nerp(w, noise_v[0], noise_v[1]));
}
float noise(vec3 p)
@@ -3563,12 +3783,12 @@ void node_light_falloff(float strength, float tsmooth, out float quadratic, out
constant = strength;
}
-void node_object_info(out vec3 location, out float object_index, out float material_index, out float random)
+void node_object_info(mat4 obmat, vec3 info, out vec3 location, out float object_index, out float material_index, out float random)
{
- location = vec3(0.0);
- object_index = 0.0;
- material_index = 0.0;
- random = 0.0;
+ location = obmat[3].xyz;
+ object_index = info.x;
+ material_index = info.y;
+ random = info.z;
}
void node_normal_map(vec4 tangent, vec3 normal, vec3 texnormal, out vec3 outnormal)
@@ -3605,9 +3825,48 @@ void node_bump(float strength, float dist, float height, vec3 N, vec3 surf_pos,
result = normalize(strength * result + (1.0 - strength) * N);
}
+void node_bevel(float radius, vec3 N, out vec3 result)
+{
+ result = N;
+}
+
+void node_displacement_object(float height, float midlevel, float scale, vec3 N, mat4 obmat, out vec3 result)
+{
+ N = (vec4(N, 0.0) * obmat).xyz;
+ result = (height - midlevel) * scale * normalize(N);
+ result = (obmat * vec4(result, 0.0)).xyz;
+}
+
+void node_displacement_world(float height, float midlevel, float scale, vec3 N, out vec3 result)
+{
+ result = (height - midlevel) * scale * normalize(N);
+}
+
+void node_vector_displacement_tangent(vec4 vector, float midlevel, float scale, vec4 tangent, vec3 normal, mat4 obmat, mat4 viewmat, out vec3 result)
+{
+ vec3 N_object = normalize(((vec4(normal, 0.0) * viewmat) * obmat).xyz);
+ vec3 T_object = normalize(((vec4(tangent.xyz, 0.0) * viewmat) * obmat).xyz);
+ vec3 B_object = tangent.w * normalize(cross(N_object, T_object));
+
+ vec3 offset = (vector.xyz - vec3(midlevel)) * scale;
+ result = offset.x * T_object + offset.y * N_object + offset.z * B_object;
+ result = (obmat * vec4(result, 0.0)).xyz;
+}
+
+void node_vector_displacement_object(vec4 vector, float midlevel, float scale, mat4 obmat, out vec3 result)
+{
+ result = (vector.xyz - vec3(midlevel)) * scale;
+ result = (obmat * vec4(result, 0.0)).xyz;
+}
+
+void node_vector_displacement_world(vec4 vector, float midlevel, float scale, out vec3 result)
+{
+ result = (vector.xyz - vec3(midlevel)) * scale;
+}
+
/* output */
-void node_output_material(vec4 surface, vec4 volume, float displacement, out vec4 result)
+void node_output_material(vec4 surface, vec4 volume, vec3 displacement, out vec4 result)
{
result = surface;
}
diff --git a/source/blender/ikplugin/intern/iksolver_plugin.c b/source/blender/ikplugin/intern/iksolver_plugin.c
index 6ea311b2c7b..f837789914e 100644
--- a/source/blender/ikplugin/intern/iksolver_plugin.c
+++ b/source/blender/ikplugin/intern/iksolver_plugin.c
@@ -217,9 +217,27 @@ static void where_is_ik_bone(bPoseChannel *pchan, float ik_mat[3][3]) // nr =
copy_m4_m3(ikmat, ik_mat);
if (pchan->parent)
- mul_m4_series(pchan->pose_mat, pchan->parent->pose_mat, pchan->chan_mat, ikmat);
+ mul_m4_m4m4(pchan->pose_mat, pchan->parent->pose_mat, pchan->chan_mat);
else
- mul_m4_m4m4(pchan->pose_mat, pchan->chan_mat, ikmat);
+ copy_m4_m4(pchan->pose_mat, pchan->chan_mat);
+
+#ifdef USE_NONUNIFORM_SCALE
+ /* apply IK mat, but as if the bones have uniform scale since the IK solver
+ * is not aware of non-uniform scale */
+ float scale[3];
+ mat4_to_size(scale, pchan->pose_mat);
+ normalize_v3_length(pchan->pose_mat[0], scale[1]);
+ normalize_v3_length(pchan->pose_mat[2], scale[1]);
+#endif
+
+ mul_m4_m4m4(pchan->pose_mat, pchan->pose_mat, ikmat);
+
+#ifdef USE_NONUNIFORM_SCALE
+ float ik_scale[3];
+ mat3_to_size(ik_scale, ik_mat);
+ normalize_v3_length(pchan->pose_mat[0], scale[0] * ik_scale[0]);
+ normalize_v3_length(pchan->pose_mat[2], scale[2] * ik_scale[2]);
+#endif
/* calculate head */
copy_v3_v3(pchan->pose_head, pchan->pose_mat[3]);
@@ -308,6 +326,10 @@ static void execute_posetree(struct Scene *scene, Object *ob, PoseTree *tree)
/* change length based on bone size */
length = bone->length * len_v3(R_bonemat[1]);
+ /* basis must be pure rotation */
+ normalize_m3(R_bonemat);
+ normalize_m3(R_parmat);
+
/* compute rest basis and its inverse */
copy_m3_m3(rest_basis, bone->bone_mat);
transpose_m3_m3(irest_basis, bone->bone_mat);
@@ -317,11 +339,7 @@ static void execute_posetree(struct Scene *scene, Object *ob, PoseTree *tree)
mul_m3_m3m3(full_basis, iR_parmat, R_bonemat);
mul_m3_m3m3(basis, irest_basis, full_basis);
- /* basis must be pure rotation */
- normalize_m3(basis);
-
/* transform offset into local bone space */
- normalize_m3(iR_parmat);
mul_m3_v3(iR_parmat, start);
IK_SetTransform(seg, start, rest_basis, basis, length);
@@ -545,18 +563,6 @@ void iksolver_execute_tree(struct Scene *scene, Object *ob, bPoseChannel *pchan
tree->pchan[a]->flag |= POSE_CHAIN;
}
-#ifdef USE_NONUNIFORM_SCALE
- float (*pchan_scale_data)[3] = MEM_mallocN(sizeof(float[3]) * tree->totchannel, __func__);
-
- for (a = 0; a < tree->totchannel; a++) {
- mat4_to_size(pchan_scale_data[a], tree->pchan[a]->pose_mat);
-
- /* make uniform at y scale since this controls the length */
- normalize_v3_length(tree->pchan[a]->pose_mat[0], pchan_scale_data[a][1]);
- normalize_v3_length(tree->pchan[a]->pose_mat[2], pchan_scale_data[a][1]);
- }
-#endif
-
/* 5. execute the IK solver */
execute_posetree(scene, ob, tree);
@@ -571,14 +577,6 @@ void iksolver_execute_tree(struct Scene *scene, Object *ob, bPoseChannel *pchan
where_is_ik_bone(tree->pchan[a], tree->basis_change[a]);
}
-#ifdef USE_NONUNIFORM_SCALE
- for (a = 0; a < tree->totchannel; a++) {
- normalize_v3_length(tree->pchan[a]->pose_mat[0], pchan_scale_data[a][0]);
- normalize_v3_length(tree->pchan[a]->pose_mat[2], pchan_scale_data[a][2]);
- }
- MEM_freeN(pchan_scale_data);
-#endif
-
/* 7. and free */
BLI_remlink(&pchan_root->iktree, tree);
free_posetree(tree);
diff --git a/source/blender/imbuf/CMakeLists.txt b/source/blender/imbuf/CMakeLists.txt
index b32f8c54cd6..e73f227dec8 100644
--- a/source/blender/imbuf/CMakeLists.txt
+++ b/source/blender/imbuf/CMakeLists.txt
@@ -73,6 +73,7 @@ set(SRC
IMB_colormanagement.h
IMB_imbuf.h
IMB_imbuf_types.h
+ IMB_metadata.h
IMB_moviecache.h
IMB_thumbs.h
intern/IMB_allocimbuf.h
@@ -81,7 +82,6 @@ set(SRC
intern/IMB_filetype.h
intern/IMB_filter.h
intern/IMB_indexer.h
- intern/IMB_metadata.h
intern/imbuf.h
# orphan include
@@ -130,16 +130,6 @@ if(WITH_CODEC_AVI)
add_definitions(-DWITH_AVI)
endif()
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../quicktime
- )
- list(APPEND INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_CODEC_FFMPEG)
list(APPEND INC
../../../intern/ffmpeg
diff --git a/source/blender/imbuf/IMB_colormanagement.h b/source/blender/imbuf/IMB_colormanagement.h
index 4164f5fa75d..ff1784c54dd 100644
--- a/source/blender/imbuf/IMB_colormanagement.h
+++ b/source/blender/imbuf/IMB_colormanagement.h
@@ -162,7 +162,7 @@ void IMB_colormanagment_colorspace_from_ibuf_ftype(struct ColorManagedColorspace
/* ** RNA helper functions ** */
void IMB_colormanagement_display_items_add(struct EnumPropertyItem **items, int *totitem);
void IMB_colormanagement_view_items_add(struct EnumPropertyItem **items, int *totitem, const char *display_name);
-void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem);
+void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem, const char *view_name);
void IMB_colormanagement_colorspace_items_add(struct EnumPropertyItem **items, int *totitem);
/* ** Tile-based buffer management ** */
diff --git a/source/blender/imbuf/IMB_imbuf.h b/source/blender/imbuf/IMB_imbuf.h
index 93d2b3e0cd0..e5cd21a3248 100644
--- a/source/blender/imbuf/IMB_imbuf.h
+++ b/source/blender/imbuf/IMB_imbuf.h
@@ -166,7 +166,7 @@ struct ImBuf *IMB_makeSingleUser(struct ImBuf *ibuf);
*
* \attention Defined in allocimbuf.c
*/
-struct ImBuf *IMB_dupImBuf(struct ImBuf *ibuf1);
+struct ImBuf *IMB_dupImBuf(const struct ImBuf *ibuf1);
/**
*
@@ -205,6 +205,7 @@ typedef enum IMB_BlendMode {
IMB_BLEND_SATURATION = 21,
IMB_BLEND_LUMINOSITY = 22,
IMB_BLEND_COLOR = 23,
+ IMB_BLEND_INTERPOLATE = 24,
IMB_BLEND_COPY = 1000,
IMB_BLEND_COPY_RGB = 1001,
@@ -379,13 +380,13 @@ struct ImBuf *IMB_onehalf(struct ImBuf *ibuf1);
*
* \attention Defined in scaling.c
*/
-struct ImBuf *IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy);
+bool IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy);
/**
*
* \attention Defined in scaling.c
*/
-struct ImBuf *IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy);
+bool IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy);
/**
*
@@ -398,7 +399,7 @@ void IMB_scaleImBuf_threaded(struct ImBuf *ibuf, unsigned int newx, unsigned int
* \attention Defined in writeimage.c
*/
short IMB_saveiff(struct ImBuf *ibuf, const char *filepath, int flags);
-struct ImBuf *IMB_prepare_write_ImBuf(const bool isfloat, struct ImBuf *ibuf);
+bool IMB_prepare_write_ImBuf(const bool isfloat, struct ImBuf *ibuf);
/**
*
@@ -565,23 +566,13 @@ void buf_rectfill_area(unsigned char *rect, float *rectf, int width, int height,
const float col[4], struct ColorManagedDisplay *display,
int x1, int y1, int x2, int y2);
-/**
- *
- * \attention Defined in metadata.c
- */
-/** read the field from the image info into the field
- * \param img - the ImBuf that contains the image data
- * \param key - the key of the field
- * \param value - the data in the field, first one found with key is returned,
- * memory has to be allocated by user.
- * \param len - length of value buffer allocated by user.
- * \return - 1 (true) if ImageInfo present and value for the key found, 0 (false) otherwise
- */
-bool IMB_metadata_get_field(struct ImBuf *img, const char *key, char *value, const size_t len);
-bool IMB_metadata_change_field(struct ImBuf *img, const char *key, const char *field);
-void IMB_metadata_copy(struct ImBuf *dimb, struct ImBuf *simb);
-
/* exported for image tools in blender, to quickly allocate 32 bits rect */
+void *imb_alloc_pixels(unsigned int x,
+ unsigned int y,
+ unsigned int channels,
+ size_t typesize,
+ const char *name);
+
bool imb_addrectImBuf(struct ImBuf *ibuf);
void imb_freerectImBuf(struct ImBuf *ibuf);
diff --git a/source/blender/imbuf/IMB_imbuf_types.h b/source/blender/imbuf/IMB_imbuf_types.h
index f4b2539d7d7..ee51854d7ed 100644
--- a/source/blender/imbuf/IMB_imbuf_types.h
+++ b/source/blender/imbuf/IMB_imbuf_types.h
@@ -237,9 +237,8 @@ typedef struct ImBuf {
/**
* \name Imbuf Component flags
* \brief These flags determine the components of an ImBuf struct.
- */
-/**@{*/
-/** \brief Flag defining the components of the ImBuf struct. */
+ *
+ * \{ */
#define IB_rect (1 << 0)
#define IB_test (1 << 1)
@@ -259,15 +258,20 @@ typedef struct ImBuf {
#define IB_thumbnail (1 << 15)
#define IB_multiview (1 << 16)
+/** \} */
+
/**
* \name Imbuf preset profile tags
* \brief Some predefined color space profiles that 8 bit imbufs can represent
- */
+ *
+ * \{ */
#define IB_PROFILE_NONE 0
#define IB_PROFILE_LINEAR_RGB 1
#define IB_PROFILE_SRGB 2
#define IB_PROFILE_CUSTOM 3
+/** \} */
+
/* dds */
#ifdef WITH_DDS
#ifndef DDS_MAKEFOURCC
@@ -291,15 +295,22 @@ typedef struct ImBuf {
#endif /* DDS */
extern const char *imb_ext_image[];
-extern const char *imb_ext_image_qt[];
extern const char *imb_ext_movie[];
extern const char *imb_ext_audio[];
/* image formats that can only be loaded via filepath */
extern const char *imb_ext_image_filepath_only[];
+/**
+ * \name Imbuf Color Management Flag
+ * \brief Used with #ImBuf.colormanage_flag
+ *
+ * \{ */
+
enum {
IMB_COLORMANAGE_IS_DATA = (1 << 0)
};
-#endif
+/** \} */
+
+#endif /* __IMB_IMBUF_TYPES_H__ */
diff --git a/source/blender/imbuf/intern/IMB_metadata.h b/source/blender/imbuf/IMB_metadata.h
index bc0b2c70ecb..6a29fa01594 100644
--- a/source/blender/imbuf/intern/IMB_metadata.h
+++ b/source/blender/imbuf/IMB_metadata.h
@@ -4,7 +4,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
@@ -25,7 +25,7 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/imbuf/intern/IMB_metadata.h
+/** \file blender/imbuf/IMB_metadata.h
* \ingroup imbuf
*/
@@ -33,7 +33,9 @@
#ifndef __IMB_METADATA_H__
#define __IMB_METADATA_H__
+struct anim;
struct ImBuf;
+struct IDProperty;
/** The metadata is a list of key/value pairs (both char *) that can me
* saved in the header of several image formats.
@@ -41,26 +43,36 @@ struct ImBuf;
* 'Software' and 'Description' (png standard) we'll use keys within the
* Blender namespace, so should be called 'Blender::StampInfo' or 'Blender::FrameNum'
* etc...
+ *
+ * The keys & values are stored in ID properties, in the group "metadata".
*/
+/** Ensure that the metadata property is a valid IDProperty object.
+ * This is a no-op when *metadata != NULL.
+ */
+void IMB_metadata_ensure(struct IDProperty **metadata);
+void IMB_metadata_free(struct IDProperty *metadata);
-/* free blender ImMetaData struct */
-void IMB_metadata_free(struct ImBuf *img);
+/** Read the field from the image info into the field.
+ * \param metadata - the IDProperty that contains the metadata
+ * \param key - the key of the field
+ * \param value - the data in the field, first one found with key is returned,
+ * memory has to be allocated by user.
+ * \param len - length of value buffer allocated by user.
+ * \return - 1 (true) if metadata is present and value for the key found, 0 (false) otherwise
+ */
+bool IMB_metadata_get_field(struct IDProperty *metadata, const char *key, char *value, const size_t len);
-/** set user data in the ImMetaData struct, which has to be allocated with IMB_metadata_create
- * before calling this function.
- * \param img - the ImBuf that contains the image data
+/** Set user data in the metadata.
+ * If the field already exists its value is overwritten, otherwise the field
+ * will be added with the given value.
+ * \param metadata - the IDProperty that contains the metadata
* \param key - the key of the field
* \param value - the data to be written to the field. zero terminated string
- * \return - 1 (true) if ImageInfo present, 0 (false) otherwise
*/
-bool IMB_metadata_add_field(struct ImBuf *img, const char *key, const char *value);
+void IMB_metadata_set_field(struct IDProperty *metadata, const char *key, const char *value);
-/** delete the key/field par in the ImMetaData struct.
- * \param img - the ImBuf that contains the image data
- * \param key - the key of the field
- * \return - 1 (true) if delete the key/field, 0 (false) otherwise
- */
-bool IMB_metadata_del_field(struct ImBuf *img, const char *key);
+void IMB_metadata_copy(struct ImBuf *dimb, struct ImBuf *simb);
+struct IDProperty *IMB_anim_load_metadata(struct anim *anim);
#endif /* __IMB_METADATA_H__ */
diff --git a/source/blender/imbuf/intern/IMB_anim.h b/source/blender/imbuf/intern/IMB_anim.h
index d89393b9903..6fa31e122cc 100644
--- a/source/blender/imbuf/intern/IMB_anim.h
+++ b/source/blender/imbuf/intern/IMB_anim.h
@@ -40,10 +40,7 @@
# include <mmsystem.h>
# include <memory.h>
# include <commdlg.h>
-
-# ifndef FREE_WINDOWS
-# include <vfw.h>
-# endif
+# include <vfw.h>
# undef AVIIF_KEYFRAME // redefined in AVI_avi.h
# undef AVIIF_LIST // redefined in AVI_avi.h
@@ -66,12 +63,6 @@
# include "AVI_avi.h"
#endif
-#ifdef WITH_QUICKTIME
-# if defined(_WIN32) || defined(__APPLE__)
-# include "quicktime_import.h"
-# endif /* _WIN32 || __APPLE__ */
-#endif /* WITH_QUICKTIME */
-
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -102,14 +93,15 @@
struct _AviMovie;
struct anim_index;
+struct IDProperty;
struct anim {
int ib_flags;
int curtype;
int curposition; /* index 0 = 1e, 1 = 2e, enz. */
int duration;
- short frs_sec;
- float frs_sec_base;
+ int frs_sec;
+ double frs_sec_base;
int x, y;
/* for number */
@@ -130,7 +122,7 @@ struct anim {
/* avi */
struct _AviMovie *avi;
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
/* windows avi */
int avistreams;
int firstvideo;
@@ -140,11 +132,6 @@ struct anim {
PGETFRAME pgf;
#endif
-#ifdef WITH_QUICKTIME
- /* quicktime */
- struct _QuicktimeMovie *qtime;
-#endif /* WITH_QUICKTIME */
-
#ifdef WITH_FFMPEG
AVFormatContext *pFormatCtx;
AVCodecContext *pCodecCtx;
@@ -172,6 +159,8 @@ struct anim {
char colorspace[64];
char suffix[64]; /* MAX_NAME - multiview */
+
+ struct IDProperty *metadata;
};
#endif
diff --git a/source/blender/imbuf/intern/IMB_colormanagement_intern.h b/source/blender/imbuf/intern/IMB_colormanagement_intern.h
index b75f12b239d..0b4557e7bef 100644
--- a/source/blender/imbuf/intern/IMB_colormanagement_intern.h
+++ b/source/blender/imbuf/intern/IMB_colormanagement_intern.h
@@ -79,6 +79,8 @@ typedef struct ColorManagedLook {
struct ColorManagedLook *next, *prev;
int index;
char name[MAX_COLORSPACE_NAME];
+ char ui_name[MAX_COLORSPACE_NAME];
+ char view[MAX_COLORSPACE_NAME];
char process_space[MAX_COLORSPACE_NAME];
bool is_noop;
} ColorManagedLook;
diff --git a/source/blender/imbuf/intern/allocimbuf.c b/source/blender/imbuf/intern/allocimbuf.c
index 33750478bb4..faa0b5f7b6e 100644
--- a/source/blender/imbuf/intern/allocimbuf.c
+++ b/source/blender/imbuf/intern/allocimbuf.c
@@ -219,7 +219,7 @@ void IMB_freeImBuf(ImBuf *ibuf)
IMB_freezbufImBuf(ibuf);
IMB_freezbuffloatImBuf(ibuf);
freeencodedbufferImBuf(ibuf);
- IMB_metadata_free(ibuf);
+ IMB_metadata_free(ibuf->metadata);
colormanage_cache_free(ibuf);
if (ibuf->dds_data.data != NULL) {
@@ -265,15 +265,11 @@ ImBuf *IMB_makeSingleUser(ImBuf *ibuf)
bool addzbufImBuf(ImBuf *ibuf)
{
- size_t size;
-
if (ibuf == NULL) return false;
IMB_freezbufImBuf(ibuf);
- size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(unsigned int);
-
- if ((ibuf->zbuf = MEM_mapallocN(size, __func__))) {
+ if ((ibuf->zbuf = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(unsigned int), __func__))) {
ibuf->mall |= IB_zbuf;
ibuf->flags |= IB_zbuf;
return true;
@@ -284,15 +280,11 @@ bool addzbufImBuf(ImBuf *ibuf)
bool addzbuffloatImBuf(ImBuf *ibuf)
{
- size_t size;
-
if (ibuf == NULL) return false;
IMB_freezbuffloatImBuf(ibuf);
- size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(float);
-
- if ((ibuf->zbuf_float = MEM_mapallocN(size, __func__))) {
+ if ((ibuf->zbuf_float = imb_alloc_pixels(ibuf->x, ibuf->y, 1, sizeof(float), __func__))) {
ibuf->mall |= IB_zbuffloat;
ibuf->flags |= IB_zbuffloat;
return true;
@@ -361,19 +353,31 @@ bool imb_enlargeencodedbufferImBuf(ImBuf *ibuf)
return true;
}
+void *imb_alloc_pixels(unsigned int x,
+ unsigned int y,
+ unsigned int channels,
+ size_t typesize,
+ const char *name)
+{
+ /* Protect against buffer overflow vulnerabilities from files specifying
+ * a width and height that overflow and alloc too little memory. */
+ if (!((uint64_t)x * (uint64_t)y < (SIZE_MAX / (channels * typesize)))) {
+ return NULL;
+ }
+
+ size_t size = (size_t)x * (size_t)y * (size_t)channels * typesize;
+ return MEM_mapallocN(size, name);
+}
+
bool imb_addrectfloatImBuf(ImBuf *ibuf)
{
- size_t size;
-
if (ibuf == NULL) return false;
if (ibuf->rect_float)
imb_freerectfloatImBuf(ibuf); /* frees mipmap too, hrm */
- size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(float[4]);
-
ibuf->channels = 4;
- if ((ibuf->rect_float = MEM_mapallocN(size, __func__))) {
+ if ((ibuf->rect_float = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(float), __func__))) {
ibuf->mall |= IB_rectfloat;
ibuf->flags |= IB_rectfloat;
return true;
@@ -385,8 +389,6 @@ bool imb_addrectfloatImBuf(ImBuf *ibuf)
/* question; why also add zbuf? */
bool imb_addrectImBuf(ImBuf *ibuf)
{
- size_t size;
-
if (ibuf == NULL) return false;
/* don't call imb_freerectImBuf, it frees mipmaps, this call is used only too give float buffers display */
@@ -394,9 +396,7 @@ bool imb_addrectImBuf(ImBuf *ibuf)
MEM_freeN(ibuf->rect);
ibuf->rect = NULL;
- size = (size_t)ibuf->x * (size_t)ibuf->y * sizeof(unsigned int);
-
- if ((ibuf->rect = MEM_mapallocN(size, __func__))) {
+ if ((ibuf->rect = imb_alloc_pixels(ibuf->x, ibuf->y, 4, sizeof(unsigned char), __func__))) {
ibuf->mall |= IB_rect;
ibuf->flags |= IB_rect;
if (ibuf->planes > 32) {
@@ -506,7 +506,7 @@ bool IMB_initImBuf(struct ImBuf *ibuf,
}
/* does no zbuffers? */
-ImBuf *IMB_dupImBuf(ImBuf *ibuf1)
+ImBuf *IMB_dupImBuf(const ImBuf *ibuf1)
{
ImBuf *ibuf2, tbuf;
int flags = 0;
diff --git a/source/blender/imbuf/intern/anim_movie.c b/source/blender/imbuf/intern/anim_movie.c
index a40b257b75b..f842b69418e 100644
--- a/source/blender/imbuf/intern/anim_movie.c
+++ b/source/blender/imbuf/intern/anim_movie.c
@@ -37,10 +37,7 @@
#include <mmsystem.h>
#include <memory.h>
#include <commdlg.h>
-
-#ifndef FREE_WINDOWS
#include <vfw.h>
-#endif
#undef AVIIF_KEYFRAME /* redefined in AVI_avi.h */
#undef AVIIF_LIST /* redefined in AVI_avi.h */
@@ -58,6 +55,7 @@
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
+#include <limits.h>
#ifndef _WIN32
#include <dirent.h>
#else
@@ -70,18 +68,10 @@
#include "MEM_guardedalloc.h"
-#include "BKE_global.h"
-
#ifdef WITH_AVI
# include "AVI_avi.h"
#endif
-#ifdef WITH_QUICKTIME
-#if defined(_WIN32) || defined(__APPLE__)
-#include "quicktime_import.h"
-#endif /* _WIN32 || __APPLE__ */
-#endif /* WITH_QUICKTIME */
-
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -90,8 +80,11 @@
#include "IMB_anim.h"
#include "IMB_indexer.h"
+#include "IMB_metadata.h"
#ifdef WITH_FFMPEG
+# include "BKE_global.h" /* ENDIAN_ORDER */
+
# include <libavformat/avformat.h>
# include <libavcodec/avcodec.h>
# include <libavutil/rational.h>
@@ -173,7 +166,7 @@ static void an_stringenc(char *string, const char *head, const char *tail, unsig
#ifdef WITH_AVI
static void free_anim_avi(struct anim *anim)
{
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
int i;
#endif
@@ -184,7 +177,7 @@ static void free_anim_avi(struct anim *anim)
MEM_freeN(anim->avi);
anim->avi = NULL;
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
if (anim->pgf) {
AVIStreamGetFrameClose(anim->pgf);
@@ -224,13 +217,11 @@ void IMB_free_anim(struct anim *anim)
free_anim_avi(anim);
#endif
-#ifdef WITH_QUICKTIME
- free_anim_quicktime(anim);
-#endif
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
IMB_free_indices(anim);
+ IMB_metadata_free(anim->metadata);
MEM_freeN(anim);
}
@@ -250,6 +241,26 @@ void IMB_close_anim_proxies(struct anim *anim)
IMB_free_indices(anim);
}
+struct IDProperty *IMB_anim_load_metadata(struct anim *anim)
+{
+#ifdef WITH_FFMPEG
+ AVDictionaryEntry *entry = NULL;
+
+ BLI_assert(anim->pFormatCtx != NULL);
+ av_log(anim->pFormatCtx, AV_LOG_DEBUG, "METADATA FETCH\n");
+
+ while (true) {
+ entry = av_dict_get(anim->pFormatCtx->metadata, "", entry, AV_DICT_IGNORE_SUFFIX);
+ if (entry == NULL) break;
+
+ /* Delay creation of the property group until there is actual metadata to put in there. */
+ IMB_metadata_ensure(&anim->metadata);
+ IMB_metadata_set_field(anim->metadata, entry->key, entry->value);
+ }
+#endif
+ return anim->metadata;
+}
+
struct anim *IMB_open_anim(const char *name, int ib_flags, int streamindex, char colorspace[IM_MAX_SPACE])
{
struct anim *anim;
@@ -283,7 +294,7 @@ static int startavi(struct anim *anim)
{
AviError avierror;
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
HRESULT hr;
int i, firstvideo = -1;
int streamcount;
@@ -304,7 +315,7 @@ static int startavi(struct anim *anim)
avierror = AVI_open_movie(anim->name, anim->avi);
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
if (avierror == AVI_ERROR_COMPRESSION) {
AVIFileInit();
hr = AVIFileOpen(&anim->pfile, anim->name, OF_READ, 0L);
@@ -401,7 +412,7 @@ static ImBuf *avi_fetchibuf(struct anim *anim, int position)
return NULL;
}
-#if defined(_WIN32) && !defined(FREE_WINDOWS)
+#if defined(_WIN32)
if (anim->avistreams) {
LPBITMAPINFOHEADER lpbi;
@@ -516,8 +527,13 @@ static int startffmpeg(struct anim *anim)
avformat_close_input(&pFormatCtx);
return -1;
}
+ if (pCodecCtx->pix_fmt == AV_PIX_FMT_NONE) {
+ avcodec_close(anim->pCodecCtx);
+ avformat_close_input(&pFormatCtx);
+ return -1;
+ }
- frame_rate = av_get_r_frame_rate_compat(pFormatCtx->streams[videoStream]);
+ frame_rate = av_get_r_frame_rate_compat(pFormatCtx, pFormatCtx->streams[videoStream]);
if (pFormatCtx->streams[videoStream]->nb_frames != 0) {
anim->duration = pFormatCtx->streams[videoStream]->nb_frames;
}
@@ -995,7 +1011,7 @@ static ImBuf *ffmpeg_fetchibuf(struct anim *anim, int position,
v_st = anim->pFormatCtx->streams[anim->videoStream];
- frame_rate = av_q2d(av_get_r_frame_rate_compat(v_st));
+ frame_rate = av_q2d(av_get_r_frame_rate_compat(anim->pFormatCtx, v_st));
st_time = anim->pFormatCtx->start_time;
pts_time_base = av_q2d(v_st->time_base);
@@ -1217,9 +1233,6 @@ static ImBuf *anim_getnew(struct anim *anim)
free_anim_avi(anim);
#endif
-#ifdef WITH_QUICKTIME
- free_anim_quicktime(anim);
-#endif
#ifdef WITH_FFMPEG
free_anim_ffmpeg(anim);
#endif
@@ -1248,12 +1261,6 @@ static ImBuf *anim_getnew(struct anim *anim)
ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
break;
#endif
-#ifdef WITH_QUICKTIME
- case ANIM_QTIME:
- if (startquicktime(anim)) return (0);
- ibuf = IMB_allocImBuf(anim->x, anim->y, 24, 0);
- break;
-#endif
#ifdef WITH_FFMPEG
case ANIM_FFMPEG:
if (startffmpeg(anim)) return (0);
@@ -1343,21 +1350,6 @@ struct ImBuf *IMB_anim_absolute(struct anim *anim, int position,
anim->curposition = position;
break;
#endif
-#ifdef WITH_QUICKTIME
- case ANIM_QTIME:
- ibuf = qtime_fetchibuf(anim, position);
- if (ibuf) {
- if (ibuf->rect) {
- /* OCIO_TODO: should happen in quicktime module, but it currently doesn't have access
- * to color management's internals
- */
- ibuf->rect_colorspace = colormanage_colorspace_get_named(anim->colorspace);
- }
-
- anim->curposition = position;
- }
- break;
-#endif
#ifdef WITH_FFMPEG
case ANIM_FFMPEG:
ibuf = ffmpeg_fetchibuf(anim, position, tc);
@@ -1396,16 +1388,32 @@ int IMB_anim_get_duration(struct anim *anim, IMB_Timecode_Type tc)
bool IMB_anim_get_fps(struct anim *anim,
short *frs_sec, float *frs_sec_base, bool no_av_base)
{
+ double frs_sec_base_double;
if (anim->frs_sec) {
- *frs_sec = anim->frs_sec;
- *frs_sec_base = anim->frs_sec_base;
+ if (anim->frs_sec > SHRT_MAX) {
+ /* We cannot store original rational in our short/float format,
+ * we need to approximate it as best as we can... */
+ *frs_sec = SHRT_MAX;
+ frs_sec_base_double = anim->frs_sec_base * (double)SHRT_MAX / (double)anim->frs_sec;
+ }
+ else {
+ *frs_sec = anim->frs_sec;
+ frs_sec_base_double = anim->frs_sec_base;
+ }
#ifdef WITH_FFMPEG
if (no_av_base) {
- *frs_sec_base /= AV_TIME_BASE;
+ *frs_sec_base = (float)(frs_sec_base_double / AV_TIME_BASE);
+ }
+ else {
+ *frs_sec_base = (float)frs_sec_base_double;
}
#else
UNUSED_VARS(no_av_base);
+ *frs_sec_base = (float)frs_sec_base_double;
#endif
+ BLI_assert(*frs_sec > 0);
+ BLI_assert(*frs_sec_base > 0.0f);
+
return true;
}
return false;
diff --git a/source/blender/imbuf/intern/bmp.c b/source/blender/imbuf/intern/bmp.c
index c5694148127..e63699ea5ba 100644
--- a/source/blender/imbuf/intern/bmp.c
+++ b/source/blender/imbuf/intern/bmp.c
@@ -124,7 +124,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
{
struct ImBuf *ibuf = NULL;
BMPINFOHEADER bmi;
- int x, y, depth, ibuf_depth, skip, i, j;
+ int x, y, depth, ibuf_depth, skip;
const unsigned char *bmp;
unsigned char *rect;
unsigned short col;
@@ -179,13 +179,17 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
}
else {
ibuf = IMB_allocImBuf(x, y, ibuf_depth, IB_rect);
+ if (!ibuf) {
+ return NULL;
+ }
+
rect = (unsigned char *) ibuf->rect;
if (depth <= 8) {
const int rowsize = (depth * x + 31) / 32 * 4;
const char (*palette)[4] = (void *)(mem + skip);
const int startmask = ((1 << depth) - 1) << 8;
- for (i = y; i > 0; i--) {
+ for (size_t i = y; i > 0; i--) {
int index;
int bitoffs = 8;
int bitmask = startmask;
@@ -194,7 +198,7 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
}
- for (j = x; j > 0; j--) {
+ for (size_t j = x; j > 0; j--) {
bitoffs -= depth;
bitmask >>= depth;
index = (bmp[0] & bitmask) >> bitoffs;
@@ -219,11 +223,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
}
}
else if (depth == 16) {
- for (i = y; i > 0; i--) {
+ for (size_t i = y; i > 0; i--) {
if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
}
- for (j = x; j > 0; j--) {
+ for (size_t j = x; j > 0; j--) {
col = bmp[0] + (bmp[1] << 8);
rect[0] = ((col >> 10) & 0x1f) << 3;
rect[1] = ((col >> 5) & 0x1f) << 3;
@@ -236,11 +240,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
}
else if (depth == 24) {
const int x_pad = x % 4;
- for (i = y; i > 0; i--) {
+ for (size_t i = y; i > 0; i--) {
if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
}
- for (j = x; j > 0; j--) {
+ for (size_t j = x; j > 0; j--) {
rect[0] = bmp[2];
rect[1] = bmp[1];
rect[2] = bmp[0];
@@ -253,11 +257,11 @@ struct ImBuf *imb_bmp_decode(const unsigned char *mem, size_t size, int flags, c
}
}
else if (depth == 32) {
- for (i = y; i > 0; i--) {
+ for (size_t i = y; i > 0; i--) {
if (top_to_bottom) {
rect = (unsigned char *) &ibuf->rect[(i - 1) * x];
}
- for (j = x; j > 0; j--) {
+ for (size_t j = x; j > 0; j--) {
rect[0] = bmp[2];
rect[1] = bmp[1];
rect[2] = bmp[0];
@@ -299,7 +303,7 @@ static int putShortLSB(unsigned short us, FILE *ofile)
int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags)
{
BMPINFOHEADER infoheader;
- int bytesize, extrabytes, x, y, t, ptr;
+ size_t bytesize, extrabytes, ptr;
uchar *data;
FILE *ofile;
@@ -331,15 +335,15 @@ int imb_savebmp(struct ImBuf *ibuf, const char *name, int flags)
putIntLSB(0, ofile);
/* Need to write out padded image data in bgr format */
- for (y = 0; y < ibuf->y; y++) {
- for (x = 0; x < ibuf->x; x++) {
+ for (size_t y = 0; y < ibuf->y; y++) {
+ for (size_t x = 0; x < ibuf->x; x++) {
ptr = (x + y * ibuf->x) * 4;
if (putc(data[ptr + 2], ofile) == EOF) return 0;
if (putc(data[ptr + 1], ofile) == EOF) return 0;
if (putc(data[ptr], ofile) == EOF) return 0;
}
/* add padding here */
- for (t = 0; t < extrabytes; t++) {
+ for (size_t t = 0; t < extrabytes; t++) {
if (putc(0, ofile) == EOF) return 0;
}
}
diff --git a/source/blender/imbuf/intern/cineon/cineon_dpx.c b/source/blender/imbuf/intern/cineon/cineon_dpx.c
index 3e2206dc013..1d2ebf88a32 100644
--- a/source/blender/imbuf/intern/cineon/cineon_dpx.c
+++ b/source/blender/imbuf/intern/cineon/cineon_dpx.c
@@ -59,7 +59,7 @@ static struct ImBuf *imb_load_dpx_cineon(
colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_FLOAT);
- logImageSetVerbose((G.f & G_DEBUG) ? 1 : 0);
+ logImageSetVerbose((G.debug & G_DEBUG) ? 1 : 0);
image = logImageOpenFromMemory(mem, size);
@@ -107,7 +107,7 @@ static int imb_save_dpx_cineon(ImBuf *ibuf, const char *filename, int use_cineon
return 0;
}
- logImageSetVerbose((G.f & G_DEBUG) ? 1 : 0);
+ logImageSetVerbose((G.debug & G_DEBUG) ? 1 : 0);
depth = (ibuf->planes + 7) >> 3;
if (depth > 4 || depth < 3) {
diff --git a/source/blender/imbuf/intern/cineon/cineonlib.c b/source/blender/imbuf/intern/cineon/cineonlib.c
index fbce508af17..50d0e843890 100644
--- a/source/blender/imbuf/intern/cineon/cineonlib.c
+++ b/source/blender/imbuf/intern/cineon/cineonlib.c
@@ -318,6 +318,7 @@ LogImageFile *cineonOpen(const unsigned char *byteStuff, int fromMemory, size_t
printf("Gamma: %f\n", cineon->gamma);
printf("Reference black: %f\n", cineon->referenceBlack);
printf("Reference white: %f\n", cineon->referenceWhite);
+ printf("Orientation: %d\n", header.imageHeader.orientation);
printf("----------------------------\n");
}
return cineon;
diff --git a/source/blender/imbuf/intern/cineon/dpxlib.c b/source/blender/imbuf/intern/cineon/dpxlib.c
index 8b4e95ac452..d29518fc5bc 100644
--- a/source/blender/imbuf/intern/cineon/dpxlib.c
+++ b/source/blender/imbuf/intern/cineon/dpxlib.c
@@ -183,7 +183,7 @@ LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t buf
if (verbose) printf("DPX: File is LSB.\n");
}
else {
- if (verbose) {
+ if (verbose) {
printf("DPX: Bad magic number %u in \"%s\".\n",
header.fileHeader.magic_num, byteStuff);
}
@@ -193,7 +193,8 @@ LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t buf
dpx->srcFormat = format_DPX;
dpx->numElements = swap_ushort(header.imageHeader.elements_per_image, dpx->isMSB);
- if (dpx->numElements == 0) {
+ size_t max_elements = sizeof(header.imageHeader.element) / sizeof(header.imageHeader.element[0]);
+ if (dpx->numElements == 0 || dpx->numElements >= max_elements) {
if (verbose) printf("DPX: Wrong number of elements: %d\n", dpx->numElements);
logImageClose(dpx);
return NULL;
@@ -377,6 +378,7 @@ LogImageFile *dpxOpen(const unsigned char *byteStuff, int fromMemory, size_t buf
printf("Gamma: %f\n", dpx->gamma);
printf("Reference black: %f\n", dpx->referenceBlack);
printf("Reference white: %f\n", dpx->referenceWhite);
+ printf("Orientation: %d\n", header.imageHeader.orientation);
printf("----------------------------\n");
}
return dpx;
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.c b/source/blender/imbuf/intern/cineon/logImageCore.c
index 6fb1bccf491..bb72f675cb8 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.c
+++ b/source/blender/imbuf/intern/cineon/logImageCore.c
@@ -38,6 +38,8 @@
#include "BLI_fileops.h"
#include "BLI_utildefines.h"
+#include "IMB_imbuf.h"
+
#include "MEM_guardedalloc.h"
/*
@@ -162,7 +164,7 @@ void logImageGetSize(LogImageFile *logImage, int *width, int *height, int *depth
* Helper
*/
-unsigned int getRowLength(int width, LogImageElement logElement)
+size_t getRowLength(size_t width, LogImageElement logElement)
{
/* return the row length in bytes according to width and packing method */
switch (logElement.bitsPerSample) {
@@ -177,19 +179,18 @@ unsigned int getRowLength(int width, LogImageElement logElement)
return ((width * logElement.depth * 10 - 1) / 32 + 1) * 4;
else if (logElement.packing == 1 || logElement.packing == 2)
return ((width * logElement.depth - 1) / 3 + 1) * 4;
-
+ break;
case 12:
if (logElement.packing == 0)
return ((width * logElement.depth * 12 - 1) / 32 + 1) * 4;
else if (logElement.packing == 1 || logElement.packing == 2)
return width * logElement.depth * 2;
-
+ break;
case 16:
return width * logElement.depth * 2;
- default:
- return 0;
}
+ return 0;
}
@@ -202,7 +203,7 @@ int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
float *elementData;
int returnValue;
- elementData = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->depth * sizeof(float), __func__);
+ elementData = (float *)imb_alloc_pixels(logImage->width, logImage->height, logImage->depth, sizeof(float), __func__);
if (elementData == NULL)
return 1;
@@ -239,9 +240,8 @@ int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned char *row;
- int x, y;
row = (unsigned char *)MEM_mallocN(rowLength, __func__);
if (row == NULL) {
@@ -250,8 +250,8 @@ static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement,
}
memset(row, 0, rowLength);
- for (y = 0; y < logImage->height; y++) {
- for (x = 0; x < logImage->width * logImage->depth; x++)
+ for (size_t y = 0; y < logImage->height; y++) {
+ for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = (unsigned char)float_uint(data[y * logImage->width * logImage->depth + x], 255);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -266,10 +266,9 @@ static int logImageSetData8(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, index;
unsigned int *row;
- int x, y, offset;
row = (unsigned int *)MEM_mallocN(rowLength, __func__);
if (row == NULL) {
@@ -277,12 +276,12 @@ static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement,
return 1;
}
- for (y = 0; y < logImage->height; y++) {
- offset = 22;
+ for (size_t y = 0; y < logImage->height; y++) {
+ int offset = 22;
index = 0;
pixel = 0;
- for (x = 0; x < logImage->width * logImage->depth; x++) {
+ for (size_t x = 0; x < logImage->width * logImage->depth; x++) {
pixel |= (unsigned int)float_uint(data[y * logImage->width * logImage->depth + x], 1023) << offset;
offset -= 10;
if (offset < 0) {
@@ -309,9 +308,8 @@ static int logImageSetData10(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned short *row;
- int x, y;
row = (unsigned short *)MEM_mallocN(rowLength, __func__);
if (row == NULL) {
@@ -319,8 +317,8 @@ static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement,
return 1;
}
- for (y = 0; y < logImage->height; y++) {
- for (x = 0; x < logImage->width * logImage->depth; x++)
+ for (size_t y = 0; y < logImage->height; y++) {
+ for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = swap_ushort(((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 4095)) << 4, logImage->isMSB);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -335,9 +333,8 @@ static int logImageSetData12(LogImageFile *logImage, LogImageElement logElement,
static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned short *row;
- int x, y;
row = (unsigned short *)MEM_mallocN(rowLength, __func__);
if (row == NULL) {
@@ -345,8 +342,8 @@ static int logImageSetData16(LogImageFile *logImage, LogImageElement logElement,
return 1;
}
- for (y = 0; y < logImage->height; y++) {
- for (x = 0; x < logImage->width * logImage->depth; x++)
+ for (size_t y = 0; y < logImage->height; y++) {
+ for (size_t x = 0; x < logImage->width * logImage->depth; x++)
row[x] = swap_ushort((unsigned short)float_uint(data[y * logImage->width * logImage->depth + x], 65535), logImage->isMSB);
if (logimage_fwrite(row, rowLength, 1, logImage) == 0) {
@@ -383,7 +380,7 @@ int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
/* descriptor_Depth and descriptor_Composite are not supported */
if (logImage->element[i].descriptor != descriptor_Depth && logImage->element[i].descriptor != descriptor_Composite) {
/* Allocate memory */
- elementData[i] = (float *)MEM_mallocN(logImage->width * logImage->height * logImage->element[i].depth * sizeof(float), __func__);
+ elementData[i] = imb_alloc_pixels(logImage->width, logImage->height, logImage->element[i].depth, sizeof(float), __func__);
if (elementData[i] == NULL) {
if (verbose) printf("DPX/Cineon: Cannot allocate memory for elementData[%d]\n.", i);
for (j = 0; j < i; j++)
@@ -531,7 +528,7 @@ int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB
}
}
- mergedData = (float *)MEM_mallocN(logImage->width * logImage->height * mergedElement.depth * sizeof(float), __func__);
+ mergedData = (float *)imb_alloc_pixels(logImage->width, logImage->height, mergedElement.depth, sizeof(float), __func__);
if (mergedData == NULL) {
if (verbose) printf("DPX/Cineon: Cannot allocate mergedData.\n");
for (i = 0; i < logImage->numElements; i++)
@@ -572,26 +569,25 @@ static int logImageElementGetData(LogImageFile *logImage, LogImageElement logEle
return logImageElementGetData10Packed(logImage, logElement, data);
else if (logElement.packing == 1 || logElement.packing == 2)
return logImageElementGetData10(logImage, logElement, data);
+ break;
case 12:
if (logElement.packing == 0)
return logImageElementGetData12Packed(logImage, logElement, data);
else if (logElement.packing == 1 || logElement.packing == 2)
return logImageElementGetData12(logImage, logElement, data);
+ break;
case 16:
return logImageElementGetData16(logImage, logElement, data);
-
- default:
- /* format not supported */
- return 1;
}
+ /* format not supported */
+ return 1;
}
static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logElement, float *data)
{
unsigned int pixel;
- int x, y, offset;
/* seek at the right place */
if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
@@ -600,14 +596,14 @@ static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logEl
}
/* read 1 bit data padded to 32 bits */
- for (y = 0; y < logImage->height; y++) {
- for (x = 0; x < logImage->width * logElement.depth; x += 32) {
+ for (size_t y = 0; y < logImage->height; y++) {
+ for (size_t x = 0; x < logImage->width * logElement.depth; x += 32) {
if (logimage_read_uint(&pixel, logImage) != 0) {
if (verbose) printf("DPX/Cineon: EOF reached\n");
return 1;
}
pixel = swap_uint(pixel, logImage->isMSB);
- for (offset = 0; offset < 32 && x + offset < logImage->width; offset++)
+ for (int offset = 0; offset < 32 && x + offset < logImage->width; offset++)
data[y * logImage->width * logElement.depth + x + offset] = (float)((pixel >> offset) & 0x01);
}
}
@@ -616,19 +612,18 @@ static int logImageElementGetData1(LogImageFile *logImage, LogImageElement logEl
static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned char pixel;
- int x, y;
/* extract required pixels */
- for (y = 0; y < logImage->height; y++) {
+ for (size_t y = 0; y < logImage->height; y++) {
/* 8 bits are 32-bits padded so we need to seek at each row */
if (logimage_fseek(logImage, logElement.dataOffset + y * rowLength, SEEK_SET) != 0) {
- if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", logElement.dataOffset + y * (int)rowLength);
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %d\n", (int)(logElement.dataOffset + y * rowLength));
return 1;
}
- for (x = 0; x < logImage->width * logElement.depth; x++) {
+ for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (logimage_read_uchar(&pixel, logImage) != 0) {
if (verbose) printf("DPX/Cineon: EOF reached\n");
return 1;
@@ -642,7 +637,6 @@ static int logImageElementGetData8(LogImageFile *logImage, LogImageElement logEl
static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logElement, float *data)
{
unsigned int pixel;
- int x, y, offset;
/* seek to data */
if (logimage_fseek(logImage, logElement.dataOffset, SEEK_SET) != 0) {
@@ -651,9 +645,9 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
}
if (logImage->depth == 1 && logImage->srcFormat == format_DPX) {
- for (y = 0; y < logImage->height; y++) {
- offset = 32;
- for (x = 0; x < logImage->width * logElement.depth; x++) {
+ for (size_t y = 0; y < logImage->height; y++) {
+ int offset = 32;
+ for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
/* we need to read the next long */
if (offset >= 30) {
if (logElement.packing == 1)
@@ -673,9 +667,9 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
}
}
else {
- for (y = 0; y < logImage->height; y++) {
- offset = -1;
- for (x = 0; x < logImage->width * logElement.depth; x++) {
+ for (size_t y = 0; y < logImage->height; y++) {
+ int offset = -1;
+ for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
/* we need to read the next long */
if (offset < 0) {
if (logElement.packing == 1)
@@ -700,23 +694,22 @@ static int logImageElementGetData10(LogImageFile *logImage, LogImageElement logE
static int logImageElementGetData10Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, oldPixel;
- int offset, offset2, x, y;
/* converting bytes to pixels */
- for (y = 0; y < logImage->height; y++) {
+ for (size_t y = 0; y < logImage->height; y++) {
/* seek to data */
if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
- if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset);
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", (unsigned int)(y * rowLength + logElement.dataOffset));
return 1;
}
oldPixel = 0;
- offset = 0;
- offset2 = 0;
+ int offset = 0;
+ int offset2 = 0;
- for (x = 0; x < logImage->width * logElement.depth; x++) {
+ for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (offset2 != 0) {
offset = 10 - offset2;
offset2 = 0;
@@ -779,23 +772,22 @@ static int logImageElementGetData12(LogImageFile *logImage, LogImageElement logE
static int logImageElementGetData12Packed(LogImageFile *logImage, LogImageElement logElement, float *data)
{
- unsigned int rowLength = getRowLength(logImage->width, logElement);
+ size_t rowLength = getRowLength(logImage->width, logElement);
unsigned int pixel, oldPixel;
- int offset, offset2, x, y;
/* converting bytes to pixels */
- for (y = 0; y < logImage->height; y++) {
+ for (size_t y = 0; y < logImage->height; y++) {
/* seek to data */
if (logimage_fseek(logImage, y * rowLength + logElement.dataOffset, SEEK_SET) != 0) {
- if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", y * rowLength + logElement.dataOffset);
+ if (verbose) printf("DPX/Cineon: Couldn't seek at %u\n", (unsigned int)(y * rowLength + logElement.dataOffset));
return 1;
}
oldPixel = 0;
- offset = 0;
- offset2 = 0;
+ int offset = 0;
+ int offset2 = 0;
- for (x = 0; x < logImage->width * logElement.depth; x++) {
+ for (size_t x = 0; x < logImage->width * logElement.depth; x++) {
if (offset2 != 0) {
offset = 12 - offset2;
offset2 = 0;
@@ -1021,6 +1013,7 @@ static int convertRGBA_RGB(float *src, float *dst, LogImageFile *logImage,
float *dst_ptr = dst;
switch (logElement.transfer) {
+ case transfer_Unspecified:
case transfer_UserDefined:
case transfer_Linear:
case transfer_Logarithmic: {
@@ -1055,6 +1048,7 @@ static int convertRGBA_RGB(float *src, float *dst, LogImageFile *logImage,
}
default:
+ if (verbose) printf("DPX/Cineon: Unknown transfer %d.\n", logElement.transfer);
return 1;
}
}
@@ -1067,6 +1061,7 @@ static int convertRGB_RGBA(float *src, float *dst, LogImageFile *logImage,
float *dst_ptr = dst;
switch (logElement.transfer) {
+ case transfer_Unspecified:
case transfer_UserDefined:
case transfer_Linear:
case transfer_Logarithmic: {
@@ -1101,6 +1096,7 @@ static int convertRGB_RGBA(float *src, float *dst, LogImageFile *logImage,
}
default:
+ if (verbose) printf("DPX/Cineon: Unknown transfer %d.\n", logElement.transfer);
return 1;
}
}
@@ -1116,7 +1112,7 @@ static int convertRGBA_RGBA(float *src, float *dst, LogImageFile *logImage,
case transfer_UserDefined:
case transfer_Linear:
case transfer_Logarithmic: {
- memcpy(dst, src, 4 * logImage->width * logImage->height * sizeof(float));
+ memcpy(dst, src, 4 * (size_t)logImage->width * (size_t)logImage->height * sizeof(float));
return 0;
}
@@ -1431,11 +1427,11 @@ static int convertRGBAToLogElement(float *src, float *dst, LogImageFile *logImag
if (srcIsLinearRGB != 0) {
/* we need to convert src to sRGB */
- srgbSrc = (float *)MEM_mallocN(4 * logImage->width * logImage->height * sizeof(float), __func__);
+ srgbSrc = (float *)imb_alloc_pixels(logImage->width, logImage->height, 4, sizeof(float), __func__);
if (srgbSrc == NULL)
return 1;
- memcpy(srgbSrc, src, 4 * logImage->width * logImage->height * sizeof(float));
+ memcpy(srgbSrc, src, 4 * (size_t)logImage->width * (size_t)logImage->height * sizeof(float));
srgbSrc_ptr = srgbSrc;
/* convert data from Linear RGB to sRGB via lut */
diff --git a/source/blender/imbuf/intern/cineon/logImageCore.h b/source/blender/imbuf/intern/cineon/logImageCore.h
index e39df1ea096..b6f4fff73f6 100644
--- a/source/blender/imbuf/intern/cineon/logImageCore.h
+++ b/source/blender/imbuf/intern/cineon/logImageCore.h
@@ -196,7 +196,7 @@ LogImageFile *logImageCreate(const char *filename, int cineon, int width, int he
void logImageClose(LogImageFile *logImage);
/* Data handling */
-unsigned int getRowLength(int width, LogImageElement logElement);
+size_t getRowLength(size_t width, LogImageElement logElement);
int logImageSetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);
int logImageGetDataRGBA(LogImageFile *logImage, float *data, int dataIsLinearRGB);
diff --git a/source/blender/imbuf/intern/colormanagement.c b/source/blender/imbuf/intern/colormanagement.c
index 48cba3e0800..b2197ecb3b5 100644
--- a/source/blender/imbuf/intern/colormanagement.c
+++ b/source/blender/imbuf/intern/colormanagement.c
@@ -47,7 +47,9 @@
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
#include "IMB_filetype.h"
+#include "IMB_filter.h"
#include "IMB_moviecache.h"
+#include "IMB_metadata.h"
#include "MEM_guardedalloc.h"
@@ -63,6 +65,7 @@
#include "BKE_context.h"
#include "BKE_image.h"
#include "BKE_main.h"
+#include "BKE_sequencer.h"
#include "RNA_define.h"
@@ -214,7 +217,7 @@ typedef struct ColormanageCacheKey {
int display; /* display device name */
} ColormanageCacheKey;
-typedef struct ColormnaageCacheData {
+typedef struct ColormanageCacheData {
int flag; /* view flags of cached buffer */
int look; /* Additional artistics transform */
float exposure; /* exposure value cached buffer is calculated with */
@@ -222,12 +225,12 @@ typedef struct ColormnaageCacheData {
float dither; /* dither value cached buffer is calculated with */
CurveMapping *curve_mapping; /* curve mapping used for cached buffer */
int curve_mapping_timestamp; /* time stamp of curve mapping used for cached buffer */
-} ColormnaageCacheData;
+} ColormanageCacheData;
typedef struct ColormanageCache {
struct MovieCache *moviecache;
- ColormnaageCacheData *data;
+ ColormanageCacheData *data;
} ColormanageCache;
static struct MovieCache *colormanage_moviecache_get(const ImBuf *ibuf)
@@ -238,7 +241,7 @@ static struct MovieCache *colormanage_moviecache_get(const ImBuf *ibuf)
return ibuf->colormanage_cache->moviecache;
}
-static ColormnaageCacheData *colormanage_cachedata_get(const ImBuf *ibuf)
+static ColormanageCacheData *colormanage_cachedata_get(const ImBuf *ibuf)
{
if (!ibuf->colormanage_cache)
return NULL;
@@ -281,7 +284,7 @@ static struct MovieCache *colormanage_moviecache_ensure(ImBuf *ibuf)
return ibuf->colormanage_cache->moviecache;
}
-static void colormanage_cachedata_set(ImBuf *ibuf, ColormnaageCacheData *data)
+static void colormanage_cachedata_set(ImBuf *ibuf, ColormanageCacheData *data)
{
if (!ibuf->colormanage_cache)
ibuf->colormanage_cache = MEM_callocN(sizeof(ColormanageCache), "imbuf colormanage cache");
@@ -361,7 +364,7 @@ static unsigned char *colormanage_cache_get(ImBuf *ibuf, const ColormanageCacheV
cache_ibuf = colormanage_cache_get_ibuf(ibuf, &key, cache_handle);
if (cache_ibuf) {
- ColormnaageCacheData *cache_data;
+ ColormanageCacheData *cache_data;
BLI_assert(cache_ibuf->x == ibuf->x &&
cache_ibuf->y == ibuf->y);
@@ -402,7 +405,7 @@ static void colormanage_cache_put(ImBuf *ibuf, const ColormanageCacheViewSetting
{
ColormanageCacheKey key;
ImBuf *cache_ibuf;
- ColormnaageCacheData *cache_data;
+ ColormanageCacheData *cache_data;
int view_flag = 1 << (view_settings->view - 1);
struct MovieCache *moviecache = colormanage_moviecache_ensure(ibuf);
CurveMapping *curve_mapping = view_settings->curve_mapping;
@@ -421,7 +424,7 @@ static void colormanage_cache_put(ImBuf *ibuf, const ColormanageCacheViewSetting
cache_ibuf->flags |= IB_rect;
/* store data which is needed to check whether cached buffer could be used for color managed display settings */
- cache_data = MEM_callocN(sizeof(ColormnaageCacheData), "color manage cache imbuf data");
+ cache_data = MEM_callocN(sizeof(ColormanageCacheData), "color manage cache imbuf data");
cache_data->look = view_settings->look;
cache_data->exposure = view_settings->exposure;
cache_data->gamma = view_settings->gamma;
@@ -710,7 +713,7 @@ void colormanage_cache_free(ImBuf *ibuf)
}
if (ibuf->colormanage_cache) {
- ColormnaageCacheData *cache_data = colormanage_cachedata_get(ibuf);
+ ColormanageCacheData *cache_data = colormanage_cachedata_get(ibuf);
struct MovieCache *moviecache = colormanage_moviecache_get(ibuf);
if (cache_data) {
@@ -1112,6 +1115,7 @@ void IMB_colormanagement_check_file_config(Main *bmain)
for (scene = bmain->scene.first; scene; scene = scene->id.next) {
ColorManagedColorspaceSettings *sequencer_colorspace_settings;
+ /* check scene color management settings */
colormanage_check_display_settings(&scene->display_settings, "scene", default_display);
colormanage_check_view_settings(&scene->display_settings, &scene->view_settings, "scene");
@@ -1122,6 +1126,15 @@ void IMB_colormanagement_check_file_config(Main *bmain)
if (sequencer_colorspace_settings->name[0] == '\0') {
BLI_strncpy(sequencer_colorspace_settings->name, global_role_default_sequencer, MAX_COLORSPACE_NAME);
}
+
+ /* check sequencer strip input color space settings */
+ Sequence *seq;
+ SEQ_BEGIN (scene->ed, seq) {
+ if (seq->strip) {
+ colormanage_check_colorspace_settings(&seq->strip->colorspace_settings, "sequencer strip");
+ }
+ }
+ SEQ_END
}
/* ** check input color space settings ** */
@@ -1406,7 +1419,7 @@ static void *do_display_buffer_apply_thread(void *handle_v)
bool is_data = handle->is_data;
if (cm_processor == NULL) {
- if (display_buffer_byte) {
+ if (display_buffer_byte && display_buffer_byte != handle->byte_buffer) {
IMB_buffer_byte_from_byte(display_buffer_byte, handle->byte_buffer, IB_PROFILE_SRGB, IB_PROFILE_SRGB,
false, width, height, width, width);
}
@@ -1510,6 +1523,10 @@ static bool is_ibuf_rect_in_display_space(ImBuf *ibuf, const ColorManagedViewSet
{
const char *from_colorspace = ibuf->rect_colorspace->name;
const char *to_colorspace = IMB_colormanagement_get_display_colorspace_name(view_settings, display_settings);
+ ColorManagedLook *look_descr = colormanage_look_get_named(view_settings->look);
+ if (look_descr != NULL && !STREQ(look_descr->process_space, "")) {
+ return false;
+ }
if (to_colorspace && STREQ(from_colorspace, to_colorspace))
return true;
@@ -1624,12 +1641,13 @@ static void *do_processor_transform_thread(void *handle_v)
if (float_from_byte) {
IMB_buffer_float_from_byte(float_buffer, byte_buffer,
IB_PROFILE_SRGB, IB_PROFILE_SRGB,
- true,
+ false,
width, height, width, width);
- IMB_colormanagement_processor_apply(handle->cm_processor,
- float_buffer,
- width, height, channels,
- predivide);
+ IMB_colormanagement_processor_apply(handle->cm_processor,
+ float_buffer,
+ width, height, channels,
+ predivide);
+ IMB_premultiply_rect_float(float_buffer, 4, width, height);
}
else {
if (byte_buffer != NULL) {
@@ -1759,15 +1777,21 @@ void IMB_colormanagement_transform_from_byte_threaded(float *float_buffer, unsig
return;
}
if (STREQ(from_colorspace, to_colorspace)) {
- /* If source and destination color spaces are identical, skip
- * threading overhead and simply do nothing
+ /* Because this function always takes a byte buffer and returns a float buffer, it must
+ * always do byte-to-float conversion of some kind. To avoid threading overhead
+ * IMB_buffer_float_from_byte is used when color spaces are identical. See T51002.
*/
+ IMB_buffer_float_from_byte(float_buffer, byte_buffer,
+ IB_PROFILE_SRGB, IB_PROFILE_SRGB,
+ false,
+ width, height, width, width);
+ IMB_premultiply_rect_float(float_buffer, 4, width, height);
return;
}
cm_processor = IMB_colormanagement_colorspace_processor_new(from_colorspace, to_colorspace);
processor_transform_apply_threaded(byte_buffer, float_buffer,
width, height, channels,
- cm_processor, true, true);
+ cm_processor, false, true);
IMB_colormanagement_processor_free(cm_processor);
}
@@ -2060,6 +2084,10 @@ ImBuf *IMB_colormanagement_imbuf_for_write(ImBuf *ibuf, bool save_as_render, boo
}
}
+ if (colormanaged_ibuf != ibuf) {
+ IMB_metadata_copy(colormanaged_ibuf, ibuf);
+ }
+
return colormanaged_ibuf;
}
@@ -2149,7 +2177,7 @@ unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSet
BLI_rcti_init(&ibuf->invalid_rect, 0, 0, 0, 0);
}
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_thread_lock(LOCK_COLORMANAGE);
/* ensure color management bit fields exists */
if (!ibuf->display_buffer_flags) {
@@ -2167,7 +2195,7 @@ unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSet
display_buffer = colormanage_cache_get(ibuf, &cache_view_settings, &cache_display_settings, cache_handle);
if (display_buffer) {
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_thread_unlock(LOCK_COLORMANAGE);
return display_buffer;
}
@@ -2178,7 +2206,7 @@ unsigned char *IMB_display_buffer_acquire(ImBuf *ibuf, const ColorManagedViewSet
colormanage_cache_put(ibuf, &cache_view_settings, &cache_display_settings, display_buffer, cache_handle);
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_thread_unlock(LOCK_COLORMANAGE);
return display_buffer;
}
@@ -2217,11 +2245,11 @@ void IMB_display_buffer_transform_apply(unsigned char *display_buffer, float *li
void IMB_display_buffer_release(void *cache_handle)
{
if (cache_handle) {
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_thread_lock(LOCK_COLORMANAGE);
colormanage_cache_handle_release(cache_handle);
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_thread_unlock(LOCK_COLORMANAGE);
}
}
@@ -2545,6 +2573,14 @@ const char *IMB_colormanagement_colorspace_get_indexed_name(int index)
void IMB_colormanagment_colorspace_from_ibuf_ftype(ColorManagedColorspaceSettings *colorspace_settings, ImBuf *ibuf)
{
+ /* Don't modify non-color data space, it does not change with file type. */
+ ColorSpace *colorspace = colormanage_colorspace_get_named(colorspace_settings->name);
+
+ if (colorspace && colorspace->is_data) {
+ return;
+ }
+
+ /* Get color space from file type. */
const ImFileType *type;
for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
@@ -2568,9 +2604,17 @@ ColorManagedLook *colormanage_look_add(const char *name, const char *process_spa
look = MEM_callocN(sizeof(ColorManagedLook), "ColorManagedLook");
look->index = index + 1;
BLI_strncpy(look->name, name, sizeof(look->name));
+ BLI_strncpy(look->ui_name, name, sizeof(look->ui_name));
BLI_strncpy(look->process_space, process_space, sizeof(look->process_space));
look->is_noop = is_noop;
+ /* Detect view specific looks. */
+ const char *separator_offset = strstr(look->name, " - ");
+ if (separator_offset) {
+ BLI_strncpy(look->view, look->name, separator_offset - look->name + 1);
+ BLI_strncpy(look->ui_name, separator_offset + strlen(" - "), sizeof(look->ui_name));
+ }
+
BLI_addtail(&global_looks, look);
global_tot_looks++;
@@ -2671,15 +2715,27 @@ void IMB_colormanagement_view_items_add(EnumPropertyItem **items, int *totitem,
}
}
-void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem)
+void IMB_colormanagement_look_items_add(struct EnumPropertyItem **items, int *totitem, const char *view_name)
{
ColorManagedLook *look;
+ const char *view_filter = NULL;
+ /* Test if this view transform is limited to specific looks. */
for (look = global_looks.first; look; look = look->next) {
+ if (STREQ(look->view, view_name)) {
+ view_filter = view_name;
+ }
+ }
+
+ for (look = global_looks.first; look; look = look->next) {
+ if (!look->is_noop && view_filter && !STREQ(look->view, view_filter)) {
+ continue;
+ }
+
EnumPropertyItem item;
item.value = look->index;
- item.name = look->name;
+ item.name = look->ui_name;
item.identifier = look->name;
item.icon = 0;
item.description = "";
@@ -2909,7 +2965,7 @@ static void imb_partial_display_buffer_update_ex(ImBuf *ibuf,
view_flag = 1 << (cache_view_settings.view - 1);
display_index = cache_display_settings.display - 1;
- BLI_lock_thread(LOCK_COLORMANAGE);
+ BLI_thread_lock(LOCK_COLORMANAGE);
if ((ibuf->userflags & IB_DISPLAY_BUFFER_INVALID) == 0) {
display_buffer = colormanage_cache_get(ibuf,
@@ -2928,7 +2984,7 @@ static void imb_partial_display_buffer_update_ex(ImBuf *ibuf,
memset(ibuf->display_buffer_flags, 0, global_tot_display * sizeof(unsigned int));
ibuf->display_buffer_flags[display_index] |= view_flag;
- BLI_unlock_thread(LOCK_COLORMANAGE);
+ BLI_thread_unlock(LOCK_COLORMANAGE);
}
if (display_buffer == NULL) {
diff --git a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
index a4281514e39..7c11fca3c34 100644
--- a/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
+++ b/source/blender/imbuf/intern/dds/DirectDrawSurface.cpp
@@ -704,11 +704,12 @@ void DDSHeader::setPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask
{
// Make sure the masks are correct.
if ((rmask & gmask) ||
- (rmask & bmask) ||
- (rmask & amask) ||
- (gmask & bmask) ||
- (gmask & amask) ||
- (bmask & amask)) {
+ (rmask & bmask) ||
+ (rmask & amask) ||
+ (gmask & bmask) ||
+ (gmask & amask) ||
+ (bmask & amask))
+ {
printf("DDS: bad RGBA masks, pixel format not set\n");
return;
}
@@ -1068,7 +1069,7 @@ bool DirectDrawSurface::isTexture3D() const
}
else
{
- return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0;
+ return (header.caps.caps2 & DDSCAPS2_VOLUME) != 0;
}
}
diff --git a/source/blender/imbuf/intern/dds/dds_api.cpp b/source/blender/imbuf/intern/dds/dds_api.cpp
index 12e03f55450..67a0b0ffd00 100644
--- a/source/blender/imbuf/intern/dds/dds_api.cpp
+++ b/source/blender/imbuf/intern/dds/dds_api.cpp
@@ -37,7 +37,7 @@ extern "C" {
#include <stdio.h> // printf
#include <fstream>
-#if defined (WIN32) && !defined(FREE_WINDOWS)
+#if defined (WIN32)
#include "utfconv.h"
#endif
@@ -62,7 +62,7 @@ int imb_save_dds(struct ImBuf *ibuf, const char *name, int /*flags*/)
/* open file for writing */
std::ofstream fildes;
-#if defined (WIN32) && !defined(FREE_WINDOWS)
+#if defined (WIN32)
wchar_t *wname = alloc_utf16_from_8(name, 0);
fildes.open(wname);
free(wname);
diff --git a/source/blender/imbuf/intern/filetype.c b/source/blender/imbuf/intern/filetype.c
index 3d3e8a0646a..7ed5c8ffbcb 100644
--- a/source/blender/imbuf/intern/filetype.c
+++ b/source/blender/imbuf/intern/filetype.c
@@ -47,10 +47,6 @@
#include "dds/dds_api.h"
#endif
-#ifdef WITH_QUICKTIME
-#include "quicktime_import.h"
-#endif
-
static int imb_ftype_default(const ImFileType *type, ImBuf *ibuf)
{
return (ibuf->ftype == type->filetype);
@@ -101,10 +97,6 @@ void imb_filetypes_init(void)
for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++)
if (type->init)
type->init();
-
-#ifdef WITH_QUICKTIME
- quicktime_init();
-#endif
}
void imb_filetypes_exit(void)
@@ -114,9 +106,5 @@ void imb_filetypes_exit(void)
for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++)
if (type->exit)
type->exit();
-
-#ifdef WITH_QUICKTIME
- quicktime_exit();
-#endif
}
diff --git a/source/blender/imbuf/intern/filter.c b/source/blender/imbuf/intern/filter.c
index 1987c6d2a9a..38609d0a342 100644
--- a/source/blender/imbuf/intern/filter.c
+++ b/source/blender/imbuf/intern/filter.c
@@ -406,7 +406,7 @@ void IMB_filter_extend(struct ImBuf *ibuf, char *mask, int filter)
const int height = ibuf->y;
const int depth = 4; /* always 4 channels */
const int chsize = ibuf->rect_float ? sizeof(float) : sizeof(unsigned char);
- const int bsize = width * height * depth * chsize;
+ const size_t bsize = ((size_t)width) * height * depth * chsize;
const bool is_float = (ibuf->rect_float != NULL);
void *dstbuf = (void *) MEM_dupallocN(ibuf->rect_float ? (void *) ibuf->rect_float : (void *) ibuf->rect);
char *dstmask = mask == NULL ? NULL : (char *) MEM_dupallocN(mask);
@@ -499,7 +499,9 @@ void IMB_filter_extend(struct ImBuf *ibuf, char *mask, int filter)
/* keep the original buffer up to date. */
memcpy(srcbuf, dstbuf, bsize);
- if (dstmask != NULL) memcpy(srcmask, dstmask, width * height);
+ if (dstmask != NULL) {
+ memcpy(srcmask, dstmask, ((size_t)width) * height);
+ }
}
/* free memory */
diff --git a/source/blender/imbuf/intern/indexer.c b/source/blender/imbuf/intern/indexer.c
index e1b3abcf2f6..eaf4dfd84b4 100644
--- a/source/blender/imbuf/intern/indexer.c
+++ b/source/blender/imbuf/intern/indexer.c
@@ -843,9 +843,9 @@ static void index_rebuild_ffmpeg_finish(FFmpegIndexBuilderContext *context, int
}
static void index_rebuild_ffmpeg_proc_decoded_frame(
- FFmpegIndexBuilderContext *context,
- AVPacket * curr_packet,
- AVFrame *in_frame)
+ FFmpegIndexBuilderContext *context,
+ AVPacket *curr_packet,
+ AVFrame *in_frame)
{
int i;
unsigned long long s_pos = context->seek_pos;
@@ -909,7 +909,7 @@ static int index_rebuild_ffmpeg(FFmpegIndexBuilderContext *context,
stream_size = avio_size(context->iFormatCtx->pb);
- context->frame_rate = av_q2d(av_get_r_frame_rate_compat(context->iStream));
+ context->frame_rate = av_q2d(av_get_r_frame_rate_compat(context->iFormatCtx, context->iStream));
context->pts_time_base = av_q2d(context->iStream->time_base);
while (av_read_frame(context->iFormatCtx, &next_packet) >= 0) {
diff --git a/source/blender/imbuf/intern/iris.c b/source/blender/imbuf/intern/iris.c
index 7a9fa2b9768..55727ed6697 100644
--- a/source/blender/imbuf/intern/iris.c
+++ b/source/blender/imbuf/intern/iris.c
@@ -48,36 +48,24 @@
#define IMAGIC 0732
typedef struct {
- unsigned short imagic; /* stuff saved on disk . . */
- unsigned short type;
- unsigned short dim;
- unsigned short xsize;
- unsigned short ysize;
- unsigned short zsize;
- unsigned int min;
- unsigned int max;
- unsigned int wastebytes;
- char name[80];
- unsigned int colormap;
-
- int file; /* stuff used in core only */
- unsigned short flags;
- short dorev;
- short x;
- short y;
- short z;
- short cnt;
- unsigned short *ptr;
- unsigned short *base;
- unsigned short *tmpbuf;
- unsigned int offset;
- unsigned int rleend; /* for rle images */
- unsigned int *rowstart; /* for rle images */
- const int *rowsize; /* for rle images */
+ ushort imagic; /* stuff saved on disk . . */
+ ushort type;
+ ushort dim;
+ ushort xsize;
+ ushort ysize;
+ ushort zsize;
+ uint min;
+ uint max;
+ uchar _pad1[4];
+ char name[80];
+ uint colormap;
+ uchar _pad2[404];
} IMAGE;
#define HEADER_SIZE 512
+BLI_STATIC_ASSERT(sizeof(IMAGE) == HEADER_SIZE, "Invalid header size");
+
#define RINTLUM (79)
#define GINTLUM (156)
#define BINTLUM (21)
@@ -106,68 +94,72 @@ typedef struct {
/* local struct for mem access */
typedef struct MFileOffset {
const uchar *_file_data;
- unsigned int _file_offset;
+ uint _file_offset;
} MFileOffset;
-#define MFILE_DATA(inf) ((void)0, (inf)->_file_data + (inf)->_file_offset)
+#define MFILE_DATA(inf) ((void)0, ((inf)->_file_data + (inf)->_file_offset))
#define MFILE_STEP(inf, step) { (inf)->_file_offset += step; } ((void)0)
#define MFILE_SEEK(inf, pos) { (inf)->_file_offset = pos; } ((void)0)
+/* error flags */
+#define DIRTY_FLAG_EOF (1 << 0)
+#define DIRTY_FLAG_ENCODING (1 << 1)
+
/* funcs */
static void readheader(MFileOffset *inf, IMAGE *image);
static int writeheader(FILE *outf, IMAGE *image);
-static unsigned short getshort(MFileOffset *inf);
-static unsigned int getlong(MFileOffset *inf);
-static void putshort(FILE *outf, unsigned short val);
-static int putlong(FILE *outf, unsigned int val);
-static int writetab(FILE *outf, unsigned int *tab, int len);
-static void readtab(MFileOffset *inf, unsigned int *tab, int len);
+static ushort getshort(MFileOffset *inf);
+static uint getlong(MFileOffset *inf);
+static void putshort(FILE *outf, ushort val);
+static int putlong(FILE *outf, uint val);
+static int writetab(FILE *outf, uint *tab, int len);
+static void readtab(MFileOffset *inf, uint *tab, int len);
-static void expandrow(unsigned char *optr, const unsigned char *iptr, int z);
-static void expandrow2(float *optr, const unsigned char *iptr, int z);
-static void interleaverow(unsigned char *lptr, const unsigned char *cptr, int z, int n);
-static void interleaverow2(float *lptr, const unsigned char *cptr, int z, int n);
-static int compressrow(unsigned char *lbuf, unsigned char *rlebuf, int z, int cnt);
-static void lumrow(unsigned char *rgbptr, unsigned char *lumptr, int n);
+static int expandrow(uchar *optr, const uchar *optr_end, const uchar *iptr, const uchar *iptr_end, int z);
+static int expandrow2(float *optr, const float *optr_end, const uchar *iptr, const uchar *iptr_end, int z);
+static void interleaverow(uchar *lptr, const uchar *cptr, int z, int n);
+static void interleaverow2(float *lptr, const uchar *cptr, int z, int n);
+static int compressrow(uchar *lbuf, uchar *rlebuf, int z, int cnt);
+static void lumrow(uchar *rgbptr, uchar *lumptr, int n);
/*
* byte order independent read/write of shorts and ints.
*
*/
-static unsigned short getshort(MFileOffset *inf)
+static ushort getshort(MFileOffset *inf)
{
- const unsigned char *buf;
+ const uchar *buf;
buf = MFILE_DATA(inf);
MFILE_STEP(inf, 2);
-
- return (buf[0] << 8) + (buf[1] << 0);
+
+ return ((ushort)buf[0] << 8) + ((ushort)buf[1] << 0);
}
-static unsigned int getlong(MFileOffset *mofs)
+static uint getlong(MFileOffset *mofs)
{
- const unsigned char *buf;
+ const uchar *buf;
buf = MFILE_DATA(mofs);
MFILE_STEP(mofs, 4);
-
- return (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + (buf[3] << 0);
+
+ return ((uint)buf[0] << 24) + ((uint)buf[1] << 16) + ((uint)buf[2] << 8) + ((uint)buf[3] << 0);
}
-static void putshort(FILE *outf, unsigned short val)
+static void putshort(FILE *outf, ushort val)
{
- unsigned char buf[2];
+ uchar buf[2];
buf[0] = (val >> 8);
buf[1] = (val >> 0);
fwrite(buf, 2, 1, outf);
}
-static int putlong(FILE *outf, unsigned int val)
+static int putlong(FILE *outf, uint val)
{
- unsigned char buf[4];
+ uchar buf[4];
buf[0] = (val >> 24);
buf[1] = (val >> 16);
@@ -205,7 +197,7 @@ static int writeheader(FILE *outf, IMAGE *image)
return fwrite("no name", 8, 1, outf);
}
-static int writetab(FILE *outf, unsigned int *tab, int len)
+static int writetab(FILE *outf, uint *tab, int len)
{
int r = 0;
@@ -216,7 +208,7 @@ static int writetab(FILE *outf, unsigned int *tab, int len)
return r;
}
-static void readtab(MFileOffset *inf, unsigned int *tab, int len)
+static void readtab(MFileOffset *inf, uint *tab, int len)
{
while (len) {
*tab++ = getlong(inf);
@@ -242,12 +234,12 @@ static void test_endian_zbuf(struct ImBuf *ibuf)
}
/* from misc_util: flip the bytes from x */
-#define GS(x) (((unsigned char *)(x))[0] << 8 | ((unsigned char *)(x))[1])
+#define GS(x) (((uchar *)(x))[0] << 8 | ((uchar *)(x))[1])
/* this one is only def-ed once, strangely... */
#define GSS(x) (((uchar *)(x))[1] << 8 | ((uchar *)(x))[0])
-int imb_is_a_iris(const unsigned char *mem)
+int imb_is_a_iris(const uchar *mem)
{
return ((GS(mem) == IMAGIC) || (GSS(mem) == IMAGIC));
}
@@ -259,46 +251,51 @@ int imb_is_a_iris(const unsigned char *mem)
*
*/
-struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
+struct ImBuf *imb_loadiris(const uchar *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
{
- unsigned int *base, *lptr = NULL;
+ uint *base, *lptr = NULL;
float *fbase, *fptr = NULL;
- unsigned int *zbase, *zptr;
- const unsigned char *rledat;
- unsigned int *starttab, *lengthtab;
+ uint *zbase, *zptr;
+ const uchar *rledat;
+ const uchar *mem_end = mem + size;
MFileOffset _inf_data = {mem, 0}, *inf = &_inf_data;
IMAGE image;
- int x, y, z, tablen;
- int xsize, ysize, zsize;
int bpp, rle, cur, badorder;
- ImBuf *ibuf;
+ ImBuf *ibuf = NULL;
+ uchar dirty_flag = 0;
- (void)size; /* unused */
-
- if (!imb_is_a_iris(mem)) return NULL;
+ if (size < HEADER_SIZE) {
+ return NULL;
+ }
+
+ if (!imb_is_a_iris(mem)) {
+ return NULL;
+ }
/* OCIO_TODO: only tested with 1 byte per pixel, not sure how to test with other settings */
colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_BYTE);
- /*printf("new iris\n");*/
-
readheader(inf, &image);
if (image.imagic != IMAGIC) {
fprintf(stderr, "longimagedata: bad magic number in image file\n");
return(NULL);
}
-
+
rle = ISRLE(image.type);
bpp = BPP(image.type);
if (bpp != 1 && bpp != 2) {
fprintf(stderr, "longimagedata: image must have 1 or 2 byte per pix chan\n");
return(NULL);
}
-
- xsize = image.xsize;
- ysize = image.ysize;
- zsize = image.zsize;
-
+ if ((uint)image.zsize > 8) {
+ fprintf(stderr, "longimagedata: channels over 8 not supported\n");
+ return(NULL);
+ }
+
+ const int xsize = image.xsize;
+ const int ysize = image.ysize;
+ const int zsize = image.zsize;
+
if (flags & IB_test) {
ibuf = IMB_allocImBuf(image.xsize, image.ysize, 8 * image.zsize, 0);
if (ibuf) ibuf->ftype = IMB_FTYPE_IMAGIC;
@@ -306,20 +303,25 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
}
if (rle) {
-
- tablen = ysize * zsize * sizeof(int);
- starttab = (unsigned int *)MEM_mallocN(tablen, "iris starttab");
- lengthtab = (unsigned int *)MEM_mallocN(tablen, "iris endtab");
+ size_t tablen = (size_t)ysize * (size_t)zsize * sizeof(int);
MFILE_SEEK(inf, HEADER_SIZE);
-
+
+ uint *starttab = MEM_mallocN(tablen, "iris starttab");
+ uint *lengthtab = MEM_mallocN(tablen, "iris endtab");
+
+#define MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(p) \
+ if (UNLIKELY((p) > mem_end)) { dirty_flag |= DIRTY_FLAG_EOF; goto fail_rle; } ((void)0)
+
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(MFILE_DATA(inf) + ((4 * 2) * tablen));
+
readtab(inf, starttab, tablen);
readtab(inf, lengthtab, tablen);
/* check data order */
cur = 0;
badorder = 0;
- for (y = 0; y < ysize; y++) {
- for (z = 0; z < zsize; z++) {
+ for (size_t y = 0; y < ysize; y++) {
+ for (size_t z = 0; z < zsize; z++) {
if (starttab[y + z * ysize] < cur) {
badorder = 1;
break;
@@ -333,38 +335,51 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
if (bpp == 1) {
ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect);
+ if (!ibuf) {
+ goto fail_rle;
+ }
if (ibuf->planes > 32) ibuf->planes = 32;
base = ibuf->rect;
- zbase = (unsigned int *)ibuf->zbuf;
+ zbase = (uint *)ibuf->zbuf;
if (badorder) {
- for (z = 0; z < zsize; z++) {
+ for (size_t z = 0; z < zsize; z++) {
lptr = base;
- for (y = 0; y < ysize; y++) {
+ for (size_t y = 0; y < ysize; y++) {
MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]);
-
- expandrow((uchar *)lptr, rledat, 3 - z);
- lptr += xsize;
+ const uchar *rledat_next = MFILE_DATA(inf);
+ uint *lptr_next = lptr + xsize;
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next);
+ dirty_flag |= expandrow((uchar *)lptr, (uchar *)lptr_next, rledat, rledat_next, 3 - z);
+ lptr = lptr_next;
}
}
}
else {
lptr = base;
zptr = zbase;
- for (y = 0; y < ysize; y++) {
-
- for (z = 0; z < zsize; z++) {
+ for (size_t y = 0; y < ysize; y++) {
+
+ uint *lptr_next = lptr + xsize;
+ uint *zptr_next = zptr + xsize;
+
+ for (size_t z = 0; z < zsize; z++) {
MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]);
-
- if (z < 4) expandrow((uchar *)lptr, rledat, 3 - z);
- else if (z < 8) expandrow((uchar *)zptr, rledat, 7 - z);
+ const uchar *rledat_next = MFILE_DATA(inf);
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next);
+ if (z < 4) {
+ dirty_flag |= expandrow((uchar *)lptr, (uchar *)lptr_next, rledat, rledat_next, 3 - z);
+ }
+ else if (z < 8) {
+ dirty_flag |= expandrow((uchar *)zptr, (uchar *)zptr_next, rledat, rledat_next, 7 - z);
+ }
}
- lptr += xsize;
- zptr += xsize;
+ lptr = lptr_next;
+ zptr = zptr_next;
}
}
@@ -373,66 +388,84 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else { /* bpp == 2 */
ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat);
-
+ if (!ibuf) {
+ goto fail_rle;
+ }
+
fbase = ibuf->rect_float;
if (badorder) {
- for (z = 0; z < zsize; z++) {
+ for (size_t z = 0; z < zsize; z++) {
fptr = fbase;
- for (y = 0; y < ysize; y++) {
+ for (size_t y = 0; y < ysize; y++) {
MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]);
-
- expandrow2(fptr, rledat, 3 - z);
- fptr += xsize * 4;
+ const uchar *rledat_next = MFILE_DATA(inf);
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next);
+ float *fptr_next = fptr + (xsize * 4);
+ dirty_flag |= expandrow2(fptr, fptr_next, rledat, rledat_next, 3 - z);
+ fptr = fptr_next;
}
}
}
else {
fptr = fbase;
+ float *fptr_next = fptr + (xsize * 4);
- for (y = 0; y < ysize; y++) {
+ for (size_t y = 0; y < ysize; y++) {
- for (z = 0; z < zsize; z++) {
+ for (size_t z = 0; z < zsize; z++) {
MFILE_SEEK(inf, starttab[y + z * ysize]);
rledat = MFILE_DATA(inf);
MFILE_STEP(inf, lengthtab[y + z * ysize]);
-
- expandrow2(fptr, rledat, 3 - z);
-
+ const uchar *rledat_next = MFILE_DATA(inf);
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next);
+ dirty_flag |= expandrow2(fptr, fptr_next, rledat, rledat_next, 3 - z);
}
- fptr += xsize * 4;
+ fptr = fptr_next;
}
}
}
-
+#undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL
+fail_rle:
MEM_freeN(starttab);
MEM_freeN(lengthtab);
+ if (!ibuf) {
+ return NULL;
+ }
}
else {
+
+#define MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(p) \
+ if (UNLIKELY((p) > mem_end)) { dirty_flag |= DIRTY_FLAG_EOF; goto fail_uncompressed; } ((void)0)
+
if (bpp == 1) {
ibuf = IMB_allocImBuf(xsize, ysize, 8 * zsize, IB_rect);
+ if (!ibuf) {
+ goto fail_uncompressed;
+ }
if (ibuf->planes > 32) ibuf->planes = 32;
base = ibuf->rect;
- zbase = (unsigned int *)ibuf->zbuf;
+ zbase = (uint *)ibuf->zbuf;
MFILE_SEEK(inf, HEADER_SIZE);
rledat = MFILE_DATA(inf);
- for (z = 0; z < zsize; z++) {
+ for (size_t z = 0; z < zsize; z++) {
if (z < 4) lptr = base;
else if (z < 8) lptr = zbase;
-
- for (y = 0; y < ysize; y++) {
- interleaverow((uchar *)lptr, rledat, 3 - z, xsize);
- rledat += xsize;
-
+ for (size_t y = 0; y < ysize; y++) {
+ const uchar *rledat_next = rledat + xsize;
+ const int z_ofs = 3 - z;
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs);
+ interleaverow((uchar *)lptr, rledat, z_ofs, xsize);
+ rledat = rledat_next;
lptr += xsize;
}
}
@@ -441,35 +474,43 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else { /* bpp == 2 */
ibuf = IMB_allocImBuf(xsize, ysize, 32, (flags & IB_rect) | IB_rectfloat);
+ if (!ibuf) {
+ goto fail_uncompressed;
+ }
fbase = ibuf->rect_float;
MFILE_SEEK(inf, HEADER_SIZE);
rledat = MFILE_DATA(inf);
- for (z = 0; z < zsize; z++) {
+ for (size_t z = 0; z < zsize; z++) {
fptr = fbase;
-
- for (y = 0; y < ysize; y++) {
- interleaverow2(fptr, rledat, 3 - z, xsize);
- rledat += xsize * 2;
-
+ for (size_t y = 0; y < ysize; y++) {
+ const uchar *rledat_next = rledat + xsize * 2;
+ const int z_ofs = 3 - z;
+ MFILE_CAPACITY_AT_PTR_OK_OR_FAIL(rledat_next + z_ofs);
+ interleaverow2(fptr, rledat, z_ofs, xsize);
+ rledat = rledat_next;
fptr += xsize * 4;
}
}
}
+#undef MFILE_CAPACITY_AT_PTR_OK_OR_FAIL
+fail_uncompressed:
+ if (!ibuf) {
+ return NULL;
+ }
}
-
-
+
if (bpp == 1) {
uchar *rect;
if (image.zsize == 1) {
rect = (uchar *) ibuf->rect;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = 255;
rect[1] = rect[2] = rect[3];
rect += 4;
@@ -478,7 +519,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else if (image.zsize == 2) {
/* grayscale with alpha */
rect = (uchar *) ibuf->rect;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = rect[2];
rect[1] = rect[2] = rect[3];
rect += 4;
@@ -487,7 +528,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else if (image.zsize == 3) {
/* add alpha */
rect = (uchar *) ibuf->rect;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
rect[0] = 255;
rect += 4;
}
@@ -498,7 +539,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
if (image.zsize == 1) {
fbase = ibuf->rect_float;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = 1;
fbase[1] = fbase[2] = fbase[3];
fbase += 4;
@@ -507,7 +548,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else if (image.zsize == 2) {
/* grayscale with alpha */
fbase = ibuf->rect_float;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = fbase[2];
fbase[1] = fbase[2] = fbase[3];
fbase += 4;
@@ -516,7 +557,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
else if (image.zsize == 3) {
/* add alpha */
fbase = ibuf->rect_float;
- for (x = ibuf->x * ibuf->y; x > 0; x--) {
+ for (size_t x = (size_t)ibuf->x * (size_t)ibuf->y; x > 0; x--) {
fbase[0] = 1;
fbase += 4;
}
@@ -528,6 +569,9 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
}
+ if (dirty_flag) {
+ fprintf(stderr, "longimagedata: corrupt file content (%d)\n", dirty_flag);
+ }
ibuf->ftype = IMB_FTYPE_IMAGIC;
test_endian_zbuf(ibuf);
@@ -541,7 +585,7 @@ struct ImBuf *imb_loadiris(const unsigned char *mem, size_t size, int flags, cha
/* static utility functions for longimagedata */
-static void interleaverow(unsigned char *lptr, const unsigned char *cptr, int z, int n)
+static void interleaverow(uchar *lptr, const uchar *cptr, int z, int n)
{
lptr += z;
while (n--) {
@@ -550,7 +594,7 @@ static void interleaverow(unsigned char *lptr, const unsigned char *cptr, int z,
}
}
-static void interleaverow2(float *lptr, const unsigned char *cptr, int z, int n)
+static void interleaverow2(float *lptr, const uchar *cptr, int z, int n)
{
lptr += z;
while (n--) {
@@ -560,19 +604,34 @@ static void interleaverow2(float *lptr, const unsigned char *cptr, int z, int n)
}
}
-static void expandrow2(float *optr, const unsigned char *iptr, int z)
+static int expandrow2(
+ float *optr, const float *optr_end,
+ const uchar *iptr, const uchar *iptr_end, int z)
{
- unsigned short pixel, count;
+ ushort pixel, count;
float pixel_f;
+#define EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next) \
+ if (UNLIKELY(iptr_next > iptr_end)) { goto fail; }
+
+#define EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL(optr_next) \
+ if (UNLIKELY(optr_next > optr_end)) { goto fail; }
+
optr += z;
+ optr_end += z;
while (1) {
+ const uchar *iptr_next = iptr + 2;
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
pixel = (iptr[0] << 8) | (iptr[1] << 0);
- iptr += 2;
-
+ iptr = iptr_next;
+
if (!(count = (pixel & 0x7f)) )
- return;
+ return false;
+ const float *optr_next = optr + count;
+ EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL(optr_next);
if (pixel & 0x80) {
+ iptr_next = iptr + (count * 2);
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
while (count >= 8) {
optr[0 * 4] = ((iptr[0] << 8) | (iptr[1] << 0)) / (float)0xFFFF;
optr[1 * 4] = ((iptr[2] << 8) | (iptr[3] << 0)) / (float)0xFFFF;
@@ -591,10 +650,13 @@ static void expandrow2(float *optr, const unsigned char *iptr, int z)
iptr += 2;
optr += 4;
}
+ BLI_assert(iptr == iptr_next);
}
else {
+ iptr_next = iptr + 2;
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
pixel_f = ((iptr[0] << 8) | (iptr[1] << 0)) / (float)0xFFFF;
- iptr += 2;
+ iptr = iptr_next;
while (count >= 8) {
optr[0 * 4] = pixel_f;
@@ -612,20 +674,45 @@ static void expandrow2(float *optr, const unsigned char *iptr, int z)
*optr = pixel_f;
optr += 4;
}
+ BLI_assert(iptr == iptr_next);
}
+ BLI_assert(optr == optr_next);
}
+ return false;
+
+#undef EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL
+#undef EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL
+fail:
+ return DIRTY_FLAG_ENCODING;
}
-static void expandrow(unsigned char *optr, const unsigned char *iptr, int z)
+static int expandrow(
+ uchar *optr, const uchar *optr_end,
+ const uchar *iptr, const uchar *iptr_end, int z)
{
- unsigned char pixel, count;
+ uchar pixel, count;
+
+#define EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next) \
+ if (UNLIKELY(iptr_next > iptr_end)) { goto fail; }
+
+#define EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL(optr_next) \
+ if (UNLIKELY(optr_next > optr_end)) { goto fail; }
optr += z;
+ optr_end += z;
while (1) {
- pixel = *iptr++;
+ const uchar *iptr_next = iptr + 1;
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
+ pixel = *iptr;
+ iptr = iptr_next;
if (!(count = (pixel & 0x7f)) )
- return;
+ return false;
+ const uchar *optr_next = optr + ((int)count * 4);
+ EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL(optr_next);
+
if (pixel & 0x80) {
+ iptr_next = iptr + count;
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
while (count >= 8) {
optr[0 * 4] = iptr[0];
optr[1 * 4] = iptr[1];
@@ -643,8 +730,11 @@ static void expandrow(unsigned char *optr, const unsigned char *iptr, int z)
*optr = *iptr++;
optr += 4;
}
+ BLI_assert(iptr == iptr_next);
}
else {
+ iptr_next = iptr + 1;
+ EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL(iptr_next);
pixel = *iptr++;
while (count >= 8) {
optr[0 * 4] = pixel;
@@ -662,8 +752,17 @@ static void expandrow(unsigned char *optr, const unsigned char *iptr, int z)
*optr = pixel;
optr += 4;
}
+ BLI_assert(iptr == iptr_next);
}
+ BLI_assert(optr == optr_next);
}
+
+ return false;
+
+#undef EXPAND_CAPACITY_AT_INPUT_OK_OR_FAIL
+#undef EXPAND_CAPACITY_AT_OUTPUT_OK_OR_FAIL
+fail:
+ return DIRTY_FLAG_ENCODING;
}
/*
@@ -679,14 +778,14 @@ static void expandrow(unsigned char *optr, const unsigned char *iptr, int z)
* Added: zbuf write
*/
-static int output_iris(unsigned int *lptr, int xsize, int ysize, int zsize, const char *name, int *zptr)
+static int output_iris(uint *lptr, int xsize, int ysize, int zsize, const char *name, int *zptr)
{
FILE *outf;
IMAGE *image;
int tablen, y, z, pos, len = 0;
- unsigned int *starttab, *lengthtab;
- unsigned char *rlebuf;
- unsigned int *lumbuf;
+ uint *starttab, *lengthtab;
+ uchar *rlebuf;
+ uint *lumbuf;
int rlebuflen, goodwrite;
goodwrite = 1;
@@ -696,14 +795,14 @@ static int output_iris(unsigned int *lptr, int xsize, int ysize, int zsize, cons
tablen = ysize * zsize * sizeof(int);
image = (IMAGE *)MEM_mallocN(sizeof(IMAGE), "iris image");
- starttab = (unsigned int *)MEM_mallocN(tablen, "iris starttab");
- lengthtab = (unsigned int *)MEM_mallocN(tablen, "iris lengthtab");
+ starttab = (uint *)MEM_mallocN(tablen, "iris starttab");
+ lengthtab = (uint *)MEM_mallocN(tablen, "iris lengthtab");
rlebuflen = 1.05 * xsize + 10;
- rlebuf = (unsigned char *)MEM_mallocN(rlebuflen, "iris rlebuf");
- lumbuf = (unsigned int *)MEM_mallocN(xsize * sizeof(int), "iris lumbuf");
+ rlebuf = (uchar *)MEM_mallocN(rlebuflen, "iris rlebuf");
+ lumbuf = (uint *)MEM_mallocN(xsize * sizeof(int), "iris lumbuf");
memset(image, 0, sizeof(IMAGE));
- image->imagic = IMB_FTYPE_IMAGIC;
+ image->imagic = IMAGIC;
image->type = RLE(1);
if (zsize > 1)
image->dim = 3;
@@ -765,7 +864,7 @@ static int output_iris(unsigned int *lptr, int xsize, int ysize, int zsize, cons
/* static utility functions for output_iris */
-static void lumrow(unsigned char *rgbptr, unsigned char *lumptr, int n)
+static void lumrow(uchar *rgbptr, uchar *lumptr, int n)
{
lumptr += CHANOFFSET(0);
while (n--) {
@@ -775,9 +874,9 @@ static void lumrow(unsigned char *rgbptr, unsigned char *lumptr, int n)
}
}
-static int compressrow(unsigned char *lbuf, unsigned char *rlebuf, int z, int cnt)
+static int compressrow(uchar *lbuf, uchar *rlebuf, int z, int cnt)
{
- unsigned char *iptr, *ibufend, *sptr, *optr;
+ uchar *iptr, *ibufend, *sptr, *optr;
short todo, cc;
int count;
@@ -830,7 +929,7 @@ static int compressrow(unsigned char *lbuf, unsigned char *rlebuf, int z, int cn
}
}
*optr++ = 0;
- return optr - (unsigned char *)rlebuf;
+ return optr - (uchar *)rlebuf;
}
int imb_saveiris(struct ImBuf *ibuf, const char *name, int flags)
diff --git a/source/blender/imbuf/intern/jp2.c b/source/blender/imbuf/intern/jp2.c
index 390f2502ee7..30a0fdf4e55 100644
--- a/source/blender/imbuf/intern/jp2.c
+++ b/source/blender/imbuf/intern/jp2.c
@@ -119,7 +119,7 @@ static void info_callback(const char *msg, void *client_data)
# define PIXEL_LOOPER_END \
} \
- } (void)0 \
+} (void)0 \
struct ImBuf *imb_jp2_decode(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
{
@@ -588,7 +588,7 @@ static opj_image_t *ibuftoimage(ImBuf *ibuf, opj_cparameters_t *parameters)
img_fol_t img_fol; /* only needed for cinema presets */
memset(&img_fol, 0, sizeof(img_fol_t));
- if (ibuf->float_colorspace) {
+ if (ibuf->float_colorspace || (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA)) {
/* float buffer was managed already, no need in color space conversion */
chanel_colormanage_cb = channel_colormanage_noop;
}
diff --git a/source/blender/imbuf/intern/jpeg.c b/source/blender/imbuf/intern/jpeg.c
index 35c7b6363a1..ef9217fbc8c 100644
--- a/source/blender/imbuf/intern/jpeg.c
+++ b/source/blender/imbuf/intern/jpeg.c
@@ -382,7 +382,8 @@ static ImBuf *ibJpegImageFromCinfo(struct jpeg_decompress_struct *cinfo, int fla
* the information when we write
* it back to disk.
*/
- IMB_metadata_add_field(ibuf, "None", str);
+ IMB_metadata_ensure(&ibuf->metadata);
+ IMB_metadata_set_field(ibuf->metadata, "None", str);
ibuf->flags |= IB_metadata;
MEM_freeN(str);
goto next_stamp_marker;
@@ -408,7 +409,8 @@ static ImBuf *ibJpegImageFromCinfo(struct jpeg_decompress_struct *cinfo, int fla
*value = '\0'; /* need finish the key string */
value++;
- IMB_metadata_add_field(ibuf, key, value);
+ IMB_metadata_ensure(&ibuf->metadata);
+ IMB_metadata_set_field(ibuf->metadata, key, value);
ibuf->flags |= IB_metadata;
MEM_freeN(str);
next_stamp_marker:
diff --git a/source/blender/imbuf/intern/metadata.c b/source/blender/imbuf/intern/metadata.c
index 134bbe88f15..ef103f7afcf 100644
--- a/source/blender/imbuf/intern/metadata.c
+++ b/source/blender/imbuf/intern/metadata.c
@@ -45,95 +45,69 @@
#include "IMB_metadata.h"
+#define METADATA_MAX_VALUE_LENGTH 1024
-void IMB_metadata_free(struct ImBuf *img)
+void IMB_metadata_ensure(struct IDProperty **metadata)
{
- if (!img)
+ if (*metadata != NULL) {
return;
- if (!img->metadata) {
+ }
+
+ IDPropertyTemplate val;
+ *metadata = IDP_New(IDP_GROUP, &val, "metadata");
+}
+
+void IMB_metadata_free(struct IDProperty *metadata)
+{
+ if (metadata == NULL) {
return;
}
- IDP_FreeProperty(img->metadata);
- MEM_freeN(img->metadata);
+ IDP_FreeProperty(metadata);
+ MEM_freeN(metadata);
}
-bool IMB_metadata_get_field(struct ImBuf *img, const char *key, char *field, const size_t len)
+bool IMB_metadata_get_field(struct IDProperty *metadata, const char *key, char *field, const size_t len)
{
IDProperty *prop;
- bool retval = false;
-
- if (!img)
- return false;
- if (!img->metadata)
+ if (metadata == NULL) {
return false;
+ }
- prop = IDP_GetPropertyFromGroup(img->metadata, key);
+ prop = IDP_GetPropertyFromGroup(metadata, key);
if (prop && prop->type == IDP_STRING) {
BLI_strncpy(field, IDP_String(prop), len);
- retval = true;
+ return true;
}
- return retval;
+ return false;
}
void IMB_metadata_copy(struct ImBuf *dimb, struct ImBuf *simb)
{
+ BLI_assert(dimb != simb);
if (simb->metadata) {
+ IMB_metadata_free(dimb->metadata);
dimb->metadata = IDP_CopyProperty(simb->metadata);
}
}
-bool IMB_metadata_add_field(struct ImBuf *img, const char *key, const char *value)
+void IMB_metadata_set_field(struct IDProperty *metadata, const char *key, const char *value)
{
- IDProperty *prop;
-
- if (!img)
- return false;
+ BLI_assert(metadata);
+ IDProperty *prop = IDP_GetPropertyFromGroup(metadata, key);
- if (!img->metadata) {
- IDPropertyTemplate val;
- img->metadata = IDP_New(IDP_GROUP, &val, "metadata");
+ if (prop != NULL && prop->type != IDP_STRING) {
+ IDP_FreeFromGroup(metadata, prop);
+ prop = NULL;
}
- prop = IDP_NewString(value, key, 512);
- return IDP_AddToGroup(img->metadata, prop);
-}
-
-bool IMB_metadata_del_field(struct ImBuf *img, const char *key)
-{
- IDProperty *prop;
-
- if ((!img) || (!img->metadata))
- return false;
-
- prop = IDP_GetPropertyFromGroup(img->metadata, key);
-
- if (prop) {
- IDP_FreeFromGroup(img->metadata, prop);
+ if (prop == NULL) {
+ prop = IDP_NewString(value, key, METADATA_MAX_VALUE_LENGTH);
+ IDP_AddToGroup(metadata, prop);
}
- return false;
-}
-
-bool IMB_metadata_change_field(struct ImBuf *img, const char *key, const char *field)
-{
- IDProperty *prop;
- if (!img)
- return false;
-
- prop = (img->metadata) ? IDP_GetPropertyFromGroup(img->metadata, key) : NULL;
-
- if (!prop) {
- return (IMB_metadata_add_field(img, key, field));
- }
- else if (prop->type == IDP_STRING) {
- IDP_AssignString(prop, field, 1024);
- return true;
- }
- else {
- return false;
- }
+ IDP_AssignString(prop, value, METADATA_MAX_VALUE_LENGTH);
}
diff --git a/source/blender/imbuf/intern/moviecache.c b/source/blender/imbuf/intern/moviecache.c
index 4b49076dcd6..daf062f5499 100644
--- a/source/blender/imbuf/intern/moviecache.c
+++ b/source/blender/imbuf/intern/moviecache.c
@@ -49,7 +49,7 @@
#include "IMB_imbuf.h"
#ifdef DEBUG_MESSAGES
-# if defined __GNUC__ || defined __sun
+# if defined __GNUC__
# define PRINT(format, args ...) printf(format, ##args)
# else
# define PRINT(format, ...) printf(__VA_ARGS__)
@@ -513,7 +513,7 @@ void IMB_moviecache_get_cache_segments(MovieCache *cache, int proxy, int render_
*points_r = cache->points;
}
else {
- int totframe = BLI_ghash_size(cache->hash);
+ int totframe = BLI_ghash_len(cache->hash);
int *frames = MEM_callocN(totframe * sizeof(int), "movieclip cache frames");
int a, totseg = 0;
GHashIterator gh_iter;
diff --git a/source/blender/imbuf/intern/oiio/openimageio_api.cpp b/source/blender/imbuf/intern/oiio/openimageio_api.cpp
index 11bf45418d6..b123d508f99 100644
--- a/source/blender/imbuf/intern/oiio/openimageio_api.cpp
+++ b/source/blender/imbuf/intern/oiio/openimageio_api.cpp
@@ -31,7 +31,7 @@
#include <set>
-#if defined(WIN32) && !defined(FREE_WINDOWS)
+#if defined(WIN32)
#include "utfconv.h"
#endif
@@ -213,7 +213,7 @@ struct ImBuf *imb_load_photoshop(const char *filename, int flags, char colorspac
in = ImageInput::create(filename);
if (!in) {
std::cerr << __func__ << ": ImageInput::create() failed:" << std::endl
- << OpenImageIO::geterror() << std::endl;
+ << OIIO_NAMESPACE::geterror() << std::endl;
return NULL;
}
diff --git a/source/blender/imbuf/intern/openexr/openexr_api.cpp b/source/blender/imbuf/intern/openexr/openexr_api.cpp
index 89e796fb7ee..ad04f1fb78d 100644
--- a/source/blender/imbuf/intern/openexr/openexr_api.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_api.cpp
@@ -69,7 +69,7 @@
#include <openexr_api.h>
-#if defined (WIN32) && !defined(FREE_WINDOWS)
+#if defined (WIN32)
#include "utfconv.h"
#endif
@@ -77,7 +77,7 @@ extern "C"
{
// The following prevents a linking error in debug mode for MSVC using the libs in CVS
-#if defined(WITH_OPENEXR) && defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && _MSC_VER < 1900
+#if defined(WITH_OPENEXR) && defined(_WIN32) && defined(DEBUG) && _MSC_VER < 1900
_CRTIMP void __cdecl _invalid_parameter_noinfo(void)
{
}
@@ -180,7 +180,7 @@ public:
: IStream(filename)
{
/* utf-8 file path support on windows */
-#if defined (WIN32) && !defined(FREE_WINDOWS)
+#if defined (WIN32)
wchar_t *wfilename = alloc_utf16_from_8(filename, 0);
ifs.open(wfilename, std::ios_base::binary);
free(wfilename);
@@ -243,7 +243,7 @@ public:
: OStream(filename)
{
/* utf-8 file path support on windows */
-#if defined (WIN32) && !defined(FREE_WINDOWS)
+#if defined (WIN32)
wchar_t *wfilename = alloc_utf16_from_8(filename, 0);
ofs.open(wfilename, std::ios_base::binary);
free(wfilename);
@@ -374,21 +374,13 @@ static void openexr_header_metadata_callback(void *data, const char *propname, c
static bool imb_save_openexr_half(
- ImBuf *ibuf, const char *name, const int flags, const int totviews,
- const char * (*getview)(void *base, int view_id),
- ImBuf *(*getbuffer)(void *base, const int view_id))
+ ImBuf *ibuf, const char *name, const int flags)
{
const int channels = ibuf->channels;
const bool is_alpha = (channels >= 4) && (ibuf->planes == 32);
const bool is_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; /* summarize */
const int width = ibuf->x;
const int height = ibuf->y;
- const bool is_multiview = (flags & IB_multiview) && ibuf->userdata;
-
- BLI_assert((!is_multiview) || (getview && getbuffer));
-
- std::vector <string> views;
- int view_id;
try
{
@@ -397,22 +389,14 @@ static bool imb_save_openexr_half(
openexr_header_compression(&header, ibuf->foptions.flag & OPENEXR_COMPRESS);
openexr_header_metadata(&header, ibuf);
- /* create views when possible */
- for (view_id = 0; view_id < totviews; view_id ++)
- views.push_back(is_multiview ? getview(ibuf->userdata, view_id) : "");
-
- if (is_multiview)
- addMultiView(header, views);
-
- for (view_id = 0; view_id < totviews; view_id ++) {
- header.channels().insert(insertViewName("R", views, view_id), Channel(HALF));
- header.channels().insert(insertViewName("G", views, view_id), Channel(HALF));
- header.channels().insert(insertViewName("B", views, view_id), Channel(HALF));
- if (is_alpha)
- header.channels().insert(insertViewName("A", views, view_id), Channel(HALF));
- if (is_zbuf) // z we do as float always
- header.channels().insert(insertViewName("Z", views, view_id), Channel(Imf::FLOAT));
- }
+ /* create channels */
+ header.channels().insert("R", Channel(HALF));
+ header.channels().insert("G", Channel(HALF));
+ header.channels().insert("B", Channel(HALF));
+ if (is_alpha)
+ header.channels().insert("A", Channel(HALF));
+ if (is_zbuf) // z we do as float always
+ header.channels().insert("Z", Channel(Imf::FLOAT));
FrameBuffer frameBuffer;
@@ -421,65 +405,51 @@ static bool imb_save_openexr_half(
OutputFile file(file_stream, header);
/* we store first everything in half array */
- std::vector<RGBAZ> pixels(height * width * totviews);
+ std::vector<RGBAZ> pixels(height * width);
+ RGBAZ *to = &pixels[0];
int xstride = sizeof(RGBAZ);
int ystride = xstride * width;
- for (view_id = 0; view_id < totviews; view_id ++) {
- ImBuf *view_ibuf = is_multiview ? getbuffer(ibuf->userdata, view_id) : ibuf;
- const size_t offset = view_id * width * height;
- RGBAZ *to = &pixels[offset];
-
- /* TODO (dfelinto)
- * In some cases we get NULL ibufs, it needs investigation, meanwhile prevent crash
- * Multiview Render + Image Editor + OpenEXR + Multi-View
- */
- if (view_ibuf == NULL) {
- throw std::runtime_error(std::string("Missing data to write to ") + name);
- }
-
- /* indicate used buffers */
- frameBuffer.insert(insertViewName("R", views, view_id), Slice(HALF, (char *) &pixels[offset].r, xstride, ystride));
- frameBuffer.insert(insertViewName("G", views, view_id), Slice(HALF, (char *) &pixels[offset].g, xstride, ystride));
- frameBuffer.insert(insertViewName("B", views, view_id), Slice(HALF, (char *) &pixels[offset].b, xstride, ystride));
- if (is_alpha)
- frameBuffer.insert(insertViewName("A", views, view_id), Slice(HALF, (char *) &pixels[offset].a, xstride, ystride));
- if (is_zbuf)
- frameBuffer.insert(insertViewName("Z", views, view_id), Slice(Imf::FLOAT, (char *)(view_ibuf->zbuf_float + (height - 1) * width),
- sizeof(float), sizeof(float) * -width));
- if (view_ibuf->rect_float) {
- float *from;
-
- for (int i = view_ibuf->y - 1; i >= 0; i--) {
- from = view_ibuf->rect_float + channels * i * width;
-
- for (int j = view_ibuf->x; j > 0; j--) {
- to->r = from[0];
- to->g = (channels >= 2) ? from[1] : from[0];
- to->b = (channels >= 3) ? from[2] : from[0];
- to->a = (channels >= 4) ? from[3] : 1.0f;
- to++; from += channels;
- }
+ /* indicate used buffers */
+ frameBuffer.insert("R", Slice(HALF, (char *) &to->r, xstride, ystride));
+ frameBuffer.insert("G", Slice(HALF, (char *) &to->g, xstride, ystride));
+ frameBuffer.insert("B", Slice(HALF, (char *) &to->b, xstride, ystride));
+ if (is_alpha) {
+ frameBuffer.insert("A", Slice(HALF, (char *) &to->a, xstride, ystride));
+ }
+ if (is_zbuf) {
+ frameBuffer.insert("Z", Slice(Imf::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 + channels * i * width;
+
+ for (int j = ibuf->x; j > 0; j--) {
+ to->r = from[0];
+ to->g = (channels >= 2) ? from[1] : from[0];
+ to->b = (channels >= 3) ? from[2] : from[0];
+ to->a = (channels >= 4) ? from[3] : 1.0f;
+ to++; from += channels;
}
}
- else {
- unsigned char *from;
+ }
+ else {
+ unsigned char *from;
- for (int i = view_ibuf->y - 1; i >= 0; i--) {
- from = (unsigned char *)view_ibuf->rect + 4 * i * width;
+ for (int i = ibuf->y - 1; i >= 0; i--) {
+ from = (unsigned char *)ibuf->rect + 4 * i * width;
- for (int j = view_ibuf->x; j > 0; j--) {
- to->r = srgb_to_linearrgb((float)from[0] / 255.0f);
- to->g = srgb_to_linearrgb((float)from[1] / 255.0f);
- to->b = srgb_to_linearrgb((float)from[2] / 255.0f);
- to->a = channels >= 4 ? (float)from[3] / 255.0f : 1.0f;
- to++; from += 4;
- }
+ for (int j = ibuf->x; j > 0; j--) {
+ to->r = srgb_to_linearrgb((float)from[0] / 255.0f);
+ to->g = srgb_to_linearrgb((float)from[1] / 255.0f);
+ to->b = srgb_to_linearrgb((float)from[2] / 255.0f);
+ to->a = channels >= 4 ? (float)from[3] / 255.0f : 1.0f;
+ to++; from += 4;
}
}
-
- if (is_multiview)
- IMB_freeImBuf(view_ibuf);
}
exr_printf("OpenEXR-save: Writing OpenEXR file of height %d.\n", height);
@@ -498,21 +468,13 @@ static bool imb_save_openexr_half(
}
static bool imb_save_openexr_float(
- ImBuf *ibuf, const char *name, const int flags, const int totviews,
- const char * (*getview)(void *base, const int view_id),
- ImBuf *(*getbuffer)(void *base, const int view_id))
+ ImBuf *ibuf, const char *name, const int flags)
{
const int channels = ibuf->channels;
const bool is_alpha = (channels >= 4) && (ibuf->planes == 32);
const bool is_zbuf = (flags & IB_zbuffloat) && ibuf->zbuf_float != NULL; /* summarize */
const int width = ibuf->x;
const int height = ibuf->y;
- const bool is_multiview = (flags & IB_multiview) && ibuf->userdata;
-
- BLI_assert((!is_multiview) || (getview && getbuffer));
-
- std::vector <string> views;
- int view_id;
try
{
@@ -521,22 +483,14 @@ static bool imb_save_openexr_float(
openexr_header_compression(&header, ibuf->foptions.flag & OPENEXR_COMPRESS);
openexr_header_metadata(&header, ibuf);
- /* create views when possible */
- for (view_id = 0; view_id < totviews; view_id ++)
- views.push_back(is_multiview ? getview(ibuf->userdata, view_id) : "");
-
- if (is_multiview)
- addMultiView(header, views);
-
- for (view_id = 0; view_id < totviews; view_id ++) {
- header.channels().insert(insertViewName("R", views, view_id), Channel(Imf::FLOAT));
- header.channels().insert(insertViewName("G", views, view_id), Channel(Imf::FLOAT));
- header.channels().insert(insertViewName("B", views, view_id), Channel(Imf::FLOAT));
- if (is_alpha)
- header.channels().insert(insertViewName("A", views, view_id), Channel(Imf::FLOAT));
- if (is_zbuf)
- header.channels().insert(insertViewName("Z", views, view_id), Channel(Imf::FLOAT));
- }
+ /* create channels */
+ header.channels().insert("R", Channel(Imf::FLOAT));
+ header.channels().insert("G", Channel(Imf::FLOAT));
+ header.channels().insert("B", Channel(Imf::FLOAT));
+ if (is_alpha)
+ header.channels().insert("A", Channel(Imf::FLOAT));
+ if (is_zbuf)
+ header.channels().insert("Z", Channel(Imf::FLOAT));
FrameBuffer frameBuffer;
@@ -547,36 +501,24 @@ static bool imb_save_openexr_float(
int xstride = sizeof(float) * channels;
int ystride = -xstride * width;
- for (view_id = 0; view_id < totviews; view_id ++) {
- float *rect[4] = {NULL, NULL, NULL, NULL};
- ImBuf *view_ibuf = is_multiview ? getbuffer(ibuf->userdata, view_id) : ibuf;
-
- /* TODO (dfelinto)
- * In some cases we get NULL ibufs, it needs investigation, meanwhile prevent crash
- * Multiview Render + Image Editor + OpenEXR + Multi-View
- */
- if (view_ibuf == NULL) {
- throw std::runtime_error(std::string("Missing data to write to ") + name);
- }
-
- /* last scanline, stride negative */
- rect[0] = view_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]; /* red as alpha, is this needed since alpha isn't written? */
-
- frameBuffer.insert(insertViewName("R", views, view_id), Slice(Imf::FLOAT, (char *)rect[0], xstride, ystride));
- frameBuffer.insert(insertViewName("G", views, view_id), Slice(Imf::FLOAT, (char *)rect[1], xstride, ystride));
- frameBuffer.insert(insertViewName("B", views, view_id), Slice(Imf::FLOAT, (char *)rect[2], xstride, ystride));
- if (is_alpha)
- frameBuffer.insert(insertViewName("A", views, view_id), Slice(Imf::FLOAT, (char *)rect[3], xstride, ystride));
- if (is_zbuf)
- frameBuffer.insert(insertViewName("Z", views, view_id), Slice(Imf::FLOAT, (char *) (view_ibuf->zbuf_float + (height - 1) * width),
- sizeof(float), sizeof(float) * -width));
-
- if (is_multiview)
- IMB_freeImBuf(view_ibuf);
+ /* last scanline, stride negative */
+ 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]; /* red as alpha, is this needed since alpha isn't written? */
+
+ frameBuffer.insert("R", Slice(Imf::FLOAT, (char *)rect[0], xstride, ystride));
+ frameBuffer.insert("G", Slice(Imf::FLOAT, (char *)rect[1], xstride, ystride));
+ frameBuffer.insert("B", Slice(Imf::FLOAT, (char *)rect[2], xstride, ystride));
+ if (is_alpha) {
+ frameBuffer.insert("A", Slice(Imf::FLOAT, (char *)rect[3], xstride, ystride));
+ }
+ if (is_zbuf) {
+ frameBuffer.insert("Z", Slice(Imf::FLOAT, (char *) (ibuf->zbuf_float + (height - 1) * width),
+ sizeof(float), sizeof(float) * -width));
}
+
file.setFrameBuffer(frameBuffer);
file.writePixels(height);
}
@@ -599,50 +541,16 @@ int imb_save_openexr(struct ImBuf *ibuf, const char *name, int flags)
}
if (ibuf->foptions.flag & OPENEXR_HALF)
- return (int) imb_save_openexr_half(ibuf, name, flags, 1, NULL, NULL);
- else {
- /* when no float rect, we save as half (16 bits is sufficient) */
- if (ibuf->rect_float == NULL)
- return (int) imb_save_openexr_half(ibuf, name, flags, 1, NULL, NULL);
- else
- return (int) imb_save_openexr_float(ibuf, name, flags, 1, NULL, NULL);
- }
-}
-
-static bool imb_save_openexr_multiview(
- ImBuf *ibuf, const char *name, const int flags, const int totviews,
- const char *(*getview)(void *base, const int view_id),
- ImBuf *(*getbuffer)(void *base, const int view_id))
-{
- if (flags & IB_mem) {
- printf("OpenEXR-save: Create multiview EXR in memory CURRENTLY NOT SUPPORTED !\n");
- imb_addencodedbufferImBuf(ibuf);
- ibuf->encodedsize = 0;
- return false;
- }
-
- if (ibuf->foptions.flag & OPENEXR_HALF)
- return imb_save_openexr_half(ibuf, name, flags, totviews, getview, getbuffer);
+ return (int) imb_save_openexr_half(ibuf, name, flags);
else {
/* when no float rect, we save as half (16 bits is sufficient) */
if (ibuf->rect_float == NULL)
- return imb_save_openexr_half(ibuf, name, flags, totviews, getview, getbuffer);
+ return (int) imb_save_openexr_half(ibuf, name, flags);
else
- return imb_save_openexr_float(ibuf, name, flags, totviews, getview, getbuffer);
+ return (int) imb_save_openexr_float(ibuf, name, flags);
}
}
-/* Save single-layer multiview OpenEXR
- * If we have more multiview formats in the future, the function below could be incorporated
- * in our ImBuf write functions, meanwhile this is an OpenEXR special case only */
-bool IMB_exr_multiview_save(
- ImBuf *ibuf, const char *name, const int flags, const int totviews,
- const char *(*getview)(void *base, const int view_id),
- ImBuf *(*getbuffer)(void *base, const int view_id))
-{
- return imb_save_openexr_multiview(ibuf, name, flags, totviews, getview, getbuffer);
-}
-
/* ********************* Nicer API, MultiLayer and with Tile file support ************************************ */
/* naming rules:
@@ -841,7 +749,7 @@ void IMB_exr_add_channel(void *handle,
if (layname && layname[0] != '\0') {
imb_exr_insert_view_name(echan->name, echan->m->name.c_str(), echan->m->view.c_str());
}
- else if (data->multiView->size() > 1) {
+ else if (data->multiView->size() >= 1) {
std::string raw_name = insertViewName(echan->m->name, *data->multiView, echan->view_id);
BLI_strncpy(echan->name, raw_name.c_str(), sizeof(echan->name));
}
@@ -1026,15 +934,16 @@ void IMB_exr_set_channel(void *handle, const char *layname, const char *passname
ExrChannel *echan;
char name[EXR_TOT_MAXNAME + 1];
- if (layname) {
+ if (layname && layname[0] != '\0') {
char lay[EXR_LAY_MAXNAME + 1], pass[EXR_PASS_MAXNAME + 1];
BLI_strncpy(lay, layname, EXR_LAY_MAXNAME);
BLI_strncpy(pass, passname, EXR_PASS_MAXNAME);
BLI_snprintf(name, sizeof(name), "%s.%s", lay, pass);
}
- else
+ else {
BLI_strncpy(name, passname, EXR_TOT_MAXNAME - 1);
+ }
echan = (ExrChannel *)BLI_findstring(&data->channels, name, offsetof(ExrChannel, name));
@@ -1043,8 +952,9 @@ void IMB_exr_set_channel(void *handle, const char *layname, const char *passname
echan->ystride = ystride;
echan->rect = rect;
}
- else
+ else {
printf("IMB_exr_set_channel error %s\n", name);
+ }
}
float *IMB_exr_channel_rect(void *handle, const char *layname, const char *passname, const char *viewname)
@@ -1069,7 +979,7 @@ float *IMB_exr_channel_rect(void *handle, const char *layname, const char *pass
imb_exr_insert_view_name(temp_buf, name, viewname);
BLI_strncpy(name, temp_buf, sizeof(name));
}
- else if (data->multiView->size() > 1) {
+ else if (data->multiView->size() >= 1) {
const int view_id = std::max(0, imb_exr_get_multiView_id(*data->multiView, viewname));
std::string raw_name = insertViewName(name, *data->multiView, view_id);
BLI_strncpy(name, raw_name.c_str(), sizeof(name));
@@ -1102,7 +1012,7 @@ void IMB_exr_write_channels(void *handle)
if (data->channels.first) {
const size_t num_pixels = ((size_t)data->width) * data->height;
- half *rect_half = NULL, *current_rect_half;
+ half *rect_half = NULL, *current_rect_half = NULL;
/* We allocate teporary storage for half pixels for all the channels at once. */
if (data->num_half_channels != 0) {
@@ -1118,13 +1028,13 @@ void IMB_exr_write_channels(void *handle)
for (size_t i = 0; i < num_pixels; ++i, ++cur) {
*cur = rect[i * echan->xstride];
}
- half *rect_to_write = current_rect_half + (data->height - 1) * data->width;
+ half *rect_to_write = current_rect_half + (data->height - 1L) * data->width;
frameBuffer.insert(echan->name, Slice(Imf::HALF, (char *)rect_to_write,
sizeof(half), -data->width * sizeof(half)));
current_rect_half += num_pixels;
}
else {
- float *rect = echan->rect + echan->xstride * (data->height - 1) * data->width;
+ float *rect = echan->rect + echan->xstride * (data->height - 1L) * data->width;
frameBuffer.insert(echan->name, Slice(Imf::FLOAT, (char *)rect,
echan->xstride * sizeof(float), -echan->ystride * sizeof(float)));
}
@@ -1149,11 +1059,11 @@ void IMB_exr_write_channels(void *handle)
/* temporary function, used for FSA and Save Buffers */
/* called once per tile * view */
-void IMB_exrtile_write_channels(void *handle, int partx, int party, int level, const char *viewname)
+void IMB_exrtile_write_channels(void *handle, int partx, int party, int level, const char *viewname, bool empty)
{
+ /* Can write empty channels for incomplete renders. */
ExrHandle *data = (ExrHandle *)handle;
FrameBuffer frameBuffer;
- ExrChannel *echan;
std::string view(viewname);
const int view_id = imb_exr_get_multiView_id(*data->multiView, view);
@@ -1161,28 +1071,32 @@ void IMB_exrtile_write_channels(void *handle, int partx, int party, int level, c
exr_printf("%s %-6s %-22s \"%s\"\n", "p", "view", "name", "internal_name");
exr_printf("---------------------------------------------------------------------\n");
- for (echan = (ExrChannel *)data->channels.first; echan; echan = echan->next) {
+ if (!empty) {
+ ExrChannel *echan;
- /* eventually we can make the parts' channels to include
- only the current view TODO */
- if (strcmp(viewname, echan->m->view.c_str()) != 0)
- continue;
+ for (echan = (ExrChannel *)data->channels.first; echan; echan = echan->next) {
- exr_printf("%d %-6s %-22s \"%s\"\n",
- echan->m->part_number,
- echan->m->view.c_str(),
- echan->m->name.c_str(),
- echan->m->internal_name.c_str()
- );
+ /* eventually we can make the parts' channels to include
+ only the current view TODO */
+ if (strcmp(viewname, echan->m->view.c_str()) != 0)
+ continue;
- float *rect = echan->rect - echan->xstride * partx - echan->ystride * party;
- frameBuffer.insert(echan->m->internal_name,
- Slice(Imf::FLOAT,
- (char *)rect,
- echan->xstride * sizeof(float),
- echan->ystride * sizeof(float)
- )
- );
+ exr_printf("%d %-6s %-22s \"%s\"\n",
+ echan->m->part_number,
+ echan->m->view.c_str(),
+ echan->m->name.c_str(),
+ echan->m->internal_name.c_str()
+ );
+
+ float *rect = echan->rect - echan->xstride * partx - echan->ystride * party;
+ frameBuffer.insert(echan->m->internal_name,
+ Slice(Imf::FLOAT,
+ (char *)rect,
+ echan->xstride * sizeof(float),
+ echan->ystride * sizeof(float)
+ )
+ );
+ }
}
TiledOutputPart out (*data->mpofile, view_id);
@@ -1197,64 +1111,10 @@ void IMB_exrtile_write_channels(void *handle, int partx, int party, int level, c
}
}
-/* called only when handle has all views */
-void IMB_exrmultiview_write_channels(void *handle, const char *viewname)
-{
- ExrHandle *data = (ExrHandle *)handle;
- const int view_id = viewname ? imb_exr_get_multiView_id(*data->multiView, viewname) : -1;
- int numparts = (view_id == -1 ? data->parts : view_id + 1);
- std::vector <FrameBuffer> frameBuffers(numparts);
- std::vector <OutputPart> outputParts;
- ExrChannel *echan;
- int i, part;
-
- if (data->channels.first == NULL)
- return;
-
- exr_printf("\nIMB_exrmultiview_write_channels()\n");
-
- for (echan = (ExrChannel *)data->channels.first; echan; echan = echan->next) {
- if (view_id != -1 && echan->view_id != view_id)
- continue;
-
- part = (view_id == -1 ? echan->m->part_number : echan->view_id);
-
- /* last scanline, stride negative */
- float *rect = echan->rect + echan->xstride * (data->height - 1) * data->width;
- frameBuffers[part].insert(echan->m->internal_name,
- Slice(Imf::FLOAT,
- (char *)rect,
- echan->xstride * sizeof(float),
- -echan->ystride * sizeof(float))
- );
- }
-
- for (i = 0; i < numparts; i++) {
- OutputPart out(*data->mpofile, i);
- out.setFrameBuffer(frameBuffers[i]);
- outputParts.push_back(out);
- }
-
- try {
- for (i = 0; i < numparts; i++) {
- if (view_id != -1 && i != view_id)
- continue;
-
- outputParts[i].writePixels(data->height);
- }
- }
- catch (const std::exception& exc) {
- std::cerr << "OpenEXR-write Multi Part: ERROR: " << exc.what() << std::endl;
- }
-}
-
void IMB_exr_read_channels(void *handle)
{
ExrHandle *data = (ExrHandle *)handle;
- ExrChannel *echan;
int numparts = data->ifile->parts();
- std::vector<FrameBuffer> frameBuffers(numparts);
- std::vector<InputPart> inputParts;
/* check if exr was saved with previous versions of blender which flipped images */
const StringAttribute *ta = data->ifile->header(0).findTypedAttribute <StringAttribute> ("BlenderMultiChannel");
@@ -1262,37 +1122,56 @@ void IMB_exr_read_channels(void *handle)
exr_printf("\nIMB_exr_read_channels\n%s %-6s %-22s \"%s\"\n---------------------------------------------------------------------\n", "p", "view", "name", "internal_name");
- for (echan = (ExrChannel *)data->channels.first; echan; echan = echan->next) {
- exr_printf("%d %-6s %-22s \"%s\"\n", echan->m->part_number, echan->m->view.c_str(), echan->m->name.c_str(), echan->m->internal_name.c_str());
+ for (int i = 0; i < numparts; i++) {
+ /* Read part header. */
+ InputPart in(*data->ifile, i);
+ Header header = in.header();
+ Box2i dw = header.dataWindow();
- if (echan->rect) {
- if (flip)
- frameBuffers[echan->m->part_number].insert(echan->m->internal_name, Slice(Imf::FLOAT, (char *)echan->rect,
- echan->xstride * sizeof(float), echan->ystride * sizeof(float)));
+ /* Insert all matching channel into framebuffer. */
+ FrameBuffer frameBuffer;
+ ExrChannel *echan;
+
+ for (echan = (ExrChannel *)data->channels.first; echan; echan = echan->next) {
+ if (echan->m->part_number != i) {
+ continue;
+ }
+
+ exr_printf("%d %-6s %-22s \"%s\"\n", echan->m->part_number, echan->m->view.c_str(), echan->m->name.c_str(), echan->m->internal_name.c_str());
+
+ if (echan->rect) {
+ float *rect = echan->rect;
+ size_t xstride = echan->xstride * sizeof(float);
+ size_t ystride = echan->ystride * sizeof(float);
+
+ if (!flip) {
+ /* inverse correct first pixel for datawindow coordinates */
+ rect -= echan->xstride * (dw.min.x - dw.min.y * data->width);
+ /* move to last scanline to flip to Blender convention */
+ rect += echan->xstride * (data->height - 1) * data->width;
+ ystride = -ystride;
+ }
+ else {
+ /* inverse correct first pixel for datawindow coordinates */
+ rect -= echan->xstride * (dw.min.x + dw.min.y * data->width);
+ }
+
+ frameBuffer.insert(echan->m->internal_name, Slice(Imf::FLOAT, (char *)rect, xstride, ystride));
+ }
else
- frameBuffers[echan->m->part_number].insert(echan->m->internal_name, Slice(Imf::FLOAT, (char *)(echan->rect + echan->xstride * (data->height - 1) * data->width),
- echan->xstride * sizeof(float), -echan->ystride * sizeof(float)));
+ printf("warning, channel with no rect set %s\n", echan->m->internal_name.c_str());
}
- else
- printf("warning, channel with no rect set %s\n", echan->m->internal_name.c_str());
- }
-
- for (int i = 0; i < numparts; i++) {
- InputPart in (*data->ifile, i);
- in.setFrameBuffer(frameBuffers[i]);
- inputParts.push_back(in);
- }
- try {
- for (int i = 0; i < numparts; i++) {
- Header header = inputParts[i].header();
- exr_printf("readPixels:readPixels[%d]: min.y: %d, max.y: %d\n", i, header.dataWindow().min.y, header.dataWindow().max.y);
- inputParts[i].readPixels(header.dataWindow().min.y, header.dataWindow().max.y);
- inputParts[i].readPixels(0, data->height - 1);
+ /* Read pixels. */
+ try {
+ in.setFrameBuffer(frameBuffer);
+ exr_printf("readPixels:readPixels[%d]: min.y: %d, max.y: %d\n", i, dw.min.y, dw.max.y);
+ in.readPixels(dw.min.y, dw.max.y);
+ }
+ catch (const std::exception& exc) {
+ std::cerr << "OpenEXR-readPixels: ERROR: " << exc.what() << std::endl;
+ break;
}
- }
- catch (const std::exception& exc) {
- std::cerr << "OpenEXR-readPixels: ERROR: " << exc.what() << std::endl;
}
}
@@ -1334,69 +1213,6 @@ void IMB_exr_multilayer_convert(void *handle, void *base,
}
}
-void IMB_exr_multiview_convert(void *handle, void *base,
- void (*addview)(void *base, const char *str),
- void (*addbuffer)(void *base, const char *str, ImBuf *ibuf, const int frame),
- const int frame)
-{
- ExrHandle *data = (ExrHandle *)handle;
- MultiPartInputFile *file = data->ifile;
- ExrLayer *lay;
- ExrPass *pass;
- ImBuf *ibuf = NULL;
- const bool is_alpha = exr_has_alpha(*file);
- Box2i dw = file->header(0).dataWindow();
- const size_t width = dw.max.x - dw.min.x + 1;
- const size_t height = dw.max.y - dw.min.y + 1;
- const bool is_depth = exr_has_zbuffer(*file);
-
- /* add views to RenderResult */
- for (StringVector::const_iterator i = data->multiView->begin(); i != data->multiView->end(); ++i) {
- addview(base, (*i).c_str());
- }
-
- if (BLI_listbase_is_empty(&data->layers)) {
- printf("cannot convert multiviews, no views in handle\n");
- return;
- }
-
- /* there is one float/pass per layer (layer here is a view) */
- BLI_assert(BLI_listbase_count_ex(&data->layers, 2) == 1);
- lay = (ExrLayer *)data->layers.first;
- for (pass = (ExrPass *)lay->passes.first; pass; pass = pass->next) {
- if (STREQ(pass->chan_id, "RGB") || STREQ(pass->chan_id, "RGBA")) {
- ibuf = IMB_allocImBuf(width, height, is_alpha ? 32 : 24, IB_rectfloat);
-
- if (!ibuf) {
- printf("error creating multiview buffer\n");
- return;
- }
-
- IMB_buffer_float_from_float(
- ibuf->rect_float, pass->rect, pass->totchan,
- IB_PROFILE_LINEAR_RGB, IB_PROFILE_LINEAR_RGB, false,
- ibuf->x, ibuf->y, ibuf->x, ibuf->x);
-
- if (hasXDensity(file->header(0))) {
- ibuf->ppm[0] = xDensity(file->header(0)) * 39.3700787f;
- ibuf->ppm[1] = ibuf->ppm[0] * (double)file->header(0).pixelAspectRatio();
- }
-
- if (is_depth) {
- ExrPass *zpass;
- for (zpass = (ExrPass *)lay->passes.first; zpass; zpass = zpass->next) {
- if (STREQ(zpass->chan_id, "Z") && STREQ(zpass->view, pass->view)) {
- addzbuffloatImBuf(ibuf);
- memcpy(ibuf->zbuf_float, zpass->rect, sizeof(float) * ibuf->x * ibuf->y);
- }
- }
- }
-
- addbuffer(base, pass->view, ibuf, frame);
- }
- }
-}
-
void IMB_exr_close(void *handle)
{
ExrHandle *data = (ExrHandle *)handle;
@@ -1474,7 +1290,7 @@ static int imb_exr_split_channel_name(ExrChannel *echan, char *layname, char *pa
return 1;
}
- /* last token is single character channel identifier */
+ /* last token is channel identifier */
len = imb_exr_split_token(name, end, &token);
if (len == 0) {
printf("multilayer read: bad channel name: %s\n", name);
@@ -1503,10 +1319,30 @@ static int imb_exr_split_channel_name(ExrChannel *echan, char *layname, char *pa
ok = true;
}
}
+ else if (BLI_strcaseeq(token, "red")) {
+ echan->chan_id = 'R';
+ ok = true;
+ }
+ else if (BLI_strcaseeq(token, "green")) {
+ echan->chan_id = 'G';
+ ok = true;
+ }
+ else if (BLI_strcaseeq(token, "blue")) {
+ echan->chan_id = 'B';
+ ok = true;
+ }
+ else if (BLI_strcaseeq(token, "alpha")) {
+ echan->chan_id = 'A';
+ ok = true;
+ }
+ else if (BLI_strcaseeq(token, "depth")) {
+ echan->chan_id = 'Z';
+ ok = true;
+ }
if (ok == false) {
BLI_strncpy(tokenbuf, token, std::min(len + 1, EXR_TOT_MAXNAME));
- printf("multilayer read: channel token too long: %s\n", tokenbuf);
+ printf("multilayer read: unknown channel token: %s\n", tokenbuf);
return 0;
}
}
@@ -1785,14 +1621,13 @@ static bool exr_has_alpha(MultiPartInputFile& file)
static bool imb_exr_is_multilayer_file(MultiPartInputFile& file)
{
- const StringAttribute *comments = file.header(0).findTypedAttribute<StringAttribute>("BlenderMultiChannel");
const ChannelList& channels = file.header(0).channels();
std::set <std::string> layerNames;
/* will not include empty layer names */
channels.layers(layerNames);
- if (comments || layerNames.size() > 1)
+ if (layerNames.size() > 1)
return true;
if (layerNames.size()) {
@@ -1831,7 +1666,7 @@ static void imb_exr_type_by_channels(ChannelList& channels, StringVector& views,
}
else {
*r_singlelayer = false;
- *r_multilayer = true;
+ *r_multilayer = (layerNames.size() > 1);
*r_multiview = false;
return;
}
@@ -1861,49 +1696,20 @@ static void imb_exr_type_by_channels(ChannelList& channels, StringVector& views,
else {
*r_singlelayer = true;
*r_multilayer = false;
- *r_multiview = false;
}
BLI_assert(r_singlelayer != r_multilayer);
}
-bool IMB_exr_has_singlelayer_multiview(void *handle)
-{
- ExrHandle *data = (ExrHandle *)handle;
- MultiPartInputFile *file = data->ifile;
- std::set <std::string> layerNames;
- const ChannelList& channels = file->header(0).channels();
- const StringAttribute *comments;
-
- if (exr_has_multiview(*file) == false)
- return false;
-
- comments = file->header(0).findTypedAttribute<StringAttribute>("BlenderMultiChannel");
-
- if (comments)
- return false;
-
- /* will not include empty layer names */
- channels.layers(layerNames);
-
- /* returns false if any layer differs from views list */
- if (layerNames.size())
- for (std::set<string>::iterator i = layerNames.begin(); i != layerNames.end(); i++)
- if (imb_exr_get_multiView_id(*data->multiView, *i) == -1)
- return false;
-
- return true;
-}
-
-bool IMB_exr_has_multilayer(void *handle)
-{
- ExrHandle *data = (ExrHandle *)handle;
- return imb_exr_is_multilayer_file(*data->ifile);
-}
-
static bool exr_has_multiview(MultiPartInputFile& file)
{
- return hasMultiView(file.header(0));
+ for (int p = 0; p < file.parts(); p++) {
+ if (hasMultiView(file.header(p))) {
+ return true;
+ }
+ }
+
+ return false;
}
static bool exr_has_multipart_file(MultiPartInputFile& file)
@@ -1927,6 +1733,12 @@ static bool imb_exr_is_multi(MultiPartInputFile& file)
return false;
}
+bool IMB_exr_has_multilayer(void *handle)
+{
+ ExrHandle *data = (ExrHandle *)handle;
+ return imb_exr_is_multi(*data->ifile);
+}
+
struct ImBuf *imb_load_openexr(const unsigned char *mem, size_t size, int flags, char colorspace[IM_MAX_SPACE])
{
struct ImBuf *ibuf = NULL;
@@ -1978,12 +1790,13 @@ struct ImBuf *imb_load_openexr(const unsigned char *mem, size_t size, int flags,
const Header & header = file->header(0);
Header::ConstIterator iter;
+ IMB_metadata_ensure(&ibuf->metadata);
for (iter = header.begin(); iter != header.end(); iter++) {
const StringAttribute *attrib = file->header(0).findTypedAttribute <StringAttribute> (iter.name());
/* not all attributes are string attributes so we might get some NULLs here */
if (attrib) {
- IMB_metadata_add_field(ibuf, iter.name(), attrib->value().c_str());
+ IMB_metadata_set_field(ibuf->metadata, iter.name(), attrib->value().c_str());
ibuf->flags |= IB_metadata;
}
}
diff --git a/source/blender/imbuf/intern/openexr/openexr_multi.h b/source/blender/imbuf/intern/openexr/openexr_multi.h
index 0fa0f64bdce..d9338c888a7 100644
--- a/source/blender/imbuf/intern/openexr/openexr_multi.h
+++ b/source/blender/imbuf/intern/openexr/openexr_multi.h
@@ -67,8 +67,7 @@ float *IMB_exr_channel_rect(void *handle, const char *layname, const char *pass
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, int level, const char *viewname);
-void IMB_exrmultiview_write_channels(void *handle, const char *viewname);
+void IMB_exrtile_write_channels(void *handle, int partx, int party, int level, const char *viewname, bool empty);
void IMB_exr_clear_channels(void *handle);
void IMB_exr_multilayer_convert(
@@ -78,23 +77,11 @@ void IMB_exr_multilayer_convert(
void (*addpass)(void *base, void *lay, const char *str, float *rect, int totchan,
const char *chan_id, const char *view));
-void IMB_exr_multiview_convert(
- void *handle, void *base,
- void (*addview)(void *base, const char *str),
- void (*addbuffer)(void *base, const char *str, struct ImBuf *ibuf, const int frame),
- const int frame);
-
-bool IMB_exr_multiview_save(
- struct ImBuf *ibuf, const char *name, const int flags, const int totviews,
- const char *(*getview)(void *base, int view_id),
- struct ImBuf *(*getbuffer)(void *base, const int view_id));
-
void IMB_exr_close(void *handle);
void IMB_exr_add_view(void *handle, const char *name);
bool IMB_exr_has_multilayer(void *handle);
-bool IMB_exr_has_singlelayer_multiview(void *handle);
#ifdef __cplusplus
} // extern "C"
diff --git a/source/blender/imbuf/intern/openexr/openexr_stub.cpp b/source/blender/imbuf/intern/openexr/openexr_stub.cpp
index 498e246a915..301e827d739 100644
--- a/source/blender/imbuf/intern/openexr/openexr_stub.cpp
+++ b/source/blender/imbuf/intern/openexr/openexr_stub.cpp
@@ -47,8 +47,7 @@ float *IMB_exr_channel_rect (void * /*handle*/, const char * /*layname*/
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*/, int /*level*/, const char * /*viewname*/) { }
-void IMB_exrmultiview_write_channels(void * /*handle*/, const char * /*viewname*/) { }
+void IMB_exrtile_write_channels (void * /*handle*/, int /*partx*/, int /*party*/, int /*level*/, const char * /*viewname*/, bool /*empty*/) { }
void IMB_exr_clear_channels (void * /*handle*/) { }
void IMB_exr_multilayer_convert(
@@ -60,24 +59,7 @@ void IMB_exr_multilayer_convert(
{
}
-void IMB_exr_multiview_convert(
- void * /*handle*/, void * /*base*/,
- void (* /*addview*/)(void *base, const char *str),
- void (* /*addbuffer*/)(void *base, const char *str, struct ImBuf *ibuf, const int frame),
- const int /*frame*/)
-{
-}
-
-bool IMB_exr_multiview_save(
- struct ImBuf * /*ibuf*/, const char * /*name*/, const int /*flags*/, const int /*totviews*/,
- const char *(* /*getview*/)(void *base, const int view_id),
- struct ImBuf *(* /*getbuffer*/)(void *base, const int view_id))
-{
- return false;
-}
-
void IMB_exr_close (void * /*handle*/) { }
void IMB_exr_add_view(void * /*handle*/, const char * /*name*/) { }
bool IMB_exr_has_multilayer(void * /*handle*/) { return false; }
-bool IMB_exr_has_singlelayer_multiview(void * /*handle*/) { return false; }
diff --git a/source/blender/imbuf/intern/png.c b/source/blender/imbuf/intern/png.c
index 5192e3f2d26..29fbe79d8db 100644
--- a/source/blender/imbuf/intern/png.c
+++ b/source/blender/imbuf/intern/png.c
@@ -152,7 +152,7 @@ int imb_savepng(struct ImBuf *ibuf, const char *name, int flags)
compression = (int)(((float)(ibuf->foptions.quality) / 11.1111f));
compression = compression < 0 ? 0 : (compression > 9 ? 9 : compression);
- if (ibuf->float_colorspace) {
+ if (ibuf->float_colorspace || (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA)) {
/* float buffer was managed already, no need in color space conversion */
chanel_colormanage_cb = channel_colormanage_noop;
}
@@ -526,7 +526,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
unsigned char *from, *to;
unsigned short *from16;
float *to_float;
- int i, bytesperpixel;
+ unsigned int channels;
if (imb_is_a_png(mem) == 0) return(NULL);
@@ -571,7 +571,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth,
&color_type, NULL, NULL, NULL);
- bytesperpixel = png_get_channels(png_ptr, info_ptr);
+ channels = png_get_channels(png_ptr, info_ptr);
switch (color_type) {
case PNG_COLOR_TYPE_RGB:
@@ -580,10 +580,10 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
case PNG_COLOR_TYPE_PALETTE:
png_set_palette_to_rgb(png_ptr);
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
- bytesperpixel = 4;
+ channels = 4;
}
else {
- bytesperpixel = 3;
+ channels = 3;
}
break;
case PNG_COLOR_TYPE_GRAY:
@@ -593,7 +593,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
bit_depth = 8;
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) {
/* PNG_COLOR_TYPE_GRAY may also have alpha 'values', like with palette. */
- bytesperpixel = 2;
+ channels = 2;
}
}
break;
@@ -602,7 +602,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
longjmp(png_jmpbuf(png_ptr), 1);
}
- ibuf = IMB_allocImBuf(width, height, 8 * bytesperpixel, 0);
+ ibuf = IMB_allocImBuf(width, height, 8 * channels, 0);
if (ibuf) {
ibuf->ftype = IMB_FTYPE_PNG;
@@ -613,11 +613,12 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
int unit_type;
png_uint_32 xres, yres;
- if (png_get_pHYs(png_ptr, info_ptr, &xres, &yres, &unit_type))
+ if (png_get_pHYs(png_ptr, info_ptr, &xres, &yres, &unit_type)) {
if (unit_type == PNG_RESOLUTION_METER) {
ibuf->ppm[0] = xres;
ibuf->ppm[1] = yres;
}
+ }
}
}
else {
@@ -629,23 +630,23 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
imb_addrectfloatImBuf(ibuf);
png_set_swap(png_ptr);
- pixels16 = MEM_mallocN(ibuf->x * ibuf->y * bytesperpixel * sizeof(png_uint_16), "pixels");
- if (pixels16 == NULL) {
+ pixels16 = imb_alloc_pixels(ibuf->x, ibuf->y, channels, sizeof(png_uint_16), "pixels");
+ if (pixels16 == NULL || ibuf->rect_float == NULL) {
printf("Cannot allocate pixels array\n");
longjmp(png_jmpbuf(png_ptr), 1);
}
/* allocate memory for an array of row-pointers */
- row_pointers = (png_bytepp) MEM_mallocN(ibuf->y * sizeof(png_uint_16p), "row_pointers");
+ row_pointers = (png_bytepp) MEM_mallocN((size_t)ibuf->y * sizeof(png_uint_16p), "row_pointers");
if (row_pointers == NULL) {
printf("Cannot allocate row-pointers array\n");
longjmp(png_jmpbuf(png_ptr), 1);
}
/* set the individual row-pointers to point at the correct offsets */
- for (i = 0; i < ibuf->y; i++) {
+ for (size_t i = 0; i < ibuf->y; i++) {
row_pointers[ibuf->y - 1 - i] = (png_bytep)
- ((png_uint_16 *)pixels16 + (i * ibuf->x) * bytesperpixel);
+ ((png_uint_16 *)pixels16 + (i * ibuf->x) * channels);
}
png_read_image(png_ptr, row_pointers);
@@ -655,9 +656,9 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
to_float = ibuf->rect_float;
from16 = pixels16;
- switch (bytesperpixel) {
+ switch (channels) {
case 4:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = from16[0] / 65535.0;
to_float[1] = from16[1] / 65535.0;
to_float[2] = from16[2] / 65535.0;
@@ -666,7 +667,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
}
break;
case 3:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = from16[0] / 65535.0;
to_float[1] = from16[1] / 65535.0;
to_float[2] = from16[2] / 65535.0;
@@ -675,14 +676,14 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
}
break;
case 2:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0;
to_float[3] = from16[1] / 65535.0;
to_float += 4; from16 += 2;
}
break;
case 1:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to_float[0] = to_float[1] = to_float[2] = from16[0] / 65535.0;
to_float[3] = 1.0;
to_float += 4; from16++;
@@ -693,23 +694,23 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
else {
imb_addrectImBuf(ibuf);
- pixels = MEM_mallocN(((size_t)ibuf->x) * ibuf->y * bytesperpixel * sizeof(unsigned char), "pixels");
- if (pixels == NULL) {
+ pixels = imb_alloc_pixels(ibuf->x, ibuf->y, channels, sizeof(unsigned char), "pixels");
+ if (pixels == NULL || ibuf->rect == NULL) {
printf("Cannot allocate pixels array\n");
longjmp(png_jmpbuf(png_ptr), 1);
}
/* allocate memory for an array of row-pointers */
- row_pointers = (png_bytepp) MEM_mallocN(ibuf->y * sizeof(png_bytep), "row_pointers");
+ row_pointers = (png_bytepp) MEM_mallocN((size_t)ibuf->y * sizeof(png_bytep), "row_pointers");
if (row_pointers == NULL) {
printf("Cannot allocate row-pointers array\n");
longjmp(png_jmpbuf(png_ptr), 1);
}
/* set the individual row-pointers to point at the correct offsets */
- for (i = 0; i < ibuf->y; i++) {
+ for (int i = 0; i < ibuf->y; i++) {
row_pointers[ibuf->y - 1 - i] = (png_bytep)
- ((unsigned char *)pixels + (((size_t)i) * ibuf->x) * bytesperpixel * sizeof(unsigned char));
+ ((unsigned char *)pixels + (((size_t)i) * ibuf->x) * channels * sizeof(unsigned char));
}
png_read_image(png_ptr, row_pointers);
@@ -719,9 +720,9 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
to = (unsigned char *) ibuf->rect;
from = pixels;
- switch (bytesperpixel) {
+ switch (channels) {
case 4:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = from[0];
to[1] = from[1];
to[2] = from[2];
@@ -730,7 +731,7 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
}
break;
case 3:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = from[0];
to[1] = from[1];
to[2] = from[2];
@@ -739,14 +740,14 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
}
break;
case 2:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = to[1] = to[2] = from[0];
to[3] = from[1];
to += 4; from += 2;
}
break;
case 1:
- for (i = ibuf->x * ibuf->y; i > 0; i--) {
+ for (size_t i = (size_t)ibuf->x * (size_t)ibuf->y; i > 0; i--) {
to[0] = to[1] = to[2] = from[0];
to[3] = 0xff;
to += 4; from++;
@@ -758,8 +759,9 @@ ImBuf *imb_loadpng(const unsigned char *mem, size_t size, int flags, char colors
if (flags & IB_metadata) {
png_text *text_chunks;
int count = png_get_text(png_ptr, info_ptr, &text_chunks, NULL);
- for (i = 0; i < count; i++) {
- IMB_metadata_add_field(ibuf, text_chunks[i].key, text_chunks[i].text);
+ IMB_metadata_ensure(&ibuf->metadata);
+ for (int i = 0; i < count; i++) {
+ IMB_metadata_set_field(ibuf->metadata, text_chunks[i].key, text_chunks[i].text);
ibuf->flags |= IB_metadata;
}
}
diff --git a/source/blender/imbuf/intern/radiance_hdr.c b/source/blender/imbuf/intern/radiance_hdr.c
index 71e74928e20..8d822a314f5 100644
--- a/source/blender/imbuf/intern/radiance_hdr.c
+++ b/source/blender/imbuf/intern/radiance_hdr.c
@@ -71,7 +71,7 @@ typedef float fCOLOR[3];
/* read routines */
static const unsigned char *oldreadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof)
{
- int i, rshift = 0, len = xmax;
+ size_t i, rshift = 0, len = xmax;
while (len > 0) {
if (UNLIKELY(mem_eof - mem < 4)) {
return NULL;
@@ -99,8 +99,6 @@ static const unsigned char *oldreadcolrs(RGBE *scan, const unsigned char *mem, i
static const unsigned char *freadcolrs(RGBE *scan, const unsigned char *mem, int xmax, const unsigned char *mem_eof)
{
- int i, j, code, val;
-
if (UNLIKELY(mem_eof - mem < 4)) {
return NULL;
}
@@ -109,32 +107,32 @@ static const unsigned char *freadcolrs(RGBE *scan, const unsigned char *mem, int
return oldreadcolrs(scan, mem, xmax, mem_eof);
}
- i = *mem++;
- if (i != 2) {
+ int val = *mem++;
+ if (val != 2) {
return oldreadcolrs(scan, mem - 1, xmax, mem_eof);
}
scan[0][GRN] = *mem++;
scan[0][BLU] = *mem++;
- i = *mem++;
+ val = *mem++;
if (scan[0][GRN] != 2 || scan[0][BLU] & 128) {
scan[0][RED] = 2;
- scan[0][EXP] = i;
+ scan[0][EXP] = val;
return oldreadcolrs(scan + 1, mem, xmax - 1, mem_eof);
}
- if (UNLIKELY(((scan[0][BLU] << 8) | i) != xmax)) {
+ if (UNLIKELY(((scan[0][BLU] << 8) | val) != xmax)) {
return NULL;
}
- for (i = 0; i < 4; i++) {
+ for (size_t i = 0; i < 4; i++) {
if (UNLIKELY(mem_eof - mem < 2)) {
return NULL;
}
- for (j = 0; j < xmax; ) {
- code = *mem++;
+ for (size_t j = 0; j < xmax; ) {
+ int code = *mem++;
if (code > 128) {
code &= 127;
if (UNLIKELY(code + j > xmax)) {
@@ -215,7 +213,6 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
float *rect_float;
int found = 0;
int width = 0, height = 0;
- int x, y;
const unsigned char *ptr, *mem_eof = mem + size;
char oriY[80], oriX[80];
@@ -223,6 +220,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_FLOAT);
/* find empty line, next line is resolution info */
+ size_t x;
for (x = 1; x < size; x++) {
if ((mem[x - 1] == '\n') && (mem[x] == '\n')) {
found = 1;
@@ -259,7 +257,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
sline = (RGBE *)MEM_mallocN(sizeof(*sline) * width, __func__);
rect_float = ibuf->rect_float;
- for (y = 0; y < height; y++) {
+ for (size_t y = 0; y < height; y++) {
ptr = freadcolrs(sline, ptr, width, mem_eof);
if (ptr == NULL) {
printf("WARNING! HDR decode error, image may be just truncated, or completely wrong...\n");
@@ -293,7 +291,7 @@ struct ImBuf *imb_loadhdr(const unsigned char *mem, size_t size, int flags, char
/* ImBuf write */
static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufscan, float *fpscan)
{
- int x, i, j, beg, c2, cnt = 0;
+ int beg, c2, cnt = 0;
fCOLOR fcol;
RGBE rgbe, *rgbe_scan;
@@ -304,8 +302,7 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
rgbe_scan = (RGBE *)MEM_mallocN(sizeof(RGBE) * width, "radhdr_write_tmpscan");
/* convert scanline */
- j = 0;
- for (i = 0; i < width; i++) {
+ for (size_t i = 0, j = 0; i < width; i++) {
if (fpscan) {
fcol[RED] = fpscan[j];
fcol[GRN] = (channels >= 2) ? fpscan[j + 1] : fpscan[j];
@@ -322,7 +319,7 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
}
if ((width < MINELEN) | (width > MAXELEN)) { /* OOBs, write out flat */
- x = fwrite((char *)rgbe_scan, sizeof(RGBE), width, file) - width;
+ int x = fwrite((char *)rgbe_scan, sizeof(RGBE), width, file) - width;
MEM_freeN(rgbe_scan);
return x;
}
@@ -332,21 +329,22 @@ static int fwritecolrs(FILE *file, int width, int channels, unsigned char *ibufs
putc((unsigned char)(width >> 8), file);
putc((unsigned char)(width & 255), file);
/* put components separately */
- for (i = 0; i < 4; i++) {
- for (j = 0; j < width; j += cnt) { /* find next run */
+ for (size_t i = 0; i < 4; i++) {
+ for (size_t j = 0; j < width; j += cnt) { /* find next run */
for (beg = j; beg < width; beg += cnt) {
for (cnt = 1; (cnt < 127) && ((beg + cnt) < width) && (rgbe_scan[beg + cnt][i] == rgbe_scan[beg][i]); cnt++) ;
if (cnt >= MINRUN) break; /* long enough */
}
if (((beg - j) > 1) && ((beg - j) < MINRUN)) {
c2 = j + 1;
- while (rgbe_scan[c2++][i] == rgbe_scan[j][i])
+ while (rgbe_scan[c2++][i] == rgbe_scan[j][i]) {
if (c2 == beg) { /* short run */
putc((unsigned char)(128 + beg - j), file);
putc((unsigned char)(rgbe_scan[j][i]), file);
j = beg;
break;
}
+ }
}
while (j < beg) { /* write out non-run */
if ((c2 = beg - j) > 128) c2 = 128;
@@ -385,7 +383,7 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags)
{
FILE *file = BLI_fopen(name, "wb");
float *fp = NULL;
- int y, width = ibuf->x, height = ibuf->y;
+ size_t width = ibuf->x, height = ibuf->y;
unsigned char *cp = NULL;
(void)flags; /* unused */
@@ -401,7 +399,7 @@ int imb_savehdr(struct ImBuf *ibuf, const char *name, int flags)
if (ibuf->rect_float)
fp = ibuf->rect_float + ibuf->channels * (height - 1) * width;
- for (y = height - 1; y >= 0; y--) {
+ for (size_t y = 0; y < height; y++) {
if (fwritecolrs(file, width, ibuf->channels, cp, fp) < 0) {
fclose(file);
printf("HDR write error\n");
diff --git a/source/blender/imbuf/intern/rectop.c b/source/blender/imbuf/intern/rectop.c
index 3360fd7548e..c4325caac91 100644
--- a/source/blender/imbuf/intern/rectop.c
+++ b/source/blender/imbuf/intern/rectop.c
@@ -301,8 +301,8 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
int destx, int desty, int origx, int origy, int srcx, int srcy, int width, int height,
IMB_BlendMode mode, bool accumulate)
{
- unsigned int *drect = NULL, *orect, *srect = NULL, *dr, *or, *sr;
- float *drectf = NULL, *orectf, *srectf = NULL, *drf, *orf, *srf;
+ unsigned int *drect = NULL, *orect = NULL, *srect = NULL, *dr, *or, *sr;
+ float *drectf = NULL, *orectf = NULL, *srectf = NULL, *drf, *orf, *srf;
unsigned short *cmaskrect = curvemask, *cmr;
unsigned short *dmaskrect = dmask, *dmr;
unsigned short *texmaskrect = texmask, *tmr;
@@ -424,6 +424,7 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
else {
switch (mode) {
case IMB_BLEND_MIX:
+ case IMB_BLEND_INTERPOLATE:
func = blend_color_mix_byte;
func_float = blend_color_mix_float;
break;
@@ -563,9 +564,15 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
mask_src[0] = src[0];
mask_src[1] = src[1];
mask_src[2] = src[2];
- mask_src[3] = divide_round_i(src[3] * mask, 65535);
- func((unsigned char *)dr, (unsigned char *)or, mask_src);
+ if (mode == IMB_BLEND_INTERPOLATE) {
+ mask_src[3] = src[3];
+ blend_color_interpolate_byte((unsigned char *)dr, (unsigned char *)or, mask_src, mask / 65535.0f);
+ }
+ else {
+ mask_src[3] = divide_round_i(src[3] * mask, 65535);
+ func((unsigned char *)dr, (unsigned char *)or, mask_src);
+ }
}
}
}
@@ -588,9 +595,15 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
mask_src[0] = src[0];
mask_src[1] = src[1];
mask_src[2] = src[2];
- mask_src[3] = divide_round_i(src[3] * mask, 65535);
- func((unsigned char *)dr, (unsigned char *)or, mask_src);
+ if (mode == IMB_BLEND_INTERPOLATE) {
+ mask_src[3] = src[3];
+ blend_color_interpolate_byte((unsigned char *)dr, (unsigned char *)or, mask_src, mask / 65535.0f);
+ }
+ else {
+ mask_src[3] = divide_round_i(src[3] * mask, 65535);
+ func((unsigned char *)dr, (unsigned char *)or, mask_src);
+ }
}
}
}
@@ -642,12 +655,16 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
mask = min_ff(mask, 65535.0);
if (mask > *dmr) {
- float mask_srf[4];
-
*dmr = mask;
- mul_v4_v4fl(mask_srf, srf, mask / 65535.0f);
- func_float(drf, orf, mask_srf);
+ if (mode == IMB_BLEND_INTERPOLATE) {
+ blend_color_interpolate_float(drf, orf, srf, mask / 65535.0f);
+ }
+ else {
+ float mask_srf[4];
+ mul_v4_v4fl(mask_srf, srf, mask / 65535.0f);
+ func_float(drf, orf, mask_srf);
+ }
}
}
}
@@ -664,11 +681,15 @@ void IMB_rectblend(ImBuf *dbuf, ImBuf *obuf, ImBuf *sbuf, unsigned short *dmask,
mask = min_ff(mask, 65535.0);
if (srf[3] && (mask > 0.0f)) {
- float mask_srf[4];
-
- mul_v4_v4fl(mask_srf, srf, mask / 65535.0f);
+ if (mode == IMB_BLEND_INTERPOLATE) {
+ blend_color_interpolate_float(drf, orf, srf, mask / 65535.0f);
+ }
+ else {
+ float mask_srf[4];
+ mul_v4_v4fl(mask_srf, srf, mask / 65535.0f);
+ func_float(drf, orf, mask_srf);
+ }
- func_float(drf, orf, mask_srf);
}
}
}
diff --git a/source/blender/imbuf/intern/scaling.c b/source/blender/imbuf/intern/scaling.c
index 504b59b2b1d..ff92ce15811 100644
--- a/source/blender/imbuf/intern/scaling.c
+++ b/source/blender/imbuf/intern/scaling.c
@@ -1550,12 +1550,17 @@ static void scalefast_Z_ImBuf(ImBuf *ibuf, int newx, int newy)
}
}
-struct ImBuf *IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy)
+/**
+ * Return true if \a ibuf is modified.
+ */
+bool IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy)
{
- if (ibuf == NULL) return (NULL);
- if (ibuf->rect == NULL && ibuf->rect_float == NULL) return (ibuf);
+ if (ibuf == NULL) return false;
+ if (ibuf->rect == NULL && ibuf->rect_float == NULL) return false;
- if (newx == ibuf->x && newy == ibuf->y) { return ibuf; }
+ if (newx == ibuf->x && newy == ibuf->y) {
+ return false;
+ }
/* scaleup / scaledown functions below change ibuf->x and ibuf->y
* so we first scale the Z-buffer (if any) */
@@ -1564,7 +1569,7 @@ struct ImBuf *IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int
/* try to scale common cases in a fast way */
/* disabled, quality loss is unacceptable, see report #18609 (ton) */
if (0 && q_scale_linear_interpolation(ibuf, newx, newy)) {
- return ibuf;
+ return true;
}
if (newx && (newx < ibuf->x)) scaledownx(ibuf, newx);
@@ -1572,14 +1577,17 @@ struct ImBuf *IMB_scaleImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int
if (newx && (newx > ibuf->x)) scaleupx(ibuf, newx);
if (newy && (newy > ibuf->y)) scaleupy(ibuf, newy);
- return(ibuf);
+ return true;
}
struct imbufRGBA {
float r, g, b, a;
};
-struct ImBuf *IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy)
+/**
+ * Return true if \a ibuf is modified.
+ */
+bool IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned int newy)
{
unsigned int *rect, *_newrect, *newrect;
struct imbufRGBA *rectf, *_newrectf, *newrectf;
@@ -1590,16 +1598,16 @@ struct ImBuf *IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned
rect = NULL; _newrect = NULL; newrect = NULL;
rectf = NULL; _newrectf = NULL; newrectf = NULL;
- if (ibuf == NULL) return(NULL);
+ if (ibuf == NULL) return false;
if (ibuf->rect) do_rect = true;
if (ibuf->rect_float) do_float = true;
- if (do_rect == false && do_float == false) return(ibuf);
+ if (do_rect == false && do_float == false) return false;
- if (newx == ibuf->x && newy == ibuf->y) return(ibuf);
+ if (newx == ibuf->x && newy == ibuf->y) return false;
if (do_rect) {
_newrect = MEM_mallocN(newx * newy * sizeof(int), "scalefastimbuf");
- if (_newrect == NULL) return(ibuf);
+ if (_newrect == NULL) return false;
newrect = _newrect;
}
@@ -1607,7 +1615,7 @@ struct ImBuf *IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned
_newrectf = MEM_mallocN(newx * newy * sizeof(float) * 4, "scalefastimbuf f");
if (_newrectf == NULL) {
if (_newrect) MEM_freeN(_newrect);
- return(ibuf);
+ return false;
}
newrectf = _newrectf;
}
@@ -1643,18 +1651,18 @@ struct ImBuf *IMB_scalefastImBuf(struct ImBuf *ibuf, unsigned int newx, unsigned
ibuf->mall |= IB_rect;
ibuf->rect = _newrect;
}
-
+
if (do_float) {
imb_freerectfloatImBuf(ibuf);
ibuf->mall |= IB_rectfloat;
ibuf->rect_float = (float *)_newrectf;
}
-
+
scalefast_Z_ImBuf(ibuf, newx, newy);
-
+
ibuf->x = newx;
ibuf->y = newy;
- return(ibuf);
+ return true;
}
/* ******** threaded scaling ******** */
diff --git a/source/blender/imbuf/intern/thumbs.c b/source/blender/imbuf/intern/thumbs.c
index 3629332a4ac..2fa5b5a0170 100644
--- a/source/blender/imbuf/intern/thumbs.c
+++ b/source/blender/imbuf/intern/thumbs.c
@@ -430,16 +430,17 @@ static ImBuf *thumb_create_ex(
IMB_scaleImBuf(img, ex, ey);
}
BLI_snprintf(desc, sizeof(desc), "Thumbnail for %s", uri);
- IMB_metadata_change_field(img, "Description", desc);
- IMB_metadata_change_field(img, "Software", "Blender");
- IMB_metadata_change_field(img, "Thumb::URI", uri);
- IMB_metadata_change_field(img, "Thumb::MTime", mtime);
+ IMB_metadata_ensure(&img->metadata);
+ IMB_metadata_set_field(img->metadata, "Software", "Blender");
+ IMB_metadata_set_field(img->metadata, "Thumb::URI", uri);
+ IMB_metadata_set_field(img->metadata, "Description", desc);
+ IMB_metadata_set_field(img->metadata, "Thumb::MTime", mtime);
if (use_hash) {
- IMB_metadata_change_field(img, "X-Blender::Hash", hash);
+ IMB_metadata_set_field(img->metadata, "X-Blender::Hash", hash);
}
if (ELEM(source, THB_SOURCE_IMAGE, THB_SOURCE_BLEND, THB_SOURCE_FONT)) {
- IMB_metadata_change_field(img, "Thumb::Image::Width", cwidth);
- IMB_metadata_change_field(img, "Thumb::Image::Height", cheight);
+ IMB_metadata_set_field(img->metadata, "Thumb::Image::Width", cwidth);
+ IMB_metadata_set_field(img->metadata, "Thumb::Image::Height", cheight);
}
img->ftype = IMB_FTYPE_PNG;
img->planes = 32;
@@ -589,7 +590,7 @@ ImBuf *IMB_thumb_manage(const char *org_path, ThumbSize size, ThumbSource source
const bool use_hash = thumbhash_from_path(file_path, source, thumb_hash);
- if (IMB_metadata_get_field(img, "Thumb::MTime", mtime, sizeof(mtime))) {
+ if (IMB_metadata_get_field(img->metadata, "Thumb::MTime", mtime, sizeof(mtime))) {
regenerate = (st.st_mtime != atol(mtime));
}
else {
@@ -598,7 +599,7 @@ ImBuf *IMB_thumb_manage(const char *org_path, ThumbSize size, ThumbSource source
}
if (use_hash && !regenerate) {
- if (IMB_metadata_get_field(img, "X-Blender::Hash", thumb_hash_curr, sizeof(thumb_hash_curr))) {
+ if (IMB_metadata_get_field(img->metadata, "X-Blender::Hash", thumb_hash_curr, sizeof(thumb_hash_curr))) {
regenerate = !STREQ(thumb_hash, thumb_hash_curr);
}
else {
@@ -652,7 +653,7 @@ static struct IMBThumbLocks {
void IMB_thumb_locks_acquire(void)
{
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (thumb_locks.lock_counter == 0) {
BLI_assert(thumb_locks.locked_paths == NULL);
@@ -663,12 +664,12 @@ void IMB_thumb_locks_acquire(void)
BLI_assert(thumb_locks.locked_paths != NULL);
BLI_assert(thumb_locks.lock_counter > 0);
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
void IMB_thumb_locks_release(void)
{
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
BLI_assert((thumb_locks.locked_paths != NULL) && (thumb_locks.lock_counter > 0));
thumb_locks.lock_counter--;
@@ -678,14 +679,14 @@ void IMB_thumb_locks_release(void)
BLI_condition_end(&thumb_locks.cond);
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
void IMB_thumb_path_lock(const char *path)
{
void *key = BLI_strdup(path);
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
BLI_assert((thumb_locks.locked_paths != NULL) && (thumb_locks.lock_counter > 0));
if (thumb_locks.locked_paths) {
@@ -694,14 +695,14 @@ void IMB_thumb_path_lock(const char *path)
}
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
void IMB_thumb_path_unlock(const char *path)
{
const void *key = path;
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
BLI_assert((thumb_locks.locked_paths != NULL) && (thumb_locks.lock_counter > 0));
if (thumb_locks.locked_paths) {
@@ -711,5 +712,5 @@ void IMB_thumb_path_unlock(const char *path)
BLI_condition_notify_all(&thumb_locks.cond);
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
diff --git a/source/blender/imbuf/intern/thumbs_blend.c b/source/blender/imbuf/intern/thumbs_blend.c
index b5c6deb6b01..d04f5fc87e6 100644
--- a/source/blender/imbuf/intern/thumbs_blend.c
+++ b/source/blender/imbuf/intern/thumbs_blend.c
@@ -36,7 +36,6 @@
#include "BLO_blend_defs.h"
#include "BLO_readfile.h"
-#include "BKE_global.h"
#include "BKE_idcode.h"
#include "BKE_icons.h"
#include "BKE_library.h"
diff --git a/source/blender/imbuf/intern/tiff.c b/source/blender/imbuf/intern/tiff.c
index 4368a428186..afd28bb570b 100644
--- a/source/blender/imbuf/intern/tiff.c
+++ b/source/blender/imbuf/intern/tiff.c
@@ -376,7 +376,7 @@ static void imb_read_tiff_resolution(ImBuf *ibuf, TIFF *image)
*/
static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
{
- ImBuf *tmpibuf;
+ ImBuf *tmpibuf = NULL;
int success = 0;
short bitspersample, spp, config;
size_t scanline;
@@ -412,16 +412,25 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
if (bitspersample == 32) {
ib_flag = IB_rectfloat;
fbuf = (float *)_TIFFmalloc(scanline);
+ if (!fbuf) {
+ goto cleanup;
+ }
}
else if (bitspersample == 16) {
ib_flag = IB_rectfloat;
sbuf = (unsigned short *)_TIFFmalloc(scanline);
+ if (!sbuf) {
+ goto cleanup;
+ }
}
else {
ib_flag = IB_rect;
}
tmpibuf = IMB_allocImBuf(ibuf->x, ibuf->y, ibuf->planes, ib_flag);
+ if (!tmpibuf) {
+ goto cleanup;
+ }
/* simple RGBA image */
if (!(bitspersample == 32 || bitspersample == 16)) {
@@ -430,7 +439,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
/* contiguous channels: RGBRGBRGB */
else if (config == PLANARCONFIG_CONTIG) {
for (row = 0; row < ibuf->y; row++) {
- int ib_offset = ibuf->x * ibuf->y * 4 - ibuf->x * 4 * (row + 1);
+ size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1));
if (bitspersample == 32) {
success |= TIFFReadScanline(image, fbuf, row, 0);
@@ -450,7 +459,7 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
* but only fill in from the TIFF scanline where necessary. */
for (chan = 0; chan < 4; chan++) {
for (row = 0; row < ibuf->y; row++) {
- int ib_offset = ibuf->x * ibuf->y * 4 - ibuf->x * 4 * (row + 1);
+ size_t ib_offset = (size_t)ibuf->x * 4 * ((size_t)ibuf->y - ((size_t)row + 1));
if (bitspersample == 32) {
if (chan == 3 && spp == 3) /* fill alpha if only RGB TIFF */
@@ -475,11 +484,6 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
}
}
}
-
- if (bitspersample == 32)
- _TIFFfree(fbuf);
- else if (bitspersample == 16)
- _TIFFfree(sbuf);
if (success) {
/* Code seems to be not needed for 16 bits tif, on PPC G5 OSX (ton) */
@@ -498,6 +502,12 @@ static int imb_read_tiff_pixels(ImBuf *ibuf, TIFF *image)
tmpibuf->mall &= ~ib_flag;
}
+cleanup:
+ if (bitspersample == 32)
+ _TIFFfree(fbuf);
+ else if (bitspersample == 16)
+ _TIFFfree(sbuf);
+
IMB_freeImBuf(tmpibuf);
return success;
@@ -813,26 +823,51 @@ int imb_savetiff(ImBuf *ibuf, const char *name, int flags)
}
/* copy pixel data. While copying, we flip the image vertically. */
+ const int channels_in_float = ibuf->channels ? ibuf->channels : 4;
for (x = 0; x < ibuf->x; x++) {
for (y = 0; y < ibuf->y; y++) {
- from_i = 4 * (y * ibuf->x + x);
+ from_i = ((size_t)channels_in_float) * (y * ibuf->x + x);
to_i = samplesperpixel * ((ibuf->y - y - 1) * ibuf->x + x);
if (pixels16) {
/* convert from float source */
float rgb[4];
-
- if (ibuf->float_colorspace) {
- /* float buffer was managed already, no need in color space conversion */
- copy_v3_v3(rgb, &fromf[from_i]);
+
+ if (channels_in_float == 3 || channels_in_float == 4) {
+ if (ibuf->float_colorspace ||
+ (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA))
+ {
+ /* Float buffer was managed already, no need in color
+ * space conversion.
+ */
+ copy_v3_v3(rgb, &fromf[from_i]);
+ }
+ else {
+ /* Standard linear-to-srgb conversion if float buffer
+ * wasn't managed.
+ */
+ linearrgb_to_srgb_v3_v3(rgb, &fromf[from_i]);
+ }
+ if (channels_in_float == 4) {
+ rgb[3] = fromf[from_i + 3];
+ }
+ else {
+ rgb[3] = 1.0f;
+ }
}
else {
- /* standard linear-to-srgb conversion if float buffer wasn't managed */
- linearrgb_to_srgb_v3_v3(rgb, &fromf[from_i]);
+ if (ibuf->float_colorspace ||
+ (ibuf->colormanage_flag & IMB_COLORMANAGE_IS_DATA))
+ {
+ rgb[0] = fromf[from_i];
+ }
+ else {
+ rgb[0] = linearrgb_to_srgb(fromf[from_i]);
+ }
+ rgb[1] = rgb[2] = rgb[0];
+ rgb[3] = 1.0f;
}
- rgb[3] = fromf[from_i + 3];
-
for (i = 0; i < samplesperpixel; i++, to_i++)
to16[to_i] = FTOUSHORT(rgb[i]);
}
diff --git a/source/blender/imbuf/intern/util.c b/source/blender/imbuf/intern/util.c
index ba8480b636f..9dfe926ddff 100644
--- a/source/blender/imbuf/intern/util.c
+++ b/source/blender/imbuf/intern/util.c
@@ -43,8 +43,6 @@
#include "BLI_fileops.h"
#include "BLI_string.h"
-#include "BKE_global.h"
-
#include "imbuf.h"
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
@@ -52,11 +50,8 @@
#include "IMB_anim.h"
-#ifdef WITH_QUICKTIME
-#include "quicktime_import.h"
-#endif
-
#ifdef WITH_FFMPEG
+#include "BKE_global.h" /* G.debug */
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavdevice/avdevice.h>
@@ -107,28 +102,6 @@ const char *imb_ext_image_filepath_only[] = {
NULL
};
-const char *imb_ext_image_qt[] = {
- ".gif",
- ".psd",
- ".pct", ".pict",
- ".pntg",
- ".qtif",
- NULL
-};
-
-#if 0 /* UNUSED */
-const char *imb_ext_movie_qt[] = {
- ".avi",
- ".flc",
- ".dv",
- ".r3d",
- ".mov",
- ".movie",
- ".mv",
- NULL
-};
-#endif
-
const char *imb_ext_movie[] = {
".avi",
".flc",
@@ -247,13 +220,6 @@ static int isavi(const char *name)
#endif
}
-#ifdef WITH_QUICKTIME
-static int isqtime(const char *name)
-{
- return anim_is_quicktime(name);
-}
-#endif
-
#ifdef WITH_FFMPEG
/* BLI_vsnprintf in ffmpeg_log_callback() causes invalid warning */
@@ -383,9 +349,6 @@ int imb_get_anim_type(const char *name)
if (UTIL_DEBUG) printf("%s: %s\n", __func__, name);
#ifndef _WIN32
-# ifdef WITH_QUICKTIME
- if (isqtime(name)) return (ANIM_QTIME);
-# endif
# ifdef WITH_FFMPEG
/* stat test below fails on large files > 4GB */
if (isffmpeg(name)) return (ANIM_FFMPEG);
@@ -401,9 +364,6 @@ int imb_get_anim_type(const char *name)
if (((st.st_mode) & S_IFMT) != S_IFREG) return(0);
if (ismovie(name)) return (ANIM_MOVIE);
-# ifdef WITH_QUICKTIME
- if (isqtime(name)) return (ANIM_QTIME);
-# endif
# ifdef WITH_FFMPEG
if (isffmpeg(name)) return (ANIM_FFMPEG);
# endif
diff --git a/source/blender/imbuf/intern/writeimage.c b/source/blender/imbuf/intern/writeimage.c
index 84ec2534e7f..e340d082895 100644
--- a/source/blender/imbuf/intern/writeimage.c
+++ b/source/blender/imbuf/intern/writeimage.c
@@ -46,7 +46,7 @@
#include "IMB_colormanagement.h"
#include "IMB_colormanagement_intern.h"
-static ImBuf *prepare_write_imbuf(const ImFileType *type, ImBuf *ibuf)
+static bool prepare_write_imbuf(const ImFileType *type, ImBuf *ibuf)
{
return IMB_prepare_write_ImBuf((type->flag & IM_FTYPE_FLOAT), ibuf);
}
@@ -64,15 +64,11 @@ short IMB_saveiff(struct ImBuf *ibuf, const char *name, int flags)
for (type = IMB_FILE_TYPES; type < IMB_FILE_TYPES_LAST; type++) {
if (type->save && type->ftype(type, ibuf)) {
- ImBuf *write_ibuf;
short result = false;
- write_ibuf = prepare_write_imbuf(type, ibuf);
+ prepare_write_imbuf(type, ibuf);
- result = type->save(write_ibuf, name, flags);
-
- if (write_ibuf != ibuf)
- IMB_freeImBuf(write_ibuf);
+ result = type->save(ibuf, name, flags);
return result;
}
@@ -83,9 +79,9 @@ short IMB_saveiff(struct ImBuf *ibuf, const char *name, int flags)
return false;
}
-ImBuf *IMB_prepare_write_ImBuf(const bool isfloat, ImBuf *ibuf)
+bool IMB_prepare_write_ImBuf(const bool isfloat, ImBuf *ibuf)
{
- ImBuf *write_ibuf = ibuf;
+ bool changed = false;
if (isfloat) {
/* pass */
@@ -94,8 +90,11 @@ ImBuf *IMB_prepare_write_ImBuf(const bool isfloat, ImBuf *ibuf)
if (ibuf->rect == NULL && ibuf->rect_float) {
ibuf->rect_colorspace = colormanage_colorspace_get_roled(COLOR_ROLE_DEFAULT_BYTE);
IMB_rect_from_float(ibuf);
+ if (ibuf->rect != NULL) {
+ changed = true;
+ }
}
}
- return write_ibuf;
+ return changed;
}
diff --git a/source/blender/makesdna/DNA_ID.h b/source/blender/makesdna/DNA_ID.h
index 2c6f3d2fc66..80640d8dffe 100644
--- a/source/blender/makesdna/DNA_ID.h
+++ b/source/blender/makesdna/DNA_ID.h
@@ -82,8 +82,6 @@ enum {
IDP_FLOAT = 2,
IDP_ARRAY = 5,
IDP_GROUP = 6,
- /* the ID link property type hasn't been implemented yet, this will require
- * some cleanup of blenkernel, most likely. */
IDP_ID = 7,
IDP_DOUBLE = 8,
IDP_IDPARRAY = 9,
@@ -129,11 +127,14 @@ typedef struct ID {
/**
* LIB_TAG_... tags (runtime only, cleared at read time).
*/
- short tag;
- short pad_s1;
+ int tag;
int us;
int icon_id;
+ int recalc;
+ int pad;
IDProperty *properties;
+
+ void *py_instance;
} ID;
/**
@@ -285,12 +286,12 @@ typedef enum ID_Type {
#define ID_MISSING(_id) (((_id)->tag & LIB_TAG_MISSING) != 0)
-#define ID_IS_LINKED_DATABLOCK(_id) (((ID *)(_id))->lib != NULL)
+#define ID_IS_LINKED(_id) (((ID *)(_id))->lib != NULL)
#ifdef GS
# undef GS
#endif
-#define GS(a) (CHECK_TYPE_ANY(a, char *, const char *, char [66], const char[66]), (*((const short *)(a))))
+#define GS(a) (CHECK_TYPE_ANY(a, char *, const char *, char [66], const char[66]), (ID_Type)(*((const short *)(a))))
#define ID_NEW_SET(_id, _idn) \
(((ID *)(_id))->newid = (ID *)(_idn), ((ID *)(_id))->newid->tag |= LIB_TAG_NEW, (void *)((ID *)(_id))->newid)
@@ -342,16 +343,26 @@ enum {
* Also used internally in readfile.c to mark datablocks needing do_versions. */
LIB_TAG_NEW = 1 << 8,
/* RESET_BEFORE_USE free test flag.
- * TODO make it a RESET_AFTER_USE too. */
+ * TODO make it a RESET_AFTER_USE too. */
LIB_TAG_DOIT = 1 << 10,
/* RESET_AFTER_USE tag existing data before linking so we know what is new. */
LIB_TAG_PRE_EXISTING = 1 << 11,
+ /* RESET_NEVER tag datablock for freeing etc. behavior (usually set when copying real one into temp/runtime one). */
+ LIB_TAG_NO_MAIN = 1 << 12, /* Datablock is not listed in Main database. */
+ LIB_TAG_NO_USER_REFCOUNT = 1 << 13, /* Datablock does not refcount usages of other IDs. */
+ /* Datablock was not allocated by standard system (BKE_libblock_alloc), do not free its memory
+ * (usual type-specific freeing is called though). */
+ LIB_TAG_NOT_ALLOCATED = 1 << 14,
+};
+
+enum {
/* RESET_AFTER_USE, used by update code (depsgraph). */
- LIB_TAG_ID_RECALC = 1 << 12,
- LIB_TAG_ID_RECALC_DATA = 1 << 13,
- LIB_TAG_ANIM_NO_RECALC = 1 << 14,
- LIB_TAG_ID_RECALC_ALL = (LIB_TAG_ID_RECALC | LIB_TAG_ID_RECALC_DATA),
+ ID_RECALC_NONE = 0,
+ ID_RECALC = 1 << 0,
+ ID_RECALC_DATA = 1 << 1,
+ ID_RECALC_SKIP_ANIM_TAG = 1 << 2,
+ ID_RECALC_ALL = (ID_RECALC | ID_RECALC_DATA),
};
/* To filter ID types (filter_id) */
diff --git a/source/blender/makesdna/DNA_action_types.h b/source/blender/makesdna/DNA_action_types.h
index 1083400ece2..1691038e13c 100644
--- a/source/blender/makesdna/DNA_action_types.h
+++ b/source/blender/makesdna/DNA_action_types.h
@@ -254,6 +254,7 @@ typedef struct bPoseChannel {
float roll1, roll2;
float curveInX, curveInY;
float curveOutX, curveOutY;
+ float ease1, ease2;
float scaleIn, scaleOut;
struct bPoseChannel *bbone_prev; /* next/prev bones to use as handle references when calculating bbones (optional) */
@@ -376,7 +377,12 @@ typedef enum eRotationModes {
typedef struct bPose {
ListBase chanbase; /* list of pose channels, PoseBones in RNA */
struct GHash *chanhash; /* ghash for quicker string lookups */
-
+
+ /* Flat array of pose channels. It references pointers from
+ * chanbase. Used for quick pose channel lookup from an index.
+ */
+ bPoseChannel **chan_array;
+
short flag, pad;
unsigned int proxy_layer; /* proxy layer: copy from armature, gets synced */
int pad1;
@@ -514,7 +520,7 @@ typedef enum eActionGroup_Flag {
AGRP_MODIFIERS_OFF = (1 << 7),
AGRP_TEMP = (1 << 30),
- AGRP_MOVED = (1 << 31)
+ AGRP_MOVED = (1u << 31)
} eActionGroup_Flag;
@@ -749,7 +755,7 @@ typedef struct bActionChannel {
} bActionChannel;
/* Action Channel flags (ONLY USED FOR DO_VERSIONS...) */
-typedef enum ACHAN_FLAG {
+typedef enum eActionChannelFlag {
ACHAN_SELECTED = (1 << 0),
ACHAN_HIGHLIGHTED = (1 << 1),
ACHAN_HIDDEN = (1 << 2),
@@ -757,7 +763,7 @@ typedef enum ACHAN_FLAG {
ACHAN_EXPANDED = (1 << 4),
ACHAN_SHOWIPO = (1 << 5),
ACHAN_SHOWCONS = (1 << 6),
- ACHAN_MOVED = (1 << 31)
-} ACHAN_FLAG;
+ ACHAN_MOVED = (1u << 31)
+} eActionChannelFlag;
#endif /* __DNA_ACTION_TYPES_H__ */
diff --git a/source/blender/makesdna/DNA_anim_types.h b/source/blender/makesdna/DNA_anim_types.h
index e50a2637fff..cea1a1cf40f 100644
--- a/source/blender/makesdna/DNA_anim_types.h
+++ b/source/blender/makesdna/DNA_anim_types.h
@@ -52,6 +52,7 @@ extern "C" {
typedef struct FModifier {
struct FModifier *next, *prev;
+ struct FCurve *curve; /* containing curve, only used for updates to CYCLES */
void *data; /* pointer to modifier data */
char name[64]; /* user-defined description for the modifier - MAX_ID_NAME-2 */
@@ -489,7 +490,10 @@ typedef struct FCurve {
float curval; /* value stored from last time curve was evaluated (not threadsafe, debug display only!) */
short flag; /* user-editable settings for this curve */
short extend; /* value-extending mode for this curve (does not cover */
+ char auto_smoothing; /* auto-handle smoothing mode */
+ char pad[7];
+
/* RNA - data link */
int array_index; /* if applicable, the index of the RNA-array item to get */
char *rna_path; /* RNA-path to resolve data-access */
@@ -544,6 +548,12 @@ typedef enum eFCurve_Coloring {
FCURVE_COLOR_CUSTOM = 2, /* custom color */
} eFCurve_Coloring;
+/* curve smoothing modes */
+typedef enum eFCurve_Smoothing {
+ FCURVE_SMOOTH_NONE = 0, /* legacy mode: auto handles only consider adjacent points */
+ FCURVE_SMOOTH_CONT_ACCEL = 1, /* maintain continuity of the acceleration */
+} eFCurve_Smoothing;
+
/* ************************************************ */
/* 'Action' Datatypes */
@@ -685,7 +695,7 @@ typedef enum eNlaStrip_Flag {
/* temporary editing flags */
/* NLA-Strip is really just a temporary meta used to facilitate easier transform code */
NLASTRIP_FLAG_TEMP_META = (1<<30),
- NLASTRIP_FLAG_EDIT_TOUCHED = (1<<31)
+ NLASTRIP_FLAG_EDIT_TOUCHED = (1u << 31)
} eNlaStrip_Flag;
/* NLA Strip Type */
@@ -830,17 +840,18 @@ typedef enum eKS_Settings {
/* Flags for use by keyframe creation/deletion calls */
typedef enum eInsertKeyFlags {
+ INSERTKEY_NOFLAGS = 0,
INSERTKEY_NEEDED = (1<<0), /* only insert keyframes where they're needed */
INSERTKEY_MATRIX = (1<<1), /* insert 'visual' keyframes where possible/needed */
INSERTKEY_FAST = (1<<2), /* don't recalculate handles,etc. after adding key */
INSERTKEY_FASTR = (1<<3), /* don't realloc mem (or increase count, as array has already been set out) */
INSERTKEY_REPLACE = (1<<4), /* only replace an existing keyframe (this overrides INSERTKEY_NEEDED) */
INSERTKEY_XYZ2RGB = (1<<5), /* transform F-Curves should have XYZ->RGB color mode */
- INSERTKEY_NO_USERPREF = (1 << 6), /* ignore user-prefs (needed for predictable API use) */
+ INSERTKEY_NO_USERPREF = (1<<6), /* ignore user-prefs (needed for predictable API use) */
/* Allow to make a full copy of new key into existing one, if any, instead of 'reusing' existing handles.
* Used by copy/paste code. */
INSERTKEY_OVERWRITE_FULL = (1<<7),
- INSERTKEY_DRIVER = (1<<8), /* for driver FCurves, use driver's "input" value - for easier corrective driver setup */
+ INSERTKEY_DRIVER = (1<<8), /* for driver FCurves, use driver's "input" value - for easier corrective driver setup */
} eInsertKeyFlags;
/* ************************************************ */
diff --git a/source/blender/makesdna/DNA_armature_types.h b/source/blender/makesdna/DNA_armature_types.h
index cda6441f0ae..757c0eb8394 100644
--- a/source/blender/makesdna/DNA_armature_types.h
+++ b/source/blender/makesdna/DNA_armature_types.h
@@ -66,12 +66,12 @@ typedef struct Bone {
float dist, weight; /* dist, weight: for non-deformgroup deforms */
float xwidth, length, zwidth; /* width: for block bones. keep in this order, transform! */
- float ease1, ease2; /* length of bezier handles */
float rad_head, rad_tail; /* radius for head/tail sphere, defining deform as well, parent->rad_tip overrides rad_head */
float roll1, roll2; /* curved bones settings - these define the "restpose" for a curved bone */
float curveInX, curveInY;
float curveOutX, curveOutY;
+ float ease1, ease2; /* length of bezier handles */
float scaleIn, scaleOut;
float size[3]; /* patch for upward compat, UNUSED! */
diff --git a/source/blender/makesdna/DNA_boid_types.h b/source/blender/makesdna/DNA_boid_types.h
index f1930ffd643..44764eb012e 100644
--- a/source/blender/makesdna/DNA_boid_types.h
+++ b/source/blender/makesdna/DNA_boid_types.h
@@ -34,7 +34,7 @@
#include "DNA_listBase.h"
-typedef enum BoidRuleType {
+typedef enum eBoidRuleType {
eBoidRuleType_None = 0,
eBoidRuleType_Goal = 1, /* go to goal assigned object or loudest assigned signal source */
eBoidRuleType_Avoid = 2, /* get away from assigned object or loudest assigned signal source */
@@ -49,7 +49,7 @@ typedef enum BoidRuleType {
//eBoidRuleType_FollowPath = 11, /* move along a assigned curve or closest curve in a group */
//eBoidRuleType_FollowWall = 12, /* move next to a deflector object's in direction of it's tangent */
NUM_BOID_RULE_TYPES
-} BoidRuleType;
+} eBoidRuleType;
/* boidrule->flag */
#define BOIDRULE_CURRENT 1
@@ -96,14 +96,14 @@ typedef struct BoidRuleFight {
float distance, flee_distance;
} BoidRuleFight;
-typedef enum BoidMode {
+typedef enum eBoidMode {
eBoidMode_InAir = 0,
eBoidMode_OnLand = 1,
eBoidMode_Climbing = 2,
eBoidMode_Falling = 3,
eBoidMode_Liftoff = 4,
NUM_BOID_MODES
-} BoidMode;
+} eBoidMode;
typedef struct BoidData {
@@ -140,12 +140,12 @@ typedef struct BoidData {
// int signal_id, channels;
//} BoidCondition;
-typedef enum BoidRulesetType {
+typedef enum eBoidRulesetType {
eBoidRulesetType_Fuzzy = 0,
eBoidRulesetType_Random = 1,
eBoidRulesetType_Average = 2,
NUM_BOID_RULESET_TYPES
-} BoidRulesetType;
+} eBoidRulesetType;
#define BOIDSTATE_CURRENT 1
typedef struct BoidState {
struct BoidState *next, *prev;
diff --git a/source/blender/makesdna/DNA_brush_types.h b/source/blender/makesdna/DNA_brush_types.h
index f4a1677efc4..fc3b4afe18d 100644
--- a/source/blender/makesdna/DNA_brush_types.h
+++ b/source/blender/makesdna/DNA_brush_types.h
@@ -72,7 +72,7 @@ typedef struct Brush {
float rake_factor; /* rake actual data (not texture), used for sculpt */
short blend; /* blend mode */
- short ob_mode; /* & with ob->mode to see if the brush is compatible, use for display only. */
+ short ob_mode; /* eObjectMode: to see if the brush is compatible, use for display only. */
float weight; /* brush weight */
int size; /* brush diameter */
int flag; /* general purpose flag */
@@ -95,13 +95,17 @@ typedef struct Brush {
float plane_offset; /* offset for plane brushes (clay, flatten, fill, scrape) */
int gradient_spacing;
- int gradient_stroke_mode; /* source for stroke color gradient application */
- int gradient_fill_mode; /* source for fill tool color gradient application */
+ char gradient_stroke_mode; /* source for stroke color gradient application */
+ char gradient_fill_mode; /* source for fill tool color gradient application */
+
+ char pad;
+ char falloff_shape; /* Projection shape (sphere, circle) */
+ float falloff_angle;
char sculpt_tool; /* active sculpt tool */
char vertexpaint_tool; /* active vertex/weight paint blend mode (poorly named) */
char imagepaint_tool; /* active image paint tool */
- char mask_tool; /* enum BrushMaskTool, only used if sculpt_tool is SCULPT_TOOL_MASK */
+ char mask_tool; /* enum eBrushMaskTool, only used if sculpt_tool is SCULPT_TOOL_MASK */
float autosmooth_factor;
@@ -167,27 +171,27 @@ typedef struct PaintCurve {
} PaintCurve;
/* Brush.gradient_source */
-typedef enum BrushGradientSourceStroke {
+typedef enum eBrushGradientSourceStroke {
BRUSH_GRADIENT_PRESSURE = 0, /* gradient from pressure */
BRUSH_GRADIENT_SPACING_REPEAT = 1, /* gradient from spacing */
BRUSH_GRADIENT_SPACING_CLAMP = 2 /* gradient from spacing */
-} BrushGradientSourceStroke;
+} eBrushGradientSourceStroke;
-typedef enum BrushGradientSourceFill {
+typedef enum eBrushGradientSourceFill {
BRUSH_GRADIENT_LINEAR = 0, /* gradient from pressure */
BRUSH_GRADIENT_RADIAL = 1 /* gradient from spacing */
-} BrushGradientSourceFill;
+} eBrushGradientSourceFill;
/* Brush.flag */
-typedef enum BrushFlags {
+typedef enum eBrushFlags {
BRUSH_AIRBRUSH = (1 << 0),
-// BRUSH_TORUS = (1 << 1), deprecated, use paint->symmetry_flags & PAINT_TILE_*
+ BRUSH_FLAG_DEPRECATED_1 = (1 << 1),
BRUSH_ALPHA_PRESSURE = (1 << 2),
BRUSH_SIZE_PRESSURE = (1 << 3),
BRUSH_JITTER_PRESSURE = (1 << 4),
BRUSH_SPACING_PRESSURE = (1 << 5),
- BRUSH_UNUSED = (1 << 6),
-// BRUSH_RAKE = (1 << 7), deprecated, use brush_angle_mode
+ BRUSH_FLAG_DEPRECATED_2 = (1 << 6),
+ BRUSH_FLAG_DEPRECATED_3 = (1 << 7),
BRUSH_ANCHORED = (1 << 8),
BRUSH_DIR_IN = (1 << 9),
BRUSH_SPACE = (1 << 10),
@@ -197,6 +201,7 @@ typedef enum BrushFlags {
BRUSH_LOCK_ALPHA = (1 << 14),
BRUSH_ORIGINAL_NORMAL = (1 << 15),
BRUSH_OFFSET_PRESSURE = (1 << 16),
+ BRUSH_FLAG_DEPRECATED_4 = (1 << 17),
BRUSH_SPACE_ATTEN = (1 << 18),
BRUSH_ADAPTIVE_SPACE = (1 << 19),
BRUSH_LOCK_SIZE = (1 << 20),
@@ -204,14 +209,14 @@ typedef enum BrushFlags {
BRUSH_EDGE_TO_EDGE = (1 << 22),
BRUSH_DRAG_DOT = (1 << 23),
BRUSH_INVERSE_SMOOTH_PRESSURE = (1 << 24),
-// BRUSH_RANDOM_ROTATION = (1 << 25), deprecated, use brush_angle_mode
+ BRUSH_FRONTFACE_FALLOFF = (1 << 25),
BRUSH_PLANE_TRIM = (1 << 26),
BRUSH_FRONTFACE = (1 << 27),
BRUSH_CUSTOM_ICON = (1 << 28),
BRUSH_LINE = (1 << 29),
BRUSH_ABSOLUTE_JITTER = (1 << 30),
- BRUSH_CURVE = (1 << 31)
-} BrushFlags;
+ BRUSH_CURVE = (1u << 31)
+} eBrushFlags;
typedef enum {
BRUSH_MASK_PRESSURE_RAMP = (1 << 1),
@@ -219,21 +224,21 @@ typedef enum {
} BrushMaskPressureFlags;
/* Brush.overlay_flags */
-typedef enum OverlayFlags {
+typedef enum eOverlayFlags {
BRUSH_OVERLAY_CURSOR = (1),
BRUSH_OVERLAY_PRIMARY = (1 << 1),
BRUSH_OVERLAY_SECONDARY = (1 << 2),
BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE = (1 << 3),
BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE = (1 << 4),
BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE = (1 << 5)
-} OverlayFlags;
+} eOverlayFlags;
#define BRUSH_OVERLAY_OVERRIDE_MASK (BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE | \
BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE | \
BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE)
/* Brush.sculpt_tool */
-typedef enum BrushSculptTool {
+typedef enum eBrushSculptTool {
SCULPT_TOOL_DRAW = 1,
SCULPT_TOOL_SMOOTH = 2,
SCULPT_TOOL_PINCH = 3,
@@ -253,7 +258,7 @@ typedef enum BrushSculptTool {
SCULPT_TOOL_BLOB = 17,
SCULPT_TOOL_CLAY_STRIPS = 18,
SCULPT_TOOL_MASK = 19
-} BrushSculptTool;
+} eBrushSculptTool;
/** When #BRUSH_ACCUMULATE is used */
#define SCULPT_TOOL_HAS_ACCUMULATE(t) ELEM(t, \
@@ -290,14 +295,14 @@ typedef enum BrushSculptTool {
) == 0)
/* ImagePaintSettings.tool */
-typedef enum BrushImagePaintTool {
+typedef enum eBrushImagePaintTool {
PAINT_TOOL_DRAW = 0,
PAINT_TOOL_SOFTEN = 1,
PAINT_TOOL_SMEAR = 2,
PAINT_TOOL_CLONE = 3,
PAINT_TOOL_FILL = 4,
PAINT_TOOL_MASK = 5
-} BrushImagePaintTool;
+} eBrushImagePaintTool;
/* direction that the brush displaces along */
enum {
@@ -315,7 +320,21 @@ enum {
PAINT_BLEND_MUL = 3,
PAINT_BLEND_BLUR = 4,
PAINT_BLEND_LIGHTEN = 5,
- PAINT_BLEND_DARKEN = 6
+ PAINT_BLEND_DARKEN = 6,
+ PAINT_BLEND_AVERAGE = 7,
+ PAINT_BLEND_SMEAR = 8,
+ PAINT_BLEND_COLORDODGE = 9,
+ PAINT_BLEND_DIFFERENCE = 10,
+ PAINT_BLEND_SCREEN = 11,
+ PAINT_BLEND_HARDLIGHT = 12,
+ PAINT_BLEND_OVERLAY = 13,
+ PAINT_BLEND_SOFTLIGHT = 14,
+ PAINT_BLEND_EXCLUSION = 15,
+ PAINT_BLEND_LUMINOCITY = 16,
+ PAINT_BLEND_SATURATION = 17,
+ PAINT_BLEND_HUE = 18,
+ PAINT_BLEND_ALPHA_SUB = 19,
+ PAINT_BLEND_ALPHA_ADD = 20,
};
typedef enum {
@@ -324,10 +343,16 @@ typedef enum {
} BrushMaskTool;
/* blur kernel types, Brush.blur_mode */
-typedef enum BlurKernelType {
+typedef enum eBlurKernelType {
KERNEL_GAUSSIAN,
KERNEL_BOX
-} BlurKernelType;
+} eBlurKernelType;
+
+/* Brush.falloff_shape */
+enum {
+ PAINT_FALLOFF_SHAPE_SPHERE = 0,
+ PAINT_FALLOFF_SHAPE_TUBE = 1,
+};
#define MAX_BRUSH_PIXEL_RADIUS 500
diff --git a/source/blender/makesdna/DNA_cachefile_types.h b/source/blender/makesdna/DNA_cachefile_types.h
index 46b1adf2725..c0e662d8a48 100644
--- a/source/blender/makesdna/DNA_cachefile_types.h
+++ b/source/blender/makesdna/DNA_cachefile_types.h
@@ -47,10 +47,12 @@ enum {
CACHEFILE_KEYFRAME_DRAWN = (1 << 0),
};
+/* Representation of an object's path inside the Alembic file.
+ * Note that this is not a file path. */
typedef struct AlembicObjectPath {
struct AlembicObjectPath *next, *prev;
- char path[1024]; /* 1024 = FILE_MAX, might use PATH_MAX in the future. */
+ char path[4096];
} AlembicObjectPath;
typedef struct CacheFile {
@@ -73,9 +75,12 @@ typedef struct CacheFile {
float scale;
float frame; /* The frame/time to lookup in the cache file. */
+ float frame_offset; /* The frame offset to subtract. */
short flag; /* Animation flag. */
short draw_flag;
+
+ char padding[4];
} CacheFile;
#ifdef __cplusplus
diff --git a/source/blender/makesdna/DNA_color_types.h b/source/blender/makesdna/DNA_color_types.h
index f7ee1ff3915..6f9c407c6c6 100644
--- a/source/blender/makesdna/DNA_color_types.h
+++ b/source/blender/makesdna/DNA_color_types.h
@@ -91,7 +91,7 @@ typedef struct CurveMapping {
#define CUMA_DRAW_SAMPLE 8
/* cumapping->preset */
-typedef enum CurveMappingPreset {
+typedef enum eCurveMappingPreset {
CURVE_PRESET_LINE = 0,
CURVE_PRESET_SHARP = 1,
CURVE_PRESET_SMOOTH = 2,
@@ -99,7 +99,7 @@ typedef enum CurveMappingPreset {
CURVE_PRESET_MID9 = 4,
CURVE_PRESET_ROUND = 5,
CURVE_PRESET_ROOT = 6,
-} CurveMappingPreset;
+} eCurveMappingPreset;
/* histogram->mode */
enum {
diff --git a/source/blender/makesdna/DNA_constraint_types.h b/source/blender/makesdna/DNA_constraint_types.h
index ca774864e95..4c4440ad573 100644
--- a/source/blender/makesdna/DNA_constraint_types.h
+++ b/source/blender/makesdna/DNA_constraint_types.h
@@ -92,23 +92,22 @@ typedef struct bConstraintTarget {
short space; /* space that target should be evaluated in (overrides bConstraint->tarspace) */
short flag; /* runtime settings (for editor, etc.) */
- short type; /* type of target (B_CONSTRAINT_OB_TYPE) */
+ short type; /* type of target (eConstraintObType) */
short rotOrder; /* rotation order for target (as defined in BLI_math.h) */
} bConstraintTarget;
/* bConstraintTarget -> flag */
-typedef enum B_CONSTRAINT_TARGET_FLAG {
+typedef enum eConstraintTargetFlag {
CONSTRAINT_TAR_TEMP = (1<<0) /* temporary target-struct that needs to be freed after use */
-} B_CONSTRAINT_TARGET_FLAG;
+} eConstraintTargetFlag;
/* bConstraintTarget/bConstraintOb -> type */
-typedef enum B_CONSTRAINT_OB_TYPE {
+typedef enum eConstraintObType {
CONSTRAINT_OBTYPE_OBJECT = 1, /* string is "" */
CONSTRAINT_OBTYPE_BONE = 2, /* string is bone-name */
CONSTRAINT_OBTYPE_VERT = 3, /* string is vertex-group name */
CONSTRAINT_OBTYPE_CV = 4 /* string is vertex-group name - is not available until curves get vgroups */
-} B_CONSTRAINT_OB_TYPE;
-
+} eConstraintObType;
/* Python Script Constraint */
@@ -128,7 +127,7 @@ typedef struct bPythonConstraint {
/* Inverse-Kinematics (IK) constraint
* This constraint supports a variety of mode determine by the type field
- * according to B_CONSTRAINT_IK_TYPE.
+ * according to eConstraint_IK_Type.
* Some fields are used by all types, some are specific to some types
* This is indicated in the comments for each field
*/
@@ -145,15 +144,15 @@ typedef struct bKinematicConstraint {
float weight; /* All: Weight of constraint in IK tree */
float orientweight; /* CopyPose: Amount of rotation a target applies on chain */
float grabtarget[3]; /* CopyPose: for target-less IK */
- short type; /* subtype of IK constraint: B_CONSTRAINT_IK_TYPE */
+ short type; /* subtype of IK constraint: eConstraint_IK_Type */
short mode; /* Distance: how to limit in relation to clamping sphere: LIMITDIST_.. */
float dist; /* Distance: distance (radius of clamping sphere) from target */
} bKinematicConstraint;
-typedef enum B_CONSTRAINT_IK_TYPE {
+typedef enum eConstraint_IK_Type {
CONSTRAINT_IK_COPYPOSE = 0, /* 'standard' IK constraint: match position and/or orientation of target */
CONSTRAINT_IK_DISTANCE = 1 /* maintain distance with target */
-} B_CONSTRAINT_IK_TYPE;
+} eConstraint_IK_Type;
/* Spline IK Constraint
diff --git a/source/blender/makesdna/DNA_curve_types.h b/source/blender/makesdna/DNA_curve_types.h
index 902fa4ce987..91b64b793c1 100644
--- a/source/blender/makesdna/DNA_curve_types.h
+++ b/source/blender/makesdna/DNA_curve_types.h
@@ -87,9 +87,7 @@ typedef struct BevList {
int charidx;
int *segbevcount;
float *seglen;
-
- /* over-alloc */
- BevPoint bevpoints[0];
+ BevPoint *bevpoints;
} BevList;
/**
@@ -118,13 +116,14 @@ typedef struct BezTriple {
char h1, h2; /* h1, h2: the handle type of the two handles */
char f1, f2, f3; /* f1, f2, f3: used for selection status */
- char hide; /* hide: used to indicate whether BezTriple is hidden (3D), type of keyframe (eBezTriple_KeyframeTypes) */
+ char hide; /* hide: used to indicate whether BezTriple is hidden (3D), type of keyframe (eBezTriple_KeyframeType) */
char easing; /* easing: easing type for interpolation mode (eBezTriple_Easing) */
float back; /* BEZT_IPO_BACK */
float amplitude, period; /* BEZT_IPO_ELASTIC */
- char pad[4];
+ char f5; /* f5: used for auto handle to distinguish between normal handle and exception (extrema) */
+ char pad[3];
} BezTriple;
/* note; alfa location in struct is abused by Key system */
@@ -379,6 +378,12 @@ enum {
/* *************** BEZTRIPLE **************** */
+/* BezTriple.f1,2,3 */
+typedef enum eBezTriple_Flag {
+ /* SELECT */
+ BEZT_FLAG_TEMP_TAG = (1 << 1), /* always clear. */
+} eBezTriple_Flag;
+
/* h1 h2 (beztriple) */
typedef enum eBezTriple_Handle {
HD_FREE = 0,
@@ -389,6 +394,12 @@ typedef enum eBezTriple_Handle {
HD_ALIGN_DOUBLESIDE = 5, /* align handles, displayed both of them. used for masks */
} eBezTriple_Handle;
+/* f5 (beztriple) */
+typedef enum eBezTriple_Auto_Type {
+ HD_AUTOTYPE_NORMAL = 0,
+ HD_AUTOTYPE_SPECIAL = 1
+} eBezTriple_Auto_Type;
+
/* interpolation modes (used only for BezTriple->ipo) */
typedef enum eBezTriple_Interpolation {
/* traditional interpolation */
@@ -436,6 +447,8 @@ typedef enum eBezTriple_KeyframeType {
#define BEZT_SEL_ALL(bezt) { (bezt)->f1 |= SELECT; (bezt)->f2 |= SELECT; (bezt)->f3 |= SELECT; } ((void)0)
#define BEZT_DESEL_ALL(bezt) { (bezt)->f1 &= ~SELECT; (bezt)->f2 &= ~SELECT; (bezt)->f3 &= ~SELECT; } ((void)0)
+#define BEZT_IS_AUTOH(bezt) (ELEM((bezt)->h1, HD_AUTO, HD_AUTO_ANIM) && ELEM((bezt)->h2, HD_AUTO, HD_AUTO_ANIM))
+
/* *************** CHARINFO **************** */
/* CharInfo.flag */
diff --git a/source/blender/makesdna/DNA_gpencil_types.h b/source/blender/makesdna/DNA_gpencil_types.h
index 0364d855f69..a62538d1032 100644
--- a/source/blender/makesdna/DNA_gpencil_types.h
+++ b/source/blender/makesdna/DNA_gpencil_types.h
@@ -60,11 +60,13 @@ typedef enum eGPDspoint_Flag {
} eGPSPoint_Flag;
/* Grease-Pencil Annotations - 'Triangle'
- * -> A triangle contains the index of three vertices for filling the stroke
- * This is only used if high quality fill is enabled
+ * A triangle contains the index of three vertices for filling the stroke
+ * This is only used if high quality fill is enabled.
+ * (not saved to blend file).
*/
typedef struct bGPDtriangle {
- int v1, v2, v3; /* indices for tesselated triangle used for GP Fill */
+ /* indices for tesselated triangle used for GP Fill */
+ unsigned int verts[3];
} bGPDtriangle;
/* GP brush (used for new strokes) */
diff --git a/source/blender/makesdna/DNA_meshdata_types.h b/source/blender/makesdna/DNA_meshdata_types.h
index 621807d111c..8bb711339f7 100644
--- a/source/blender/makesdna/DNA_meshdata_types.h
+++ b/source/blender/makesdna/DNA_meshdata_types.h
@@ -164,8 +164,8 @@ typedef struct MLoop {
* MEdge *ed = &medge[mloop[lt->tri[j]].e];
* unsigned int tri_edge[2] = {mloop[lt->tri[j]].v, mloop[lt->tri[j_next]].v};
*
- * if (ELEM(ed->v1, tri_edge[0], tri_edge[1]) &&
- * ELEM(ed->v2, tri_edge[0], tri_edge[1]))
+ * if (((ed->v1 == tri_edge[0]) && (ed->v1 == tri_edge[1])) ||
+ * ((ed->v1 == tri_edge[1]) && (ed->v1 == tri_edge[0])))
* {
* printf("real edge found %u %u\n", tri_edge[0], tri_edge[1]);
* }
@@ -356,7 +356,7 @@ typedef struct GridPaintMask {
int pad;
} GridPaintMask;
-typedef enum MVertSkinFlag {
+typedef enum eMVertSkinFlag {
/* Marks a vertex as the edge-graph root, used for calculating rotations for all connected edges (recursively).
* Also used to choose a root when generating an armature.
*/
@@ -366,13 +366,13 @@ typedef enum MVertSkinFlag {
* directly hulled together, rather than the default of generating intermediate frames.
*/
MVERT_SKIN_LOOSE = 2,
-} MVertSkinFlag;
+} eMVertSkinFlag;
typedef struct MVertSkin {
/* Radii of the skin, define how big the generated frames are. Currently only the first two elements are used. */
float radius[3];
- /* MVertSkinFlag */
+ /* eMVertSkinFlag */
int flag;
} MVertSkin;
diff --git a/source/blender/makesdna/DNA_meta_types.h b/source/blender/makesdna/DNA_meta_types.h
index 8bbe53b33a6..68d16700a73 100644
--- a/source/blender/makesdna/DNA_meta_types.h
+++ b/source/blender/makesdna/DNA_meta_types.h
@@ -32,6 +32,7 @@
#ifndef __DNA_META_TYPES_H__
#define __DNA_META_TYPES_H__
+#include "DNA_defs.h"
#include "DNA_listBase.h"
#include "DNA_ID.h"
diff --git a/source/blender/makesdna/DNA_modifier_types.h b/source/blender/makesdna/DNA_modifier_types.h
index f95533a88f9..258acbab31a 100644
--- a/source/blender/makesdna/DNA_modifier_types.h
+++ b/source/blender/makesdna/DNA_modifier_types.h
@@ -86,6 +86,7 @@ typedef enum ModifierType {
eModifierType_NormalEdit = 50,
eModifierType_CorrectiveSmooth = 51,
eModifierType_MeshSequenceCache = 52,
+ eModifierType_SurfaceDeform = 53,
NUM_MODIFIER_TYPES
} ModifierType;
@@ -97,7 +98,7 @@ typedef enum ModifierMode {
eModifierMode_Expanded = (1 << 4),
eModifierMode_Virtual = (1 << 5),
eModifierMode_ApplyOnSpline = (1 << 6),
- eModifierMode_DisableTemporary = (1 << 31)
+ eModifierMode_DisableTemporary = (1u << 31)
} ModifierMode;
typedef struct ModifierData {
@@ -248,6 +249,7 @@ typedef struct ArrayModifierData {
int flags;
/* the number of duplicates to generate for MOD_ARR_FIXEDCOUNT */
int count;
+ float uv_offset[2];
} ArrayModifierData;
/* ArrayModifierData->fit_type */
@@ -276,6 +278,8 @@ typedef struct MirrorModifierData {
short axis DNA_DEPRECATED; /* deprecated, use flag instead */
short flag;
float tolerance;
+ float uv_offset[2];
+ float uv_offset_copy[2];
struct Object *mirror_ob;
} MirrorModifierData;
@@ -599,7 +603,7 @@ typedef struct ClothModifierData {
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 */
+ struct PointCache *point_cache; /* definition is in DNA_object_force_types.h */
struct ListBase ptcaches;
/* XXX nasty hack, remove once hair can be separated from cloth modifier data */
struct ClothHairData *hairdata;
@@ -651,8 +655,8 @@ typedef struct BooleanModifierData {
struct Object *object;
char operation;
- char solver;
char pad[2];
+ char bm_flag;
float double_threshold;
} BooleanModifierData;
@@ -662,10 +666,12 @@ typedef enum {
eBooleanModifierOp_Difference = 2,
} BooleanModifierOp;
-typedef enum {
- eBooleanModifierSolver_Carve = 0,
- eBooleanModifierSolver_BMesh = 1,
-} BooleanSolver;
+/* bm_flag (only used when G_DEBUG) */
+enum {
+ eBooleanModifierBMeshFlag_BMesh_Separate = (1 << 0),
+ eBooleanModifierBMeshFlag_BMesh_NoDissolve = (1 << 1),
+ eBooleanModifierBMeshFlag_BMesh_NoConnectRegions = (1 << 2),
+};
typedef struct MDefInfluence {
int vertex;
@@ -747,12 +753,21 @@ typedef enum {
eParticleInstanceFlag_UseSize = (1 << 7),
} ParticleInstanceModifierFlag;
+typedef enum {
+ eParticleInstanceSpace_World = 0,
+ eParticleInstanceSpace_Local = 1,
+} ParticleInstanceModifierSpace;
+
typedef struct ParticleInstanceModifierData {
ModifierData modifier;
struct Object *ob;
- short psys, flag, axis, pad;
+ short psys, flag, axis, space;
float position, random_position;
+ float rotation, random_rotation;
+ float particle_amount, particle_offset;
+ char index_layer_name[64]; /* MAX_CUSTOMDATA_LAYER_NAME */
+ char value_layer_name[64]; /* MAX_CUSTOMDATA_LAYER_NAME */
} ParticleInstanceModifierData;
typedef enum {
@@ -788,8 +803,8 @@ typedef enum {
typedef struct FluidsimModifierData {
ModifierData modifier;
- struct FluidsimSettings *fss; /* definition is in DNA_object_fluidsim.h */
- struct PointCache *point_cache; /* definition is in DNA_object_force.h */
+ struct FluidsimSettings *fss; /* definition is in DNA_object_fluidsim_types.h */
+ struct PointCache *point_cache; /* definition is in DNA_object_force_types.h */
} FluidsimModifierData;
typedef struct ShrinkwrapModifierData {
@@ -856,8 +871,8 @@ typedef struct SimpleDeformModifierData {
char mode; /* deform function */
char axis; /* lock axis (for taper and strech) */
+ char deform_axis; /* axis to perform the deform on (default is X, but can be overridden by origin */
char flag;
- char pad;
} SimpleDeformModifierData;
@@ -877,6 +892,7 @@ enum {
enum {
MOD_SIMPLEDEFORM_LOCK_AXIS_X = (1 << 0),
MOD_SIMPLEDEFORM_LOCK_AXIS_Y = (1 << 1),
+ MOD_SIMPLEDEFORM_LOCK_AXIS_Z = (1 << 2),
};
typedef struct ShapeKeyModifierData {
@@ -922,9 +938,10 @@ typedef struct ScrewModifierData {
unsigned int iter;
float screw_ofs;
float angle;
- char axis;
- char pad;
+ float merge_dist;
short flag;
+ char axis;
+ char pad[5];
} ScrewModifierData;
enum {
@@ -935,6 +952,7 @@ enum {
MOD_SCREW_SMOOTH_SHADING = (1 << 5),
MOD_SCREW_UV_STRETCH_U = (1 << 6),
MOD_SCREW_UV_STRETCH_V = (1 << 7),
+ MOD_SCREW_MERGE = (1 << 8),
};
typedef struct OceanModifierData {
@@ -1213,19 +1231,19 @@ enum {
};
/* Remesh modifier */
-typedef enum RemeshModifierFlags {
+typedef enum eRemeshModifierFlags {
MOD_REMESH_FLOOD_FILL = 1,
MOD_REMESH_SMOOTH_SHADING = 2,
} RemeshModifierFlags;
-typedef enum RemeshModifierMode {
+typedef enum eRemeshModifierMode {
/* blocky */
MOD_REMESH_CENTROID = 0,
/* smooth */
MOD_REMESH_MASS_POINT = 1,
/* keeps sharp edges */
MOD_REMESH_SHARP_FEATURES = 2,
-} RemeshModifierMode;
+} eRemeshModifierMode;
typedef struct RemeshModifierData {
ModifierData modifier;
@@ -1513,7 +1531,7 @@ enum {
MOD_DATATRANSFER_USE_VERT = 1 << 28,
MOD_DATATRANSFER_USE_EDGE = 1 << 29,
MOD_DATATRANSFER_USE_LOOP = 1 << 30,
- MOD_DATATRANSFER_USE_POLY = 1 << 31,
+ MOD_DATATRANSFER_USE_POLY = 1u << 31,
};
/* Set Split Normals modifier */
@@ -1570,6 +1588,46 @@ enum {
MOD_MESHSEQ_READ_COLOR = (1 << 3),
};
+typedef struct SDefBind {
+ unsigned int *vert_inds;
+ unsigned int numverts;
+ int mode;
+ float *vert_weights;
+ float normal_dist;
+ float influence;
+} SDefBind;
+
+typedef struct SDefVert {
+ SDefBind *binds;
+ unsigned int numbinds;
+ char pad[4];
+} SDefVert;
+
+typedef struct SurfaceDeformModifierData {
+ ModifierData modifier;
+
+ struct Object *target; /* bind target object */
+ SDefVert *verts; /* vertex bind data */
+ float falloff;
+ unsigned int numverts, numpoly;
+ int flags;
+ float mat[4][4];
+} SurfaceDeformModifierData;
+
+/* Surface Deform modifier flags */
+enum {
+ MOD_SDEF_BIND = (1 << 0),
+ MOD_SDEF_USES_LOOPTRI = (1 << 1),
+ MOD_SDEF_HAS_CONCAVE = (1 << 2),
+};
+
+/* Surface Deform vertex bind modes */
+enum {
+ MOD_SDEF_MODE_LOOPTRI = 0,
+ MOD_SDEF_MODE_NGON = 1,
+ MOD_SDEF_MODE_CENTROID = 2,
+};
+
#define MOD_MESHSEQ_READ_ALL \
(MOD_MESHSEQ_READ_VERT | MOD_MESHSEQ_READ_POLY | MOD_MESHSEQ_READ_UV | MOD_MESHSEQ_READ_COLOR)
diff --git a/source/blender/makesdna/DNA_node_types.h b/source/blender/makesdna/DNA_node_types.h
index 47677e50451..8ae1a79f8f7 100644
--- a/source/blender/makesdna/DNA_node_types.h
+++ b/source/blender/makesdna/DNA_node_types.h
@@ -111,7 +111,7 @@ typedef struct bNodeSocket {
short stack_index; /* local stack index */
/* XXX deprecated, kept for forward compatibility */
short stack_type DNA_DEPRECATED;
- int pad;
+ char draw_shape, pad[3];
void *cache; /* cached data from execution */
@@ -143,6 +143,13 @@ typedef enum eNodeSocketDatatype {
SOCK_STRING = 7
} eNodeSocketDatatype;
+/* socket shape */
+typedef enum eNodeSocketDrawShape {
+ SOCK_DRAW_SHAPE_CIRCLE = 0,
+ SOCK_DRAW_SHAPE_SQUARE = 1,
+ SOCK_DRAW_SHAPE_DIAMOND = 2
+} eNodeSocketDrawShape;
+
/* socket side (input/output) */
typedef enum eNodeSocketInOut {
SOCK_IN = 1,
@@ -569,9 +576,9 @@ typedef struct NodeEllipseMask {
/* layer info for image node outputs */
typedef struct NodeImageLayer {
/* index in the Image->layers->passes lists */
- int pass_index;
- /* render pass flag, in case this is an original render pass */
- int pass_flag;
+ int pass_index DNA_DEPRECATED;
+ /* render pass name */
+ char pass_name[64]; /* amount defined in openexr_multi.h */
} NodeImageLayer;
typedef struct NodeBlurData {
@@ -1022,12 +1029,12 @@ typedef struct NodeSunBeams {
#define SHD_TANGENT_AXIS_Y 1
#define SHD_TANGENT_AXIS_Z 2
-/* normal map space */
-#define SHD_NORMAL_MAP_TANGENT 0
-#define SHD_NORMAL_MAP_OBJECT 1
-#define SHD_NORMAL_MAP_WORLD 2
-#define SHD_NORMAL_MAP_BLENDER_OBJECT 3
-#define SHD_NORMAL_MAP_BLENDER_WORLD 4
+/* normal map, displacement space */
+#define SHD_SPACE_TANGENT 0
+#define SHD_SPACE_OBJECT 1
+#define SHD_SPACE_WORLD 2
+#define SHD_SPACE_BLENDER_OBJECT 3
+#define SHD_SPACE_BLENDER_WORLD 4
/* math node clamp */
#define SHD_MATH_CLAMP 1
@@ -1067,6 +1074,7 @@ enum {
SHD_SUBSURFACE_CUBIC = 1,
SHD_SUBSURFACE_GAUSSIAN = 2,
SHD_SUBSURFACE_BURLEY = 3,
+ SHD_SUBSURFACE_RANDOM_WALK = 4,
};
/* blur node */
diff --git a/source/blender/makesdna/DNA_object_enums.h b/source/blender/makesdna/DNA_object_enums.h
new file mode 100644
index 00000000000..58f9e29297f
--- /dev/null
+++ b/source/blender/makesdna/DNA_object_enums.h
@@ -0,0 +1,49 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file DNA_object_enums.h
+ * \ingroup DNA
+ *
+ * Enums typedef's for use in public headers.
+ */
+
+#ifndef __DNA_OBJECT_ENUMS_H__
+#define __DNA_OBJECT_ENUMS_H__
+
+/* Object.mode */
+typedef enum eObjectMode {
+ OB_MODE_OBJECT = 0,
+ OB_MODE_EDIT = 1 << 0,
+ OB_MODE_SCULPT = 1 << 1,
+ OB_MODE_VERTEX_PAINT = 1 << 2,
+ OB_MODE_WEIGHT_PAINT = 1 << 3,
+ OB_MODE_TEXTURE_PAINT = 1 << 4,
+ OB_MODE_PARTICLE_EDIT = 1 << 5,
+ OB_MODE_POSE = 1 << 6,
+ OB_MODE_GPENCIL = 1 << 7, /* NOTE: Just a dummy to make the UI nicer */
+} eObjectMode;
+
+/* Any mode where the brush system is used. */
+#define OB_MODE_ALL_PAINT (OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)
+
+/* Any mode that uses Object.sculpt. */
+#define OB_MODE_ALL_SCULPT (OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT)
+
+#endif /* __DNA_OBJECT_ENUMS_H__ */
diff --git a/source/blender/makesdna/DNA_object_fluidsim.h b/source/blender/makesdna/DNA_object_fluidsim_types.h
index a714195dd5d..b305235083a 100644
--- a/source/blender/makesdna/DNA_object_fluidsim.h
+++ b/source/blender/makesdna/DNA_object_fluidsim_types.h
@@ -25,12 +25,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file DNA_object_fluidsim.h
+/** \file DNA_object_fluidsim_types.h
* \ingroup DNA
*/
-#ifndef __DNA_OBJECT_FLUIDSIM_H__
-#define __DNA_OBJECT_FLUIDSIM_H__
+#ifndef __DNA_OBJECT_FLUIDSIM_TYPES_H__
+#define __DNA_OBJECT_FLUIDSIM_TYPES_H__
#include "DNA_ID.h"
#include "DNA_defs.h"
@@ -179,6 +179,7 @@ typedef struct FluidsimSettings {
#define OB_FLUIDSIM_ACTIVE (1 << 1)
#define OB_FLUIDSIM_OVERRIDE_TIME (1 << 2)
+#define OB_FLUIDSIM_SURF_DIR_DEFAULT "cache_fluid"
#define OB_FLUIDSIM_SURF_PREVIEW_OBJ_FNAME "fluidsurface_preview_####.bobj.gz"
#define OB_FLUIDSIM_SURF_FINAL_OBJ_FNAME "fluidsurface_final_####.bobj.gz"
#define OB_FLUIDSIM_SURF_FINAL_VEL_FNAME "fluidsurface_final_####.bvel.gz"
@@ -188,6 +189,5 @@ typedef struct FluidsimSettings {
}
#endif
-#endif
-
+#endif /* __DNA_OBJECT_FLUIDSIM_TYPES_H__ */
diff --git a/source/blender/makesdna/DNA_object_force.h b/source/blender/makesdna/DNA_object_force_types.h
index 59acefeffe4..47467917315 100644
--- a/source/blender/makesdna/DNA_object_force.h
+++ b/source/blender/makesdna/DNA_object_force_types.h
@@ -25,12 +25,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file DNA_object_force.h
+/** \file DNA_object_force_types.h
* \ingroup DNA
*/
-#ifndef __DNA_OBJECT_FORCE_H__
-#define __DNA_OBJECT_FORCE_H__
+#ifndef __DNA_OBJECT_FORCE_TYPES_H__
+#define __DNA_OBJECT_FORCE_TYPES_H__
#ifdef __cplusplus
extern "C" {
@@ -39,7 +39,7 @@ extern "C" {
#include "DNA_listBase.h"
/* pd->forcefield: Effector Fields types */
-typedef enum PFieldType {
+typedef enum ePFieldType {
PFIELD_NULL = 0, /* (this is used for general effector weight) */
PFIELD_FORCE = 1, /* Force away/towards a point depending on force strength */
PFIELD_VORTEX = 2, /* Force around the effector normal */
@@ -56,8 +56,8 @@ typedef enum PFieldType {
PFIELD_DRAG = 12, /* Linear & quadratic drag */
PFIELD_SMOKEFLOW = 13, /* Force based on smoke simulation air flow */
NUM_PFIELD_TYPES
-} PFieldType;
-
+} ePFieldType;
+
typedef struct PartDeflect {
int flag; /* general settings flag */
short deflect; /* Deflection flag - does mesh deflect particles */
@@ -372,6 +372,7 @@ typedef struct SoftBody {
#define PFIELD_DO_ROTATION (1<<15)
#define PFIELD_GUIDE_PATH_WEIGHT (1<<16) /* apply curve weights */
#define PFIELD_SMOKE_DENSITY (1<<17) /* multiply smoke force by density */
+#define PFIELD_GRAVITATION (1<<18) /* used for (simple) force */
/* pd->falloff */
#define PFIELD_FALL_SPHERE 0
@@ -452,5 +453,5 @@ typedef struct SoftBody {
}
#endif
-#endif
+#endif /* __DNA_OBJECT_FORCE_TYPES_H__ */
diff --git a/source/blender/makesdna/DNA_object_types.h b/source/blender/makesdna/DNA_object_types.h
index d24c7faa9f5..e0b4d117bd1 100644
--- a/source/blender/makesdna/DNA_object_types.h
+++ b/source/blender/makesdna/DNA_object_types.h
@@ -33,6 +33,8 @@
#ifndef __DNA_OBJECT_TYPES_H__
#define __DNA_OBJECT_TYPES_H__
+#include "DNA_object_enums.h"
+
#include "DNA_defs.h"
#include "DNA_listBase.h"
#include "DNA_ID.h"
@@ -137,6 +139,7 @@ typedef struct Object {
bAnimVizSettings avs; /* settings for visualization of object-transform animation */
bMotionPath *mpath; /* motion path cache for this object */
+ void *pad1;
ListBase constraintChannels DNA_DEPRECATED; // XXX deprecated... old animation system
ListBase effect DNA_DEPRECATED; // XXX deprecated... keep for readfile
@@ -253,8 +256,6 @@ typedef struct Object {
int gameflag;
int gameflag2;
- struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */
-
char restrictflag; /* for restricting view, select, render etc. accessible in outliner */
char recalc; /* dependency flag */
short softflag; /* softbody settings */
@@ -265,6 +266,7 @@ typedef struct Object {
ListBase hooks DNA_DEPRECATED; // XXX deprecated... old animation system
ListBase particlesystem; /* particle systems */
+ struct BulletSoftBody *bsoft; /* settings for game engine bullet soft body */
struct PartDeflect *pd; /* particle deflector/attractor/collision data */
struct SoftBody *soft; /* if exists, saved in file */
struct Group *dup_group; /* object duplicator for group */
@@ -294,6 +296,7 @@ typedef struct Object {
float ima_ofs[2]; /* offset for image empties */
ImageUser *iuser; /* must be non-null when oject is an empty image */
+ void *pad3;
ListBase lodlevels; /* contains data for levels of detail */
LodLevel *currentlod;
@@ -335,6 +338,8 @@ typedef struct DupliObject {
/* particle this dupli was generated from */
struct ParticleSystem *particle_system;
+ unsigned int random_id;
+ unsigned int pad;
} DupliObject;
/* **************** OBJECT ********************* */
@@ -494,9 +499,13 @@ enum {
/* also needed for base!!!!! or rather, they interfere....*/
/* base->flag and ob->flag */
-#define BA_WAS_SEL (1 << 1)
-#define BA_HAS_RECALC_OB (1 << 2)
-#define BA_HAS_RECALC_DATA (1 << 3)
+enum {
+ BA_WAS_SEL = (1 << 1),
+ /* NOTE: BA_HAS_RECALC_DATA can be re-used later if freed in readfile.c. */
+ // BA_HAS_RECALC_OB = (1 << 2), /* DEPRECATED */
+ // BA_HAS_RECALC_DATA = (1 << 3), /* DEPRECATED */
+ BA_SNAP_FIX_DEPS_FIASCO = (1 << 2), /* Yes, re-use deprecated bit, all fine since it's runtime only. */
+};
/* NOTE: this was used as a proper setting in past, so nullify before using */
#define BA_TEMP_TAG (1 << 5)
@@ -664,23 +673,7 @@ enum {
OB_LOCK_ROTW = 1 << 9,
OB_LOCK_ROT4D = 1 << 10,
};
-
-/* ob->mode */
-typedef enum ObjectMode {
- OB_MODE_OBJECT = 0,
- OB_MODE_EDIT = 1 << 0,
- OB_MODE_SCULPT = 1 << 1,
- OB_MODE_VERTEX_PAINT = 1 << 2,
- OB_MODE_WEIGHT_PAINT = 1 << 3,
- OB_MODE_TEXTURE_PAINT = 1 << 4,
- OB_MODE_PARTICLE_EDIT = 1 << 5,
- OB_MODE_POSE = 1 << 6,
- OB_MODE_GPENCIL = 1 << 7, /* NOTE: Just a dummy to make the UI nicer */
-} ObjectMode;
-
-/* any mode where the brush system is used */
-#define OB_MODE_ALL_PAINT (OB_MODE_SCULPT | OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT)
-
+
#define MAX_DUPLI_RECUR 8
#ifdef __cplusplus
diff --git a/source/blender/makesdna/DNA_packedFile_types.h b/source/blender/makesdna/DNA_packedFile_types.h
index 56140c84cb1..00a54c2db7f 100644
--- a/source/blender/makesdna/DNA_packedFile_types.h
+++ b/source/blender/makesdna/DNA_packedFile_types.h
@@ -40,7 +40,7 @@ typedef struct PackedFile {
void *data;
} PackedFile;
-enum PF_FileStatus {
+enum ePF_FileStatus {
PF_EQUAL = 0,
PF_DIFFERS = 1,
PF_NOFILE = 2,
diff --git a/source/blender/makesdna/DNA_particle_types.h b/source/blender/makesdna/DNA_particle_types.h
index 1deb9bf3787..9dbd1a18703 100644
--- a/source/blender/makesdna/DNA_particle_types.h
+++ b/source/blender/makesdna/DNA_particle_types.h
@@ -261,6 +261,10 @@ typedef struct ParticleSettings {
short use_modifier_stack;
short pad5[3];
+ float twist;
+ float pad6;
+ struct CurveMapping *twistcurve;
+ void *pad7;
} ParticleSettings;
typedef struct ParticleSystem {
@@ -303,7 +307,8 @@ typedef struct ParticleSystem {
char bb_uvname[3][64]; /* billboard uv name, MAX_CUSTOMDATA_LAYER_NAME */
/* if you change these remember to update array lengths to PSYS_TOT_VG! */
- short vgroup[12], vg_neg, rt3; /* vertex groups, 0==disable, 1==starting index */
+ short vgroup[13], vg_neg, rt3; /* vertex groups, 0==disable, 1==starting index */
+ char pad[6];
/* temporary storage during render */
struct ParticleRenderData *renderdata;
@@ -323,7 +328,7 @@ typedef struct ParticleSystem {
struct ParticleDrawData *pdd;
float dt_frac; /* current time step, as a fraction of a frame */
- float _pad; /* spare capacity */
+ float lattice_strength; /* influence of the lattice modifier */
} ParticleSystem;
typedef enum eParticleDrawFlag {
@@ -435,6 +440,7 @@ typedef enum eParticleChildFlag {
PART_CHILD_USE_CLUMP_NOISE = (1<<0),
PART_CHILD_USE_CLUMP_CURVE = (1<<1),
PART_CHILD_USE_ROUGH_CURVE = (1<<2),
+ PART_CHILD_USE_TWIST_CURVE = (1<<3),
} eParticleChildFlag;
/* part->draw_col */
@@ -562,7 +568,7 @@ typedef enum eParticleChildFlag {
#define PART_DUPLIW_CURRENT 1
/* psys->vg */
-#define PSYS_TOT_VG 12
+#define PSYS_TOT_VG 13
#define PSYS_VG_DENSITY 0
#define PSYS_VG_VEL 1
@@ -576,6 +582,7 @@ typedef enum eParticleChildFlag {
#define PSYS_VG_TAN 9
#define PSYS_VG_ROT 10
#define PSYS_VG_EFFECTOR 11
+#define PSYS_VG_TWIST 12
/* ParticleTarget->flag */
#define PTARGET_CURRENT 1
@@ -607,7 +614,8 @@ typedef enum eParticleTextureInfluence {
PAMAP_KINK_AMP = (1<<12),
PAMAP_ROUGH = (1<<9),
PAMAP_LENGTH = (1<<4),
- PAMAP_CHILD = (PAMAP_CLUMP | PAMAP_KINK_FREQ | PAMAP_KINK_AMP | PAMAP_ROUGH | PAMAP_LENGTH),
+ PAMAP_TWIST = (1<<13),
+ PAMAP_CHILD = (PAMAP_CLUMP | PAMAP_KINK_FREQ | PAMAP_KINK_AMP | PAMAP_ROUGH | PAMAP_LENGTH | PAMAP_TWIST),
} eParticleTextureInfluence;
#endif
diff --git a/source/blender/makesdna/DNA_scene_types.h b/source/blender/makesdna/DNA_scene_types.h
index 156e59dca2c..90a08e62893 100644
--- a/source/blender/makesdna/DNA_scene_types.h
+++ b/source/blender/makesdna/DNA_scene_types.h
@@ -99,55 +99,30 @@ typedef struct AviCodecData {
char avicodecname[128];
} AviCodecData;
-typedef struct QuicktimeCodecData {
- /*Old quicktime implementation compatibility fields, read only in 2.5 - deprecated*/
- void *cdParms; /* codec/compressor options */
- void *pad; /* padding */
-
- unsigned int cdSize; /* size of cdParms buffer */
- unsigned int pad2; /* padding */
-
- char qtcodecname[128];
-} QuicktimeCodecData;
-
-typedef struct QuicktimeCodecSettings {
- /* Codec settings detailed for 2.5 implementation*/
- int codecType; /* Types defined in quicktime_export.h */
- int codecSpatialQuality; /* in 0-100 scale, to be translated in 0-1024 for qt use */
-
- /* Settings not available in current QTKit API */
- int codec;
- int codecFlags;
- int colorDepth;
- int codecTemporalQuality; /* in 0-100 scale, to be translated in 0-1024 for qt use */
- int minSpatialQuality; /* in 0-100 scale, to be translated in 0-1024 for qt use */
- int minTemporalQuality; /* in 0-100 scale, to be translated in 0-1024 for qt use */
- int keyFrameRate;
- int bitRate; /* bitrate in bps */
-
- /* Audio Codec settings */
- int audiocodecType;
- int audioSampleRate;
- short audioBitDepth;
- short audioChannels;
- int audioCodecFlags;
- int audioBitRate;
- int pad1;
-} QuicktimeCodecSettings;
-
-typedef enum FFMpegPreset {
+typedef enum eFFMpegPreset {
FFM_PRESET_NONE,
- FFM_PRESET_ULTRAFAST,
- FFM_PRESET_SUPERFAST,
- FFM_PRESET_VERYFAST,
- FFM_PRESET_FASTER,
- FFM_PRESET_FAST,
- FFM_PRESET_MEDIUM,
- FFM_PRESET_SLOW,
- FFM_PRESET_SLOWER,
- FFM_PRESET_VERYSLOW,
-} FFMpegPreset;
+#ifdef DNA_DEPRECATED
+ /* Previously used by h.264 to control encoding speed vs. file size. */
+ FFM_PRESET_ULTRAFAST, /* DEPRECATED */
+ FFM_PRESET_SUPERFAST, /* DEPRECATED */
+ FFM_PRESET_VERYFAST, /* DEPRECATED */
+ FFM_PRESET_FASTER, /* DEPRECATED */
+ FFM_PRESET_FAST, /* DEPRECATED */
+ FFM_PRESET_MEDIUM, /* DEPRECATED */
+ FFM_PRESET_SLOW, /* DEPRECATED */
+ FFM_PRESET_SLOWER, /* DEPRECATED */
+ FFM_PRESET_VERYSLOW, /* DEPRECATED */
+#endif
+
+ /* Used by WEBM/VP9 and h.264 to control encoding speed vs. file size.
+ * WEBM/VP9 use these values directly, whereas h.264 map those to
+ * respectively the MEDIUM, SLOWER, and SUPERFAST presets.
+ */
+ FFM_PRESET_GOOD = 10, /* the default and recommended for most applications */
+ FFM_PRESET_BEST, /* recommended if you have lots of time and want the best compression efficiency */
+ FFM_PRESET_REALTIME, /* recommended for live / fast encoding */
+} eFFMpegPreset;
/* Mapping from easily-understandable descriptions to CRF values.
* Assumes we output 8-bit video. Needs to be remapped if 10-bit
@@ -155,7 +130,7 @@ typedef enum FFMpegPreset {
* We use a slightly wider than "subjectively sane range" according
* to https://trac.ffmpeg.org/wiki/Encode/H.264#a1.ChooseaCRFvalue
*/
-typedef enum FFMpegCrf {
+typedef enum eFFMpegCrf {
FFM_CRF_NONE = -1,
FFM_CRF_LOSSLESS = 0,
FFM_CRF_PERC_LOSSLESS = 17,
@@ -164,7 +139,7 @@ typedef enum FFMpegCrf {
FFM_CRF_LOW = 26,
FFM_CRF_VERYLOW = 29,
FFM_CRF_LOWEST = 32,
-} FFMpegCrf;
+} eFFMpegCrf;
typedef struct FFMpegCodecData {
int type;
@@ -180,7 +155,7 @@ typedef struct FFMpegCodecData {
int max_b_frames; /* only used if FFMPEG_USE_MAX_B_FRAMES flag is set. */
int flags;
int constant_rate_factor;
- int ffmpeg_preset; /* see FFMpegPreset */
+ int ffmpeg_preset; /* see eFFMpegPreset */
int rc_min_rate;
int rc_max_rate;
@@ -219,21 +194,25 @@ typedef struct SceneRenderLayer {
struct Material *mat_override;
struct Group *light_override;
- unsigned int lay; /* scene->lay itself has priority over this */
+ unsigned int lay; /* Scene.lay itself has priority over this */
unsigned int lay_zmask; /* has to be after lay, this is for Z-masking */
unsigned int lay_exclude; /* not used by internal, exclude */
int layflag;
-
- int passflag; /* pass_xor has to be after passflag */
+
+ /* pass_xor has to be after passflag */
+ /* note, this is treestore element 'nr' in outliner, short still... */
+ int passflag;
int pass_xor;
int samples;
float pass_alpha_threshold;
-
+
+ IDProperty *prop;
+
struct FreestyleConfig freestyleConfig;
} SceneRenderLayer;
-/* srl->layflag */
+/* SceneRenderLayer.layflag */
#define SCE_LAY_SOLID 1
#define SCE_LAY_ZTRA 2
#define SCE_LAY_HALO 4
@@ -250,8 +229,8 @@ typedef struct SceneRenderLayer {
#define SCE_LAY_ZMASK 0x40000
#define SCE_LAY_NEG_ZMASK 0x80000
-/* srl->passflag */
-typedef enum ScenePassType {
+/* SceneRenderLayer.passflag */
+typedef enum eScenePassType {
SCE_PASS_COMBINED = (1 << 0),
SCE_PASS_Z = (1 << 1),
SCE_PASS_RGBA = (1 << 2),
@@ -283,10 +262,44 @@ typedef enum ScenePassType {
SCE_PASS_SUBSURFACE_DIRECT = (1 << 28),
SCE_PASS_SUBSURFACE_INDIRECT = (1 << 29),
SCE_PASS_SUBSURFACE_COLOR = (1 << 30),
- SCE_PASS_DEBUG = (1 << 31), /* This is a virtual pass. */
-} ScenePassType;
+ SCE_PASS_ROUGHNESS = (1 << 31),
+} eScenePassType;
+
+#define RE_PASSNAME_COMBINED "Combined"
+#define RE_PASSNAME_Z "Depth"
+#define RE_PASSNAME_VECTOR "Vector"
+#define RE_PASSNAME_NORMAL "Normal"
+#define RE_PASSNAME_UV "UV"
+#define RE_PASSNAME_RGBA "Color"
+#define RE_PASSNAME_EMIT "Emit"
+#define RE_PASSNAME_DIFFUSE "Diffuse"
+#define RE_PASSNAME_SPEC "Spec"
+#define RE_PASSNAME_SHADOW "Shadow"
+
+#define RE_PASSNAME_AO "AO"
+#define RE_PASSNAME_ENVIRONMENT "Env"
+#define RE_PASSNAME_INDIRECT "Indirect"
+#define RE_PASSNAME_REFLECT "Reflect"
+#define RE_PASSNAME_REFRACT "Refract"
+#define RE_PASSNAME_INDEXOB "IndexOB"
+#define RE_PASSNAME_INDEXMA "IndexMA"
+#define RE_PASSNAME_MIST "Mist"
+
+#define RE_PASSNAME_RAYHITS "RayHits"
+#define RE_PASSNAME_DIFFUSE_DIRECT "DiffDir"
+#define RE_PASSNAME_DIFFUSE_INDIRECT "DiffInd"
+#define RE_PASSNAME_DIFFUSE_COLOR "DiffCol"
+#define RE_PASSNAME_GLOSSY_DIRECT "GlossDir"
+#define RE_PASSNAME_GLOSSY_INDIRECT "GlossInd"
+#define RE_PASSNAME_GLOSSY_COLOR "GlossCol"
+#define RE_PASSNAME_TRANSM_DIRECT "TransDir"
+#define RE_PASSNAME_TRANSM_INDIRECT "TransInd"
+#define RE_PASSNAME_TRANSM_COLOR "TransCol"
+
+#define RE_PASSNAME_SUBSURFACE_DIRECT "SubsurfaceDir"
+#define RE_PASSNAME_SUBSURFACE_INDIRECT "SubsurfaceInd"
+#define RE_PASSNAME_SUBSURFACE_COLOR "SubsurfaceCol"
-/* note, srl->passflag is treestore element 'nr' in outliner, short still... */
/* View - MultiView */
typedef struct SceneRenderView {
@@ -301,16 +314,16 @@ typedef struct SceneRenderView {
} SceneRenderView;
-/* srv->viewflag */
+/* SceneRenderView.viewflag */
#define SCE_VIEW_DISABLE (1<<0)
-/* scene.render.views_format */
+/* RenderData.views_format */
enum {
SCE_VIEWS_FORMAT_STEREO_3D = 0,
SCE_VIEWS_FORMAT_MULTIVIEW = 1,
};
-/* ImageFormatData.views_output */
+/* ImageFormatData.views_format (also used for Sequence.views_format) */
enum {
R_IMF_VIEWS_INDIVIDUAL = 0,
R_IMF_VIEWS_STEREO_3D = 1,
@@ -420,7 +433,7 @@ typedef struct ImageFormatData {
#define R_IMF_IMTYPE_AVIJPEG 16
#define R_IMF_IMTYPE_PNG 17
/* #define R_IMF_IMTYPE_AVICODEC 18 */ /* avicodec is nomore */
-#define R_IMF_IMTYPE_QUICKTIME 19
+/* #define R_IMF_IMTYPE_QUICKTIME 19 */ /* quicktime is nomore */
#define R_IMF_IMTYPE_BMP 20
#define R_IMF_IMTYPE_RADHDR 21
#define R_IMF_IMTYPE_TIFF 22
@@ -510,24 +523,24 @@ typedef struct BakeData {
char cage[64]; /* MAX_NAME */
} BakeData;
-/* (char) normal_swizzle */
-typedef enum BakeNormalSwizzle {
+/* BakeData.normal_swizzle (char) */
+typedef enum eBakeNormalSwizzle {
R_BAKE_POSX = 0,
R_BAKE_POSY = 1,
R_BAKE_POSZ = 2,
R_BAKE_NEGX = 3,
R_BAKE_NEGY = 4,
R_BAKE_NEGZ = 5,
-} BakeNormalSwizzle;
+} eBakeNormalSwizzle;
-/* (char) save_mode */
-typedef enum BakeSaveMode {
+/* BakeData.save_mode (char) */
+typedef enum eBakeSaveMode {
R_BAKE_SAVE_INTERNAL = 0,
R_BAKE_SAVE_EXTERNAL = 1,
-} BakeSaveMode;
+} eBakeSaveMode;
-/* bake->pass_filter */
-typedef enum BakePassFilter {
+/* BakeData.pass_filter */
+typedef enum eBakePassFilter {
R_BAKE_PASS_FILTER_NONE = 0,
R_BAKE_PASS_FILTER_AO = (1 << 0),
R_BAKE_PASS_FILTER_EMIT = (1 << 1),
@@ -538,7 +551,7 @@ typedef enum BakePassFilter {
R_BAKE_PASS_FILTER_DIRECT = (1 << 6),
R_BAKE_PASS_FILTER_INDIRECT = (1 << 7),
R_BAKE_PASS_FILTER_COLOR = (1 << 8),
-} BakePassFilter;
+} eBakePassFilter;
#define R_BAKE_PASS_FILTER_ALL (~0)
@@ -549,8 +562,6 @@ typedef struct RenderData {
struct ImageFormatData im_format;
struct AviCodecData *avicodecdata;
- struct QuicktimeCodecData *qtcodecdata;
- struct QuicktimeCodecSettings qtcodecsettings;
struct FFMpegCodecData ffcodecdata;
int cfra, sfra, efra; /* frames as in 'images' */
@@ -715,7 +726,7 @@ typedef struct RenderData {
/* sequencer options */
char seq_prev_type;
- char seq_rend_type;
+ char seq_rend_type; /* UNUSED! */
char seq_flag; /* flag use for sequence render/draw */
char pad5[5];
@@ -754,14 +765,13 @@ typedef struct RenderData {
struct BakeData bake;
int preview_start_resolution;
+ short preview_pixel_size;
/* Type of the debug pass to use.
* Only used when built with debug passes support.
*/
short debug_pass_type;
- short pad;
-
/* MultiView */
ListBase views; /* SceneRenderView */
short actview;
@@ -799,6 +809,7 @@ typedef struct GameDome {
struct Text *warptext;
} GameDome;
+/* GameDome.mode */
#define DOME_FISHEYE 1
#define DOME_TRUNCATED_FRONT 2
#define DOME_TRUNCATED_REAR 3
@@ -814,6 +825,7 @@ typedef struct GameFraming {
char type, pad1, pad2, pad3;
} GameFraming;
+/* GameFraming.type */
#define SCE_GAMEFRAMING_BARS 0
#define SCE_GAMEFRAMING_EXTEND 1
#define SCE_GAMEFRAMING_SCALE 2
@@ -837,6 +849,7 @@ typedef struct RecastData {
short pad2;
} RecastData;
+/* RecastData.partitioning */
#define RC_PARTITION_WATERSHED 0
#define RC_PARTITION_MONOTONE 1
#define RC_PARTITION_LAYERS 2
@@ -886,10 +899,12 @@ typedef struct GameData {
} GameData;
+/* GameData.stereoflag */
#define STEREO_NOSTEREO 1
#define STEREO_ENABLED 2
#define STEREO_DOME 3
+/* GameData.stereomode */
//#define STEREO_NOSTEREO 1
#define STEREO_QUADBUFFERED 2
#define STEREO_ABOVEBELOW 3
@@ -900,7 +915,7 @@ typedef struct GameData {
//#define STEREO_DOME 8
#define STEREO_3DTVTOPBOTTOM 9
-/* physicsEngine */
+/* GameData.physicsEngine */
#define WOPHY_NONE 0
#define WOPHY_BULLET 5
@@ -909,13 +924,13 @@ typedef struct GameData {
#define OBSTSIMULATION_TOI_rays 1
#define OBSTSIMULATION_TOI_cells 2
-/* Raster storage */
+/* GameData.raster_storage */
#define RAS_STORE_AUTO 0
-#define RAS_STORE_IMMEDIATE 1
+/* #define RAS_STORE_IMMEDIATE 1 */ /* DEPRECATED */
#define RAS_STORE_VA 2
#define RAS_STORE_VBO 3
-/* vsync */
+/* GameData.vsync */
#define VSYNC_ON 0
#define VSYNC_OFF 1
#define VSYNC_ADAPTIVE 2
@@ -959,13 +974,16 @@ enum {
#define SCE_LOD_USE_HYST (1 << 0)
/* UV Paint */
+/* ToolSettings.uv_sculpt_settings */
#define UV_SCULPT_LOCK_BORDERS 1
#define UV_SCULPT_ALL_ISLANDS 2
+/* ToolSettings.uv_sculpt_tool */
#define UV_SCULPT_TOOL_PINCH 1
#define UV_SCULPT_TOOL_RELAX 2
#define UV_SCULPT_TOOL_GRAB 3
+/* ToolSettings.uv_relax_method */
#define UV_SCULPT_TOOL_RELAX_LAPLACIAN 1
#define UV_SCULPT_TOOL_RELAX_HC 2
@@ -975,17 +993,18 @@ enum {
#define STEREO_RIGHT_SUFFIX "_R"
#define STEREO_LEFT_SUFFIX "_L"
-typedef enum StereoViews {
+/* View3D.stereo3d_camera / View3D.multiview_eye / ImageUser.multiview_eye */
+typedef enum eStereoViews {
STEREO_LEFT_ID = 0,
STEREO_RIGHT_ID = 1,
STEREO_3D_ID = 2,
STEREO_MONO_ID = 3,
-} StereoViews;
+} eStereoViews;
/* *************************************************************** */
/* Markers */
-typedef struct TimeMarker {
+typedef struct TimeMarker {
struct TimeMarker *next, *prev;
int frame;
char name[64];
@@ -1008,7 +1027,7 @@ typedef struct Paint {
void *paint_cursor;
unsigned char paint_cursor_col[4];
- /* enum PaintFlags */
+ /* enum ePaintFlags */
int flags;
/* Paint stroke can use up to PAINT_MAX_INPUT_SAMPLES inputs to
@@ -1063,7 +1082,7 @@ typedef struct ParticleEditSettings {
short totaddkey;
short brushtype;
- ParticleBrushData brush[7]; /* 7 = PE_TOT_BRUSH */
+ ParticleBrushData brush[7];
void *paintcursor; /* runtime */
float emitterdist, rt;
@@ -1120,29 +1139,21 @@ typedef struct UvSculpt {
/* Vertex Paint */
typedef struct VPaint {
Paint paint;
-
- short flag, pad;
- int tot; /* allocation size of prev buffers */
- unsigned int *vpaint_prev; /* previous mesh colors */
- struct MDeformVert *wpaint_prev; /* previous vertex weights */
-
- void *paintcursor; /* wm handle */
+ char flag;
+ char pad[3];
+ int radial_symm[3]; /* For mirrored painting */
} VPaint;
/* VPaint.flag */
enum {
- // VP_COLINDEX = (1 << 0), /* only paint onto active material*/ /* deprecated since before 2.49 */
- // VP_AREA = (1 << 1), /* deprecated since 2.70 */
- VP_NORMALS = (1 << 3),
- VP_SPRAY = (1 << 4),
- // VP_MIRROR_X = (1 << 5), /* deprecated in 2.5x use (me->editflag & ME_EDIT_MIRROR_X) */
- VP_ONLYVGROUP = (1 << 7) /* weight paint only */
+ /* weight paint only */
+ VP_FLAG_VGROUP_RESTRICT = (1 << 7)
};
/* ------------------------------------------- */
/* GPencil Stroke Sculpting */
-/* Brush types */
+/* GP_BrushEdit_Settings.brushtype */
typedef enum eGP_EditBrush_Types {
GP_EDITBRUSH_TYPE_SMOOTH = 0,
GP_EDITBRUSH_TYPE_THICKNESS = 1,
@@ -1160,7 +1171,7 @@ typedef enum eGP_EditBrush_Types {
TOT_GP_EDITBRUSH_TYPES
} eGP_EditBrush_Types;
-/* Lock axis options */
+/* GP_BrushEdit_Settings.lock_axis */
typedef enum eGP_Lockaxis_Types {
GP_LOCKAXIS_NONE = 0,
GP_LOCKAXIS_X = 1,
@@ -1198,7 +1209,7 @@ typedef struct GP_BrushEdit_Settings {
int brushtype; /* eGP_EditBrush_Types */
int flag; /* eGP_BrushEdit_SettingsFlag */
- int lock_axis; /* lock drawing to one axis */
+ int lock_axis; /* eGP_Lockaxis_Types lock drawing to one axis */
float alpha; /* alpha factor for selection color */
} GP_BrushEdit_Settings;
@@ -1348,6 +1359,7 @@ typedef struct UnifiedPaintSettings {
struct ColorSpace *colorspace;
} UnifiedPaintSettings;
+/* UnifiedPaintSettings.flag */
typedef enum {
UNIFIED_PAINT_SIZE = (1 << 0),
UNIFIED_PAINT_ALPHA = (1 << 1),
@@ -1362,7 +1374,7 @@ typedef enum {
/* only used if unified alpha is enabled, mirrors the brush flag
* BRUSH_ALPHA_PRESSURE */
UNIFIED_PAINT_BRUSH_ALPHA_PRESSURE = (1 << 4)
-} UnifiedPaintSettingsFlags;
+} eUnifiedPaintSettingsFlags;
typedef struct CurvePaintSettings {
@@ -1631,8 +1643,7 @@ typedef struct Scene {
struct Object *obedit; /* name replaces old G.obedit */
float cursor[3]; /* 3d cursor location */
- float twcent[3]; /* center for transform widget */
- float twmin[3], twmax[3]; /* boundbox of selection for transform widget */
+ char _pad[4];
unsigned int lay; /* bitflags for layer visibility */
int layact; /* active layer */
@@ -1687,12 +1698,12 @@ typedef struct Scene {
/* Grease Pencil */
struct bGPdata *gpd;
- /* Physics simulation settings */
- struct PhysicsSettings physics_settings;
-
/* Movie Tracking */
struct MovieClip *clip; /* active movie clip */
+ /* Physics simulation settings */
+ struct PhysicsSettings physics_settings;
+
uint64_t customdata_mask; /* XXX. runtime flag for drawing, actually belongs in the window, only used by BKE_object_handle_update() */
uint64_t customdata_mask_modal; /* XXX. same as above but for temp operator use (gl renders) */
@@ -1709,15 +1720,14 @@ typedef struct Scene {
/* **************** RENDERDATA ********************* */
-/* flag */
+/* RenderData.flag */
/* use preview range */
#define SCER_PRV_RANGE (1<<0)
#define SCER_LOCK_FRAME_SELECTION (1<<1)
- /* timeline/keyframe jumping - only selected items (on by default) */
-#define SCE_KEYS_NO_SELONLY (1<<2)
+ /* show/use subframes (for checking motion blur) */
#define SCER_SHOW_SUBFRAME (1<<3)
-/* mode (int now) */
+/* RenderData.mode */
#define R_OSA 0x0001
#define R_SHADOW 0x0002
#define R_GAMMA 0x0004
@@ -1730,7 +1740,8 @@ typedef struct Scene {
#define R_BORDER 0x0200
#define R_PANORAMA 0x0400 /* deprecated as scene option, still used in renderer */
#define R_CROP 0x0800
-/*#define R_COSMO 0x1000 deprecated */
+ /* Disable camera switching: runtime (DURIAN_CAMERA_SWITCH) */
+#define R_NO_CAMERA_SWITCH 0x1000
#define R_ODDFIELD 0x2000
#define R_MBLUR 0x4000
/* unified was here */
@@ -1753,20 +1764,22 @@ typedef struct Scene {
#define R_PERSISTENT_DATA 0x4000000 /* keep data around for re-render */
#define R_USE_WS_SHADING 0x8000000 /* use world space interpretation of lighting data */
-/* seq_flag */
-#define R_SEQ_GL_PREV 1
-// #define R_SEQ_GL_REND 2 // UNUSED, opengl render has its own operator now.
-#define R_SEQ_SOLID_TEX 4
-
-/* displaymode */
+/* RenderData.seq_flag */
+enum {
+ // R_SEQ_GL_PREV = (1 << 1), // UNUSED, we just use setting from seq_prev_type now.
+ // R_SEQ_GL_REND = (1 << 2), // UNUSED, opengl render has its own operator now.
+ R_SEQ_SOLID_TEX = (1 << 3),
+ R_SEQ_CAMERA_DOF = (1 << 4),
+};
+/* RenderData.displaymode */
#define R_OUTPUT_SCREEN 0
#define R_OUTPUT_AREA 1
#define R_OUTPUT_WINDOW 2
#define R_OUTPUT_NONE 3
/*#define R_OUTPUT_FORKED 4*/
-/* filtertype */
+/* RenderData.filtertype */
#define R_FILTER_BOX 0
#define R_FILTER_TENT 1
#define R_FILTER_QUAD 2
@@ -1776,7 +1789,7 @@ typedef struct Scene {
#define R_FILTER_MITCH 6
#define R_FILTER_FAST_GAUSS 7 /* note, this is only used for nodes at the moment */
-/* raytrace structure */
+/* RenderData.raytrace_structure */
#define R_RAYSTRUCTURE_AUTO 0
#define R_RAYSTRUCTURE_OCTREE 1
#define R_RAYSTRUCTURE_BLIBVH 2 /* removed */
@@ -1784,11 +1797,11 @@ typedef struct Scene {
#define R_RAYSTRUCTURE_SIMD_SVBVH 4 /* needs SIMD */
#define R_RAYSTRUCTURE_SIMD_QBVH 5 /* needs SIMD */
-/* raytrace_options */
+/* RenderData.raytrace_options */
#define R_RAYTRACE_USE_LOCAL_COORDS 0x0001
#define R_RAYTRACE_USE_INSTANCES 0x0002
-/* scemode (int now) */
+/* RenderData.scemode (int now) */
#define R_DOSEQ 0x0001
#define R_BG_RENDER 0x0002
/* passepartout is camera option now, keep this for backward compatibility */
@@ -1813,7 +1826,7 @@ typedef struct Scene {
#define R_EXR_CACHE_FILE 0x100000
#define R_MULTIVIEW 0x200000
-/* r->stamp */
+/* RenderData.stamp */
#define R_STAMP_TIME 0x0001
#define R_STAMP_FRAME 0x0002
#define R_STAMP_DATE 0x0004
@@ -1829,24 +1842,25 @@ typedef struct Scene {
#define R_STAMP_STRIPMETA 0x1000
#define R_STAMP_MEMORY 0x2000
#define R_STAMP_HIDE_LABELS 0x4000
+#define R_STAMP_FRAME_RANGE 0x8000
#define R_STAMP_ALL (R_STAMP_TIME|R_STAMP_FRAME|R_STAMP_DATE|R_STAMP_CAMERA|R_STAMP_SCENE| \
R_STAMP_NOTE|R_STAMP_MARKER|R_STAMP_FILENAME|R_STAMP_SEQSTRIP| \
R_STAMP_RENDERTIME|R_STAMP_CAMERALENS|R_STAMP_MEMORY| \
- R_STAMP_HIDE_LABELS)
+ R_STAMP_HIDE_LABELS|R_STAMP_FRAME_RANGE)
-/* alphamode */
+/* RenderData.alphamode */
#define R_ADDSKY 0
#define R_ALPHAPREMUL 1
/*#define R_ALPHAKEY 2*/ /* deprecated, shouldn't be used */
-/* color_mgt_flag */
+/* RenderData.color_mgt_flag */
enum {
R_COLOR_MANAGEMENT = (1 << 0), /* deprecated, should only be used in versioning code only */
/*R_COLOR_MANAGEMENT_PREDIVIDE = (1 << 1)*/ /* deprecated, shouldn't be used */
};
#ifdef DNA_DEPRECATED
-/* subimtype, flag options for imtype */
+/* RenderData.subimtype flag options for imtype */
enum {
R_OPENEXR_HALF = 1, /*deprecated*/
R_OPENEXR_ZBUF = 2, /*deprecated*/
@@ -1863,7 +1877,7 @@ enum {
#endif
/* bake_mode: same as RE_BAKE_xxx defines */
-/* bake_flag: */
+/* RenderData.bake_flag */
#define R_BAKE_CLEAR 1
#define R_BAKE_OSA 2
#define R_BAKE_TO_ACTIVE 4
@@ -1876,22 +1890,22 @@ enum {
#define R_BAKE_SPLIT_MAT 512
#define R_BAKE_AUTO_NAME 1024
-/* bake_normal_space */
+/* RenderData.bake_normal_space */
#define R_BAKE_SPACE_CAMERA 0
#define R_BAKE_SPACE_WORLD 1
#define R_BAKE_SPACE_OBJECT 2
#define R_BAKE_SPACE_TANGENT 3
-/* simplify_flag */
+/* RenderData.simplify_flag */
#define R_SIMPLE_NO_TRIANGULATE 1
-/* line_thickness_mode */
+/* RenderData.line_thickness_mode */
#define R_LINE_THICKNESS_ABSOLUTE 1
#define R_LINE_THICKNESS_RELATIVE 2
/* sequencer seq_prev_type seq_rend_type */
-/* scene->r.engine (scene.c) */
+/* RenderData.engine (scene.c) */
extern const char *RE_engine_id_BLENDER_RENDER;
extern const char *RE_engine_id_BLENDER_GAME;
extern const char *RE_engine_id_CYCLES;
@@ -1899,16 +1913,18 @@ extern const char *RE_engine_id_CYCLES;
/* **************** SCENE ********************* */
/* note that much higher maxframes give imprecise sub-frames, see: T46859 */
+/* Current precision is 16 for the sub-frames closer to MAXFRAME. */
+
/* for general use */
-#define MAXFRAME 500000
-#define MAXFRAMEF 500000.0f
+#define MAXFRAME 1048574
+#define MAXFRAMEF 1048574.0f
#define MINFRAME 0
#define MINFRAMEF 0.0f
/* (minimum frame number for current-frame) */
-#define MINAFRAME -500000
-#define MINAFRAMEF -500000.0f
+#define MINAFRAME -1048574
+#define MINAFRAMEF -1048574.0f
/* depricate this! */
#define TESTBASE(v3d, base) ( \
@@ -1958,9 +1974,9 @@ extern const char *RE_engine_id_CYCLES;
#define TIME2FRA(a) ((((double) scene->r.frs_sec) * (double)(a)) / (double)scene->r.frs_sec_base)
#define FPS (((double) scene->r.frs_sec) / (double)scene->r.frs_sec_base)
-/* base->flag is in DNA_object_types.h */
+/* Base.flag is in DNA_object_types.h */
-/* toolsettings->snap_flag */
+/* ToolSettings.snap_flag */
#define SCE_SNAP 1
#define SCE_SNAP_ROTATE 2
#define SCE_SNAP_PEEL_OBJECT 4
@@ -1968,12 +1984,12 @@ extern const char *RE_engine_id_CYCLES;
#define SCE_SNAP_NO_SELF 16
#define SCE_SNAP_ABS_GRID 32
-/* toolsettings->snap_target */
+/* ToolSettings.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
-/* toolsettings->snap_mode */
+/* ToolSettings.snap_mode */
#define SCE_SNAP_MODE_INCREMENT 0
#define SCE_SNAP_MODE_VERTEX 1
#define SCE_SNAP_MODE_EDGE 2
@@ -1984,24 +2000,24 @@ extern const char *RE_engine_id_CYCLES;
#define SCE_SNAP_MODE_NODE_XY 7
#define SCE_SNAP_MODE_GRID 8
-/* toolsettings->selectmode */
+/* ToolSettings.selectmode */
#define SCE_SELECT_VERTEX 1 /* for mesh */
#define SCE_SELECT_EDGE 2
#define SCE_SELECT_FACE 4
-/* toolsettings->statvis->type */
+/* MeshStatVis.type */
#define SCE_STATVIS_OVERHANG 0
#define SCE_STATVIS_THICKNESS 1
#define SCE_STATVIS_INTERSECT 2
#define SCE_STATVIS_DISTORT 3
#define SCE_STATVIS_SHARP 4
-/* toolsettings->particle.selectmode for particles */
+/* ParticleEditSettings.selectmode for particles */
#define SCE_SELECT_PATH 1
#define SCE_SELECT_POINT 2
#define SCE_SELECT_END 4
-/* toolsettings->prop_mode (proportional falloff) */
+/* ToolSettings.prop_mode (proportional falloff) */
#define PROP_SMOOTH 0
#define PROP_SPHERE 1
#define PROP_ROOT 2
@@ -2012,21 +2028,21 @@ extern const char *RE_engine_id_CYCLES;
#define PROP_INVSQUARE 7
#define PROP_MODE_MAX 8
-/* toolsettings->proportional */
+/* ToolSettings.proportional */
#define PROP_EDIT_OFF 0
#define PROP_EDIT_ON 1
#define PROP_EDIT_CONNECTED 2
#define PROP_EDIT_PROJECTED 3
-/* toolsettings->weightuser */
+/* ToolSettings.weightuser */
enum {
OB_DRAW_GROUPUSER_NONE = 0,
OB_DRAW_GROUPUSER_ACTIVE = 1,
OB_DRAW_GROUPUSER_ALL = 2
};
-/* toolsettings->vgroupsubset */
/* object_vgroup.c */
+/* ToolSettings.vgroupsubset */
typedef enum eVGroupSelect {
WT_VGROUP_ALL = 0,
WT_VGROUP_ACTIVE = 1,
@@ -2043,12 +2059,12 @@ typedef enum eVGroupSelect {
(1 << WT_VGROUP_ALL))
-/* sce->flag */
+/* Scene.flag */
#define SCE_DS_SELECTED (1<<0)
#define SCE_DS_COLLAPSED (1<<1)
#define SCE_NLA_EDIT_ON (1<<2)
#define SCE_FRAME_DROP (1<<3)
-
+#define SCE_KEYS_NO_SELONLY (1<<4)
/* return flag BKE_scene_base_iter_next functions */
/* #define F_ERROR -1 */ /* UNUSED */
@@ -2056,12 +2072,13 @@ typedef enum eVGroupSelect {
#define F_SCENE 1
#define F_DUPLI 3
-/* audio->flag */
+/* AudioData.flag */
#define AUDIO_MUTE (1<<0)
#define AUDIO_SYNC (1<<1)
#define AUDIO_SCRUB (1<<2)
#define AUDIO_VOLUME_ANIMATED (1<<3)
+/* FFMpegCodecData.flags */
enum {
#ifdef DNA_DEPRECATED
FFMPEG_MULTIPLEX_AUDIO = 1, /* deprecated, you can choose none as audiocodec now */
@@ -2072,16 +2089,16 @@ enum {
};
/* Paint.flags */
-typedef enum {
+typedef enum ePaintFlags {
PAINT_SHOW_BRUSH = (1 << 0),
PAINT_FAST_NAVIGATE = (1 << 1),
PAINT_SHOW_BRUSH_ON_SURFACE = (1 << 2),
PAINT_USE_CAVITY_MASK = (1 << 3)
-} PaintFlags;
+} ePaintFlags;
/* Paint.symmetry_flags
* (for now just a duplicate of sculpt symmetry flags) */
-typedef enum SymmetryFlags {
+typedef enum ePaintSymmetryFlags {
PAINT_SYMM_X = (1 << 0),
PAINT_SYMM_Y = (1 << 1),
PAINT_SYMM_Z = (1 << 2),
@@ -2089,13 +2106,13 @@ typedef enum SymmetryFlags {
PAINT_TILE_X = (1 << 4),
PAINT_TILE_Y = (1 << 5),
PAINT_TILE_Z = (1 << 6),
-} SymmetryFlags;
+} ePaintSymmetryFlags;
#define PAINT_SYMM_AXIS_ALL (PAINT_SYMM_X | PAINT_SYMM_Y | PAINT_SYMM_Z)
/* Sculpt.flags */
/* These can eventually be moved to paint flags? */
-typedef enum SculptFlags {
+typedef enum eSculptFlags {
#ifdef DNA_DEPRECATED
/* deprecated, part of paint struct symmetry_flags now */
SCULPT_SYMM_X = (1 << 0),
@@ -2125,12 +2142,16 @@ typedef enum SculptFlags {
/* If set, dynamic-topology detail size will be constant in object space */
SCULPT_DYNTOPO_DETAIL_CONSTANT = (1 << 13),
SCULPT_DYNTOPO_DETAIL_BRUSH = (1 << 14),
-} SculptFlags;
-typedef enum ImagePaintMode {
+ /* Don't display mask in viewport, but still use it for strokes. */
+ SCULPT_HIDE_MASK = (1 << 15),
+} eSculptFlags;
+
+/* ImagePaintSettings.mode */
+typedef enum eImagePaintMode {
IMAGEPAINT_MODE_MATERIAL, /* detect texture paint slots from the material */
IMAGEPAINT_MODE_IMAGE, /* select texture paint image directly */
-} ImagePaintMode;
+} eImagePaintMode;
/* ImagePaintSettings.flag */
#define IMAGEPAINT_DRAWING 1
@@ -2138,6 +2159,7 @@ typedef enum ImagePaintMode {
// #define IMAGEPAINT_DRAW_TOOL_DRAWING 4 // deprecated
/* projection painting only */
+/* ImagePaintSettings.flag */
#define IMAGEPAINT_PROJECT_XRAY (1 << 4)
#define IMAGEPAINT_PROJECT_BACKFACE (1 << 5)
#define IMAGEPAINT_PROJECT_FLAT (1 << 6)
@@ -2145,13 +2167,13 @@ typedef enum ImagePaintMode {
#define IMAGEPAINT_PROJECT_LAYER_STENCIL (1 << 8)
#define IMAGEPAINT_PROJECT_LAYER_STENCIL_INV (1 << 9)
-
+/* ImagePaintSettings.missing_data */
#define IMAGEPAINT_MISSING_UVS (1 << 0)
#define IMAGEPAINT_MISSING_MATERIAL (1 << 1)
#define IMAGEPAINT_MISSING_TEX (1 << 2)
#define IMAGEPAINT_MISSING_STENCIL (1 << 3)
-/* toolsettings->uvcalc_flag */
+/* ToolSettings.uvcalc_flag */
#define UVCALC_DEPRECATED1 1
#define UVCALC_DEPRECATED2 2
#define UVCALC_TRANSFORM_CORRECT 4 /* adjust UV's while transforming to avoid distortion */
@@ -2161,17 +2183,17 @@ typedef enum ImagePaintMode {
#define UVCALC_TRANSFORM_CORRECT 4 /* adjust UV's while transforming to avoid distortion */
#define UVCALC_USESUBSURF 8 /* Use mesh data after subsurf to compute UVs*/
-/* toolsettings->uv_flag */
+/* ToolSettings.uv_flag */
#define UV_SYNC_SELECTION 1
#define UV_SHOW_SAME_IMAGE 2
-/* toolsettings->uv_selectmode */
+/* ToolSettings.uv_selectmode */
#define UV_SELECT_VERTEX 1
#define UV_SELECT_EDGE 2
#define UV_SELECT_FACE 4
#define UV_SELECT_ISLAND 8
-/* toolsettings->edge_mode */
+/* ToolSettings.edge_mode */
#define EDGE_MODE_SELECT 0
#define EDGE_MODE_TAG_SEAM 1
#define EDGE_MODE_TAG_SHARP 2
@@ -2179,7 +2201,7 @@ typedef enum ImagePaintMode {
#define EDGE_MODE_TAG_BEVEL 4
#define EDGE_MODE_TAG_FREESTYLE 5
-/* toolsettings->gpencil_flags */
+/* ToolSettings.gpencil_flags */
typedef enum eGPencil_Flags {
/* "Continuous Drawing" - The drawing operator enters a mode where multiple strokes can be drawn */
GP_TOOL_FLAG_PAINTSESSIONS_ON = (1 << 0),
@@ -2189,13 +2211,13 @@ typedef enum eGPencil_Flags {
GP_TOOL_FLAG_PAINT_ONBACK = (1 << 2)
} eGPencil_Flags;
-/* toolsettings->gpencil_src */
+/* ToolSettings.gpencil_src */
typedef enum eGPencil_Source_3D {
GP_TOOL_SOURCE_SCENE = 0,
GP_TOOL_SOURCE_OBJECT = 1
} eGPencil_Source_3d;
-/* toolsettings->gpencil_*_align - Stroke Placement mode flags */
+/* ToolSettings.gpencil_*_align - Stroke Placement mode flags */
typedef enum eGPencil_Placement_Flags {
/* New strokes are added in viewport/data space (i.e. not screen space) */
GP_PROJECT_VIEWSPACE = (1 << 0),
@@ -2211,7 +2233,7 @@ typedef enum eGPencil_Placement_Flags {
GP_PROJECT_DEPTH_STROKE_ENDPOINTS = (1 << 4),
} eGPencil_Placement_Flags;
-/* toolsettings->particle flag */
+/* ToolSettings.particle flag */
#define PE_KEEP_LENGTHS 1
#define PE_LOCK_FIRST 2
#define PE_DEFLECT_EMITTER 4
@@ -2221,7 +2243,7 @@ typedef enum eGPencil_Placement_Flags {
#define PE_FADE_TIME 128
#define PE_AUTO_VELOCITY 256
-/* toolsetting->particle brushtype */
+/* ParticleEditSettings.brushtype */
#define PE_BRUSH_NONE -1
#define PE_BRUSH_COMB 0
#define PE_BRUSH_CUT 1
@@ -2231,18 +2253,15 @@ typedef enum eGPencil_Placement_Flags {
#define PE_BRUSH_SMOOTH 5
#define PE_BRUSH_WEIGHT 6
-/* this must equal ParticleEditSettings.brush array size */
-#define PE_TOT_BRUSH 6
-
-/* ParticleBrushData->flag */
+/* ParticleBrushData.flag */
#define PE_BRUSH_DATA_PUFF_VOLUME 1
-/* tooksettings->particle edittype */
+/* ParticleBrushData.edittype */
#define PE_TYPE_PARTICLES 0
#define PE_TYPE_SOFTBODY 1
#define PE_TYPE_CLOTH 2
-/* toolsettings->skgen_options */
+/* ToolSettings.skgen_options */
#define SKGEN_FILTER_INTERNAL (1 << 0)
#define SKGEN_FILTER_EXTERNAL (1 << 1)
#define SKGEN_SYMMETRY (1 << 2)
@@ -2264,40 +2283,40 @@ typedef enum eGPencil_Placement_Flags {
#define SKGEN_SUB_CORRELATION 2
#define SKGEN_SUB_TOTAL 3
-/* toolsettings->skgen_postpro */
+/* ToolSettings.skgen_postpro */
#define SKGEN_SMOOTH 0
#define SKGEN_AVERAGE 1
#define SKGEN_SHARPEN 2
-/* toolsettings->bone_sketching */
+/* ToolSettings.bone_sketching */
#define BONE_SKETCHING 1
#define BONE_SKETCHING_QUICK 2
#define BONE_SKETCHING_ADJUST 4
-/* toolsettings->bone_sketching_convert */
+/* ToolSettings.bone_sketching_convert */
#define SK_CONVERT_CUT_FIXED 0
#define SK_CONVERT_CUT_LENGTH 1
#define SK_CONVERT_CUT_ADAPTATIVE 2
#define SK_CONVERT_RETARGET 3
-/* toolsettings->skgen_retarget_options */
+/* ToolSettings.skgen_retarget_options */
#define SK_RETARGET_AUTONAME 1
-/* toolsettings->skgen_retarget_roll */
+/* ToolSettings.skgen_retarget_roll */
#define SK_RETARGET_ROLL_NONE 0
#define SK_RETARGET_ROLL_VIEW 1
#define SK_RETARGET_ROLL_JOINT 2
-/* physics_settings->flag */
+/* PhysicsSettings.flag */
#define PHYS_GLOBAL_GRAVITY 1
/* UnitSettings */
-/* UnitSettings->system */
+/* UnitSettings.system */
#define USER_UNIT_NONE 0
#define USER_UNIT_METRIC 1
#define USER_UNIT_IMPERIAL 2
-/* UnitSettings->flag */
+/* UnitSettings.flag */
#define USER_UNIT_OPT_SPLIT 1
#define USER_UNIT_ROT_RADIANS 2
diff --git a/source/blender/makesdna/DNA_screen_types.h b/source/blender/makesdna/DNA_screen_types.h
index e208ef39719..a7718883438 100644
--- a/source/blender/makesdna/DNA_screen_types.h
+++ b/source/blender/makesdna/DNA_screen_types.h
@@ -44,6 +44,7 @@ struct PanelType;
struct Scene;
struct uiLayout;
struct wmTimer;
+struct wmTooltipState;
typedef struct bScreen {
ID id;
@@ -76,6 +77,8 @@ typedef struct bScreen {
struct wmTimer *animtimer; /* if set, screen has timer handler added in window */
void *context; /* context callback */
+
+ struct wmTooltipState *tool_tip; /* runtime */
} bScreen;
typedef struct ScrVert {
@@ -280,11 +283,11 @@ typedef struct ARegion {
/* area->flag */
enum {
HEADER_NO_PULLDOWN = (1 << 0),
- AREA_FLAG_DRAWJOINTO = (1 << 1),
- AREA_FLAG_DRAWJOINFROM = (1 << 2),
+// AREA_FLAG_DEPRECATED_1 = (1 << 1),
+// AREA_FLAG_DEPRECATED_2 = (1 << 2),
AREA_TEMP_INFO = (1 << 3),
- AREA_FLAG_DRAWSPLIT_H = (1 << 4),
- AREA_FLAG_DRAWSPLIT_V = (1 << 5),
+// AREA_FLAG_DEPRECATED_4 = (1 << 4),
+// AREA_FLAG_DEPRECATED_5 = (1 << 5),
/* used to check if we should switch back to prevspace (of a different type) */
AREA_FLAG_TEMP_TYPE = (1 << 6),
/* for temporary fullscreens (file browser, image editor render) that are opened above user set fullscreens */
@@ -366,7 +369,7 @@ enum {
/* uiList filter orderby type */
enum {
UILST_FLT_SORT_ALPHA = 1 << 0,
- UILST_FLT_SORT_REVERSE = 1 << 31 /* Special value, bitflag used to reverse order! */
+ UILST_FLT_SORT_REVERSE = 1u << 31 /* Special value, bitflag used to reverse order! */
};
#define UILST_FLT_SORT_MASK (((unsigned int)UILST_FLT_SORT_REVERSE) - 1)
diff --git a/source/blender/makesdna/DNA_sequence_types.h b/source/blender/makesdna/DNA_sequence_types.h
index 1f4e4df4660..b7e118d2053 100644
--- a/source/blender/makesdna/DNA_sequence_types.h
+++ b/source/blender/makesdna/DNA_sequence_types.h
@@ -301,6 +301,11 @@ enum {
SEQ_TEXT_ALIGN_Y_BOTTOM = 2,
};
+typedef struct ColorMixVars {
+ int blend_effect; /* value from SEQ_TYPE_XXX enumeration */
+ float factor; /* blend factor [0.0f, 1.0f] */
+} ColorMixVars;
+
/* ***************** Sequence modifiers ****************** */
typedef struct SequenceModifierData {
@@ -442,7 +447,7 @@ enum {
/* access scene strips directly (like a metastrip) */
SEQ_SCENE_STRIPS = (1 << 30),
- SEQ_INVALID_EFFECT = (1 << 31),
+ SEQ_INVALID_EFFECT = (1u << 31),
};
/* StripProxy->storage */
@@ -516,8 +521,29 @@ enum {
SEQ_TYPE_ADJUSTMENT = 31,
SEQ_TYPE_GAUSSIAN_BLUR = 40,
SEQ_TYPE_TEXT = 41,
-
- SEQ_TYPE_MAX = 41
+ SEQ_TYPE_COLORMIX = 42,
+
+ /* Blend modes */
+ SEQ_TYPE_SCREEN = 43,
+ SEQ_TYPE_LIGHTEN = 44,
+ SEQ_TYPE_DODGE = 45,
+ SEQ_TYPE_DARKEN = 46,
+ SEQ_TYPE_BURN = 47,
+ SEQ_TYPE_LINEAR_BURN = 48,
+ SEQ_TYPE_OVERLAY = 49,
+ SEQ_TYPE_HARD_LIGHT = 50,
+ SEQ_TYPE_SOFT_LIGHT = 51,
+ SEQ_TYPE_PIN_LIGHT = 52,
+ SEQ_TYPE_LIN_LIGHT = 53,
+ SEQ_TYPE_VIVID_LIGHT = 54,
+ SEQ_TYPE_HUE = 55,
+ SEQ_TYPE_SATURATION = 56,
+ SEQ_TYPE_VALUE = 57,
+ SEQ_TYPE_BLEND_COLOR = 58,
+ SEQ_TYPE_DIFFERENCE = 59,
+ SEQ_TYPE_EXCLUSION = 60,
+
+ SEQ_TYPE_MAX = 60
};
#define SEQ_MOVIECLIP_RENDER_UNDISTORTED (1 << 0)
diff --git a/source/blender/makesdna/DNA_smoke_types.h b/source/blender/makesdna/DNA_smoke_types.h
index c95e0a1f54a..c1565bde882 100644
--- a/source/blender/makesdna/DNA_smoke_types.h
+++ b/source/blender/makesdna/DNA_smoke_types.h
@@ -189,7 +189,7 @@ typedef struct SmokeDomainSettings {
char pad[2];
/* Smoke uses only one cache from now on (index [0]), but keeping the array for now for reading old files. */
- struct PointCache *point_cache[2]; /* definition is in DNA_object_force.h */
+ struct PointCache *point_cache[2]; /* definition is in DNA_object_force_types.h */
struct ListBase ptcaches[2];
struct EffectorWeights *effector_weights;
int border_collisions; /* How domain border collisions are handled */
@@ -217,6 +217,9 @@ typedef struct SmokeDomainSettings {
char use_coba;
char coba_field; /* simulation field used for the color mapping */
char pad2;
+
+ float clipping;
+ float pad3;
} SmokeDomainSettings;
diff --git a/source/blender/makesdna/DNA_space_types.h b/source/blender/makesdna/DNA_space_types.h
index 5e015544dc9..693917939ef 100644
--- a/source/blender/makesdna/DNA_space_types.h
+++ b/source/blender/makesdna/DNA_space_types.h
@@ -512,6 +512,9 @@ typedef struct SpaceSeq {
char multiview_eye; /* multiview current eye - for internal use */
char pad2[7];
+
+ struct GPUFX *compositor;
+ void *pad3;
} SpaceSeq;
@@ -664,7 +667,7 @@ typedef struct FSMenuEntry {
} FSMenuEntry;
/* FileSelectParams.display */
-enum FileDisplayTypeE {
+enum eFileDisplayType {
FILE_DEFAULTDISPLAY = 0,
FILE_SHORTDISPLAY = 1,
FILE_LONGDISPLAY = 2,
@@ -672,7 +675,7 @@ enum FileDisplayTypeE {
};
/* FileSelectParams.sort */
-enum FileSortTypeE {
+enum eFileSortType {
FILE_SORT_NONE = 0,
FILE_SORT_ALPHA = 1,
FILE_SORT_EXTENSION = 2,
@@ -704,6 +707,8 @@ typedef enum eFileSel_Action {
} eFileSel_Action;
/* sfile->params->flag and simasel->flag */
+/* Note: short flag, also used as 16 lower bits of flags in link/append code
+ * (WM and BLO code area, see BLO_LibLinkFlags in BLO_readfile.h). */
typedef enum eFileSel_Params_Flag {
FILE_SHOWSHORT = (1 << 0),
FILE_RELPATH = (1 << 1), /* was FILE_STRINGCODE */
@@ -741,7 +746,7 @@ typedef enum eFileSel_File_Types {
FILE_TYPE_ALEMBIC = (1 << 16),
FILE_TYPE_DIR = (1 << 30), /* An FS directory (i.e. S_ISDIR on its path is true). */
- FILE_TYPE_BLENDERLIB = (1 << 31),
+ FILE_TYPE_BLENDERLIB = (1u << 31),
} eFileSel_File_Types;
/* Selection Flags in filesel: struct direntry, unsigned char selflag */
@@ -1151,7 +1156,7 @@ typedef enum eSpaceNode_Flag {
SNODE_SHOW_G = (1 << 8),
SNODE_SHOW_B = (1 << 9),
SNODE_AUTO_RENDER = (1 << 5),
- SNODE_SHOW_HIGHLIGHT = (1 << 6),
+// SNODE_SHOW_HIGHLIGHT = (1 << 6), DNA_DEPRECATED
// SNODE_USE_HIDDEN_PREVIEW = (1 << 10), DNA_DEPRECATED December2013
SNODE_NEW_SHADERS = (1 << 11),
SNODE_PIN = (1 << 12),
diff --git a/source/blender/makesdna/DNA_text_types.h b/source/blender/makesdna/DNA_text_types.h
index 8d1bba6ca4f..163dda678d9 100644
--- a/source/blender/makesdna/DNA_text_types.h
+++ b/source/blender/makesdna/DNA_text_types.h
@@ -51,6 +51,7 @@ typedef struct Text {
ID id;
char *name;
+ void *compiled;
int flags, nlines;
@@ -58,10 +59,6 @@ typedef struct Text {
TextLine *curl, *sell;
int curc, selc;
- char *undo_buf;
- int undo_pos, undo_len;
-
- void *compiled;
double mtime;
} Text;
diff --git a/source/blender/makesdna/DNA_texture_types.h b/source/blender/makesdna/DNA_texture_types.h
index 995d7645dc0..0eb54a9b5b3 100644
--- a/source/blender/makesdna/DNA_texture_types.h
+++ b/source/blender/makesdna/DNA_texture_types.h
@@ -86,7 +86,7 @@ typedef struct MTex {
float timefac, lengthfac, clumpfac, dampfac;
float kinkfac, kinkampfac, roughfac, padensfac, gravityfac;
float lifefac, sizefac, ivelfac, fieldfac;
- int pad2;
+ float twistfac;
/* lamp */
float shadowfac;
diff --git a/source/blender/makesdna/DNA_userdef_types.h b/source/blender/makesdna/DNA_userdef_types.h
index 0ad4482708f..a7759a1d143 100644
--- a/source/blender/makesdna/DNA_userdef_types.h
+++ b/source/blender/makesdna/DNA_userdef_types.h
@@ -48,7 +48,8 @@ struct ColorBand;
#define MAX_STYLE_NAME 64
-/* default uifont_id offered by Blender */
+/* default offered by Blender.
+ * uiFont.uifont_id */
typedef enum eUIFont_ID {
UIFONT_DEFAULT = 0,
/* UIFONT_BITMAP = 1 */ /* UNUSED */
@@ -64,7 +65,7 @@ typedef struct uiFont {
struct uiFont *next, *prev;
char filename[1024];/* 1024 = FILE_MAX */
short blf_id; /* from blfont lib */
- short uifont_id; /* own id */
+ short uifont_id; /* own id (eUIFont_ID) */
short r_to_l; /* fonts that read from left to right */
short hinting;
} uiFont;
@@ -84,7 +85,7 @@ typedef struct uiFontStyle {
float shadowcolor; /* 1 value, typically white or black anyway */
} uiFontStyle;
-/* uiFontStyle->align */
+/* uiFontStyle.align */
typedef enum eFontStyle_Align {
UI_STYLE_TEXT_LEFT = 0,
UI_STYLE_TEXT_CENTER = 1,
@@ -354,11 +355,11 @@ typedef struct ThemeWireColor {
char select[4];
char active[4];
- short flag;
+ short flag; /* eWireColor_Flags */
short pad;
} ThemeWireColor;
-/* flags for ThemeWireColor */
+/* ThemeWireColor.flag */
typedef enum eWireColor_Flags {
TH_WIRECOLOR_CONSTCOLS = (1 << 0),
TH_WIRECOLOR_TEXTCOLS = (1 << 1),
@@ -401,7 +402,6 @@ typedef struct bTheme {
#define UI_THEMESPACE_START(btheme) (CHECK_TYPE_INLINE(btheme, bTheme *), &((btheme)->tbuts))
#define UI_THEMESPACE_END(btheme) (CHECK_TYPE_INLINE(btheme, bTheme *), (&((btheme)->tclip) + 1))
-/* for the moment only the name. may want to store options with this later */
typedef struct bAddon {
struct bAddon *next, *prev;
char module[64];
@@ -434,7 +434,8 @@ typedef struct UserDef {
/* UserDef has separate do-version handling, and can be read from other files */
int versionfile, subversionfile;
- int flag, dupflag;
+ int flag; /* eUserPref_Flag */
+ int dupflag; /* eDupli_ID_Flags */
int savetime;
char tempdir[768]; /* FILE_MAXDIR length */
char fontdir[768];
@@ -450,15 +451,19 @@ typedef struct UserDef {
int anim_player_preset;
short v2d_min_gridsize; /* minimum spacing between gridlines in View2D grids */
- short timecode_style; /* style of timecode display */
+ short timecode_style; /* eTimecodeStyles, style of timecode display */
short versions;
short dbl_click_time;
short gameflags;
short wheellinescroll;
- int uiflag, uiflag2;
- int language;
+ int uiflag; /* eUserpref_UI_Flag */
+ int uiflag2; /* eUserpref_UI_Flag2 */
+ /* Experimental flag for app-templates to make changes to behavior
+ * which are outside the scope of typical preferences. */
+ short app_flag;
+ short language;
short userpref, viewzoom;
int mixbufsize;
@@ -467,13 +472,18 @@ typedef struct UserDef {
int audioformat;
int audiochannels;
- int scrollback; /* console scrollback limit */
- int dpi; /* range 48-128? */
- char node_margin; /* node insert offset (aka auto-offset) margin, but might be useful for later stuff as well */
+ int scrollback; /* console scrollback limit */
+ int dpi; /* range 48-128? */
+ float ui_scale; /* interface scale */
+ int ui_line_width; /* interface line width */
+ char node_margin; /* node insert offset (aka auto-offset) margin, but might be useful for later stuff as well */
char pad2;
- short transopts;
+ short transopts; /* eUserpref_Translation_Flags */
short menuthreshold1, menuthreshold2;
-
+
+ /* startup template */
+ char app_template[64];
+
struct ListBase themes;
struct ListBase uifonts;
struct ListBase uistyles;
@@ -484,20 +494,21 @@ typedef struct UserDef {
char keyconfigstr[64];
short undosteps;
- short undomemory;
+ short pad1;
+ int undomemory;
+ int pad3;
short gp_manhattendist, gp_euclideandist, gp_eraser;
- short gp_settings;
+ short gp_settings; /* eGP_UserdefSettings */
short tb_leftmouse, tb_rightmouse;
struct SolidLight light[3];
short tw_hotspot, tw_flag, tw_handlesize, tw_size;
short textimeout, texcollectrate;
- short wmdrawmethod; /* removed wmpad */
+ short wmdrawmethod; /* eWM_DrawMethod */
short dragthreshold;
int memcachelimit;
int prefetchframes;
float pad_rot_angle; /* control the rotation step of the view when PAD2, PAD4, PAD6&PAD8 is use */
short frameserverport;
- short pad4;
short obcenter_dia;
short rvisize; /* rotating view icon size */
short rvibright; /* rotating view icon brightness */
@@ -505,11 +516,13 @@ typedef struct UserDef {
short smooth_viewtx; /* miliseconds to spend spinning the view */
short glreslimit;
short curssize;
- short color_picker_type;
+ short color_picker_type; /* eColorPicker_Types */
char ipo_new; /* interpolation mode for newly added F-Curves */
char keyhandles_new; /* handle types for newly added keyframes */
char gpu_select_method;
- char view_frame_type;
+ char gpu_select_pick_deph;
+ char pad4;
+ char view_frame_type; /* eZoomFrame_Mode */
int view_frame_keyframes; /* number of keyframes to zoom around current frame */
float view_frame_seconds; /* seconds to zoom around current frame */
@@ -524,15 +537,16 @@ typedef struct UserDef {
float ndof_sensitivity; /* overall sensitivity of 3D mouse */
float ndof_orbit_sensitivity;
float ndof_deadzone; /* deadzone of 3D mouse */
- int ndof_flag; /* flags for 3D mouse */
+ int ndof_flag; /* eNdof_Flag, flags for 3D mouse */
- short ogl_multisamples; /* amount of samples for OpenGL FSA, if zero no FSA */
+ short ogl_multisamples; /* eMultiSample_Type, amount of samples for OpenGL FSA, if zero no FSA */
- short image_draw_method; /* Method to be used to draw the images (AUTO, GLSL, Textures or DrawPixels) */
+ /* eImageDrawMethod, Method to be used to draw the images (AUTO, GLSL, Textures or DrawPixels) */
+ short image_draw_method;
float glalphaclip;
- short autokey_mode; /* autokeying mode */
+ short autokey_mode; /* eAutokey_Mode, autokeying mode */
short autokey_flag; /* flags for autokeying */
short text_render, pad9; /* options for text rendering */
@@ -576,7 +590,7 @@ extern UserDef U; /* from blenkernel blender.c */
/* ***************** USERDEF ****************** */
-/* userpref/section */
+/* UserDef.userpref (UI active_section) */
typedef enum eUserPref_Section {
USER_SECTION_INTERFACE = 0,
USER_SECTION_EDIT = 1,
@@ -587,19 +601,19 @@ typedef enum eUserPref_Section {
USER_SECTION_ADDONS = 6,
} eUserPref_Section;
-/* flag */
+/* UserDef.flag */
typedef enum eUserPref_Flag {
USER_AUTOSAVE = (1 << 0),
-/* USER_AUTOGRABGRID = (1 << 1), deprecated */
-/* USER_AUTOROTGRID = (1 << 2), deprecated */
-/* USER_AUTOSIZEGRID = (1 << 3), deprecated */
+ USER_FLAG_DEPRECATED_1 = (1 << 1), /* cleared */
+ USER_FLAG_DEPRECATED_2 = (1 << 2), /* cleared */
+ USER_FLAG_DEPRECATED_3 = (1 << 3), /* cleared */
USER_SCENEGLOBAL = (1 << 4),
USER_TRACKBALL = (1 << 5),
-/* USER_DUPLILINK = (1 << 6), deprecated */
-/* USER_FSCOLLUM = (1 << 7), deprecated */
+ USER_FLAG_DEPRECATED_6 = (1 << 6), /* cleared */
+ USER_FLAG_DEPRECATED_7 = (1 << 7), /* cleared */
USER_MAT_ON_OB = (1 << 8),
-/* USER_NO_CAPSLOCK = (1 << 9), */ /* not used anywhere */
-/* USER_VIEWMOVE = (1 << 10), */ /* not used anywhere */
+ USER_FLAG_DEPRECATED_9 = (1 << 9), /* cleared */
+ USER_FLAG_DEPRECATED_10 = (1 << 10), /* cleared */
USER_TOOLTIPS = (1 << 11),
USER_TWOBUTTONMOUSE = (1 << 12),
USER_NONUMPAD = (1 << 13),
@@ -618,7 +632,7 @@ typedef enum eUserPref_Flag {
USER_TOOLTIPS_PYTHON = (1 << 26),
} eUserPref_Flag;
-/* flag */
+/* bPathCompare.flag */
typedef enum ePathCompare_Flag {
USER_PATHCMP_GLOB = (1 << 0),
} ePathCompare_Flag;
@@ -629,41 +643,44 @@ typedef enum ePathCompare_Flag {
cfra = 0; \
} (void)0
-/* viewzoom */
+/* UserDef.viewzoom */
typedef enum eViewZoom_Style {
USER_ZOOM_CONT = 0,
USER_ZOOM_SCALE = 1,
USER_ZOOM_DOLLY = 2
} eViewZoom_Style;
-/* navigation_mode */
+/* UserDef.navigation_mode */
typedef enum eViewNavigation_Method {
VIEW_NAVIGATION_WALK = 0,
VIEW_NAVIGATION_FLY = 1,
} eViewNavigation_Method;
-/* flag */
+/* UserDef.flag */
typedef enum eWalkNavigation_Flag {
USER_WALK_GRAVITY = (1 << 0),
USER_WALK_MOUSE_REVERSE = (1 << 1),
} eWalkNavigation_Flag;
-/* uiflag */
+/* UserDef.uiflag */
typedef enum eUserpref_UI_Flag {
/* flags 0 and 1 were old flags (for autokeying) that aren't used anymore */
USER_WHEELZOOMDIR = (1 << 2),
USER_FILTERFILEEXTS = (1 << 3),
USER_DRAWVIEWINFO = (1 << 4),
USER_PLAINMENUS = (1 << 5),
- /* flags 6 and 7 were old flags that are no-longer used */
+ USER_LOCK_CURSOR_ADJUST = (1 << 6),
+ /* Avoid accidentally adjusting the layout
+ * (exact behavior may change based on whats considered reasonable to lock down). */
+ USER_UIFLAG_DEPRECATED_7 = (1 << 7),
USER_ALLWINCODECS = (1 << 8),
USER_MENUOPENAUTO = (1 << 9),
- USER_ZBUF_CURSOR = (1 << 10),
+ USER_DEPTH_CURSOR = (1 << 10),
USER_AUTOPERSP = (1 << 11),
USER_LOCKAROUND = (1 << 12),
USER_GLOBALUNDO = (1 << 13),
USER_ORBIT_SELECTION = (1 << 14),
- USER_ZBUF_ORBIT = (1 << 15),
+ USER_DEPTH_NAVIGATE = (1 << 15),
USER_HIDE_DOT = (1 << 16),
USER_SHOW_ROTVIEWICON = (1 << 17),
USER_SHOW_VIEWPORTNAME = (1 << 18),
@@ -679,17 +696,24 @@ typedef enum eUserpref_UI_Flag {
USER_HIDE_RECENT = (1 << 28),
USER_SHOW_THUMBNAILS = (1 << 29),
USER_QUIT_PROMPT = (1 << 30),
- USER_HIDE_SYSTEM_BOOKMARKS = (1 << 31)
+ USER_HIDE_SYSTEM_BOOKMARKS = (1u << 31)
} eUserpref_UI_Flag;
-/* uiflag2 */
+/* UserDef.uiflag2 */
typedef enum eUserpref_UI_Flag2 {
USER_KEEP_SESSION = (1 << 0),
USER_REGION_OVERLAP = (1 << 1),
USER_TRACKPAD_NATURAL = (1 << 2),
} eUserpref_UI_Flag2;
-
-/* Auto-Keying mode */
+
+/* UserDef.app_flag */
+typedef enum eUserpref_APP_Flag {
+ USER_APP_LOCK_UI_LAYOUT = (1 << 0),
+ USER_APP_VIEW3D_HIDE_CURSOR = (1 << 1),
+} eUserpref_APP_Flag;
+
+/* Auto-Keying mode.
+ * UserDef.autokey_mode */
typedef enum eAutokey_Mode {
/* AUTOKEY_ON is a bitflag */
AUTOKEY_ON = 1,
@@ -699,7 +723,8 @@ typedef enum eAutokey_Mode {
AUTOKEY_MODE_EDITKEYS = 5
} eAutokey_Mode;
-/* Zoom to frame mode */
+/* Zoom to frame mode.
+ * UserDef.view_frame_type */
typedef enum eZoomFrame_Mode {
ZOOM_FRAME_MODE_KEEP_RANGE = 0,
ZOOM_FRAME_MODE_SECONDS = 1,
@@ -722,20 +747,20 @@ typedef enum eAutokey_Flag {
ANIMRECORD_FLAG_WITHNLA = (1 << 10),
} eAutokey_Flag;
-/* transopts */
+/* UserDef.transopts */
typedef enum eUserpref_Translation_Flags {
USER_TR_TOOLTIPS = (1 << 0),
USER_TR_IFACE = (1 << 1),
-/* USER_TR_MENUS = (1 << 2), deprecated */
-/* USER_TR_FILESELECT = (1 << 3), deprecated */
-/* USER_TR_TEXTEDIT = (1 << 4), deprecated */
+ USER_TR_DEPRECATED_2 = (1 << 2), /* cleared */
+ USER_TR_DEPRECATED_3 = (1 << 3), /* cleared */
+ USER_TR_DEPRECATED_4 = (1 << 4), /* cleared */
USER_DOTRANSLATE = (1 << 5),
- USER_USETEXTUREFONT = (1 << 6),
-/* CONVERT_TO_UTF8 = (1 << 7), deprecated */
+ USER_TR_DEPRECATED_6 = (1 << 6), /* cleared */
+ USER_TR_DEPRECATED_7 = (1 << 7), /* cleared */
USER_TR_NEWDATANAME = (1 << 8),
} eUserpref_Translation_Flags;
-/* dupflag */
+/* UserDef.dupflag */
typedef enum eDupli_ID_Flags {
USER_DUP_MESH = (1 << 0),
USER_DUP_CURVE = (1 << 1),
@@ -751,14 +776,13 @@ typedef enum eDupli_ID_Flags {
USER_DUP_PSYS = (1 << 11)
} eDupli_ID_Flags;
-/* gameflags */
+/* UserDef.gameflags */
typedef enum eOpenGL_RenderingOptions {
- /* USER_DEPRECATED_FLAG = (1 << 0), */
- /* USER_DISABLE_SOUND = (1 << 1), */ /* deprecated, don't use without checking for */
- /* backwards compatibilty in do_versions! */
- USER_DISABLE_MIPMAP = (1 << 2),
- /* USER_DISABLE_VBO = (1 << 3), */ /* DEPRECATED we always use vertex buffers now */
- /* USER_DISABLE_AA = (1 << 4), */ /* DEPRECATED */
+ USER_GL_RENDER_DEPRECATED_0 = (1 << 0),
+ USER_GL_RENDER_DEPRECATED_1 = (1 << 1),
+ USER_DISABLE_MIPMAP = (1 << 2),
+ USER_GL_RENDER_DEPRECATED_3 = (1 << 3),
+ USER_GL_RENDER_DEPRECATED_4 = (1 << 4),
} eOpenGL_RenderingOptions;
/* selection method for opengl gpu_select_method */
@@ -768,7 +792,8 @@ typedef enum eOpenGL_SelectOptions {
USER_SELECT_USE_SELECT_RENDERMODE = 2
} eOpenGL_SelectOptions;
-/* wm draw method */
+/* wm draw method.
+ * UserDef.wmdrawmethod */
typedef enum eWM_DrawMethod {
USER_DRAW_TRIPLE = 0,
USER_DRAW_OVERLAP = 1,
@@ -777,20 +802,23 @@ typedef enum eWM_DrawMethod {
USER_DRAW_OVERLAP_FLIP = 4,
} eWM_DrawMethod;
-/* text draw options */
+/* text draw options
+ * UserDef.text_render */
typedef enum eText_Draw_Options {
USER_TEXT_DISABLE_AA = (1 << 0),
} eText_Draw_Options;
/* tw_flag (transform widget) */
-/* gp_settings (Grease Pencil Settings) */
+/* Grease Pencil Settings.
+ * UserDef.gp_settings */
typedef enum eGP_UserdefSettings {
GP_PAINT_DOSMOOTH = (1 << 0),
GP_PAINT_DOSIMPLIFY = (1 << 1),
} eGP_UserdefSettings;
-/* color picker types */
+/* Color Picker Types.
+ * UserDef.color_picker_type */
typedef enum eColorPicker_Types {
USER_CP_CIRCLE_HSV = 0,
USER_CP_SQUARE_SV = 1,
@@ -799,7 +827,8 @@ typedef enum eColorPicker_Types {
USER_CP_CIRCLE_HSL = 4,
} eColorPicker_Types;
-/* timecode display styles */
+/* timecode display styles
+ * UserDef.timecode_style */
typedef enum eTimecodeStyles {
/* as little info as is necessary to show relevant info
* with '+' to denote the frames
@@ -834,7 +863,7 @@ typedef enum eTheme_DrawTypes {
TH_SHADED = 4
} eTheme_DrawTypes;
-/* ndof_flag (3D mouse options) */
+/* UserDef.ndof_flag (3D mouse options) */
typedef enum eNdof_Flag {
NDOF_SHOW_GUIDE = (1 << 0),
NDOF_FLY_HELICOPTER = (1 << 1),
@@ -867,6 +896,7 @@ typedef enum eNdof_Flag {
#define NDOF_PIXELS_PER_SECOND 600.0f
+/* UserDef.ogl_multisamples */
typedef enum eMultiSample_Type {
USER_MULTISAMPLE_NONE = 0,
USER_MULTISAMPLE_2 = 2,
@@ -874,7 +904,8 @@ typedef enum eMultiSample_Type {
USER_MULTISAMPLE_8 = 8,
USER_MULTISAMPLE_16 = 16,
} eMultiSample_Type;
-
+
+/* UserDef.image_draw_method */
typedef enum eImageDrawMethod {
/* IMAGE_DRAW_METHOD_AUTO = 0, */ /* Currently unused */
IMAGE_DRAW_METHOD_GLSL = 1,
@@ -882,6 +913,7 @@ typedef enum eImageDrawMethod {
IMAGE_DRAW_METHOD_DRAWPIXELS = 3,
} eImageDrawMethod;
+/* UserDef.virtual_pixel */
typedef enum eUserpref_VirtualPixel {
VIRTUAL_PIXEL_NATIVE = 0,
VIRTUAL_PIXEL_DOUBLE = 1,
diff --git a/source/blender/makesdna/DNA_view2d_types.h b/source/blender/makesdna/DNA_view2d_types.h
index 6f2e347c84d..3319fed8cdd 100644
--- a/source/blender/makesdna/DNA_view2d_types.h
+++ b/source/blender/makesdna/DNA_view2d_types.h
@@ -67,90 +67,101 @@ typedef struct View2D {
/* animated smooth view */
struct SmoothView2DStore *sms;
struct wmTimer *smooth_timer;
-
} View2D;
/* ---------------------------------- */
/* view zooming restrictions, per axis (v2d->keepzoom) */
+enum {
/* zoom is clamped to lie within limits set by minzoom and maxzoom */
-#define V2D_LIMITZOOM 0x0001
+ V2D_LIMITZOOM = (1 << 0),
/* aspect ratio is maintained on view resize */
-#define V2D_KEEPASPECT 0x0002
+ V2D_KEEPASPECT = (1 << 1),
/* zoom is kept when the window resizes */
-#define V2D_KEEPZOOM 0x0004
+ V2D_KEEPZOOM = (1 << 2),
/* zooming on x-axis is not allowed */
-#define V2D_LOCKZOOM_X 0x0100
+ V2D_LOCKZOOM_X = (1 << 8),
/* zooming on y-axis is not allowed */
-#define V2D_LOCKZOOM_Y 0x0200
+ V2D_LOCKZOOM_Y = (1 << 9),
+};
/* view panning restrictions, per axis (v2d->keepofs) */
+enum {
/* panning on x-axis is not allowed */
-#define V2D_LOCKOFS_X (1<<1)
+ V2D_LOCKOFS_X = (1 << 1),
/* panning on y-axis is not allowed */
-#define V2D_LOCKOFS_Y (1<<2)
+ V2D_LOCKOFS_Y = (1 << 2),
/* on resize, keep the x offset */
-#define V2D_KEEPOFS_X (1<<3)
+ V2D_KEEPOFS_X = (1 << 3),
/* on resize, keep the y offset */
-#define V2D_KEEPOFS_Y (1<<4)
+ V2D_KEEPOFS_Y = (1 << 4),
+};
/* view extent restrictions (v2d->keeptot) */
+enum {
/* 'cur' view can be out of extents of 'tot' */
-#define V2D_KEEPTOT_FREE 0
+ V2D_KEEPTOT_FREE = 0,
/* 'cur' rect is adjusted so that it satisfies the extents of 'tot', with some compromises */
-#define V2D_KEEPTOT_BOUNDS 1
+ V2D_KEEPTOT_BOUNDS = 1,
/* 'cur' rect is moved so that the 'minimum' bounds of the 'tot' rect are always respected (particularly in x-axis) */
-#define V2D_KEEPTOT_STRICT 2
+ V2D_KEEPTOT_STRICT = 2,
+};
/* general refresh settings (v2d->flag) */
+enum {
/* global view2d horizontal locking (for showing same time interval) */
/* TODO: this flag may be set in old files but is not accessible currently, should be exposed from RNA - Campbell */
-#define V2D_VIEWSYNC_SCREEN_TIME (1<<0)
+ V2D_VIEWSYNC_SCREEN_TIME = (1 << 0),
/* within area (i.e. between regions) view2d vertical locking */
-#define V2D_VIEWSYNC_AREA_VERTICAL (1<<1)
+ V2D_VIEWSYNC_AREA_VERTICAL = (1 << 1),
/* apply pixel offsets on x-axis when setting view matrices */
-#define V2D_PIXELOFS_X (1<<2)
+ V2D_PIXELOFS_X = (1 << 2),
/* apply pixel offsets on y-axis when setting view matrices */
-#define V2D_PIXELOFS_Y (1<<3)
+ V2D_PIXELOFS_Y = (1 << 3),
/* view settings need to be set still... */
-#define V2D_IS_INITIALISED (1<<10)
+ V2D_IS_INITIALISED = (1 << 10),
+};
/* scroller flags for View2D (v2d->scroll) */
+enum {
/* left scrollbar */
-#define V2D_SCROLL_LEFT (1<<0)
-#define V2D_SCROLL_RIGHT (1<<1)
-#define V2D_SCROLL_VERTICAL (V2D_SCROLL_LEFT|V2D_SCROLL_RIGHT)
+ V2D_SCROLL_LEFT = (1 << 0),
+ V2D_SCROLL_RIGHT = (1 << 1),
+ V2D_SCROLL_VERTICAL = (V2D_SCROLL_LEFT | V2D_SCROLL_RIGHT),
/* horizontal scrollbar */
-#define V2D_SCROLL_TOP (1<<2)
-#define V2D_SCROLL_BOTTOM (1<<3)
-
-/* UNUSED (1<<4) */
-#define V2D_SCROLL_HORIZONTAL (V2D_SCROLL_TOP|V2D_SCROLL_BOTTOM)
+ V2D_SCROLL_TOP = (1 << 2),
+ V2D_SCROLL_BOTTOM = (1 << 3),
+ /* UNUSED = (1 << 4), */
+ V2D_SCROLL_HORIZONTAL = (V2D_SCROLL_TOP | V2D_SCROLL_BOTTOM),
/* scale markings - vertical */
-#define V2D_SCROLL_SCALE_VERTICAL (1<<5)
+ V2D_SCROLL_SCALE_VERTICAL = (1 << 5),
/* scale markings - horizontal */
-#define V2D_SCROLL_SCALE_HORIZONTAL (1<<6)
+ V2D_SCROLL_SCALE_HORIZONTAL = (1 << 6),
/* induce hiding of scrollbars - set by region drawing in response to size of region */
-#define V2D_SCROLL_VERTICAL_HIDE (1<<7)
-#define V2D_SCROLL_HORIZONTAL_HIDE (1<<8)
+ V2D_SCROLL_VERTICAL_HIDE = (1 << 7),
+ V2D_SCROLL_HORIZONTAL_HIDE = (1 << 8),
/* scrollbar extends beyond its available window - set when calculating scrollbars for drawing */
-#define V2D_SCROLL_VERTICAL_FULLR (1<<9)
-#define V2D_SCROLL_HORIZONTAL_FULLR (1<<10)
+ V2D_SCROLL_VERTICAL_FULLR = (1 << 9),
+ V2D_SCROLL_HORIZONTAL_FULLR = (1 << 10),
+};
/* scroll_ui, activate flag for drawing */
-#define V2D_SCROLL_H_ACTIVE (1<<0)
-#define V2D_SCROLL_V_ACTIVE (1<<1)
+enum {
+ V2D_SCROLL_H_ACTIVE = (1 << 0),
+ V2D_SCROLL_V_ACTIVE = (1 << 1),
+};
/* alignment flags for totrect, flags use 'shading-out' convention (v2d->align) */
+enum {
/* all quadrants free */
-#define V2D_ALIGN_FREE 0
+ V2D_ALIGN_FREE = 0,
/* horizontal restrictions */
-#define V2D_ALIGN_NO_POS_X (1<<0)
-#define V2D_ALIGN_NO_NEG_X (1<<1)
+ V2D_ALIGN_NO_POS_X = (1 << 0),
+ V2D_ALIGN_NO_NEG_X = (1 << 1),
/* vertical restrictions */
-#define V2D_ALIGN_NO_POS_Y (1<<2)
-#define V2D_ALIGN_NO_NEG_Y (1<<3)
-
+ V2D_ALIGN_NO_POS_Y = (1 << 2),
+ V2D_ALIGN_NO_NEG_Y = (1 << 3),
+};
#endif
diff --git a/source/blender/makesdna/DNA_view3d_types.h b/source/blender/makesdna/DNA_view3d_types.h
index 4c243507e82..b9894d46b5b 100644
--- a/source/blender/makesdna/DNA_view3d_types.h
+++ b/source/blender/makesdna/DNA_view3d_types.h
@@ -225,7 +225,8 @@ typedef struct View3D {
struct GPUFXSettings fx_settings;
void *properties_storage; /* Nkey panel stores stuff here (runtime only!) */
- struct Material *defmaterial; /* used by matcap now */
+ /* Allocated per view, not library data (used by matcap). */
+ struct Material *defmaterial;
/* XXX deprecated? */
struct bGPdata *gpd DNA_DEPRECATED; /* Grease-Pencil Data (annotation layers) */
diff --git a/source/blender/makesdna/DNA_windowmanager_types.h b/source/blender/makesdna/DNA_windowmanager_types.h
index 14400c84b69..20470ba862e 100644
--- a/source/blender/makesdna/DNA_windowmanager_types.h
+++ b/source/blender/makesdna/DNA_windowmanager_types.h
@@ -58,6 +58,7 @@ struct ReportList;
struct Report;
struct uiLayout;
struct Stereo3dFormat;
+struct UndoStep;
#define OP_MAX_TYPENAME 64
#define KMAP_MAX_NAME 64
@@ -154,6 +155,8 @@ typedef struct wmWindowManager {
ListBase timers; /* active timers */
struct wmTimer *autosavetimer; /* timer for auto save */
+ struct UndoStack *undo_stack; /* all undo history (runtime only). */
+
char is_interface_locked; /* indicates whether interface is locked for user interaction */
char par[7];
} wmWindowManager;
@@ -220,6 +223,9 @@ typedef struct wmWindow {
ListBase gesture; /* gesture stuff */
struct Stereo3dFormat *stereo3d_format; /* properties for stereoscopic displays */
+
+ /* custom drawing callbacks */
+ ListBase drawcalls;
} wmWindow;
#ifdef ime_data
@@ -310,8 +316,10 @@ typedef struct wmKeyMap {
short kmi_id; /* last kmi id */
/* runtime */
- int (*poll)(struct bContext *); /* verify if enabled in the current context */
- void *modal_items; /* for modal, EnumPropertyItem for now */
+ /** Verify if enabled in the current context, use #WM_keymap_poll instead of direct calls. */
+ int (*poll)(struct bContext *);
+ /** For modal, #EnumPropertyItem for now. */
+ const void *modal_items;
} wmKeyMap;
/* wmKeyMap.flag */
@@ -395,13 +403,15 @@ enum {
/* low level flag so exec() operators can tell if they were invoked, use with care.
* typically this shouldn't make any difference, but it rare cases its needed (see smooth-view) */
OP_IS_INVOKE = (1 << 0),
+ /* So we can detect if an operators exec() call is activated from an interactive repeat. */
+ OP_IS_REPEAT = (1 << 1),
/* When the cursor is grabbed */
- OP_IS_MODAL_GRAB_CURSOR = (1 << 1),
+ OP_IS_MODAL_GRAB_CURSOR = (1 << 2),
/* allow modal operators to have the region under the cursor for their context
* (the regiontype is maintained to prevent errors) */
- OP_IS_MODAL_CURSOR_REGION = (1 << 2),
+ OP_IS_MODAL_CURSOR_REGION = (1 << 3),
};
#endif /* __DNA_WINDOWMANAGER_TYPES_H__ */
diff --git a/source/blender/makesdna/intern/CMakeLists.txt b/source/blender/makesdna/intern/CMakeLists.txt
index 8c758c33dc5..5b8dcd97108 100644
--- a/source/blender/makesdna/intern/CMakeLists.txt
+++ b/source/blender/makesdna/intern/CMakeLists.txt
@@ -107,6 +107,7 @@ set(INC_SYS
set(SRC
../../blenlib/intern/BLI_ghash.c
+ ../../blenlib/intern/BLI_ghash_utils.c
../../blenlib/intern/BLI_mempool.c
../../blenlib/intern/endian_switch.c
../../blenlib/intern/hash_mm2a.c
diff --git a/source/blender/makesdna/intern/dna_genfile.c b/source/blender/makesdna/intern/dna_genfile.c
index 181d01e04fc..2e21223d042 100644
--- a/source/blender/makesdna/intern/dna_genfile.c
+++ b/source/blender/makesdna/intern/dna_genfile.c
@@ -57,7 +57,7 @@
* \section dna_genfile Overview
*
* - please note: no builtin security to detect input of double structs
- * - if you want a struct not to be in DNA file: add two hash marks above it (#<enter>#<enter>)
+ * - if you want a struct not to be in DNA file: add two hash marks above it `(#<enter>#<enter>)`.
*
* Structure DNA data is added to each blender file and to each executable, this to detect
* in .blend files new variables in structs, changed array sizes, etc. It's also used for
@@ -173,7 +173,9 @@ void DNA_sdna_free(SDNA *sdna)
MEM_freeN(sdna->structs);
#ifdef WITH_DNA_GHASH
- BLI_ghash_free(sdna->structs_map, NULL, NULL);
+ if (sdna->structs_map) {
+ BLI_ghash_free(sdna->structs_map, NULL, NULL);
+ }
#endif
MEM_freeN(sdna);
diff --git a/source/blender/makesdna/intern/makesdna.c b/source/blender/makesdna/intern/makesdna.c
index 2cea8715a65..a5f474b93bf 100644
--- a/source/blender/makesdna/intern/makesdna.c
+++ b/source/blender/makesdna/intern/makesdna.c
@@ -86,8 +86,8 @@ static const char *includefiles[] = {
"DNA_modifier_types.h",
"DNA_lattice_types.h",
"DNA_object_types.h",
- "DNA_object_force.h",
- "DNA_object_fluidsim.h",
+ "DNA_object_force_types.h",
+ "DNA_object_fluidsim_types.h",
"DNA_world_types.h",
"DNA_scene_types.h",
"DNA_view3d_types.h",
@@ -464,7 +464,7 @@ static int preprocess_include(char *maindata, int len)
if (cp[0] == '/' && cp[1] == '/') {
comment = 1;
}
- else if (*cp < 32) {
+ else if (*cp == '\n') {
comment = 0;
}
if (comment || *cp < 32 || *cp > 128) *cp = 32;
@@ -562,9 +562,10 @@ static int convert_include(const char *filename)
/* read include file, skip structs with a '#' before it.
* store all data in temporal arrays.
*/
- int filelen, count, overslaan, slen, type, name, strct;
+ int filelen, count, slen, type, name, strct;
short *structpoin, *sp;
char *maindata, *mainend, *md, *md1;
+ bool skip_struct;
md = maindata = read_file_data(filename, &filelen);
if (filelen == -1) {
@@ -577,18 +578,18 @@ static int convert_include(const char *filename)
/* we look for '{' and then back to 'struct' */
count = 0;
- overslaan = 0;
+ skip_struct = false;
while (count < filelen) {
/* code for skipping a struct: two hashes on 2 lines. (preprocess added a space) */
if (md[0] == '#' && md[1] == ' ' && md[2] == '#') {
- overslaan = 1;
+ skip_struct = true;
}
if (md[0] == '{') {
md[0] = 0;
- if (overslaan) {
- overslaan = 0;
+ if (skip_struct) {
+ skip_struct = false;
}
else {
if (md[-1] == ' ') md[-1] = 0;
@@ -978,7 +979,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs
char str[SDNA_MAX_FILENAME_LENGTH], *cp;
int firststruct;
- if (debugSDNA > -1) {
+ if (debugSDNA > 0) {
fflush(stdout);
printf("Running makesdna at debug level %d\n", debugSDNA);
}
@@ -1074,7 +1075,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs
/* file writing */
- if (debugSDNA > -1) printf("Writing file ... ");
+ if (debugSDNA > 0) printf("Writing file ... ");
if (nr_names == 0 || nr_structs == 0) {
/* pass */
@@ -1184,7 +1185,7 @@ static int make_structDNA(const char *baseDirectory, FILE *file, FILE *file_offs
MEM_freeN(typelens_64);
MEM_freeN(structs);
- if (debugSDNA > -1) printf("done.\n");
+ if (debugSDNA > 0) printf("done.\n");
return(0);
}
@@ -1298,8 +1299,8 @@ int main(int argc, char **argv)
#include "DNA_modifier_types.h"
#include "DNA_lattice_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_force_types.h"
+#include "DNA_object_fluidsim_types.h"
#include "DNA_world_types.h"
#include "DNA_scene_types.h"
#include "DNA_view3d_types.h"
diff --git a/source/blender/makesrna/RNA_access.h b/source/blender/makesrna/RNA_access.h
index 66e6f30feeb..e512aebfa71 100644
--- a/source/blender/makesrna/RNA_access.h
+++ b/source/blender/makesrna/RNA_access.h
@@ -117,6 +117,7 @@ extern StructRNA RNA_ColorManagedViewSettings;
extern StructRNA RNA_ColorRamp;
extern StructRNA RNA_ColorRampElement;
extern StructRNA RNA_ColorSequence;
+extern StructRNA RNA_ColorMixSequence;
extern StructRNA RNA_CompositorNode;
extern StructRNA RNA_CompositorNodeAlphaOver;
extern StructRNA RNA_CompositorNodeBilateralblur;
@@ -131,6 +132,7 @@ extern StructRNA RNA_CompositorNodeCombRGBA;
extern StructRNA RNA_CompositorNodeCombYCCA;
extern StructRNA RNA_CompositorNodeCombYUVA;
extern StructRNA RNA_CompositorNodeComposite;
+extern StructRNA RNA_CompositorNodeCornerPin;
extern StructRNA RNA_CompositorNodeCrop;
extern StructRNA RNA_CompositorNodeCurveRGB;
extern StructRNA RNA_CompositorNodeCurveVec;
@@ -174,6 +176,7 @@ extern StructRNA RNA_CompositorNodeSepYCCA;
extern StructRNA RNA_CompositorNodeSepYUVA;
extern StructRNA RNA_CompositorNodeSetAlpha;
extern StructRNA RNA_CompositorNodeSplitViewer;
+extern StructRNA RNA_CompositorNodeSunBeams;
extern StructRNA RNA_CompositorNodeSwitchView;
extern StructRNA RNA_CompositorNodeTexture;
extern StructRNA RNA_CompositorNodeTime;
@@ -488,7 +491,6 @@ extern StructRNA RNA_PropertyGroupItem;
extern StructRNA RNA_PropertySensor;
extern StructRNA RNA_PythonConstraint;
extern StructRNA RNA_PythonController;
-extern StructRNA RNA_QuickTimeSettings;
extern StructRNA RNA_RadarSensor;
extern StructRNA RNA_RandomSensor;
extern StructRNA RNA_RaySensor;
@@ -598,6 +600,7 @@ extern StructRNA RNA_StucciTexture;
extern StructRNA RNA_SubsurfModifier;
extern StructRNA RNA_SunLamp;
extern StructRNA RNA_SurfaceCurve;
+extern StructRNA RNA_SurfaceDeformModifier;
extern StructRNA RNA_SurfaceModifier;
extern StructRNA RNA_TexMapping;
extern StructRNA RNA_Text;
@@ -721,6 +724,7 @@ extern StructRNA RNA_XorController;
void RNA_main_pointer_create(struct Main *main, PointerRNA *r_ptr);
void RNA_id_pointer_create(struct ID *id, PointerRNA *r_ptr);
void RNA_pointer_create(struct ID *id, StructRNA *type, void *data, PointerRNA *r_ptr);
+bool RNA_pointer_is_null(const PointerRNA *ptr);
bool RNA_path_resolved_create(
PointerRNA *ptr, struct PropertyRNA *prop,
@@ -744,9 +748,11 @@ const char *RNA_struct_ui_description_raw(const StructRNA *type);
const char *RNA_struct_translation_context(const StructRNA *type);
int RNA_struct_ui_icon(const StructRNA *type);
-PropertyRNA *RNA_struct_name_property(StructRNA *type);
+PropertyRNA *RNA_struct_name_property(const StructRNA *type);
+const EnumPropertyItem *RNA_struct_property_tag_defines(const StructRNA *type);
PropertyRNA *RNA_struct_iterator_property(StructRNA *type);
StructRNA *RNA_struct_base(StructRNA *type);
+const StructRNA *RNA_struct_base_child_of(const StructRNA *type, const StructRNA *parent_type);
bool RNA_struct_is_ID(const StructRNA *type);
bool RNA_struct_is_a(const StructRNA *type, const StructRNA *srna);
@@ -766,10 +772,13 @@ void RNA_struct_blender_type_set(StructRNA *srna, void *blender_type);
struct IDProperty *RNA_struct_idprops(PointerRNA *ptr, bool create);
bool RNA_struct_idprops_check(StructRNA *srna);
bool RNA_struct_idprops_register_check(const StructRNA *type);
+bool RNA_struct_idprops_datablock_allowed(const StructRNA *type);
+bool RNA_struct_idprops_contains_datablock(const StructRNA *type);
bool RNA_struct_idprops_unset(PointerRNA *ptr, const char *identifier);
PropertyRNA *RNA_struct_find_property(PointerRNA *ptr, const char *identifier);
bool RNA_struct_contains_property(PointerRNA *ptr, PropertyRNA *prop_test);
+unsigned int RNA_struct_count_properties(StructRNA *srna);
/* lower level functions for access to type properties */
const struct ListBase *RNA_struct_type_properties(StructRNA *srna);
@@ -780,6 +789,9 @@ const struct ListBase *RNA_struct_type_functions(StructRNA *srna);
char *RNA_struct_name_get_alloc(PointerRNA *ptr, char *fixedbuf, int fixedlen, int *r_len);
+bool RNA_struct_available_or_report(struct ReportList *reports, const char *identifier);
+bool RNA_struct_bl_idname_ok_or_report(struct ReportList *reports, const char *identifier, const char *sep);
+
/* Properties
*
* Access to struct properties. All this works with RNA pointers rather than
@@ -794,6 +806,7 @@ PropertyType RNA_property_type(PropertyRNA *prop);
PropertySubType RNA_property_subtype(PropertyRNA *prop);
PropertyUnit RNA_property_unit(PropertyRNA *prop);
int RNA_property_flag(PropertyRNA *prop);
+int RNA_property_tags(PropertyRNA *prop);
bool RNA_property_builtin(PropertyRNA *prop);
void *RNA_property_py_data_get(PropertyRNA *prop);
@@ -824,22 +837,26 @@ void RNA_property_float_ui_range(PointerRNA *ptr, PropertyRNA *prop, float *soft
int RNA_property_float_clamp(PointerRNA *ptr, PropertyRNA *prop, float *value);
int RNA_property_int_clamp(PointerRNA *ptr, PropertyRNA *prop, int *value);
-bool RNA_enum_identifier(EnumPropertyItem *item, const int value, const char **identifier);
-int RNA_enum_bitflag_identifiers(EnumPropertyItem *item, const int value, const char **identifier);
-bool RNA_enum_name(EnumPropertyItem *item, const int value, const char **r_name);
-bool RNA_enum_description(EnumPropertyItem *item, const int value, const char **description);
-int RNA_enum_from_value(EnumPropertyItem *item, const int value);
-int RNA_enum_from_identifier(EnumPropertyItem *item, const char *identifier);
+bool RNA_enum_identifier(const EnumPropertyItem *item, const int value, const char **identifier);
+int RNA_enum_bitflag_identifiers(const EnumPropertyItem *item, const int value, const char **identifier);
+bool RNA_enum_name(const EnumPropertyItem *item, const int value, const char **r_name);
+bool RNA_enum_description(const EnumPropertyItem *item, const int value, const char **description);
+int RNA_enum_from_value(const EnumPropertyItem *item, const int value);
+int RNA_enum_from_identifier(const EnumPropertyItem *item, const char *identifier);
+unsigned int RNA_enum_items_count(const EnumPropertyItem *item);
void RNA_property_enum_items_ex(
struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, const bool use_static,
- EnumPropertyItem **item, int *r_totitem, bool *r_free);
-void RNA_property_enum_items(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
- EnumPropertyItem **item, int *r_totitem, bool *r_free);
-void RNA_property_enum_items_gettexted(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
- EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
-void RNA_property_enum_items_gettexted_all(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
- EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
+void RNA_property_enum_items(
+ struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
+void RNA_property_enum_items_gettexted(
+ struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
+void RNA_property_enum_items_gettexted_all(
+ struct bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free);
bool RNA_property_enum_value(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, const char *identifier, int *r_value);
bool RNA_property_enum_identifier(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **identifier);
bool RNA_property_enum_name(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **name);
@@ -910,6 +927,7 @@ float RNA_property_float_get_default_index(PointerRNA *ptr, PropertyRNA *prop, i
void RNA_property_string_get(PointerRNA *ptr, PropertyRNA *prop, char *value);
char *RNA_property_string_get_alloc(PointerRNA *ptr, PropertyRNA *prop, char *fixedbuf, int fixedlen, int *r_len);
void RNA_property_string_set(PointerRNA *ptr, PropertyRNA *prop, const char *value);
+void RNA_property_string_set_bytes(PointerRNA *ptr, PropertyRNA *prop, const char *value, int len);
int RNA_property_string_length(PointerRNA *ptr, PropertyRNA *prop);
void RNA_property_string_get_default(PointerRNA *ptr, PropertyRNA *prop, char *value);
char *RNA_property_string_get_default_alloc(PointerRNA *ptr, PropertyRNA *prop, char *fixedbuf, int fixedlen);
@@ -1037,10 +1055,10 @@ void RNA_enum_set_identifier(struct bContext *C, PointerRNA *ptr, const char *na
bool RNA_enum_is_equal(struct bContext *C, PointerRNA *ptr, const char *name, const char *enumname);
/* lower level functions that don't use a PointerRNA */
-bool RNA_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *r_value);
-bool RNA_enum_id_from_value(EnumPropertyItem *item, int value, const char **r_identifier);
-bool RNA_enum_icon_from_value(EnumPropertyItem *item, int value, int *r_icon);
-bool RNA_enum_name_from_value(EnumPropertyItem *item, int value, const char **r_name);
+bool RNA_enum_value_from_id(const EnumPropertyItem *item, const char *identifier, int *r_value);
+bool RNA_enum_id_from_value(const EnumPropertyItem *item, int value, const char **r_identifier);
+bool RNA_enum_icon_from_value(const EnumPropertyItem *item, int value, int *r_icon);
+bool RNA_enum_name_from_value(const EnumPropertyItem *item, int value, const char **r_name);
void RNA_string_get(PointerRNA *ptr, const char *name, char *value);
char *RNA_string_get_alloc(PointerRNA *ptr, const char *name, char *fixedbuf, int fixedlen);
@@ -1111,7 +1129,7 @@ bool RNA_property_is_set(PointerRNA *ptr, PropertyRNA *prop);
void RNA_property_unset(PointerRNA *ptr, PropertyRNA *prop);
bool RNA_struct_property_is_set_ex(PointerRNA *ptr, const char *identifier, bool use_ghost);
bool RNA_struct_property_is_set(PointerRNA *ptr, const char *identifier);
-bool RNA_property_is_idprop(PropertyRNA *prop);
+bool RNA_property_is_idprop(const PropertyRNA *prop);
bool RNA_property_is_unlink(PropertyRNA *prop);
void RNA_struct_property_unset(PointerRNA *ptr, const char *identifier);
@@ -1180,9 +1198,12 @@ int RNA_function_call_direct_va(struct bContext *C, struct ReportList *reports,
int RNA_function_call_direct_va_lookup(struct bContext *C, struct ReportList *reports, PointerRNA *ptr,
const char *identifier, const char *format, va_list args);
+const char *RNA_translate_ui_text(
+ const char *text, const char *text_ctxt, struct StructRNA *type, struct PropertyRNA *prop, int translate);
+
/* ID */
-short RNA_type_to_ID_code(StructRNA *type);
+short RNA_type_to_ID_code(const StructRNA *type);
StructRNA *ID_code_to_RNA_type(short idcode);
@@ -1194,7 +1215,7 @@ StructRNA *ID_code_to_RNA_type(short idcode);
} (void)0
/* macro which inserts the function name */
-#if defined __GNUC__ || defined __sun
+#if defined __GNUC__
# define RNA_warning(format, args ...) _RNA_warning("%s: " format "\n", __func__, ##args)
#else
# define RNA_warning(format, ...) _RNA_warning("%s: " format "\n", __FUNCTION__, __VA_ARGS__)
diff --git a/source/blender/makesrna/RNA_define.h b/source/blender/makesrna/RNA_define.h
index 2a680b6eaeb..5f71f2ccdcf 100644
--- a/source/blender/makesrna/RNA_define.h
+++ b/source/blender/makesrna/RNA_define.h
@@ -58,11 +58,13 @@ void RNA_def_struct_name_property(StructRNA *srna, PropertyRNA *prop);
void RNA_def_struct_nested(BlenderRNA *brna, StructRNA *srna, const char *structname);
void RNA_def_struct_flag(StructRNA *srna, int flag);
void RNA_def_struct_clear_flag(StructRNA *srna, int flag);
+void RNA_def_struct_property_tags(StructRNA *srna, const EnumPropertyItem *prop_tag_defines);
void RNA_def_struct_refine_func(StructRNA *srna, const char *refine);
void RNA_def_struct_idprops_func(StructRNA *srna, const char *refine);
void RNA_def_struct_register_funcs(StructRNA *srna, const char *reg, const char *unreg, const char *instance);
void RNA_def_struct_path_func(StructRNA *srna, const char *path);
-void RNA_def_struct_identifier(StructRNA *srna, const char *identifier);
+void RNA_def_struct_identifier_no_struct_map(StructRNA *srna, const char *identifier);
+void RNA_def_struct_identifier(BlenderRNA *brna, StructRNA *srna, const char *identifier);
void RNA_def_struct_ui_text(StructRNA *srna, const char *name, const char *description);
void RNA_def_struct_ui_icon(StructRNA *srna, int icon);
void RNA_struct_free_extension(StructRNA *srna, ExtensionRNA *ext);
@@ -139,6 +141,7 @@ void RNA_def_property_collection_sdna(PropertyRNA *prop, const char *structname,
void RNA_def_property_flag(PropertyRNA *prop, PropertyFlag flag);
void RNA_def_property_clear_flag(PropertyRNA *prop, PropertyFlag flag);
+void RNA_def_property_tags(PropertyRNA *prop, int tags);
void RNA_def_property_subtype(PropertyRNA *prop, PropertySubType subtype);
void RNA_def_property_array(PropertyRNA *prop, int length);
void RNA_def_property_multi_array(PropertyRNA *prop, int dimension, const int length[]);
@@ -167,6 +170,7 @@ void RNA_def_property_editable_func(PropertyRNA *prop, const char *editable);
void RNA_def_property_editable_array_func(PropertyRNA *prop, const char *editable);
void RNA_def_property_update_runtime(PropertyRNA *prop, const void *func);
+void RNA_def_property_poll_runtime(PropertyRNA *prop, const void *func);
void RNA_def_property_dynamic_array_funcs(PropertyRNA *prop, const char *getlength);
void RNA_def_property_boolean_funcs(PropertyRNA *prop, const char *get, const char *set);
@@ -209,14 +213,14 @@ void RNA_def_parameter_clear_flags(PropertyRNA *prop, PropertyFlag flag_property
void RNA_enum_item_add(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item);
void RNA_enum_item_add_separator(EnumPropertyItem **items, int *totitem);
-void RNA_enum_items_add(EnumPropertyItem **items, int *totitem, EnumPropertyItem *item);
-void RNA_enum_items_add_value(EnumPropertyItem **items, int *totitem, EnumPropertyItem *item, int value);
+void RNA_enum_items_add(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item);
+void RNA_enum_items_add_value(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item, int value);
void RNA_enum_item_end(EnumPropertyItem **items, int *totitem);
/* Memory management */
-void RNA_def_struct_duplicate_pointers(StructRNA *srna);
-void RNA_def_struct_free_pointers(StructRNA *srna);
+void RNA_def_struct_duplicate_pointers(BlenderRNA *brna, StructRNA *srna);
+void RNA_def_struct_free_pointers(BlenderRNA *brna, StructRNA *srna);
void RNA_def_func_duplicate_pointers(FunctionRNA *func);
void RNA_def_func_free_pointers(FunctionRNA *func);
void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA *prop);
diff --git a/source/blender/makesrna/RNA_enum_types.h b/source/blender/makesrna/RNA_enum_types.h
index 1c9b3593d17..0f4e20a02ab 100644
--- a/source/blender/makesrna/RNA_enum_types.h
+++ b/source/blender/makesrna/RNA_enum_types.h
@@ -36,207 +36,212 @@ struct bNodeSocketType;
/* Types */
/* use in cases where only dynamic types are used */
-extern EnumPropertyItem DummyRNA_NULL_items[];
-extern EnumPropertyItem DummyRNA_DEFAULT_items[];
+extern const EnumPropertyItem DummyRNA_NULL_items[];
+extern const EnumPropertyItem DummyRNA_DEFAULT_items[];
/* all others should follow 'rna_enum_*_items' naming */
-extern EnumPropertyItem rna_enum_id_type_items[];
+extern const EnumPropertyItem rna_enum_id_type_items[];
-extern EnumPropertyItem rna_enum_object_mode_items[];
-extern EnumPropertyItem rna_enum_object_empty_drawtype_items[];
-extern EnumPropertyItem rna_enum_metaelem_type_items[];
+extern const EnumPropertyItem rna_enum_object_mode_items[];
+extern const EnumPropertyItem rna_enum_object_empty_drawtype_items[];
+extern const EnumPropertyItem rna_enum_metaelem_type_items[];
-extern EnumPropertyItem rna_enum_proportional_falloff_items[];
-extern EnumPropertyItem rna_enum_proportional_falloff_curve_only_items[];
-extern EnumPropertyItem rna_enum_proportional_editing_items[];
-extern EnumPropertyItem rna_enum_snap_target_items[];
-extern EnumPropertyItem rna_enum_snap_element_items[];
-extern EnumPropertyItem rna_enum_snap_node_element_items[];
-extern EnumPropertyItem rna_enum_curve_fit_method_items[];
-extern EnumPropertyItem rna_enum_mesh_select_mode_items[];
-extern EnumPropertyItem rna_enum_mesh_delimit_mode_items[];
-extern EnumPropertyItem rna_enum_space_type_items[];
-extern EnumPropertyItem rna_enum_region_type_items[];
-extern EnumPropertyItem rna_enum_object_modifier_type_items[];
-extern EnumPropertyItem rna_enum_constraint_type_items[];
-extern EnumPropertyItem rna_enum_boidrule_type_items[];
-extern EnumPropertyItem rna_enum_sequence_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_proportional_falloff_items[];
+extern const EnumPropertyItem rna_enum_proportional_falloff_curve_only_items[];
+extern const EnumPropertyItem rna_enum_proportional_editing_items[];
+extern const EnumPropertyItem rna_enum_snap_target_items[];
+extern const EnumPropertyItem rna_enum_snap_element_items[];
+extern const EnumPropertyItem rna_enum_snap_node_element_items[];
+extern const EnumPropertyItem rna_enum_curve_fit_method_items[];
+extern const EnumPropertyItem rna_enum_mesh_select_mode_items[];
+extern const EnumPropertyItem rna_enum_mesh_delimit_mode_items[];
+extern const EnumPropertyItem rna_enum_space_type_items[];
+extern const EnumPropertyItem rna_enum_region_type_items[];
+extern const EnumPropertyItem rna_enum_object_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_constraint_type_items[];
+extern const EnumPropertyItem rna_enum_boidrule_type_items[];
+extern const EnumPropertyItem rna_enum_sequence_modifier_type_items[];
-extern EnumPropertyItem rna_enum_modifier_triangulate_quad_method_items[];
-extern EnumPropertyItem rna_enum_modifier_triangulate_ngon_method_items[];
+extern const EnumPropertyItem rna_enum_modifier_triangulate_quad_method_items[];
+extern const EnumPropertyItem rna_enum_modifier_triangulate_ngon_method_items[];
-extern EnumPropertyItem rna_enum_image_type_items[];
-extern EnumPropertyItem rna_enum_image_color_mode_items[];
-extern EnumPropertyItem rna_enum_image_color_depth_items[];
-extern EnumPropertyItem rna_enum_image_generated_type_items[];
+extern const EnumPropertyItem rna_enum_image_type_items[];
+extern const EnumPropertyItem rna_enum_image_color_mode_items[];
+extern const EnumPropertyItem rna_enum_image_color_depth_items[];
+extern const EnumPropertyItem rna_enum_image_generated_type_items[];
-extern EnumPropertyItem rna_enum_normal_space_items[];
-extern EnumPropertyItem rna_enum_normal_swizzle_items[];
-extern EnumPropertyItem rna_enum_bake_save_mode_items[];
+extern const EnumPropertyItem rna_enum_normal_space_items[];
+extern const EnumPropertyItem rna_enum_normal_swizzle_items[];
+extern const EnumPropertyItem rna_enum_bake_save_mode_items[];
-extern EnumPropertyItem rna_enum_views_format_items[];
-extern EnumPropertyItem rna_enum_views_format_multilayer_items[];
-extern EnumPropertyItem rna_enum_views_format_multiview_items[];
-extern EnumPropertyItem rna_enum_stereo3d_display_items[];
-extern EnumPropertyItem rna_enum_stereo3d_anaglyph_type_items[];
-extern EnumPropertyItem rna_enum_stereo3d_interlace_type_items[];
+extern const EnumPropertyItem rna_enum_views_format_items[];
+extern const EnumPropertyItem rna_enum_views_format_multilayer_items[];
+extern const EnumPropertyItem rna_enum_views_format_multiview_items[];
+extern const EnumPropertyItem rna_enum_stereo3d_display_items[];
+extern const EnumPropertyItem rna_enum_stereo3d_anaglyph_type_items[];
+extern const EnumPropertyItem rna_enum_stereo3d_interlace_type_items[];
-extern EnumPropertyItem rna_enum_exr_codec_items[];
-extern EnumPropertyItem rna_enum_color_sets_items[];
+extern const EnumPropertyItem rna_enum_exr_codec_items[];
+extern const EnumPropertyItem rna_enum_color_sets_items[];
-extern EnumPropertyItem rna_enum_beztriple_keyframe_type_items[];
-extern EnumPropertyItem rna_enum_beztriple_interpolation_mode_items[];
-extern EnumPropertyItem rna_enum_beztriple_interpolation_easing_items[];
-extern EnumPropertyItem rna_enum_keyframe_handle_type_items[];
+extern const EnumPropertyItem rna_enum_beztriple_keyframe_type_items[];
+extern const EnumPropertyItem rna_enum_beztriple_interpolation_mode_items[];
+extern const EnumPropertyItem rna_enum_beztriple_interpolation_easing_items[];
+extern const EnumPropertyItem rna_enum_keyframe_handle_type_items[];
-extern EnumPropertyItem rna_enum_keyblock_type_items[];
+extern const EnumPropertyItem rna_enum_keyblock_type_items[];
-extern EnumPropertyItem rna_enum_keyingset_path_grouping_items[];
-extern EnumPropertyItem rna_enum_keying_flag_items[];
+extern const EnumPropertyItem rna_enum_keyingset_path_grouping_items[];
+extern const EnumPropertyItem rna_enum_keying_flag_items[];
-extern EnumPropertyItem rna_enum_keyframe_paste_offset_items[];
-extern EnumPropertyItem rna_enum_keyframe_paste_merge_items[];
+extern const EnumPropertyItem rna_enum_keyframe_paste_offset_items[];
+extern const EnumPropertyItem rna_enum_keyframe_paste_merge_items[];
-extern EnumPropertyItem rna_enum_fmodifier_type_items[];
+extern const EnumPropertyItem rna_enum_fmodifier_type_items[];
-extern EnumPropertyItem rna_enum_nla_mode_extend_items[];
-extern EnumPropertyItem rna_enum_nla_mode_blend_items[];
+extern const EnumPropertyItem rna_enum_nla_mode_extend_items[];
+extern const EnumPropertyItem rna_enum_nla_mode_blend_items[];
-extern EnumPropertyItem rna_enum_motionpath_bake_location_items[];
+extern const EnumPropertyItem rna_enum_motionpath_bake_location_items[];
-extern EnumPropertyItem rna_enum_event_value_items[];
-extern EnumPropertyItem rna_enum_event_type_items[];
-extern EnumPropertyItem rna_enum_operator_return_items[];
+extern const EnumPropertyItem rna_enum_event_value_items[];
+extern const EnumPropertyItem rna_enum_event_type_items[];
+extern const EnumPropertyItem rna_enum_operator_return_items[];
-extern EnumPropertyItem rna_enum_brush_sculpt_tool_items[];
-extern EnumPropertyItem rna_enum_brush_vertex_tool_items[];
-extern EnumPropertyItem rna_enum_brush_image_tool_items[];
+extern const EnumPropertyItem rna_enum_brush_sculpt_tool_items[];
+extern const EnumPropertyItem rna_enum_brush_vertex_tool_items[];
+extern const EnumPropertyItem rna_enum_brush_image_tool_items[];
-extern EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[];
+extern const EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[];
-extern EnumPropertyItem rna_enum_axis_xy_items[];
-extern EnumPropertyItem rna_enum_axis_xyz_items[];
+extern const EnumPropertyItem rna_enum_uv_sculpt_tool_items[];
-extern EnumPropertyItem rna_enum_axis_flag_xyz_items[];
+extern const EnumPropertyItem rna_enum_axis_xy_items[];
+extern const EnumPropertyItem rna_enum_axis_xyz_items[];
-extern EnumPropertyItem rna_enum_symmetrize_direction_items[];
+extern const EnumPropertyItem rna_enum_axis_flag_xyz_items[];
-extern EnumPropertyItem rna_enum_texture_type_items[];
+extern const EnumPropertyItem rna_enum_symmetrize_direction_items[];
-extern EnumPropertyItem rna_enum_lamp_type_items[];
+extern const EnumPropertyItem rna_enum_texture_type_items[];
-extern EnumPropertyItem rna_enum_unpack_method_items[];
+extern const EnumPropertyItem rna_enum_lamp_type_items[];
-extern EnumPropertyItem rna_enum_object_type_items[];
+extern const EnumPropertyItem rna_enum_unpack_method_items[];
-extern EnumPropertyItem rna_enum_object_type_curve_items[];
+extern const EnumPropertyItem rna_enum_object_type_items[];
-extern EnumPropertyItem rna_enum_rigidbody_object_type_items[];
-extern EnumPropertyItem rna_enum_rigidbody_object_shape_items[];
-extern EnumPropertyItem rna_enum_rigidbody_constraint_type_items[];
+extern const EnumPropertyItem rna_enum_object_type_curve_items[];
-extern EnumPropertyItem rna_enum_object_axis_items[];
+extern const EnumPropertyItem rna_enum_rigidbody_object_type_items[];
+extern const EnumPropertyItem rna_enum_rigidbody_object_shape_items[];
+extern const EnumPropertyItem rna_enum_rigidbody_constraint_type_items[];
-extern EnumPropertyItem rna_enum_controller_type_items[];
+extern const EnumPropertyItem rna_enum_object_axis_items[];
-extern EnumPropertyItem rna_enum_render_pass_type_items[];
-extern EnumPropertyItem rna_enum_render_pass_debug_type_items[];
+extern const EnumPropertyItem rna_enum_controller_type_items[];
-extern EnumPropertyItem rna_enum_bake_pass_type_items[];
-extern EnumPropertyItem rna_enum_bake_pass_filter_type_items[];
+extern const EnumPropertyItem rna_enum_render_pass_type_items[];
+extern const EnumPropertyItem rna_enum_render_pass_debug_type_items[];
-extern EnumPropertyItem rna_enum_keymap_propvalue_items[];
+extern const EnumPropertyItem rna_enum_bake_pass_type_items[];
+extern const EnumPropertyItem rna_enum_bake_pass_filter_type_items[];
-extern EnumPropertyItem rna_enum_operator_context_items[];
+extern const EnumPropertyItem rna_enum_keymap_propvalue_items[];
-extern EnumPropertyItem rna_enum_wm_report_items[];
+extern const EnumPropertyItem rna_enum_operator_context_items[];
-extern EnumPropertyItem rna_enum_transform_mode_types[];
+extern const EnumPropertyItem rna_enum_wm_report_items[];
-extern EnumPropertyItem rna_enum_posebone_rotmode_items[];
+extern const EnumPropertyItem rna_enum_transform_mode_types[];
-extern EnumPropertyItem rna_enum_property_type_items[];
-extern EnumPropertyItem rna_enum_property_subtype_items[];
-extern EnumPropertyItem rna_enum_property_unit_items[];
+extern const EnumPropertyItem rna_enum_posebone_rotmode_items[];
-extern EnumPropertyItem rna_enum_gameproperty_type_items[];
+extern const EnumPropertyItem rna_enum_property_type_items[];
+extern const EnumPropertyItem rna_enum_property_subtype_items[];
+extern const EnumPropertyItem rna_enum_property_unit_items[];
-extern EnumPropertyItem rna_enum_viewport_shade_items[];
+extern const EnumPropertyItem rna_enum_gameproperty_type_items[];
-extern EnumPropertyItem rna_enum_navigation_mode_items[];
+extern const EnumPropertyItem rna_enum_viewport_shade_items[];
-extern EnumPropertyItem rna_enum_file_sort_items[];
+extern const EnumPropertyItem rna_enum_navigation_mode_items[];
-extern EnumPropertyItem rna_enum_node_socket_in_out_items[];
-extern EnumPropertyItem rna_enum_node_icon_items[];
+extern const EnumPropertyItem rna_enum_file_sort_items[];
-extern EnumPropertyItem rna_enum_node_math_items[];
-extern EnumPropertyItem rna_enum_node_vec_math_items[];
-extern EnumPropertyItem rna_enum_node_filter_items[];
+extern const EnumPropertyItem rna_enum_node_socket_in_out_items[];
+extern const EnumPropertyItem rna_enum_node_icon_items[];
-extern EnumPropertyItem rna_enum_ramp_blend_items[];
+extern const EnumPropertyItem rna_enum_node_math_items[];
+extern const EnumPropertyItem rna_enum_node_vec_math_items[];
+extern const EnumPropertyItem rna_enum_node_filter_items[];
-extern EnumPropertyItem rna_enum_prop_dynamicpaint_type_items[];
+extern const EnumPropertyItem rna_enum_ramp_blend_items[];
-extern EnumPropertyItem rna_enum_clip_editor_mode_items[];
+extern const EnumPropertyItem rna_enum_prop_dynamicpaint_type_items[];
-extern EnumPropertyItem rna_enum_icon_items[];
-extern EnumPropertyItem rna_enum_uilist_layout_type_items[];
+extern const EnumPropertyItem rna_enum_clip_editor_mode_items[];
-extern EnumPropertyItem rna_enum_linestyle_color_modifier_type_items[];
-extern EnumPropertyItem rna_enum_linestyle_alpha_modifier_type_items[];
-extern EnumPropertyItem rna_enum_linestyle_thickness_modifier_type_items[];
-extern EnumPropertyItem rna_enum_linestyle_geometry_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_icon_items[];
+extern const EnumPropertyItem rna_enum_uilist_layout_type_items[];
-extern EnumPropertyItem rna_enum_window_cursor_items[];
+extern const EnumPropertyItem rna_enum_linestyle_color_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_linestyle_alpha_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_linestyle_thickness_modifier_type_items[];
+extern const EnumPropertyItem rna_enum_linestyle_geometry_modifier_type_items[];
-extern EnumPropertyItem rna_enum_dt_method_vertex_items[];
-extern EnumPropertyItem rna_enum_dt_method_edge_items[];
-extern EnumPropertyItem rna_enum_dt_method_loop_items[];
-extern EnumPropertyItem rna_enum_dt_method_poly_items[];
-extern EnumPropertyItem rna_enum_dt_mix_mode_items[];
-extern EnumPropertyItem rna_enum_dt_layers_select_src_items[];
-extern EnumPropertyItem rna_enum_dt_layers_select_dst_items[];
+extern const EnumPropertyItem rna_enum_window_cursor_items[];
-extern EnumPropertyItem rna_enum_abc_compression_items[];
+extern const EnumPropertyItem rna_enum_dt_method_vertex_items[];
+extern const EnumPropertyItem rna_enum_dt_method_edge_items[];
+extern const EnumPropertyItem rna_enum_dt_method_loop_items[];
+extern const EnumPropertyItem rna_enum_dt_method_poly_items[];
+extern const EnumPropertyItem rna_enum_dt_mix_mode_items[];
+extern const EnumPropertyItem rna_enum_dt_layers_select_src_items[];
+extern const EnumPropertyItem rna_enum_dt_layers_select_dst_items[];
+
+extern const EnumPropertyItem rna_enum_abc_compression_items[];
/* API calls */
int rna_node_tree_type_to_enum(struct bNodeTreeType *typeinfo);
int rna_node_tree_idname_to_enum(const char *idname);
struct bNodeTreeType *rna_node_tree_type_from_enum(int value);
-EnumPropertyItem *rna_node_tree_type_itemf(void *data, int (*poll)(void *data, struct bNodeTreeType *), bool *r_free);
+const EnumPropertyItem *rna_node_tree_type_itemf(
+ void *data, int (*poll)(void *data, struct bNodeTreeType *), bool *r_free);
int rna_node_type_to_enum(struct bNodeType *typeinfo);
int rna_node_idname_to_enum(const char *idname);
struct bNodeType *rna_node_type_from_enum(int value);
-EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, struct bNodeType *), bool *r_free);
+const EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, struct bNodeType *), bool *r_free);
int rna_node_socket_type_to_enum(struct bNodeSocketType *typeinfo);
int rna_node_socket_idname_to_enum(const char *idname);
struct bNodeSocketType *rna_node_socket_type_from_enum(int value);
-EnumPropertyItem *rna_node_socket_type_itemf(void *data, int (*poll)(void *data, struct bNodeSocketType *), bool *r_free);
+const EnumPropertyItem *rna_node_socket_type_itemf(
+ void *data, int (*poll)(void *data, struct bNodeSocketType *), bool *r_free);
struct bContext;
struct PointerRNA;
struct PropertyRNA;
-EnumPropertyItem *rna_TransformOrientation_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *rna_Sensor_type_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *rna_Actuator_type_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *rna_TransformOrientation_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *rna_Sensor_type_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *rna_Actuator_type_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
/* Generic functions, return an enum from library data, index is the position
* in the linked list can add more for different types as needed */
-EnumPropertyItem *RNA_action_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_action_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
// EnumPropertyItem *RNA_action_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_group_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_group_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_image_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_image_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_scene_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_scene_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_movieclip_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_movieclip_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_mask_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
-EnumPropertyItem *RNA_mask_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_group_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_group_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_image_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_image_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_scene_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_scene_without_active_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_scene_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_movieclip_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_movieclip_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_mask_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+const EnumPropertyItem *RNA_mask_local_itemf(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
#endif /* __RNA_ENUM_TYPES_H__ */
diff --git a/source/blender/makesrna/RNA_types.h b/source/blender/makesrna/RNA_types.h
index dee8df7d933..705d3914a52 100644
--- a/source/blender/makesrna/RNA_types.h
+++ b/source/blender/makesrna/RNA_types.h
@@ -178,7 +178,7 @@ typedef enum PropertyFlag {
* after every typed char, instead of waiting final validation. Used e.g. for text searchbox.
* It will also cause UI_BUT_VALUE_CLEAR to be set for text buttons. We could add an own flag
* for search/filter properties, but this works just fine for now. */
- PROP_TEXTEDIT_UPDATE = (1 << 31),
+ PROP_TEXTEDIT_UPDATE = (1u << 31),
/* icon */
PROP_ICONS_CONSECUTIVE = (1 << 12),
@@ -360,7 +360,7 @@ typedef void (*StringPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA
typedef int (*EnumPropertyGetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop);
typedef void (*EnumPropertySetFunc)(struct PointerRNA *ptr, struct PropertyRNA *prop, int value);
/* same as PropEnumItemFunc */
-typedef EnumPropertyItem *(*EnumPropertyItemFunc)(struct bContext *C, PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
+typedef const EnumPropertyItem *(*EnumPropertyItemFunc)(struct bContext *C, PointerRNA *ptr, struct PropertyRNA *prop, bool *r_free);
typedef struct PropertyRNA PropertyRNA;
@@ -398,22 +398,46 @@ typedef struct ParameterDynAlloc {
/* Function */
typedef enum FunctionFlag {
- FUNC_NO_SELF = (1 << 0), /* for static functions */
- FUNC_USE_SELF_TYPE = (1 << 1), /* for class methods, only used when FUNC_NO_SELF is set */
+ /***** Options affecting callback signature. *****/
+ /* Those add additionnal parameters at the beginning of the C callback, like that:
+ * rna_my_func([ID *_selfid],
+ * [<DNA_STRUCT> *self|StructRNA *type],
+ * [Main *bmain],
+ * [bContext *C],
+ * [ReportList *reports],
+ * <other RNA-defined parameters>);
+ */
+ /* Pass ID owning 'self' data (i.e. ptr->id.data, might be same as self in case data is an ID...). */
+ FUNC_USE_SELF_ID = (1 << 11),
+
+ /* Do not pass the object (DNA struct pointer) from which it is called, used to define static or class functions. */
+ FUNC_NO_SELF = (1 << 0),
+ /* Pass RNA type, used to define class functions, only valid when FUNC_NO_SELF is set. */
+ FUNC_USE_SELF_TYPE = (1 << 1),
+
+ /* Pass Main, bContext and/or ReportList. */
FUNC_USE_MAIN = (1 << 2),
FUNC_USE_CONTEXT = (1 << 3),
FUNC_USE_REPORTS = (1 << 4),
- FUNC_USE_SELF_ID = (1 << 11),
- FUNC_ALLOW_WRITE = (1 << 12),
- /* registering */
+
+ /***** Registering of python subclasses. *****/
+ /* This function is part of the registerable class' interface, and can be implemented/redefined in python. */
FUNC_REGISTER = (1 << 5),
+ /* Subclasses can choose not to implement this function. */
FUNC_REGISTER_OPTIONAL = FUNC_REGISTER | (1 << 6),
+ /* If not set, the python function implementing this call is not allowed to write into data-blocks.
+ * Except for WindowManager and Screen currently, see rna_id_write_error() in bpy_rna.c */
+ FUNC_ALLOW_WRITE = (1 << 12),
- /* internal flags */
+ /***** Internal flags. *****/
+ /* UNUSED CURRENTLY? ??? */
FUNC_BUILTIN = (1 << 7),
+ /* UNUSED CURRENTLY. ??? */
FUNC_EXPORT = (1 << 8),
+ /* Function has been defined at runtime, not statically in RNA source code. */
FUNC_RUNTIME = (1 << 9),
+ /* UNUSED CURRENTLY? Function owns its identifier and description strings, and has to free them when deleted. */
FUNC_FREE_POINTERS = (1 << 10),
} FunctionFlag;
@@ -434,6 +458,10 @@ typedef enum StructFlag {
STRUCT_GENERATED = (1 << 4),
STRUCT_FREE_POINTERS = (1 << 5),
STRUCT_NO_IDPROPERTIES = (1 << 6), /* Menus and Panels don't need properties */
+ STRUCT_NO_DATABLOCK_IDPROPERTIES = (1 << 7), /* e.g. for Operator */
+ STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES = (1 << 8), /* for PropertyGroup which contains pointers to datablocks */
+ STRUCT_PUBLIC_NAMESPACE = (1 << 9), /* Added to type-map #BlenderRNA.structs_map */
+ STRUCT_PUBLIC_NAMESPACE_INHERIT = (1 << 10), /* All subtypes are added too. */
} StructFlag;
typedef int (*StructValidateFunc)(struct PointerRNA *ptr, void *data, int *have_function);
diff --git a/source/blender/makesrna/intern/CMakeLists.txt b/source/blender/makesrna/intern/CMakeLists.txt
index 0f3ea27a7f9..743d192f0c5 100644
--- a/source/blender/makesrna/intern/CMakeLists.txt
+++ b/source/blender/makesrna/intern/CMakeLists.txt
@@ -140,6 +140,9 @@ set(GENSRC_CFLAGS)
if(CMAKE_COMPILER_IS_GNUCC OR (CMAKE_C_COMPILER_ID MATCHES "Clang"))
set(GENSRC_CFLAGS "-Wno-missing-prototypes")
endif()
+if(CMAKE_C_COMPILER_ID MATCHES "Clang")
+ set(GENSRC_CFLAGS "${GENSRC_CFLAGS} -Wno-missing-variable-declarations")
+endif()
if(GENSRC_CFLAGS)
set_source_files_properties(${GENSRC} PROPERTIES COMPILE_FLAGS "${GENSRC_CFLAGS}")
@@ -176,9 +179,6 @@ set(INC_SYS
if(WITH_CYCLES)
add_definitions(-DWITH_CYCLES)
- if(WITH_CYCLES_DEBUG)
- add_definitions(-DWITH_CYCLES_DEBUG)
- endif()
endif()
if(WITH_PYTHON)
@@ -232,13 +232,6 @@ if(WITH_AUDASPACE)
)
endif()
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../../quicktime
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_CODEC_FFMPEG)
list(APPEND INC
../../../../intern/ffmpeg
diff --git a/source/blender/makesrna/intern/makesrna.c b/source/blender/makesrna/intern/makesrna.c
index 4552c773097..e1d4e8fb8ad 100644
--- a/source/blender/makesrna/intern/makesrna.c
+++ b/source/blender/makesrna/intern/makesrna.c
@@ -46,6 +46,14 @@
# endif
#endif
+/**
+ * Variable to control debug output of makesrna.
+ * debugSRNA:
+ * - 0 = no output, except errors
+ * - 1 = detail actions
+ */
+static int debugSRNA = 0;
+
/* stub for BLI_abort() */
#ifndef NDEBUG
void BLI_system_backtrace(FILE *fp)
@@ -62,7 +70,9 @@ void BLI_system_backtrace(FILE *fp)
static int file_older(const char *file1, const char *file2)
{
struct stat st1, st2;
- /* printf("compare: %s %s\n", file1, file2); */
+ if (debugSRNA > 0) {
+ printf("compare: %s %s\n", file1, file2);
+ }
if (stat(file1, &st1)) return 0;
if (stat(file2, &st2)) return 0;
@@ -507,7 +517,7 @@ static void rna_float_print(FILE *f, float num)
{
if (num == -FLT_MAX) fprintf(f, "-FLT_MAX");
else if (num == FLT_MAX) fprintf(f, "FLT_MAX");
- else if ((int64_t)num == num) fprintf(f, "%.1ff", num);
+ else if ((ABS(num) < INT64_MAX) && ((int64_t)num == num)) fprintf(f, "%.1ff", num);
else fprintf(f, "%.10ff", num);
}
@@ -2583,17 +2593,23 @@ static void rna_generate_blender(BlenderRNA *brna, FILE *f)
{
StructRNA *srna;
- fprintf(f, "BlenderRNA BLENDER_RNA = {");
-
+ fprintf(f,
+ "BlenderRNA BLENDER_RNA = {\n"
+ "\t.structs = {"
+ );
srna = brna->structs.first;
- if (srna) fprintf(f, "{&RNA_%s, ", srna->identifier);
- else fprintf(f, "{NULL, ");
+ if (srna) fprintf(f, "&RNA_%s, ", srna->identifier);
+ else fprintf(f, "NULL, ");
srna = brna->structs.last;
- if (srna) fprintf(f, "&RNA_%s}", srna->identifier);
- else fprintf(f, "NULL}");
+ if (srna) fprintf(f, "&RNA_%s},\n", srna->identifier);
+ else fprintf(f, "NULL},\n");
- fprintf(f, "};\n\n");
+ fprintf(f,
+ "\t.structs_map = NULL,\n"
+ "\t.structs_len = 0,\n"
+ "};\n\n"
+ );
}
static void rna_generate_property_prototypes(BlenderRNA *UNUSED(brna), StructRNA *srna, FILE *f)
@@ -2866,7 +2882,7 @@ static void rna_generate_property(FILE *f, StructRNA *srna, const char *nest, Pr
int i, defaultfound = 0, totflag = 0;
if (eprop->item) {
- fprintf(f, "static EnumPropertyItem rna_%s%s_%s_items[%d] = {\n\t", srna->identifier,
+ fprintf(f, "static const EnumPropertyItem rna_%s%s_%s_items[%d] = {\n\t", srna->identifier,
strnest, prop->identifier, eprop->totitem + 1);
for (i = 0; i < eprop->totitem; i++) {
@@ -2994,7 +3010,7 @@ static void rna_generate_property(FILE *f, StructRNA *srna, const char *nest, Pr
else fprintf(f, "NULL,\n");
fprintf(f, "\t%d, ", prop->magic);
rna_print_c_string(f, prop->identifier);
- fprintf(f, ", %d, %d, %d, ", prop->flag, prop->flag_parameter, prop->flag_internal);
+ fprintf(f, ", %d, %d, %d, %d, ", prop->flag, prop->flag_parameter, prop->flag_internal, prop->tags);
rna_print_c_string(f, prop->name); fprintf(f, ",\n\t");
rna_print_c_string(f, prop->description); fprintf(f, ",\n\t");
fprintf(f, "%d, ", prop->icon);
@@ -3238,7 +3254,7 @@ static void rna_generate_struct(BlenderRNA *UNUSED(brna), StructRNA *srna, FILE
fprintf(f, "\t");
rna_print_c_string(f, srna->identifier);
fprintf(f, ", NULL, NULL"); /* PyType - Cant initialize here */
- fprintf(f, ", %d, ", srna->flag);
+ fprintf(f, ", %d, NULL, ", srna->flag);
rna_print_c_string(f, srna->name);
fprintf(f, ",\n\t");
rna_print_c_string(f, srna->description);
@@ -3746,7 +3762,7 @@ static const char *cpp_classes = ""
"template<typename T, TBeginFunc Tbegin, TNextFunc Tnext, TEndFunc Tend>\n"
"class CollectionIterator {\n"
"public:\n"
-" CollectionIterator() : t(iter.ptr), init(false) { iter.valid = false; }\n"
+" CollectionIterator() : iter(), t(iter.ptr), init(false) { iter.valid = false; }\n"
" ~CollectionIterator(void) { if (init) Tend(&iter); };\n"
"\n"
" operator bool(void)\n"
@@ -4128,7 +4144,9 @@ int main(int argc, char **argv)
return_status = 1;
}
else {
- fprintf(stderr, "Running makesrna\n");
+ if (debugSRNA > 0) {
+ fprintf(stderr, "Running makesrna\n");
+ }
makesrna_path = argv[0];
return_status = rna_preprocess(argv[1]);
}
diff --git a/source/blender/makesrna/intern/rna_ID.c b/source/blender/makesrna/intern/rna_ID.c
index 671902c5cc7..bc2c26c2b2b 100644
--- a/source/blender/makesrna/intern/rna_ID.c
+++ b/source/blender/makesrna/intern/rna_ID.c
@@ -48,7 +48,7 @@
/* enum of ID-block types
* NOTE: need to keep this in line with the other defines for these
*/
-EnumPropertyItem rna_enum_id_type_items[] = {
+const EnumPropertyItem rna_enum_id_type_items[] = {
{ID_AC, "ACTION", ICON_ACTION, "Action", ""},
{ID_AR, "ARMATURE", ICON_ARMATURE_DATA, "Armature", ""},
{ID_BR, "BRUSH", ICON_BRUSH_DATA, "Brush", ""},
@@ -136,48 +136,54 @@ static int rna_ID_name_editable(PointerRNA *ptr, const char **UNUSED(r_info))
return PROP_EDITABLE;
}
-short RNA_type_to_ID_code(StructRNA *type)
-{
- if (RNA_struct_is_a(type, &RNA_Action)) return ID_AC;
- if (RNA_struct_is_a(type, &RNA_Armature)) return ID_AR;
- if (RNA_struct_is_a(type, &RNA_Brush)) return ID_BR;
- if (RNA_struct_is_a(type, &RNA_CacheFile)) return ID_CF;
- if (RNA_struct_is_a(type, &RNA_Camera)) return ID_CA;
- if (RNA_struct_is_a(type, &RNA_Curve)) return ID_CU;
- if (RNA_struct_is_a(type, &RNA_GreasePencil)) return ID_GD;
- if (RNA_struct_is_a(type, &RNA_Group)) return ID_GR;
- if (RNA_struct_is_a(type, &RNA_Image)) return ID_IM;
- if (RNA_struct_is_a(type, &RNA_Key)) return ID_KE;
- if (RNA_struct_is_a(type, &RNA_Lamp)) return ID_LA;
- if (RNA_struct_is_a(type, &RNA_Library)) return ID_LI;
- if (RNA_struct_is_a(type, &RNA_FreestyleLineStyle)) return ID_LS;
- if (RNA_struct_is_a(type, &RNA_Lattice)) return ID_LT;
- if (RNA_struct_is_a(type, &RNA_Material)) return ID_MA;
- if (RNA_struct_is_a(type, &RNA_MetaBall)) return ID_MB;
- if (RNA_struct_is_a(type, &RNA_MovieClip)) return ID_MC;
- if (RNA_struct_is_a(type, &RNA_Mesh)) return ID_ME;
- if (RNA_struct_is_a(type, &RNA_Mask)) return ID_MSK;
- if (RNA_struct_is_a(type, &RNA_NodeTree)) return ID_NT;
- if (RNA_struct_is_a(type, &RNA_Object)) return ID_OB;
- if (RNA_struct_is_a(type, &RNA_ParticleSettings)) return ID_PA;
- if (RNA_struct_is_a(type, &RNA_Palette)) return ID_PAL;
- if (RNA_struct_is_a(type, &RNA_PaintCurve)) return ID_PC;
- if (RNA_struct_is_a(type, &RNA_Scene)) return ID_SCE;
- if (RNA_struct_is_a(type, &RNA_Screen)) return ID_SCR;
- if (RNA_struct_is_a(type, &RNA_Sound)) return ID_SO;
- if (RNA_struct_is_a(type, &RNA_Speaker)) return ID_SPK;
- if (RNA_struct_is_a(type, &RNA_Texture)) return ID_TE;
- if (RNA_struct_is_a(type, &RNA_Text)) return ID_TXT;
- if (RNA_struct_is_a(type, &RNA_VectorFont)) return ID_VF;
- if (RNA_struct_is_a(type, &RNA_World)) return ID_WO;
- if (RNA_struct_is_a(type, &RNA_WindowManager)) return ID_WM;
+short RNA_type_to_ID_code(const StructRNA *type)
+{
+ const StructRNA *base_type = RNA_struct_base_child_of(type, &RNA_ID);
+ if (UNLIKELY(base_type == NULL)) {
+ return 0;
+ }
+ if (base_type == &RNA_Action) return ID_AC;
+ if (base_type == &RNA_Armature) return ID_AR;
+ if (base_type == &RNA_Brush) return ID_BR;
+ if (base_type == &RNA_CacheFile) return ID_CF;
+ if (base_type == &RNA_Camera) return ID_CA;
+ if (base_type == &RNA_Curve) return ID_CU;
+ if (base_type == &RNA_GreasePencil) return ID_GD;
+ if (base_type == &RNA_Group) return ID_GR;
+ if (base_type == &RNA_Image) return ID_IM;
+ if (base_type == &RNA_Key) return ID_KE;
+ if (base_type == &RNA_Lamp) return ID_LA;
+ if (base_type == &RNA_Library) return ID_LI;
+ if (base_type == &RNA_FreestyleLineStyle) return ID_LS;
+ if (base_type == &RNA_Lattice) return ID_LT;
+ if (base_type == &RNA_Material) return ID_MA;
+ if (base_type == &RNA_MetaBall) return ID_MB;
+ if (base_type == &RNA_MovieClip) return ID_MC;
+ if (base_type == &RNA_Mesh) return ID_ME;
+ if (base_type == &RNA_Mask) return ID_MSK;
+ if (base_type == &RNA_NodeTree) return ID_NT;
+ if (base_type == &RNA_Object) return ID_OB;
+ if (base_type == &RNA_ParticleSettings) return ID_PA;
+ if (base_type == &RNA_Palette) return ID_PAL;
+ if (base_type == &RNA_PaintCurve) return ID_PC;
+ if (base_type == &RNA_Scene) return ID_SCE;
+ if (base_type == &RNA_Screen) return ID_SCR;
+ if (base_type == &RNA_Sound) return ID_SO;
+ if (base_type == &RNA_Speaker) return ID_SPK;
+ if (base_type == &RNA_Texture) return ID_TE;
+ if (base_type == &RNA_Text) return ID_TXT;
+ if (base_type == &RNA_VectorFont) return ID_VF;
+ if (base_type == &RNA_World) return ID_WO;
+ if (base_type == &RNA_WindowManager) return ID_WM;
return 0;
}
StructRNA *ID_code_to_RNA_type(short idcode)
{
- switch (idcode) {
+ /* Note, this switch doesn't use a 'default',
+ * so adding new ID's causes a warning. */
+ switch ((ID_Type)idcode) {
case ID_AC: return &RNA_Action;
case ID_AR: return &RNA_Armature;
case ID_BR: return &RNA_Brush;
@@ -212,8 +218,11 @@ StructRNA *ID_code_to_RNA_type(short idcode)
case ID_WM: return &RNA_WindowManager;
case ID_WO: return &RNA_World;
- default: return &RNA_ID;
+ /* deprecated */
+ case ID_IP: break;
}
+
+ return &RNA_ID;
}
StructRNA *rna_ID_refine(PointerRNA *ptr)
@@ -250,9 +259,10 @@ void rna_PropertyGroup_unregister(Main *UNUSED(bmain), StructRNA *type)
RNA_struct_free(&BLENDER_RNA, type);
}
-StructRNA *rna_PropertyGroup_register(Main *UNUSED(bmain), ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc UNUSED(call),
- StructFreeFunc UNUSED(free))
+StructRNA *rna_PropertyGroup_register(
+ Main *UNUSED(bmain), ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc UNUSED(call),
+ StructFreeFunc UNUSED(free))
{
PointerRNA dummyptr;
@@ -342,7 +352,7 @@ static void rna_ID_user_clear(ID *id)
static void rna_ID_user_remap(ID *id, Main *bmain, ID *new_id)
{
- if (GS(id->name) == GS(new_id->name)) {
+ if ((GS(id->name) == GS(new_id->name)) && (id != new_id)) {
/* For now, do not allow remapping data in linked data from here... */
BKE_libblock_remap(bmain, id, new_id, ID_REMAP_SKIP_INDIRECT_USAGE | ID_REMAP_SKIP_NEVER_NULL_USAGE);
}
@@ -377,6 +387,14 @@ static void rna_ID_animation_data_free(ID *id, Main *bmain)
DAG_relations_tag_update(bmain);
}
+#ifdef WITH_PYTHON
+void **rna_ID_instance(PointerRNA *ptr)
+{
+ ID *id = (ID *)ptr->data;
+ return &id->py_instance;
+}
+#endif
+
static void rna_IDPArray_begin(CollectionPropertyIterator *iter, PointerRNA *ptr)
{
IDProperty *prop = (IDProperty *)ptr->data;
@@ -736,6 +754,14 @@ static PointerRNA rna_IDPreview_get(PointerRNA *ptr)
return rna_pointer_inherit_refine(ptr, &RNA_ImagePreview, prv_img);
}
+static IDProperty *rna_IDPropertyWrapPtr_idprops(PointerRNA *ptr, bool UNUSED(create))
+{
+ if (ptr == NULL) {
+ return NULL;
+ }
+ return ptr->data;
+}
+
#else
static void rna_def_ID_properties(BlenderRNA *brna)
@@ -802,7 +828,11 @@ static void rna_def_ID_properties(BlenderRNA *brna)
RNA_def_struct_name_property(srna, prop);
#endif
- /* IDP_ID -- not implemented yet in id properties */
+ /* IDP_ID */
+ prop = RNA_def_property(srna, "id", PROP_POINTER, PROP_NONE);
+ RNA_def_property_flag(prop, PROP_EXPORT | PROP_IDPROPERTY | PROP_NEVER_UNLINK);
+ RNA_def_property_struct_type(prop, "ID");
+
/* ID property groups > level 0, since level 0 group is merged
* with native RNA properties. the builtin_properties will take
@@ -934,7 +964,7 @@ static void rna_def_ID(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *prop, *parm;
- static EnumPropertyItem update_flag_items[] = {
+ static const EnumPropertyItem update_flag_items[] = {
{OB_RECALC_OB, "OBJECT", 0, "Object", ""},
{OB_RECALC_DATA, "DATA", 0, "Data", ""},
{OB_RECALC_TIME, "TIME", 0, "Time", ""},
@@ -975,12 +1005,12 @@ static void rna_def_ID(BlenderRNA *brna)
"(initial state is undefined)");
prop = RNA_def_property(srna, "is_updated", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "tag", LIB_TAG_ID_RECALC);
+ RNA_def_property_boolean_sdna(prop, NULL, "recalc", ID_RECALC);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Is Updated", "Data-block is tagged for recalculation");
prop = RNA_def_property(srna, "is_updated_data", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "tag", LIB_TAG_ID_RECALC_DATA);
+ RNA_def_property_boolean_sdna(prop, NULL, "recalc", ID_RECALC_DATA);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Is Updated Data", "Data-block data is tagged for recalculation");
@@ -1050,6 +1080,10 @@ static void rna_def_ID(BlenderRNA *brna)
"Tag the ID to update its display data, "
"e.g. when calling :class:`bpy.types.Scene.update`");
RNA_def_enum_flag(func, "refresh", update_flag_items, 0, "", "Type of updates to perform");
+
+#ifdef WITH_PYTHON
+ RNA_def_struct_register_funcs(srna, NULL, NULL, "rna_ID_instance");
+#endif
}
static void rna_def_library(BlenderRNA *brna)
@@ -1079,6 +1113,20 @@ static void rna_def_library(BlenderRNA *brna)
RNA_def_function_flag(func, FUNC_USE_REPORTS | FUNC_USE_CONTEXT);
RNA_def_function_ui_description(func, "Reload this library and all its linked data-blocks");
}
+
+/**
+ * \attention This is separate from the above. It allows for RNA functions to
+ * return an IDProperty *. See MovieClip.metadata for a usage example.
+ **/
+static void rna_def_idproperty_wrap_ptr(BlenderRNA *brna)
+{
+ StructRNA *srna;
+
+ srna = RNA_def_struct(brna, "IDPropertyWrapPtr", NULL);
+ RNA_def_struct_idprops_func(srna, "rna_IDPropertyWrapPtr_idprops");
+ RNA_def_struct_flag(srna, STRUCT_NO_DATABLOCK_IDPROPERTIES);
+}
+
void RNA_def_ID(BlenderRNA *brna)
{
StructRNA *srna;
@@ -1096,6 +1144,7 @@ void RNA_def_ID(BlenderRNA *brna)
rna_def_ID_properties(brna);
rna_def_ID_materials(brna);
rna_def_library(brna);
+ rna_def_idproperty_wrap_ptr(brna);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_access.c b/source/blender/makesrna/intern/rna_access.c
index bb839fd77f8..80e377ad8e1 100644
--- a/source/blender/makesrna/intern/rna_access.c
+++ b/source/blender/makesrna/intern/rna_access.c
@@ -50,6 +50,7 @@
#include "BKE_idcode.h"
#include "BKE_idprop.h"
#include "BKE_fcurve.h"
+#include "BKE_library.h"
#include "BKE_main.h"
#include "BKE_report.h"
@@ -75,6 +76,9 @@ void RNA_init(void)
StructRNA *srna;
PropertyRNA *prop;
+ BLENDER_RNA.structs_map = BLI_ghash_str_new_ex(__func__, 2048);
+ BLENDER_RNA.structs_len = 0;
+
for (srna = BLENDER_RNA.structs.first; srna; srna = srna->cont.next) {
if (!srna->cont.prophash) {
srna->cont.prophash = BLI_ghash_str_new("RNA_init gh");
@@ -85,6 +89,9 @@ void RNA_init(void)
}
}
}
+ BLI_assert(srna->flag & STRUCT_PUBLIC_NAMESPACE);
+ BLI_ghash_insert(BLENDER_RNA.structs_map, (void *)srna->identifier, srna);
+ BLENDER_RNA.structs_len += 1;
}
}
@@ -165,6 +172,11 @@ void RNA_pointer_create(ID *id, StructRNA *type, void *data, PointerRNA *r_ptr)
}
}
+bool RNA_pointer_is_null(const PointerRNA *ptr)
+{
+ return !((ptr->data != NULL) && (ptr->id.data != NULL) && (ptr->type != NULL));
+}
+
static void rna_pointer_inherit_id(StructRNA *type, PointerRNA *parent, PointerRNA *ptr)
{
if (type && type->flag & STRUCT_ID) {
@@ -265,8 +277,9 @@ IDProperty *RNA_struct_idprops(PointerRNA *ptr, bool create)
{
StructRNA *type = ptr->type;
- if (type && type->idproperties)
+ if (type && type->idproperties) {
return type->idproperties(ptr, create);
+ }
return NULL;
}
@@ -280,8 +293,16 @@ static IDProperty *rna_idproperty_find(PointerRNA *ptr, const char *name)
{
IDProperty *group = RNA_struct_idprops(ptr, 0);
- if (group)
- return IDP_GetPropertyFromGroup(group, name);
+ if (group) {
+ if (group->type == IDP_GROUP) {
+ return IDP_GetPropertyFromGroup(group, name);
+ }
+ else {
+ /* Not sure why that happens sometimes, with nested properties... */
+ /* Seems to be actually array prop, name is usually "0"... To be sorted out later. */
+// printf("Got unexpected IDProp container when trying to retrieve %s: %d\n", name, group->type);
+ }
+ }
return NULL;
}
@@ -380,6 +401,7 @@ static bool rna_idproperty_verify_valid(PointerRNA *ptr, PropertyRNA *prop, IDPr
return false;
break;
case IDP_GROUP:
+ case IDP_ID:
if (prop->type != PROP_POINTER)
return false;
break;
@@ -395,7 +417,8 @@ static PropertyRNA *typemap[IDP_NUMTYPES] = {
(PropertyRNA *)&rna_PropertyGroupItem_int,
(PropertyRNA *)&rna_PropertyGroupItem_float,
NULL, NULL, NULL,
- (PropertyRNA *)&rna_PropertyGroupItem_group, NULL,
+ (PropertyRNA *)&rna_PropertyGroupItem_group,
+ (PropertyRNA *)&rna_PropertyGroupItem_id,
(PropertyRNA *)&rna_PropertyGroupItem_double,
(PropertyRNA *)&rna_PropertyGroupItem_idp_array
};
@@ -510,13 +533,7 @@ static const char *rna_ensure_property_name(const PropertyRNA *prop)
StructRNA *RNA_struct_find(const char *identifier)
{
- StructRNA *type;
- if (identifier) {
- for (type = BLENDER_RNA.structs.first; type; type = type->cont.next)
- if (STREQ(type->identifier, identifier))
- return type;
- }
- return NULL;
+ return BLI_ghash_lookup(BLENDER_RNA.structs_map, identifier);
}
const char *RNA_struct_identifier(const StructRNA *type)
@@ -557,11 +574,16 @@ const char *RNA_struct_translation_context(const StructRNA *type)
return type->translation_context;
}
-PropertyRNA *RNA_struct_name_property(StructRNA *type)
+PropertyRNA *RNA_struct_name_property(const StructRNA *type)
{
return type->nameproperty;
}
+const EnumPropertyItem *RNA_struct_property_tag_defines(const StructRNA *type)
+{
+ return type->prop_tag_defines;
+}
+
PropertyRNA *RNA_struct_iterator_property(StructRNA *type)
{
return type->iteratorproperty;
@@ -572,6 +594,22 @@ StructRNA *RNA_struct_base(StructRNA *type)
return type->base;
}
+/**
+ * Use to find the subtype directly below a base-type.
+ *
+ * So if type were `RNA_SpotLamp`, `RNA_struct_base_of(type, &RNA_ID)` would return `&RNA_Lamp`.
+ */
+const StructRNA *RNA_struct_base_child_of(const StructRNA *type, const StructRNA *parent_type)
+{
+ while (type) {
+ if (type->base == parent_type) {
+ return type;
+ }
+ type = type->base;
+ }
+ return NULL;
+}
+
bool RNA_struct_is_ID(const StructRNA *type)
{
return (type->flag & STRUCT_ID) != 0;
@@ -587,6 +625,21 @@ bool RNA_struct_idprops_register_check(const StructRNA *type)
return (type->flag & STRUCT_NO_IDPROPERTIES) == 0;
}
+bool RNA_struct_idprops_datablock_allowed(const StructRNA *type)
+{
+ return (type->flag & (STRUCT_NO_DATABLOCK_IDPROPERTIES | STRUCT_NO_IDPROPERTIES)) == 0;
+}
+
+/**
+ * Whether given type implies datablock usage by IDProperties.
+ * This is used to prevent classes allowed to have IDProperties, but not datablock ones, to indirectly use some
+ * (e.g. by assigning an IDP_GROUP containing some IDP_ID pointers...).
+ */
+bool RNA_struct_idprops_contains_datablock(const StructRNA *type)
+{
+ return (type->flag & (STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES | STRUCT_ID)) != 0;
+}
+
/* remove an id-property */
bool RNA_struct_idprops_unset(PointerRNA *ptr, const char *identifier)
{
@@ -628,8 +681,11 @@ PropertyRNA *RNA_struct_find_property(PointerRNA *ptr, const char *identifier)
/* id prop lookup, not so common */
PropertyRNA *r_prop = NULL;
PointerRNA r_ptr; /* only support single level props */
- if (RNA_path_resolve(ptr, identifier, &r_ptr, &r_prop) && (r_ptr.type == ptr->type) && (r_ptr.data == ptr->data))
+ if (RNA_path_resolve_property(ptr, identifier, &r_ptr, &r_prop) &&
+ (r_ptr.type == ptr->type) && (r_ptr.data == ptr->data))
+ {
return r_prop;
+ }
}
else {
/* most common case */
@@ -684,6 +740,23 @@ bool RNA_struct_contains_property(PointerRNA *ptr, PropertyRNA *prop_test)
return found;
}
+unsigned int RNA_struct_count_properties(StructRNA *srna)
+{
+ PointerRNA struct_ptr;
+ unsigned int counter = 0;
+
+ RNA_pointer_create(NULL, srna, NULL, &struct_ptr);
+
+ RNA_STRUCT_BEGIN (&struct_ptr, prop)
+ {
+ counter++;
+ UNUSED_VARS(prop);
+ }
+ RNA_STRUCT_END;
+
+ return counter;
+}
+
/* low level direct access to type->properties, note this ignores parent classes so should be used with care */
const struct ListBase *RNA_struct_type_properties(StructRNA *srna)
{
@@ -708,7 +781,7 @@ FunctionRNA *RNA_struct_find_function(StructRNA *srna, const char *identifier)
}
return NULL;
- /* funcitonal but slow */
+ /* functional but slow */
#else
PointerRNA tptr;
PropertyRNA *iterprop;
@@ -794,6 +867,89 @@ char *RNA_struct_name_get_alloc(PointerRNA *ptr, char *fixedbuf, int fixedlen, i
return NULL;
}
+/**
+ * Use when registering structs with the #STRUCT_PUBLIC_NAMESPACE flag.
+ */
+bool RNA_struct_available_or_report(ReportList *reports, const char *identifier)
+{
+ const StructRNA *srna_exists = RNA_struct_find(identifier);
+ if (UNLIKELY(srna_exists != NULL)) {
+ /* Use comprehensive string construction since this is such a rare occurrence
+ * and information here may cut down time troubleshooting. */
+ DynStr *dynstr = BLI_dynstr_new();
+ BLI_dynstr_appendf(dynstr, "Type identifier '%s' is already in use: '", identifier);
+ BLI_dynstr_append(dynstr, srna_exists->identifier);
+ int i = 0;
+ if (srna_exists->base) {
+ for (const StructRNA *base = srna_exists->base; base; base = base->base) {
+ BLI_dynstr_append(dynstr, "(");
+ BLI_dynstr_append(dynstr, base->identifier);
+ i += 1;
+ }
+ while (i--) {
+ BLI_dynstr_append(dynstr, ")");
+ }
+ }
+ BLI_dynstr_append(dynstr, "'.");
+ char *result = BLI_dynstr_get_cstring(dynstr);
+ BLI_dynstr_free(dynstr);
+ BKE_report(reports, RPT_ERROR, result);
+ MEM_freeN(result);
+ return false;
+ }
+ else {
+ return true;
+ }
+}
+
+bool RNA_struct_bl_idname_ok_or_report(ReportList *reports, const char *identifier, const char *sep)
+{
+ const int len_sep = strlen(sep);
+ const int len_id = strlen(identifier);
+ const char *p = strstr(identifier, sep);
+ /* TODO: make error, for now warning until add-ons update. */
+#if 1
+ const int report_level = RPT_WARNING;
+ const bool failure = true;
+#else
+ const int report_level = RPT_ERROR;
+ const bool failure = false;
+#endif
+ if (p == NULL || p == identifier || p + len_sep >= identifier + len_id) {
+ BKE_reportf(reports, report_level, "'%s' doesn't contain '%s' with prefix & suffix", identifier, sep);
+ return failure;
+ }
+
+ const char *c, *start, *end, *last;
+ start = identifier;
+ end = p;
+ last = end - 1;
+ for (c = start; c != end; c++) {
+ if (((*c >= 'A' && *c <= 'Z') ||
+ ((c != start) && (*c >= '0' && *c <= '9')) ||
+ ((c != start) && (c != last) && (*c == '_'))) == 0)
+ {
+ BKE_reportf(reports, report_level, "'%s' doesn't have upper case alpha-numeric prefix", identifier);
+ return failure;
+ }
+ }
+
+ start = p + len_sep;
+ end = identifier + len_id;
+ last = end - 1;
+ for (c = start; c != end; c++) {
+ if (((*c >= 'A' && *c <= 'Z') ||
+ (*c >= 'a' && *c <= 'z') ||
+ (*c >= '0' && *c <= '9') ||
+ ((c != start) && (c != last) && (*c == '_'))) == 0)
+ {
+ BKE_reportf(reports, report_level, "'%s' doesn't have an alpha-numeric suffix", identifier);
+ return failure;
+ }
+ }
+ return true;
+}
+
/* Property Information */
const char *RNA_property_identifier(PropertyRNA *prop)
@@ -826,6 +982,17 @@ int RNA_property_flag(PropertyRNA *prop)
return rna_ensure_property(prop)->flag;
}
+/**
+ * Get the tags set for \a prop as int bitfield.
+ * \note Doesn't perform any validity check on the set bits. #RNA_def_property_tags does this
+ * in debug builds (to avoid performance issues in non-debug builds), which should be
+ * the only way to set tags. Hence, at this point we assume the tag bitfield to be valid.
+ */
+int RNA_property_tags(PropertyRNA *prop)
+{
+ return rna_ensure_property(prop)->tags;
+}
+
bool RNA_property_builtin(PropertyRNA *prop)
{
return (rna_ensure_property(prop)->flag_internal & PROP_INTERN_BUILTIN) != 0;
@@ -1201,37 +1368,44 @@ int RNA_property_pointer_poll(PointerRNA *ptr, PropertyRNA *prop, PointerRNA *va
if (prop->type == PROP_POINTER) {
PointerPropertyRNA *pprop = (PointerPropertyRNA *)prop;
- if (pprop->poll)
- return pprop->poll(ptr, *value);
+
+ if (pprop->poll) {
+ if (rna_idproperty_check(&prop, ptr)) {
+ return ((PropPointerPollFuncPy) pprop->poll)(ptr, *value, prop);
+ }
+ else {
+ return pprop->poll(ptr, *value);
+ }
+ }
return 1;
}
- printf("%s %s: is not a pointer property.\n", __func__, prop->identifier);
+ printf("%s: %s is not a pointer property.\n", __func__, prop->identifier);
return 0;
}
/* Reuse for dynamic types */
-EnumPropertyItem DummyRNA_NULL_items[] = {
+const EnumPropertyItem DummyRNA_NULL_items[] = {
{0, NULL, 0, NULL, NULL}
};
/* Reuse for dynamic types with default value */
-EnumPropertyItem DummyRNA_DEFAULT_items[] = {
+const EnumPropertyItem DummyRNA_DEFAULT_items[] = {
{0, "DEFAULT", 0, "Default", ""},
{0, NULL, 0, NULL, NULL}
};
void RNA_property_enum_items_ex(
bContext *C, PointerRNA *ptr, PropertyRNA *prop, const bool use_static,
- EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
{
EnumPropertyRNA *eprop = (EnumPropertyRNA *)rna_ensure_property(prop);
*r_free = false;
if (!use_static && eprop->itemf && (C != NULL || (prop->flag & PROP_ENUM_NO_CONTEXT))) {
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
if (prop->flag & PROP_ENUM_NO_CONTEXT)
item = eprop->itemf(NULL, ptr, prop, r_free);
@@ -1259,13 +1433,15 @@ void RNA_property_enum_items_ex(
}
void RNA_property_enum_items(
- bContext *C, PointerRNA *ptr, PropertyRNA *prop, EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
+ bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
{
RNA_property_enum_items_ex(C, ptr, prop, false, r_item, r_totitem, r_free);
}
#ifdef WITH_INTERNATIONAL
-static void property_enum_translate(PropertyRNA *prop, EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
+static void property_enum_translate(
+ PropertyRNA *prop, EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
{
if (!(prop->flag & PROP_ENUM_NO_TRANSLATE)) {
int i;
@@ -1282,7 +1458,7 @@ static void property_enum_translate(PropertyRNA *prop, EnumPropertyItem **r_item
nitem = *r_item;
}
else {
- EnumPropertyItem *item = *r_item;
+ const EnumPropertyItem *item = *r_item;
int tot;
if (r_totitem) {
@@ -1315,31 +1491,36 @@ static void property_enum_translate(PropertyRNA *prop, EnumPropertyItem **r_item
}
#endif
-void RNA_property_enum_items_gettexted(bContext *C, PointerRNA *ptr, PropertyRNA *prop,
- EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
+void RNA_property_enum_items_gettexted(
+ bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
{
RNA_property_enum_items(C, ptr, prop, r_item, r_totitem, r_free);
#ifdef WITH_INTERNATIONAL
- property_enum_translate(prop, r_item, r_totitem, r_free);
+ /* Normally dropping 'const' is _not_ ok, in this case it's only modified if we own the memory
+ * so allow the exception (callers are creating new arrays in this case). */
+ property_enum_translate(prop, (EnumPropertyItem **)r_item, r_totitem, r_free);
#endif
}
-void RNA_property_enum_items_gettexted_all(bContext *C, PointerRNA *ptr, PropertyRNA *prop,
- EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
+void RNA_property_enum_items_gettexted_all(
+ bContext *C, PointerRNA *ptr, PropertyRNA *prop,
+ const EnumPropertyItem **r_item, int *r_totitem, bool *r_free)
{
EnumPropertyRNA *eprop = (EnumPropertyRNA *)rna_ensure_property(prop);
int mem_size = sizeof(EnumPropertyItem) * (eprop->totitem + 1);
/* first return all items */
+ EnumPropertyItem *item_array = MEM_mallocN(mem_size, "enum_gettext_all");
*r_free = true;
- *r_item = MEM_mallocN(mem_size, "enum_gettext_all");
- memcpy(*r_item, eprop->item, mem_size);
+ memcpy(item_array, eprop->item, mem_size);
- if (r_totitem)
+ if (r_totitem) {
*r_totitem = eprop->totitem;
+ }
if (eprop->itemf && (C != NULL || (prop->flag & PROP_ENUM_NO_CONTEXT))) {
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int i;
bool free = false;
@@ -1357,30 +1538,32 @@ void RNA_property_enum_items_gettexted_all(bContext *C, PointerRNA *ptr, Propert
/* items that do not exist on list are returned, but have their names/identifiers NULLed out */
for (i_fixed = 0; item[i_fixed].identifier; i_fixed++) {
- if (STREQ(item[i_fixed].identifier, (*r_item)[i].identifier)) {
+ if (STREQ(item[i_fixed].identifier, item_array[i].identifier)) {
exists = true;
break;
}
}
if (!exists) {
- (*r_item)[i].name = NULL;
- (*r_item)[i].identifier = "";
+ item_array[i].name = NULL;
+ item_array[i].identifier = "";
}
}
- if (free)
- MEM_freeN(item);
+ if (free) {
+ MEM_freeN((void *)item);
+ }
}
#ifdef WITH_INTERNATIONAL
- property_enum_translate(prop, r_item, r_totitem, r_free);
+ property_enum_translate(prop, &item_array, r_totitem, r_free);
#endif
+ *r_item = item_array;
}
bool RNA_property_enum_value(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const char *identifier, int *r_value)
{
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
bool free;
bool found;
@@ -1397,7 +1580,7 @@ bool RNA_property_enum_value(bContext *C, PointerRNA *ptr, PropertyRNA *prop, co
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
}
else {
@@ -1406,7 +1589,7 @@ bool RNA_property_enum_value(bContext *C, PointerRNA *ptr, PropertyRNA *prop, co
return found;
}
-bool RNA_enum_identifier(EnumPropertyItem *item, const int value, const char **r_identifier)
+bool RNA_enum_identifier(const EnumPropertyItem *item, const int value, const char **r_identifier)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -1418,7 +1601,7 @@ bool RNA_enum_identifier(EnumPropertyItem *item, const int value, const char **r
}
}
-int RNA_enum_bitflag_identifiers(EnumPropertyItem *item, const int value, const char **r_identifier)
+int RNA_enum_bitflag_identifiers(const EnumPropertyItem *item, const int value, const char **r_identifier)
{
int index = 0;
for (; item->identifier; item++) {
@@ -1430,7 +1613,7 @@ int RNA_enum_bitflag_identifiers(EnumPropertyItem *item, const int value, const
return index;
}
-bool RNA_enum_name(EnumPropertyItem *item, const int value, const char **r_name)
+bool RNA_enum_name(const EnumPropertyItem *item, const int value, const char **r_name)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -1442,7 +1625,7 @@ bool RNA_enum_name(EnumPropertyItem *item, const int value, const char **r_name)
}
}
-bool RNA_enum_description(EnumPropertyItem *item, const int value, const char **r_description)
+bool RNA_enum_description(const EnumPropertyItem *item, const int value, const char **r_description)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -1454,7 +1637,7 @@ bool RNA_enum_description(EnumPropertyItem *item, const int value, const char **
}
}
-int RNA_enum_from_identifier(EnumPropertyItem *item, const char *identifier)
+int RNA_enum_from_identifier(const EnumPropertyItem *item, const char *identifier)
{
int i = 0;
for (; item->identifier; item++, i++) {
@@ -1465,7 +1648,7 @@ int RNA_enum_from_identifier(EnumPropertyItem *item, const char *identifier)
return -1;
}
-int RNA_enum_from_value(EnumPropertyItem *item, const int value)
+int RNA_enum_from_value(const EnumPropertyItem *item, const int value)
{
int i = 0;
for (; item->identifier; item++, i++) {
@@ -1476,19 +1659,31 @@ int RNA_enum_from_value(EnumPropertyItem *item, const int value)
return -1;
}
+unsigned int RNA_enum_items_count(const EnumPropertyItem *item)
+{
+ unsigned int i = 0;
+
+ while (item->identifier) {
+ item++;
+ i++;
+ }
+
+ return i;
+}
+
bool RNA_property_enum_identifier(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value,
const char **identifier)
{
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
bool free;
RNA_property_enum_items(C, ptr, prop, &item, NULL, &free);
if (item) {
bool result;
result = RNA_enum_identifier(item, value, identifier);
- if (free)
- MEM_freeN(item);
-
+ if (free) {
+ MEM_freeN((void *)item);
+ }
return result;
}
return false;
@@ -1496,15 +1691,16 @@ bool RNA_property_enum_identifier(bContext *C, PointerRNA *ptr, PropertyRNA *pro
bool RNA_property_enum_name(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value, const char **name)
{
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
bool free;
RNA_property_enum_items(C, ptr, prop, &item, NULL, &free);
if (item) {
bool result;
result = RNA_enum_name(item, value, name);
- if (free)
- MEM_freeN(item);
+ if (free) {
+ MEM_freeN((void *)item);
+ }
return result;
}
@@ -1532,7 +1728,7 @@ bool RNA_property_enum_item_from_value(
bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value,
EnumPropertyItem *r_item)
{
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
bool free;
RNA_property_enum_items(C, ptr, prop, &item, NULL, &free);
@@ -1548,8 +1744,9 @@ bool RNA_property_enum_item_from_value(
result = false;
}
- if (free)
- MEM_freeN(item);
+ if (free) {
+ MEM_freeN((void *)item);
+ }
return result;
}
@@ -1576,7 +1773,7 @@ bool RNA_property_enum_item_from_value_gettexted(
int RNA_property_enum_bitflag_identifiers(bContext *C, PointerRNA *ptr, PropertyRNA *prop, const int value,
const char **identifier)
{
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
bool free;
RNA_property_enum_items(C, ptr, prop, &item, NULL, &free);
@@ -1584,7 +1781,7 @@ int RNA_property_enum_bitflag_identifiers(bContext *C, PointerRNA *ptr, Property
int result;
result = RNA_enum_bitflag_identifiers(item, value, identifier);
if (free)
- MEM_freeN(item);
+ MEM_freeN((void *)item);
return result;
}
@@ -1633,7 +1830,7 @@ bool RNA_property_editable(PointerRNA *ptr, PropertyRNA *prop)
return ((flag & PROP_EDITABLE) &&
(flag & PROP_REGISTER) == 0 &&
- (!id || !ID_IS_LINKED_DATABLOCK(id) || (prop->flag & PROP_LIB_EXCEPTION)));
+ (!id || !ID_IS_LINKED(id) || (prop->flag & PROP_LIB_EXCEPTION)));
}
/**
@@ -1654,14 +1851,14 @@ bool RNA_property_editable_info(PointerRNA *ptr, PropertyRNA *prop, const char *
else {
flag = prop->flag;
if ((flag & PROP_EDITABLE) == 0 || (flag & PROP_REGISTER)) {
- *r_info = "This property is for internal use only and can't be edited.";
+ *r_info = N_("This property is for internal use only and can't be edited");
}
}
/* property from linked data-block */
- if (id && ID_IS_LINKED_DATABLOCK(id) && (prop->flag & PROP_LIB_EXCEPTION) == 0) {
+ if (id && ID_IS_LINKED(id) && (prop->flag & PROP_LIB_EXCEPTION) == 0) {
if (!(*r_info)[0]) {
- *r_info = "Can't edit this property from a linked data-block.";
+ *r_info = N_("Can't edit this property from a linked data-block");
}
return false;
}
@@ -1701,7 +1898,7 @@ bool RNA_property_editable_index(PointerRNA *ptr, PropertyRNA *prop, int index)
id = ptr->id.data;
- return (flag & PROP_EDITABLE) && (!id || !ID_IS_LINKED_DATABLOCK(id) || (prop->flag & PROP_LIB_EXCEPTION));
+ return (flag & PROP_EDITABLE) && (!id || !ID_IS_LINKED(id) || (prop->flag & PROP_LIB_EXCEPTION));
}
bool RNA_property_animateable(PointerRNA *ptr, PropertyRNA *prop)
@@ -2816,6 +3013,42 @@ void RNA_property_string_set(PointerRNA *ptr, PropertyRNA *prop, const char *val
}
}
+void RNA_property_string_set_bytes(PointerRNA *ptr, PropertyRNA *prop, const char *value, int len)
+{
+ StringPropertyRNA *sprop = (StringPropertyRNA *)prop;
+ IDProperty *idprop;
+
+ BLI_assert(RNA_property_type(prop) == PROP_STRING);
+ BLI_assert(RNA_property_subtype(prop) == PROP_BYTESTRING);
+
+ if ((idprop = rna_idproperty_check(&prop, ptr))) {
+ IDP_ResizeArray(idprop, len);
+ memcpy(idprop->data.pointer, value, (size_t)len);
+
+ rna_idproperty_touch(idprop);
+ }
+ else if (sprop->set) {
+ /* XXX, should take length argument (currently not used). */
+ sprop->set(ptr, value); /* set function needs to clamp its self */
+ }
+ else if (sprop->set_ex) {
+ /* XXX, should take length argument (currently not used). */
+ sprop->set_ex(ptr, prop, value); /* set function needs to clamp its self */
+ }
+ else if (prop->flag & PROP_EDITABLE) {
+ IDProperty *group;
+
+ group = RNA_struct_idprops(ptr, 1);
+ if (group) {
+ IDPropertyTemplate val = {0};
+ val.string.str = value;
+ val.string.len = len;
+ val.string.subtype = IDP_STRING_SUB_BYTE;
+ IDP_AddToGroup(group, IDP_New(IDP_STRING, &val, prop->identifier));
+ }
+ }
+}
+
void RNA_property_string_get_default(PointerRNA *UNUSED(ptr), PropertyRNA *prop, char *value)
{
StringPropertyRNA *sprop = (StringPropertyRNA *)rna_ensure_property(prop);
@@ -2927,7 +3160,7 @@ void *RNA_property_enum_py_data_get(PropertyRNA *prop)
*/
int RNA_property_enum_step(const bContext *C, PointerRNA *ptr, PropertyRNA *prop, int from_value, int step)
{
- EnumPropertyItem *item_array;
+ const EnumPropertyItem *item_array;
int totitem;
bool free;
int result_value = from_value;
@@ -2951,7 +3184,7 @@ int RNA_property_enum_step(const bContext *C, PointerRNA *ptr, PropertyRNA *prop
}
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
return result_value;
@@ -2967,6 +3200,10 @@ PointerRNA RNA_property_pointer_get(PointerRNA *ptr, PropertyRNA *prop)
if ((idprop = rna_idproperty_check(&prop, ptr))) {
pprop = (PointerPropertyRNA *)prop;
+ if (RNA_struct_is_ID(pprop->type)) {
+ return rna_pointer_inherit_refine(ptr, pprop->type, IDP_Id(idprop));
+ }
+
/* for groups, data is idprop itself */
if (pprop->typef)
return rna_pointer_inherit_refine(ptr, pprop->typef(ptr), idprop);
@@ -2989,22 +3226,32 @@ PointerRNA RNA_property_pointer_get(PointerRNA *ptr, PropertyRNA *prop)
void RNA_property_pointer_set(PointerRNA *ptr, PropertyRNA *prop, PointerRNA ptr_value)
{
- /*IDProperty *idprop;*/
-
+ PointerPropertyRNA *pprop = (PointerPropertyRNA *)prop;
BLI_assert(RNA_property_type(prop) == PROP_POINTER);
- if ((/*idprop = */ rna_idproperty_check(&prop, ptr))) {
- /* not supported */
- /* rna_idproperty_touch(idprop); */
+ /* Check types */
+ if (ptr_value.type != NULL && !RNA_struct_is_a(ptr_value.type, pprop->type)) {
+ printf("%s: expected %s type, not %s.\n", __func__, pprop->type->identifier, ptr_value.type->identifier);
+ return;
}
- else {
- PointerPropertyRNA *pprop = (PointerPropertyRNA *)prop;
- if (pprop->set &&
- !((prop->flag & PROP_NEVER_NULL) && ptr_value.data == NULL) &&
- !((prop->flag & PROP_ID_SELF_CHECK) && ptr->id.data == ptr_value.id.data))
- {
- pprop->set(ptr, ptr_value);
+ /* RNA */
+ if (pprop->set &&
+ !((prop->flag & PROP_NEVER_NULL) && ptr_value.data == NULL) &&
+ !((prop->flag & PROP_ID_SELF_CHECK) && ptr->id.data == ptr_value.id.data))
+ {
+ pprop->set(ptr, ptr_value);
+ }
+ /* IDProperty */
+ else if (prop->flag & PROP_EDITABLE) {
+ IDPropertyTemplate val = {0};
+ IDProperty *group;
+
+ val.id = ptr_value.data;
+
+ group = RNA_struct_idprops(ptr, true);
+ if (group) {
+ IDP_ReplaceInGroup(group, IDP_New(IDP_ID, &val, prop->identifier));
}
}
}
@@ -5211,7 +5458,7 @@ void RNA_enum_set_identifier(bContext *C, PointerRNA *ptr, const char *name, con
bool RNA_enum_is_equal(bContext *C, PointerRNA *ptr, const char *name, const char *enumname)
{
PropertyRNA *prop = RNA_struct_find_property(ptr, name);
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
bool free;
if (prop) {
@@ -5225,7 +5472,7 @@ bool RNA_enum_is_equal(bContext *C, PointerRNA *ptr, const char *name, const cha
}
if (free) {
- MEM_freeN(item);
+ MEM_freeN((void *)item);
}
if (i != -1) {
@@ -5241,7 +5488,7 @@ bool RNA_enum_is_equal(bContext *C, PointerRNA *ptr, const char *name, const cha
}
}
-bool RNA_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *r_value)
+bool RNA_enum_value_from_id(const EnumPropertyItem *item, const char *identifier, int *r_value)
{
const int i = RNA_enum_from_identifier(item, identifier);
if (i != -1) {
@@ -5253,7 +5500,7 @@ bool RNA_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int
}
}
-bool RNA_enum_id_from_value(EnumPropertyItem *item, int value, const char **r_identifier)
+bool RNA_enum_id_from_value(const EnumPropertyItem *item, int value, const char **r_identifier)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -5265,7 +5512,7 @@ bool RNA_enum_id_from_value(EnumPropertyItem *item, int value, const char **r_id
}
}
-bool RNA_enum_icon_from_value(EnumPropertyItem *item, int value, int *r_icon)
+bool RNA_enum_icon_from_value(const EnumPropertyItem *item, int value, int *r_icon)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -5277,7 +5524,7 @@ bool RNA_enum_icon_from_value(EnumPropertyItem *item, int value, int *r_icon)
}
}
-bool RNA_enum_name_from_value(EnumPropertyItem *item, int value, const char **r_name)
+bool RNA_enum_name_from_value(const EnumPropertyItem *item, int value, const char **r_name)
{
const int i = RNA_enum_from_value(item, value);
if (i != -1) {
@@ -5486,7 +5733,7 @@ void RNA_struct_property_unset(PointerRNA *ptr, const char *identifier)
}
}
-bool RNA_property_is_idprop(PropertyRNA *prop)
+bool RNA_property_is_idprop(const PropertyRNA *prop)
{
return (prop->magic != RNA_MAGIC);
}
@@ -5543,7 +5790,7 @@ char *RNA_pointer_as_string_id(bContext *C, PointerRNA *ptr)
static char *rna_pointer_as_string__bldata(PointerRNA *ptr)
{
- if (ptr->type == NULL) {
+ if (ptr->type == NULL || ptr->id.data == NULL) {
return BLI_strdup("None");
}
else if (RNA_struct_is_ID(ptr->type)) {
@@ -5554,9 +5801,13 @@ static char *rna_pointer_as_string__bldata(PointerRNA *ptr)
}
}
-char *RNA_pointer_as_string(bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *prop_ptr, PointerRNA *ptr_prop)
+char *RNA_pointer_as_string(bContext *C, PointerRNA *ptr, PropertyRNA *prop_ptr, PointerRNA *ptr_prop)
{
- if (RNA_property_flag(prop_ptr) & PROP_IDPROPERTY) {
+ IDProperty *prop;
+ if (ptr_prop->data == NULL) {
+ return BLI_strdup("None");
+ }
+ else if ((prop = rna_idproperty_check(&prop_ptr, ptr)) && prop->type != IDP_ID) {
return RNA_pointer_as_string_id(C, ptr_prop);
}
else {
@@ -5791,14 +6042,14 @@ char *RNA_property_as_string(bContext *C, PointerRNA *ptr, PropertyRNA *prop, in
if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
/* represent as a python set */
if (val) {
- EnumPropertyItem *item_array;
+ const EnumPropertyItem *item_array;
bool free;
BLI_dynstr_append(dynstr, "{");
RNA_property_enum_items(C, ptr, prop, &item_array, NULL, &free);
if (item_array) {
- EnumPropertyItem *item = item_array;
+ const EnumPropertyItem *item = item_array;
bool is_first = true;
for (; item->identifier; item++) {
if (item->identifier[0] && item->value & val) {
@@ -5808,7 +6059,7 @@ char *RNA_property_as_string(bContext *C, PointerRNA *ptr, PropertyRNA *prop, in
}
if (free) {
- MEM_freeN(item_array);
+ MEM_freeN((void *)item_array);
}
}
@@ -6397,7 +6648,7 @@ static int rna_function_parameter_parse(PointerRNA *ptr, PropertyRNA *prop, Prop
tid, fid, pid, RNA_struct_identifier(ptype), RNA_struct_identifier(srna));
return -1;
}
-
+
*((void **)dest) = *((void **)src);
break;
@@ -6651,6 +6902,12 @@ int RNA_function_call_direct_va_lookup(bContext *C, ReportList *reports, Pointer
return 0;
}
+const char *RNA_translate_ui_text(
+ const char *text, const char *text_ctxt, StructRNA *type, PropertyRNA *prop, int translate)
+{
+ return rna_translate_ui_text(text, text_ctxt, type, prop, translate);
+}
+
bool RNA_property_reset(PointerRNA *ptr, PropertyRNA *prop, int index)
{
int len;
diff --git a/source/blender/makesrna/intern/rna_action.c b/source/blender/makesrna/intern/rna_action.c
index 0c4c7ddac81..d398ce95a52 100644
--- a/source/blender/makesrna/intern/rna_action.c
+++ b/source/blender/makesrna/intern/rna_action.c
@@ -34,6 +34,8 @@
#include "BLI_utildefines.h"
+#include "BLT_translation.h"
+
#include "BKE_action.h"
#include "RNA_access.h"
@@ -731,6 +733,7 @@ static void rna_def_action(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "ID Root Type",
"Type of ID block that action can be used on - "
"DO NOT CHANGE UNLESS YOU KNOW WHAT YOU ARE DOING");
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_ID);
/* API calls */
RNA_api_action(srna);
diff --git a/source/blender/makesrna/intern/rna_actuator.c b/source/blender/makesrna/intern/rna_actuator.c
index 004acbe4dbd..26ec813a14f 100644
--- a/source/blender/makesrna/intern/rna_actuator.c
+++ b/source/blender/makesrna/intern/rna_actuator.c
@@ -47,7 +47,7 @@
#include "WM_types.h"
/* Always keep in alphabetical order */
-static EnumPropertyItem actuator_type_items[] = {
+static const EnumPropertyItem actuator_type_items[] = {
{ACT_ACTION, "ACTION", 0, "Action", ""},
{ACT_ARMATURE, "ARMATURE", 0, "Armature", ""},
{ACT_CAMERA, "CAMERA", 0, "Camera", ""},
@@ -432,7 +432,7 @@ static void rna_StateActuator_state_set(PointerRNA *ptr, const int *values)
}
/* Always keep in alphabetical order */
-EnumPropertyItem *rna_Actuator_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *rna_Actuator_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
Object *ob = NULL;
@@ -579,7 +579,7 @@ static void rna_def_action_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_ACTION_PLAY, "PLAY", 0, "Play", ""},
{ACT_ACTION_PINGPONG, "PINGPONG", 0, "Ping Pong", ""},
{ACT_ACTION_FLIPPER, "FLIPPER", 0, "Flipper", ""},
@@ -592,7 +592,7 @@ static void rna_def_action_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_blend_items[] = {
+ static const EnumPropertyItem prop_blend_items[] = {
{ACT_ACTION_BLEND, "BLEND", 0, "Blend", ""},
{ACT_ACTION_ADD, "ADD", 0, "Add", ""},
{0, NULL, 0, NULL, NULL}
@@ -714,7 +714,7 @@ static void rna_def_object_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_OBJECT_NORMAL, "OBJECT_NORMAL", 0, "Simple Motion", ""},
{ACT_OBJECT_SERVO, "OBJECT_SERVO", 0, "Servo Control", ""},
{ACT_OBJECT_CHARACTER, "OBJECT_CHARACTER", 0, "Character Motion", ""},
@@ -915,7 +915,7 @@ static void rna_def_camera_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_axis_items[] = {
+ static const EnumPropertyItem prop_axis_items[] = {
{OB_POSX, "POS_X", 0, "+X", "Camera tries to get behind the X axis"},
{OB_POSY, "POS_Y", 0, "+Y", "Camera tries to get behind the Y axis"},
{OB_NEGX, "NEG_X", 0, "-X", "Camera tries to get behind the -X axis"},
@@ -970,7 +970,7 @@ static void rna_def_sound_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_SND_PLAY_STOP_SOUND, "PLAYSTOP", 0, "Play Stop", ""},
{ACT_SND_PLAY_END_SOUND, "PLAYEND", 0, "Play End", ""},
{ACT_SND_LOOP_STOP_SOUND, "LOOPSTOP", 0, "Loop Stop", ""},
@@ -1072,7 +1072,7 @@ static void rna_def_property_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_PROP_ASSIGN, "ASSIGN", 0, "Assign", ""},
{ACT_PROP_ADD, "ADD", 0, "Add", ""},
{ACT_PROP_COPY, "COPY", 0, "Copy", ""},
@@ -1120,7 +1120,7 @@ static void rna_def_constraint_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_CONST_TYPE_LOC, "LOC", 0, "Location Constraint", ""},
{ACT_CONST_TYPE_DIST, "DIST", 0, "Distance Constraint", ""},
{ACT_CONST_TYPE_ORI, "ORI", 0, "Orientation Constraint", ""},
@@ -1128,7 +1128,7 @@ static void rna_def_constraint_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_limit_items[] = {
+ static const EnumPropertyItem prop_limit_items[] = {
{ACT_CONST_NONE, "NONE", 0, "None", ""},
{ACT_CONST_LOCX, "LOCX", 0, "Loc X", ""},
{ACT_CONST_LOCY, "LOCY", 0, "Loc Y", ""},
@@ -1136,7 +1136,7 @@ static void rna_def_constraint_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_direction_items[] = {
+ static const EnumPropertyItem prop_direction_items[] = {
{ACT_CONST_NONE, "NONE", 0, "None", ""},
{ACT_CONST_DIRPX, "DIRPX", 0, "X axis", ""},
{ACT_CONST_DIRPY, "DIRPY", 0, "Y axis", ""},
@@ -1147,7 +1147,7 @@ static void rna_def_constraint_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_direction_pos_items[] = {
+ static const EnumPropertyItem prop_direction_pos_items[] = {
{ACT_CONST_NONE, "NONE", 0, "None", ""},
{ACT_CONST_DIRPX, "DIRPX", 0, "X axis", ""},
{ACT_CONST_DIRPY, "DIRPY", 0, "Y axis", ""},
@@ -1339,7 +1339,7 @@ static void rna_def_edit_object_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_dyn_items[] = {
+ static const EnumPropertyItem prop_dyn_items[] = {
{ACT_EDOB_RESTORE_DYN, "RESTOREDYN", 0, "Restore Dynamics", ""},
{ACT_EDOB_SUSPEND_DYN, "SUSPENDDYN", 0, "Suspend Dynamics", ""},
{ACT_EDOB_ENABLE_RB, "ENABLERIGIDBODY", 0, "Enable Rigid Body", ""},
@@ -1348,7 +1348,7 @@ static void rna_def_edit_object_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_EDOB_ADD_OBJECT, "ADDOBJECT", 0, "Add Object", ""},
{ACT_EDOB_END_OBJECT, "ENDOBJECT", 0, "End Object", ""},
{ACT_EDOB_REPLACE_MESH, "REPLACEMESH", 0, "Replace Mesh", ""},
@@ -1357,7 +1357,7 @@ static void rna_def_edit_object_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_track_axis_items[] = {
+ static const EnumPropertyItem prop_track_axis_items[] = {
{ACT_TRACK_TRAXIS_X, "TRACKAXISX", 0, "X axis", ""},
{ACT_TRACK_TRAXIS_Y, "TRACKAXISY", 0, "Y axis", ""},
{ACT_TRACK_TRAXIS_Z, "TRACKAXISZ", 0, "Z axis", ""},
@@ -1367,7 +1367,7 @@ static void rna_def_edit_object_actuator(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_up_axis_items[] = {
+ static const EnumPropertyItem prop_up_axis_items[] = {
{ACT_TRACK_UP_X, "UPAXISX", 0, "X axis", ""},
{ACT_TRACK_UP_Y, "UPAXISY", 0, "Y axis", ""},
{ACT_TRACK_UP_Z, "UPAXISZ", 0, "Z axis", ""},
@@ -1484,7 +1484,7 @@ static void rna_def_scene_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_SCENE_RESTART, "RESTART", 0, "Restart", ""},
{ACT_SCENE_SET, "SET", 0, "Set Scene", ""},
{ACT_SCENE_CAMERA, "CAMERA", 0, "Set Camera", ""},
@@ -1525,7 +1525,7 @@ static void rna_def_random_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_distribution_items[] = {
+ static const EnumPropertyItem prop_distribution_items[] = {
{ACT_RANDOM_BOOL_CONST, "BOOL_CONSTANT", 0, "Bool Constant", ""},
{ACT_RANDOM_BOOL_UNIFORM, "BOOL_UNIFORM", 0, "Bool Uniform", ""},
{ACT_RANDOM_BOOL_BERNOUILLI, "BOOL_BERNOUILLI", 0, "Bool Bernoulli", ""},
@@ -1653,7 +1653,7 @@ static void rna_def_message_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_body_type_items[] = {
+ static const EnumPropertyItem prop_body_type_items[] = {
{ACT_MESG_MESG, "TEXT", 0, "Text", ""},
{ACT_MESG_PROP, "PROPERTY", 0, "Property", ""},
{0, NULL, 0, NULL, NULL}
@@ -1696,7 +1696,7 @@ static void rna_def_game_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
/* {ACT_GAME_LOAD, "LOAD", 0, "Load Game", ""}, */
/* {ACT_GAME_START, "START", 0, "Start Loaded Game", ""}, */
/* keeping the load/start hacky for compatibility with 2.49 */
@@ -1765,7 +1765,7 @@ static void rna_def_twodfilter_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_2DFILTER_ENABLED, "ENABLE", 0, "Enable Filter", ""},
{ACT_2DFILTER_DISABLED, "DISABLE", 0, "Disable Filter", ""},
{ACT_2DFILTER_NOFILTER, "REMOVE", 0, "Remove Filter", ""},
@@ -1826,7 +1826,7 @@ static void rna_def_parent_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_PARENT_SET, "SETPARENT", 0, "Set Parent", ""},
{ACT_PARENT_REMOVE, "REMOVEPARENT", 0, "Remove Parent", ""},
{0, NULL, 0, NULL, NULL}
@@ -1868,7 +1868,7 @@ static void rna_def_state_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_STATE_SET, "SET", 0, "Set State", ""},
{ACT_STATE_ADD, "ADD", 0, "Add State", ""},
{ACT_STATE_REMOVE, "REMOVE", 0, "Remove State", ""},
@@ -1898,7 +1898,7 @@ static void rna_def_armature_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_ARM_RUN, "RUN", 0, "Run Armature", ""},
{ACT_ARM_ENABLE, "ENABLE", 0, "Enable", ""},
{ACT_ARM_DISABLE, "DISABLE", 0, "Disable", ""},
@@ -1961,14 +1961,14 @@ static void rna_def_steering_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_STEERING_SEEK, "SEEK", 0, "Seek", ""},
{ACT_STEERING_FLEE, "FLEE", 0, "Flee", ""},
{ACT_STEERING_PATHFOLLOWING, "PATHFOLLOWING", 0, "Path following", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem facingaxis_items[] = {
+ static const EnumPropertyItem facingaxis_items[] = {
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
{3, "Z", 0, "Z", ""},
@@ -2070,13 +2070,13 @@ static void rna_def_mouse_actuator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{ACT_MOUSE_VISIBILITY, "VISIBILITY", 0, "Visibility", ""},
{ACT_MOUSE_LOOK, "LOOK", 0, "Look", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_object_axis_items[] = {
+ static const EnumPropertyItem prop_object_axis_items[] = {
{ACT_MOUSE_OBJECT_AXIS_X, "OBJECT_AXIS_X", 0, "X Axis", ""},
{ACT_MOUSE_OBJECT_AXIS_Y, "OBJECT_AXIS_Y", 0, "Y Axis", ""},
{ACT_MOUSE_OBJECT_AXIS_Z, "OBJECT_AXIS_Z", 0, "Z Axis", ""},
diff --git a/source/blender/makesrna/intern/rna_animation.c b/source/blender/makesrna/intern/rna_animation.c
index 9adbf5f6b2e..6779e74700d 100644
--- a/source/blender/makesrna/intern/rna_animation.c
+++ b/source/blender/makesrna/intern/rna_animation.c
@@ -32,6 +32,8 @@
#include "BLI_utildefines.h"
+#include "BLT_translation.h"
+
#include "MEM_guardedalloc.h"
#include "RNA_access.h"
@@ -45,7 +47,7 @@
#include "ED_keyframing.h"
/* exported for use in API */
-EnumPropertyItem rna_enum_keyingset_path_grouping_items[] = {
+const EnumPropertyItem rna_enum_keyingset_path_grouping_items[] = {
{KSP_GROUP_NAMED, "NAMED", 0, "Named Group", ""},
{KSP_GROUP_NONE, "NONE", 0, "None", ""},
{KSP_GROUP_KSNAME, "KEYINGSET", 0, "Keying Set Name", ""},
@@ -55,7 +57,7 @@ EnumPropertyItem rna_enum_keyingset_path_grouping_items[] = {
/* It would be cool to get rid of this 'INSERTKEY_' prefix in 'py strings' values, but it would break existing
* exported keyingset... :/
*/
-EnumPropertyItem rna_enum_keying_flag_items[] = {
+const EnumPropertyItem rna_enum_keying_flag_items[] = {
{INSERTKEY_NEEDED, "INSERTKEY_NEEDED", 0, "Only Needed",
"Only insert keyframes where they're needed in the relevant F-Curves"},
{INSERTKEY_MATRIX, "INSERTKEY_VISUAL", 0, "Visual Keying",
@@ -244,8 +246,9 @@ static void rna_KeyingSetInfo_unregister(Main *bmain, StructRNA *type)
ANIM_keyingset_info_unregister(bmain, ksi);
}
-static StructRNA *rna_KeyingSetInfo_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_KeyingSetInfo_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
KeyingSetInfo dummyksi = {NULL};
KeyingSetInfo *ksi;
@@ -268,9 +271,10 @@ static StructRNA *rna_KeyingSetInfo_register(Main *bmain, ReportList *reports, v
/* check if we have registered this info before, and remove it */
ksi = ANIM_keyingset_info_find_name(dummyksi.idname);
- if (ksi && ksi->ext.srna)
+ if (ksi && ksi->ext.srna) {
rna_KeyingSetInfo_unregister(bmain, ksi->ext.srna);
-
+ }
+
/* create a new KeyingSetInfo type */
ksi = MEM_callocN(sizeof(KeyingSetInfo), "python keying set info");
memcpy(ksi, &dummyksi, sizeof(KeyingSetInfo));
@@ -515,7 +519,7 @@ static void rna_KeyingSet_paths_clear(KeyingSet *keyingset, ReportList *reports)
/* needs wrapper function to push notifier */
static NlaTrack *rna_NlaTrack_new(AnimData *adt, bContext *C, NlaTrack *track)
{
- NlaTrack *new_track = add_nlatrack(adt, track);
+ NlaTrack *new_track = BKE_nlatrack_add(adt, track);
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_ADDED, NULL);
@@ -531,7 +535,7 @@ static void rna_NlaTrack_remove(AnimData *adt, bContext *C, ReportList *reports,
return;
}
- free_nlatrack(&adt->nla_tracks, track);
+ BKE_nlatrack_free(&adt->nla_tracks, track);
RNA_POINTER_INVALIDATE(track_ptr);
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_REMOVED, NULL);
@@ -671,7 +675,7 @@ static void rna_def_keyingset_info(BlenderRNA *brna)
/* Regarding why we don't use rna_def_common_keying_flags() here:
* - Using it would keep this case in sync with the other places
- * where these options are exposed (which are optimised for being
+ * where these options are exposed (which are optimized for being
* used in the UI).
* - Unlike all the other places, this case is used for defining
* new "built in" Keying Sets via the Python API. In that case,
@@ -742,6 +746,7 @@ static void rna_def_keyingset_path(BlenderRNA *brna)
RNA_def_property_enum_default(prop, ID_OB);
RNA_def_property_enum_funcs(prop, NULL, "rna_ksPath_id_type_set", NULL);
RNA_def_property_ui_text(prop, "ID Type", "Type of ID-block that can be used");
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_ID);
RNA_def_property_update(prop, NC_SCENE | ND_KEYINGSET | NA_EDITED, NULL); /* XXX: maybe a bit too noisy */
/* Group */
diff --git a/source/blender/makesrna/intern/rna_animviz.c b/source/blender/makesrna/intern/rna_animviz.c
index eea24bfb1e0..2ba067629a9 100644
--- a/source/blender/makesrna/intern/rna_animviz.c
+++ b/source/blender/makesrna/intern/rna_animviz.c
@@ -43,7 +43,7 @@
/* Which part of bone(s) get baked */
// TODO: icons?
-EnumPropertyItem rna_enum_motionpath_bake_location_items[] = {
+const EnumPropertyItem rna_enum_motionpath_bake_location_items[] = {
{MOTIONPATH_BAKE_HEADS, "HEADS", 0, "Heads", "Calculate bone paths from heads"},
{0, "TAILS", 0, "Tails", "Calculate bone paths from tails"},
//{MOTIONPATH_BAKE_CENTERS, "CENTROID", 0, "Centers", "Calculate bone paths from center of mass"},
@@ -174,6 +174,7 @@ static void rna_def_animviz_motion_path(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Use Bone Heads",
"For PoseBone paths, use the bone head location when calculating this path");
+ /* FIXME: Motion Paths are not currently editable... */
prop = RNA_def_property(srna, "is_modified", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", MOTIONPATH_FLAG_EDIT);
RNA_def_property_ui_text(prop, "Edit Path", "Path is being edited");
@@ -364,6 +365,12 @@ static void rna_def_animviz_paths(BlenderRNA *brna)
"(only for 'Around Current Frame' Onion-skinning method)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL); /* XXX since this is only for 3d-view drawing */
+
+ /* Readonly Property - Do any motion paths exist/need updating? (Mainly for bone paths) */
+ prop = RNA_def_property(srna, "has_motion_paths", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "path_bakeflag", MOTIONPATH_BAKE_HAS_PATHS);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE); /* NOTE: This is really an internal state var for convenience, so don't allow edits! */
+ RNA_def_property_ui_text(prop, "Has Motion Paths", "Are there any bone paths that will need updating (read-only)");
}
/* --- */
diff --git a/source/blender/makesrna/intern/rna_armature.c b/source/blender/makesrna/intern/rna_armature.c
index 07d295c8bbc..7feca708fe8 100644
--- a/source/blender/makesrna/intern/rna_armature.c
+++ b/source/blender/makesrna/intern/rna_armature.c
@@ -107,7 +107,7 @@ static EditBone *rna_Armature_edit_bone_new(bArmature *arm, ReportList *reports,
BKE_reportf(reports, RPT_ERROR, "Armature '%s' not in edit mode, cannot add an editbone", arm->id.name + 2);
return NULL;
}
- return ED_armature_edit_bone_add(arm, name);
+ return ED_armature_ebone_add(arm, name);
}
static void rna_Armature_edit_bone_remove(bArmature *arm, ReportList *reports, PointerRNA *ebone_ptr)
@@ -123,7 +123,7 @@ static void rna_Armature_edit_bone_remove(bArmature *arm, ReportList *reports, P
return;
}
- ED_armature_edit_bone_remove(arm, ebone);
+ ED_armature_ebone_remove(arm, ebone);
RNA_POINTER_INVALIDATE(ebone_ptr);
}
@@ -187,6 +187,9 @@ static void rna_Bone_select_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Po
}
WM_main_add_notifier(NC_GEOM | ND_DATA, id);
+
+ /* spaces that show animation data of the selected bone need updating */
+ WM_main_add_notifier(NC_ANIMATION | ND_ANIMCHAN, id);
}
static char *rna_Bone_path(PointerRNA *ptr)
@@ -423,7 +426,7 @@ static void rna_Armature_editbone_transform_update(Main *bmain, Scene *scene, Po
copy_v3_v3(child->head, ebone->tail);
if (arm->flag & ARM_MIRROR_EDIT) {
- eboflip = ED_armature_bone_get_mirrored(arm->edbo, ebone);
+ eboflip = ED_armature_ebone_get_mirrored(arm->edbo, ebone);
if (eboflip) {
eboflip->roll = -ebone->roll;
@@ -477,7 +480,7 @@ static int rna_Armature_is_editmode_get(PointerRNA *ptr)
static void rna_Armature_transform(struct bArmature *arm, float *mat)
{
- ED_armature_transform(arm, (float (*)[4])mat);
+ ED_armature_transform(arm, (float (*)[4])mat, true);
}
#else
@@ -539,7 +542,22 @@ void rna_def_bone_curved_common(StructRNA *srna, bool is_posebone)
RNA_def_property_range(prop, -5.0f, 5.0f);
RNA_def_property_ui_text(prop, "Out Y", "Y-axis handle offset for end of the B-Bone's curve, adjusts curvature");
RNA_DEF_CURVEBONE_UPDATE(prop, is_posebone);
+
+ /* Ease In/Out */
+ prop = RNA_def_property(srna, "bbone_easein", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "ease1");
+ RNA_def_property_range(prop, -5.0f, 5.0f);
+ RNA_def_property_float_default(prop, 1.0f);
+ RNA_def_property_ui_text(prop, "Ease In", "Length of first Bezier Handle (for B-Bones only)");
+ RNA_DEF_CURVEBONE_UPDATE(prop, is_posebone);
+ prop = RNA_def_property(srna, "bbone_easeout", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "ease2");
+ RNA_def_property_range(prop, -5.0f, 5.0f);
+ RNA_def_property_float_default(prop, 1.0f);
+ RNA_def_property_ui_text(prop, "Ease Out", "Length of second Bezier Handle (for B-Bones only)");
+ RNA_DEF_CURVEBONE_UPDATE(prop, is_posebone);
+
/* Scale In/Out */
prop = RNA_def_property(srna, "bbone_scalein", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "scaleIn");
@@ -677,18 +695,6 @@ static void rna_def_bone_common(StructRNA *srna, int editbone)
RNA_def_property_ui_text(prop, "B-Bone Segments", "Number of subdivisions of bone (for B-Bones only)");
RNA_def_property_update(prop, 0, "rna_Armature_update_data");
- prop = RNA_def_property(srna, "bbone_in", PROP_FLOAT, PROP_NONE);
- RNA_def_property_float_sdna(prop, NULL, "ease1");
- RNA_def_property_range(prop, 0.0f, 2.0f);
- RNA_def_property_ui_text(prop, "B-Bone Ease In", "Length of first Bezier Handle (for B-Bones only)");
- RNA_def_property_update(prop, 0, "rna_Armature_update_data");
-
- prop = RNA_def_property(srna, "bbone_out", PROP_FLOAT, PROP_NONE);
- RNA_def_property_float_sdna(prop, NULL, "ease2");
- RNA_def_property_range(prop, 0.0f, 2.0f);
- RNA_def_property_ui_text(prop, "B-Bone Ease Out", "Length of second Bezier Handle (for B-Bones only)");
- RNA_def_property_update(prop, 0, "rna_Armature_update_data");
-
prop = RNA_def_property(srna, "bbone_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "xwidth");
RNA_def_property_range(prop, 0.0f, 1000.0f);
@@ -971,7 +977,7 @@ static void rna_def_armature(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem prop_drawtype_items[] = {
+ static const EnumPropertyItem prop_drawtype_items[] = {
{ARM_OCTA, "OCTAHEDRAL", 0, "Octahedral", "Display bones as octahedral shape (default)"},
{ARM_LINE, "STICK", 0, "Stick", "Display bones as simple 2D lines with dots"},
{ARM_B_BONE, "BBONE", 0, "B-Bone", "Display bones as boxes, showing subdivision and B-Splines"},
@@ -980,12 +986,12 @@ static void rna_def_armature(BlenderRNA *brna)
{ARM_WIRE, "WIRE", 0, "Wire", "Display bones as thin wires, showing subdivision and B-Splines"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_vdeformer[] = {
+ static const EnumPropertyItem prop_vdeformer[] = {
{ARM_VDEF_BLENDER, "BLENDER", 0, "Blender", "Use Blender's armature vertex deformation"},
{ARM_VDEF_BGE_CPU, "BGE_CPU", 0, "BGE", "Use vertex deformation code optimized for the BGE"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_ghost_type_items[] = {
+ static const EnumPropertyItem prop_ghost_type_items[] = {
{ARM_GHOST_CUR, "CURRENT_FRAME", 0, "Around Frame",
"Display Ghosts of poses within a fixed number of frames around the current frame"},
{ARM_GHOST_RANGE, "RANGE", 0, "In Range", "Display Ghosts of poses within specified range"},
diff --git a/source/blender/makesrna/intern/rna_armature_api.c b/source/blender/makesrna/intern/rna_armature_api.c
index 0616331bc05..222baf99afd 100644
--- a/source/blender/makesrna/intern/rna_armature_api.c
+++ b/source/blender/makesrna/intern/rna_armature_api.c
@@ -46,7 +46,7 @@
static void rna_EditBone_align_roll(EditBone *ebo, float no[3])
{
- ebo->roll = ED_rollBoneToVector(ebo, no, false);
+ ebo->roll = ED_armature_ebone_roll_to_vector(ebo, no, false);
}
static float rna_Bone_do_envelope(Bone *bone, float *vec)
diff --git a/source/blender/makesrna/intern/rna_boid.c b/source/blender/makesrna/intern/rna_boid.c
index 72f67b86c23..fd3694e7c45 100644
--- a/source/blender/makesrna/intern/rna_boid.c
+++ b/source/blender/makesrna/intern/rna_boid.c
@@ -48,7 +48,7 @@
#include "WM_api.h"
#include "WM_types.h"
-EnumPropertyItem rna_enum_boidrule_type_items[] = {
+const EnumPropertyItem rna_enum_boidrule_type_items[] = {
{eBoidRuleType_Goal, "GOAL", 0, "Goal", "Go to assigned object or loudest assigned signal source"},
{eBoidRuleType_Avoid, "AVOID", 0, "Avoid", "Get away from assigned object or loudest assigned signal source"},
{eBoidRuleType_AvoidCollision, "AVOID_COLLISION", 0, "Avoid Collision",
@@ -71,7 +71,7 @@ EnumPropertyItem rna_enum_boidrule_type_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem boidruleset_type_items[] = {
+static const EnumPropertyItem boidruleset_type_items[] = {
{eBoidRulesetType_Fuzzy, "FUZZY", 0, "Fuzzy",
"Rules are gone through top to bottom (only the first rule which effect is above "
"fuzziness threshold is evaluated)"},
diff --git a/source/blender/makesrna/intern/rna_brush.c b/source/blender/makesrna/intern/rna_brush.c
index ac348c1750c..1fd17afdc60 100644
--- a/source/blender/makesrna/intern/rna_brush.c
+++ b/source/blender/makesrna/intern/rna_brush.c
@@ -43,13 +43,13 @@
#include "WM_types.h"
-static EnumPropertyItem prop_direction_items[] = {
+static const EnumPropertyItem prop_direction_items[] = {
{0, "ADD", 0, "Add", "Add effect of brush"},
{BRUSH_DIR_IN, "SUBTRACT", 0, "Subtract", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem sculpt_stroke_method_items[] = {
+static const EnumPropertyItem sculpt_stroke_method_items[] = {
{0, "DOTS", 0, "Dots", "Apply paint on each mouse move step"},
{BRUSH_DRAG_DOT, "DRAG_DOT", 0, "Drag Dot", "Allows a single dot to be carefully positioned"},
{BRUSH_SPACE, "SPACE", 0, "Space", "Limit brush application to the distance specified by spacing"},
@@ -62,7 +62,7 @@ static EnumPropertyItem sculpt_stroke_method_items[] = {
};
-EnumPropertyItem rna_enum_brush_sculpt_tool_items[] = {
+const EnumPropertyItem rna_enum_brush_sculpt_tool_items[] = {
{SCULPT_TOOL_BLOB, "BLOB", ICON_BRUSH_BLOB, "Blob", ""},
{SCULPT_TOOL_CLAY, "CLAY", ICON_BRUSH_CLAY, "Clay", ""},
{SCULPT_TOOL_CLAY_STRIPS, "CLAY_STRIPS", ICON_BRUSH_CLAY_STRIPS, "Clay Strips", ""},
@@ -86,7 +86,7 @@ EnumPropertyItem rna_enum_brush_sculpt_tool_items[] = {
};
-EnumPropertyItem rna_enum_brush_vertex_tool_items[] = {
+const EnumPropertyItem rna_enum_brush_vertex_tool_items[] = {
{PAINT_BLEND_MIX, "MIX", ICON_BRUSH_MIX, "Mix", "Use mix blending mode while painting"},
{PAINT_BLEND_ADD, "ADD", ICON_BRUSH_ADD, "Add", "Use add blending mode while painting"},
{PAINT_BLEND_SUB, "SUB", ICON_BRUSH_SUBTRACT, "Subtract", "Use subtract blending mode while painting"},
@@ -94,10 +94,25 @@ EnumPropertyItem rna_enum_brush_vertex_tool_items[] = {
{PAINT_BLEND_BLUR, "BLUR", ICON_BRUSH_BLUR, "Blur", "Blur the color with surrounding values"},
{PAINT_BLEND_LIGHTEN, "LIGHTEN", ICON_BRUSH_LIGHTEN, "Lighten", "Use lighten blending mode while painting"},
{PAINT_BLEND_DARKEN, "DARKEN", ICON_BRUSH_DARKEN, "Darken", "Use darken blending mode while painting"},
+ {PAINT_BLEND_AVERAGE, "AVERAGE", ICON_BRUSH_BLUR, "Average", "Use average blending mode while painting"},
+ {PAINT_BLEND_SMEAR, "SMEAR", ICON_BRUSH_BLUR, "Smear", "Use smear blending mode while painting"},
+ {PAINT_BLEND_COLORDODGE, "COLORDODGE", ICON_BRUSH_BLUR, "Color Dodge", "Use color dodge blending mode while painting" },
+ {PAINT_BLEND_DIFFERENCE, "DIFFERENCE", ICON_BRUSH_BLUR, "Difference", "Use difference blending mode while painting"},
+ {PAINT_BLEND_SCREEN, "SCREEN", ICON_BRUSH_BLUR, "Screen", "Use screen blending mode while painting"},
+ {PAINT_BLEND_HARDLIGHT, "HARDLIGHT", ICON_BRUSH_BLUR, "Hardlight", "Use hardlight blending mode while painting"},
+ {PAINT_BLEND_OVERLAY, "OVERLAY", ICON_BRUSH_BLUR, "Overlay", "Use overlay blending mode while painting"},
+ {PAINT_BLEND_SOFTLIGHT, "SOFTLIGHT", ICON_BRUSH_BLUR, "Softlight", "Use softlight blending mode while painting"},
+ {PAINT_BLEND_EXCLUSION, "EXCLUSION", ICON_BRUSH_BLUR, "Exclusion", "Use exclusion blending mode while painting"},
+ {PAINT_BLEND_LUMINOCITY, "LUMINOCITY", ICON_BRUSH_BLUR, "Luminocity", "Use luminocity blending mode while painting"},
+ {PAINT_BLEND_SATURATION, "SATURATION", ICON_BRUSH_BLUR, "Saturation", "Use saturation blending mode while painting"},
+ {PAINT_BLEND_HUE, "HUE", ICON_BRUSH_BLUR, "Hue", "Use hue blending mode while painting"},
+ {PAINT_BLEND_ALPHA_SUB, "ERASE_ALPHA", 0, "Erase Alpha", "Erase alpha while painting"},
+ {PAINT_BLEND_ALPHA_ADD, "ADD_ALPHA", 0, "Add Alpha", "Add alpha while painting"},
+
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_brush_image_tool_items[] = {
+const EnumPropertyItem rna_enum_brush_image_tool_items[] = {
{PAINT_TOOL_DRAW, "DRAW", ICON_BRUSH_TEXDRAW, "Draw", ""},
{PAINT_TOOL_SOFTEN, "SOFTEN", ICON_BRUSH_SOFTEN, "Soften", ""},
{PAINT_TOOL_SMEAR, "SMEAR", ICON_BRUSH_SMEAR, "Smear", ""},
@@ -113,7 +128,7 @@ EnumPropertyItem rna_enum_brush_image_tool_items[] = {
#include "RNA_access.h"
-#include "BKE_texture.h"
+#include "BKE_colorband.h"
#include "BKE_brush.h"
#include "BKE_icons.h"
#include "BKE_paint.h"
@@ -223,11 +238,7 @@ static int rna_SculptToolCapabilities_has_sculpt_plane_get(PointerRNA *ptr)
static int rna_SculptToolCapabilities_has_secondary_color_get(PointerRNA *ptr)
{
Brush *br = (Brush *)ptr->data;
- return ELEM(br->sculpt_tool,
- SCULPT_TOOL_BLOB, SCULPT_TOOL_CLAY, SCULPT_TOOL_CLAY_STRIPS,
- SCULPT_TOOL_CREASE, SCULPT_TOOL_DRAW, SCULPT_TOOL_FILL,
- SCULPT_TOOL_FLATTEN, SCULPT_TOOL_INFLATE, SCULPT_TOOL_PINCH,
- SCULPT_TOOL_SCRAPE);
+ return BKE_brush_sculpt_has_secondary_color(br);
}
static int rna_SculptToolCapabilities_has_smooth_stroke_get(PointerRNA *ptr)
@@ -419,7 +430,6 @@ static void rna_Brush_icon_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Poi
br->id.icon_id = 0;
if (br->flag & BRUSH_CUSTOM_ICON) {
- BKE_previewimg_id_ensure(&br->id);
BKE_icon_changed(BKE_icon_id_ensure(&br->id));
}
@@ -454,7 +464,7 @@ static void rna_Brush_use_gradient_set(PointerRNA *ptr, int value)
else br->flag &= ~BRUSH_USE_GRADIENT;
if ((br->flag & BRUSH_USE_GRADIENT) && br->gradient == NULL)
- br->gradient = add_colorband(true);
+ br->gradient = BKE_colorband_add(true);
}
static void rna_Brush_set_unprojected_radius(PointerRNA *ptr, float value)
@@ -466,48 +476,48 @@ static void rna_Brush_set_unprojected_radius(PointerRNA *ptr, float value)
brush->unprojected_radius = value;
}
-static EnumPropertyItem *rna_Brush_direction_itemf(bContext *C, PointerRNA *ptr,
+static const EnumPropertyItem *rna_Brush_direction_itemf(bContext *C, PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
- static EnumPropertyItem prop_default_items[] = {
+ static const EnumPropertyItem prop_default_items[] = {
{0, NULL, 0, NULL, NULL}
};
/* sculpt mode */
- static EnumPropertyItem prop_flatten_contrast_items[] = {
+ static const EnumPropertyItem prop_flatten_contrast_items[] = {
{0, "FLATTEN", 0, "Flatten", "Add effect of brush"},
{BRUSH_DIR_IN, "CONTRAST", 0, "Contrast", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_fill_deepen_items[] = {
+ static const EnumPropertyItem prop_fill_deepen_items[] = {
{0, "FILL", 0, "Fill", "Add effect of brush"},
{BRUSH_DIR_IN, "DEEPEN", 0, "Deepen", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_scrape_peaks_items[] = {
+ static const EnumPropertyItem prop_scrape_peaks_items[] = {
{0, "SCRAPE", 0, "Scrape", "Add effect of brush"},
{BRUSH_DIR_IN, "PEAKS", 0, "Peaks", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_pinch_magnify_items[] = {
+ static const EnumPropertyItem prop_pinch_magnify_items[] = {
{0, "PINCH", 0, "Pinch", "Add effect of brush"},
{BRUSH_DIR_IN, "MAGNIFY", 0, "Magnify", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_inflate_deflate_items[] = {
+ static const EnumPropertyItem prop_inflate_deflate_items[] = {
{0, "INFLATE", 0, "Inflate", "Add effect of brush"},
{BRUSH_DIR_IN, "DEFLATE", 0, "Deflate", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}
};
/* texture paint mode */
- static EnumPropertyItem prop_soften_sharpen_items[] = {
+ static const EnumPropertyItem prop_soften_sharpen_items[] = {
{0, "SOFTEN", 0, "Soften", "Blur effect of brush"},
{BRUSH_DIR_IN, "SHARPEN", 0, "Sharpen", "Sharpen effect of brush"},
{0, NULL, 0, NULL, NULL}
@@ -572,12 +582,12 @@ static EnumPropertyItem *rna_Brush_direction_itemf(bContext *C, PointerRNA *ptr,
}
}
-static EnumPropertyItem *rna_Brush_stroke_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_Brush_stroke_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
- PaintMode mode = BKE_paintmode_get_active_from_context(C);
+ ePaintMode mode = BKE_paintmode_get_active_from_context(C);
- static EnumPropertyItem brush_stroke_method_items[] = {
+ static const EnumPropertyItem brush_stroke_method_items[] = {
{0, "DOTS", 0, "Dots", "Apply paint on each mouse move step"},
{BRUSH_SPACE, "SPACE", 0, "Space", "Limit brush application to the distance specified by spacing"},
{BRUSH_AIRBRUSH, "AIRBRUSH", 0, "Airbrush", "Keep applying paint effect while holding mouse (spray)"},
@@ -603,7 +613,7 @@ static void rna_def_brush_texture_slot(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_map_mode_items[] = {
+ static const EnumPropertyItem prop_map_mode_items[] = {
{MTEX_MAP_MODE_VIEW, "VIEW_PLANE", 0, "View Plane", ""},
{MTEX_MAP_MODE_AREA, "AREA_PLANE", 0, "Area Plane", ""},
{MTEX_MAP_MODE_TILED, "TILED", 0, "Tiled", ""},
@@ -613,7 +623,7 @@ static void rna_def_brush_texture_slot(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_tex_paint_map_mode_items[] = {
+ static const EnumPropertyItem prop_tex_paint_map_mode_items[] = {
{MTEX_MAP_MODE_VIEW, "VIEW_PLANE", 0, "View Plane", ""},
{MTEX_MAP_MODE_TILED, "TILED", 0, "Tiled", ""},
{MTEX_MAP_MODE_3D, "3D", 0, "3D", ""},
@@ -622,7 +632,7 @@ static void rna_def_brush_texture_slot(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mask_paint_map_mode_items[] = {
+ static const EnumPropertyItem prop_mask_paint_map_mode_items[] = {
{MTEX_MAP_MODE_VIEW, "VIEW_PLANE", 0, "View Plane", ""},
{MTEX_MAP_MODE_TILED, "TILED", 0, "Tiled", ""},
{MTEX_MAP_MODE_RANDOM, "RANDOM", 0, "Random", ""},
@@ -788,7 +798,7 @@ static void rna_def_brush(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_blend_items[] = {
+ static const EnumPropertyItem prop_blend_items[] = {
{IMB_BLEND_MIX, "MIX", 0, "Mix", "Use mix blending mode while painting"},
{IMB_BLEND_ADD, "ADD", 0, "Add", "Use add blending mode while painting"},
{IMB_BLEND_SUB, "SUB", 0, "Subtract", "Use subtract blending mode while painting"},
@@ -816,7 +826,7 @@ static void rna_def_brush(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_sculpt_plane_items[] = {
+ static const EnumPropertyItem brush_sculpt_plane_items[] = {
{SCULPT_DISP_DIR_AREA, "AREA", 0, "Area Plane", ""},
{SCULPT_DISP_DIR_VIEW, "VIEW", 0, "View Plane", ""},
{SCULPT_DISP_DIR_X, "X", 0, "X Plane", ""},
@@ -825,32 +835,32 @@ static void rna_def_brush(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_mask_tool_items[] = {
+ static const EnumPropertyItem brush_mask_tool_items[] = {
{BRUSH_MASK_DRAW, "DRAW", 0, "Draw", ""},
{BRUSH_MASK_SMOOTH, "SMOOTH", 0, "Smooth", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_blur_mode_items[] = {
+ static const EnumPropertyItem brush_blur_mode_items[] = {
{KERNEL_BOX, "BOX", 0, "Box", ""},
{KERNEL_GAUSSIAN, "GAUSSIAN", 0, "Gaussian", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_gradient_items[] = {
+ static const EnumPropertyItem brush_gradient_items[] = {
{BRUSH_GRADIENT_PRESSURE, "PRESSURE", 0, "Pressure", ""},
{BRUSH_GRADIENT_SPACING_REPEAT, "SPACING_REPEAT", 0, "Repeat", ""},
{BRUSH_GRADIENT_SPACING_CLAMP, "SPACING_CLAMP", 0, "Clamp", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_gradient_fill_items[] = {
+ static const EnumPropertyItem brush_gradient_fill_items[] = {
{BRUSH_GRADIENT_LINEAR, "LINEAR", 0, "Linear", ""},
{BRUSH_GRADIENT_RADIAL, "RADIAL", 0, "Radial", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem brush_mask_pressure_items[] = {
+ static const EnumPropertyItem brush_mask_pressure_items[] = {
{0, "NONE", 0, "Off", ""},
{BRUSH_MASK_PRESSURE_RAMP, "RAMP", ICON_STYLUS_PRESSURE, "Ramp", ""},
{BRUSH_MASK_PRESSURE_CUTOFF, "CUTOFF", ICON_STYLUS_PRESSURE, "Cutoff", ""},
@@ -1105,7 +1115,20 @@ static void rna_def_brush(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Blur Mode", "");
RNA_def_property_update(prop, 0, "rna_Brush_update");
+ prop = RNA_def_property(srna, "falloff_angle", PROP_FLOAT, PROP_ANGLE);
+ RNA_def_property_float_sdna(prop, NULL, "falloff_angle");
+ RNA_def_property_range(prop, 0, M_PI / 2);
+ RNA_def_property_ui_text(prop, "Falloff Angle",
+ "Paint most on faces pointing towards the view according to this angle");
+ RNA_def_property_update(prop, 0, "rna_Brush_update");
+
/* flag */
+ /* This is an enum but its unlikely we add other shapes, so expose as a boolean. */
+ prop = RNA_def_property(srna, "use_projected", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "falloff_shape", BRUSH_AIRBRUSH);
+ RNA_def_property_ui_text(prop, "2D Falloff", "Apply brush influence in 2D circle instead of a sphere");
+ RNA_def_property_update(prop, 0, "rna_Brush_update");
+
prop = RNA_def_property(srna, "use_airbrush", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_AIRBRUSH);
RNA_def_property_ui_text(prop, "Airbrush", "Keep applying paint effect while holding mouse (spray)");
@@ -1182,6 +1205,11 @@ static void rna_def_brush(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Use Front-Face", "Brush only affects vertexes that face the viewer");
RNA_def_property_update(prop, 0, "rna_Brush_update");
+ prop = RNA_def_property(srna, "use_frontface_falloff", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_FRONTFACE_FALLOFF);
+ RNA_def_property_ui_text(prop, "Use Front-Face Falloff", "Blend brush influence by how much they face the front");
+ RNA_def_property_update(prop, 0, "rna_Brush_update");
+
prop = RNA_def_property(srna, "use_anchor", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", BRUSH_ANCHORED);
RNA_def_property_ui_text(prop, "Anchored", "Keep the brush anchored to the initial location");
@@ -1248,7 +1276,7 @@ static void rna_def_brush(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Restore Mesh", "Allow a single dot to be carefully positioned");
RNA_def_property_update(prop, 0, "rna_Brush_update");
- /* only for projection paint, TODO, other paint modes */
+ /* only for projection paint & vertex paint, TODO, other paint modes */
prop = RNA_def_property(srna, "use_alpha", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", BRUSH_LOCK_ALPHA);
RNA_def_property_ui_text(prop, "Alpha", "When this is disabled, lock alpha while painting");
diff --git a/source/blender/makesrna/intern/rna_cachefile.c b/source/blender/makesrna/intern/rna_cachefile.c
index 09fdeb15b10..73928d377f1 100644
--- a/source/blender/makesrna/intern/rna_cachefile.c
+++ b/source/blender/makesrna/intern/rna_cachefile.c
@@ -34,11 +34,11 @@
#ifdef RNA_RUNTIME
+#include "BLI_string.h"
+
#include "BKE_cachefile.h"
#include "BKE_depsgraph.h"
-#include "BLI_string.h"
-
#include "DEG_depsgraph.h"
#include "WM_api.h"
@@ -148,6 +148,15 @@ static void rna_def_cachefile(BlenderRNA *brna)
" or to determine which file to use in a file sequence");
RNA_def_property_update(prop, 0, "rna_CacheFile_update");
+ prop = RNA_def_property(srna, "frame_offset", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "frame_offset");
+ RNA_def_property_range(prop, -MAXFRAME, MAXFRAME);
+ RNA_def_property_ui_text(prop, "Frame Offset",
+ "Subtracted from the current frame to use for "
+ "looking up the data in the cache file, or to "
+ "determine which file to use in a file sequence");
+ RNA_def_property_update(prop, 0, "rna_CacheFile_update");
+
/* ----------------- Axis Conversion ----------------- */
prop = RNA_def_property(srna, "forward_axis", PROP_ENUM, PROP_NONE);
diff --git a/source/blender/makesrna/intern/rna_camera.c b/source/blender/makesrna/intern/rna_camera.c
index 078ba13d76d..981ae75e7c5 100644
--- a/source/blender/makesrna/intern/rna_camera.c
+++ b/source/blender/makesrna/intern/rna_camera.c
@@ -39,8 +39,11 @@
#ifdef RNA_RUNTIME
#include "BKE_camera.h"
-#include "BKE_object.h"
#include "BKE_depsgraph.h"
+#include "BKE_object.h"
+#include "BKE_sequencer.h"
+
+#include "WM_api.h"
static float rna_Camera_angle_get(PointerRNA *ptr)
{
@@ -94,6 +97,14 @@ static void rna_Camera_dependency_update(Main *bmain, Scene *UNUSED(scene), Poin
DAG_id_tag_update(&camera->id, 0);
}
+static void rna_Camera_dof_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *UNUSED(ptr))
+{
+ /* TODO(sergey): Can be more selective here. */
+ BKE_sequencer_cache_cleanup();
+ BKE_sequencer_preprocessed_cache_cleanup();
+ WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, scene);
+}
+
#else
static void rna_def_camera_stereo_data(BlenderRNA *brna)
@@ -101,14 +112,14 @@ static void rna_def_camera_stereo_data(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem convergence_mode_items[] = {
+ static const EnumPropertyItem convergence_mode_items[] = {
{CAM_S3D_OFFAXIS, "OFFAXIS", 0, "Off-Axis", "Off-axis frustums converging in a plane"},
{CAM_S3D_PARALLEL, "PARALLEL", 0, "Parallel", "Parallel cameras with no convergence"},
{CAM_S3D_TOE, "TOE", 0, "Toe-in", "Rotated cameras, looking at the convergence distance"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem pivot_items[] = {
+ static const EnumPropertyItem pivot_items[] = {
{CAM_S3D_PIVOT_LEFT, "LEFT", 0, "Left", ""},
{CAM_S3D_PIVOT_RIGHT, "RIGHT", 0, "Right", ""},
{CAM_S3D_PIVOT_CENTER, "CENTER", 0, "Center", ""},
@@ -175,13 +186,13 @@ void RNA_def_camera(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{CAM_PERSP, "PERSP", 0, "Perspective", ""},
{CAM_ORTHO, "ORTHO", 0, "Orthographic", ""},
{CAM_PANO, "PANO", 0, "Panoramic", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_draw_type_extra_items[] = {
+ static const EnumPropertyItem prop_draw_type_extra_items[] = {
{CAM_DTX_CENTER, "CENTER", 0, "Center", ""},
{CAM_DTX_CENTER_DIAG, "CENTER_DIAGONAL", 0, "Center Diagonal", ""},
{CAM_DTX_THIRDS, "THIRDS", 0, "Thirds", ""},
@@ -192,12 +203,12 @@ void RNA_def_camera(BlenderRNA *brna)
{CAM_DTX_HARMONY_TRI_B, "HARMONY_TRIANGLE_B", 0, "Harmonious Triangle B", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_lens_unit_items[] = {
+ static const EnumPropertyItem prop_lens_unit_items[] = {
{0, "MILLIMETERS", 0, "Millimeters", "Specify the lens in millimeters"},
{CAM_ANGLETOGGLE, "FOV", 0, "Field of View", "Specify the lens as the field of view's angle"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem sensor_fit_items[] = {
+ static const EnumPropertyItem sensor_fit_items[] = {
{CAMERA_SENSOR_FIT_AUTO, "AUTO", 0, "Auto", "Fit to the sensor width or height depending on image resolution"},
{CAMERA_SENSOR_FIT_HOR, "HORIZONTAL", 0, "Horizontal", "Fit to the sensor width"},
{CAMERA_SENSOR_FIT_VERT, "VERTICAL", 0, "Vertical", "Fit to the sensor height"},
@@ -323,7 +334,7 @@ void RNA_def_camera(BlenderRNA *brna)
RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_ui_range(prop, 0.0f, 5000.0f, 1, 2);
RNA_def_property_ui_text(prop, "DOF Distance", "Distance to the focus point for depth of field");
- RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL);
+ RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Camera_dof_update");
/* Stereo Settings */
prop = RNA_def_property(srna, "stereo", PROP_POINTER, PROP_NONE);
diff --git a/source/blender/makesrna/intern/rna_cloth.c b/source/blender/makesrna/intern/rna_cloth.c
index d8bcbc2cc72..0ac5bf899a3 100644
--- a/source/blender/makesrna/intern/rna_cloth.c
+++ b/source/blender/makesrna/intern/rna_cloth.c
@@ -291,7 +291,7 @@ static void rna_def_cloth_solver_result(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem status_items[] = {
+ static const EnumPropertyItem status_items[] = {
{BPH_SOLVER_SUCCESS, "SUCCESS", 0, "Success", "Computation was successful"},
{BPH_SOLVER_NUMERICAL_ISSUE, "NUMERICAL_ISSUE", 0, "Numerical Issue", "The provided data did not satisfy the prerequisites"},
{BPH_SOLVER_NO_CONVERGENCE, "NO_CONVERGENCE", 0, "No Convergence", "Iterative procedure did not converge"},
diff --git a/source/blender/makesrna/intern/rna_color.c b/source/blender/makesrna/intern/rna_color.c
index d3cd3d12c4d..d51436df563 100644
--- a/source/blender/makesrna/intern/rna_color.c
+++ b/source/blender/makesrna/intern/rna_color.c
@@ -52,13 +52,13 @@
#include "MEM_guardedalloc.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_depsgraph.h"
#include "BKE_image.h"
#include "BKE_movieclip.h"
#include "BKE_node.h"
#include "BKE_sequencer.h"
-#include "BKE_texture.h"
#include "BKE_linestyle.h"
#include "ED_node.h"
@@ -361,12 +361,12 @@ static void rna_ColorRamp_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *
static void rna_ColorRamp_eval(struct ColorBand *coba, float position, float color[4])
{
- do_colorband(coba, position, color);
+ BKE_colorband_evaluate(coba, position, color);
}
static CBData *rna_ColorRampElement_new(struct ColorBand *coba, ReportList *reports, float position)
{
- CBData *element = colorband_element_add(coba, position);
+ CBData *element = BKE_colorband_element_add(coba, position);
if (element == NULL)
BKE_reportf(reports, RPT_ERROR, "Unable to add element to colorband (limit %d)", MAXCOLORBAND);
@@ -378,7 +378,7 @@ static void rna_ColorRampElement_remove(struct ColorBand *coba, ReportList *repo
{
CBData *element = element_ptr->data;
int index = (int)(element - coba->data);
- if (colorband_element_remove(coba, index) == false) {
+ if (BKE_colorband_element_remove(coba, index) == false) {
BKE_report(reports, RPT_ERROR, "Element not found in element collection or last element");
return;
}
@@ -420,7 +420,7 @@ static void rna_ColorManagedDisplaySettings_display_device_set(struct PointerRNA
}
}
-static EnumPropertyItem *rna_ColorManagedDisplaySettings_display_device_itemf(
+static const EnumPropertyItem *rna_ColorManagedDisplaySettings_display_device_itemf(
bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *items = NULL;
@@ -474,7 +474,7 @@ static void rna_ColorManagedViewSettings_view_transform_set(PointerRNA *ptr, int
}
}
-static EnumPropertyItem *rna_ColorManagedViewSettings_view_transform_itemf(
+static const EnumPropertyItem *rna_ColorManagedViewSettings_view_transform_itemf(
bContext *C, PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
Scene *scene = CTX_data_scene(C);
@@ -507,13 +507,14 @@ static void rna_ColorManagedViewSettings_look_set(PointerRNA *ptr, int value)
}
}
-static EnumPropertyItem *rna_ColorManagedViewSettings_look_itemf(
- bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rna_ColorManagedViewSettings_look_itemf(
+ bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
+ ColorManagedViewSettings *view = (ColorManagedViewSettings *) ptr->data;
EnumPropertyItem *items = NULL;
int totitem = 0;
- IMB_colormanagement_look_items_add(&items, &totitem);
+ IMB_colormanagement_look_items_add(&items, &totitem, view->view_transform);
RNA_enum_item_end(&items, &totitem);
*r_free = true;
@@ -559,7 +560,7 @@ static void rna_ColorManagedColorspaceSettings_colorspace_set(struct PointerRNA
}
}
-static EnumPropertyItem *rna_ColorManagedColorspaceSettings_colorspace_itemf(
+static const EnumPropertyItem *rna_ColorManagedColorspaceSettings_colorspace_itemf(
bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *items = NULL;
@@ -688,7 +689,7 @@ static void rna_def_curvemappoint(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_handle_type_items[] = {
+ static const EnumPropertyItem prop_handle_type_items[] = {
{0, "AUTO", 0, "Auto Handle", ""},
{CUMA_HANDLE_AUTO_ANIM, "AUTO_CLAMPED", 0, "Auto Clamped Handle", ""},
{CUMA_HANDLE_VECTOR, "VECTOR", 0, "Vector Handle", ""},
@@ -747,7 +748,7 @@ static void rna_def_curvemap(BlenderRNA *brna)
PropertyRNA *prop, *parm;
FunctionRNA *func;
- static EnumPropertyItem prop_extend_items[] = {
+ static const EnumPropertyItem prop_extend_items[] = {
{0, "HORIZONTAL", 0, "Horizontal", ""},
{CUMA_EXTEND_EXTRAPOLATE, "EXTRAPOLATED", 0, "Extrapolated", ""},
{0, NULL, 0, NULL, NULL}
@@ -910,7 +911,7 @@ static void rna_def_color_ramp(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem prop_interpolation_items[] = {
+ static const EnumPropertyItem prop_interpolation_items[] = {
{COLBAND_INTERP_EASE, "EASE", 0, "Ease", ""},
{COLBAND_INTERP_CARDINAL, "CARDINAL", 0, "Cardinal", ""},
{COLBAND_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
@@ -919,14 +920,14 @@ static void rna_def_color_ramp(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mode_items[] = {
+ static const EnumPropertyItem prop_mode_items[] = {
{COLBAND_BLEND_RGB, "RGB", 0, "RGB", ""},
{COLBAND_BLEND_HSV, "HSV", 0, "HSV", ""},
{COLBAND_BLEND_HSL, "HSL", 0, "HSL", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_hsv_items[] = {
+ static const EnumPropertyItem prop_hsv_items[] = {
{COLBAND_HUE_NEAR, "NEAR", 0, "Near", ""},
{COLBAND_HUE_FAR, "FAR", 0, "Far", ""},
{COLBAND_HUE_CW, "CW", 0, "Clockwise", ""},
@@ -990,7 +991,7 @@ static void rna_def_histogram(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_mode_items[] = {
+ static const EnumPropertyItem prop_mode_items[] = {
{HISTO_MODE_LUMA, "LUMA", 0, "Luma", "Luma"},
{HISTO_MODE_RGB, "RGB", 0, "RGB", "Red Green Blue"},
{HISTO_MODE_R, "R", 0, "R", "Red"},
@@ -1019,7 +1020,7 @@ static void rna_def_scopes(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_wavefrm_mode_items[] = {
+ static const EnumPropertyItem prop_wavefrm_mode_items[] = {
{SCOPES_WAVEFRM_LUMA, "LUMA", ICON_COLOR, "Luma", ""},
{SCOPES_WAVEFRM_RGB_PARADE, "PARADE", ICON_COLOR, "Parade", ""},
{SCOPES_WAVEFRM_YCC_601, "YCBCR601", ICON_COLOR, "YCbCr (ITU 601)", ""},
@@ -1071,22 +1072,22 @@ static void rna_def_colormanage(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem display_device_items[] = {
+ static const EnumPropertyItem display_device_items[] = {
{0, "DEFAULT", 0, "Default", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem look_items[] = {
+ static const EnumPropertyItem look_items[] = {
{0, "NONE", 0, "None", "Do not modify image in an artistic manner"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem view_transform_items[] = {
+ static const EnumPropertyItem view_transform_items[] = {
{0, "NONE", 0, "None", "Do not perform any color transform on display, use old non-color managed technique for display"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem color_space_items[] = {
+ static const EnumPropertyItem color_space_items[] = {
{0, "NONE", 0, "None", "Do not perform any color transform on load, treat colors as in scene linear space already"},
{0, NULL, 0, NULL, NULL}
};
diff --git a/source/blender/makesrna/intern/rna_constraint.c b/source/blender/makesrna/intern/rna_constraint.c
index de1a0f24c31..bef121cd535 100644
--- a/source/blender/makesrna/intern/rna_constraint.c
+++ b/source/blender/makesrna/intern/rna_constraint.c
@@ -46,7 +46,7 @@
#include "ED_object.h"
/* please keep the names in sync with constraint.c */
-EnumPropertyItem rna_enum_constraint_type_items[] = {
+const EnumPropertyItem rna_enum_constraint_type_items[] = {
{0, "", 0, N_("Motion Tracking"), ""},
{CONSTRAINT_TYPE_CAMERASOLVER, "CAMERA_SOLVER", ICON_CONSTRAINT_DATA, "Camera Solver", ""},
{CONSTRAINT_TYPE_FOLLOWTRACK, "FOLLOW_TRACK", ICON_CONSTRAINT_DATA, "Follow Track", ""},
@@ -109,7 +109,7 @@ EnumPropertyItem rna_enum_constraint_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem target_space_pchan_items[] = {
+static const EnumPropertyItem target_space_pchan_items[] = {
{CONSTRAINT_SPACE_WORLD, "WORLD", 0, "World Space",
"The transformation of the target is evaluated relative to the world "
"coordinate system"},
@@ -125,7 +125,7 @@ static EnumPropertyItem target_space_pchan_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem owner_space_pchan_items[] = {
+static const EnumPropertyItem owner_space_pchan_items[] = {
{CONSTRAINT_SPACE_WORLD, "WORLD", 0, "World Space",
"The constraint is applied relative to the world coordinate system"},
{CONSTRAINT_SPACE_POSE, "POSE", 0, "Pose Space",
@@ -140,7 +140,7 @@ static EnumPropertyItem owner_space_pchan_items[] = {
#ifdef RNA_RUNTIME
-static EnumPropertyItem space_object_items[] = {
+static const EnumPropertyItem space_object_items[] = {
{CONSTRAINT_SPACE_WORLD, "WORLD", 0, "World Space",
"The transformation of the target is evaluated relative to the world coordinate system"},
{CONSTRAINT_SPACE_LOCAL, "LOCAL", 0, "Local Space",
@@ -316,7 +316,7 @@ static void rna_Constraint_ik_type_set(struct PointerRNA *ptr, int value)
}
}
-static EnumPropertyItem *rna_Constraint_owner_space_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Constraint_owner_space_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
Object *ob = (Object *)ptr->id.data;
@@ -328,7 +328,7 @@ static EnumPropertyItem *rna_Constraint_owner_space_itemf(bContext *UNUSED(C), P
return space_object_items;
}
-static EnumPropertyItem *rna_Constraint_target_space_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Constraint_target_space_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
bConstraint *con = (bConstraint *)ptr->data;
@@ -494,7 +494,7 @@ static void rna_Constraint_transformCache_object_path_update(Main *bmain, Scene
#else
-static EnumPropertyItem constraint_distance_items[] = {
+static const EnumPropertyItem constraint_distance_items[] = {
{LIMITDIST_INSIDE, "LIMITDIST_INSIDE", 0, "Inside",
"The object is constrained inside a virtual sphere around the target object, "
"with a radius defined by the limit distance"},
@@ -659,13 +659,13 @@ static void rna_def_constraint_kinematic(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem constraint_ik_axisref_items[] = {
+ static const EnumPropertyItem constraint_ik_axisref_items[] = {
{0, "BONE", 0, "Bone", ""},
{CONSTRAINT_IK_TARGETAXIS, "TARGET", 0, "Target", ""},
{0, NULL, 0, NULL, NULL},
};
- static EnumPropertyItem constraint_ik_type_items[] = {
+ static const EnumPropertyItem constraint_ik_type_items[] = {
{CONSTRAINT_IK_COPYPOSE, "COPY_POSE", 0, "Copy Pose", ""},
{CONSTRAINT_IK_DISTANCE, "DISTANCE", 0, "Distance", ""},
{0, NULL, 0, NULL, NULL},
@@ -807,7 +807,7 @@ static void rna_def_constraint_track_to(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem track_items[] = {
+ static const EnumPropertyItem track_items[] = {
{TRACK_X, "TRACK_X", 0, "X", ""},
{TRACK_Y, "TRACK_Y", 0, "Y", ""},
{TRACK_Z, "TRACK_Z", 0, "Z", ""},
@@ -817,7 +817,7 @@ static void rna_def_constraint_track_to(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem up_items[] = {
+ static const EnumPropertyItem up_items[] = {
{TRACK_X, "UP_X", 0, "X", ""},
{TRACK_Y, "UP_Y", 0, "Y", ""},
{TRACK_Z, "UP_Z", 0, "Z", ""},
@@ -1023,7 +1023,7 @@ static void rna_def_constraint_same_volume(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem volume_items[] = {
+ static const EnumPropertyItem volume_items[] = {
{SAMEVOL_X, "SAMEVOL_X", 0, "X", ""},
{SAMEVOL_Y, "SAMEVOL_Y", 0, "Y", ""},
{SAMEVOL_Z, "SAMEVOL_Z", 0, "Z", ""},
@@ -1077,7 +1077,7 @@ static void rna_def_constraint_minmax(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem minmax_items[] = {
+ static const EnumPropertyItem minmax_items[] = {
{TRACK_X, "FLOOR_X", 0, "X", ""},
{TRACK_Y, "FLOOR_Y", 0, "Y", ""},
{TRACK_Z, "FLOOR_Z", 0, "Z", ""},
@@ -1129,7 +1129,7 @@ static void rna_def_constraint_action(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem transform_channel_items[] = {
+ static const EnumPropertyItem transform_channel_items[] = {
{20, "LOCATION_X", 0, "X Location", ""},
{21, "LOCATION_Y", 0, "Y Location", ""},
{22, "LOCATION_Z", 0, "Z Location", ""},
@@ -1210,7 +1210,7 @@ static void rna_def_constraint_locked_track(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem locktrack_items[] = {
+ static const EnumPropertyItem locktrack_items[] = {
{TRACK_X, "TRACK_X", 0, "X", ""},
{TRACK_Y, "TRACK_Y", 0, "Y", ""},
{TRACK_Z, "TRACK_Z", 0, "Z", ""},
@@ -1220,7 +1220,7 @@ static void rna_def_constraint_locked_track(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem lock_items[] = {
+ static const EnumPropertyItem lock_items[] = {
{TRACK_X, "LOCK_X", 0, "X", ""},
{TRACK_Y, "LOCK_Y", 0, "Y", ""},
{TRACK_Z, "LOCK_Z", 0, "Z", ""},
@@ -1264,7 +1264,7 @@ static void rna_def_constraint_follow_path(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem forwardpath_items[] = {
+ static const EnumPropertyItem forwardpath_items[] = {
{TRACK_X, "FORWARD_X", 0, "X", ""},
{TRACK_Y, "FORWARD_Y", 0, "Y", ""},
{TRACK_Z, "FORWARD_Z", 0, "Z", ""},
@@ -1274,7 +1274,7 @@ static void rna_def_constraint_follow_path(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem pathup_items[] = {
+ static const EnumPropertyItem pathup_items[] = {
{TRACK_X, "UP_X", 0, "X", ""},
{TRACK_Y, "UP_Y", 0, "Y", ""},
{TRACK_Z, "UP_Z", 0, "Z", ""},
@@ -1338,7 +1338,7 @@ static void rna_def_constraint_stretch_to(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem volume_items[] = {
+ static const EnumPropertyItem volume_items[] = {
{VOLUME_XZ, "VOLUME_XZX", 0, "XZ", ""},
{VOLUME_X, "VOLUME_X", 0, "X", ""},
{VOLUME_Z, "VOLUME_Z", 0, "Z", ""},
@@ -1346,7 +1346,7 @@ static void rna_def_constraint_stretch_to(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem plane_items[] = {
+ static const EnumPropertyItem plane_items[] = {
{PLANE_X, "PLANE_X", 0, "X", "Keep X Axis"},
{PLANE_Z, "PLANE_Z", 0, "Z", "Keep Z Axis"},
{0, NULL, 0, NULL, NULL}
@@ -1425,7 +1425,7 @@ static void rna_def_constraint_rigid_body_joint(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem pivot_items[] = {
+ static const EnumPropertyItem pivot_items[] = {
{CONSTRAINT_RB_BALL, "BALL", 0, "Ball", "Allow rotations around all axes"},
{CONSTRAINT_RB_HINGE, "HINGE", 0, "Hinge", "Work in one plane, allow rotations around one axis only"},
{CONSTRAINT_RB_CONETWIST, "CONE_TWIST", 0, "Cone Twist",
@@ -1597,7 +1597,7 @@ static void rna_def_constraint_clamp_to(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem clamp_items[] = {
+ static const EnumPropertyItem clamp_items[] = {
{CLAMPTO_AUTO, "CLAMPTO_AUTO", 0, "Auto", ""},
{CLAMPTO_X, "CLAMPTO_X", 0, "X", ""},
{CLAMPTO_Y, "CLAMPTO_Y", 0, "Y", ""},
@@ -1634,7 +1634,7 @@ static void rna_def_constraint_transform(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem transform_items[] = {
+ static const EnumPropertyItem transform_items[] = {
{TRANS_LOCATION, "LOCATION", 0, "Loc", ""},
{TRANS_ROTATION, "ROTATION", 0, "Rot", ""},
{TRANS_SCALE, "SCALE", 0, "Scale", ""},
@@ -2185,7 +2185,7 @@ static void rna_def_constraint_shrinkwrap(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{MOD_SHRINKWRAP_NEAREST_SURFACE, "NEAREST_SURFACE", 0, "Nearest Surface Point",
"Shrink the location to the nearest target surface"},
{MOD_SHRINKWRAP_PROJECT, "PROJECT", 0, "Project",
@@ -2244,7 +2244,7 @@ static void rna_def_constraint_damped_track(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem damptrack_items[] = {
+ static const EnumPropertyItem damptrack_items[] = {
{TRACK_X, "TRACK_X", 0, "X", ""},
{TRACK_Y, "TRACK_Y", 0, "Y", ""},
{TRACK_Z, "TRACK_Z", 0, "Z", ""},
@@ -2285,7 +2285,7 @@ static void rna_def_constraint_spline_ik(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem splineik_xz_scale_mode[] = {
+ static const EnumPropertyItem splineik_xz_scale_mode[] = {
{CONSTRAINT_SPLINEIK_XZS_NONE, "NONE", 0, "None", "Don't scale the X and Z axes (Default)"},
{CONSTRAINT_SPLINEIK_XZS_ORIGINAL, "BONE_ORIGINAL", 0, "Bone Original",
"Use the original scaling of the bones"},
@@ -2398,7 +2398,7 @@ static void rna_def_constraint_pivot(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem pivot_rotAxis_items[] = {
+ static const EnumPropertyItem pivot_rotAxis_items[] = {
{PIVOTCON_AXIS_NONE, "ALWAYS_ACTIVE", 0, "Always", "Use the pivot point in every rotation"},
{PIVOTCON_AXIS_X_NEG, "NX", 0, "-X Rot",
"Use the pivot point in the negative rotation range around the X-axis"},
diff --git a/source/blender/makesrna/intern/rna_context.c b/source/blender/makesrna/intern/rna_context.c
index d7a679e9702..4bbf31d6500 100644
--- a/source/blender/makesrna/intern/rna_context.c
+++ b/source/blender/makesrna/intern/rna_context.c
@@ -134,7 +134,7 @@ void RNA_def_context(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem mode_items[] = {
+ static const EnumPropertyItem mode_items[] = {
{CTX_MODE_EDIT_MESH, "EDIT_MESH", 0, "Mesh Edit", ""},
{CTX_MODE_EDIT_CURVE, "EDIT_CURVE", 0, "Curve Edit", ""},
{CTX_MODE_EDIT_SURFACE, "EDIT_SURFACE", 0, "Surface Edit", ""},
diff --git a/source/blender/makesrna/intern/rna_controller.c b/source/blender/makesrna/intern/rna_controller.c
index 3fa9d7ef270..bdb3daedebb 100644
--- a/source/blender/makesrna/intern/rna_controller.c
+++ b/source/blender/makesrna/intern/rna_controller.c
@@ -41,7 +41,7 @@
#include "WM_types.h"
-EnumPropertyItem rna_enum_controller_type_items[] = {
+const EnumPropertyItem rna_enum_controller_type_items[] = {
{CONT_LOGIC_AND, "LOGIC_AND", 0, "And", "Logic And"},
{CONT_LOGIC_OR, "LOGIC_OR", 0, "Or", "Logic Or"},
{CONT_LOGIC_NAND, "LOGIC_NAND", 0, "Nand", "Logic Nand"},
@@ -190,7 +190,7 @@ void RNA_def_controller(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem python_controller_modes[] = {
+ static const EnumPropertyItem python_controller_modes[] = {
{CONT_PY_SCRIPT, "SCRIPT", 0, "Script", ""},
{CONT_PY_MODULE, "MODULE", 0, "Module", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/makesrna/intern/rna_curve.c b/source/blender/makesrna/intern/rna_curve.c
index 7787533d311..45b312a742d 100644
--- a/source/blender/makesrna/intern/rna_curve.c
+++ b/source/blender/makesrna/intern/rna_curve.c
@@ -47,7 +47,7 @@
#include "WM_types.h"
#ifndef RNA_RUNTIME
-static EnumPropertyItem beztriple_handle_type_items[] = {
+static const EnumPropertyItem beztriple_handle_type_items[] = {
{HD_FREE, "FREE", 0, "Free", ""},
{HD_VECT, "VECTOR", 0, "Vector", ""},
{HD_ALIGN, "ALIGNED", 0, "Aligned", ""},
@@ -56,7 +56,7 @@ static EnumPropertyItem beztriple_handle_type_items[] = {
};
#endif
-EnumPropertyItem rna_enum_keyframe_handle_type_items[] = {
+const EnumPropertyItem rna_enum_keyframe_handle_type_items[] = {
{HD_FREE, "FREE", 0, "Free", ""},
{HD_VECT, "VECTOR", 0, "Vector", ""},
{HD_ALIGN, "ALIGNED", 0, "Aligned", ""},
@@ -65,7 +65,7 @@ EnumPropertyItem rna_enum_keyframe_handle_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_beztriple_interpolation_mode_items[] = {
+const EnumPropertyItem rna_enum_beztriple_interpolation_mode_items[] = {
/* interpolation */
{0, "", 0, N_("Interpolation"), "Standard transitions between keyframes"},
{BEZT_IPO_CONST, "CONSTANT", ICON_IPO_CONSTANT, "Constant", "No interpolation, value of A gets held until B is encountered"},
@@ -91,7 +91,7 @@ EnumPropertyItem rna_enum_beztriple_interpolation_mode_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem curve_type_items[] = {
+static const EnumPropertyItem curve_type_items[] = {
{CU_POLY, "POLY", 0, "Poly", ""},
{CU_BEZIER, "BEZIER", 0, "Bezier", ""},
{CU_BSPLINE, "BSPLINE", 0, "BSpline", ""},
@@ -300,7 +300,7 @@ static void rna_Curve_dimension_set(PointerRNA *ptr, int value)
BKE_curve_curve_dimension_update(cu);
}
-static EnumPropertyItem *rna_Curve_fill_mode_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Curve_fill_mode_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
Curve *cu = (Curve *)ptr->id.data;
@@ -953,7 +953,7 @@ static void rna_def_font(BlenderRNA *UNUSED(brna), StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_align_items[] = {
+ static const EnumPropertyItem prop_align_items[] = {
{CU_ALIGN_X_LEFT, "LEFT", 0, "Left", "Align text to the left"},
{CU_ALIGN_X_MIDDLE, "CENTER", 0, "Center", "Center text"},
{CU_ALIGN_X_RIGHT, "RIGHT", 0, "Right", "Align text to the right"},
@@ -962,7 +962,7 @@ static void rna_def_font(BlenderRNA *UNUSED(brna), StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_align_y_items[] = {
+ static const EnumPropertyItem prop_align_y_items[] = {
{CU_ALIGN_Y_TOP_BASELINE, "TOP_BASELINE", 0, "Top Base-Line", "Align to top but use the base-line of the text"},
{CU_ALIGN_Y_TOP, "TOP", 0, "Top", "Align text to the top"},
{CU_ALIGN_Y_CENTER, "CENTER", 0, "Center", "Align text to the middle"},
@@ -1334,7 +1334,7 @@ static void rna_def_curve(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem curve_twist_mode_items[] = {
+ static const EnumPropertyItem curve_twist_mode_items[] = {
{CU_TWIST_Z_UP, "Z_UP", 0, "Z-Up", "Use Z-Up axis to calculate the curve twist at each point"},
{CU_TWIST_MINIMUM, "MINIMUM", 0, "Minimum", "Use the least twist over the entire curve"},
{CU_TWIST_TANGENT, "TANGENT", 0, "Tangent", "Use the tangent to calculate twist"},
@@ -1348,7 +1348,7 @@ static void rna_def_curve(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bevfac_mapping_items[] = {
+ static const EnumPropertyItem bevfac_mapping_items[] = {
{CU_BEVFAC_MAP_RESOLU, "RESOLUTION", 0, "Resolution", "Map the bevel factor to the number of subdivisions of a spline (U resolution)"},
{CU_BEVFAC_MAP_SEGMENT, "SEGMENTS", 0, "Segments", "Map the bevel factor to the length of a segment and to the number of subdivisions of a segment"},
{CU_BEVFAC_MAP_SPLINE, "SPLINE", 0, "Spline", "Map the bevel factor to the length of a spline"},
@@ -1600,7 +1600,7 @@ static void rna_def_curve(BlenderRNA *brna)
static void rna_def_curve_nurb(BlenderRNA *brna)
{
- static EnumPropertyItem spline_interpolation_items[] = {
+ static const EnumPropertyItem spline_interpolation_items[] = {
{KEY_LINEAR, "LINEAR", 0, "Linear", ""},
{KEY_CARDINAL, "CARDINAL", 0, "Cardinal", ""},
{KEY_BSPLINE, "BSPLINE", 0, "BSpline", ""},
diff --git a/source/blender/makesrna/intern/rna_curve_api.c b/source/blender/makesrna/intern/rna_curve_api.c
index b4b3aa84ec5..be6808567bb 100644
--- a/source/blender/makesrna/intern/rna_curve_api.c
+++ b/source/blender/makesrna/intern/rna_curve_api.c
@@ -45,7 +45,7 @@
#ifdef RNA_RUNTIME
static void rna_Curve_transform(Curve *cu, float *mat, int shape_keys)
{
- BKE_curve_transform(cu, (float (*)[4])mat, shape_keys);
+ BKE_curve_transform(cu, (float (*)[4])mat, shape_keys, true);
DAG_id_tag_update(&cu->id, 0);
}
diff --git a/source/blender/makesrna/intern/rna_define.c b/source/blender/makesrna/intern/rna_define.c
index dc97d39052b..c8a6a503fd9 100644
--- a/source/blender/makesrna/intern/rna_define.c
+++ b/source/blender/makesrna/intern/rna_define.c
@@ -44,6 +44,8 @@
#include "BLT_translation.h"
+#include "UI_interface.h" /* For things like UI_PRECISION_FLOAT_MAX... */
+
#include "RNA_define.h"
#include "rna_internal.h"
@@ -71,8 +73,8 @@ BlenderDefRNA DefRNA = {NULL, {NULL, NULL}, {NULL, NULL}, NULL, 0, 0, 0, 1, 1};
if (description && (description)[0]) { \
int i = strlen(description); \
if (i > 3 && (description)[i - 1] == '.' && (description)[i - 3] != '.') { \
- fprintf(stderr, "%s: '%s' '%s' description ends with a '.' !\n", \
- __func__, id1 ? id1 : "", id2 ? id2 : ""); \
+ fprintf(stderr, "%s: '%s' description from '%s' '%s' ends with a '.' !\n", \
+ __func__, description, id1 ? id1 : "", id2 ? id2 : ""); \
} \
} (void)0
@@ -135,6 +137,38 @@ void rna_freelistN(ListBase *listbase)
listbase->first = listbase->last = NULL;
}
+static void rna_brna_structs_add(BlenderRNA *brna, StructRNA *srna)
+{
+ rna_addtail(&brna->structs, srna);
+ brna->structs_len += 1;
+
+ /* This exception is only needed for pre-processing.
+ * otherwise we don't allow empty names. */
+ if ((srna->flag & STRUCT_PUBLIC_NAMESPACE) &&
+ (srna->identifier[0] != '\0'))
+ {
+ BLI_ghash_insert(brna->structs_map, (void *)srna->identifier, srna);
+ }
+}
+
+#ifdef RNA_RUNTIME
+static void rna_brna_structs_remove_and_free(BlenderRNA *brna, StructRNA *srna)
+{
+ if ((srna->flag & STRUCT_PUBLIC_NAMESPACE) && brna->structs_map) {
+ if (srna->identifier[0] != '\0') {
+ BLI_ghash_remove(brna->structs_map, (void *)srna->identifier, NULL, NULL);
+ }
+ }
+
+ RNA_def_struct_free_pointers(NULL, srna);
+
+ if (srna->flag & STRUCT_RUNTIME) {
+ rna_freelinkN(&brna->structs, srna);
+ }
+ brna->structs_len -= 1;
+}
+#endif
+
StructDefRNA *rna_find_struct_def(StructRNA *srna)
{
StructDefRNA *dsrna;
@@ -534,6 +568,8 @@ BlenderRNA *RNA_create(void)
const char *error_message = NULL;
BLI_listbase_clear(&DefRNA.structs);
+ brna->structs_map = BLI_ghash_str_new_ex(__func__, 2048);
+
DefRNA.error = 0;
DefRNA.preprocess = 1;
@@ -640,10 +676,8 @@ void RNA_struct_free(BlenderRNA *brna, StructRNA *srna)
rna_freelinkN(&srna->functions, func);
}
- RNA_def_struct_free_pointers(srna);
- if (srna->flag & STRUCT_RUNTIME)
- rna_freelinkN(&brna->structs, srna);
+ rna_brna_structs_remove_and_free(brna, srna);
#else
UNUSED_VARS(brna, srna);
#endif
@@ -654,6 +688,9 @@ void RNA_free(BlenderRNA *brna)
StructRNA *srna, *nextsrna;
FunctionRNA *func;
+ BLI_ghash_free(brna->structs_map, NULL, NULL);
+ brna->structs_map = NULL;
+
if (DefRNA.preprocess) {
RNA_define_free(brna);
@@ -730,12 +767,19 @@ StructRNA *RNA_def_struct_ptr(BlenderRNA *brna, const char *identifier, StructRN
BLI_listbase_clear(&srna->functions);
srna->py_type = NULL;
+ srna->base = srnafrom;
+
if (DefRNA.preprocess) {
- srna->base = srnafrom;
dsfrom = rna_find_def_struct(srnafrom);
}
- else
- srna->base = srnafrom;
+ else {
+ if (srnafrom->flag & STRUCT_PUBLIC_NAMESPACE_INHERIT) {
+ srna->flag |= STRUCT_PUBLIC_NAMESPACE | STRUCT_PUBLIC_NAMESPACE_INHERIT;
+ }
+ else {
+ srna->flag &= ~(STRUCT_PUBLIC_NAMESPACE | STRUCT_PUBLIC_NAMESPACE_INHERIT);
+ }
+ }
}
srna->identifier = identifier;
@@ -747,7 +791,11 @@ StructRNA *RNA_def_struct_ptr(BlenderRNA *brna, const char *identifier, StructRN
if (!srnafrom)
srna->icon = ICON_DOT;
- rna_addtail(&brna->structs, srna);
+ if (DefRNA.preprocess) {
+ srna->flag |= STRUCT_PUBLIC_NAMESPACE;
+ }
+
+ rna_brna_structs_add(brna, srna);
if (DefRNA.preprocess) {
ds = MEM_callocN(sizeof(StructDefRNA), "StructDefRNA");
@@ -819,10 +867,8 @@ StructRNA *RNA_def_struct(BlenderRNA *brna, const char *identifier, const char *
if (from) {
/* find struct to derive from */
- for (srnafrom = brna->structs.first; srnafrom; srnafrom = srnafrom->cont.next)
- if (STREQ(srnafrom->identifier, from))
- break;
-
+ /* Inline RNA_struct_find(...) because it wont link from here. */
+ srnafrom = BLI_ghash_lookup(brna->structs_map, from);
if (!srnafrom) {
fprintf(stderr, "%s: struct %s not found to define %s.\n", __func__, from, identifier);
DefRNA.error = 1;
@@ -901,10 +947,7 @@ void RNA_def_struct_nested(BlenderRNA *brna, StructRNA *srna, const char *struct
StructRNA *srnafrom;
/* find struct to derive from */
- for (srnafrom = brna->structs.first; srnafrom; srnafrom = srnafrom->cont.next)
- if (STREQ(srnafrom->identifier, structname))
- break;
-
+ srnafrom = BLI_ghash_lookup(brna->structs_map, structname);
if (!srnafrom) {
fprintf(stderr, "%s: struct %s not found for %s.\n", __func__, structname, srna->identifier);
DefRNA.error = 1;
@@ -923,6 +966,11 @@ void RNA_def_struct_clear_flag(StructRNA *srna, int flag)
srna->flag &= ~flag;
}
+void RNA_def_struct_property_tags(StructRNA *srna, const EnumPropertyItem *prop_tag_defines)
+{
+ srna->prop_tag_defines = prop_tag_defines;
+}
+
void RNA_def_struct_refine_func(StructRNA *srna, const char *refine)
{
if (!DefRNA.preprocess) {
@@ -965,7 +1013,32 @@ void RNA_def_struct_path_func(StructRNA *srna, const char *path)
if (path) srna->path = (StructPathFunc)path;
}
-void RNA_def_struct_identifier(StructRNA *srna, const char *identifier)
+void RNA_def_struct_identifier(BlenderRNA *brna, StructRNA *srna, const char *identifier)
+{
+ if (DefRNA.preprocess) {
+ fprintf(stderr, "%s: only at runtime.\n", __func__);
+ return;
+ }
+
+ /* Operator registration may set twice, see: operator_properties_init */
+ if (srna->flag & STRUCT_PUBLIC_NAMESPACE) {
+ if (identifier != srna->identifier) {
+ if (srna->identifier[0] != '\0') {
+ BLI_ghash_remove(brna->structs_map, (void *)srna->identifier, NULL, NULL);
+ }
+ if (identifier[0] != '\0') {
+ BLI_ghash_insert(brna->structs_map, (void *)identifier, srna);
+ }
+ }
+ }
+
+ srna->identifier = identifier;
+}
+
+/**
+ * Only used in one case when we name the struct for the purpose of useful error messages.
+ */
+void RNA_def_struct_identifier_no_struct_map(StructRNA *srna, const char *identifier)
{
if (DefRNA.preprocess) {
fprintf(stderr, "%s: only at runtime.\n", __func__);
@@ -1212,6 +1285,18 @@ void RNA_def_property_clear_flag(PropertyRNA *prop, PropertyFlag flag)
prop->flag &= ~flag;
}
+/**
+ * Add the property-tags passed as \a tags to \a prop (if valid).
+ *
+ * \note Multiple tags can be set by passing them within \a tags (using bitflags).
+ * \note Doesn't do any type-checking with the tags defined in the parent StructRNA
+ * of \a prop. This should be done before (e.g. see #WM_operatortype_prop_tag).
+ */
+void RNA_def_property_tags(PropertyRNA *prop, int tags)
+{
+ prop->tags |= tags;
+}
+
void RNA_def_parameter_flags(PropertyRNA *prop, PropertyFlag flag_property, ParameterFlag flag_parameter)
{
prop->flag |= flag_property;
@@ -1339,13 +1424,13 @@ void RNA_def_property_ui_icon(PropertyRNA *prop, int icon, bool consecutive)
* For ints, whole values are used.
*
* \param precision The number of zeros to show
- * (as a whole number - common range is 1 - 6), see PRECISION_FLOAT_MAX
+ * (as a whole number - common range is 1 - 6), see UI_PRECISION_FLOAT_MAX
*/
void RNA_def_property_ui_range(PropertyRNA *prop, double min, double max, double step, int precision)
{
StructRNA *srna = DefRNA.laststruct;
-#ifdef DEBUG
+#ifndef NDEBUG
if (min > max) {
fprintf(stderr, "%s: \"%s.%s\", min > max.\n",
__func__, srna->identifier, prop->identifier);
@@ -1358,8 +1443,8 @@ void RNA_def_property_ui_range(PropertyRNA *prop, double min, double max, double
DefRNA.error = 1;
}
- if (precision < -1 || precision > 10) {
- fprintf(stderr, "%s: \"%s.%s\", step outside range.\n",
+ if (precision < -1 || precision > UI_PRECISION_FLOAT_MAX) {
+ fprintf(stderr, "%s: \"%s.%s\", precision outside range.\n",
__func__, srna->identifier, prop->identifier);
DefRNA.error = 1;
}
@@ -1381,21 +1466,6 @@ void RNA_def_property_ui_range(PropertyRNA *prop, double min, double max, double
fprop->softmax = (float)max;
fprop->step = (float)step;
fprop->precision = (int)precision;
-#if 0 /* handy but annoying */
- if (DefRNA.preprocess) {
- /* check we're not over PRECISION_FLOAT_MAX */
- if (fprop->precision > 6) {
- fprintf(stderr, "%s: \"%s.%s\", precision value over maximum.\n",
- __func__, srna->identifier, prop->identifier);
- DefRNA.error = 1;
- }
- else if (fprop->precision < 1) {
- fprintf(stderr, "%s: \"%s.%s\", precision value under minimum.\n",
- __func__, srna->identifier, prop->identifier);
- DefRNA.error = 1;
- }
- }
-#endif
break;
}
default:
@@ -2168,6 +2238,16 @@ void RNA_def_property_update_runtime(PropertyRNA *prop, const void *func)
prop->update = (void *)func;
}
+void RNA_def_property_poll_runtime(PropertyRNA *prop, const void *func)
+{
+ if (prop->type == PROP_POINTER) {
+ ((PointerPropertyRNA *)prop)->poll = func;
+ }
+ else {
+ fprintf(stderr, "%s: %s is not a Pointer Property.\n", __func__, prop->identifier);
+ }
+}
+
void RNA_def_property_dynamic_array_funcs(PropertyRNA *prop, const char *getlength)
{
if (!DefRNA.preprocess) {
@@ -2982,6 +3062,9 @@ PropertyRNA *RNA_def_pointer_runtime(StructOrFunctionRNA *cont_, const char *ide
prop = RNA_def_property(cont, identifier, PROP_POINTER, PROP_NONE);
RNA_def_property_struct_runtime(prop, type);
+ if ((type->flag & STRUCT_ID) != 0) {
+ prop->flag |= PROP_EDITABLE;
+ }
RNA_def_property_ui_text(prop, ui_name, ui_description);
return prop;
@@ -3157,8 +3240,9 @@ int rna_parameter_size(PropertyRNA *parm)
StringPropertyRNA *sparm = (StringPropertyRNA *)parm;
return sizeof(char) * sparm->maxlength;
}
- else
+ else {
return sizeof(char *);
+ }
case PROP_POINTER:
{
#ifdef RNA_RUNTIME
@@ -3217,17 +3301,17 @@ void RNA_enum_item_add(EnumPropertyItem **items, int *totitem, const EnumPropert
void RNA_enum_item_add_separator(EnumPropertyItem **items, int *totitem)
{
- static EnumPropertyItem sepr = {0, "", 0, NULL, NULL};
+ static const EnumPropertyItem sepr = {0, "", 0, NULL, NULL};
RNA_enum_item_add(items, totitem, &sepr);
}
-void RNA_enum_items_add(EnumPropertyItem **items, int *totitem, EnumPropertyItem *item)
+void RNA_enum_items_add(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item)
{
for (; item->identifier; item++)
RNA_enum_item_add(items, totitem, item);
}
-void RNA_enum_items_add_value(EnumPropertyItem **items, int *totitem, EnumPropertyItem *item, int value)
+void RNA_enum_items_add_value(EnumPropertyItem **items, int *totitem, const EnumPropertyItem *item, int value)
{
for (; item->identifier; item++) {
if (item->value == value) {
@@ -3241,28 +3325,48 @@ void RNA_enum_items_add_value(EnumPropertyItem **items, int *totitem, EnumProper
void RNA_enum_item_end(EnumPropertyItem **items, int *totitem)
{
- static EnumPropertyItem empty = {0, NULL, 0, NULL, NULL};
+ static const EnumPropertyItem empty = {0, NULL, 0, NULL, NULL};
RNA_enum_item_add(items, totitem, &empty);
}
/* Memory management */
#ifdef RNA_RUNTIME
-void RNA_def_struct_duplicate_pointers(StructRNA *srna)
+void RNA_def_struct_duplicate_pointers(BlenderRNA *brna, StructRNA *srna)
{
- if (srna->identifier) srna->identifier = BLI_strdup(srna->identifier);
- if (srna->name) srna->name = BLI_strdup(srna->name);
- if (srna->description) srna->description = BLI_strdup(srna->description);
+ if (srna->identifier) {
+ srna->identifier = BLI_strdup(srna->identifier);
+ if (srna->flag & STRUCT_PUBLIC_NAMESPACE) {
+ BLI_ghash_replace_key(brna->structs_map, (void *)srna->identifier);
+ }
+ }
+ if (srna->name) {
+ srna->name = BLI_strdup(srna->name);
+ }
+ if (srna->description) {
+ srna->description = BLI_strdup(srna->description);
+ }
srna->flag |= STRUCT_FREE_POINTERS;
}
-void RNA_def_struct_free_pointers(StructRNA *srna)
+void RNA_def_struct_free_pointers(BlenderRNA *brna, StructRNA *srna)
{
if (srna->flag & STRUCT_FREE_POINTERS) {
- if (srna->identifier) MEM_freeN((void *)srna->identifier);
- if (srna->name) MEM_freeN((void *)srna->name);
- if (srna->description) MEM_freeN((void *)srna->description);
+ if (srna->identifier) {
+ if (srna->flag & STRUCT_PUBLIC_NAMESPACE) {
+ if (brna != NULL) {
+ BLI_ghash_remove(brna->structs_map, (void *)srna->identifier, NULL, NULL);
+ }
+ }
+ MEM_freeN((void *)srna->identifier);
+ }
+ if (srna->name) {
+ MEM_freeN((void *)srna->name);
+ }
+ if (srna->description) {
+ MEM_freeN((void *)srna->description);
+ }
}
}
@@ -3338,12 +3442,12 @@ void RNA_def_property_duplicate_pointers(StructOrFunctionRNA *cont_, PropertyRNA
eprop->item = earray;
for (a = 0; a < eprop->totitem; a++) {
- if (eprop->item[a].identifier)
- eprop->item[a].identifier = BLI_strdup(eprop->item[a].identifier);
- if (eprop->item[a].name)
- eprop->item[a].name = BLI_strdup(eprop->item[a].name);
- if (eprop->item[a].description)
- eprop->item[a].description = BLI_strdup(eprop->item[a].description);
+ if (earray[a].identifier)
+ earray[a].identifier = BLI_strdup(earray[a].identifier);
+ if (earray[a].name)
+ earray[a].name = BLI_strdup(earray[a].name);
+ if (earray[a].description)
+ earray[a].description = BLI_strdup(earray[a].description);
}
}
break;
diff --git a/source/blender/makesrna/intern/rna_depsgraph.c b/source/blender/makesrna/intern/rna_depsgraph.c
index 2748bd8b877..c6b18d8d387 100644
--- a/source/blender/makesrna/intern/rna_depsgraph.c
+++ b/source/blender/makesrna/intern/rna_depsgraph.c
@@ -38,44 +38,47 @@
#include "BKE_depsgraph.h"
-#ifdef RNA_RUNTIME
+#define STATS_MAX_SIZE 16384
-#include "BKE_report.h"
+#ifdef RNA_RUNTIME
+#include "DEG_depsgraph_build.h"
#include "DEG_depsgraph_debug.h"
-static void rna_Depsgraph_debug_graphviz(Depsgraph *graph, const char *filename)
+static void rna_Depsgraph_debug_relations_graphviz(Depsgraph *depsgraph,
+ const char *filename)
{
FILE *f = fopen(filename, "w");
- if (f == NULL)
+ if (f == NULL) {
return;
-
- DEG_debug_graphviz(graph, f, "Depsgraph", false);
-
+ }
+ DEG_debug_relations_graphviz(depsgraph, f, "Depsgraph");
fclose(f);
}
-static void rna_Depsgraph_debug_rebuild(Depsgraph *UNUSED(graph), Main *bmain)
+static void rna_Depsgraph_debug_stats_gnuplot(Depsgraph *depsgraph,
+ const char *filename,
+ const char *output_filename)
{
- Scene *sce;
- DAG_relations_tag_update(bmain);
- for (sce = bmain->scene.first; sce; sce = sce->id.next) {
- DAG_scene_relations_rebuild(bmain, sce);
- DEG_graph_on_visible_update(bmain, sce);
+ FILE *f = fopen(filename, "w");
+ if (f == NULL) {
+ return;
}
+ DEG_debug_stats_gnuplot(depsgraph, f, "Timing Statistics", output_filename);
+ fclose(f);
}
-static void rna_Depsgraph_debug_stats(Depsgraph *graph, ReportList *reports)
+static void rna_Depsgraph_debug_tag_update(Depsgraph *depsgraph)
+{
+ DEG_graph_tag_relations_update(depsgraph);
+}
+
+static void rna_Depsgraph_debug_stats(Depsgraph *depsgraph, char *result)
{
size_t outer, ops, rels;
-
- DEG_stats_simple(graph, &outer, &ops, &rels);
-
- // XXX: report doesn't seem to work
- printf("Approx %lu Operations, %lu Relations, %lu Outer Nodes\n",
- ops, rels, outer);
-
- BKE_reportf(reports, RPT_WARNING, "Approx. %lu Operations, %lu Relations, %lu Outer Nodes",
+ DEG_stats_simple(depsgraph, &outer, &ops, &rels);
+ BLI_snprintf(result, STATS_MAX_SIZE,
+ "Approx %lu Operations, %lu Relations, %lu Outer Nodes",
ops, rels, outer);
}
@@ -89,18 +92,28 @@ static void rna_def_depsgraph(BlenderRNA *brna)
srna = RNA_def_struct(brna, "Depsgraph", NULL);
RNA_def_struct_ui_text(srna, "Dependency Graph", "");
-
- func = RNA_def_function(srna, "debug_graphviz", "rna_Depsgraph_debug_graphviz");
+
+ func = RNA_def_function(srna, "debug_relations_graphviz", "rna_Depsgraph_debug_relations_graphviz");
parm = RNA_def_string_file_path(func, "filename", NULL, FILE_MAX, "File Name",
"File in which to store graphviz debug output");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
- func = RNA_def_function(srna, "debug_rebuild", "rna_Depsgraph_debug_rebuild");
- RNA_def_function_flag(func, FUNC_USE_MAIN);
+ func = RNA_def_function(srna, "debug_stats_gnuplot", "rna_Depsgraph_debug_stats_gnuplot");
+ parm = RNA_def_string_file_path(func, "filename", NULL, FILE_MAX, "File Name",
+ "File in which to store graphviz debug output");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_string_file_path(func, "output_filename", NULL, FILE_MAX, "Output File Name",
+ "File name where gnuplot script will save the result");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+
+ func = RNA_def_function(srna, "debug_tag_update", "rna_Depsgraph_debug_tag_update");
func = RNA_def_function(srna, "debug_stats", "rna_Depsgraph_debug_stats");
RNA_def_function_ui_description(func, "Report the number of elements in the Dependency Graph");
- RNA_def_function_flag(func, FUNC_USE_REPORTS);
+ /* weak!, no way to return dynamic string type */
+ parm = RNA_def_string(func, "result", NULL, STATS_MAX_SIZE, "result", "");
+ RNA_def_parameter_flags(parm, PROP_THICK_WRAP, 0); /* needed for string return value */
+ RNA_def_function_output(func, parm);
}
void RNA_def_depsgraph(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_dynamicpaint.c b/source/blender/makesrna/intern/rna_dynamicpaint.c
index 4bb7f3a9ffd..94fda7097ee 100644
--- a/source/blender/makesrna/intern/rna_dynamicpaint.c
+++ b/source/blender/makesrna/intern/rna_dynamicpaint.c
@@ -34,7 +34,7 @@
#include "DNA_dynamicpaint_types.h"
#include "DNA_modifier_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
@@ -45,7 +45,7 @@
#include "WM_types.h"
-EnumPropertyItem rna_enum_prop_dynamicpaint_type_items[] = {
+const EnumPropertyItem rna_enum_prop_dynamicpaint_type_items[] = {
{MOD_DYNAMICPAINT_TYPE_CANVAS, "CANVAS", 0, "Canvas", ""},
{MOD_DYNAMICPAINT_TYPE_BRUSH, "BRUSH", 0, "Brush", ""},
{0, NULL, 0, NULL, NULL}
@@ -245,7 +245,7 @@ static int rna_DynamicPaint_is_output_exists(DynamicPaintSurface *surface, Objec
}
-static EnumPropertyItem *rna_DynamicPaint_surface_type_itemf(
+static const EnumPropertyItem *rna_DynamicPaint_surface_type_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
DynamicPaintSurface *surface = (DynamicPaintSurface *)ptr->data;
@@ -331,7 +331,7 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
FunctionRNA *func;
/* Surface format */
- static EnumPropertyItem prop_dynamicpaint_surface_format[] = {
+ static const EnumPropertyItem prop_dynamicpaint_surface_format[] = {
/*{MOD_DPAINT_SURFACE_F_PTEX, "PTEX", ICON_TEXTURE_SHADED, "Ptex", ""}, */
{MOD_DPAINT_SURFACE_F_VERTEX, "VERTEX", ICON_OUTLINER_DATA_MESH, "Vertex", ""},
{MOD_DPAINT_SURFACE_F_IMAGESEQ, "IMAGE", ICON_FILE_IMAGE, "Image Sequence", ""},
@@ -339,20 +339,20 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
};
/* Surface type - generated dynamically based on surface format */
- static EnumPropertyItem prop_dynamicpaint_surface_type[] = {
+ static const EnumPropertyItem prop_dynamicpaint_surface_type[] = {
{MOD_DPAINT_SURFACE_T_PAINT, "PAINT", 0, "Paint", ""},
{0, NULL, 0, NULL, NULL}
};
/* Surface output preview. currently only paint has multiple outputs */
- static EnumPropertyItem prop_dynamicpaint_surface_preview[] = {
+ static const EnumPropertyItem prop_dynamicpaint_surface_preview[] = {
{MOD_DPAINT_SURFACE_PREV_PAINT, "PAINT", 0, "Paint", ""},
{MOD_DPAINT_SURFACE_PREV_WETMAP, "WETMAP", 0, "Wetmap", ""},
{0, NULL, 0, NULL, NULL}
};
/* Initial color setting */
- static EnumPropertyItem prop_dynamicpaint_init_color_type[] = {
+ static const EnumPropertyItem prop_dynamicpaint_init_color_type[] = {
{MOD_DPAINT_INITIAL_NONE, "NONE", 0, "None", ""},
{MOD_DPAINT_INITIAL_COLOR, "COLOR", ICON_COLOR, "Color", ""},
{MOD_DPAINT_INITIAL_TEXTURE, "TEXTURE", ICON_TEXTURE, "UV Texture", ""},
@@ -362,7 +362,7 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
/* Effect type
* Only used by ui to view per effect settings */
- static EnumPropertyItem prop_dynamicpaint_effecttype[] = {
+ static const EnumPropertyItem prop_dynamicpaint_effecttype[] = {
{1, "SPREAD", 0, "Spread", ""},
{2, "DRIP", 0, "Drip", ""},
{3, "SHRINK", 0, "Shrink", ""},
@@ -370,7 +370,7 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
};
/* Displacemap file format */
- static EnumPropertyItem prop_dynamicpaint_image_fileformat[] = {
+ static const EnumPropertyItem prop_dynamicpaint_image_fileformat[] = {
{MOD_DPAINT_IMGFORMAT_PNG, "PNG", 0, "PNG", ""},
#ifdef WITH_OPENEXR
{MOD_DPAINT_IMGFORMAT_OPENEXR, "OPENEXR", 0, "OpenEXR", ""},
@@ -379,7 +379,7 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
};
/* Displacemap type */
- static EnumPropertyItem prop_dynamicpaint_displace_type[] = {
+ static const EnumPropertyItem prop_dynamicpaint_displace_type[] = {
{MOD_DPAINT_DISP_DISPLACE, "DISPLACE", 0, "Displacement", ""},
{MOD_DPAINT_DISP_DEPTH, "DEPTH", 0, "Depth", ""},
{0, NULL, 0, NULL, NULL}
@@ -722,11 +722,11 @@ static void rna_def_canvas_surface(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flags", MOD_DPAINT_WAVE_OPEN_BORDERS);
RNA_def_property_ui_text(prop, "Open Borders", "Pass waves through mesh edges");
-
/* cache */
prop = RNA_def_property(srna, "point_cache", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
RNA_def_property_pointer_sdna(prop, NULL, "pointcache");
+ RNA_def_property_struct_type(prop, "PointCache");
RNA_def_property_ui_text(prop, "Point Cache", "");
/* is cache used */
@@ -772,7 +772,7 @@ static void rna_def_dynamic_paint_brush_settings(BlenderRNA *brna)
PropertyRNA *prop;
/* paint collision type */
- static EnumPropertyItem prop_dynamicpaint_collisiontype[] = {
+ static const EnumPropertyItem prop_dynamicpaint_collisiontype[] = {
{MOD_DPAINT_COL_PSYS, "PARTICLE_SYSTEM", ICON_PARTICLES, "Particle System", ""},
{MOD_DPAINT_COL_POINT, "POINT", ICON_META_EMPTY, "Object Center", ""},
{MOD_DPAINT_COL_DIST, "DISTANCE", ICON_META_EMPTY, "Proximity", ""},
@@ -781,14 +781,14 @@ static void rna_def_dynamic_paint_brush_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_dynamicpaint_prox_falloff[] = {
+ static const EnumPropertyItem prop_dynamicpaint_prox_falloff[] = {
{MOD_DPAINT_PRFALL_SMOOTH, "SMOOTH", ICON_SPHERECURVE, "Smooth", ""},
{MOD_DPAINT_PRFALL_CONSTANT, "CONSTANT", ICON_NOCURVE, "Constant", ""},
{MOD_DPAINT_PRFALL_RAMP, "RAMP", ICON_COLOR, "Color Ramp", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_dynamicpaint_brush_wave_type[] = {
+ static const EnumPropertyItem prop_dynamicpaint_brush_wave_type[] = {
{MOD_DPAINT_WAVEB_CHANGE, "CHANGE", 0, "Depth Change", ""},
{MOD_DPAINT_WAVEB_DEPTH, "DEPTH", 0, "Obstacle", ""},
{MOD_DPAINT_WAVEB_FORCE, "FORCE", 0, "Force", ""},
@@ -796,7 +796,7 @@ static void rna_def_dynamic_paint_brush_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_dynamicpaint_brush_ray_dir[] = {
+ static const EnumPropertyItem prop_dynamicpaint_brush_ray_dir[] = {
{MOD_DPAINT_RAY_CANVAS, "CANVAS", 0, "Canvas Normal", ""},
{MOD_DPAINT_RAY_BRUSH_AVG, "BRUSH", 0, "Brush Normal", ""},
{MOD_DPAINT_RAY_ZPLUS, "Z_AXIS", 0, "Z-Axis", ""},
diff --git a/source/blender/makesrna/intern/rna_fcurve.c b/source/blender/makesrna/intern/rna_fcurve.c
index 4acdee490b8..c8ee6e15689 100644
--- a/source/blender/makesrna/intern/rna_fcurve.c
+++ b/source/blender/makesrna/intern/rna_fcurve.c
@@ -35,6 +35,8 @@
#include "BLI_math.h"
+#include "BLT_translation.h"
+
#include "BKE_action.h"
#include "RNA_access.h"
@@ -48,7 +50,7 @@
#include "ED_keyframing.h"
#include "ED_keyframes_edit.h"
-EnumPropertyItem rna_enum_fmodifier_type_items[] = {
+const EnumPropertyItem rna_enum_fmodifier_type_items[] = {
{FMODIFIER_TYPE_NULL, "NULL", 0, "Invalid", ""},
{FMODIFIER_TYPE_GENERATOR, "GENERATOR", 0, "Generator",
"Generate a curve using a factorized or expanded polynomial"},
@@ -69,7 +71,7 @@ EnumPropertyItem rna_enum_fmodifier_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_beztriple_keyframe_type_items[] = {
+const EnumPropertyItem rna_enum_beztriple_keyframe_type_items[] = {
{BEZT_KEYTYPE_KEYFRAME, "KEYFRAME", VICO_KEYTYPE_KEYFRAME_VEC, "Keyframe", "Normal keyframe - e.g. for key poses"},
{BEZT_KEYTYPE_BREAKDOWN, "BREAKDOWN", VICO_KEYTYPE_BREAKDOWN_VEC, "Breakdown", "A breakdown pose - e.g. for transitions between key poses"},
{BEZT_KEYTYPE_MOVEHOLD, "MOVING_HOLD", VICO_KEYTYPE_MOVING_HOLD_VEC, "Moving Hold", "A keyframe that is part of a moving hold"},
@@ -78,7 +80,7 @@ EnumPropertyItem rna_enum_beztriple_keyframe_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_beztriple_interpolation_easing_items[] = {
+const EnumPropertyItem rna_enum_beztriple_interpolation_easing_items[] = {
/* XXX: auto-easing is currently using a placeholder icon... */
{BEZT_IPO_EASE_AUTO, "AUTO", ICON_IPO_EASE_IN_OUT, "Automatic Easing",
"Easing type is chosen automatically based on what the type of interpolation used "
@@ -493,7 +495,7 @@ static void rna_FCurve_active_modifier_set(PointerRNA *ptr, PointerRNA value)
static FModifier *rna_FCurve_modifiers_new(FCurve *fcu, int type)
{
- return add_fmodifier(&fcu->modifiers, type);
+ return add_fmodifier(&fcu->modifiers, type, fcu);
}
static void rna_FCurve_modifiers_remove(FCurve *fcu, ReportList *reports, PointerRNA *fcm_ptr)
@@ -584,11 +586,15 @@ static void rna_FModifier_blending_range(PointerRNA *ptr, float *min, float *max
static void rna_FModifier_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
ID *id = ptr->id.data;
+ FModifier *fcm = (FModifier *)ptr->data;
AnimData *adt = BKE_animdata_from_id(id);
DAG_id_tag_update(id, (GS(id->name) == ID_OB) ? OB_RECALC_OB : OB_RECALC_DATA);
if (adt != NULL) {
adt->recalc |= ADT_RECALC_ANIM;
}
+ if (fcm->curve && fcm->type == FMODIFIER_TYPE_CYCLES) {
+ calchandles_fcurve(fcm->curve);
+ }
}
static void rna_FModifier_verify_data_update(Main *bmain, Scene *scene, PointerRNA *ptr)
@@ -763,6 +769,38 @@ static void rna_FModifierStepped_end_frame_range(PointerRNA *ptr, float *min, fl
*max = MAXFRAMEF;
}
+static void rna_FModifierStepped_frame_start_set(PointerRNA *ptr, float value)
+{
+ FModifier *fcm = (FModifier *)ptr->data;
+ FMod_Stepped *data = fcm->data;
+
+ float prop_clamp_min = -FLT_MAX, prop_clamp_max = FLT_MAX, prop_soft_min, prop_soft_max;
+ rna_FModifierStepped_start_frame_range(ptr, &prop_clamp_min, &prop_clamp_max, &prop_soft_min, &prop_soft_max);
+ value = CLAMPIS(value, prop_clamp_min, prop_clamp_max);
+
+ /* Need to set both step-data's start/end and the start/end on the base-data,
+ * or else Restrict-Range doesn't work due to RNA-property shadowing (T52009)
+ */
+ data->start_frame = value;
+ fcm->sfra = value;
+}
+
+static void rna_FModifierStepped_frame_end_set(PointerRNA *ptr, float value)
+{
+ FModifier *fcm = (FModifier *)ptr->data;
+ FMod_Stepped *data = fcm->data;
+
+ float prop_clamp_min = -FLT_MAX, prop_clamp_max = FLT_MAX, prop_soft_min, prop_soft_max;
+ rna_FModifierStepped_end_frame_range(ptr, &prop_clamp_min, &prop_clamp_max, &prop_soft_min, &prop_soft_max);
+ value = CLAMPIS(value, prop_clamp_min, prop_clamp_max);
+
+ /* Need to set both step-data's start/end and the start/end on the base-data,
+ * or else Restrict-Range doesn't work due to RNA-property shadowing (T52009)
+ */
+ data->end_frame = value;
+ fcm->efra = value;
+}
+
static BezTriple *rna_FKeyframe_points_insert(FCurve *fcu, float frame, float value, int keyframe_type, int flag)
{
int index = insert_vert_fcurve(fcu, frame, value, (char)keyframe_type, flag | INSERTKEY_NO_USERPREF);
@@ -883,7 +921,7 @@ static void rna_def_fmodifier_generator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem generator_mode_items[] = {
+ static const EnumPropertyItem generator_mode_items[] = {
{FCM_GENERATOR_POLYNOMIAL, "POLYNOMIAL", 0, "Expanded Polynomial", ""},
{FCM_GENERATOR_POLYNOMIAL_FACTORISED, "POLYNOMIAL_FACTORISED", 0, "Factorized Polynomial", ""},
{0, NULL, 0, NULL, NULL}
@@ -930,7 +968,7 @@ static void rna_def_fmodifier_function_generator(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{0, "SIN", 0, "Sine", ""},
{1, "COS", 0, "Cosine", ""},
{2, "TAN", 0, "Tangent", ""},
@@ -1081,7 +1119,7 @@ static void rna_def_fmodifier_cycles(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{FCM_EXTRAPOLATE_NONE, "NONE", 0, "No Cycles", "Don't do anything"},
{FCM_EXTRAPOLATE_CYCLIC, "REPEAT", 0, "Repeat Motion", "Repeat keyframe range as-is"},
{FCM_EXTRAPOLATE_CYCLIC_OFFSET, "REPEAT_OFFSET", 0, "Repeat with Offset",
@@ -1198,7 +1236,7 @@ static void rna_def_fmodifier_noise(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_modification_items[] = {
+ static const EnumPropertyItem prop_modification_items[] = {
{FCM_NOISE_MODIF_REPLACE, "REPLACE", 0, "Replace", ""},
{FCM_NOISE_MODIF_ADD, "ADD", 0, "Add", ""},
{FCM_NOISE_MODIF_SUBTRACT, "SUBTRACT", 0, "Subtract", ""},
@@ -1282,13 +1320,13 @@ static void rna_def_fmodifier_stepped(BlenderRNA *brna)
prop = RNA_def_property(srna, "frame_start", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "start_frame");
- RNA_def_property_float_funcs(prop, NULL, NULL, "rna_FModifierStepped_start_frame_range");
+ RNA_def_property_float_funcs(prop, NULL, "rna_FModifierStepped_frame_start_set", "rna_FModifierStepped_start_frame_range");
RNA_def_property_ui_text(prop, "Start Frame", "Frame that modifier's influence starts (if applicable)");
RNA_def_property_update(prop, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, "rna_FModifier_update");
prop = RNA_def_property(srna, "frame_end", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "end_frame");
- RNA_def_property_float_funcs(prop, NULL, NULL, "rna_FModifierStepped_end_frame_range");
+ RNA_def_property_float_funcs(prop, NULL, "rna_FModifierStepped_frame_end_set", "rna_FModifierStepped_end_frame_range");
RNA_def_property_ui_text(prop, "End Frame", "Frame that modifier's influence ends (if applicable)");
RNA_def_property_update(prop, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, "rna_FModifier_update");
}
@@ -1403,7 +1441,7 @@ static void rna_def_drivertarget(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_trans_chan_items[] = {
+ static const EnumPropertyItem prop_trans_chan_items[] = {
{DTAR_TRANSCHAN_LOCX, "LOC_X", 0, "X Location", ""},
{DTAR_TRANSCHAN_LOCY, "LOC_Y", 0, "Y Location", ""},
{DTAR_TRANSCHAN_LOCZ, "LOC_Z", 0, "Z Location", ""},
@@ -1416,7 +1454,7 @@ static void rna_def_drivertarget(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_local_space_items[] = {
+ static const EnumPropertyItem prop_local_space_items[] = {
{0, "WORLD_SPACE", 0, "World Space", "Transforms include effects of parenting/restpose and constraints"},
{DTAR_FLAG_LOCALSPACE, "TRANSFORM_SPACE", 0, "Transform Space",
"Transforms don't include parenting/restpose or constraints"},
@@ -1448,6 +1486,7 @@ static void rna_def_drivertarget(BlenderRNA *brna)
RNA_def_property_enum_funcs(prop, NULL, "rna_DriverTarget_id_type_set", NULL);
RNA_def_property_editable_func(prop, "rna_DriverTarget_id_type_editable");
RNA_def_property_ui_text(prop, "ID Type", "Type of ID-block that can be used");
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_ID);
RNA_def_property_update(prop, 0, "rna_DriverTarget_update_data");
/* Target Properties - Property to Drive */
@@ -1480,7 +1519,7 @@ static void rna_def_drivervar(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{DVAR_TYPE_SINGLE_PROP, "SINGLE_PROP", ICON_RNA, "Single Property", "Use the value from some RNA property (Default)"},
{DVAR_TYPE_TRANSFORM_CHAN, "TRANSFORMS", ICON_MANIPUL, "Transform Channel",
"Final transformation value of object or bone"},
@@ -1563,7 +1602,7 @@ static void rna_def_channeldriver(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{DRIVER_TYPE_AVERAGE, "AVERAGE", 0, "Averaged Value", ""},
{DRIVER_TYPE_SUM, "SUM", 0, "Sum Values", ""},
{DRIVER_TYPE_PYTHON, "SCRIPTED", 0, "Scripted Expression", ""},
@@ -1793,7 +1832,7 @@ static void rna_def_fcurve_keyframe_points(BlenderRNA *brna, PropertyRNA *cprop)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem keyframe_flag_items[] = {
+ static const EnumPropertyItem keyframe_flag_items[] = {
{INSERTKEY_REPLACE, "REPLACE", 0, "Replace", "Don't add any new keyframes, but just replace existing ones"},
{INSERTKEY_NEEDED, "NEEDED", 0, "Needed", "Only adds keyframes that are needed"},
{INSERTKEY_FAST, "FAST", 0, "Fast", "Fast keyframe insertion to avoid recalculating the curve each time"},
@@ -1840,12 +1879,12 @@ static void rna_def_fcurve(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem prop_mode_extend_items[] = {
+ static const EnumPropertyItem prop_mode_extend_items[] = {
{FCURVE_EXTRAPOLATE_CONSTANT, "CONSTANT", 0, "Constant", "Hold values of endpoint keyframes"},
{FCURVE_EXTRAPOLATE_LINEAR, "LINEAR", 0, "Linear", "Use slope of curve leading in/out of endpoint keyframes"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mode_color_items[] = {
+ static const EnumPropertyItem prop_mode_color_items[] = {
{FCURVE_COLOR_AUTO_RAINBOW, "AUTO_RAINBOW", 0, "Auto Rainbow",
"Cycle through the rainbow, trying to give each curve a unique color"},
{FCURVE_COLOR_AUTO_RGB, "AUTO_RGB", 0, "Auto XYZ to RGB",
@@ -1856,6 +1895,11 @@ static void rna_def_fcurve(BlenderRNA *brna)
"Use custom hand-picked color for F-Curve"},
{0, NULL, 0, NULL, NULL}
};
+ static EnumPropertyItem prop_mode_smoothing_items[] = {
+ {FCURVE_SMOOTH_NONE, "NONE", 0, "None", "Auto handles only take adjacent keys into account (legacy mode)"},
+ {FCURVE_SMOOTH_CONT_ACCEL, "CONT_ACCEL", 0, "Continuous Acceleration", "Auto handles are placed to avoid jumps in acceleration"},
+ {0, NULL, 0, NULL, NULL}
+ };
srna = RNA_def_struct(brna, "FCurve", NULL);
RNA_def_struct_ui_text(srna, "F-Curve", "F-Curve defining values of a period of time");
@@ -1929,6 +1973,11 @@ static void rna_def_fcurve(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Hide", "F-Curve and its keyframes are hidden in the Graph Editor graphs");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
+ prop = RNA_def_property(srna, "auto_smoothing", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_items(prop, prop_mode_smoothing_items);
+ RNA_def_property_ui_text(prop, "Auto Handle Smoothing", "Algorithm used to compute automatic handles");
+ RNA_def_property_update(prop, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, "rna_FCurve_update_data");
+
/* State Info (for Debugging) */
prop = RNA_def_property(srna, "is_valid", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", FCURVE_DISABLED);
diff --git a/source/blender/makesrna/intern/rna_fluidsim.c b/source/blender/makesrna/intern/rna_fluidsim.c
index 091950a8e66..c7cfde18723 100644
--- a/source/blender/makesrna/intern/rna_fluidsim.c
+++ b/source/blender/makesrna/intern/rna_fluidsim.c
@@ -26,7 +26,7 @@
#include <stdlib.h>
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "BLI_threads.h"
#include "BLI_utildefines.h"
@@ -136,7 +136,7 @@ static void rna_FluidSettings_update_type(Main *bmain, Scene *scene, PointerRNA
if (ob->type == OB_MESH && !psys) {
/* add particle system */
- part = psys_new_settings("ParticleSettings", bmain);
+ part = BKE_particlesettings_add(bmain, "ParticleSettings");
psys = MEM_callocN(sizeof(ParticleSystem), "particle_system");
part->type = PART_FLUID;
@@ -185,12 +185,16 @@ static void rna_DomainFluidSettings_memory_estimate_get(PointerRNA *ptr, char *v
#endif
}
-static int rna_DomainFluidSettings_memory_estimate_length(PointerRNA *UNUSED(ptr))
+static int rna_DomainFluidSettings_memory_estimate_length(PointerRNA *ptr)
{
#ifndef WITH_MOD_FLUID
+ UNUSED_VARS(ptr);
return 0;
#else
- return 31;
+ char value[32];
+
+ rna_DomainFluidSettings_memory_estimate_get(ptr, value);
+ return strlen(value);
#endif
}
@@ -210,7 +214,7 @@ static void rna_def_fluidsim_slip(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem slip_items[] = {
+ static const EnumPropertyItem slip_items[] = {
{OB_FSBND_NOSLIP, "NOSLIP", 0, "No Slip",
"Obstacle causes zero normal and tangential velocity (=sticky), default for all "
"(only option for moving objects)"},
@@ -256,7 +260,7 @@ static void rna_def_fluidsim_domain(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem quality_items[] = {
+ static const EnumPropertyItem quality_items[] = {
{OB_FSDOM_GEOM, "GEOMETRY", 0, "Geometry", "Display geometry"},
{OB_FSDOM_PREVIEW, "PREVIEW", 0, "Preview", "Display preview quality results"},
{OB_FSDOM_FINAL, "FINAL", 0, "Final", "Display final quality results"},
@@ -440,7 +444,7 @@ static void rna_def_fluidsim_volume(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem volume_type_items[] = {
+ static const EnumPropertyItem volume_type_items[] = {
{1, "VOLUME", 0, "Volume", "Use only the inner volume of the mesh"},
{2, "SHELL", 0, "Shell", "Use only the outer shell of the mesh"},
{3, "BOTH", 0, "Both", "Use both the inner volume and the outer shell of the mesh"},
@@ -663,7 +667,7 @@ void RNA_def_fluidsim(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_fluid_type_items[] = {
+ static const EnumPropertyItem prop_fluid_type_items[] = {
{OB_FLUIDSIM_ENABLE, "NONE", 0, "None", ""},
{OB_FLUIDSIM_DOMAIN, "DOMAIN", 0, "Domain",
"Bounding box of this object represents the computational domain of the "
diff --git a/source/blender/makesrna/intern/rna_gpencil.c b/source/blender/makesrna/intern/rna_gpencil.c
index 6e0d6ad2bcd..b15f6dbccfa 100644
--- a/source/blender/makesrna/intern/rna_gpencil.c
+++ b/source/blender/makesrna/intern/rna_gpencil.c
@@ -46,7 +46,7 @@
#include "ED_gpencil.h"
/* parent type */
-static EnumPropertyItem parent_type_items[] = {
+static const EnumPropertyItem parent_type_items[] = {
{PAROBJECT, "OBJECT", 0, "Object", "The layer is parented to an object"},
{PARSKEL, "ARMATURE", 0, "Armature", ""},
{PARBONE, "BONE", 0, "Bone", "The layer is parented to a bone"},
@@ -74,7 +74,7 @@ static void rna_GPencil_editmode_update(Main *UNUSED(bmain), Scene *UNUSED(scene
{
/* Notify all places where GPencil data lives that the editing state is different */
WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
- WM_main_add_notifier(NC_SCENE | ND_MODE, NULL);
+ WM_main_add_notifier(NC_SCENE | ND_MODE | NC_MOVIECLIP, NULL);
}
static void rna_GPencil_onion_skinning_update(Main *bmain, Scene *scene, PointerRNA *ptr)
@@ -249,7 +249,7 @@ static void rna_GPencilLayer_parent_bone_set(PointerRNA *ptr, const char *value)
/* parent types enum */
-static EnumPropertyItem *rna_Object_parent_type_itemf(
+static const EnumPropertyItem *rna_Object_parent_type_itemf(
bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
@@ -959,19 +959,19 @@ static void rna_def_gpencil_triangle(BlenderRNA *brna)
/* point v1 */
prop = RNA_def_property(srna, "v1", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "v1");
+ RNA_def_property_int_sdna(prop, NULL, "verts[0]");
RNA_def_property_ui_text(prop, "v1", "First triangle vertex index");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
/* point v2 */
prop = RNA_def_property(srna, "v2", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "v2");
+ RNA_def_property_int_sdna(prop, NULL, "verts[1]");
RNA_def_property_ui_text(prop, "v2", "Second triangle vertex index");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
/* point v3 */
prop = RNA_def_property(srna, "v3", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "v3");
+ RNA_def_property_int_sdna(prop, NULL, "verts[2]");
RNA_def_property_ui_text(prop, "v3", "Third triangle vertex index");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
}
@@ -981,7 +981,7 @@ static void rna_def_gpencil_stroke(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem stroke_draw_mode_items[] = {
+ static const EnumPropertyItem stroke_draw_mode_items[] = {
{0, "SCREEN", 0, "Screen", "Stroke is in screen-space"},
{GP_STROKE_3DSPACE, "3DSPACE", 0, "3D Space", "Stroke is in 3D-space"},
{GP_STROKE_2DSPACE, "2DSPACE", 0, "2D Space", "Stroke is in 2D-space"},
diff --git a/source/blender/makesrna/intern/rna_image.c b/source/blender/makesrna/intern/rna_image.c
index f65aa90ea71..cb71cf756ec 100644
--- a/source/blender/makesrna/intern/rna_image.c
+++ b/source/blender/makesrna/intern/rna_image.c
@@ -44,14 +44,14 @@
#include "WM_types.h"
#include "WM_api.h"
-EnumPropertyItem rna_enum_image_generated_type_items[] = {
+const EnumPropertyItem rna_enum_image_generated_type_items[] = {
{IMA_GENTYPE_BLANK, "BLANK", 0, "Blank", "Generate a blank image"},
{IMA_GENTYPE_GRID, "UV_GRID", 0, "UV Grid", "Generated grid to test UV mappings"},
{IMA_GENTYPE_GRID_COLOR, "COLOR_GRID", 0, "Color Grid", "Generated improved UV grid to test UV mappings"},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem image_source_items[] = {
+static const EnumPropertyItem image_source_items[] = {
{IMA_SRC_FILE, "FILE", 0, "Single Image", "Single image file"},
{IMA_SRC_SEQUENCE, "SEQUENCE", 0, "Image Sequence", "Multiple image files, as a sequence"},
{IMA_SRC_MOVIE, "MOVIE", 0, "Movie", "Movie file"},
@@ -174,6 +174,11 @@ static void rna_ImageUser_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *
ImageUser *iuser = ptr->data;
BKE_image_user_frame_calc(iuser, scene->r.cfra, 0);
+
+ if (ptr->id.data) {
+ /* Update material or texture for render preview. */
+ DAG_id_tag_update(ptr->id.data, 0);
+ }
}
@@ -192,13 +197,15 @@ static char *rna_ImageUser_path(PointerRNA *ptr)
{
return rna_Node_ImageUser_path(ptr);
}
+ default:
+ break;
}
}
return BLI_strdup("");
}
-static EnumPropertyItem *rna_Image_source_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Image_source_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
Image *ima = (Image *)ptr->data;
@@ -871,7 +878,7 @@ static void rna_def_image(BlenderRNA *brna)
prop = RNA_def_property(srna, "has_data", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_funcs(prop, "rna_Image_has_data_get", NULL);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- RNA_def_property_ui_text(prop, "Has data", "True if this image has data");
+ RNA_def_property_ui_text(prop, "Has Data", "True if the image data is loaded into memory");
prop = RNA_def_property(srna, "depth", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_funcs(prop, "rna_Image_depth_get", NULL, NULL);
diff --git a/source/blender/makesrna/intern/rna_image_api.c b/source/blender/makesrna/intern/rna_image_api.c
index 344c1781b46..61f1edc0af5 100644
--- a/source/blender/makesrna/intern/rna_image_api.c
+++ b/source/blender/makesrna/intern/rna_image_api.c
@@ -67,7 +67,7 @@
static void rna_ImagePackedFile_save(ImagePackedFile *imapf, ReportList *reports)
{
if (writePackedFile(reports, imapf->filepath, imapf->packedfile, 0) != RET_OK) {
- BKE_reportf(reports, RPT_ERROR, "Image could not save packed file to '%s'",
+ BKE_reportf(reports, RPT_ERROR, "Could not save packed file to disk as '%s'",
imapf->filepath);
}
}
@@ -291,7 +291,7 @@ static void rna_Image_filepath_from_user(Image *image, ImageUser *image_user, ch
static void rna_Image_buffers_free(Image *image)
{
- BKE_image_free_buffers(image);
+ BKE_image_free_buffers_ex(image, true);
}
#else
diff --git a/source/blender/makesrna/intern/rna_internal.h b/source/blender/makesrna/intern/rna_internal.h
index 76455adbc78..2d513bd60b4 100644
--- a/source/blender/makesrna/intern/rna_internal.h
+++ b/source/blender/makesrna/intern/rna_internal.h
@@ -217,6 +217,7 @@ void rna_ID_name_set(struct PointerRNA *ptr, const char *value);
struct StructRNA *rna_ID_refine(struct PointerRNA *ptr);
struct IDProperty *rna_ID_idprops(struct PointerRNA *ptr, bool create);
void rna_ID_fake_user_set(struct PointerRNA *ptr, int value);
+void **rna_ID_instance(PointerRNA *ptr);
struct IDProperty *rna_PropertyGroup_idprops(struct PointerRNA *ptr, bool create);
void rna_PropertyGroup_unregister(struct Main *bmain, struct StructRNA *type);
struct StructRNA *rna_PropertyGroup_register(struct Main *bmain, struct ReportList *reports, void *data,
@@ -344,6 +345,7 @@ extern IntPropertyRNA rna_PropertyGroupItem_int_array;
extern FloatPropertyRNA rna_PropertyGroupItem_float;
extern FloatPropertyRNA rna_PropertyGroupItem_float_array;
extern PointerPropertyRNA rna_PropertyGroupItem_group;
+extern PointerPropertyRNA rna_PropertyGroupItem_id;
extern CollectionPropertyRNA rna_PropertyGroupItem_collection;
extern CollectionPropertyRNA rna_PropertyGroupItem_idp_array;
extern FloatPropertyRNA rna_PropertyGroupItem_double;
@@ -412,6 +414,8 @@ void rna_mtex_texture_slots_clear(struct ID *self, struct bContext *C, struct Re
int rna_IDMaterials_assign_int(struct PointerRNA *ptr, int key, const struct PointerRNA *assign_ptr);
+const char *rna_translate_ui_text(
+ const char *text, const char *text_ctxt, struct StructRNA *type, struct PropertyRNA *prop, int translate);
/* Internal functions that cycles uses so we need to declare (tsk tsk) */
void rna_RenderLayer_rect_set(PointerRNA *ptr, const float *values);
diff --git a/source/blender/makesrna/intern/rna_internal_types.h b/source/blender/makesrna/intern/rna_internal_types.h
index fce81e6967e..d93f3308b2a 100644
--- a/source/blender/makesrna/intern/rna_internal_types.h
+++ b/source/blender/makesrna/intern/rna_internal_types.h
@@ -88,12 +88,14 @@ typedef int (*PropStringLengthFunc)(struct PointerRNA *ptr);
typedef void (*PropStringSetFunc)(struct PointerRNA *ptr, const char *value);
typedef int (*PropEnumGetFunc)(struct PointerRNA *ptr);
typedef void (*PropEnumSetFunc)(struct PointerRNA *ptr, int value);
-typedef EnumPropertyItem *(*PropEnumItemFunc)(struct bContext *C, struct PointerRNA *ptr,
- struct PropertyRNA *prop, bool *r_free);
+typedef const EnumPropertyItem *(*PropEnumItemFunc)(
+ struct bContext *C, struct PointerRNA *ptr,
+ struct PropertyRNA *prop, bool *r_free);
typedef PointerRNA (*PropPointerGetFunc)(struct PointerRNA *ptr);
typedef StructRNA *(*PropPointerTypeFunc)(struct PointerRNA *ptr);
typedef void (*PropPointerSetFunc)(struct PointerRNA *ptr, const PointerRNA value);
typedef int (*PropPointerPollFunc)(struct PointerRNA *ptr, const PointerRNA value);
+typedef int (*PropPointerPollFuncPy)(struct PointerRNA *ptr, const PointerRNA value, const PropertyRNA *prop);
typedef void (*PropCollectionBeginFunc)(struct CollectionPropertyIterator *iter, struct PointerRNA *ptr);
typedef void (*PropCollectionNextFunc)(struct CollectionPropertyIterator *iter);
typedef void (*PropCollectionEndFunc)(struct CollectionPropertyIterator *iter);
@@ -166,6 +168,8 @@ struct PropertyRNA {
short flag_parameter;
/* Internal ("private") flags. */
short flag_internal;
+ /* The subset of StructRNA.prop_tag_defines values that applies to this property. */
+ short tags;
/* user readable name */
const char *name;
@@ -315,7 +319,7 @@ typedef struct EnumPropertyRNA {
PropEnumSetFuncEx set_ex;
void *py_data; /* store py callback here */
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int totitem;
int defaultvalue;
@@ -363,6 +367,9 @@ struct StructRNA {
/* various options */
int flag;
+ /* Each StructRNA type can define own tags which properties can set
+ * (PropertyRNA.tags) for changed behavior based on struct-type. */
+ const EnumPropertyItem *prop_tag_defines;
/* user readable name */
const char *name;
@@ -412,6 +419,11 @@ struct StructRNA {
struct BlenderRNA {
ListBase structs;
+ /* A map of structs: {StructRNA.identifier -> StructRNA}
+ * These are ensured to have unique names (with STRUCT_PUBLIC_NAMESPACE enabled). */
+ struct GHash *structs_map;
+ /* Needed because types with an empty identifier aren't included in 'structs_map'. */
+ unsigned int structs_len;
};
#define CONTAINER_RNA_ID(cont) (*(const char **)(((ContainerRNA *)(cont))+1))
diff --git a/source/blender/makesrna/intern/rna_key.c b/source/blender/makesrna/intern/rna_key.c
index a5abc8a3be2..e65011d34d7 100644
--- a/source/blender/makesrna/intern/rna_key.c
+++ b/source/blender/makesrna/intern/rna_key.c
@@ -178,6 +178,8 @@ static Mesh *rna_KeyBlock_normals_get_mesh(PointerRNA *ptr, ID *id)
return ob->data;
}
}
+ default:
+ break;
}
}
@@ -589,7 +591,7 @@ static char *rna_ShapeKeyPoint_path(PointerRNA *ptr)
#else
-EnumPropertyItem rna_enum_keyblock_type_items[] = {
+const EnumPropertyItem rna_enum_keyblock_type_items[] = {
{KEY_LINEAR, "KEY_LINEAR", 0, "Linear", ""},
{KEY_CARDINAL, "KEY_CARDINAL", 0, "Cardinal", ""},
{KEY_CATMULL_ROM, "KEY_CATMULL_ROM", 0, "Catmull-Rom", ""},
diff --git a/source/blender/makesrna/intern/rna_lamp.c b/source/blender/makesrna/intern/rna_lamp.c
index 51709d3137c..f29fa44d306 100644
--- a/source/blender/makesrna/intern/rna_lamp.c
+++ b/source/blender/makesrna/intern/rna_lamp.c
@@ -166,7 +166,7 @@ static void rna_Lamp_use_nodes_update(bContext *C, PointerRNA *ptr)
#else
/* Don't define icons here, so they don't show up in the Lamp UI (properties Editor) - DingTo */
-EnumPropertyItem rna_enum_lamp_type_items[] = {
+const EnumPropertyItem rna_enum_lamp_type_items[] = {
{LA_LOCAL, "POINT", 0, "Point", "Omnidirectional point light source"},
{LA_SUN, "SUN", 0, "Sun", "Constant direction parallel ray light source"},
{LA_SPOT, "SPOT", 0, "Spot", "Directional cone light source"},
@@ -180,7 +180,7 @@ static void rna_def_lamp_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_texture_coordinates_items[] = {
+ static const EnumPropertyItem prop_texture_coordinates_items[] = {
{TEXCO_GLOB, "GLOBAL", 0, "Global", "Use global coordinates for the texture coordinates"},
{TEXCO_VIEW, "VIEW", 0, "View", "Use view coordinates for the texture coordinates"},
{TEXCO_OBJECT, "OBJECT", 0, "Object", "Use linked object's coordinates for texture coordinates"},
@@ -230,7 +230,7 @@ static void rna_def_lamp_sky_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_skycolorspace_items[] = {
+ static const EnumPropertyItem prop_skycolorspace_items[] = {
{0, "SMPTE", 0, "SMPTE", ""},
{1, "REC709", 0, "REC709", ""},
{2, "CIE", 0, "CIE", ""},
@@ -416,7 +416,7 @@ static void rna_def_lamp_falloff(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_fallofftype_items[] = {
+ static const EnumPropertyItem prop_fallofftype_items[] = {
{LA_FALLOFF_CONSTANT, "CONSTANT", 0, "Constant", ""},
{LA_FALLOFF_INVLINEAR, "INVERSE_LINEAR", 0, "Inverse Linear", ""},
{LA_FALLOFF_INVSQUARE, "INVERSE_SQUARE", 0, "Inverse Square", ""},
@@ -479,33 +479,33 @@ static void rna_def_lamp_shadow(StructRNA *srna, int spot, int area)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_shadow_items[] = {
+ static const EnumPropertyItem prop_shadow_items[] = {
{0, "NOSHADOW", 0, "No Shadow", ""},
{LA_SHAD_RAY, "RAY_SHADOW", 0, "Ray Shadow", "Use ray tracing for shadow"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_spot_shadow_items[] = {
+ static const EnumPropertyItem prop_spot_shadow_items[] = {
{0, "NOSHADOW", 0, "No Shadow", ""},
{LA_SHAD_BUF, "BUFFER_SHADOW", 0, "Buffer Shadow", "Let spotlight produce shadows using shadow buffer"},
{LA_SHAD_RAY, "RAY_SHADOW", 0, "Ray Shadow", "Use ray tracing for shadow"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_ray_sampling_method_items[] = {
+ static const EnumPropertyItem prop_ray_sampling_method_items[] = {
{LA_SAMP_HALTON, "ADAPTIVE_QMC", 0, "Adaptive QMC", ""},
{LA_SAMP_HAMMERSLEY, "CONSTANT_QMC", 0, "Constant QMC", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_spot_ray_sampling_method_items[] = {
+ static const EnumPropertyItem prop_spot_ray_sampling_method_items[] = {
{LA_SAMP_HALTON, "ADAPTIVE_QMC", 0, "Adaptive QMC", ""},
{LA_SAMP_HAMMERSLEY, "CONSTANT_QMC", 0, "Constant QMC", ""},
{LA_SAMP_CONSTANT, "CONSTANT_JITTERED", 0, "Constant Jittered", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_shadbuftype_items[] = {
+ static const EnumPropertyItem prop_shadbuftype_items[] = {
{LA_SHADBUF_REGULAR, "REGULAR", 0, "Classical", "Classic shadow buffer"},
{LA_SHADBUF_HALFWAY, "HALFWAY", 0, "Classic-Halfway",
"Regular buffer, averaging the closest and 2nd closest Z value to reducing "
@@ -518,14 +518,14 @@ static void rna_def_lamp_shadow(StructRNA *srna, int spot, int area)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_shadbuffiltertype_items[] = {
+ static const EnumPropertyItem prop_shadbuffiltertype_items[] = {
{LA_SHADBUF_BOX, "BOX", 0, "Box", "Apply the Box filter to shadow buffer samples"},
{LA_SHADBUF_TENT, "TENT", 0, "Tent", "Apply the Tent Filter to shadow buffer samples"},
{LA_SHADBUF_GAUSS, "GAUSS", 0, "Gauss", "Apply the Gauss filter to shadow buffer samples"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_numbuffer_items[] = {
+ static const EnumPropertyItem prop_numbuffer_items[] = {
{1, "BUFFERS_1", 0, "1", "Only one buffer rendered"},
{4, "BUFFERS_4", 0, "4", "Render 4 buffers for better AA, this quadruples memory usage"},
{9, "BUFFERS_9", 0, "9", "Render 9 buffers for better AA, this uses nine times more memory"},
@@ -533,7 +533,7 @@ static void rna_def_lamp_shadow(StructRNA *srna, int spot, int area)
};
/* GE only */
- static EnumPropertyItem prop_ge_shadowbuffer_type_items[] = {
+ static const EnumPropertyItem prop_ge_shadowbuffer_type_items[] = {
{LA_SHADMAP_SIMPLE, "SIMPLE", 0, "Simple", "Simple shadow maps"},
{LA_SHADMAP_VARIANCE, "VARIANCE", 0, "Variance", "Variance shadow maps"},
{0, NULL, 0, NULL, NULL}
@@ -710,7 +710,7 @@ static void rna_def_area_lamp(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_areashape_items[] = {
+ static const EnumPropertyItem prop_areashape_items[] = {
{LA_AREA_SQUARE, "SQUARE", 0, "Square", ""},
{LA_AREA_RECT, "RECTANGLE", 0, "Rectangle", ""},
{0, NULL, 0, NULL, NULL}
diff --git a/source/blender/makesrna/intern/rna_linestyle.c b/source/blender/makesrna/intern/rna_linestyle.c
index 1199cccc4e6..bcd8ab054ae 100644
--- a/source/blender/makesrna/intern/rna_linestyle.c
+++ b/source/blender/makesrna/intern/rna_linestyle.c
@@ -42,7 +42,7 @@
#include "WM_types.h"
#include "WM_api.h"
-EnumPropertyItem rna_enum_linestyle_color_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_linestyle_color_modifier_type_items[] = {
{LS_MODIFIER_ALONG_STROKE, "ALONG_STROKE", ICON_MODIFIER, "Along Stroke", ""},
{LS_MODIFIER_CREASE_ANGLE, "CREASE_ANGLE", ICON_MODIFIER, "Crease Angle", ""},
{LS_MODIFIER_CURVATURE_3D, "CURVATURE_3D", ICON_MODIFIER, "Curvature 3D", ""},
@@ -54,7 +54,7 @@ EnumPropertyItem rna_enum_linestyle_color_modifier_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_linestyle_alpha_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_linestyle_alpha_modifier_type_items[] = {
{LS_MODIFIER_ALONG_STROKE, "ALONG_STROKE", ICON_MODIFIER, "Along Stroke", ""},
{LS_MODIFIER_CREASE_ANGLE, "CREASE_ANGLE", ICON_MODIFIER, "Crease Angle", ""},
{LS_MODIFIER_CURVATURE_3D, "CURVATURE_3D", ICON_MODIFIER, "Curvature 3D", ""},
@@ -66,7 +66,7 @@ EnumPropertyItem rna_enum_linestyle_alpha_modifier_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_linestyle_thickness_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_linestyle_thickness_modifier_type_items[] = {
{LS_MODIFIER_ALONG_STROKE, "ALONG_STROKE", ICON_MODIFIER, "Along Stroke", ""},
{LS_MODIFIER_CALLIGRAPHY, "CALLIGRAPHY", ICON_MODIFIER, "Calligraphy", ""},
{LS_MODIFIER_CREASE_ANGLE, "CREASE_ANGLE", ICON_MODIFIER, "Crease Angle", ""},
@@ -79,7 +79,7 @@ EnumPropertyItem rna_enum_linestyle_thickness_modifier_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_linestyle_geometry_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_linestyle_geometry_modifier_type_items[] = {
{LS_MODIFIER_2D_OFFSET, "2D_OFFSET", ICON_MODIFIER, "2D Offset", ""},
{LS_MODIFIER_2D_TRANSFORM, "2D_TRANSFORM", ICON_MODIFIER, "2D Transform", ""},
{LS_MODIFIER_BACKBONE_STRETCHER, "BACKBONE_STRETCHER", ICON_MODIFIER, "Backbone Stretcher", ""},
@@ -474,7 +474,7 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem texco_items[] = {
+ static const EnumPropertyItem texco_items[] = {
{TEXCO_WINDOW, "WINDOW", 0, "Window", "Use screen coordinates as texture coordinates"},
{TEXCO_GLOB, "GLOBAL", 0, "Global", "Use global coordinates for the texture coordinates"},
{TEXCO_STROKE, "ALONG_STROKE", 0, "Along stroke", "Use stroke length for texture coordinates"},
@@ -482,7 +482,7 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mapping_items[] = {
+ static const EnumPropertyItem prop_mapping_items[] = {
{MTEX_FLAT, "FLAT", 0, "Flat", "Map X and Y coordinates directly"},
{MTEX_CUBE, "CUBE", 0, "Cube", "Map using the normal vector"},
{MTEX_TUBE, "TUBE", 0, "Tube", "Map with Z as central axis"},
@@ -490,7 +490,7 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_x_mapping_items[] = {
+ static const EnumPropertyItem prop_x_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -498,7 +498,7 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_y_mapping_items[] = {
+ static const EnumPropertyItem prop_y_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -506,7 +506,7 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_z_mapping_items[] = {
+ static const EnumPropertyItem prop_z_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -578,13 +578,13 @@ static void rna_def_linestyle_mtex(BlenderRNA *brna)
}
static void rna_def_modifier_type_common(
- StructRNA *srna, EnumPropertyItem *modifier_type_items,
+ StructRNA *srna, const EnumPropertyItem *modifier_type_items,
const char *set_name_func, const bool blend, const bool color)
{
PropertyRNA *prop;
/* TODO: Check this is not already defined somewhere else, e.g. in nodes... */
- static EnumPropertyItem value_blend_items[] = {
+ static const EnumPropertyItem value_blend_items[] = {
{LS_VALUE_BLEND, "MIX", 0, "Mix", ""},
{LS_VALUE_ADD, "ADD", 0, "Add", ""},
{LS_VALUE_SUB, "SUBTRACT", 0, "Subtract", ""},
@@ -684,7 +684,7 @@ static void rna_def_modifier_curve_common(StructRNA *srna, bool range, bool valu
{
PropertyRNA *prop;
- static EnumPropertyItem mapping_items[] = {
+ static const EnumPropertyItem mapping_items[] = {
{0, "LINEAR", 0, "Linear", "Use linear mapping"},
{LS_MODIFIER_USE_CURVE, "CURVE", 0, "Curve", "Use curve mapping"},
{0, NULL, 0, NULL, NULL}
@@ -736,7 +736,7 @@ static void rna_def_modifier_material_common(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem mat_attr_items[] = {
+ static const EnumPropertyItem mat_attr_items[] = {
{LS_MODIFIER_MATERIAL_LINE, "LINE", 0, "Line Color", ""},
{LS_MODIFIER_MATERIAL_LINE_R, "LINE_R", 0, "Line Color Red", ""},
{LS_MODIFIER_MATERIAL_LINE_G, "LINE_G", 0, "Line Color Green", ""},
@@ -768,14 +768,14 @@ static void rna_def_linestyle_modifiers(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem blueprint_shape_items[] = {
+ static const EnumPropertyItem blueprint_shape_items[] = {
{LS_MODIFIER_BLUEPRINT_CIRCLES, "CIRCLES", 0, "Circles", "Draw a blueprint using circular contour strokes"},
{LS_MODIFIER_BLUEPRINT_ELLIPSES, "ELLIPSES", 0, "Ellipses", "Draw a blueprint using elliptic contour strokes"},
{LS_MODIFIER_BLUEPRINT_SQUARES, "SQUARES", 0, "Squares", "Draw a blueprint using square contour strokes"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem transform_pivot_items[] = {
+ static const EnumPropertyItem transform_pivot_items[] = {
{LS_MODIFIER_2D_TRANSFORM_PIVOT_CENTER, "CENTER", 0, "Stroke Center", ""},
{LS_MODIFIER_2D_TRANSFORM_PIVOT_START, "START", 0, "Stroke Start", ""},
{LS_MODIFIER_2D_TRANSFORM_PIVOT_END, "END", 0, "Stroke End", ""},
@@ -1558,7 +1558,7 @@ static void rna_def_linestyle(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem panel_items[] = {
+ static const EnumPropertyItem panel_items[] = {
{LS_PANEL_STROKES, "STROKES", 0, "Strokes", "Show the panel for stroke construction"},
{LS_PANEL_COLOR, "COLOR", 0, "Color", "Show the panel for line color options"},
{LS_PANEL_ALPHA, "ALPHA", 0, "Alpha", "Show the panel for alpha transparency options"},
@@ -1570,37 +1570,37 @@ static void rna_def_linestyle(BlenderRNA *brna)
#endif
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem chaining_items[] = {
+ static const EnumPropertyItem chaining_items[] = {
{LS_CHAINING_PLAIN, "PLAIN", 0, "Plain", "Plain chaining"},
{LS_CHAINING_SKETCHY, "SKETCHY", 0, "Sketchy", "Sketchy chaining with a multiple touch"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem cap_items[] = {
+ static const EnumPropertyItem cap_items[] = {
{LS_CAPS_BUTT, "BUTT", 0, "Butt", "Butt cap (flat)"},
{LS_CAPS_ROUND, "ROUND", 0, "Round", "Round cap (half-circle)"},
{LS_CAPS_SQUARE, "SQUARE", 0, "Square", "Square cap (flat and extended)"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem thickness_position_items[] = {
+ static const EnumPropertyItem thickness_position_items[] = {
{LS_THICKNESS_CENTER, "CENTER", 0, "Center", "Silhouettes and border edges are centered along stroke geometry"},
{LS_THICKNESS_INSIDE, "INSIDE", 0, "Inside", "Silhouettes and border edges are drawn inside of stroke geometry"},
{LS_THICKNESS_OUTSIDE, "OUTSIDE", 0, "Outside", "Silhouettes and border edges are drawn outside of stroke geometry"},
{LS_THICKNESS_RELATIVE, "RELATIVE", 0, "Relative", "Silhouettes and border edges are shifted by a user-defined ratio"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem sort_key_items[] = {
+ static const EnumPropertyItem sort_key_items[] = {
{LS_SORT_KEY_DISTANCE_FROM_CAMERA, "DISTANCE_FROM_CAMERA", 0, "Distance from Camera", "Sort by distance from camera (closer lines lie on top of further lines)"},
{LS_SORT_KEY_2D_LENGTH, "2D_LENGTH", 0, "2D Length", "Sort by curvilinear 2D length (longer lines lie on top of shorter lines)"},
{LS_SORT_KEY_PROJECTED_X, "PROJECTED_X", 0, "Projected X", "Sort by the projected X value in the image coordinate system"},
{LS_SORT_KEY_PROJECTED_Y, "PROJECTED_Y", 0, "Projected Y", "Sort by the projected Y value in the image coordinate system"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem sort_order_items[] = {
+ static const EnumPropertyItem sort_order_items[] = {
{0, "DEFAULT", 0, "Default", "Default order of the sort key"},
{LS_REVERSE_ORDER, "REVERSE", 0, "Reverse", "Reverse order"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem integration_type_items[] = {
+ static const EnumPropertyItem integration_type_items[] = {
{LS_INTEGRATION_MEAN, "MEAN", 0, "Mean", "The value computed for the chain is the mean of the values obtained for chain vertices"},
{LS_INTEGRATION_MIN, "MIN", 0, "Min", "The value computed for the chain is the minimum of the values obtained for chain vertices"},
{LS_INTEGRATION_MAX, "MAX", 0, "Max", "The value computed for the chain is the maximum of the values obtained for chain vertices"},
@@ -1620,6 +1620,7 @@ static void rna_def_linestyle(BlenderRNA *brna)
prop = RNA_def_property(srna, "panel", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_bitflag_sdna(prop, NULL, "panel");
RNA_def_property_enum_items(prop, panel_items);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_ui_text(prop, "Panel", "Select the property panel to be shown");
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR);
diff --git a/source/blender/makesrna/intern/rna_main_api.c b/source/blender/makesrna/intern/rna_main_api.c
index c110dbff6c4..4aa4eddaddb 100644
--- a/source/blender/makesrna/intern/rna_main_api.c
+++ b/source/blender/makesrna/intern/rna_main_api.c
@@ -123,7 +123,8 @@ static void rna_idname_validate(const char *name, char *r_name)
}
-static void rna_Main_ID_remove(Main *bmain, ReportList *reports, PointerRNA *id_ptr, int do_unlink)
+static void rna_Main_ID_remove(Main *bmain, ReportList *reports, PointerRNA *id_ptr,
+ int do_unlink, int do_id_user, int do_ui_user)
{
ID *id = id_ptr->data;
if (do_unlink) {
@@ -131,7 +132,7 @@ static void rna_Main_ID_remove(Main *bmain, ReportList *reports, PointerRNA *id_
RNA_POINTER_INVALIDATE(id_ptr);
}
else if (ID_REAL_USERS(id) <= 0) {
- BKE_libblock_free(bmain, id);
+ BKE_libblock_free_ex(bmain, id, do_id_user, do_ui_user);
RNA_POINTER_INVALIDATE(id_ptr);
}
else {
@@ -184,7 +185,7 @@ static void rna_Main_scenes_remove(Main *bmain, bContext *C, ReportList *reports
}
}
- rna_Main_ID_remove(bmain, reports, scene_ptr, do_unlink);
+ rna_Main_ID_remove(bmain, reports, scene_ptr, do_unlink, true, true);
}
else {
BKE_reportf(reports, RPT_ERROR, "Scene '%s' is the last, cannot be removed", scene->id.name + 2);
@@ -258,7 +259,7 @@ static Material *rna_Main_materials_new(Main *bmain, const char *name)
return (Material *)id;
}
-static EnumPropertyItem *rna_Main_nodetree_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rna_Main_nodetree_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
return rna_node_tree_type_itemf(NULL, NULL, r_free);
}
@@ -429,7 +430,7 @@ static World *rna_Main_worlds_new(Main *bmain, const char *name)
char safe_name[MAX_ID_NAME - 2];
rna_idname_validate(name, safe_name);
- World *world = add_world(bmain, safe_name);
+ World *world = BKE_world_add(bmain, safe_name);
id_us_min(&world->id);
return world;
}
@@ -504,7 +505,7 @@ static bAction *rna_Main_actions_new(Main *bmain, const char *name)
char safe_name[MAX_ID_NAME - 2];
rna_idname_validate(name, safe_name);
- bAction *act = add_empty_action(bmain, safe_name);
+ bAction *act = BKE_action_add(bmain, safe_name);
id_fake_user_clear(&act->id);
return act;
}
@@ -514,7 +515,7 @@ static ParticleSettings *rna_Main_particles_new(Main *bmain, const char *name)
char safe_name[MAX_ID_NAME - 2];
rna_idname_validate(name, safe_name);
- ParticleSettings *part = psys_new_settings(safe_name, bmain);
+ ParticleSettings *part = BKE_particlesettings_add(bmain, safe_name);
id_us_min(&part->id);
return part;
}
@@ -542,9 +543,13 @@ static MovieClip *rna_Main_movieclip_load(Main *bmain, ReportList *reports, cons
clip = BKE_movieclip_file_add(bmain, filepath);
}
- if (!clip)
+ if (clip != NULL) {
+ DAG_relations_tag_update(bmain);
+ }
+ else {
BKE_reportf(reports, RPT_ERROR, "Cannot read '%s': %s", filepath,
errno ? strerror(errno) : TIP_("unable to load movie clip"));
+ }
id_us_min((ID *)clip);
return clip;
@@ -661,6 +666,10 @@ void RNA_def_main_cameras(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this camera before deleting it "
"(WARNING: will also delete objects instancing that camera data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this camera");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this camera");
func = RNA_def_function(srna, "tag", "rna_Main_cameras_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -739,6 +748,10 @@ void RNA_def_main_objects(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this object before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this object");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this object");
func = RNA_def_function(srna, "tag", "rna_Main_objects_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -776,6 +789,10 @@ void RNA_def_main_materials(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this material before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this material");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this material");
func = RNA_def_function(srna, "tag", "rna_Main_materials_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -792,7 +809,7 @@ void RNA_def_main_node_groups(BlenderRNA *brna, PropertyRNA *cprop)
PropertyRNA *parm;
PropertyRNA *prop;
- static EnumPropertyItem dummy_items[] = {
+ static const EnumPropertyItem dummy_items[] = {
{0, "DUMMY", 0, "", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -820,6 +837,10 @@ void RNA_def_main_node_groups(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this node tree before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this node tree");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this node tree");
func = RNA_def_function(srna, "tag", "rna_Main_node_groups_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -836,7 +857,7 @@ void RNA_def_main_meshes(BlenderRNA *brna, PropertyRNA *cprop)
PropertyRNA *parm;
PropertyRNA *prop;
- static EnumPropertyItem mesh_type_items[] = {
+ static const EnumPropertyItem mesh_type_items[] = {
{eModifierMode_Realtime, "PREVIEW", 0, "Preview", "Apply modifier preview settings"},
{eModifierMode_Render, "RENDER", 0, "Render", "Apply modifier render settings"},
{0, NULL, 0, NULL, NULL}
@@ -881,6 +902,10 @@ void RNA_def_main_meshes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this mesh before deleting it "
"(WARNING: will also delete objects instancing that mesh data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this mesh data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this mesh data");
func = RNA_def_function(srna, "tag", "rna_Main_meshes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -921,6 +946,10 @@ void RNA_def_main_lamps(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this lamp before deleting it "
"(WARNING: will also delete objects instancing that lamp data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this lamp data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this lamp data");
func = RNA_def_function(srna, "tag", "rna_Main_lamps_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1037,6 +1066,10 @@ void RNA_def_main_images(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this image before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this image");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this image");
func = RNA_def_function(srna, "tag", "rna_Main_images_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1076,6 +1109,10 @@ void RNA_def_main_lattices(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this lattice before deleting it "
"(WARNING: will also delete objects instancing that lattice data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this lattice data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this lattice data");
func = RNA_def_function(srna, "tag", "rna_Main_lattices_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1116,6 +1153,10 @@ void RNA_def_main_curves(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this curve before deleting it "
"(WARNING: will also delete objects instancing that curve data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this curve data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this curve data");
func = RNA_def_function(srna, "tag", "rna_Main_curves_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1154,6 +1195,10 @@ void RNA_def_main_metaballs(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this metaball before deleting it "
"(WARNING: will also delete objects instancing that metaball data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this metaball data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this metaball data");
func = RNA_def_function(srna, "tag", "rna_Main_metaballs_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1192,6 +1237,10 @@ void RNA_def_main_fonts(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this font before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this font");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this font");
func = RNA_def_function(srna, "tag", "rna_Main_fonts_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1230,6 +1279,10 @@ void RNA_def_main_textures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this texture before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this texture");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this texture");
func = RNA_def_function(srna, "tag", "rna_Main_textures_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1267,6 +1320,10 @@ void RNA_def_main_brushes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this brush before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this brush");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this brush");
func = RNA_def_function(srna, "tag", "rna_Main_brushes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1304,6 +1361,10 @@ void RNA_def_main_worlds(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this world before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this world");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this world");
func = RNA_def_function(srna, "tag", "rna_Main_worlds_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1341,6 +1402,10 @@ void RNA_def_main_groups(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this group before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this group");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this group");
func = RNA_def_function(srna, "tag", "rna_Main_groups_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1380,6 +1445,10 @@ void RNA_def_main_speakers(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this speaker before deleting it "
"(WARNING: will also delete objects instancing that speaker data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this speaker data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this speaker data");
func = RNA_def_function(srna, "tag", "rna_Main_speakers_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1417,6 +1486,10 @@ void RNA_def_main_texts(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this text before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this text");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this text");
/* load func */
func = RNA_def_function(srna, "load", "rna_Main_texts_load");
@@ -1467,6 +1540,10 @@ void RNA_def_main_sounds(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this sound before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this sound");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this sound");
func = RNA_def_function(srna, "tag", "rna_Main_sounds_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1506,6 +1583,10 @@ void RNA_def_main_armatures(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_boolean(func, "do_unlink", true, "",
"Unlink all usages of this armature before deleting it "
"(WARNING: will also delete objects instancing that armature data)");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this armature data");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this armature data");
func = RNA_def_function(srna, "tag", "rna_Main_armatures_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1542,6 +1623,10 @@ void RNA_def_main_actions(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this action before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this action");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this action");
func = RNA_def_function(srna, "tag", "rna_Main_actions_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1578,6 +1663,10 @@ void RNA_def_main_particles(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of those particle settings before deleting them");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this particle settings");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this particle settings");
func = RNA_def_function(srna, "tag", "rna_Main_particles_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1614,6 +1703,10 @@ void RNA_def_main_palettes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this palette before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this palette");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this palette");
func = RNA_def_function(srna, "tag", "rna_Main_palettes_tag");
parm = RNA_def_boolean(func, "value", 0, "Value", "");
@@ -1694,6 +1787,10 @@ void RNA_def_main_gpencil(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this grease pencil before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this grease pencil");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this grease pencil");
prop = RNA_def_property(srna, "is_updated", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
@@ -1723,6 +1820,10 @@ void RNA_def_main_movieclips(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this movie clip before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this movie clip");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this movie clip");
/* load func */
func = RNA_def_function(srna, "load", "rna_Main_movieclip_load");
@@ -1775,6 +1876,10 @@ void RNA_def_main_masks(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this mask before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this mask");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this mask");
prop = RNA_def_property(srna, "is_updated", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
@@ -1812,6 +1917,10 @@ void RNA_def_main_linestyles(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
RNA_def_parameter_clear_flags(parm, PROP_THICK_WRAP, 0);
RNA_def_boolean(func, "do_unlink", true, "", "Unlink all usages of this line style before deleting it");
+ RNA_def_boolean(func, "do_id_user", true, "",
+ "Decrement user counter of all datablocks used by this line style");
+ RNA_def_boolean(func, "do_ui_user", true, "",
+ "Make sure interface does not reference this line style");
prop = RNA_def_property(srna, "is_updated", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
diff --git a/source/blender/makesrna/intern/rna_mask.c b/source/blender/makesrna/intern/rna_mask.c
index 24dfff89832..c266e0e7f31 100644
--- a/source/blender/makesrna/intern/rna_mask.c
+++ b/source/blender/makesrna/intern/rna_mask.c
@@ -52,13 +52,13 @@
#ifdef RNA_RUNTIME
+#include "BLI_math.h"
+
#include "DNA_movieclip_types.h"
#include "BKE_depsgraph.h"
#include "BKE_mask.h"
-#include "BLI_math.h"
-
#include "RNA_access.h"
#include "WM_api.h"
@@ -593,11 +593,11 @@ static void rna_def_maskParent(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem mask_id_type_items[] = {
+ static const EnumPropertyItem mask_id_type_items[] = {
{ID_MC, "MOVIECLIP", ICON_SEQUENCE, "Movie Clip", ""},
{0, NULL, 0, NULL, NULL}};
- static EnumPropertyItem parent_type_items[] = {
+ static const EnumPropertyItem parent_type_items[] = {
{MASK_PARENT_POINT_TRACK, "POINT_TRACK", 0, "Point Track", ""},
{MASK_PARENT_PLANE_TRACK, "PLANE_TRACK", 0, "Plane Track", ""},
{0, NULL, 0, NULL, NULL}};
@@ -677,7 +677,7 @@ static void rna_def_maskSplinePoint(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem handle_type_items[] = {
+ static const EnumPropertyItem handle_type_items[] = {
{HD_AUTO, "AUTO", 0, "Auto", ""},
{HD_VECT, "VECTOR", 0, "Vector", ""},
{HD_ALIGN, "ALIGNED", 0, "Aligned Single", ""},
@@ -824,13 +824,13 @@ static void rna_def_maskSplinePoints(BlenderRNA *brna)
static void rna_def_maskSpline(BlenderRNA *brna)
{
- static EnumPropertyItem spline_interpolation_items[] = {
+ static const EnumPropertyItem spline_interpolation_items[] = {
{MASK_SPLINE_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
{MASK_SPLINE_INTERP_EASE, "EASE", 0, "Ease", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem spline_offset_mode_items[] = {
+ static const EnumPropertyItem spline_offset_mode_items[] = {
{MASK_SPLINE_OFFSET_EVEN, "EVEN", 0, "Even", "Calculate even feather offset"},
{MASK_SPLINE_OFFSET_SMOOTH, "SMOOTH", 0, "Smooth", "Calculate feather offset as a second curve"},
{0, NULL, 0, NULL, NULL}
@@ -888,7 +888,7 @@ static void rna_def_maskSpline(BlenderRNA *brna)
static void rna_def_mask_layer(BlenderRNA *brna)
{
- static EnumPropertyItem masklay_blend_mode_items[] = {
+ static const EnumPropertyItem masklay_blend_mode_items[] = {
{MASK_BLEND_MERGE_ADD, "MERGE_ADD", 0, "Merge Add", ""},
{MASK_BLEND_MERGE_SUBTRACT, "MERGE_SUBTRACT", 0, "Merge Subtract", ""},
{MASK_BLEND_ADD, "ADD", 0, "Add", ""},
diff --git a/source/blender/makesrna/intern/rna_material.c b/source/blender/makesrna/intern/rna_material.c
index b293f20dd95..1959a017e43 100644
--- a/source/blender/makesrna/intern/rna_material.c
+++ b/source/blender/makesrna/intern/rna_material.c
@@ -38,7 +38,7 @@
#include "WM_api.h"
#include "WM_types.h"
-static EnumPropertyItem prop_texture_coordinates_items[] = {
+static const EnumPropertyItem prop_texture_coordinates_items[] = {
{TEXCO_GLOB, "GLOBAL", 0, "Global", "Use global coordinates for the texture coordinates"},
{TEXCO_OBJECT, "OBJECT", 0, "Object", "Use linked object's coordinates for texture coordinates"},
{TEXCO_UV, "UV", 0, "UV", "Use UV coordinates for texture coordinates"},
@@ -54,7 +54,7 @@ static EnumPropertyItem prop_texture_coordinates_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_ramp_blend_items[] = {
+const EnumPropertyItem rna_enum_ramp_blend_items[] = {
{MA_RAMP_BLEND, "MIX", 0, "Mix", ""},
{MA_RAMP_ADD, "ADD", 0, "Add", ""},
{MA_RAMP_MULT, "MULTIPLY", 0, "Multiply", ""},
@@ -85,6 +85,7 @@ EnumPropertyItem rna_enum_ramp_blend_items[] = {
#include "DNA_screen_types.h"
#include "DNA_space_types.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_main.h"
@@ -321,7 +322,7 @@ static void rna_Material_use_diffuse_ramp_set(PointerRNA *ptr, int value)
else ma->mode &= ~MA_RAMP_COL;
if ((ma->mode & MA_RAMP_COL) && ma->ramp_col == NULL)
- ma->ramp_col = add_colorband(false);
+ ma->ramp_col = BKE_colorband_add(false);
}
static void rna_Material_use_specular_ramp_set(PointerRNA *ptr, int value)
@@ -332,7 +333,7 @@ static void rna_Material_use_specular_ramp_set(PointerRNA *ptr, int value)
else ma->mode &= ~MA_RAMP_SPEC;
if ((ma->mode & MA_RAMP_SPEC) && ma->ramp_spec == NULL)
- ma->ramp_spec = add_colorband(false);
+ ma->ramp_spec = BKE_colorband_add(false);
}
static void rna_Material_use_nodes_update(bContext *C, PointerRNA *ptr)
@@ -345,7 +346,7 @@ static void rna_Material_use_nodes_update(bContext *C, PointerRNA *ptr)
rna_Material_draw_update(CTX_data_main(C), CTX_data_scene(C), ptr);
}
-static EnumPropertyItem *rna_Material_texture_coordinates_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Material_texture_coordinates_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
Material *ma = (Material *)ptr->id.data;
@@ -357,7 +358,7 @@ static EnumPropertyItem *rna_Material_texture_coordinates_itemf(bContext *UNUSED
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_ORCO);
if (ma->material_type == MA_TYPE_VOLUME) {
-
+ /* pass */
}
else if (ELEM(ma->material_type, MA_TYPE_SURFACE, MA_TYPE_HALO, MA_TYPE_WIRE)) {
RNA_enum_items_add_value(&item, &totitem, prop_texture_coordinates_items, TEXCO_UV);
@@ -441,7 +442,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_mapping_items[] = {
+ static const EnumPropertyItem prop_mapping_items[] = {
{MTEX_FLAT, "FLAT", 0, "Flat", "Map X and Y coordinates directly"},
{MTEX_CUBE, "CUBE", 0, "Cube", "Map using the normal vector"},
{MTEX_TUBE, "TUBE", 0, "Tube", "Map with Z as central axis"},
@@ -449,7 +450,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_x_mapping_items[] = {
+ static const EnumPropertyItem prop_x_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -457,7 +458,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_y_mapping_items[] = {
+ static const EnumPropertyItem prop_y_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -465,7 +466,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_z_mapping_items[] = {
+ static const EnumPropertyItem prop_z_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -473,7 +474,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_normal_map_space_items[] = {
+ static const EnumPropertyItem prop_normal_map_space_items[] = {
{MTEX_NSPACE_CAMERA, "CAMERA", 0, "Camera", ""},
{MTEX_NSPACE_WORLD, "WORLD", 0, "World", ""},
{MTEX_NSPACE_OBJECT, "OBJECT", 0, "Object", ""},
@@ -481,7 +482,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_bump_method_items[] = {
+ static const EnumPropertyItem prop_bump_method_items[] = {
{0, "BUMP_ORIGINAL", 0, "Original", ""},
{MTEX_COMPAT_BUMP, "BUMP_COMPATIBLE", 0, "Compatible", ""},
{MTEX_3TAP_BUMP, "BUMP_LOW_QUALITY", 0, "Low Quality", "Use 3 tap filtering"},
@@ -492,7 +493,7 @@ static void rna_def_material_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_bump_space_items[] = {
+ static const EnumPropertyItem prop_bump_space_items[] = {
{0, "BUMP_VIEWSPACE", 0, "ViewSpace", ""},
{MTEX_BUMP_OBJECTSPACE, "BUMP_OBJECTSPACE", 0, "ObjectSpace", ""},
{MTEX_BUMP_TEXTURESPACE, "BUMP_TEXTURESPACE", 0, "TextureSpace", ""},
@@ -829,7 +830,7 @@ static void rna_def_material_gamesettings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_alpha_blend_items[] = {
+ static const EnumPropertyItem prop_alpha_blend_items[] = {
{GEMAT_SOLID, "OPAQUE", 0, "Opaque", "Render color of textured face as color"},
{GEMAT_ADD, "ADD", 0, "Add", "Render face transparent and add color of face"},
{GEMAT_CLIP, "CLIP", 0, "Alpha Clip", "Use the image alpha values clipped with no blending (binary alpha)"},
@@ -842,7 +843,7 @@ static void rna_def_material_gamesettings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_face_orientation_items[] = {
+ static const EnumPropertyItem prop_face_orientation_items[] = {
{GEMAT_NORMAL, "NORMAL", 0, "Normal", "No transformation"},
{GEMAT_HALO, "HALO", 0, "Halo", "Screen aligned billboard"},
{GEMAT_BILLBOARD, "BILLBOARD", 0, "Billboard", "Billboard with Z-axis constraint"},
@@ -889,7 +890,7 @@ static void rna_def_material_colors(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_ramp_input_items[] = {
+ static const EnumPropertyItem prop_ramp_input_items[] = {
{MA_RAMP_IN_SHADER, "SHADER", 0, "Shader", ""},
{MA_RAMP_IN_ENERGY, "ENERGY", 0, "Energy", ""},
{MA_RAMP_IN_NOR, "NORMAL", 0, "Normal", ""},
@@ -1006,7 +1007,7 @@ static void rna_def_material_diffuse(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_diff_shader_items[] = {
+ static const EnumPropertyItem prop_diff_shader_items[] = {
{MA_DIFF_LAMBERT, "LAMBERT", 0, "Lambert", "Use a Lambertian shader"},
{MA_DIFF_ORENNAYAR, "OREN_NAYAR", 0, "Oren-Nayar", "Use an Oren-Nayar shader"},
{MA_DIFF_TOON, "TOON", 0, "Toon", "Use a toon shader"},
@@ -1067,7 +1068,7 @@ static void rna_def_material_raymirror(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_fadeto_mir_items[] = {
+ static const EnumPropertyItem prop_fadeto_mir_items[] = {
{MA_RAYMIR_FADETOSKY, "FADE_TO_SKY", 0, "Sky", ""},
{MA_RAYMIR_FADETOMAT, "FADE_TO_MATERIAL", 0, "Material", ""},
{0, NULL, 0, NULL, NULL}
@@ -1237,7 +1238,7 @@ static void rna_def_material_volume(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_lighting_items[] = {
+ static const EnumPropertyItem prop_lighting_items[] = {
{MA_VOL_SHADE_SHADELESS, "SHADELESS", 0, "Shadeless", "Do not calculate lighting and shadows"},
{MA_VOL_SHADE_SHADOWED, "SHADOWED", 0, "Shadowed", ""},
{MA_VOL_SHADE_SHADED, "SHADED", 0, "Shaded", ""},
@@ -1246,7 +1247,7 @@ static void rna_def_material_volume(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_stepsize_items[] = {
+ static const EnumPropertyItem prop_stepsize_items[] = {
{MA_VOL_STEP_RANDOMIZED, "RANDOMIZED", 0, "Randomized", ""},
{MA_VOL_STEP_CONSTANT, "CONSTANT", 0, "Constant", ""},
/*{MA_VOL_STEP_ADAPTIVE, "ADAPTIVE", 0, "Adaptive", ""}, */
@@ -1594,7 +1595,7 @@ static void rna_def_material_specularity(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem prop_specular_shader_items[] = {
+ static const EnumPropertyItem prop_specular_shader_items[] = {
{MA_SPEC_COOKTORR, "COOKTORR", 0, "CookTorr", "Use a Cook-Torrance shader"},
{MA_SPEC_PHONG, "PHONG", 0, "Phong", "Use a Phong shader"},
{MA_SPEC_BLINN, "BLINN", 0, "Blinn", "Use a Blinn shader"},
@@ -1771,14 +1772,14 @@ void RNA_def_material(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{MA_TYPE_SURFACE, "SURFACE", 0, "Surface", "Render object as a surface"},
{MA_TYPE_WIRE, "WIRE", 0, "Wire", "Render the edges of faces as wires (not supported in raytracing)"},
{MA_TYPE_VOLUME, "VOLUME", 0, "Volume", "Render object as a volume"},
{MA_TYPE_HALO, "HALO", 0, "Halo", "Render object as halo particles"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem transparency_items[] = {
+ static const EnumPropertyItem transparency_items[] = {
{0, "MASK", 0, "Mask", "Mask the background"},
{MA_ZTRANSP, "Z_TRANSPARENCY", 0, "Z Transparency", "Use alpha buffer for transparent faces"},
{MA_RAYTRANSP, "RAYTRACE", 0, "Raytrace", "Use raytracing for transparent refraction rendering"},
@@ -1786,7 +1787,7 @@ void RNA_def_material(BlenderRNA *brna)
};
/* Render Preview Types */
- static EnumPropertyItem preview_type_items[] = {
+ static const EnumPropertyItem preview_type_items[] = {
{MA_FLAT, "FLAT", ICON_MATPLANE, "Flat", "Flat XY plane"},
{MA_SPHERE, "SPHERE", ICON_MATSPHERE, "Sphere", "Sphere"},
{MA_CUBE, "CUBE", ICON_MATCUBE, "Cube", "Cube"},
@@ -1796,7 +1797,7 @@ void RNA_def_material(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_shadows_only_items[] = {
+ static const EnumPropertyItem prop_shadows_only_items[] = {
{MA_SO_OLD, "SHADOW_ONLY_OLD", 0, "Shadow and Distance", "Old shadow only method"},
{MA_SO_SHADOW, "SHADOW_ONLY", 0, "Shadow Only", "Improved shadow only method"},
{MA_SO_SHADED, "SHADOW_ONLY_SHADED", 0, "Shadow and Shading",
diff --git a/source/blender/makesrna/intern/rna_mesh.c b/source/blender/makesrna/intern/rna_mesh.c
index ad5f320625c..e115485b192 100644
--- a/source/blender/makesrna/intern/rna_mesh.c
+++ b/source/blender/makesrna/intern/rna_mesh.c
@@ -46,12 +46,13 @@
#include "RNA_access.h"
#include "RNA_define.h"
#include "RNA_types.h"
+#include "RNA_enum_types.h"
#include "rna_internal.h"
#include "WM_types.h"
-EnumPropertyItem rna_enum_mesh_delimit_mode_items[] = {
+const EnumPropertyItem rna_enum_mesh_delimit_mode_items[] = {
{BMO_DELIM_NORMAL, "NORMAL", 0, "Normal", "Delimit by face directions"},
{BMO_DELIM_MATERIAL, "MATERIAL", 0, "Material", "Delimit by face material"},
{BMO_DELIM_SEAM, "SEAM", 0, "Seam", "Delimit by edge seams"},
@@ -303,7 +304,7 @@ static float rna_MeshVertex_bevel_weight_get(PointerRNA *ptr)
static void rna_MeshVertex_bevel_weight_set(PointerRNA *ptr, float value)
{
MVert *mvert = (MVert *)ptr->data;
- mvert->bweight = (char)(CLAMPIS(value * 255.0f, 0, 255));
+ mvert->bweight = round_fl_to_uchar_clamp(value * 255.0f);
}
static float rna_MEdge_bevel_weight_get(PointerRNA *ptr)
@@ -315,7 +316,7 @@ static float rna_MEdge_bevel_weight_get(PointerRNA *ptr)
static void rna_MEdge_bevel_weight_set(PointerRNA *ptr, float value)
{
MEdge *medge = (MEdge *)ptr->data;
- medge->bweight = (char)(CLAMPIS(value * 255.0f, 0, 255));
+ medge->bweight = round_fl_to_uchar_clamp(value * 255.0f);
}
static float rna_MEdge_crease_get(PointerRNA *ptr)
@@ -327,7 +328,7 @@ static float rna_MEdge_crease_get(PointerRNA *ptr)
static void rna_MEdge_crease_set(PointerRNA *ptr, float value)
{
MEdge *medge = (MEdge *)ptr->data;
- medge->crease = (char)(CLAMPIS(value * 255.0f, 0, 255));
+ medge->crease = round_fl_to_uchar_clamp(value * 255.0f);
}
static void rna_MeshLoop_normal_get(PointerRNA *ptr, float *values)
@@ -576,90 +577,100 @@ static void rna_MeshColor_color1_get(PointerRNA *ptr, float *values)
{
MCol *mcol = (MCol *)ptr->data;
- values[2] = (&mcol[0].r)[0] / 255.0f;
- values[1] = (&mcol[0].r)[1] / 255.0f;
- values[0] = (&mcol[0].r)[2] / 255.0f;
+ values[3] = mcol[0].a / 255.0f;
+ values[2] = mcol[0].r / 255.0f;
+ values[1] = mcol[0].g / 255.0f;
+ values[0] = mcol[0].b / 255.0f;
}
static void rna_MeshColor_color1_set(PointerRNA *ptr, const float *values)
{
MCol *mcol = (MCol *)ptr->data;
- (&mcol[0].r)[2] = (char)(CLAMPIS(values[0] * 255.0f, 0, 255));
- (&mcol[0].r)[1] = (char)(CLAMPIS(values[1] * 255.0f, 0, 255));
- (&mcol[0].r)[0] = (char)(CLAMPIS(values[2] * 255.0f, 0, 255));
+ mcol[0].a = round_fl_to_uchar_clamp(values[3] * 255.0f);
+ mcol[0].r = round_fl_to_uchar_clamp(values[2] * 255.0f);
+ mcol[0].g = round_fl_to_uchar_clamp(values[1] * 255.0f);
+ mcol[0].b = round_fl_to_uchar_clamp(values[0] * 255.0f);
}
static void rna_MeshColor_color2_get(PointerRNA *ptr, float *values)
{
MCol *mcol = (MCol *)ptr->data;
- values[2] = (&mcol[1].r)[0] / 255.0f;
- values[1] = (&mcol[1].r)[1] / 255.0f;
- values[0] = (&mcol[1].r)[2] / 255.0f;
+ values[3] = mcol[1].a / 255.0f;
+ values[2] = mcol[1].r / 255.0f;
+ values[1] = mcol[1].g / 255.0f;
+ values[0] = mcol[1].b / 255.0f;
}
static void rna_MeshColor_color2_set(PointerRNA *ptr, const float *values)
{
MCol *mcol = (MCol *)ptr->data;
- (&mcol[1].r)[2] = (char)(CLAMPIS(values[0] * 255.0f, 0, 255));
- (&mcol[1].r)[1] = (char)(CLAMPIS(values[1] * 255.0f, 0, 255));
- (&mcol[1].r)[0] = (char)(CLAMPIS(values[2] * 255.0f, 0, 255));
+ mcol[1].a = round_fl_to_uchar_clamp(values[3] * 255.0f);
+ mcol[1].r = round_fl_to_uchar_clamp(values[2] * 255.0f);
+ mcol[1].g = round_fl_to_uchar_clamp(values[1] * 255.0f);
+ mcol[1].b = round_fl_to_uchar_clamp(values[0] * 255.0f);
}
static void rna_MeshColor_color3_get(PointerRNA *ptr, float *values)
{
MCol *mcol = (MCol *)ptr->data;
- values[2] = (&mcol[2].r)[0] / 255.0f;
- values[1] = (&mcol[2].r)[1] / 255.0f;
- values[0] = (&mcol[2].r)[2] / 255.0f;
+ values[3] = mcol[2].a / 255.0f;
+ values[2] = mcol[2].r / 255.0f;
+ values[1] = mcol[2].g / 255.0f;
+ values[0] = mcol[2].b / 255.0f;
}
static void rna_MeshColor_color3_set(PointerRNA *ptr, const float *values)
{
MCol *mcol = (MCol *)ptr->data;
- (&mcol[2].r)[2] = (char)(CLAMPIS(values[0] * 255.0f, 0, 255));
- (&mcol[2].r)[1] = (char)(CLAMPIS(values[1] * 255.0f, 0, 255));
- (&mcol[2].r)[0] = (char)(CLAMPIS(values[2] * 255.0f, 0, 255));
+ mcol[2].a = round_fl_to_uchar_clamp(values[3] * 255.0f);
+ mcol[2].r = round_fl_to_uchar_clamp(values[2] * 255.0f);
+ mcol[2].g = round_fl_to_uchar_clamp(values[1] * 255.0f);
+ mcol[2].b = round_fl_to_uchar_clamp(values[0] * 255.0f);
}
static void rna_MeshColor_color4_get(PointerRNA *ptr, float *values)
{
MCol *mcol = (MCol *)ptr->data;
- values[2] = (&mcol[3].r)[0] / 255.0f;
- values[1] = (&mcol[3].r)[1] / 255.0f;
- values[0] = (&mcol[3].r)[2] / 255.0f;
+ values[3] = mcol[3].a / 255.0f;
+ values[2] = mcol[3].r / 255.0f;
+ values[1] = mcol[3].g / 255.0f;
+ values[0] = mcol[3].b / 255.0f;
}
static void rna_MeshColor_color4_set(PointerRNA *ptr, const float *values)
{
MCol *mcol = (MCol *)ptr->data;
- (&mcol[3].r)[2] = (char)(CLAMPIS(values[0] * 255.0f, 0, 255));
- (&mcol[3].r)[1] = (char)(CLAMPIS(values[1] * 255.0f, 0, 255));
- (&mcol[3].r)[0] = (char)(CLAMPIS(values[2] * 255.0f, 0, 255));
+ mcol[3].a = round_fl_to_uchar_clamp(values[3] * 255.0f);
+ mcol[3].r = round_fl_to_uchar_clamp(values[2] * 255.0f);
+ mcol[3].g = round_fl_to_uchar_clamp(values[1] * 255.0f);
+ mcol[3].b = round_fl_to_uchar_clamp(values[0] * 255.0f);
}
static void rna_MeshLoopColor_color_get(PointerRNA *ptr, float *values)
{
- MLoopCol *mcol = (MLoopCol *)ptr->data;
+ MLoopCol *mlcol = (MLoopCol *)ptr->data;
- values[0] = (&mcol->r)[0] / 255.0f;
- values[1] = (&mcol->r)[1] / 255.0f;
- values[2] = (&mcol->r)[2] / 255.0f;
+ values[0] = mlcol->r / 255.0f;
+ values[1] = mlcol->g / 255.0f;
+ values[2] = mlcol->b / 255.0f;
+ values[3] = mlcol->a / 255.0f;
}
static void rna_MeshLoopColor_color_set(PointerRNA *ptr, const float *values)
{
- MLoopCol *mcol = (MLoopCol *)ptr->data;
+ MLoopCol *mlcol = (MLoopCol *)ptr->data;
- (&mcol->r)[0] = (char)(CLAMPIS(values[0] * 255.0f, 0, 255));
- (&mcol->r)[1] = (char)(CLAMPIS(values[1] * 255.0f, 0, 255));
- (&mcol->r)[2] = (char)(CLAMPIS(values[2] * 255.0f, 0, 255));
+ mlcol->r = round_fl_to_uchar_clamp(values[0] * 255.0f);
+ mlcol->g = round_fl_to_uchar_clamp(values[1] * 255.0f);
+ mlcol->b = round_fl_to_uchar_clamp(values[2] * 255.0f);
+ mlcol->a = round_fl_to_uchar_clamp(values[3] * 255.0f);
}
static int rna_Mesh_texspace_editable(PointerRNA *ptr, const char **UNUSED(r_info))
@@ -1645,7 +1656,7 @@ static int rna_MeshPolygonStringPropertyLayer_data_length(PointerRNA *ptr)
return me->totpoly;
}
-/* XXX, we dont have propper byte string support yet, so for now use the (bytes + 1)
+/* XXX, we dont have proper byte string support yet, so for now use the (bytes + 1)
* bmesh API exposes correct python/bytestring access */
void rna_MeshStringProperty_s_get(PointerRNA *ptr, char *value)
{
@@ -2503,28 +2514,28 @@ static void rna_def_mcol(BlenderRNA *brna)
RNA_def_struct_path_func(srna, "rna_MeshColor_path");
prop = RNA_def_property(srna, "color1", PROP_FLOAT, PROP_COLOR);
- RNA_def_property_array(prop, 3);
+ RNA_def_property_array(prop, 4);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_funcs(prop, "rna_MeshColor_color1_get", "rna_MeshColor_color1_set", NULL);
RNA_def_property_ui_text(prop, "Color 1", "");
RNA_def_property_update(prop, 0, "rna_Mesh_update_data");
prop = RNA_def_property(srna, "color2", PROP_FLOAT, PROP_COLOR);
- RNA_def_property_array(prop, 3);
+ RNA_def_property_array(prop, 4);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_funcs(prop, "rna_MeshColor_color2_get", "rna_MeshColor_color2_set", NULL);
RNA_def_property_ui_text(prop, "Color 2", "");
RNA_def_property_update(prop, 0, "rna_Mesh_update_data");
prop = RNA_def_property(srna, "color3", PROP_FLOAT, PROP_COLOR);
- RNA_def_property_array(prop, 3);
+ RNA_def_property_array(prop, 4);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_funcs(prop, "rna_MeshColor_color3_get", "rna_MeshColor_color3_set", NULL);
RNA_def_property_ui_text(prop, "Color 3", "");
RNA_def_property_update(prop, 0, "rna_Mesh_update_data");
prop = RNA_def_property(srna, "color4", PROP_FLOAT, PROP_COLOR);
- RNA_def_property_array(prop, 3);
+ RNA_def_property_array(prop, 4);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_funcs(prop, "rna_MeshColor_color4_get", "rna_MeshColor_color4_set", NULL);
RNA_def_property_ui_text(prop, "Color 4", "");
@@ -2574,7 +2585,7 @@ static void rna_def_mloopcol(BlenderRNA *brna)
RNA_def_struct_path_func(srna, "rna_MeshColor_path");
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR);
- RNA_def_property_array(prop, 3);
+ RNA_def_property_array(prop, 4);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_funcs(prop, "rna_MeshLoopColor_color_get", "rna_MeshLoopColor_color_set", NULL);
RNA_def_property_ui_text(prop, "Color", "");
diff --git a/source/blender/makesrna/intern/rna_mesh_utils.h b/source/blender/makesrna/intern/rna_mesh_utils.h
index 0f42596ff13..93b3fd6579e 100644
--- a/source/blender/makesrna/intern/rna_mesh_utils.h
+++ b/source/blender/makesrna/intern/rna_mesh_utils.h
@@ -85,7 +85,7 @@
} \
else { \
layer = NULL; \
- } \
+ } \
return rna_pointer_inherit_refine(ptr, &RNA_##layer_rna_type, layer); \
} \
\
diff --git a/source/blender/makesrna/intern/rna_meta.c b/source/blender/makesrna/intern/rna_meta.c
index 91a65c7ccc5..1a45db1e45f 100644
--- a/source/blender/makesrna/intern/rna_meta.c
+++ b/source/blender/makesrna/intern/rna_meta.c
@@ -295,7 +295,7 @@ static void rna_def_metaball(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_update_items[] = {
+ static const EnumPropertyItem prop_update_items[] = {
{MB_UPDATE_ALWAYS, "UPDATE_ALWAYS", 0, "Always", "While editing, update metaball always"},
{MB_UPDATE_HALFRES, "HALFRES", 0, "Half", "While editing, update metaball in half resolution"},
{MB_UPDATE_FAST, "FAST", 0, "Fast", "While editing, update metaball without polygonization"},
diff --git a/source/blender/makesrna/intern/rna_meta_api.c b/source/blender/makesrna/intern/rna_meta_api.c
index 3d8f375fd88..4c3fa787b94 100644
--- a/source/blender/makesrna/intern/rna_meta_api.c
+++ b/source/blender/makesrna/intern/rna_meta_api.c
@@ -45,7 +45,7 @@
#ifdef RNA_RUNTIME
static void rna_Meta_transform(struct MetaBall *mb, float *mat)
{
- BKE_mball_transform(mb, (float (*)[4])mat);
+ BKE_mball_transform(mb, (float (*)[4])mat, true);
DAG_id_tag_update(&mb->id, 0);
}
diff --git a/source/blender/makesrna/intern/rna_modifier.c b/source/blender/makesrna/intern/rna_modifier.c
index c4f0db38a16..0ebd29b200c 100644
--- a/source/blender/makesrna/intern/rna_modifier.c
+++ b/source/blender/makesrna/intern/rna_modifier.c
@@ -34,7 +34,7 @@
#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_scene_types.h"
#include "MEM_guardedalloc.h"
@@ -62,7 +62,7 @@
#include "WM_api.h"
#include "WM_types.h"
-EnumPropertyItem rna_enum_object_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_object_modifier_type_items[] = {
{0, "", 0, N_("Modify"), ""},
{eModifierType_DataTransfer, "DATA_TRANSFER", ICON_MOD_DATA_TRANSFER, "Data Transfer", ""},
{eModifierType_MeshCache, "MESH_CACHE", ICON_MOD_MESHDEFORM, "Mesh Cache", ""},
@@ -105,6 +105,7 @@ EnumPropertyItem rna_enum_object_modifier_type_items[] = {
{eModifierType_Shrinkwrap, "SHRINKWRAP", ICON_MOD_SHRINKWRAP, "Shrinkwrap", ""},
{eModifierType_SimpleDeform, "SIMPLE_DEFORM", ICON_MOD_SIMPLEDEFORM, "Simple Deform", ""},
{eModifierType_Smooth, "SMOOTH", ICON_MOD_SMOOTH, "Smooth", ""},
+ {eModifierType_SurfaceDeform, "SURFACE_DEFORM", ICON_MOD_MESHDEFORM, "Surface Deform", ""},
{eModifierType_Warp, "WARP", ICON_MOD_WARP, "Warp", ""},
{eModifierType_Wave, "WAVE", ICON_MOD_WAVE, "Wave", ""},
{0, "", 0, N_("Simulate"), ""},
@@ -122,7 +123,7 @@ EnumPropertyItem rna_enum_object_modifier_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_modifier_triangulate_quad_method_items[] = {
+const EnumPropertyItem rna_enum_modifier_triangulate_quad_method_items[] = {
{MOD_TRIANGULATE_QUAD_BEAUTY, "BEAUTY", 0, "Beauty ", "Split the quads in nice triangles, slower method"},
{MOD_TRIANGULATE_QUAD_FIXED, "FIXED", 0, "Fixed", "Split the quads on the first and third vertices"},
{MOD_TRIANGULATE_QUAD_ALTERNATE, "FIXED_ALTERNATE", 0, "Fixed Alternate",
@@ -132,7 +133,7 @@ EnumPropertyItem rna_enum_modifier_triangulate_quad_method_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_modifier_triangulate_ngon_method_items[] = {
+const EnumPropertyItem rna_enum_modifier_triangulate_ngon_method_items[] = {
{MOD_TRIANGULATE_NGON_BEAUTY, "BEAUTY", 0, "Beauty", "Arrange the new triangles evenly (slow)"},
{MOD_TRIANGULATE_NGON_EARCLIP, "CLIP", 0, "Clip", "Split the polygons with an ear clipping algorithm"},
{0, NULL, 0, NULL, NULL}
@@ -140,7 +141,7 @@ EnumPropertyItem rna_enum_modifier_triangulate_ngon_method_items[] = {
#ifndef RNA_RUNTIME
/* use eWarp_Falloff_*** & eHook_Falloff_***, they're in sync */
-static EnumPropertyItem modifier_warp_falloff_items[] = {
+static const EnumPropertyItem modifier_warp_falloff_items[] = {
{eWarp_Falloff_None, "NONE", 0, "No Falloff", ""},
{eWarp_Falloff_Curve, "CURVE", 0, "Curve", ""},
{eWarp_Falloff_Smooth, "SMOOTH", ICON_SMOOTHCURVE, "Smooth", ""},
@@ -156,7 +157,7 @@ static EnumPropertyItem modifier_warp_falloff_items[] = {
/* ***** Data Transfer ***** */
-EnumPropertyItem rna_enum_dt_method_vertex_items[] = {
+const EnumPropertyItem rna_enum_dt_method_vertex_items[] = {
{MREMAP_MODE_TOPOLOGY, "TOPOLOGY", 0, "Topology",
"Copy from identical topology meshes"},
{MREMAP_MODE_VERT_NEAREST, "NEAREST", 0, "Nearest vertex",
@@ -174,7 +175,7 @@ EnumPropertyItem rna_enum_dt_method_vertex_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_method_edge_items[] = {
+const EnumPropertyItem rna_enum_dt_method_edge_items[] = {
{MREMAP_MODE_TOPOLOGY, "TOPOLOGY", 0, "Topology",
"Copy from identical topology meshes"},
{MREMAP_MODE_EDGE_VERT_NEAREST, "VERT_NEAREST", 0, "Nearest Vertices",
@@ -188,7 +189,7 @@ EnumPropertyItem rna_enum_dt_method_edge_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_method_loop_items[] = {
+const EnumPropertyItem rna_enum_dt_method_loop_items[] = {
{MREMAP_MODE_TOPOLOGY, "TOPOLOGY", 0, "Topology",
"Copy from identical topology meshes"},
{MREMAP_MODE_LOOP_NEAREST_LOOPNOR, "NEAREST_NORMAL", 0, "Nearest Corner And Best Matching Normal",
@@ -204,7 +205,7 @@ EnumPropertyItem rna_enum_dt_method_loop_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_method_poly_items[] = {
+const EnumPropertyItem rna_enum_dt_method_poly_items[] = {
{MREMAP_MODE_TOPOLOGY, "TOPOLOGY", 0, "Topology",
"Copy from identical topology meshes"},
{MREMAP_MODE_POLY_NEAREST, "NEAREST", 0, "Nearest Face",
@@ -216,7 +217,7 @@ EnumPropertyItem rna_enum_dt_method_poly_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_mix_mode_items[] = {
+const EnumPropertyItem rna_enum_dt_mix_mode_items[] = {
{CDT_MIX_TRANSFER, "REPLACE", 0, "Replace",
"Overwrite all elements' data"},
{CDT_MIX_REPLACE_ABOVE_THRESHOLD, "ABOVE_THRESHOLD", 0, "Above Threshold",
@@ -235,7 +236,7 @@ EnumPropertyItem rna_enum_dt_mix_mode_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_layers_select_src_items[] = {
+const EnumPropertyItem rna_enum_dt_layers_select_src_items[] = {
{DT_LAYERS_ACTIVE_SRC, "ACTIVE", 0, "Active Layer",
"Only transfer active data layer"},
{DT_LAYERS_ALL_SRC, "ALL", 0, "All Layers",
@@ -247,7 +248,7 @@ EnumPropertyItem rna_enum_dt_layers_select_src_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_dt_layers_select_dst_items[] = {
+const EnumPropertyItem rna_enum_dt_layers_select_dst_items[] = {
{DT_LAYERS_ACTIVE_DST, "ACTIVE", 0, "Active Layer",
"Affect active data layer of all targets"},
{DT_LAYERS_NAME_DST, "NAME", 0, "By Name",
@@ -257,20 +258,20 @@ EnumPropertyItem rna_enum_dt_layers_select_dst_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_axis_xy_items[] = {
+const EnumPropertyItem rna_enum_axis_xy_items[] = {
{0, "X", 0, "X", ""},
{1, "Y", 0, "Y", ""},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_axis_xyz_items[] = {
+const EnumPropertyItem rna_enum_axis_xyz_items[] = {
{0, "X", 0, "X", ""},
{1, "Y", 0, "Y", ""},
{2, "Z", 0, "Z", ""},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_axis_flag_xyz_items[] = {
+const EnumPropertyItem rna_enum_axis_flag_xyz_items[] = {
{(1 << 0), "X", 0, "X", ""},
{(1 << 1), "Y", 0, "Y", ""},
{(1 << 2), "Z", 0, "Z", ""},
@@ -408,6 +409,8 @@ static StructRNA *rna_Modifier_refine(struct PointerRNA *ptr)
return &RNA_CorrectiveSmoothModifier;
case eModifierType_MeshSequenceCache:
return &RNA_MeshSequenceCacheModifier;
+ case eModifierType_SurfaceDeform:
+ return &RNA_SurfaceDeformModifier;
/* Default */
case eModifierType_None:
case eModifierType_ShapeKey:
@@ -573,6 +576,7 @@ RNA_MOD_OBJECT_SET(MeshDeform, object, OB_MESH);
RNA_MOD_OBJECT_SET(NormalEdit, target, OB_EMPTY);
RNA_MOD_OBJECT_SET(Shrinkwrap, target, OB_MESH);
RNA_MOD_OBJECT_SET(Shrinkwrap, auxTarget, OB_MESH);
+RNA_MOD_OBJECT_SET(SurfaceDeform, target, OB_MESH);
static void rna_HookModifier_object_set(PointerRNA *ptr, PointerRNA value)
{
@@ -885,7 +889,7 @@ static void rna_DataTransferModifier_polys_data_types_set(struct PointerRNA *ptr
dtmd->data_types |= value;
}
-static EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
{
DataTransferModifierData *dtmd = (DataTransferModifierData *)ptr->data;
EnumPropertyItem *item = NULL, tmp_item = {0};
@@ -977,7 +981,7 @@ static EnumPropertyItem *rna_DataTransferModifier_layers_select_src_itemf(bConte
return item;
}
-static EnumPropertyItem *rna_DataTransferModifier_layers_select_dst_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *rna_DataTransferModifier_layers_select_dst_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
{
DataTransferModifierData *dtmd = (DataTransferModifierData *)ptr->data;
EnumPropertyItem *item = NULL, tmp_item = {0};
@@ -1069,7 +1073,7 @@ static EnumPropertyItem *rna_DataTransferModifier_layers_select_dst_itemf(bConte
return item;
}
-static EnumPropertyItem *rna_DataTransferModifier_mix_mode_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rna_DataTransferModifier_mix_mode_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
DataTransferModifierData *dtmd = (DataTransferModifierData *)ptr->data;
EnumPropertyItem *item = NULL;
@@ -1131,6 +1135,11 @@ static int rna_CorrectiveSmoothModifier_is_bind_get(PointerRNA *ptr)
return (csmd->bind_coords != NULL);
}
+static int rna_SurfaceDeformModifier_is_bound_get(PointerRNA *ptr)
+{
+ return (((SurfaceDeformModifierData *)ptr->data)->verts != NULL);
+}
+
static void rna_MeshSequenceCache_object_path_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
#ifdef WITH_ALEMBIC
@@ -1146,11 +1155,48 @@ static void rna_MeshSequenceCache_object_path_update(Main *bmain, Scene *scene,
rna_Modifier_update(bmain, scene, ptr);
}
+static int rna_ParticleInstanceModifier_particle_system_poll(PointerRNA *ptr, const PointerRNA value)
+{
+ ParticleInstanceModifierData *psmd = ptr->data;
+ ParticleSystem *psys = value.data;
+
+ if (!psmd->ob)
+ return false;
+
+ /* make sure psys is in the object */
+ return BLI_findindex(&psmd->ob->particlesystem, psys) >= 0;
+}
+
+static PointerRNA rna_ParticleInstanceModifier_particle_system_get(PointerRNA *ptr)
+{
+ ParticleInstanceModifierData *psmd = ptr->data;
+ ParticleSystem *psys;
+ PointerRNA rptr;
+
+ if (!psmd->ob)
+ return PointerRNA_NULL;
+
+ psys = BLI_findlink(&psmd->ob->particlesystem, psmd->psys - 1);
+ RNA_pointer_create((ID *)psmd->ob, &RNA_ParticleSystem, psys, &rptr);
+ return rptr;
+}
+
+static void rna_ParticleInstanceModifier_particle_system_set(PointerRNA *ptr, const PointerRNA value)
+{
+ ParticleInstanceModifierData *psmd = ptr->data;
+
+ if (!psmd->ob)
+ return;
+
+ psmd->psys = BLI_findindex(&psmd->ob->particlesystem, value.data) + 1;
+ CLAMP_MIN(psmd->psys, 1);
+}
+
#else
static PropertyRNA *rna_def_property_subdivision_common(StructRNA *srna, const char type[])
{
- static EnumPropertyItem prop_subdivision_type_items[] = {
+ static const EnumPropertyItem prop_subdivision_type_items[] = {
{0, "CATMULL_CLARK", 0, "Catmull-Clark", ""},
{1, "SIMPLE", 0, "Simple", ""},
{0, NULL, 0, NULL, NULL}
@@ -1211,7 +1257,7 @@ static void rna_def_modifier_subsurf(BlenderRNA *brna)
static void rna_def_modifier_generic_map_info(StructRNA *srna)
{
- static EnumPropertyItem prop_texture_coordinates_items[] = {
+ static const EnumPropertyItem prop_texture_coordinates_items[] = {
{MOD_DISP_MAP_LOCAL, "LOCAL", 0, "Local", "Use the local coordinate system for the texture coordinates"},
{MOD_DISP_MAP_GLOBAL, "GLOBAL", 0, "Global", "Use the global coordinate system for the texture coordinates"},
{MOD_DISP_MAP_OBJECT, "OBJECT", 0, "Object",
@@ -1394,7 +1440,7 @@ static void rna_def_modifier_curve(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_deform_axis_items[] = {
+ static const EnumPropertyItem prop_deform_axis_items[] = {
{MOD_CURVE_POSX, "POS_X", 0, "X", ""},
{MOD_CURVE_POSY, "POS_Y", 0, "Y", ""},
{MOD_CURVE_POSZ, "POS_Z", 0, "Z", ""},
@@ -1509,12 +1555,40 @@ static void rna_def_modifier_mirror(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_mirror_u", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_MIR_MIRROR_U);
- RNA_def_property_ui_text(prop, "Mirror U", "Mirror the U texture coordinate around the 0.5 point");
+ RNA_def_property_ui_text(prop, "Mirror U", "Mirror the U texture coordinate around the flip offset point");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
prop = RNA_def_property(srna, "use_mirror_v", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_MIR_MIRROR_V);
- RNA_def_property_ui_text(prop, "Mirror V", "Mirror the V texture coordinate around the 0.5 point");
+ RNA_def_property_ui_text(prop, "Mirror V", "Mirror the V texture coordinate around the flip offset point");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "mirror_offset_u", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset[0]");
+ RNA_def_property_range(prop, -1, 1);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "Flip U Offset", "Amount to offset mirrored UVs flipping point from the 0.5 on the U axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "mirror_offset_v", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset[1]");
+ RNA_def_property_range(prop, -1, 1);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "Flip V Offset", "Amount to offset mirrored UVs flipping point from the 0.5 point on the V axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "offset_u", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset_copy[0]");
+ RNA_def_property_range(prop, -10000.0f, 10000.0f);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "U Offset", "Mirrored UV offset on the U axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "offset_v", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset_copy[1]");
+ RNA_def_property_range(prop, -10000.0f, 10000.0f);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "V Offset", "Mirrored UV offset on the V axis");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
prop = RNA_def_property(srna, "merge_threshold", PROP_FLOAT, PROP_DISTANCE);
@@ -1533,7 +1607,7 @@ static void rna_def_modifier_mirror(BlenderRNA *brna)
static void rna_def_modifier_decimate(BlenderRNA *brna)
{
- static EnumPropertyItem modifier_decim_mode_items[] = {
+ static const EnumPropertyItem modifier_decim_mode_items[] = {
{MOD_DECIM_MODE_COLLAPSE, "COLLAPSE", 0, "Collapse", "Use edge collapsing"},
{MOD_DECIM_MODE_UNSUBDIV, "UNSUBDIV", 0, "Un-Subdivide", "Use un-subdivide face reduction"},
{MOD_DECIM_MODE_DISSOLVE, "DISSOLVE", 0, "Planar", "Dissolve geometry to form planar polygons"},
@@ -1913,7 +1987,7 @@ static void rna_def_modifier_boolean(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_operation_items[] = {
+ static const EnumPropertyItem prop_operation_items[] = {
{eBooleanModifierOp_Intersect, "INTERSECT", 0, "Intersect",
"Keep the part of the mesh that intersects with the other selected object"},
{eBooleanModifierOp_Union, "UNION", 0, "Union", "Combine two meshes in an additive way"},
@@ -1921,12 +1995,6 @@ static void rna_def_modifier_boolean(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_solver_items[] = {
- {eBooleanModifierSolver_BMesh, "BMESH", 0, "BMesh", "Use the BMesh boolean solver"},
- {eBooleanModifierSolver_Carve, "CARVE", 0, "Carve", "Use the Carve boolean solver"},
- {0, NULL, 0, NULL, NULL}
- };
-
srna = RNA_def_struct(brna, "BooleanModifier", "Modifier");
RNA_def_struct_ui_text(srna, "Boolean Modifier", "Boolean operations modifier");
RNA_def_struct_sdna(srna, "BooleanModifierData");
@@ -1943,17 +2011,29 @@ static void rna_def_modifier_boolean(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Operation", "");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
- prop = RNA_def_property(srna, "solver", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_items(prop, prop_solver_items);
- RNA_def_property_ui_text(prop, "Solver", "");
- RNA_def_property_update(prop, 0, "rna_Modifier_update");
-
prop = RNA_def_property(srna, "double_threshold", PROP_FLOAT, PROP_DISTANCE);
RNA_def_property_float_sdna(prop, NULL, "double_threshold");
RNA_def_property_range(prop, 0, 1.0f);
- RNA_def_property_ui_range(prop, 0, 1, 0.0001, 7);
+ RNA_def_property_ui_range(prop, 0, 1, 0.0001, 6);
RNA_def_property_ui_text(prop, "Overlap Threshold", "Threshold for checking overlapping geometry");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ /* BMesh debugging options, only used when G_DEBUG is set */
+
+ /* BMesh intersection options */
+ static const EnumPropertyItem debug_items[] = {
+ {eBooleanModifierBMeshFlag_BMesh_Separate, "SEPARATE", 0, "Separate", ""},
+ {eBooleanModifierBMeshFlag_BMesh_NoDissolve, "NO_DISSOLVE", 0, "No Dissolve", ""},
+ {eBooleanModifierBMeshFlag_BMesh_NoConnectRegions, "NO_CONNECT_REGIONS", 0, "No Connect Regions", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ prop = RNA_def_property(srna, "debug_options", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_items(prop, debug_items);
+ RNA_def_property_enum_sdna(prop, NULL, "bm_flag");
+ RNA_def_property_flag(prop, PROP_ENUM_FLAG);
+ RNA_def_property_ui_text(prop, "Debug", "Debugging options, only when started with '-d'");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
}
static void rna_def_modifier_array(BlenderRNA *brna)
@@ -1961,7 +2041,7 @@ static void rna_def_modifier_array(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_fit_type_items[] = {
+ static const EnumPropertyItem prop_fit_type_items[] = {
{MOD_ARR_FIXEDCOUNT, "FIXED_COUNT", 0, "Fixed Count", "Duplicate the object a certain number of times"},
{MOD_ARR_FITLENGTH, "FIT_LENGTH", 0, "Fit Length",
"Duplicate the object as many times as fits in a certain length"},
@@ -2068,6 +2148,20 @@ static void rna_def_modifier_array(BlenderRNA *brna)
RNA_def_property_pointer_funcs(prop, NULL, "rna_ArrayModifier_end_cap_set", NULL, "rna_Mesh_object_poll");
RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_SELF_CHECK);
RNA_def_property_update(prop, 0, "rna_Modifier_dependency_update");
+
+ prop = RNA_def_property(srna, "offset_u", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset[0]");
+ RNA_def_property_range(prop, -1, 1);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "U Offset", "Amount to offset array UVs on the U axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "offset_v", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "uv_offset[1]");
+ RNA_def_property_range(prop, -1, 1);
+ RNA_def_property_ui_range(prop, -1, 1, 2, 4);
+ RNA_def_property_ui_text(prop, "V Offset", "Amount to offset array UVs on the V axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
}
static void rna_def_modifier_edgesplit(BlenderRNA *brna)
@@ -2102,7 +2196,7 @@ static void rna_def_modifier_displace(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_direction_items[] = {
+ static const EnumPropertyItem prop_direction_items[] = {
{MOD_DISP_DIR_X, "X", 0, "X", "Use the texture's intensity value to displace in the X direction"},
{MOD_DISP_DIR_Y, "Y", 0, "Y", "Use the texture's intensity value to displace in the Y direction"},
{MOD_DISP_DIR_Z, "Z", 0, "Z", "Use the texture's intensity value to displace in the Z direction"},
@@ -2115,7 +2209,7 @@ static void rna_def_modifier_displace(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_space_items[] = {
+ static const EnumPropertyItem prop_space_items[] = {
{MOD_DISP_SPACE_LOCAL, "LOCAL", 0, "Local", "Direction is defined in local coordinates"},
{MOD_DISP_SPACE_GLOBAL, "GLOBAL", 0, "Global", "Direction is defined in global coordinates"},
{0, NULL, 0, NULL, NULL}
@@ -2293,7 +2387,7 @@ static void rna_def_modifier_correctivesmooth(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem modifier_smooth_type_items[] = {
+ static const EnumPropertyItem modifier_smooth_type_items[] = {
{MOD_CORRECTIVESMOOTH_SMOOTH_SIMPLE, "SIMPLE", 0, "Simple",
"Use the average of adjacent edge-vertices"},
{MOD_CORRECTIVESMOOTH_SMOOTH_LENGTH_WEIGHT, "LENGTH_WEIGHTED", 0, "Length Weight",
@@ -2301,7 +2395,7 @@ static void rna_def_modifier_correctivesmooth(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem modifier_rest_source_items[] = {
+ static const EnumPropertyItem modifier_rest_source_items[] = {
{MOD_CORRECTIVESMOOTH_RESTSOURCE_ORCO, "ORCO", 0, "Original Coords",
"Use base mesh vert coords as the rest position"},
{MOD_CORRECTIVESMOOTH_RESTSOURCE_BIND, "BIND", 0, "Bind Coords",
@@ -2439,7 +2533,7 @@ static void rna_def_modifier_cast(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_cast_type_items[] = {
+ static const EnumPropertyItem prop_cast_type_items[] = {
{MOD_CAST_TYPE_SPHERE, "SPHERE", 0, "Sphere", ""},
{MOD_CAST_TYPE_CYLINDER, "CYLINDER", 0, "Cylinder", ""},
{MOD_CAST_TYPE_CUBOID, "CUBOID", 0, "Cuboid", ""},
@@ -2522,7 +2616,7 @@ static void rna_def_modifier_meshdeform(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
#if 0
- static EnumPropertyItem prop_mode_items[] = {
+ static const EnumPropertyItem prop_mode_items[] = {
{0, "VOLUME", 0, "Volume", "Bind to volume inside cage mesh"},
{1, "SURFACE", 0, "Surface", "Bind to surface of cage mesh"},
{0, NULL, 0, NULL, NULL}
@@ -2598,6 +2692,12 @@ static void rna_def_modifier_particleinstance(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
+ static EnumPropertyItem particleinstance_space[] = {
+ {eParticleInstanceSpace_Local, "LOCAL", 0, "Local", "Use offset from the particle object in the instance object"},
+ {eParticleInstanceSpace_World, "WORLD", 0, "World", "Use world space offset in the instance object"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
srna = RNA_def_struct(brna, "ParticleInstanceModifier", "Modifier");
RNA_def_struct_ui_text(srna, "ParticleInstance Modifier", "Particle system instancing modifier");
RNA_def_struct_sdna(srna, "ParticleInstanceModifierData");
@@ -2612,16 +2712,30 @@ static void rna_def_modifier_particleinstance(BlenderRNA *brna)
prop = RNA_def_property(srna, "particle_system_index", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "psys");
- RNA_def_property_range(prop, 1, 10);
+ RNA_def_property_range(prop, 1, SHRT_MAX);
RNA_def_property_ui_text(prop, "Particle System Number", "");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ prop = RNA_def_property(srna, "particle_system", PROP_POINTER, PROP_NONE);
+ RNA_def_property_struct_type(prop, "ParticleSystem");
+ RNA_def_property_pointer_funcs(prop, "rna_ParticleInstanceModifier_particle_system_get", "rna_ParticleInstanceModifier_particle_system_set",
+ NULL, "rna_ParticleInstanceModifier_particle_system_poll");
+ RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Particle System", "");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
prop = RNA_def_property(srna, "axis", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "axis");
RNA_def_property_enum_items(prop, rna_enum_axis_xyz_items);
RNA_def_property_ui_text(prop, "Axis", "Pole axis for rotation");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
-
+
+ prop = RNA_def_property(srna, "space", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "space");
+ RNA_def_property_enum_items(prop, particleinstance_space);
+ RNA_def_property_ui_text(prop, "Space", "Space to use for copying mesh data");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
prop = RNA_def_property(srna, "use_normal", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", eParticleInstanceFlag_Parents);
RNA_def_property_ui_text(prop, "Normal", "Create instances from normal particles");
@@ -2673,6 +2787,40 @@ static void rna_def_modifier_particleinstance(BlenderRNA *brna)
RNA_def_property_range(prop, 0.0, 1.0);
RNA_def_property_ui_text(prop, "Random Position", "Randomize position along path");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "rotation", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "rotation");
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_text(prop, "Rotation", "Rotation around path");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "random_rotation", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_float_sdna(prop, NULL, "random_rotation");
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_text(prop, "Random Rotation", "Randomize rotation around path");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "particle_amount", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_text(prop, "Particle Amount", "Amount of particles to use for instancing");
+ RNA_def_property_float_default(prop, 1.0f);
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "particle_offset", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_text(prop, "Particle Offset", "Relative offset of particles to use for instancing, to avoid overlap of multiple instances");
+ RNA_def_property_float_default(prop, 0.0f);
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "index_layer_name", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "index_layer_name");
+ RNA_def_property_ui_text(prop, "Index Layer Name", "Custom data layer name for the index");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "value_layer_name", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "value_layer_name");
+ RNA_def_property_ui_text(prop, "Value Layer Name", "Custom data layer name for the randomized value");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
}
static void rna_def_modifier_explode(BlenderRNA *brna)
@@ -2777,7 +2925,7 @@ static void rna_def_modifier_smoke(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_smoke_type_items[] = {
+ static const EnumPropertyItem prop_smoke_type_items[] = {
{0, "NONE", 0, "None", ""},
{MOD_SMOKE_TYPE_DOMAIN, "DOMAIN", 0, "Domain", ""},
{MOD_SMOKE_TYPE_FLOW, "FLOW", 0, "Flow", "Inflow/Outflow"},
@@ -2858,7 +3006,7 @@ static void rna_def_modifier_bevel(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_limit_method_items[] = {
+ static const EnumPropertyItem prop_limit_method_items[] = {
{0, "NONE", 0, "None", "Bevel the entire mesh by a constant amount"},
{MOD_BEVEL_ANGLE, "ANGLE", 0, "Angle", "Only bevel edges with sharp enough angles between faces"},
{MOD_BEVEL_WEIGHT, "WEIGHT", 0, "Weight",
@@ -2868,7 +3016,7 @@ static void rna_def_modifier_bevel(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_val_type_items[] = {
+ static const EnumPropertyItem prop_val_type_items[] = {
{MOD_BEVEL_AMT_OFFSET, "OFFSET", 0, "Offset", "Amount is offset of new edges from original"},
{MOD_BEVEL_AMT_WIDTH, "WIDTH", 0, "Width", "Amount is width of new face"},
{MOD_BEVEL_AMT_DEPTH, "DEPTH", 0, "Depth", "Amount is perpendicular distance from original edge to bevel face"},
@@ -2877,7 +3025,7 @@ static void rna_def_modifier_bevel(BlenderRNA *brna)
};
/* TO BE DEPRECATED */
- static EnumPropertyItem prop_edge_weight_method_items[] = {
+ static const EnumPropertyItem prop_edge_weight_method_items[] = {
{0, "AVERAGE", 0, "Average", ""},
{MOD_BEVEL_EMIN, "SHARPEST", 0, "Sharpest", ""},
{MOD_BEVEL_EMAX, "LARGEST", 0, "Largest", ""},
@@ -2946,7 +3094,7 @@ static void rna_def_modifier_bevel(BlenderRNA *brna)
prop = RNA_def_property(srna, "profile", PROP_FLOAT, PROP_FACTOR);
RNA_def_property_range(prop, 0.0f, 1.0f);
- RNA_def_property_ui_range(prop, 0.15f, 1.0f, 0.05, 2);
+ RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.05, 2);
RNA_def_property_ui_text(prop, "Profile", "The profile shape (0.5 = round)");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
@@ -2967,7 +3115,7 @@ static void rna_def_modifier_shrinkwrap(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem shrink_type_items[] = {
+ static const EnumPropertyItem shrink_type_items[] = {
{MOD_SHRINKWRAP_NEAREST_SURFACE, "NEAREST_SURFACEPOINT", 0, "Nearest Surface Point",
"Shrink the mesh to the nearest target surface"},
{MOD_SHRINKWRAP_PROJECT, "PROJECT", 0, "Project",
@@ -2977,7 +3125,7 @@ static void rna_def_modifier_shrinkwrap(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem shrink_face_cull_items[] = {
+ static const EnumPropertyItem shrink_face_cull_items[] = {
{0, "OFF", 0, "Off", "No culling"},
{MOD_SHRINKWRAP_CULL_TARGET_FRONTFACE, "FRONT", 0, "Front", "No projection when in front of the face"},
{MOD_SHRINKWRAP_CULL_TARGET_BACKFACE, "BACK", 0, "Back", "No projection when behind the face"},
@@ -3104,7 +3252,7 @@ static void rna_def_modifier_mask(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem modifier_mask_mode_items[] = {
+ static const EnumPropertyItem modifier_mask_mode_items[] = {
{MOD_MASK_MODE_VGROUP, "VERTEX_GROUP", 0, "Vertex Group", ""},
{MOD_MASK_MODE_ARM, "ARMATURE", 0, "Armature", ""},
{0, NULL, 0, NULL, NULL}
@@ -3144,7 +3292,7 @@ static void rna_def_modifier_simpledeform(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem simple_deform_mode_items[] = {
+ static const EnumPropertyItem simple_deform_mode_items[] = {
{MOD_SIMPLEDEFORM_MODE_TWIST, "TWIST", 0, "Twist", "Rotate around the Z axis of the modifier space"},
{MOD_SIMPLEDEFORM_MODE_BEND, "BEND", 0, "Bend", "Bend the mesh over the Z axis of the modifier space"},
{MOD_SIMPLEDEFORM_MODE_TAPER, "TAPER", 0, "Taper", "Linearly scale along Z axis of the modifier space"},
@@ -3171,6 +3319,11 @@ static void rna_def_modifier_simpledeform(BlenderRNA *brna)
RNA_def_property_string_funcs(prop, NULL, NULL, "rna_SimpleDeformModifier_vgroup_name_set");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ prop = RNA_def_property(srna, "deform_axis", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_items(prop, rna_enum_axis_xyz_items);
+ RNA_def_property_ui_text(prop, "Axis", "Deform around local axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
prop = RNA_def_property(srna, "origin", PROP_POINTER, PROP_NONE);
RNA_def_property_ui_text(prop, "Origin", "Offset the origin and orientation of the deformation");
RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_SELF_CHECK);
@@ -3200,12 +3353,17 @@ static void rna_def_modifier_simpledeform(BlenderRNA *brna)
prop = RNA_def_property(srna, "lock_x", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "axis", MOD_SIMPLEDEFORM_LOCK_AXIS_X);
- RNA_def_property_ui_text(prop, "Lock X Axis", "Do not allow deformation along the X axis");
+ RNA_def_property_ui_text(prop, "X", "Do not allow deformation along the X axis");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
prop = RNA_def_property(srna, "lock_y", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "axis", MOD_SIMPLEDEFORM_LOCK_AXIS_Y);
- RNA_def_property_ui_text(prop, "Lock Y Axis", "Do not allow deformation along the Y axis");
+ RNA_def_property_ui_text(prop, "Y", "Do not allow deformation along the Y axis");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "lock_z", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "axis", MOD_SIMPLEDEFORM_LOCK_AXIS_Z);
+ RNA_def_property_ui_text(prop, "Z", "Do not allow deformation along the Z axis");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
prop = RNA_def_property(srna, "invert_vertex_group", PROP_BOOLEAN, PROP_NONE);
@@ -3390,6 +3548,13 @@ static void rna_def_modifier_screw(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Screw", "Offset the revolution along its axis");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ prop = RNA_def_property(srna, "merge_threshold", PROP_FLOAT, PROP_DISTANCE);
+ RNA_def_property_float_sdna(prop, NULL, "merge_dist");
+ RNA_def_property_range(prop, 0, FLT_MAX);
+ RNA_def_property_ui_range(prop, 0, 1, 1, 4);
+ RNA_def_property_ui_text(prop, "Merge Distance", "Limit below which to merge vertices");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
prop = RNA_def_property(srna, "use_normal_flip", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_SCREW_NORMAL_FLIP);
RNA_def_property_ui_text(prop, "Flip", "Flip normals of lathed faces");
@@ -3405,6 +3570,12 @@ static void rna_def_modifier_screw(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Object Screw", "Use the distance between the objects to make a screw");
RNA_def_property_update(prop, 0, "rna_Modifier_update");
+ /* Vertex merging parameters */
+ prop = RNA_def_property(srna, "use_merge_vertices", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_SCREW_MERGE);
+ RNA_def_property_ui_text(prop, "Merge Vertices", "Merge adjacent vertices (screw offset must be zero)");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
prop = RNA_def_property(srna, "use_smooth_shade", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", MOD_SCREW_SMOOTH_SHADING);
RNA_def_property_ui_text(prop, "Smooth Shading", "Output faces with smooth shading rather than flat shaded");
@@ -3493,7 +3664,7 @@ static void rna_def_modifier_uvwarp(BlenderRNA *brna)
static void rna_def_modifier_weightvg_mask(BlenderRNA *UNUSED(brna), StructRNA *srna,
const char *mask_vgroup_setter, const char *mask_uvlayer_setter)
{
- static EnumPropertyItem weightvg_mask_tex_map_items[] = {
+ static const EnumPropertyItem weightvg_mask_tex_map_items[] = {
{MOD_DISP_MAP_LOCAL, "LOCAL", 0, "Local", "Use local generated coordinates"},
{MOD_DISP_MAP_GLOBAL, "GLOBAL", 0, "Global", "Use global coordinates"},
{MOD_DISP_MAP_OBJECT, "OBJECT", 0, "Object", "Use local generated coordinates of another object"},
@@ -3501,7 +3672,7 @@ static void rna_def_modifier_weightvg_mask(BlenderRNA *UNUSED(brna), StructRNA *
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem weightvg_mask_tex_used_items[] = {
+ static const EnumPropertyItem weightvg_mask_tex_used_items[] = {
{MOD_WVG_MASK_TEX_USE_INT, "INT", 0, "Intensity", ""},
{MOD_WVG_MASK_TEX_USE_RED, "RED", 0, "Red", ""},
{MOD_WVG_MASK_TEX_USE_GREEN, "GREEN", 0, "Green", ""},
@@ -3559,7 +3730,7 @@ static void rna_def_modifier_weightvg_mask(BlenderRNA *UNUSED(brna), StructRNA *
static void rna_def_modifier_weightvgedit(BlenderRNA *brna)
{
- static EnumPropertyItem weightvg_edit_falloff_type_items[] = {
+ static const EnumPropertyItem weightvg_edit_falloff_type_items[] = {
{MOD_WVG_MAPPING_NONE, "LINEAR", ICON_LINCURVE, "Linear", "Null action"},
{MOD_WVG_MAPPING_CURVE, "CURVE", ICON_RNDCURVE, "Custom Curve", ""},
{MOD_WVG_MAPPING_SHARP, "SHARP", ICON_SHARPCURVE, "Sharp", ""},
@@ -3640,7 +3811,7 @@ static void rna_def_modifier_weightvgedit(BlenderRNA *brna)
static void rna_def_modifier_weightvgmix(BlenderRNA *brna)
{
- static EnumPropertyItem weightvg_mix_modes_items[] = {
+ static const EnumPropertyItem weightvg_mix_modes_items[] = {
{MOD_WVG_MIX_SET, "SET", 0, "Replace", "Replace VGroup A's weights by VGroup B's ones"},
{MOD_WVG_MIX_ADD, "ADD", 0, "Add", "Add VGroup B's weights to VGroup A's ones"},
{MOD_WVG_MIX_SUB, "SUB", 0, "Subtract", "Subtract VGroup B's weights from VGroup A's ones"},
@@ -3651,7 +3822,7 @@ static void rna_def_modifier_weightvgmix(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem weightvg_mix_set_items[] = {
+ static const EnumPropertyItem weightvg_mix_set_items[] = {
{MOD_WVG_SET_ALL, "ALL", 0, "All", "Affect all vertices (might add some to VGroup A)"},
{MOD_WVG_SET_A, "A", 0, "VGroup A", "Affect vertices in VGroup A"},
{MOD_WVG_SET_B, "B", 0, "VGroup B", "Affect vertices in VGroup B (might add some to VGroup A)"},
@@ -3714,7 +3885,7 @@ static void rna_def_modifier_weightvgmix(BlenderRNA *brna)
static void rna_def_modifier_weightvgproximity(BlenderRNA *brna)
{
- static EnumPropertyItem weightvg_proximity_modes_items[] = {
+ static const EnumPropertyItem weightvg_proximity_modes_items[] = {
{MOD_WVG_PROXIMITY_OBJECT, "OBJECT", 0, "Object",
"Use distance between affected and target objects"},
{MOD_WVG_PROXIMITY_GEOMETRY, "GEOMETRY", 0, "Geometry",
@@ -3723,14 +3894,14 @@ static void rna_def_modifier_weightvgproximity(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem proximity_geometry_items[] = {
+ static const EnumPropertyItem proximity_geometry_items[] = {
{MOD_WVG_PROXIMITY_GEOM_VERTS, "VERTEX", 0, "Vertex", "Compute distance to nearest vertex"},
{MOD_WVG_PROXIMITY_GEOM_EDGES, "EDGE", 0, "Edge", "Compute distance to nearest edge"},
{MOD_WVG_PROXIMITY_GEOM_FACES, "FACE", 0, "Face", "Compute distance to nearest face"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem weightvg_proximity_falloff_type_items[] = {
+ static const EnumPropertyItem weightvg_proximity_falloff_type_items[] = {
{MOD_WVG_MAPPING_NONE, "LINEAR", ICON_LINCURVE, "Linear", "Null action"},
/* No curve mapping here! */
{MOD_WVG_MAPPING_SHARP, "SHARP", ICON_SHARPCURVE, "Sharp", ""},
@@ -3806,7 +3977,7 @@ static void rna_def_modifier_weightvgproximity(BlenderRNA *brna)
static void rna_def_modifier_remesh(BlenderRNA *brna)
{
- static EnumPropertyItem mode_items[] = {
+ static const EnumPropertyItem mode_items[] = {
{MOD_REMESH_CENTROID, "BLOCKS", 0, "Blocks", "Output a blocky surface with no smoothing"},
{MOD_REMESH_MASS_POINT, "SMOOTH", 0, "Smooth", "Output a smooth surface with no sharp-features detection"},
{MOD_REMESH_SHARP_FEATURES, "SHARP", 0, "Sharp",
@@ -3873,7 +4044,7 @@ static void rna_def_modifier_ocean(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem geometry_items[] = {
+ static const EnumPropertyItem geometry_items[] = {
{MOD_OCEAN_GEOM_GENERATE, "GENERATE", 0, "Generate",
"Generate ocean surface geometry at the specified resolution"},
{MOD_OCEAN_GEOM_DISPLACE, "DISPLACE", 0, "Displace", "Displace existing geometry according to simulation"},
@@ -4110,13 +4281,13 @@ static void rna_def_modifier_triangulate(BlenderRNA *brna)
static void rna_def_modifier_meshcache(BlenderRNA *brna)
{
- static EnumPropertyItem prop_format_type_items[] = {
+ static const EnumPropertyItem prop_format_type_items[] = {
{MOD_MESHCACHE_TYPE_MDD, "MDD", 0, "MDD ", ""},
{MOD_MESHCACHE_TYPE_PC2, "PC2", 0, "PC2", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_deform_mode_items[] = {
+ static const EnumPropertyItem prop_deform_mode_items[] = {
{MOD_MESHCACHE_DEFORM_OVERWRITE, "OVERWRITE", 0, "Overwrite",
"Replace vertex coords with cached values"},
{MOD_MESHCACHE_DEFORM_INTEGRATE, "INTEGRATE", 0, "Integrate",
@@ -4124,7 +4295,7 @@ static void rna_def_modifier_meshcache(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_interpolation_type_items[] = {
+ static const EnumPropertyItem prop_interpolation_type_items[] = {
{MOD_MESHCACHE_INTERP_NONE, "NONE", 0, "None ", ""},
{MOD_MESHCACHE_INTERP_LINEAR, "LINEAR", 0, "Linear", ""},
/* for cardinal we'd need to read 4x cache's */
@@ -4132,7 +4303,7 @@ static void rna_def_modifier_meshcache(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_time_type_items[] = {
+ static const EnumPropertyItem prop_time_type_items[] = {
/* use 'eval_frame' */
{MOD_MESHCACHE_TIME_FRAME, "FRAME", 0, "Frame", "Control playback using a frame-number "
"(ignoring time FPS and start frame from the file)"},
@@ -4143,7 +4314,7 @@ static void rna_def_modifier_meshcache(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_time_play_items[] = {
+ static const EnumPropertyItem prop_time_play_items[] = {
{MOD_MESHCACHE_PLAY_CFEA, "SCENE", 0, "Scene", "Use the time from the scene"},
{MOD_MESHCACHE_PLAY_EVAL, "CUSTOM", 0, "Custom", "Use the modifier's own time evaluation"},
{0, NULL, 0, NULL, NULL}
@@ -4274,7 +4445,7 @@ static void rna_def_modifier_meshseqcache(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Object Path", "Path to the object in the Alembic archive used to lookup geometric data");
RNA_def_property_update(prop, 0, "rna_MeshSequenceCache_object_path_update");
- static EnumPropertyItem read_flag_items[] = {
+ static const EnumPropertyItem read_flag_items[] = {
{MOD_MESHSEQ_READ_VERT, "VERT", 0, "Vertex", ""},
{MOD_MESHSEQ_READ_POLY, "POLY", 0, "Faces", ""},
{MOD_MESHSEQ_READ_UV, "UV", 0, "UV", ""},
@@ -4408,7 +4579,7 @@ static void rna_def_modifier_datatransfer(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem DT_layer_vert_items[] = {
+ static const EnumPropertyItem DT_layer_vert_items[] = {
{DT_TYPE_MDEFORMVERT, "VGROUP_WEIGHTS", 0, "Vertex Group(s)", "Transfer active or all vertex groups"},
#if 0 /* TODO */
{DT_TYPE_SHAPEKEY, "SHAPEKEYS", 0, "Shapekey(s)", "Transfer active or all shape keys"},
@@ -4420,7 +4591,7 @@ static void rna_def_modifier_datatransfer(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem DT_layer_edge_items[] = {
+ static const EnumPropertyItem DT_layer_edge_items[] = {
{DT_TYPE_SHARP_EDGE, "SHARP_EDGE", 0, "Sharp", "Transfer sharp mark"},
{DT_TYPE_SEAM, "SEAM", 0, "UV Seam", "Transfer UV seam mark"},
{DT_TYPE_CREASE, "CREASE", 0, "Subsurf Crease", "Transfer crease values"},
@@ -4429,14 +4600,14 @@ static void rna_def_modifier_datatransfer(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem DT_layer_loop_items[] = {
+ static const EnumPropertyItem DT_layer_loop_items[] = {
{DT_TYPE_LNOR, "CUSTOM_NORMAL", 0, "Custom Normals", "Transfer custom normals"},
{DT_TYPE_VCOL, "VCOL", 0, "VCol", "Vertex (face corners) colors"},
{DT_TYPE_UV, "UV", 0, "UVs", "Transfer UV layers"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem DT_layer_poly_items[] = {
+ static const EnumPropertyItem DT_layer_poly_items[] = {
{DT_TYPE_SHARP_FACE, "SMOOTH", 0, "Smooth", "Transfer flat/smooth mark"},
{DT_TYPE_FREESTYLE_FACE, "FREESTYLE_FACE", 0, "Freestyle Mark", "Transfer Freestyle face mark"},
{0, NULL, 0, NULL, NULL}
@@ -4631,7 +4802,7 @@ static void rna_def_modifier_normaledit(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_mode_items[] = {
+ static const EnumPropertyItem prop_mode_items[] = {
{MOD_NORMALEDIT_MODE_RADIAL, "RADIAL", 0, "Radial",
"From an ellipsoid (shape defined by the boundbox's dimensions, target is optional)"},
{MOD_NORMALEDIT_MODE_DIRECTIONAL, "DIRECTIONAL", 0, "Directional",
@@ -4639,7 +4810,7 @@ static void rna_def_modifier_normaledit(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mix_mode_items[] = {
+ static const EnumPropertyItem prop_mix_mode_items[] = {
{MOD_NORMALEDIT_MIX_COPY, "COPY", 0, "Copy", "Copy new normals (overwrite existing)"},
{MOD_NORMALEDIT_MIX_ADD, "ADD", 0, "Add", "Copy sum of new and old normals"},
{MOD_NORMALEDIT_MIX_SUB, "SUB", 0, "Subtract", "Copy new normals minus old normals"},
@@ -4702,6 +4873,33 @@ static void rna_def_modifier_normaledit(BlenderRNA *brna)
RNA_def_property_update(prop, 0, "rna_Modifier_update");
}
+static void rna_def_modifier_surfacedeform(BlenderRNA *brna)
+{
+ StructRNA *srna;
+ PropertyRNA *prop;
+
+ srna = RNA_def_struct(brna, "SurfaceDeformModifier", "Modifier");
+ RNA_def_struct_ui_text(srna, "SurfaceDeform Modifier", "");
+ RNA_def_struct_sdna(srna, "SurfaceDeformModifierData");
+ RNA_def_struct_ui_icon(srna, ICON_MOD_MESHDEFORM);
+
+ prop = RNA_def_property(srna, "target", PROP_POINTER, PROP_NONE);
+ RNA_def_property_ui_text(prop, "Target", "Mesh object to deform with");
+ RNA_def_property_pointer_funcs(prop, NULL, "rna_SurfaceDeformModifier_target_set", NULL, "rna_Mesh_object_poll");
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_SELF_CHECK);
+ RNA_def_property_update(prop, 0, "rna_Modifier_dependency_update");
+
+ prop = RNA_def_property(srna, "falloff", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, 2.0f, 16.0f);
+ RNA_def_property_ui_text(prop, "Interpolation falloff", "Controls how much nearby polygons influence deformation");
+ RNA_def_property_update(prop, 0, "rna_Modifier_update");
+
+ prop = RNA_def_property(srna, "is_bound", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_funcs(prop, "rna_SurfaceDeformModifier_is_bound_get", NULL);
+ RNA_def_property_ui_text(prop, "Bound", "Whether geometry has been bound to target mesh");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+}
+
void RNA_def_modifier(BlenderRNA *brna)
{
StructRNA *srna;
@@ -4819,6 +5017,7 @@ void RNA_def_modifier(BlenderRNA *brna)
rna_def_modifier_datatransfer(brna);
rna_def_modifier_normaledit(brna);
rna_def_modifier_meshseqcache(brna);
+ rna_def_modifier_surfacedeform(brna);
}
#endif
diff --git a/source/blender/makesrna/intern/rna_movieclip.c b/source/blender/makesrna/intern/rna_movieclip.c
index 15411f85ba3..d63f3fe76f8 100644
--- a/source/blender/makesrna/intern/rna_movieclip.c
+++ b/source/blender/makesrna/intern/rna_movieclip.c
@@ -33,6 +33,7 @@
#include "DNA_movieclip_types.h"
#include "DNA_scene_types.h"
+#include "RNA_access.h"
#include "RNA_define.h"
#include "rna_internal.h"
@@ -44,6 +45,7 @@
#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"
+#include "IMB_metadata.h"
#ifdef RNA_RUNTIME
@@ -103,6 +105,22 @@ static void rna_MovieClipUser_proxy_render_settings_update(Main *UNUSED(bmain),
}
}
+static PointerRNA rna_MovieClip_metadata_get(MovieClip *clip)
+{
+ if (clip == NULL || clip->anim == NULL) {
+ return PointerRNA_NULL;
+ }
+
+ IDProperty *metadata = IMB_anim_load_metadata(clip->anim);
+ if (metadata == NULL) {
+ return PointerRNA_NULL;
+ }
+
+ PointerRNA ptr;
+ RNA_pointer_create(NULL, &RNA_IDPropertyWrapPtr, metadata, &ptr);
+ return ptr;
+}
+
#else
static void rna_def_movieclip_proxy(BlenderRNA *brna)
@@ -211,7 +229,7 @@ static void rna_def_moviecliUser(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem clip_render_size_items[] = {
+ static const EnumPropertyItem clip_render_size_items[] = {
{MCLIP_PROXY_RENDER_SIZE_25, "PROXY_25", 0, "Proxy size 25%", ""},
{MCLIP_PROXY_RENDER_SIZE_50, "PROXY_50", 0, "Proxy size 50%", ""},
{MCLIP_PROXY_RENDER_SIZE_75, "PROXY_75", 0, "Proxy size 75%", ""},
@@ -257,8 +275,10 @@ static void rna_def_movieclip(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
+ FunctionRNA *func;
+ PropertyRNA *parm;
- static EnumPropertyItem clip_source_items[] = {
+ static const EnumPropertyItem clip_source_items[] = {
{MCLIP_SRC_SEQUENCE, "SEQUENCE", 0, "Image Sequence", "Multiple image files, as a sequence"},
{MCLIP_SRC_MOVIE, "MOVIE", 0, "Movie File", "Movie file"},
{0, NULL, 0, NULL, NULL}
@@ -348,6 +368,14 @@ static void rna_def_movieclip(BlenderRNA *brna)
RNA_def_property_struct_type(prop, "ColorManagedInputColorspaceSettings");
RNA_def_property_ui_text(prop, "Color Space Settings", "Input color space settings");
+ /* metadata */
+ func = RNA_def_function(srna, "metadata", "rna_MovieClip_metadata_get");
+ RNA_def_function_ui_description(func, "Retrieve metadata of the movie file");
+ /* return type */
+ parm = RNA_def_pointer(func, "metadata", "IDPropertyWrapPtr", "", "Dict-like object containing the metadata");
+ RNA_def_parameter_flags(parm, 0, PARM_RNAPTR);
+ RNA_def_function_return(func, parm);
+
rna_def_animdata_common(srna);
}
diff --git a/source/blender/makesrna/intern/rna_nla.c b/source/blender/makesrna/intern/rna_nla.c
index e44a6420045..f1c02896447 100644
--- a/source/blender/makesrna/intern/rna_nla.c
+++ b/source/blender/makesrna/intern/rna_nla.c
@@ -371,7 +371,7 @@ static FCurve *rna_NlaStrip_fcurve_find(NlaStrip *strip, ReportList *reports, co
static NlaStrip *rna_NlaStrip_new(NlaTrack *track, bContext *C, ReportList *reports, const char *UNUSED(name),
int start, bAction *action)
{
- NlaStrip *strip = add_nlastrip(action);
+ NlaStrip *strip = BKE_nlastrip_new(action);
if (strip == NULL) {
BKE_report(reports, RPT_ERROR, "Unable to create new strip");
@@ -384,7 +384,7 @@ static NlaStrip *rna_NlaStrip_new(NlaTrack *track, bContext *C, ReportList *repo
if (BKE_nlastrips_add_strip(&track->strips, strip) == 0) {
BKE_report(reports, RPT_ERROR,
"Unable to add strip (the track does not have any space to accommodate this new strip)");
- free_nlastrip(NULL, strip);
+ BKE_nlastrip_free(NULL, strip);
return NULL;
}
@@ -425,7 +425,7 @@ static void rna_NlaStrip_remove(NlaTrack *track, bContext *C, ReportList *report
return;
}
- free_nlastrip(&track->strips, strip);
+ BKE_nlastrip_free(&track->strips, strip);
RNA_POINTER_INVALIDATE(strip_ptr);
WM_event_add_notifier(C, NC_ANIMATION | ND_NLA | NA_REMOVED, NULL);
@@ -471,7 +471,7 @@ static void rna_NlaTrack_solo_set(PointerRNA *ptr, int value)
#else
/* enum defines exported for rna_animation.c */
-EnumPropertyItem rna_enum_nla_mode_blend_items[] = {
+const EnumPropertyItem rna_enum_nla_mode_blend_items[] = {
{NLASTRIP_MODE_REPLACE, "REPLACE", 0, "Replace",
"Result strip replaces the accumulated results by amount specified by influence"},
{NLASTRIP_MODE_ADD, "ADD", 0, "Add", "Weighted result of strip is added to the accumulated results"},
@@ -482,7 +482,7 @@ EnumPropertyItem rna_enum_nla_mode_blend_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_nla_mode_extend_items[] = {
+const EnumPropertyItem rna_enum_nla_mode_extend_items[] = {
{NLASTRIP_EXTEND_NOTHING, "NOTHING", 0, "Nothing", "Strip has no influence past its extents"},
{NLASTRIP_EXTEND_HOLD, "HOLD", 0, "Hold",
"Hold the first frame if no previous strips in track, and always hold last frame"},
@@ -521,7 +521,7 @@ static void rna_def_nlastrip(BlenderRNA *brna)
PropertyRNA *prop;
/* enum defs */
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{NLASTRIP_TYPE_CLIP, "CLIP", 0, "Action Clip", "NLA Strip references some Action"},
{NLASTRIP_TYPE_TRANSITION, "TRANSITION", 0, "Transition", "NLA Strip 'transitions' between adjacent strips"},
{NLASTRIP_TYPE_META, "META", 0, "Meta", "NLA Strip acts as a container for adjacent strips"},
@@ -659,7 +659,10 @@ static void rna_def_nlastrip(BlenderRNA *brna)
prop = RNA_def_property(srna, "influence", PROP_FLOAT, PROP_NONE);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_text(prop, "Influence", "Amount the strip contributes to the current result");
- RNA_def_property_update(prop, NC_ANIMATION | ND_NLA | NA_EDITED, "rna_NlaStrip_update");
+ /* XXX: Update temporarily disabled so that the property can be edited at all!
+ * Even autokey only applies after the curves have been re-evaluated, causing the unkeyed values to be lost
+ */
+ RNA_def_property_update(prop, NC_ANIMATION | ND_NLA | NA_EDITED, /*"rna_NlaStrip_update"*/ NULL);
prop = RNA_def_property(srna, "strip_time", PROP_FLOAT, PROP_TIME);
RNA_def_property_ui_text(prop, "Strip Time", "Frame of referenced Action to evaluate");
diff --git a/source/blender/makesrna/intern/rna_nodetree.c b/source/blender/makesrna/intern/rna_nodetree.c
index 784004182dd..773ca307a8c 100644
--- a/source/blender/makesrna/intern/rna_nodetree.c
+++ b/source/blender/makesrna/intern/rna_nodetree.c
@@ -64,14 +64,23 @@
#include "RE_render_ext.h"
-EnumPropertyItem rna_enum_node_socket_in_out_items[] = {
+#include "NOD_composite.h"
+
+const EnumPropertyItem rna_enum_node_socket_in_out_items[] = {
{ SOCK_IN, "IN", 0, "Input", "" },
{ SOCK_OUT, "OUT", 0, "Output", "" },
{ 0, NULL, 0, NULL, NULL }
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem node_socket_type_items[] = {
+static const EnumPropertyItem rna_enum_node_socket_draw_shape_items[] = {
+ {SOCK_DRAW_SHAPE_CIRCLE, "CIRCLE", 0, "Circle", ""},
+ {SOCK_DRAW_SHAPE_SQUARE, "SQUARE", 0, "Square", ""},
+ {SOCK_DRAW_SHAPE_DIAMOND, "DIAMOND", 0, "Diamond", ""},
+ {0, NULL, 0, NULL, NULL }
+};
+
+static const EnumPropertyItem node_socket_type_items[] = {
{SOCK_CUSTOM, "CUSTOM", 0, "Custom", ""},
{SOCK_FLOAT, "VALUE", 0, "Value", ""},
{SOCK_INT, "INT", 0, "Int", ""},
@@ -83,14 +92,14 @@ static EnumPropertyItem node_socket_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_quality_items[] = {
+static const EnumPropertyItem node_quality_items[] = {
{NTREE_QUALITY_HIGH, "HIGH", 0, "High", "High quality"},
{NTREE_QUALITY_MEDIUM, "MEDIUM", 0, "Medium", "Medium quality"},
{NTREE_QUALITY_LOW, "LOW", 0, "Low", "Low quality"},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_chunksize_items[] = {
+static const EnumPropertyItem node_chunksize_items[] = {
{NTREE_CHUNCKSIZE_32, "32", 0, "32x32", "Chunksize of 32x32"},
{NTREE_CHUNCKSIZE_64, "64", 0, "64x64", "Chunksize of 64x64"},
{NTREE_CHUNCKSIZE_128, "128", 0, "128x128", "Chunksize of 128x128"},
@@ -104,14 +113,14 @@ static EnumPropertyItem node_chunksize_items[] = {
#define DEF_ICON_BLANK_SKIP
#define DEF_ICON(name) {ICON_##name, (#name), 0, (#name), ""},
#define DEF_VICO(name)
-EnumPropertyItem rna_enum_node_icon_items[] = {
+const EnumPropertyItem rna_enum_node_icon_items[] = {
#include "UI_icons.h"
{0, NULL, 0, NULL, NULL}};
#undef DEF_ICON_BLANK_SKIP
#undef DEF_ICON
#undef DEF_VICO
-EnumPropertyItem rna_enum_node_math_items[] = {
+const EnumPropertyItem rna_enum_node_math_items[] = {
{NODE_MATH_ADD, "ADD", 0, "Add", ""},
{NODE_MATH_SUB, "SUBTRACT", 0, "Subtract", ""},
{NODE_MATH_MUL, "MULTIPLY", 0, "Multiply", ""},
@@ -134,7 +143,7 @@ EnumPropertyItem rna_enum_node_math_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_node_vec_math_items[] = {
+const EnumPropertyItem rna_enum_node_vec_math_items[] = {
{0, "ADD", 0, "Add", ""},
{1, "SUBTRACT", 0, "Subtract", ""},
{2, "AVERAGE", 0, "Average", ""},
@@ -144,7 +153,7 @@ EnumPropertyItem rna_enum_node_vec_math_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_node_filter_items[] = {
+const EnumPropertyItem rna_enum_node_filter_items[] = {
{0, "SOFTEN", 0, "Soften", ""},
{1, "SHARPEN", 0, "Sharpen", ""},
{2, "LAPLACE", 0, "Laplace", ""},
@@ -156,7 +165,7 @@ EnumPropertyItem rna_enum_node_filter_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem node_sampler_type_items[] = {
+static const EnumPropertyItem node_sampler_type_items[] = {
{0, "NEAREST", 0, "Nearest", ""},
{1, "BILINEAR", 0, "Bilinear", ""},
{2, "BICUBIC", 0, "Bicubic", ""},
@@ -234,12 +243,12 @@ bNodeTreeType *rna_node_tree_type_from_enum(int value)
return result;
}
-EnumPropertyItem *rna_node_tree_type_itemf(void *data, int (*poll)(void *data, bNodeTreeType *), bool *r_free)
+const EnumPropertyItem *rna_node_tree_type_itemf(void *data, int (*poll)(void *data, bNodeTreeType *), bool *r_free)
{
- EnumPropertyItem tmp = {0, "", 0, "", ""};
+ EnumPropertyItem tmp = {0};
EnumPropertyItem *item = NULL;
int totitem = 0, i = 0;
-
+
NODE_TREE_TYPES_BEGIN (nt)
{
if (poll && !poll(data, nt)) {
@@ -259,9 +268,14 @@ EnumPropertyItem *rna_node_tree_type_itemf(void *data, int (*poll)(void *data, b
}
NODE_TREE_TYPES_END;
+ if (totitem == 0) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
+ }
+
RNA_enum_item_end(&item, &totitem);
*r_free = true;
-
+
return item;
}
@@ -305,12 +319,12 @@ bNodeType *rna_node_type_from_enum(int value)
return result;
}
-EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, bNodeType *), bool *r_free)
+const EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, bNodeType *), bool *r_free)
{
EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
+ EnumPropertyItem tmp = {0};
int totitem = 0, i = 0;
-
+
NODE_TYPES_BEGIN(ntype)
if (poll && !poll(data, ntype)) {
++i;
@@ -327,9 +341,15 @@ EnumPropertyItem *rna_node_type_itemf(void *data, int (*poll)(void *data, bNodeT
++i;
NODE_TYPES_END
+
+ if (totitem == 0) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
+ }
+
RNA_enum_item_end(&item, &totitem);
*r_free = true;
-
+
return item;
}
@@ -373,13 +393,14 @@ bNodeSocketType *rna_node_socket_type_from_enum(int value)
return result;
}
-EnumPropertyItem *rna_node_socket_type_itemf(void *data, int (*poll)(void *data, bNodeSocketType *), bool *r_free)
+const EnumPropertyItem *rna_node_socket_type_itemf(
+ void *data, int (*poll)(void *data, bNodeSocketType *), bool *r_free)
{
EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
+ EnumPropertyItem tmp = {0};
int totitem = 0, i = 0;
StructRNA *srna;
-
+
NODE_SOCKET_TYPES_BEGIN(stype)
if (poll && !poll(data, stype)) {
++i;
@@ -397,36 +418,42 @@ EnumPropertyItem *rna_node_socket_type_itemf(void *data, int (*poll)(void *data,
++i;
NODE_SOCKET_TYPES_END
+
+ if (totitem == 0) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
+ }
+
RNA_enum_item_end(&item, &totitem);
*r_free = true;
-
+
return item;
}
-static EnumPropertyItem *rna_node_static_type_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rna_node_static_type_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
EnumPropertyItem tmp;
int totitem = 0;
-
+
/* hack, don't want to add include path to RNA just for this, since in the future RNA types
* for nodes should be defined locally at runtime anyway ...
*/
-
+
tmp.value = NODE_CUSTOM;
tmp.identifier = "CUSTOM";
tmp.name = "Custom";
tmp.description = "Custom Node";
tmp.icon = ICON_NONE;
RNA_enum_item_add(&item, &totitem, &tmp);
-
+
tmp.value = NODE_UNDEFINED;
tmp.identifier = "UNDEFINED";
tmp.name = "UNDEFINED";
tmp.description = "";
tmp.icon = ICON_NONE;
RNA_enum_item_add(&item, &totitem, &tmp);
-
+
#define DefNode(Category, ID, DefFunc, EnumName, StructName, UIName, UIDesc) \
if (STREQ(#Category, "Node")) { \
tmp.value = ID; \
@@ -438,7 +465,7 @@ static EnumPropertyItem *rna_node_static_type_itemf(bContext *UNUSED(C), Pointer
}
#include "../../nodes/NOD_static_types.h"
#undef DefNode
-
+
if (RNA_struct_is_a(ptr->type, &RNA_ShaderNode)) {
#define DefNode(Category, ID, DefFunc, EnumName, StructName, UIName, UIDesc) \
if (STREQ(#Category, "ShaderNode")) { \
@@ -466,7 +493,7 @@ static EnumPropertyItem *rna_node_static_type_itemf(bContext *UNUSED(C), Pointer
#include "../../nodes/NOD_static_types.h"
#undef DefNode
}
-
+
if (RNA_struct_is_a(ptr->type, &RNA_TextureNode)) {
#define DefNode(Category, ID, DefFunc, EnumName, StructName, UIName, UIDesc) \
if (STREQ(#Category, "TextureNode")) { \
@@ -483,7 +510,7 @@ static EnumPropertyItem *rna_node_static_type_itemf(bContext *UNUSED(C), Pointer
RNA_enum_item_end(&item, &totitem);
*r_free = true;
-
+
return item;
}
@@ -576,11 +603,10 @@ static void rna_NodeTree_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &nt->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
ntreeTypeFreeLink(nt);
- RNA_struct_free(&BLENDER_RNA, type);
-
/* update while blender is running */
WM_main_add_notifier(NC_NODE | NA_EDITED, NULL);
}
@@ -612,9 +638,10 @@ static StructRNA *rna_NodeTree_register(
/* check if we have registered this tree type before, and remove it */
nt = ntreeTypeFind(dummynt.idname);
- if (nt)
+ if (nt) {
rna_NodeTree_unregister(bmain, nt->ext.srna);
-
+ }
+
/* create a new node tree type */
nt = MEM_callocN(sizeof(bNodeTreeType), "node tree type");
memcpy(nt, &dummynt, sizeof(dummynt));
@@ -1329,11 +1356,11 @@ static void rna_Node_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &nt->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
/* this also frees the allocated nt pointer, no MEM_free call needed! */
nodeUnregisterType(nt);
- RNA_struct_free(&BLENDER_RNA, type);
/* update while blender is running */
WM_main_add_notifier(NC_NODE | NA_EDITED, NULL);
@@ -1374,8 +1401,9 @@ static bNodeType *rna_Node_register_base(Main *bmain, ReportList *reports, Struc
/* check if we have registered this node type before, and remove it */
nt = nodeTypeFind(dummynt.idname);
- if (nt)
+ if (nt) {
rna_Node_unregister(bmain, nt->ext.srna);
+ }
/* create a new node type */
nt = MEM_callocN(sizeof(bNodeType), "node type");
@@ -1791,10 +1819,10 @@ static void rna_NodeSocket_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &st->ext_socket);
+ RNA_struct_free(&BLENDER_RNA, type);
nodeUnregisterSocketType(st);
- RNA_struct_free(&BLENDER_RNA, type);
/* update while blender is running */
WM_main_add_notifier(NC_NODE | NA_EDITED, NULL);
@@ -2608,16 +2636,16 @@ static void rna_Node_image_layer_update(Main *bmain, Scene *scene, PointerRNA *p
rna_Node_update(bmain, scene, ptr);
if (scene->nodetree != NULL) {
- ntreeCompositForceHidden(scene->nodetree);
+ ntreeCompositUpdateRLayers(scene->nodetree);
}
}
-static EnumPropertyItem *renderresult_layers_add_enum(RenderLayer *rl)
+static const EnumPropertyItem *renderresult_layers_add_enum(RenderLayer *rl)
{
EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
+ EnumPropertyItem tmp = {0};
int i = 0, totitem = 0;
-
+
while (rl) {
tmp.identifier = rl->name;
/* little trick: using space char instead empty string makes the item selectable in the dropdown */
@@ -2629,31 +2657,30 @@ static EnumPropertyItem *renderresult_layers_add_enum(RenderLayer *rl)
RNA_enum_item_add(&item, &totitem, &tmp);
rl = rl->next;
}
-
+
RNA_enum_item_end(&item, &totitem);
return item;
}
-static EnumPropertyItem *rna_Node_image_layer_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Node_image_layer_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
bNode *node = (bNode *)ptr->data;
Image *ima = (Image *)node->id;
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
RenderLayer *rl;
-
- if (ima && ima->rr) {
- rl = ima->rr->layers.first;
- item = renderresult_layers_add_enum(rl);
- }
- else {
- int totitem = 0;
- RNA_enum_item_end(&item, &totitem);
+
+ if (ima == NULL || ima->rr == NULL) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
}
-
+
+ rl = ima->rr->layers.first;
+ item = renderresult_layers_add_enum(rl);
+
*r_free = true;
-
+
return item;
}
@@ -2674,10 +2701,10 @@ static int rna_Node_image_has_views_get(PointerRNA *ptr)
if (!ima || !(ima->rr)) return 0;
- return BLI_listbase_count_ex(&ima->rr->views, 2) > 1;
+ return BLI_listbase_count_at_most(&ima->rr->views, 2) > 1;
}
-static EnumPropertyItem *renderresult_views_add_enum(RenderView *rv)
+static const EnumPropertyItem *renderresult_views_add_enum(RenderView *rv)
{
EnumPropertyItem *item = NULL;
EnumPropertyItem tmp = {0, "ALL", 0, "All", ""};
@@ -2703,43 +2730,45 @@ static EnumPropertyItem *renderresult_views_add_enum(RenderView *rv)
return item;
}
-static EnumPropertyItem *rna_Node_image_view_itemf(bContext *UNUSED(C), PointerRNA *ptr,
- PropertyRNA *UNUSED(prop), bool *free)
+static const EnumPropertyItem *rna_Node_image_view_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+ PropertyRNA *UNUSED(prop), bool *r_free)
{
bNode *node = (bNode *)ptr->data;
Image *ima = (Image *)node->id;
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
RenderView *rv;
- if (!ima || !(ima->rr)) return NULL;
+ if (ima == NULL || ima->rr == NULL) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
+ }
rv = ima->rr->views.first;
item = renderresult_views_add_enum(rv);
- *free = true;
+ *r_free = true;
return item;
}
-static EnumPropertyItem *rna_Node_scene_layer_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Node_scene_layer_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
bNode *node = (bNode *)ptr->data;
Scene *sce = (Scene *)node->id;
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
RenderLayer *rl;
-
- if (sce) {
- rl = sce->r.layers.first;
- item = renderresult_layers_add_enum(rl);
- }
- else {
- int totitem = 0;
- RNA_enum_item_end(&item, &totitem);
+
+ if (sce == NULL) {
+ *r_free = false;
+ return DummyRNA_NULL_items;
}
-
+
+ rl = sce->r.layers.first;
+ item = renderresult_layers_add_enum(rl);
+
*r_free = true;
-
+
return item;
}
@@ -2747,16 +2776,16 @@ static void rna_Node_scene_layer_update(Main *bmain, Scene *scene, PointerRNA *p
{
rna_Node_update(bmain, scene, ptr);
if (scene->nodetree != NULL) {
- ntreeCompositForceHidden(scene->nodetree);
+ ntreeCompositUpdateRLayers(scene->nodetree);
}
}
-static EnumPropertyItem *rna_Node_channel_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Node_channel_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
bNode *node = (bNode *)ptr->data;
EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
+ EnumPropertyItem tmp = {0};
int totitem = 0;
switch (node->custom1) {
@@ -2793,7 +2822,7 @@ static EnumPropertyItem *rna_Node_channel_itemf(bContext *UNUSED(C), PointerRNA
RNA_enum_item_add(&item, &totitem, &tmp);
break;
default:
- break;
+ return DummyRNA_NULL_items;
}
RNA_enum_item_end(&item, &totitem);
@@ -2995,6 +3024,15 @@ static void rna_ShaderNodeScript_update(Main *bmain, Scene *scene, PointerRNA *p
ED_node_tag_update_nodetree(bmain, ntree, node);
}
+static void rna_ShaderNodePrincipled_update(Main *bmain, Scene *scene, PointerRNA *ptr)
+{
+ bNodeTree *ntree = (bNodeTree *)ptr->id.data;
+ bNode *node = (bNode *)ptr->data;
+
+ nodeUpdate(ntree, node);
+ rna_Node_update(bmain, scene, ptr);
+}
+
static void rna_ShaderNodeSubsurface_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
bNodeTree *ntree = (bNodeTree *)ptr->id.data;
@@ -3168,43 +3206,43 @@ void rna_ShaderNodePointDensity_density_minmax(bNode *self,
#else
-static EnumPropertyItem prop_image_layer_items[] = {
+static const EnumPropertyItem prop_image_layer_items[] = {
{ 0, "PLACEHOLDER", 0, "Placeholder", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_image_view_items[] = {
+static const EnumPropertyItem prop_image_view_items[] = {
{ 0, "ALL", 0, "All", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_scene_layer_items[] = {
+static const EnumPropertyItem prop_scene_layer_items[] = {
{ 0, "PLACEHOLDER", 0, "Placeholder", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_tri_channel_items[] = {
+static const EnumPropertyItem prop_tri_channel_items[] = {
{ 1, "R", 0, "R", ""},
{ 2, "G", 0, "G", ""},
{ 3, "B", 0, "B", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_flip_items[] = {
+static const EnumPropertyItem node_flip_items[] = {
{0, "X", 0, "Flip X", ""},
{1, "Y", 0, "Flip Y", ""},
{2, "XY", 0, "Flip X & Y", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_ycc_items[] = {
+static const EnumPropertyItem node_ycc_items[] = {
{ 0, "ITUBT601", 0, "ITU 601", ""},
{ 1, "ITUBT709", 0, "ITU 709", ""},
{ 2, "JFIF", 0, "Jpeg", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_glossy_items[] = {
+static const EnumPropertyItem node_glossy_items[] = {
{SHD_GLOSSY_SHARP, "SHARP", 0, "Sharp", ""},
{SHD_GLOSSY_BECKMANN, "BECKMANN", 0, "Beckmann", ""},
{SHD_GLOSSY_GGX, "GGX", 0, "GGX", ""},
@@ -3213,7 +3251,7 @@ static EnumPropertyItem node_glossy_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_anisotropic_items[] = {
+static const EnumPropertyItem node_anisotropic_items[] = {
{SHD_GLOSSY_BECKMANN, "BECKMANN", 0, "Beckmann", ""},
{SHD_GLOSSY_GGX, "GGX", 0, "GGX", ""},
{SHD_GLOSSY_MULTI_GGX, "MULTI_GGX", 0, "Multiscatter GGX", ""},
@@ -3221,7 +3259,7 @@ static EnumPropertyItem node_anisotropic_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_glass_items[] = {
+static const EnumPropertyItem node_glass_items[] = {
{SHD_GLOSSY_SHARP, "SHARP", 0, "Sharp", ""},
{SHD_GLOSSY_BECKMANN, "BECKMANN", 0, "Beckmann", ""},
{SHD_GLOSSY_GGX, "GGX", 0, "GGX", ""},
@@ -3229,31 +3267,44 @@ static EnumPropertyItem node_glass_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_refraction_items[] = {
+static const EnumPropertyItem node_refraction_items[] = {
{SHD_GLOSSY_SHARP, "SHARP", 0, "Sharp", ""},
{SHD_GLOSSY_BECKMANN, "BECKMANN", 0, "Beckmann", ""},
{SHD_GLOSSY_GGX, "GGX", 0, "GGX", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_toon_items[] = {
+static const EnumPropertyItem node_toon_items[] = {
{SHD_TOON_DIFFUSE, "DIFFUSE", 0, "Diffuse", ""},
{SHD_TOON_GLOSSY, "GLOSSY", 0, "Glossy", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_hair_items[] = {
+static const EnumPropertyItem node_hair_items[] = {
{SHD_HAIR_REFLECTION, "Reflection", 0, "Reflection", ""},
{SHD_HAIR_TRANSMISSION, "Transmission", 0, "Transmission", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem node_script_mode_items[] = {
+static const EnumPropertyItem node_script_mode_items[] = {
{NODE_SCRIPT_INTERNAL, "INTERNAL", 0, "Internal", "Use internal text data-block"},
{NODE_SCRIPT_EXTERNAL, "EXTERNAL", 0, "External", "Use external .osl or .oso file"},
{0, NULL, 0, NULL, NULL}
};
+static const EnumPropertyItem node_principled_distribution_items[] = {
+ {SHD_GLOSSY_GGX, "GGX", 0, "GGX", ""},
+ {SHD_GLOSSY_MULTI_GGX, "MULTI_GGX", 0, "Multiscatter GGX", ""},
+ {0, NULL, 0, NULL, NULL}
+};
+
+static const EnumPropertyItem node_subsurface_method_items[] = {
+ {SHD_SUBSURFACE_BURLEY, "BURLEY", 0, "Christensen-Burley", "Approximation to physically based volume scattering"},
+ {SHD_SUBSURFACE_RANDOM_WALK, "RANDOM_WALK", 0, "Random Walk", "Volumetric approximation to physically based volume scattering"},
+ { 0, NULL, 0, NULL, NULL }
+};
+
+
/* -- Common nodes ---------------------------------------------------------- */
static void def_group_input(StructRNA *srna)
@@ -3322,11 +3373,12 @@ static void def_frame(StructRNA *srna)
prop = RNA_def_property(srna, "text", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_struct_type(prop, "Text");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Text", "");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
RNA_def_struct_sdna_from(srna, "NodeFrame", "storage");
+ RNA_def_struct_translation_context(srna, BLT_I18NCONTEXT_ID_NODETREE);
prop = RNA_def_property(srna, "shrink", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", NODE_FRAME_SHRINK);
@@ -3507,7 +3559,7 @@ static void def_sh_material(StructRNA *srna)
static void def_sh_mapping(StructRNA *srna)
{
- static EnumPropertyItem prop_vect_type_items[] = {
+ static const EnumPropertyItem prop_vect_type_items[] = {
{TEXMAP_TYPE_TEXTURE, "TEXTURE", 0, "Texture", "Transform a texture by inverse mapping the texture coordinate"},
{TEXMAP_TYPE_POINT, "POINT", 0, "Point", "Transform a point"},
{TEXMAP_TYPE_VECTOR, "VECTOR", 0, "Vector", "Transform a direction vector"},
@@ -3591,7 +3643,7 @@ static void def_sh_lamp(StructRNA *srna)
prop = RNA_def_property(srna, "lamp_object", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_struct_type(prop, "Object");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_pointer_funcs(prop, NULL, NULL, NULL, "rna_Lamp_object_poll");
RNA_def_property_ui_text(prop, "Lamp Object", "");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
@@ -3626,7 +3678,7 @@ static void def_sh_tex(StructRNA *srna)
static void def_sh_tex_sky(StructRNA *srna)
{
- static EnumPropertyItem prop_sky_type[] = {
+ static const EnumPropertyItem prop_sky_type[] = {
{SHD_SKY_OLD, "PREETHAM", 0, "Preetham", ""},
{SHD_SKY_NEW, "HOSEK_WILKIE", 0, "Hosek / Wilkie", ""},
{0, NULL, 0, NULL, NULL}
@@ -3677,7 +3729,7 @@ static const EnumPropertyItem sh_tex_prop_interpolation_items[] = {
{SHD_INTERP_CLOSEST, "Closest", 0, "Closest",
"No interpolation (sample closest texel)"},
{SHD_INTERP_CUBIC, "Cubic", 0, "Cubic",
- "Cubic interpolation (CPU only)"},
+ "Cubic interpolation"},
{SHD_INTERP_SMART, "Smart", 0, "Smart",
"Bicubic when magnifying, else bilinear (OSL only)"},
{0, NULL, 0, NULL, NULL}
@@ -3743,7 +3795,7 @@ static void def_sh_tex_image(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_image_extension[] = {
+ static const EnumPropertyItem prop_image_extension[] = {
{SHD_IMAGE_EXTENSION_REPEAT, "REPEAT", 0, "Repeat", "Cause the image to repeat horizontally and vertically"},
{SHD_IMAGE_EXTENSION_EXTEND, "EXTEND", 0, "Extend", "Extend by repeating edge pixels of the image"},
{SHD_IMAGE_EXTENSION_CLIP, "CLIP", 0, "Clip", "Clip to image size and set exterior pixels as transparent"},
@@ -3797,7 +3849,7 @@ static void def_sh_tex_image(StructRNA *srna)
static void def_sh_tex_gradient(StructRNA *srna)
{
- static EnumPropertyItem prop_gradient_type[] = {
+ static const EnumPropertyItem prop_gradient_type[] = {
{SHD_BLEND_LINEAR, "LINEAR", 0, "Linear", "Create a linear progression"},
{SHD_BLEND_QUADRATIC, "QUADRATIC", 0, "Quadratic", "Create a quadratic progression"},
{SHD_BLEND_EASING, "EASING", 0, "Easing", "Create a progression easing from one step to the next"},
@@ -3885,7 +3937,7 @@ static void def_sh_tex_magic(StructRNA *srna)
static void def_sh_tex_musgrave(StructRNA *srna)
{
- static EnumPropertyItem prop_musgrave_type[] = {
+ static const EnumPropertyItem prop_musgrave_type[] = {
{SHD_MUSGRAVE_MULTIFRACTAL, "MULTIFRACTAL", 0, "Multifractal", ""},
{SHD_MUSGRAVE_RIDGED_MULTIFRACTAL, "RIDGED_MULTIFRACTAL", 0, "Ridged Multifractal", ""},
{SHD_MUSGRAVE_HYBRID_MULTIFRACTAL, "HYBRID_MULTIFRACTAL", 0, "Hybrid Multifractal", ""},
@@ -3908,7 +3960,7 @@ static void def_sh_tex_musgrave(StructRNA *srna)
static void def_sh_tex_voronoi(StructRNA *srna)
{
- static EnumPropertyItem prop_coloring_items[] = {
+ static const EnumPropertyItem prop_coloring_items[] = {
{SHD_VORONOI_INTENSITY, "INTENSITY", 0, "Intensity", "Only calculate intensity"},
{SHD_VORONOI_CELLS, "CELLS", 0, "Cells", "Color cells by position"},
{0, NULL, 0, NULL, NULL}
@@ -3928,13 +3980,13 @@ static void def_sh_tex_voronoi(StructRNA *srna)
static void def_sh_tex_wave(StructRNA *srna)
{
- static EnumPropertyItem prop_wave_type_items[] = {
+ static const EnumPropertyItem prop_wave_type_items[] = {
{SHD_WAVE_BANDS, "BANDS", 0, "Bands", "Use standard wave texture in bands"},
{SHD_WAVE_RINGS, "RINGS", 0, "Rings", "Use wave texture in rings"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_wave_profile_items[] = {
+ static const EnumPropertyItem prop_wave_profile_items[] = {
{SHD_WAVE_PROFILE_SIN, "SIN", 0, "Sine", "Use a standard sine profile"},
{SHD_WAVE_PROFILE_SAW, "SAW", 0, "Saw", "Use a sawtooth profile"},
{0, NULL, 0, NULL, NULL}
@@ -3965,7 +4017,7 @@ static void def_sh_tex_coord(StructRNA *srna)
prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_struct_type(prop, "Object");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Object", "Use coordinates from this object (for object texture coordinates output)");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
@@ -3977,14 +4029,14 @@ static void def_sh_tex_coord(StructRNA *srna)
static void def_sh_vect_transform(StructRNA *srna)
{
- static EnumPropertyItem prop_vect_type_items[] = {
+ static const EnumPropertyItem prop_vect_type_items[] = {
{SHD_VECT_TRANSFORM_TYPE_POINT, "POINT", 0, "Point", "Transform a point"},
{SHD_VECT_TRANSFORM_TYPE_VECTOR, "VECTOR", 0, "Vector", "Transform a direction vector"},
{SHD_VECT_TRANSFORM_TYPE_NORMAL, "NORMAL", 0, "Normal", "Transform a normal vector with unit length"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_vect_space_items[] = {
+ static const EnumPropertyItem prop_vect_space_items[] = {
{SHD_VECT_TRANSFORM_SPACE_WORLD, "WORLD", 0, "World", ""},
{SHD_VECT_TRANSFORM_SPACE_OBJECT, "OBJECT", 0, "Object", ""},
{SHD_VECT_TRANSFORM_SPACE_CAMERA, "CAMERA", 0, "Camera", ""},
@@ -4029,7 +4081,7 @@ static void def_sh_tex_pointdensity(StructRNA *srna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem point_source_items[] = {
+ static const EnumPropertyItem point_source_items[] = {
{SHD_POINTDENSITY_SOURCE_PSYS, "PARTICLE_SYSTEM", 0, "Particle System",
"Generate point density from a particle system"},
{SHD_POINTDENSITY_SOURCE_OBJECT, "OBJECT", 0, "Object Vertices",
@@ -4043,17 +4095,17 @@ static void def_sh_tex_pointdensity(StructRNA *srna)
{SHD_INTERP_LINEAR, "Linear", 0, "Linear",
"Linear interpolation"},
{SHD_INTERP_CUBIC, "Cubic", 0, "Cubic",
- "Cubic interpolation (CPU only)"},
+ "Cubic interpolation"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem space_items[] = {
+ static const EnumPropertyItem space_items[] = {
{SHD_POINTDENSITY_SPACE_OBJECT, "OBJECT", 0, "Object Space", ""},
{SHD_POINTDENSITY_SPACE_WORLD, "WORLD", 0, "World Space", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem particle_color_source_items[] = {
+ static const EnumPropertyItem particle_color_source_items[] = {
{SHD_POINTDENSITY_COLOR_PARTAGE, "PARTICLE_AGE", 0, "Particle Age",
"Lifetime mapped as 0.0 - 1.0 intensity"},
{SHD_POINTDENSITY_COLOR_PARTSPEED, "PARTICLE_SPEED", 0, "Particle Speed",
@@ -4063,7 +4115,7 @@ static void def_sh_tex_pointdensity(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vertex_color_source_items[] = {
+ static const EnumPropertyItem vertex_color_source_items[] = {
{SHD_POINTDENSITY_COLOR_VERTCOL, "VERTEX_COLOR", 0, "Vertex Color", "Vertex color layer"},
{SHD_POINTDENSITY_COLOR_VERTWEIGHT, "VERTEX_WEIGHT", 0, "Vertex Weight", "Vertex group weight"},
{SHD_POINTDENSITY_COLOR_VERTNOR, "VERTEX_NORMAL", 0, "Vertex Normal",
@@ -4072,7 +4124,7 @@ static void def_sh_tex_pointdensity(StructRNA *srna)
};
/* TODO(sergey): Use some mnemonic names for the hardcoded values here. */
- static EnumPropertyItem calc_mode_items[] = {
+ static const EnumPropertyItem calc_mode_items[] = {
{0, "VIEWPORT", 0, "Viewport", "Canculate density using viewport settings"},
{1, "RENDER", 0, "Render", "Canculate duplis using render settings"},
{0, NULL, 0, NULL, NULL}
@@ -4081,7 +4133,7 @@ static void def_sh_tex_pointdensity(StructRNA *srna)
prop = RNA_def_property(srna, "object", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_struct_type(prop, "Object");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Object", "Object to take point data from");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
@@ -4187,6 +4239,23 @@ static void def_glass(StructRNA *srna)
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
+static void def_principled(StructRNA *srna)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "distribution", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "custom1");
+ RNA_def_property_enum_items(prop, node_principled_distribution_items);
+ RNA_def_property_ui_text(prop, "Distribution", "");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNodePrincipled_update");
+
+ prop = RNA_def_property(srna, "subsurface_method", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "custom2");
+ RNA_def_property_enum_items(prop, node_subsurface_method_items);
+ RNA_def_property_ui_text(prop, "Subsurface Method", "Method for rendering subsurface scattering");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_ShaderNodePrincipled_update");
+}
+
static void def_refraction(StructRNA *srna)
{
PropertyRNA *prop;
@@ -4271,12 +4340,12 @@ static void def_sh_uvalongstroke(StructRNA *srna)
static void def_sh_normal_map(StructRNA *srna)
{
- static EnumPropertyItem prop_space_items[] = {
- {SHD_NORMAL_MAP_TANGENT, "TANGENT", 0, "Tangent Space", "Tangent space normal mapping"},
- {SHD_NORMAL_MAP_OBJECT, "OBJECT", 0, "Object Space", "Object space normal mapping"},
- {SHD_NORMAL_MAP_WORLD, "WORLD", 0, "World Space", "World space normal mapping"},
- {SHD_NORMAL_MAP_BLENDER_OBJECT, "BLENDER_OBJECT", 0, "Blender Object Space", "Object space normal mapping, compatible with Blender render baking"},
- {SHD_NORMAL_MAP_BLENDER_WORLD, "BLENDER_WORLD", 0, "Blender World Space", "World space normal mapping, compatible with Blender render baking"},
+ static const EnumPropertyItem prop_space_items[] = {
+ {SHD_SPACE_TANGENT, "TANGENT", 0, "Tangent Space", "Tangent space normal mapping"},
+ {SHD_SPACE_OBJECT, "OBJECT", 0, "Object Space", "Object space normal mapping"},
+ {SHD_SPACE_WORLD, "WORLD", 0, "World Space", "World space normal mapping"},
+ {SHD_SPACE_BLENDER_OBJECT, "BLENDER_OBJECT", 0, "Blender Object Space", "Object space normal mapping, compatible with Blender render baking"},
+ {SHD_SPACE_BLENDER_WORLD, "BLENDER_WORLD", 0, "Blender World Space", "World space normal mapping, compatible with Blender render baking"},
{0, NULL, 0, NULL, NULL}
};
@@ -4296,15 +4365,54 @@ static void def_sh_normal_map(StructRNA *srna)
RNA_def_struct_sdna_from(srna, "bNode", NULL);
}
+static void def_sh_displacement(StructRNA *srna)
+{
+ static const EnumPropertyItem prop_space_items[] = {
+ {SHD_SPACE_OBJECT, "OBJECT", 0, "Object Space", "Displacement is in object space, affected by object scale"},
+ {SHD_SPACE_WORLD, "WORLD", 0, "World Space", "Displacement is in world space, not affected by object scale"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "space", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "custom1");
+ RNA_def_property_enum_items(prop, prop_space_items);
+ RNA_def_property_ui_text(prop, "Space", "Space of the input height");
+ RNA_def_property_update(prop, 0, "rna_Node_update");
+
+ RNA_def_struct_sdna_from(srna, "bNode", NULL);
+}
+
+static void def_sh_vector_displacement(StructRNA *srna)
+{
+ static const EnumPropertyItem prop_space_items[] = {
+ {SHD_SPACE_TANGENT, "TANGENT", 0, "Tangent Space", "Tagent space vector displacement mapping"},
+ {SHD_SPACE_OBJECT, "OBJECT", 0, "Object Space", "Object space vector displacement mapping"},
+ {SHD_SPACE_WORLD, "WORLD", 0, "World Space", "World space vector displacement mapping"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "space", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "custom1");
+ RNA_def_property_enum_items(prop, prop_space_items);
+ RNA_def_property_ui_text(prop, "Space", "Space of the input height");
+ RNA_def_property_update(prop, 0, "rna_Node_update");
+
+ RNA_def_struct_sdna_from(srna, "bNode", NULL);
+}
+
static void def_sh_tangent(StructRNA *srna)
{
- static EnumPropertyItem prop_direction_type_items[] = {
+ static const EnumPropertyItem prop_direction_type_items[] = {
{SHD_TANGENT_RADIAL, "RADIAL", 0, "Radial", "Radial tangent around the X, Y or Z axis"},
{SHD_TANGENT_UVMAP, "UV_MAP", 0, "UV Map", "Tangent from UV map"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_axis_items[] = {
+ static const EnumPropertyItem prop_axis_items[] = {
{SHD_TANGENT_AXIS_X, "X", 0, "X", "X axis"},
{SHD_TANGENT_AXIS_Y, "Y", 0, "Y", "Y axis"},
{SHD_TANGENT_AXIS_Z, "Z", 0, "Z", "Z axis"},
@@ -4332,13 +4440,24 @@ static void def_sh_tangent(StructRNA *srna)
RNA_def_struct_sdna_from(srna, "bNode", NULL);
}
+static void def_sh_bevel(StructRNA *srna)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "samples", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_int_sdna(prop, NULL, "custom1");
+ RNA_def_property_range(prop, 2, 16);
+ RNA_def_property_ui_text(prop, "Samples", "Number of rays to trace per shader evaluation");
+ RNA_def_property_update(prop, 0, "rna_Node_update");
+}
static void def_sh_subsurface(StructRNA *srna)
{
- static EnumPropertyItem prop_subsurface_falloff_items[] = {
+ static const EnumPropertyItem prop_subsurface_falloff_items[] = {
{SHD_SUBSURFACE_CUBIC, "CUBIC", 0, "Cubic", "Simple cubic falloff function"},
{SHD_SUBSURFACE_GAUSSIAN, "GAUSSIAN", 0, "Gaussian", "Normal distribution, multiple can be combined to fit more complex profiles"},
{SHD_SUBSURFACE_BURLEY, "BURLEY", 0, "Christensen-Burley", "Approximation to physically based volume scattering"},
+ {SHD_SUBSURFACE_RANDOM_WALK, "RANDOM_WALK", 0, "Random Walk", "Volumetric approximation to physically based volume scattering"},
{0, NULL, 0, NULL, NULL}
};
@@ -4447,7 +4566,7 @@ static void def_cmp_blur(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem filter_type_items[] = {
+ static const EnumPropertyItem filter_type_items[] = {
{R_FILTER_BOX, "FLAT", 0, "Flat", ""},
{R_FILTER_TENT, "TENT", 0, "Tent", ""},
{R_FILTER_QUAD, "QUAD", 0, "Quadratic", ""},
@@ -4459,7 +4578,7 @@ static void def_cmp_blur(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem aspect_correction_type_items[] = {
+ static const EnumPropertyItem aspect_correction_type_items[] = {
{CMP_NODE_BLUR_ASPECT_NONE, "NONE", 0, "None", ""},
{CMP_NODE_BLUR_ASPECT_Y, "Y", 0, "Y", ""},
{CMP_NODE_BLUR_ASPECT_X, "X", 0, "X", ""},
@@ -4646,7 +4765,7 @@ static void def_cmp_levels(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem channel_items[] = {
+ static const EnumPropertyItem channel_items[] = {
{1, "COMBINED_RGB", 0, "C", "Combined RGB"},
{2, "RED", 0, "R", "Red Channel"},
{3, "GREEN", 0, "G", "Green Channel"},
@@ -4730,7 +4849,7 @@ static void def_cmp_image(StructRNA *srna)
PropertyRNA *prop;
#if 0
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{IMA_SRC_FILE, "IMAGE", 0, "Image", ""},
{IMA_SRC_MOVIE, "MOVIE", "Movie", ""},
{IMA_SRC_SEQUENCE, "SEQUENCE", "Sequence", ""},
@@ -4767,9 +4886,9 @@ static void def_cmp_render_layers(StructRNA *srna)
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_pointer_funcs(prop, NULL, "rna_Node_scene_set", NULL, NULL);
RNA_def_property_struct_type(prop, "Scene");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Scene", "");
- RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_scene_layer_update");
prop = RNA_def_property(srna, "layer", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "custom1");
@@ -4904,7 +5023,7 @@ static void def_cmp_dilate_erode(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem mode_items[] = {
+ static const EnumPropertyItem mode_items[] = {
{CMP_NODE_DILATEERODE_STEP, "STEP", 0, "Step", ""},
{CMP_NODE_DILATEERODE_DISTANCE_THRESH, "THRESHOLD", 0, "Threshold", ""},
{CMP_NODE_DILATEERODE_DISTANCE, "DISTANCE", 0, "Distance", ""},
@@ -4984,7 +5103,7 @@ static void def_cmp_scale(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem space_items[] = {
+ static const EnumPropertyItem space_items[] = {
{CMP_SCALE_RELATIVE, "RELATIVE", 0, "Relative", ""},
{CMP_SCALE_ABSOLUTE, "ABSOLUTE", 0, "Absolute", ""},
{CMP_SCALE_SCENEPERCENT, "SCENE_SIZE", 0, "Scene Size", ""},
@@ -5085,7 +5204,7 @@ static void def_cmp_distance_matte(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem color_space_items[] = {
+ static const EnumPropertyItem color_space_items[] = {
{1, "RGB", 0, "RGB", "RGB color space"},
{2, "YCC", 0, "YCC", "YCbCr Suppression"},
{0, NULL, 0, NULL, NULL}
@@ -5119,21 +5238,21 @@ static void def_cmp_color_spill(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem channel_items[] = {
+ static const EnumPropertyItem channel_items[] = {
{1, "R", 0, "R", "Red Spill Suppression"},
{2, "G", 0, "G", "Green Spill Suppression"},
{3, "B", 0, "B", "Blue Spill Suppression"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem limit_channel_items[] = {
+ static const EnumPropertyItem limit_channel_items[] = {
{0, "R", 0, "R", "Limit by Red"},
{1, "G", 0, "G", "Limit by Green"},
{2, "B", 0, "B", "Limit by Blue"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem algorithm_items[] = {
+ static const EnumPropertyItem algorithm_items[] = {
{0, "SIMPLE", 0, "Simple", "Simple Limit Algorithm"},
{1, "AVERAGE", 0, "Average", "Average Limit Algorithm"},
{0, NULL, 0, NULL, NULL}
@@ -5198,18 +5317,28 @@ static void def_cmp_luma_matte(StructRNA *srna)
prop = RNA_def_property(srna, "limit_max", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "t1");
RNA_def_property_float_funcs(prop, NULL, "rna_Matte_t1_set", NULL);
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_range(prop, 0, 1, 0.1f, 3);
RNA_def_property_ui_text(prop, "High", "Values higher than this setting are 100% opaque");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
prop = RNA_def_property(srna, "limit_min", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "t2");
RNA_def_property_float_funcs(prop, NULL, "rna_Matte_t2_set", NULL);
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_range(prop, 0, 1, 0.1f, 3);
RNA_def_property_ui_text(prop, "Low", "Values lower than this setting are 100% keyed");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
+static void def_cmp_brightcontrast(StructRNA *srna)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "use_premultiply", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "custom1", 1);
+ RNA_def_property_ui_text(prop, "Convert Premul", "Keep output image premultiplied alpha");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
+}
+
static void def_cmp_chroma_matte(StructRNA *srna)
{
PropertyRNA *prop;
@@ -5253,7 +5382,7 @@ static void def_cmp_channel_matte(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem color_space_items[] = {
+ static const EnumPropertyItem color_space_items[] = {
{CMP_NODE_CHANNEL_MATTE_CS_RGB, "RGB", 0, "RGB", "RGB Color Space"},
{CMP_NODE_CHANNEL_MATTE_CS_HSV, "HSV", 0, "HSV", "HSV Color Space"},
{CMP_NODE_CHANNEL_MATTE_CS_YUV, "YUV", 0, "YUV", "YUV Color Space"},
@@ -5261,7 +5390,7 @@ static void def_cmp_channel_matte(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem algorithm_items[] = {
+ static const EnumPropertyItem algorithm_items[] = {
{0, "SINGLE", 0, "Single", "Limit by single channel"},
{1, "MAX", 0, "Max", "Limit by max of other channels "},
{0, NULL, 0, NULL, NULL}
@@ -5298,14 +5427,14 @@ static void def_cmp_channel_matte(StructRNA *srna)
prop = RNA_def_property(srna, "limit_max", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "t1");
RNA_def_property_float_funcs(prop, NULL, "rna_Matte_t1_set", NULL);
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_range(prop, 0, 1, 0.1f, 3);
RNA_def_property_ui_text(prop, "High", "Values higher than this setting are 100% opaque");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
prop = RNA_def_property(srna, "limit_min", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "t2");
RNA_def_property_float_funcs(prop, NULL, "rna_Matte_t2_set", NULL);
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_range(prop, 0, 1, 0.1f, 3);
RNA_def_property_ui_text(prop, "Low", "Values lower than this setting are 100% keyed");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
@@ -5358,13 +5487,13 @@ static void def_cmp_double_edge_mask(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem BufEdgeMode_items[] = {
+ static const EnumPropertyItem BufEdgeMode_items[] = {
{0, "BLEED_OUT", 0, "Bleed Out", "Allow mask pixels to bleed along edges"},
{1, "KEEP_IN", 0, "Keep In", "Restrict mask pixels from touching edges"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem InnerEdgeMode_items[] = {
+ static const EnumPropertyItem InnerEdgeMode_items[] = {
{0, "ALL", 0, "All", "All pixels on inner mask edge are considered during mask calculation"},
{1, "ADJACENT_ONLY", 0, "Adjacent Only",
"Only inner mask pixels adjacent to outer mask pixels are considered during mask calculation"},
@@ -5399,7 +5528,7 @@ static void def_cmp_defocus(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem bokeh_items[] = {
+ static const EnumPropertyItem bokeh_items[] = {
{8, "OCTAGON", 0, "Octagonal", "8 sides"},
{7, "HEPTAGON", 0, "Heptagonal", "7 sides"},
{6, "HEXAGON", 0, "Hexagonal", "6 sides"},
@@ -5414,7 +5543,7 @@ static void def_cmp_defocus(StructRNA *srna)
RNA_def_property_pointer_sdna(prop, NULL, "id");
RNA_def_property_pointer_funcs(prop, NULL, "rna_Node_scene_set", NULL, NULL);
RNA_def_property_struct_type(prop, "Scene");
- RNA_def_property_flag(prop, PROP_EDITABLE);
+ RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Scene", "Scene from which to select the active camera (render scene if undefined)");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
@@ -5643,7 +5772,7 @@ static void def_cmp_premul_key(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{0, "STRAIGHT_TO_PREMUL", 0, "Straight to Premul", ""},
{1, "PREMUL_TO_STRAIGHT", 0, "Premul to Straight", ""},
{0, NULL, 0, NULL, NULL}
@@ -5661,7 +5790,7 @@ static void def_cmp_glare(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{3, "GHOSTS", 0, "Ghosts", ""},
{2, "STREAKS", 0, "Streaks", ""},
{1, "FOG_GLOW", 0, "Fog Glow", ""},
@@ -5669,7 +5798,7 @@ static void def_cmp_glare(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem quality_items[] = {
+ static const EnumPropertyItem quality_items[] = {
{0, "HIGH", 0, "High", ""},
{1, "MEDIUM", 0, "Medium", ""},
{2, "LOW", 0, "Low", ""},
@@ -5757,7 +5886,7 @@ static void def_cmp_tonemap(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{1, "RD_PHOTORECEPTOR", 0, "R/D Photoreceptor", ""},
{0, "RH_SIMPLE", 0, "Rh Simple", ""},
{0, NULL, 0, NULL, NULL}
@@ -5844,7 +5973,7 @@ static void def_cmp_colorbalance(StructRNA *srna)
PropertyRNA *prop;
static float default_1[3] = {1.f, 1.f, 1.f};
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{0, "LIFT_GAMMA_GAIN", 0, "Lift/Gamma/Gain", ""},
{1, "OFFSET_POWER_SLOPE", 0, "Offset/Power/Slope (ASC-CDL)", "ASC-CDL standard color correction"},
{0, NULL, 0, NULL, NULL}
@@ -5993,7 +6122,7 @@ static void def_cmp_moviedistortion(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem distortion_type_items[] = {
+ static const EnumPropertyItem distortion_type_items[] = {
{0, "UNDISTORT", 0, "Undistort", ""},
{1, "DISTORT", 0, "Distort", ""},
{0, NULL, 0, NULL, NULL}
@@ -6017,7 +6146,7 @@ static void def_cmp_mask(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem aspect_type_items[] = {
+ static const EnumPropertyItem aspect_type_items[] = {
{0, "SCENE", 0, "Scene Size", ""},
{CMP_NODEFLAG_MASK_FIXED, "FIXED", 0, "Fixed", "Use pixel size for the buffer"},
{CMP_NODEFLAG_MASK_FIXED_SCENE, "FIXED_SCENE", 0, "Fixed/Scene", "Pixel size scaled by scene percentage"},
@@ -6091,7 +6220,7 @@ static void dev_cmd_transform(StructRNA *srna)
/* -- Compositor Nodes ------------------------------------------------------ */
-static EnumPropertyItem node_masktype_items[] = {
+static const EnumPropertyItem node_masktype_items[] = {
{0, "ADD", 0, "Add", ""},
{1, "SUBTRACT", 0, "Subtract", ""},
{2, "MULTIPLY", 0, "Multiply", ""},
@@ -6281,14 +6410,8 @@ static void def_cmp_switch(StructRNA *srna)
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
-static void def_cmp_switch_view(StructRNA *srna)
+static void def_cmp_switch_view(StructRNA *UNUSED(srna))
{
- PropertyRNA *prop;
-
- prop = RNA_def_property(srna, "check", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "custom1", 0);
- RNA_def_property_ui_text(prop, "Switch", "Off: first socket, On: second socket");
- RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_Node_update");
}
static void def_cmp_colorcorrection(StructRNA *srna)
@@ -6473,7 +6596,7 @@ static void def_cmp_colorcorrection(StructRNA *srna)
static void def_cmp_viewer(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem tileorder_items[] = {
+ static const EnumPropertyItem tileorder_items[] = {
{0, "CENTEROUT", 0, "Center", "Expand from center"},
{1, "RANDOM", 0, "Random", "Random tiles"},
{2, "BOTTOMUP", 0, "Bottom up", "Expand from bottom"},
@@ -6620,7 +6743,7 @@ static void def_cmp_trackpos(StructRNA *srna)
{
PropertyRNA *prop;
- static EnumPropertyItem position_items[] = {
+ static const EnumPropertyItem position_items[] = {
{CMP_TRACKPOS_ABSOLUTE, "ABSOLUTE", 0,
"Absolute", "Output absolute position of a marker"},
{CMP_TRACKPOS_RELATIVE_START, "RELATIVE_START", 0,
@@ -6665,7 +6788,7 @@ static void def_cmp_trackpos(StructRNA *srna)
static void def_cmp_translate(StructRNA *srna)
{
- static EnumPropertyItem translate_items[] = {
+ static const EnumPropertyItem translate_items[] = {
{CMP_NODE_WRAP_NONE, "NONE", 0, "None", "No wrapping on X and Y"},
{CMP_NODE_WRAP_X, "XAXIS", 0, "X Axis", "Wrap all pixels on the X axis"},
{CMP_NODE_WRAP_Y, "YAXIS", 0, "Y Axis", "Wrap all pixels on the Y axis"},
@@ -6935,6 +7058,13 @@ static void rna_def_node_socket(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Type", "Data type");
RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeSocket_update");
+ prop = RNA_def_property(srna, "draw_shape", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "draw_shape");
+ RNA_def_property_enum_items(prop, rna_enum_node_socket_draw_shape_items);
+ RNA_def_property_enum_default(prop, SOCK_DRAW_SHAPE_CIRCLE);
+ RNA_def_property_ui_text(prop, "Shape", "Socket shape");
+ RNA_def_property_update(prop, NC_NODE | NA_EDITED, "rna_NodeSocket_update");
+
/* registration */
prop = RNA_def_property(srna, "bl_idname", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "typeinfo->idname");
@@ -7614,11 +7744,11 @@ static void rna_def_node(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem dummy_static_type_items[] = {
+ static const EnumPropertyItem dummy_static_type_items[] = {
{NODE_CUSTOM, "CUSTOM", 0, "Custom", "Custom Node"},
{0, NULL, 0, NULL, NULL}};
- static EnumPropertyItem node_shading_compatibilities[] = {
+ static const EnumPropertyItem node_shading_compatibilities[] = {
{NODE_OLD_SHADING, "OLD_SHADING", 0, "Old Shading", "Old shading system compatibility"},
{NODE_NEW_SHADING, "NEW_SHADING", 0, "New Shading", "New shading system compatibility"},
{0, NULL, 0, NULL, NULL}
@@ -8075,7 +8205,7 @@ static void rna_def_nodetree(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem static_type_items[] = {
+ static const EnumPropertyItem static_type_items[] = {
{NTREE_SHADER, "SHADER", ICON_MATERIAL, "Shader", "Shader nodes"},
{NTREE_TEXTURE, "TEXTURE", ICON_TEXTURE, "Texture", "Texture nodes"},
{NTREE_COMPOSIT, "COMPOSITING", ICON_RENDERLAYERS, "Compositing", "Compositing nodes"},
diff --git a/source/blender/makesrna/intern/rna_object.c b/source/blender/makesrna/intern/rna_object.c
index 0cffba47f16..84318b7124a 100644
--- a/source/blender/makesrna/intern/rna_object.c
+++ b/source/blender/makesrna/intern/rna_object.c
@@ -33,7 +33,7 @@
#include "DNA_group_types.h"
#include "DNA_material_types.h"
#include "DNA_mesh_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_property_types.h"
#include "DNA_scene_types.h"
@@ -44,6 +44,7 @@
#include "BKE_camera.h"
#include "BKE_paint.h"
+#include "BKE_editlattice.h"
#include "BKE_editmesh.h"
#include "BKE_group.h" /* needed for BKE_group_object_exists() */
#include "BKE_object_deform.h"
@@ -60,7 +61,7 @@
#include "WM_api.h"
#include "WM_types.h"
-EnumPropertyItem rna_enum_object_mode_items[] = {
+const EnumPropertyItem rna_enum_object_mode_items[] = {
{OB_MODE_OBJECT, "OBJECT", ICON_OBJECT_DATAMODE, "Object Mode", ""},
{OB_MODE_EDIT, "EDIT", ICON_EDITMODE_HLT, "Edit Mode", ""},
{OB_MODE_POSE, "POSE", ICON_POSE_HLT, "Pose Mode", ""},
@@ -73,7 +74,7 @@ EnumPropertyItem rna_enum_object_mode_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_object_empty_drawtype_items[] = {
+const EnumPropertyItem rna_enum_object_empty_drawtype_items[] = {
{OB_PLAINAXES, "PLAIN_AXES", 0, "Plain Axes", ""},
{OB_ARROWS, "ARROWS", 0, "Arrows", ""},
{OB_SINGLE_ARROW, "SINGLE_ARROW", 0, "Single Arrow", ""},
@@ -86,7 +87,7 @@ EnumPropertyItem rna_enum_object_empty_drawtype_items[] = {
};
-static EnumPropertyItem parent_type_items[] = {
+static const EnumPropertyItem parent_type_items[] = {
{PAROBJECT, "OBJECT", 0, "Object", "The object is parented to an object"},
{PARSKEL, "ARMATURE", 0, "Armature", ""},
{PARSKEL, "LATTICE", 0, "Lattice", "The object is parented to a lattice"}, /* PARSKEL reuse will give issues */
@@ -97,7 +98,7 @@ static EnumPropertyItem parent_type_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem dupli_items[] = {
+static const EnumPropertyItem dupli_items[] = {
{0, "NONE", 0, "None", ""},
{OB_DUPLIFRAMES, "FRAMES", 0, "Frames", "Make copy of object for every frame"},
{OB_DUPLIVERTS, "VERTS", 0, "Verts", "Duplicate child objects on all vertices"},
@@ -107,7 +108,7 @@ static EnumPropertyItem dupli_items[] = {
};
#endif
-static EnumPropertyItem collision_bounds_items[] = {
+static const EnumPropertyItem collision_bounds_items[] = {
{OB_BOUND_BOX, "BOX", ICON_MESH_CUBE, "Box", ""},
{OB_BOUND_SPHERE, "SPHERE", ICON_MESH_UVSPHERE, "Sphere", ""},
{OB_BOUND_CYLINDER, "CYLINDER", ICON_MESH_CYLINDER, "Cylinder", ""},
@@ -119,7 +120,7 @@ static EnumPropertyItem collision_bounds_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_metaelem_type_items[] = {
+const EnumPropertyItem rna_enum_metaelem_type_items[] = {
{MB_BALL, "BALL", ICON_META_BALL, "Ball", ""},
{MB_TUBE, "CAPSULE", ICON_META_CAPSULE, "Capsule", ""},
{MB_PLANE, "PLANE", ICON_META_PLANE, "Plane", ""},
@@ -133,7 +134,7 @@ EnumPropertyItem rna_enum_metaelem_type_items[] = {
#define OBTYPE_CU_SURF {OB_SURF, "SURFACE", 0, "Surface", ""}
#define OBTYPE_CU_FONT {OB_FONT, "FONT", 0, "Font", ""}
-EnumPropertyItem rna_enum_object_type_items[] = {
+const EnumPropertyItem rna_enum_object_type_items[] = {
{OB_MESH, "MESH", 0, "Mesh", ""},
OBTYPE_CU_CURVE,
OBTYPE_CU_SURF,
@@ -150,14 +151,14 @@ EnumPropertyItem rna_enum_object_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_object_type_curve_items[] = {
+const EnumPropertyItem rna_enum_object_type_curve_items[] = {
OBTYPE_CU_CURVE,
OBTYPE_CU_SURF,
OBTYPE_CU_FONT,
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_object_axis_items[] = {
+const EnumPropertyItem rna_enum_object_axis_items[] = {
{OB_POSX, "POS_X", 0, "+X", ""},
{OB_POSY, "POS_Y", 0, "+Y", ""},
{OB_POSZ, "POS_Z", 0, "+Z", ""},
@@ -202,6 +203,12 @@ static void rna_Object_internal_update(Main *UNUSED(bmain), Scene *UNUSED(scene)
DAG_id_tag_update(ptr->id.data, OB_RECALC_OB);
}
+static void rna_Object_internal_update_draw(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
+{
+ DAG_id_tag_update(ptr->id.data, OB_RECALC_OB);
+ WM_main_add_notifier(NC_OBJECT | ND_DRAW, ptr->id.data);
+}
+
static void rna_Object_matrix_world_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
/* don't use compat so we get predictable rotation */
@@ -267,7 +274,7 @@ static void rna_Object_active_shape_update(Main *bmain, Scene *scene, PointerRNA
switch (ob->type) {
case OB_MESH:
EDBM_mesh_load(ob);
- EDBM_mesh_make(scene->toolsettings, ob, true);
+ EDBM_mesh_make(ob, scene->toolsettings->selectmode, true);
DAG_id_tag_update(ob->data, 0);
@@ -280,8 +287,8 @@ static void rna_Object_active_shape_update(Main *bmain, Scene *scene, PointerRNA
ED_curve_editnurb_make(ob);
break;
case OB_LATTICE:
- ED_lattice_editlatt_load(ob);
- ED_lattice_editlatt_make(ob);
+ BKE_editlattice_load(ob);
+ BKE_editlattice_make(ob);
break;
}
}
@@ -432,11 +439,7 @@ static void rna_Object_parent_set(PointerRNA *ptr, PointerRNA value)
{
Object *ob = (Object *)ptr->data;
Object *par = (Object *)value.data;
-
-#ifdef FREE_WINDOWS
- /* NOTE: this dummy check here prevents this method causing weird runtime errors on mingw 4.6.2 */
- if (ob)
-#endif
+
{
ED_object_parent(ob, par, ob->partype, ob->parsubstr);
}
@@ -449,7 +452,7 @@ static void rna_Object_parent_type_set(PointerRNA *ptr, int value)
ED_object_parent(ob, ob->parent, value, ob->parsubstr);
}
-static EnumPropertyItem *rna_Object_parent_type_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Object_parent_type_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = (Object *)ptr->data;
@@ -490,7 +493,7 @@ static void rna_Object_empty_draw_type_set(PointerRNA *ptr, int value)
BKE_object_empty_draw_type_set(ob, value);
}
-static EnumPropertyItem *rna_Object_collision_bounds_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Object_collision_bounds_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = (Object *)ptr->data;
@@ -532,8 +535,9 @@ static void rna_Object_dup_group_set(PointerRNA *ptr, PointerRNA value)
* thus causing a cycle/infinite-recursion leading to crashes on load [#25298]
*/
if (BKE_group_object_exists(grp, ob) == 0) {
+ id_us_min(&ob->dup_group->id);
ob->dup_group = grp;
- id_lib_extern((ID *)grp);
+ id_us_plus(&ob->dup_group->id);
}
else {
BKE_report(NULL, RPT_ERROR,
@@ -718,10 +722,10 @@ static int rna_Object_active_material_editable(PointerRNA *ptr, const char **UNU
bool is_editable;
if ((ob->matbits == NULL) || (ob->actcol == 0) || ob->matbits[ob->actcol - 1]) {
- is_editable = !ID_IS_LINKED_DATABLOCK(ob);
+ is_editable = !ID_IS_LINKED(ob);
}
else {
- is_editable = ob->data ? !ID_IS_LINKED_DATABLOCK(ob->data) : false;
+ is_editable = ob->data ? !ID_IS_LINKED(ob->data) : false;
}
return is_editable ? PROP_EDITABLE : 0;
@@ -1321,8 +1325,12 @@ static void rna_Object_active_constraint_set(PointerRNA *ptr, PointerRNA value)
static bConstraint *rna_Object_constraints_new(Object *object, int type)
{
+ bConstraint *new_con = BKE_constraint_add_for_object(object, NULL, type);
+
+ ED_object_constraint_tag_update(object, new_con);
WM_main_add_notifier(NC_OBJECT | ND_CONSTRAINT | NA_ADDED, object);
- return BKE_constraint_add_for_object(object, NULL, type);
+
+ return new_con;
}
static void rna_Object_constraints_remove(Object *object, ReportList *reports, PointerRNA *con_ptr)
@@ -1523,7 +1531,7 @@ static void rna_def_vertex_group(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem assign_mode_items[] = {
+ static const EnumPropertyItem assign_mode_items[] = {
{WEIGHT_REPLACE, "REPLACE", 0, "Replace", "Replace"},
{WEIGHT_ADD, "ADD", 0, "Add", "Add"},
{WEIGHT_SUBTRACT, "SUBTRACT", 0, "Subtract", "Subtract"},
@@ -1585,7 +1593,7 @@ static void rna_def_material_slot(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem link_items[] = {
+ static const EnumPropertyItem link_items[] = {
{1, "OBJECT", 0, "Object", ""},
{0, "DATA", 0, "Data", ""},
{0, NULL, 0, NULL, NULL}
@@ -1626,7 +1634,7 @@ static void rna_def_object_game_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem body_type_items[] = {
+ static const EnumPropertyItem body_type_items[] = {
{OB_BODY_TYPE_NO_COLLISION, "NO_COLLISION", 0, "No Collision", "Disable collision for this object"},
{OB_BODY_TYPE_STATIC, "STATIC", 0, "Static", "Stationary object"},
{OB_BODY_TYPE_DYNAMIC, "DYNAMIC", 0, "Dynamic", "Linear physics"},
@@ -2161,14 +2169,14 @@ static void rna_def_object(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem up_items[] = {
+ static const EnumPropertyItem up_items[] = {
{OB_POSX, "X", 0, "X", ""},
{OB_POSY, "Y", 0, "Y", ""},
{OB_POSZ, "Z", 0, "Z", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem drawtype_items[] = {
+ static const EnumPropertyItem drawtype_items[] = {
{OB_BOUNDBOX, "BOUNDS", 0, "Bounds", "Draw the bounds of the object"},
{OB_WIRE, "WIRE", 0, "Wire", "Draw the object as a wireframe"},
{OB_SOLID, "SOLID", 0, "Solid", "Draw the object as a solid (if solid drawing is enabled in the viewport)"},
@@ -2177,7 +2185,7 @@ static void rna_def_object(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem boundtype_items[] = {
+ static const EnumPropertyItem boundtype_items[] = {
{OB_BOUND_BOX, "BOX", 0, "Box", "Draw bounds as box"},
{OB_BOUND_SPHERE, "SPHERE", 0, "Sphere", "Draw bounds as sphere"},
{OB_BOUND_CYLINDER, "CYLINDER", 0, "Cylinder", "Draw bounds as cylinder"},
@@ -2189,7 +2197,7 @@ static void rna_def_object(BlenderRNA *brna)
/* XXX: this RNA enum define is currently duplicated for objects,
* since there is some text here which is not applicable */
- static EnumPropertyItem prop_rotmode_items[] = {
+ static const EnumPropertyItem prop_rotmode_items[] = {
{ROT_MODE_QUAT, "QUATERNION", 0, "Quaternion (WXYZ)", "No Gimbal Lock"},
{ROT_MODE_XYZ, "XYZ", 0, "XYZ Euler", "XYZ Rotation Order - prone to Gimbal Lock (default)"},
{ROT_MODE_XZY, "XZY", 0, "XZY Euler", "XZY Rotation Order - prone to Gimbal Lock"},
@@ -2391,7 +2399,7 @@ static void rna_def_object(BlenderRNA *brna)
/* only for the transform-panel and conflicts with animating scale */
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_float_funcs(prop, "rna_Object_dimensions_get", "rna_Object_dimensions_set", NULL);
- RNA_def_property_ui_range(prop, 0.0f, FLT_MAX, 1, 3);
+ RNA_def_property_ui_range(prop, 0.0f, FLT_MAX, 1, RNA_TRANSLATION_PREC_DEFAULT);
RNA_def_property_ui_text(prop, "Dimensions", "Absolute bounding box dimensions of the object");
RNA_def_property_update(prop, NC_OBJECT | ND_TRANSFORM, "rna_Object_internal_update");
@@ -2561,7 +2569,7 @@ static void rna_def_object(BlenderRNA *brna)
prop = RNA_def_property(srna, "pass_index", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "index");
RNA_def_property_ui_text(prop, "Pass Index", "Index number for the \"Object Index\" render pass");
- RNA_def_property_update(prop, NC_OBJECT, "rna_Object_internal_update");
+ RNA_def_property_update(prop, NC_OBJECT, "rna_Object_internal_update_draw");
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR);
RNA_def_property_float_sdna(prop, NULL, "col");
@@ -2893,6 +2901,10 @@ static void rna_def_dupli_object(BlenderRNA *brna)
RNA_def_property_enum_items(prop, dupli_items);
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE | PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Dupli Type", "Duplicator type that generated this dupli object");
+
+ prop = RNA_def_property(srna, "random_id", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE | PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Dupli random id", "Random id for this dupli object");
}
static void rna_def_object_base(BlenderRNA *brna)
diff --git a/source/blender/makesrna/intern/rna_object_api.c b/source/blender/makesrna/intern/rna_object_api.c
index c680abe71a4..be63fc4abc8 100644
--- a/source/blender/makesrna/intern/rna_object_api.c
+++ b/source/blender/makesrna/intern/rna_object_api.c
@@ -47,7 +47,7 @@
#include "rna_internal.h" /* own include */
-static EnumPropertyItem space_items[] = {
+static const EnumPropertyItem space_items[] = {
{CONSTRAINT_SPACE_WORLD, "WORLD", 0, "World Space",
"The most gobal space in Blender"},
{CONSTRAINT_SPACE_POSE, "POSE", 0, "Pose Space",
@@ -91,7 +91,7 @@ static EnumPropertyItem space_items[] = {
#include "DEG_depsgraph.h"
/* Convert a given matrix from a space to another (using the object and/or a bone as reference). */
-static void rna_Scene_mat_convert_space(Object *ob, ReportList *reports, bPoseChannel *pchan,
+static void rna_Object_mat_convert_space(Object *ob, ReportList *reports, bPoseChannel *pchan,
float *mat, float *mat_ret, int from, int to)
{
copy_m4_m4((float (*)[4])mat_ret, (float (*)[4])mat);
@@ -321,49 +321,55 @@ static void rna_Object_ray_cast(
float origin[3], float direction[3], float distance,
int *r_success, float r_location[3], float r_normal[3], int *r_index)
{
- BVHTreeFromMesh treeData = {NULL};
-
+ bool success = false;
+
if (ob->derivedFinal == NULL) {
BKE_reportf(reports, RPT_ERROR, "Object '%s' has no mesh data to be used for ray casting", ob->id.name + 2);
return;
}
- /* no need to managing allocation or freeing of the BVH data. this is generated and freed as needed */
- bvhtree_from_mesh_looptri(&treeData, ob->derivedFinal, 0.0f, 4, 6);
+ /* Test BoundBox first (efficiency) */
+ BoundBox *bb = BKE_object_boundbox_get(ob);
+ float distmin;
+ if (!bb || (isect_ray_aabb_v3_simple(origin, direction, bb->vec[0], bb->vec[6], &distmin, NULL) && distmin <= distance)) {
- /* may fail if the mesh has no faces, in that case the ray-cast misses */
- if (treeData.tree != NULL) {
- BVHTreeRayHit hit;
+ BVHTreeFromMesh treeData = {NULL};
- hit.index = -1;
- hit.dist = distance;
-
- normalize_v3(direction);
+ /* no need to managing allocation or freeing of the BVH data. this is generated and freed as needed */
+ bvhtree_from_mesh_looptri(&treeData, ob->derivedFinal, 0.0f, 4, 6);
+
+ /* may fail if the mesh has no faces, in that case the ray-cast misses */
+ if (treeData.tree != NULL) {
+ BVHTreeRayHit hit;
+
+ hit.index = -1;
+ hit.dist = distance;
+ normalize_v3(direction);
- if (BLI_bvhtree_ray_cast(treeData.tree, origin, direction, 0.0f, &hit,
- treeData.raycast_callback, &treeData) != -1)
- {
- if (hit.dist <= distance) {
- *r_success = true;
- copy_v3_v3(r_location, hit.co);
- copy_v3_v3(r_normal, hit.no);
- *r_index = dm_looptri_to_poly_index(ob->derivedFinal, &treeData.looptri[hit.index]);
+ if (BLI_bvhtree_ray_cast(treeData.tree, origin, direction, 0.0f, &hit,
+ treeData.raycast_callback, &treeData) != -1)
+ {
+ if (hit.dist <= distance) {
+ *r_success = success = true;
- goto finally;
+ copy_v3_v3(r_location, hit.co);
+ copy_v3_v3(r_normal, hit.no);
+ *r_index = dm_looptri_to_poly_index(ob->derivedFinal, &treeData.looptri[hit.index]);
+ }
}
+
+ free_bvhtree_from_mesh(&treeData);
}
}
+ if (success == false) {
+ *r_success = false;
- *r_success = false;
-
- zero_v3(r_location);
- zero_v3(r_normal);
- *r_index = -1;
-
-finally:
- free_bvhtree_from_mesh(&treeData);
+ zero_v3(r_location);
+ zero_v3(r_normal);
+ *r_index = -1;
+ }
}
static void rna_Object_closest_point_on_mesh(
@@ -470,10 +476,7 @@ void rna_Object_dm_info(struct Object *ob, int type, char *result)
static int rna_Object_update_from_editmode(Object *ob)
{
- if (ob->mode & OB_MODE_EDIT) {
- return ED_object_editmode_load(ob);
- }
- return false;
+ return ED_object_editmode_load(ob);
}
#else /* RNA_RUNTIME */
@@ -482,13 +485,13 @@ void RNA_api_object(StructRNA *srna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem mesh_type_items[] = {
+ static const EnumPropertyItem mesh_type_items[] = {
{eModifierMode_Realtime, "PREVIEW", 0, "Preview", "Apply modifier preview settings"},
{eModifierMode_Render, "RENDER", 0, "Render", "Apply modifier render settings"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem dupli_eval_mode_items[] = {
+ static const EnumPropertyItem dupli_eval_mode_items[] = {
{DAG_EVAL_VIEWPORT, "VIEWPORT", 0, "Viewport", "Generate duplis using viewport settings"},
{DAG_EVAL_PREVIEW, "PREVIEW", 0, "Preview", "Generate duplis using preview settings"},
{DAG_EVAL_RENDER, "RENDER", 0, "Render", "Generate duplis using render settings"},
@@ -496,7 +499,7 @@ void RNA_api_object(StructRNA *srna)
};
#ifndef NDEBUG
- static EnumPropertyItem mesh_dm_info_items[] = {
+ static const EnumPropertyItem mesh_dm_info_items[] = {
{0, "SOURCE", 0, "Source", "Source mesh"},
{1, "DEFORM", 0, "Deform", "Objects deform mesh"},
{2, "FINAL", 0, "Final", "Objects final mesh"},
@@ -505,7 +508,7 @@ void RNA_api_object(StructRNA *srna)
#endif
/* Matrix space conversion */
- func = RNA_def_function(srna, "convert_space", "rna_Scene_mat_convert_space");
+ func = RNA_def_function(srna, "convert_space", "rna_Object_mat_convert_space");
RNA_def_function_ui_description(func, "Convert (transform) the given matrix from one space to another");
RNA_def_function_flag(func, FUNC_USE_REPORTS);
parm = RNA_def_pointer(func, "pose_bone", "PoseBone", "",
diff --git a/source/blender/makesrna/intern/rna_object_force.c b/source/blender/makesrna/intern/rna_object_force.c
index 1d89f7535c4..c9c3372000f 100644
--- a/source/blender/makesrna/intern/rna_object_force.c
+++ b/source/blender/makesrna/intern/rna_object_force.c
@@ -28,7 +28,7 @@
#include "DNA_cloth_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_smoke_types.h"
@@ -41,7 +41,7 @@
#include "WM_api.h"
#include "WM_types.h"
-static EnumPropertyItem effector_shape_items[] = {
+static const EnumPropertyItem effector_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{PFIELD_SHAPE_SURFACE, "SURFACE", 0, "Surface", ""},
@@ -55,20 +55,20 @@ static EnumPropertyItem effector_shape_items[] = {
/* type specific return values only used from functions */
-static EnumPropertyItem curve_shape_items[] = {
+static const EnumPropertyItem curve_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{PFIELD_SHAPE_SURFACE, "SURFACE", 0, "Curve", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem empty_shape_items[] = {
+static const EnumPropertyItem empty_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem vortex_shape_items[] = {
+static const EnumPropertyItem vortex_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{PFIELD_SHAPE_SURFACE, "SURFACE", 0, "Surface falloff (New)", ""},
@@ -76,14 +76,14 @@ static EnumPropertyItem vortex_shape_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem curve_vortex_shape_items[] = {
+static const EnumPropertyItem curve_vortex_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{PFIELD_SHAPE_SURFACE, "SURFACE", 0, "Curve (New)", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem empty_vortex_shape_items[] = {
+static const EnumPropertyItem empty_vortex_shape_items[] = {
{PFIELD_SHAPE_POINT, "POINT", 0, "Point", ""},
{PFIELD_SHAPE_PLANE, "PLANE", 0, "Plane", ""},
{0, NULL, 0, NULL, NULL}
@@ -736,7 +736,7 @@ static void rna_softbody_dependency_update(Main *bmain, Scene *scene, PointerRNA
rna_softbody_update(bmain, scene, ptr);
}
-static EnumPropertyItem *rna_Effector_shape_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Effector_shape_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
Object *ob = NULL;
@@ -768,50 +768,23 @@ static EnumPropertyItem *rna_Effector_shape_itemf(bContext *UNUSED(C), PointerRN
#else
-/* ptcache.point_caches */
-static void rna_def_ptcache_point_caches(BlenderRNA *brna, PropertyRNA *cprop)
+static void rna_def_pointcache_common(StructRNA *srna)
{
- StructRNA *srna;
PropertyRNA *prop;
- /* FunctionRNA *func; */
- /* PropertyRNA *parm; */
-
- RNA_def_property_srna(cprop, "PointCaches");
- srna = RNA_def_struct(brna, "PointCaches", NULL);
- RNA_def_struct_sdna(srna, "PointCache");
- RNA_def_struct_ui_text(srna, "Point Caches", "Collection of point caches");
-
- prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_UNSIGNED);
- RNA_def_property_int_funcs(prop, "rna_Cache_active_point_cache_index_get",
- "rna_Cache_active_point_cache_index_set",
- "rna_Cache_active_point_cache_index_range");
- RNA_def_property_ui_text(prop, "Active Point Cache Index", "");
- RNA_def_property_update(prop, NC_OBJECT, "rna_Cache_change");
-}
-
-static void rna_def_pointcache(BlenderRNA *brna)
-{
- StructRNA *srna;
- PropertyRNA *prop;
-
- static EnumPropertyItem point_cache_compress_items[] = {
+ static const EnumPropertyItem point_cache_compress_items[] = {
{PTCACHE_COMPRESS_NO, "NO", 0, "No", "No compression"},
{PTCACHE_COMPRESS_LZO, "LIGHT", 0, "Light", "Fast but not so effective compression"},
{PTCACHE_COMPRESS_LZMA, "HEAVY", 0, "Heavy", "Effective but slow compression"},
{0, NULL, 0, NULL, NULL}
};
- srna = RNA_def_struct(brna, "PointCache", NULL);
- RNA_def_struct_ui_text(srna, "Point Cache", "Point cache for physics simulations");
- RNA_def_struct_ui_icon(srna, ICON_PHYSICS);
-
prop = RNA_def_property(srna, "frame_start", PROP_INT, PROP_TIME);
RNA_def_property_int_sdna(prop, NULL, "startframe");
RNA_def_property_range(prop, -MAXFRAME, MAXFRAME);
RNA_def_property_ui_range(prop, 1, MAXFRAME, 1, 1);
RNA_def_property_ui_text(prop, "Start", "Frame on which the simulation starts");
-
+
prop = RNA_def_property(srna, "frame_end", PROP_INT, PROP_TIME);
RNA_def_property_int_sdna(prop, NULL, "endframe");
RNA_def_property_range(prop, 1, MAXFRAME);
@@ -892,13 +865,59 @@ static void rna_def_pointcache(BlenderRNA *brna)
"Use this file's path for the disk cache when library linked into another file "
"(for local bakes per scene file, disable this option)");
RNA_def_property_update(prop, NC_OBJECT, "rna_Cache_idname_change");
+}
+
+static void rna_def_ptcache_point_caches(BlenderRNA *brna, PropertyRNA *cprop)
+{
+ StructRNA *srna;
+ PropertyRNA *prop;
+ /* FunctionRNA *func; */
+ /* PropertyRNA *parm; */
+
+ RNA_def_property_srna(cprop, "PointCaches");
+ srna = RNA_def_struct(brna, "PointCaches", NULL);
+ RNA_def_struct_sdna(srna, "PointCache");
+ RNA_def_struct_ui_text(srna, "Point Caches", "Collection of point caches");
+
+ prop = RNA_def_property(srna, "active_index", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_int_funcs(prop, "rna_Cache_active_point_cache_index_get",
+ "rna_Cache_active_point_cache_index_set",
+ "rna_Cache_active_point_cache_index_range");
+ RNA_def_property_ui_text(prop, "Active Point Cache Index", "");
+ RNA_def_property_update(prop, NC_OBJECT, "rna_Cache_change");
+
+ /* And define another RNA type for those collection items. */
+ srna = RNA_def_struct(brna, "PointCacheItem", NULL);
+ RNA_def_struct_sdna(srna, "PointCache");
+ RNA_def_struct_ui_text(srna, "Point Cache", "point cache for physics simulations");
+ RNA_def_struct_ui_icon(srna, ICON_PHYSICS);
+
+ rna_def_pointcache_common(srna);
+}
+
+static void rna_def_pointcache_active(BlenderRNA *brna)
+{
+ StructRNA *srna;
+ PropertyRNA *prop;
+
+ srna = RNA_def_struct(brna, "PointCache", NULL);
+ RNA_def_struct_ui_text(srna, "Active Point Cache", "Active point cache for physics simulations");
+ RNA_def_struct_ui_icon(srna, ICON_PHYSICS);
+
+ rna_def_pointcache_common(srna);
+
+ /* This first-level RNA pointer also has list of all caches from owning ID.
+ * Those caches items have exact same content as 'active' one, except for that collection,
+ * to prevent ugly recursive layout pattern.
+ * Note: This shall probably be redone from scratch in a proper way at some poitn, but for now that will do,
+ * and shall not break anything in the API. */
prop = RNA_def_property(srna, "point_caches", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_funcs(prop, "rna_Cache_list_begin", "rna_iterator_listbase_next",
"rna_iterator_listbase_end", "rna_iterator_listbase_get",
NULL, NULL, NULL, NULL);
- RNA_def_property_struct_type(prop, "PointCache");
- RNA_def_property_ui_text(prop, "Point Cache List", "Point cache list");
+ RNA_def_property_struct_type(prop, "PointCacheItem");
+ RNA_def_property_ui_text(prop, "Point Cache List", "");
rna_def_ptcache_point_caches(brna, prop);
}
@@ -1123,7 +1142,7 @@ static void rna_def_field(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem field_type_items[] = {
+ static const EnumPropertyItem field_type_items[] = {
{0, "NONE", 0, "None", ""},
{PFIELD_FORCE, "FORCE", ICON_FORCE_FORCE, "Force", "Radial field toward the center of object"},
{PFIELD_WIND, "WIND", ICON_FORCE_WIND, "Wind", "Constant force along the force object's local Z axis"},
@@ -1146,28 +1165,28 @@ static void rna_def_field(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem falloff_items[] = {
+ static const EnumPropertyItem falloff_items[] = {
{PFIELD_FALL_SPHERE, "SPHERE", 0, "Sphere", ""},
{PFIELD_FALL_TUBE, "TUBE", 0, "Tube", ""},
{PFIELD_FALL_CONE, "CONE", 0, "Cone", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem texture_items[] = {
+ static const EnumPropertyItem texture_items[] = {
{PFIELD_TEX_RGB, "RGB", 0, "RGB", ""},
{PFIELD_TEX_GRAD, "GRADIENT", 0, "Gradient", ""},
{PFIELD_TEX_CURL, "CURL", 0, "Curl", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem zdirection_items[] = {
+ static const EnumPropertyItem zdirection_items[] = {
{PFIELD_Z_BOTH, "BOTH", 0, "Both Z", ""},
{PFIELD_Z_POS, "POSITIVE", 0, "+Z", ""},
{PFIELD_Z_NEG, "NEGATIVE", 0, "-Z", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem guide_kink_items[] = {
+ static const EnumPropertyItem guide_kink_items[] = {
{0, "NONE", 0, "Nothing", ""},
{1, "CURL", 0, "Curl", ""},
{2, "RADIAL", 0, "Radial", ""},
@@ -1262,7 +1281,8 @@ static void rna_def_field(BlenderRNA *brna)
prop = RNA_def_property(srna, "size", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "f_size");
- RNA_def_property_range(prop, 0.0f, 10.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
+ RNA_def_property_ui_range(prop, 0.0f, 10.0f, 1.0f, 3);
RNA_def_property_ui_text(prop, "Size", "Size of the turbulence");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
@@ -1275,7 +1295,7 @@ static void rna_def_field(BlenderRNA *brna)
prop = RNA_def_property(srna, "falloff_power", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "f_power");
RNA_def_property_range(prop, 0.0f, 10.0f);
- RNA_def_property_ui_text(prop, "Falloff Power", "Falloff power (real gravitational falloff = 2)");
+ RNA_def_property_ui_text(prop, "Falloff Power", "");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
prop = RNA_def_property(srna, "distance_min", PROP_FLOAT, PROP_NONE);
@@ -1286,7 +1306,8 @@ static void rna_def_field(BlenderRNA *brna)
prop = RNA_def_property(srna, "distance_max", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "maxdist");
- RNA_def_property_range(prop, 0.0f, 1000.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
+ RNA_def_property_ui_range(prop, 0.0f, 1000.0f, 1.0f, 3);
RNA_def_property_ui_text(prop, "Maximum Distance", "Maximum distance for the field to work");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
@@ -1394,6 +1415,11 @@ static void rna_def_field(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", PFIELD_SMOKE_DENSITY);
RNA_def_property_ui_text(prop, "Apply Density", "Adjust force strength based on smoke density");
RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
+ prop = RNA_def_property(srna, "use_gravity_falloff", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", PFIELD_GRAVITATION);
+ RNA_def_property_ui_text(prop, "Gravity Falloff", "Multiply force by 1/distance²");
+ RNA_def_property_update(prop, 0, "rna_FieldSettings_update");
+
/* Pointer */
@@ -1560,7 +1586,7 @@ static void rna_def_softbody(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem collision_type_items[] = {
+ static const EnumPropertyItem collision_type_items[] = {
{SBC_MODE_MANUAL, "MANUAL", 0, "Manual", "Manual adjust"},
{SBC_MODE_AVG, "AVERAGE", 0, "Average", "Average Spring length * Ball Size"},
{SBC_MODE_MIN, "MINIMAL", 0, "Minimal", "Minimal Spring length * Ball Size"},
@@ -1569,7 +1595,7 @@ static void rna_def_softbody(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem aerodynamics_type[] = {
+ static const EnumPropertyItem aerodynamics_type[] = {
{0, "SIMPLE", 0, "Simple", "Edges receive a drag force from surrounding media"},
{1, "LIFT_FORCE", 0, "Lift Force", "Edges receive a lift force when passing through surrounding media"},
{0, NULL, 0, NULL, NULL}
@@ -1871,7 +1897,7 @@ static void rna_def_softbody(BlenderRNA *brna)
void RNA_def_object_force(BlenderRNA *brna)
{
- rna_def_pointcache(brna);
+ rna_def_pointcache_active(brna);
rna_def_collision(brna);
rna_def_effector_weight(brna);
rna_def_field(brna);
diff --git a/source/blender/makesrna/intern/rna_packedfile.c b/source/blender/makesrna/intern/rna_packedfile.c
index f3da03714a1..c7891680adb 100644
--- a/source/blender/makesrna/intern/rna_packedfile.c
+++ b/source/blender/makesrna/intern/rna_packedfile.c
@@ -35,7 +35,7 @@
#include "rna_internal.h"
-EnumPropertyItem rna_enum_unpack_method_items[] = {
+const EnumPropertyItem rna_enum_unpack_method_items[] = {
{PF_USE_LOCAL, "USE_LOCAL", 0, "Use Local File", ""},
{PF_WRITE_LOCAL, "WRITE_LOCAL", 0, "Write Local File (overwrite existing)", ""},
{PF_USE_ORIGINAL, "USE_ORIGINAL", 0, "Use Original File", ""},
diff --git a/source/blender/makesrna/intern/rna_particle.c b/source/blender/makesrna/intern/rna_particle.c
index 95dab13571d..2710a184367 100644
--- a/source/blender/makesrna/intern/rna_particle.c
+++ b/source/blender/makesrna/intern/rna_particle.c
@@ -36,7 +36,7 @@
#include "DNA_modifier_types.h"
#include "DNA_cloth_types.h"
#include "DNA_particle_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_boid_types.h"
@@ -55,7 +55,7 @@
#include "WM_api.h"
#ifdef RNA_RUNTIME
-static EnumPropertyItem part_from_items[] = {
+static const EnumPropertyItem part_from_items[] = {
{PART_FROM_VERT, "VERT", 0, "Verts", ""},
{PART_FROM_FACE, "FACE", 0, "Faces", ""},
{PART_FROM_VOLUME, "VOLUME", 0, "Volume", ""},
@@ -64,7 +64,7 @@ static EnumPropertyItem part_from_items[] = {
#endif
#ifndef RNA_RUNTIME
-static EnumPropertyItem part_reactor_from_items[] = {
+static const EnumPropertyItem part_reactor_from_items[] = {
{PART_FROM_VERT, "VERT", 0, "Verts", ""},
{PART_FROM_FACE, "FACE", 0, "Faces", ""},
{PART_FROM_VOLUME, "VOLUME", 0, "Volume", ""},
@@ -72,7 +72,7 @@ static EnumPropertyItem part_reactor_from_items[] = {
};
#endif
-static EnumPropertyItem part_dist_items[] = {
+static const EnumPropertyItem part_dist_items[] = {
{PART_DISTR_JIT, "JIT", 0, "Jittered", ""},
{PART_DISTR_RAND, "RAND", 0, "Random", ""},
{PART_DISTR_GRID, "GRID", 0, "Grid", ""},
@@ -80,14 +80,14 @@ static EnumPropertyItem part_dist_items[] = {
};
#ifdef RNA_RUNTIME
-static EnumPropertyItem part_hair_dist_items[] = {
+static const EnumPropertyItem part_hair_dist_items[] = {
{PART_DISTR_JIT, "JIT", 0, "Jittered", ""},
{PART_DISTR_RAND, "RAND", 0, "Random", ""},
{0, NULL, 0, NULL, NULL}
};
#endif
-static EnumPropertyItem part_draw_as_items[] = {
+static const EnumPropertyItem part_draw_as_items[] = {
{PART_DRAW_NOT, "NONE", 0, "None", ""},
{PART_DRAW_REND, "RENDER", 0, "Rendered", ""},
{PART_DRAW_DOT, "DOT", 0, "Point", ""},
@@ -98,7 +98,7 @@ static EnumPropertyItem part_draw_as_items[] = {
};
#ifdef RNA_RUNTIME
-static EnumPropertyItem part_hair_draw_as_items[] = {
+static const EnumPropertyItem part_hair_draw_as_items[] = {
{PART_DRAW_NOT, "NONE", 0, "None", ""},
{PART_DRAW_REND, "RENDER", 0, "Rendered", ""},
{PART_DRAW_PATH, "PATH", 0, "Path", ""},
@@ -106,7 +106,7 @@ static EnumPropertyItem part_hair_draw_as_items[] = {
};
#endif
-static EnumPropertyItem part_ren_as_items[] = {
+static const EnumPropertyItem part_ren_as_items[] = {
{PART_DRAW_NOT, "NONE", 0, "None", ""},
{PART_DRAW_HALO, "HALO", 0, "Halo", ""},
{PART_DRAW_LINE, "LINE", 0, "Line", ""},
@@ -118,7 +118,7 @@ static EnumPropertyItem part_ren_as_items[] = {
};
#ifdef RNA_RUNTIME
-static EnumPropertyItem part_hair_ren_as_items[] = {
+static const EnumPropertyItem part_hair_ren_as_items[] = {
{PART_DRAW_NOT, "NONE", 0, "None", ""},
{PART_DRAW_PATH, "PATH", 0, "Path", ""},
{PART_DRAW_OB, "OBJECT", 0, "Object", ""},
@@ -397,7 +397,7 @@ static void rna_ParticleSystem_co_hair(ParticleSystem *particlesystem, Object *o
}
-static EnumPropertyItem *rna_Particle_Material_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_Particle_Material_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
Object *ob = CTX_data_pointer_get(C, "object").data;
@@ -446,10 +446,12 @@ static int rna_ParticleSystem_tessfaceidx_on_emitter(ParticleSystem *particlesys
int totpart;
int totchild = 0;
int totface;
+ int totvert;
int num = -1;
DM_ensure_tessface(modifier->dm_final); /* BMESH - UNTIL MODIFIER IS UPDATED FOR MPoly */
totface = modifier->dm_final->getNumTessFaces(modifier->dm_final);
+ totvert = modifier->dm_final->getNumVerts(modifier->dm_final);
/* 1. check that everything is ok & updated */
if (!particlesystem || !totface) {
@@ -484,13 +486,29 @@ static int rna_ParticleSystem_tessfaceidx_on_emitter(ParticleSystem *particlesys
return num;
}
}
+ else if (part->from == PART_FROM_VERT) {
+ if (num != DMCACHE_NOTFOUND && num < totvert) {
+ MFace *mface = modifier->dm_final->getTessFaceDataArray(modifier->dm_final, CD_MFACE);
+
+ *r_fuv = &particle->fuv;
+
+ /* This finds the first face to contain the emitting vertex,
+ * this is not ideal, but is mostly fine as UV seams generally
+ * map to equal-colored parts of a texture */
+ for (int i = 0; i < totface; i++, mface++) {
+ if (ELEM(num, mface->v1, mface->v2, mface->v3, mface->v4)) {
+ return i;
+ }
+ }
+ }
+ }
}
else {
ChildParticle *cpa = particlesystem->child + particle_no - totpart;
num = cpa->num;
if (part->childtype == PART_CHILD_FACES) {
- if (ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME)) {
+ if (ELEM(part->from, PART_FROM_FACE, PART_FROM_VOLUME, PART_FROM_VERT)) {
if (num != DMCACHE_NOTFOUND && num < totface) {
*r_fuv = &cpa->fuv;
return num;
@@ -510,6 +528,22 @@ static int rna_ParticleSystem_tessfaceidx_on_emitter(ParticleSystem *particlesys
return num;
}
}
+ else if (part->from == PART_FROM_VERT) {
+ if (num != DMCACHE_NOTFOUND && num < totvert) {
+ MFace *mface = modifier->dm_final->getTessFaceDataArray(modifier->dm_final, CD_MFACE);
+
+ *r_fuv = &parent->fuv;
+
+ /* This finds the first face to contain the emitting vertex,
+ * this is not ideal, but is mostly fine as UV seams generally
+ * map to equal-colored parts of a texture */
+ for (int i = 0; i < totface; i++, mface++) {
+ if (ELEM(num, mface->v1, mface->v2, mface->v3, mface->v4)) {
+ return i;
+ }
+ }
+ }
+ }
}
}
@@ -641,6 +675,7 @@ static void rna_Particle_reset_dependency(Main *bmain, Scene *scene, PointerRNA
static void rna_Particle_change_type(Main *bmain, Scene *scene, PointerRNA *ptr)
{
particle_recalc(bmain, scene, ptr, PSYS_RECALC_RESET | PSYS_RECALC_TYPE);
+ DAG_relations_tag_update(bmain);
}
static void rna_Particle_change_physics(Main *bmain, Scene *scene, PointerRNA *ptr)
@@ -723,7 +758,7 @@ static void rna_Particle_target_redo(Main *UNUSED(bmain), Scene *UNUSED(scene),
}
}
-static void rna_Particle_hair_dynamics(Main *bmain, Scene *scene, PointerRNA *ptr)
+static void rna_Particle_hair_dynamics_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Object *ob = (Object *)ptr->id.data;
ParticleSystem *psys = (ParticleSystem *)ptr->data;
@@ -735,10 +770,12 @@ static void rna_Particle_hair_dynamics(Main *bmain, Scene *scene, PointerRNA *pt
psys->clmd->coll_parms->flags &= ~CLOTH_COLLSETTINGS_FLAG_SELF;
rna_Particle_redo(bmain, scene, ptr);
}
- else
+ else {
WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, NULL);
+ }
DAG_id_tag_update(&ob->id, OB_RECALC_DATA);
+ DAG_relations_tag_update(bmain);
}
static PointerRNA rna_particle_settings_get(PointerRNA *ptr)
{
@@ -907,6 +944,19 @@ static void rna_ParticleSettings_use_roughness_curve_update(Main *bmain, Scene *
rna_Particle_redo_child(bmain, scene, ptr);
}
+static void rna_ParticleSettings_use_twist_curve_update(Main *bmain, Scene *scene, PointerRNA *ptr)
+{
+ ParticleSettings *part = ptr->data;
+
+ if (part->child_flag & PART_CHILD_USE_TWIST_CURVE) {
+ if (!part->twistcurve) {
+ BKE_particlesettings_twist_curve_init(part);
+ }
+ }
+
+ rna_Particle_redo_child(bmain, scene, ptr);
+}
+
static void rna_ParticleSystem_name_set(PointerRNA *ptr, const char *value)
{
Object *ob = ptr->id.data;
@@ -1107,7 +1157,7 @@ static int rna_ParticleDupliWeight_name_length(PointerRNA *ptr)
return strlen(tstr);
}
-static EnumPropertyItem *rna_Particle_from_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_Particle_from_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
/*if (part->type==PART_REACTOR) */
@@ -1116,7 +1166,7 @@ static EnumPropertyItem *rna_Particle_from_itemf(bContext *UNUSED(C), PointerRNA
return part_from_items;
}
-static EnumPropertyItem *rna_Particle_dist_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Particle_dist_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
ParticleSettings *part = ptr->id.data;
@@ -1127,7 +1177,7 @@ static EnumPropertyItem *rna_Particle_dist_itemf(bContext *UNUSED(C), PointerRNA
return part_dist_items;
}
-static EnumPropertyItem *rna_Particle_draw_as_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Particle_draw_as_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
ParticleSettings *part = ptr->id.data;
@@ -1138,7 +1188,7 @@ static EnumPropertyItem *rna_Particle_draw_as_itemf(bContext *UNUSED(C), Pointer
return part_draw_as_items;
}
-static EnumPropertyItem *rna_Particle_ren_as_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_Particle_ren_as_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
ParticleSettings *part = ptr->id.data;
@@ -1263,6 +1313,7 @@ static void rna_ParticleVGroup_name_get_8(PointerRNA *ptr, char *value) { psys_v
static void rna_ParticleVGroup_name_get_9(PointerRNA *ptr, char *value) { psys_vg_name_get__internal(ptr, value, 9); }
static void rna_ParticleVGroup_name_get_10(PointerRNA *ptr, char *value) { psys_vg_name_get__internal(ptr, value, 10); }
static void rna_ParticleVGroup_name_get_11(PointerRNA *ptr, char *value) { psys_vg_name_get__internal(ptr, value, 11); }
+static void rna_ParticleVGroup_name_get_12(PointerRNA *ptr, char *value) { psys_vg_name_get__internal(ptr, value, 12); }
static int rna_ParticleVGroup_name_len_0(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 0); }
static int rna_ParticleVGroup_name_len_1(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 1); }
@@ -1276,6 +1327,7 @@ static int rna_ParticleVGroup_name_len_8(PointerRNA *ptr) { return psys_vg_name_
static int rna_ParticleVGroup_name_len_9(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 9); }
static int rna_ParticleVGroup_name_len_10(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 10); }
static int rna_ParticleVGroup_name_len_11(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 11); }
+static int rna_ParticleVGroup_name_len_12(PointerRNA *ptr) { return psys_vg_name_len__internal(ptr, 12); }
static void rna_ParticleVGroup_name_set_0(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 0); }
static void rna_ParticleVGroup_name_set_1(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 1); }
@@ -1289,6 +1341,7 @@ static void rna_ParticleVGroup_name_set_8(PointerRNA *ptr, const char *value) {
static void rna_ParticleVGroup_name_set_9(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 9); }
static void rna_ParticleVGroup_name_set_10(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 10); }
static void rna_ParticleVGroup_name_set_11(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 11); }
+static void rna_ParticleVGroup_name_set_12(PointerRNA *ptr, const char *value) { psys_vg_name_set__internal(ptr, value, 12); }
#else
@@ -1392,7 +1445,7 @@ static void rna_def_particle(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem alive_items[] = {
+ static const EnumPropertyItem alive_items[] = {
/*{PARS_KILLED, "KILLED", 0, "Killed", ""}, */
{PARS_DEAD, "DEAD", 0, "Dead", ""},
{PARS_UNBORN, "UNBORN", 0, "Unborn", ""},
@@ -1536,7 +1589,7 @@ static void rna_def_fluid_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem sph_solver_items[] = {
+ static const EnumPropertyItem sph_solver_items[] = {
{SPH_SOLVER_DDR, "DDR", 0, "Double-Density", "An artistic solver with strong surface tension effects (original)"},
{SPH_SOLVER_CLASSICAL, "CLASSICAL", 0, "Classical", "A more physically-accurate solver"},
{0, NULL, 0, NULL, NULL}
@@ -1686,7 +1739,7 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem texco_items[] = {
+ static const EnumPropertyItem texco_items[] = {
{TEXCO_GLOB, "GLOBAL", 0, "Global", "Use global coordinates for the texture coordinates"},
{TEXCO_OBJECT, "OBJECT", 0, "Object", "Use linked object's coordinates for texture coordinates"},
{TEXCO_UV, "UV", 0, "UV", "Use UV coordinates for texture coordinates"},
@@ -1696,7 +1749,7 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mapping_items[] = {
+ static const EnumPropertyItem prop_mapping_items[] = {
{MTEX_FLAT, "FLAT", 0, "Flat", "Map X and Y coordinates directly"},
{MTEX_CUBE, "CUBE", 0, "Cube", "Map using the normal vector"},
{MTEX_TUBE, "TUBE", 0, "Tube", "Map with Z as central axis"},
@@ -1704,7 +1757,7 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_x_mapping_items[] = {
+ static const EnumPropertyItem prop_x_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -1712,7 +1765,7 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_y_mapping_items[] = {
+ static const EnumPropertyItem prop_y_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -1720,7 +1773,7 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_z_mapping_items[] = {
+ static const EnumPropertyItem prop_z_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -1841,6 +1894,10 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Length", "Affect the child hair length");
RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
+ prop = RNA_def_property(srna, "use_map_twist", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "mapto", PAMAP_TWIST);
+ RNA_def_property_ui_text(prop, "Twist", "Affect the child twist");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
/* influence factors */
prop = RNA_def_property(srna, "time_factor", PROP_FLOAT, PROP_NONE);
@@ -1922,6 +1979,12 @@ static void rna_def_particle_settings_mtex(BlenderRNA *brna)
RNA_def_property_ui_range(prop, 0, 1, 10, 3);
RNA_def_property_ui_text(prop, "Rough Factor", "Amount texture affects child roughness");
RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
+
+ prop = RNA_def_property(srna, "twist_factor", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "twistfac");
+ RNA_def_property_ui_range(prop, 0, 1, 10, 3);
+ RNA_def_property_ui_text(prop, "Twist Factor", "Amount texture affects child twist");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
}
static void rna_def_particle_settings(BlenderRNA *brna)
@@ -1929,14 +1992,14 @@ static void rna_def_particle_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{PART_EMITTER, "EMITTER", 0, "Emitter", ""},
/*{PART_REACTOR, "REACTOR", 0, "Reactor", ""}, */
{PART_HAIR, "HAIR", 0, "Hair", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem phys_type_items[] = {
+ static const EnumPropertyItem phys_type_items[] = {
{PART_PHYS_NO, "NO", 0, "No", ""},
{PART_PHYS_NEWTON, "NEWTON", 0, "Newtonian", ""},
{PART_PHYS_KEYED, "KEYED", 0, "Keyed", ""},
@@ -1945,7 +2008,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem rot_mode_items[] = {
+ static const EnumPropertyItem rot_mode_items[] = {
{0, "NONE", 0, "None", ""},
{PART_ROT_NOR, "NOR", 0, "Normal", ""},
{PART_ROT_NOR_TAN, "NOR_TAN", 0, "Normal-Tangent", ""},
@@ -1959,7 +2022,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ave_mode_items[] = {
+ static const EnumPropertyItem ave_mode_items[] = {
{0, "NONE", 0, "None", ""},
{PART_AVE_VELOCITY, "VELOCITY", 0, "Velocity", ""},
{PART_AVE_HORIZONTAL, "HORIZONTAL", 0, "Horizontal", ""},
@@ -1971,14 +2034,14 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem react_event_items[] = {
+ static const EnumPropertyItem react_event_items[] = {
{PART_EVENT_DEATH, "DEATH", 0, "Death", ""},
{PART_EVENT_COLLIDE, "COLLIDE", 0, "Collision", ""},
{PART_EVENT_NEAR, "NEAR", 0, "Near", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem child_type_items[] = {
+ static const EnumPropertyItem child_type_items[] = {
{0, "NONE", 0, "None", ""},
{PART_CHILD_PARTICLES, "SIMPLE", 0, "Simple", ""},
{PART_CHILD_FACES, "INTERPOLATED", 0, "Interpolated", ""},
@@ -1986,7 +2049,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
};
/*TODO: names, tooltips */
- static EnumPropertyItem integrator_type_items[] = {
+ static const EnumPropertyItem integrator_type_items[] = {
{PART_INT_EULER, "EULER", 0, "Euler", ""},
{PART_INT_VERLET, "VERLET", 0, "Verlet", ""},
{PART_INT_MIDPOINT, "MIDPOINT", 0, "Midpoint", ""},
@@ -1994,7 +2057,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem kink_type_items[] = {
+ static const EnumPropertyItem kink_type_items[] = {
{PART_KINK_NO, "NO", 0, "Nothing", ""},
{PART_KINK_CURL, "CURL", 0, "Curl", ""},
{PART_KINK_RADIAL, "RADIAL", 0, "Radial", ""},
@@ -2004,7 +2067,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bb_align_items[] = {
+ static const EnumPropertyItem bb_align_items[] = {
{PART_BB_X, "X", 0, "X", ""},
{PART_BB_Y, "Y", 0, "Y", ""},
{PART_BB_Z, "Z", 0, "Z", ""},
@@ -2013,7 +2076,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bb_anim_items[] = {
+ static const EnumPropertyItem bb_anim_items[] = {
{PART_BB_ANIM_NONE, "NONE", 0, "None", ""},
{PART_BB_ANIM_AGE, "AGE", 0, "Age", ""},
{PART_BB_ANIM_FRAME, "FRAME", 0, "Frame", ""},
@@ -2021,14 +2084,14 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bb_split_offset_items[] = {
+ static const EnumPropertyItem bb_split_offset_items[] = {
{PART_BB_OFF_NONE, "NONE", 0, "None", ""},
{PART_BB_OFF_LINEAR, "LINEAR", 0, "Linear", ""},
{PART_BB_OFF_RANDOM, "RANDOM", 0, "Random", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem draw_col_items[] = {
+ static const EnumPropertyItem draw_col_items[] = {
{PART_DRAW_COL_NONE, "NONE", 0, "None", ""},
{PART_DRAW_COL_MAT, "MATERIAL", 0, "Material", ""},
{PART_DRAW_COL_VEL, "VELOCITY", 0, "Velocity", ""},
@@ -2036,7 +2099,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem part_mat_items[] = {
+ static const EnumPropertyItem part_mat_items[] = {
{0, "DUMMY", 0, "Dummy", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -2095,7 +2158,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Even Distribution",
"Use even distribution from faces based on face areas or edge lengths");
RNA_def_property_update(prop, 0, "rna_Particle_reset");
-
+
prop = RNA_def_property(srna, "use_die_on_collision", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", PART_DIE_ON_COL);
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
@@ -2300,7 +2363,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_render_adaptive", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "draw", PART_DRAW_REN_ADAPT);
- RNA_def_property_ui_text(prop, "Adaptive render", "Draw steps of the particle path");
+ RNA_def_property_ui_text(prop, "Adaptive Render", "Draw steps of the particle path");
RNA_def_property_update(prop, 0, "rna_Particle_redo");
prop = RNA_def_property(srna, "use_velocity_length", PROP_BOOLEAN, PROP_NONE);
@@ -2315,7 +2378,7 @@ static void rna_def_particle_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_strand_primitive", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "draw", PART_DRAW_REN_STRAND);
- RNA_def_property_ui_text(prop, "Strand render", "Use the strand primitive for rendering");
+ RNA_def_property_ui_text(prop, "Strand Render", "Use the strand primitive for rendering");
RNA_def_property_update(prop, 0, "rna_Particle_redo");
prop = RNA_def_property(srna, "draw_method", PROP_ENUM, PROP_NONE);
@@ -2363,7 +2426,8 @@ static void rna_def_particle_settings(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Render", "How many steps paths are rendered with (power of 2)");
prop = RNA_def_property(srna, "hair_step", PROP_INT, PROP_NONE);
- RNA_def_property_range(prop, 2, 50);
+ RNA_def_property_range(prop, 2, SHRT_MAX);
+ RNA_def_property_ui_range(prop, 2, 50, 1, 1);
RNA_def_property_ui_text(prop, "Segments", "Number of hair segments");
RNA_def_property_update(prop, 0, "rna_Particle_reset");
@@ -3132,6 +3196,25 @@ static void rna_def_particle_settings(BlenderRNA *brna)
RNA_def_property_struct_type(prop, "FieldSettings");
RNA_def_property_pointer_funcs(prop, "rna_Particle_field2_get", NULL, NULL, NULL);
RNA_def_property_ui_text(prop, "Force Field 2", "");
+
+ /* twist */
+ prop = RNA_def_property(srna, "twist", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_range(prop, -100000.0f, 100000.0f);
+ RNA_def_property_ui_range(prop, -10.0f, 10.0f, 0.1, 3);
+ RNA_def_property_ui_text(prop, "Twist", "Number of turns around parent allong the strand");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
+
+ prop = RNA_def_property(srna, "use_twist_curve", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "child_flag", PART_CHILD_USE_TWIST_CURVE);
+ RNA_def_property_ui_text(prop, "Use Twist Curve", "Use a curve to define twist");
+ RNA_def_property_update(prop, 0, "rna_ParticleSettings_use_twist_curve_update");
+
+ prop = RNA_def_property(srna, "twist_curve", PROP_POINTER, PROP_NONE);
+ RNA_def_property_pointer_sdna(prop, NULL, "twistcurve");
+ RNA_def_property_struct_type(prop, "CurveMapping");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Twist Curve", "Curve defining twist");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
}
static void rna_def_particle_target(BlenderRNA *brna)
@@ -3139,7 +3222,7 @@ static void rna_def_particle_target(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem mode_items[] = {
+ static const EnumPropertyItem mode_items[] = {
{PTARGET_MODE_FRIEND, "FRIEND", 0, "Friend", ""},
{PTARGET_MODE_NEUTRAL, "NEUTRAL", 0, "Neutral", ""},
{PTARGET_MODE_ENEMY, "ENEMY", 0, "Enemy", ""},
@@ -3202,7 +3285,7 @@ static void rna_def_particle_system(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem resolution_items[] = {
+ static const EnumPropertyItem resolution_items[] = {
{eModifierMode_Realtime, "PREVIEW", 0, "Preview", "Apply modifier preview settings"},
{eModifierMode_Render, "RENDER", 0, "Render", "Apply modifier render settings"},
{0, NULL, 0, NULL, NULL}
@@ -3257,7 +3340,7 @@ static void rna_def_particle_system(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_hair_dynamics", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", PSYS_HAIR_DYNAMICS);
RNA_def_property_ui_text(prop, "Hair Dynamics", "Enable hair dynamics using cloth simulation");
- RNA_def_property_update(prop, 0, "rna_Particle_hair_dynamics");
+ RNA_def_property_update(prop, 0, "rna_Particle_hair_dynamics_update");
prop = RNA_def_property(srna, "cloth", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "clmd");
@@ -3465,6 +3548,18 @@ static void rna_def_particle_system(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Vertex Group Field Negate", "Negate the effect of the field vertex group");
RNA_def_property_update(prop, 0, "rna_Particle_reset");
+ prop = RNA_def_property(srna, "vertex_group_twist", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_funcs(prop, "rna_ParticleVGroup_name_get_12", "rna_ParticleVGroup_name_len_12",
+ "rna_ParticleVGroup_name_set_12");
+ RNA_def_property_ui_text(prop, "Vertex Group Twist", "Vertex group to control twist");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
+
+ prop = RNA_def_property(srna, "invert_vertex_group_twist", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "vg_neg", (1 << PSYS_VG_TWIST));
+ RNA_def_property_ui_text(prop, "Vertex Group Twist Negate",
+ "Negate the effect of the twist vertex group");
+ RNA_def_property_update(prop, 0, "rna_Particle_redo_child");
+
/* pointcache */
prop = RNA_def_property(srna, "point_cache", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
diff --git a/source/blender/makesrna/intern/rna_pose.c b/source/blender/makesrna/intern/rna_pose.c
index 28ce63a61bd..ac27a6c21a5 100644
--- a/source/blender/makesrna/intern/rna_pose.c
+++ b/source/blender/makesrna/intern/rna_pose.c
@@ -52,7 +52,7 @@
/* XXX: this RNA enum define is currently duplicated for objects,
* since there is some text here which is not applicable */
-EnumPropertyItem rna_enum_posebone_rotmode_items[] = {
+const EnumPropertyItem rna_enum_posebone_rotmode_items[] = {
{ROT_MODE_QUAT, "QUATERNION", 0, "Quaternion (WXYZ)", "No Gimbal Lock (default)"},
{ROT_MODE_XYZ, "XYZ", 0, "XYZ Euler", "XYZ Rotation Order (prone to Gimbal Lock)"},
{ROT_MODE_XZY, "XZY", 0, "XZY Euler", "XZY Rotation Order (prone to Gimbal Lock)"},
@@ -66,7 +66,7 @@ EnumPropertyItem rna_enum_posebone_rotmode_items[] = {
};
/* Bone and Group Color Sets */
-EnumPropertyItem rna_enum_color_sets_items[] = {
+const EnumPropertyItem rna_enum_color_sets_items[] = {
{0, "DEFAULT", 0, "Default Colors", ""},
{1, "THEME01", VICO_COLORSET_01_VEC, "01 - Theme Color Set", ""},
{2, "THEME02", VICO_COLORSET_02_VEC, "02 - Theme Color Set", ""},
@@ -524,12 +524,15 @@ static void rna_PoseChannel_active_constraint_set(PointerRNA *ptr, PointerRNA va
BKE_constraints_active_set(&pchan->constraints, (bConstraint *)value.data);
}
-static bConstraint *rna_PoseChannel_constraints_new(bPoseChannel *pchan, int type)
+static bConstraint *rna_PoseChannel_constraints_new(ID *id, bPoseChannel *pchan, Main *main, int type)
{
- /*WM_main_add_notifier(NC_OBJECT|ND_CONSTRAINT|NA_ADDED, object); */
- /* TODO, pass object also */
- /* TODO, new pose bones don't have updated draw flags */
- return BKE_constraint_add_for_pose(NULL, pchan, NULL, type);
+ Object *ob = (Object *)id;
+ bConstraint *new_con = BKE_constraint_add_for_pose(ob, pchan, NULL, type);
+
+ ED_object_constraint_dependency_tag_update(main, ob, new_con);
+ WM_main_add_notifier(NC_OBJECT | ND_CONSTRAINT | NA_ADDED, id);
+
+ return new_con;
}
static void rna_PoseChannel_constraints_remove(ID *id, bPoseChannel *pchan, ReportList *reports, PointerRNA *con_ptr)
@@ -726,13 +729,13 @@ static void rna_def_bone_group(BlenderRNA *brna)
rna_def_actionbone_group_common(srna, NC_OBJECT | ND_POSE, "rna_Pose_update");
}
-static EnumPropertyItem prop_iksolver_items[] = {
+static const EnumPropertyItem prop_iksolver_items[] = {
{IKSOLVER_STANDARD, "LEGACY", 0, "Standard", "Original IK solver"},
{IKSOLVER_ITASC, "ITASC", 0, "iTaSC", "Multi constraint, stateful IK solver"},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_solver_items[] = {
+static const EnumPropertyItem prop_solver_items[] = {
{ITASC_SOLVER_SDLS, "SDLS", 0, "SDLS", "Selective Damped Least Square"},
{ITASC_SOLVER_DLS, "DLS", 0, "DLS", "Damped Least Square with Numerical Filtering"},
{0, NULL, 0, NULL, NULL}
@@ -764,6 +767,7 @@ static void rna_def_pose_channel_constraints(BlenderRNA *brna, PropertyRNA *cpro
/* Constraint collection */
func = RNA_def_function(srna, "new", "rna_PoseChannel_constraints_new");
RNA_def_function_ui_description(func, "Add a constraint to this object");
+ RNA_def_function_flag(func, FUNC_USE_MAIN | FUNC_USE_SELF_ID); /* ID and Main needed for refresh */
/* return type */
parm = RNA_def_pointer(func, "constraint", "Constraint", "", "New constraint");
RNA_def_function_return(func, parm);
diff --git a/source/blender/makesrna/intern/rna_property.c b/source/blender/makesrna/intern/rna_property.c
index fb70870f49b..7ee792b5d1f 100644
--- a/source/blender/makesrna/intern/rna_property.c
+++ b/source/blender/makesrna/intern/rna_property.c
@@ -43,7 +43,7 @@
#include "WM_types.h"
-EnumPropertyItem rna_enum_gameproperty_type_items[] = {
+const EnumPropertyItem rna_enum_gameproperty_type_items[] = {
{GPROP_BOOL, "BOOL", 0, "Boolean", "Boolean Property"},
{GPROP_INT, "INT", 0, "Integer", "Integer Property"},
{GPROP_FLOAT, "FLOAT", 0, "Float", "Floating-Point Property"},
diff --git a/source/blender/makesrna/intern/rna_render.c b/source/blender/makesrna/intern/rna_render.c
index 518c7efd915..98ae6eb0480 100644
--- a/source/blender/makesrna/intern/rna_render.c
+++ b/source/blender/makesrna/intern/rna_render.c
@@ -26,12 +26,16 @@
#include <stdlib.h>
+#include "DNA_node_types.h"
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
#include "BLI_utildefines.h"
#include "BLI_path_util.h"
+#include "BKE_scene.h"
+#include "BKE_image.h"
+
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -40,8 +44,10 @@
#include "RE_engine.h"
#include "RE_pipeline.h"
+#include "ED_render.h"
-EnumPropertyItem rna_enum_render_pass_type_items[] = {
+/* Deprecated, only provided for API compatibility. */
+const EnumPropertyItem rna_enum_render_pass_type_items[] = {
{SCE_PASS_COMBINED, "COMBINED", 0, "Combined", ""},
{SCE_PASS_Z, "Z", 0, "Z", ""},
{SCE_PASS_RGBA, "COLOR", 0, "Color", ""},
@@ -77,24 +83,13 @@ EnumPropertyItem rna_enum_render_pass_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_render_pass_debug_type_items[] = {
- {RENDER_PASS_DEBUG_BVH_TRAVERSED_NODES, "BVH_TRAVERSED_NODES", 0, "BVH Traversed Nodes",
- "Number of nodes traversed in BVH for the camera rays"},
- {RENDER_PASS_DEBUG_BVH_TRAVERSED_INSTANCES, "BVH_TRAVERSED_INSTANCES", 0, "BVH Traversed Instances",
- "Number of BVH instances traversed by camera rays"},
- {RENDER_PASS_DEBUG_BVH_INTERSECTIONS, "BVH_INTERSECTIONS", 0, "BVH Intersections",
- "Number of primitive intersections performed by the camera rays"},
- {RENDER_PASS_DEBUG_RAY_BOUNCES, "RAY_BOUNCES", 0, "Ray Steps",
- "Number of bounces done by the main integration loop"},
- {0, NULL, 0, NULL, NULL}
-};
-
-EnumPropertyItem rna_enum_bake_pass_type_items[] = {
+const EnumPropertyItem rna_enum_bake_pass_type_items[] = {
{SCE_PASS_COMBINED, "COMBINED", 0, "Combined", ""},
{SCE_PASS_AO, "AO", 0, "AO", ""},
{SCE_PASS_SHADOW, "SHADOW", 0, "Shadow", ""},
{SCE_PASS_NORMAL, "NORMAL", 0, "Normal", ""},
{SCE_PASS_UV, "UV", 0, "UV", ""},
+ {SCE_PASS_ROUGHNESS, "ROUGHNESS", 0, "ROUGHNESS", ""},
{SCE_PASS_EMIT, "EMIT", 0, "Emit", ""},
{SCE_PASS_ENVIRONMENT, "ENVIRONMENT", 0, "Environment", ""},
{SCE_PASS_DIFFUSE_COLOR, "DIFFUSE", 0, "Diffuse", ""},
@@ -133,6 +128,11 @@ static int engine_support_display_space_shader(RenderEngine *UNUSED(engine), Sce
return IMB_colormanagement_support_glsl_draw(&scene->view_settings);
}
+static int engine_get_preview_pixel_size(RenderEngine *UNUSED(engine), Scene *scene)
+{
+ return BKE_render_preview_pixel_size(&scene->r);
+}
+
static void engine_bind_display_space_shader(RenderEngine *UNUSED(engine), Scene *scene)
{
IMB_colormanagement_setup_glsl_draw(&scene->view_settings,
@@ -261,9 +261,27 @@ static void engine_update_script_node(RenderEngine *engine, struct bNodeTree *nt
RNA_parameter_list_free(&list);
}
+static void engine_update_render_passes(RenderEngine *engine, struct Scene *scene, struct SceneRenderLayer *srl)
+{
+ extern FunctionRNA rna_RenderEngine_update_render_passes_func;
+ PointerRNA ptr;
+ ParameterList list;
+ FunctionRNA *func;
+
+ RNA_pointer_create(NULL, engine->type->ext.srna, engine, &ptr);
+ func = &rna_RenderEngine_update_render_passes_func;
+
+ RNA_parameter_list_create(&list, &ptr, func);
+ RNA_parameter_set_lookup(&list, "scene", &scene);
+ RNA_parameter_set_lookup(&list, "renderlayer", &srl);
+ engine->type->ext.call(NULL, &ptr, func, &list);
+
+ RNA_parameter_list_free(&list);
+}
+
/* RenderEngine registration */
-static void rna_RenderEngine_unregister(Main *UNUSED(bmain), StructRNA *type)
+static void rna_RenderEngine_unregister(Main *bmain, StructRNA *type)
{
RenderEngineType *et = RNA_struct_blender_type_get(type);
@@ -271,17 +289,21 @@ static void rna_RenderEngine_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &et->ext);
- BLI_freelinkN(&R_engines, et);
RNA_struct_free(&BLENDER_RNA, type);
+ BLI_freelinkN(&R_engines, et);
+
+ /* Stop all renders in case we were using this one. */
+ ED_render_engine_changed(bmain);
}
-static StructRNA *rna_RenderEngine_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_RenderEngine_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
RenderEngineType *et, dummyet = {NULL};
RenderEngine dummyengine = {NULL};
PointerRNA dummyptr;
- int have_function[6];
+ int have_function[7];
/* setup dummy engine & engine type to store static properties in */
dummyengine.type = &dummyet;
@@ -323,6 +345,7 @@ static StructRNA *rna_RenderEngine_register(Main *bmain, ReportList *reports, vo
et->view_update = (have_function[3]) ? engine_view_update : NULL;
et->view_draw = (have_function[4]) ? engine_view_draw : NULL;
et->update_script_node = (have_function[5]) ? engine_update_script_node : NULL;
+ et->update_render_passes = (have_function[6]) ? engine_update_render_passes : NULL;
BLI_addtail(&R_engines, et);
@@ -380,6 +403,12 @@ static void rna_RenderResult_layers_begin(CollectionPropertyIterator *iter, Poin
rna_iterator_listbase_begin(iter, &rr->layers, NULL);
}
+static void rna_RenderResult_stamp_data_add_field(RenderResult *rr, const char *field, const char *value)
+{
+ BKE_render_result_stamp_data(rr, field, value);
+}
+
+
static void rna_RenderLayer_passes_begin(CollectionPropertyIterator *iter, PointerRNA *ptr)
{
RenderLayer *rl = (RenderLayer *)ptr->data;
@@ -419,6 +448,11 @@ static RenderPass *rna_RenderPass_find_by_type(RenderLayer *rl, int passtype, co
return RE_pass_find_by_type(rl, passtype, view);
}
+static RenderPass *rna_RenderPass_find_by_name(RenderLayer *rl, const char *name, const char *view)
+{
+ return RE_pass_find_by_name(rl, name, view);
+}
+
#else /* RNA_RUNTIME */
static void rna_def_render_engine(BlenderRNA *brna)
@@ -429,6 +463,13 @@ static void rna_def_render_engine(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
+ static const EnumPropertyItem render_pass_type_items[] = {
+ {SOCK_FLOAT, "VALUE", 0, "Value", ""},
+ {SOCK_VECTOR, "VECTOR", 0, "Vector", ""},
+ {SOCK_RGBA, "COLOR", 0, "Color", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
srna = RNA_def_struct(brna, "RenderEngine", NULL);
RNA_def_struct_sdna(srna, "RenderEngine");
RNA_def_struct_ui_text(srna, "Render Engine", "Render engine");
@@ -497,6 +538,12 @@ static void rna_def_render_engine(BlenderRNA *brna)
func = RNA_def_function(srna, "tag_update", "engine_tag_update");
RNA_def_function_ui_description(func, "Request update call for viewport rendering");
+ func = RNA_def_function(srna, "update_render_passes", NULL);
+ RNA_def_function_ui_description(func, "Update the render passes that will be generated");
+ RNA_def_function_flag(func, FUNC_REGISTER_OPTIONAL | FUNC_ALLOW_WRITE);
+ parm = RNA_def_pointer(func, "scene", "Scene", "", "");
+ parm = RNA_def_pointer(func, "renderlayer", "SceneRenderLayer", "", "");
+
func = RNA_def_function(srna, "begin_result", "RE_engine_begin_result");
RNA_def_function_ui_description(func, "Create render result to write linear floating point render layers and passes");
parm = RNA_def_int(func, "x", 0, 0, INT_MAX, "X", "", 0, INT_MAX);
@@ -522,8 +569,24 @@ static void rna_def_render_engine(BlenderRNA *brna)
parm = RNA_def_pointer(func, "result", "RenderResult", "Result", "");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
RNA_def_boolean(func, "cancel", 0, "Cancel", "Don't mark tile as done, don't merge results unless forced");
+ RNA_def_boolean(func, "highlight", 0, "Highlight", "Don't mark tile as done yet");
RNA_def_boolean(func, "do_merge_results", 0, "Merge Results", "Merge results even if cancel=true");
+ func = RNA_def_function(srna, "add_pass", "RE_engine_add_pass");
+ RNA_def_function_ui_description(func, "Add a pass to the render layer");
+ parm = RNA_def_string(func, "name", NULL, 0, "Name", "Name of the Pass, without view or channel tag");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_int(func, "channels", 0, 0, INT_MAX, "Channels", "", 0, INT_MAX);
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_string(func, "chan_id", NULL, 0, "Channel IDs", "Channel names, one character per channel");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ RNA_def_string(func, "layer", NULL, 0, "Layer", "Single layer to add render pass to"); /* NULL ok here */
+
+ func = RNA_def_function(srna, "get_result", "RE_engine_get_result");
+ RNA_def_function_ui_description(func, "Get final result for non-pixel operations");
+ parm = RNA_def_pointer(func, "result", "RenderResult", "Result", "");
+ RNA_def_function_return(func, parm);
+
func = RNA_def_function(srna, "test_break", "RE_engine_test_break");
RNA_def_function_ui_description(func, "Test if the render operation should been canceled, this is a fast call that should be used regularly for responsiveness");
parm = RNA_def_boolean(func, "do_break", 0, "Break", "");
@@ -608,6 +671,13 @@ static void rna_def_render_engine(BlenderRNA *brna)
parm = RNA_def_boolean(func, "supported", 0, "Supported", "");
RNA_def_function_return(func, parm);
+ func = RNA_def_function(srna, "get_preview_pixel_size", "engine_get_preview_pixel_size");
+ RNA_def_function_ui_description(func, "Get the pixel size that should be used for preview rendering");
+ parm = RNA_def_pointer(func, "scene", "Scene", "", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_int(func, "pixel_size", 0, 1, 8, "Pixel Size", "", 1, 8);
+ RNA_def_function_return(func, parm);
+
RNA_define_verify_sdna(0);
prop = RNA_def_property(srna, "is_animation", PROP_BOOLEAN, PROP_NONE);
@@ -646,6 +716,21 @@ static void rna_def_render_engine(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_highlight_tiles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", RE_ENGINE_HIGHLIGHT_TILES);
+ func = RNA_def_function(srna, "register_pass", "RE_engine_register_pass");
+ RNA_def_function_ui_description(func, "Register a render pass that will be part of the render with the current settings");
+ prop = RNA_def_pointer(func, "scene", "Scene", "", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ prop = RNA_def_pointer(func, "srl", "SceneRenderLayer", "", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ prop = RNA_def_string(func, "name", NULL, MAX_NAME, "Name", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ prop = RNA_def_int(func, "channels", 1, 1, 8, "Channels", "", 1, 4);
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ prop = RNA_def_string(func, "chanid", NULL, 8, "Channel IDs", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ prop = RNA_def_enum(func, "type", render_pass_type_items, SOCK_FLOAT, "Type", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+
/* registration */
prop = RNA_def_property(srna, "bl_idname", PROP_STRING, PROP_NONE);
@@ -711,6 +796,13 @@ static void rna_def_render_result(BlenderRNA *brna)
"the render result");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ func = RNA_def_function(srna, "stamp_data_add_field", "rna_RenderResult_stamp_data_add_field");
+ RNA_def_function_ui_description(func, "Add engine-specific stamp data to the result");
+ parm = RNA_def_string(func, "field", NULL, 1024, "Field", "Name of the stamp field to add");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_string(func, "value", NULL, 1024, "Value", "Value of the stamp data");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+
RNA_define_verify_sdna(0);
prop = RNA_def_property(srna, "resolution_x", PROP_INT, PROP_PIXEL);
@@ -774,6 +866,15 @@ static void rna_def_render_passes(BlenderRNA *brna, PropertyRNA *cprop)
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
parm = RNA_def_pointer(func, "render_pass", "RenderPass", "", "The matching render pass");
RNA_def_function_return(func, parm);
+
+ func = RNA_def_function(srna, "find_by_name", "rna_RenderPass_find_by_name");
+ RNA_def_function_ui_description(func, "Get the render pass for a given name and view");
+ parm = RNA_def_string(func, "name", RE_PASSNAME_COMBINED, 0, "Pass", "");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_string(func, "view", NULL, 0, "View", "Render view to get pass from"); /* NULL ok here */
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ parm = RNA_def_pointer(func, "render_pass", "RenderPass", "", "The matching render pass");
+ RNA_def_function_return(func, parm);
}
static void rna_def_render_layer(BlenderRNA *brna)
@@ -822,6 +923,11 @@ static void rna_def_render_pass(BlenderRNA *brna)
RNA_define_verify_sdna(0);
+ prop = RNA_def_property(srna, "fullname", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "fullname");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_struct_name_property(srna, prop);
+
prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "name");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
@@ -835,11 +941,6 @@ static void rna_def_render_pass(BlenderRNA *brna)
RNA_def_property_int_sdna(prop, NULL, "channels");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_sdna(prop, NULL, "passtype");
- RNA_def_property_enum_items(prop, rna_enum_render_pass_type_items);
- RNA_def_property_clear_flag(prop, PROP_EDITABLE);
-
prop = RNA_def_property(srna, "rect", PROP_FLOAT, PROP_NONE);
RNA_def_property_flag(prop, PROP_DYNAMIC);
RNA_def_property_multi_array(prop, 2, NULL);
@@ -850,11 +951,6 @@ static void rna_def_render_pass(BlenderRNA *brna)
RNA_def_property_int_sdna(prop, NULL, "view_id");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
- prop = RNA_def_property(srna, "debug_type", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_sdna(prop, NULL, "debug_type");
- RNA_def_property_enum_items(prop, rna_enum_render_pass_debug_type_items);
- RNA_def_property_clear_flag(prop, PROP_EDITABLE);
-
RNA_define_verify_sdna(1);
}
diff --git a/source/blender/makesrna/intern/rna_rigidbody.c b/source/blender/makesrna/intern/rna_rigidbody.c
index a1a7efdaba5..4c3301d5f9e 100644
--- a/source/blender/makesrna/intern/rna_rigidbody.c
+++ b/source/blender/makesrna/intern/rna_rigidbody.c
@@ -44,13 +44,13 @@
#include "WM_types.h"
/* roles of objects in RigidBody Sims */
-EnumPropertyItem rna_enum_rigidbody_object_type_items[] = {
+const EnumPropertyItem rna_enum_rigidbody_object_type_items[] = {
{RBO_TYPE_ACTIVE, "ACTIVE", 0, "Active", "Object is directly controlled by simulation results"},
{RBO_TYPE_PASSIVE, "PASSIVE", 0, "Passive", "Object is directly controlled by animation system"},
{0, NULL, 0, NULL, NULL}};
/* collision shapes of objects in rigid body sim */
-EnumPropertyItem rna_enum_rigidbody_object_shape_items[] = {
+const EnumPropertyItem rna_enum_rigidbody_object_shape_items[] = {
{RB_SHAPE_BOX, "BOX", ICON_MESH_CUBE, "Box", "Box-like shapes (i.e. cubes), including planes (i.e. ground planes)"},
{RB_SHAPE_SPHERE, "SPHERE", ICON_MESH_UVSPHERE, "Sphere", ""},
{RB_SHAPE_CAPSULE, "CAPSULE", ICON_MESH_CAPSULE, "Capsule", ""},
@@ -64,7 +64,7 @@ EnumPropertyItem rna_enum_rigidbody_object_shape_items[] = {
{0, NULL, 0, NULL, NULL}};
/* collision shapes of constraints in rigid body sim */
-EnumPropertyItem rna_enum_rigidbody_constraint_type_items[] = {
+const EnumPropertyItem rna_enum_rigidbody_constraint_type_items[] = {
{RBC_TYPE_FIXED, "FIXED", ICON_NONE, "Fixed", "Glue rigid bodies together"},
{RBC_TYPE_POINT, "POINT", ICON_NONE, "Point", "Constrain rigid bodies to move around common pivot point"},
{RBC_TYPE_HINGE, "HINGE", ICON_NONE, "Hinge", "Restrict rigid body rotation to one axis"},
@@ -78,7 +78,7 @@ EnumPropertyItem rna_enum_rigidbody_constraint_type_items[] = {
#ifndef RNA_RUNTIME
/* mesh source for collision shape creation */
-static EnumPropertyItem rigidbody_mesh_source_items[] = {
+static const EnumPropertyItem rigidbody_mesh_source_items[] = {
{RBO_MESH_BASE, "BASE", 0, "Base", "Base mesh"},
{RBO_MESH_DEFORM, "DEFORM", 0, "Deform", "Deformations (shape keys, deform modifiers)"},
{RBO_MESH_FINAL, "FINAL", 0, "Final", "All modifiers"},
@@ -803,6 +803,7 @@ static void rna_def_rigidbody_world(BlenderRNA *brna)
prop = RNA_def_property(srna, "point_cache", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
RNA_def_property_pointer_sdna(prop, NULL, "pointcache");
+ RNA_def_property_struct_type(prop, "PointCache");
RNA_def_property_ui_text(prop, "Point Cache", "");
/* effector weights */
@@ -1292,49 +1293,49 @@ static void rna_def_rigidbody_constraint(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Z Angle Stiffness", "Stiffness on the Z rotational axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_x", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_x");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_x_set", NULL);
RNA_def_property_ui_text(prop, "Damping X", "Damping on the X axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_y", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_y", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_y");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_y_set", NULL);
RNA_def_property_ui_text(prop, "Damping Y", "Damping on the Y axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_z", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_z", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_z");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_z_set", NULL);
RNA_def_property_ui_text(prop, "Damping Z", "Damping on the Z axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_ang_x", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_ang_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_ang_x");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_ang_x_set", NULL);
RNA_def_property_ui_text(prop, "Damping X Angle", "Damping on the X rotational axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_ang_y", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_ang_y", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_ang_y");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_ang_y_set", NULL);
RNA_def_property_ui_text(prop, "Damping Y Angle", "Damping on the Y rotational axis");
RNA_def_property_update(prop, NC_OBJECT, "rna_RigidBodyOb_reset");
- prop = RNA_def_property(srna, "spring_damping_ang_z", PROP_FLOAT, PROP_FACTOR);
+ prop = RNA_def_property(srna, "spring_damping_ang_z", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "spring_damping_ang_z");
- RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_float_default(prop, 0.5f);
RNA_def_property_float_funcs(prop, NULL, "rna_RigidBodyCon_spring_damping_ang_z_set", NULL);
RNA_def_property_ui_text(prop, "Damping Z Angle", "Damping on the Z rotational axis");
diff --git a/source/blender/makesrna/intern/rna_rna.c b/source/blender/makesrna/intern/rna_rna.c
index abded187b33..b1b7965286f 100644
--- a/source/blender/makesrna/intern/rna_rna.c
+++ b/source/blender/makesrna/intern/rna_rna.c
@@ -36,7 +36,7 @@
#include "rna_internal.h"
-EnumPropertyItem rna_enum_property_type_items[] = {
+const EnumPropertyItem rna_enum_property_type_items[] = {
{PROP_BOOLEAN, "BOOLEAN", 0, "Boolean", ""},
{PROP_INT, "INT", 0, "Integer", ""},
{PROP_FLOAT, "FLOAT", 0, "Float", ""},
@@ -50,7 +50,7 @@ EnumPropertyItem rna_enum_property_type_items[] = {
/* XXX Keep in sync with bpy_props.c's property_subtype_xxx_items ???
* Currently it is not...
*/
-EnumPropertyItem rna_enum_property_subtype_items[] = {
+const EnumPropertyItem rna_enum_property_subtype_items[] = {
{PROP_NONE, "NONE", 0, "None", ""},
/* strings */
@@ -90,7 +90,7 @@ EnumPropertyItem rna_enum_property_subtype_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_property_unit_items[] = {
+const EnumPropertyItem rna_enum_property_unit_items[] = {
{PROP_UNIT_NONE, "NONE", 0, "None", ""},
{PROP_UNIT_LENGTH, "LENGTH", 0, "Length", ""},
{PROP_UNIT_AREA, "AREA", 0, "Area", ""},
@@ -330,6 +330,16 @@ static PointerRNA rna_Struct_functions_get(CollectionPropertyIterator *iter)
return rna_pointer_inherit_refine(&iter->parent, &RNA_Function, internal->link);
}
+static void rna_Struct_property_tags_begin(CollectionPropertyIterator *iter, PointerRNA *ptr)
+{
+ /* here ptr->data should always be the same as iter->parent.type */
+ StructRNA *srna = (StructRNA *)ptr->data;
+ const EnumPropertyItem *tag_defines = RNA_struct_property_tag_defines(srna);
+ unsigned int tag_count = tag_defines ? RNA_enum_items_count(tag_defines) : 0;
+
+ rna_iterator_array_begin(iter, (void *)tag_defines, sizeof(EnumPropertyItem), tag_count, 0, NULL);
+}
+
/* Builtin properties iterator re-uses the Struct properties iterator, only
* difference is that we need to set the ptr data to the type of the struct
* whose properties we want to iterate over. */
@@ -603,6 +613,34 @@ static int rna_Property_is_library_editable_flag_get(PointerRNA *ptr)
return (prop->flag & PROP_LIB_EXCEPTION) != 0;
}
+static int rna_Property_tags_get(PointerRNA *ptr)
+{
+ return RNA_property_tags(ptr->data);
+}
+
+static const EnumPropertyItem *rna_Property_tags_itemf(
+ bContext *UNUSED(C), PointerRNA *ptr,
+ PropertyRNA *UNUSED(prop), bool *r_free)
+{
+ PropertyRNA *this_prop = (PropertyRNA *)ptr->data;
+ const StructRNA *srna = RNA_property_pointer_type(ptr, this_prop);
+ EnumPropertyItem *prop_tags;
+ EnumPropertyItem tmp = {0, "", 0, "", ""};
+ int totitem = 0;
+
+ for (const EnumPropertyItem *struct_tags = RNA_struct_property_tag_defines(srna);
+ struct_tags != NULL && struct_tags->identifier != NULL;
+ struct_tags++)
+ {
+ memcpy(&tmp, struct_tags, sizeof(tmp));
+ RNA_enum_item_add(&prop_tags, &totitem, &tmp);
+ }
+ RNA_enum_item_end(&prop_tags, &totitem);
+ *r_free = true;
+
+ return prop_tags;
+}
+
static int rna_Property_array_length_get(PointerRNA *ptr)
{
PropertyRNA *prop = (PropertyRNA *)ptr->data;
@@ -610,6 +648,22 @@ static int rna_Property_array_length_get(PointerRNA *ptr)
return prop->totarraylength;
}
+static void rna_Property_array_dimensions_get(PointerRNA *ptr, int dimensions[RNA_MAX_ARRAY_DIMENSION])
+{
+ PropertyRNA *prop = (PropertyRNA *)ptr->data;
+ rna_idproperty_check(&prop, ptr);
+
+ if (prop->arraydimension > 1) {
+ for (int i = RNA_MAX_ARRAY_DIMENSION; i--; ) {
+ dimensions[i] = (i >= prop->arraydimension) ? 0 : prop->arraylength[i];
+ }
+ }
+ else {
+ memset(dimensions, 0, sizeof(*dimensions) * RNA_MAX_ARRAY_DIMENSION);
+ dimensions[0] = prop->totarraylength;
+ }
+}
+
static int rna_Property_is_registered_get(PointerRNA *ptr)
{
PropertyRNA *prop = (PropertyRNA *)ptr->data;
@@ -808,7 +862,7 @@ static int rna_StringProperty_max_length_get(PointerRNA *ptr)
return ((StringPropertyRNA *)prop)->maxlength;
}
-static EnumPropertyItem *rna_EnumProperty_default_itemf(bContext *C, PointerRNA *ptr,
+static const EnumPropertyItem *rna_EnumProperty_default_itemf(bContext *C, PointerRNA *ptr,
PropertyRNA *prop_parent, bool *r_free)
{
PropertyRNA *prop = (PropertyRNA *)ptr->data;
@@ -854,7 +908,7 @@ static void rna_EnumProperty_items_begin(CollectionPropertyIterator *iter, Point
{
PropertyRNA *prop = (PropertyRNA *)ptr->data;
/* EnumPropertyRNA *eprop; *//* UNUSED */
- EnumPropertyItem *item = NULL;
+ const EnumPropertyItem *item = NULL;
int totitem;
bool free;
@@ -983,21 +1037,32 @@ static int rna_Function_use_self_type_get(PointerRNA *ptr)
/* Blender RNA */
+static int rna_struct_is_publc(CollectionPropertyIterator *UNUSED(iter), void *data)
+{
+ StructRNA *srna = data;
+
+ return !(srna->flag & STRUCT_PUBLIC_NAMESPACE);
+}
+
+
static void rna_BlenderRNA_structs_begin(CollectionPropertyIterator *iter, PointerRNA *ptr)
{
- rna_iterator_listbase_begin(iter, &((BlenderRNA *)ptr->data)->structs, NULL);
+ BlenderRNA *brna = ptr->data;
+ rna_iterator_listbase_begin(iter, &brna->structs, rna_struct_is_publc);
}
/* optional, for faster lookups */
static int rna_BlenderRNA_structs_length(PointerRNA *ptr)
{
- return BLI_listbase_count(&((BlenderRNA *)ptr->data)->structs);
+ BlenderRNA *brna = ptr->data;
+ BLI_assert(brna->structs_len == BLI_listbase_count(&brna->structs));
+ return brna->structs_len;
}
static int rna_BlenderRNA_structs_lookup_int(PointerRNA *ptr, int index, PointerRNA *r_ptr)
{
- StructRNA *srna = BLI_findlink(&((BlenderRNA *)ptr->data)->structs, index);
-
- if (srna) {
+ BlenderRNA *brna = ptr->data;
+ StructRNA *srna = index < brna->structs_len ? BLI_findlink(&brna->structs, index) : NULL;
+ if (srna != NULL) {
RNA_pointer_create(NULL, &RNA_Struct, srna, r_ptr);
return true;
}
@@ -1007,12 +1072,11 @@ static int rna_BlenderRNA_structs_lookup_int(PointerRNA *ptr, int index, Pointer
}
static int rna_BlenderRNA_structs_lookup_string(PointerRNA *ptr, const char *key, PointerRNA *r_ptr)
{
- StructRNA *srna = ((BlenderRNA *)ptr->data)->structs.first;
- for (; srna; srna = srna->cont.next) {
- if (key[0] == srna->identifier[0] && STREQ(key, srna->identifier)) {
- RNA_pointer_create(NULL, &RNA_Struct, srna, r_ptr);
- return true;
- }
+ BlenderRNA *brna = ptr->data;
+ StructRNA *srna = BLI_ghash_lookup(brna->structs_map, (void *)key);
+ if (srna != NULL) {
+ RNA_pointer_create(NULL, &RNA_Struct, srna, r_ptr);
+ return true;
}
return false;
@@ -1086,13 +1150,21 @@ static void rna_def_struct(BlenderRNA *brna)
"rna_iterator_listbase_end", "rna_Struct_functions_get",
NULL, NULL, NULL, NULL);
RNA_def_property_ui_text(prop, "Functions", "");
+
+ prop = RNA_def_property(srna, "property_tags", PROP_COLLECTION, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_struct_type(prop, "EnumPropertyItem");
+ RNA_def_property_collection_funcs(prop, "rna_Struct_property_tags_begin", "rna_iterator_array_next",
+ "rna_iterator_array_end", "rna_iterator_array_get",
+ NULL, NULL, NULL, NULL);
+ RNA_def_property_ui_text(prop, "Property Tags", "Tags that properties can use to influence behavior");
}
static void rna_def_property(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem subtype_items[] = {
+ static const EnumPropertyItem subtype_items[] = {
{PROP_NONE, "NONE", 0, "None", ""},
{PROP_FILEPATH, "FILE_PATH", 0, "File Path", ""},
{PROP_DIRPATH, "DIR_PATH", 0, "Directory Path", ""},
@@ -1116,6 +1188,9 @@ static void rna_def_property(BlenderRNA *brna)
{PROP_LAYER_MEMBER, "LAYER_MEMBERSHIP", 0, "Layer Membership", ""},
{0, NULL, 0, NULL, NULL}
};
+ EnumPropertyItem dummy_prop_tags[] = {
+ {0, NULL, 0, NULL, NULL}
+ };
srna = RNA_def_struct(brna, "Property", NULL);
RNA_def_struct_ui_text(srna, "Property Definition", "RNA property definition");
@@ -1240,6 +1315,13 @@ static void rna_def_property(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_boolean_funcs(prop, "rna_Property_is_library_editable_flag_get", NULL);
RNA_def_property_ui_text(prop, "Library Editable", "Property is editable from linked instances (changes not saved)");
+
+ prop = RNA_def_property(srna, "tags", PROP_ENUM, PROP_NONE);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_enum_items(prop, dummy_prop_tags);
+ RNA_def_property_enum_funcs(prop, "rna_Property_tags_get", NULL, "rna_Property_tags_itemf");
+ RNA_def_property_flag(prop, PROP_REGISTER_OPTIONAL | PROP_ENUM_FLAG);
+ RNA_def_property_ui_text(prop, "Tags", "Subset of tags (defined in parent struct) that are set for this property");
}
static void rna_def_function(BlenderRNA *brna)
@@ -1344,6 +1426,12 @@ static void rna_def_number_property(StructRNA *srna, PropertyType type)
RNA_def_property_int_funcs(prop, "rna_Property_array_length_get", NULL, NULL);
RNA_def_property_ui_text(prop, "Array Length", "Maximum length of the array, 0 means unlimited");
+ prop = RNA_def_property(srna, "array_dimensions", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_array(prop, RNA_MAX_ARRAY_DIMENSION);
+ RNA_def_property_int_funcs(prop, "rna_Property_array_dimensions_get", NULL, NULL);
+ RNA_def_property_ui_text(prop, "Array Dimensions", "Length of each dimension of the array");
+
prop = RNA_def_property(srna, "is_array", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_boolean_funcs(prop, "rna_NumberProperty_is_array_get", NULL);
@@ -1410,7 +1498,7 @@ static void rna_def_enum_property(BlenderRNA *brna, StructRNA *srna)
PropertyRNA *prop;
/* the itemf func is used instead, keep blender happy */
- static EnumPropertyItem default_dummy_items[] = {
+ static const EnumPropertyItem default_dummy_items[] = {
{PROP_NONE, "DUMMY", 0, "Dummy", ""},
{0, NULL, 0, NULL, NULL}
};
diff --git a/source/blender/makesrna/intern/rna_scene.c b/source/blender/makesrna/intern/rna_scene.c
index 8ee49045bc5..07e1c85c788 100644
--- a/source/blender/makesrna/intern/rna_scene.c
+++ b/source/blender/makesrna/intern/rna_scene.c
@@ -58,11 +58,6 @@
#include "RE_engine.h"
#include "RE_pipeline.h"
-#ifdef WITH_QUICKTIME
-# include "quicktime_export.h"
-# include AUD_TYPES_H
-#endif
-
#ifdef WITH_FFMPEG
# include "BKE_writeffmpeg.h"
# include <libavcodec/avcodec.h>
@@ -78,7 +73,7 @@
#include "BLI_threads.h"
#ifdef WITH_OPENEXR
-EnumPropertyItem rna_enum_exr_codec_items[] = {
+const EnumPropertyItem rna_enum_exr_codec_items[] = {
{R_IMF_EXR_CODEC_NONE, "NONE", 0, "None", ""},
{R_IMF_EXR_CODEC_PXR24, "PXR24", 0, "Pxr24 (lossy)", ""},
{R_IMF_EXR_CODEC_ZIP, "ZIP", 0, "ZIP (lossless)", ""},
@@ -88,18 +83,21 @@ EnumPropertyItem rna_enum_exr_codec_items[] = {
{R_IMF_EXR_CODEC_B44, "B44", 0, "B44 (lossy)", ""},
{R_IMF_EXR_CODEC_B44A, "B44A", 0, "B44A (lossy)", ""},
{R_IMF_EXR_CODEC_DWAA, "DWAA", 0, "DWAA (lossy)", ""},
- {R_IMF_EXR_CODEC_DWAB, "DWAB", 0, "DWAB (lossy)", ""},
+ /* NOTE: Commented out for until new OpenEXR is released, see T50673. */
+ /* {R_IMF_EXR_CODEC_DWAB, "DWAB", 0, "DWAB (lossy)", ""}, */
{0, NULL, 0, NULL, NULL}
};
#endif
-EnumPropertyItem uv_sculpt_relaxation_items[] = {
+#ifndef RNA_RUNTIME
+static const EnumPropertyItem uv_sculpt_relaxation_items[] = {
{UV_SCULPT_TOOL_RELAX_LAPLACIAN, "LAPLACIAN", 0, "Laplacian", "Use Laplacian method for relaxation"},
{UV_SCULPT_TOOL_RELAX_HC, "HC", 0, "HC", "Use HC method for relaxation"},
{0, NULL, 0, NULL, NULL}
};
+#endif
-EnumPropertyItem uv_sculpt_tool_items[] = {
+const EnumPropertyItem rna_enum_uv_sculpt_tool_items[] = {
{UV_SCULPT_TOOL_PINCH, "PINCH", 0, "Pinch", "Pinch UVs"},
{UV_SCULPT_TOOL_RELAX, "RELAX", 0, "Relax", "Relax UVs"},
{UV_SCULPT_TOOL_GRAB, "GRAB", 0, "Grab", "Grab UVs"},
@@ -107,15 +105,15 @@ EnumPropertyItem uv_sculpt_tool_items[] = {
};
-EnumPropertyItem rna_enum_snap_target_items[] = {
+const EnumPropertyItem rna_enum_snap_target_items[] = {
{SCE_SNAP_TARGET_CLOSEST, "CLOSEST", 0, "Closest", "Snap closest point onto target"},
- {SCE_SNAP_TARGET_CENTER, "CENTER", 0, "Center", "Snap center onto target"},
+ {SCE_SNAP_TARGET_CENTER, "CENTER", 0, "Center", "Snap transormation center onto target"},
{SCE_SNAP_TARGET_MEDIAN, "MEDIAN", 0, "Median", "Snap median onto target"},
{SCE_SNAP_TARGET_ACTIVE, "ACTIVE", 0, "Active", "Snap active onto target"},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_proportional_falloff_items[] = {
+const EnumPropertyItem rna_enum_proportional_falloff_items[] = {
{PROP_SMOOTH, "SMOOTH", ICON_SMOOTHCURVE, "Smooth", "Smooth falloff"},
{PROP_SPHERE, "SPHERE", ICON_SPHERECURVE, "Sphere", "Spherical falloff"},
{PROP_ROOT, "ROOT", ICON_ROOTCURVE, "Root", "Root falloff"},
@@ -128,7 +126,7 @@ EnumPropertyItem rna_enum_proportional_falloff_items[] = {
};
/* subset of the enum - only curves, missing random and const */
-EnumPropertyItem rna_enum_proportional_falloff_curve_only_items[] = {
+const EnumPropertyItem rna_enum_proportional_falloff_curve_only_items[] = {
{PROP_SMOOTH, "SMOOTH", ICON_SMOOTHCURVE, "Smooth", "Smooth falloff"},
{PROP_SPHERE, "SPHERE", ICON_SPHERECURVE, "Sphere", "Spherical falloff"},
{PROP_ROOT, "ROOT", ICON_ROOTCURVE, "Root", "Root falloff"},
@@ -139,7 +137,7 @@ EnumPropertyItem rna_enum_proportional_falloff_curve_only_items[] = {
};
-EnumPropertyItem rna_enum_proportional_editing_items[] = {
+const EnumPropertyItem rna_enum_proportional_editing_items[] = {
{PROP_EDIT_OFF, "DISABLED", ICON_PROP_OFF, "Disable", "Proportional Editing disabled"},
{PROP_EDIT_ON, "ENABLED", ICON_PROP_ON, "Enable", "Proportional Editing enabled"},
{PROP_EDIT_PROJECTED, "PROJECTED", ICON_PROP_ON, "Projected (2D)",
@@ -150,14 +148,14 @@ EnumPropertyItem rna_enum_proportional_editing_items[] = {
};
/* keep for operators, not used here */
-EnumPropertyItem rna_enum_mesh_select_mode_items[] = {
+const EnumPropertyItem rna_enum_mesh_select_mode_items[] = {
{SCE_SELECT_VERTEX, "VERTEX", ICON_VERTEXSEL, "Vertex", "Vertex selection mode"},
{SCE_SELECT_EDGE, "EDGE", ICON_EDGESEL, "Edge", "Edge selection mode"},
{SCE_SELECT_FACE, "FACE", ICON_FACESEL, "Face", "Face selection mode"},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_snap_element_items[] = {
+const EnumPropertyItem rna_enum_snap_element_items[] = {
{SCE_SNAP_MODE_INCREMENT, "INCREMENT", ICON_SNAP_INCREMENT, "Increment", "Snap to increments of grid"},
{SCE_SNAP_MODE_VERTEX, "VERTEX", ICON_SNAP_VERTEX, "Vertex", "Snap to vertices"},
{SCE_SNAP_MODE_EDGE, "EDGE", ICON_SNAP_EDGE, "Edge", "Snap to edges"},
@@ -166,7 +164,7 @@ EnumPropertyItem rna_enum_snap_element_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_snap_node_element_items[] = {
+const EnumPropertyItem rna_enum_snap_node_element_items[] = {
{SCE_SNAP_MODE_GRID, "GRID", ICON_SNAP_GRID, "Grid", "Snap to grid"},
{SCE_SNAP_MODE_NODE_X, "NODE_X", ICON_SNAP_EDGE, "Node X", "Snap to left/right node border"},
{SCE_SNAP_MODE_NODE_Y, "NODE_Y", ICON_SNAP_EDGE, "Node Y", "Snap to top/bottom node border"},
@@ -174,13 +172,15 @@ EnumPropertyItem rna_enum_snap_node_element_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem snap_uv_element_items[] = {
+#ifndef RNA_RUNTIME
+static const EnumPropertyItem snap_uv_element_items[] = {
{SCE_SNAP_MODE_INCREMENT, "INCREMENT", ICON_SNAP_INCREMENT, "Increment", "Snap to increments of grid"},
{SCE_SNAP_MODE_VERTEX, "VERTEX", ICON_SNAP_VERTEX, "Vertex", "Snap to vertices"},
{0, NULL, 0, NULL, NULL}
};
+#endif
-EnumPropertyItem rna_enum_curve_fit_method_items[] = {
+const EnumPropertyItem rna_enum_curve_fit_method_items[] = {
{CURVE_PAINT_FIT_METHOD_REFIT, "REFIT", 0, "Refit", "Incrementally re-fit the curve (high quality)"},
{CURVE_PAINT_FIT_METHOD_SPLIT, "SPLIT", 0, "Split", "Split the curve until the tolerance is met (fast)"},
{0, NULL, 0, NULL, NULL}};
@@ -264,14 +264,16 @@ EnumPropertyItem rna_enum_curve_fit_method_items[] = {
R_IMF_ENUM_TIFF \
-EnumPropertyItem image_only_type_items[] = {
+#ifdef RNA_RUNTIME
+static const EnumPropertyItem image_only_type_items[] = {
IMAGE_TYPE_ITEMS_IMAGE_ONLY
{0, NULL, 0, NULL, NULL}
};
+#endif
-EnumPropertyItem rna_enum_image_type_items[] = {
+const EnumPropertyItem rna_enum_image_type_items[] = {
{0, "", 0, N_("Image"), NULL},
IMAGE_TYPE_ITEMS_IMAGE_ONLY
@@ -285,13 +287,10 @@ EnumPropertyItem rna_enum_image_type_items[] = {
#ifdef WITH_FFMPEG
{R_IMF_IMTYPE_FFMPEG, "FFMPEG", ICON_FILE_MOVIE, "FFmpeg video", "The most versatile way to output video files"},
#endif
-#ifdef WITH_QUICKTIME
- {R_IMF_IMTYPE_QUICKTIME, "QUICKTIME", ICON_FILE_MOVIE, "QuickTime", "Output video in Quicktime format"},
-#endif
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_image_color_mode_items[] = {
+const EnumPropertyItem rna_enum_image_color_mode_items[] = {
{R_IMF_PLANES_BW, "BW", 0, "BW", "Images get saved in 8 bits grayscale (only PNG, JPEG, TGA, TIF)"},
{R_IMF_PLANES_RGB, "RGB", 0, "RGB", "Images are saved with RGB (color) data"},
{R_IMF_PLANES_RGBA, "RGBA", 0, "RGBA", "Images are saved with RGB and Alpha data (if supported)"},
@@ -304,7 +303,7 @@ EnumPropertyItem rna_enum_image_color_mode_items[] = {
#define IMAGE_COLOR_MODE_RGBA rna_enum_image_color_mode_items[2]
#endif
-EnumPropertyItem rna_enum_image_color_depth_items[] = {
+const EnumPropertyItem rna_enum_image_color_depth_items[] = {
/* 1 (monochrome) not used */
{R_IMF_CHAN_DEPTH_8, "8", 0, "8", "8 bit color channels"},
{R_IMF_CHAN_DEPTH_10, "10", 0, "10", "10 bit color channels"},
@@ -315,13 +314,13 @@ EnumPropertyItem rna_enum_image_color_depth_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_normal_space_items[] = {
+const EnumPropertyItem rna_enum_normal_space_items[] = {
{R_BAKE_SPACE_OBJECT, "OBJECT", 0, "Object", "Bake the normals in object space"},
{R_BAKE_SPACE_TANGENT, "TANGENT", 0, "Tangent", "Bake the normals in tangent space"},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_normal_swizzle_items[] = {
+const EnumPropertyItem rna_enum_normal_swizzle_items[] = {
{R_BAKE_POSX, "POS_X", 0, "+X", ""},
{R_BAKE_POSY, "POS_Y", 0, "+Y", ""},
{R_BAKE_POSZ, "POS_Z", 0, "+Z", ""},
@@ -331,7 +330,7 @@ EnumPropertyItem rna_enum_normal_swizzle_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_bake_save_mode_items[] = {
+const EnumPropertyItem rna_enum_bake_save_mode_items[] = {
{R_BAKE_SAVE_INTERNAL, "INTERNAL", 0, "Internal", "Save the baking map in an internal image data-block"},
{R_BAKE_SAVE_EXTERNAL, "EXTERNAL", 0, "External", "Save the baking map in an external file"},
{0, NULL, 0, NULL, NULL}
@@ -343,19 +342,19 @@ EnumPropertyItem rna_enum_bake_save_mode_items[] = {
"Single file with an encoded stereo pair"},
#define R_IMF_VIEWS_ENUM_MV {R_IMF_VIEWS_MULTIVIEW, "MULTIVIEW", 0, "Multi-View", "Single file with all the views"},
-EnumPropertyItem rna_enum_views_format_items[] = {
+const EnumPropertyItem rna_enum_views_format_items[] = {
R_IMF_VIEWS_ENUM_IND
R_IMF_VIEWS_ENUM_S3D
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_views_format_multilayer_items[] = {
+const EnumPropertyItem rna_enum_views_format_multilayer_items[] = {
R_IMF_VIEWS_ENUM_IND
R_IMF_VIEWS_ENUM_MV
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_views_format_multiview_items[] = {
+const EnumPropertyItem rna_enum_views_format_multiview_items[] = {
R_IMF_VIEWS_ENUM_IND
R_IMF_VIEWS_ENUM_S3D
R_IMF_VIEWS_ENUM_MV
@@ -366,7 +365,7 @@ EnumPropertyItem rna_enum_views_format_multiview_items[] = {
#undef R_IMF_VIEWS_ENUM_S3D
#undef R_IMF_VIEWS_ENUM_MV
-EnumPropertyItem rna_enum_stereo3d_display_items[] = {
+const EnumPropertyItem rna_enum_stereo3d_display_items[] = {
{S3D_DISPLAY_ANAGLYPH, "ANAGLYPH", 0, "Anaglyph",
"Render views for left and right eyes as two differently filtered colors in a single image "
"(anaglyph glasses are required)"},
@@ -379,21 +378,21 @@ EnumPropertyItem rna_enum_stereo3d_display_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_stereo3d_anaglyph_type_items[] = {
+const EnumPropertyItem rna_enum_stereo3d_anaglyph_type_items[] = {
{S3D_ANAGLYPH_REDCYAN, "RED_CYAN", 0, "Red-Cyan", ""},
{S3D_ANAGLYPH_GREENMAGENTA, "GREEN_MAGENTA", 0, "Green-Magenta", ""},
{S3D_ANAGLYPH_YELLOWBLUE, "YELLOW_BLUE", 0, "Yellow-Blue", ""},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_stereo3d_interlace_type_items[] = {
+const EnumPropertyItem rna_enum_stereo3d_interlace_type_items[] = {
{S3D_INTERLACE_ROW, "ROW_INTERLEAVED", 0, "Row Interleaved", ""},
{S3D_INTERLACE_COLUMN, "COLUMN_INTERLEAVED", 0, "Column Interleaved", ""},
{S3D_INTERLACE_CHECKERBOARD, "CHECKERBOARD_INTERLEAVED", 0, "Checkerboard Interleaved", ""},
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_bake_pass_filter_type_items[] = {
+const EnumPropertyItem rna_enum_bake_pass_filter_type_items[] = {
{R_BAKE_PASS_FILTER_NONE, "NONE", 0, "None", ""},
{R_BAKE_PASS_FILTER_AO, "AO", 0, "AO", ""},
{R_BAKE_PASS_FILTER_EMIT, "EMIT", 0, "Emit", ""},
@@ -407,11 +406,12 @@ EnumPropertyItem rna_enum_bake_pass_filter_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_gpencil_interpolation_mode_items[] = {
+#ifndef RNA_RUNTIME
+static const EnumPropertyItem rna_enum_gpencil_interpolation_mode_items[] = {
/* interpolation */
{0, "", 0, N_("Interpolation"), "Standard transitions between keyframes"},
{GP_IPO_LINEAR, "LINEAR", ICON_IPO_LINEAR, "Linear", "Straight-line interpolation between A and B (i.e. no ease in/out)"},
- {GP_IPO_CURVEMAP, "CUSTOM", ICON_IPO_BEZIER, "Custom", "Custom interpolation defined using a curvemap"},
+ {GP_IPO_CURVEMAP, "CUSTOM", ICON_IPO_BEZIER, "Custom", "Custom interpolation defined using a curve map"},
/* easing */
{0, "", 0, N_("Easing (by strength)"), "Predefined inertial transitions, useful for motion graphics (from least to most ''dramatic'')"},
@@ -430,6 +430,7 @@ EnumPropertyItem rna_enum_gpencil_interpolation_mode_items[] = {
{0, NULL, 0, NULL, NULL}
};
+#endif
#ifdef RNA_RUNTIME
@@ -448,6 +449,7 @@ EnumPropertyItem rna_enum_gpencil_interpolation_mode_items[] = {
#include "BKE_colortools.h"
#include "BKE_context.h"
#include "BKE_global.h"
+#include "BKE_idprop.h"
#include "BKE_image.h"
#include "BKE_main.h"
#include "BKE_node.h"
@@ -988,6 +990,11 @@ static char *rna_RenderSettings_path(PointerRNA *UNUSED(ptr))
return BLI_sprintfN("render");
}
+static char *rna_BakeSettings_path(PointerRNA *UNUSED(ptr))
+{
+ return BLI_sprintfN("render.bake");
+}
+
static char *rna_ImageFormatSettings_path(PointerRNA *ptr)
{
ImageFormatData *imf = (ImageFormatData *)ptr->data;
@@ -1116,14 +1123,11 @@ static void rna_ImageFormatSettings_file_format_set(PointerRNA *ptr, int value)
#ifdef WITH_FFMPEG
BKE_ffmpeg_image_type_verify(rd, imf);
#endif
-#ifdef WITH_QUICKTIME
- quicktime_verify_image_type(rd, imf);
-#endif
(void)rd;
}
}
-static EnumPropertyItem *rna_ImageFormatSettings_file_format_itemf(
+static const EnumPropertyItem *rna_ImageFormatSettings_file_format_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
ID *id = ptr->id.data;
@@ -1135,7 +1139,7 @@ static EnumPropertyItem *rna_ImageFormatSettings_file_format_itemf(
}
}
-static EnumPropertyItem *rna_ImageFormatSettings_color_mode_itemf(
+static const EnumPropertyItem *rna_ImageFormatSettings_color_mode_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
ImageFormatData *imf = (ImageFormatData *)ptr->data;
@@ -1180,7 +1184,7 @@ static EnumPropertyItem *rna_ImageFormatSettings_color_mode_itemf(
}
}
-static EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(
+static const EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
ImageFormatData *imf = (ImageFormatData *)ptr->data;
@@ -1192,11 +1196,11 @@ static EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(
const int depth_ok = BKE_imtype_valid_depths(imf->imtype);
const int is_float = ELEM(imf->imtype, R_IMF_IMTYPE_RADHDR, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER);
- EnumPropertyItem *item_8bit = &rna_enum_image_color_depth_items[0];
- EnumPropertyItem *item_10bit = &rna_enum_image_color_depth_items[1];
- EnumPropertyItem *item_12bit = &rna_enum_image_color_depth_items[2];
- EnumPropertyItem *item_16bit = &rna_enum_image_color_depth_items[3];
- EnumPropertyItem *item_32bit = &rna_enum_image_color_depth_items[4];
+ const EnumPropertyItem *item_8bit = &rna_enum_image_color_depth_items[0];
+ const EnumPropertyItem *item_10bit = &rna_enum_image_color_depth_items[1];
+ const EnumPropertyItem *item_12bit = &rna_enum_image_color_depth_items[2];
+ const EnumPropertyItem *item_16bit = &rna_enum_image_color_depth_items[3];
+ const EnumPropertyItem *item_32bit = &rna_enum_image_color_depth_items[4];
int totitem = 0;
EnumPropertyItem *item = NULL;
@@ -1243,7 +1247,7 @@ static EnumPropertyItem *rna_ImageFormatSettings_color_depth_itemf(
}
}
-static EnumPropertyItem *rna_ImageFormatSettings_views_format_itemf(
+static const EnumPropertyItem *rna_ImageFormatSettings_views_format_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
ImageFormatData *imf = (ImageFormatData *)ptr->data;
@@ -1265,7 +1269,7 @@ static EnumPropertyItem *rna_ImageFormatSettings_views_format_itemf(
#ifdef WITH_OPENEXR
/* OpenEXR */
-static EnumPropertyItem *rna_ImageFormatSettings_exr_codec_itemf(
+static const EnumPropertyItem *rna_ImageFormatSettings_exr_codec_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
ImageFormatData *imf = (ImageFormatData *)ptr->data;
@@ -1307,84 +1311,6 @@ static void rna_SceneRender_file_ext_get(PointerRNA *ptr, char *str)
BKE_image_path_ensure_ext_from_imformat(str, &rd->im_format);
}
-#ifdef WITH_QUICKTIME
-static int rna_RenderSettings_qtcodecsettings_codecType_get(PointerRNA *ptr)
-{
- QuicktimeCodecSettings *settings = (QuicktimeCodecSettings *)ptr->data;
-
- return quicktime_rnatmpvalue_from_videocodectype(settings->codecType);
-}
-
-static void rna_RenderSettings_qtcodecsettings_codecType_set(PointerRNA *ptr, int value)
-{
- QuicktimeCodecSettings *settings = (QuicktimeCodecSettings *)ptr->data;
-
- settings->codecType = quicktime_videocodecType_from_rnatmpvalue(value);
-}
-
-static EnumPropertyItem *rna_RenderSettings_qtcodecsettings_codecType_itemf(
- bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
-{
- EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
- QuicktimeCodecTypeDesc *codecTypeDesc;
- int i = 1, totitem = 0;
-
- for (i = 0; i < quicktime_get_num_videocodecs(); i++) {
- codecTypeDesc = quicktime_get_videocodecType_desc(i);
- if (!codecTypeDesc) break;
-
- tmp.value = codecTypeDesc->rnatmpvalue;
- tmp.identifier = codecTypeDesc->codecName;
- tmp.name = codecTypeDesc->codecName;
- RNA_enum_item_add(&item, &totitem, &tmp);
- }
-
- RNA_enum_item_end(&item, &totitem);
- *r_free = true;
-
- return item;
-}
-
-static int rna_RenderSettings_qtcodecsettings_audiocodecType_get(PointerRNA *ptr)
-{
- QuicktimeCodecSettings *settings = (QuicktimeCodecSettings *)ptr->data;
-
- return quicktime_rnatmpvalue_from_audiocodectype(settings->audiocodecType);
-}
-
-static void rna_RenderSettings_qtcodecsettings_audiocodecType_set(PointerRNA *ptr, int value)
-{
- QuicktimeCodecSettings *settings = (QuicktimeCodecSettings *)ptr->data;
-
- settings->audiocodecType = quicktime_audiocodecType_from_rnatmpvalue(value);
-}
-
-static EnumPropertyItem *rna_RenderSettings_qtcodecsettings_audiocodecType_itemf(
- bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
-{
- EnumPropertyItem *item = NULL;
- EnumPropertyItem tmp = {0, "", 0, "", ""};
- QuicktimeCodecTypeDesc *codecTypeDesc;
- int i = 1, totitem = 0;
-
- for (i = 0; i < quicktime_get_num_audiocodecs(); i++) {
- codecTypeDesc = quicktime_get_audiocodecType_desc(i);
- if (!codecTypeDesc) break;
-
- tmp.value = codecTypeDesc->rnatmpvalue;
- tmp.identifier = codecTypeDesc->codecName;
- tmp.name = codecTypeDesc->codecName;
- RNA_enum_item_add(&item, &totitem, &tmp);
- }
-
- RNA_enum_item_end(&item, &totitem);
- *r_free = true;
-
- return item;
-}
-#endif
-
#ifdef WITH_FFMPEG
static void rna_FFmpegSettings_lossless_output_set(PointerRNA *ptr, int value)
{
@@ -1548,7 +1474,7 @@ static void rna_RenderSettings_engine_set(PointerRNA *ptr, int value)
BLI_strncpy_utf8(rd->engine, type->idname, sizeof(rd->engine));
}
-static EnumPropertyItem *rna_RenderSettings_engine_itemf(
+static const EnumPropertyItem *rna_RenderSettings_engine_itemf(
bContext *UNUSED(C), PointerRNA *UNUSED(ptr), PropertyRNA *UNUSED(prop), bool *r_free)
{
RenderEngineType *type;
@@ -1608,6 +1534,18 @@ static void rna_Scene_use_view_map_cache_update(Main *UNUSED(bmain), Scene *UNUS
#endif
}
+static IDProperty *rna_SceneRenderLayer_idprops(PointerRNA *ptr, bool create)
+{
+ SceneRenderLayer *srl = (SceneRenderLayer *)ptr->data;
+
+ if (create && !srl->prop) {
+ IDPropertyTemplate val = {0};
+ srl->prop = IDP_New(IDP_GROUP, &val, "SceneRenderLayer ID properties");
+ }
+
+ return srl->prop;
+}
+
static void rna_SceneRenderLayer_name_set(PointerRNA *ptr, const char *value)
{
Scene *scene = (Scene *)ptr->id.data;
@@ -1712,11 +1650,18 @@ static void rna_SceneRenderLayer_pass_update(Main *bmain, Scene *activescene, Po
Scene *scene = (Scene *)ptr->id.data;
if (scene->nodetree)
- ntreeCompositForceHidden(scene->nodetree);
-
+ ntreeCompositUpdateRLayers(scene->nodetree);
+
rna_Scene_glsl_update(bmain, activescene, ptr);
}
+static void rna_SceneRenderLayer_update_render_passes(ID *id)
+{
+ Scene *scene = (Scene *)id;
+ if (scene->nodetree)
+ ntreeCompositUpdateRLayers(scene->nodetree);
+}
+
static void rna_Scene_use_nodes_update(bContext *C, PointerRNA *ptr)
{
Scene *scene = (Scene *)ptr->data;
@@ -1795,7 +1740,7 @@ static void object_simplify_update(Object *ob)
}
}
-static void rna_Scene_use_simplify_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr)
+static void rna_Scene_use_simplify_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Scene *sce = ptr->id.data;
Scene *sce_iter;
@@ -1806,6 +1751,7 @@ static void rna_Scene_use_simplify_update(Main *bmain, Scene *UNUSED(scene), Poi
object_simplify_update(base->object);
WM_main_add_notifier(NC_GEOM | ND_DATA, NULL);
+ DAG_id_tag_update(&scene->id, 0);
}
static void rna_Scene_simplify_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr)
@@ -1816,6 +1762,13 @@ static void rna_Scene_simplify_update(Main *bmain, Scene *UNUSED(scene), Pointer
rna_Scene_use_simplify_update(bmain, sce, ptr);
}
+static void rna_SceneRenderData_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
+{
+ Scene *sce = ptr->id.data;
+
+ DAG_id_tag_update(&sce->id, 0);
+}
+
static void rna_Scene_use_persistent_data_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
Scene *sce = ptr->id.data;
@@ -2180,6 +2133,14 @@ static void rna_GPUDOFSettings_blades_set(PointerRNA *ptr, const int value)
dofsettings->num_blades = value;
}
+static void rna_GPUDOFSettings_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *UNUSED(ptr))
+{
+ /* TODO(sergey): Can be more selective here. */
+ BKE_sequencer_cache_cleanup();
+ BKE_sequencer_preprocessed_cache_cleanup();
+ WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, scene);
+}
+
static void rna_Stereo3dFormat_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
ID *id = ptr->id.data;
@@ -2497,7 +2458,7 @@ static void rna_def_tool_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem uv_select_mode_items[] = {
+ static const EnumPropertyItem uv_select_mode_items[] = {
{UV_SELECT_VERTEX, "VERTEX", ICON_UV_VERTEXSEL, "Vertex", "Vertex selection mode"},
{UV_SELECT_EDGE, "EDGE", ICON_UV_EDGESEL, "Edge", "Edge selection mode"},
{UV_SELECT_FACE, "FACE", ICON_UV_FACESEL, "Face", "Face selection mode"},
@@ -2509,20 +2470,20 @@ static void rna_def_tool_settings(BlenderRNA *brna)
* with 1st position only for for on/off (and exposed as boolean), while others are mutually
* exclusive options but which will only have any effect when autokey is enabled
*/
- static EnumPropertyItem auto_key_items[] = {
+ static const EnumPropertyItem auto_key_items[] = {
{AUTOKEY_MODE_NORMAL & ~AUTOKEY_ON, "ADD_REPLACE_KEYS", 0, "Add & Replace", ""},
{AUTOKEY_MODE_EDITKEYS & ~AUTOKEY_ON, "REPLACE_KEYS", 0, "Replace", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem retarget_roll_items[] = {
+ static const EnumPropertyItem retarget_roll_items[] = {
{SK_RETARGET_ROLL_NONE, "NONE", 0, "None", "Don't adjust roll"},
{SK_RETARGET_ROLL_VIEW, "VIEW", 0, "View", "Roll bones to face the view"},
{SK_RETARGET_ROLL_JOINT, "JOINT", 0, "Joint", "Roll bone to original joint plane offset"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem sketch_convert_items[] = {
+ static const EnumPropertyItem sketch_convert_items[] = {
{SK_CONVERT_CUT_FIXED, "FIXED", 0, "Fixed", "Subdivide stroke in fixed number of bones"},
{SK_CONVERT_CUT_LENGTH, "LENGTH", 0, "Length", "Subdivide stroke in bones of specific length"},
{SK_CONVERT_CUT_ADAPTATIVE, "ADAPTIVE", 0, "Adaptive",
@@ -2531,7 +2492,7 @@ static void rna_def_tool_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem edge_tag_items[] = {
+ static const EnumPropertyItem edge_tag_items[] = {
{EDGE_MODE_SELECT, "SELECT", 0, "Select", ""},
{EDGE_MODE_TAG_SEAM, "SEAM", 0, "Tag Seam", ""},
{EDGE_MODE_TAG_SHARP, "SHARP", 0, "Tag Sharp", ""},
@@ -2541,21 +2502,21 @@ static void rna_def_tool_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem draw_groupuser_items[] = {
+ static const EnumPropertyItem draw_groupuser_items[] = {
{OB_DRAW_GROUPUSER_NONE, "NONE", 0, "None", ""},
{OB_DRAW_GROUPUSER_ACTIVE, "ACTIVE", 0, "Active", "Show vertices with no weights in the active group"},
{OB_DRAW_GROUPUSER_ALL, "ALL", 0, "All", "Show vertices with no weights in any group"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vertex_group_select_items[] = {
+ static const EnumPropertyItem vertex_group_select_items[] = {
{WT_VGROUP_ALL, "ALL", 0, "All", "All Vertex Groups"},
{WT_VGROUP_BONE_DEFORM, "BONE_DEFORM", 0, "Deform", "Vertex Groups assigned to Deform Bones"},
{WT_VGROUP_BONE_DEFORM_OFF, "OTHER_DEFORM", 0, "Other", "Vertex Groups assigned to non Deform Bones"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem gpencil_source_3d_items[] = {
+ static const EnumPropertyItem gpencil_source_3d_items[] = {
{GP_TOOL_SOURCE_SCENE, "SCENE", 0, "Scene",
"Grease Pencil data attached to the current scene is used, "
"unless the active object already has Grease Pencil data (i.e. for old files)"},
@@ -2565,7 +2526,7 @@ static void rna_def_tool_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem gpencil_stroke_placement_items[] = {
+ static const EnumPropertyItem gpencil_stroke_placement_items[] = {
{GP_PROJECT_VIEWSPACE, "CURSOR", 0, "Cursor", "Draw stroke at the 3D cursor"},
{0, "VIEW", 0, "View", "Stick stroke to the view "}, /* weird, GP_PROJECT_VIEWALIGN is inverted */
{GP_PROJECT_VIEWSPACE | GP_PROJECT_DEPTH_VIEW, "SURFACE", 0, "Surface", "Stick stroke to surfaces"},
@@ -2643,7 +2604,7 @@ static void rna_def_tool_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "uv_sculpt_tool", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "uv_sculpt_tool");
- RNA_def_property_enum_items(prop, uv_sculpt_tool_items);
+ RNA_def_property_enum_items(prop, rna_enum_uv_sculpt_tool_items);
RNA_def_property_ui_text(prop, "UV Sculpt Tools", "Select Tools for the UV sculpt brushes");
prop = RNA_def_property(srna, "uv_relax_method", PROP_ENUM, PROP_NONE);
@@ -3115,7 +3076,7 @@ static void rna_def_curve_paint_settings(BlenderRNA *brna)
RNA_def_struct_path_func(srna, "rna_CurvePaintSettings_path");
RNA_def_struct_ui_text(srna, "Curve Paint Settings", "");
- static EnumPropertyItem curve_type_items[] = {
+ static const EnumPropertyItem curve_type_items[] = {
{CU_POLY, "POLY", 0, "Poly", ""},
{CU_BEZIER, "BEZIER", 0, "Bezier", ""},
{0, NULL, 0, NULL, NULL}};
@@ -3182,7 +3143,7 @@ static void rna_def_curve_paint_settings(BlenderRNA *brna)
RNA_def_property_ui_range(prop, -1.0f, 1.0, 1, 2);
RNA_def_property_ui_text(prop, "Offset", "Offset the stroke from the surface");
- static EnumPropertyItem depth_mode_items[] = {
+ static const EnumPropertyItem depth_mode_items[] = {
{CURVE_PAINT_PROJECT_CURSOR, "CURSOR", 0, "Cursor", ""},
{CURVE_PAINT_PROJECT_SURFACE, "SURFACE", 0, "Surface", ""},
{0, NULL, 0, NULL, NULL}};
@@ -3192,7 +3153,7 @@ static void rna_def_curve_paint_settings(BlenderRNA *brna)
RNA_def_property_enum_items(prop, depth_mode_items);
RNA_def_property_ui_text(prop, "Depth", "Method of projecting depth");
- static EnumPropertyItem surface_plane_items[] = {
+ static const EnumPropertyItem surface_plane_items[] = {
{CURVE_PAINT_SURFACE_PLANE_NORMAL_VIEW, "NORMAL_VIEW", 0, "Normal/View", "Draw perpendicular to the surface"},
{CURVE_PAINT_SURFACE_PLANE_NORMAL_SURFACE, "NORMAL_SURFACE", 0, "Normal/Surface", "Draw aligned to the surface"},
{CURVE_PAINT_SURFACE_PLANE_VIEW, "VIEW", 0, "View", "Draw aligned to the viewport"},
@@ -3209,7 +3170,7 @@ static void rna_def_statvis(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem stat_type[] = {
+ static const EnumPropertyItem stat_type[] = {
{SCE_STATVIS_OVERHANG, "OVERHANG", 0, "Overhang", ""},
{SCE_STATVIS_THICKNESS, "THICKNESS", 0, "Thickness", ""},
{SCE_STATVIS_INTERSECT, "INTERSECT", 0, "Intersect", ""},
@@ -3314,14 +3275,14 @@ static void rna_def_unit_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem unit_systems[] = {
+ static const EnumPropertyItem unit_systems[] = {
{USER_UNIT_NONE, "NONE", 0, "None", ""},
{USER_UNIT_METRIC, "METRIC", 0, "Metric", ""},
{USER_UNIT_IMPERIAL, "IMPERIAL", 0, "Imperial", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem rotation_units[] = {
+ static const EnumPropertyItem rotation_units[] = {
{0, "DEGREES", 0, "Degrees", "Use degrees for measuring angles and rotations"},
{USER_UNIT_ROT_RADIANS, "RADIANS", 0, "Radians", ""},
{0, NULL, 0, NULL, NULL}
@@ -3804,42 +3765,42 @@ static void rna_def_freestyle_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem edge_type_negation_items[] = {
+ static const EnumPropertyItem edge_type_negation_items[] = {
{0, "INCLUSIVE", 0, "Inclusive", "Select feature edges satisfying the given edge type conditions"},
{FREESTYLE_LINESET_FE_NOT, "EXCLUSIVE", 0, "Exclusive",
"Select feature edges not satisfying the given edge type conditions"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem edge_type_combination_items[] = {
+ static const EnumPropertyItem edge_type_combination_items[] = {
{0, "OR", 0, "Logical OR", "Select feature edges satisfying at least one of edge type conditions"},
{FREESTYLE_LINESET_FE_AND, "AND", 0, "Logical AND",
"Select feature edges satisfying all edge type conditions"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem group_negation_items[] = {
+ static const EnumPropertyItem group_negation_items[] = {
{0, "INCLUSIVE", 0, "Inclusive", "Select feature edges belonging to some object in the group"},
{FREESTYLE_LINESET_GR_NOT, "EXCLUSIVE", 0, "Exclusive",
"Select feature edges not belonging to any object in the group"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem face_mark_negation_items[] = {
+ static const EnumPropertyItem face_mark_negation_items[] = {
{0, "INCLUSIVE", 0, "Inclusive", "Select feature edges satisfying the given face mark conditions"},
{FREESTYLE_LINESET_FM_NOT, "EXCLUSIVE", 0, "Exclusive",
"Select feature edges not satisfying the given face mark conditions"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem face_mark_condition_items[] = {
+ static const EnumPropertyItem face_mark_condition_items[] = {
{0, "ONE", 0, "One Face", "Select a feature edge if either of its adjacent faces is marked"},
{FREESTYLE_LINESET_FM_BOTH, "BOTH", 0, "Both Faces",
"Select a feature edge if both of its adjacent faces are marked"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem freestyle_ui_mode_items[] = {
+ static const EnumPropertyItem freestyle_ui_mode_items[] = {
{FREESTYLE_CONTROL_SCRIPT_MODE, "SCRIPT", 0, "Python Scripting Mode",
"Advanced mode for using style modules written in Python"},
{FREESTYLE_CONTROL_EDITOR_MODE, "EDITOR", 0, "Parameter Editor Mode",
@@ -3847,7 +3808,7 @@ static void rna_def_freestyle_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem visibility_items[] = {
+ static const EnumPropertyItem visibility_items[] = {
{FREESTYLE_QI_VISIBLE, "VISIBLE", 0, "Visible", "Select visible feature edges"},
{FREESTYLE_QI_HIDDEN, "HIDDEN", 0, "Hidden", "Select hidden feature edges"},
{FREESTYLE_QI_RANGE, "RANGE", 0, "QI Range",
@@ -4174,7 +4135,7 @@ static void rna_def_scene_game_recast_data(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem rna_enum_partitioning_items[] = {
+ static const EnumPropertyItem rna_enum_partitioning_items[] = {
{RC_PARTITION_WATERSHED, "WATERSHED", 0, "Watershed", "Classic Recast partitioning method generating the nicest tessellation"},
{RC_PARTITION_MONOTONE, "MONOTONE", 0, "Monotone", "Fastest navmesh generation method, may create long thin polygons"},
{RC_PARTITION_LAYERS, "LAYERS", 0, "Layers", "Reasonably fast method that produces better triangles than monotone partitioning"},
@@ -4296,6 +4257,7 @@ static void rna_def_bake_data(BlenderRNA *brna)
RNA_def_struct_sdna(srna, "BakeData");
RNA_def_struct_nested(brna, srna, "RenderSettings");
RNA_def_struct_ui_text(srna, "Bake Data", "Bake data for a Scene data-block");
+ RNA_def_struct_path_func(srna, "rna_BakeSettings_path");
prop = RNA_def_property(srna, "cage_object", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "cage");
@@ -4454,7 +4416,7 @@ static void rna_def_scene_game_data(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem aasamples_items[] = {
+ static const EnumPropertyItem aasamples_items[] = {
{0, "SAMPLES_0", 0, "Off", ""},
{2, "SAMPLES_2", 0, "2x", ""},
{4, "SAMPLES_4", 0, "4x", ""},
@@ -4463,7 +4425,7 @@ static void rna_def_scene_game_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem framing_types_items[] = {
+ static const EnumPropertyItem framing_types_items[] = {
{SCE_GAMEFRAMING_BARS, "LETTERBOX", 0, "Letterbox",
"Show the entire viewport in the display window, using bar horizontally or vertically"},
{SCE_GAMEFRAMING_EXTEND, "EXTEND", 0, "Extend",
@@ -4473,7 +4435,7 @@ static void rna_def_scene_game_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem dome_modes_items[] = {
+ static const EnumPropertyItem dome_modes_items[] = {
{DOME_FISHEYE, "FISHEYE", 0, "Fisheye", ""},
{DOME_TRUNCATED_FRONT, "TRUNCATED_FRONT", 0, "Front-Truncated", ""},
{DOME_TRUNCATED_REAR, "TRUNCATED_REAR", 0, "Rear-Truncated", ""},
@@ -4482,7 +4444,7 @@ static void rna_def_scene_game_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem stereo_modes_items[] = {
+ static const EnumPropertyItem stereo_modes_items[] = {
{STEREO_QUADBUFFERED, "QUADBUFFERED", 0, "Quad-Buffer", ""},
{STEREO_ABOVEBELOW, "ABOVEBELOW", 0, "Above-Below", ""},
{STEREO_INTERLACED, "INTERLACED", 0, "Interlaced", ""},
@@ -4493,40 +4455,40 @@ static void rna_def_scene_game_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem stereo_items[] = {
+ static const EnumPropertyItem stereo_items[] = {
{STEREO_NOSTEREO, "NONE", 0, "None", "Disable Stereo and Dome environments"},
{STEREO_ENABLED, "STEREO", 0, "Stereo", "Enable Stereo environment"},
{STEREO_DOME, "DOME", 0, "Dome", "Enable Dome environment"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem physics_engine_items[] = {
+ static const EnumPropertyItem physics_engine_items[] = {
{WOPHY_NONE, "NONE", 0, "None", "Don't use a physics engine"},
{WOPHY_BULLET, "BULLET", 0, "Bullet", "Use the Bullet physics engine"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem material_items[] = {
+ static const EnumPropertyItem material_items[] = {
{GAME_MAT_MULTITEX, "MULTITEXTURE", 0, "Multitexture", "Multitexture materials"},
{GAME_MAT_GLSL, "GLSL", 0, "GLSL", "OpenGL shading language shaders"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem obstacle_simulation_items[] = {
+ static const EnumPropertyItem obstacle_simulation_items[] = {
{OBSTSIMULATION_NONE, "NONE", 0, "None", ""},
{OBSTSIMULATION_TOI_rays, "RVO_RAYS", 0, "RVO (rays)", ""},
{OBSTSIMULATION_TOI_cells, "RVO_CELLS", 0, "RVO (cells)", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vsync_items[] = {
+ static const EnumPropertyItem vsync_items[] = {
{VSYNC_OFF, "OFF", 0, "Off", "Disable vsync"},
{VSYNC_ON, "ON", 0, "On", "Enable vsync"},
{VSYNC_ADAPTIVE, "ADAPTIVE", 0, "Adaptive", "Enable adaptive vsync (if supported)"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem storage_items[] = {
+ static const EnumPropertyItem storage_items[] = {
{RAS_STORE_AUTO, "AUTO", 0, "Auto Select", "Choose the best supported mode"},
{RAS_STORE_VA, "VERTEX_ARRAY", 0, "Vertex Arrays", "Usually the best choice (good performance with display lists)"},
{RAS_STORE_VBO, "VERTEX_BUFFER_OBJECT", 0, "Vertex Buffer Objects",
@@ -4955,37 +4917,37 @@ static void rna_def_gpu_dof_fx(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Focus distance", "Viewport depth of field focus distance");
RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_ui_range(prop, 0.0f, 5000.0f, 1, 2);
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "focal_length", PROP_FLOAT, PROP_DISTANCE_CAMERA);
RNA_def_property_ui_text(prop, "Focal Length", "Focal length for dof effect");
RNA_def_property_range(prop, 1.0f, FLT_MAX);
RNA_def_property_ui_range(prop, 1.0f, 5000.0f, 1, 2);
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "sensor", PROP_FLOAT, PROP_DISTANCE_CAMERA);
RNA_def_property_ui_text(prop, "Sensor", "Size of sensor");
RNA_def_property_range(prop, 1.0f, FLT_MAX);
RNA_def_property_ui_range(prop, 1.0f, 5000.0f, 1, 2);
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "fstop", PROP_FLOAT, PROP_NONE);
RNA_def_property_ui_text(prop, "F-stop", "F-stop for dof effect");
RNA_def_property_range(prop, 0.0f, FLT_MAX);
RNA_def_property_ui_range(prop, 0.1f, 128.0f, 10, 1);
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "blades", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "num_blades");
RNA_def_property_ui_text(prop, "Blades", "Blades for dof effect");
RNA_def_property_range(prop, 0, 16);
RNA_def_property_int_funcs(prop, NULL, "rna_GPUDOFSettings_blades_set", NULL);
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "use_high_quality", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "high_quality", 1);
RNA_def_property_ui_text(prop, "High Quality", "Use high quality depth of field");
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
+ RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_GPUDOFSettings_update");
prop = RNA_def_property(srna, "is_hq_supported", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_funcs(prop, "rna_gpu_is_hq_supported_get", NULL);
@@ -5072,14 +5034,20 @@ static void rna_def_scene_render_layer(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
+ FunctionRNA *func;
srna = RNA_def_struct(brna, "SceneRenderLayer", NULL);
RNA_def_struct_ui_text(srna, "Scene Render Layer", "Render layer");
RNA_def_struct_ui_icon(srna, ICON_RENDERLAYERS);
RNA_def_struct_path_func(srna, "rna_SceneRenderLayer_path");
+ RNA_def_struct_idprops_func(srna, "rna_SceneRenderLayer_idprops");
rna_def_render_layer_common(srna, 1);
+ func = RNA_def_function(srna, "update_render_passes", "rna_SceneRenderLayer_update_render_passes");
+ RNA_def_function_ui_description(func, "Requery the enabled render passes from the render engine");
+ RNA_def_function_flag(func, FUNC_USE_SELF_ID | FUNC_NO_SELF);
+
/* Freestyle */
rna_def_freestyle_settings(brna);
@@ -5221,7 +5189,7 @@ static void rna_def_image_format_stereo3d_format(BlenderRNA *brna)
PropertyRNA *prop;
/* rna_enum_stereo3d_display_items, without (S3D_DISPLAY_PAGEFLIP) */
- static EnumPropertyItem stereo3d_display_items[] = {
+ static const EnumPropertyItem stereo3d_display_items[] = {
{S3D_DISPLAY_ANAGLYPH, "ANAGLYPH", 0, "Anaglyph",
"Render views for left and right eyes as two differently filtered colors in a single image "
"(anaglyph glasses are required)"},
@@ -5278,7 +5246,7 @@ static void rna_def_scene_image_format_data(BlenderRNA *brna)
{
#ifdef WITH_OPENJPEG
- static EnumPropertyItem jp2_codec_items[] = {
+ static const EnumPropertyItem jp2_codec_items[] = {
{R_IMF_JP2_CODEC_JP2, "JP2", 0, "JP2", ""},
{R_IMF_JP2_CODEC_J2K, "J2K", 0, "J2K", ""},
{0, NULL, 0, NULL, NULL}
@@ -5286,7 +5254,7 @@ static void rna_def_scene_image_format_data(BlenderRNA *brna)
#endif
#ifdef WITH_TIFF
- static EnumPropertyItem tiff_codec_items[] = {
+ static const EnumPropertyItem tiff_codec_items[] = {
{R_IMF_TIFF_CODEC_NONE, "NONE", 0, "None", ""},
{R_IMF_TIFF_CODEC_DEFLATE, "DEFLATE", 0, "Deflate", ""},
{R_IMF_TIFF_CODEC_LZW, "LZW", 0, "LZW", ""},
@@ -5390,7 +5358,7 @@ static void rna_def_scene_image_format_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "jpeg2k_codec", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "jp2_codec");
RNA_def_property_enum_items(prop, jp2_codec_items);
- RNA_def_property_ui_text(prop, "Codec", "Codec settings for Jpek2000");
+ RNA_def_property_ui_text(prop, "Codec", "Codec settings for Jpeg2000");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
#endif
@@ -5461,54 +5429,51 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
#ifdef WITH_FFMPEG
/* Container types */
- static EnumPropertyItem ffmpeg_format_items[] = {
+ static const EnumPropertyItem ffmpeg_format_items[] = {
{FFMPEG_MPEG1, "MPEG1", 0, "MPEG-1", ""},
{FFMPEG_MPEG2, "MPEG2", 0, "MPEG-2", ""},
{FFMPEG_MPEG4, "MPEG4", 0, "MPEG-4", ""},
{FFMPEG_AVI, "AVI", 0, "AVI", ""},
{FFMPEG_MOV, "QUICKTIME", 0, "Quicktime", ""},
{FFMPEG_DV, "DV", 0, "DV", ""},
-// {FFMPEG_H264, "H264", 0, "H.264", ""}, not a container
-// {FFMPEG_XVID, "XVID", 0, "Xvid", ""}, not a container
{FFMPEG_OGG, "OGG", 0, "Ogg", ""},
{FFMPEG_MKV, "MKV", 0, "Matroska", ""},
{FFMPEG_FLV, "FLASH", 0, "Flash", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ffmpeg_codec_items[] = {
- {AV_CODEC_ID_NONE, "NONE", 0, "None", ""},
- {AV_CODEC_ID_MPEG1VIDEO, "MPEG1", 0, "MPEG-1", ""},
- {AV_CODEC_ID_MPEG2VIDEO, "MPEG2", 0, "MPEG-2", ""},
- {AV_CODEC_ID_MPEG4, "MPEG4", 0, "MPEG-4(divx)", ""},
- {AV_CODEC_ID_HUFFYUV, "HUFFYUV", 0, "HuffYUV", ""},
+ static const EnumPropertyItem ffmpeg_codec_items[] = {
+ {AV_CODEC_ID_NONE, "NONE", 0, "No Video", "Disables video output, for audio-only renders"},
+ {AV_CODEC_ID_DNXHD, "DNXHD", 0, "DNxHD", ""},
{AV_CODEC_ID_DVVIDEO, "DV", 0, "DV", ""},
- {AV_CODEC_ID_H264, "H264", 0, "H.264", ""},
- {AV_CODEC_ID_THEORA, "THEORA", 0, "Theora", ""},
- {AV_CODEC_ID_FLV1, "FLASH", 0, "Flash Video", ""},
{AV_CODEC_ID_FFV1, "FFV1", 0, "FFmpeg video codec #1", ""},
- {AV_CODEC_ID_QTRLE, "QTRLE", 0, "QT rle / QT Animation", ""},
- {AV_CODEC_ID_DNXHD, "DNXHD", 0, "DNxHD", ""},
+ {AV_CODEC_ID_FLV1, "FLASH", 0, "Flash Video", ""},
+ {AV_CODEC_ID_H264, "H264", 0, "H.264", ""},
+ {AV_CODEC_ID_HUFFYUV, "HUFFYUV", 0, "HuffYUV", ""},
+ {AV_CODEC_ID_MPEG1VIDEO, "MPEG1", 0, "MPEG-1", ""},
+ {AV_CODEC_ID_MPEG2VIDEO, "MPEG2", 0, "MPEG-2", ""},
+ {AV_CODEC_ID_MPEG4, "MPEG4", 0, "MPEG-4 (divx)", ""},
{AV_CODEC_ID_PNG, "PNG", 0, "PNG", ""},
+ {AV_CODEC_ID_QTRLE, "QTRLE", 0, "QT rle / QT Animation", ""},
+ {AV_CODEC_ID_THEORA, "THEORA", 0, "Theora", ""},
+ {AV_CODEC_ID_VP9, "WEBM", 0, "WEBM / VP9", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ffmpeg_preset_items[] = {
- {FFM_PRESET_ULTRAFAST, "ULTRAFAST", 0, "Ultra fast; biggest file", ""},
- {FFM_PRESET_SUPERFAST, "SUPERFAST", 0, "Super fast", ""},
- {FFM_PRESET_VERYFAST, "VERYFAST", 0, "Very fast", ""},
- {FFM_PRESET_FASTER, "FASTER", 0, "Faster", ""},
- {FFM_PRESET_FAST, "FAST", 0, "Fast", ""},
- {FFM_PRESET_MEDIUM, "MEDIUM", 0, "Medium speed", ""},
- {FFM_PRESET_SLOW, "SLOW", 0, "Slow", ""},
- {FFM_PRESET_SLOWER, "SLOWER", 0, "Slower", ""},
- {FFM_PRESET_VERYSLOW, "VERYSLOW", 0, "Very slow; smallest file", ""},
+ /* Recommendations come from the FFmpeg wiki, https://trac.ffmpeg.org/wiki/Encode/VP9.
+ * The label for BEST has been changed to "Slowest" so that it fits the "Encoding Speed"
+ * property label in the UI. */
+ static const EnumPropertyItem ffmpeg_preset_items[] = {
+ {FFM_PRESET_BEST, "BEST", 0, "Slowest",
+ "Recommended if you have lots of time and want the best compression efficiency"},
+ {FFM_PRESET_GOOD, "GOOD", 0, "Good", "The default and recommended for most applications"},
+ {FFM_PRESET_REALTIME, "REALTIME", 0, "Realtime", "Recommended for fast encoding"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ffmpeg_crf_items[] = {
- {FFM_CRF_NONE, "NONE", 0, "None; use constant bit-rate",
- "Use constant bit rate, rather than constant output quality"},
+ static const EnumPropertyItem ffmpeg_crf_items[] = {
+ {FFM_CRF_NONE, "NONE", 0, "Constant Bitrate",
+ "Configure constant bit rate, rather than constant output quality"},
{FFM_CRF_LOSSLESS, "LOSSLESS", 0, "Lossless", ""},
{FFM_CRF_PERC_LOSSLESS, "PERC_LOSSLESS", 0, "Perceptually lossless", ""},
{FFM_CRF_HIGH, "HIGH", 0, "High quality", ""},
@@ -5519,20 +5484,20 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ffmpeg_audio_codec_items[] = {
- {AV_CODEC_ID_NONE, "NONE", 0, "None", ""},
- {AV_CODEC_ID_MP2, "MP2", 0, "MP2", ""},
- {AV_CODEC_ID_MP3, "MP3", 0, "MP3", ""},
- {AV_CODEC_ID_AC3, "AC3", 0, "AC3", ""},
+ static const EnumPropertyItem ffmpeg_audio_codec_items[] = {
+ {AV_CODEC_ID_NONE, "NONE", 0, "No Audio", "Disables audio output, for video-only renders"},
{AV_CODEC_ID_AAC, "AAC", 0, "AAC", ""},
- {AV_CODEC_ID_VORBIS, "VORBIS", 0, "Vorbis", ""},
+ {AV_CODEC_ID_AC3, "AC3", 0, "AC3", ""},
{AV_CODEC_ID_FLAC, "FLAC", 0, "FLAC", ""},
+ {AV_CODEC_ID_MP2, "MP2", 0, "MP2", ""},
+ {AV_CODEC_ID_MP3, "MP3", 0, "MP3", ""},
{AV_CODEC_ID_PCM_S16LE, "PCM", 0, "PCM", ""},
+ {AV_CODEC_ID_VORBIS, "VORBIS", 0, "Vorbis", ""},
{0, NULL, 0, NULL, NULL}
};
#endif
- static EnumPropertyItem audio_channel_items[] = {
+ static const EnumPropertyItem audio_channel_items[] = {
{1, "MONO", 0, "Mono", "Set audio channels to mono"},
{2, "STEREO", 0, "Stereo", "Set audio channels to stereo"},
{4, "SURROUND4", 0, "4 Channels", "Set audio channels to 4 channels"},
@@ -5559,7 +5524,7 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_enum_items(prop, ffmpeg_codec_items);
RNA_def_property_enum_default(prop, AV_CODEC_ID_H264);
- RNA_def_property_ui_text(prop, "Codec", "FFmpeg codec to use");
+ RNA_def_property_ui_text(prop, "Video Codec", "FFmpeg codec to use for video output");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_FFmpegSettings_codec_settings_update");
prop = RNA_def_property(srna, "video_bitrate", PROP_INT, PROP_NONE);
@@ -5638,7 +5603,7 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
RNA_def_property_enum_bitflag_sdna(prop, NULL, "ffmpeg_preset");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_enum_items(prop, ffmpeg_preset_items);
- RNA_def_property_enum_default(prop, FFM_PRESET_MEDIUM);
+ RNA_def_property_enum_default(prop, FFM_PRESET_GOOD);
RNA_def_property_ui_text(prop, "Encoding speed",
"Tradeoff between encoding speed and compression ratio");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
@@ -5695,112 +5660,12 @@ static void rna_def_scene_ffmpeg_settings(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Audio Channels", "Audio channel count");
}
-#ifdef WITH_QUICKTIME
-static void rna_def_scene_quicktime_settings(BlenderRNA *brna)
-{
- StructRNA *srna;
- PropertyRNA *prop;
-
- static EnumPropertyItem quicktime_codec_type_items[] = {
- {0, "codec", 0, "codec", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
- static EnumPropertyItem quicktime_audio_samplerate_items[] = {
- {22050, "22050", 0, "22kHz", ""},
- {44100, "44100", 0, "44.1kHz", ""},
- {48000, "48000", 0, "48kHz", ""},
- {88200, "88200", 0, "88.2kHz", ""},
- {96000, "96000", 0, "96kHz", ""},
- {192000, "192000", 0, "192kHz", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
- static EnumPropertyItem quicktime_audio_bitdepth_items[] = {
- {AUD_FORMAT_U8, "8BIT", 0, "8bit", ""},
- {AUD_FORMAT_S16, "16BIT", 0, "16bit", ""},
- {AUD_FORMAT_S24, "24BIT", 0, "24bit", ""},
- {AUD_FORMAT_S32, "32BIT", 0, "32bit", ""},
- {AUD_FORMAT_FLOAT32, "FLOAT32", 0, "float32", ""},
- {AUD_FORMAT_FLOAT64, "FLOAT64", 0, "float64", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
- static EnumPropertyItem quicktime_audio_bitrate_items[] = {
- {64000, "64000", 0, "64kbps", ""},
- {112000, "112000", 0, "112kpbs", ""},
- {128000, "128000", 0, "128kbps", ""},
- {192000, "192000", 0, "192kbps", ""},
- {256000, "256000", 0, "256kbps", ""},
- {320000, "320000", 0, "320kbps", ""},
- {0, NULL, 0, NULL, NULL}
- };
-
- /* QuickTime */
- srna = RNA_def_struct(brna, "QuickTimeSettings", NULL);
- RNA_def_struct_sdna(srna, "QuicktimeCodecSettings");
- RNA_def_struct_ui_text(srna, "QuickTime Settings", "QuickTime related settings for the scene");
-
- prop = RNA_def_property(srna, "codec_type", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_bitflag_sdna(prop, NULL, "codecType");
- RNA_def_property_enum_items(prop, quicktime_codec_type_items);
- RNA_def_property_enum_funcs(prop, "rna_RenderSettings_qtcodecsettings_codecType_get",
- "rna_RenderSettings_qtcodecsettings_codecType_set",
- "rna_RenderSettings_qtcodecsettings_codecType_itemf");
- RNA_def_property_ui_text(prop, "Codec", "QuickTime codec type");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "codec_spatial_quality", PROP_INT, PROP_PERCENTAGE);
- RNA_def_property_int_sdna(prop, NULL, "codecSpatialQuality");
- RNA_def_property_range(prop, 0, 100);
- RNA_def_property_ui_text(prop, "Spatial quality", "Intra-frame spatial quality level");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audiocodec_type", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_bitflag_sdna(prop, NULL, "audiocodecType");
- RNA_def_property_enum_items(prop, quicktime_codec_type_items);
- RNA_def_property_enum_funcs(prop, "rna_RenderSettings_qtcodecsettings_audiocodecType_get",
- "rna_RenderSettings_qtcodecsettings_audiocodecType_set",
- "rna_RenderSettings_qtcodecsettings_audiocodecType_itemf");
- RNA_def_property_ui_text(prop, "Audio Codec", "QuickTime audio codec type");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audio_samplerate", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_bitflag_sdna(prop, NULL, "audioSampleRate");
- RNA_def_property_enum_items(prop, quicktime_audio_samplerate_items);
- RNA_def_property_ui_text(prop, "Smp Rate", "Sample Rate");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audio_bitdepth", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_bitflag_sdna(prop, NULL, "audioBitDepth");
- RNA_def_property_enum_items(prop, quicktime_audio_bitdepth_items);
- RNA_def_property_ui_text(prop, "Bit Depth", "Bit Depth");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audio_resampling_hq", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_negative_sdna(prop, NULL, "audioCodecFlags", QTAUDIO_FLAG_RESAMPLE_NOHQ);
- RNA_def_property_ui_text(prop, "HQ", "Use High Quality resampling algorithm");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audio_codec_isvbr", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_negative_sdna(prop, NULL, "audioCodecFlags", QTAUDIO_FLAG_CODEC_ISCBR);
- RNA_def_property_ui_text(prop, "VBR", "Use Variable Bit Rate compression (improves quality at same bitrate)");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-
- prop = RNA_def_property(srna, "audio_bitrate", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_bitflag_sdna(prop, NULL, "audioBitRate");
- RNA_def_property_enum_items(prop, quicktime_audio_bitrate_items);
- RNA_def_property_ui_text(prop, "Bitrate", "Compressed audio bitrate");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-}
-#endif
-
static void rna_def_scene_render_data(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem pixel_filter_items[] = {
+ static const EnumPropertyItem pixel_filter_items[] = {
{R_FILTER_BOX, "BOX", 0, "Box", "Use a box filter for anti-aliasing"},
{R_FILTER_TENT, "TENT", 0, "Tent", "Use a tent filter for anti-aliasing"},
{R_FILTER_QUAD, "QUADRATIC", 0, "Quadratic", "Use a quadratic filter for anti-aliasing"},
@@ -5811,13 +5676,13 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem alpha_mode_items[] = {
+ static const EnumPropertyItem alpha_mode_items[] = {
{R_ADDSKY, "SKY", 0, "Sky", "Transparent pixels are filled with sky color"},
{R_ALPHAPREMUL, "TRANSPARENT", 0, "Transparent", "World background is transparent with premultiplied alpha"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem display_mode_items[] = {
+ static const EnumPropertyItem display_mode_items[] = {
{R_OUTPUT_SCREEN, "SCREEN", 0, "Full Screen", "Images are rendered in full Screen"},
{R_OUTPUT_AREA, "AREA", 0, "Image Editor", "Images are rendered in Image Editor"},
{R_OUTPUT_WINDOW, "WINDOW", 0, "New Window", "Images are rendered in new Window"},
@@ -5826,7 +5691,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
};
/* Bake */
- static EnumPropertyItem bake_mode_items[] = {
+ static const EnumPropertyItem bake_mode_items[] = {
{RE_BAKE_ALL, "FULL", 0, "Full Render", "Bake everything"},
{RE_BAKE_AO, "AO", 0, "Ambient Occlusion", "Bake ambient occlusion"},
{RE_BAKE_SHADOW, "SHADOW", 0, "Shadow", "Bake shadows"},
@@ -5844,7 +5709,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bake_normal_space_items[] = {
+ static const EnumPropertyItem bake_normal_space_items[] = {
{R_BAKE_SPACE_CAMERA, "CAMERA", 0, "Camera", "Bake the normals in camera space"},
{R_BAKE_SPACE_WORLD, "WORLD", 0, "World", "Bake the normals in world space"},
{R_BAKE_SPACE_OBJECT, "OBJECT", 0, "Object", "Bake the normals in object space"},
@@ -5852,14 +5717,23 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bake_qyad_split_items[] = {
+ static const EnumPropertyItem bake_qyad_split_items[] = {
{0, "AUTO", 0, "Automatic", "Split quads to give the least distortion while baking"},
{1, "FIXED", 0, "Fixed", "Split quads predictably (0,1,2) (0,2,3)"},
{2, "FIXED_ALT", 0, "Fixed Alternate", "Split quads predictably (1,2,3) (1,3,0)"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem octree_resolution_items[] = {
+ static const EnumPropertyItem pixel_size_items[] = {
+ {0, "AUTO", 0, "Automatic", "Automatic pixel size, depends on the UI scale"},
+ {1, "1", 0, "1x", "Render at full resolution"},
+ {2, "2", 0, "2x", "Render at 50% resolution"},
+ {4, "4", 0, "4x", "Render at 25% resolution"},
+ {8, "8", 0, "8x", "Render at 12.5% resolution"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ static const EnumPropertyItem octree_resolution_items[] = {
{64, "64", 0, "64", ""},
{128, "128", 0, "128", ""},
{256, "256", 0, "256", ""},
@@ -5867,7 +5741,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem raytrace_structure_items[] = {
+ static const EnumPropertyItem raytrace_structure_items[] = {
{R_RAYSTRUCTURE_AUTO, "AUTO", 0, "Auto", "Automatically select acceleration structure"},
{R_RAYSTRUCTURE_OCTREE, "OCTREE", 0, "Octree", "Use old Octree structure"},
{R_RAYSTRUCTURE_VBVH, "VBVH", 0, "vBVH", "Use vBVH"},
@@ -5876,7 +5750,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem fixed_oversample_items[] = {
+ static const EnumPropertyItem fixed_oversample_items[] = {
{5, "5", 0, "5", ""},
{8, "8", 0, "8", ""},
{11, "11", 0, "11", ""},
@@ -5884,31 +5758,31 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem field_order_items[] = {
+ static const EnumPropertyItem field_order_items[] = {
{0, "EVEN_FIRST", 0, "Upper First", "Upper field first"},
{R_ODDFIELD, "ODD_FIRST", 0, "Lower First", "Lower field first"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem threads_mode_items[] = {
+ static const EnumPropertyItem threads_mode_items[] = {
{0, "AUTO", 0, "Auto-detect", "Automatically determine the number of threads, based on CPUs"},
{R_FIXED_THREADS, "FIXED", 0, "Fixed", "Manually determine the number of threads"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem engine_items[] = {
+ static const EnumPropertyItem engine_items[] = {
{0, "BLENDER_RENDER", 0, "Blender Render", "Use the Blender internal rendering engine for rendering"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem freestyle_thickness_items[] = {
+ static const EnumPropertyItem freestyle_thickness_items[] = {
{R_LINE_THICKNESS_ABSOLUTE, "ABSOLUTE", 0, "Absolute", "Specify unit line thickness in pixels"},
{R_LINE_THICKNESS_RELATIVE, "RELATIVE", 0, "Relative",
"Unit line thickness is scaled by the proportion of the present vertical image "
"resolution to 480 pixels"},
{0, NULL, 0, NULL, NULL}};
- static EnumPropertyItem views_format_items[] = {
+ static const EnumPropertyItem views_format_items[] = {
{SCE_VIEWS_FORMAT_STEREO_3D, "STEREO_3D", 0, "Stereo 3D",
"Single stereo camera system, adjust the stereo settings in the camera panel"},
{SCE_VIEWS_FORMAT_MULTIVIEW, "MULTIVIEW", 0, "Multi-View",
@@ -5919,9 +5793,6 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
rna_def_scene_ffmpeg_settings(brna);
-#ifdef WITH_QUICKTIME
- rna_def_scene_quicktime_settings(brna);
-#endif
srna = RNA_def_struct(brna, "RenderSettings", NULL);
RNA_def_struct_sdna(srna, "RenderData");
@@ -5982,6 +5853,12 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
"progressively increasing it to the full viewport size");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ prop = RNA_def_property(srna, "preview_pixel_size", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "preview_pixel_size");
+ RNA_def_property_enum_items(prop, pixel_size_items);
+ RNA_def_property_ui_text(prop, "Pixel Size", "Pixel size for viewport rendering");
+ RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_SceneRenderData_update");
+
prop = RNA_def_property(srna, "pixel_aspect_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "xasp");
RNA_def_property_flag(prop, PROP_PROPORTIONAL);
@@ -6000,14 +5877,6 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
"Vertical aspect ratio - for anamorphic or non-square pixel output");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_SceneCamera_update");
-#ifdef WITH_QUICKTIME
- prop = RNA_def_property(srna, "quicktime", PROP_POINTER, PROP_NONE);
- RNA_def_property_struct_type(prop, "QuickTimeSettings");
- RNA_def_property_pointer_sdna(prop, NULL, "qtcodecsettings");
- RNA_def_property_flag(prop, PROP_NEVER_UNLINK);
- RNA_def_property_ui_text(prop, "QuickTime Settings", "QuickTime related settings for the scene");
-#endif
-
prop = RNA_def_property(srna, "ffmpeg", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "FFmpegSettings");
RNA_def_property_pointer_sdna(prop, NULL, "ffcodecdata");
@@ -6017,14 +5886,16 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "fps", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "frs_sec");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_range(prop, 1, 120);
+ RNA_def_property_range(prop, 1, SHRT_MAX);
+ RNA_def_property_ui_range(prop, 1, 120, 1, -1);
RNA_def_property_ui_text(prop, "FPS", "Framerate, expressed in frames per second");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_fps_update");
prop = RNA_def_property(srna, "fps_base", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "frs_sec_base");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_range(prop, 0.1f, 120.0f);
+ RNA_def_property_range(prop, 1e-5f, 1e6f);
+ RNA_def_property_ui_range(prop, 0.1f, 120.0f, 2, -1);
RNA_def_property_ui_text(prop, "FPS Base", "Framerate base");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_fps_update");
@@ -6214,8 +6085,8 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "motion_blur_shutter", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "blurfac");
RNA_def_property_ui_range(prop, 0.01f, 2.0f, 1, 2);
- RNA_def_property_ui_text(prop, "Shutter", "Time taken in frames between shutter open and close");
- RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
+ RNA_def_property_ui_text(prop, "Shutter", "Time taken in frames between shutter open and close "
+ "(NOTE: Blender Internal does not support animated shutter)");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, "rna_Scene_glsl_update");
prop = RNA_def_property(srna, "motion_blur_shutter_curve", PROP_POINTER, PROP_NONE);
@@ -6481,7 +6352,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_stamp_date", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_DATE);
- RNA_def_property_ui_text(prop, "Stamp Date", "Include the current date in image metadata");
+ RNA_def_property_ui_text(prop, "Stamp Date", "Include the current date in image/video metadata");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
prop = RNA_def_property(srna, "use_stamp_frame", PROP_BOOLEAN, PROP_NONE);
@@ -6489,6 +6360,11 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Stamp Frame", "Include the frame number in image metadata");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+ prop = RNA_def_property(srna, "use_stamp_frame_range", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_FRAME_RANGE);
+ RNA_def_property_ui_text(prop, "Stamp Frame", "Include the rendered frame range in image/video metadata");
+ RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
+
prop = RNA_def_property(srna, "use_stamp_camera", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_CAMERA);
RNA_def_property_ui_text(prop, "Stamp Camera", "Include the name of the active camera in image metadata");
@@ -6501,12 +6377,12 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_stamp_scene", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_SCENE);
- RNA_def_property_ui_text(prop, "Stamp Scene", "Include the name of the active scene in image metadata");
+ RNA_def_property_ui_text(prop, "Stamp Scene", "Include the name of the active scene in image/video metadata");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
prop = RNA_def_property(srna, "use_stamp_note", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_NOTE);
- RNA_def_property_ui_text(prop, "Stamp Note", "Include a custom note in image metadata");
+ RNA_def_property_ui_text(prop, "Stamp Note", "Include a custom note in image/video metadata");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
prop = RNA_def_property(srna, "use_stamp_marker", PROP_BOOLEAN, PROP_NONE);
@@ -6516,7 +6392,7 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_stamp_filename", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "stamp", R_STAMP_FILENAME);
- RNA_def_property_ui_text(prop, "Stamp Filename", "Include the .blend filename in image metadata");
+ RNA_def_property_ui_text(prop, "Stamp Filename", "Include the .blend filename in image/video metadata");
RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
prop = RNA_def_property(srna, "use_stamp_sequencer_strip", PROP_BOOLEAN, PROP_NONE);
@@ -6577,11 +6453,6 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
/* sequencer draw options */
- prop = RNA_def_property(srna, "use_sequencer_gl_preview", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_GL_PREV);
- RNA_def_property_ui_text(prop, "Sequencer OpenGL", "");
- RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SceneSequencer_update");
-
#if 0 /* see R_SEQ_GL_REND comment */
prop = RNA_def_property(srna, "use_sequencer_gl_render", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_GL_REND);
@@ -6594,16 +6465,24 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Sequencer Preview Shading", "Method to draw in the sequencer view");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SceneSequencer_update");
+#if 0 /* UNUSED, see R_SEQ_GL_REND comment */
prop = RNA_def_property(srna, "sequencer_gl_render", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "seq_rend_type");
RNA_def_property_enum_items(prop, rna_enum_viewport_shade_items);
+ /* XXX Label and tooltips are obviously wrong! */
RNA_def_property_ui_text(prop, "Sequencer Preview Shading", "Method to draw in the sequencer view");
+#endif
prop = RNA_def_property(srna, "use_sequencer_gl_textured_solid", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_SOLID_TEX);
RNA_def_property_ui_text(prop, "Textured Solid", "Draw face-assigned textures in solid draw method");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SceneSequencer_update");
+ prop = RNA_def_property(srna, "use_sequencer_gl_dof", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "seq_flag", R_SEQ_CAMERA_DOF);
+ RNA_def_property_ui_text(prop, "Depth of Field", "Use depth of field using the values from scene strip active camera");
+ RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SceneSequencer_update");
+
/* layers */
prop = RNA_def_property(srna, "layers", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "layers", NULL);
@@ -6742,14 +6621,6 @@ static void rna_def_scene_render_data(BlenderRNA *brna)
RNA_def_property_struct_type(prop, "BakeSettings");
RNA_def_property_ui_text(prop, "Bake Data", "");
- /* Debugging settings. */
-#ifdef WITH_CYCLES_DEBUG
- prop = RNA_def_property(srna, "debug_pass_type", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_items(prop, rna_enum_render_pass_debug_type_items);
- RNA_def_property_ui_text(prop, "Debug Pass Type", "Type of the debug pass to use");
- RNA_def_property_update(prop, NC_SCENE | ND_RENDER_OPTIONS, NULL);
-#endif
-
/* Nestled Data */
/* *** Non-Animated *** */
RNA_define_animate_sdna(false);
@@ -6968,7 +6839,7 @@ static void rna_def_display_safe_areas(BlenderRNA *brna)
RNA_def_property_array(prop, 2);
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_float_array_default(prop, default_title);
- RNA_def_property_ui_text(prop, "Title Safe margins", "Safe area for text and graphics");
+ RNA_def_property_ui_text(prop, "Title Safe Margins", "Safe area for text and graphics");
RNA_def_property_update(prop, NC_SCENE | ND_DRAW_RENDER_VIEWPORT, NULL);
prop = RNA_def_property(srna, "action", PROP_FLOAT, PROP_XYZ);
@@ -6979,7 +6850,6 @@ static void rna_def_display_safe_areas(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Action Safe Margins", "Safe area for general elements");
RNA_def_property_update(prop, NC_SCENE | ND_DRAW_RENDER_VIEWPORT, NULL);
-
prop = RNA_def_property(srna, "title_center", PROP_FLOAT, PROP_XYZ);
RNA_def_property_float_sdna(prop, NULL, "title_center");
RNA_def_property_array(prop, 2);
@@ -7006,7 +6876,7 @@ void RNA_def_scene(BlenderRNA *brna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem audio_distance_model_items[] = {
+ static const EnumPropertyItem audio_distance_model_items[] = {
{0, "NONE", 0, "None", "No distance attenuation"},
{1, "INVERSE", 0, "Inverse", "Inverse distance model"},
{2, "INVERSE_CLAMPED", 0, "Inverse Clamped", "Inverse distance model with clamping"},
@@ -7017,7 +6887,7 @@ void RNA_def_scene(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem sync_mode_items[] = {
+ static const EnumPropertyItem sync_mode_items[] = {
{0, "NONE", 0, "No Sync", "Do not sync, play every frame"},
{SCE_FRAME_DROP, "FRAME_DROP", 0, "Frame Dropping", "Drop frames if playback is too slow"},
{AUDIO_SYNC, "AUDIO_SYNC", 0, "AV-sync", "Sync to audio playback, dropping frames"},
diff --git a/source/blender/makesrna/intern/rna_scene_api.c b/source/blender/makesrna/intern/rna_scene_api.c
index fe781a309a4..e6d030877d7 100644
--- a/source/blender/makesrna/intern/rna_scene_api.c
+++ b/source/blender/makesrna/intern/rna_scene_api.c
@@ -49,7 +49,7 @@
# include "../../alembic/ABC_alembic.h"
#endif
-EnumPropertyItem rna_enum_abc_compression_items[] = {
+const EnumPropertyItem rna_enum_abc_compression_items[] = {
#ifdef WITH_ALEMBIC
{ ABC_ARCHIVE_OGAWA, "OGAWA", 0, "Ogawa", "" },
{ ABC_ARCHIVE_HDF5, "HDF5", 0, "HDF5", "" },
@@ -75,7 +75,7 @@ EnumPropertyItem rna_enum_abc_compression_items[] = {
# include "BPY_extern.h"
#endif
-static void rna_Scene_frame_set(Scene *scene, int frame, float subframe)
+static void rna_Scene_frame_set(Scene *scene, Main *bmain, int frame, float subframe)
{
double cfra = (double)frame + (double)subframe;
@@ -87,7 +87,7 @@ static void rna_Scene_frame_set(Scene *scene, int frame, float subframe)
#endif
/* It's possible that here we're including layers which were never visible before. */
- BKE_scene_update_for_newframe_ex(G.main->eval_ctx, G.main, scene, (1 << 20) - 1, true);
+ BKE_scene_update_for_newframe_ex(bmain->eval_ctx, bmain, scene, (1 << 20) - 1, true);
#ifdef WITH_PYTHON
BPy_END_ALLOW_THREADS;
@@ -112,7 +112,7 @@ static void rna_Scene_uvedit_aspect(Scene *scene, Object *ob, float *aspect)
if ((ob->type == OB_MESH) && (ob->mode == OB_MODE_EDIT)) {
BMEditMesh *em;
em = BKE_editmesh_from_object(ob);
- if (EDBM_mtexpoly_check(em)) {
+ if (EDBM_uv_check(em)) {
ED_uvedit_get_aspect(scene, ob, em->bm, aspect, aspect + 1);
return;
}
@@ -121,13 +121,13 @@ static void rna_Scene_uvedit_aspect(Scene *scene, Object *ob, float *aspect)
aspect[0] = aspect[1] = 1.0f;
}
-static void rna_Scene_update_tagged(Scene *scene)
+static void rna_Scene_update_tagged(Scene *scene, Main *bmain)
{
#ifdef WITH_PYTHON
BPy_BEGIN_ALLOW_THREADS;
#endif
- BKE_scene_update_tagged(G.main->eval_ctx, G.main, scene);
+ BKE_scene_update_tagged(bmain->eval_ctx, bmain, scene);
#ifdef WITH_PYTHON
BPy_END_ALLOW_THREADS;
@@ -164,7 +164,6 @@ static void rna_Scene_ray_cast(
bool ret = ED_transform_snap_object_project_ray_ex(
sctx,
- SCE_SNAP_MODE_FACE,
&(const struct SnapObjectParams){
.snap_select = SNAP_ALL,
},
@@ -208,6 +207,8 @@ static void rna_Scene_alembic_export(
int renderable_only,
int face_sets,
int use_subdiv_schema,
+ int export_hair,
+ int export_particles,
int compression_type,
int packuv,
float scale,
@@ -225,8 +226,8 @@ static void rna_Scene_alembic_export(
.frame_start = frame_start,
.frame_end = frame_end,
- .frame_step_xform = 1.0 / (double)xform_samples,
- .frame_step_shape = 1.0 / (double)geom_samples,
+ .frame_samples_xform = xform_samples,
+ .frame_samples_shape = geom_samples,
.shutter_open = shutter_open,
.shutter_close = shutter_close,
@@ -241,16 +242,18 @@ static void rna_Scene_alembic_export(
.renderable_only = renderable_only,
.face_sets = face_sets,
.use_subdiv_schema = use_subdiv_schema,
+ .export_hair = export_hair,
+ .export_particles = export_particles,
.compression_type = compression_type,
.packuv = packuv,
- .triangulate = triangulate,
- .quad_method = quad_method,
- .ngon_method = ngon_method,
+ .triangulate = triangulate,
+ .quad_method = quad_method,
+ .ngon_method = ngon_method,
.global_scale = scale,
};
- ABC_export(scene, C, filepath, &params);
+ ABC_export(scene, C, filepath, &params, true);
#ifdef WITH_PYTHON
BPy_END_ALLOW_THREADS;
@@ -259,42 +262,6 @@ static void rna_Scene_alembic_export(
#endif
-#ifdef WITH_COLLADA
-/* don't remove this, as COLLADA exporting cannot be done through operators in render() callback. */
-#include "../../collada/collada.h"
-
-static void rna_Scene_collada_export(
- Scene *scene,
- const char *filepath,
- int apply_modifiers,
- int export_mesh_type,
-
- int selected,
- int include_children,
- int include_armatures,
- int include_shapekeys,
- int deform_bones_only,
-
- int active_uv_only,
- int include_uv_textures,
- int include_material_textures,
- int use_texture_copies,
-
- int use_ngons,
- int use_object_instantiation,
- int use_blender_profile,
- int sort_by_name,
- int open_sim,
- int export_transformation_type)
-{
- collada_export(scene, filepath, apply_modifiers, export_mesh_type, selected,
- include_children, include_armatures, include_shapekeys, deform_bones_only,
- active_uv_only, include_uv_textures, include_material_textures,
- use_texture_copies, use_ngons, use_object_instantiation, use_blender_profile, sort_by_name, export_transformation_type, open_sim);
-}
-
-#endif
-
#else
void RNA_api_scene(StructRNA *srna)
@@ -307,10 +274,12 @@ void RNA_api_scene(StructRNA *srna)
parm = RNA_def_int(func, "frame", 0, MINAFRAME, MAXFRAME, "", "Frame number to set", MINAFRAME, MAXFRAME);
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
RNA_def_float(func, "subframe", 0.0, 0.0, 1.0, "", "Sub-frame time, between 0.0 and 1.0", 0.0, 1.0);
+ RNA_def_function_flag(func, FUNC_USE_MAIN);
func = RNA_def_function(srna, "update", "rna_Scene_update_tagged");
RNA_def_function_ui_description(func,
"Update data tagged to be updated from previous access to data or operators");
+ RNA_def_function_flag(func, FUNC_USE_MAIN);
func = RNA_def_function(srna, "uvedit_aspect", "rna_Scene_uvedit_aspect");
RNA_def_function_ui_description(func, "Get uv aspect for current object");
@@ -348,41 +317,10 @@ void RNA_api_scene(StructRNA *srna)
parm = RNA_def_float_matrix(func, "matrix", 4, 4, NULL, 0.0f, 0.0f, "", "Matrix", 0.0f, 0.0f);
RNA_def_function_output(func, parm);
-#ifdef WITH_COLLADA
- /* don't remove this, as COLLADA exporting cannot be done through operators in render() callback. */
- func = RNA_def_function(srna, "collada_export", "rna_Scene_collada_export");
- parm = RNA_def_string(func, "filepath", NULL, FILE_MAX, "File Path", "File path to write Collada file");
- RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
- RNA_def_property_subtype(parm, PROP_FILEPATH); /* allow non utf8 */
- RNA_def_boolean(func, "apply_modifiers", 0, "Apply Modifiers", "Apply modifiers");
- RNA_def_int(func, "export_mesh_type", 0, INT_MIN, INT_MAX,
- "Resolution", "Modifier resolution for export", INT_MIN, INT_MAX);
- RNA_def_boolean(func, "selected", 0, "Selection Only", "Export only selected elements");
- RNA_def_boolean(func, "include_children", 0, "Include Children", "Export all children of selected objects (even if not selected)");
- RNA_def_boolean(func, "include_armatures", 0, "Include Armatures", "Export related armatures (even if not selected)");
- RNA_def_boolean(func, "include_shapekeys", 0, "Include Shape Keys", "Export all Shape Keys from Mesh Objects");
- RNA_def_boolean(func, "deform_bones_only", 0, "Deform Bones only", "Only export deforming bones with armatures");
-
- RNA_def_boolean(func, "active_uv_only", 0, "Active UV Layer only", "Export only the active UV Layer");
- RNA_def_boolean(func, "include_uv_textures", 0, "Include UV Textures", "Export textures assigned to the object UV maps");
- RNA_def_boolean(func, "include_material_textures", 0, "Include Material Textures", "Export textures assigned to the object Materials");
- RNA_def_boolean(func, "use_texture_copies", 0, "copy", "Copy textures to same folder where the .dae file is exported");
-
- RNA_def_boolean(func, "use_ngons", 1, "Use NGons", "Keep NGons in Export");
- RNA_def_boolean(func, "use_object_instantiation", 1, "Use Object Instances", "Instantiate multiple Objects from same Data");
- RNA_def_boolean(func, "use_blender_profile", 1, "Use Blender Profile", "Export additional Blender specific information (for material, shaders, bones, etc.)");
- RNA_def_boolean(func, "sort_by_name", 0, "Sort by Object name", "Sort exported data by Object name");
- RNA_def_boolean(func, "open_sim", 0, "Export for SL/OpenSim", "Compatibility mode for SL, OpenSim and similar online worlds");
-
- RNA_def_int(func, "export_transformation_type", 0, INT_MIN, INT_MAX,
- "Transformation", "Transformation type for translation, scale and rotation", INT_MIN, INT_MAX);
-
- RNA_def_function_ui_description(func, "Export to collada file");
-#endif
-
#ifdef WITH_ALEMBIC
+ /* XXX Deprecated, will be removed in 2.8 in favour of calling the export operator. */
func = RNA_def_function(srna, "alembic_export", "rna_Scene_alembic_export");
- RNA_def_function_ui_description(func, "Export to Alembic file");
+ RNA_def_function_ui_description(func, "Export to Alembic file (deprecated, use the Alembic export operator)");
parm = RNA_def_string(func, "filepath", NULL, FILE_MAX, "File Path", "File path to write Alembic file");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
@@ -396,7 +334,7 @@ void RNA_api_scene(StructRNA *srna)
RNA_def_float(func, "shutter_close", 1.0f, -1.0f, 1.0f, "Shutter close", "", -1.0f, 1.0f);
RNA_def_boolean(func, "selected_only" , 0, "Selected only", "Export only selected objects");
RNA_def_boolean(func, "uvs" , 1, "UVs", "Export UVs");
- RNA_def_boolean(func, "normals" , 1, "Normals", "Export cormals");
+ RNA_def_boolean(func, "normals" , 1, "Normals", "Export normals");
RNA_def_boolean(func, "vcolors" , 0, "Vertex colors", "Export vertex colors");
RNA_def_boolean(func, "apply_subdiv" , 1, "Subsurfs as meshes", "Export subdivision surfaces as meshes");
RNA_def_boolean(func, "flatten" , 0, "Flatten hierarchy", "Flatten hierarchy");
@@ -404,6 +342,8 @@ void RNA_api_scene(StructRNA *srna)
RNA_def_boolean(func, "renderable_only" , 0, "Renderable objects only", "Export only objects marked renderable in the outliner");
RNA_def_boolean(func, "face_sets" , 0, "Facesets", "Export face sets");
RNA_def_boolean(func, "subdiv_schema", 0, "Use Alembic subdivision Schema", "Use Alembic subdivision Schema");
+ RNA_def_boolean(func, "export_hair", 1, "Export Hair", "Exports hair particle systems as animated curves");
+ RNA_def_boolean(func, "export_particles", 1, "Export Particles", "Exports non-hair particle systems");
RNA_def_enum(func, "compression_type", rna_enum_abc_compression_items, 0, "Compression", "");
RNA_def_boolean(func, "packuv" , 0, "Export with packed UV islands", "Export with packed UV islands");
RNA_def_float(func, "scale", 1.0f, 0.0001f, 1000.0f, "Scale", "Value by which to enlarge or shrink the objects with respect to the world's origin", 0.0001f, 1000.0f);
diff --git a/source/blender/makesrna/intern/rna_screen.c b/source/blender/makesrna/intern/rna_screen.c
index b44e404c364..ce6d60a4ae7 100644
--- a/source/blender/makesrna/intern/rna_screen.c
+++ b/source/blender/makesrna/intern/rna_screen.c
@@ -36,7 +36,7 @@
#include "DNA_screen_types.h"
#include "DNA_scene_types.h"
-EnumPropertyItem rna_enum_region_type_items[] = {
+const EnumPropertyItem rna_enum_region_type_items[] = {
{RGN_TYPE_WINDOW, "WINDOW", 0, "Window", ""},
{RGN_TYPE_HEADER, "HEADER", 0, "Header", ""},
{RGN_TYPE_CHANNELS, "CHANNELS", 0, "Channels", ""},
@@ -123,7 +123,7 @@ static int rna_Screen_fullscreen_get(PointerRNA *ptr)
/* UI compatible list: should not be needed, but for now we need to keep EMPTY
* at least in the static version of this enum for python scripts. */
-static EnumPropertyItem *rna_Area_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_Area_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
/* +1 to skip SPACE_EMPTY */
diff --git a/source/blender/makesrna/intern/rna_sculpt_paint.c b/source/blender/makesrna/intern/rna_sculpt_paint.c
index 40aea37d9d2..6dbfc3634b2 100644
--- a/source/blender/makesrna/intern/rna_sculpt_paint.c
+++ b/source/blender/makesrna/intern/rna_sculpt_paint.c
@@ -27,7 +27,10 @@
#include <stdlib.h>
+#include "BLI_utildefines.h"
+
#include "RNA_define.h"
+#include "RNA_enum_types.h"
#include "rna_internal.h"
@@ -45,10 +48,9 @@
#include "WM_api.h"
#include "WM_types.h"
-#include "BLI_utildefines.h"
#include "bmesh.h"
-static EnumPropertyItem particle_edit_hair_brush_items[] = {
+static const EnumPropertyItem particle_edit_hair_brush_items[] = {
{PE_BRUSH_NONE, "NONE", 0, "None", "Don't use any brush"},
{PE_BRUSH_COMB, "COMB", 0, "Comb", "Comb hairs"},
{PE_BRUSH_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth hairs"},
@@ -60,7 +62,7 @@ static EnumPropertyItem particle_edit_hair_brush_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[] = {
+const EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[] = {
{GP_EDITBRUSH_TYPE_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth stroke points"},
{GP_EDITBRUSH_TYPE_THICKNESS, "THICKNESS", 0, "Thickness", "Adjust thickness of strokes"},
{ GP_EDITBRUSH_TYPE_STRENGTH, "STRENGTH", 0, "Strength", "Adjust color strength of strokes" },
@@ -75,15 +77,17 @@ EnumPropertyItem rna_enum_gpencil_sculpt_brush_items[] = {
{ 0, NULL, 0, NULL, NULL }
};
-EnumPropertyItem rna_enum_gpencil_lockaxis_items[] = {
+#ifndef RNA_RUNTIME
+static const EnumPropertyItem rna_enum_gpencil_lockaxis_items[] = {
{ GP_LOCKAXIS_NONE, "GP_LOCKAXIS_NONE", 0, "None", "" },
{ GP_LOCKAXIS_X, "GP_LOCKAXIS_X", 0, "X", "Project strokes to plane locked to X" },
{ GP_LOCKAXIS_Y, "GP_LOCKAXIS_Y", 0, "Y", "Project strokes to plane locked to Y" },
{ GP_LOCKAXIS_Z, "GP_LOCKAXIS_Z", 0, "Z", "Project strokes to plane locked to Z" },
{ 0, NULL, 0, NULL, NULL }
};
+#endif
-EnumPropertyItem rna_enum_symmetrize_direction_items[] = {
+const EnumPropertyItem rna_enum_symmetrize_direction_items[] = {
{BMO_SYMMETRIZE_NEGATIVE_X, "NEGATIVE_X", 0, "-X to +X", ""},
{BMO_SYMMETRIZE_POSITIVE_X, "POSITIVE_X", 0, "+X to -X", ""},
@@ -114,7 +118,7 @@ static void rna_GPencil_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Pointe
WM_main_add_notifier(NC_GPENCIL | NA_EDITED, NULL);
}
-static EnumPropertyItem particle_edit_disconnected_hair_brush_items[] = {
+static const EnumPropertyItem particle_edit_disconnected_hair_brush_items[] = {
{PE_BRUSH_NONE, "NONE", 0, "None", "Don't use any brush"},
{PE_BRUSH_COMB, "COMB", 0, "Comb", "Comb hairs"},
{PE_BRUSH_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth hairs"},
@@ -124,7 +128,7 @@ static EnumPropertyItem particle_edit_disconnected_hair_brush_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem particle_edit_cache_brush_items[] = {
+static const EnumPropertyItem particle_edit_cache_brush_items[] = {
{PE_BRUSH_NONE, "NONE", 0, "None", "Don't use any brush"},
{PE_BRUSH_COMB, "COMB", 0, "Comb", "Comb paths"},
{PE_BRUSH_SMOOTH, "SMOOTH", 0, "Smooth", "Smooth paths"},
@@ -180,7 +184,7 @@ static void rna_ParticleEdit_tool_set(PointerRNA *ptr, int value)
pset->brushtype = value;
}
-static EnumPropertyItem *rna_ParticleEdit_tool_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_ParticleEdit_tool_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
Scene *scene = CTX_data_scene(C);
@@ -283,6 +287,20 @@ static void rna_Sculpt_ShowDiffuseColor_update(Main *UNUSED(bmain), Scene *scene
}
}
+static void rna_Sculpt_ShowMask_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *UNUSED(ptr))
+{
+ Object *object = (scene->basact) ? scene->basact->object : NULL;
+ if (object == NULL || object->sculpt == NULL) {
+ return;
+ }
+ Sculpt *sd = scene->toolsettings->sculpt;
+ object->sculpt->show_mask = ((sd->flags & SCULPT_HIDE_MASK) == 0);
+ if (object->sculpt->pbvh != NULL) {
+ pbvh_show_mask_set(object->sculpt->pbvh, object->sculpt->show_mask);
+ }
+ WM_main_add_notifier(NC_OBJECT | ND_DRAW, object);
+}
+
static char *rna_Sculpt_path(PointerRNA *UNUSED(ptr))
{
return BLI_strdup("tool_settings.sculpt");
@@ -521,7 +539,7 @@ static void rna_def_paint(BlenderRNA *brna)
static void rna_def_sculpt(BlenderRNA *brna)
{
- static EnumPropertyItem detail_refine_items[] = {
+ static const EnumPropertyItem detail_refine_items[] = {
{SCULPT_DYNTOPO_SUBDIVIDE, "SUBDIVIDE", 0,
"Subdivide Edges", "Subdivide long edges to add mesh detail where needed"},
{SCULPT_DYNTOPO_COLLAPSE, "COLLAPSE", 0,
@@ -531,7 +549,7 @@ static void rna_def_sculpt(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem detail_type_items[] = {
+ static const EnumPropertyItem detail_type_items[] = {
{0, "RELATIVE", 0,
"Relative Detail", "Mesh detail is relative to the brush size and detail size"},
{SCULPT_DYNTOPO_DETAIL_CONSTANT, "CONSTANT", 0,
@@ -590,6 +608,11 @@ static void rna_def_sculpt(BlenderRNA *brna)
"Show diffuse color of object and overlay sculpt mask on top of it");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Sculpt_ShowDiffuseColor_update");
+ prop = RNA_def_property(srna, "show_mask", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_negative_sdna(prop, NULL, "flags", SCULPT_HIDE_MASK);
+ RNA_def_property_ui_text(prop, "Show Mask", "Show mask as overlay on object");
+ RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, "rna_Sculpt_ShowMask_update");
+
prop = RNA_def_property(srna, "detail_size", PROP_FLOAT, PROP_PIXEL);
RNA_def_property_ui_range(prop, 0.5, 40.0, 10, 2);
RNA_def_property_ui_text(prop, "Detail Size", "Maximum edge length for dynamic topology sculpting (in pixels)");
@@ -668,22 +691,20 @@ static void rna_def_vertex_paint(BlenderRNA *brna)
RNA_def_struct_path_func(srna, "rna_VertexPaint_path");
RNA_def_struct_ui_text(srna, "Vertex Paint", "Properties of vertex and weight paint mode");
- /* vertex paint only */
- prop = RNA_def_property(srna, "use_normal", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "flag", VP_NORMALS);
- RNA_def_property_ui_text(prop, "Normals", "Apply the vertex normal before painting");
- RNA_def_property_update(prop, NC_SCENE | ND_TOOLSETTINGS, NULL);
-
- prop = RNA_def_property(srna, "use_spray", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "flag", VP_SPRAY);
- RNA_def_property_ui_text(prop, "Spray", "Keep applying paint effect while holding mouse");
- RNA_def_property_update(prop, NC_SCENE | ND_TOOLSETTINGS, NULL);
-
/* weight paint only */
prop = RNA_def_property(srna, "use_group_restrict", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "flag", VP_ONLYVGROUP);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", VP_FLAG_VGROUP_RESTRICT);
RNA_def_property_ui_text(prop, "Restrict", "Restrict painting to vertices in the group");
RNA_def_property_update(prop, NC_SCENE | ND_TOOLSETTINGS, NULL);
+
+ /* Mirroring */
+ prop = RNA_def_property(srna, "radial_symmetry", PROP_INT, PROP_XYZ);
+ RNA_def_property_int_sdna(prop, NULL, "radial_symm");
+ RNA_def_property_int_default(prop, 1);
+ RNA_def_property_range(prop, 1, 64);
+ RNA_def_property_ui_range(prop, 1, 32, 1, 1);
+ RNA_def_property_ui_text(prop, "Radial Symmetry Count X Axis",
+ "Number of times to copy strokes across the surface");
}
static void rna_def_image_paint(BlenderRNA *brna)
@@ -692,7 +713,7 @@ static void rna_def_image_paint(BlenderRNA *brna)
PropertyRNA *prop;
FunctionRNA *func;
- static EnumPropertyItem paint_type_items[] = {
+ static const EnumPropertyItem paint_type_items[] = {
{IMAGEPAINT_MODE_MATERIAL, "MATERIAL", 0,
"Material", "Detect image slots from the material"},
{IMAGEPAINT_MODE_IMAGE, "IMAGE", 0,
@@ -822,26 +843,26 @@ static void rna_def_particle_edit(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem select_mode_items[] = {
+ static const EnumPropertyItem select_mode_items[] = {
{SCE_SELECT_PATH, "PATH", ICON_PARTICLE_PATH, "Path", "Path edit mode"},
{SCE_SELECT_POINT, "POINT", ICON_PARTICLE_POINT, "Point", "Point select mode"},
{SCE_SELECT_END, "TIP", ICON_PARTICLE_TIP, "Tip", "Tip select mode"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem puff_mode[] = {
+ static const EnumPropertyItem puff_mode[] = {
{0, "ADD", 0, "Add", "Make hairs more puffy"},
{1, "SUB", 0, "Sub", "Make hairs less puffy"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem length_mode[] = {
+ static const EnumPropertyItem length_mode[] = {
{0, "GROW", 0, "Grow", "Make hairs longer"},
{1, "SHRINK", 0, "Shrink", "Make hairs shorter"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem edit_type_items[] = {
+ static const EnumPropertyItem edit_type_items[] = {
{PE_TYPE_PARTICLES, "PARTICLES", 0, "Particles", ""},
{PE_TYPE_SOFTBODY, "SOFT_BODY", 0, "Soft body", ""},
{PE_TYPE_CLOTH, "CLOTH", 0, "Cloth", ""},
@@ -1001,7 +1022,7 @@ static void rna_def_particle_edit(BlenderRNA *brna)
static void rna_def_gpencil_sculpt(BlenderRNA *brna)
{
- static EnumPropertyItem prop_direction_items[] = {
+ static const EnumPropertyItem prop_direction_items[] = {
{0, "ADD", 0, "Add", "Add effect of brush"},
{GP_EDITBRUSH_FLAG_INVERT, "SUBTRACT", 0, "Subtract", "Subtract effect of brush"},
{0, NULL, 0, NULL, NULL}};
diff --git a/source/blender/makesrna/intern/rna_sensor.c b/source/blender/makesrna/intern/rna_sensor.c
index d0afab7a1e3..735df471721 100644
--- a/source/blender/makesrna/intern/rna_sensor.c
+++ b/source/blender/makesrna/intern/rna_sensor.c
@@ -45,7 +45,7 @@
#include "WM_types.h"
/* Always keep in alphabetical order */
-static EnumPropertyItem sensor_type_items[] = {
+static const EnumPropertyItem sensor_type_items[] = {
{SENS_ACTUATOR, "ACTUATOR", 0, "Actuator", ""},
{SENS_ALWAYS, "ALWAYS", 0, "Always", ""},
{SENS_ARMATURE, "ARMATURE", 0, "Armature", ""},
@@ -137,7 +137,7 @@ static int rna_Sensor_controllers_length(PointerRNA *ptr)
return (int) sens->totlinks;
}
-EnumPropertyItem *rna_Sensor_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *rna_Sensor_type_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
Object *ob = NULL;
@@ -392,7 +392,7 @@ static void rna_def_mouse_sensor(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem mouse_event_items[] = {
+ static const EnumPropertyItem mouse_event_items[] = {
{BL_SENS_MOUSE_LEFT_BUTTON, "LEFTCLICK", 0, "Left Button", ""},
{BL_SENS_MOUSE_MIDDLE_BUTTON, "MIDDLECLICK", 0, "Middle Button", ""},
{BL_SENS_MOUSE_RIGHT_BUTTON, "RIGHTCLICK", 0, "Right Button", ""},
@@ -501,7 +501,7 @@ static void rna_def_property_sensor(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{SENS_PROP_EQUAL, "PROPEQUAL", 0, "Equal", ""},
{SENS_PROP_NEQUAL, "PROPNEQUAL", 0, "Not Equal", ""},
{SENS_PROP_INTERVAL, "PROPINTERVAL", 0, "Interval", ""},
@@ -547,7 +547,7 @@ static void rna_def_armature_sensor(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_type_items[] = {
+ static const EnumPropertyItem prop_type_items[] = {
{SENS_ARM_STATE_CHANGED, "STATECHG", 0, "State Changed", ""},
{SENS_ARM_LIN_ERROR_BELOW, "LINERRORBELOW", 0, "Lin error below", ""},
{SENS_ARM_LIN_ERROR_ABOVE, "LINERRORABOVE", 0, "Lin error above", ""},
@@ -675,7 +675,7 @@ static void rna_def_radar_sensor(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem axis_items[] = {
+ static const EnumPropertyItem axis_items[] = {
{SENS_RADAR_X_AXIS, "XAXIS", 0, "+X axis", ""},
{SENS_RADAR_Y_AXIS, "YAXIS", 0, "+Y axis", ""},
{SENS_RADAR_Z_AXIS, "ZAXIS", 0, "+Z axis", ""},
@@ -731,7 +731,7 @@ static void rna_def_ray_sensor(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem axis_items[] = {
+ static const EnumPropertyItem axis_items[] = {
{SENS_RAY_X_AXIS, "XAXIS", 0, "+X axis", ""},
{SENS_RAY_Y_AXIS, "YAXIS", 0, "+Y axis", ""},
{SENS_RAY_Z_AXIS, "ZAXIS", 0, "+Z axis", ""},
@@ -817,7 +817,7 @@ static void rna_def_joystick_sensor(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem event_type_joystick_items[] = {
+ static const EnumPropertyItem event_type_joystick_items[] = {
{SENS_JOY_BUTTON, "BUTTON", 0, "Button", ""},
{SENS_JOY_AXIS, "AXIS", 0, "Axis", ""},
{SENS_JOY_HAT, "HAT", 0, "Hat", ""},
@@ -825,7 +825,7 @@ static void rna_def_joystick_sensor(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem axis_direction_items[] = {
+ static const EnumPropertyItem axis_direction_items[] = {
{SENS_JOY_X_AXIS, "RIGHTAXIS", 0, "Right Axis", ""},
{SENS_JOY_Y_AXIS, "UPAXIS", 0, "Up Axis", ""},
{SENS_JOY_NEG_X_AXIS, "LEFTAXIS", 0, "Left Axis", ""},
@@ -833,7 +833,7 @@ static void rna_def_joystick_sensor(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem hat_direction_items[] = {
+ static const EnumPropertyItem hat_direction_items[] = {
{SENS_JOY_HAT_UP, "UP", 0, "Up", ""},
{SENS_JOY_HAT_DOWN, "DOWN", 0, "Down", ""},
{SENS_JOY_HAT_LEFT, "LEFT", 0, "Left", ""},
diff --git a/source/blender/makesrna/intern/rna_sequencer.c b/source/blender/makesrna/intern/rna_sequencer.c
index 3e6d8441363..33621af69af 100644
--- a/source/blender/makesrna/intern/rna_sequencer.c
+++ b/source/blender/makesrna/intern/rna_sequencer.c
@@ -38,10 +38,11 @@
#include "BLT_translation.h"
#include "BKE_animsys.h"
-#include "BKE_global.h"
#include "BKE_sequencer.h"
#include "BKE_sound.h"
+#include "IMB_metadata.h"
+
#include "MEM_guardedalloc.h"
#include "RNA_access.h"
@@ -60,7 +61,7 @@ typedef struct EffectInfo {
int inputs;
} EffectInfo;
-EnumPropertyItem rna_enum_sequence_modifier_type_items[] = {
+const EnumPropertyItem rna_enum_sequence_modifier_type_items[] = {
{seqModifierType_ColorBalance, "COLOR_BALANCE", ICON_NONE, "Color Balance", ""},
{seqModifierType_Curves, "CURVES", ICON_NONE, "Curves", ""},
{seqModifierType_HueCorrect, "HUE_CORRECT", ICON_NONE, "Hue Correct", ""},
@@ -75,6 +76,7 @@ EnumPropertyItem rna_enum_sequence_modifier_type_items[] = {
#include "BKE_report.h"
#include "BKE_idprop.h"
+#include "BKE_movieclip.h"
#include "WM_api.h"
@@ -341,7 +343,7 @@ static void rna_Sequence_use_translation_set(PointerRNA *ptr, int value)
}
}
else {
- seq->flag ^= SEQ_USE_TRANSFORM;
+ seq->flag &= ~SEQ_USE_TRANSFORM;
}
}
@@ -355,7 +357,7 @@ static void rna_Sequence_use_crop_set(PointerRNA *ptr, int value)
}
}
else {
- seq->flag ^= SEQ_USE_CROP;
+ seq->flag &= ~SEQ_USE_CROP;
}
}
@@ -550,6 +552,8 @@ static StructRNA *rna_Sequence_refine(struct PointerRNA *ptr)
return &RNA_GaussianBlurSequence;
case SEQ_TYPE_TEXT:
return &RNA_TextSequence;
+ case SEQ_TYPE_COLORMIX:
+ return &RNA_ColorMixSequence;
default:
return &RNA_Sequence;
}
@@ -585,6 +589,27 @@ static IDProperty *rna_Sequence_idprops(PointerRNA *ptr, bool create)
return seq->prop;
}
+static PointerRNA rna_MovieSequence_metadata_get(Sequence *seq)
+{
+ if (seq == NULL || seq->anims.first == NULL) {
+ return PointerRNA_NULL;
+ }
+
+ StripAnim *sanim = seq->anims.first;
+ if (sanim->anim == NULL) {
+ return PointerRNA_NULL;
+ }
+
+ IDProperty *metadata = IMB_anim_load_metadata(sanim->anim);
+ if (metadata == NULL) {
+ return PointerRNA_NULL;
+ }
+
+ PointerRNA ptr;
+ RNA_pointer_create(NULL, &RNA_IDPropertyWrapPtr, metadata, &ptr);
+ return ptr;
+}
+
static PointerRNA rna_SequenceEditor_meta_stack_get(CollectionPropertyIterator *iter)
{
ListBaseIterator *internal = &iter->internal.listbase;
@@ -725,8 +750,9 @@ static void rna_Sequence_filepath_update(Main *bmain, Scene *UNUSED(scene), Poin
static void rna_Sequence_sound_update(Main *bmain, Scene *scene, PointerRNA *ptr)
{
Sequence *seq = (Sequence *) ptr->data;
-
- BKE_sound_update_scene_sound(seq->scene_sound, seq->sound);
+ if (seq->sound != NULL) {
+ BKE_sound_update_scene_sound(seq->scene_sound, seq->sound);
+ }
rna_Sequence_update(bmain, scene, ptr);
}
@@ -1082,6 +1108,13 @@ static void rna_Sequence_modifier_clear(Sequence *seq, bContext *C)
WM_main_add_notifier(NC_SCENE | ND_SEQUENCER, NULL);
}
+static float rna_Sequence_fps_get(PointerRNA *ptr)
+{
+ Scene *scene = (Scene *)ptr->id.data;
+ Sequence *seq = (Sequence *)(ptr->data);
+ return BKE_sequence_get_fps(scene, seq);
+}
+
#else
static void rna_def_strip_element(BlenderRNA *brna)
@@ -1095,7 +1128,7 @@ static void rna_def_strip_element(BlenderRNA *brna)
prop = RNA_def_property(srna, "filename", PROP_STRING, PROP_FILENAME);
RNA_def_property_string_sdna(prop, NULL, "name");
- RNA_def_property_ui_text(prop, "Filename", "");
+ RNA_def_property_ui_text(prop, "Filename", "Name of the source file");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceElement_update");
prop = RNA_def_property(srna, "orig_width", PROP_INT, PROP_NONE);
@@ -1120,25 +1153,25 @@ static void rna_def_strip_crop(BlenderRNA *brna)
prop = RNA_def_property(srna, "max_y", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "top");
- RNA_def_property_ui_text(prop, "Top", "");
+ RNA_def_property_ui_text(prop, "Top", "Number of pixels to crop from the top");
RNA_def_property_ui_range(prop, 0, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceCrop_update");
prop = RNA_def_property(srna, "min_y", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "bottom");
- RNA_def_property_ui_text(prop, "Bottom", "");
+ RNA_def_property_ui_text(prop, "Bottom", "Number of pixels to crop from the bottom");
RNA_def_property_ui_range(prop, 0, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceCrop_update");
prop = RNA_def_property(srna, "min_x", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "left");
- RNA_def_property_ui_text(prop, "Left", "");
+ RNA_def_property_ui_text(prop, "Left", "Number of pixels to crop from the left side");
RNA_def_property_ui_range(prop, 0, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceCrop_update");
prop = RNA_def_property(srna, "max_x", PROP_INT, PROP_UNSIGNED);
RNA_def_property_int_sdna(prop, NULL, "right");
- RNA_def_property_ui_text(prop, "Right", "");
+ RNA_def_property_ui_text(prop, "Right", "Number of pixels to crop from the right side");
RNA_def_property_ui_range(prop, 0, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceCrop_update");
@@ -1156,13 +1189,13 @@ static void rna_def_strip_transform(BlenderRNA *brna)
prop = RNA_def_property(srna, "offset_x", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "xofs");
- RNA_def_property_ui_text(prop, "Offset X", "");
+ RNA_def_property_ui_text(prop, "Offset X", "Amount to move the input on the X axis within its boundaries");
RNA_def_property_ui_range(prop, -4096, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceTransform_update");
prop = RNA_def_property(srna, "offset_y", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "yofs");
- RNA_def_property_ui_text(prop, "Offset Y", "");
+ RNA_def_property_ui_text(prop, "Offset Y", "Amount to move the input on the Y axis within its boundaries");
RNA_def_property_ui_range(prop, -4096, 4096, 1, -1);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceTransform_update");
@@ -1246,7 +1279,7 @@ static void rna_def_strip_proxy(BlenderRNA *brna)
prop = RNA_def_property(srna, "timecode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "tc");
RNA_def_property_enum_items(prop, seq_tc_items);
- RNA_def_property_ui_text(prop, "Timecode", "");
+ RNA_def_property_ui_text(prop, "Timecode", "Method for reading the inputs timecode");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_tcindex_update");
prop = RNA_def_property(srna, "use_proxy_custom_directory", PROP_BOOLEAN, PROP_NONE);
@@ -1289,17 +1322,17 @@ static void rna_def_color_balance(BlenderRNA *brna)
prop = RNA_def_property(srna, "invert_gain", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_COLOR_BALANCE_INVERSE_GAIN);
- RNA_def_property_ui_text(prop, "Inverse Gain", "");
+ RNA_def_property_ui_text(prop, "Inverse Gain", "Invert the gain color`");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceColorBalance_update");
prop = RNA_def_property(srna, "invert_gamma", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_COLOR_BALANCE_INVERSE_GAMMA);
- RNA_def_property_ui_text(prop, "Inverse Gamma", "");
+ RNA_def_property_ui_text(prop, "Inverse Gamma", "Invert the gamma color");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceColorBalance_update");
prop = RNA_def_property(srna, "invert_lift", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_COLOR_BALANCE_INVERSE_LIFT);
- RNA_def_property_ui_text(prop, "Inverse Lift", "");
+ RNA_def_property_ui_text(prop, "Inverse Lift", "Invert the lift color");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceColorBalance_update");
/* not yet used */
@@ -1327,7 +1360,7 @@ static void rna_def_strip_color_balance(BlenderRNA *brna)
RNA_def_struct_sdna(srna, "StripColorBalance");
}
-static EnumPropertyItem blend_mode_items[] = {
+static const EnumPropertyItem blend_mode_items[] = {
{SEQ_BLEND_REPLACE, "REPLACE", 0, "Replace", ""},
{SEQ_TYPE_CROSS, "CROSS", 0, "Cross", ""},
{SEQ_TYPE_ADD, "ADD", 0, "Add", ""},
@@ -1337,6 +1370,24 @@ static EnumPropertyItem blend_mode_items[] = {
{SEQ_TYPE_GAMCROSS, "GAMMA_CROSS", 0, "Gamma Cross", ""},
{SEQ_TYPE_MUL, "MULTIPLY", 0, "Multiply", ""},
{SEQ_TYPE_OVERDROP, "OVER_DROP", 0, "Over Drop", ""},
+ {SEQ_TYPE_LIGHTEN, "LIGHTEN", 0, "Lighten", ""},
+ {SEQ_TYPE_DARKEN, "DARKEN", 0, "Darken", ""},
+ {SEQ_TYPE_SCREEN, "SCREEN", 0, "Screen", ""},
+ {SEQ_TYPE_OVERLAY, "OVERLAY", 0, "Overlay", ""},
+ {SEQ_TYPE_DODGE, "DODGE", 0, "Dodge", ""},
+ {SEQ_TYPE_BURN, "BURN", 0, "Burn", ""},
+ {SEQ_TYPE_LINEAR_BURN, "LINEAR_BURN", 0, "Linear Burn", ""},
+ {SEQ_TYPE_SOFT_LIGHT, "SOFT_LIGHT", 0, "Soft Light", ""},
+ {SEQ_TYPE_HARD_LIGHT, "HARD_LIGHT", 0, "Hard Light", ""},
+ {SEQ_TYPE_PIN_LIGHT, "PIN_LIGHT", 0, "Pin Light", ""},
+ {SEQ_TYPE_LIN_LIGHT, "LINEAR_LIGHT", 0, "Linear Light", ""},
+ {SEQ_TYPE_VIVID_LIGHT, "VIVID_LIGHT", 0, "Vivid Light", ""},
+ {SEQ_TYPE_BLEND_COLOR, "COLOR", 0, "Color", ""},
+ {SEQ_TYPE_HUE, "HUE", 0, "Hue", ""},
+ {SEQ_TYPE_SATURATION, "SATURATION", 0, "Saturation", ""},
+ {SEQ_TYPE_VALUE, "VALUE", 0, "Value", ""},
+ {SEQ_TYPE_DIFFERENCE, "DIFFERENCE", 0, "Difference", ""},
+ {SEQ_TYPE_EXCLUSION, "EXCLUSION", 0, "Exclusion", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -1410,6 +1461,7 @@ static void rna_def_sequence(BlenderRNA *brna)
{SEQ_TYPE_ADJUSTMENT, "ADJUSTMENT", 0, "Adjustment Layer", ""},
{SEQ_TYPE_GAUSSIAN_BLUR, "GAUSSIAN_BLUR", 0, "Gaussian Blur", ""},
{SEQ_TYPE_TEXT, "TEXT", 0, "Text", ""},
+ {SEQ_TYPE_COLORMIX, "COLORMIX", 0, "Color Mix", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -1453,13 +1505,13 @@ static void rna_def_sequence(BlenderRNA *brna)
prop = RNA_def_property(srna, "mute", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_MUTE);
RNA_def_property_ui_icon(prop, ICON_RESTRICT_VIEW_OFF, true);
- RNA_def_property_ui_text(prop, "Mute", "");
+ RNA_def_property_ui_text(prop, "Mute", "Disable strip so that it cannot be viewed in the output");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_mute_update");
prop = RNA_def_property(srna, "lock", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_LOCK);
RNA_def_property_ui_icon(prop, ICON_UNLOCKED, true);
- RNA_def_property_ui_text(prop, "Lock", "Lock strip so that it can't be transformed");
+ RNA_def_property_ui_text(prop, "Lock", "Lock strip so that it cannot be transformed");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, NULL);
/* strip positioning */
@@ -1481,7 +1533,7 @@ static void rna_def_sequence(BlenderRNA *brna)
prop = RNA_def_property(srna, "frame_start", PROP_INT, PROP_TIME);
RNA_def_property_int_sdna(prop, NULL, "start");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
- RNA_def_property_ui_text(prop, "Start Frame", "");
+ RNA_def_property_ui_text(prop, "Start Frame", "X position where the strip begins");
RNA_def_property_int_funcs(prop, NULL, "rna_Sequence_start_frame_set", NULL); /* overlap tests and calc_seq_disp */
RNA_def_property_editable_func(prop, "rna_Sequence_frame_editable");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
@@ -1552,12 +1604,12 @@ static void rna_def_sequence(BlenderRNA *brna)
prop = RNA_def_property(srna, "blend_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "blend_mode");
RNA_def_property_enum_items(prop, blend_mode_items);
- RNA_def_property_ui_text(prop, "Blend Mode", "");
+ RNA_def_property_ui_text(prop, "Blend Mode", "Method for controlling how the strip combines with other strips");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "blend_alpha", PROP_FLOAT, PROP_FACTOR);
RNA_def_property_range(prop, 0.0f, 1.0f);
- RNA_def_property_ui_text(prop, "Blend Opacity", "");
+ RNA_def_property_ui_text(prop, "Blend Opacity", "Percentage of how much the strip's colors affect other strips");
/* stupid 0-100 -> 0-1 */
RNA_def_property_float_funcs(prop, "rna_Sequence_opacity_get", "rna_Sequence_opacity_set", NULL);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
@@ -1566,7 +1618,7 @@ static void rna_def_sequence(BlenderRNA *brna)
RNA_def_property_range(prop, 0.0f, 1.0f);
RNA_def_property_ui_range(prop, 0.0f, 1.0f, 0.1, 3);
RNA_def_property_float_sdna(prop, NULL, "effect_fader");
- RNA_def_property_ui_text(prop, "Effect fader position", "");
+ RNA_def_property_ui_text(prop, "Effect fader position", "Custom fade value");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "use_default_fade", PROP_BOOLEAN, PROP_NONE);
@@ -1714,7 +1766,7 @@ static void rna_def_filter_video(StructRNA *srna)
RNA_def_property_range(prop, 0.0f, 20.0f);
RNA_def_property_ui_range(prop, 0.0f, 2.0f, 3, 3);
RNA_def_property_float_default(prop, 1.0f);
- RNA_def_property_ui_text(prop, "Saturation", "");
+ RNA_def_property_ui_text(prop, "Saturation", "Adjust the intensity of the input's color");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "strobe", PROP_FLOAT, PROP_NONE);
@@ -1818,6 +1870,16 @@ static void rna_def_color_management(StructRNA *srna)
RNA_def_property_ui_text(prop, "Color Space Settings", "Input color space settings");
}
+static void rna_def_movie_types(StructRNA *srna)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_property(srna, "fps", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_ui_text(prop, "FPS", "Frames per second");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_float_funcs(prop, "rna_Sequence_fps_get", NULL, NULL);
+}
+
static void rna_def_image(BlenderRNA *brna)
{
StructRNA *srna;
@@ -1917,13 +1979,16 @@ static void rna_def_scene(BlenderRNA *brna)
rna_def_filter_video(srna);
rna_def_proxy(srna);
rna_def_input(srna);
+ rna_def_movie_types(srna);
}
static void rna_def_movie(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+ FunctionRNA *func;
+ PropertyRNA *parm;
+
srna = RNA_def_struct(brna, "MovieSequence", "Sequence");
RNA_def_struct_ui_text(srna, "Movie Sequence", "Sequence strip to load a video");
RNA_def_struct_sdna(srna, "Sequence");
@@ -1955,6 +2020,14 @@ static void rna_def_movie(BlenderRNA *brna)
"rna_Sequence_filepath_set");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_filepath_update");
+ /* metadata */
+ func = RNA_def_function(srna, "metadata", "rna_MovieSequence_metadata_get");
+ RNA_def_function_ui_description(func, "Retrieve metadata of the movie file");
+ /* return type */
+ parm = RNA_def_pointer(func, "metadata", "IDPropertyWrapPtr", "", "Dict-like object containing the metadata");
+ RNA_def_parameter_flags(parm, 0, PARM_RNAPTR);
+ RNA_def_function_return(func, parm);
+
/* multiview */
prop = RNA_def_property(srna, "use_multiview", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_USE_VIEWS);
@@ -1977,6 +2050,7 @@ static void rna_def_movie(BlenderRNA *brna)
rna_def_proxy(srna);
rna_def_input(srna);
rna_def_color_management(srna);
+ rna_def_movie_types(srna);
}
static void rna_def_movieclip(BlenderRNA *brna)
@@ -2002,6 +2076,7 @@ static void rna_def_movieclip(BlenderRNA *brna)
rna_def_filter_video(srna);
rna_def_input(srna);
+ rna_def_movie_types(srna);
}
static void rna_def_mask(BlenderRNA *brna)
@@ -2138,6 +2213,7 @@ static void rna_def_wipe(StructRNA *srna)
prop = RNA_def_property(srna, "transition_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "wipetype");
RNA_def_property_enum_items(prop, wipe_type_items);
+ RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_SEQUENCE);
RNA_def_property_ui_text(prop, "Transition Type", "");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
}
@@ -2205,13 +2281,13 @@ static void rna_def_transform(StructRNA *srna)
prop = RNA_def_property(srna, "scale_start_x", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "ScalexIni");
- RNA_def_property_ui_text(prop, "Scale X", "");
+ RNA_def_property_ui_text(prop, "Scale X", "Amount to scale the input in the X axis");
RNA_def_property_ui_range(prop, 0, 10, 3, 6);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "scale_start_y", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "ScaleyIni");
- RNA_def_property_ui_text(prop, "Scale Y", "");
+ RNA_def_property_ui_text(prop, "Scale Y", "Amount to scale the input in the Y axis");
RNA_def_property_ui_range(prop, 0, 10, 3, 6);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
@@ -2222,33 +2298,33 @@ static void rna_def_transform(StructRNA *srna)
prop = RNA_def_property(srna, "translate_start_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "xIni");
- RNA_def_property_ui_text(prop, "Translate X", "");
+ RNA_def_property_ui_text(prop, "Translate X", "Amount to move the input on the X axis");
RNA_def_property_ui_range(prop, -4000.0f, 4000.0f, 3, 6);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "translate_start_y", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "yIni");
- RNA_def_property_ui_text(prop, "Translate Y", "");
+ RNA_def_property_ui_text(prop, "Translate Y", "Amount to move the input on the Y axis");
RNA_def_property_ui_range(prop, -4000.0f, 4000.0f, 3, 6);
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "rotation_start", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "rotIni");
RNA_def_property_range(prop, -360.0f, 360.0f);
- RNA_def_property_ui_text(prop, "Rotation", "");
+ RNA_def_property_ui_text(prop, "Rotation", "Degrees to rotate the input");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "translation_unit", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "percent");
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); /* not meant to be animated */
RNA_def_property_enum_items(prop, translation_unit_items);
- RNA_def_property_ui_text(prop, "Translation Unit", "");
+ RNA_def_property_ui_text(prop, "Translation Unit", "Unit of measure to translate the input");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "interpolation", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_items(prop, interpolation_items);
RNA_def_property_clear_flag(prop, PROP_ANIMATABLE); /* not meant to be animated */
- RNA_def_property_ui_text(prop, "Interpolation", "");
+ RNA_def_property_ui_text(prop, "Interpolation", "Method to determine how missing pixels are created");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
}
@@ -2260,7 +2336,7 @@ static void rna_def_solid_color(StructRNA *srna)
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR_GAMMA);
RNA_def_property_float_sdna(prop, NULL, "col");
- RNA_def_property_ui_text(prop, "Color", "");
+ RNA_def_property_ui_text(prop, "Color", "Effect Strip color");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
}
@@ -2307,13 +2383,13 @@ static void rna_def_gaussian_blur(StructRNA *srna)
static void rna_def_text(StructRNA *srna)
{
- static EnumPropertyItem text_align_x_items[] = {
+ static const EnumPropertyItem text_align_x_items[] = {
{SEQ_TEXT_ALIGN_X_LEFT, "LEFT", 0, "Left", ""},
{SEQ_TEXT_ALIGN_X_CENTER, "CENTER", 0, "Center", ""},
{SEQ_TEXT_ALIGN_X_RIGHT, "RIGHT", 0, "Right", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem text_align_y_items[] = {
+ static const EnumPropertyItem text_align_y_items[] = {
{SEQ_TEXT_ALIGN_Y_TOP, "TOP", 0, "Top", ""},
{SEQ_TEXT_ALIGN_Y_CENTER, "CENTER", 0, "Center", ""},
{SEQ_TEXT_ALIGN_Y_BOTTOM, "BOTTOM", 0, "Bottom", ""},
@@ -2333,7 +2409,7 @@ static void rna_def_text(StructRNA *srna)
prop = RNA_def_property(srna, "color", PROP_FLOAT, PROP_COLOR_GAMMA);
RNA_def_property_float_sdna(prop, NULL, "color");
- RNA_def_property_ui_text(prop, "Color", "");
+ RNA_def_property_ui_text(prop, "Color", "Text color");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "shadow_color", PROP_FLOAT, PROP_COLOR_GAMMA);
@@ -2358,13 +2434,13 @@ static void rna_def_text(StructRNA *srna)
prop = RNA_def_property(srna, "align_x", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "align");
RNA_def_property_enum_items(prop, text_align_x_items);
- RNA_def_property_ui_text(prop, "Align X", "");
+ RNA_def_property_ui_text(prop, "Align X", "Align the text along the X axis");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "align_y", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "align_y");
RNA_def_property_enum_items(prop, text_align_y_items);
- RNA_def_property_ui_text(prop, "Align Y", "");
+ RNA_def_property_ui_text(prop, "Align Y", "Align the image along the Y axis");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
prop = RNA_def_property(srna, "text", PROP_STRING, PROP_NONE);
@@ -2377,6 +2453,49 @@ static void rna_def_text(StructRNA *srna)
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
}
+static void rna_def_color_mix(StructRNA *srna)
+{
+ static EnumPropertyItem blend_color_items[] = {
+ {SEQ_TYPE_ADD, "ADD", 0, "Add", ""},
+ {SEQ_TYPE_SUB, "SUBTRACT", 0, "Subtract", ""},
+ {SEQ_TYPE_MUL, "MULTIPLY", 0, "Multiply", ""},
+ {SEQ_TYPE_LIGHTEN, "LIGHTEN", 0, "Lighten", ""},
+ {SEQ_TYPE_DARKEN, "DARKEN", 0, "Darken", ""},
+ {SEQ_TYPE_SCREEN, "SCREEN", 0, "Screen", ""},
+ {SEQ_TYPE_OVERLAY, "OVERLAY", 0, "Overlay", ""},
+ {SEQ_TYPE_DODGE, "DODGE", 0, "Dodge", ""},
+ {SEQ_TYPE_BURN, "BURN", 0, "Burn", ""},
+ {SEQ_TYPE_LINEAR_BURN, "LINEAR_BURN", 0, "Linear Burn", ""},
+ {SEQ_TYPE_SOFT_LIGHT, "SOFT_LIGHT", 0, "Soft Light", ""},
+ {SEQ_TYPE_HARD_LIGHT, "HARD_LIGHT", 0, "Hard Light", ""},
+ {SEQ_TYPE_PIN_LIGHT, "PIN_LIGHT", 0, "Pin Light", ""},
+ {SEQ_TYPE_LIN_LIGHT, "LINEAR_LIGHT", 0, "Linear Light", ""},
+ {SEQ_TYPE_VIVID_LIGHT, "VIVID_LIGHT", 0, "Vivid Light", ""},
+ {SEQ_TYPE_BLEND_COLOR, "COLOR", 0, "Color", ""},
+ {SEQ_TYPE_HUE, "HUE", 0, "Hue", ""},
+ {SEQ_TYPE_SATURATION, "SATURATION", 0, "Saturation", ""},
+ {SEQ_TYPE_VALUE, "VALUE", 0, "Value", ""},
+ {SEQ_TYPE_DIFFERENCE, "DIFFERENCE", 0, "Difference", ""},
+ {SEQ_TYPE_EXCLUSION, "EXCLUSION", 0, "Exclusion", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
+ PropertyRNA *prop;
+
+ RNA_def_struct_sdna_from(srna, "ColorMixVars", "effectdata");
+
+ prop = RNA_def_property(srna, "blend_effect", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_sdna(prop, NULL, "blend_effect");
+ RNA_def_property_enum_items(prop, blend_color_items);
+ RNA_def_property_ui_text(prop, "Blend Effect", "Method for controlling how the strip combines with other strips");
+ RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
+
+ prop = RNA_def_property(srna, "factor", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_range(prop, 0.0f, 1.0f);
+ RNA_def_property_ui_text(prop, "Blend Factor", "Percentage of how much the strip's colors affect other strips");
+ RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_Sequence_update");
+}
+
static EffectInfo def_effects[] = {
{"AddSequence", "Add Sequence", "Add Sequence", NULL, 2},
{"AdjustmentSequence", "Adjustment Layer Sequence",
@@ -2403,6 +2522,7 @@ static EffectInfo def_effects[] = {
rna_def_gaussian_blur, 1},
{"TextSequence", "Text Sequence", "Sequence strip creating text",
rna_def_text, 0},
+ {"ColorMixSequence", "Color Mix Sequence", "Color Mix Sequence", rna_def_color_mix, 2},
{"", "", "", NULL, 0}
};
@@ -2512,7 +2632,7 @@ static void rna_def_colorbalance_modifier(BlenderRNA *brna)
RNA_def_property_float_sdna(prop, NULL, "color_multiply");
RNA_def_property_range(prop, 0.0f, 20.0f);
RNA_def_property_float_default(prop, 1.0f);
- RNA_def_property_ui_text(prop, "Multiply Colors", "");
+ RNA_def_property_ui_text(prop, "Multiply Colors", "Multiply the intensity of each pixel");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceModifier_update");
}
@@ -2576,13 +2696,13 @@ static void rna_def_brightcontrast_modifier(BlenderRNA *brna)
prop = RNA_def_property(srna, "bright", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "bright");
RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);
- RNA_def_property_ui_text(prop, "Bright", "");
+ RNA_def_property_ui_text(prop, "Bright", "Adjust the luminosity of the colors");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceModifier_update");
prop = RNA_def_property(srna, "contrast", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "contrast");
RNA_def_property_range(prop, -FLT_MAX, FLT_MAX);
- RNA_def_property_ui_text(prop, "Contrast", "");
+ RNA_def_property_ui_text(prop, "Contrast", "Adjust the difference in luminosity between pixels");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceModifier_update");
}
@@ -2591,7 +2711,7 @@ static void rna_def_tonemap_modifier(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem type_items[] = {
+ static const EnumPropertyItem type_items[] = {
{SEQ_TONEMAP_RD_PHOTORECEPTOR, "RD_PHOTORECEPTOR", 0, "R/D Photoreceptor", ""},
{SEQ_TONEMAP_RH_SIMPLE, "RH_SIMPLE", 0, "Rh Simple", ""},
{0, NULL, 0, NULL, NULL}
@@ -2599,13 +2719,12 @@ static void rna_def_tonemap_modifier(BlenderRNA *brna)
srna = RNA_def_struct(brna, "SequencerTonemapModifierData", "SequenceModifier");
RNA_def_struct_sdna(srna, "SequencerTonemapModifierData");
- RNA_def_struct_ui_text(srna, "SequencerTonemapModifierData",
- "Tone mapping modifier");
+ RNA_def_struct_ui_text(srna, "SequencerTonemapModifierData", "Tone mapping modifier");
prop = RNA_def_property(srna, "tonemap_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "type");
RNA_def_property_enum_items(prop, type_items);
- RNA_def_property_ui_text(prop, "Tonemap Type", "");
+ RNA_def_property_ui_text(prop, "Tonemap Type", "Tone mapping algorithm");
RNA_def_property_update(prop, NC_SCENE | ND_SEQUENCER, "rna_SequenceModifier_update");
prop = RNA_def_property(srna, "key", PROP_FLOAT, PROP_FACTOR);
diff --git a/source/blender/makesrna/intern/rna_sequencer_api.c b/source/blender/makesrna/intern/rna_sequencer_api.c
index 76f5a4934cf..d447d2972f6 100644
--- a/source/blender/makesrna/intern/rna_sequencer_api.c
+++ b/source/blender/makesrna/intern/rna_sequencer_api.c
@@ -457,7 +457,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
PropertyRNA *parm;
FunctionRNA *func;
- static EnumPropertyItem seq_effect_items[] = {
+ static const EnumPropertyItem seq_effect_items[] = {
{SEQ_TYPE_CROSS, "CROSS", 0, "Cross", ""},
{SEQ_TYPE_ADD, "ADD", 0, "Add", ""},
{SEQ_TYPE_SUB, "SUBTRACT", 0, "Subtract", ""},
@@ -475,6 +475,7 @@ void RNA_api_sequences(BlenderRNA *brna, PropertyRNA *cprop)
{SEQ_TYPE_ADJUSTMENT, "ADJUSTMENT", 0, "Adjustment Layer", ""},
{SEQ_TYPE_GAUSSIAN_BLUR, "GAUSSIAN_BLUR", 0, "Gaussian Blur", ""},
{SEQ_TYPE_TEXT, "TEXT", 0, "Text", ""},
+ {SEQ_TYPE_COLORMIX, "COLORMIX", 0, "Color Mix", ""},
{0, NULL, 0, NULL, NULL}
};
diff --git a/source/blender/makesrna/intern/rna_smoke.c b/source/blender/makesrna/intern/rna_smoke.c
index 6db370fc152..38c297def32 100644
--- a/source/blender/makesrna/intern/rna_smoke.c
+++ b/source/blender/makesrna/intern/rna_smoke.c
@@ -29,6 +29,9 @@
#include <stdlib.h>
#include <limits.h>
+#include "BLI_sys_types.h"
+#include "BLI_threads.h"
+
#include "RNA_define.h"
#include "RNA_enum_types.h"
@@ -38,10 +41,8 @@
#include "BKE_smoke.h"
#include "BKE_pointcache.h"
-#include "BLI_threads.h"
-
#include "DNA_modifier_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_smoke_types.h"
@@ -51,10 +52,10 @@
#ifdef RNA_RUNTIME
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_particle.h"
-#include "BKE_texture.h"
#include "smoke_API.h"
@@ -361,6 +362,42 @@ static void rna_SmokeModifier_heat_grid_get(PointerRNA *ptr, float *values)
#endif
}
+static void rna_SmokeModifier_temperature_grid_get(PointerRNA *ptr, float *values)
+{
+#ifdef WITH_SMOKE
+ SmokeDomainSettings *sds = (SmokeDomainSettings *)ptr->data;
+ int length[RNA_MAX_ARRAY_DIMENSION];
+ int size = rna_SmokeModifier_grid_get_length(ptr, length);
+ float *flame;
+
+ BLI_rw_mutex_lock(sds->fluid_mutex, THREAD_LOCK_READ);
+
+ if (sds->flags & MOD_SMOKE_HIGHRES && sds->wt) {
+ flame = smoke_turbulence_get_flame(sds->wt);
+ }
+ else {
+ flame = smoke_get_flame(sds->fluid);
+ }
+
+ if (flame) {
+ /* Output is such that 0..1 maps to 0..1000K */
+ float offset = sds->flame_ignition;
+ float scale = sds->flame_max_temp - sds->flame_ignition;
+
+ for (int i = 0; i < size; i++) {
+ values[i] = (flame[i] > 0.01f) ? offset + flame[i] * scale : 0.0f;
+ }
+ }
+ else {
+ memset(values, 0, size * sizeof(float));
+ }
+
+ BLI_rw_mutex_unlock(sds->fluid_mutex);
+#else
+ UNUSED_VARS(ptr, values);
+#endif
+}
+
static void rna_SmokeFlow_density_vgroup_get(PointerRNA *ptr, char *value)
{
SmokeFlowSettings *flow = (SmokeFlowSettings *)ptr->data;
@@ -392,7 +429,7 @@ static void rna_Smoke_use_color_ramp_set(PointerRNA *ptr, int value)
sds->use_coba = value;
if (value && sds->coba == NULL) {
- sds->coba = add_colorband(false);
+ sds->coba = BKE_colorband_add(false);
}
}
@@ -403,7 +440,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_noise_type_items[] = {
+ static const EnumPropertyItem prop_noise_type_items[] = {
{MOD_SMOKE_NOISEWAVE, "NOISEWAVE", 0, "Wavelet", ""},
#ifdef WITH_FFTW3
{MOD_SMOKE_NOISEFFT, "NOISEFFT", 0, "FFT", ""},
@@ -412,7 +449,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_compression_items[] = {
+ static const EnumPropertyItem prop_compression_items[] = {
{ VDB_COMPRESSION_ZIP, "ZIP", 0, "Zip", "Effective but slow compression" },
#ifdef WITH_OPENVDB_BLOSC
{ VDB_COMPRESSION_BLOSC, "BLOSC", 0, "Blosc", "Multithreaded compression, similar in size and quality as 'Zip'" },
@@ -421,26 +458,26 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
{ 0, NULL, 0, NULL, NULL }
};
- static EnumPropertyItem smoke_cache_comp_items[] = {
+ static const EnumPropertyItem smoke_cache_comp_items[] = {
{SM_CACHE_LIGHT, "CACHELIGHT", 0, "Light", "Fast but not so effective compression"},
{SM_CACHE_HEAVY, "CACHEHEAVY", 0, "Heavy", "Effective but slow compression"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoke_highres_sampling_items[] = {
+ static const EnumPropertyItem smoke_highres_sampling_items[] = {
{SM_HRES_FULLSAMPLE, "FULLSAMPLE", 0, "Full Sample", ""},
{SM_HRES_LINEAR, "LINEAR", 0, "Linear", ""},
{SM_HRES_NEAREST, "NEAREST", 0, "Nearest", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoke_data_depth_items[] = {
+ static const EnumPropertyItem smoke_data_depth_items[] = {
{16, "16", 0, "Float (Half)", "Half float (16 bit data)"},
{0, "32", 0, "Float (Full)", "Full float (32 bit data)"}, /* default */
{0, NULL, 0, NULL, NULL},
};
- static EnumPropertyItem smoke_domain_colli_items[] = {
+ static const EnumPropertyItem smoke_domain_colli_items[] = {
{SM_BORDER_OPEN, "BORDEROPEN", 0, "Open", "Smoke doesn't collide with any border"},
{SM_BORDER_VERTICAL, "BORDERVERTICAL", 0, "Vertically Open",
"Smoke doesn't collide with top and bottom sides"},
@@ -448,7 +485,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem cache_file_type_items[] = {
+ static const EnumPropertyItem cache_file_type_items[] = {
{PTCACHE_FILE_PTCACHE, "POINTCACHE", 0, "Point Cache", "Blender specific point cache file format"},
#ifdef WITH_OPENVDB
{PTCACHE_FILE_OPENVDB, "OPENVDB", 0, "OpenVDB", "OpenVDB file format"},
@@ -456,19 +493,19 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoke_view_items[] = {
+ static const EnumPropertyItem smoke_view_items[] = {
{MOD_SMOKE_SLICE_VIEW_ALIGNED, "VIEW_ALIGNED", 0, "View", "Slice volume parallel to the view plane"},
{MOD_SMOKE_SLICE_AXIS_ALIGNED, "AXIS_ALIGNED", 0, "Axis", "Slice volume parallel to the major axis"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem axis_slice_method_items[] = {
+ static const EnumPropertyItem axis_slice_method_items[] = {
{AXIS_SLICE_FULL, "FULL", 0, "Full", "Slice the whole domain object"},
{AXIS_SLICE_SINGLE, "SINGLE", 0, "Single", "Perform a single slice of the domain object"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem axis_slice_position_items[] = {
+ static const EnumPropertyItem axis_slice_position_items[] = {
{SLICE_AXIS_AUTO, "AUTO", 0, "Auto", "Adjust slice direction according to the view direction"},
{SLICE_AXIS_X, "X", 0, "X", "Slice along the X axis"},
{SLICE_AXIS_Y, "Y", 0, "Y", "Slice along the Y axis"},
@@ -476,7 +513,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vector_draw_items[] = {
+ static const EnumPropertyItem vector_draw_items[] = {
{VECTOR_DRAW_NEEDLE, "NEEDLE", 0, "Needle", "Draw vectors as needles"},
{VECTOR_DRAW_STREAMLINE, "STREAMLINE", 0, "Streamlines", "Draw vectors as streamlines"},
{0, NULL, 0, NULL, NULL}
@@ -585,6 +622,7 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
prop = RNA_def_property(srna, "point_cache", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_NEVER_NULL);
RNA_def_property_pointer_sdna(prop, NULL, "point_cache[0]");
+ RNA_def_property_struct_type(prop, "PointCache");
RNA_def_property_ui_text(prop, "Point Cache", "");
prop = RNA_def_property(srna, "point_cache_compress_type", PROP_ENUM, PROP_NONE);
@@ -676,6 +714,14 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_float_funcs(prop, "rna_SmokeModifier_heat_grid_get", NULL, NULL);
RNA_def_property_ui_text(prop, "Heat Grid", "Smoke heat grid");
+ prop = RNA_def_property(srna, "temperature_grid", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_array(prop, 32);
+ RNA_def_property_flag(prop, PROP_DYNAMIC);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_dynamic_array_funcs(prop, "rna_SmokeModifier_grid_get_length");
+ RNA_def_property_float_funcs(prop, "rna_SmokeModifier_temperature_grid_get", NULL, NULL);
+ RNA_def_property_ui_text(prop, "Temperature Grid", "Smoke temperature grid, range 0..1 represents 0..1000K");
+
prop = RNA_def_property(srna, "cell_size", PROP_FLOAT, PROP_XYZ); /* can change each frame when using adaptive domain */
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "cell_size", "Cell Size");
@@ -828,18 +874,18 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
"Render a simulation field while mapping its voxels values to the colors of a ramp");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL);
- static EnumPropertyItem coba_field_items[] = {
+ static const EnumPropertyItem coba_field_items[] = {
{FLUID_FIELD_COLOR_R, "COLOR_R", 0, "Red", "Red component of the color field"},
{FLUID_FIELD_COLOR_G, "COLOR_G", 0, "Green", "Green component of the color field"},
{FLUID_FIELD_COLOR_B, "COLOR_B", 0, "Blue", "Blue component of the color field"},
- {FLUID_FIELD_DENSITY, "DENSITY", 0, "Density", "Quantity of soot in the fluid"},
+ {FLUID_FIELD_DENSITY, "DENSITY", 0, "Density", "Quantity of soot in the fluid"},
{FLUID_FIELD_FLAME, "FLAME", 0, "Flame", "Flame field"},
{FLUID_FIELD_FUEL, "FUEL", 0, "Fuel", "Fuel field"},
{FLUID_FIELD_HEAT, "HEAT", 0, "Heat", "Temperature of the fluid"},
{FLUID_FIELD_VELOCITY_X, "VELOCITY_X", 0, "X Velocity", "X component of the velocity field"},
{FLUID_FIELD_VELOCITY_Y, "VELOCITY_Y", 0, "Y Velocity", "Y component of the velocity field"},
{FLUID_FIELD_VELOCITY_Z, "VELOCITY_Z", 0, "Z Velocity", "Z component of the velocity field"},
- {0, NULL, 0, NULL, NULL}
+ {0, NULL, 0, NULL, NULL}
};
prop = RNA_def_property(srna, "coba_field", PROP_ENUM, PROP_NONE);
@@ -853,6 +899,14 @@ static void rna_def_smoke_domain_settings(BlenderRNA *brna)
RNA_def_property_struct_type(prop, "ColorRamp");
RNA_def_property_ui_text(prop, "Color Ramp", "");
RNA_def_property_update(prop, NC_OBJECT | ND_DRAW, NULL);
+
+ prop = RNA_def_property(srna, "clipping", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "clipping");
+ RNA_def_property_range(prop, 0.0, 1.0);
+ RNA_def_property_ui_range(prop, 0.0, 1.0, 0.1, 3);
+ RNA_def_property_ui_text(prop, "Clipping",
+ "Value under which voxels are considered empty space to optimize caching or rendering");
+ RNA_def_property_update(prop, NC_OBJECT | ND_MODIFIER, NULL);
}
static void rna_def_smoke_flow_settings(BlenderRNA *brna)
@@ -860,7 +914,7 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem smoke_flow_types[] = {
+ static const EnumPropertyItem smoke_flow_types[] = {
{MOD_SMOKE_FLOW_TYPE_OUTFLOW, "OUTFLOW", 0, "Outflow", "Delete smoke from simulation"},
{MOD_SMOKE_FLOW_TYPE_SMOKE, "SMOKE", 0, "Smoke", "Add smoke"},
{MOD_SMOKE_FLOW_TYPE_SMOKEFIRE, "BOTH", 0, "Fire + Smoke", "Add fire and smoke"},
@@ -868,13 +922,13 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoke_flow_sources[] = {
+ static const EnumPropertyItem smoke_flow_sources[] = {
{MOD_SMOKE_FLOW_SOURCE_PARTICLES, "PARTICLES", ICON_PARTICLES, "Particle System", "Emit smoke from particles"},
{MOD_SMOKE_FLOW_SOURCE_MESH, "MESH", ICON_META_CUBE, "Mesh", "Emit smoke from mesh surface or volume"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoke_flow_texture_types[] = {
+ static const EnumPropertyItem smoke_flow_texture_types[] = {
{MOD_SMOKE_FLOW_TEXTURE_MAP_AUTO, "AUTO", 0, "Generated", "Generated coordinates centered to flow object"},
{MOD_SMOKE_FLOW_TEXTURE_MAP_UV, "UV", 0, "UV", "Use UV layer for texture coordinates"},
{0, NULL, 0, NULL, NULL}
@@ -1035,7 +1089,7 @@ static void rna_def_smoke_flow_settings(BlenderRNA *brna)
static void rna_def_smoke_coll_settings(BlenderRNA *brna)
{
- static EnumPropertyItem smoke_coll_type_items[] = {
+ static const EnumPropertyItem smoke_coll_type_items[] = {
{SM_COLL_STATIC, "COLLSTATIC", 0, "Static", "Non moving obstacle"},
{SM_COLL_RIGID, "COLLRIGID", 0, "Rigid", "Rigid obstacle"},
{SM_COLL_ANIMATED, "COLLANIMATED", 0, "Animated", "Animated obstacle"},
diff --git a/source/blender/makesrna/intern/rna_space.c b/source/blender/makesrna/intern/rna_space.c
index 5e364a3adf1..d6a304f4dfe 100644
--- a/source/blender/makesrna/intern/rna_space.c
+++ b/source/blender/makesrna/intern/rna_space.c
@@ -60,31 +60,41 @@
#include "RNA_enum_types.h"
-EnumPropertyItem rna_enum_space_type_items[] = {
+const EnumPropertyItem rna_enum_space_type_items[] = {
/* empty must be here for python, is skipped for UI */
{SPACE_EMPTY, "EMPTY", ICON_NONE, "Empty", ""},
+
+ /* General */
+ {0, "", ICON_NONE, "General", ""},
{SPACE_VIEW3D, "VIEW_3D", ICON_VIEW3D, "3D View", "3D viewport"},
- {0, "", ICON_NONE, NULL, NULL},
+ {SPACE_IMAGE, "IMAGE_EDITOR", ICON_IMAGE_COL, "UV/Image Editor", "View and edit images and UV Maps"},
+ {SPACE_NODE, "NODE_EDITOR", ICON_NODETREE, "Node Editor", "Editor for node-based shading and compositing tools"},
+ {SPACE_SEQ, "SEQUENCE_EDITOR", ICON_SEQUENCE, "Video Sequencer", "Video editing tools"},
+ {SPACE_CLIP, "CLIP_EDITOR", ICON_CLIP, "Movie Clip Editor", "Motion tracking tools"},
+
+ /* Animation */
+ {0, "", ICON_NONE, "Animation", ""},
{SPACE_TIME, "TIMELINE", ICON_TIME, "Timeline", "Timeline and playback controls"},
{SPACE_IPO, "GRAPH_EDITOR", ICON_IPO, "Graph Editor", "Edit drivers and keyframe interpolation"},
{SPACE_ACTION, "DOPESHEET_EDITOR", ICON_ACTION, "Dope Sheet", "Adjust timing of keyframes"},
{SPACE_NLA, "NLA_EDITOR", ICON_NLA, "NLA Editor", "Combine and layer Actions"},
- {0, "", ICON_NONE, NULL, NULL},
- {SPACE_IMAGE, "IMAGE_EDITOR", ICON_IMAGE_COL, "UV/Image Editor", "View and edit images and UV Maps"},
- {SPACE_SEQ, "SEQUENCE_EDITOR", ICON_SEQUENCE, "Video Sequence Editor", "Video editing tools"},
- {SPACE_CLIP, "CLIP_EDITOR", ICON_CLIP, "Movie Clip Editor", "Motion tracking tools"},
+
+ /* Scripting */
+ {0, "", ICON_NONE, "Scripting", ""},
{SPACE_TEXT, "TEXT_EDITOR", ICON_TEXT, "Text Editor", "Edit scripts and in-file documentation"},
- {SPACE_NODE, "NODE_EDITOR", ICON_NODETREE, "Node Editor", "Editor for node-based shading and compositing tools"},
{SPACE_LOGIC, "LOGIC_EDITOR", ICON_LOGIC, "Logic Editor", "Game logic editing"},
- {0, "", ICON_NONE, NULL, NULL},
- {SPACE_BUTS, "PROPERTIES", ICON_BUTS, "Properties", "Edit properties of active object and related data-blocks"},
+ {SPACE_CONSOLE, "CONSOLE", ICON_CONSOLE, "Python Console", "Interactive programmatic console for "
+ "advanced editing and script development"},
+ {SPACE_INFO, "INFO", ICON_INFO, "Info", "Main menu bar and list of error messages "
+ "(drag down to expand and display)"},
+
+ /* Data */
+ {0, "", ICON_NONE, "Data", ""},
{SPACE_OUTLINER, "OUTLINER", ICON_OOPS, "Outliner", "Overview of scene graph and all available data-blocks"},
- {SPACE_USERPREF, "USER_PREFERENCES", ICON_PREFERENCES, "User Preferences", "Edit persistent configuration settings"},
- {SPACE_INFO, "INFO", ICON_INFO, "Info", "Main menu bar and list of error messages (drag down to expand and display)"},
- {0, "", ICON_NONE, NULL, NULL},
+ {SPACE_BUTS, "PROPERTIES", ICON_BUTS, "Properties", "Edit properties of active object and related data-blocks"},
{SPACE_FILE, "FILE_BROWSER", ICON_FILESEL, "File Browser", "Browse for files and assets"},
- {0, "", ICON_NONE, NULL, NULL},
- {SPACE_CONSOLE, "CONSOLE", ICON_CONSOLE, "Python Console", "Interactive programmatic console for advanced editing and script development"},
+ {SPACE_USERPREF, "USER_PREFERENCES", ICON_PREFERENCES, "User Preferences",
+ "Edit persistent configuration settings"},
{0, NULL, 0, NULL, NULL}
};
@@ -95,7 +105,7 @@ EnumPropertyItem rna_enum_space_type_items[] = {
#define V3D_S3D_CAMERA_VIEWS {STEREO_MONO_ID, "MONO", ICON_RESTRICT_RENDER_OFF, "Views", ""},
#endif
-static EnumPropertyItem stereo3d_camera_items[] = {
+static const EnumPropertyItem stereo3d_camera_items[] = {
V3D_S3D_CAMERA_LEFT
V3D_S3D_CAMERA_RIGHT
V3D_S3D_CAMERA_S3D
@@ -103,7 +113,7 @@ static EnumPropertyItem stereo3d_camera_items[] = {
};
#ifdef RNA_RUNTIME
-static EnumPropertyItem multiview_camera_items[] = {
+static const EnumPropertyItem multiview_camera_items[] = {
V3D_S3D_CAMERA_VIEWS
V3D_S3D_CAMERA_S3D
{0, NULL, 0, NULL, NULL}
@@ -116,14 +126,14 @@ static EnumPropertyItem multiview_camera_items[] = {
#undef V3D_S3D_CAMERA_VIEWS
#ifndef RNA_RUNTIME
-static EnumPropertyItem stereo3d_eye_items[] = {
+static const EnumPropertyItem stereo3d_eye_items[] = {
{STEREO_LEFT_ID, "LEFT_EYE", ICON_NONE, "Left Eye"},
{STEREO_RIGHT_ID, "RIGHT_EYE", ICON_NONE, "Right Eye"},
{0, NULL, 0, NULL, NULL}
};
#endif
-static EnumPropertyItem pivot_items_full[] = {
+static const EnumPropertyItem pivot_items_full[] = {
{V3D_AROUND_CENTER_BOUNDS, "BOUNDING_BOX_CENTER", ICON_ROTATE, "Bounding Box Center",
"Pivot around bounding box center of selected object(s)"},
{V3D_AROUND_CURSOR, "CURSOR", ICON_CURSOR, "3D Cursor", "Pivot around the 3D cursor"},
@@ -135,7 +145,7 @@ static EnumPropertyItem pivot_items_full[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem draw_channels_items[] = {
+static const EnumPropertyItem draw_channels_items[] = {
{SI_USE_ALPHA, "COLOR_ALPHA", ICON_IMAGE_RGB_ALPHA, "Color and Alpha",
"Draw image with RGB colors and alpha transparency"},
{0, "COLOR", ICON_IMAGE_RGB, "Color", "Draw image with RGB colors"},
@@ -148,7 +158,7 @@ static EnumPropertyItem draw_channels_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem transform_orientation_items[] = {
+static const EnumPropertyItem transform_orientation_items[] = {
{V3D_MANIP_GLOBAL, "GLOBAL", 0, "Global", "Align the transformation axes to world space"},
{V3D_MANIP_LOCAL, "LOCAL", 0, "Local", "Align the transformation axes to the selected objects' local space"},
{V3D_MANIP_NORMAL, "NORMAL", 0, "Normal",
@@ -161,7 +171,7 @@ static EnumPropertyItem transform_orientation_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem autosnap_items[] = {
+static const EnumPropertyItem autosnap_items[] = {
{SACTSNAP_OFF, "NONE", 0, "No Auto-Snap", ""},
/* {-1, "", 0, "", ""}, */
{SACTSNAP_STEP, "STEP", 0, "Frame Step", "Snap to 1.0 frame intervals"},
@@ -175,7 +185,7 @@ static EnumPropertyItem autosnap_items[] = {
};
#endif
-EnumPropertyItem rna_enum_viewport_shade_items[] = {
+const EnumPropertyItem rna_enum_viewport_shade_items[] = {
{OB_BOUNDBOX, "BOUNDBOX", ICON_BBOX, "Bounding Box", "Display the object's local bounding boxes only"},
{OB_WIRE, "WIREFRAME", ICON_WIRE, "Wireframe", "Display the object as wire edges"},
{OB_SOLID, "SOLID", ICON_SOLID, "Solid", "Display the object solid, lit with default OpenGL lights"},
@@ -186,14 +196,14 @@ EnumPropertyItem rna_enum_viewport_shade_items[] = {
};
-EnumPropertyItem rna_enum_clip_editor_mode_items[] = {
+const EnumPropertyItem rna_enum_clip_editor_mode_items[] = {
{SC_MODE_TRACKING, "TRACKING", ICON_ANIM_DATA, "Tracking", "Show tracking and solving tools"},
{SC_MODE_MASKEDIT, "MASK", ICON_MOD_MASK, "Mask", "Show mask editing tools"},
{0, NULL, 0, NULL, NULL}
};
/* Actually populated dynamically trough a function, but helps for context-less access (e.g. doc, i18n...). */
-static EnumPropertyItem buttons_context_items[] = {
+static const EnumPropertyItem buttons_context_items[] = {
{BCONTEXT_SCENE, "SCENE", ICON_SCENE_DATA, "Scene", "Scene"},
{BCONTEXT_RENDER, "RENDER", ICON_SCENE, "Render", "Render"},
{BCONTEXT_RENDER_LAYER, "RENDER_LAYER", ICON_RENDERLAYERS, "Render Layers", "Render layers"},
@@ -212,7 +222,7 @@ static EnumPropertyItem buttons_context_items[] = {
};
/* Actually populated dynamically trough a function, but helps for context-less access (e.g. doc, i18n...). */
-static EnumPropertyItem buttons_texture_context_items[] = {
+static const EnumPropertyItem buttons_texture_context_items[] = {
{SB_TEXC_MATERIAL, "MATERIAL", ICON_MATERIAL, "", "Show material textures"},
{SB_TEXC_WORLD, "WORLD", ICON_WORLD, "", "Show world textures"},
{SB_TEXC_LAMP, "LAMP", ICON_LAMP, "", "Show lamp textures"},
@@ -223,7 +233,7 @@ static EnumPropertyItem buttons_texture_context_items[] = {
};
-static EnumPropertyItem fileselectparams_recursion_level_items[] = {
+static const EnumPropertyItem fileselectparams_recursion_level_items[] = {
{0, "NONE", 0, "None", "Only list current directory's content, with no recursion"},
{1, "BLEND", 0, "Blend File", "List .blend files' content"},
{2, "ALL_1", 0, "One Level", "List all sub-directories' content, one level of recursion"},
@@ -232,7 +242,7 @@ static EnumPropertyItem fileselectparams_recursion_level_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_file_sort_items[] = {
+const EnumPropertyItem rna_enum_file_sort_items[] = {
{FILE_SORT_ALPHA, "FILE_SORT_ALPHA", ICON_SORTALPHA, "Sort alphabetically", "Sort the file list alphabetically"},
{FILE_SORT_EXTENSION, "FILE_SORT_EXTENSION", ICON_SORTBYEXT, "Sort by extension", "Sort the file list by extension/type"},
{FILE_SORT_TIME, "FILE_SORT_TIME", ICON_SORTTIME, "Sort by time", "Sort files by modification time"},
@@ -415,7 +425,8 @@ static PointerRNA rna_CurrentOrientation_get(PointerRNA *ptr)
BLI_findlink(&scene->transform_spaces, v3d->twmode - V3D_MANIP_CUSTOM));
}
-EnumPropertyItem *rna_TransformOrientation_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *rna_TransformOrientation_itemf(
+ bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
Scene *scene = NULL;
ListBase *transform_spaces;
@@ -492,7 +503,7 @@ static void rna_View3D_CursorLocation_get(PointerRNA *ptr, float *values)
bScreen *sc = (bScreen *)ptr->id.data;
Scene *scene = (Scene *)sc->scene;
const float *loc = ED_view3d_cursor3d_get(scene, v3d);
-
+
copy_v3_v3(values, loc);
}
@@ -502,7 +513,7 @@ static void rna_View3D_CursorLocation_set(PointerRNA *ptr, const float *values)
bScreen *sc = (bScreen *)ptr->id.data;
Scene *scene = (Scene *)sc->scene;
float *cursor = ED_view3d_cursor3d_get(scene, v3d);
-
+
copy_v3_v3(cursor, values);
}
@@ -518,7 +529,7 @@ static float rna_View3D_GridScaleUnit_get(PointerRNA *ptr)
static void rna_SpaceView3D_layer_set(PointerRNA *ptr, const int *values)
{
View3D *v3d = (View3D *)(ptr->data);
-
+
v3d->lay = ED_view3d_scene_layer_set(v3d->lay, values, &v3d->layact);
}
@@ -534,27 +545,27 @@ static void rna_SpaceView3D_layer_update(Main *bmain, Scene *UNUSED(scene), Poin
DAG_on_visible_update(bmain, false);
}
-static void rna_SpaceView3D_viewport_shade_update(Main *bmain, Scene *scene, PointerRNA *ptr)
+static void rna_SpaceView3D_viewport_shade_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *ptr)
{
View3D *v3d = (View3D *)(ptr->data);
ScrArea *sa = rna_area_from_space(ptr);
- ED_view3d_shade_update(bmain, scene, v3d, sa);
+ ED_view3d_shade_update(bmain, v3d, sa);
}
static void rna_SpaceView3D_matcap_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
View3D *v3d = (View3D *)(ptr->data);
-
+
if (v3d->defmaterial) {
Material *ma = v3d->defmaterial;
-
+
if (ma->preview)
BKE_previewimg_free(&ma->preview);
-
+
if (ma->gpumaterial.first)
GPU_material_free(&ma->gpumaterial);
-
+
WM_main_add_notifier(NC_MATERIAL | ND_SHADING_DRAW, ma);
}
}
@@ -562,7 +573,7 @@ static void rna_SpaceView3D_matcap_update(Main *UNUSED(bmain), Scene *UNUSED(sce
static void rna_SpaceView3D_matcap_enable(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
View3D *v3d = (View3D *)(ptr->data);
-
+
if (v3d->matcap_icon < ICON_MATCAP_01 ||
v3d->matcap_icon > ICON_MATCAP_24)
{
@@ -714,12 +725,12 @@ static void rna_SpaceView3D_viewport_shade_set(PointerRNA *ptr, int value)
v3d->drawtype = value;
}
-static EnumPropertyItem *rna_SpaceView3D_viewport_shade_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_SpaceView3D_viewport_shade_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
Scene *scene = ((bScreen *)ptr->id.data)->scene;
RenderEngineType *type = RE_engines_find(scene->r.engine);
-
+
EnumPropertyItem *item = NULL;
int totitem = 0;
@@ -728,7 +739,7 @@ static EnumPropertyItem *rna_SpaceView3D_viewport_shade_itemf(bContext *UNUSED(C
RNA_enum_items_add_value(&item, &totitem, rna_enum_viewport_shade_items, OB_SOLID);
RNA_enum_items_add_value(&item, &totitem, rna_enum_viewport_shade_items, OB_TEXTURE);
RNA_enum_items_add_value(&item, &totitem, rna_enum_viewport_shade_items, OB_MATERIAL);
-
+
if (type && type->view_draw)
RNA_enum_items_add_value(&item, &totitem, rna_enum_viewport_shade_items, OB_RENDER);
@@ -738,7 +749,7 @@ static EnumPropertyItem *rna_SpaceView3D_viewport_shade_itemf(bContext *UNUSED(C
return item;
}
-static EnumPropertyItem *rna_SpaceView3D_stereo3d_camera_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_SpaceView3D_stereo3d_camera_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
Scene *scene = ((bScreen *)ptr->id.data)->scene;
@@ -834,7 +845,7 @@ static void rna_SpaceImageEditor_mask_set(PointerRNA *ptr, PointerRNA value)
ED_space_image_set_mask(NULL, sima, (Mask *)value.data);
}
-static EnumPropertyItem *rna_SpaceImageEditor_draw_channels_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_SpaceImageEditor_draw_channels_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
SpaceImage *sima = (SpaceImage *)ptr->data;
@@ -844,7 +855,7 @@ static EnumPropertyItem *rna_SpaceImageEditor_draw_channels_itemf(bContext *UNUS
int zbuf, alpha, totitem = 0;
ibuf = ED_space_image_acquire_buffer(sima, &lock);
-
+
alpha = ibuf && (ibuf->channels == 4);
zbuf = ibuf && (ibuf->zbuf || ibuf->zbuf_float || (ibuf->channels == 1));
@@ -895,14 +906,14 @@ static void rna_SpaceImageEditor_zoom_get(PointerRNA *ptr, float *values)
static void rna_SpaceImageEditor_cursor_location_get(PointerRNA *ptr, float *values)
{
SpaceImage *sima = (SpaceImage *)ptr->data;
-
+
if (sima->flag & SI_COORDFLOATS) {
copy_v2_v2(values, sima->cursor);
}
else {
int w, h;
ED_space_image_get_size(sima, &w, &h);
-
+
values[0] = sima->cursor[0] * w;
values[1] = sima->cursor[1] * h;
}
@@ -911,14 +922,14 @@ static void rna_SpaceImageEditor_cursor_location_get(PointerRNA *ptr, float *val
static void rna_SpaceImageEditor_cursor_location_set(PointerRNA *ptr, const float *values)
{
SpaceImage *sima = (SpaceImage *)ptr->data;
-
+
if (sima->flag & SI_COORDFLOATS) {
copy_v2_v2(sima->cursor, values);
}
else {
int w, h;
ED_space_image_get_size(sima, &w, &h);
-
+
sima->cursor[0] = values[0] / w;
sima->cursor[1] = values[1] / h;
}
@@ -947,7 +958,7 @@ static void rna_SpaceImageEditor_scopes_update(struct bContext *C, struct Pointe
SpaceImage *sima = (SpaceImage *)ptr->data;
ImBuf *ibuf;
void *lock;
-
+
ibuf = ED_space_image_acquire_buffer(sima, &lock);
if (ibuf) {
ED_space_image_scopes_update(C, sima, ibuf, true);
@@ -956,10 +967,10 @@ static void rna_SpaceImageEditor_scopes_update(struct bContext *C, struct Pointe
ED_space_image_release_buffer(sima, ibuf, lock);
}
-static EnumPropertyItem *rna_SpaceImageEditor_pivot_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_SpaceImageEditor_pivot_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
- static EnumPropertyItem pivot_items[] = {
+ static const EnumPropertyItem pivot_items[] = {
{V3D_AROUND_CENTER_BOUNDS, "CENTER", ICON_ROTATE, "Bounding Box Center", ""},
{V3D_AROUND_CENTER_MEAN, "MEDIAN", ICON_ROTATECENTER, "Median Point", ""},
{V3D_AROUND_CURSOR, "CURSOR", ICON_CURSOR, "2D Cursor", ""},
@@ -1026,12 +1037,12 @@ static void rna_SpaceProperties_pin_id_update(Main *UNUSED(bmain), Scene *UNUSED
{
SpaceButs *sbuts = (SpaceButs *)(ptr->data);
ID *id = sbuts->pinid;
-
+
if (id == NULL) {
sbuts->flag &= ~SB_PIN_CONTEXT;
return;
}
-
+
switch (GS(id->name)) {
case ID_MA:
WM_main_add_notifier(NC_MATERIAL | ND_SHADING, NULL);
@@ -1045,6 +1056,8 @@ static void rna_SpaceProperties_pin_id_update(Main *UNUSED(bmain), Scene *UNUSED
case ID_LA:
WM_main_add_notifier(NC_LAMP, NULL);
break;
+ default:
+ break;
}
}
@@ -1052,12 +1065,12 @@ static void rna_SpaceProperties_pin_id_update(Main *UNUSED(bmain), Scene *UNUSED
static void rna_SpaceProperties_context_set(PointerRNA *ptr, int value)
{
SpaceButs *sbuts = (SpaceButs *)(ptr->data);
-
+
sbuts->mainb = value;
sbuts->mainbuser = value;
}
-static EnumPropertyItem *rna_SpaceProperties_context_itemf(bContext *UNUSED(C), PointerRNA *ptr,
+static const EnumPropertyItem *rna_SpaceProperties_context_itemf(bContext *UNUSED(C), PointerRNA *ptr,
PropertyRNA *UNUSED(prop), bool *r_free)
{
SpaceButs *sbuts = (SpaceButs *)(ptr->data);
@@ -1130,7 +1143,8 @@ static EnumPropertyItem *rna_SpaceProperties_context_itemf(bContext *UNUSED(C),
static void rna_SpaceProperties_context_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
SpaceButs *sbuts = (SpaceButs *)(ptr->data);
- if (ELEM(sbuts->mainb, BCONTEXT_WORLD, BCONTEXT_MATERIAL, BCONTEXT_TEXTURE)) {
+ /* XXX BCONTEXT_DATA is ugly, but required for lamps... See T51318. */
+ if (ELEM(sbuts->mainb, BCONTEXT_WORLD, BCONTEXT_MATERIAL, BCONTEXT_TEXTURE, BCONTEXT_DATA)) {
sbuts->preview = 1;
}
}
@@ -1143,7 +1157,7 @@ static void rna_SpaceProperties_align_set(PointerRNA *ptr, int value)
sbuts->re_align = 1;
}
-static EnumPropertyItem *rna_SpaceProperties_texture_context_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_SpaceProperties_texture_context_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
@@ -1203,7 +1217,7 @@ static void rna_ConsoleLine_body_set(PointerRNA *ptr, const char *value)
{
ConsoleLine *ci = (ConsoleLine *)ptr->data;
int len = strlen(value);
-
+
if ((len >= ci->len_alloc) || (len * 2 < ci->len_alloc) ) { /* allocate a new string */
MEM_freeN(ci->line);
ci->line = MEM_mallocN((len + 1) * sizeof(char), "rna_consoleline");
@@ -1231,7 +1245,7 @@ static void rna_SpaceDopeSheetEditor_action_set(PointerRNA *ptr, PointerRNA valu
{
SpaceAction *saction = (SpaceAction *)(ptr->data);
bAction *act = (bAction *)value.data;
-
+
if ((act == NULL) || (act->idroot == 0)) {
/* just set if we're clearing the action or if the action is "amorphous" still */
saction->action = act;
@@ -1268,7 +1282,7 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *bmain, Scene *scene, Po
/* we must set this action to be the one used by active object (if not pinned) */
if (obact /* && saction->pin == 0*/) {
AnimData *adt = NULL;
-
+
if (saction->mode == SACTCONT_ACTION) {
/* TODO: context selector could help decide this with more control? */
adt = BKE_animdata_add_id(&obact->id); /* this only adds if non-existent */
@@ -1278,7 +1292,7 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *bmain, Scene *scene, Po
if (key)
adt = BKE_animdata_add_id(&key->id); /* this only adds if non-existent */
}
-
+
/* set action */
// FIXME: this overlaps a lot with the BKE_animdata_set_action() API method
if (adt) {
@@ -1286,11 +1300,11 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *bmain, Scene *scene, Po
if (adt->action != saction->action) {
/* NLA Tweak Mode needs special handling... */
if (adt->flag & ADT_NLA_EDIT_ON) {
- /* Exit editmode first - we cannot change actions while in tweakmode
+ /* Exit editmode first - we cannot change actions while in tweakmode
* NOTE: This will clear the action ref properly
*/
BKE_nla_tweakmode_exit(adt);
-
+
/* Assign new action, and adjust the usercounts accordingly */
adt->action = saction->action;
id_us_plus((ID *)adt->action);
@@ -1300,7 +1314,7 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *bmain, Scene *scene, Po
if (adt->action) {
/* Fix id-count of action we're replacing */
id_us_min(&adt->action->id);
-
+
/* To prevent data loss (i.e. if users flip between actions using the Browse menu),
* stash this action if nothing else uses it.
*
@@ -1317,17 +1331,17 @@ static void rna_SpaceDopeSheetEditor_action_update(Main *bmain, Scene *scene, Po
BKE_nla_action_stash(adt);
}
}
-
+
/* Assign new action, and adjust the usercounts accordingly */
adt->action = saction->action;
id_us_plus((ID *)adt->action);
}
}
-
+
/* Force update of animdata */
adt->recalc |= ADT_RECALC_ANIM;
}
-
+
/* force depsgraph flush too */
DAG_id_tag_update(&obact->id, OB_RECALC_OB | OB_RECALC_DATA);
/* Update relations as well, so new time source dependency is added. */
@@ -1339,17 +1353,17 @@ static void rna_SpaceDopeSheetEditor_mode_update(Main *UNUSED(bmain), Scene *sce
{
SpaceAction *saction = (SpaceAction *)(ptr->data);
Object *obact = (scene->basact) ? scene->basact->object : NULL;
-
+
/* special exceptions for ShapeKey Editor mode */
if (saction->mode == SACTCONT_SHAPEKEY) {
Key *key = BKE_key_from_object(obact);
-
+
/* 1) update the action stored for the editor */
if (key)
saction->action = (key->adt) ? key->adt->action : NULL;
else
saction->action = NULL;
-
+
/* 2) enable 'show sliders' by default, since one of the main
* points of the ShapeKey Editor is to provide a one-stop shop
* for controlling the shapekeys, whose main control is the value
@@ -1365,7 +1379,7 @@ static void rna_SpaceDopeSheetEditor_mode_update(Main *UNUSED(bmain), Scene *sce
else
saction->action = NULL;
}
-
+
/* recalculate extents of channel list */
saction->flag |= SACTION_TEMP_NEEDCHANSYNC;
}
@@ -1375,7 +1389,7 @@ static void rna_SpaceDopeSheetEditor_mode_update(Main *UNUSED(bmain), Scene *sce
static void rna_SpaceGraphEditor_display_mode_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *ptr)
{
ScrArea *sa = rna_area_from_space(ptr);
-
+
/* after changing view mode, must force recalculation of F-Curve colors
* which can only be achieved using refresh as opposed to redraw
*/
@@ -1427,7 +1441,7 @@ static void rna_BackgroundImage_size_set(PointerRNA *ptr, float value)
static BGpic *rna_BackgroundImage_new(View3D *v3d)
{
- BGpic *bgpic = ED_view3D_background_image_new(v3d);
+ BGpic *bgpic = ED_view3d_background_image_new(v3d);
WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D, v3d);
@@ -1441,7 +1455,7 @@ static void rna_BackgroundImage_remove(View3D *v3d, ReportList *reports, Pointer
BKE_report(reports, RPT_ERROR, "Background image cannot be removed");
}
- ED_view3D_background_image_remove(v3d, bgpic);
+ ED_view3d_background_image_remove(v3d, bgpic);
RNA_POINTER_INVALIDATE(bgpic_ptr);
WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D, v3d);
@@ -1449,7 +1463,7 @@ static void rna_BackgroundImage_remove(View3D *v3d, ReportList *reports, Pointer
static void rna_BackgroundImage_clear(View3D *v3d)
{
- ED_view3D_background_image_clear(v3d);
+ ED_view3d_background_image_clear(v3d);
WM_main_add_notifier(NC_SPACE | ND_SPACE_VIEW3D, v3d);
}
@@ -1465,7 +1479,7 @@ static int rna_SpaceNodeEditor_node_tree_poll(PointerRNA *ptr, const PointerRNA
{
SpaceNode *snode = (SpaceNode *)ptr->data;
bNodeTree *ntree = (bNodeTree *)value.data;
-
+
/* node tree type must match the selected type in node editor */
return (STREQ(snode->tree_idname, ntree->idname));
}
@@ -1493,7 +1507,7 @@ static int rna_SpaceNodeEditor_tree_type_poll(void *Cv, bNodeTreeType *type)
else
return true;
}
-static EnumPropertyItem *rna_SpaceNodeEditor_tree_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_SpaceNodeEditor_tree_type_itemf(bContext *C, PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
return rna_node_tree_type_itemf(C, rna_SpaceNodeEditor_tree_type_poll, r_free);
@@ -1544,7 +1558,7 @@ static void rna_SpaceNodeEditor_show_backdrop_update(Main *UNUSED(bmain), Scene
static void rna_SpaceNodeEditor_cursor_location_from_region(SpaceNode *snode, bContext *C, int x, int y)
{
ARegion *ar = CTX_wm_region(C);
-
+
UI_view2d_region_to_view(&ar->v2d, x, y, &snode->cursor[0], &snode->cursor[1]);
snode->cursor[0] /= UI_DPI_FAC;
snode->cursor[1] /= UI_DPI_FAC;
@@ -1595,7 +1609,7 @@ static int rna_FileSelectParams_use_lib_get(PointerRNA *ptr)
return params && (params->type == FILE_LOADLIB);
}
-static EnumPropertyItem *rna_FileSelectParams_recursion_level_itemf(
+static const EnumPropertyItem *rna_FileSelectParams_recursion_level_itemf(
bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
FileSelectParams *params = ptr->data;
@@ -1884,7 +1898,7 @@ static void rna_FileBrowser_FSMenuRecent_active_range(PointerRNA *ptr, int *min,
#else
-static EnumPropertyItem dt_uv_items[] = {
+static const EnumPropertyItem dt_uv_items[] = {
{SI_UVDT_OUTLINE, "OUTLINE", 0, "Outline", "Draw white edges with black outline"},
{SI_UVDT_DASH, "DASH", 0, "Dash", "Draw dashed black-white edges"},
{SI_UVDT_BLACK, "BLACK", 0, "Black", "Draw black edges"},
@@ -1896,12 +1910,12 @@ static void rna_def_space(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "Space", NULL);
RNA_def_struct_sdna(srna, "SpaceLink");
RNA_def_struct_ui_text(srna, "Space", "Space data for a screen area");
RNA_def_struct_refine_func(srna, "rna_Space_refine");
-
+
prop = RNA_def_property(srna, "type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "spacetype");
RNA_def_property_enum_items(prop, rna_enum_space_type_items);
@@ -1920,7 +1934,7 @@ static void rna_def_space_mask_info(StructRNA *srna, int noteflag, const char *m
{
PropertyRNA *prop;
- static EnumPropertyItem overlay_mode_items[] = {
+ static const EnumPropertyItem overlay_mode_items[] = {
{MASK_OVERLAY_ALPHACHANNEL, "ALPHACHANNEL", ICON_NONE, "Alpha Channel", "Show alpha channel of the mask"},
{MASK_OVERLAY_COMBINED, "COMBINED", ICON_NONE, "Combined", "Combine space background image with the mask"},
{0, NULL, 0, NULL, NULL}
@@ -1962,7 +1976,7 @@ static void rna_def_space_image_uv(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem sticky_mode_items[] = {
+ static const EnumPropertyItem sticky_mode_items[] = {
{SI_STICKY_DISABLE, "DISABLED", ICON_STICKY_UVS_DISABLE, "Disabled", "Sticky vertex selection disabled"},
{SI_STICKY_LOC, "SHARED_LOCATION", ICON_STICKY_UVS_LOC, "Shared Location",
"Select UVs that are at the same location and share a mesh vertex"},
@@ -1971,13 +1985,13 @@ static void rna_def_space_image_uv(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem dt_uvstretch_items[] = {
+ static const EnumPropertyItem dt_uvstretch_items[] = {
{SI_UVDT_STRETCH_ANGLE, "ANGLE", 0, "Angle", "Angular distortion between UV and 3D angles"},
{SI_UVDT_STRETCH_AREA, "AREA", 0, "Area", "Area distortion between UV and 3D faces"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem other_uv_filter_items[] = {
+ static const EnumPropertyItem other_uv_filter_items[] = {
{SI_FILTER_ALL, "ALL", 0, "All", "No filter, show all islands from other objects"},
{SI_FILTER_SAME_IMAGE, "SAME_IMAGE", ICON_IMAGE_DATA, "Same Image",
"Only show others' UV islands whose active image matches image of the active face"},
@@ -2085,7 +2099,7 @@ static void rna_def_space_outliner(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem display_mode_items[] = {
+ static const EnumPropertyItem display_mode_items[] = {
{SO_ALL_SCENES, "ALL_SCENES", 0, "All Scenes", "Display data-blocks in all scenes"},
{SO_CUR_SCENE, "CURRENT_SCENE", 0, "Current Scene", "Display data-blocks in current scene"},
{SO_VISIBLE, "VISIBLE_LAYERS", 0, "Visible Layers", "Display data-blocks in visible layers"},
@@ -2102,28 +2116,28 @@ static void rna_def_space_outliner(BlenderRNA *brna)
"Display data-blocks which are unused and/or will be lost when the file is reloaded"},
{0, NULL, 0, NULL, NULL}
};
-
+
srna = RNA_def_struct(brna, "SpaceOutliner", "Space");
RNA_def_struct_sdna(srna, "SpaceOops");
RNA_def_struct_ui_text(srna, "Space Outliner", "Outliner space data");
-
+
prop = RNA_def_property(srna, "display_mode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "outlinevis");
RNA_def_property_enum_items(prop, display_mode_items);
RNA_def_property_ui_text(prop, "Display Mode", "Type of information to display");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_OUTLINER, NULL);
-
+
prop = RNA_def_property(srna, "filter_text", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "search_string");
RNA_def_property_ui_text(prop, "Display Filter", "Live search filtering string");
RNA_def_property_flag(prop, PROP_TEXTEDIT_UPDATE);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_OUTLINER, NULL);
-
+
prop = RNA_def_property(srna, "use_filter_case_sensitive", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "search_flags", SO_FIND_CASE_SENSITIVE);
RNA_def_property_ui_text(prop, "Case Sensitive Matches Only", "Only use case sensitive matches of search string");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_OUTLINER, NULL);
-
+
prop = RNA_def_property(srna, "use_filter_complete", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "search_flags", SO_FIND_COMPLETE);
RNA_def_property_ui_text(prop, "Complete Matches Only", "Only use complete matches of search string");
@@ -2146,7 +2160,7 @@ static void rna_def_background_image(BlenderRNA *brna)
PropertyRNA *prop;
/* note: combinations work but don't flip so arnt that useful */
- static EnumPropertyItem bgpic_axis_items[] = {
+ static const EnumPropertyItem bgpic_axis_items[] = {
{0, "", 0, N_("X Axis"), ""},
{(1 << RV3D_VIEW_LEFT), "LEFT", 0, "Left", "Show background image while looking to the left"},
{(1 << RV3D_VIEW_RIGHT), "RIGHT", 0, "Right", "Show background image while looking to the right"},
@@ -2165,7 +2179,7 @@ static void rna_def_background_image(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem bgpic_source_items[] = {
+ static const EnumPropertyItem bgpic_source_items[] = {
{V3D_BGPIC_IMAGE, "IMAGE", 0, "Image", ""},
{V3D_BGPIC_MOVIE, "MOVIE_CLIP", 0, "Movie Clip", ""},
{0, NULL, 0, NULL, NULL}
@@ -2219,17 +2233,17 @@ static void rna_def_background_image(BlenderRNA *brna)
RNA_def_property_pointer_sdna(prop, NULL, "cuser");
RNA_def_property_ui_text(prop, "Clip User", "Parameters defining which frame of the movie clip is displayed");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "offset_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "xof");
RNA_def_property_ui_text(prop, "X Offset", "Offset image horizontally from the world origin");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "offset_y", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "yof");
RNA_def_property_ui_text(prop, "Y Offset", "Offset image vertically from the world origin");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "size", PROP_FLOAT, PROP_DISTANCE);
RNA_def_property_float_sdna(prop, NULL, "size");
RNA_def_property_float_funcs(prop, "rna_BackgroundImage_size_get", "rna_BackgroundImage_size_set", NULL);
@@ -2333,7 +2347,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem manipulators_items[] = {
+ static const EnumPropertyItem manipulators_items[] = {
{V3D_MANIP_TRANSLATE, "TRANSLATE", ICON_MAN_TRANS, "Translate",
"Use the manipulator for movement transformations"},
{V3D_MANIP_ROTATE, "ROTATE", ICON_MAN_ROT, "Rotate",
@@ -2343,14 +2357,14 @@ static void rna_def_space_view3d(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem rv3d_persp_items[] = {
+ static const EnumPropertyItem rv3d_persp_items[] = {
{RV3D_PERSP, "PERSP", 0, "Perspective", ""},
{RV3D_ORTHO, "ORTHO", 0, "Orthographic", ""},
{RV3D_CAMOB, "CAMERA", 0, "Camera", ""},
{0, NULL, 0, NULL, NULL}
};
-
- static EnumPropertyItem bundle_drawtype_items[] = {
+
+ static const EnumPropertyItem bundle_drawtype_items[] = {
{OB_PLAINAXES, "PLAIN_AXES", 0, "Plain Axes", ""},
{OB_ARROWS, "ARROWS", 0, "Arrows", ""},
{OB_SINGLE_ARROW, "SINGLE_ARROW", 0, "Single Arrow", ""},
@@ -2360,8 +2374,8 @@ static void rna_def_space_view3d(BlenderRNA *brna)
{OB_EMPTY_CONE, "CONE", 0, "Cone", ""},
{0, NULL, 0, NULL, NULL}
};
-
- static EnumPropertyItem view3d_matcap_items[] = {
+
+ static const EnumPropertyItem view3d_matcap_items[] = {
{ICON_MATCAP_01, "01", ICON_MATCAP_01, "", ""},
{ICON_MATCAP_02, "02", ICON_MATCAP_02, "", ""},
{ICON_MATCAP_03, "03", ICON_MATCAP_03, "", ""},
@@ -2388,11 +2402,11 @@ static void rna_def_space_view3d(BlenderRNA *brna)
{ICON_MATCAP_24, "24", ICON_MATCAP_24, "", ""},
{0, NULL, 0, NULL, NULL}
};
-
+
srna = RNA_def_struct(brna, "SpaceView3D", "Space");
RNA_def_struct_sdna(srna, "View3D");
RNA_def_struct_ui_text(srna, "3D View Space", "3D View space data");
-
+
prop = RNA_def_property(srna, "camera", PROP_POINTER, PROP_NONE);
RNA_def_property_flag(prop, PROP_EDITABLE);
RNA_def_property_pointer_sdna(prop, NULL, "camera");
@@ -2437,7 +2451,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_pointer_sdna(prop, NULL, "ob_centre");
RNA_def_property_ui_text(prop, "Lock to Object", "3D View center is locked to this object's position");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "lock_bone", PROP_STRING, PROP_NONE);
RNA_def_property_string_sdna(prop, NULL, "ob_centre_bone");
RNA_def_property_ui_text(prop, "Lock to Bone", "3D View center is locked to this bone's position");
@@ -2460,7 +2474,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_pointer_sdna(prop, NULL, "localvd");
RNA_def_property_ui_text(prop, "Local View",
"Display an isolated sub-set of objects, apart from the scene visibility");
-
+
prop = RNA_def_property(srna, "cursor_location", PROP_FLOAT, PROP_XYZ_LENGTH);
RNA_def_property_array(prop, 3);
RNA_def_property_float_funcs(prop, "rna_View3D_CursorLocation_get", "rna_View3D_CursorLocation_set", NULL);
@@ -2468,13 +2482,13 @@ static void rna_def_space_view3d(BlenderRNA *brna)
"3D cursor location for this view (dependent on local view setting)");
RNA_def_property_ui_range(prop, -10000.0, 10000.0, 1, RNA_TRANSLATION_PREC_DEFAULT);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "lens", PROP_FLOAT, PROP_UNIT_CAMERA);
RNA_def_property_float_sdna(prop, NULL, "lens");
RNA_def_property_ui_text(prop, "Lens", "Viewport lens angle");
RNA_def_property_range(prop, 1.0f, 250.0f);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "clip_start", PROP_FLOAT, PROP_DISTANCE);
RNA_def_property_float_sdna(prop, NULL, "near");
RNA_def_property_range(prop, 1e-6f, FLT_MAX);
@@ -2505,7 +2519,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_range(prop, 0, 1024);
RNA_def_property_int_default(prop, 16);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "grid_subdivisions", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "gridsubdiv");
RNA_def_property_ui_text(prop, "Grid Subdivisions", "Number of subdivisions between grid lines");
@@ -2522,28 +2536,28 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "gridflag", V3D_SHOW_FLOOR);
RNA_def_property_ui_text(prop, "Display Grid Floor", "Show the ground plane grid in perspective view");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_axis_x", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "gridflag", V3D_SHOW_X);
RNA_def_property_ui_text(prop, "Display X Axis", "Show the X axis line in perspective view");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_axis_y", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "gridflag", V3D_SHOW_Y);
RNA_def_property_ui_text(prop, "Display Y Axis", "Show the Y axis line in perspective view");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_axis_z", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "gridflag", V3D_SHOW_Z);
RNA_def_property_ui_text(prop, "Display Z Axis", "Show the Z axis line in perspective view");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_outline_selected", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", V3D_SELECT_OUTLINE);
RNA_def_property_ui_text(prop, "Outline Selected",
"Show an outline highlight around selected objects in non-wireframe views");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_all_objects_origin", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", V3D_DRAW_CENTERS);
RNA_def_property_ui_text(prop, "All Object Origins",
@@ -2555,7 +2569,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Relationship Lines",
"Show dashed lines indicating parent or constraint relationships");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_grease_pencil", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_SHOW_GPENCIL);
RNA_def_property_ui_text(prop, "Show Grease Pencil",
@@ -2591,7 +2605,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_RENDER_OVERRIDE);
RNA_def_property_ui_text(prop, "Only Render", "Display only objects which will be rendered");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "show_world", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag3", V3D_SHOW_WORLD);
RNA_def_property_ui_text(prop, "World Background", "Display world colors in the background");
@@ -2621,7 +2635,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_enum_items(prop, pivot_items_full);
RNA_def_property_ui_text(prop, "Pivot Point", "Pivot center for rotation/scaling");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_SpaceView3D_pivot_update");
-
+
prop = RNA_def_property(srna, "use_pivot_point_align", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", V3D_ALIGN);
RNA_def_property_ui_text(prop, "Align", "Manipulate center points (object, pose and weight paint mode only)");
@@ -2640,7 +2654,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_flag(prop, PROP_ENUM_FLAG);
RNA_def_property_ui_text(prop, "Transform Manipulators", "Transformation manipulators");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
prop = RNA_def_property(srna, "transform_orientation", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "twmode");
RNA_def_property_enum_items(prop, transform_orientation_items);
@@ -2678,7 +2692,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_array(prop, 8);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_ui_text(prop, "Local View Layers", "Local view layers visible in this 3D View");
-
+
prop = RNA_def_property(srna, "layers_used", PROP_BOOLEAN, PROP_LAYER_MEMBER);
RNA_def_property_boolean_sdna(prop, NULL, "lay_used", 1);
RNA_def_property_array(prop, 20);
@@ -2730,7 +2744,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag2", V3D_SOLID_MATCAP);
RNA_def_property_ui_text(prop, "Matcap", "Active Objects draw images mapped on normals, enhancing Solid Draw Mode");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_SpaceView3D_matcap_enable");
-
+
prop = RNA_def_property(srna, "matcap_icon", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "matcap_icon");
RNA_def_property_enum_items(prop, view3d_matcap_items);
@@ -2793,17 +2807,17 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "viewlock", RV3D_LOCKED);
RNA_def_property_ui_text(prop, "Lock", "Lock view rotation in side views");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_RegionView3D_quadview_update");
-
+
prop = RNA_def_property(srna, "show_sync_view", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "viewlock", RV3D_BOXVIEW);
RNA_def_property_ui_text(prop, "Box", "Sync view position between side views");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_RegionView3D_quadview_update");
-
+
prop = RNA_def_property(srna, "use_box_clip", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "viewlock", RV3D_BOXCLIP);
RNA_def_property_ui_text(prop, "Clip", "Clip objects based on what's visible in other side views");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, "rna_RegionView3D_quadview_clip_update");
-
+
prop = RNA_def_property(srna, "perspective_matrix", PROP_FLOAT, PROP_MATRIX);
RNA_def_property_float_sdna(prop, NULL, "persmat");
RNA_def_property_clear_flag(prop, PROP_EDITABLE); /* XXX: for now, it's too risky for users to do this */
@@ -2816,7 +2830,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_multi_array(prop, 2, rna_matrix_dimsize_4x4);
RNA_def_property_ui_text(prop, "Window Matrix", "Current window matrix");
-
+
prop = RNA_def_property(srna, "view_matrix", PROP_FLOAT, PROP_MATRIX);
RNA_def_property_float_sdna(prop, NULL, "viewmat");
RNA_def_property_multi_array(prop, 2, rna_matrix_dimsize_4x4);
@@ -2834,7 +2848,17 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "is_persp", 1);
RNA_def_property_ui_text(prop, "Is Perspective", "");
RNA_def_property_flag(prop, PROP_EDITABLE);
-
+
+ /* This isn't directly accessible from the UI, only an operator. */
+ prop = RNA_def_property(srna, "use_clip_planes", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "rflag", RV3D_CLIPPING);
+ RNA_def_property_ui_text(prop, "Use Clip Planes", "");
+
+ prop = RNA_def_property(srna, "clip_planes", PROP_FLOAT, PROP_NONE);
+ RNA_def_property_float_sdna(prop, NULL, "clip");
+ RNA_def_property_multi_array(prop, 2, (int[]){6, 4});
+ RNA_def_property_ui_text(prop, "Clip Planes", "");
+
prop = RNA_def_property(srna, "view_location", PROP_FLOAT, PROP_TRANSLATION);
#if 0
RNA_def_property_float_sdna(prop, NULL, "ofs"); /* cant use because its negated */
@@ -2846,7 +2870,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "View Location", "View pivot location");
RNA_def_property_ui_range(prop, -10000.0, 10000.0, 10, RNA_TRANSLATION_PREC_DEFAULT);
RNA_def_property_update(prop, NC_WINDOW, NULL);
-
+
prop = RNA_def_property(srna, "view_rotation", PROP_FLOAT, PROP_QUATERNION); /* cant use because its inverted */
#if 0
RNA_def_property_float_sdna(prop, NULL, "viewquat");
@@ -2857,7 +2881,7 @@ static void rna_def_space_view3d(BlenderRNA *brna)
#endif
RNA_def_property_ui_text(prop, "View Rotation", "Rotation in quaternions (keep normalized)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_VIEW3D, NULL);
-
+
/* not sure we need rna access to these but adding anyway */
prop = RNA_def_property(srna, "view_distance", PROP_FLOAT, PROP_UNSIGNED);
RNA_def_property_float_sdna(prop, NULL, "dist");
@@ -2884,7 +2908,7 @@ static void rna_def_space_buttons(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem align_items[] = {
+ static const EnumPropertyItem align_items[] = {
{BUT_HORIZONTAL, "HORIZONTAL", 0, "Horizontal", ""},
{BUT_VERTICAL, "VERTICAL", 0, "Vertical", ""},
{0, NULL, 0, NULL, NULL}
@@ -2893,14 +2917,14 @@ static void rna_def_space_buttons(BlenderRNA *brna)
srna = RNA_def_struct(brna, "SpaceProperties", "Space");
RNA_def_struct_sdna(srna, "SpaceButs");
RNA_def_struct_ui_text(srna, "Properties Space", "Properties space data");
-
+
prop = RNA_def_property(srna, "context", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "mainb");
RNA_def_property_enum_items(prop, buttons_context_items);
RNA_def_property_enum_funcs(prop, NULL, "rna_SpaceProperties_context_set", "rna_SpaceProperties_context_itemf");
RNA_def_property_ui_text(prop, "Context", "Type of active data to display and edit");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_PROPERTIES, "rna_SpaceProperties_context_update");
-
+
prop = RNA_def_property(srna, "align", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "align");
RNA_def_property_enum_items(prop, align_items);
@@ -2937,7 +2961,7 @@ static void rna_def_space_buttons(BlenderRNA *brna)
static void rna_def_space_image(BlenderRNA *brna)
{
- static EnumPropertyItem image_space_mode_items[] = {
+ static const EnumPropertyItem image_space_mode_items[] = {
{SI_MODE_VIEW, "VIEW", ICON_FILE_IMAGE, "View", "View the image and UV edit in mesh editmode"},
{SI_MODE_PAINT, "PAINT", ICON_TPAINT_HLT, "Paint", "2D image painting mode"},
{SI_MODE_MASK, "MASK", ICON_MOD_MASK, "Mask", "Mask editing"},
@@ -2988,7 +3012,7 @@ static void rna_def_space_image(BlenderRNA *brna)
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_float_funcs(prop, "rna_SpaceImageEditor_zoom_get", NULL, NULL);
RNA_def_property_ui_text(prop, "Zoom", "Zoom factor");
-
+
/* image draw */
prop = RNA_def_property(srna, "show_repeat", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SI_DRAW_TILE);
@@ -3020,7 +3044,7 @@ static void rna_def_space_image(BlenderRNA *brna)
RNA_def_property_struct_type(prop, "SpaceUVEditor");
RNA_def_property_pointer_funcs(prop, "rna_SpaceImageEditor_uvedit_get", NULL, NULL, NULL);
RNA_def_property_ui_text(prop, "UV Editor", "UV editor settings");
-
+
/* mode */
prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "mode");
@@ -3050,7 +3074,7 @@ static void rna_def_space_image(BlenderRNA *brna)
RNA_def_property_flag(prop, PROP_EDITABLE | PROP_ID_REFCOUNT);
RNA_def_property_ui_text(prop, "Grease Pencil", "Grease pencil data for this space");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_IMAGE, NULL);
-
+
/* update */
prop = RNA_def_property(srna, "use_realtime_update", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "lock", 0);
@@ -3089,15 +3113,15 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
- static EnumPropertyItem view_type_items[] = {
+
+ static const EnumPropertyItem view_type_items[] = {
{SEQ_VIEW_SEQUENCE, "SEQUENCER", ICON_SEQ_SEQUENCER, "Sequencer", ""},
{SEQ_VIEW_PREVIEW, "PREVIEW", ICON_SEQ_PREVIEW, "Image Preview", ""},
{SEQ_VIEW_SEQUENCE_PREVIEW, "SEQUENCER_PREVIEW", ICON_SEQ_SPLITVIEW, "Sequencer and Image Preview", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem display_mode_items[] = {
+ static const EnumPropertyItem display_mode_items[] = {
{SEQ_DRAW_IMG_IMBUF, "IMAGE", ICON_SEQ_PREVIEW, "Image Preview", ""},
{SEQ_DRAW_IMG_WAVEFORM, "WAVEFORM", ICON_SEQ_LUMA_WAVEFORM, "Luma Waveform", ""},
{SEQ_DRAW_IMG_VECTORSCOPE, "VECTOR_SCOPE", ICON_SEQ_CHROMA_SCOPE, "Chroma Vectorscope", ""},
@@ -3105,7 +3129,7 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem proxy_render_size_items[] = {
+ static const EnumPropertyItem proxy_render_size_items[] = {
{SEQ_PROXY_RENDER_SIZE_NONE, "NONE", 0, "No display", ""},
{SEQ_PROXY_RENDER_SIZE_SCENE, "SCENE", 0, "Scene render size", ""},
{SEQ_PROXY_RENDER_SIZE_25, "PROXY_25", 0, "Proxy size 25%", ""},
@@ -3116,21 +3140,21 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem overlay_type_items[] = {
+ static const EnumPropertyItem overlay_type_items[] = {
{SEQ_DRAW_OVERLAY_RECT, "RECTANGLE", 0, "Rectangle", "Show rectangle area overlay"},
{SEQ_DRAW_OVERLAY_REFERENCE, "REFERENCE", 0, "Reference", "Show reference frame only"},
{SEQ_DRAW_OVERLAY_CURRENT, "CURRENT", 0, "Current", "Show current frame only"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem preview_channels_items[] = {
+ static const EnumPropertyItem preview_channels_items[] = {
{SEQ_USE_ALPHA, "COLOR_ALPHA", ICON_IMAGE_RGB_ALPHA, "Color and Alpha",
"Draw image with RGB colors and alpha transparency"},
{0, "COLOR", ICON_IMAGE_RGB, "Color", "Draw image with RGB colors"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem waveform_type_draw_items[] = {
+ static const EnumPropertyItem waveform_type_draw_items[] = {
{SEQ_NO_WAVEFORMS, "NO_WAVEFORMS", 0, "Waveforms Off",
"No waveforms drawn for any sound strips"},
{SEQ_ALL_WAVEFORMS, "ALL_WAVEFORMS", 0, "Waveforms On",
@@ -3143,7 +3167,7 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
srna = RNA_def_struct(brna, "SpaceSequenceEditor", "Space");
RNA_def_struct_sdna(srna, "SpaceSeq");
RNA_def_struct_ui_text(srna, "Space Sequence Editor", "Sequence editor space data");
-
+
/* view type, fairly important */
prop = RNA_def_property(srna, "view_type", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "view");
@@ -3164,17 +3188,17 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Show Frame Number Indicator",
"Show frame number beside the current frame indicator line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
prop = RNA_def_property(srna, "show_frames", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_DRAWFRAMES);
RNA_def_property_ui_text(prop, "Draw Frames", "Draw frames rather than seconds");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
prop = RNA_def_property(srna, "use_marker_sync", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_MARKER_TRANS);
RNA_def_property_ui_text(prop, "Sync Markers", "Transform markers as well as strips");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
prop = RNA_def_property(srna, "show_separate_color", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_DRAW_COLOR_SEPARATED);
RNA_def_property_ui_text(prop, "Separate Colors", "Separate color channels in preview");
@@ -3199,7 +3223,7 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SEQ_DRAWFRAMES);
RNA_def_property_ui_text(prop, "Show Seconds", "Show timing in seconds not frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
prop = RNA_def_property(srna, "show_grease_pencil", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SEQ_SHOW_GPENCIL);
RNA_def_property_ui_text(prop, "Show Grease Pencil",
@@ -3230,14 +3254,14 @@ static void rna_def_space_sequencer(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Show Overexposed", "Show overexposed areas with zebra stripes");
RNA_def_property_range(prop, 0, 110);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
prop = RNA_def_property(srna, "proxy_render_size", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "render_size");
RNA_def_property_enum_items(prop, proxy_render_size_items);
RNA_def_property_ui_text(prop, "Proxy render size",
"Draw preview using full resolution or different proxy resolutions");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_SEQUENCER, NULL);
-
+
/* grease pencil */
prop = RNA_def_property(srna, "grease_pencil", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "gpd");
@@ -3298,7 +3322,7 @@ static void rna_def_space_text(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Syntax Highlight", "Syntax highlight for scripting");
RNA_def_property_ui_icon(prop, ICON_SYNTAX_OFF, 1);
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TEXT, NULL);
-
+
prop = RNA_def_property(srna, "show_line_highlight", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "line_hlight", 0);
RNA_def_property_ui_text(prop, "Highlight Line", "Highlight the current line");
@@ -3343,12 +3367,12 @@ static void rna_def_space_text(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "overwrite", 1);
RNA_def_property_ui_text(prop, "Overwrite", "Overwrite characters when typing rather than inserting them");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TEXT, NULL);
-
+
prop = RNA_def_property(srna, "use_live_edit", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "live_edit", 1);
RNA_def_property_ui_text(prop, "Live Edit", "Run python while editing");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TEXT, NULL);
-
+
/* find */
prop = RNA_def_property(srna, "use_find_all", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flags", ST_FIND_ALL);
@@ -3382,9 +3406,9 @@ static void rna_def_space_dopesheet(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
/* XXX: action-editor is currently for object-level only actions, so show that using object-icon hint */
- static EnumPropertyItem mode_items[] = {
+ static const EnumPropertyItem mode_items[] = {
{SACTCONT_DOPESHEET, "DOPESHEET", ICON_OOPS, "Dope Sheet", "Edit all keyframes in scene"},
{SACTCONT_ACTION, "ACTION", ICON_OBJECT_DATA, "Action Editor", "Edit keyframes in active object's Object-level action"},
{SACTCONT_SHAPEKEY, "SHAPEKEY", ICON_SHAPEKEY_DATA, "Shape Key Editor", "Edit keyframes in active object's Shape Keys action"},
@@ -3393,8 +3417,8 @@ static void rna_def_space_dopesheet(BlenderRNA *brna)
{SACTCONT_CACHEFILE, "CACHEFILE", ICON_FILE, "Cache File", "Edit timings for Cache File data-blocks"},
{0, NULL, 0, NULL, NULL}
};
-
-
+
+
srna = RNA_def_struct(brna, "SpaceDopeSheetEditor", "Space");
RNA_def_struct_sdna(srna, "SpaceAction");
RNA_def_struct_ui_text(srna, "Space Dope Sheet Editor", "Dope Sheet space data");
@@ -3406,51 +3430,51 @@ static void rna_def_space_dopesheet(BlenderRNA *brna)
"rna_Action_actedit_assign_poll");
RNA_def_property_ui_text(prop, "Action", "Action displayed and edited in this space");
RNA_def_property_update(prop, NC_ANIMATION | ND_KEYFRAME | NA_EDITED, "rna_SpaceDopeSheetEditor_action_update");
-
+
/* mode */
prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "mode");
RNA_def_property_enum_items(prop, mode_items);
RNA_def_property_ui_text(prop, "Mode", "Editing context being displayed");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, "rna_SpaceDopeSheetEditor_mode_update");
-
+
/* display */
prop = RNA_def_property(srna, "show_seconds", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SACTION_DRAWTIME);
RNA_def_property_ui_text(prop, "Show Seconds", "Show timing in seconds not frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
prop = RNA_def_property(srna, "show_frame_indicator", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SACTION_NODRAWCFRANUM);
RNA_def_property_ui_text(prop, "Show Frame Number Indicator",
"Show frame number beside the current frame indicator line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
prop = RNA_def_property(srna, "show_sliders", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SACTION_SLIDERS);
RNA_def_property_ui_text(prop, "Show Sliders", "Show sliders beside F-Curve channels");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
prop = RNA_def_property(srna, "show_pose_markers", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SACTION_POSEMARKERS_SHOW);
RNA_def_property_ui_text(prop, "Show Pose Markers",
"Show markers belonging to the active action instead of Scene markers "
"(Action and Shape Key Editors only)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
prop = RNA_def_property(srna, "show_group_colors", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SACTION_NODRAWGCOLORS);
RNA_def_property_ui_text(prop, "Show Group Colors",
"Draw groups and channels with colors matching their corresponding groups "
"(pose bones only currently)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
/* editing */
prop = RNA_def_property(srna, "use_auto_merge_keyframes", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SACTION_NOTRANSKEYCULL);
RNA_def_property_ui_text(prop, "AutoMerge Keyframes", "Automatically merge nearby keyframes");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_DOPESHEET, NULL);
-
+
prop = RNA_def_property(srna, "use_realtime_update", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SACTION_NOREALTIMEUPDATES);
RNA_def_property_ui_text(prop, "Realtime Updates",
@@ -3479,16 +3503,16 @@ static void rna_def_space_graph(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
- static EnumPropertyItem mode_items[] = {
+
+ static const EnumPropertyItem mode_items[] = {
{SIPO_MODE_ANIMATION, "FCURVES", ICON_IPO, "F-Curve",
"Edit animation/keyframes displayed as 2D curves"},
{SIPO_MODE_DRIVERS, "DRIVERS", ICON_DRIVER, "Drivers", "Edit drivers"},
{0, NULL, 0, NULL, NULL}
};
-
+
/* this is basically the same as the one for the 3D-View, but with some entries omitted */
- static EnumPropertyItem gpivot_items[] = {
+ static const EnumPropertyItem gpivot_items[] = {
{V3D_AROUND_CENTER_BOUNDS, "BOUNDING_BOX_CENTER", ICON_ROTATE, "Bounding Box Center", ""},
{V3D_AROUND_CURSOR, "CURSOR", ICON_CURSOR, "2D Cursor", ""},
{V3D_AROUND_LOCAL_ORIGINS, "INDIVIDUAL_ORIGINS", ICON_ROTATECOLLECTION, "Individual Centers", ""},
@@ -3497,93 +3521,93 @@ static void rna_def_space_graph(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
-
+
srna = RNA_def_struct(brna, "SpaceGraphEditor", "Space");
RNA_def_struct_sdna(srna, "SpaceIpo");
RNA_def_struct_ui_text(srna, "Space Graph Editor", "Graph Editor space data");
-
+
/* mode */
prop = RNA_def_property(srna, "mode", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "mode");
RNA_def_property_enum_items(prop, mode_items);
RNA_def_property_ui_text(prop, "Mode", "Editing context being displayed");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, "rna_SpaceGraphEditor_display_mode_update");
-
+
/* display */
prop = RNA_def_property(srna, "show_seconds", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SIPO_DRAWTIME);
RNA_def_property_ui_text(prop, "Show Seconds", "Show timing in seconds not frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "show_frame_indicator", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NODRAWCFRANUM);
RNA_def_property_ui_text(prop, "Show Frame Number Indicator",
"Show frame number beside the current frame indicator line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "show_sliders", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SIPO_SLIDERS);
RNA_def_property_ui_text(prop, "Show Sliders", "Show sliders beside F-Curve channels");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "show_handles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NOHANDLES);
RNA_def_property_ui_text(prop, "Show Handles", "Show handles of Bezier control points");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "use_only_selected_curves_handles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SIPO_SELCUVERTSONLY);
RNA_def_property_ui_text(prop, "Only Selected Curve Keyframes",
"Only keyframes of selected F-Curves are visible and editable");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "use_only_selected_keyframe_handles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SIPO_SELVHANDLESONLY);
RNA_def_property_ui_text(prop, "Only Selected Keyframes Handles",
"Only show and edit handles of selected keyframes");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "use_beauty_drawing", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_BEAUTYDRAW_OFF);
RNA_def_property_ui_text(prop, "Use High Quality Drawing",
"Draw F-Curves using Anti-Aliasing and other fancy effects "
"(disable for better performance)");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "show_group_colors", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NODRAWGCOLORS);
RNA_def_property_ui_text(prop, "Show Group Colors",
"Draw groups and channels with colors matching their corresponding groups");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
/* editing */
prop = RNA_def_property(srna, "use_auto_merge_keyframes", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NOTRANSKEYCULL);
RNA_def_property_ui_text(prop, "AutoMerge Keyframes", "Automatically merge nearby keyframes");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "use_realtime_update", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NOREALTIMEUPDATES);
RNA_def_property_ui_text(prop, "Realtime Updates",
"When transforming keyframes, changes to the animation data are flushed to other views");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
/* cursor */
prop = RNA_def_property(srna, "show_cursor", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SIPO_NODRAWCURSOR);
RNA_def_property_ui_text(prop, "Show Cursor", "Show 2D cursor");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "cursor_position_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "cursorTime");
RNA_def_property_ui_text(prop, "Cursor X-Value", "Graph Editor 2D-Value cursor - X-Value component");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "cursor_position_y", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "cursorVal");
RNA_def_property_ui_text(prop, "Cursor Y-Value", "Graph Editor 2D-Value cursor - Y-Value component");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_GRAPH, NULL);
-
+
prop = RNA_def_property(srna, "pivot_point", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "around");
RNA_def_property_enum_items(prop, gpivot_items);
@@ -3627,34 +3651,34 @@ static void rna_def_space_nla(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "SpaceNLA", "Space");
RNA_def_struct_sdna(srna, "SpaceNla");
RNA_def_struct_ui_text(srna, "Space Nla Editor", "NLA editor space data");
-
+
/* display */
prop = RNA_def_property(srna, "show_seconds", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", SNLA_DRAWTIME);
RNA_def_property_ui_text(prop, "Show Seconds", "Show timing in seconds not frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NLA, NULL);
-
+
prop = RNA_def_property(srna, "show_frame_indicator", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SNLA_NODRAWCFRANUM);
RNA_def_property_ui_text(prop, "Show Frame Number Indicator",
"Show frame number beside the current frame indicator line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NLA, NULL);
-
+
prop = RNA_def_property(srna, "show_strip_curves", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SNLA_NOSTRIPCURVES);
RNA_def_property_ui_text(prop, "Show Control F-Curves", "Show influence F-Curves on strips");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NLA, NULL);
-
+
prop = RNA_def_property(srna, "show_local_markers", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SNLA_NOLOCALMARKERS);
RNA_def_property_ui_text(prop, "Show Local Markers",
"Show action-local markers on the strips, useful when synchronizing timing across strips");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NLA, NULL);
-
+
/* editing */
prop = RNA_def_property(srna, "use_realtime_update", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", SNLA_NOREALTIMEUPDATES);
@@ -3680,54 +3704,54 @@ static void rna_def_space_time(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "SpaceTimeline", "Space");
RNA_def_struct_sdna(srna, "SpaceTime");
RNA_def_struct_ui_text(srna, "Space Timeline Editor", "Timeline editor space data");
-
+
/* view settings */
prop = RNA_def_property(srna, "show_frame_indicator", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", TIME_CFRA_NUM);
RNA_def_property_ui_text(prop, "Show Frame Number Indicator",
"Show frame number beside the current frame indicator line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "show_seconds", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "flag", TIME_DRAWFRAMES);
RNA_def_property_ui_text(prop, "Show Seconds", "Show timing in seconds not frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
/* displaying cache status */
prop = RNA_def_property(srna, "show_cache", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_DISPLAY);
RNA_def_property_ui_text(prop, "Show Cache", "Show the status of cached frames in the timeline");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_softbody", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_SOFTBODY);
RNA_def_property_ui_text(prop, "Softbody", "Show the active object's softbody point cache");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_particles", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_PARTICLES);
RNA_def_property_ui_text(prop, "Particles", "Show the active object's particle point cache");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_cloth", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_CLOTH);
RNA_def_property_ui_text(prop, "Cloth", "Show the active object's cloth point cache");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_smoke", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_SMOKE);
RNA_def_property_ui_text(prop, "Smoke", "Show the active object's smoke cache");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_dynamicpaint", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_DYNAMICPAINT);
RNA_def_property_ui_text(prop, "Dynamic Paint", "Show the active object's Dynamic Paint cache");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_TIME, NULL);
-
+
prop = RNA_def_property(srna, "cache_rigidbody", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "cache_display", TIME_CACHE_RIGIDBODY);
RNA_def_property_ui_text(prop, "Rigid Body", "Show the active object's Rigid Body cache");
@@ -3736,7 +3760,7 @@ static void rna_def_space_time(BlenderRNA *brna)
static void rna_def_console_line(BlenderRNA *brna)
{
- static EnumPropertyItem console_line_type_items[] = {
+ static const EnumPropertyItem console_line_type_items[] = {
{CONSOLE_LINE_OUTPUT, "OUTPUT", 0, "Output", ""},
{CONSOLE_LINE_INPUT, "INPUT", 0, "Input", ""},
{CONSOLE_LINE_INFO, "INFO", 0, "Info", ""},
@@ -3746,17 +3770,17 @@ static void rna_def_console_line(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "ConsoleLine", NULL);
RNA_def_struct_ui_text(srna, "Console Input", "Input line for the interactive console");
-
+
prop = RNA_def_property(srna, "body", PROP_STRING, PROP_NONE);
RNA_def_property_string_funcs(prop, "rna_ConsoleLine_body_get", "rna_ConsoleLine_body_length",
"rna_ConsoleLine_body_set");
RNA_def_property_ui_text(prop, "Line", "Text in the line");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_CONSOLE, NULL);
RNA_def_property_translation_context(prop, BLT_I18NCONTEXT_ID_TEXT);
-
+
prop = RNA_def_property(srna, "current_character", PROP_INT, PROP_NONE); /* copied from text editor */
RNA_def_property_int_sdna(prop, NULL, "cursor");
RNA_def_property_int_funcs(prop, NULL, NULL, "rna_ConsoleLine_cursor_index_range");
@@ -3767,16 +3791,16 @@ static void rna_def_console_line(BlenderRNA *brna)
RNA_def_property_enum_items(prop, console_line_type_items);
RNA_def_property_ui_text(prop, "Type", "Console line type when used in scrollback");
}
-
+
static void rna_def_space_console(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "SpaceConsole", "Space");
RNA_def_struct_sdna(srna, "SpaceConsole");
RNA_def_struct_ui_text(srna, "Space Console", "Interactive python console");
-
+
/* display */
prop = RNA_def_property(srna, "font_size", PROP_INT, PROP_NONE); /* copied from text editor */
RNA_def_property_int_sdna(prop, NULL, "lheight");
@@ -3788,14 +3812,14 @@ static void rna_def_space_console(BlenderRNA *brna)
prop = RNA_def_property(srna, "select_start", PROP_INT, PROP_UNSIGNED); /* copied from text editor */
RNA_def_property_int_sdna(prop, NULL, "sel_start");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_CONSOLE, NULL);
-
+
prop = RNA_def_property(srna, "select_end", PROP_INT, PROP_UNSIGNED); /* copied from text editor */
RNA_def_property_int_sdna(prop, NULL, "sel_end");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_CONSOLE, NULL);
prop = RNA_def_property(srna, "prompt", PROP_STRING, PROP_NONE);
RNA_def_property_ui_text(prop, "Prompt", "Command line prompt");
-
+
prop = RNA_def_property(srna, "language", PROP_STRING, PROP_NONE);
RNA_def_property_ui_text(prop, "Language", "Command line prompt language");
@@ -3803,7 +3827,7 @@ static void rna_def_space_console(BlenderRNA *brna)
RNA_def_property_collection_sdna(prop, NULL, "history", NULL);
RNA_def_property_struct_type(prop, "ConsoleLine");
RNA_def_property_ui_text(prop, "History", "Command history");
-
+
prop = RNA_def_property(srna, "scrollback", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "scrollback", NULL);
RNA_def_property_struct_type(prop, "ConsoleLine");
@@ -3814,15 +3838,15 @@ static void rna_def_fileselect_params(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
- static EnumPropertyItem file_display_items[] = {
+
+ static const EnumPropertyItem file_display_items[] = {
{FILE_SHORTDISPLAY, "LIST_SHORT", ICON_SHORTDISPLAY, "Short List", "Display files as short list"},
{FILE_LONGDISPLAY, "LIST_LONG", ICON_LONGDISPLAY, "Long List", "Display files as a detailed list"},
{FILE_IMGDISPLAY, "THUMBNAIL", ICON_IMGDISPLAY, "Thumbnails", "Display files as thumbnails"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem display_size_items[] = {
+ static const EnumPropertyItem display_size_items[] = {
{32, "TINY", 0, "Tiny", ""},
{64, "SMALL", 0, "Small", ""},
{128, "NORMAL", 0, "Normal", ""},
@@ -3830,7 +3854,7 @@ static void rna_def_fileselect_params(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem file_filter_idtypes_items[] = {
+ static const EnumPropertyItem file_filter_idtypes_items[] = {
{FILTER_ID_AC, "ACTION", ICON_ANIM_DATA, "Actions", "Show/hide Action data-blocks"},
{FILTER_ID_AR, "ARMATURE", ICON_ARMATURE_DATA, "Armatures", "Show/hide Armature data-blocks"},
{FILTER_ID_BR, "BRUSH", ICON_BRUSH_DATA, "Brushes", "Show/hide Brushes data-blocks"},
@@ -3865,7 +3889,7 @@ static void rna_def_fileselect_params(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem file_filter_idcategories_items[] = {
+ static const EnumPropertyItem file_filter_idcategories_items[] = {
{FILTER_ID_SCE,
"SCENE", ICON_SCENE_DATA, "Scenes", "Show/hide scenes"},
{FILTER_ID_AC,
@@ -4078,7 +4102,7 @@ static void rna_def_space_filebrowser(BlenderRNA *brna)
prop = RNA_def_property(srna, "params", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "params");
RNA_def_property_ui_text(prop, "Filebrowser Parameter", "Parameters and Settings for the Filebrowser");
-
+
prop = RNA_def_property(srna, "active_operator", PROP_POINTER, PROP_NONE);
RNA_def_property_pointer_sdna(prop, NULL, "op");
RNA_def_property_ui_text(prop, "Active Operator", "");
@@ -4159,28 +4183,28 @@ static void rna_def_space_info(BlenderRNA *brna)
srna = RNA_def_struct(brna, "SpaceInfo", "Space");
RNA_def_struct_sdna(srna, "SpaceInfo");
RNA_def_struct_ui_text(srna, "Space Info", "Info space data");
-
+
/* reporting display */
prop = RNA_def_property(srna, "show_report_debug", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "rpt_mask", INFO_RPT_DEBUG);
RNA_def_property_ui_text(prop, "Show Debug", "Display debug reporting info");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
-
+
prop = RNA_def_property(srna, "show_report_info", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "rpt_mask", INFO_RPT_INFO);
RNA_def_property_ui_text(prop, "Show Info", "Display general information");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
-
+
prop = RNA_def_property(srna, "show_report_operator", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "rpt_mask", INFO_RPT_OP);
RNA_def_property_ui_text(prop, "Show Operator", "Display the operator log");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
-
+
prop = RNA_def_property(srna, "show_report_warning", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "rpt_mask", INFO_RPT_WARN);
RNA_def_property_ui_text(prop, "Show Warn", "Display warnings");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
-
+
prop = RNA_def_property(srna, "show_report_error", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "rpt_mask", INFO_RPT_ERR);
RNA_def_property_ui_text(prop, "Show Error", "Display error text");
@@ -4189,14 +4213,14 @@ static void rna_def_space_info(BlenderRNA *brna)
static void rna_def_space_userpref(BlenderRNA *brna)
{
- static EnumPropertyItem filter_type_items[] = {
+ static const EnumPropertyItem filter_type_items[] = {
{0, "NAME", 0, "Name", "Filter based on the operator name"},
{1, "KEY", 0, "Key-Binding", "Filter based on key bindings"},
{0, NULL, 0, NULL, NULL}};
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "SpaceUserPreferences", "Space");
RNA_def_struct_sdna(srna, "SpaceUserPref");
RNA_def_struct_ui_text(srna, "Space User Preferences", "User preferences space data");
@@ -4218,7 +4242,7 @@ static void rna_def_node_tree_path(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
-
+
srna = RNA_def_struct(brna, "NodeTreePath", NULL);
RNA_def_struct_sdna(srna, "bNodeTreePath");
RNA_def_struct_ui_text(srna, "Node Tree Path", "Element of the node space tree path");
@@ -4273,7 +4297,7 @@ static void rna_def_space_node(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem texture_id_type_items[] = {
+ static const EnumPropertyItem texture_id_type_items[] = {
{SNODE_TEX_OBJECT, "OBJECT", ICON_OBJECT_DATA, "Object", "Edit texture nodes from Object"},
{SNODE_TEX_WORLD, "WORLD", ICON_WORLD_DATA, "World", "Edit texture nodes from World"},
{SNODE_TEX_BRUSH, "BRUSH", ICON_BRUSH_DATA, "Brush", "Edit texture nodes from Brush"},
@@ -4283,7 +4307,7 @@ static void rna_def_space_node(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem shader_type_items[] = {
+ static const EnumPropertyItem shader_type_items[] = {
{SNODE_SHADER_OBJECT, "OBJECT", ICON_OBJECT_DATA, "Object", "Edit shader nodes from Object"},
{SNODE_SHADER_WORLD, "WORLD", ICON_WORLD_DATA, "World", "Edit shader nodes from World"},
#ifdef WITH_FREESTYLE
@@ -4292,7 +4316,7 @@ static void rna_def_space_node(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem backdrop_channels_items[] = {
+ static const EnumPropertyItem backdrop_channels_items[] = {
{SNODE_USE_ALPHA, "COLOR_ALPHA", ICON_IMAGE_RGB_ALPHA, "Color and Alpha",
"Draw image with RGB colors and alpha transparency"},
{0, "COLOR", ICON_IMAGE_RGB, "Color", "Draw image with RGB colors"},
@@ -4303,13 +4327,13 @@ static void rna_def_space_node(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem insert_ofs_dir_items[] = {
+ static const EnumPropertyItem insert_ofs_dir_items[] = {
{SNODE_INSERTOFS_DIR_RIGHT, "RIGHT", 0, "Right"},
{SNODE_INSERTOFS_DIR_LEFT, "LEFT", 0, "Left"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem dummy_items[] = {
+ static const EnumPropertyItem dummy_items[] = {
{0, "DUMMY", 0, "", ""},
{0, NULL, 0, NULL, NULL}};
@@ -4385,7 +4409,7 @@ static void rna_def_space_node(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "flag", SNODE_AUTO_RENDER);
RNA_def_property_ui_text(prop, "Auto Render", "Re-render and composite changed layers on 3D edits");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NODE_VIEW, NULL);
-
+
prop = RNA_def_property(srna, "backdrop_zoom", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "zoom");
RNA_def_property_float_default(prop, 1.0f);
@@ -4393,7 +4417,7 @@ static void rna_def_space_node(BlenderRNA *brna)
RNA_def_property_ui_range(prop, 0.01, 100, 1, 2);
RNA_def_property_ui_text(prop, "Backdrop Zoom", "Backdrop zoom factor");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NODE_VIEW, NULL);
-
+
prop = RNA_def_property(srna, "backdrop_x", PROP_FLOAT, PROP_NONE);
RNA_def_property_float_sdna(prop, NULL, "xof");
RNA_def_property_ui_text(prop, "Backdrop X", "Backdrop X offset");
@@ -4410,11 +4434,6 @@ static void rna_def_space_node(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Draw Channels", "Channels of the image to draw");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NODE_VIEW, NULL);
- prop = RNA_def_property(srna, "show_highlight", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "flag", SNODE_SHOW_HIGHLIGHT);
- RNA_def_property_ui_text(prop, "Highlight", "Highlight nodes that are being calculated");
- RNA_def_property_update(prop, NC_SPACE | ND_SPACE_NODE_VIEW, NULL);
-
/* the mx/my "cursor" in the node editor is used only by operators to store the mouse position */
prop = RNA_def_property(srna, "cursor_location", PROP_FLOAT, PROP_XYZ);
RNA_def_property_array(prop, 2);
@@ -4453,12 +4472,12 @@ static void rna_def_space_logic(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_SEL);
RNA_def_property_ui_text(prop, "Show Selected Object", "Show sensors of all selected objects");
RNA_def_property_update(prop, NC_LOGIC, NULL);
-
+
prop = RNA_def_property(srna, "show_sensors_active_object", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_ACT);
RNA_def_property_ui_text(prop, "Show Active Object", "Show sensors of active object");
RNA_def_property_update(prop, NC_LOGIC, NULL);
-
+
prop = RNA_def_property(srna, "show_sensors_linked_controller", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_SENS_LINK);
RNA_def_property_ui_text(prop, "Show Linked to Controller", "Show linked objects to the controller");
@@ -4474,7 +4493,7 @@ static void rna_def_space_logic(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_CONT_SEL);
RNA_def_property_ui_text(prop, "Show Selected Object", "Show controllers of all selected objects");
RNA_def_property_update(prop, NC_LOGIC, NULL);
-
+
prop = RNA_def_property(srna, "show_controllers_active_object", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_CONT_ACT);
RNA_def_property_ui_text(prop, "Show Active Object", "Show controllers of active object");
@@ -4490,12 +4509,12 @@ static void rna_def_space_logic(BlenderRNA *brna)
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_SEL);
RNA_def_property_ui_text(prop, "Show Selected Object", "Show actuators of all selected objects");
RNA_def_property_update(prop, NC_LOGIC, NULL);
-
+
prop = RNA_def_property(srna, "show_actuators_active_object", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_ACT);
RNA_def_property_ui_text(prop, "Show Active Object", "Show actuators of active object");
RNA_def_property_update(prop, NC_LOGIC, NULL);
-
+
prop = RNA_def_property(srna, "show_actuators_linked_controller", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "scaflag", BUTS_ACT_LINK);
RNA_def_property_ui_text(prop, "Show Linked to Actuator", "Show linked objects to the actuator");
@@ -4513,20 +4532,20 @@ static void rna_def_space_clip(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem view_items[] = {
+ static const EnumPropertyItem view_items[] = {
{SC_VIEW_CLIP, "CLIP", ICON_SEQUENCE, "Clip", "Show editing clip preview"},
{SC_VIEW_GRAPH, "GRAPH", ICON_IPO, "Graph", "Show graph view for active element"},
{SC_VIEW_DOPESHEET, "DOPESHEET", ICON_ACTION, "Dopesheet", "Dopesheet view for tracking data"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem gpencil_source_items[] = {
+ static const EnumPropertyItem gpencil_source_items[] = {
{SC_GPENCIL_SRC_CLIP, "CLIP", 0, "Clip", "Show grease pencil data-block which belongs to movie clip"},
{SC_GPENCIL_SRC_TRACK, "TRACK", 0, "Track", "Show grease pencil data-block which belongs to active track"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem pivot_items[] = {
+ static const EnumPropertyItem pivot_items[] = {
{V3D_AROUND_CENTER_BOUNDS, "BOUNDING_BOX_CENTER", ICON_ROTATE, "Bounding Box Center",
"Pivot around bounding box center of selected object(s)"},
{V3D_AROUND_CURSOR, "CURSOR", ICON_CURSOR, "2D Cursor", "Pivot around the 2D cursor"},
@@ -4609,7 +4628,7 @@ static void rna_def_space_clip(BlenderRNA *brna)
/* path length */
prop = RNA_def_property(srna, "path_length", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "path_length");
- RNA_def_property_range(prop, 0, 50);
+ RNA_def_property_range(prop, 0, INT_MAX);
RNA_def_property_ui_text(prop, "Path Length", "Length of displaying path, in frames");
RNA_def_property_update(prop, NC_SPACE | ND_SPACE_CLIP, NULL);
diff --git a/source/blender/makesrna/intern/rna_space_api.c b/source/blender/makesrna/intern/rna_space_api.c
index c72d6d9e581..8f771eda99d 100644
--- a/source/blender/makesrna/intern/rna_space_api.c
+++ b/source/blender/makesrna/intern/rna_space_api.c
@@ -47,7 +47,7 @@ static void rna_RegionView3D_update(ID *id, RegionView3D *rv3d)
v3d = (View3D *)sa->spacedata.first;
- ED_view3d_update_viewmat(sc->scene, v3d, ar, NULL, NULL);
+ ED_view3d_update_viewmat(sc->scene, v3d, ar, NULL, NULL, NULL);
}
}
diff --git a/source/blender/makesrna/intern/rna_text_api.c b/source/blender/makesrna/intern/rna_text_api.c
index 0287f74587b..d7a862fecbc 100644
--- a/source/blender/makesrna/intern/rna_text_api.c
+++ b/source/blender/makesrna/intern/rna_text_api.c
@@ -40,13 +40,13 @@
static void rna_Text_clear(Text *text)
{
- BKE_text_clear(text);
+ BKE_text_clear(text, NULL);
WM_main_add_notifier(NC_TEXT | NA_EDITED, text);
}
static void rna_Text_write(Text *text, const char *str)
{
- BKE_text_write(text, str);
+ BKE_text_write(text, NULL, str);
WM_main_add_notifier(NC_TEXT | NA_EDITED, text);
}
diff --git a/source/blender/makesrna/intern/rna_texture.c b/source/blender/makesrna/intern/rna_texture.c
index 1e88585a286..39674724889 100644
--- a/source/blender/makesrna/intern/rna_texture.c
+++ b/source/blender/makesrna/intern/rna_texture.c
@@ -52,7 +52,7 @@
#include "WM_types.h"
#ifndef RNA_RUNTIME
-static EnumPropertyItem texture_filter_items[] = {
+static const EnumPropertyItem texture_filter_items[] = {
{TXF_BOX, "BOX", 0, "Box", ""},
{TXF_EWA, "EWA", 0, "EWA", ""},
{TXF_FELINE, "FELINE", 0, "FELINE", ""},
@@ -61,7 +61,7 @@ static EnumPropertyItem texture_filter_items[] = {
};
#endif
-EnumPropertyItem rna_enum_texture_type_items[] = {
+const EnumPropertyItem rna_enum_texture_type_items[] = {
{0, "NONE", 0, "None", ""},
{TEX_BLEND, "BLEND", ICON_TEXTURE, "Blend", "Procedural - create a ramp texture"},
{TEX_CLOUDS, "CLOUDS", ICON_TEXTURE, "Clouds", "Procedural - create a cloud-like fractal noise texture"},
@@ -85,7 +85,7 @@ EnumPropertyItem rna_enum_texture_type_items[] = {
};
#ifndef RNA_RUNTIME
-static EnumPropertyItem blend_type_items[] = {
+static const EnumPropertyItem blend_type_items[] = {
{MTEX_BLEND, "MIX", 0, "Mix", ""},
{MTEX_ADD, "ADD", 0, "Add", ""},
{MTEX_SUB, "SUBTRACT", 0, "Subtract", ""},
@@ -112,6 +112,7 @@ static EnumPropertyItem blend_type_items[] = {
#include "RNA_access.h"
+#include "BKE_colorband.h"
#include "BKE_context.h"
#include "BKE_depsgraph.h"
#include "BKE_image.h"
@@ -267,6 +268,8 @@ void rna_TextureSlot_update(Main *UNUSED(bmain), Scene *scene, PointerRNA *ptr)
WM_main_add_notifier(NC_OBJECT | ND_PARTICLE | NA_EDITED, NULL);
break;
}
+ default:
+ break;
}
}
@@ -357,8 +360,9 @@ static int rna_TextureSlot_output_node_get(PointerRNA *ptr)
}
-static EnumPropertyItem *rna_TextureSlot_output_node_itemf(bContext *UNUSED(C), PointerRNA *ptr,
- PropertyRNA *UNUSED(prop), bool *r_free)
+static const EnumPropertyItem *rna_TextureSlot_output_node_itemf(
+ bContext *UNUSED(C), PointerRNA *ptr,
+ PropertyRNA *UNUSED(prop), bool *r_free)
{
MTex *mtex = ptr->data;
Tex *tex = mtex->tex;
@@ -401,7 +405,7 @@ static void rna_Texture_use_color_ramp_set(PointerRNA *ptr, int value)
else tex->flag &= ~TEX_COLORBAND;
if ((tex->flag & TEX_COLORBAND) && tex->coba == NULL)
- tex->coba = add_colorband(false);
+ tex->coba = BKE_colorband_add(false);
}
static void rna_Texture_use_nodes_update(bContext *C, PointerRNA *ptr)
@@ -478,7 +482,7 @@ static char *rna_OceanTex_path(PointerRNA *UNUSED(ptr))
static void rna_def_texmapping(BlenderRNA *brna)
{
- static EnumPropertyItem prop_mapping_items[] = {
+ static const EnumPropertyItem prop_mapping_items[] = {
{MTEX_FLAT, "FLAT", 0, "Flat", "Map X and Y coordinates directly"},
{MTEX_CUBE, "CUBE", 0, "Cube", "Map using the normal vector"},
{MTEX_TUBE, "TUBE", 0, "Tube", "Map with Z as central axis"},
@@ -486,7 +490,7 @@ static void rna_def_texmapping(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_vect_type_items[] = {
+ static const EnumPropertyItem prop_vect_type_items[] = {
{TEXMAP_TYPE_TEXTURE, "TEXTURE", 0, "Texture", "Transform a texture by inverse mapping the texture coordinate"},
{TEXMAP_TYPE_POINT, "POINT", 0, "Point", "Transform a point"},
{TEXMAP_TYPE_VECTOR, "VECTOR", 0, "Vector", "Transform a direction vector"},
@@ -494,7 +498,7 @@ static void rna_def_texmapping(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_xyz_mapping_items[] = {
+ static const EnumPropertyItem prop_xyz_mapping_items[] = {
{0, "NONE", 0, "None", ""},
{1, "X", 0, "X", ""},
{2, "Y", 0, "Y", ""},
@@ -631,7 +635,7 @@ static void rna_def_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem output_node_items[] = {
+ static const EnumPropertyItem output_node_items[] = {
{0, "DUMMY", 0, "Dummy", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -768,14 +772,14 @@ static void rna_def_environment_map(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_source_items[] = {
+ static const EnumPropertyItem prop_source_items[] = {
{ENV_STATIC, "STATIC", 0, "Static", "Calculate environment map only once"},
{ENV_ANIM, "ANIMATED", 0, "Animated", "Calculate environment map at each rendering"},
{ENV_LOAD, "IMAGE_FILE", 0, "Image File", "Load a saved environment map image from disk"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_mapping_items[] = {
+ static const EnumPropertyItem prop_mapping_items[] = {
{ENV_CUBE, "CUBE", 0, "Cube", "Use environment map with six cube sides"},
{ENV_PLANE, "PLANE", 0, "Plane", "Only one side is rendered, with Z axis pointing in direction of image"},
{0, NULL, 0, NULL, NULL}
@@ -851,7 +855,7 @@ static void rna_def_environment_map(BlenderRNA *brna)
RNA_api_environment_map(srna);
}
-static EnumPropertyItem prop_noise_basis_items[] = {
+static const EnumPropertyItem prop_noise_basis_items[] = {
{TEX_BLENDER, "BLENDER_ORIGINAL", 0, "Blender Original",
"Noise algorithm - Blender original: Smooth interpolated noise"},
{TEX_STDPERLIN, "ORIGINAL_PERLIN", 0, "Original Perlin",
@@ -874,7 +878,7 @@ static EnumPropertyItem prop_noise_basis_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem prop_noise_type[] = {
+static const EnumPropertyItem prop_noise_type[] = {
{TEX_NOISESOFT, "SOFT_NOISE", 0, "Soft", "Generate soft noise (smooth transitions)"},
{TEX_NOISEPERL, "HARD_NOISE", 0, "Hard", "Generate hard noise (sharp transitions)"},
{0, NULL, 0, NULL, NULL}
@@ -886,7 +890,7 @@ static void rna_def_texture_clouds(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_clouds_stype[] = {
+ static const EnumPropertyItem prop_clouds_stype[] = {
{TEX_DEFAULT, "GRAYSCALE", 0, "Grayscale", ""},
{TEX_COLOR, "COLOR", 0, "Color", ""},
{0, NULL, 0, NULL, NULL}
@@ -940,7 +944,7 @@ static void rna_def_texture_wood(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_wood_stype[] = {
+ static const EnumPropertyItem prop_wood_stype[] = {
{TEX_BAND, "BANDS", 0, "Bands", "Use standard wood texture in bands"},
{TEX_RING, "RINGS", 0, "Rings", "Use wood texture in rings"},
{TEX_BANDNOISE, "BANDNOISE", 0, "Band Noise", "Add noise to standard wood"},
@@ -948,7 +952,7 @@ static void rna_def_texture_wood(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_wood_noisebasis2[] = {
+ static const EnumPropertyItem prop_wood_noisebasis2[] = {
{TEX_SIN, "SIN", 0, "Sine", "Use a sine wave to produce bands"},
{TEX_SAW, "SAW", 0, "Saw", "Use a saw wave to produce bands"},
{TEX_TRI, "TRI", 0, "Tri", "Use a triangle wave to produce bands"},
@@ -1010,14 +1014,14 @@ static void rna_def_texture_marble(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_marble_stype[] = {
+ static const EnumPropertyItem prop_marble_stype[] = {
{TEX_SOFT, "SOFT", 0, "Soft", "Use soft marble"},
{TEX_SHARP, "SHARP", 0, "Sharp", "Use more clearly defined marble"},
{TEX_SHARPER, "SHARPER", 0, "Sharper", "Use very clearly defined marble"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_marble_noisebasis2[] = {
+ static const EnumPropertyItem prop_marble_noisebasis2[] = {
{TEX_SIN, "SIN", 0, "Sin", "Use a sine wave to produce bands"},
{TEX_SAW, "SAW", 0, "Saw", "Use a saw wave to produce bands"},
{TEX_TRI, "TRI", 0, "Tri", "Use a triangle wave to produce bands"},
@@ -1110,7 +1114,7 @@ static void rna_def_texture_blend(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_blend_progression[] = {
+ static const EnumPropertyItem prop_blend_progression[] = {
{TEX_LIN, "LINEAR", 0, "Linear", "Create a linear progression"},
{TEX_QUAD, "QUADRATIC", 0, "Quadratic", "Create a quadratic progression"},
{TEX_EASE, "EASING", 0, "Easing", "Create a progression easing from one step to the next"},
@@ -1151,7 +1155,7 @@ static void rna_def_texture_stucci(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_stucci_stype[] = {
+ static const EnumPropertyItem prop_stucci_stype[] = {
{TEX_PLASTIC, "PLASTIC", 0, "Plastic", "Use standard stucci"},
{TEX_WALLIN, "WALL_IN", 0, "Wall in", "Create Dimples"},
{TEX_WALLOUT, "WALL_OUT", 0, "Wall out", "Create Ridges"},
@@ -1209,7 +1213,7 @@ static void rna_def_texture_image(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_image_extension[] = {
+ static const EnumPropertyItem prop_image_extension[] = {
{TEX_EXTEND, "EXTEND", 0, "Extend", "Extend by repeating edge pixels of the image"},
{TEX_CLIP, "CLIP", 0, "Clip", "Clip to image size and set exterior pixels as transparent"},
{TEX_CLIPCUBE, "CLIP_CUBE", 0, "Clip Cube",
@@ -1400,7 +1404,7 @@ static void rna_def_texture_musgrave(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_musgrave_type[] = {
+ static const EnumPropertyItem prop_musgrave_type[] = {
{TEX_MFRACTAL, "MULTIFRACTAL", 0, "Multifractal", "Use Perlin noise as a basis"},
{TEX_RIDGEDMF, "RIDGED_MULTIFRACTAL", 0, "Ridged Multifractal",
"Use Perlin noise with inflection as a basis"},
@@ -1482,7 +1486,7 @@ static void rna_def_texture_voronoi(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem prop_distance_metric_items[] = {
+ static const EnumPropertyItem prop_distance_metric_items[] = {
{TEX_DISTANCE, "DISTANCE", 0, "Actual Distance", "sqrt(x*x+y*y+z*z)"},
{TEX_DISTANCE_SQUARED, "DISTANCE_SQUARED", 0, "Distance Squared", "(x*x+y*y+z*z)"},
{TEX_MANHATTAN, "MANHATTAN", 0, "Manhattan",
@@ -1499,7 +1503,7 @@ static void rna_def_texture_voronoi(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_coloring_items[] = {
+ static const EnumPropertyItem prop_coloring_items[] = {
/* XXX: OK names / descriptions? */
{TEX_INTENSITY, "INTENSITY", 0, "Intensity", "Only calculate intensity"},
{TEX_COL1, "POSITION", 0, "Position", "Color cells by position"},
@@ -1622,28 +1626,28 @@ static void rna_def_texture_pointdensity(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem point_source_items[] = {
+ static const EnumPropertyItem point_source_items[] = {
{TEX_PD_PSYS, "PARTICLE_SYSTEM", 0, "Particle System", "Generate point density from a particle system"},
{TEX_PD_OBJECT, "OBJECT", 0, "Object Vertices", "Generate point density from an object's vertices"},
/*{TEX_PD_FILE, "FILE", 0, "File", ""}, */
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem particle_cache_items[] = {
+ static const EnumPropertyItem particle_cache_items[] = {
{TEX_PD_OBJECTLOC, "OBJECT_LOCATION", 0, "Emit Object Location", ""},
{TEX_PD_OBJECTSPACE, "OBJECT_SPACE", 0, "Emit Object Space", ""},
{TEX_PD_WORLDSPACE, "WORLD_SPACE", 0, "Global Space", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vertex_cache_items[] = {
+ static const EnumPropertyItem vertex_cache_items[] = {
{TEX_PD_OBJECTLOC, "OBJECT_LOCATION", 0, "Object Location", ""},
{TEX_PD_OBJECTSPACE, "OBJECT_SPACE", 0, "Object Space", ""},
{TEX_PD_WORLDSPACE, "WORLD_SPACE", 0, "Global Space", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem falloff_items[] = {
+ static const EnumPropertyItem falloff_items[] = {
{TEX_PD_FALLOFF_STD, "STANDARD", 0, "Standard", ""},
{TEX_PD_FALLOFF_SMOOTH, "SMOOTH", 0, "Smooth", ""},
{TEX_PD_FALLOFF_SOFT, "SOFT", 0, "Soft", ""},
@@ -1654,7 +1658,7 @@ static void rna_def_texture_pointdensity(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem particle_color_source_items[] = {
+ static const EnumPropertyItem particle_color_source_items[] = {
{TEX_PD_COLOR_CONSTANT, "CONSTANT", 0, "Constant", ""},
{TEX_PD_COLOR_PARTAGE, "PARTICLE_AGE", 0, "Particle Age", "Lifetime mapped as 0.0 - 1.0 intensity"},
{TEX_PD_COLOR_PARTSPEED, "PARTICLE_SPEED", 0, "Particle Speed",
@@ -1663,7 +1667,7 @@ static void rna_def_texture_pointdensity(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem vertex_color_source_items[] = {
+ static const EnumPropertyItem vertex_color_source_items[] = {
{TEX_PD_COLOR_CONSTANT, "CONSTANT", 0, "Constant", ""},
{TEX_PD_COLOR_VERTCOL, "VERTEX_COLOR", 0, "Vertex Color", "Vertex color layer"},
{TEX_PD_COLOR_VERTWEIGHT, "VERTEX_WEIGHT", 0, "Vertex Weight", "Vertex group weight"},
@@ -1671,7 +1675,7 @@ static void rna_def_texture_pointdensity(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem turbulence_influence_items[] = {
+ static const EnumPropertyItem turbulence_influence_items[] = {
{TEX_PD_NOISE_STATIC, "STATIC", 0, "Static",
"Noise patterns will remain unchanged, faster and suitable for stills"},
{TEX_PD_NOISE_VEL, "PARTICLE_VELOCITY", 0, "Particle Velocity",
@@ -1835,7 +1839,7 @@ static void rna_def_texture_voxeldata(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem interpolation_type_items[] = {
+ static const EnumPropertyItem interpolation_type_items[] = {
{TEX_VD_NEARESTNEIGHBOR, "NEREASTNEIGHBOR", 0, "Nearest Neighbor",
"No interpolation, fast but blocky and low quality"},
{TEX_VD_LINEAR, "TRILINEAR", 0, "Linear", "Good smoothness and speed"},
@@ -1846,7 +1850,7 @@ static void rna_def_texture_voxeldata(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem file_format_items[] = {
+ static const EnumPropertyItem file_format_items[] = {
{TEX_VD_BLENDERVOXEL, "BLENDER_VOXEL", 0, "Blender Voxel", "Default binary voxel file format"},
{TEX_VD_RAW_8BIT, "RAW_8BIT", 0, "8 bit RAW", "8 bit grayscale binary data"},
/*{TEX_VD_RAW_16BIT, "RAW_16BIT", 0, "16 bit RAW", ""}, */
@@ -1857,14 +1861,14 @@ static void rna_def_texture_voxeldata(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem voxeldata_extension[] = {
+ static const EnumPropertyItem voxeldata_extension[] = {
{TEX_EXTEND, "EXTEND", 0, "Extend", "Extend by repeating edge pixels of the image"},
{TEX_CLIP, "CLIP", 0, "Clip", "Clip to image size and set exterior pixels as transparent"},
{TEX_REPEAT, "REPEAT", 0, "Repeat", "Cause the image to repeat horizontally and vertically"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem smoked_type_items[] = {
+ static const EnumPropertyItem smoked_type_items[] = {
{TEX_VD_SMOKEDENSITY, "SMOKEDENSITY", 0, "Smoke", "Use smoke density and color as texture data"},
{TEX_VD_SMOKEFLAME, "SMOKEFLAME", 0, "Flame", "Use flame temperature as texture data"},
{TEX_VD_SMOKEHEAT, "SMOKEHEAT", 0, "Heat", "Use smoke heat as texture data. Values from -2.0 to 2.0 are used"},
@@ -1872,7 +1876,7 @@ static void rna_def_texture_voxeldata(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem hair_type_items[] = {
+ static const EnumPropertyItem hair_type_items[] = {
{TEX_VD_HAIRDENSITY, "HAIRDENSITY", 0, "Density", "Use hair density as texture data"},
{TEX_VD_HAIRRESTDENSITY, "HAIRRESTDENSITY", 0, "Rest Density", "Use hair rest density as texture data"},
{TEX_VD_HAIRVELOCITY, "HAIRVELOCITY", 0, "Velocity", "Use hair velocity as texture data"},
@@ -1979,7 +1983,7 @@ static void rna_def_texture_ocean(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem ocean_output_items[] = {
+ static const EnumPropertyItem ocean_output_items[] = {
{TEX_OCN_DISPLACEMENT, "DISPLACEMENT", 0, "Displacement", "Output XYZ displacement in RGB channels"},
/*{TEX_OCN_NORMALS, "NORMALS", 0, "Normals", "Outputs wave normals"}, *//* these are in nor channel now */
{TEX_OCN_FOAM, "FOAM", 0, "Foam", "Output Foam (wave overlap) amount in single channel"},
diff --git a/source/blender/makesrna/intern/rna_tracking.c b/source/blender/makesrna/intern/rna_tracking.c
index 7a01e3a4f6b..f44f7336cdf 100644
--- a/source/blender/makesrna/intern/rna_tracking.c
+++ b/source/blender/makesrna/intern/rna_tracking.c
@@ -48,6 +48,9 @@
#ifdef RNA_RUNTIME
+#include "DNA_anim_types.h"
+
+#include "BKE_animsys.h"
#include "BKE_depsgraph.h"
#include "BKE_node.h"
@@ -55,71 +58,6 @@
#include "WM_api.h"
-static MovieTrackingObject *tracking_object_from_track(MovieClip *clip,
- MovieTrackingTrack *track)
-{
- MovieTracking *tracking = &clip->tracking;
- ListBase *tracksbase = &tracking->tracks;
- /* TODO: it's a bit difficult to find list track came from knowing just
- * movie clip ID and MovieTracking structure, so keep this naive
- * search for a while */
- if (BLI_findindex(tracksbase, track) == -1) {
- MovieTrackingObject *object = tracking->objects.first;
- while (object) {
- if (BLI_findindex(&object->tracks, track) != -1) {
- return object;
- }
- object = object->next;
- }
- }
- return NULL;
-}
-
-static ListBase *tracking_tracksbase_from_track(MovieClip *clip,
- MovieTrackingTrack *track)
-{
- MovieTracking *tracking = &clip->tracking;
- MovieTrackingObject *object = tracking_object_from_track(clip, track);
- if (object != NULL) {
- return &object->tracks;
- }
- return &tracking->tracks;
-}
-
-static MovieTrackingObject *tracking_object_from_plane_track(
- MovieClip *clip,
- MovieTrackingPlaneTrack *plane_track)
-{
- MovieTracking *tracking = &clip->tracking;
- ListBase *plane_tracks_base = &tracking->plane_tracks;
- /* TODO: it's a bit difficult to find list track came from knowing just
- * movie clip ID and MovieTracking structure, so keep this naive
- * search for a while */
- if (BLI_findindex(plane_tracks_base, plane_track) == -1) {
- MovieTrackingObject *object = tracking->objects.first;
- while (object) {
- if (BLI_findindex(&object->plane_tracks, plane_track) != -1) {
- return object;
- }
- object = object->next;
- }
- }
- return NULL;
-}
-
-static ListBase *tracking_tracksbase_from_plane_track(
- MovieClip *clip,
- MovieTrackingPlaneTrack *plane_track)
-{
- MovieTracking *tracking = &clip->tracking;
- MovieTrackingObject *object = tracking_object_from_plane_track(clip,
- plane_track);
- if (object != NULL) {
- return &object->plane_tracks;
- }
- return &tracking->plane_tracks;
-}
-
static char *rna_tracking_path(PointerRNA *UNUSED(ptr))
{
return BLI_sprintfN("tracking");
@@ -149,19 +87,12 @@ static char *rna_trackingTrack_path(PointerRNA *ptr)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTrackingTrack *track = (MovieTrackingTrack *)ptr->data;
- MovieTrackingObject *object = tracking_object_from_track(clip, track);
- char track_name_esc[sizeof(track->name) * 2];
- BLI_strescape(track_name_esc, track->name, sizeof(track_name_esc));
- if (object == NULL) {
- return BLI_sprintfN("tracking.tracks[\"%s\"]", track_name_esc);
- }
- else {
- char object_name_esc[sizeof(object->name) * 2];
- BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
- return BLI_sprintfN("tracking.objects[\"%s\"].tracks[\"%s\"]",
- object_name_esc,
- track_name_esc);
- }
+ /* Escaped object name, escaped track name, rest of the path. */
+ char rna_path[MAX_NAME * 4 + 64];
+ BKE_tracking_get_rna_path_for_track(&clip->tracking,
+ track,
+ rna_path, sizeof(rna_path));
+ return BLI_strdup(rna_path);
}
static void rna_trackingTracks_begin(CollectionPropertyIterator *iter, PointerRNA *ptr)
@@ -255,9 +186,26 @@ static void rna_trackingTrack_name_set(PointerRNA *ptr, const char *value)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTrackingTrack *track = (MovieTrackingTrack *)ptr->data;
- ListBase *tracksbase = tracking_tracksbase_from_track(clip, track);
+ ListBase *tracksbase =
+ BKE_tracking_find_tracks_list_for_track(&clip->tracking, track);
+ /* Store old name, for the animation fix later. */
+ char old_name[sizeof(track->name)];
+ BLI_strncpy(old_name, track->name, sizeof(track->name));
+ /* Update the name, */
BLI_strncpy(track->name, value, sizeof(track->name));
BKE_tracking_track_unique_name(tracksbase, track);
+ /* Fix animation paths. */
+ AnimData *adt = BKE_animdata_from_id(&clip->id);
+ if (adt != NULL) {
+ char rna_path[MAX_NAME * 2 + 64];
+ BKE_tracking_get_rna_path_prefix_for_track(&clip->tracking,
+ track,
+ rna_path, sizeof(rna_path));
+ BKE_animdata_fix_paths_rename(&clip->id, adt, NULL,
+ rna_path,
+ old_name, track->name,
+ 0, 0, 1);
+ }
}
static int rna_trackingTrack_select_get(PointerRNA *ptr)
@@ -326,28 +274,40 @@ static char *rna_trackingPlaneTrack_path(PointerRNA *ptr)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTrackingPlaneTrack *plane_track = (MovieTrackingPlaneTrack *)ptr->data;
- char track_name_esc[sizeof(plane_track->name) * 2];
- MovieTrackingObject *object = tracking_object_from_plane_track(clip, plane_track);
- BLI_strescape(track_name_esc, plane_track->name, sizeof(track_name_esc));
- if (object == NULL) {
- return BLI_sprintfN("tracking.plane_tracks[\"%s\"]", track_name_esc);
- }
- else {
- char object_name_esc[sizeof(object->name) * 2];
- BLI_strescape(object_name_esc, object->name, sizeof(object_name_esc));
- return BLI_sprintfN("tracking.objects[\"%s\"].plane_tracks[\"%s\"]",
- object_name_esc,
- track_name_esc);
- }
+ /* Escaped object name, escaped track name, rest of the path. */
+ char rna_path[MAX_NAME * 4 + 64];
+ BKE_tracking_get_rna_path_for_plane_track(&clip->tracking,
+ plane_track,
+ rna_path, sizeof(rna_path));
+ return BLI_strdup(rna_path);
}
static void rna_trackingPlaneTrack_name_set(PointerRNA *ptr, const char *value)
{
MovieClip *clip = (MovieClip *)ptr->id.data;
MovieTrackingPlaneTrack *plane_track = (MovieTrackingPlaneTrack *)ptr->data;
- ListBase *plane_tracks_base = tracking_tracksbase_from_plane_track(clip, plane_track);
+ ListBase *plane_tracks_base =
+ BKE_tracking_find_tracks_list_for_plane_track(&clip->tracking,
+ plane_track);
+ /* Store old name, for the animation fix later. */
+ char old_name[sizeof(plane_track->name)];
+ BLI_strncpy(old_name, plane_track->name, sizeof(plane_track->name));
+ /* Update the name, */
BLI_strncpy(plane_track->name, value, sizeof(plane_track->name));
BKE_tracking_plane_track_unique_name(plane_tracks_base, plane_track);
+ /* Fix animation paths. */
+ AnimData *adt = BKE_animdata_from_id(&clip->id);
+ if (adt != NULL) {
+ char rna_path[MAX_NAME * 2 + 64];
+ BKE_tracking_get_rna_path_prefix_for_plane_track(&clip->tracking,
+ plane_track,
+ rna_path,
+ sizeof(rna_path));
+ BKE_animdata_fix_paths_rename(&clip->id, adt, NULL,
+ rna_path,
+ old_name, plane_track->name,
+ 0, 0, 1);
+ }
}
static char *rna_trackingCamera_path(PointerRNA *UNUSED(ptr))
@@ -826,7 +786,7 @@ static void rna_trackingCameras_matrix_from_frame(ID *id, MovieTrackingReconstru
#else
-static EnumPropertyItem tracker_motion_model[] = {
+static const EnumPropertyItem tracker_motion_model[] = {
{TRACK_MOTION_MODEL_HOMOGRAPHY, "Perspective", 0, "Perspective",
"Search for markers that are perspectively deformed (homography) between frames"},
{TRACK_MOTION_MODEL_AFFINE, "Affine", 0, "Affine",
@@ -842,7 +802,7 @@ static EnumPropertyItem tracker_motion_model[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem pattern_match_items[] = {
+static const EnumPropertyItem pattern_match_items[] = {
{TRACK_MATCH_KEYFRAME, "KEYFRAME", 0, "Keyframe", "Track pattern from keyframe to next frame"},
{TRACK_MATCH_PREVFRAME, "PREV_FRAME", 0, "Previous frame", "Track pattern from current frame to next frame"},
{0, NULL, 0, NULL, NULL}
@@ -853,7 +813,7 @@ static void rna_def_trackingSettings(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem speed_items[] = {
+ static const EnumPropertyItem speed_items[] = {
{0, "FASTEST", 0, "Fastest", "Track as fast as it's possible"},
{TRACKING_SPEED_DOUBLE, "DOUBLE", 0, "Double", "Track with double speed"},
{TRACKING_SPEED_REALTIME, "REALTIME", 0, "Realtime", "Track with realtime speed"},
@@ -862,14 +822,14 @@ static void rna_def_trackingSettings(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem cleanup_items[] = {
+ static const EnumPropertyItem cleanup_items[] = {
{TRACKING_CLEAN_SELECT, "SELECT", 0, "Select", "Select unclean tracks"},
{TRACKING_CLEAN_DELETE_TRACK, "DELETE_TRACK", 0, "Delete Track", "Delete unclean tracks"},
{TRACKING_CLEAN_DELETE_SEGMENT, "DELETE_SEGMENTS", 0, "Delete Segments", "Delete unclean segments of tracks"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem refine_items[] = {
+ static const EnumPropertyItem refine_items[] = {
{0, "NONE", 0, "Nothing", "Do not refine camera intrinsics"},
{REFINE_FOCAL_LENGTH, "FOCAL_LENGTH", 0, "Focal Length", "Refine focal length"},
{REFINE_FOCAL_LENGTH | REFINE_RADIAL_DISTORTION_K1, "FOCAL_LENGTH_RADIAL_K1", 0, "Focal length, K1",
@@ -1085,14 +1045,14 @@ static void rna_def_trackingCamera(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem distortion_model_items[] = {
+ static const EnumPropertyItem distortion_model_items[] = {
{TRACKING_DISTORTION_MODEL_POLYNOMIAL, "POLYNOMIAL", 0, "Polynomial", "Radial distortion model which fits common cameras"},
{TRACKING_DISTORTION_MODEL_DIVISION, "DIVISION", 0, "Divisions", "Division distortion model which "
"better represents wide-angle cameras"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem camera_units_items[] = {
+ static const EnumPropertyItem camera_units_items[] = {
{CAMERA_UNITS_PX, "PIXELS", 0, "px", "Use pixels for units of focal length"},
{CAMERA_UNITS_MM, "MILLIMETERS", 0, "mm", "Use millimeters for units of focal length"},
{0, NULL, 0, NULL, NULL}
@@ -1650,6 +1610,7 @@ static void rna_def_trackingPlaneTrack(BlenderRNA *brna)
/* auto keyframing */
prop = RNA_def_property(srna, "use_auto_keying", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "flag", PLANE_TRACK_AUTOKEY);
+ RNA_def_property_clear_flag(prop, PROP_ANIMATABLE);
RNA_def_property_ui_text(prop, "Auto Keyframe", "Automatic keyframe insertion when moving plane corners");
RNA_def_property_ui_icon(prop, ICON_REC, 0);
@@ -1673,7 +1634,7 @@ static void rna_def_trackingStabilization(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem filter_items[] = {
+ static const EnumPropertyItem filter_items[] = {
{TRACKING_FILTER_NEAREST, "NEAREST", 0, "Nearest", "No interpolation, use nearest neighbor pixel"},
{TRACKING_FILTER_BILINEAR, "BILINEAR", 0, "Bilinear", "Simple interpolation between adjacent pixels"},
{TRACKING_FILTER_BICUBIC, "BICUBIC", 0, "Bicubic", "High quality pixel interpolation"},
@@ -2124,7 +2085,7 @@ static void rna_def_trackingDopesheet(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem sort_items[] = {
+ static const EnumPropertyItem sort_items[] = {
{TRACKING_DOPE_SORT_NAME, "NAME", 0, "Name", "Sort channels by their names"},
{TRACKING_DOPE_SORT_LONGEST, "LONGEST", 0, "Longest", "Sort channels by longest tracked segment"},
{TRACKING_DOPE_SORT_TOTAL, "TOTAL", 0, "Total", "Sort channels by overall amount of tracked segments"},
diff --git a/source/blender/makesrna/intern/rna_ui.c b/source/blender/makesrna/intern/rna_ui.c
index 7a3c862f04c..f2527a8a5e9 100644
--- a/source/blender/makesrna/intern/rna_ui.c
+++ b/source/blender/makesrna/intern/rna_ui.c
@@ -43,7 +43,7 @@
#include "WM_types.h"
/* see WM_types.h */
-EnumPropertyItem rna_enum_operator_context_items[] = {
+const EnumPropertyItem rna_enum_operator_context_items[] = {
{WM_OP_INVOKE_DEFAULT, "INVOKE_DEFAULT", 0, "Invoke Default", ""},
{WM_OP_INVOKE_REGION_WIN, "INVOKE_REGION_WIN", 0, "Invoke Region Window", ""},
{WM_OP_INVOKE_REGION_CHANNELS, "INVOKE_REGION_CHANNELS", 0, "Invoke Region Channels", ""},
@@ -59,7 +59,7 @@ EnumPropertyItem rna_enum_operator_context_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_uilist_layout_type_items[] = {
+const EnumPropertyItem rna_enum_uilist_layout_type_items[] = {
{UILST_LAYOUT_DEFAULT, "DEFAULT", 0, "Default Layout", "Use the default, multi-rows layout"},
{UILST_LAYOUT_COMPACT, "COMPACT", 0, "Compact Layout", "Use the compact, single-row layout"},
{UILST_LAYOUT_GRID, "GRID", 0, "Grid Layout", "Use the grid-based layout"},
@@ -177,16 +177,17 @@ static void rna_Panel_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &pt->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
BLI_freelinkN(&art->paneltypes, pt);
- RNA_struct_free(&BLENDER_RNA, type);
/* update while blender is running */
WM_main_add_notifier(NC_WINDOW, NULL);
}
-static StructRNA *rna_Panel_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_Panel_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
ARegionType *art;
PanelType *pt, dummypt = {NULL};
@@ -229,6 +230,12 @@ static StructRNA *rna_Panel_register(Main *bmain, ReportList *reports, void *dat
break;
}
}
+ if (!RNA_struct_available_or_report(reports, dummypt.idname)) {
+ return NULL;
+ }
+ if (!RNA_struct_bl_idname_ok_or_report(reports, dummypt.idname, "_PT_")) {
+ return NULL;
+ }
/* create a new panel type */
pt = MEM_callocN(sizeof(PanelType), "python buttons panel");
@@ -455,17 +462,17 @@ static void rna_UIList_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &ult->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
WM_uilisttype_freelink(ult);
- RNA_struct_free(&BLENDER_RNA, type);
-
/* update while blender is running */
WM_main_add_notifier(NC_WINDOW, NULL);
}
-static StructRNA *rna_UIList_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_UIList_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
uiListType *ult, dummyult = {NULL};
uiList dummyuilist = {NULL};
@@ -489,8 +496,15 @@ static StructRNA *rna_UIList_register(Main *bmain, ReportList *reports, void *da
/* check if we have registered this uilist type before, and remove it */
ult = WM_uilisttype_find(dummyult.idname, true);
- if (ult && ult->ext.srna)
+ if (ult && ult->ext.srna) {
rna_UIList_unregister(bmain, ult->ext.srna);
+ }
+ if (!RNA_struct_available_or_report(reports, dummyult.idname)) {
+ return NULL;
+ }
+ if (!RNA_struct_bl_idname_ok_or_report(reports, dummyult.idname, "_UL_")) {
+ return NULL;
+ }
/* create a new menu type */
ult = MEM_callocN(sizeof(uiListType) + over_alloc, "python uilist");
@@ -551,16 +565,17 @@ static void rna_Header_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &ht->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
BLI_freelinkN(&art->headertypes, ht);
- RNA_struct_free(&BLENDER_RNA, type);
/* update while blender is running */
WM_main_add_notifier(NC_WINDOW, NULL);
}
-static StructRNA *rna_Header_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_Header_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
ARegionType *art;
HeaderType *ht, dummyht = {NULL};
@@ -593,6 +608,12 @@ static StructRNA *rna_Header_register(Main *bmain, ReportList *reports, void *da
break;
}
}
+ if (!RNA_struct_available_or_report(reports, dummyht.idname)) {
+ return NULL;
+ }
+ if (!RNA_struct_bl_idname_ok_or_report(reports, dummyht.idname, "_HT_")) {
+ return NULL;
+ }
/* create a new header type */
ht = MEM_callocN(sizeof(HeaderType), "python buttons header");
@@ -673,17 +694,17 @@ static void rna_Menu_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &mt->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
WM_menutype_freelink(mt);
- RNA_struct_free(&BLENDER_RNA, type);
-
/* update while blender is running */
WM_main_add_notifier(NC_WINDOW, NULL);
}
-static StructRNA *rna_Menu_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_Menu_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
MenuType *mt, dummymt = {NULL};
Menu dummymenu = {NULL};
@@ -714,8 +735,15 @@ static StructRNA *rna_Menu_register(Main *bmain, ReportList *reports, void *data
/* check if we have registered this menu type before, and remove it */
mt = WM_menutype_find(dummymt.idname, true);
- if (mt && mt->ext.srna)
+ if (mt && mt->ext.srna) {
rna_Menu_unregister(bmain, mt->ext.srna);
+ }
+ if (!RNA_struct_available_or_report(reports, dummymt.idname)) {
+ return NULL;
+ }
+ if (!RNA_struct_bl_idname_ok_or_report(reports, dummymt.idname, "_MT_")) {
+ return NULL;
+ }
/* create a new menu type */
if (_menu_descr[0]) {
@@ -868,7 +896,7 @@ static void rna_def_ui_layout(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem alignment_items[] = {
+ static const EnumPropertyItem alignment_items[] = {
{UI_LAYOUT_ALIGN_EXPAND, "EXPAND", 0, "Expand", ""},
{UI_LAYOUT_ALIGN_LEFT, "LEFT", 0, "Left", ""},
{UI_LAYOUT_ALIGN_CENTER, "CENTER", 0, "Center", ""},
@@ -922,7 +950,7 @@ static void rna_def_panel(BlenderRNA *brna)
PropertyRNA *parm;
FunctionRNA *func;
- static EnumPropertyItem panel_flag_items[] = {
+ static const EnumPropertyItem panel_flag_items[] = {
{PNL_DEFAULT_CLOSED, "DEFAULT_CLOSED", 0, "Default Closed",
"Defines if the panel has to be open or collapsed at the time of its creation"},
{PNL_NO_HEADER, "HIDE_HEADER", 0, "Hide Header",
@@ -937,6 +965,7 @@ static void rna_def_panel(BlenderRNA *brna)
RNA_def_struct_refine_func(srna, "rna_Panel_refine");
RNA_def_struct_register_funcs(srna, "rna_Panel_register", "rna_Panel_unregister", NULL);
RNA_def_struct_translation_context(srna, BLT_I18NCONTEXT_DEFAULT_BPYRNA);
+ RNA_def_struct_flag(srna, STRUCT_PUBLIC_NAMESPACE_INHERIT);
/* poll */
func = RNA_def_function(srna, "poll", NULL);
@@ -1039,6 +1068,7 @@ static void rna_def_uilist(BlenderRNA *brna)
RNA_def_struct_refine_func(srna, "rna_UIList_refine");
RNA_def_struct_register_funcs(srna, "rna_UIList_register", "rna_UIList_unregister", NULL);
RNA_def_struct_idprops_func(srna, "rna_UIList_idprops");
+ RNA_def_struct_flag(srna, STRUCT_NO_DATABLOCK_IDPROPERTIES | STRUCT_PUBLIC_NAMESPACE_INHERIT);
/* Registration */
prop = RNA_def_property(srna, "bl_idname", PROP_STRING, PROP_NONE);
@@ -1160,6 +1190,7 @@ static void rna_def_header(BlenderRNA *brna)
RNA_def_struct_sdna(srna, "Header");
RNA_def_struct_refine_func(srna, "rna_Header_refine");
RNA_def_struct_register_funcs(srna, "rna_Header_register", "rna_Header_unregister", NULL);
+ RNA_def_struct_flag(srna, STRUCT_PUBLIC_NAMESPACE_INHERIT);
/* draw */
func = RNA_def_function(srna, "draw", NULL);
@@ -1207,6 +1238,7 @@ static void rna_def_menu(BlenderRNA *brna)
RNA_def_struct_refine_func(srna, "rna_Menu_refine");
RNA_def_struct_register_funcs(srna, "rna_Menu_register", "rna_Menu_unregister", NULL);
RNA_def_struct_translation_context(srna, BLT_I18NCONTEXT_DEFAULT_BPYRNA);
+ RNA_def_struct_flag(srna, STRUCT_PUBLIC_NAMESPACE_INHERIT);
/* poll */
func = RNA_def_function(srna, "poll", NULL);
diff --git a/source/blender/makesrna/intern/rna_ui_api.c b/source/blender/makesrna/intern/rna_ui_api.c
index 46775af21db..dd3a2bf6fe2 100644
--- a/source/blender/makesrna/intern/rna_ui_api.c
+++ b/source/blender/makesrna/intern/rna_ui_api.c
@@ -50,7 +50,7 @@
#define DEF_ICON_BLANK_SKIP
#define DEF_ICON(name) {ICON_##name, (#name), 0, (#name), ""},
#define DEF_VICO(name) {VICO_##name, (#name), 0, (#name), ""},
-EnumPropertyItem rna_enum_icon_items[] = {
+const EnumPropertyItem rna_enum_icon_items[] = {
#include "UI_icons.h"
{0, NULL, 0, NULL, NULL}
};
@@ -60,8 +60,8 @@ EnumPropertyItem rna_enum_icon_items[] = {
#ifdef RNA_RUNTIME
-static const char *rna_translate_ui_text(const char *text, const char *text_ctxt, StructRNA *type, PropertyRNA *prop,
- int translate)
+const char *rna_translate_ui_text(
+ const char *text, const char *text_ctxt, StructRNA *type, PropertyRNA *prop, int translate)
{
/* Also return text if UI labels translation is disabled. */
if (!text || !text[0] || !translate || !BLT_translate_iface()) {
@@ -175,11 +175,11 @@ static void rna_uiItemPointerR(uiLayout *layout, struct PointerRNA *ptr, const c
uiItemPointerR(layout, ptr, propname, searchptr, searchpropname, name, icon);
}
-static PointerRNA rna_uiItemO(uiLayout *layout, const char *opname, const char *name, const char *text_ctxt,
- int translate, int icon, int emboss, int icon_value)
+static PointerRNA rna_uiItemO(
+ uiLayout *layout, const char *opname, const char *name, const char *text_ctxt,
+ int translate, int icon, int emboss, int depress, int icon_value)
{
wmOperatorType *ot;
- int flag;
ot = WM_operatortype_find(opname, 0); /* print error next */
if (!ot || !ot->srna) {
@@ -193,13 +193,39 @@ static PointerRNA rna_uiItemO(uiLayout *layout, const char *opname, const char *
if (icon_value && !icon) {
icon = icon_value;
}
+ int flag = (emboss) ? 0 : UI_ITEM_R_NO_BG;
+ flag |= (depress) ? UI_ITEM_O_DEPRESS : 0;
- flag = UI_ITEM_O_RETURN_PROPS;
- flag |= (emboss) ? 0 : UI_ITEM_R_NO_BG;
+ PointerRNA opptr;
+ uiItemFullO_ptr(layout, ot, name, icon, NULL, uiLayoutGetOperatorContext(layout), flag, &opptr);
+ return opptr;
+}
+
+static PointerRNA rna_uiItemOMenuHold(
+ uiLayout *layout, const char *opname, const char *name, const char *text_ctxt,
+ int translate, int icon, int emboss, int depress, int icon_value,
+ const char *menu)
+{
+ wmOperatorType *ot = WM_operatortype_find(opname, 0); /* print error next */
+ if (!ot || !ot->srna) {
+ RNA_warning("%s '%s'", ot ? "unknown operator" : "operator missing srna", opname);
+ return PointerRNA_NULL;
+ }
+
+ /* Get translated name (label). */
+ name = rna_translate_ui_text(name, text_ctxt, ot->srna, NULL, translate);
+ if (icon_value && !icon) {
+ icon = icon_value;
+ }
+ int flag = (emboss) ? 0 : UI_ITEM_R_NO_BG;
+ flag |= (depress) ? UI_ITEM_O_DEPRESS : 0;
- return uiItemFullO_ptr(layout, ot, name, icon, NULL, uiLayoutGetOperatorContext(layout), flag);
+ PointerRNA opptr;
+ uiItemFullOMenuHold_ptr(layout, ot, name, icon, NULL, uiLayoutGetOperatorContext(layout), flag, menu, &opptr);
+ return opptr;
}
+
static void rna_uiItemMenuEnumO(uiLayout *layout, bContext *C, const char *opname, const char *propname, const char *name,
const char *text_ctxt, int translate, int icon)
{
@@ -213,8 +239,7 @@ static void rna_uiItemMenuEnumO(uiLayout *layout, bContext *C, const char *opnam
/* Get translated name (label). */
name = rna_translate_ui_text(name, text_ctxt, ot->srna, NULL, translate);
- /* XXX This will search operator again :( */
- uiItemMenuEnumO(layout, C, opname, propname, name, icon);
+ uiItemMenuEnumO_ptr(layout, C, ot, propname, name, icon);
}
static void rna_uiItemL(uiLayout *layout, const char *name, const char *text_ctxt, int translate,
@@ -285,7 +310,7 @@ static int rna_ui_get_rnaptr_icon(bContext *C, PointerRNA *ptr_icon)
static const char *rna_ui_get_enum_name(bContext *C, PointerRNA *ptr, const char *propname, const char *identifier)
{
PropertyRNA *prop = NULL;
- EnumPropertyItem *items = NULL, *item;
+ const EnumPropertyItem *items = NULL, *item;
bool free;
const char *name = "";
@@ -305,7 +330,7 @@ static const char *rna_ui_get_enum_name(bContext *C, PointerRNA *ptr, const char
}
}
if (free) {
- MEM_freeN(items);
+ MEM_freeN((void *)items);
}
}
@@ -316,7 +341,7 @@ static const char *rna_ui_get_enum_description(bContext *C, PointerRNA *ptr, con
const char *identifier)
{
PropertyRNA *prop = NULL;
- EnumPropertyItem *items = NULL, *item;
+ const EnumPropertyItem *items = NULL, *item;
bool free;
const char *desc = "";
@@ -336,7 +361,7 @@ static const char *rna_ui_get_enum_description(bContext *C, PointerRNA *ptr, con
}
}
if (free) {
- MEM_freeN(items);
+ MEM_freeN((void *)items);
}
}
@@ -346,7 +371,7 @@ static const char *rna_ui_get_enum_description(bContext *C, PointerRNA *ptr, con
static int rna_ui_get_enum_icon(bContext *C, PointerRNA *ptr, const char *propname, const char *identifier)
{
PropertyRNA *prop = NULL;
- EnumPropertyItem *items = NULL, *item;
+ const EnumPropertyItem *items = NULL, *item;
bool free;
int icon = ICON_NONE;
@@ -366,7 +391,7 @@ static int rna_ui_get_enum_icon(bContext *C, PointerRNA *ptr, const char *propna
}
}
if (free) {
- MEM_freeN(items);
+ MEM_freeN((void *)items);
}
}
@@ -421,7 +446,7 @@ void RNA_api_ui_layout(StructRNA *srna)
FunctionRNA *func;
PropertyRNA *parm;
- static EnumPropertyItem curve_type_items[] = {
+ static const EnumPropertyItem curve_type_items[] = {
{0, "NONE", 0, "None", ""},
{'v', "VECTOR", 0, "Vector", ""},
{'c', "COLOR", 0, "Color", ""},
@@ -429,6 +454,12 @@ void RNA_api_ui_layout(StructRNA *srna)
{0, NULL, 0, NULL, NULL}
};
+ static const EnumPropertyItem id_template_filter_items[] = {
+ {UI_TEMPLATE_ID_FILTER_ALL, "ALL", 0, "All", ""},
+ {UI_TEMPLATE_ID_FILTER_AVAILABLE, "AVAILABLE", 0, "Available", ""},
+ {0, NULL, 0, NULL, NULL}
+ };
+
static float node_socket_color_default[] = { 0.0f, 0.0f, 0.0f, 1.0f };
/* simple layout specifiers */
@@ -524,7 +555,7 @@ void RNA_api_ui_layout(StructRNA *srna)
RNA_def_boolean(func, "icon_only", false, "", "Draw only icons in buttons, no text");
RNA_def_boolean(func, "event", false, "", "Use button to input key events");
RNA_def_boolean(func, "full_event", false, "", "Use button to input full events including modifiers");
- RNA_def_boolean(func, "emboss", true, "", "Draw the button itself, just the icon/text");
+ RNA_def_boolean(func, "emboss", true, "", "Draw the button itself, not just the icon/text");
RNA_def_int(func, "index", -1, -2, INT_MAX, "",
"The index of this button, when set a single member of an array can be accessed, "
"when set to -1 all array members are used", -2, INT_MAX); /* RNA_NO_INDEX == -1 */
@@ -552,16 +583,24 @@ void RNA_api_ui_layout(StructRNA *srna)
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
api_ui_item_common(func);
- func = RNA_def_function(srna, "operator", "rna_uiItemO");
- api_ui_item_op_common(func);
- RNA_def_boolean(func, "emboss", true, "", "Draw the button itself, just the icon/text");
- parm = RNA_def_property(func, "icon_value", PROP_INT, PROP_UNSIGNED);
- RNA_def_property_ui_text(parm, "Icon Value", "Override automatic icon of the item");
- parm = RNA_def_pointer(func, "properties", "OperatorProperties", "",
- "Operator properties to fill in, return when 'properties' is set to true");
- RNA_def_parameter_flags(parm, 0, PARM_REQUIRED | PARM_RNAPTR);
- RNA_def_function_return(func, parm);
- RNA_def_function_ui_description(func, "Item. Places a button into the layout to call an Operator");
+ for (int is_menu_hold = 0; is_menu_hold < 2; is_menu_hold++) {
+ func = (is_menu_hold) ?
+ RNA_def_function(srna, "operator_menu_hold", "rna_uiItemOMenuHold") :
+ RNA_def_function(srna, "operator", "rna_uiItemO");
+ api_ui_item_op_common(func);
+ RNA_def_boolean(func, "emboss", true, "", "Draw the button itself, not just the icon/text");
+ RNA_def_boolean(func, "depress", false, "", "Draw pressed in");
+ parm = RNA_def_property(func, "icon_value", PROP_INT, PROP_UNSIGNED);
+ RNA_def_property_ui_text(parm, "Icon Value", "Override automatic icon of the item");
+ if (is_menu_hold) {
+ parm = RNA_def_string(func, "menu", NULL, 0, "", "Identifier of the menu");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ }
+ parm = RNA_def_pointer(func, "properties", "OperatorProperties", "", "Operator properties to fill in");
+ RNA_def_parameter_flags(parm, 0, PARM_REQUIRED | PARM_RNAPTR);
+ RNA_def_function_return(func, parm);
+ RNA_def_function_ui_description(func, "Item. Places a button into the layout to call an Operator");
+ }
func = RNA_def_function(srna, "operator_enum", "uiItemsEnumO");
parm = RNA_def_string(func, "operator", NULL, 0, "", "Identifier of the operator");
@@ -652,7 +691,9 @@ void RNA_api_ui_layout(StructRNA *srna)
RNA_def_string(func, "new", NULL, 0, "", "Operator identifier to create a new ID block");
RNA_def_string(func, "open", NULL, 0, "", "Operator identifier to open a file for creating a new ID block");
RNA_def_string(func, "unlink", NULL, 0, "", "Operator identifier to unlink the ID block");
-
+ RNA_def_enum(func, "filter", id_template_filter_items, UI_TEMPLATE_ID_FILTER_ALL,
+ "", "Optionally limit the items which can be selected");
+
func = RNA_def_function(srna, "template_ID_preview", "uiTemplateIDPreview");
RNA_def_function_flag(func, FUNC_USE_CONTEXT);
api_ui_item_rna_common(func);
@@ -661,7 +702,9 @@ void RNA_api_ui_layout(StructRNA *srna)
RNA_def_string(func, "unlink", NULL, 0, "", "Operator identifier to unlink the ID block");
RNA_def_int(func, "rows", 0, 0, INT_MAX, "Number of thumbnail preview rows to display", "", 0, INT_MAX);
RNA_def_int(func, "cols", 0, 0, INT_MAX, "Number of thumbnail preview columns to display", "", 0, INT_MAX);
-
+ RNA_def_enum(func, "filter", id_template_filter_items, UI_TEMPLATE_ID_FILTER_ALL,
+ "", "Optionally limit the items which can be selected");
+
func = RNA_def_function(srna, "template_any_ID", "rna_uiTemplateAnyID");
parm = RNA_def_pointer(func, "data", "AnyType", "", "Data from which to take property");
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_REQUIRED | PARM_RNAPTR);
diff --git a/source/blender/makesrna/intern/rna_userdef.c b/source/blender/makesrna/intern/rna_userdef.c
index e68e67586e9..d813c095589 100644
--- a/source/blender/makesrna/intern/rna_userdef.c
+++ b/source/blender/makesrna/intern/rna_userdef.c
@@ -24,6 +24,7 @@
* \ingroup RNA
*/
+#include <limits.h>
#include <stdlib.h>
#include "DNA_curve_types.h"
@@ -34,6 +35,7 @@
#include "DNA_scene_types.h"
#include "BLI_utildefines.h"
+#include "BLI_math_base.h"
#include "BKE_appdir.h"
#include "BKE_DerivedMesh.h"
@@ -53,7 +55,7 @@
#include "GPU_buffers.h"
#ifdef WITH_OPENSUBDIV
-static EnumPropertyItem opensubdiv_compute_type_items[] = {
+static const EnumPropertyItem opensubdiv_compute_type_items[] = {
{USER_OPENSUBDIV_COMPUTE_NONE, "NONE", 0, "None", ""},
{USER_OPENSUBDIV_COMPUTE_CPU, "CPU", 0, "CPU", ""},
{USER_OPENSUBDIV_COMPUTE_OPENMP, "OPENMP", 0, "OpenMP", ""},
@@ -65,7 +67,7 @@ static EnumPropertyItem opensubdiv_compute_type_items[] = {
};
#endif
-static EnumPropertyItem audio_device_items[] = {
+static const EnumPropertyItem audio_device_items[] = {
{0, "NONE", 0, "None", "Null device - there will be no audio output"},
#ifdef WITH_SDL
{1, "SDL", 0, "SDL", "SDL device - simple direct media layer, recommended for sequencer usage"},
@@ -79,14 +81,14 @@ static EnumPropertyItem audio_device_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_navigation_mode_items[] = {
+const EnumPropertyItem rna_enum_navigation_mode_items[] = {
{VIEW_NAVIGATION_WALK, "WALK", 0, "Walk", "Interactively walk or free navigate around the scene"},
{VIEW_NAVIGATION_FLY, "FLY", 0, "Fly", "Use fly dynamics to navigate the scene"},
{0, NULL, 0, NULL, NULL}
};
#if defined(WITH_INTERNATIONAL) || !defined(RNA_RUNTIME)
-static EnumPropertyItem rna_enum_language_default_items[] = {
+static const EnumPropertyItem rna_enum_language_default_items[] = {
{0, "DEFAULT", 0, "Default (Default)", ""},
{0, NULL, 0, NULL, NULL}
};
@@ -138,23 +140,11 @@ static void rna_userdef_update(Main *UNUSED(bmain), Scene *UNUSED(scene), Pointe
}
/* also used by buffer swap switching */
-static void rna_userdef_dpi_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
+static void rna_userdef_dpi_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
{
/* font's are stored at each DPI level, without this we can easy load 100's of fonts */
BLF_cache_clear();
- BKE_blender_userdef_refresh();
- WM_main_add_notifier(NC_WINDOW, NULL); /* full redraw */
- WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */
-}
-
-static void rna_userdef_virtual_pixel_update(Main *bmain, Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
-{
- /* font's are stored at each DPI level, without this we can easy load 100's of fonts */
- BLF_cache_clear();
-
- BKE_blender_userdef_refresh();
-
/* force setting drawable again */
wmWindowManager *wm = bmain->wm.first;
if (wm) {
@@ -165,6 +155,12 @@ static void rna_userdef_virtual_pixel_update(Main *bmain, Scene *UNUSED(scene),
WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */
}
+static void rna_userdef_update_ui(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
+{
+ WM_main_add_notifier(NC_WINDOW, NULL);
+ WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */
+}
+
static void rna_userdef_language_update(Main *UNUSED(bmain), Scene *UNUSED(scene), PointerRNA *UNUSED(ptr))
{
BLF_cache_clear();
@@ -405,26 +401,23 @@ static void rna_userdef_autosave_update(Main *bmain, Scene *scene, PointerRNA *p
static bAddon *rna_userdef_addon_new(void)
{
- bAddon *bext = MEM_callocN(sizeof(bAddon), "bAddon");
- BLI_addtail(&U.addons, bext);
- return bext;
+ ListBase *addons_list = &U.addons;
+ bAddon *addon = BKE_addon_new();
+ BLI_addtail(addons_list, addon);
+ return addon;
}
-static void rna_userdef_addon_remove(ReportList *reports, PointerRNA *path_cmp_ptr)
+static void rna_userdef_addon_remove(ReportList *reports, PointerRNA *addon_ptr)
{
- bAddon *bext = path_cmp_ptr->data;
- if (BLI_findindex(&U.addons, bext) == -1) {
+ ListBase *addons_list = &U.addons;
+ bAddon *addon = addon_ptr->data;
+ if (BLI_findindex(addons_list, addon) == -1) {
BKE_report(reports, RPT_ERROR, "Add-on is no longer valid");
return;
}
-
- if (bext->prop) {
- IDP_FreeProperty(bext->prop);
- MEM_freeN(bext->prop);
- }
-
- BLI_freelinkN(&U.addons, bext);
- RNA_POINTER_INVALIDATE(path_cmp_ptr);
+ BLI_remlink(addons_list, addon);
+ BKE_addon_free(addon);
+ RNA_POINTER_INVALIDATE(addon_ptr);
}
static bPathCompare *rna_userdef_pathcompare_new(void)
@@ -457,6 +450,12 @@ static void rna_userdef_text_update(Main *UNUSED(bmain), Scene *UNUSED(scene), P
WM_main_add_notifier(NC_WINDOW, NULL);
}
+static void rna_userdef_text_antialiasing_update(Main *bmain, Scene *scene, PointerRNA *ptr)
+{
+ BLF_antialias_set((U.text_render & USER_TEXT_DISABLE_AA) == 0);
+ rna_userdef_text_update(bmain, scene, ptr);
+}
+
static PointerRNA rna_Theme_space_generic_get(PointerRNA *ptr)
{
return rna_pointer_inherit_refine(ptr, &RNA_ThemeSpaceGeneric, ptr->data);
@@ -474,7 +473,7 @@ static PointerRNA rna_Theme_space_list_generic_get(PointerRNA *ptr)
#ifdef WITH_OPENSUBDIV
-static EnumPropertyItem *rna_userdef_opensubdiv_compute_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_userdef_opensubdiv_compute_type_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
EnumPropertyItem *item = NULL;
@@ -521,7 +520,7 @@ static void rna_userdef_opensubdiv_update(Main *bmain, Scene *UNUSED(scene), Poi
#endif
-static EnumPropertyItem *rna_userdef_audio_device_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_userdef_audio_device_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *r_free)
{
int index = 0;
@@ -573,10 +572,10 @@ static EnumPropertyItem *rna_userdef_audio_device_itemf(bContext *UNUSED(C), Poi
}
#ifdef WITH_INTERNATIONAL
-static EnumPropertyItem *rna_lang_enum_properties_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+static const EnumPropertyItem *rna_lang_enum_properties_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
PropertyRNA *UNUSED(prop), bool *UNUSED(r_free))
{
- EnumPropertyItem *items = BLT_lang_RNA_enum_properties();
+ const EnumPropertyItem *items = BLT_lang_RNA_enum_properties();
if (items == NULL) {
items = rna_enum_language_default_items;
}
@@ -618,16 +617,17 @@ static void rna_AddonPref_unregister(Main *UNUSED(bmain), StructRNA *type)
return;
RNA_struct_free_extension(type, &apt->ext);
+ RNA_struct_free(&BLENDER_RNA, type);
BKE_addon_pref_type_remove(apt);
- RNA_struct_free(&BLENDER_RNA, type);
/* update while blender is running */
WM_main_add_notifier(NC_WINDOW, NULL);
}
-static StructRNA *rna_AddonPref_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_AddonPref_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
bAddonPrefType *apt, dummyapt = {{'\0'}};
bAddon dummyaddon = {NULL};
@@ -650,10 +650,8 @@ static StructRNA *rna_AddonPref_register(Main *bmain, ReportList *reports, void
/* check if we have registered this header type before, and remove it */
apt = BKE_addon_pref_type_find(dummyaddon.module, true);
- if (apt) {
- if (apt->ext.srna) {
- rna_AddonPref_unregister(bmain, apt->ext.srna);
- }
+ if (apt && apt->ext.srna) {
+ rna_AddonPref_unregister(bmain, apt->ext.srna);
}
/* create a new header type */
@@ -683,12 +681,33 @@ static StructRNA *rna_AddonPref_refine(PointerRNA *ptr)
#else
+/* TODO(sergey): This technically belongs to blenlib, but we don't link
+ * makesrna against it.
+ */
+
+/* Get maximum addressable memory in megabytes, */
+static size_t max_memory_in_megabytes(void)
+{
+ /* Maximum addressable bytes on this platform. */
+ const size_t limit_bytes = (((size_t)1) << ((sizeof(size_t) * 8) - 1));
+ /* Convert it to megabytes and return. */
+ return (limit_bytes >> 20);
+}
+
+/* Same as above, but clipped to int capacity. */
+static int max_memory_in_megabytes_int(void)
+{
+ const size_t limit_megabytes = max_memory_in_megabytes();
+ /* NOTE: The result will fit into integer. */
+ return (int)min_zz(limit_megabytes, (size_t)INT_MAX);
+}
+
static void rna_def_userdef_theme_ui_font_style(BlenderRNA *brna)
{
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem font_kerning_style[] = {
+ static const EnumPropertyItem font_kerning_style[] = {
{0, "UNFITTED", 0, "Unfitted", "Use scaled but un-grid-fitted kerning distances"},
{1, "FITTED", 0, "Fitted", "Use scaled and grid-fitted kerning distances"},
{0, NULL, 0, NULL, NULL}
@@ -2961,7 +2980,7 @@ static void rna_def_userdef_themes(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem active_theme_area[] = {
+ static const EnumPropertyItem active_theme_area[] = {
{0, "USER_INTERFACE", ICON_UI, "User Interface", ""},
{19, "STYLE", ICON_FONTPREVIEW, "Text Style", ""},
{18, "BONE_COLOR_SETS", ICON_COLOR, "Bone Color Sets", ""},
@@ -3168,6 +3187,7 @@ static void rna_def_userdef_addon_pref(BlenderRNA *brna)
RNA_def_struct_refine_func(srna, "rna_AddonPref_refine");
RNA_def_struct_register_funcs(srna, "rna_AddonPref_register", "rna_AddonPref_unregister", NULL);
RNA_def_struct_idprops_func(srna, "rna_AddonPref_idprops");
+ RNA_def_struct_flag(srna, STRUCT_NO_DATABLOCK_IDPROPERTIES); /* Mandatory! */
/* registration */
RNA_define_verify_sdna(0);
@@ -3292,7 +3312,7 @@ static void rna_def_userdef_walk_navigation(BlenderRNA *brna)
static void rna_def_userdef_view(BlenderRNA *brna)
{
- static EnumPropertyItem timecode_styles[] = {
+ static const EnumPropertyItem timecode_styles[] = {
{USER_TIMECODE_MINIMAL, "MINIMAL", 0, "Minimal Info",
"Most compact representation, uses '+' as separator for sub-second frame numbers, "
"with left and right truncation of the timecode as necessary"},
@@ -3308,13 +3328,20 @@ static void rna_def_userdef_view(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem zoom_frame_modes[] = {
+ static const EnumPropertyItem zoom_frame_modes[] = {
{ZOOM_FRAME_MODE_KEEP_RANGE, "KEEP_RANGE", 0, "Keep Range", ""},
{ZOOM_FRAME_MODE_SECONDS, "SECONDS", 0, "Seconds", ""},
{ZOOM_FRAME_MODE_KEYFRAMES, "KEYFRAMES", 0, "Keyframes", ""},
{0, NULL, 0, NULL, NULL}
};
+ static const EnumPropertyItem line_width[] = {
+ {-1, "THIN", 0, "Thin", "Thinner lines than the default"},
+ { 0, "AUTO", 0, "Auto", "Automatic line width based on UI scale"},
+ { 1, "THICK", 0, "Thick", "Thicker lines than the default"},
+ {0, NULL, 0, NULL, NULL}
+ };
+
PropertyRNA *prop;
StructRNA *srna;
@@ -3325,6 +3352,18 @@ static void rna_def_userdef_view(BlenderRNA *brna)
RNA_def_struct_ui_text(srna, "View & Controls", "Preferences related to viewing data");
/* View */
+ prop = RNA_def_property(srna, "ui_scale", PROP_FLOAT, PROP_FACTOR);
+ RNA_def_property_ui_text(prop, "UI Scale", "Changes the size of the fonts and buttons in the interface");
+ RNA_def_property_range(prop, 0.25f, 4.0f);
+ RNA_def_property_ui_range(prop, 0.5f, 2.0f, 1, 2);
+ RNA_def_property_float_default(prop, 1.0f);
+ RNA_def_property_update(prop, 0, "rna_userdef_dpi_update");
+
+ prop = RNA_def_property(srna, "ui_line_width", PROP_ENUM, PROP_NONE);
+ RNA_def_property_enum_items(prop, line_width);
+ RNA_def_property_ui_text(prop, "UI Line Width",
+ "Changes the thickness of lines and points in the interface");
+ RNA_def_property_update(prop, 0, "rna_userdef_dpi_update");
/* display */
prop = RNA_def_property(srna, "show_tooltips", PROP_BOOLEAN, PROP_NONE);
@@ -3359,12 +3398,24 @@ static void rna_def_userdef_view(BlenderRNA *brna)
RNA_def_property_boolean_negative_sdna(prop, NULL, "uiflag", USER_SPLASH_DISABLE);
RNA_def_property_ui_text(prop, "Show Splash", "Display splash screen on startup");
+
prop = RNA_def_property(srna, "show_playback_fps", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_SHOW_FPS);
RNA_def_property_ui_text(prop, "Show Playback FPS",
"Show the frames per second screen refresh rate, while animation is played back");
RNA_def_property_update(prop, 0, "rna_userdef_update");
-
+
+ /* app flags (use for app-templates) */
+ prop = RNA_def_property(srna, "show_layout_ui", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_negative_sdna(prop, NULL, "app_flag", USER_APP_LOCK_UI_LAYOUT);
+ RNA_def_property_ui_text(prop, "Show Layout Widgets", "Show screen layout editing UI");
+ RNA_def_property_update(prop, 0, "rna_userdef_update_ui");
+
+ prop = RNA_def_property(srna, "show_view3d_cursor", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_negative_sdna(prop, NULL, "app_flag", USER_APP_VIEW3D_HIDE_CURSOR);
+ RNA_def_property_ui_text(prop, "Show 3D View Cursor", "");
+ RNA_def_property_update(prop, 0, "rna_userdef_update");
+
/* menus */
prop = RNA_def_property(srna, "use_mouse_over_open", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_MENUOPENAUTO);
@@ -3441,15 +3492,20 @@ static void rna_def_userdef_view(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Global Pivot", "Lock the same rotation/scaling pivot in all 3D Views");
prop = RNA_def_property(srna, "use_mouse_depth_navigate", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_ZBUF_ORBIT);
+ RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DEPTH_NAVIGATE);
RNA_def_property_ui_text(prop, "Auto Depth",
"Use the depth under the mouse to improve view pan/rotate/zoom functionality");
prop = RNA_def_property(srna, "use_mouse_depth_cursor", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_ZBUF_CURSOR);
+ RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_DEPTH_CURSOR);
RNA_def_property_ui_text(prop, "Cursor Depth",
"Use the depth under the mouse when placing the cursor");
+ prop = RNA_def_property(srna, "use_cursor_lock_adjust", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "uiflag", USER_LOCK_CURSOR_ADJUST);
+ RNA_def_property_ui_text(prop, "Cursor Lock Adjust",
+ "Place the cursor without 'jumping' to the new location (when lock-to-cursor is used)");
+
prop = RNA_def_property(srna, "use_camera_lock_parent", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "uiflag", USER_CAM_LOCK_NO_PARENT);
RNA_def_property_ui_text(prop, "Camera Parent Lock",
@@ -3574,7 +3630,7 @@ static void rna_def_userdef_edit(BlenderRNA *brna)
PropertyRNA *prop;
StructRNA *srna;
- static EnumPropertyItem auto_key_modes[] = {
+ static const EnumPropertyItem auto_key_modes[] = {
{AUTOKEY_MODE_NORMAL, "ADD_REPLACE_KEYS", 0, "Add/Replace", ""},
{AUTOKEY_MODE_EDITKEYS, "REPLACE_KEYS", 0, "Replace", ""},
{0, NULL, 0, NULL, NULL}
@@ -3632,7 +3688,7 @@ static void rna_def_userdef_edit(BlenderRNA *brna)
prop = RNA_def_property(srna, "undo_memory_limit", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "undomemory");
- RNA_def_property_range(prop, 0, 32767);
+ RNA_def_property_range(prop, 0, max_memory_in_megabytes_int());
RNA_def_property_ui_text(prop, "Undo Memory Size", "Maximum memory usage in megabytes (0 means unlimited)");
prop = RNA_def_property(srna, "use_global_undo", PROP_BOOLEAN, PROP_NONE);
@@ -3804,7 +3860,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
PropertyRNA *prop;
StructRNA *srna;
- static EnumPropertyItem gl_texture_clamp_items[] = {
+ static const EnumPropertyItem gl_texture_clamp_items[] = {
{0, "CLAMP_OFF", 0, "Off", ""},
{8192, "CLAMP_8192", 0, "8192", ""},
{4096, "CLAMP_4096", 0, "4096", ""},
@@ -3816,7 +3872,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem anisotropic_items[] = {
+ static const EnumPropertyItem anisotropic_items[] = {
{1, "FILTER_0", 0, "Off", ""},
{2, "FILTER_2", 0, "2x", ""},
{4, "FILTER_4", 0, "4x", ""},
@@ -3825,7 +3881,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem audio_mixing_samples_items[] = {
+ static const EnumPropertyItem audio_mixing_samples_items[] = {
{256, "SAMPLES_256", 0, "256", "Set audio mixing buffer size to 256 samples"},
{512, "SAMPLES_512", 0, "512", "Set audio mixing buffer size to 512 samples"},
{1024, "SAMPLES_1024", 0, "1024", "Set audio mixing buffer size to 1024 samples"},
@@ -3837,7 +3893,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem audio_rate_items[] = {
+ static const EnumPropertyItem audio_rate_items[] = {
/* {8000, "RATE_8000", 0, "8 kHz", "Set audio sampling rate to 8000 samples per second"}, */
/* {11025, "RATE_11025", 0, "11.025 kHz", "Set audio sampling rate to 11025 samples per second"}, */
/* {16000, "RATE_16000", 0, "16 kHz", "Set audio sampling rate to 16000 samples per second"}, */
@@ -3851,7 +3907,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem audio_format_items[] = {
+ static const EnumPropertyItem audio_format_items[] = {
{0x01, "U8", 0, "8-bit Unsigned", "Set audio sample format to 8 bit unsigned integer"},
{0x12, "S16", 0, "16-bit Signed", "Set audio sample format to 16 bit signed integer"},
{0x13, "S24", 0, "24-bit Signed", "Set audio sample format to 24 bit signed integer"},
@@ -3861,7 +3917,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem audio_channel_items[] = {
+ static const EnumPropertyItem audio_channel_items[] = {
{1, "MONO", 0, "Mono", "Set audio channels to mono"},
{2, "STEREO", 0, "Stereo", "Set audio channels to stereo"},
{4, "SURROUND4", 0, "4 Channels", "Set audio channels to 4 channels"},
@@ -3870,7 +3926,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem draw_method_items[] = {
+ static const EnumPropertyItem draw_method_items[] = {
{USER_DRAW_AUTOMATIC, "AUTOMATIC", 0, "Automatic", "Automatically set based on graphics card and driver"},
{USER_DRAW_TRIPLE, "TRIPLE_BUFFER", 0, "Triple Buffer",
"Use a third buffer for minimal redraws at the cost of more memory"},
@@ -3884,7 +3940,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem color_picker_types[] = {
+ static const EnumPropertyItem color_picker_types[] = {
{USER_CP_CIRCLE_HSV, "CIRCLE_HSV", 0, "Circle (HSV)", "A circular Hue/Saturation color wheel, with Value slider"},
{USER_CP_CIRCLE_HSL, "CIRCLE_HSL", 0, "Circle (HSL)", "A circular Hue/Saturation color wheel, with Lightness slider"},
{USER_CP_SQUARE_SV, "SQUARE_SV", 0, "Square (SV + H)", "A square showing Saturation/Value, with Hue slider"},
@@ -3893,7 +3949,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem multi_sample_levels[] = {
+ static const EnumPropertyItem multi_sample_levels[] = {
{USER_MULTISAMPLE_NONE, "NONE", 0, "No MultiSample", "Do not use OpenGL MultiSample"},
{USER_MULTISAMPLE_2, "2", 0, "MultiSample: 2", "Use 2x OpenGL MultiSample (requires restart)"},
{USER_MULTISAMPLE_4, "4", 0, "MultiSample: 4", "Use 4x OpenGL MultiSample (requires restart)"},
@@ -3902,26 +3958,20 @@ static void rna_def_userdef_system(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem image_draw_methods[] = {
+ static const EnumPropertyItem image_draw_methods[] = {
{IMAGE_DRAW_METHOD_2DTEXTURE, "2DTEXTURE", 0, "2D Texture", "Use CPU for display transform and draw image with 2D texture"},
{IMAGE_DRAW_METHOD_GLSL, "GLSL", 0, "GLSL", "Use GLSL shaders for display transform and draw image with 2D texture"},
{IMAGE_DRAW_METHOD_DRAWPIXELS, "DRAWPIXELS", 0, "DrawPixels", "Use CPU for display transform and draw image using DrawPixels"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem gpu_select_method_items[] = {
+ static const EnumPropertyItem gpu_select_method_items[] = {
{USER_SELECT_AUTO, "AUTO", 0, "Automatic", ""},
{USER_SELECT_USE_SELECT_RENDERMODE, "GL_SELECT", 0, "OpenGL Select", ""},
{USER_SELECT_USE_OCCLUSION_QUERY, "GL_QUERY", 0, "OpenGL Occlusion Queries", ""},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem virtual_pixel_mode_items[] = {
- {VIRTUAL_PIXEL_NATIVE, "NATIVE", 0, "Native", "Use native pixel size of the display"},
- {VIRTUAL_PIXEL_DOUBLE, "DOUBLE", 0, "Double", "Use double the native pixel size of the display"},
- {0, NULL, 0, NULL, NULL}
- };
-
srna = RNA_def_struct(brna, "UserPreferencesSystem", NULL);
RNA_def_struct_sdna(srna, "UserDef");
RNA_def_struct_nested(brna, srna, "UserPreferences");
@@ -3936,21 +3986,19 @@ static void rna_def_userdef_system(BlenderRNA *brna)
RNA_def_property_update(prop, NC_WINDOW, "rna_userdef_language_update");
prop = RNA_def_property(srna, "dpi", PROP_INT, PROP_NONE);
- RNA_def_property_int_sdna(prop, NULL, "dpi");
- RNA_def_property_range(prop, 48, 144);
- RNA_def_property_ui_text(prop, "DPI", "Font size and resolution for display");
- RNA_def_property_update(prop, 0, "rna_userdef_dpi_update");
-
- prop = RNA_def_property(srna, "virtual_pixel_mode", PROP_ENUM, PROP_NONE);
- RNA_def_property_enum_sdna(prop, NULL, "virtual_pixel");
- RNA_def_property_enum_items(prop, virtual_pixel_mode_items);
- RNA_def_property_ui_text(prop, "Virtual Pixel Mode", "Modify the pixel size for hi-res devices");
- RNA_def_property_update(prop, 0, "rna_userdef_virtual_pixel_update");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "DPI",
+ "DPI for add-ons to use when drawing custom user interface elements, controlled by "
+ "operating system settings and Blender UI scale, with a reference value of 72 DPI "
+ "(note that since this value includes a user defined scale, it is not always the "
+ "actual monitor DPI)");
prop = RNA_def_property(srna, "pixel_size", PROP_FLOAT, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_float_sdna(prop, NULL, "pixelsize");
- RNA_def_property_ui_text(prop, "Pixel Size", "");
+ RNA_def_property_ui_text(prop, "Pixel Size",
+ "Suggested line thickness and point size in pixels, for add-ons drawing custom user "
+ "interface elements, controlled by operating system settings and Blender UI scale");
prop = RNA_def_property(srna, "font_path_ui", PROP_STRING, PROP_FILEPATH);
RNA_def_property_string_sdna(prop, NULL, "font_path_ui");
@@ -3998,11 +4046,6 @@ static void rna_def_userdef_system(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Translate New Names", "Translate new data names (when adding/creating some)");
RNA_def_property_update(prop, 0, "rna_userdef_update");
- prop = RNA_def_property(srna, "use_textured_fonts", PROP_BOOLEAN, PROP_NONE);
- RNA_def_property_boolean_sdna(prop, NULL, "transopts", USER_USETEXTUREFONT);
- RNA_def_property_ui_text(prop, "Textured Fonts", "Use textures for drawing international fonts");
- RNA_def_property_update(prop, 0, "rna_userdef_update");
-
/* System & OpenGL */
prop = RNA_def_property(srna, "solid_lights", PROP_COLLECTION, PROP_NONE);
@@ -4055,7 +4098,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
prop = RNA_def_property(srna, "memory_cache_limit", PROP_INT, PROP_NONE);
RNA_def_property_int_sdna(prop, NULL, "memcachelimit");
- RNA_def_property_range(prop, 0, (sizeof(void *) == 8) ? 1024 * 32 : 1024); /* 32 bit 2 GB, 64 bit 32 GB */
+ RNA_def_property_range(prop, 0, max_memory_in_megabytes_int());
RNA_def_property_ui_text(prop, "Memory Cache Limit", "Memory cache limit (in megabytes)");
RNA_def_property_update(prop, 0, "rna_Userdef_memcache_update");
@@ -4172,7 +4215,7 @@ static void rna_def_userdef_system(BlenderRNA *brna)
prop = RNA_def_property(srna, "use_text_antialiasing", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_boolean_negative_sdna(prop, NULL, "text_render", USER_TEXT_DISABLE_AA);
RNA_def_property_ui_text(prop, "Text Anti-aliasing", "Draw user interface text anti-aliased");
- RNA_def_property_update(prop, 0, "rna_userdef_text_update");
+ RNA_def_property_update(prop, 0, "rna_userdef_text_antialiasing_update");
prop = RNA_def_property(srna, "select_method", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_sdna(prop, NULL, "gpu_select_method");
@@ -4180,6 +4223,10 @@ static void rna_def_userdef_system(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Selection Method",
"Use OpenGL occlusion queries or selection render mode to accelerate selection");
+ prop = RNA_def_property(srna, "use_select_pick_depth", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "gpu_select_pick_deph", 1);
+ RNA_def_property_ui_text(prop, "OpenGL Depth Picking", "Use the depth buffer for picking 3D View selection");
+
/* Full scene anti-aliasing */
prop = RNA_def_property(srna, "multi_sample", PROP_ENUM, PROP_NONE);
RNA_def_property_enum_bitflag_sdna(prop, NULL, "ogl_multisamples");
@@ -4217,33 +4264,33 @@ static void rna_def_userdef_input(BlenderRNA *brna)
PropertyRNA *prop;
StructRNA *srna;
- static EnumPropertyItem select_mouse_items[] = {
+ static const EnumPropertyItem select_mouse_items[] = {
{USER_LMOUSESELECT, "LEFT", 0, "Left", "Use left Mouse Button for selection"},
{0, "RIGHT", 0, "Right", "Use Right Mouse Button for selection"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem view_rotation_items[] = {
+ static const EnumPropertyItem view_rotation_items[] = {
{0, "TURNTABLE", 0, "Turntable", "Use turntable style rotation in the viewport"},
{USER_TRACKBALL, "TRACKBALL", 0, "Trackball", "Use trackball style rotation in the viewport"},
{0, NULL, 0, NULL, NULL}
};
#ifdef WITH_INPUT_NDOF
- static EnumPropertyItem ndof_view_navigation_items[] = {
+ static const EnumPropertyItem ndof_view_navigation_items[] = {
{0, "FREE", 0, "Free", "Use full 6 degrees of freedom by default"},
{NDOF_MODE_ORBIT, "ORBIT", 0, "Orbit", "Orbit about the view center by default"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem ndof_view_rotation_items[] = {
+ static const EnumPropertyItem ndof_view_rotation_items[] = {
{NDOF_TURNTABLE, "TURNTABLE", 0, "Turntable", "Use turntable style rotation in the viewport"},
{0, "TRACKBALL", 0, "Trackball", "Use trackball style rotation in the viewport"},
{0, NULL, 0, NULL, NULL}
};
#endif /* WITH_INPUT_NDOF */
- static EnumPropertyItem view_zoom_styles[] = {
+ static const EnumPropertyItem view_zoom_styles[] = {
{USER_ZOOM_CONT, "CONTINUE", 0, "Continue", "Old style zoom, continues while moving mouse up or down"},
{USER_ZOOM_DOLLY, "DOLLY", 0, "Dolly", "Zoom in and out based on vertical mouse movement"},
{USER_ZOOM_SCALE, "SCALE", 0, "Scale",
@@ -4251,7 +4298,7 @@ static void rna_def_userdef_input(BlenderRNA *brna)
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem view_zoom_axes[] = {
+ static const EnumPropertyItem view_zoom_axes[] = {
{0, "VERTICAL", 0, "Vertical", "Zoom in and out based on vertical mouse movement"},
{USER_ZOOM_HORIZ, "HORIZONTAL", 0, "Horizontal", "Zoom in and out based on horizontal mouse movement"},
{0, NULL, 0, NULL, NULL}
@@ -4452,7 +4499,7 @@ static void rna_def_userdef_filepaths(BlenderRNA *brna)
PropertyRNA *prop;
StructRNA *srna;
- static EnumPropertyItem anim_player_presets[] = {
+ static const EnumPropertyItem anim_player_presets[] = {
{0, "INTERNAL", 0, "Internal", "Built-in animation player"},
{2, "DJV", 0, "Djv", "Open source frame player: http://djv.sourceforge.net"},
{3, "FRAMECYCLER", 0, "FrameCycler", "Frame player from IRIDAS"},
@@ -4647,7 +4694,7 @@ void RNA_def_userdef(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem user_pref_sections[] = {
+ static const EnumPropertyItem user_pref_sections[] = {
{USER_SECTION_INTERFACE, "INTERFACE", 0, "Interface", ""},
{USER_SECTION_EDIT, "EDITING", 0, "Editing", ""},
{USER_SECTION_INPUT, "INPUT", 0, "Input", ""},
@@ -4674,6 +4721,11 @@ void RNA_def_userdef(BlenderRNA *brna)
"Active section of the user preferences shown in the user interface");
RNA_def_property_update(prop, 0, "rna_userdef_update");
+ /* don't expose this directly via the UI, modify via an operator */
+ prop = RNA_def_property(srna, "app_template", PROP_STRING, PROP_NONE);
+ RNA_def_property_string_sdna(prop, NULL, "app_template");
+ RNA_def_property_ui_text(prop, "Application Template", "");
+
prop = RNA_def_property(srna, "themes", PROP_COLLECTION, PROP_NONE);
RNA_def_property_collection_sdna(prop, NULL, "themes", NULL);
RNA_def_property_struct_type(prop, "Theme");
diff --git a/source/blender/makesrna/intern/rna_wm.c b/source/blender/makesrna/intern/rna_wm.c
index 35c9c9bcc89..b71eca3d850 100644
--- a/source/blender/makesrna/intern/rna_wm.c
+++ b/source/blender/makesrna/intern/rna_wm.c
@@ -32,6 +32,7 @@
#include "DNA_windowmanager_types.h"
#include "BLI_utildefines.h"
+#include "BLI_string_utils.h"
#include "BLT_translation.h"
@@ -44,7 +45,7 @@
#include "WM_types.h"
#ifdef RNA_RUNTIME
-static EnumPropertyItem event_keymouse_value_items[] = {
+static const EnumPropertyItem event_keymouse_value_items[] = {
{KM_ANY, "ANY", 0, "Any", ""},
{KM_PRESS, "PRESS", 0, "Press", ""},
{KM_RELEASE, "RELEASE", 0, "Release", ""},
@@ -53,7 +54,7 @@ static EnumPropertyItem event_keymouse_value_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_tweak_value_items[] = {
+static const EnumPropertyItem event_tweak_value_items[] = {
{KM_ANY, "ANY", 0, "Any", ""},
{EVT_GESTURE_N, "NORTH", 0, "North", ""},
{EVT_GESTURE_NE, "NORTH_EAST", 0, "North-East", ""},
@@ -66,7 +67,7 @@ static EnumPropertyItem event_tweak_value_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_tweak_type_items[] = {
+static const EnumPropertyItem event_tweak_type_items[] = {
{EVT_TWEAK_L, "EVT_TWEAK_L", 0, "Left", ""},
{EVT_TWEAK_M, "EVT_TWEAK_M", 0, "Middle", ""},
{EVT_TWEAK_R, "EVT_TWEAK_R", 0, "Right", ""},
@@ -75,7 +76,7 @@ static EnumPropertyItem event_tweak_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_mouse_type_items[] = {
+static const EnumPropertyItem event_mouse_type_items[] = {
{LEFTMOUSE, "LEFTMOUSE", 0, "Left", ""},
{MIDDLEMOUSE, "MIDDLEMOUSE", 0, "Middle", ""},
{RIGHTMOUSE, "RIGHTMOUSE", 0, "Right", ""},
@@ -101,7 +102,7 @@ static EnumPropertyItem event_mouse_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_timer_type_items[] = {
+static const EnumPropertyItem event_timer_type_items[] = {
{TIMER, "TIMER", 0, "Timer", ""},
{TIMER0, "TIMER0", 0, "Timer 0", ""},
{TIMER1, "TIMER1", 0, "Timer 1", ""},
@@ -113,12 +114,12 @@ static EnumPropertyItem event_timer_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_textinput_type_items[] = {
+static const EnumPropertyItem event_textinput_type_items[] = {
{KM_TEXTINPUT, "TEXTINPUT", 0, "Text Input", ""},
{0, NULL, 0, NULL, NULL}
};
-static EnumPropertyItem event_ndof_type_items[] = {
+static const EnumPropertyItem event_ndof_type_items[] = {
{NDOF_MOTION, "NDOF_MOTION", 0, "Motion", ""},
/* buttons on all 3dconnexion devices */
{NDOF_BUTTON_MENU, "NDOF_BUTTON_MENU", 0, "Menu", ""},
@@ -170,7 +171,7 @@ static EnumPropertyItem event_ndof_type_items[] = {
#endif /* RNA_RUNTIME */
/* not returned: CAPSLOCKKEY, UNKNOWNKEY */
-EnumPropertyItem rna_enum_event_type_items[] = {
+const EnumPropertyItem rna_enum_event_type_items[] = {
/* Note we abuse 'tooltip' message here to store a 'compact' form of some (too) long names. */
{0, "NONE", 0, "", ""},
{LEFTMOUSE, "LEFTMOUSE", 0, "Left Mouse", "LMB"},
@@ -381,7 +382,7 @@ EnumPropertyItem rna_enum_event_type_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_event_value_items[] = {
+const EnumPropertyItem rna_enum_event_value_items[] = {
{KM_ANY, "ANY", 0, "Any", ""},
{KM_NOTHING, "NOTHING", 0, "Nothing", ""},
{KM_PRESS, "PRESS", 0, "Press", ""},
@@ -399,13 +400,13 @@ EnumPropertyItem rna_enum_event_value_items[] = {
{0, NULL, 0, NULL, NULL}
};
-EnumPropertyItem rna_enum_keymap_propvalue_items[] = {
+const EnumPropertyItem rna_enum_keymap_propvalue_items[] = {
{0, "NONE", 0, "", ""},
{0, NULL, 0, NULL, NULL}
};
#if 0
-static EnumPropertyItem keymap_modifiers_items[] = {
+static const EnumPropertyItem keymap_modifiers_items[] = {
{KM_ANY, "ANY", 0, "Any", ""},
{0, "NONE", 0, "None", ""},
{1, "FIRST", 0, "First", ""},
@@ -416,7 +417,7 @@ static EnumPropertyItem keymap_modifiers_items[] = {
#ifndef RNA_RUNTIME
-static EnumPropertyItem operator_flag_items[] = {
+static const EnumPropertyItem operator_flag_items[] = {
{OPTYPE_REGISTER, "REGISTER", 0, "Register", "Display in the info window and support the redo toolbar panel"},
{OPTYPE_UNDO, "UNDO", 0, "Undo", "Push an undo event (needed for operator redo)"},
{OPTYPE_UNDO_GROUPED, "UNDO_GROUPED", 0, "Grouped Undo", "Push a single undo event for repetead instances of this operator"},
@@ -431,7 +432,7 @@ static EnumPropertyItem operator_flag_items[] = {
};
#endif
-EnumPropertyItem rna_enum_operator_return_items[] = {
+const EnumPropertyItem rna_enum_operator_return_items[] = {
{OPERATOR_RUNNING_MODAL, "RUNNING_MODAL", 0, "Running Modal", "Keep the operator running with blender"},
{OPERATOR_CANCELLED, "CANCELLED", 0, "Cancelled", "When no action has been taken, operator exits"},
{OPERATOR_FINISHED, "FINISHED", 0, "Finished", "When the operator is complete, operator exits"},
@@ -442,7 +443,7 @@ EnumPropertyItem rna_enum_operator_return_items[] = {
};
/* flag/enum */
-EnumPropertyItem rna_enum_wm_report_items[] = {
+const EnumPropertyItem rna_enum_wm_report_items[] = {
{RPT_DEBUG, "DEBUG", 0, "Debug", ""},
{RPT_INFO, "INFO", 0, "Info", ""},
{RPT_OPERATOR, "OPERATOR", 0, "Operator", ""},
@@ -731,7 +732,7 @@ static void rna_wmKeyMapItem_keymodifier_set(PointerRNA *ptr, int value)
}
-static EnumPropertyItem *rna_KeyMapItem_type_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
+static const EnumPropertyItem *rna_KeyMapItem_type_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
bool *UNUSED(r_free))
{
int map_type = rna_wmKeyMapItem_map_type_get(ptr);
@@ -744,7 +745,7 @@ static EnumPropertyItem *rna_KeyMapItem_type_itemf(bContext *UNUSED(C), PointerR
else return rna_enum_event_type_items;
}
-static EnumPropertyItem *rna_KeyMapItem_value_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
+static const EnumPropertyItem *rna_KeyMapItem_value_itemf(bContext *UNUSED(C), PointerRNA *ptr, PropertyRNA *UNUSED(prop),
bool *UNUSED(r_free))
{
int map_type = rna_wmKeyMapItem_map_type_get(ptr);
@@ -757,7 +758,7 @@ static EnumPropertyItem *rna_KeyMapItem_value_itemf(bContext *UNUSED(C), Pointer
return rna_enum_event_value_items;
}
-static EnumPropertyItem *rna_KeyMapItem_propvalue_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop),
+static const EnumPropertyItem *rna_KeyMapItem_propvalue_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop),
bool *UNUSED(r_free))
{
wmWindowManager *wm = CTX_wm_manager(C);
@@ -939,35 +940,8 @@ static void rna_wmClipboard_set(PointerRNA *UNUSED(ptr), const char *value)
}
#ifdef WITH_PYTHON
-static void rna_Operator_unregister(struct Main *bmain, StructRNA *type)
-{
- const char *idname;
- wmOperatorType *ot = RNA_struct_blender_type_get(type);
- wmWindowManager *wm;
-
- if (!ot)
- return;
- /* update while blender is running */
- wm = bmain->wm.first;
- if (wm) {
- WM_operator_stack_clear(wm);
-
- WM_operator_handlers_clear(wm, ot);
- }
- WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);
-
- RNA_struct_free_extension(type, &ot->ext);
-
- idname = ot->idname;
- WM_operatortype_remove_ptr(ot);
- MEM_freeN((void *)idname);
-
- /* not to be confused with the RNA_struct_free that WM_operatortype_remove calls, they are 2 different srna's */
- RNA_struct_free(&BLENDER_RNA, type);
-}
-
-static int operator_poll(bContext *C, wmOperatorType *ot)
+static int rna_operator_poll_cb(bContext *C, wmOperatorType *ot)
{
extern FunctionRNA rna_Operator_poll_func;
@@ -992,7 +966,7 @@ static int operator_poll(bContext *C, wmOperatorType *ot)
return visible;
}
-static int operator_execute(bContext *C, wmOperator *op)
+static int rna_operator_execute_cb(bContext *C, wmOperator *op)
{
extern FunctionRNA rna_Operator_execute_func;
@@ -1018,7 +992,7 @@ static int operator_execute(bContext *C, wmOperator *op)
}
/* same as execute() but no return value */
-static bool operator_check(bContext *C, wmOperator *op)
+static bool rna_operator_check_cb(bContext *C, wmOperator *op)
{
extern FunctionRNA rna_Operator_check_func;
@@ -1043,7 +1017,7 @@ static bool operator_check(bContext *C, wmOperator *op)
return result;
}
-static int operator_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+static int rna_operator_invoke_cb(bContext *C, wmOperator *op, const wmEvent *event)
{
extern FunctionRNA rna_Operator_invoke_func;
@@ -1070,7 +1044,7 @@ static int operator_invoke(bContext *C, wmOperator *op, const wmEvent *event)
}
/* same as invoke */
-static int operator_modal(bContext *C, wmOperator *op, const wmEvent *event)
+static int rna_operator_modal_cb(bContext *C, wmOperator *op, const wmEvent *event)
{
extern FunctionRNA rna_Operator_modal_func;
@@ -1096,7 +1070,7 @@ static int operator_modal(bContext *C, wmOperator *op, const wmEvent *event)
return result;
}
-static void operator_draw(bContext *C, wmOperator *op)
+static void rna_operator_draw_cb(bContext *C, wmOperator *op)
{
extern FunctionRNA rna_Operator_draw_func;
@@ -1115,7 +1089,7 @@ static void operator_draw(bContext *C, wmOperator *op)
}
/* same as exec(), but call cancel */
-static void operator_cancel(bContext *C, wmOperator *op)
+static void rna_operator_cancel_cb(bContext *C, wmOperator *op)
{
extern FunctionRNA rna_Operator_cancel_func;
@@ -1133,112 +1107,84 @@ static void operator_cancel(bContext *C, wmOperator *op)
RNA_parameter_list_free(&list);
}
-void operator_wrapper(wmOperatorType *ot, void *userdata);
-void macro_wrapper(wmOperatorType *ot, void *userdata);
+static void rna_Operator_unregister(struct Main *bmain, StructRNA *type);
+
+/* bpy_operator_wrap.c */
+extern void BPY_RNA_operator_wrapper(wmOperatorType *ot, void *userdata);
+extern void BPY_RNA_operator_macro_wrapper(wmOperatorType *ot, void *userdata);
-static char _operator_idname[OP_MAX_TYPENAME];
-static char _operator_name[OP_MAX_TYPENAME];
-static char _operator_descr[RNA_DYN_DESCR_MAX];
-static char _operator_ctxt[RNA_DYN_DESCR_MAX];
-static char _operator_undo_group[OP_MAX_TYPENAME];
-static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_Operator_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
wmOperatorType dummyot = {NULL};
wmOperator dummyop = {NULL};
PointerRNA dummyotr;
int have_function[7];
+ struct {
+ char idname[OP_MAX_TYPENAME];
+ char name[OP_MAX_TYPENAME];
+ char description[RNA_DYN_DESCR_MAX];
+ char translation_context[RNA_DYN_DESCR_MAX];
+ char undo_group[OP_MAX_TYPENAME];
+ } temp_buffers;
+
/* setup dummy operator & operator type to store static properties in */
dummyop.type = &dummyot;
- dummyot.idname = _operator_idname; /* only assigne the pointer, string is NULL'd */
- dummyot.name = _operator_name; /* only assigne the pointer, string is NULL'd */
- dummyot.description = _operator_descr; /* only assigne the pointer, string is NULL'd */
- dummyot.translation_context = _operator_ctxt; /* only assigne the pointer, string is NULL'd */
- dummyot.undo_group = _operator_undo_group; /* only assigne the pointer, string is NULL'd */
+ dummyot.idname = temp_buffers.idname; /* only assigne the pointer, string is NULL'd */
+ dummyot.name = temp_buffers.name; /* only assigne the pointer, string is NULL'd */
+ dummyot.description = temp_buffers.description; /* only assigne the pointer, string is NULL'd */
+ dummyot.translation_context = temp_buffers.translation_context; /* only assigne the pointer, string is NULL'd */
+ dummyot.undo_group = temp_buffers.undo_group; /* only assigne the pointer, string is NULL'd */
RNA_pointer_create(NULL, &RNA_Operator, &dummyop, &dummyotr);
/* clear in case they are left unset */
- _operator_idname[0] = _operator_name[0] = _operator_descr[0] = _operator_undo_group[0] = '\0';
+ temp_buffers.idname[0] = temp_buffers.name[0] = temp_buffers.description[0] = temp_buffers.undo_group[0] = '\0';
/* We have to set default op context! */
- strcpy(_operator_ctxt, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
+ strcpy(temp_buffers.translation_context, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
/* validate the python class */
if (validate(&dummyotr, data, have_function) != 0)
return NULL;
- { /* convert foo.bar to FOO_OT_bar
- * allocate the description and the idname in 1 go */
-
- /* inconveniently long name sanity check */
- {
- char *ch = _operator_idname;
- int i;
- int dot = 0;
- for (i = 0; *ch; i++) {
- if ((*ch >= 'a' && *ch <= 'z') || (*ch >= '0' && *ch <= '9') || *ch == '_') {
- /* pass */
- }
- else if (*ch == '.') {
- dot++;
- }
- else {
- BKE_reportf(reports, RPT_ERROR,
- "Registering operator class: '%s', invalid bl_idname '%s', at position %d",
- identifier, _operator_idname, i);
- return NULL;
- }
+ /* check if we have registered this operator type before, and remove it */
+ {
+ wmOperatorType *ot = WM_operatortype_find(dummyot.idname, true);
+ if (ot && ot->ext.srna)
+ rna_Operator_unregister(bmain, ot->ext.srna);
+ }
- ch++;
- }
+ if (!WM_operator_py_idname_ok_or_report(reports, identifier, dummyot.idname)) {
+ return NULL;
+ }
- if (i > ((int)sizeof(dummyop.idname)) - 3) {
- BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s', invalid bl_idname '%s', "
- "is too long, maximum length is %d", identifier, _operator_idname,
- (int)sizeof(dummyop.idname) - 3);
- return NULL;
- }
+ char idname_conv[sizeof(dummyop.idname)];
+ WM_operator_bl_idname(idname_conv, dummyot.idname); /* convert the idname from python */
- if (dot != 1) {
- BKE_reportf(reports, RPT_ERROR,
- "Registering operator class: '%s', invalid bl_idname '%s', must contain 1 '.' character",
- identifier, _operator_idname);
- return NULL;
- }
- }
- /* end sanity check */
-
- {
- int idlen = strlen(_operator_idname) + 4;
- int namelen = strlen(_operator_name) + 1;
- int desclen = strlen(_operator_descr) + 1;
- int ctxtlen = strlen(_operator_ctxt) + 1;
- int ugrouplen = strlen(_operator_undo_group) + 1;
- char *ch;
- /* 2 terminators and 3 to convert a.b -> A_OT_b */
- ch = MEM_callocN(sizeof(char) * (idlen + namelen + desclen + ctxtlen + ugrouplen), "_operator_idname");
- WM_operator_bl_idname(ch, _operator_idname); /* convert the idname from python */
- dummyot.idname = ch;
- ch += idlen;
- strcpy(ch, _operator_name);
- dummyot.name = ch;
- ch += namelen;
- strcpy(ch, _operator_descr);
- dummyot.description = ch;
- ch += desclen;
- strcpy(ch, _operator_ctxt);
- dummyot.translation_context = ch;
- ch += ctxtlen;
- strcpy(ch, _operator_undo_group);
- dummyot.undo_group = ch;
- }
+ if (!RNA_struct_available_or_report(reports, idname_conv)) {
+ return NULL;
}
- /* check if we have registered this operator type before, and remove it */
+ /* Convert foo.bar to FOO_OT_bar
+ * allocate all strings at once. */
{
- wmOperatorType *ot = WM_operatortype_find(dummyot.idname, true);
- if (ot && ot->ext.srna)
- rna_Operator_unregister(bmain, ot->ext.srna);
+ const char *strings[] = {
+ idname_conv,
+ temp_buffers.name,
+ temp_buffers.description,
+ temp_buffers.translation_context,
+ temp_buffers.undo_group,
+ };
+ char *strings_table[ARRAY_SIZE(strings)];
+ BLI_string_join_array_by_sep_char_with_tableN('\0', strings_table, strings, ARRAY_SIZE(strings));
+
+ dummyot.idname = strings_table[0]; /* allocated string stored here */
+ dummyot.name = strings_table[1];
+ dummyot.description = strings_table[2];
+ dummyot.translation_context = strings_table[3];
+ dummyot.undo_group = strings_table[4];
+ BLI_assert(ARRAY_SIZE(strings) == 5);
}
/* XXX, this doubles up with the operator name [#29666]
@@ -1252,14 +1198,14 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
dummyot.ext.call = call;
dummyot.ext.free = free;
- dummyot.pyop_poll = (have_function[0]) ? operator_poll : NULL;
- dummyot.exec = (have_function[1]) ? operator_execute : NULL;
- dummyot.check = (have_function[2]) ? operator_check : NULL;
- dummyot.invoke = (have_function[3]) ? operator_invoke : NULL;
- dummyot.modal = (have_function[4]) ? operator_modal : NULL;
- dummyot.ui = (have_function[5]) ? operator_draw : NULL;
- dummyot.cancel = (have_function[6]) ? operator_cancel : NULL;
- WM_operatortype_append_ptr(operator_wrapper, (void *)&dummyot);
+ dummyot.pyop_poll = (have_function[0]) ? rna_operator_poll_cb : NULL;
+ dummyot.exec = (have_function[1]) ? rna_operator_execute_cb : NULL;
+ dummyot.check = (have_function[2]) ? rna_operator_check_cb : NULL;
+ dummyot.invoke = (have_function[3]) ? rna_operator_invoke_cb : NULL;
+ dummyot.modal = (have_function[4]) ? rna_operator_modal_cb : NULL;
+ dummyot.ui = (have_function[5]) ? rna_operator_draw_cb : NULL;
+ dummyot.cancel = (have_function[6]) ? rna_operator_cancel_cb : NULL;
+ WM_operatortype_append_ptr(BPY_RNA_operator_wrapper, (void *)&dummyot);
/* update while blender is running */
WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);
@@ -1267,64 +1213,76 @@ static StructRNA *rna_Operator_register(Main *bmain, ReportList *reports, void *
return dummyot.ext.srna;
}
+static void rna_Operator_unregister(struct Main *bmain, StructRNA *type)
+{
+ const char *idname;
+ wmOperatorType *ot = RNA_struct_blender_type_get(type);
+ wmWindowManager *wm;
+
+ if (!ot)
+ return;
+
+ /* update while blender is running */
+ wm = bmain->wm.first;
+ if (wm) {
+ WM_operator_stack_clear(wm);
+
+ WM_operator_handlers_clear(wm, ot);
+ }
+ WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);
+
+ RNA_struct_free_extension(type, &ot->ext);
+
+ idname = ot->idname;
+ WM_operatortype_remove_ptr(ot);
+
+ /* not to be confused with the RNA_struct_free that WM_operatortype_remove calls, they are 2 different srna's */
+ RNA_struct_free(&BLENDER_RNA, type);
+
+ MEM_freeN((void *)idname);
+}
+
static void **rna_Operator_instance(PointerRNA *ptr)
{
wmOperator *op = ptr->data;
return &op->py_instance;
}
-static StructRNA *rna_MacroOperator_register(Main *bmain, ReportList *reports, void *data, const char *identifier,
- StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
+static StructRNA *rna_MacroOperator_register(
+ Main *bmain, ReportList *reports, void *data, const char *identifier,
+ StructValidateFunc validate, StructCallbackFunc call, StructFreeFunc free)
{
wmOperatorType dummyot = {NULL};
wmOperator dummyop = {NULL};
PointerRNA dummyotr;
int have_function[4];
+ struct {
+ char idname[OP_MAX_TYPENAME];
+ char name[OP_MAX_TYPENAME];
+ char description[RNA_DYN_DESCR_MAX];
+ char translation_context[RNA_DYN_DESCR_MAX];
+ char undo_group[OP_MAX_TYPENAME];
+ } temp_buffers;
+
/* setup dummy operator & operator type to store static properties in */
dummyop.type = &dummyot;
- dummyot.idname = _operator_idname; /* only assigne the pointer, string is NULL'd */
- dummyot.name = _operator_name; /* only assigne the pointer, string is NULL'd */
- dummyot.description = _operator_descr; /* only assigne the pointer, string is NULL'd */
- dummyot.translation_context = _operator_ctxt; /* only assigne the pointer, string is NULL'd */
- dummyot.undo_group = _operator_undo_group; /* only assigne the pointer, string is NULL'd */
+ dummyot.idname = temp_buffers.idname; /* only assigne the pointer, string is NULL'd */
+ dummyot.name = temp_buffers.name; /* only assigne the pointer, string is NULL'd */
+ dummyot.description = temp_buffers.description; /* only assigne the pointer, string is NULL'd */
+ dummyot.translation_context = temp_buffers.translation_context; /* only assigne the pointer, string is NULL'd */
+ dummyot.undo_group = temp_buffers.undo_group; /* only assigne the pointer, string is NULL'd */
RNA_pointer_create(NULL, &RNA_Macro, &dummyop, &dummyotr);
/* clear in case they are left unset */
- _operator_idname[0] = _operator_name[0] = _operator_descr[0] = _operator_undo_group[0] = '\0';
+ temp_buffers.idname[0] = temp_buffers.name[0] = temp_buffers.description[0] = temp_buffers.undo_group[0] = '\0';
/* We have to set default op context! */
- strcpy(_operator_ctxt, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
+ strcpy(temp_buffers.translation_context, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
/* validate the python class */
if (validate(&dummyotr, data, have_function) != 0)
return NULL;
- { /* convert foo.bar to FOO_OT_bar
- * allocate the description and the idname in 1 go */
- int idlen = strlen(_operator_idname) + 4;
- int namelen = strlen(_operator_name) + 1;
- int desclen = strlen(_operator_descr) + 1;
- int ctxtlen = strlen(_operator_ctxt) + 1;
- int ugrouplen = strlen(_operator_undo_group) + 1;
- char *ch;
- /* 2 terminators and 3 to convert a.b -> A_OT_b */
- ch = MEM_callocN(sizeof(char) * (idlen + namelen + desclen + ctxtlen + ugrouplen), "_operator_idname");
- WM_operator_bl_idname(ch, _operator_idname); /* convert the idname from python */
- dummyot.idname = ch;
- ch += idlen;
- strcpy(ch, _operator_name);
- dummyot.name = ch;
- ch += namelen;
- strcpy(ch, _operator_descr);
- dummyot.description = ch;
- ch += desclen;
- strcpy(ch, _operator_ctxt);
- dummyot.translation_context = ch;
- ch += ctxtlen;
- strcpy(ch, _operator_undo_group);
- dummyot.undo_group = ch;
- }
-
if (strlen(identifier) >= sizeof(dummyop.idname)) {
BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s' is too long, maximum length is %d",
identifier, (int)sizeof(dummyop.idname));
@@ -1338,6 +1296,38 @@ static StructRNA *rna_MacroOperator_register(Main *bmain, ReportList *reports, v
rna_Operator_unregister(bmain, ot->ext.srna);
}
+ if (!WM_operator_py_idname_ok_or_report(reports, identifier, dummyot.idname)) {
+ return NULL;
+ }
+
+ char idname_conv[sizeof(dummyop.idname)];
+ WM_operator_bl_idname(idname_conv, dummyot.idname); /* convert the idname from python */
+
+ if (!RNA_struct_available_or_report(reports, idname_conv)) {
+ return NULL;
+ }
+
+ /* Convert foo.bar to FOO_OT_bar
+ * allocate all strings at once. */
+ {
+ const char *strings[] = {
+ idname_conv,
+ temp_buffers.name,
+ temp_buffers.description,
+ temp_buffers.translation_context,
+ temp_buffers.undo_group,
+ };
+ char *strings_table[ARRAY_SIZE(strings)];
+ BLI_string_join_array_by_sep_char_with_tableN('\0', strings_table, strings, ARRAY_SIZE(strings));
+
+ dummyot.idname = strings_table[0]; /* allocated string stored here */
+ dummyot.name = strings_table[1];
+ dummyot.description = strings_table[2];
+ dummyot.translation_context = strings_table[3];
+ dummyot.undo_group = strings_table[4];
+ BLI_assert(ARRAY_SIZE(strings) == 5);
+ }
+
/* XXX, this doubles up with the operator name [#29666]
* for now just remove from dir(bpy.types) */
@@ -1348,10 +1338,10 @@ static StructRNA *rna_MacroOperator_register(Main *bmain, ReportList *reports, v
dummyot.ext.call = call;
dummyot.ext.free = free;
- dummyot.pyop_poll = (have_function[0]) ? operator_poll : NULL;
- dummyot.ui = (have_function[3]) ? operator_draw : NULL;
+ dummyot.pyop_poll = (have_function[0]) ? rna_operator_poll_cb : NULL;
+ dummyot.ui = (have_function[3]) ? rna_operator_draw_cb : NULL;
- WM_operatortype_append_macro_ptr(macro_wrapper, (void *)&dummyot);
+ WM_operatortype_append_macro_ptr(BPY_RNA_operator_macro_wrapper, (void *)&dummyot);
/* update while blender is running */
WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL);
@@ -1453,6 +1443,11 @@ static void rna_def_operator_options_runtime(BlenderRNA *brna)
RNA_def_property_ui_text(prop, "Invoke", "True when invoked (even if only the execute callbacks available)");
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ prop = RNA_def_property(srna, "is_repeat", PROP_BOOLEAN, PROP_BOOLEAN);
+ RNA_def_property_boolean_sdna(prop, NULL, "flag", OP_IS_REPEAT);
+ RNA_def_property_ui_text(prop, "Repeat", "True when run from the redo panel");
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+
prop = RNA_def_property(srna, "use_cursor_region", PROP_BOOLEAN, PROP_BOOLEAN);
RNA_def_property_boolean_sdna(prop, NULL, "flag", OP_IS_MODAL_CURSOR_REGION);
RNA_def_property_ui_text(prop, "Focus Region", "Enable to use the region under the cursor for modal execution");
@@ -1471,6 +1466,7 @@ static void rna_def_operator(BlenderRNA *brna)
RNA_def_struct_register_funcs(srna, "rna_Operator_register", "rna_Operator_unregister", "rna_Operator_instance");
#endif
RNA_def_struct_translation_context(srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
+ RNA_def_struct_flag(srna, STRUCT_PUBLIC_NAMESPACE_INHERIT);
prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
@@ -1556,6 +1552,7 @@ static void rna_def_operator(BlenderRNA *brna)
RNA_def_struct_ui_text(srna, "Operator Properties", "Input properties of an Operator");
RNA_def_struct_refine_func(srna, "rna_OperatorProperties_refine");
RNA_def_struct_idprops_func(srna, "rna_OperatorProperties_idprops");
+ RNA_def_struct_flag(srna, STRUCT_NO_DATABLOCK_IDPROPERTIES);
}
static void rna_def_macro_operator(BlenderRNA *brna)
@@ -1573,6 +1570,7 @@ static void rna_def_macro_operator(BlenderRNA *brna)
"rna_Operator_instance");
#endif
RNA_def_struct_translation_context(srna, BLT_I18NCONTEXT_OPERATOR_DEFAULT);
+ RNA_def_struct_flag(srna, STRUCT_PUBLIC_NAMESPACE_INHERIT);
prop = RNA_def_property(srna, "name", PROP_STRING, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
@@ -1771,7 +1769,12 @@ static void rna_def_event(BlenderRNA *brna)
prop = RNA_def_property(srna, "is_tablet", PROP_BOOLEAN, PROP_NONE);
RNA_def_property_clear_flag(prop, PROP_EDITABLE);
RNA_def_property_boolean_funcs(prop, "rna_Event_is_tablet_get", NULL);
- RNA_def_property_ui_text(prop, "Tablet Pressure", "The pressure of the tablet or 1.0 if no tablet present");
+ RNA_def_property_ui_text(prop, "Is Tablet", "The event has tablet data");
+
+ prop = RNA_def_property(srna, "is_mouse_absolute", PROP_BOOLEAN, PROP_NONE);
+ RNA_def_property_boolean_sdna(prop, NULL, "is_motion_absolute", 1);
+ RNA_def_property_clear_flag(prop, PROP_EDITABLE);
+ RNA_def_property_ui_text(prop, "Absolute Motion", "The last motion event was an absolute input");
/* modifiers */
prop = RNA_def_property(srna, "shift", PROP_BOOLEAN, PROP_NONE);
@@ -1827,44 +1830,36 @@ static void rna_def_timer(BlenderRNA *brna)
RNA_define_verify_sdna(1); /* not in sdna */
}
-static void rna_def_popupmenu(BlenderRNA *brna)
+static void rna_def_popup_menu_wrapper(
+ BlenderRNA *brna, const char *rna_type, const char *c_type, const char *layout_get_fn)
{
StructRNA *srna;
PropertyRNA *prop;
- srna = RNA_def_struct(brna, "UIPopupMenu", NULL);
- RNA_def_struct_ui_text(srna, "PopupMenu", "");
- RNA_def_struct_sdna(srna, "uiPopupMenu");
+ srna = RNA_def_struct(brna, rna_type, NULL);
+ /* UI name isn't visible, name same as type. */
+ RNA_def_struct_ui_text(srna, rna_type, "");
+ RNA_def_struct_sdna(srna, c_type);
RNA_define_verify_sdna(0); /* not in sdna */
/* could wrap more, for now this is enough */
prop = RNA_def_property(srna, "layout", PROP_POINTER, PROP_NONE);
RNA_def_property_struct_type(prop, "UILayout");
- RNA_def_property_pointer_funcs(prop, "rna_PopupMenu_layout_get",
+ RNA_def_property_pointer_funcs(prop, layout_get_fn,
NULL, NULL, NULL);
RNA_define_verify_sdna(1); /* not in sdna */
}
-static void rna_def_piemenu(BlenderRNA *brna)
+static void rna_def_popupmenu(BlenderRNA *brna)
{
- StructRNA *srna;
- PropertyRNA *prop;
-
- srna = RNA_def_struct(brna, "UIPieMenu", NULL);
- RNA_def_struct_ui_text(srna, "PieMenu", "");
- RNA_def_struct_sdna(srna, "uiPieMenu");
-
- RNA_define_verify_sdna(0); /* not in sdna */
-
- /* could wrap more, for now this is enough */
- prop = RNA_def_property(srna, "layout", PROP_POINTER, PROP_NONE);
- RNA_def_property_struct_type(prop, "UILayout");
- RNA_def_property_pointer_funcs(prop, "rna_PieMenu_layout_get",
- NULL, NULL, NULL);
+ rna_def_popup_menu_wrapper(brna, "UIPopupMenu", "uiPopupMenu", "rna_PopupMenu_layout_get");
+}
- RNA_define_verify_sdna(1); /* not in sdna */
+static void rna_def_piemenu(BlenderRNA *brna)
+{
+ rna_def_popup_menu_wrapper(brna, "UIPieMenu", "uiPieMenu", "rna_PieMenu_layout_get");
}
static void rna_def_window_stereo3d(BlenderRNA *brna)
@@ -2048,7 +2043,7 @@ static void rna_def_keyconfig(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem map_type_items[] = {
+ static const EnumPropertyItem map_type_items[] = {
{KMI_TYPE_KEYBOARD, "KEYBOARD", 0, "Keyboard", ""},
{KMI_TYPE_TWEAK, "TWEAK", 0, "Tweak", ""},
{KMI_TYPE_MOUSE, "MOUSE", 0, "Mouse", ""},
diff --git a/source/blender/makesrna/intern/rna_wm_api.c b/source/blender/makesrna/intern/rna_wm_api.c
index 1f23ab938fb..d2cd72b2f1e 100644
--- a/source/blender/makesrna/intern/rna_wm_api.c
+++ b/source/blender/makesrna/intern/rna_wm_api.c
@@ -46,7 +46,7 @@
#include "rna_internal.h" /* own include */
/* confusingm 2 enums mixed up here */
-EnumPropertyItem rna_enum_window_cursor_items[] = {
+const EnumPropertyItem rna_enum_window_cursor_items[] = {
{CURSOR_STD, "DEFAULT", 0, "Default", ""},
{CURSOR_NONE, "NONE", 0, "None", ""},
{CURSOR_WAIT, "WAIT", 0, "Wait", ""},
@@ -87,6 +87,11 @@ static void rna_Operator_report(wmOperator *op, int type, const char *msg)
BKE_report(op->reports, type, msg);
}
+static int rna_Operator_is_repeat(wmOperator *op, bContext *C)
+{
+ return WM_operator_is_repeat(C, op);
+}
+
/* since event isn't needed... */
static void rna_Operator_enum_search_invoke(bContext *C, wmOperator *op)
{
@@ -293,7 +298,7 @@ static void rna_KeyConfig_remove(wmWindowManager *wm, ReportList *reports, Point
}
/* popup menu wrapper */
-static PointerRNA rna_PupMenuBegin(bContext *C, const char *title, int icon)
+static PointerRNA rna_PopMenuBegin(bContext *C, const char *title, int icon)
{
PointerRNA r_ptr;
void *data;
@@ -305,7 +310,7 @@ static PointerRNA rna_PupMenuBegin(bContext *C, const char *title, int icon)
return r_ptr;
}
-static void rna_PupMenuEnd(bContext *C, PointerRNA *handle)
+static void rna_PopMenuEnd(bContext *C, PointerRNA *handle)
{
UI_popup_menu_end(C, handle->data);
}
@@ -454,8 +459,11 @@ void RNA_api_wm(StructRNA *srna)
/* invoke enum */
func = RNA_def_function(srna, "invoke_search_popup", "rna_Operator_enum_search_invoke");
- RNA_def_function_ui_description(func, "Operator search popup invoke (search in values of "
- "operator's type 'prop' EnumProperty, and execute it on confirmation)");
+ RNA_def_function_ui_description(
+ func,
+ "Operator search popup invoke which "
+ "searches values of the operator's :class:`bpy.types.Operator.bl_property` "
+ "(which must be an EnumProperty), executing it on confirmation");
rna_generic_op_invoke(func, 0);
/* invoke functions, for use with python */
@@ -471,7 +479,7 @@ void RNA_api_wm(StructRNA *srna)
/* wrap UI_popup_menu_begin */
- func = RNA_def_function(srna, "pupmenu_begin__internal", "rna_PupMenuBegin");
+ func = RNA_def_function(srna, "popmenu_begin__internal", "rna_PopMenuBegin");
RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_CONTEXT);
parm = RNA_def_string(func, "title", NULL, 0, "", "");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
@@ -483,7 +491,7 @@ void RNA_api_wm(StructRNA *srna)
RNA_def_function_return(func, parm);
/* wrap UI_popup_menu_end */
- func = RNA_def_function(srna, "pupmenu_end__internal", "rna_PupMenuEnd");
+ func = RNA_def_function(srna, "popmenu_end__internal", "rna_PopMenuEnd");
RNA_def_function_flag(func, FUNC_NO_SELF | FUNC_USE_CONTEXT);
parm = RNA_def_pointer(func, "menu", "UIPopupMenu", "", "");
RNA_def_parameter_flags(parm, PROP_NEVER_NULL, PARM_RNAPTR);
@@ -521,6 +529,12 @@ void RNA_api_operator(StructRNA *srna)
parm = RNA_def_string(func, "message", NULL, 0, "Report Message", "");
RNA_def_parameter_flags(parm, 0, PARM_REQUIRED);
+ /* utility, not for registering */
+ func = RNA_def_function(srna, "is_repeat", "rna_Operator_is_repeat");
+ RNA_def_function_flag(func, FUNC_USE_CONTEXT);
+ /* return */
+ parm = RNA_def_boolean(func, "result", 0, "result", "");
+ RNA_def_function_return(func, parm);
/* Registration */
diff --git a/source/blender/makesrna/intern/rna_world.c b/source/blender/makesrna/intern/rna_world.c
index 7c1ef6b0d87..925bc52d06f 100644
--- a/source/blender/makesrna/intern/rna_world.c
+++ b/source/blender/makesrna/intern/rna_world.c
@@ -128,7 +128,7 @@ static void rna_def_world_mtex(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem texco_items[] = {
+ static const EnumPropertyItem texco_items[] = {
{TEXCO_VIEW, "VIEW", 0, "View", "Use view vector for the texture coordinates"},
{TEXCO_GLOB, "GLOBAL", 0, "Global", "Use global coordinates for the texture coordinates (interior mist)"},
{TEXCO_ANGMAP, "ANGMAP", 0, "AngMap", "Use 360 degree angular coordinates, e.g. for spherical light probes"},
@@ -208,27 +208,27 @@ static void rna_def_lighting(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem blend_mode_items[] = {
+ static const EnumPropertyItem blend_mode_items[] = {
{WO_AOMUL, "MULTIPLY", 0, "Multiply", "Multiply direct lighting with ambient occlusion, darkening the result"},
{WO_AOADD, "ADD", 0, "Add", "Add light and shadow"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_color_items[] = {
+ static const EnumPropertyItem prop_color_items[] = {
{WO_AOPLAIN, "PLAIN", 0, "White", "Plain diffuse energy (white.)"},
{WO_AOSKYCOL, "SKY_COLOR", 0, "Sky Color", "Use horizon and zenith color for diffuse energy"},
{WO_AOSKYTEX, "SKY_TEXTURE", 0, "Sky Texture", "Does full Sky texture render for diffuse energy"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_sample_method_items[] = {
+ static const EnumPropertyItem prop_sample_method_items[] = {
{WO_AOSAMP_CONSTANT, "CONSTANT_JITTERED", 0, "Constant Jittered", "Fastest and gives the most noise"},
{WO_AOSAMP_HALTON, "ADAPTIVE_QMC", 0, "Adaptive QMC", "Fast in high-contrast areas"},
{WO_AOSAMP_HAMMERSLEY, "CONSTANT_QMC", 0, "Constant QMC", "Best quality"},
{0, NULL, 0, NULL, NULL}
};
- static EnumPropertyItem prop_gather_method_items[] = {
+ static const EnumPropertyItem prop_gather_method_items[] = {
{WO_AOGATHER_RAYTRACE, "RAYTRACE", 0, "Raytrace", "Accurate, but slow when noise-free results are required"},
{WO_AOGATHER_APPROX, "APPROXIMATE", 0, "Approximate", "Inaccurate, but faster and without noise"},
{0, NULL, 0, NULL, NULL}
@@ -389,7 +389,7 @@ static void rna_def_world_mist(BlenderRNA *brna)
StructRNA *srna;
PropertyRNA *prop;
- static EnumPropertyItem falloff_items[] = {
+ static const EnumPropertyItem falloff_items[] = {
{0, "QUADRATIC", 0, "Quadratic", "Use quadratic progression"},
{1, "LINEAR", 0, "Linear", "Use linear progression"},
{2, "INVERSE_QUADRATIC", 0, "Inverse Quadratic", "Use inverse quadratic progression"},
diff --git a/source/blender/modifiers/CMakeLists.txt b/source/blender/modifiers/CMakeLists.txt
index bacfc177432..a70612447d3 100644
--- a/source/blender/modifiers/CMakeLists.txt
+++ b/source/blender/modifiers/CMakeLists.txt
@@ -93,6 +93,7 @@ set(SRC
intern/MOD_solidify.c
intern/MOD_subsurf.c
intern/MOD_surface.c
+ intern/MOD_surfacedeform.c
intern/MOD_triangulate.c
intern/MOD_util.c
intern/MOD_uvwarp.c
@@ -106,7 +107,6 @@ set(SRC
intern/MOD_wireframe.c
MOD_modifiertypes.h
- intern/MOD_boolean_util.h
intern/MOD_fluidsim_util.h
intern/MOD_meshcache_util.h
intern/MOD_util.h
@@ -124,16 +124,6 @@ if(WITH_ALEMBIC)
)
endif()
-if(WITH_MOD_BOOLEAN)
- add_definitions(-DWITH_MOD_BOOLEAN)
- list(APPEND SRC
- intern/MOD_boolean_util.c
- )
- list(APPEND INC
- ../../../extern/carve
- )
-endif()
-
if(WITH_MOD_REMESH)
add_definitions(-DWITH_MOD_REMESH)
list(APPEND INC
diff --git a/source/blender/modifiers/MOD_modifiertypes.h b/source/blender/modifiers/MOD_modifiertypes.h
index 4c881445893..bf121af2bd1 100644
--- a/source/blender/modifiers/MOD_modifiertypes.h
+++ b/source/blender/modifiers/MOD_modifiertypes.h
@@ -85,6 +85,7 @@ extern ModifierTypeInfo modifierType_DataTransfer;
extern ModifierTypeInfo modifierType_NormalEdit;
extern ModifierTypeInfo modifierType_CorrectiveSmooth;
extern ModifierTypeInfo modifierType_MeshSequenceCache;
+extern ModifierTypeInfo modifierType_SurfaceDeform;
/* MOD_util.c */
void modifier_type_init(ModifierTypeInfo *types[]);
diff --git a/source/blender/modifiers/intern/MOD_armature.c b/source/blender/modifiers/intern/MOD_armature.c
index 2400dbcb898..22ec13cd0a0 100644
--- a/source/blender/modifiers/intern/MOD_armature.c
+++ b/source/blender/modifiers/intern/MOD_armature.c
@@ -64,13 +64,13 @@ static void initData(ModifierData *md)
static void copyData(ModifierData *md, ModifierData *target)
{
+#if 0
ArmatureModifierData *amd = (ArmatureModifierData *) md;
+#endif
ArmatureModifierData *tamd = (ArmatureModifierData *) target;
- tamd->object = amd->object;
- tamd->deformflag = amd->deformflag;
- tamd->multi = amd->multi;
- BLI_strncpy(tamd->defgrp_name, amd->defgrp_name, sizeof(tamd->defgrp_name));
+ modifier_copyData_generic(md, target);
+ tamd->prevCos = NULL;
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
@@ -99,32 +99,24 @@ static void foreachObjectLink(
walk(userData, ob, &amd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ArmatureModifierData *amd = (ArmatureModifierData *) md;
if (amd->object) {
- DagNode *curNode = dag_get_node(forest, amd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, amd->object);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Armature Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ArmatureModifierData *amd = (ArmatureModifierData *)md;
if (amd->object != NULL) {
- DEG_add_object_relation(node, amd->object, DEG_OB_COMP_EVAL_POSE, "Armature Modifier");
- DEG_add_object_relation(node, amd->object, DEG_OB_COMP_TRANSFORM, "Armature Modifier");
+ DEG_add_object_relation(ctx->node, amd->object, DEG_OB_COMP_EVAL_POSE, "Armature Modifier");
+ DEG_add_object_relation(ctx->node, amd->object, DEG_OB_COMP_TRANSFORM, "Armature Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_array.c b/source/blender/modifiers/intern/MOD_array.c
index 2b739dc0093..5119f9e9d8e 100644
--- a/source/blender/modifiers/intern/MOD_array.c
+++ b/source/blender/modifiers/intern/MOD_array.c
@@ -50,6 +50,8 @@
#include "BKE_curve.h"
#include "BKE_library_query.h"
#include "BKE_modifier.h"
+#include "BKE_mesh.h"
+#include "BKE_object_deform.h"
#include "MOD_util.h"
@@ -101,81 +103,58 @@ static void foreachObjectLink(
walk(userData, ob, &amd->offset_ob, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ArrayModifierData *amd = (ArrayModifierData *) md;
if (amd->start_cap) {
- DagNode *curNode = dag_get_node(forest, amd->start_cap);
+ DagNode *curNode = dag_get_node(ctx->forest, amd->start_cap);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->end_cap) {
- DagNode *curNode = dag_get_node(forest, amd->end_cap);
+ DagNode *curNode = dag_get_node(ctx->forest, amd->end_cap);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->curve_ob) {
- DagNode *curNode = dag_get_node(forest, amd->curve_ob);
+ DagNode *curNode = dag_get_node(ctx->forest, amd->curve_ob);
curNode->eval_flags |= DAG_EVAL_NEED_CURVE_PATH;
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
if (amd->offset_ob) {
- DagNode *curNode = dag_get_node(forest, amd->offset_ob);
+ DagNode *curNode = dag_get_node(ctx->forest, amd->offset_ob);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Array Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ArrayModifierData *amd = (ArrayModifierData *)md;
if (amd->start_cap != NULL) {
- DEG_add_object_relation(node, amd->start_cap, DEG_OB_COMP_TRANSFORM, "Array Modifier Start Cap");
+ DEG_add_object_relation(ctx->node, amd->start_cap, DEG_OB_COMP_TRANSFORM, "Array Modifier Start Cap");
+ DEG_add_object_relation(ctx->node, amd->start_cap, DEG_OB_COMP_GEOMETRY, "Array Modifier Start Cap");
}
if (amd->end_cap != NULL) {
- DEG_add_object_relation(node, amd->end_cap, DEG_OB_COMP_TRANSFORM, "Array Modifier End Cap");
+ DEG_add_object_relation(ctx->node, amd->end_cap, DEG_OB_COMP_TRANSFORM, "Array Modifier End Cap");
+ DEG_add_object_relation(ctx->node, amd->end_cap, DEG_OB_COMP_GEOMETRY, "Array Modifier End Cap");
}
if (amd->curve_ob) {
- DEG_add_object_relation(node, amd->curve_ob, DEG_OB_COMP_GEOMETRY, "Array Modifier Curve");
- DEG_add_special_eval_flag(scene->depsgraph, &amd->curve_ob->id, DAG_EVAL_NEED_CURVE_PATH);
+ struct Depsgraph *depsgraph = DEG_get_graph_from_handle(ctx->node);
+ DEG_add_object_relation(ctx->node, amd->curve_ob, DEG_OB_COMP_GEOMETRY, "Array Modifier Curve");
+ DEG_add_special_eval_flag(depsgraph, &amd->curve_ob->id, DAG_EVAL_NEED_CURVE_PATH);
}
if (amd->offset_ob != NULL) {
- DEG_add_object_relation(node, amd->offset_ob, DEG_OB_COMP_TRANSFORM, "Array Modifier Offset");
+ DEG_add_object_relation(ctx->node, amd->offset_ob, DEG_OB_COMP_TRANSFORM, "Array Modifier Offset");
}
}
-static float vertarray_size(const MVert *mvert, int numVerts, int axis)
-{
- int i;
- float min_co, max_co;
-
- /* if there are no vertices, width is 0 */
- if (numVerts == 0) return 0;
-
- /* find the minimum and maximum coordinates on the desired axis */
- min_co = max_co = mvert->co[axis];
- mvert++;
- for (i = 1; i < numVerts; ++i, ++mvert) {
- if (mvert->co[axis] < min_co) min_co = mvert->co[axis];
- if (mvert->co[axis] > max_co) max_co = mvert->co[axis];
- }
-
- return max_co - min_co;
-}
-
BLI_INLINE float sum_v3(const float v[3])
{
return v[0] + v[1] + v[2];
@@ -234,8 +213,8 @@ static void dm_mvert_map_doubles(
source_end = source_start + source_num_verts;
/* build array of MVerts to be tested for merging */
- sorted_verts_target = MEM_mallocN(sizeof(SortVertsElem) * target_num_verts, __func__);
- sorted_verts_source = MEM_mallocN(sizeof(SortVertsElem) * source_num_verts, __func__);
+ sorted_verts_target = MEM_malloc_arrayN(target_num_verts, sizeof(SortVertsElem), __func__);
+ sorted_verts_source = MEM_malloc_arrayN(source_num_verts, sizeof(SortVertsElem), __func__);
/* Copy target vertices index and cos into SortVertsElem array */
svert_from_mvert(sorted_verts_target, mverts + target_start, target_start, target_end);
@@ -336,7 +315,7 @@ static void dm_mvert_map_doubles(
static void dm_merge_transform(
DerivedMesh *result, DerivedMesh *cap_dm, float cap_offset[4][4],
unsigned int cap_verts_index, unsigned int cap_edges_index, int cap_loops_index, int cap_polys_index,
- int cap_nverts, int cap_nedges, int cap_nloops, int cap_npolys)
+ int cap_nverts, int cap_nedges, int cap_nloops, int cap_npolys, int *remap, int remap_len)
{
int *index_orig;
int i;
@@ -344,6 +323,7 @@ static void dm_merge_transform(
MEdge *me;
MLoop *ml;
MPoly *mp;
+ MDeformVert *dvert;
/* needed for subsurf so arrays are allocated */
cap_dm->getVertArray(cap_dm);
@@ -364,6 +344,12 @@ static void dm_merge_transform(
mv->flag = mv->bweight = 0;
}
+ /* remap the vertex groups if necessary */
+ dvert = DM_get_vert_data(result, cap_verts_index, CD_MDEFORMVERT);
+ if (dvert != NULL) {
+ BKE_object_defgroup_index_map_apply(dvert, cap_nverts, remap, remap_len);
+ }
+
/* adjust cap edge vertex indices */
me = CDDM_get_edges(result) + cap_edges_index;
for (i = 0; i < cap_nedges; i++, me++) {
@@ -441,6 +427,11 @@ static DerivedMesh *arrayModifier_doArray(
DerivedMesh *result, *start_cap_dm = NULL, *end_cap_dm = NULL;
+ int *vgroup_start_cap_remap = NULL;
+ int vgroup_start_cap_remap_len = 0;
+ int *vgroup_end_cap_remap = NULL;
+ int vgroup_end_cap_remap_len = 0;
+
chunk_nverts = dm->getNumVerts(dm);
chunk_nedges = dm->getNumEdges(dm);
chunk_nloops = dm->getNumLoops(dm);
@@ -449,6 +440,8 @@ static DerivedMesh *arrayModifier_doArray(
count = amd->count;
if (amd->start_cap && amd->start_cap != ob && amd->start_cap->type == OB_MESH) {
+ vgroup_start_cap_remap = BKE_object_defgroup_index_map_create(amd->start_cap, ob, &vgroup_start_cap_remap_len);
+
start_cap_dm = get_dm_for_modifier(amd->start_cap, flag);
if (start_cap_dm) {
start_cap_nverts = start_cap_dm->getNumVerts(start_cap_dm);
@@ -458,6 +451,8 @@ static DerivedMesh *arrayModifier_doArray(
}
}
if (amd->end_cap && amd->end_cap != ob && amd->end_cap->type == OB_MESH) {
+ vgroup_end_cap_remap = BKE_object_defgroup_index_map_create(amd->end_cap, ob, &vgroup_end_cap_remap_len);
+
end_cap_dm = get_dm_for_modifier(amd->end_cap, flag);
if (end_cap_dm) {
end_cap_nverts = end_cap_dm->getNumVerts(end_cap_dm);
@@ -472,12 +467,22 @@ static DerivedMesh *arrayModifier_doArray(
unit_m4(offset);
src_mvert = dm->getVertArray(dm);
- if (amd->offset_type & MOD_ARR_OFF_CONST)
- add_v3_v3v3(offset[3], offset[3], amd->offset);
+ if (amd->offset_type & MOD_ARR_OFF_CONST) {
+ add_v3_v3(offset[3], amd->offset);
+ }
if (amd->offset_type & MOD_ARR_OFF_RELATIVE) {
- for (j = 0; j < 3; j++)
- offset[3][j] += amd->scale[j] * vertarray_size(src_mvert, chunk_nverts, j);
+ float min[3], max[3];
+ const MVert *src_mv;
+
+ INIT_MINMAX(min, max);
+ for (src_mv = src_mvert, j = chunk_nverts; j--; src_mv++) {
+ minmax_v3v3_v3(min, max, src_mv->co);
+ }
+
+ for (j = 3; j--; ) {
+ offset[3][j] += amd->scale[j] * (max[j] - min[j]);
+ }
}
if (use_offset_ob) {
@@ -545,7 +550,7 @@ static DerivedMesh *arrayModifier_doArray(
if (use_merge) {
/* Will need full_doubles_map for handling merge */
- full_doubles_map = MEM_mallocN(sizeof(int) * result_nverts, "mod array doubles map");
+ full_doubles_map = MEM_malloc_arrayN(result_nverts, sizeof(int), "mod array doubles map");
copy_vn_i(full_doubles_map, result_nverts, -1);
}
@@ -555,8 +560,8 @@ static DerivedMesh *arrayModifier_doArray(
DM_copy_loop_data(dm, result, 0, 0, chunk_nloops);
DM_copy_poly_data(dm, result, 0, 0, chunk_npolys);
- /* subsurf for eg wont have mesh data in the
- * now add mvert/medge/mface layers */
+ /* Subsurf for eg wont have mesh data in the custom data arrays.
+ * now add mvert/medge/mpoly layers. */
if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) {
dm->copyVertArray(dm, result_dm_verts);
@@ -662,6 +667,26 @@ static DerivedMesh *arrayModifier_doArray(
}
}
+ /* handle UVs */
+ if (chunk_nloops > 0 && is_zero_v2(amd->uv_offset) == false) {
+ const int totuv = CustomData_number_of_layers(&result->loopData, CD_MLOOPUV);
+ for (i = 0; i < totuv; i++) {
+ MLoopUV *dmloopuv = CustomData_get_layer_n(&result->loopData, CD_MLOOPUV, i);
+ dmloopuv += chunk_nloops;
+ for (c = 1; c < count; c++) {
+ const float uv_offset[2] = {
+ amd->uv_offset[0] * (float)c,
+ amd->uv_offset[1] * (float)c,
+ };
+ int l_index = chunk_nloops;
+ for (; l_index-- != 0; dmloopuv++) {
+ dmloopuv->uv[0] += uv_offset[0];
+ dmloopuv->uv[1] += uv_offset[1];
+ }
+ }
+ }
+ }
+
last_chunk_start = (count - 1) * chunk_nverts;
last_chunk_nverts = chunk_nverts;
@@ -690,7 +715,8 @@ static DerivedMesh *arrayModifier_doArray(
result_nedges - start_cap_nedges - end_cap_nedges,
result_nloops - start_cap_nloops - end_cap_nloops,
result_npolys - start_cap_npolys - end_cap_npolys,
- start_cap_nverts, start_cap_nedges, start_cap_nloops, start_cap_npolys);
+ start_cap_nverts, start_cap_nedges, start_cap_nloops, start_cap_npolys,
+ vgroup_start_cap_remap, vgroup_start_cap_remap_len);
/* Identify doubles with first chunk */
if (use_merge) {
dm_mvert_map_doubles(
@@ -714,7 +740,8 @@ static DerivedMesh *arrayModifier_doArray(
result_nedges - end_cap_nedges,
result_nloops - end_cap_nloops,
result_npolys - end_cap_npolys,
- end_cap_nverts, end_cap_nedges, end_cap_nloops, end_cap_npolys);
+ end_cap_nverts, end_cap_nedges, end_cap_nloops, end_cap_npolys,
+ vgroup_end_cap_remap, vgroup_end_cap_remap_len);
/* Identify doubles with last chunk */
if (use_merge) {
dm_mvert_map_doubles(
@@ -762,6 +789,13 @@ static DerivedMesh *arrayModifier_doArray(
result->dirty |= DM_DIRTY_NORMALS;
}
+ if (vgroup_start_cap_remap) {
+ MEM_freeN(vgroup_start_cap_remap);
+ }
+ if (vgroup_end_cap_remap) {
+ MEM_freeN(vgroup_end_cap_remap);
+ }
+
return result;
}
diff --git a/source/blender/modifiers/intern/MOD_bevel.c b/source/blender/modifiers/intern/MOD_bevel.c
index 5874029ae08..93dc0203f83 100644
--- a/source/blender/modifiers/intern/MOD_bevel.c
+++ b/source/blender/modifiers/intern/MOD_bevel.c
@@ -65,19 +65,11 @@ static void initData(ModifierData *md)
static void copyData(ModifierData *md, ModifierData *target)
{
+#if 0
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->mat = bmd->mat;
- tbmd->profile = bmd->profile;
- tbmd->bevel_angle = bmd->bevel_angle;
- BLI_strncpy(tbmd->defgrp_name, bmd->defgrp_name, sizeof(tbmd->defgrp_name));
+#endif
+ modifier_copyData_generic(md, target);
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
diff --git a/source/blender/modifiers/intern/MOD_boolean.c b/source/blender/modifiers/intern/MOD_boolean.c
index f828bc68857..93c4d83870a 100644
--- a/source/blender/modifiers/intern/MOD_boolean.c
+++ b/source/blender/modifiers/intern/MOD_boolean.c
@@ -33,10 +33,6 @@
*/
// #ifdef DEBUG_TIME
-#define USE_BMESH
-#ifdef WITH_MOD_BOOLEAN
-# define USE_CARVE WITH_MOD_BOOLEAN
-#endif
#include <stdio.h>
@@ -51,31 +47,28 @@
#include "depsgraph_private.h"
-#include "MOD_boolean_util.h"
#include "MOD_util.h"
-#ifdef USE_BMESH
#include "BLI_alloca.h"
#include "BLI_math_geom.h"
#include "BKE_material.h"
+#include "BKE_global.h" /* only to check G.debug */
#include "MEM_guardedalloc.h"
#include "bmesh.h"
#include "bmesh_tools.h"
#include "tools/bmesh_intersect.h"
-#endif
#ifdef DEBUG_TIME
-#include "PIL_time.h"
-#include "PIL_time_utildefines.h"
+# include "PIL_time.h"
+# include "PIL_time_utildefines.h"
#endif
static void initData(ModifierData *md)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
- bmd->solver = eBooleanModifierSolver_BMesh;
bmd->double_threshold = 1e-6f;
}
@@ -104,39 +97,29 @@ static void foreachObjectLink(
walk(userData, ob, &bmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
BooleanModifierData *bmd = (BooleanModifierData *) md;
if (bmd->object) {
- DagNode *curNode = dag_get_node(forest, bmd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, bmd->object);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Boolean Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
BooleanModifierData *bmd = (BooleanModifierData *)md;
if (bmd->object != NULL) {
- DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
- DEG_add_object_relation(node, bmd->object, DEG_OB_COMP_GEOMETRY, "Boolean Modifier");
+ DEG_add_object_relation(ctx->node, bmd->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
+ DEG_add_object_relation(ctx->node, bmd->object, DEG_OB_COMP_GEOMETRY, "Boolean Modifier");
}
/* We need own transformation as well. */
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Boolean Modifier");
}
-#if defined(USE_CARVE) || defined(USE_BMESH)
-
static DerivedMesh *get_quick_derivedMesh(
Object *ob_self, DerivedMesh *dm_self,
Object *ob_other, DerivedMesh *dm_other,
@@ -183,13 +166,7 @@ static DerivedMesh *get_quick_derivedMesh(
return result;
}
-#endif /* defined(USE_CARVE) || defined(USE_BMESH) */
-
-
-/* -------------------------------------------------------------------- */
-/* BMESH */
-#ifdef USE_BMESH
/* has no meaning for faces, do this so we can tell which face is which */
#define BM_FACE_TAG BM_ELEM_DRAW
@@ -202,7 +179,7 @@ static int bm_face_isect_pair(BMFace *f, void *UNUSED(user_data))
return BM_elem_flag_test(f, BM_FACE_TAG) ? 1 : 0;
}
-static DerivedMesh *applyModifier_bmesh(
+static DerivedMesh *applyModifier(
ModifierData *md, Object *ob,
DerivedMesh *dm,
ModifierApplyFlag flag)
@@ -224,6 +201,8 @@ static DerivedMesh *applyModifier_bmesh(
result = get_quick_derivedMesh(ob, dm, bmd->object, dm_other, bmd->operation);
if (result == NULL) {
+ const bool is_flip = (is_negative_m4(ob->obmat) != is_negative_m4(bmd->object->obmat));
+
BMesh *bm;
const BMAllocTemplate allocsize = BMALLOC_TEMPLATE_FROM_DM(dm, dm_other);
@@ -235,6 +214,16 @@ static DerivedMesh *applyModifier_bmesh(
&((struct BMeshCreateParams){.use_toolflags = false,}));
DM_to_bmesh_ex(dm_other, bm, true);
+
+ if (UNLIKELY(is_flip)) {
+ const int cd_loop_mdisp_offset = CustomData_get_offset(&bm->ldata, CD_MDISPS);
+ BMIter iter;
+ BMFace *efa;
+ BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
+ BM_face_normal_flip_ex(bm, efa, cd_loop_mdisp_offset, true);
+ }
+ }
+
DM_to_bmesh_ex(dm, bm, true);
/* main bmesh intersection setup */
@@ -244,9 +233,9 @@ static DerivedMesh *applyModifier_bmesh(
int tottri;
BMLoop *(*looptris)[3];
- looptris = MEM_mallocN(sizeof(*looptris) * looptris_tot, __func__);
+ looptris = MEM_malloc_arrayN(looptris_tot, sizeof(*looptris), __func__);
- BM_mesh_calc_tessellation(bm, looptris, &tottri);
+ BM_mesh_calc_tessellation_beauty(bm, looptris, &tottri);
/* postpone this until after tessellating
* so we can use the original normals before the vertex are moved */
@@ -262,7 +251,6 @@ static DerivedMesh *applyModifier_bmesh(
invert_m4_m4(imat, ob->obmat);
mul_m4_m4m4(omat, imat, bmd->object->obmat);
-
BMVert *eve;
i = 0;
BM_ITER_MESH (eve, &iter, bm, BM_VERTS_OF_MESH) {
@@ -275,8 +263,13 @@ static DerivedMesh *applyModifier_bmesh(
/* we need face normals because of 'BM_face_split_edgenet'
* we could calculate on the fly too (before calling split). */
{
- float nmat[4][4];
- invert_m4_m4(nmat, omat);
+ float nmat[3][3];
+ copy_m3_m4(nmat, omat);
+ invert_m3(nmat);
+
+ if (UNLIKELY(is_flip)) {
+ negate_m3(nmat);
+ }
const short ob_src_totcol = bmd->object->totcol;
short *material_remap = BLI_array_alloca(material_remap, ob_src_totcol ? ob_src_totcol : 1);
@@ -286,7 +279,7 @@ static DerivedMesh *applyModifier_bmesh(
BMFace *efa;
i = 0;
BM_ITER_MESH (efa, &iter, bm, BM_FACES_OF_MESH) {
- mul_transposed_mat3_m4_v3(nmat, efa->no);
+ mul_transposed_m3_v3(nmat, efa->no);
normalize_v3(efa->no);
BM_elem_flag_enable(efa, BM_FACE_TAG); /* temp tag to test which side split faces are from */
@@ -306,11 +299,17 @@ static DerivedMesh *applyModifier_bmesh(
* currently this is ok for 'BM_mesh_intersect' */
// BM_mesh_normals_update(bm);
- /* change for testing */
bool use_separate = false;
bool use_dissolve = true;
bool use_island_connect = true;
+ /* change for testing */
+ if (G.debug & G_DEBUG) {
+ use_separate = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_Separate) != 0;
+ use_dissolve = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoDissolve) == 0;
+ use_island_connect = (bmd->bm_flag & eBooleanModifierBMeshFlag_BMesh_NoConnectRegions) == 0;
+ }
+
BM_mesh_intersect(
bm,
looptris, tottri,
@@ -319,6 +318,7 @@ static DerivedMesh *applyModifier_bmesh(
use_separate,
use_dissolve,
use_island_connect,
+ false,
bmd->operation,
bmd->double_threshold);
@@ -348,66 +348,6 @@ static DerivedMesh *applyModifier_bmesh(
return dm;
}
-#endif /* USE_BMESH */
-
-
-/* -------------------------------------------------------------------- */
-/* CARVE */
-
-#ifdef USE_CARVE
-static DerivedMesh *applyModifier_carve(
- ModifierData *md, Object *ob,
- DerivedMesh *derivedData,
- ModifierApplyFlag flag)
-{
- BooleanModifierData *bmd = (BooleanModifierData *) md;
- DerivedMesh *dm;
-
- if (!bmd->object)
- return derivedData;
-
- dm = get_dm_for_modifier(bmd->object, flag);
-
- if (dm) {
- DerivedMesh *result;
-
- /* when one of objects is empty (has got no faces) we could speed up
- * calculation a bit returning one of objects' derived meshes (or empty one)
- * Returning mesh is depended on modifiers operation (sergey) */
- result = get_quick_derivedMesh(ob, derivedData, bmd->object, dm, bmd->operation);
-
- if (result == NULL) {
-#ifdef DEBUG_TIME
- TIMEIT_START(boolean_carve);
-#endif
-
- result = NewBooleanDerivedMesh(dm, bmd->object, derivedData, ob,
- 1 + bmd->operation);
-#ifdef DEBUG_TIME
- TIMEIT_END(boolean_carve);
-#endif
- }
-
- /* if new mesh returned, return it; otherwise there was
- * an error, so delete the modifier object */
- if (result)
- return result;
- else
- modifier_setError(md, "Cannot execute boolean operation");
- }
-
- return derivedData;
-}
-#endif /* USE_CARVE */
-
-
-static DerivedMesh *applyModifier_nop(
- ModifierData *UNUSED(md), Object *UNUSED(ob),
- DerivedMesh *derivedData,
- ModifierApplyFlag UNUSED(flag))
-{
- return derivedData;
-}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
{
@@ -418,28 +358,6 @@ static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(
return dataMask;
}
-static DerivedMesh *applyModifier(
- ModifierData *md, Object *ob,
- DerivedMesh *derivedData,
- ModifierApplyFlag flag)
-{
- BooleanModifierData *bmd = (BooleanModifierData *)md;
-
- switch (bmd->solver) {
-#ifdef USE_CARVE
- case eBooleanModifierSolver_Carve:
- return applyModifier_carve(md, ob, derivedData, flag);
-#endif
-#ifdef USE_BMESH
- case eBooleanModifierSolver_BMesh:
- return applyModifier_bmesh(md, ob, derivedData, flag);
-#endif
- default:
- return applyModifier_nop(md, ob, derivedData, flag);
- }
-}
-
-
ModifierTypeInfo modifierType_Boolean = {
/* name */ "Boolean",
/* structName */ "BooleanModifierData",
diff --git a/source/blender/modifiers/intern/MOD_boolean_util.c b/source/blender/modifiers/intern/MOD_boolean_util.c
deleted file mode 100644
index 061b1198f7e..00000000000
--- a/source/blender/modifiers/intern/MOD_boolean_util.c
+++ /dev/null
@@ -1,787 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) Blender Foundation
- * All rights reserved.
- *
- * Contributor(s): Sergey Sharybin.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/modifiers/intern/MOD_boolean_util.c
- * \ingroup modifiers
- */
-
-#include "MEM_guardedalloc.h"
-
-#include "DNA_material_types.h"
-#include "DNA_meshdata_types.h"
-#include "DNA_object_types.h"
-
-#include "BLI_utildefines.h"
-#include "BLI_alloca.h"
-#include "BLI_ghash.h"
-#include "BLI_math.h"
-
-#include "BKE_cdderivedmesh.h"
-#include "BKE_material.h"
-
-#include "MOD_boolean_util.h"
-
-#include "carve-capi.h"
-
-/* Adopted from BM_loop_interp_from_face(),
- *
- * Transform matrix is used in cases when target coordinate needs
- * to be converted to source space (namely when interpolating
- * boolean result loops from second operand).
- *
- * TODO(sergey): Consider making it a generic function in DerivedMesh.c.
- */
-static void DM_loop_interp_from_poly(DerivedMesh *source_dm,
- MVert *source_mverts,
- MLoop *source_mloops,
- MPoly *source_poly,
- DerivedMesh *target_dm,
- MVert *target_mverts,
- MLoop *target_mloop,
- float transform[4][4],
- int target_loop_index)
-{
- float (*cos_3d)[3] = BLI_array_alloca(cos_3d, source_poly->totloop);
- int *source_indices = BLI_array_alloca(source_indices, source_poly->totloop);
- float *weights = BLI_array_alloca(weights, source_poly->totloop);
- int i;
- int target_vert_index = target_mloop[target_loop_index].v;
- float coord[3];
-
- for (i = 0; i < source_poly->totloop; ++i) {
- MLoop *mloop = &source_mloops[source_poly->loopstart + i];
- source_indices[i] = source_poly->loopstart + i;
- copy_v3_v3(cos_3d[i], source_mverts[mloop->v].co);
- }
-
- if (transform) {
- mul_v3_m4v3(coord, transform, target_mverts[target_vert_index].co);
- }
- else {
- copy_v3_v3(coord, target_mverts[target_vert_index].co);
- }
-
- interp_weights_poly_v3(weights, cos_3d, source_poly->totloop, coord);
-
- DM_interp_loop_data(source_dm, target_dm, source_indices, weights,
- source_poly->totloop, target_loop_index);
-}
-
-typedef struct DMArrays {
- MVert *mvert;
- MEdge *medge;
- MLoop *mloop;
- MPoly *mpoly;
- bool mvert_allocated;
- bool medge_allocated;
- bool mloop_allocated;
- bool mpoly_allocated;
-} DMArrays;
-
-static void dm_arrays_get(DerivedMesh *dm, DMArrays *arrays)
-{
- arrays->mvert = DM_get_vert_array(dm, &arrays->mvert_allocated);
- arrays->medge = DM_get_edge_array(dm, &arrays->medge_allocated);
- arrays->mloop = DM_get_loop_array(dm, &arrays->mloop_allocated);
- arrays->mpoly = DM_get_poly_array(dm, &arrays->mpoly_allocated);
-}
-
-static void dm_arrays_free(DMArrays *arrays)
-{
- if (arrays->mvert_allocated) {
- MEM_freeN(arrays->mvert);
- }
- if (arrays->medge_allocated) {
- MEM_freeN(arrays->medge);
- }
- if (arrays->mloop_allocated) {
- MEM_freeN(arrays->mloop);
- }
- if (arrays->mpoly_allocated) {
- MEM_freeN(arrays->mpoly);
- }
-}
-
-/* **** Importer from derived mesh to Carve **** */
-
-typedef struct ImportMeshData {
- DerivedMesh *dm;
- float obmat[4][4];
- MVert *mvert;
- MEdge *medge;
- MLoop *mloop;
- MPoly *mpoly;
-} ImportMeshData;
-
-/* Get number of vertices. */
-static int importer_GetNumVerts(ImportMeshData *import_data)
-{
- DerivedMesh *dm = import_data->dm;
- return dm->getNumVerts(dm);
-}
-
-/* Get number of edges. */
-static int importer_GetNumEdges(ImportMeshData *import_data)
-{
- DerivedMesh *dm = import_data->dm;
- return dm->getNumEdges(dm);
-}
-
-/* Get number of loops. */
-static int importer_GetNumLoops(ImportMeshData *import_data)
-{
- DerivedMesh *dm = import_data->dm;
- return dm->getNumLoops(dm);
-}
-
-/* Get number of polys. */
-static int importer_GetNumPolys(ImportMeshData *import_data)
-{
- DerivedMesh *dm = import_data->dm;
- return dm->getNumPolys(dm);
-}
-
-/* Get 3D coordinate of vertex with given index. */
-static void importer_GetVertCoord(ImportMeshData *import_data, int vert_index, float coord[3])
-{
- MVert *mvert = import_data->mvert;
-
- BLI_assert(vert_index >= 0 && vert_index < import_data->dm->getNumVerts(import_data->dm));
-
- mul_v3_m4v3(coord, import_data->obmat, mvert[vert_index].co);
-}
-
-/* Get index of vertices which are adjucent to edge specified by it's index. */
-static void importer_GetEdgeVerts(ImportMeshData *import_data, int edge_index, int *v1, int *v2)
-{
- MEdge *medge = &import_data->medge[edge_index];
-
- BLI_assert(edge_index >= 0 && edge_index < import_data->dm->getNumEdges(import_data->dm));
-
- *v1 = medge->v1;
- *v2 = medge->v2;
-}
-
-/* Get number of adjucent vertices to the poly specified by it's index. */
-static int importer_GetPolyNumVerts(ImportMeshData *import_data, int poly_index)
-{
- MPoly *mpoly = import_data->mpoly;
-
- BLI_assert(poly_index >= 0 && poly_index < import_data->dm->getNumPolys(import_data->dm));
-
- return mpoly[poly_index].totloop;
-}
-
-/* Get list of adjucent vertices to the poly specified by it's index. */
-static void importer_GetPolyVerts(ImportMeshData *import_data, int poly_index, int *verts)
-{
- MPoly *mpoly = &import_data->mpoly[poly_index];
- MLoop *mloop = import_data->mloop + mpoly->loopstart;
- int i;
- BLI_assert(poly_index >= 0 && poly_index < import_data->dm->getNumPolys(import_data->dm));
- for (i = 0; i < mpoly->totloop; i++, mloop++) {
- verts[i] = mloop->v;
- }
-}
-
-// Triangulate 2D polygon.
-#if 0
-static int importer_triangulate2DPoly(ImportMeshData *UNUSED(import_data),
- const float (*vertices)[2], int num_vertices,
- unsigned int (*triangles)[3])
-{
- // TODO(sergey): Currently import_data is unused but in the future we could
- // put memory arena there which will reduce amount of allocations happening
- // over the triangulation period.
- //
- // However that's not so much straighforward to do it right now because we
- // also are tu consider threaded import/export.
-
- BLI_assert(num_vertices > 3);
-
- BLI_polyfill_calc(vertices, num_vertices, triangles);
-
- return num_vertices - 2;
-}
-#endif
-
-static CarveMeshImporter MeshImporter = {
- importer_GetNumVerts,
- importer_GetNumEdges,
- importer_GetNumLoops,
- importer_GetNumPolys,
- importer_GetVertCoord,
- importer_GetEdgeVerts,
- importer_GetPolyNumVerts,
- importer_GetPolyVerts,
-
- /* TODO(sergey): We don't use BLI_polyfill_calc() because it tends
- * to generate degenerated geometry which is fatal for booleans.
- *
- * For now we stick to Carve's triangulation.
- */
- NULL, /* importer_triangulate2DPoly */
-};
-
-/* **** Exporter from Carve to derived mesh **** */
-
-typedef struct ExportMeshData {
- DerivedMesh *dm;
- float obimat[4][4];
- MVert *mvert;
- MEdge *medge;
- MLoop *mloop;
- MPoly *mpoly;
- int *vert_origindex;
- int *edge_origindex;
- int *poly_origindex;
- int *loop_origindex;
-
- /* Objects and derived meshes of left and right operands.
- * Used for custom data merge and interpolation.
- */
- Object *ob_left;
- Object *ob_right;
- DerivedMesh *dm_left;
- DerivedMesh *dm_right;
- MVert *mvert_left;
- MEdge *medge_left;
- MLoop *mloop_left;
- MPoly *mpoly_left;
- MVert *mvert_right;
- MEdge *medge_right;
- MLoop *mloop_right;
- MPoly *mpoly_right;
-
- float left_to_right_mat[4][4];
-
- /* Hash to map materials from right object to result. */
- GHash *material_hash;
-} ExportMeshData;
-
-BLI_INLINE Object *which_object(ExportMeshData *export_data, int which_mesh)
-{
- Object *object = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- object = export_data->ob_left;
- break;
- case CARVE_MESH_RIGHT:
- object = export_data->ob_right;
- break;
- }
- return object;
-}
-
-BLI_INLINE DerivedMesh *which_dm(ExportMeshData *export_data, int which_mesh)
-{
- DerivedMesh *dm = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- dm = export_data->dm_left;
- break;
- case CARVE_MESH_RIGHT:
- dm = export_data->dm_right;
- break;
- }
- return dm;
-}
-
-BLI_INLINE MVert *which_mvert(ExportMeshData *export_data, int which_mesh)
-{
- MVert *mvert = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- mvert = export_data->mvert_left;
- break;
- case CARVE_MESH_RIGHT:
- mvert = export_data->mvert_right;
- break;
- }
- return mvert;
-}
-
-BLI_INLINE MEdge *which_medge(ExportMeshData *export_data, int which_mesh)
-{
- MEdge *medge = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- medge = export_data->medge_left;
- break;
- case CARVE_MESH_RIGHT:
- medge = export_data->medge_right;
- break;
- }
- return medge;
-}
-
-BLI_INLINE MLoop *which_mloop(ExportMeshData *export_data, int which_mesh)
-{
- MLoop *mloop = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- mloop = export_data->mloop_left;
- break;
- case CARVE_MESH_RIGHT:
- mloop = export_data->mloop_right;
- break;
- }
- return mloop;
-}
-
-BLI_INLINE MPoly *which_mpoly(ExportMeshData *export_data, int which_mesh)
-{
- MPoly *mpoly = NULL;
- switch (which_mesh) {
- case CARVE_MESH_LEFT:
- mpoly = export_data->mpoly_left;
- break;
- case CARVE_MESH_RIGHT:
- mpoly = export_data->mpoly_right;
- break;
- }
- return mpoly;
-}
-
-/* Create new external mesh */
-static void exporter_InitGeomArrays(ExportMeshData *export_data,
- int num_verts, int num_edges,
- int num_loops, int num_polys)
-{
- DerivedMesh *dm = CDDM_new(num_verts, num_edges, 0,
- num_loops, num_polys);
- DerivedMesh *dm_left = export_data->dm_left,
- *dm_right = export_data->dm_right;
-
- /* Mask for custom data layers to be merged from operands. */
- CustomDataMask merge_mask = CD_MASK_DERIVEDMESH & ~CD_MASK_ORIGINDEX;
-
- export_data->dm = dm;
- export_data->mvert = dm->getVertArray(dm);
- export_data->medge = dm->getEdgeArray(dm);
- export_data->mloop = dm->getLoopArray(dm);
- export_data->mpoly = dm->getPolyArray(dm);
-
- /* Merge custom data layers from operands.
- *
- * Will only create custom data layers for all the layers which appears in
- * the operand. Data for those layers will not be allocated or initialized.
- */
-
- CustomData_merge(&dm_left->loopData, &dm->loopData, merge_mask, CD_DEFAULT, num_loops);
- CustomData_merge(&dm_right->loopData, &dm->loopData, merge_mask, CD_DEFAULT, num_loops);
-
- CustomData_merge(&dm_left->polyData, &dm->polyData, merge_mask, CD_DEFAULT, num_polys);
- CustomData_merge(&dm_right->polyData, &dm->polyData, merge_mask, CD_DEFAULT, num_polys);
-
- CustomData_merge(&dm_left->edgeData, &dm->edgeData, merge_mask, CD_DEFAULT, num_edges);
- CustomData_merge(&dm_right->edgeData, &dm->edgeData, merge_mask, CD_DEFAULT, num_edges);
-
- export_data->vert_origindex = dm->getVertDataArray(dm, CD_ORIGINDEX);
- export_data->edge_origindex = dm->getEdgeDataArray(dm, CD_ORIGINDEX);
- export_data->poly_origindex = dm->getPolyDataArray(dm, CD_ORIGINDEX);
- export_data->loop_origindex = dm->getLoopDataArray(dm, CD_ORIGINDEX);
-}
-
-/* Set coordinate of vertex with given index. */
-static void exporter_SetVert(ExportMeshData *export_data,
- int vert_index, float coord[3],
- int which_orig_mesh, int orig_vert_index)
-{
- DerivedMesh *dm = export_data->dm;
- DerivedMesh *dm_orig;
- MVert *mvert = export_data->mvert;
-
- BLI_assert(vert_index >= 0 && vert_index <= dm->getNumVerts(dm));
-
- dm_orig = which_dm(export_data, which_orig_mesh);
- if (dm_orig) {
- BLI_assert(orig_vert_index >= 0 && orig_vert_index < dm_orig->getNumVerts(dm_orig));
- mvert[vert_index] = which_mvert(export_data, which_orig_mesh)[orig_vert_index];
- CustomData_copy_data(&dm_orig->vertData, &dm->vertData, orig_vert_index, vert_index, 1);
- }
-
- /* Set original index of the vertex. */
- if (export_data->vert_origindex) {
- if (which_orig_mesh == CARVE_MESH_LEFT) {
- export_data->vert_origindex[vert_index] = orig_vert_index;
- }
- else {
- export_data->vert_origindex[vert_index] = ORIGINDEX_NONE;
- }
- }
-
- mul_v3_m4v3(mvert[vert_index].co, export_data->obimat, coord);
-}
-
-/* Set vertices which are adjucent to the edge specified by it's index. */
-static void exporter_SetEdge(ExportMeshData *export_data,
- int edge_index, int v1, int v2,
- int which_orig_mesh, int orig_edge_index)
-{
- DerivedMesh *dm = export_data->dm;
- MEdge *medge = &export_data->medge[edge_index];
- DerivedMesh *dm_orig;
-
- BLI_assert(edge_index >= 0 && edge_index < dm->getNumEdges(dm));
- BLI_assert(v1 >= 0 && v1 < dm->getNumVerts(dm));
- BLI_assert(v2 >= 0 && v2 < dm->getNumVerts(dm));
-
- dm_orig = which_dm(export_data, which_orig_mesh);
- if (dm_orig) {
- BLI_assert(orig_edge_index >= 0 && orig_edge_index < dm_orig->getNumEdges(dm_orig));
-
- *medge = which_medge(export_data, which_orig_mesh)[orig_edge_index];
-
- /* Copy all edge layers, including medge. */
- CustomData_copy_data(&dm_orig->edgeData, &dm->edgeData, orig_edge_index, edge_index, 1);
- }
-
- /* Set original index of the edge. */
- if (export_data->edge_origindex) {
- if (which_orig_mesh == CARVE_MESH_LEFT) {
- export_data->edge_origindex[edge_index] = orig_edge_index;
- }
- else {
- export_data->edge_origindex[edge_index] = ORIGINDEX_NONE;
- }
- }
-
- medge->v1 = v1;
- medge->v2 = v2;
-
- medge->flag |= ME_EDGEDRAW | ME_EDGERENDER;
-}
-
-static void setMPolyMaterial(ExportMeshData *export_data,
- MPoly *mpoly,
- int which_orig_mesh)
-{
- Object *orig_object;
- GHash *material_hash;
- Material *orig_mat;
-
- if (which_orig_mesh == CARVE_MESH_LEFT) {
- /* No need to change materian index for faces from left operand */
- return;
- }
-
- material_hash = export_data->material_hash;
- orig_object = which_object(export_data, which_orig_mesh);
-
- /* Set material, based on lookup in hash table. */
- orig_mat = give_current_material(orig_object, mpoly->mat_nr + 1);
-
- if (orig_mat) {
- /* For faces from right operand check if there's requested material
- * in the left operand. And if it is, use index of that material,
- * otherwise fallback to first material (material with index=0).
- */
- if (!BLI_ghash_haskey(material_hash, orig_mat)) {
- int a, mat_nr;
-
- mat_nr = 0;
- for (a = 0; a < export_data->ob_left->totcol; a++) {
- if (give_current_material(export_data->ob_left, a + 1) == orig_mat) {
- mat_nr = a;
- break;
- }
- }
-
- BLI_ghash_insert(material_hash, orig_mat, SET_INT_IN_POINTER(mat_nr));
-
- mpoly->mat_nr = mat_nr;
- }
- else
- mpoly->mat_nr = GET_INT_FROM_POINTER(BLI_ghash_lookup(material_hash, orig_mat));
- }
- else {
- mpoly->mat_nr = 0;
- }
-}
-
-/* Set list of adjucent loops to the poly specified by it's index. */
-static void exporter_SetPoly(ExportMeshData *export_data,
- int poly_index, int start_loop, int num_loops,
- int which_orig_mesh, int orig_poly_index)
-{
- DerivedMesh *dm = export_data->dm;
- MPoly *mpoly = &export_data->mpoly[poly_index];
- DerivedMesh *dm_orig;
- int i;
-
- /* Poly is always to be either from left or right operand. */
- dm_orig = which_dm(export_data, which_orig_mesh);
-
- BLI_assert(poly_index >= 0 && poly_index < dm->getNumPolys(dm));
- BLI_assert(start_loop >= 0 && start_loop <= dm->getNumLoops(dm) - num_loops);
- BLI_assert(num_loops >= 3);
- BLI_assert(dm_orig != NULL);
- BLI_assert(orig_poly_index >= 0 && orig_poly_index < dm_orig->getNumPolys(dm_orig));
-
- /* Copy all poly layers, including mpoly. */
- *mpoly = which_mpoly(export_data, which_orig_mesh)[orig_poly_index];
- CustomData_copy_data(&dm_orig->polyData, &dm->polyData, orig_poly_index, poly_index, 1);
-
- /* Set material of the curren poly.
- * This would re-map materials from right operand to materials from the
- * left one as well.
- */
- setMPolyMaterial(export_data, mpoly, which_orig_mesh);
-
- /* Set original index of the poly. */
- if (export_data->poly_origindex) {
- if (which_orig_mesh == CARVE_MESH_LEFT) {
- export_data->poly_origindex[poly_index] = orig_poly_index;
- }
- else {
- export_data->poly_origindex[poly_index] = ORIGINDEX_NONE;
- }
- }
-
- /* Set poly data itself. */
- mpoly->loopstart = start_loop;
- mpoly->totloop = num_loops;
-
- /* Interpolate data for poly loops. */
- {
- MVert *source_mverts = which_mvert(export_data, which_orig_mesh);
- MLoop *source_mloops = which_mloop(export_data, which_orig_mesh);
- MPoly *source_mpolys = which_mpoly(export_data, which_orig_mesh);
- MPoly *source_poly = &source_mpolys[orig_poly_index];
- MVert *target_mverts = export_data->mvert;
- MLoop *target_mloops = export_data->mloop;
- float (*transform)[4] = NULL;
-
- if (which_orig_mesh == CARVE_MESH_RIGHT) {
- transform = export_data->left_to_right_mat;
- }
-
- for (i = 0; i < mpoly->totloop; i++) {
- DM_loop_interp_from_poly(dm_orig,
- source_mverts,
- source_mloops,
- source_poly,
- dm,
- target_mverts,
- target_mloops,
- transform,
- i + mpoly->loopstart);
- }
- }
-}
-
-/* Set list vertex and edge which are adjucent to loop with given index. */
-static void exporter_SetLoop(ExportMeshData *export_data,
- int loop_index, int vertex, int edge,
- int which_orig_mesh, int orig_loop_index)
-{
- DerivedMesh *dm = export_data->dm;
- MLoop *mloop = &export_data->mloop[loop_index];
- DerivedMesh *dm_orig;
-
- BLI_assert(loop_index >= 0 && loop_index < dm->getNumLoops(dm));
- BLI_assert(vertex >= 0 && vertex < dm->getNumVerts(dm));
- BLI_assert(edge >= 0 && vertex < dm->getNumEdges(dm));
-
- dm_orig = which_dm(export_data, which_orig_mesh);
- if (dm_orig) {
- BLI_assert(orig_loop_index >= 0 && orig_loop_index < dm_orig->getNumLoops(dm_orig));
-
- /* Copy all loop layers, including mloop. */
- *mloop = which_mloop(export_data, which_orig_mesh)[orig_loop_index];
- CustomData_copy_data(&dm_orig->loopData, &dm->loopData, orig_loop_index, loop_index, 1);
- }
-
- /* Set original index of the loop. */
- if (export_data->loop_origindex) {
- if (which_orig_mesh == CARVE_MESH_LEFT) {
- export_data->loop_origindex[loop_index] = orig_loop_index;
- }
- else {
- export_data->loop_origindex[loop_index] = ORIGINDEX_NONE;
- }
- }
-
- mloop->v = vertex;
- mloop->e = edge;
-}
-
-/* Edge index from a loop index for a given original mesh. */
-static int exporter_MapLoopToEdge(ExportMeshData *export_data,
- int which_mesh, int loop_index)
-{
- DerivedMesh *dm = which_dm(export_data, which_mesh);
- MLoop *mloop = which_mloop(export_data, which_mesh);
-
- (void) dm; /* Unused in release builds. */
-
- BLI_assert(dm != NULL);
- BLI_assert(loop_index >= 0 && loop_index < dm->getNumLoops(dm));
-
- return mloop[loop_index].e;
-}
-
-static CarveMeshExporter MeshExporter = {
- exporter_InitGeomArrays,
- exporter_SetVert,
- exporter_SetEdge,
- exporter_SetPoly,
- exporter_SetLoop,
- exporter_MapLoopToEdge
-};
-
-static int operation_from_optype(int int_op_type)
-{
- int operation;
-
- switch (int_op_type) {
- case 1:
- operation = CARVE_OP_INTERSECTION;
- break;
- case 2:
- operation = CARVE_OP_UNION;
- break;
- case 3:
- operation = CARVE_OP_A_MINUS_B;
- break;
- default:
- BLI_assert(!"Should not happen");
- operation = -1;
- break;
- }
-
- return operation;
-}
-
-static void prepare_import_data(Object *object,
- DerivedMesh *dm,
- const DMArrays *dm_arrays,
- ImportMeshData *import_data)
-{
- import_data->dm = dm;
- copy_m4_m4(import_data->obmat, object->obmat);
- import_data->mvert = dm_arrays->mvert;
- import_data->medge = dm_arrays->medge;
- import_data->mloop = dm_arrays->mloop;
- import_data->mpoly = dm_arrays->mpoly;
-}
-
-static struct CarveMeshDescr *carve_mesh_from_dm(Object *object,
- DerivedMesh *dm,
- const DMArrays *dm_arrays)
-{
- ImportMeshData import_data;
- prepare_import_data(object, dm, dm_arrays, &import_data);
- return carve_addMesh(&import_data, &MeshImporter);
-}
-
-static void prepare_export_data(Object *object_left, DerivedMesh *dm_left, const DMArrays *dm_left_arrays,
- Object *object_right, DerivedMesh *dm_right, const DMArrays *dm_right_arrays,
- ExportMeshData *export_data)
-{
- float object_right_imat[4][4];
-
- invert_m4_m4(export_data->obimat, object_left->obmat);
-
- export_data->ob_left = object_left;
- export_data->ob_right = object_right;
-
- export_data->dm_left = dm_left;
- export_data->dm_right = dm_right;
-
- export_data->mvert_left = dm_left_arrays->mvert;
- export_data->medge_left = dm_left_arrays->medge;
- export_data->mloop_left = dm_left_arrays->mloop;
- export_data->mpoly_left = dm_left_arrays->mpoly;
- export_data->mvert_right = dm_right_arrays->mvert;
- export_data->medge_right = dm_right_arrays->medge;
- export_data->mloop_right = dm_right_arrays->mloop;
- export_data->mpoly_right = dm_right_arrays->mpoly;
-
- export_data->material_hash = BLI_ghash_ptr_new("CSG_mat gh");
-
- /* Matrix to convert coord from left object's loca; space to
- * right object's local space.
- */
- invert_m4_m4(object_right_imat, object_right->obmat);
- mul_m4_m4m4(export_data->left_to_right_mat, object_left->obmat,
- object_right_imat);
-}
-
-DerivedMesh *NewBooleanDerivedMesh(DerivedMesh *dm, struct Object *ob,
- DerivedMesh *dm_select, struct Object *ob_select,
- int int_op_type)
-{
-
- struct CarveMeshDescr *left, *right, *output = NULL;
- DerivedMesh *output_dm = NULL;
- int operation;
- bool result;
- DMArrays dm_left_arrays, dm_right_arrays;
-
- if (dm == NULL || dm_select == NULL) {
- return NULL;
- }
-
- operation = operation_from_optype(int_op_type);
- if (operation == -1) {
- return NULL;
- }
-
- dm_arrays_get(dm_select, &dm_left_arrays);
- dm_arrays_get(dm, &dm_right_arrays);
-
- left = carve_mesh_from_dm(ob_select, dm_select, &dm_left_arrays);
- right = carve_mesh_from_dm(ob, dm, &dm_right_arrays);
-
- result = carve_performBooleanOperation(left, right, operation, &output);
-
- carve_deleteMesh(left);
- carve_deleteMesh(right);
-
- if (result) {
- ExportMeshData export_data;
-
- prepare_export_data(ob_select, dm_select, &dm_left_arrays,
- ob, dm, &dm_right_arrays,
- &export_data);
-
- carve_exportMesh(output, &MeshExporter, &export_data);
- output_dm = export_data.dm;
-
- /* Free memory used by export mesh. */
- BLI_ghash_free(export_data.material_hash, NULL, NULL);
-
- output_dm->cd_flag |= dm->cd_flag | dm_select->cd_flag;
- output_dm->dirty |= DM_DIRTY_NORMALS;
- carve_deleteMesh(output);
- }
-
- dm_arrays_free(&dm_left_arrays);
- dm_arrays_free(&dm_right_arrays);
-
- return output_dm;
-}
diff --git a/source/blender/modifiers/intern/MOD_build.c b/source/blender/modifiers/intern/MOD_build.c
index a364eef2974..f71d14efb2b 100644
--- a/source/blender/modifiers/intern/MOD_build.c
+++ b/source/blender/modifiers/intern/MOD_build.c
@@ -47,6 +47,8 @@
#include "BKE_particle.h"
#include "BKE_scene.h"
+
+
#ifdef _OPENMP
# include "BKE_mesh.h" /* BKE_MESH_OMP_LIMIT */
#endif
@@ -102,9 +104,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
MVert *mvert_src = dm->getVertArray(dm);
- vertMap = MEM_mallocN(sizeof(*vertMap) * numVert_src, "build modifier vertMap");
- edgeMap = MEM_mallocN(sizeof(*edgeMap) * numEdge_src, "build modifier edgeMap");
- faceMap = MEM_mallocN(sizeof(*faceMap) * numPoly_src, "build modifier faceMap");
+ vertMap = MEM_malloc_arrayN(numVert_src, sizeof(*vertMap), "build modifier vertMap");
+ edgeMap = MEM_malloc_arrayN(numEdge_src, sizeof(*edgeMap), "build modifier edgeMap");
+ faceMap = MEM_malloc_arrayN(numPoly_src, sizeof(*faceMap), "build modifier faceMap");
range_vn_i(vertMap, numVert_src, 0);
range_vn_i(edgeMap, numEdge_src, 0);
@@ -152,7 +154,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
numLoops_dst += mp->totloop;
}
- BLI_assert(hash_num == BLI_ghash_size(vertHash));
+ BLI_assert(hash_num == BLI_ghash_len(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)
@@ -185,7 +187,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
*/
medge = medge_src;
hash_num = 0;
- BLI_assert(hash_num == BLI_ghash_size(vertHash));
+ BLI_assert(hash_num == BLI_ghash_len(vertHash));
for (i = 0; i < numEdges_dst; i++) {
void **val_p;
me = medge + edgeMap[i];
@@ -199,11 +201,11 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
hash_num++;
}
}
- BLI_assert(hash_num == BLI_ghash_size(vertHash));
+ BLI_assert(hash_num == BLI_ghash_len(vertHash));
/* get the set of edges that will be in the new mesh */
for (i = 0; i < numEdges_dst; i++) {
- j = BLI_ghash_size(edgeHash);
+ j = BLI_ghash_len(edgeHash);
BLI_ghash_insert(edgeHash, SET_INT_IN_POINTER(j),
SET_INT_IN_POINTER(edgeMap[i]));
@@ -230,8 +232,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
/* now we know the number of verts, edges and faces, we can create
* the mesh
*/
- result = CDDM_from_template(dm, BLI_ghash_size(vertHash),
- BLI_ghash_size(edgeHash), 0, numLoops_dst, numFaces_dst);
+ result = CDDM_from_template(dm, BLI_ghash_len(vertHash),
+ BLI_ghash_len(edgeHash), 0, numLoops_dst, numFaces_dst);
/* copy the vertices across */
GHASH_ITER (gh_iter, vertHash) {
@@ -248,7 +250,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *UNUSED(ob),
}
/* copy the edges across, remapping indices */
- for (i = 0; i < BLI_ghash_size(edgeHash); i++) {
+ for (i = 0; i < BLI_ghash_len(edgeHash); i++) {
MEdge source;
MEdge *dest;
int oldIndex = GET_INT_FROM_POINTER(BLI_ghash_lookup(edgeHash, SET_INT_IN_POINTER(i)));
diff --git a/source/blender/modifiers/intern/MOD_cast.c b/source/blender/modifiers/intern/MOD_cast.c
index ddcf1852dc6..60465df0492 100644
--- a/source/blender/modifiers/intern/MOD_cast.c
+++ b/source/blender/modifiers/intern/MOD_cast.c
@@ -105,32 +105,24 @@ static void foreachObjectLink(
walk(userData, ob, &cmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
CastModifierData *cmd = (CastModifierData *) md;
if (cmd->object) {
- DagNode *curNode = dag_get_node(forest, cmd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, cmd->object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA,
"Cast Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *object,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
CastModifierData *cmd = (CastModifierData *)md;
if (cmd->object != NULL) {
- DEG_add_object_relation(node, cmd->object, DEG_OB_COMP_TRANSFORM, "Cast Modifier");
- DEG_add_object_relation(node, object, DEG_OB_COMP_TRANSFORM, "Cast Modifier");
+ DEG_add_object_relation(ctx->node, cmd->object, DEG_OB_COMP_TRANSFORM, "Cast Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Cast Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_cloth.c b/source/blender/modifiers/intern/MOD_cloth.c
index e8c39770a14..2b181c0fb18 100644
--- a/source/blender/modifiers/intern/MOD_cloth.c
+++ b/source/blender/modifiers/intern/MOD_cloth.c
@@ -117,38 +117,29 @@ static void deformVerts(ModifierData *md, Object *ob, DerivedMesh *derivedData,
dm->release(dm);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- Scene *scene, Object *ob, DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ClothModifierData *clmd = (ClothModifierData *) md;
if (clmd) {
/* Actual code uses get_collisionobjects */
#ifdef WITH_LEGACY_DEPSGRAPH
- dag_add_collision_relations(forest, scene, ob, obNode, clmd->coll_parms->group, ob->lay|scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision");
- dag_add_forcefield_relations(forest, scene, ob, obNode, clmd->sim_parms->effector_weights, true, 0, "Cloth Field");
+ dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, clmd->coll_parms->group, ctx->object->lay|ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision");
+ dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, clmd->sim_parms->effector_weights, true, 0, "Cloth Field");
#else
- (void)forest;
- (void)scene;
- (void)ob;
- (void)obNode;
+ (void)ctx;
#endif
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ClothModifierData *clmd = (ClothModifierData *)md;
if (clmd != NULL) {
/* Actual code uses get_collisionobjects */
- DEG_add_collision_relations(node, scene, ob, clmd->coll_parms->group, ob->lay|scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision");
+ DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, clmd->coll_parms->group, ctx->object->lay|ctx->scene->lay, eModifierType_Collision, NULL, true, "Cloth Collision");
- DEG_add_forcefield_relations(node, scene, ob, clmd->sim_parms->effector_weights, true, 0, "Cloth Field");
+ DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, clmd->sim_parms->effector_weights, true, 0, "Cloth Field");
}
}
diff --git a/source/blender/modifiers/intern/MOD_collision.c b/source/blender/modifiers/intern/MOD_collision.c
index e7ff0a90fbc..0a15799f61a 100644
--- a/source/blender/modifiers/intern/MOD_collision.c
+++ b/source/blender/modifiers/intern/MOD_collision.c
@@ -40,7 +40,6 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
-
#include "BKE_collision.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_global.h"
@@ -48,6 +47,8 @@
#include "BKE_pointcache.h"
#include "BKE_scene.h"
+#include "MOD_modifiertypes.h"
+
static void initData(ModifierData *md)
{
CollisionModifierData *collmd = (CollisionModifierData *) md;
@@ -152,14 +153,12 @@ static void deformVerts(ModifierData *md, Object *ob,
collmd->current_v = MEM_dupallocN(collmd->x); // inter-frame
collmd->mvert_num = mvert_num;
-
- DM_ensure_looptri(dm);
collmd->tri_num = dm->getNumLoopTri(dm);
{
const MLoop *mloop = dm->getLoopArray(dm);
const MLoopTri *looptri = dm->getLoopTriArray(dm);
- MVertTri *tri = MEM_mallocN(sizeof(*tri) * collmd->tri_num, __func__);
+ MVertTri *tri = MEM_malloc_arrayN(collmd->tri_num, sizeof(*tri), __func__);
DM_verttri_from_looptri(tri, mloop, looptri, collmd->tri_num);
collmd->tri = tri;
}
diff --git a/source/blender/modifiers/intern/MOD_correctivesmooth.c b/source/blender/modifiers/intern/MOD_correctivesmooth.c
index 77fd84a2948..08f4588df87 100644
--- a/source/blender/modifiers/intern/MOD_correctivesmooth.c
+++ b/source/blender/modifiers/intern/MOD_correctivesmooth.c
@@ -156,7 +156,7 @@ static void dm_get_boundaries(DerivedMesh *dm, float *smooth_weights)
mpoly_num = (unsigned int)dm->getNumPolys(dm);
medge_num = (unsigned int)dm->getNumEdges(dm);
- boundaries = MEM_callocN(medge_num * sizeof(*boundaries), __func__);
+ boundaries = MEM_calloc_arrayN(medge_num, sizeof(*boundaries), __func__);
/* count the number of adjacent faces */
for (i = 0; i < mpoly_num; i++) {
@@ -199,9 +199,9 @@ static void smooth_iter__simple(
struct SmoothingData_Simple {
float delta[3];
- } *smooth_data = MEM_callocN((size_t)numVerts * sizeof(*smooth_data), __func__);
+ } *smooth_data = MEM_calloc_arrayN(numVerts, sizeof(*smooth_data), __func__);
- vertex_edge_count_div = MEM_callocN((size_t)numVerts * sizeof(float), __func__);
+ vertex_edge_count_div = MEM_calloc_arrayN(numVerts, sizeof(float), __func__);
/* calculate as floats to avoid int->float conversion in #smooth_iter */
for (i = 0; i < numEdges; i++) {
@@ -277,11 +277,11 @@ static void smooth_iter__length_weight(
struct SmoothingData_Weighted {
float delta[3];
float edge_length_sum;
- } *smooth_data = MEM_callocN((size_t)numVerts * sizeof(*smooth_data), __func__);
+ } *smooth_data = MEM_calloc_arrayN(numVerts, sizeof(*smooth_data), __func__);
/* calculate as floats to avoid int->float conversion in #smooth_iter */
- vertex_edge_count = MEM_callocN((size_t)numVerts * sizeof(float), __func__);
+ vertex_edge_count = MEM_calloc_arrayN(numVerts, sizeof(float), __func__);
for (i = 0; i < numEdges; i++) {
vertex_edge_count[edges[i].v1] += 1.0f;
vertex_edge_count[edges[i].v2] += 1.0f;
@@ -382,7 +382,7 @@ static void smooth_verts(
if (dvert || (csmd->flag & MOD_CORRECTIVESMOOTH_PIN_BOUNDARY)) {
- smooth_weights = MEM_mallocN(numVerts * sizeof(float), __func__);
+ smooth_weights = MEM_malloc_arrayN(numVerts, sizeof(float), __func__);
if (dvert) {
dm_get_weights(
@@ -530,7 +530,7 @@ static void calc_deltas(
float (*tangent_spaces)[3][3];
unsigned int i;
- tangent_spaces = MEM_callocN((size_t)(numVerts) * sizeof(float[3][3]), __func__);
+ tangent_spaces = MEM_calloc_arrayN(numVerts, sizeof(float[3][3]), __func__);
if (csmd->delta_cache_num != numVerts) {
MEM_SAFE_FREE(csmd->delta_cache);
@@ -539,7 +539,7 @@ static void calc_deltas(
/* allocate deltas if they have not yet been allocated, otheriwse we will just write over them */
if (!csmd->delta_cache) {
csmd->delta_cache_num = numVerts;
- csmd->delta_cache = MEM_mallocN((size_t)numVerts * sizeof(float[3]), __func__);
+ csmd->delta_cache = MEM_malloc_arrayN(numVerts, sizeof(float[3]), __func__);
}
smooth_verts(csmd, dm, dvert, defgrp_index, smooth_vertex_coords, numVerts);
@@ -575,7 +575,7 @@ static void correctivesmooth_modifier_do(
const bool force_delta_cache_update =
/* XXX, take care! if mesh data its self changes we need to forcefully recalculate deltas */
((csmd->rest_source == MOD_CORRECTIVESMOOTH_RESTSOURCE_ORCO) &&
- (((ID *)ob->data)->tag & LIB_TAG_ID_RECALC));
+ (((ID *)ob->data)->recalc & ID_RECALC));
bool use_only_smooth = (csmd->flag & MOD_CORRECTIVESMOOTH_ONLY_SMOOTH) != 0;
MDeformVert *dvert = NULL;
@@ -680,7 +680,7 @@ static void correctivesmooth_modifier_do(
float (*tangent_spaces)[3][3];
/* calloc, since values are accumulated */
- tangent_spaces = MEM_callocN((size_t)numVerts * sizeof(float[3][3]), __func__);
+ tangent_spaces = MEM_calloc_arrayN(numVerts, sizeof(float[3][3]), __func__);
calc_tangent_spaces(dm, vertexCos, tangent_spaces);
diff --git a/source/blender/modifiers/intern/MOD_curve.c b/source/blender/modifiers/intern/MOD_curve.c
index 09444476bfe..7e16bf450fc 100644
--- a/source/blender/modifiers/intern/MOD_curve.c
+++ b/source/blender/modifiers/intern/MOD_curve.c
@@ -39,7 +39,6 @@
#include "BLI_utildefines.h"
-
#include "BKE_cdderivedmesh.h"
#include "BKE_lattice.h"
#include "BKE_library_query.h"
@@ -48,6 +47,7 @@
#include "depsgraph_private.h"
#include "DEG_depsgraph_build.h"
+#include "MOD_modifiertypes.h"
static void initData(ModifierData *md)
{
@@ -92,28 +92,20 @@ static void foreachObjectLink(
walk(userData, ob, &cmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
CurveModifierData *cmd = (CurveModifierData *) md;
if (cmd->object) {
- DagNode *curNode = dag_get_node(forest, cmd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, cmd->object);
curNode->eval_flags |= DAG_EVAL_NEED_CURVE_PATH;
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Curve Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *object,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
CurveModifierData *cmd = (CurveModifierData *)md;
if (cmd->object != NULL) {
@@ -123,11 +115,12 @@ static void updateDepsgraph(ModifierData *md,
/* TODO(sergey): Currently path is evaluated as a part of modifier stack,
* might be changed in the future.
*/
- DEG_add_object_relation(node, cmd->object, DEG_OB_COMP_GEOMETRY, "Curve Modifier");
- DEG_add_special_eval_flag(scene->depsgraph, &cmd->object->id, DAG_EVAL_NEED_CURVE_PATH);
+ struct Depsgraph *depsgraph = DEG_get_graph_from_handle(ctx->node);
+ DEG_add_object_relation(ctx->node, cmd->object, DEG_OB_COMP_GEOMETRY, "Curve Modifier");
+ DEG_add_special_eval_flag(depsgraph, &cmd->object->id, DAG_EVAL_NEED_CURVE_PATH);
}
- DEG_add_object_relation(node, object, DEG_OB_COMP_TRANSFORM, "Curve Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Curve Modifier");
}
static void deformVerts(ModifierData *md, Object *ob,
diff --git a/source/blender/modifiers/intern/MOD_datatransfer.c b/source/blender/modifiers/intern/MOD_datatransfer.c
index a2210893602..d810978fb0b 100644
--- a/source/blender/modifiers/intern/MOD_datatransfer.c
+++ b/source/blender/modifiers/intern/MOD_datatransfer.c
@@ -127,31 +127,24 @@ static void foreachObjectLink(
walk(userData, ob, &dtmd->ob_source, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DataTransferModifierData *dtmd = (DataTransferModifierData *) md;
DagNode *curNode;
if (dtmd->ob_source) {
- curNode = dag_get_node(forest, dtmd->ob_source);
+ curNode = dag_get_node(ctx->forest, dtmd->ob_source);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"DataTransfer Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DataTransferModifierData *dtmd = (DataTransferModifierData *) md;
if (dtmd->ob_source != NULL) {
- DEG_add_object_relation(node, dtmd->ob_source, DEG_OB_COMP_GEOMETRY, "DataTransfer Modifier");
+ DEG_add_object_relation(ctx->node, dtmd->ob_source, DEG_OB_COMP_GEOMETRY, "DataTransfer Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_decimate.c b/source/blender/modifiers/intern/MOD_decimate.c
index 617ae5a89f3..8b5b0542442 100644
--- a/source/blender/modifiers/intern/MOD_decimate.c
+++ b/source/blender/modifiers/intern/MOD_decimate.c
@@ -142,7 +142,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
const unsigned int vert_tot = dm->getNumVerts(dm);
unsigned int i;
- vweights = MEM_mallocN(vert_tot * sizeof(float), __func__);
+ vweights = MEM_malloc_arrayN(vert_tot, sizeof(float), __func__);
if (dmd->flag & MOD_DECIM_FLAG_INVERT_VGROUP) {
for (i = 0; i < vert_tot; i++) {
diff --git a/source/blender/modifiers/intern/MOD_displace.c b/source/blender/modifiers/intern/MOD_displace.c
index 18f60bab490..72122fae6b4 100644
--- a/source/blender/modifiers/intern/MOD_displace.c
+++ b/source/blender/modifiers/intern/MOD_displace.c
@@ -75,22 +75,10 @@ static void copyData(ModifierData *md, ModifierData *target)
{
#if 0
DisplaceModifierData *dmd = (DisplaceModifierData *) md;
-#endif
DisplaceModifierData *tdmd = (DisplaceModifierData *) target;
+#endif
modifier_copyData_generic(md, target);
-
- if (tdmd->texture) {
- id_us_plus(&tdmd->texture->id);
- }
-}
-
-static void freeData(ModifierData *md)
-{
- DisplaceModifierData *dmd = (DisplaceModifierData *) md;
- if (dmd->texture) {
- id_us_min(&dmd->texture->id);
- }
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
@@ -159,18 +147,14 @@ static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
return ((!dmd->texture && dmd->direction == MOD_DISP_DIR_RGB_XYZ) || dmd->strength == 0.0f);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DisplaceModifierData *dmd = (DisplaceModifierData *) md;
if (dmd->map_object && dmd->texmapping == MOD_DISP_MAP_OBJECT) {
- DagNode *curNode = dag_get_node(forest, dmd->map_object);
+ DagNode *curNode = dag_get_node(ctx->forest, dmd->map_object);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier");
}
@@ -179,26 +163,22 @@ static void updateDepgraph(ModifierData *md, DagForest *forest,
(ELEM(dmd->direction, MOD_DISP_DIR_X, MOD_DISP_DIR_Y, MOD_DISP_DIR_Z, MOD_DISP_DIR_RGB_XYZ) &&
dmd->space == MOD_DISP_SPACE_GLOBAL))
{
- dag_add_relation(forest, obNode, obNode,
+ dag_add_relation(ctx->forest, ctx->obNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Displace Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DisplaceModifierData *dmd = (DisplaceModifierData *)md;
if (dmd->map_object != NULL && dmd->texmapping == MOD_DISP_MAP_OBJECT) {
- DEG_add_object_relation(node, dmd->map_object, DEG_OB_COMP_TRANSFORM, "Displace Modifier");
+ DEG_add_object_relation(ctx->node, dmd->map_object, DEG_OB_COMP_TRANSFORM, "Displace Modifier");
}
if (dmd->texmapping == MOD_DISP_MAP_GLOBAL ||
(ELEM(dmd->direction, MOD_DISP_DIR_X, MOD_DISP_DIR_Y, MOD_DISP_DIR_Z, MOD_DISP_DIR_RGB_XYZ) &&
dmd->space == MOD_DISP_SPACE_GLOBAL))
{
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Displace Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Displace Modifier");
}
}
@@ -217,7 +197,10 @@ typedef struct DisplaceUserdata {
float (*vert_clnors)[3];
} DisplaceUserdata;
-static void displaceModifier_do_task(void *userdata, const int iter)
+static void displaceModifier_do_task(
+ void *__restrict userdata,
+ const int iter,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
DisplaceUserdata *data = (DisplaceUserdata *)userdata;
DisplaceModifierData *dmd = data->dmd;
@@ -335,7 +318,7 @@ static void displaceModifier_do(
modifier_get_vgroup(ob, dm, dmd->defgrp_name, &dvert, &defgrp_index);
if (dmd->texture) {
- tex_co = MEM_callocN(sizeof(*tex_co) * numVerts,
+ tex_co = MEM_calloc_arrayN((size_t)numVerts, sizeof(*tex_co),
"displaceModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)dmd, ob, dm, vertexCos, tex_co, numVerts);
@@ -356,7 +339,7 @@ static void displaceModifier_do(
}
clnors = CustomData_get_layer(ldata, CD_NORMAL);
- vert_clnors = MEM_mallocN(sizeof(*vert_clnors) * (size_t)numVerts, __func__);
+ vert_clnors = MEM_malloc_arrayN(numVerts, sizeof(*vert_clnors), __func__);
BKE_mesh_normals_loop_to_vertex(numVerts, dm->getLoopArray(dm), dm->getNumLoops(dm),
(const float (*)[3])clnors, vert_clnors);
}
@@ -384,8 +367,15 @@ static void displaceModifier_do(
data.vert_clnors = vert_clnors;
if (dmd->texture != NULL) {
data.pool = BKE_image_pool_new();
+ BKE_texture_fetch_images_for_pool(dmd->texture, data.pool);
}
- BLI_task_parallel_range(0, numVerts, &data, displaceModifier_do_task, numVerts > 512);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numVerts > 512);
+ BLI_task_parallel_range(0, numVerts,
+ &data,
+ displaceModifier_do_task,
+ &settings);
if (data.pool != NULL) {
BKE_image_pool_free(data.pool);
@@ -446,7 +436,7 @@ ModifierTypeInfo modifierType_Displace = {
/* applyModifierEM */ NULL,
/* initData */ initData,
/* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
+ /* freeData */ NULL,
/* isDisabled */ isDisabled,
/* updateDepgraph */ updateDepgraph,
/* updateDepsgraph */ updateDepsgraph,
diff --git a/source/blender/modifiers/intern/MOD_dynamicpaint.c b/source/blender/modifiers/intern/MOD_dynamicpaint.c
index 05068b9b597..faf06f2d128 100644
--- a/source/blender/modifiers/intern/MOD_dynamicpaint.c
+++ b/source/blender/modifiers/intern/MOD_dynamicpaint.c
@@ -29,19 +29,21 @@
#include "DNA_dynamicpaint_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_scene_types.h"
#include "BLI_utildefines.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_dynamicpaint.h"
+#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_modifier.h"
#include "depsgraph_private.h"
#include "DEG_depsgraph_build.h"
+#include "MOD_modifiertypes.h"
static void initData(ModifierData *md)
{
@@ -58,6 +60,15 @@ static void copyData(ModifierData *md, ModifierData *target)
DynamicPaintModifierData *tpmd = (DynamicPaintModifierData *)target;
dynamicPaint_Modifier_copy(pmd, tpmd);
+
+ if (tpmd->canvas) {
+ for (DynamicPaintSurface *surface = tpmd->canvas->surfaces.first; surface; surface = surface->next) {
+ id_us_plus((ID *)surface->init_texture);
+ }
+ }
+ if (tpmd->brush) {
+ id_us_plus((ID *)tpmd->brush->mat);
+ }
}
static void freeData(ModifierData *md)
@@ -116,14 +127,10 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
static bool is_brush_cb(Object *UNUSED(ob), ModifierData *pmd)
{
- return ((DynamicPaintModifierData*)pmd)->brush != NULL;
+ return ((DynamicPaintModifierData *)pmd)->brush != NULL;
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DynamicPaintModifierData *pmd = (DynamicPaintModifierData *) md;
@@ -132,37 +139,30 @@ static void updateDepgraph(ModifierData *md, DagForest *forest,
#ifdef WITH_LEGACY_DEPSGRAPH
for (DynamicPaintSurface *surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
if (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) {
- dag_add_forcefield_relations(forest, scene, ob, obNode, surface->effector_weights, true, 0, "Dynamic Paint Field");
+ dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, surface->effector_weights, true, 0, "Dynamic Paint Field");
}
/* Actual code uses custom loop over group/scene without layer checks in dynamicPaint_doStep */
- dag_add_collision_relations(forest, scene, ob, obNode, surface->brush_group, -1, eModifierType_DynamicPaint, is_brush_cb, false, "Dynamic Paint Brush");
+ dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, surface->brush_group, -1, eModifierType_DynamicPaint, is_brush_cb, false, "Dynamic Paint Brush");
}
#else
- (void)forest;
- (void)scene;
- (void)ob;
- (void)obNode;
+ (void)ctx;
#endif
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
DynamicPaintModifierData *pmd = (DynamicPaintModifierData *)md;
/* Add relation from canvases to all brush objects. */
if (pmd->canvas != NULL) {
for (DynamicPaintSurface *surface = pmd->canvas->surfaces.first; surface; surface = surface->next) {
if (surface->effect & MOD_DPAINT_EFFECT_DO_DRIP) {
- DEG_add_forcefield_relations(node, scene, ob, surface->effector_weights, true, 0, "Dynamic Paint Field");
+ DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, surface->effector_weights, true, 0, "Dynamic Paint Field");
}
/* Actual code uses custom loop over group/scene without layer checks in dynamicPaint_doStep */
- DEG_add_collision_relations(node, scene, ob, surface->brush_group, -1, eModifierType_DynamicPaint, is_brush_cb, false, "Dynamic Paint Brush");
+ DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, surface->brush_group, -1, eModifierType_DynamicPaint, is_brush_cb, false, "Dynamic Paint Brush");
}
}
}
diff --git a/source/blender/modifiers/intern/MOD_edgesplit.c b/source/blender/modifiers/intern/MOD_edgesplit.c
index 4441edb299b..a17870f2bf4 100644
--- a/source/blender/modifiers/intern/MOD_edgesplit.c
+++ b/source/blender/modifiers/intern/MOD_edgesplit.c
@@ -48,6 +48,7 @@
#include "DNA_object_types.h"
+#include "MOD_modifiertypes.h"
static DerivedMesh *doEdgeSplit(DerivedMesh *dm, EdgeSplitModifierData *emd)
{
diff --git a/source/blender/modifiers/intern/MOD_explode.c b/source/blender/modifiers/intern/MOD_explode.c
index ca7b3ce8039..c22901f1947 100644
--- a/source/blender/modifiers/intern/MOD_explode.c
+++ b/source/blender/modifiers/intern/MOD_explode.c
@@ -51,9 +51,9 @@
#include "BKE_particle.h"
#include "BKE_scene.h"
-
#include "MEM_guardedalloc.h"
+#include "MOD_modifiertypes.h"
static void initData(ModifierData *md)
{
@@ -119,9 +119,9 @@ static void createFacepa(ExplodeModifierData *emd,
if (emd->facepa)
MEM_freeN(emd->facepa);
- facepa = emd->facepa = MEM_callocN(sizeof(int) * totface, "explode_facepa");
+ facepa = emd->facepa = MEM_calloc_arrayN(totface, sizeof(int), "explode_facepa");
- vertpa = MEM_callocN(sizeof(int) * totvert, "explode_vertpa");
+ vertpa = MEM_calloc_arrayN(totvert, sizeof(int), "explode_vertpa");
/* initialize all faces & verts to no particle */
for (i = 0; i < totface; i++)
@@ -557,8 +557,8 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm)
int totvert = dm->getNumVerts(dm);
int totface = dm->getNumTessFaces(dm);
- int *facesplit = MEM_callocN(sizeof(int) * totface, "explode_facesplit");
- int *vertpa = MEM_callocN(sizeof(int) * totvert, "explode_vertpa2");
+ int *facesplit = MEM_calloc_arrayN(totface, sizeof(int), "explode_facesplit");
+ int *vertpa = MEM_calloc_arrayN(totvert, sizeof(int), "explode_vertpa2");
int *facepa = emd->facepa;
int *fs, totesplit = 0, totfsplit = 0, curdupface = 0;
int i, v1, v2, v3, v4, esplit,
@@ -656,7 +656,7 @@ static DerivedMesh *cutEdges(ExplodeModifierData *emd, DerivedMesh *dm)
* later interpreted as tri's, for this to work right I think we probably
* have to stop using tessface - campbell */
- facepa = MEM_callocN(sizeof(int) * (totface + (totfsplit * 2)), "explode_facepa");
+ facepa = MEM_calloc_arrayN((totface + (totfsplit * 2)), sizeof(int), "explode_facepa");
//memcpy(facepa, emd->facepa, totface*sizeof(int));
emd->facepa = facepa;
diff --git a/source/blender/modifiers/intern/MOD_fluidsim.c b/source/blender/modifiers/intern/MOD_fluidsim.c
index c202c5e1cb4..37eabdf2425 100644
--- a/source/blender/modifiers/intern/MOD_fluidsim.c
+++ b/source/blender/modifiers/intern/MOD_fluidsim.c
@@ -34,7 +34,7 @@
#include "DNA_scene_types.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "DNA_object_types.h"
#include "BLI_utildefines.h"
@@ -47,6 +47,8 @@
#include "DEG_depsgraph_build.h"
#include "MOD_fluidsim_util.h"
+#include "MOD_modifiertypes.h"
+
#include "MEM_guardedalloc.h"
/* Fluidsim */
@@ -68,12 +70,13 @@ static void 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);
- if (tfluidmd->fss && (tfluidmd->fss->meshVelocities != NULL)) {
- tfluidmd->fss->meshVelocities = MEM_dupallocN(tfluidmd->fss->meshVelocities);
+ fluidsim_free(tfluidmd);
+
+ if (fluidmd->fss) {
+ tfluidmd->fss = MEM_dupallocN(fluidmd->fss);
+ if (tfluidmd->fss && (tfluidmd->fss->meshVelocities != NULL)) {
+ tfluidmd->fss->meshVelocities = MEM_dupallocN(tfluidmd->fss->meshVelocities);
+ }
}
}
@@ -100,26 +103,23 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
return result ? result : dm;
}
-static void updateDepgraph(
- ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain), Scene *scene,
- Object *ob, DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
FluidsimModifierData *fluidmd = (FluidsimModifierData *) md;
Base *base;
if (fluidmd && fluidmd->fss) {
if (fluidmd->fss->type == OB_FLUIDSIM_DOMAIN) {
- for (base = scene->base.first; base; base = base->next) {
+ for (base = ctx->scene->base.first; base; base = base->next) {
Object *ob1 = base->object;
- if (ob1 != ob) {
+ if (ob1 != ctx->object) {
FluidsimModifierData *fluidmdtmp =
(FluidsimModifierData *)modifiers_findByType(ob1, eModifierType_Fluidsim);
/* only put dependencies 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");
+ DagNode *curNode = dag_get_node(ctx->forest, ob1);
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Fluidsim Object");
}
}
}
@@ -127,25 +127,21 @@ static void updateDepgraph(
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
FluidsimModifierData *fluidmd = (FluidsimModifierData *) md;
if (fluidmd && fluidmd->fss) {
if (fluidmd->fss->type == OB_FLUIDSIM_DOMAIN) {
Base *base;
- for (base = scene->base.first; base; base = base->next) {
+ for (base = ctx->scene->base.first; base; base = base->next) {
Object *ob1 = base->object;
- if (ob1 != ob) {
+ if (ob1 != ctx->object) {
FluidsimModifierData *fluidmdtmp =
(FluidsimModifierData *)modifiers_findByType(ob1, eModifierType_Fluidsim);
/* Only put dependencies from NON-DOMAIN fluids in here. */
if (fluidmdtmp && fluidmdtmp->fss && (fluidmdtmp->fss->type != OB_FLUIDSIM_DOMAIN)) {
- DEG_add_object_relation(node, ob1, DEG_OB_COMP_TRANSFORM, "Fluidsim Object");
+ DEG_add_object_relation(ctx->node, ob1, DEG_OB_COMP_TRANSFORM, "Fluidsim Object");
}
}
}
diff --git a/source/blender/modifiers/intern/MOD_fluidsim_util.c b/source/blender/modifiers/intern/MOD_fluidsim_util.c
index ffbbb1b0745..72c44121e0b 100644
--- a/source/blender/modifiers/intern/MOD_fluidsim_util.c
+++ b/source/blender/modifiers/intern/MOD_fluidsim_util.c
@@ -40,7 +40,7 @@
#include "DNA_scene_types.h"
#include "DNA_mesh_types.h"
#include "DNA_meshdata_types.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "BLI_blenlib.h"
#include "BLI_math.h"
@@ -48,7 +48,9 @@
#include "BKE_fluidsim.h" /* ensure definitions here match */
#include "BKE_cdderivedmesh.h"
-#include "BKE_global.h" /* G.main->name only */
+#ifdef WITH_MOD_FLUID
+# include "BKE_global.h"
+#endif
#include "MOD_fluidsim_util.h"
#include "MOD_modifiertypes.h"
@@ -78,8 +80,8 @@ void fluidsim_init(FluidsimModifierData *fluidmd)
fss->resolutionxyz = 65;
fss->previewresxyz = 45;
fss->realsize = 0.5;
- fss->guiDisplayMode = 2; // preview
- fss->renderDisplayMode = 3; // render
+ fss->guiDisplayMode = OB_FSDOM_PREVIEW;
+ fss->renderDisplayMode = OB_FSDOM_FINAL;
fss->viscosityValue = 1.0;
fss->viscosityExponent = 6;
@@ -98,7 +100,7 @@ void fluidsim_init(FluidsimModifierData *fluidmd)
/* fluid/inflow settings
* fss->iniVel --> automatically set to 0 */
- modifier_path_init(fss->surfdataPath, sizeof(fss->surfdataPath), "cache_fluid");
+ modifier_path_init(fss->surfdataPath, sizeof(fss->surfdataPath), OB_FLUIDSIM_SURF_DIR_DEFAULT);
/* first init of bounding box */
/* no bounding box needed */
@@ -150,9 +152,8 @@ void fluidsim_free(FluidsimModifierData *fluidmd)
if (fluidmd && fluidmd->fss) {
if (fluidmd->fss->meshVelocities) {
MEM_freeN(fluidmd->fss->meshVelocities);
- fluidmd->fss->meshVelocities = NULL;
}
- MEM_freeN(fluidmd->fss);
+ MEM_SAFE_FREE(fluidmd->fss);
}
return;
@@ -240,7 +241,7 @@ static DerivedMesh *fluidsim_read_obj(const char *filename, const MPoly *mp_exam
return NULL;
}
- normals = MEM_callocN(sizeof(short) * numverts * 3, "fluid_tmp_normals");
+ normals = MEM_calloc_arrayN(numverts, 3 * sizeof(short), "fluid_tmp_normals");
if (!normals) {
if (dm)
dm->release(dm);
@@ -385,7 +386,7 @@ static void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *
if (fss->domainNovecgen > 0) return;
- fss->meshVelocities = MEM_callocN(sizeof(FluidVertexVelocity) * dm->getNumVerts(dm), "Fluidsim_velocities");
+ fss->meshVelocities = MEM_calloc_arrayN(dm->getNumVerts(dm), sizeof(FluidVertexVelocity), "Fluidsim_velocities");
fss->totvert = totvert;
velarray = fss->meshVelocities;
@@ -423,8 +424,6 @@ static void fluidsim_read_vel_cache(FluidsimModifierData *fluidmd, DerivedMesh *
static DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm,
FluidsimModifierData *fluidmd, int framenr, int useRenderParams)
{
- int displaymode = 0;
-
int curFrame = framenr /* - 1 */ /*scene->r.sfra*/; /* start with 0 at start frame */
/* why start with 0 as start frame?? Animations + time are frozen for frame 0 anyway. (See physics_fluid.c for that. - DG */
/* If we start with frame 0, we need to remap all animation channels, too, because they will all be 1 frame late if using frame-1! - DG */
@@ -435,25 +434,23 @@ static DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm,
MPoly *mpoly;
MPoly mp_example = {0};
- if (!useRenderParams) {
- displaymode = fss->guiDisplayMode;
- }
- else {
- displaymode = fss->renderDisplayMode;
- }
+ const int displaymode = useRenderParams ? fss->renderDisplayMode : fss->guiDisplayMode;
switch (displaymode) {
- case 1:
+ case OB_FSDOM_GEOM:
/* just display original object */
return NULL;
- case 2:
+ case OB_FSDOM_PREVIEW:
/* use preview mesh */
BLI_join_dirfile(targetFile, sizeof(targetFile), fss->surfdataPath, OB_FLUIDSIM_SURF_PREVIEW_OBJ_FNAME);
break;
- default: /* 3 */
- /* 3. use final mesh */
+ case OB_FSDOM_FINAL:
+ /* use final mesh */
BLI_join_dirfile(targetFile, sizeof(targetFile), fss->surfdataPath, OB_FLUIDSIM_SURF_FINAL_OBJ_FNAME);
break;
+ default:
+ BLI_assert(!"Wrong fluidsim display type");
+ return NULL;
}
/* offset baked frame */
@@ -494,7 +491,7 @@ static DerivedMesh *fluidsim_read_cache(Object *ob, DerivedMesh *orgdm,
/* 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) {
+ if (displaymode == OB_FSDOM_FINAL) {
fluidsim_read_vel_cache(fluidmd, dm, targetFile);
}
else {
diff --git a/source/blender/modifiers/intern/MOD_hook.c b/source/blender/modifiers/intern/MOD_hook.c
index 56c494ff3c0..80c029157f7 100644
--- a/source/blender/modifiers/intern/MOD_hook.c
+++ b/source/blender/modifiers/intern/MOD_hook.c
@@ -118,39 +118,31 @@ static void foreachObjectLink(
walk(userData, ob, &hmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
HookModifierData *hmd = (HookModifierData *) md;
if (hmd->object) {
- DagNode *curNode = dag_get_node(forest, hmd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, hmd->object);
if (hmd->subtarget[0])
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Hook Modifier");
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Hook Modifier");
else
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA, "Hook Modifier");
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA, "Hook Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
HookModifierData *hmd = (HookModifierData *)md;
if (hmd->object != NULL) {
if (hmd->subtarget[0]) {
- DEG_add_bone_relation(node, hmd->object, hmd->subtarget, DEG_OB_COMP_BONE, "Hook Modifier");
+ DEG_add_bone_relation(ctx->node, hmd->object, hmd->subtarget, DEG_OB_COMP_BONE, "Hook Modifier");
}
- DEG_add_object_relation(node, hmd->object, DEG_OB_COMP_TRANSFORM, "Hook Modifier");
+ DEG_add_object_relation(ctx->node, hmd->object, DEG_OB_COMP_TRANSFORM, "Hook Modifier");
}
/* We need own transformation as well. */
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Hook Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Hook Modifier");
}
struct HookData_cb {
diff --git a/source/blender/modifiers/intern/MOD_laplaciandeform.c b/source/blender/modifiers/intern/MOD_laplaciandeform.c
index ce3fdc4bbe8..91d41a6badd 100644
--- a/source/blender/modifiers/intern/MOD_laplaciandeform.c
+++ b/source/blender/modifiers/intern/MOD_laplaciandeform.c
@@ -29,7 +29,7 @@
*/
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_math.h"
#include "BLI_string.h"
@@ -108,12 +108,12 @@ static LaplacianSystem *initLaplacianSystem(
sys->total_anchors = totalAnchors;
sys->repeat = iterations;
BLI_strncpy(sys->anchor_grp_name, defgrpName, sizeof(sys->anchor_grp_name));
- sys->co = MEM_mallocN(sizeof(float[3]) * totalVerts, "DeformCoordinates");
- sys->no = MEM_callocN(sizeof(float[3]) * totalVerts, "DeformNormals");
- sys->delta = MEM_callocN(sizeof(float[3]) * totalVerts, "DeformDeltas");
- sys->tris = MEM_mallocN(sizeof(int[3]) * totalTris, "DeformFaces");
- sys->index_anchors = MEM_mallocN(sizeof(int) * (totalAnchors), "DeformAnchors");
- sys->unit_verts = MEM_callocN(sizeof(int) * totalVerts, "DeformUnitVerts");
+ sys->co = MEM_malloc_arrayN(totalVerts, sizeof(float[3]), "DeformCoordinates");
+ sys->no = MEM_calloc_arrayN(totalVerts, sizeof(float[3]), "DeformNormals");
+ sys->delta = MEM_calloc_arrayN(totalVerts, sizeof(float[3]), "DeformDeltas");
+ sys->tris = MEM_malloc_arrayN(totalTris, sizeof(int[3]), "DeformFaces");
+ sys->index_anchors = MEM_malloc_arrayN((totalAnchors), sizeof(int), "DeformAnchors");
+ sys->unit_verts = MEM_calloc_arrayN(totalVerts, sizeof(int), "DeformUnitVerts");
return sys;
}
@@ -142,7 +142,7 @@ static void createFaceRingMap(
{
int i, j, totalr = 0;
int *indices, *index_iter;
- MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * mvert_tot, "DeformRingMap");
+ MeshElemMap *map = MEM_calloc_arrayN(mvert_tot, sizeof(MeshElemMap), "DeformRingMap");
const MLoopTri *mlt;
for (i = 0, mlt = mlooptri; i < mtri_tot; i++, mlt++) {
@@ -153,7 +153,7 @@ static void createFaceRingMap(
totalr++;
}
}
- indices = MEM_callocN(sizeof(int) * totalr, "DeformRingIndex");
+ indices = MEM_calloc_arrayN(totalr, sizeof(int), "DeformRingIndex");
index_iter = indices;
for (i = 0; i < mvert_tot; i++) {
map[i].indices = index_iter;
@@ -175,7 +175,7 @@ static void createVertRingMap(
const int mvert_tot, const MEdge *medge, const int medge_tot,
MeshElemMap **r_map, int **r_indices)
{
- MeshElemMap *map = MEM_callocN(sizeof(MeshElemMap) * mvert_tot, "DeformNeighborsMap");
+ MeshElemMap *map = MEM_calloc_arrayN(mvert_tot, sizeof(MeshElemMap), "DeformNeighborsMap");
int i, vid[2], totalr = 0;
int *indices, *index_iter;
const MEdge *me;
@@ -187,7 +187,7 @@ static void createVertRingMap(
map[vid[1]].count++;
totalr += 2;
}
- indices = MEM_callocN(sizeof(int) * totalr, "DeformNeighborsIndex");
+ indices = MEM_calloc_arrayN(totalr, sizeof(int), "DeformNeighborsIndex");
index_iter = indices;
for (i = 0; i < mvert_tot; i++) {
map[i].indices = index_iter;
@@ -521,7 +521,7 @@ static void initSystem(LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh
LaplacianSystem *sys;
if (isValidVertexGroup(lmd, ob, dm)) {
- int *index_anchors = MEM_mallocN(sizeof(int) * numVerts, __func__); /* over-alloc */
+ int *index_anchors = MEM_malloc_arrayN(numVerts, sizeof(int), __func__); /* over-alloc */
const MLoopTri *mlooptri;
const MLoop *mloop;
@@ -539,7 +539,7 @@ static void initSystem(LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh
STACK_PUSH(index_anchors, i);
}
}
- DM_ensure_looptri(dm);
+
total_anchors = STACK_SIZE(index_anchors);
lmd->cache_system = initLaplacianSystem(numVerts, dm->getNumEdges(dm), dm->getNumLoopTri(dm),
total_anchors, lmd->anchor_grp_name, lmd->repeat);
@@ -547,7 +547,7 @@ static void initSystem(LaplacianDeformModifierData *lmd, Object *ob, DerivedMesh
memcpy(sys->index_anchors, index_anchors, sizeof(int) * total_anchors);
memcpy(sys->co, vertexCos, sizeof(float[3]) * numVerts);
MEM_freeN(index_anchors);
- lmd->vertexco = MEM_mallocN(sizeof(float[3]) * numVerts, "ModDeformCoordinates");
+ lmd->vertexco = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "ModDeformCoordinates");
memcpy(lmd->vertexco, vertexCos, sizeof(float[3]) * numVerts);
lmd->total_verts = numVerts;
@@ -631,7 +631,7 @@ static void LaplacianDeformModifier_do(
sys = lmd->cache_system;
if (sysdif) {
if (sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_ANCHORS || sysdif == LAPDEFORM_SYSTEM_ONLY_CHANGE_GROUP) {
- filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempModDeformCoordinates");
+ filevertexCos = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "TempModDeformCoordinates");
memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
MEM_SAFE_FREE(lmd->vertexco);
lmd->total_verts = 0;
@@ -667,7 +667,7 @@ static void LaplacianDeformModifier_do(
lmd->flag &= ~MOD_LAPLACIANDEFORM_BIND;
}
else if (lmd->total_verts > 0 && lmd->total_verts == numVerts) {
- filevertexCos = MEM_mallocN(sizeof(float[3]) * numVerts, "TempDeformCoordinates");
+ filevertexCos = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "TempDeformCoordinates");
memcpy(filevertexCos, lmd->vertexco, sizeof(float[3]) * numVerts);
MEM_SAFE_FREE(lmd->vertexco);
lmd->total_verts = 0;
diff --git a/source/blender/modifiers/intern/MOD_laplaciansmooth.c b/source/blender/modifiers/intern/MOD_laplaciansmooth.c
index f1216ff462a..b3a542f68b7 100644
--- a/source/blender/modifiers/intern/MOD_laplaciansmooth.c
+++ b/source/blender/modifiers/intern/MOD_laplaciansmooth.c
@@ -132,14 +132,14 @@ static LaplacianSystem *init_laplacian_system(int a_numEdges, int a_numPolys, in
sys->numLoops = a_numLoops;
sys->numVerts = a_numVerts;
- sys->eweights = MEM_callocN(sizeof(float) * sys->numEdges, __func__);
- sys->fweights = MEM_callocN(sizeof(float[3]) * sys->numLoops, __func__);
- sys->numNeEd = MEM_callocN(sizeof(short) * sys->numVerts, __func__);
- sys->numNeFa = MEM_callocN(sizeof(short) * sys->numVerts, __func__);
- sys->ring_areas = MEM_callocN(sizeof(float) * sys->numVerts, __func__);
- sys->vlengths = MEM_callocN(sizeof(float) * sys->numVerts, __func__);
- sys->vweights = MEM_callocN(sizeof(float) * sys->numVerts, __func__);
- sys->zerola = MEM_callocN(sizeof(short) * sys->numVerts, __func__);
+ sys->eweights = MEM_calloc_arrayN(sys->numEdges, sizeof(float), __func__);
+ sys->fweights = MEM_calloc_arrayN(sys->numLoops, sizeof(float[3]), __func__);
+ sys->numNeEd = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
+ sys->numNeFa = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
+ sys->ring_areas = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
+ sys->vlengths = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
+ sys->vweights = MEM_calloc_arrayN(sys->numVerts, sizeof(float), __func__);
+ sys->zerola = MEM_calloc_arrayN(sys->numVerts, sizeof(short), __func__);
return sys;
}
diff --git a/source/blender/modifiers/intern/MOD_lattice.c b/source/blender/modifiers/intern/MOD_lattice.c
index dc246084dca..0df6329cf04 100644
--- a/source/blender/modifiers/intern/MOD_lattice.c
+++ b/source/blender/modifiers/intern/MOD_lattice.c
@@ -91,34 +91,26 @@ static void foreachObjectLink(
walk(userData, ob, &lmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
LatticeModifierData *lmd = (LatticeModifierData *) md;
if (lmd->object) {
- DagNode *latNode = dag_get_node(forest, lmd->object);
+ DagNode *latNode = dag_get_node(ctx->forest, lmd->object);
- dag_add_relation(forest, latNode, obNode,
+ dag_add_relation(ctx->forest, latNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Lattice Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *object,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
LatticeModifierData *lmd = (LatticeModifierData *)md;
if (lmd->object != NULL) {
- DEG_add_object_relation(node, lmd->object, DEG_OB_COMP_GEOMETRY, "Lattice Modifier");
- DEG_add_object_relation(node, lmd->object, DEG_OB_COMP_TRANSFORM, "Lattice Modifier");
+ DEG_add_object_relation(ctx->node, lmd->object, DEG_OB_COMP_GEOMETRY, "Lattice Modifier");
+ DEG_add_object_relation(ctx->node, lmd->object, DEG_OB_COMP_TRANSFORM, "Lattice Modifier");
}
- DEG_add_object_relation(node, object, DEG_OB_COMP_TRANSFORM, "Lattice Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Lattice Modifier");
}
static void deformVerts(ModifierData *md, Object *ob,
diff --git a/source/blender/modifiers/intern/MOD_mask.c b/source/blender/modifiers/intern/MOD_mask.c
index dcc7fe4d4f1..351e7116d49 100644
--- a/source/blender/modifiers/intern/MOD_mask.c
+++ b/source/blender/modifiers/intern/MOD_mask.c
@@ -53,6 +53,8 @@
#include "depsgraph_private.h"
#include "DEG_depsgraph_build.h"
+#include "MOD_modifiertypes.h"
+
#include "BLI_strict_flags.h"
static void copyData(ModifierData *md, ModifierData *target)
@@ -77,36 +79,28 @@ static void foreachObjectLink(
walk(userData, ob, &mmd->ob_arm, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MaskModifierData *mmd = (MaskModifierData *)md;
if (mmd->ob_arm) {
bArmature *arm = (bArmature *)mmd->ob_arm->data;
- DagNode *armNode = dag_get_node(forest, mmd->ob_arm);
+ DagNode *armNode = dag_get_node(ctx->forest, mmd->ob_arm);
/* tag relationship in depsgraph, but also on the armature */
- dag_add_relation(forest, armNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
+ dag_add_relation(ctx->forest, armNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Mask Modifier");
arm->flag |= ARM_HAS_VIZ_DEPS;
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MaskModifierData *mmd = (MaskModifierData *)md;
if (mmd->ob_arm) {
bArmature *arm = (bArmature *)mmd->ob_arm->data;
/* Tag relationship in depsgraph, but also on the armature. */
/* TODO(sergey): Is it a proper relation here? */
- DEG_add_object_relation(node, mmd->ob_arm, DEG_OB_COMP_TRANSFORM, "Mask Modifier");
+ DEG_add_object_relation(ctx->node, mmd->ob_arm, DEG_OB_COMP_TRANSFORM, "Mask Modifier");
arm->flag |= ARM_HAS_VIZ_DEPS;
}
}
@@ -179,7 +173,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
* - each cell is a boolean saying whether bone corresponding to the ith group is selected
* - groups that don't match a bone are treated as not existing (along with the corresponding ungrouped verts)
*/
- bone_select_array = MEM_mallocN((size_t)defbase_tot * sizeof(char), "mask array");
+ bone_select_array = MEM_malloc_arrayN((size_t)defbase_tot, sizeof(char), "mask array");
for (i = 0, def = ob->defbase.first; def; def = def->next, i++) {
pchan = BKE_pose_channel_find_name(oba->pose, def->name);
@@ -263,7 +257,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
mloop_src = dm->getLoopArray(dm);
/* overalloc, assume all polys are seen */
- loop_mapping = MEM_mallocN(sizeof(int) * (size_t)maxPolys, "mask loopmap");
+ loop_mapping = MEM_malloc_arrayN((size_t)maxPolys, sizeof(int), "mask loopmap");
/* loop over edges and faces, and do the same thing to
* ensure that they only reference existing verts
diff --git a/source/blender/modifiers/intern/MOD_meshcache.c b/source/blender/modifiers/intern/MOD_meshcache.c
index aa3e3ebcf7e..e026d4da29a 100644
--- a/source/blender/modifiers/intern/MOD_meshcache.c
+++ b/source/blender/modifiers/intern/MOD_meshcache.c
@@ -94,7 +94,7 @@ static void meshcache_do(
{
const bool use_factor = mcmd->factor < 1.0f;
float (*vertexCos_Store)[3] = (use_factor || (mcmd->deform_mode == MOD_MESHCACHE_DEFORM_INTEGRATE)) ?
- MEM_mallocN(sizeof(*vertexCos_Store) * numVerts, __func__) : NULL;
+ MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_Store), __func__) : NULL;
float (*vertexCos)[3] = vertexCos_Store ? vertexCos_Store : vertexCos_Real;
Scene *scene = mcmd->modifier.scene;
@@ -197,8 +197,8 @@ static void meshcache_do(
/* the moons align! */
int i;
- float (*vertexCos_Source)[3] = MEM_mallocN(sizeof(*vertexCos_Source) * numVerts, __func__);
- float (*vertexCos_New)[3] = MEM_mallocN(sizeof(*vertexCos_New) * numVerts, __func__);
+ float (*vertexCos_Source)[3] = MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_Source), __func__);
+ float (*vertexCos_New)[3] = MEM_malloc_arrayN(numVerts, sizeof(*vertexCos_New), __func__);
MVert *mv = me->mvert;
for (i = 0; i < numVerts; i++, mv++) {
diff --git a/source/blender/modifiers/intern/MOD_meshcache_mdd.c b/source/blender/modifiers/intern/MOD_meshcache_mdd.c
index 90fc750de3b..3dd3a5fc598 100644
--- a/source/blender/modifiers/intern/MOD_meshcache_mdd.c
+++ b/source/blender/modifiers/intern/MOD_meshcache_mdd.c
@@ -35,6 +35,9 @@
#ifdef __LITTLE_ENDIAN__
# include "BLI_endian_switch.h"
#endif
+#ifdef WIN32
+# include "BLI_winstuff.h"
+#endif
#include "MOD_meshcache_util.h" /* own include */
@@ -157,7 +160,7 @@ bool MOD_meshcache_read_mdd_index(FILE *fp,
return false;
}
- if (fseek(fp, index * mdd_head.verts_tot * sizeof(float) * 3, SEEK_CUR) != 0) {
+ if (fseek(fp, sizeof(float) * 3 * index * mdd_head.verts_tot, SEEK_CUR) != 0) {
*err_str = "Failed to seek frame";
return false;
}
diff --git a/source/blender/modifiers/intern/MOD_meshcache_pc2.c b/source/blender/modifiers/intern/MOD_meshcache_pc2.c
index 219eae4ecca..4b2b3f17d18 100644
--- a/source/blender/modifiers/intern/MOD_meshcache_pc2.c
+++ b/source/blender/modifiers/intern/MOD_meshcache_pc2.c
@@ -35,6 +35,10 @@
# include "BLI_endian_switch.h"
#endif
+#ifdef WIN32
+# include "BLI_winstuff.h"
+#endif
+
#include "MOD_meshcache_util.h" /* own include */
#include "DNA_modifier_types.h"
@@ -142,7 +146,7 @@ bool MOD_meshcache_read_pc2_index(FILE *fp,
return false;
}
- if (fseek(fp, index * pc2_head.verts_tot * sizeof(float) * 3, SEEK_CUR) != 0) {
+ if (fseek(fp, sizeof(float) * 3 * index * pc2_head.verts_tot, SEEK_CUR) != 0) {
*err_str = "Failed to seek frame";
return false;
}
diff --git a/source/blender/modifiers/intern/MOD_meshcache_util.c b/source/blender/modifiers/intern/MOD_meshcache_util.c
index c263c4810e4..10861f5b02b 100644
--- a/source/blender/modifiers/intern/MOD_meshcache_util.c
+++ b/source/blender/modifiers/intern/MOD_meshcache_util.c
@@ -36,7 +36,7 @@ void MOD_meshcache_calc_range(const float frame, const char interp,
int r_index_range[2], float *r_factor)
{
if (interp == MOD_MESHCACHE_INTERP_NONE) {
- r_index_range[0] = r_index_range[1] = max_ii(0, min_ii(frame_tot - 1, iroundf(frame)));
+ r_index_range[0] = r_index_range[1] = max_ii(0, min_ii(frame_tot - 1, round_fl_to_int(frame)));
*r_factor = 1.0f; /* dummy */
}
else {
diff --git a/source/blender/modifiers/intern/MOD_meshdeform.c b/source/blender/modifiers/intern/MOD_meshdeform.c
index 406ce398ee0..c125495a234 100644
--- a/source/blender/modifiers/intern/MOD_meshdeform.c
+++ b/source/blender/modifiers/intern/MOD_meshdeform.c
@@ -83,7 +83,7 @@ static void copyData(ModifierData *md, ModifierData *target)
MeshDeformModifierData *mmd = (MeshDeformModifierData *) md;
MeshDeformModifierData *tmmd = (MeshDeformModifierData *) target;
- *tmmd = *mmd;
+ modifier_copyData_generic(md, target);
if (mmd->bindinfluences) tmmd->bindinfluences = MEM_dupallocN(mmd->bindinfluences);
if (mmd->bindoffsets) tmmd->bindoffsets = MEM_dupallocN(mmd->bindoffsets);
@@ -91,8 +91,8 @@ static void copyData(ModifierData *md, ModifierData *target)
if (mmd->dyngrid) tmmd->dyngrid = MEM_dupallocN(mmd->dyngrid);
if (mmd->dyninfluences) tmmd->dyninfluences = MEM_dupallocN(mmd->dyninfluences);
if (mmd->dynverts) tmmd->dynverts = MEM_dupallocN(mmd->dynverts);
- if (mmd->bindweights) tmmd->dynverts = MEM_dupallocN(mmd->bindweights); /* deprecated */
- if (mmd->bindcos) tmmd->dynverts = MEM_dupallocN(mmd->bindcos); /* deprecated */
+ if (mmd->bindweights) tmmd->bindweights = MEM_dupallocN(mmd->bindweights); /* deprecated */
+ if (mmd->bindcos) tmmd->bindcos = MEM_dupallocN(mmd->bindcos); /* deprecated */
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
@@ -122,33 +122,25 @@ static void foreachObjectLink(
walk(userData, ob, &mmd->object, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData *) md;
if (mmd->object) {
- DagNode *curNode = dag_get_node(forest, mmd->object);
+ DagNode *curNode = dag_get_node(ctx->forest, mmd->object);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA | DAG_RL_DATA_OB | DAG_RL_OB_OB,
"Mesh Deform Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MeshDeformModifierData *mmd = (MeshDeformModifierData *)md;
if (mmd->object != NULL) {
/* TODO(sergey): Do we need transform component here? */
- DEG_add_object_relation(node, mmd->object, DEG_OB_COMP_GEOMETRY, "Mesh Deform Modifier");
+ DEG_add_object_relation(ctx->node, mmd->object, DEG_OB_COMP_GEOMETRY, "Mesh Deform Modifier");
}
}
@@ -234,7 +226,10 @@ typedef struct MeshdeformUserdata {
float (*icagemat)[3];
} MeshdeformUserdata;
-static void meshdeform_vert_task(void *userdata, const int iter)
+static void meshdeform_vert_task(
+ void *__restrict userdata,
+ const int iter,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
MeshdeformUserdata *data = userdata;
/*const*/ MeshDeformModifierData *mmd = data->mmd;
@@ -377,7 +372,7 @@ static void meshdeformModifier_do(
return;
}
- cagecos = MEM_mallocN(sizeof(*cagecos) * totcagevert, "meshdeformModifier vertCos");
+ cagecos = MEM_malloc_arrayN(totcagevert, sizeof(*cagecos), "meshdeformModifier vertCos");
/* setup deformation data */
cagedm->getVertCos(cagedm, cagecos);
@@ -386,7 +381,7 @@ static void meshdeformModifier_do(
/* We allocate 1 element extra to make it possible to
* load the values to SSE registers, which are float4.
*/
- dco = MEM_callocN(sizeof(*dco) * (totcagevert + 1), "MDefDco");
+ dco = MEM_calloc_arrayN((totcagevert + 1), sizeof(*dco), "MDefDco");
zero_v3(dco[totcagevert]);
for (a = 0; a < totcagevert; a++) {
/* get cage vertex in world space with binding transform */
@@ -413,7 +408,13 @@ static void meshdeformModifier_do(
data.icagemat = icagemat;
/* Do deformation. */
- BLI_task_parallel_range(0, totvert, &data, meshdeform_vert_task, totvert > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.min_iter_per_thread = 16;
+ BLI_task_parallel_range(0, totvert,
+ &data,
+ meshdeform_vert_task,
+ &settings);
/* release cage derivedmesh */
MEM_freeN(dco);
@@ -477,8 +478,8 @@ void modifier_mdef_compact_influences(ModifierData *md)
}
/* allocate bind influences */
- mmd->bindinfluences = MEM_callocN(sizeof(MDefInfluence) * mmd->totinfluence, "MDefBindInfluence");
- mmd->bindoffsets = MEM_callocN(sizeof(int) * (totvert + 1), "MDefBindOffset");
+ mmd->bindinfluences = MEM_calloc_arrayN(mmd->totinfluence, sizeof(MDefInfluence), "MDefBindInfluence");
+ mmd->bindoffsets = MEM_calloc_arrayN((totvert + 1), sizeof(int), "MDefBindOffset");
/* write influences */
totinfluence = 0;
diff --git a/source/blender/modifiers/intern/MOD_meshsequencecache.c b/source/blender/modifiers/intern/MOD_meshsequencecache.c
index d956763fc1f..04de6fae336 100644
--- a/source/blender/modifiers/intern/MOD_meshsequencecache.c
+++ b/source/blender/modifiers/intern/MOD_meshsequencecache.c
@@ -25,13 +25,14 @@
*/
#include "DNA_cachefile_types.h"
+#include "DNA_mesh_types.h"
#include "DNA_modifier_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "BKE_cachefile.h"
#include "BKE_DerivedMesh.h"
-#include "BKE_global.h"
+#include "BKE_cdderivedmesh.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_scene.h"
@@ -43,6 +44,7 @@
#ifdef WITH_ALEMBIC
# include "ABC_alembic.h"
+# include "BKE_global.h"
#endif
static void initData(ModifierData *md)
@@ -73,10 +75,6 @@ static void freeData(ModifierData *md)
{
MeshSeqCacheModifierData *mcmd = (MeshSeqCacheModifierData *) md;
- if (mcmd->cache_file) {
- id_us_min(&mcmd->cache_file->id);
- }
-
if (mcmd->reader) {
#ifdef WITH_ALEMBIC
CacheReader_free(mcmd->reader);
@@ -95,15 +93,18 @@ static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
DerivedMesh *dm,
- ModifierApplyFlag flag)
+ ModifierApplyFlag UNUSED(flag))
{
#ifdef WITH_ALEMBIC
MeshSeqCacheModifierData *mcmd = (MeshSeqCacheModifierData *) md;
+ /* Only used to check whether we are operating on org data or not... */
+ Mesh *me = (ob->type == OB_MESH) ? ob->data : NULL;
+ DerivedMesh *org_dm = dm;
+
Scene *scene = md->scene;
const float frame = BKE_scene_frame_get(scene);
const float time = BKE_cachefile_time_offset(mcmd->cache_file, frame, FPS);
-
const char *err_str = NULL;
CacheFile *cache_file = mcmd->cache_file;
@@ -112,7 +113,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
if (!mcmd->reader) {
mcmd->reader = CacheReader_open_alembic_object(cache_file->handle,
- mcmd->reader,
+ NULL,
ob,
mcmd->object_path);
if (!mcmd->reader) {
@@ -121,6 +122,16 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
}
+ if (me != NULL) {
+ MVert *mvert = dm->getVertArray(dm);
+ MEdge *medge = dm->getEdgeArray(dm);
+ MPoly *mpoly = dm->getPolyArray(dm);
+ if ((me->mvert == mvert) || (me->medge == medge) || (me->mpoly == mpoly)) {
+ /* We need to duplicate data here, otherwise we'll modify org mesh, see T51701. */
+ dm = CDDM_copy(dm);
+ }
+ }
+
DerivedMesh *result = ABC_read_mesh(mcmd->reader,
ob,
dm,
@@ -132,11 +143,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
modifier_setError(md, "%s", err_str);
}
+ if (!ELEM(result, NULL, dm) && (dm != org_dm)) {
+ dm->release(dm);
+ dm = org_dm;
+ }
+
return result ? result : dm;
- UNUSED_VARS(flag);
#else
return dm;
- UNUSED_VARS(md, ob, flag);
+ UNUSED_VARS(md, ob);
#endif
}
@@ -155,36 +170,25 @@ static void foreachIDLink(ModifierData *md, Object *ob,
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *bmain,
- struct Scene *scene,
- Object *ob, DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MeshSeqCacheModifierData *mcmd = (MeshSeqCacheModifierData *) md;
if (mcmd->cache_file != NULL) {
- DagNode *curNode = dag_get_node(forest, mcmd->cache_file);
+ DagNode *curNode = dag_get_node(ctx->forest, mcmd->cache_file);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Cache File Modifier");
}
-
- UNUSED_VARS(bmain, scene, ob);
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *bmain,
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MeshSeqCacheModifierData *mcmd = (MeshSeqCacheModifierData *) md;
if (mcmd->cache_file != NULL) {
- DEG_add_object_cache_relation(node, mcmd->cache_file, DEG_OB_COMP_CACHE, "Mesh Cache File");
+ DEG_add_object_cache_relation(ctx->node, mcmd->cache_file, DEG_OB_COMP_CACHE, "Mesh Cache File");
}
-
- UNUSED_VARS(bmain, scene, ob);
}
ModifierTypeInfo modifierType_MeshSequenceCache = {
diff --git a/source/blender/modifiers/intern/MOD_mirror.c b/source/blender/modifiers/intern/MOD_mirror.c
index dd127cc255c..875a1e8d468 100644
--- a/source/blender/modifiers/intern/MOD_mirror.c
+++ b/source/blender/modifiers/intern/MOD_mirror.c
@@ -48,6 +48,8 @@
#include "depsgraph_private.h"
#include "DEG_depsgraph_build.h"
+#include "MOD_modifiertypes.h"
+
static void initData(ModifierData *md)
{
MirrorModifierData *mmd = (MirrorModifierData *) md;
@@ -75,32 +77,24 @@ static void foreachObjectLink(
walk(userData, ob, &mmd->mirror_ob, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MirrorModifierData *mmd = (MirrorModifierData *) md;
if (mmd->mirror_ob) {
- DagNode *latNode = dag_get_node(forest, mmd->mirror_ob);
+ DagNode *latNode = dag_get_node(ctx->forest, mmd->mirror_ob);
- dag_add_relation(forest, latNode, obNode, DAG_RL_OB_DATA, "Mirror Modifier");
+ dag_add_relation(ctx->forest, latNode, ctx->obNode, DAG_RL_OB_DATA, "Mirror Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
MirrorModifierData *mmd = (MirrorModifierData *)md;
if (mmd->mirror_ob != NULL) {
- DEG_add_object_relation(node, mmd->mirror_ob, DEG_OB_COMP_TRANSFORM, "Mirror Modifier");
+ DEG_add_object_relation(ctx->node, mmd->mirror_ob, DEG_OB_COMP_TRANSFORM, "Mirror Modifier");
}
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "Mirror Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "Mirror Modifier");
}
static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
@@ -158,8 +152,8 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
DM_copy_poly_data(dm, result, 0, 0, maxPolys);
- /* subsurf for eg wont have mesh data in the */
- /* now add mvert/medge/mface layers */
+ /* Subsurf for eg wont have mesh data in the custom data arrays.
+ * now add mvert/medge/mpoly layers. */
if (!CustomData_has_layer(&dm->vertData, CD_MVERT)) {
dm->copyVertArray(dm, CDDM_get_verts(result));
@@ -181,7 +175,7 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
if (do_vtargetmap) {
/* second half is filled with -1 */
- vtargetmap = MEM_mallocN(sizeof(int) * maxVerts * 2, "MOD_mirror tarmap");
+ vtargetmap = MEM_malloc_arrayN(maxVerts, 2 * sizeof(int), "MOD_mirror tarmap");
vtmap_a = vtargetmap;
vtmap_b = vtargetmap + maxVerts;
@@ -263,7 +257,7 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
/* handle uvs,
* let tessface recalc handle updating the MTFace data */
- if (mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V)) {
+ if (mmd->flag & (MOD_MIR_MIRROR_U | MOD_MIR_MIRROR_V) || (is_zero_v2(mmd->uv_offset_copy) == false)) {
const bool do_mirr_u = (mmd->flag & MOD_MIR_MIRROR_U) != 0;
const bool do_mirr_v = (mmd->flag & MOD_MIR_MIRROR_V) != 0;
@@ -274,8 +268,10 @@ static DerivedMesh *doMirrorOnAxis(MirrorModifierData *mmd,
int j = maxLoops;
dmloopuv += j; /* second set of loops only */
for (; j-- > 0; dmloopuv++) {
- if (do_mirr_u) dmloopuv->uv[0] = 1.0f - dmloopuv->uv[0];
- if (do_mirr_v) dmloopuv->uv[1] = 1.0f - dmloopuv->uv[1];
+ if (do_mirr_u) dmloopuv->uv[0] = 1.0f - dmloopuv->uv[0] + mmd->uv_offset[0];
+ if (do_mirr_v) dmloopuv->uv[1] = 1.0f - dmloopuv->uv[1] + mmd->uv_offset[1];
+ dmloopuv->uv[0] += mmd->uv_offset_copy[0];
+ dmloopuv->uv[1] += mmd->uv_offset_copy[1];
}
}
}
diff --git a/source/blender/modifiers/intern/MOD_multires.c b/source/blender/modifiers/intern/MOD_multires.c
index 90ad1bdfdc2..f9f17b88fa4 100644
--- a/source/blender/modifiers/intern/MOD_multires.c
+++ b/source/blender/modifiers/intern/MOD_multires.c
@@ -46,6 +46,8 @@
#include "BKE_modifier.h"
#include "BKE_subsurf.h"
+#include "MOD_modifiertypes.h"
+
static void initData(ModifierData *md)
{
MultiresModifierData *mmd = (MultiresModifierData *)md;
diff --git a/source/blender/modifiers/intern/MOD_normal_edit.c b/source/blender/modifiers/intern/MOD_normal_edit.c
index 20eae751ca4..0b703fffda3 100644
--- a/source/blender/modifiers/intern/MOD_normal_edit.c
+++ b/source/blender/modifiers/intern/MOD_normal_edit.c
@@ -119,7 +119,7 @@ static void mix_normals(
int i;
if (dvert) {
- facs = MEM_mallocN(sizeof(*facs) * (size_t)num_loops, __func__);
+ facs = MEM_malloc_arrayN((size_t)num_loops, sizeof(*facs), __func__);
BKE_defvert_extract_vgroup_to_loopweights(
dvert, defgrp_index, num_verts, mloop, num_loops, facs, use_invert_vgroup);
}
@@ -197,8 +197,8 @@ static void normalEditModifier_do_radial(
{
int i;
- float (*cos)[3] = MEM_mallocN(sizeof(*cos) * num_verts, __func__);
- float (*nos)[3] = MEM_mallocN(sizeof(*nos) * num_loops, __func__);
+ float (*cos)[3] = MEM_malloc_arrayN((size_t)num_verts, sizeof(*cos), __func__);
+ float (*nos)[3] = MEM_malloc_arrayN((size_t)num_loops, sizeof(*nos), __func__);
float size[3];
BLI_bitmap *done_verts = BLI_BITMAP_NEW((size_t)num_verts, __func__);
@@ -296,8 +296,8 @@ static void normalEditModifier_do_directional(
{
const bool use_parallel_normals = (enmd->flag & MOD_NORMALEDIT_USE_DIRECTION_PARALLEL) != 0;
- float (*cos)[3] = MEM_mallocN(sizeof(*cos) * num_verts, __func__);
- float (*nos)[3] = MEM_mallocN(sizeof(*nos) * num_loops, __func__);
+ float (*cos)[3] = MEM_malloc_arrayN((size_t)num_verts, sizeof(*cos), __func__);
+ float (*nos)[3] = MEM_malloc_arrayN((size_t)num_loops, sizeof(*nos), __func__);
float target_co[3];
int i;
@@ -436,7 +436,7 @@ static DerivedMesh *normalEditModifier_do(NormalEditModifierData *enmd, Object *
polynors = dm->getPolyDataArray(dm, CD_NORMAL);
if (!polynors) {
- polynors = MEM_mallocN(sizeof(*polynors) * num_polys, __func__);
+ polynors = MEM_malloc_arrayN((size_t)num_polys, sizeof(*polynors), __func__);
BKE_mesh_calc_normals_poly(mvert, NULL, num_verts, mloop, mpoly, num_loops, num_polys, polynors, false);
free_polynors = true;
}
@@ -511,29 +511,22 @@ static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
return !is_valid_target(enmd);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
NormalEditModifierData *enmd = (NormalEditModifierData *) md;
if (enmd->target) {
- DagNode *Node = dag_get_node(forest, enmd->target);
+ DagNode *Node = dag_get_node(ctx->forest, enmd->target);
- dag_add_relation(forest, Node, obNode, DAG_RL_OB_DATA, "NormalEdit Modifier");
+ dag_add_relation(ctx->forest, Node, ctx->obNode, DAG_RL_OB_DATA, "NormalEdit Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
NormalEditModifierData *enmd = (NormalEditModifierData *) md;
if (enmd->target) {
- DEG_add_object_relation(node, enmd->target, DEG_OB_COMP_TRANSFORM, "NormalEdit Modifier");
+ DEG_add_object_relation(ctx->node, enmd->target, DEG_OB_COMP_TRANSFORM, "NormalEdit Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_ocean.c b/source/blender/modifiers/intern/MOD_ocean.c
index e77cc655c16..a9c4afcc0af 100644
--- a/source/blender/modifiers/intern/MOD_ocean.c
+++ b/source/blender/modifiers/intern/MOD_ocean.c
@@ -44,6 +44,8 @@
#include "BKE_modifier.h"
#include "BKE_ocean.h"
+#include "MOD_modifiertypes.h"
+
#ifdef WITH_OCEANSIM
static void init_cache_data(Object *ob, struct OceanModifierData *omd)
{
@@ -160,40 +162,19 @@ static void freeData(ModifierData *md)
static void copyData(ModifierData *md, ModifierData *target)
{
#ifdef WITH_OCEANSIM
+#if 0
OceanModifierData *omd = (OceanModifierData *) md;
+#endif
OceanModifierData *tomd = (OceanModifierData *) target;
- tomd->geometry_mode = omd->geometry_mode;
- tomd->resolution = omd->resolution;
- tomd->spatial_size = omd->spatial_size;
-
- tomd->wind_velocity = omd->wind_velocity;
-
- tomd->damp = omd->damp;
- tomd->smallest_wave = omd->smallest_wave;
- tomd->depth = omd->depth;
+ freeData(target);
- tomd->wave_alignment = omd->wave_alignment;
- tomd->wave_direction = omd->wave_direction;
- tomd->wave_scale = omd->wave_scale;
-
- tomd->chop_amount = omd->chop_amount;
- tomd->foam_coverage = omd->foam_coverage;
- tomd->time = omd->time;
-
- tomd->seed = omd->seed;
- tomd->flag = omd->flag;
+ modifier_copyData_generic(md, target);
tomd->refresh = 0;
- tomd->size = omd->size;
- tomd->repeat_x = omd->repeat_x;
- tomd->repeat_y = omd->repeat_y;
-
/* XXX todo: copy cache runtime too */
tomd->cached = 0;
- tomd->bakestart = omd->bakestart;
- tomd->bakeend = omd->bakeend;
tomd->oceancache = NULL;
tomd->ocean = BKE_ocean_add();
@@ -280,7 +261,10 @@ typedef struct GenerateOceanGeometryData {
float ix, iy;
} GenerateOceanGeometryData;
-static void generate_ocean_geometry_vertices(void *userdata, const int y)
+static void generate_ocean_geometry_vertices(
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
GenerateOceanGeometryData *gogd = userdata;
int x;
@@ -294,7 +278,10 @@ static void generate_ocean_geometry_vertices(void *userdata, const int y)
}
}
-static void generate_ocean_geometry_polygons(void *userdata, const int y)
+static void generate_ocean_geometry_polygons(
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
GenerateOceanGeometryData *gogd = userdata;
int x;
@@ -324,7 +311,10 @@ static void generate_ocean_geometry_polygons(void *userdata, const int y)
}
}
-static void generate_ocean_geometry_uvs(void *userdata, const int y)
+static void generate_ocean_geometry_uvs(
+ void *__restrict userdata,
+ const int y,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
GenerateOceanGeometryData *gogd = userdata;
int x;
@@ -386,11 +376,15 @@ static DerivedMesh *generate_ocean_geometry(OceanModifierData *omd)
gogd.origindex = CustomData_get_layer(&result->polyData, CD_ORIGINDEX);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = use_threading;
+
/* create vertices */
- BLI_task_parallel_range(0, gogd.res_y + 1, &gogd, generate_ocean_geometry_vertices, use_threading);
+ BLI_task_parallel_range(0, gogd.res_y + 1, &gogd, generate_ocean_geometry_vertices, &settings);
/* create faces */
- BLI_task_parallel_range(0, gogd.res_y, &gogd, generate_ocean_geometry_polygons, use_threading);
+ BLI_task_parallel_range(0, gogd.res_y, &gogd, generate_ocean_geometry_polygons, &settings);
CDDM_calc_edges(result);
@@ -403,7 +397,7 @@ static DerivedMesh *generate_ocean_geometry(OceanModifierData *omd)
gogd.ix = 1.0 / gogd.rx;
gogd.iy = 1.0 / gogd.ry;
- BLI_task_parallel_range(0, gogd.res_y, &gogd, generate_ocean_geometry_uvs, use_threading);
+ BLI_task_parallel_range(0, gogd.res_y, &gogd, generate_ocean_geometry_uvs, &settings);
}
}
diff --git a/source/blender/modifiers/intern/MOD_particleinstance.c b/source/blender/modifiers/intern/MOD_particleinstance.c
index fbf5a958254..f0b80cda447 100644
--- a/source/blender/modifiers/intern/MOD_particleinstance.c
+++ b/source/blender/modifiers/intern/MOD_particleinstance.c
@@ -40,6 +40,7 @@
#include "BLI_math.h"
#include "BLI_listbase.h"
#include "BLI_rand.h"
+#include "BLI_string.h"
#include "BLI_utildefines.h"
#include "BKE_cdderivedmesh.h"
@@ -63,7 +64,12 @@ static void initData(ModifierData *md)
pimd->psys = 1;
pimd->position = 1.0f;
pimd->axis = 2;
+ pimd->space = eParticleInstanceSpace_World;
+ pimd->particle_amount = 1.0f;
+ pimd->particle_offset = 0.0f;
+ STRNCPY(pimd->index_layer_name, "");
+ STRNCPY(pimd->value_layer_name, "");
}
static void copyData(ModifierData *md, ModifierData *target)
{
@@ -74,19 +80,34 @@ static void copyData(ModifierData *md, ModifierData *target)
modifier_copyData_generic(md, target);
}
+static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
+{
+ ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
+ CustomDataMask dataMask = 0;
+
+ if (pimd->index_layer_name[0] != '\0' ||
+ pimd->value_layer_name[0] != '\0')
+ {
+ dataMask |= CD_MASK_MLOOPCOL;
+ }
+
+ return dataMask;
+
+}
+
static bool isDisabled(ModifierData *md, int useRenderParams)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *)md;
ParticleSystem *psys;
ModifierData *ob_md;
-
+
if (!pimd->ob)
return true;
-
+
psys = BLI_findlink(&pimd->ob->particlesystem, pimd->psys - 1);
if (psys == NULL)
return true;
-
+
/* If the psys modifier is disabled we cannot use its data.
* First look up the psys modifier from the object, then check if it is enabled.
*/
@@ -95,48 +116,41 @@ static bool isDisabled(ModifierData *md, int useRenderParams)
ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)ob_md;
if (psmd->psys == psys) {
int required_mode;
-
+
if (useRenderParams) required_mode = eModifierMode_Render;
else required_mode = eModifierMode_Realtime;
-
+
if (!modifier_isEnabled(md->scene, ob_md, required_mode))
return true;
-
+
break;
}
}
}
-
+
return false;
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
if (pimd->ob) {
- DagNode *curNode = dag_get_node(forest, pimd->ob);
+ DagNode *curNode = dag_get_node(ctx->forest, pimd->ob);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"Particle Instance Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ParticleInstanceModifierData *pimd = (ParticleInstanceModifierData *) md;
if (pimd->ob != NULL) {
- DEG_add_object_relation(node, pimd->ob, DEG_OB_COMP_TRANSFORM, "Particle Instance Modifier");
+ DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_TRANSFORM, "Particle Instance Modifier");
+ DEG_add_object_relation(ctx->node, pimd->ob, DEG_OB_COMP_GEOMETRY, "Particle Instance Modifier");
}
}
@@ -148,39 +162,59 @@ static void foreachObjectLink(ModifierData *md, Object *ob,
walk(userData, ob, &pimd->ob, IDWALK_CB_NOP);
}
-static int particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *psys, int p)
+static bool particle_skip(ParticleInstanceModifierData *pimd, ParticleSystem *psys, int p)
{
+ const bool between = (psys->part->childtype == PART_CHILD_FACES);
ParticleData *pa;
+ int totpart, randp, minp, maxp;
- if (pimd->flag & eParticleInstanceFlag_Parents) {
- if (p >= psys->totpart) {
- if (psys->part->childtype == PART_CHILD_PARTICLES) {
- pa = psys->particles + (psys->child + p - psys->totpart)->parent;
- }
- else {
- pa = NULL;
- }
- }
- else {
- pa = psys->particles + p;
- }
+ if (p >= psys->totpart) {
+ ChildParticle *cpa = psys->child + (p - psys->totpart);
+ pa = psys->particles + (between? cpa->pa[0]: cpa->parent);
}
else {
- if (psys->part->childtype == PART_CHILD_PARTICLES) {
- pa = psys->particles + (psys->child + p)->parent;
- }
- else {
- pa = NULL;
- }
+ pa = psys->particles + p;
}
if (pa) {
- if (pa->alive == PARS_UNBORN && (pimd->flag & eParticleInstanceFlag_Unborn) == 0) return 1;
- if (pa->alive == PARS_ALIVE && (pimd->flag & eParticleInstanceFlag_Alive) == 0) return 1;
- if (pa->alive == PARS_DEAD && (pimd->flag & eParticleInstanceFlag_Dead) == 0) return 1;
+ if (pa->alive == PARS_UNBORN && (pimd->flag & eParticleInstanceFlag_Unborn) == 0) return true;
+ if (pa->alive == PARS_ALIVE && (pimd->flag & eParticleInstanceFlag_Alive) == 0) return true;
+ if (pa->alive == PARS_DEAD && (pimd->flag & eParticleInstanceFlag_Dead) == 0) return true;
+ }
+
+ if (pimd->particle_amount == 1.0f) {
+ /* Early output, all particles are to be instanced. */
+ return false;
+ }
+
+ /* Randomly skip particles based on desired amount of visible particles. */
+
+ totpart = psys->totpart + psys->totchild;
+
+ /* TODO make randomization optional? */
+ randp = (int)(psys_frand(psys, 3578 + p) * totpart) % totpart;
+
+ minp = (int)(totpart * pimd->particle_offset) % (totpart+1);
+ maxp = (int)(totpart * (pimd->particle_offset + pimd->particle_amount)) % (totpart+1);
+
+ if (maxp > minp) {
+ return randp < minp || randp >= maxp;
+ }
+ else if (maxp < minp) {
+ return randp < minp && randp >= maxp;
+ }
+ else {
+ return true;
}
-
- return 0;
+
+ return false;
+}
+
+static void store_float_in_vcol(MLoopCol *vcol, float float_value)
+{
+ const uchar value = FTOCHAR(float_value);
+ vcol->r = vcol->g = vcol->b = value;
+ vcol->a = 1.0f;
}
static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
@@ -196,11 +230,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
MLoop *mloop, *orig_mloop;
MVert *mvert, *orig_mvert;
int totvert, totpoly, totloop /* , totedge */;
- int maxvert, maxpoly, maxloop, totpart = 0, first_particle = 0;
+ int maxvert, maxpoly, maxloop, part_end = 0, part_start;
int k, p, p_skip;
short track = ob->trackflag % 3, trackneg, axis = pimd->axis;
float max_co = 0.0, min_co = 0.0, temp_co[3];
float *size = NULL;
+ float spacemat[4][4];
+ const bool use_parents = pimd->flag & eParticleInstanceFlag_Parents;
+ const bool use_children = pimd->flag & eParticleInstanceFlag_Children;
+ bool between;
trackneg = ((ob->trackflag > 2) ? 1 : 0);
@@ -218,25 +256,26 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
return derivedData;
}
- if (pimd->flag & eParticleInstanceFlag_Parents)
- totpart += psys->totpart;
- if (pimd->flag & eParticleInstanceFlag_Children) {
- if (totpart == 0)
- first_particle = psys->totpart;
- totpart += psys->totchild;
- }
+ part_start = use_parents ? 0 : psys->totpart;
- if (totpart == 0)
+ part_end = 0;
+ if (use_parents)
+ part_end += psys->totpart;
+ if (use_children)
+ part_end += psys->totchild;
+
+ if (part_end == 0)
return derivedData;
sim.scene = md->scene;
sim.ob = pimd->ob;
sim.psys = psys;
sim.psmd = psys_get_modifier(pimd->ob, psys);
+ between = (psys->part->childtype == PART_CHILD_FACES);
if (pimd->flag & eParticleInstanceFlag_UseSize) {
float *si;
- si = size = MEM_callocN(totpart * sizeof(float), "particle size array");
+ si = size = MEM_calloc_arrayN(part_end, sizeof(float), "particle size array");
if (pimd->flag & eParticleInstanceFlag_Parents) {
for (p = 0, pa = psys->particles; p < psys->totpart; p++, pa++, si++)
@@ -252,6 +291,21 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
}
+ switch (pimd->space) {
+ case eParticleInstanceSpace_World:
+ /* particle states are in world space already */
+ unit_m4(spacemat);
+ break;
+ case eParticleInstanceSpace_Local:
+ /* get particle states in the particle object's local space */
+ invert_m4_m4(spacemat, pimd->ob->obmat);
+ break;
+ default:
+ /* should not happen */
+ BLI_assert(false);
+ break;
+ }
+
totvert = dm->getNumVerts(dm);
totpoly = dm->getNumPolys(dm);
totloop = dm->getNumLoops(dm);
@@ -262,7 +316,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
maxpoly = 0;
maxloop = 0;
- for (p = 0; p < totpart; p++) {
+ for (p = part_start; p < part_end; p++) {
if (particle_skip(pimd, psys, p))
continue;
@@ -291,10 +345,22 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
mloop = result->getLoopArray(result);
orig_mloop = dm->getLoopArray(dm);
- for (p = 0, p_skip = 0; p < totpart; p++) {
+ MLoopCol *mloopcols_index = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, pimd->index_layer_name);
+ MLoopCol *mloopcols_value = CustomData_get_layer_named(&result->loopData, CD_MLOOPCOL, pimd->value_layer_name);
+ int *vert_part_index = NULL;
+ float *vert_part_value = NULL;
+ if (mloopcols_index != NULL) {
+ vert_part_index = MEM_calloc_arrayN(maxvert, sizeof(int), "vertex part index array");
+ }
+ if (mloopcols_value) {
+ vert_part_value = MEM_calloc_arrayN(maxvert, sizeof(float), "vertex part value array");
+ }
+
+ for (p = part_start, p_skip = 0; p < part_end; p++) {
float prev_dir[3];
float frame[4]; /* frame orientation quaternion */
-
+ float p_random = psys_frand(psys, 77091 + 283*p);
+
/* skip particle? */
if (particle_skip(pimd, psys, p))
continue;
@@ -303,12 +369,20 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
for (k = 0; k < totvert; k++) {
ParticleKey state;
MVert *inMV;
- MVert *mv = mvert + p_skip * totvert + k;
+ int vindex = p_skip * totvert + k;
+ MVert *mv = mvert + vindex;
inMV = orig_mvert + k;
DM_copy_vert_data(dm, result, k, p_skip * totvert + k, 1);
*mv = *inMV;
+ if (vert_part_index != NULL) {
+ vert_part_index[vindex] = p;
+ }
+ if (vert_part_value != NULL) {
+ vert_part_value[vindex] = p_random;
+ }
+
/*change orientation based on object trackflag*/
copy_v3_v3(temp_co, mv->co);
mv->co[axis] = temp_co[track];
@@ -336,7 +410,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
mv->co[axis] = 0.0;
}
- psys_get_particle_on_path(&sim, first_particle + p, &state, 1);
+ psys_get_particle_on_path(&sim, p, &state, 1);
normalize_v3(state.vel);
@@ -344,18 +418,27 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
if (k == 0) {
float hairmat[4][4];
float mat[3][3];
-
- if (first_particle + p < psys->totpart)
- pa = psys->particles + first_particle + p;
+
+ if (p < psys->totpart)
+ pa = psys->particles + p;
else {
ChildParticle *cpa = psys->child + (p - psys->totpart);
- pa = psys->particles + cpa->parent;
+ pa = psys->particles + (between? cpa->pa[0]: cpa->parent);
}
psys_mat_hair_to_global(sim.ob, sim.psmd->dm_final, sim.psys->part->from, pa, hairmat);
copy_m3_m4(mat, hairmat);
/* to quaternion */
mat3_to_quat(frame, mat);
-
+
+ if (pimd->rotation > 0.0f || pimd->random_rotation > 0.0f) {
+ float angle = 2.0f*M_PI * (pimd->rotation + pimd->random_rotation * (psys_frand(psys, 19957323 + p) - 0.5f));
+ float eul[3] = { 0.0f, 0.0f, angle };
+ float rot[4];
+
+ eul_to_quat(rot, eul);
+ mul_qt_qtqt(frame, frame, rot);
+ }
+
/* note: direction is same as normal vector currently,
* but best to keep this separate so the frame can be
* rotated later if necessary
@@ -364,14 +447,14 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
else {
float rot[4];
-
+
/* incrementally rotate along bend direction */
rotation_between_vecs_to_quat(rot, prev_dir, state.vel);
mul_qt_qtqt(frame, rot, frame);
-
+
copy_v3_v3(prev_dir, state.vel);
}
-
+
copy_qt_qt(state.rot, frame);
#if 0
/* Absolute Frame (Frenet Frame) */
@@ -382,9 +465,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
float cross[3];
float temp[3] = {0.0f, 0.0f, 0.0f};
temp[axis] = 1.0f;
-
+
cross_v3_v3v3(cross, temp, state.vel);
-
+
/* state.vel[axis] is the only component surviving from a dot product with the axis */
axis_angle_to_quat(state.rot, cross, saacos(state.vel[axis]));
}
@@ -392,13 +475,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
else {
state.time = -1.0;
- psys_get_particle_state(&sim, first_particle + p, &state, 1);
+ psys_get_particle_state(&sim, p, &state, 1);
}
mul_qt_v3(state.rot, mv->co);
if (pimd->flag & eParticleInstanceFlag_UseSize)
mul_v3_fl(mv->co, size[p]);
add_v3_v3(mv->co, state.co);
+
+ mul_m4_v3(spacemat, mv->co);
}
/* create polys and loops */
@@ -418,6 +503,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
DM_copy_loop_data(dm, result, inMP->loopstart, mp->loopstart, j);
for (; j; j--, ml++, inML++) {
ml->v = inML->v + (p_skip * totvert);
+ const int ml_index = (ml - mloop);
+ if (mloopcols_index != NULL) {
+ const int part_index = vert_part_index[ml->v];
+ store_float_in_vcol(&mloopcols_index[ml_index], (float)part_index / psys->totpart);
+ }
+ if (mloopcols_value != NULL) {
+ const float part_value = vert_part_value[ml->v];
+ store_float_in_vcol(&mloopcols_value[ml_index], part_value);
+ }
}
}
}
@@ -435,6 +529,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
if (size)
MEM_freeN(size);
+ MEM_SAFE_FREE(vert_part_index);
+ MEM_SAFE_FREE(vert_part_value);
+
result->dirty |= DM_DIRTY_NORMALS;
return result;
@@ -457,7 +554,7 @@ ModifierTypeInfo modifierType_ParticleInstance = {
/* applyModifier */ applyModifier,
/* applyModifierEM */ NULL,
/* initData */ initData,
- /* requiredDataMask */ NULL,
+ /* requiredDataMask */ requiredDataMask,
/* freeData */ NULL,
/* isDisabled */ isDisabled,
/* updateDepgraph */ updateDepgraph,
diff --git a/source/blender/modifiers/intern/MOD_screw.c b/source/blender/modifiers/intern/MOD_screw.c
index 87859cd240a..047b1d5c47d 100644
--- a/source/blender/modifiers/intern/MOD_screw.c
+++ b/source/blender/modifiers/intern/MOD_screw.c
@@ -112,6 +112,56 @@ static void screwvert_iter_step(ScrewVertIter *iter)
}
}
+static DerivedMesh *dm_remove_doubles_on_axis(
+ DerivedMesh *result, MVert *mvert_new, const uint totvert, const uint step_tot,
+ const float axis_vec[3], const float axis_offset[3], const float merge_threshold)
+{
+ const float merge_threshold_sq = SQUARE(merge_threshold);
+ const bool use_offset = axis_offset != NULL;
+ uint tot_doubles = 0;
+ for (uint i = 0; i < totvert; i += 1) {
+ float axis_co[3];
+ if (use_offset) {
+ float offset_co[3];
+ sub_v3_v3v3(offset_co, mvert_new[i].co, axis_offset);
+ project_v3_v3v3_normalized(axis_co, offset_co, axis_vec);
+ add_v3_v3(axis_co, axis_offset);
+ }
+ else {
+ project_v3_v3v3_normalized(axis_co, mvert_new[i].co, axis_vec);
+ }
+ const float dist_sq = len_squared_v3v3(axis_co, mvert_new[i].co);
+ if (dist_sq <= merge_threshold_sq) {
+ mvert_new[i].flag |= ME_VERT_TMP_TAG;
+ tot_doubles += 1;
+ copy_v3_v3(mvert_new[i].co, axis_co);
+ }
+ }
+
+ if (tot_doubles != 0) {
+ uint tot = totvert * step_tot;
+ int *full_doubles_map = MEM_malloc_arrayN(tot, sizeof(int), __func__);
+ copy_vn_i(full_doubles_map, (int)tot, -1);
+
+ uint tot_doubles_left = tot_doubles;
+ for (uint i = 0; i < totvert; i += 1) {
+ if (mvert_new[i].flag & ME_VERT_TMP_TAG) {
+ int *doubles_map = &full_doubles_map[totvert + i] ;
+ for (uint step = 1; step < step_tot; step += 1) {
+ *doubles_map = (int)i;
+ doubles_map += totvert;
+ }
+ tot_doubles_left -= 1;
+ if (tot_doubles_left == 0) {
+ break;
+ }
+ }
+ }
+ result = CDDM_merge_verts(result, full_doubles_map, (int)(tot_doubles * (step_tot - 1)), CDDM_MERGE_VERTS_DUMP_IF_MAPPED);
+ MEM_freeN(full_doubles_map);
+ }
+ return result;
+}
static void initData(ModifierData *md)
{
@@ -123,6 +173,7 @@ static void initData(ModifierData *md)
ltmd->steps = 16;
ltmd->render_steps = 16;
ltmd->iter = 1;
+ ltmd->merge_dist = 0.01f;
}
static void copyData(ModifierData *md, ModifierData *target)
@@ -398,10 +449,10 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
mpoly_orig = dm->getPolyArray(dm);
mloop_orig = dm->getLoopArray(dm);
- edge_poly_map = MEM_mallocN(sizeof(*edge_poly_map) * totedge, __func__);
+ edge_poly_map = MEM_malloc_arrayN(totedge, sizeof(*edge_poly_map), __func__);
memset(edge_poly_map, 0xff, sizeof(*edge_poly_map) * totedge);
- vert_loop_map = MEM_mallocN(sizeof(*vert_loop_map) * totvert, __func__);
+ vert_loop_map = MEM_malloc_arrayN(totvert, sizeof(*vert_loop_map), __func__);
memset(vert_loop_map, 0xff, sizeof(*vert_loop_map) * totvert);
for (i = 0, mp_orig = mpoly_orig; i < totpoly; i++, mp_orig++) {
@@ -447,7 +498,7 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
* This makes the modifier faster with one less alloc.
*/
- vert_connect = MEM_mallocN(sizeof(ScrewVertConnect) * totvert, "ScrewVertConnect");
+ vert_connect = MEM_malloc_arrayN(totvert, sizeof(ScrewVertConnect), "ScrewVertConnect");
//vert_connect = (ScrewVertConnect *) &medge_new[totvert]; /* skip the first slice of verts */
vc = vert_connect;
@@ -1050,6 +1101,16 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
MEM_freeN(vert_loop_map);
}
+ if ((ltmd->flag & MOD_SCREW_MERGE) && (screw_ofs == 0.0f)) {
+ DerivedMesh *result_prev = result;
+ result = dm_remove_doubles_on_axis(
+ result, mvert_new, totvert, step_tot,
+ axis_vec, ltmd->ob_axis ? mtx_tx[3] : NULL, ltmd->merge_dist);
+ if (result != result_prev) {
+ result->dirty |= DM_DIRTY_NORMALS;
+ }
+ }
+
if ((ltmd->flag & MOD_SCREW_NORMAL_CALC) == 0) {
result->dirty |= DM_DIRTY_NORMALS;
}
@@ -1058,32 +1119,24 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ScrewModifierData *ltmd = (ScrewModifierData *) md;
if (ltmd->ob_axis) {
- DagNode *curNode = dag_get_node(forest, ltmd->ob_axis);
+ DagNode *curNode = dag_get_node(ctx->forest, ltmd->ob_axis);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"Screw Modifier");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ScrewModifierData *ltmd = (ScrewModifierData *)md;
if (ltmd->ob_axis != NULL) {
- DEG_add_object_relation(node, ltmd->ob_axis, DEG_OB_COMP_TRANSFORM, "Screw Modifier");
+ DEG_add_object_relation(ctx->node, ltmd->ob_axis, DEG_OB_COMP_TRANSFORM, "Screw Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_shrinkwrap.c b/source/blender/modifiers/intern/MOD_shrinkwrap.c
index a14747bc153..e0f48ae5a2f 100644
--- a/source/blender/modifiers/intern/MOD_shrinkwrap.c
+++ b/source/blender/modifiers/intern/MOD_shrinkwrap.c
@@ -143,37 +143,29 @@ static void deformVertsEM(ModifierData *md, Object *ob, struct BMEditMesh *editD
dm->release(dm);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ShrinkwrapModifierData *smd = (ShrinkwrapModifierData *) md;
if (smd->target)
- dag_add_relation(forest, dag_get_node(forest, smd->target), obNode,
+ dag_add_relation(ctx->forest, dag_get_node(ctx->forest, smd->target), ctx->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_add_relation(ctx->forest, dag_get_node(ctx->forest, smd->auxTarget), ctx->obNode,
DAG_RL_OB_DATA | DAG_RL_DATA_DATA, "Shrinkwrap Modifier");
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
ShrinkwrapModifierData *smd = (ShrinkwrapModifierData *)md;
if (smd->target != NULL) {
- DEG_add_object_relation(node, smd->target, DEG_OB_COMP_TRANSFORM, "Shrinkwrap Modifier");
- DEG_add_object_relation(node, smd->target, DEG_OB_COMP_GEOMETRY, "Shrinkwrap Modifier");
+ DEG_add_object_relation(ctx->node, smd->target, DEG_OB_COMP_TRANSFORM, "Shrinkwrap Modifier");
+ DEG_add_object_relation(ctx->node, smd->target, DEG_OB_COMP_GEOMETRY, "Shrinkwrap Modifier");
}
if (smd->auxTarget != NULL) {
- DEG_add_object_relation(node, smd->auxTarget, DEG_OB_COMP_TRANSFORM, "Shrinkwrap Modifier");
- DEG_add_object_relation(node, smd->auxTarget, DEG_OB_COMP_GEOMETRY, "Shrinkwrap Modifier");
+ DEG_add_object_relation(ctx->node, smd->auxTarget, DEG_OB_COMP_TRANSFORM, "Shrinkwrap Modifier");
+ DEG_add_object_relation(ctx->node, smd->auxTarget, DEG_OB_COMP_GEOMETRY, "Shrinkwrap Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_simpledeform.c b/source/blender/modifiers/intern/MOD_simpledeform.c
index 379eaea5b0c..71109922f11 100644
--- a/source/blender/modifiers/intern/MOD_simpledeform.c
+++ b/source/blender/modifiers/intern/MOD_simpledeform.c
@@ -32,7 +32,6 @@
* \ingroup modifiers
*/
-
#include "DNA_meshdata_types.h"
#include "DNA_object_types.h"
@@ -51,9 +50,33 @@
#define BEND_EPS 0.000001f
+/* Re-maps the indicies for X Y Z by shifting them up and wrapping, such that
+ * X = Y, Y = Z, Z = X (for X axis), and X = Z, Y = X, Z = Y (for Y axis). This
+ * exists because the deformations (excluding bend) are based on the Z axis.
+ * Having this helps avoid long, drawn out switches. */
+static const uint axis_map_table[3][3] = {
+ {1, 2, 0},
+ {2, 0, 1},
+ {0, 1, 2},
+};
+
+BLI_INLINE void copy_v3_v3_map(float a[3], const float b[3], const uint map[3])
+{
+ a[0] = b[map[0]];
+ a[1] = b[map[1]];
+ a[2] = b[map[2]];
+}
+
+BLI_INLINE void copy_v3_v3_unmap(float a[3], const float b[3], const uint map[3])
+{
+ a[map[0]] = b[0];
+ a[map[1]] = b[1];
+ a[map[2]] = b[2];
+}
+
/* Clamps/Limits the given coordinate to: limits[0] <= co[axis] <= limits[1]
* The amount of clamp is saved on dcut */
-static void axis_limit(int axis, const float limits[2], float co[3], float dcut[3])
+static void axis_limit(const int axis, const float limits[2], float co[3], float dcut[3])
{
float val = co[axis];
if (limits[0] > val) val = limits[0];
@@ -63,7 +86,7 @@ static void axis_limit(int axis, const float limits[2], float co[3], float dcut[
co[axis] = val;
}
-static void simpleDeform_taper(const float factor, const float dcut[3], float r_co[3])
+static void simpleDeform_taper(const float factor, const int UNUSED(axis), const float dcut[3], float r_co[3])
{
float x = r_co[0], y = r_co[1], z = r_co[2];
float scale = z * factor;
@@ -72,14 +95,10 @@ static void simpleDeform_taper(const float factor, const float dcut[3], float r_
r_co[1] = y + y * scale;
r_co[2] = z;
- {
- r_co[0] += dcut[0];
- r_co[1] += dcut[1];
- r_co[2] += dcut[2];
- }
+ add_v3_v3(r_co, dcut);
}
-static void simpleDeform_stretch(const float factor, const float dcut[3], float r_co[3])
+static void simpleDeform_stretch(const float factor, const int UNUSED(axis), const float dcut[3], float r_co[3])
{
float x = r_co[0], y = r_co[1], z = r_co[2];
float scale;
@@ -90,14 +109,10 @@ static void simpleDeform_stretch(const float factor, const float dcut[3], float
r_co[1] = y * scale;
r_co[2] = z * (1.0f + factor);
- {
- r_co[0] += dcut[0];
- r_co[1] += dcut[1];
- r_co[2] += dcut[2];
- }
+ add_v3_v3(r_co, dcut);
}
-static void simpleDeform_twist(const float factor, const float *dcut, float r_co[3])
+static void simpleDeform_twist(const float factor, const int UNUSED(axis), const float *dcut, float r_co[3])
{
float x = r_co[0], y = r_co[1], z = r_co[2];
float theta, sint, cost;
@@ -110,32 +125,58 @@ static void simpleDeform_twist(const float factor, const float *dcut, float r_co
r_co[1] = x * sint + y * cost;
r_co[2] = z;
- {
- r_co[0] += dcut[0];
- r_co[1] += dcut[1];
- r_co[2] += dcut[2];
- }
+ add_v3_v3(r_co, dcut);
}
-static void simpleDeform_bend(const float factor, const float dcut[3], float r_co[3])
+static void simpleDeform_bend(const float factor, const int axis, const float dcut[3], float r_co[3])
{
float x = r_co[0], y = r_co[1], z = r_co[2];
float theta, sint, cost;
BLI_assert(!(fabsf(factor) < BEND_EPS));
- theta = x * factor;
+ switch (axis) {
+ case 0:
+ ATTR_FALLTHROUGH;
+ case 1:
+ theta = z * factor;
+ break;
+ default:
+ theta = x * factor;
+ }
sint = sinf(theta);
cost = cosf(theta);
- r_co[0] = -(y - 1.0f / factor) * sint;
- r_co[1] = (y - 1.0f / factor) * cost + 1.0f / factor;
- r_co[2] = z;
-
- {
- r_co[0] += cost * dcut[0];
- r_co[1] += sint * dcut[0];
- r_co[2] += dcut[2];
+ switch (axis) {
+ case 0:
+ r_co[0] = x;
+ r_co[1] = (y - 1.0f / factor) * cost + 1.0f / factor;
+ r_co[2] = -(y - 1.0f / factor) * sint;
+ {
+ r_co[0] += dcut[0];
+ r_co[1] += sint * dcut[2];
+ r_co[2] += cost * dcut[2];
+ }
+ break;
+ case 1:
+ r_co[0] = (x - 1.0f / factor) * cost + 1.0f / factor;
+ r_co[1] = y;
+ r_co[2] = -(x - 1.0f / factor) * sint;
+ {
+ r_co[0] += sint * dcut[2];
+ r_co[1] += dcut[1];
+ r_co[2] += cost * dcut[2];
+ }
+ break;
+ default:
+ r_co[0] = -(y - 1.0f / factor) * sint;
+ r_co[1] = (y - 1.0f / factor) * cost + 1.0f / factor;
+ r_co[2] = z;
+ {
+ r_co[0] += cost * dcut[0];
+ r_co[1] += sint * dcut[0];
+ r_co[2] += dcut[2];
+ }
}
}
@@ -145,16 +186,36 @@ static void simpleDeform_bend(const float factor, const float dcut[3], float r_c
static 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};
+ const float base_limit[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[3]) = NULL; /* Mode callback */
+ void (*simpleDeform_callback)(const float factor, const int axis, const float dcut[3], float co[3]) = NULL; /* Mode callback */
int vgroup;
MDeformVert *dvert;
+ /* This is historically the lock axis, _not_ the deform axis as the name would imply */
+ const int deform_axis = smd->deform_axis;
+ int lock_axis = smd->axis;
+ if (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) { /* Bend mode shouln't have any lock axis */
+ lock_axis = 0;
+ }
+ else {
+ /* Don't lock axis if it is the chosen deform axis, as this flattens
+ * the geometry */
+ if (deform_axis == 0) {
+ lock_axis &= ~MOD_SIMPLEDEFORM_LOCK_AXIS_X;
+ }
+ if (deform_axis == 1) {
+ lock_axis &= ~MOD_SIMPLEDEFORM_LOCK_AXIS_Y;
+ }
+ if (deform_axis == 2) {
+ lock_axis &= ~MOD_SIMPLEDEFORM_LOCK_AXIS_Z;
+ }
+ }
+
+
/* Safe-check */
if (smd->origin == ob) smd->origin = NULL; /* No self references */
@@ -169,11 +230,21 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
BLI_SPACE_TRANSFORM_SETUP(transf, ob, smd->origin);
}
- /* Setup vars,
- * Bend limits on X.. all other modes limit on Z */
- limit_axis = (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) ? 0 : 2;
-
/* Update limits if needed */
+ int limit_axis = deform_axis;
+ if (smd->mode == MOD_SIMPLEDEFORM_MODE_BEND) {
+ /* Bend is a special case. */
+ switch (deform_axis) {
+ case 0:
+ ATTR_FALLTHROUGH;
+ case 1:
+ limit_axis = 2;
+ break;
+ default:
+ limit_axis = 0;
+ }
+ }
+
{
float lower = FLT_MAX;
float upper = -FLT_MAX;
@@ -215,6 +286,7 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
modifier_get_vgroup(ob, dm, smd->vgroup_name, &dvert, &vgroup);
const bool invert_vgroup = (smd->flag & MOD_SIMPLEDEFORM_FLAG_INVERT_VGROUP) != 0;
+ const uint *axis_map = axis_map_table[(smd->mode != MOD_SIMPLEDEFORM_MODE_BEND) ? deform_axis : 2];
for (i = 0; i < numVerts; i++) {
float weight = defvert_array_find_weight_safe(dvert, i, vgroup);
@@ -232,14 +304,26 @@ static void SimpleDeformModifier_do(SimpleDeformModifierData *smd, struct Object
copy_v3_v3(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);
+ /* Apply axis limits, and axis mappings */
+ if (lock_axis & MOD_SIMPLEDEFORM_LOCK_AXIS_X) {
+ axis_limit(0, base_limit, co, dcut);
+ }
+ if (lock_axis & MOD_SIMPLEDEFORM_LOCK_AXIS_Y) {
+ axis_limit(1, base_limit, co, dcut);
+ }
+ if (lock_axis & MOD_SIMPLEDEFORM_LOCK_AXIS_Z) {
+ axis_limit(2, base_limit, co, dcut);
}
axis_limit(limit_axis, smd_limit, co, dcut);
- simpleDeform_callback(smd_factor, dcut, co); /* apply deform */
+ /* apply the deform to a mapped copy of the vertex, and then re-map it back. */
+ float co_remap[3];
+ float dcut_remap[3];
+ copy_v3_v3_map(co_remap, co, axis_map);
+ copy_v3_v3_map(dcut_remap, dcut, axis_map);
+ simpleDeform_callback(smd_factor, deform_axis, dcut_remap, co_remap); /* apply deform */
+ copy_v3_v3_unmap(co, co_remap, axis_map);
+
interp_v3_v3v3(vertexCos[i], vertexCos[i], co, weight); /* Use vertex weight has coef of linear interpolation */
if (transf) {
@@ -257,6 +341,7 @@ static void initData(ModifierData *md)
smd->mode = MOD_SIMPLEDEFORM_MODE_TWIST;
smd->axis = 0;
+ smd->deform_axis = 0;
smd->origin = NULL;
smd->factor = DEG2RADF(45.0f);
@@ -293,27 +378,19 @@ static void foreachObjectLink(
walk(userData, ob, &smd->origin, IDWALK_CB_NOP);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
SimpleDeformModifierData *smd = (SimpleDeformModifierData *)md;
if (smd->origin)
- dag_add_relation(forest, dag_get_node(forest, smd->origin), obNode, DAG_RL_OB_DATA, "SimpleDeform Modifier");
+ dag_add_relation(ctx->forest, dag_get_node(ctx->forest, smd->origin), ctx->obNode, DAG_RL_OB_DATA, "SimpleDeform Modifier");
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
SimpleDeformModifierData *smd = (SimpleDeformModifierData *)md;
if (smd->origin != NULL) {
- DEG_add_object_relation(node, smd->origin, DEG_OB_COMP_TRANSFORM, "SimpleDeform Modifier");
+ DEG_add_object_relation(ctx->node, smd->origin, DEG_OB_COMP_TRANSFORM, "SimpleDeform Modifier");
}
}
diff --git a/source/blender/modifiers/intern/MOD_skin.c b/source/blender/modifiers/intern/MOD_skin.c
index 8ed623734be..dda0c413f57 100644
--- a/source/blender/modifiers/intern/MOD_skin.c
+++ b/source/blender/modifiers/intern/MOD_skin.c
@@ -77,6 +77,8 @@
#include "BKE_mesh_mapping.h"
#include "BKE_modifier.h"
+#include "MOD_modifiertypes.h"
+
#include "bmesh.h"
typedef struct {
@@ -417,7 +419,7 @@ static Frame **collect_hull_frames(int v, SkinNode *frames,
int nbr, i;
(*tothullframe) = emap[v].count;
- hull_frames = MEM_callocN(sizeof(Frame *) * (*tothullframe),
+ hull_frames = MEM_calloc_arrayN((*tothullframe), sizeof(Frame *),
"hull_from_frames.hull_frames");
i = 0;
for (nbr = 0; nbr < emap[v].count; nbr++) {
@@ -598,7 +600,7 @@ static SkinNode *build_frames(const MVert *mvert, int totvert,
SkinNode *skin_nodes;
int v;
- skin_nodes = MEM_callocN(sizeof(SkinNode) * totvert, "build_frames.skin_nodes");
+ skin_nodes = MEM_calloc_arrayN(totvert, sizeof(SkinNode), "build_frames.skin_nodes");
for (v = 0; v < totvert; v++) {
if (emap[v].count <= 1)
@@ -720,7 +722,7 @@ static EMat *build_edge_mats(const MVertSkin *vs,
stack = BLI_stack_new(sizeof(stack_elem), "build_edge_mats.stack");
visited_e = BLI_BITMAP_NEW(totedge, "build_edge_mats.visited_e");
- emat = MEM_callocN(sizeof(EMat) * totedge, "build_edge_mats.emat");
+ emat = MEM_calloc_arrayN(totedge, sizeof(EMat), "build_edge_mats.emat");
/* Edge matrices are built from the root nodes, add all roots with
* children to the stack */
@@ -834,14 +836,14 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig)
totorigedge = orig->getNumEdges(orig);
/* Get degree of all vertices */
- degree = MEM_callocN(sizeof(int) * totorigvert, "degree");
+ degree = MEM_calloc_arrayN(totorigvert, sizeof(int), "degree");
for (i = 0; i < totorigedge; i++) {
degree[origedge[i].v1]++;
degree[origedge[i].v2]++;
}
/* Per edge, store how many subdivisions are needed */
- edge_subd = MEM_callocN(sizeof(int) * totorigedge, "edge_subd");
+ edge_subd = MEM_calloc_arrayN(totorigedge, sizeof(int), "edge_subd");
for (i = 0, totsubd = 0; i < totorigedge; i++) {
edge_subd[i] += calc_edge_subdivisions(origvert, orignode,
&origedge[i], degree);
@@ -880,7 +882,7 @@ static DerivedMesh *subdivide_base(DerivedMesh *orig)
if (origdvert) {
const MDeformVert *dv1 = &origdvert[e->v1];
const MDeformVert *dv2 = &origdvert[e->v2];
- vgroups = MEM_callocN(sizeof(*vgroups) * dv1->totweight, "vgroup");
+ vgroups = MEM_calloc_arrayN(dv1->totweight, sizeof(*vgroups), "vgroup");
/* Only want vertex groups used by both vertices */
for (j = 0; j < dv1->totweight; j++) {
@@ -1302,9 +1304,9 @@ static void skin_fix_hole_no_good_verts(BMesh *bm, Frame *frame, BMFace *split_f
else if (split_face->len > 4) {
/* Maintain a dynamic vert array containing the split_face's
* vertices, avoids frequent allocs in collapse_face_corners() */
- if (BLI_array_count(vert_buf) < split_face->len) {
+ if (BLI_array_len(vert_buf) < split_face->len) {
BLI_array_grow_items(vert_buf, (split_face->len -
- BLI_array_count(vert_buf)));
+ BLI_array_len(vert_buf)));
}
/* Get split face's verts */
@@ -1468,7 +1470,7 @@ static void hull_merge_triangles(SkinOutput *so, const SkinModifierData *smd)
while (!BLI_heap_is_empty(heap)) {
BMFace *adj[2];
- e = BLI_heap_popmin(heap);
+ e = BLI_heap_pop_min(heap);
if (BM_edge_face_pair(e, &adj[0], &adj[1])) {
/* If both triangles still free, and if they don't already
diff --git a/source/blender/modifiers/intern/MOD_smoke.c b/source/blender/modifiers/intern/MOD_smoke.c
index c105a3ab3a7..2073e23b7b2 100644
--- a/source/blender/modifiers/intern/MOD_smoke.c
+++ b/source/blender/modifiers/intern/MOD_smoke.c
@@ -41,11 +41,10 @@
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "DNA_smoke_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "BLI_utildefines.h"
-
#include "BKE_cdderivedmesh.h"
#include "BKE_library.h"
#include "BKE_library_query.h"
@@ -56,6 +55,8 @@
#include "depsgraph_private.h"
#include "DEG_depsgraph_build.h"
+#include "MOD_modifiertypes.h"
+
static void initData(ModifierData *md)
{
SmokeModifierData *smd = (SmokeModifierData *) md;
@@ -129,42 +130,32 @@ static bool is_coll_cb(Object *UNUSED(ob), ModifierData *md)
return (smd->type & MOD_SMOKE_TYPE_COLL) && smd->coll;
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *scene, struct Object *ob,
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
SmokeModifierData *smd = (SmokeModifierData *) md;
if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) {
/* Actual code uses get_collisionobjects */
#ifdef WITH_LEGACY_DEPSGRAPH
- dag_add_collision_relations(forest, scene, ob, obNode, smd->domain->fluid_group, ob->lay|scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow");
- dag_add_collision_relations(forest, scene, ob, obNode, smd->domain->coll_group, ob->lay|scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll");
- dag_add_forcefield_relations(forest, scene, ob, obNode, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field");
+ dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->fluid_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow");
+ dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->coll_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll");
+ dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field");
#else
- (void)forest;
- (void)scene;
- (void)ob;
- (void)obNode;
+ (void)ctx;
#endif
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
SmokeModifierData *smd = (SmokeModifierData *)md;
if (smd && (smd->type & MOD_SMOKE_TYPE_DOMAIN) && smd->domain) {
/* Actual code uses get_collisionobjects */
- DEG_add_collision_relations(node, scene, ob, smd->domain->fluid_group, ob->lay|scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow");
- DEG_add_collision_relations(node, scene, ob, smd->domain->coll_group, ob->lay|scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll");
+ DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->fluid_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_flow_cb, true, "Smoke Flow");
+ DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, smd->domain->coll_group, ctx->object->lay|ctx->scene->lay, eModifierType_Smoke, is_coll_cb, true, "Smoke Coll");
- DEG_add_forcefield_relations(node, scene, ob, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field");
+ DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, smd->domain->effector_weights, true, PFIELD_SMOKEFLOW, "Smoke Force Field");
}
}
diff --git a/source/blender/modifiers/intern/MOD_smooth.c b/source/blender/modifiers/intern/MOD_smooth.c
index d45c8528510..92025512f02 100644
--- a/source/blender/modifiers/intern/MOD_smooth.c
+++ b/source/blender/modifiers/intern/MOD_smooth.c
@@ -102,10 +102,10 @@ static void smoothModifier_do(
unsigned char *uctmp;
float *ftmp, fac, facm;
- ftmp = (float *)MEM_callocN(3 * sizeof(float) * numVerts,
+ ftmp = (float *)MEM_calloc_arrayN(numVerts, 3 * sizeof(float),
"smoothmodifier_f");
if (!ftmp) return;
- uctmp = (unsigned char *)MEM_callocN(sizeof(unsigned char) * numVerts,
+ uctmp = (unsigned char *)MEM_calloc_arrayN(numVerts, sizeof(unsigned char),
"smoothmodifier_uc");
if (!uctmp) {
if (ftmp) MEM_freeN(ftmp);
diff --git a/source/blender/modifiers/intern/MOD_softbody.c b/source/blender/modifiers/intern/MOD_softbody.c
index a0bbe5da04a..e760ff5ca01 100644
--- a/source/blender/modifiers/intern/MOD_softbody.c
+++ b/source/blender/modifiers/intern/MOD_softbody.c
@@ -35,7 +35,7 @@
#include <stdio.h>
#include "DNA_scene_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "BLI_utildefines.h"
@@ -62,36 +62,27 @@ static bool dependsOnTime(ModifierData *UNUSED(md))
return true;
}
-static void updateDepgraph(ModifierData *UNUSED(md), DagForest *forest,
- struct Main *UNUSED(bmain),
- Scene *scene, Object *ob, DagNode *obNode)
+static void updateDepgraph(ModifierData *UNUSED(md), const ModifierUpdateDepsgraphContext *ctx)
{
- if (ob->soft) {
+ if (ctx->object->soft) {
#ifdef WITH_LEGACY_DEPSGRAPH
/* Actual code uses ccd_build_deflector_hash */
- dag_add_collision_relations(forest, scene, ob, obNode, ob->soft->collision_group, ob->lay, eModifierType_Collision, NULL, false, "Softbody Collision");
+ dag_add_collision_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, ctx->object->soft->collision_group, ctx->object->lay, eModifierType_Collision, NULL, false, "Softbody Collision");
- dag_add_forcefield_relations(forest, scene, ob, obNode, ob->soft->effector_weights, true, 0, "Softbody Field");
+ dag_add_forcefield_relations(ctx->forest, ctx->scene, ctx->object, ctx->obNode, ctx->object->soft->effector_weights, true, 0, "Softbody Field");
#else
- (void)forest;
- (void)scene;
- (void)ob;
- (void)obNode;
+ (void)ctx;
#endif
}
}
-static void updateDepsgraph(ModifierData *UNUSED(md),
- struct Main *UNUSED(bmain),
- struct Scene *scene,
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *UNUSED(md), const ModifierUpdateDepsgraphContext *ctx)
{
- if (ob->soft) {
+ if (ctx->object->soft) {
/* Actual code uses ccd_build_deflector_hash */
- DEG_add_collision_relations(node, scene, ob, ob->soft->collision_group, ob->lay, eModifierType_Collision, NULL, false, "Softbody Collision");
+ DEG_add_collision_relations(ctx->node, ctx->scene, ctx->object, ctx->object->soft->collision_group, ctx->object->lay, eModifierType_Collision, NULL, false, "Softbody Collision");
- DEG_add_forcefield_relations(node, scene, ob, ob->soft->effector_weights, true, 0, "Softbody Field");
+ DEG_add_forcefield_relations(ctx->node, ctx->scene, ctx->object, ctx->object->soft->effector_weights, true, 0, "Softbody Field");
}
}
diff --git a/source/blender/modifiers/intern/MOD_solidify.c b/source/blender/modifiers/intern/MOD_solidify.c
index 911b6997058..aa5b0caea2a 100644
--- a/source/blender/modifiers/intern/MOD_solidify.c
+++ b/source/blender/modifiers/intern/MOD_solidify.c
@@ -36,7 +36,7 @@
#include "MEM_guardedalloc.h"
#include "BLI_utildefines.h"
-#include "BLI_stackdefines.h"
+#include "BLI_utildefines_stack.h"
#include "BLI_bitmap.h"
#include "BLI_math.h"
@@ -101,7 +101,7 @@ static void dm_calc_normal(DerivedMesh *dm, float (*face_nors)[3], float (*r_ver
mp = mpoly;
{
- EdgeFaceRef *edge_ref_array = MEM_callocN(sizeof(EdgeFaceRef) * (size_t)numEdges, "Edge Connectivity");
+ EdgeFaceRef *edge_ref_array = MEM_calloc_arrayN((size_t)numEdges, sizeof(EdgeFaceRef), "Edge Connectivity");
EdgeFaceRef *edge_ref;
float edge_normal[3];
@@ -235,7 +235,7 @@ static DerivedMesh *applyModifier(
unsigned int *new_edge_arr = NULL;
STACK_DECLARE(new_edge_arr);
- unsigned int *old_vert_arr = MEM_callocN(sizeof(*old_vert_arr) * (size_t)numVerts, "old_vert_arr in solidify");
+ unsigned int *old_vert_arr = MEM_calloc_arrayN(numVerts, sizeof(*old_vert_arr), "old_vert_arr in solidify");
unsigned int *edge_users = NULL;
char *edge_order = NULL;
@@ -270,7 +270,7 @@ static DerivedMesh *applyModifier(
if (need_face_normals) {
/* calculate only face normals */
- face_nors = MEM_mallocN(sizeof(*face_nors) * (size_t)numFaces, __func__);
+ face_nors = MEM_malloc_arrayN(numFaces, sizeof(*face_nors), __func__);
BKE_mesh_calc_normals_poly(
orig_mvert, NULL, (int)numVerts,
orig_mloop, orig_mpoly,
@@ -289,11 +289,11 @@ static DerivedMesh *applyModifier(
#define INVALID_UNUSED ((unsigned int)-1)
#define INVALID_PAIR ((unsigned int)-2)
- new_vert_arr = MEM_mallocN(sizeof(*new_vert_arr) * (size_t)(numVerts * 2), __func__);
- new_edge_arr = MEM_mallocN(sizeof(*new_edge_arr) * (size_t)((numEdges * 2) + numVerts), __func__);
+ new_vert_arr = MEM_malloc_arrayN(numVerts, 2 * sizeof(*new_vert_arr), __func__);
+ new_edge_arr = MEM_malloc_arrayN(((numEdges * 2) + numVerts), sizeof(*new_edge_arr), __func__);
- edge_users = MEM_mallocN(sizeof(*edge_users) * (size_t)numEdges, "solid_mod edges");
- edge_order = MEM_mallocN(sizeof(*edge_order) * (size_t)numEdges, "solid_mod eorder");
+ edge_users = MEM_malloc_arrayN(numEdges, sizeof(*edge_users), "solid_mod edges");
+ edge_order = MEM_malloc_arrayN(numEdges, sizeof(*edge_order), "solid_mod eorder");
/* save doing 2 loops here... */
@@ -366,7 +366,7 @@ static DerivedMesh *applyModifier(
}
if (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) {
- vert_nors = MEM_callocN(sizeof(float) * (size_t)numVerts * 3, "mod_solid_vno_hq");
+ vert_nors = MEM_calloc_arrayN(numVerts, 3 * sizeof(float), "mod_solid_vno_hq");
dm_calc_normal(dm, face_nors, vert_nors);
}
@@ -517,7 +517,7 @@ static DerivedMesh *applyModifier(
if (do_clamp) {
unsigned int i;
- vert_lens = MEM_mallocN(sizeof(float) * numVerts, "vert_lens");
+ vert_lens = MEM_malloc_arrayN(numVerts, sizeof(float), "vert_lens");
copy_vn_fl(vert_lens, (int)numVerts, FLT_MAX);
for (i = 0; i < numEdges; i++) {
const float ed_len_sq = len_squared_v3v3(mvert[medge[i].v1].co, mvert[medge[i].v2].co);
@@ -596,13 +596,13 @@ static DerivedMesh *applyModifier(
const bool check_non_manifold = (smd->flag & MOD_SOLIDIFY_NORMAL_CALC) != 0;
#endif
/* same as EM_solidify() in editmesh_lib.c */
- float *vert_angles = MEM_callocN(sizeof(float) * numVerts * 2, "mod_solid_pair"); /* 2 in 1 */
+ float *vert_angles = MEM_calloc_arrayN(numVerts, 2 * sizeof(float), "mod_solid_pair"); /* 2 in 1 */
float *vert_accum = vert_angles + numVerts;
unsigned int vidx;
unsigned int i;
if (vert_nors == NULL) {
- vert_nors = MEM_mallocN(sizeof(float) * numVerts * 3, "mod_solid_vno");
+ vert_nors = MEM_malloc_arrayN(numVerts, 3 * sizeof(float), "mod_solid_vno");
for (i = 0, mv = mvert; i < numVerts; i++, mv++) {
normal_short_to_float_v3(vert_nors[i], mv->no);
}
@@ -682,7 +682,7 @@ static DerivedMesh *applyModifier(
}
if (do_clamp) {
- float *vert_lens_sq = MEM_mallocN(sizeof(float) * numVerts, "vert_lens");
+ float *vert_lens_sq = MEM_malloc_arrayN(numVerts, sizeof(float), "vert_lens");
const float offset = fabsf(smd->offset) * smd->offset_clamp;
const float offset_sq = offset * offset;
copy_vn_fl(vert_lens_sq, (int)numVerts, FLT_MAX);
@@ -765,7 +765,7 @@ static DerivedMesh *applyModifier(
#ifdef SOLIDIFY_SIDE_NORMALS
const bool do_side_normals = !(result->dirty & DM_DIRTY_NORMALS);
/* annoying to allocate these since we only need the edge verts, */
- float (*edge_vert_nos)[3] = do_side_normals ? MEM_callocN(sizeof(float) * numVerts * 3, __func__) : NULL;
+ float (*edge_vert_nos)[3] = do_side_normals ? MEM_calloc_arrayN(numVerts, 3 * sizeof(float), __func__) : NULL;
float nor[3];
#endif
const unsigned char crease_rim = smd->crease_rim * 255.0f;
diff --git a/source/blender/modifiers/intern/MOD_surface.c b/source/blender/modifiers/intern/MOD_surface.c
index 68987a1d28e..7bb4c0b2fd1 100644
--- a/source/blender/modifiers/intern/MOD_surface.c
+++ b/source/blender/modifiers/intern/MOD_surface.c
@@ -130,8 +130,8 @@ static void deformVerts(ModifierData *md, Object *ob,
surmd->v = NULL;
}
- surmd->x = MEM_callocN(numverts * sizeof(MVert), "MVert");
- surmd->v = MEM_callocN(numverts * sizeof(MVert), "MVert");
+ surmd->x = MEM_calloc_arrayN(numverts, sizeof(MVert), "MVert");
+ surmd->v = MEM_calloc_arrayN(numverts, sizeof(MVert), "MVert");
surmd->numverts = numverts;
@@ -172,6 +172,7 @@ ModifierTypeInfo modifierType_Surface = {
/* structSize */ sizeof(SurfaceModifierData),
/* type */ eModifierTypeType_OnlyDeform,
/* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_AcceptsCVs |
eModifierTypeFlag_NoUserAdd,
/* copyData */ NULL,
diff --git a/source/blender/modifiers/intern/MOD_surfacedeform.c b/source/blender/modifiers/intern/MOD_surfacedeform.c
new file mode 100644
index 00000000000..fc605dd48e1
--- /dev/null
+++ b/source/blender/modifiers/intern/MOD_surfacedeform.c
@@ -0,0 +1,1241 @@
+#include "DNA_object_types.h"
+#include "DNA_scene_types.h"
+
+#include "BLI_alloca.h"
+#include "BLI_math.h"
+#include "BLI_math_geom.h"
+#include "BLI_task.h"
+
+#include "BKE_cdderivedmesh.h"
+#include "BKE_editmesh.h"
+#include "BKE_library_query.h"
+#include "BKE_modifier.h"
+
+#include "depsgraph_private.h"
+
+#include "MEM_guardedalloc.h"
+
+#include "MOD_util.h"
+
+typedef struct SDefAdjacency {
+ struct SDefAdjacency *next;
+ unsigned int index;
+} SDefAdjacency;
+
+typedef struct SDefAdjacencyArray {
+ SDefAdjacency *first;
+ unsigned int num; /* Careful, this is twice the number of polygons (avoids an extra loop) */
+} SDefAdjacencyArray;
+
+typedef struct SDefEdgePolys {
+ unsigned int polys[2], num;
+} SDefEdgePolys;
+
+typedef struct SDefBindCalcData {
+ BVHTreeFromMesh * const treeData;
+ const SDefAdjacencyArray * const vert_edges;
+ const SDefEdgePolys * const edge_polys;
+ SDefVert * const bind_verts;
+ const MLoopTri * const looptri;
+ const MPoly * const mpoly;
+ const MEdge * const medge;
+ const MLoop * const mloop;
+ float (* const targetCos)[3];
+ float (* const vertexCos)[3];
+ float imat[4][4];
+ const float falloff;
+ int success;
+} SDefBindCalcData;
+
+typedef struct SDefBindPoly {
+ float (*coords)[3];
+ float (*coords_v2)[2];
+ float point_v2[2];
+ float weight_angular;
+ float weight_dist_proj;
+ float weight_dist;
+ float weight;
+ float scales[2];
+ float centroid[3];
+ float centroid_v2[2];
+ float normal[3];
+ float cent_edgemid_vecs_v2[2][2];
+ float edgemid_angle;
+ float point_edgemid_angles[2];
+ float corner_edgemid_angles[2];
+ float dominant_angle_weight;
+ unsigned int index;
+ unsigned int numverts;
+ unsigned int loopstart;
+ unsigned int edge_inds[2];
+ unsigned int edge_vert_inds[2];
+ unsigned int corner_ind;
+ unsigned int dominant_edge;
+ bool inside;
+} SDefBindPoly;
+
+typedef struct SDefBindWeightData {
+ SDefBindPoly *bind_polys;
+ unsigned int numpoly;
+ unsigned int numbinds;
+} SDefBindWeightData;
+
+typedef struct SDefDeformData {
+ const SDefVert * const bind_verts;
+ float (* const targetCos)[3];
+ float (* const vertexCos)[3];
+} SDefDeformData;
+
+/* Bind result values */
+enum {
+ MOD_SDEF_BIND_RESULT_SUCCESS = 1,
+ MOD_SDEF_BIND_RESULT_GENERIC_ERR = 0,
+ MOD_SDEF_BIND_RESULT_MEM_ERR = -1,
+ MOD_SDEF_BIND_RESULT_NONMANY_ERR = -2,
+ MOD_SDEF_BIND_RESULT_CONCAVE_ERR = -3,
+ MOD_SDEF_BIND_RESULT_OVERLAP_ERR = -4,
+};
+
+/* Infinite weight flags */
+enum {
+ MOD_SDEF_INFINITE_WEIGHT_ANGULAR = (1 << 0),
+ MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ = (1 << 1),
+ MOD_SDEF_INFINITE_WEIGHT_DIST = (1 << 2),
+};
+
+static void initData(ModifierData *md)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+ smd->target = NULL;
+ smd->verts = NULL;
+ smd->flags = 0;
+ smd->falloff = 4.0f;
+}
+
+static void freeData(ModifierData *md)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+
+ if (smd->verts) {
+ for (int i = 0; i < smd->numverts; i++) {
+ if (smd->verts[i].binds) {
+ for (int j = 0; j < smd->verts[i].numbinds; j++) {
+ MEM_SAFE_FREE(smd->verts[i].binds[j].vert_inds);
+ MEM_SAFE_FREE(smd->verts[i].binds[j].vert_weights);
+ }
+
+ MEM_freeN(smd->verts[i].binds);
+ }
+ }
+
+ MEM_freeN(smd->verts);
+ smd->verts = NULL;
+ }
+}
+
+static void copyData(ModifierData *md, ModifierData *target)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+ SurfaceDeformModifierData *tsmd = (SurfaceDeformModifierData *)target;
+
+ freeData(target);
+
+ modifier_copyData_generic(md, target);
+
+ if (smd->verts) {
+ tsmd->verts = MEM_dupallocN(smd->verts);
+
+ for (int i = 0; i < smd->numverts; i++) {
+ if (smd->verts[i].binds) {
+ tsmd->verts[i].binds = MEM_dupallocN(smd->verts[i].binds);
+
+ for (int j = 0; j < smd->verts[i].numbinds; j++) {
+ if (smd->verts[i].binds[j].vert_inds) {
+ tsmd->verts[i].binds[j].vert_inds = MEM_dupallocN(smd->verts[i].binds[j].vert_inds);
+ }
+
+ if (smd->verts[i].binds[j].vert_weights) {
+ tsmd->verts[i].binds[j].vert_weights = MEM_dupallocN(smd->verts[i].binds[j].vert_weights);
+ }
+ }
+ }
+ }
+ }
+}
+
+static void foreachObjectLink(ModifierData *md, Object *ob, ObjectWalkFunc walk, void *userData)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+
+ walk(userData, ob, &smd->target, IDWALK_NOP);
+}
+
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+
+ if (smd->target) {
+ DagNode *curNode = dag_get_node(ctx->forest, smd->target);
+
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA, "Surface Deform Modifier");
+ }
+}
+
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+ if (smd->target != NULL) {
+ DEG_add_object_relation(ctx->node, smd->target, DEG_OB_COMP_GEOMETRY, "Surface Deform Modifier");
+ }
+}
+
+static void freeAdjacencyMap(SDefAdjacencyArray * const vert_edges, SDefAdjacency * const adj_ref, SDefEdgePolys * const edge_polys)
+{
+ MEM_freeN(edge_polys);
+
+ MEM_freeN(adj_ref);
+
+ MEM_freeN(vert_edges);
+}
+
+static int buildAdjacencyMap(const MPoly *poly, const MEdge *edge, const MLoop * const mloop, const unsigned int numpoly, const unsigned int numedges,
+ SDefAdjacencyArray * const vert_edges, SDefAdjacency *adj, SDefEdgePolys * const edge_polys)
+{
+ const MLoop *loop;
+
+ /* Fing polygons adjacent to edges */
+ for (int i = 0; i < numpoly; i++, poly++) {
+ loop = &mloop[poly->loopstart];
+
+ for (int j = 0; j < poly->totloop; j++, loop++) {
+ if (edge_polys[loop->e].num == 0) {
+ edge_polys[loop->e].polys[0] = i;
+ edge_polys[loop->e].polys[1] = -1;
+ edge_polys[loop->e].num++;
+ }
+ else if (edge_polys[loop->e].num == 1) {
+ edge_polys[loop->e].polys[1] = i;
+ edge_polys[loop->e].num++;
+ }
+ else {
+ return MOD_SDEF_BIND_RESULT_NONMANY_ERR;
+ }
+ }
+ }
+
+ /* Find edges adjacent to vertices */
+ for (int i = 0; i < numedges; i++, edge++) {
+ adj->next = vert_edges[edge->v1].first;
+ adj->index = i;
+ vert_edges[edge->v1].first = adj;
+ vert_edges[edge->v1].num += edge_polys[i].num;
+ adj++;
+
+ adj->next = vert_edges[edge->v2].first;
+ adj->index = i;
+ vert_edges[edge->v2].first = adj;
+ vert_edges[edge->v2].num += edge_polys[i].num;
+ adj++;
+ }
+
+ return MOD_SDEF_BIND_RESULT_SUCCESS;
+}
+
+BLI_INLINE void sortPolyVertsEdge(unsigned int *indices, const MLoop * const mloop, const unsigned int edge, const unsigned int num)
+{
+ bool found = false;
+
+ for (int i = 0; i < num; i++) {
+ if (mloop[i].e == edge) {
+ found = true;
+ }
+ if (found) {
+ *indices = mloop[i].v;
+ indices++;
+ }
+ }
+
+ /* Fill in remaining vertex indices that occur before the edge */
+ for (int i = 0; mloop[i].e != edge; i++) {
+ *indices = mloop[i].v;
+ indices++;
+ }
+}
+
+BLI_INLINE void sortPolyVertsTri(unsigned int *indices, const MLoop * const mloop, const unsigned int loopstart, const unsigned int num)
+{
+ for (int i = loopstart; i < num; i++) {
+ *indices = mloop[i].v;
+ indices++;
+ }
+
+ for (int i = 0; i < loopstart; i++) {
+ *indices = mloop[i].v;
+ indices++;
+ }
+}
+
+BLI_INLINE unsigned int nearestVert(SDefBindCalcData * const data, const float point_co[3])
+{
+ BVHTreeNearest nearest = {.dist_sq = FLT_MAX, .index = -1};
+ const MPoly *poly;
+ const MEdge *edge;
+ const MLoop *loop;
+ float t_point[3];
+ float max_dist = FLT_MAX;
+ float dist;
+ unsigned int index = 0;
+
+ mul_v3_m4v3(t_point, data->imat, point_co);
+
+ BLI_bvhtree_find_nearest(data->treeData->tree, t_point, &nearest, data->treeData->nearest_callback, data->treeData);
+
+ poly = &data->mpoly[data->looptri[nearest.index].poly];
+ loop = &data->mloop[poly->loopstart];
+
+ for (int i = 0; i < poly->totloop; i++, loop++) {
+ edge = &data->medge[loop->e];
+ dist = dist_squared_to_line_segment_v3(point_co, data->targetCos[edge->v1], data->targetCos[edge->v2]);
+
+ if (dist < max_dist) {
+ max_dist = dist;
+ index = loop->e;
+ }
+ }
+
+ edge = &data->medge[index];
+ if (len_squared_v3v3(point_co, data->targetCos[edge->v1]) < len_squared_v3v3(point_co, data->targetCos[edge->v2])) {
+ return edge->v1;
+ }
+ else {
+ return edge->v2;
+ }
+}
+
+BLI_INLINE int isPolyValid(const float coords[][2], const unsigned int nr)
+{
+ float prev_co[2];
+ float curr_vec[2], prev_vec[2];
+
+ if (!is_poly_convex_v2(coords, nr)) {
+ return MOD_SDEF_BIND_RESULT_CONCAVE_ERR;
+ }
+
+ copy_v2_v2(prev_co, coords[nr - 1]);
+ sub_v2_v2v2(prev_vec, prev_co, coords[nr - 2]);
+ normalize_v2(prev_vec);
+
+ for (int i = 0; i < nr; i++) {
+ sub_v2_v2v2(curr_vec, coords[i], prev_co);
+
+ const float curr_len = normalize_v2(curr_vec);
+ if (curr_len < FLT_EPSILON) {
+ return MOD_SDEF_BIND_RESULT_OVERLAP_ERR;
+ }
+
+ if (1.0f - dot_v2v2(prev_vec, curr_vec) < FLT_EPSILON) {
+ return MOD_SDEF_BIND_RESULT_CONCAVE_ERR;
+ }
+
+ copy_v2_v2(prev_co, coords[i]);
+ copy_v2_v2(prev_vec, curr_vec);
+ }
+
+ return MOD_SDEF_BIND_RESULT_SUCCESS;
+}
+
+static void freeBindData(SDefBindWeightData * const bwdata)
+{
+ SDefBindPoly *bpoly = bwdata->bind_polys;
+
+ if (bwdata->bind_polys) {
+ for (int i = 0; i < bwdata->numpoly; bpoly++, i++) {
+ MEM_SAFE_FREE(bpoly->coords);
+ MEM_SAFE_FREE(bpoly->coords_v2);
+ }
+
+ MEM_freeN(bwdata->bind_polys);
+ }
+
+ MEM_freeN(bwdata);
+}
+
+BLI_INLINE float computeAngularWeight(const float point_angle, const float edgemid_angle)
+{
+ float weight;
+
+ weight = point_angle;
+ weight /= edgemid_angle;
+ weight *= M_PI_2;
+
+ return sinf(weight);
+}
+
+BLI_INLINE SDefBindWeightData *computeBindWeights(SDefBindCalcData * const data, const float point_co[3])
+{
+ const unsigned int nearest = nearestVert(data, point_co);
+ const SDefAdjacency * const vert_edges = data->vert_edges[nearest].first;
+ const SDefEdgePolys * const edge_polys = data->edge_polys;
+
+ const SDefAdjacency *vedge;
+ const MPoly *poly;
+ const MLoop *loop;
+
+ SDefBindWeightData *bwdata;
+ SDefBindPoly *bpoly;
+
+ float world[3] = {0.0f, 0.0f, 1.0f};
+ float avg_point_dist = 0.0f;
+ float tot_weight = 0.0f;
+ int inf_weight_flags = 0;
+
+ bwdata = MEM_callocN(sizeof(*bwdata), "SDefBindWeightData");
+ if (bwdata == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return NULL;
+ }
+
+ bwdata->numpoly = data->vert_edges[nearest].num / 2;
+
+ bpoly = MEM_calloc_arrayN(bwdata->numpoly, sizeof(*bpoly), "SDefBindPoly");
+ if (bpoly == NULL) {
+ freeBindData(bwdata);
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return NULL;
+ }
+
+ bwdata->bind_polys = bpoly;
+
+ /* Loop over all adjacent edges, and build the SDefBindPoly data for each poly adjacent to those */
+ for (vedge = vert_edges; vedge; vedge = vedge->next) {
+ unsigned int edge_ind = vedge->index;
+
+ for (int i = 0; i < edge_polys[edge_ind].num; i++) {
+ {
+ bpoly = bwdata->bind_polys;
+
+ for (int j = 0; j < bwdata->numpoly; bpoly++, j++) {
+ /* If coords isn't allocated, we have reached the first uninitialized bpoly */
+ if ((bpoly->index == edge_polys[edge_ind].polys[i]) || (!bpoly->coords)) {
+ break;
+ }
+ }
+ }
+
+ /* Check if poly was already created by another edge or still has to be initialized */
+ if (!bpoly->coords) {
+ float angle;
+ float axis[3];
+ float tmp_vec_v2[2];
+ int is_poly_valid;
+
+ bpoly->index = edge_polys[edge_ind].polys[i];
+ bpoly->coords = NULL;
+ bpoly->coords_v2 = NULL;
+
+ /* Copy poly data */
+ poly = &data->mpoly[bpoly->index];
+ loop = &data->mloop[poly->loopstart];
+
+ bpoly->numverts = poly->totloop;
+ bpoly->loopstart = poly->loopstart;
+
+ bpoly->coords = MEM_malloc_arrayN(poly->totloop, sizeof(*bpoly->coords), "SDefBindPolyCoords");
+ if (bpoly->coords == NULL) {
+ freeBindData(bwdata);
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return NULL;
+ }
+
+ bpoly->coords_v2 = MEM_malloc_arrayN(poly->totloop, sizeof(*bpoly->coords_v2), "SDefBindPolyCoords_v2");
+ if (bpoly->coords_v2 == NULL) {
+ freeBindData(bwdata);
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return NULL;
+ }
+
+ for (int j = 0; j < poly->totloop; j++, loop++) {
+ copy_v3_v3(bpoly->coords[j], data->targetCos[loop->v]);
+
+ /* Find corner and edge indices within poly loop array */
+ if (loop->v == nearest) {
+ bpoly->corner_ind = j;
+ bpoly->edge_vert_inds[0] = (j == 0) ? (poly->totloop - 1) : (j - 1);
+ bpoly->edge_vert_inds[1] = (j == poly->totloop - 1) ? (0) : (j + 1);
+
+ bpoly->edge_inds[0] = data->mloop[poly->loopstart + bpoly->edge_vert_inds[0]].e;
+ bpoly->edge_inds[1] = loop->e;
+ }
+ }
+
+ /* Compute poly's parametric data */
+ mid_v3_v3_array(bpoly->centroid, bpoly->coords, poly->totloop);
+ normal_poly_v3(bpoly->normal, bpoly->coords, poly->totloop);
+
+ /* Compute poly skew angle and axis */
+ angle = angle_normalized_v3v3(bpoly->normal, world);
+
+ cross_v3_v3v3(axis, bpoly->normal, world);
+ normalize_v3(axis);
+
+ /* Map coords onto 2d normal plane */
+ map_to_plane_axis_angle_v2_v3v3fl(bpoly->point_v2, point_co, axis, angle);
+
+ zero_v2(bpoly->centroid_v2);
+ for (int j = 0; j < poly->totloop; j++) {
+ map_to_plane_axis_angle_v2_v3v3fl(bpoly->coords_v2[j], bpoly->coords[j], axis, angle);
+ madd_v2_v2fl(bpoly->centroid_v2, bpoly->coords_v2[j], 1.0f / poly->totloop);
+ }
+
+ is_poly_valid = isPolyValid(bpoly->coords_v2, poly->totloop);
+
+ if (is_poly_valid != MOD_SDEF_BIND_RESULT_SUCCESS) {
+ freeBindData(bwdata);
+ data->success = is_poly_valid;
+ return NULL;
+ }
+
+ bpoly->inside = isect_point_poly_v2(bpoly->point_v2, bpoly->coords_v2, poly->totloop, false);
+
+ /* Initialize weight components */
+ bpoly->weight_angular = 1.0f;
+ bpoly->weight_dist_proj = len_v2v2(bpoly->centroid_v2, bpoly->point_v2);
+ bpoly->weight_dist = len_v3v3(bpoly->centroid, point_co);
+
+ avg_point_dist += bpoly->weight_dist;
+
+ /* Compute centroid to mid-edge vectors */
+ mid_v2_v2v2(bpoly->cent_edgemid_vecs_v2[0],
+ bpoly->coords_v2[bpoly->edge_vert_inds[0]],
+ bpoly->coords_v2[bpoly->corner_ind]);
+
+ mid_v2_v2v2(bpoly->cent_edgemid_vecs_v2[1],
+ bpoly->coords_v2[bpoly->edge_vert_inds[1]],
+ bpoly->coords_v2[bpoly->corner_ind]);
+
+ sub_v2_v2(bpoly->cent_edgemid_vecs_v2[0], bpoly->centroid_v2);
+ sub_v2_v2(bpoly->cent_edgemid_vecs_v2[1], bpoly->centroid_v2);
+
+ /* Compute poly scales with respect to mid-edges, and normalize the vectors */
+ bpoly->scales[0] = normalize_v2(bpoly->cent_edgemid_vecs_v2[0]);
+ bpoly->scales[1] = normalize_v2(bpoly->cent_edgemid_vecs_v2[1]);
+
+ /* Compute the required polygon angles */
+ bpoly->edgemid_angle = angle_normalized_v2v2(bpoly->cent_edgemid_vecs_v2[0], bpoly->cent_edgemid_vecs_v2[1]);
+
+ sub_v2_v2v2(tmp_vec_v2, bpoly->coords_v2[bpoly->corner_ind], bpoly->centroid_v2);
+ normalize_v2(tmp_vec_v2);
+
+ bpoly->corner_edgemid_angles[0] = angle_normalized_v2v2(tmp_vec_v2, bpoly->cent_edgemid_vecs_v2[0]);
+ bpoly->corner_edgemid_angles[1] = angle_normalized_v2v2(tmp_vec_v2, bpoly->cent_edgemid_vecs_v2[1]);
+
+ /* Check for inifnite weights, and compute angular data otherwise */
+ if (bpoly->weight_dist < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ;
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST;
+ }
+ else if (bpoly->weight_dist_proj < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ;
+ }
+ else {
+ float cent_point_vec[2];
+
+ sub_v2_v2v2(cent_point_vec, bpoly->point_v2, bpoly->centroid_v2);
+ normalize_v2(cent_point_vec);
+
+ bpoly->point_edgemid_angles[0] = angle_normalized_v2v2(cent_point_vec, bpoly->cent_edgemid_vecs_v2[0]);
+ bpoly->point_edgemid_angles[1] = angle_normalized_v2v2(cent_point_vec, bpoly->cent_edgemid_vecs_v2[1]);
+ }
+ }
+ }
+ }
+
+ avg_point_dist /= bwdata->numpoly;
+
+ /* If weights 1 and 2 are not infinite, loop over all adjacent edges again,
+ * and build adjacency dependent angle data (depends on all polygons having been computed) */
+ if (!inf_weight_flags) {
+ for (vedge = vert_edges; vedge; vedge = vedge->next) {
+ SDefBindPoly *bpolys[2];
+ const SDefEdgePolys *epolys;
+ float ang_weights[2];
+ unsigned int edge_ind = vedge->index;
+ unsigned int edge_on_poly[2];
+
+ epolys = &edge_polys[edge_ind];
+
+ /* Find bind polys corresponding to the edge's adjacent polys */
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0, j = 0; (i < bwdata->numpoly) && (j < epolys->num); bpoly++, i++) {
+ if (ELEM(bpoly->index, epolys->polys[0], epolys->polys[1])) {
+ bpolys[j] = bpoly;
+
+ if (bpoly->edge_inds[0] == edge_ind) {
+ edge_on_poly[j] = 0;
+ }
+ else {
+ edge_on_poly[j] = 1;
+ }
+
+ j++;
+ }
+ }
+
+ /* Compute angular weight component */
+ if (epolys->num == 1) {
+ ang_weights[0] = computeAngularWeight(bpolys[0]->point_edgemid_angles[edge_on_poly[0]], bpolys[0]->edgemid_angle);
+ bpolys[0]->weight_angular *= ang_weights[0] * ang_weights[0];
+ }
+ else if (epolys->num == 2) {
+ ang_weights[0] = computeAngularWeight(bpolys[0]->point_edgemid_angles[edge_on_poly[0]], bpolys[0]->edgemid_angle);
+ ang_weights[1] = computeAngularWeight(bpolys[1]->point_edgemid_angles[edge_on_poly[1]], bpolys[1]->edgemid_angle);
+
+ bpolys[0]->weight_angular *= ang_weights[0] * ang_weights[1];
+ bpolys[1]->weight_angular *= ang_weights[0] * ang_weights[1];
+ }
+ }
+ }
+
+ /* Compute scalings and falloff.
+ * Scale all weights if no infinite weight is found,
+ * scale only unprojected weight if projected weight is infinite,
+ * scale none if both are infinite. */
+ if (!inf_weight_flags) {
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0; i < bwdata->numpoly; bpoly++, i++) {
+ float corner_angle_weights[2];
+ float scale_weight, sqr, inv_sqr;
+
+ corner_angle_weights[0] = bpoly->point_edgemid_angles[0] / bpoly->corner_edgemid_angles[0];
+ corner_angle_weights[1] = bpoly->point_edgemid_angles[1] / bpoly->corner_edgemid_angles[1];
+
+ if (isnan(corner_angle_weights[0]) || isnan(corner_angle_weights[1])) {
+ freeBindData(bwdata);
+ data->success = MOD_SDEF_BIND_RESULT_GENERIC_ERR;
+ return NULL;
+ }
+
+ /* Find which edge the point is closer to */
+ if (corner_angle_weights[0] < corner_angle_weights[1]) {
+ bpoly->dominant_edge = 0;
+ bpoly->dominant_angle_weight = corner_angle_weights[0];
+ }
+ else {
+ bpoly->dominant_edge = 1;
+ bpoly->dominant_angle_weight = corner_angle_weights[1];
+ }
+
+ bpoly->dominant_angle_weight = sinf(bpoly->dominant_angle_weight * M_PI_2);
+
+ /* Compute quadratic angular scale interpolation weight */
+ scale_weight = bpoly->point_edgemid_angles[bpoly->dominant_edge] / bpoly->edgemid_angle;
+ scale_weight /= scale_weight + (bpoly->point_edgemid_angles[!bpoly->dominant_edge] / bpoly->edgemid_angle);
+
+ sqr = scale_weight * scale_weight;
+ inv_sqr = 1.0f - scale_weight;
+ inv_sqr *= inv_sqr;
+ scale_weight = sqr / (sqr + inv_sqr);
+
+ /* Compute interpolated scale (no longer need the individual scales,
+ * so simply storing the result over the scale in index zero) */
+ bpoly->scales[0] = bpoly->scales[bpoly->dominant_edge] * (1.0f - scale_weight) +
+ bpoly->scales[!bpoly->dominant_edge] * scale_weight;
+
+ /* Scale the point distance weights, and introduce falloff */
+ bpoly->weight_dist_proj /= bpoly->scales[0];
+ bpoly->weight_dist_proj = powf(bpoly->weight_dist_proj, data->falloff);
+
+ bpoly->weight_dist /= avg_point_dist;
+ bpoly->weight_dist = powf(bpoly->weight_dist, data->falloff);
+
+ /* Re-check for infinite weights, now that all scalings and interpolations are computed */
+ if (bpoly->weight_dist < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ;
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST;
+ }
+ else if (bpoly->weight_dist_proj < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ;
+ }
+ else if (bpoly->weight_angular < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_ANGULAR;
+ }
+ }
+ }
+ else if (!(inf_weight_flags & MOD_SDEF_INFINITE_WEIGHT_DIST)) {
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0; i < bwdata->numpoly; bpoly++, i++) {
+ /* Scale the point distance weight by average point distance, and introduce falloff */
+ bpoly->weight_dist /= avg_point_dist;
+ bpoly->weight_dist = powf(bpoly->weight_dist, data->falloff);
+
+ /* Re-check for infinite weights, now that all scalings and interpolations are computed */
+ if (bpoly->weight_dist < FLT_EPSILON) {
+ inf_weight_flags |= MOD_SDEF_INFINITE_WEIGHT_DIST;
+ }
+ }
+ }
+
+ /* Final loop, to compute actual weights */
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0; i < bwdata->numpoly; bpoly++, i++) {
+ /* Weight computation from components */
+ if (inf_weight_flags & MOD_SDEF_INFINITE_WEIGHT_DIST) {
+ bpoly->weight = bpoly->weight_dist < FLT_EPSILON ? 1.0f : 0.0f;
+ }
+ else if (inf_weight_flags & MOD_SDEF_INFINITE_WEIGHT_DIST_PROJ) {
+ bpoly->weight = bpoly->weight_dist_proj < FLT_EPSILON ?
+ 1.0f / bpoly->weight_dist : 0.0f;
+ }
+ else if (inf_weight_flags & MOD_SDEF_INFINITE_WEIGHT_ANGULAR) {
+ bpoly->weight = bpoly->weight_angular < FLT_EPSILON ?
+ 1.0f / bpoly->weight_dist_proj / bpoly->weight_dist : 0.0f;
+ }
+ else {
+ bpoly->weight = 1.0f / bpoly->weight_angular /
+ bpoly->weight_dist_proj /
+ bpoly->weight_dist;
+ }
+
+ tot_weight += bpoly->weight;
+ }
+
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0; i < bwdata->numpoly; bpoly++, i++) {
+ bpoly->weight /= tot_weight;
+
+ /* Evaluate if this poly is relevant to bind */
+ /* Even though the weights should add up to 1.0,
+ * the losses of weights smaller than epsilon here
+ * should be negligible... */
+ if (bpoly->weight >= FLT_EPSILON) {
+ if (bpoly->inside) {
+ bwdata->numbinds += 1;
+ }
+ else {
+ if (bpoly->dominant_angle_weight < FLT_EPSILON || 1.0f - bpoly->dominant_angle_weight < FLT_EPSILON) {
+ bwdata->numbinds += 1;
+ }
+ else {
+ bwdata->numbinds += 2;
+ }
+ }
+ }
+ }
+
+ return bwdata;
+}
+
+BLI_INLINE float computeNormalDisplacement(const float point_co[3], const float point_co_proj[3], const float normal[3])
+{
+ float disp_vec[3];
+ float normal_dist;
+
+ sub_v3_v3v3(disp_vec, point_co, point_co_proj);
+ normal_dist = len_v3(disp_vec);
+
+ if (dot_v3v3(disp_vec, normal) < 0) {
+ normal_dist *= -1;
+ }
+
+ return normal_dist;
+}
+
+static void bindVert(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ SDefBindCalcData * const data = (SDefBindCalcData *)userdata;
+ float point_co[3];
+ float point_co_proj[3];
+
+ SDefBindWeightData *bwdata;
+ SDefVert *sdvert = data->bind_verts + index;
+ SDefBindPoly *bpoly;
+ SDefBind *sdbind;
+
+ if (data->success != MOD_SDEF_BIND_RESULT_SUCCESS) {
+ sdvert->binds = NULL;
+ sdvert->numbinds = 0;
+ return;
+ }
+
+ copy_v3_v3(point_co, data->vertexCos[index]);
+ bwdata = computeBindWeights(data, point_co);
+
+ if (bwdata == NULL) {
+ sdvert->binds = NULL;
+ sdvert->numbinds = 0;
+ return;
+ }
+
+ sdvert->binds = MEM_calloc_arrayN(bwdata->numbinds, sizeof(*sdvert->binds), "SDefVertBindData");
+ if (sdvert->binds == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ sdvert->numbinds = 0;
+ return;
+ }
+
+ sdvert->numbinds = bwdata->numbinds;
+
+ sdbind = sdvert->binds;
+
+ bpoly = bwdata->bind_polys;
+
+ for (int i = 0; i < bwdata->numbinds; bpoly++) {
+ if (bpoly->weight >= FLT_EPSILON) {
+ if (bpoly->inside) {
+ const MLoop *loop = &data->mloop[bpoly->loopstart];
+
+ sdbind->influence = bpoly->weight;
+ sdbind->numverts = bpoly->numverts;
+
+ sdbind->mode = MOD_SDEF_MODE_NGON;
+ sdbind->vert_weights = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_weights), "SDefNgonVertWeights");
+ if (sdbind->vert_weights == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefNgonVertInds");
+ if (sdbind->vert_inds == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ interp_weights_poly_v2(sdbind->vert_weights, bpoly->coords_v2, bpoly->numverts, bpoly->point_v2);
+
+ /* Reproject vert based on weights and original poly verts, to reintroduce poly non-planarity */
+ zero_v3(point_co_proj);
+ for (int j = 0; j < bpoly->numverts; j++, loop++) {
+ madd_v3_v3fl(point_co_proj, bpoly->coords[j], sdbind->vert_weights[j]);
+ sdbind->vert_inds[j] = loop->v;
+ }
+
+ sdbind->normal_dist = computeNormalDisplacement(point_co, point_co_proj, bpoly->normal);
+
+ sdbind++;
+ i++;
+ }
+ else {
+ float tmp_vec[3];
+ float cent[3], norm[3];
+ float v1[3], v2[3], v3[3];
+
+ if (1.0f - bpoly->dominant_angle_weight >= FLT_EPSILON) {
+ sdbind->influence = bpoly->weight * (1.0f - bpoly->dominant_angle_weight);
+ sdbind->numverts = bpoly->numverts;
+
+ sdbind->mode = MOD_SDEF_MODE_CENTROID;
+ sdbind->vert_weights = MEM_malloc_arrayN(3, sizeof(*sdbind->vert_weights), "SDefCentVertWeights");
+ if (sdbind->vert_weights == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefCentVertInds");
+ if (sdbind->vert_inds == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ sortPolyVertsEdge(sdbind->vert_inds, &data->mloop[bpoly->loopstart],
+ bpoly->edge_inds[bpoly->dominant_edge], bpoly->numverts);
+
+ copy_v3_v3(v1, data->targetCos[sdbind->vert_inds[0]]);
+ copy_v3_v3(v2, data->targetCos[sdbind->vert_inds[1]]);
+ copy_v3_v3(v3, bpoly->centroid);
+
+ mid_v3_v3v3v3(cent, v1, v2, v3);
+ normal_tri_v3(norm, v1, v2, v3);
+
+ add_v3_v3v3(tmp_vec, point_co, bpoly->normal);
+
+ /* We are sure the line is not parallel to the plane.
+ * Checking return value just to avoid warning... */
+ if (!isect_line_plane_v3(point_co_proj, point_co, tmp_vec, cent, norm)) {
+ BLI_assert(false);
+ }
+
+ interp_weights_tri_v3(sdbind->vert_weights, v1, v2, v3, point_co_proj);
+
+ sdbind->normal_dist = computeNormalDisplacement(point_co, point_co_proj, bpoly->normal);
+
+ sdbind++;
+ i++;
+ }
+
+ if (bpoly->dominant_angle_weight >= FLT_EPSILON) {
+ sdbind->influence = bpoly->weight * bpoly->dominant_angle_weight;
+ sdbind->numverts = bpoly->numverts;
+
+ sdbind->mode = MOD_SDEF_MODE_LOOPTRI;
+ sdbind->vert_weights = MEM_malloc_arrayN(3, sizeof(*sdbind->vert_weights), "SDefTriVertWeights");
+ if (sdbind->vert_weights == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ sdbind->vert_inds = MEM_malloc_arrayN(bpoly->numverts, sizeof(*sdbind->vert_inds), "SDefTriVertInds");
+ if (sdbind->vert_inds == NULL) {
+ data->success = MOD_SDEF_BIND_RESULT_MEM_ERR;
+ return;
+ }
+
+ sortPolyVertsTri(sdbind->vert_inds, &data->mloop[bpoly->loopstart], bpoly->edge_vert_inds[0], bpoly->numverts);
+
+ copy_v3_v3(v1, data->targetCos[sdbind->vert_inds[0]]);
+ copy_v3_v3(v2, data->targetCos[sdbind->vert_inds[1]]);
+ copy_v3_v3(v3, data->targetCos[sdbind->vert_inds[2]]);
+
+ mid_v3_v3v3v3(cent, v1, v2, v3);
+ normal_tri_v3(norm, v1, v2, v3);
+
+ add_v3_v3v3(tmp_vec, point_co, bpoly->normal);
+
+ /* We are sure the line is not parallel to the plane.
+ * Checking return value just to avoid warning... */
+ if (!isect_line_plane_v3(point_co_proj, point_co, tmp_vec, cent, norm)) {
+ BLI_assert(false);
+ }
+
+ interp_weights_tri_v3(sdbind->vert_weights, v1, v2, v3, point_co_proj);
+
+ sdbind->normal_dist = computeNormalDisplacement(point_co, point_co_proj, bpoly->normal);
+
+ sdbind++;
+ i++;
+ }
+ }
+ }
+ }
+
+ freeBindData(bwdata);
+}
+
+static bool surfacedeformBind(SurfaceDeformModifierData *smd, float (*vertexCos)[3],
+ unsigned int numverts, unsigned int tnumpoly, unsigned int tnumverts, DerivedMesh *tdm)
+{
+ BVHTreeFromMesh treeData = {NULL};
+ const MVert *mvert = tdm->getVertArray(tdm);
+ const MPoly *mpoly = tdm->getPolyArray(tdm);
+ const MEdge *medge = tdm->getEdgeArray(tdm);
+ const MLoop *mloop = tdm->getLoopArray(tdm);
+ unsigned int tnumedges = tdm->getNumEdges(tdm);
+ int adj_result;
+ SDefAdjacencyArray *vert_edges;
+ SDefAdjacency *adj_array;
+ SDefEdgePolys *edge_polys;
+
+ vert_edges = MEM_calloc_arrayN(tnumverts, sizeof(*vert_edges), "SDefVertEdgeMap");
+ if (vert_edges == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ return false;
+ }
+
+ adj_array = MEM_malloc_arrayN(tnumedges, 2 * sizeof(*adj_array), "SDefVertEdge");
+ if (adj_array == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ MEM_freeN(vert_edges);
+ return false;
+ }
+
+ edge_polys = MEM_calloc_arrayN(tnumedges, sizeof(*edge_polys), "SDefEdgeFaceMap");
+ if (edge_polys == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ MEM_freeN(vert_edges);
+ MEM_freeN(adj_array);
+ return false;
+ }
+
+ smd->verts = MEM_malloc_arrayN(numverts, sizeof(*smd->verts), "SDefBindVerts");
+ if (smd->verts == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ freeAdjacencyMap(vert_edges, adj_array, edge_polys);
+ return false;
+ }
+
+ bvhtree_from_mesh_looptri(&treeData, tdm, 0.0, 2, 6);
+ if (treeData.tree == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ freeAdjacencyMap(vert_edges, adj_array, edge_polys);
+ MEM_freeN(smd->verts);
+ smd->verts = NULL;
+ return false;
+ }
+
+ adj_result = buildAdjacencyMap(mpoly, medge, mloop, tnumpoly, tnumedges, vert_edges, adj_array, edge_polys);
+
+ if (adj_result == MOD_SDEF_BIND_RESULT_NONMANY_ERR) {
+ modifier_setError((ModifierData *)smd, "Target has edges with more than two polygons");
+ freeAdjacencyMap(vert_edges, adj_array, edge_polys);
+ free_bvhtree_from_mesh(&treeData);
+ MEM_freeN(smd->verts);
+ smd->verts = NULL;
+ return false;
+ }
+
+ smd->numverts = numverts;
+ smd->numpoly = tnumpoly;
+
+ SDefBindCalcData data = {.treeData = &treeData,
+ .vert_edges = vert_edges,
+ .edge_polys = edge_polys,
+ .mpoly = mpoly,
+ .medge = medge,
+ .mloop = mloop,
+ .looptri = tdm->getLoopTriArray(tdm),
+ .targetCos = MEM_malloc_arrayN(tnumverts, sizeof(float[3]), "SDefTargetBindVertArray"),
+ .bind_verts = smd->verts,
+ .vertexCos = vertexCos,
+ .falloff = smd->falloff,
+ .success = MOD_SDEF_BIND_RESULT_SUCCESS};
+
+ if (data.targetCos == NULL) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ freeData((ModifierData *)smd);
+ return false;
+ }
+
+ invert_m4_m4(data.imat, smd->mat);
+
+ for (int i = 0; i < tnumverts; i++) {
+ mul_v3_m4v3(data.targetCos[i], smd->mat, mvert[i].co);
+ }
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numverts > 10000);
+ BLI_task_parallel_range(0, numverts,
+ &data,
+ bindVert,
+ &settings);
+
+ MEM_freeN(data.targetCos);
+
+ if (data.success == MOD_SDEF_BIND_RESULT_MEM_ERR) {
+ modifier_setError((ModifierData *)smd, "Out of memory");
+ freeData((ModifierData *)smd);
+ }
+ else if (data.success == MOD_SDEF_BIND_RESULT_NONMANY_ERR) {
+ modifier_setError((ModifierData *)smd, "Target has edges with more than two polygons");
+ freeData((ModifierData *)smd);
+ }
+ else if (data.success == MOD_SDEF_BIND_RESULT_CONCAVE_ERR) {
+ modifier_setError((ModifierData *)smd, "Target contains concave polygons");
+ freeData((ModifierData *)smd);
+ }
+ else if (data.success == MOD_SDEF_BIND_RESULT_OVERLAP_ERR) {
+ modifier_setError((ModifierData *)smd, "Target contains overlapping verts");
+ freeData((ModifierData *)smd);
+ }
+ else if (data.success == MOD_SDEF_BIND_RESULT_GENERIC_ERR) {
+ /* I know this message is vague, but I could not think of a way
+ * to explain this whith a reasonably sized message.
+ * Though it shouldn't really matter all that much,
+ * because this is very unlikely to occur */
+ modifier_setError((ModifierData *)smd, "Target contains invalid polygons");
+ freeData((ModifierData *)smd);
+ }
+
+ freeAdjacencyMap(vert_edges, adj_array, edge_polys);
+ free_bvhtree_from_mesh(&treeData);
+
+ return data.success == 1;
+}
+
+static void deformVert(
+ void *__restrict userdata,
+ const int index,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
+{
+ const SDefDeformData * const data = (SDefDeformData *)userdata;
+ const SDefBind *sdbind = data->bind_verts[index].binds;
+ float * const vertexCos = data->vertexCos[index];
+ float norm[3], temp[3];
+
+ zero_v3(vertexCos);
+
+ for (int j = 0; j < data->bind_verts[index].numbinds; j++, sdbind++) {
+ /* Mode-generic operations (allocate poly coordinates) */
+ float (*coords)[3] = MEM_malloc_arrayN(sdbind->numverts, sizeof(*coords), "SDefDoPolyCoords");
+
+ for (int k = 0; k < sdbind->numverts; k++) {
+ copy_v3_v3(coords[k], data->targetCos[sdbind->vert_inds[k]]);
+ }
+
+ normal_poly_v3(norm, coords, sdbind->numverts);
+ zero_v3(temp);
+
+ /* ---------- looptri mode ---------- */
+ if (sdbind->mode == MOD_SDEF_MODE_LOOPTRI) {
+ madd_v3_v3fl(temp, data->targetCos[sdbind->vert_inds[0]], sdbind->vert_weights[0]);
+ madd_v3_v3fl(temp, data->targetCos[sdbind->vert_inds[1]], sdbind->vert_weights[1]);
+ madd_v3_v3fl(temp, data->targetCos[sdbind->vert_inds[2]], sdbind->vert_weights[2]);
+ }
+ else {
+ /* ---------- ngon mode ---------- */
+ if (sdbind->mode == MOD_SDEF_MODE_NGON) {
+ for (int k = 0; k < sdbind->numverts; k++) {
+ madd_v3_v3fl(temp, coords[k], sdbind->vert_weights[k]);
+ }
+ }
+
+ /* ---------- centroid mode ---------- */
+ else if (sdbind->mode == MOD_SDEF_MODE_CENTROID) {
+ float cent[3];
+ mid_v3_v3_array(cent, coords, sdbind->numverts);
+
+ madd_v3_v3fl(temp, data->targetCos[sdbind->vert_inds[0]], sdbind->vert_weights[0]);
+ madd_v3_v3fl(temp, data->targetCos[sdbind->vert_inds[1]], sdbind->vert_weights[1]);
+ madd_v3_v3fl(temp, cent, sdbind->vert_weights[2]);
+ }
+ }
+
+ MEM_freeN(coords);
+
+ /* Apply normal offset (generic for all modes) */
+ madd_v3_v3fl(temp, norm, sdbind->normal_dist);
+
+ madd_v3_v3fl(vertexCos, temp, sdbind->influence);
+ }
+}
+
+static void surfacedeformModifier_do(ModifierData *md, float (*vertexCos)[3], unsigned int numverts, Object *ob)
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+ DerivedMesh *tdm;
+ unsigned int tnumverts, tnumpoly;
+
+ /* Exit function if bind flag is not set (free bind data if any) */
+ if (!(smd->flags & MOD_SDEF_BIND)) {
+ freeData(md);
+ return;
+ }
+
+ /* Handle target mesh both in and out of edit mode */
+ if (smd->target == md->scene->obedit) {
+ BMEditMesh *em = BKE_editmesh_from_object(smd->target);
+ tdm = em->derivedFinal;
+ }
+ else {
+ tdm = smd->target->derivedFinal;
+ }
+
+ if (!tdm) {
+ modifier_setError(md, "No valid target mesh");
+ return;
+ }
+
+ tnumverts = tdm->getNumVerts(tdm);
+ tnumpoly = tdm->getNumPolys(tdm);
+
+ /* If not bound, execute bind */
+ if (!(smd->verts)) {
+ float tmp_mat[4][4];
+
+ invert_m4_m4(tmp_mat, ob->obmat);
+ mul_m4_m4m4(smd->mat, tmp_mat, smd->target->obmat);
+
+ if (!surfacedeformBind(smd, vertexCos, numverts, tnumpoly, tnumverts, tdm)) {
+ smd->flags &= ~MOD_SDEF_BIND;
+ return;
+ }
+ }
+
+ /* Poly count checks */
+ if (smd->numverts != numverts) {
+ modifier_setError(md, "Verts changed from %u to %u", smd->numverts, numverts);
+ return;
+ }
+ else if (smd->numpoly != tnumpoly) {
+ modifier_setError(md, "Target polygons changed from %u to %u", smd->numpoly, tnumpoly);
+ return;
+ }
+
+ /* Actual vertex location update starts here */
+ SDefDeformData data = {
+ .bind_verts = smd->verts,
+ .targetCos = MEM_malloc_arrayN(tnumverts, sizeof(float[3]), "SDefTargetVertArray"),
+ .vertexCos = vertexCos,
+ };
+
+ if (data.targetCos != NULL) {
+ bool tdm_vert_alloc;
+ const MVert * const mvert = DM_get_vert_array(tdm, &tdm_vert_alloc);
+
+ for (int i = 0; i < tnumverts; i++) {
+ mul_v3_m4v3(data.targetCos[i], smd->mat, mvert[i].co);
+ }
+
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numverts > 10000);
+ BLI_task_parallel_range(0, numverts,
+ &data,
+ deformVert,
+ &settings);
+
+ if (tdm_vert_alloc) {
+ MEM_freeN((void *)mvert);
+ }
+
+ MEM_freeN(data.targetCos);
+ }
+}
+
+static void deformVerts(ModifierData *md, Object *ob,
+ DerivedMesh *UNUSED(derivedData),
+ float (*vertexCos)[3], int numVerts,
+ ModifierApplyFlag UNUSED(flag))
+{
+ surfacedeformModifier_do(md, vertexCos, numVerts, ob);
+}
+
+static void deformVertsEM(ModifierData *md, Object *ob,
+ struct BMEditMesh *UNUSED(editData),
+ DerivedMesh *UNUSED(derivedData),
+ float (*vertexCos)[3], int numVerts)
+{
+ surfacedeformModifier_do(md, vertexCos, numVerts, ob);
+}
+
+static bool isDisabled(ModifierData *md, int UNUSED(useRenderParams))
+{
+ SurfaceDeformModifierData *smd = (SurfaceDeformModifierData *)md;
+
+ return !smd->target && !(smd->verts && !(smd->flags & MOD_SDEF_BIND));
+}
+
+ModifierTypeInfo modifierType_SurfaceDeform = {
+ /* name */ "Surface Deform",
+ /* structName */ "SurfaceDeformModifierData",
+ /* structSize */ sizeof(SurfaceDeformModifierData),
+ /* type */ eModifierTypeType_OnlyDeform,
+ /* flags */ eModifierTypeFlag_AcceptsMesh |
+ eModifierTypeFlag_SupportsEditmode,
+
+ /* copyData */ copyData,
+ /* deformVerts */ deformVerts,
+ /* deformMatrices */ NULL,
+ /* deformVertsEM */ deformVertsEM,
+ /* deformMatricesEM */ NULL,
+ /* applyModifier */ NULL,
+ /* applyModifierEM */ NULL,
+ /* initData */ initData,
+ /* requiredDataMask */ NULL,
+ /* freeData */ freeData,
+ /* isDisabled */ isDisabled,
+ /* updateDepgraph */ updateDepgraph,
+ /* updateDepsgraph */ updateDepsgraph,
+ /* dependsOnTime */ NULL,
+ /* dependsOnNormals */ NULL,
+ /* foreachObjectLink */ foreachObjectLink,
+ /* foreachIDLink */ NULL,
+ /* foreachTexLink */ NULL,
+};
diff --git a/source/blender/modifiers/intern/MOD_triangulate.c b/source/blender/modifiers/intern/MOD_triangulate.c
index 6fad2756f82..b057d6d5a86 100644
--- a/source/blender/modifiers/intern/MOD_triangulate.c
+++ b/source/blender/modifiers/intern/MOD_triangulate.c
@@ -35,6 +35,8 @@
#include "bmesh.h"
#include "bmesh_tools.h"
+#include "MOD_modifiertypes.h"
+
static DerivedMesh *triangulate_dm(DerivedMesh *dm, const int quad_method, const int ngon_method)
{
DerivedMesh *result;
diff --git a/source/blender/modifiers/intern/MOD_util.c b/source/blender/modifiers/intern/MOD_util.c
index 93414562ccf..5b19bcf4817 100644
--- a/source/blender/modifiers/intern/MOD_util.c
+++ b/source/blender/modifiers/intern/MOD_util.c
@@ -87,7 +87,7 @@ void get_texture_coords(MappingInfoModifierData *dmd, Object *ob,
MPoly *mpoly = dm->getPolyArray(dm);
MPoly *mp;
MLoop *mloop = dm->getLoopArray(dm);
- char *done = MEM_callocN(sizeof(*done) * numVerts,
+ char *done = MEM_calloc_arrayN(numVerts, sizeof(*done),
"get_texture_coords done");
int numPolys = dm->getNumPolys(dm);
char uvname[MAX_CUSTOMDATA_LAYER_NAME];
@@ -287,5 +287,6 @@ void modifier_type_init(ModifierTypeInfo *types[])
INIT_TYPE(NormalEdit);
INIT_TYPE(CorrectiveSmooth);
INIT_TYPE(MeshSequenceCache);
+ INIT_TYPE(SurfaceDeform);
#undef INIT_TYPE
}
diff --git a/source/blender/modifiers/intern/MOD_uvproject.c b/source/blender/modifiers/intern/MOD_uvproject.c
index 78dc1ea8bcb..1cefb07b50a 100644
--- a/source/blender/modifiers/intern/MOD_uvproject.c
+++ b/source/blender/modifiers/intern/MOD_uvproject.c
@@ -45,6 +45,7 @@
#include "BKE_camera.h"
+#include "BKE_library.h"
#include "BKE_library_query.h"
#include "BKE_mesh.h"
#include "BKE_DerivedMesh.h"
@@ -70,9 +71,12 @@ static void copyData(ModifierData *md, ModifierData *target)
{
#if 0
UVProjectModifierData *umd = (UVProjectModifierData *) md;
- UVProjectModifierData *tumd = (UVProjectModifierData *) target;
#endif
+ UVProjectModifierData *tumd = (UVProjectModifierData *) target;
+
modifier_copyData_generic(md, target);
+
+ id_us_plus((ID *)tumd->image);
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *UNUSED(md))
@@ -105,36 +109,28 @@ static void foreachIDLink(ModifierData *md, Object *ob,
foreachObjectLink(md, ob, (ObjectWalkFunc)walk, userData);
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
UVProjectModifierData *umd = (UVProjectModifierData *) md;
int i;
for (i = 0; i < umd->num_projectors; ++i) {
if (umd->projectors[i]) {
- DagNode *curNode = dag_get_node(forest, umd->projectors[i]);
+ DagNode *curNode = dag_get_node(ctx->forest, umd->projectors[i]);
- dag_add_relation(forest, curNode, obNode,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode,
DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "UV Project Modifier");
}
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
UVProjectModifierData *umd = (UVProjectModifierData *)md;
int i;
for (i = 0; i < umd->num_projectors; ++i) {
if (umd->projectors[i] != NULL) {
- DEG_add_object_relation(node, umd->projectors[i], DEG_OB_COMP_TRANSFORM, "UV Project Modifier");
+ DEG_add_object_relation(ctx->node, umd->projectors[i], DEG_OB_COMP_TRANSFORM, "UV Project Modifier");
}
}
}
@@ -247,7 +243,7 @@ static DerivedMesh *uvprojectModifier_do(UVProjectModifierData *umd,
numVerts = dm->getNumVerts(dm);
- coords = MEM_mallocN(sizeof(*coords) * numVerts,
+ coords = MEM_malloc_arrayN(numVerts, sizeof(*coords),
"uvprojectModifier_do coords");
dm->getVertCos(dm, coords);
diff --git a/source/blender/modifiers/intern/MOD_uvwarp.c b/source/blender/modifiers/intern/MOD_uvwarp.c
index b3fc3842635..384efc74666 100644
--- a/source/blender/modifiers/intern/MOD_uvwarp.c
+++ b/source/blender/modifiers/intern/MOD_uvwarp.c
@@ -112,7 +112,10 @@ typedef struct UVWarpData {
int axis_v;
} UVWarpData;
-static void uv_warp_compute(void *userdata, const int i)
+static void uv_warp_compute(
+ void *__restrict userdata,
+ const int i,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
const UVWarpData *data = userdata;
@@ -210,7 +213,13 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob,
UVWarpData data = {.mpoly = mpoly, .mloop = mloop, .mloopuv = mloopuv,
.dvert = dvert, .defgrp_index = defgrp_index,
.warp_mat = warp_mat, .axis_u = axis_u, .axis_v = axis_v};
- BLI_task_parallel_range(0, numPolys, &data, uv_warp_compute, numPolys > 1000);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numPolys > 1000);
+ BLI_task_parallel_range(0, numPolys,
+ &data,
+ uv_warp_compute,
+ &settings);
dm->dirty |= DM_DIRTY_TESS_CDLAYERS;
@@ -226,7 +235,7 @@ static void foreachObjectLink(ModifierData *md, Object *ob, ObjectWalkFunc walk,
}
static void uv_warp_deps_object_bone(DagForest *forest, DagNode *obNode,
- Object *obj, const char *bonename)
+ Object *obj, const char *bonename)
{
if (obj) {
DagNode *curNode = dag_get_node(forest, obj);
@@ -238,16 +247,12 @@ static void uv_warp_deps_object_bone(DagForest *forest, DagNode *obNode,
}
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
UVWarpModifierData *umd = (UVWarpModifierData *) md;
- uv_warp_deps_object_bone(forest, obNode, umd->object_src, umd->bone_src);
- uv_warp_deps_object_bone(forest, obNode, umd->object_dst, umd->bone_dst);
+ uv_warp_deps_object_bone(ctx->forest, ctx->obNode, umd->object_src, umd->bone_src);
+ uv_warp_deps_object_bone(ctx->forest, ctx->obNode, umd->object_dst, umd->bone_dst);
}
static void uv_warp_deps_object_bone_new(struct DepsNodeHandle *node,
@@ -262,16 +267,12 @@ static void uv_warp_deps_object_bone_new(struct DepsNodeHandle *node,
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
UVWarpModifierData *umd = (UVWarpModifierData *) md;
- uv_warp_deps_object_bone_new(node, umd->object_src, umd->bone_src);
- uv_warp_deps_object_bone_new(node, umd->object_dst, umd->bone_dst);
+ uv_warp_deps_object_bone_new(ctx->node, umd->object_src, umd->bone_src);
+ uv_warp_deps_object_bone_new(ctx->node, umd->object_dst, umd->bone_dst);
}
ModifierTypeInfo modifierType_UVWarp = {
diff --git a/source/blender/modifiers/intern/MOD_warp.c b/source/blender/modifiers/intern/MOD_warp.c
index 92d44257d03..00d7906a442 100644
--- a/source/blender/modifiers/intern/MOD_warp.c
+++ b/source/blender/modifiers/intern/MOD_warp.c
@@ -66,6 +66,10 @@ static void copyData(ModifierData *md, ModifierData *target)
WarpModifierData *wmd = (WarpModifierData *) md;
WarpModifierData *twmd = (WarpModifierData *) target;
+ if (twmd->curfalloff != NULL) {
+ curvemapping_free(twmd->curfalloff);
+ }
+
modifier_copyData_generic(md, target);
twmd->curfalloff = curvemapping_copy(wmd->curfalloff);
@@ -135,40 +139,33 @@ static void foreachTexLink(ModifierData *md, Object *ob, TexWalkFunc walk, void
walk(userData, ob, md, "texture");
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WarpModifierData *wmd = (WarpModifierData *) md;
if (wmd->object_from && wmd->object_to) {
- DagNode *fromNode = dag_get_node(forest, wmd->object_from);
- DagNode *toNode = dag_get_node(forest, wmd->object_to);
+ DagNode *fromNode = dag_get_node(ctx->forest, wmd->object_from);
+ DagNode *toNode = dag_get_node(ctx->forest, wmd->object_to);
- dag_add_relation(forest, fromNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier1");
- dag_add_relation(forest, toNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier2");
+ dag_add_relation(ctx->forest, fromNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier1");
+ dag_add_relation(ctx->forest, toNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier2");
}
if ((wmd->texmapping == MOD_DISP_MAP_OBJECT) && wmd->map_object) {
- DagNode *curNode = dag_get_node(forest, wmd->map_object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier3");
+ DagNode *curNode = dag_get_node(ctx->forest, wmd->map_object);
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA, "Warp Modifier3");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WarpModifierData *wmd = (WarpModifierData *) md;
if (wmd->object_from != NULL && wmd->object_to != NULL) {
- DEG_add_object_relation(node, wmd->object_from, DEG_OB_COMP_TRANSFORM, "Warp Modifier from");
- DEG_add_object_relation(node, wmd->object_to, DEG_OB_COMP_TRANSFORM, "Warp Modifier to");
+ DEG_add_object_relation(ctx->node, wmd->object_from, DEG_OB_COMP_TRANSFORM, "Warp Modifier from");
+ DEG_add_object_relation(ctx->node, wmd->object_to, DEG_OB_COMP_TRANSFORM, "Warp Modifier to");
}
if ((wmd->texmapping == MOD_DISP_MAP_OBJECT) && wmd->map_object != NULL) {
- DEG_add_object_relation(node, wmd->map_object, DEG_OB_COMP_TRANSFORM, "Warp Modifier map");
+ DEG_add_object_relation(ctx->node, wmd->map_object, DEG_OB_COMP_TRANSFORM, "Warp Modifier map");
}
}
@@ -233,7 +230,7 @@ static void warpModifier_do(WarpModifierData *wmd, Object *ob,
weight = strength;
if (wmd->texture) {
- tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts, "warpModifier_do tex_co");
+ tex_co = MEM_malloc_arrayN(numVerts, sizeof(*tex_co), "warpModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts);
modifier_init_texture(wmd->modifier.scene, wmd->texture);
diff --git a/source/blender/modifiers/intern/MOD_wave.c b/source/blender/modifiers/intern/MOD_wave.c
index f0c4940816e..8fe29c78486 100644
--- a/source/blender/modifiers/intern/MOD_wave.c
+++ b/source/blender/modifiers/intern/MOD_wave.c
@@ -78,26 +78,14 @@ static void initData(ModifierData *md)
wmd->defgrp_name[0] = 0;
}
-static void freeData(ModifierData *md)
-{
- WaveModifierData *wmd = (WaveModifierData *) md;
- if (wmd->texture) {
- id_us_min(&wmd->texture->id);
- }
-}
-
static void copyData(ModifierData *md, ModifierData *target)
{
#if 0
WaveModifierData *wmd = (WaveModifierData *) md;
-#endif
WaveModifierData *twmd = (WaveModifierData *) target;
+#endif
modifier_copyData_generic(md, target);
-
- if (twmd->texture) {
- id_us_plus(&twmd->texture->id);
- }
}
static bool dependsOnTime(ModifierData *UNUSED(md))
@@ -131,41 +119,33 @@ static void foreachTexLink(ModifierData *md, Object *ob,
walk(userData, ob, md, "texture");
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- Scene *UNUSED(scene),
- Object *UNUSED(ob),
- DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WaveModifierData *wmd = (WaveModifierData *) md;
if (wmd->objectcenter) {
- DagNode *curNode = dag_get_node(forest, wmd->objectcenter);
+ DagNode *curNode = dag_get_node(ctx->forest, wmd->objectcenter);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA,
"Wave Modifier");
}
if (wmd->map_object) {
- DagNode *curNode = dag_get_node(forest, wmd->map_object);
+ DagNode *curNode = dag_get_node(ctx->forest, wmd->map_object);
- dag_add_relation(forest, curNode, obNode, DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_OB_DATA,
"Wave Modifer");
}
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob),
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WaveModifierData *wmd = (WaveModifierData *)md;
if (wmd->objectcenter != NULL) {
- DEG_add_object_relation(node, wmd->objectcenter, DEG_OB_COMP_TRANSFORM, "Wave Modifier");
+ DEG_add_object_relation(ctx->node, wmd->objectcenter, DEG_OB_COMP_TRANSFORM, "Wave Modifier");
}
if (wmd->map_object != NULL) {
- DEG_add_object_relation(node, wmd->map_object, DEG_OB_COMP_TRANSFORM, "Wave Modifier");
+ DEG_add_object_relation(ctx->node, wmd->map_object, DEG_OB_COMP_TRANSFORM, "Wave Modifier");
}
}
@@ -232,7 +212,7 @@ static void waveModifier_do(WaveModifierData *md,
}
if (wmd->texture) {
- tex_co = MEM_mallocN(sizeof(*tex_co) * numVerts,
+ tex_co = MEM_malloc_arrayN(numVerts, sizeof(*tex_co),
"waveModifier_do tex_co");
get_texture_coords((MappingInfoModifierData *)wmd, ob, dm, vertexCos, tex_co, numVerts);
@@ -395,7 +375,7 @@ ModifierTypeInfo modifierType_Wave = {
/* applyModifierEM */ NULL,
/* initData */ initData,
/* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
+ /* freeData */ NULL,
/* isDisabled */ NULL,
/* updateDepgraph */ updateDepgraph,
/* updateDepsgraph */ updateDepsgraph,
diff --git a/source/blender/modifiers/intern/MOD_weightvg_util.c b/source/blender/modifiers/intern/MOD_weightvg_util.c
index da7230ed5af..416f2964d6e 100644
--- a/source/blender/modifiers/intern/MOD_weightvg_util.c
+++ b/source/blender/modifiers/intern/MOD_weightvg_util.c
@@ -143,9 +143,9 @@ void weightvg_do_mask(int num, const int *indices, float *org_w, const float *ne
t_map.map_object = tex_map_object;
BLI_strncpy(t_map.uvlayer_name, tex_uvlayer_name, sizeof(t_map.uvlayer_name));
t_map.texmapping = tex_mapping;
- v_co = MEM_mallocN(sizeof(*v_co) * numVerts, "WeightVG Modifier, TEX mode, v_co");
+ v_co = MEM_malloc_arrayN(numVerts, sizeof(*v_co), "WeightVG Modifier, TEX mode, v_co");
dm->getVertCos(dm, v_co);
- tex_co = MEM_callocN(sizeof(*tex_co) * numVerts, "WeightVG Modifier, TEX mode, tex_co");
+ tex_co = MEM_calloc_arrayN(numVerts, sizeof(*tex_co), "WeightVG Modifier, TEX mode, tex_co");
get_texture_coords(&t_map, ob, dm, v_co, tex_co, num);
MEM_freeN(v_co);
diff --git a/source/blender/modifiers/intern/MOD_weightvgedit.c b/source/blender/modifiers/intern/MOD_weightvgedit.c
index 2a822ac07b5..8d77747b45d 100644
--- a/source/blender/modifiers/intern/MOD_weightvgedit.c
+++ b/source/blender/modifiers/intern/MOD_weightvgedit.c
@@ -50,7 +50,9 @@
#include "DEG_depsgraph_build.h"
#include "MEM_guardedalloc.h"
+
#include "MOD_weightvg_util.h"
+#include "MOD_modifiertypes.h"
/**************************************
* Modifiers functions. *
@@ -77,10 +79,6 @@ static void freeData(ModifierData *md)
{
WeightVGEditModifierData *wmd = (WeightVGEditModifierData *) md;
curvemapping_free(wmd->cmap_curve);
-
- if (wmd->mask_texture) {
- id_us_min(&wmd->mask_texture->id);
- }
}
static void copyData(ModifierData *md, ModifierData *target)
@@ -91,10 +89,6 @@ static void copyData(ModifierData *md, ModifierData *target)
modifier_copyData_generic(md, target);
twmd->cmap_curve = curvemapping_copy(wmd->cmap_curve);
-
- if (twmd->mask_texture) {
- id_us_plus(&twmd->mask_texture->id);
- }
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
@@ -143,38 +137,31 @@ static void foreachTexLink(ModifierData *md, Object *ob, TexWalkFunc walk, void
walk(userData, ob, md, "mask_texture");
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGEditModifierData *wmd = (WeightVGEditModifierData *) md;
DagNode *curNode;
if (wmd->mask_tex_map_obj && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- curNode = dag_get_node(forest, wmd->mask_tex_map_obj);
+ curNode = dag_get_node(ctx->forest, wmd->mask_tex_map_obj);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGEdit Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL)
- dag_add_relation(forest, obNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, ctx->obNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGEdit Modifier");
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGEditModifierData *wmd = (WeightVGEditModifierData *)md;
if (wmd->mask_tex_map_obj != NULL && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- DEG_add_object_relation(node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGEdit Modifier");
+ DEG_add_object_relation(ctx->node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGEdit Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL) {
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "WeightVGEdit Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "WeightVGEdit Modifier");
}
}
@@ -226,17 +213,16 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
if (!do_add)
return dm;
/* Else, add a valid data layer! */
- dvert = CustomData_add_layer_named(&dm->vertData, CD_MDEFORMVERT, CD_CALLOC,
- NULL, numVerts, wmd->defgrp_name);
+ dvert = CustomData_add_layer(&dm->vertData, CD_MDEFORMVERT, CD_CALLOC, NULL, numVerts);
/* Ultimate security check. */
if (!dvert)
return dm;
}
/* Get org weights, assuming 0.0 for vertices not in given vgroup. */
- org_w = MEM_mallocN(sizeof(float) * numVerts, "WeightVGEdit Modifier, org_w");
- new_w = MEM_mallocN(sizeof(float) * numVerts, "WeightVGEdit Modifier, new_w");
- dw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGEdit Modifier, dw");
+ org_w = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGEdit Modifier, org_w");
+ new_w = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGEdit Modifier, new_w");
+ dw = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGEdit Modifier, dw");
for (i = 0; i < numVerts; i++) {
dw[i] = defvert_find_index(&dvert[i], defgrp_index);
if (dw[i]) {
diff --git a/source/blender/modifiers/intern/MOD_weightvgmix.c b/source/blender/modifiers/intern/MOD_weightvgmix.c
index 9bff7bf11f1..bd1f58e7d5e 100644
--- a/source/blender/modifiers/intern/MOD_weightvgmix.c
+++ b/source/blender/modifiers/intern/MOD_weightvgmix.c
@@ -47,7 +47,9 @@
#include "DEG_depsgraph_build.h"
#include "MEM_guardedalloc.h"
+
#include "MOD_weightvg_util.h"
+#include "MOD_modifiertypes.h"
/**
@@ -124,26 +126,14 @@ static void initData(ModifierData *md)
wmd->mask_tex_mapping = MOD_DISP_MAP_LOCAL;
}
-static void freeData(ModifierData *md)
-{
- WeightVGMixModifierData *wmd = (WeightVGMixModifierData *) md;
- if (wmd->mask_texture) {
- id_us_min(&wmd->mask_texture->id);
- }
-}
-
static void copyData(ModifierData *md, ModifierData *target)
{
#if 0
WeightVGMixModifierData *wmd = (WeightVGMixModifierData *) md;
-#endif
WeightVGMixModifierData *twmd = (WeightVGMixModifierData *) target;
+#endif
modifier_copyData_generic(md, target);
-
- if (twmd->mask_texture) {
- id_us_plus(&twmd->mask_texture->id);
- }
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
@@ -192,40 +182,33 @@ static void foreachTexLink(ModifierData *md, Object *ob, TexWalkFunc walk, void
walk(userData, ob, md, "mask_texture");
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGMixModifierData *wmd = (WeightVGMixModifierData *) md;
DagNode *curNode;
if (wmd->mask_tex_map_obj && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- curNode = dag_get_node(forest, wmd->mask_tex_map_obj);
+ curNode = dag_get_node(ctx->forest, wmd->mask_tex_map_obj);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGMix Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL)
- dag_add_relation(forest, obNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, ctx->obNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGMix Modifier");
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGMixModifierData *wmd = (WeightVGMixModifierData *) md;
if (wmd->mask_tex_map_obj != NULL && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- DEG_add_object_relation(node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGMix Modifier");
- DEG_add_object_relation(node, wmd->mask_tex_map_obj, DEG_OB_COMP_GEOMETRY, "WeightVGMix Modifier");
+ DEG_add_object_relation(ctx->node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGMix Modifier");
+ DEG_add_object_relation(ctx->node, wmd->mask_tex_map_obj, DEG_OB_COMP_GEOMETRY, "WeightVGMix Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL) {
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "WeightVGMix Modifier");
- DEG_add_object_relation(node, ob, DEG_OB_COMP_GEOMETRY, "WeightVGMix Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "WeightVGMix Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_GEOMETRY, "WeightVGMix Modifier");
}
}
@@ -282,16 +265,15 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
if (wmd->mix_set != MOD_WVG_SET_ALL)
return dm;
/* Else, add a valid data layer! */
- dvert = CustomData_add_layer_named(&dm->vertData, CD_MDEFORMVERT, CD_CALLOC,
- NULL, numVerts, wmd->defgrp_name_a);
+ dvert = CustomData_add_layer(&dm->vertData, CD_MDEFORMVERT, CD_CALLOC, NULL, numVerts);
/* Ultimate security check. */
if (!dvert)
return dm;
}
/* Find out which vertices to work on. */
- tidx = MEM_mallocN(sizeof(int) * numVerts, "WeightVGMix Modifier, tidx");
- tdw1 = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGMix Modifier, tdw1");
- tdw2 = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGMix Modifier, tdw2");
+ tidx = MEM_malloc_arrayN(numVerts, sizeof(int), "WeightVGMix Modifier, tidx");
+ tdw1 = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGMix Modifier, tdw1");
+ tdw2 = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGMix Modifier, tdw2");
switch (wmd->mix_set) {
case MOD_WVG_SET_A:
/* All vertices in first vgroup. */
@@ -357,12 +339,12 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
return dm;
}
if (numIdx != -1) {
- indices = MEM_mallocN(sizeof(int) * numIdx, "WeightVGMix Modifier, indices");
+ indices = MEM_malloc_arrayN(numIdx, sizeof(int), "WeightVGMix Modifier, indices");
memcpy(indices, tidx, sizeof(int) * numIdx);
- dw1 = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGMix Modifier, dw1");
+ dw1 = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGMix Modifier, dw1");
memcpy(dw1, tdw1, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tdw1);
- dw2 = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGMix Modifier, dw2");
+ dw2 = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGMix Modifier, dw2");
memcpy(dw2, tdw2, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tdw2);
}
@@ -375,8 +357,8 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
}
MEM_freeN(tidx);
- org_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGMix Modifier, org_w");
- new_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGMix Modifier, new_w");
+ org_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGMix Modifier, org_w");
+ new_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGMix Modifier, new_w");
/* Mix weights. */
for (i = 0; i < numIdx; i++) {
@@ -437,7 +419,7 @@ ModifierTypeInfo modifierType_WeightVGMix = {
/* applyModifierEM */ NULL,
/* initData */ initData,
/* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
+ /* freeData */ NULL,
/* isDisabled */ isDisabled,
/* updateDepgraph */ updateDepgraph,
/* updateDepsgraph */ updateDepsgraph,
diff --git a/source/blender/modifiers/intern/MOD_weightvgproximity.c b/source/blender/modifiers/intern/MOD_weightvgproximity.c
index 2c87838aeab..09991887f69 100644
--- a/source/blender/modifiers/intern/MOD_weightvgproximity.c
+++ b/source/blender/modifiers/intern/MOD_weightvgproximity.c
@@ -51,7 +51,9 @@
#include "DEG_depsgraph_build.h"
#include "MEM_guardedalloc.h"
+
#include "MOD_weightvg_util.h"
+#include "MOD_modifiertypes.h"
//#define USE_TIMEIT
@@ -89,10 +91,13 @@ typedef struct Vert2GeomDataChunk {
/**
* Callback used by BLI_task 'for loop' helper.
*/
-static void vert2geom_task_cb_ex(void *userdata, void *userdata_chunk, const int iter, const int UNUSED(thread_id))
+static void vert2geom_task_cb_ex(
+ void *__restrict userdata,
+ const int iter,
+ const ParallelRangeTLS *__restrict tls)
{
Vert2GeomData *data = userdata;
- Vert2GeomDataChunk *data_chunk = userdata_chunk;
+ Vert2GeomDataChunk *data_chunk = tls->userdata_chunk;
float tmp_co[3];
int i;
@@ -176,9 +181,16 @@ static void get_vert2geom_distance(int numVerts, float (*v_cos)[3],
data.dist[1] = dist_e;
data.dist[2] = dist_f;
- BLI_task_parallel_range_ex(
- 0, numVerts, &data, &data_chunk, sizeof(data_chunk), vert2geom_task_cb_ex,
- numVerts > 10000, false);
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (numVerts > 10000);
+ settings.userdata_chunk = &data_chunk;
+ settings.userdata_chunk_size = sizeof(data_chunk);
+ BLI_task_parallel_range(
+ 0, numVerts,
+ &data,
+ vert2geom_task_cb_ex,
+ &settings);
if (dist_v)
free_bvhtree_from_mesh(&treeData_v);
@@ -274,26 +286,14 @@ static void initData(ModifierData *md)
wmd->max_dist = 1.0f; /* vert arbitrary distance, but don't use 0 */
}
-static void freeData(ModifierData *md)
-{
- WeightVGProximityModifierData *wmd = (WeightVGProximityModifierData *) md;
- if (wmd->mask_texture) {
- id_us_min(&wmd->mask_texture->id);
- }
-}
-
static void copyData(ModifierData *md, ModifierData *target)
{
#if 0
WeightVGProximityModifierData *wmd = (WeightVGProximityModifierData *) md;
-#endif
WeightVGProximityModifierData *twmd = (WeightVGProximityModifierData *) target;
+#endif
modifier_copyData_generic(md, target);
-
- if (twmd->mask_texture) {
- id_us_plus(&twmd->mask_texture->id);
- }
}
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
@@ -343,50 +343,43 @@ static void foreachTexLink(ModifierData *md, Object *ob, TexWalkFunc walk, void
walk(userData, ob, md, "mask_texture");
}
-static void updateDepgraph(ModifierData *md, DagForest *forest,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *UNUSED(ob), DagNode *obNode)
+static void updateDepgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGProximityModifierData *wmd = (WeightVGProximityModifierData *) md;
DagNode *curNode;
if (wmd->proximity_ob_target) {
- curNode = dag_get_node(forest, wmd->proximity_ob_target);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ curNode = dag_get_node(ctx->forest, wmd->proximity_ob_target);
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGProximity Modifier");
}
if (wmd->mask_tex_map_obj && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- curNode = dag_get_node(forest, wmd->mask_tex_map_obj);
+ curNode = dag_get_node(ctx->forest, wmd->mask_tex_map_obj);
- dag_add_relation(forest, curNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, curNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGProximity Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL)
- dag_add_relation(forest, obNode, obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
+ dag_add_relation(ctx->forest, ctx->obNode, ctx->obNode, DAG_RL_DATA_DATA | DAG_RL_OB_DATA,
"WeightVGProximity Modifier");
}
-static void updateDepsgraph(ModifierData *md,
- struct Main *UNUSED(bmain),
- struct Scene *UNUSED(scene),
- Object *ob,
- struct DepsNodeHandle *node)
+static void updateDepsgraph(ModifierData *md, const ModifierUpdateDepsgraphContext *ctx)
{
WeightVGProximityModifierData *wmd = (WeightVGProximityModifierData *)md;
if (wmd->proximity_ob_target != NULL) {
- DEG_add_object_relation(node, wmd->proximity_ob_target, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
- DEG_add_object_relation(node, wmd->proximity_ob_target, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, wmd->proximity_ob_target, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, wmd->proximity_ob_target, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
}
if (wmd->mask_tex_map_obj != NULL && wmd->mask_tex_mapping == MOD_DISP_MAP_OBJECT) {
- DEG_add_object_relation(node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
- DEG_add_object_relation(node, wmd->mask_tex_map_obj, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, wmd->mask_tex_map_obj, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, wmd->mask_tex_map_obj, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
}
if (wmd->mask_tex_mapping == MOD_DISP_MAP_GLOBAL) {
- DEG_add_object_relation(node, ob, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
- DEG_add_object_relation(node, ob, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_TRANSFORM, "WeightVGProximity Modifier");
+ DEG_add_object_relation(ctx->node, ctx->object, DEG_OB_COMP_GEOMETRY, "WeightVGProximity Modifier");
}
}
@@ -452,9 +445,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
/* Find out which vertices to work on (all vertices in vgroup), and get their relevant weight.
*/
- tidx = MEM_mallocN(sizeof(int) * numVerts, "WeightVGProximity Modifier, tidx");
- tw = MEM_mallocN(sizeof(float) * numVerts, "WeightVGProximity Modifier, tw");
- tdw = MEM_mallocN(sizeof(MDeformWeight *) * numVerts, "WeightVGProximity Modifier, tdw");
+ tidx = MEM_malloc_arrayN(numVerts, sizeof(int), "WeightVGProximity Modifier, tidx");
+ tw = MEM_malloc_arrayN(numVerts, sizeof(float), "WeightVGProximity Modifier, tw");
+ tdw = MEM_malloc_arrayN(numVerts, sizeof(MDeformWeight *), "WeightVGProximity Modifier, tdw");
for (i = 0; i < numVerts; i++) {
MDeformWeight *_dw = defvert_find_index(&dvert[i], defgrp_index);
if (_dw) {
@@ -471,11 +464,11 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
return dm;
}
if (numIdx != numVerts) {
- indices = MEM_mallocN(sizeof(int) * numIdx, "WeightVGProximity Modifier, indices");
+ indices = MEM_malloc_arrayN(numIdx, sizeof(int), "WeightVGProximity Modifier, indices");
memcpy(indices, tidx, sizeof(int) * numIdx);
- org_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGProximity Modifier, org_w");
+ org_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGProximity Modifier, org_w");
memcpy(org_w, tw, sizeof(float) * numIdx);
- dw = MEM_mallocN(sizeof(MDeformWeight *) * numIdx, "WeightVGProximity Modifier, dw");
+ dw = MEM_malloc_arrayN(numIdx, sizeof(MDeformWeight *), "WeightVGProximity Modifier, dw");
memcpy(dw, tdw, sizeof(MDeformWeight *) * numIdx);
MEM_freeN(tw);
MEM_freeN(tdw);
@@ -484,16 +477,16 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
org_w = tw;
dw = tdw;
}
- new_w = MEM_mallocN(sizeof(float) * numIdx, "WeightVGProximity Modifier, new_w");
+ new_w = MEM_malloc_arrayN(numIdx, sizeof(float), "WeightVGProximity Modifier, new_w");
MEM_freeN(tidx);
/* Get our vertex coordinates. */
- v_cos = MEM_mallocN(sizeof(float[3]) * numIdx, "WeightVGProximity Modifier, v_cos");
+ v_cos = MEM_malloc_arrayN(numIdx, sizeof(float[3]), "WeightVGProximity Modifier, v_cos");
if (numIdx != numVerts) {
/* XXX In some situations, this code can be up to about 50 times more performant
* than simply using getVertCo for each affected vertex...
*/
- float (*tv_cos)[3] = MEM_mallocN(sizeof(float[3]) * numVerts, "WeightVGProximity Modifier, tv_cos");
+ float (*tv_cos)[3] = MEM_malloc_arrayN(numVerts, sizeof(float[3]), "WeightVGProximity Modifier, tv_cos");
dm->getVertCos(dm, tv_cos);
for (i = 0; i < numIdx; i++)
copy_v3_v3(v_cos[i], tv_cos[indices[i]]);
@@ -532,9 +525,9 @@ static DerivedMesh *applyModifier(ModifierData *md, Object *ob, DerivedMesh *der
/* We must check that we do have a valid target_dm! */
if (target_dm) {
SpaceTransform loc2trgt;
- float *dists_v = use_trgt_verts ? MEM_mallocN(sizeof(float) * numIdx, "dists_v") : NULL;
- float *dists_e = use_trgt_edges ? MEM_mallocN(sizeof(float) * numIdx, "dists_e") : NULL;
- float *dists_f = use_trgt_faces ? MEM_mallocN(sizeof(float) * numIdx, "dists_f") : NULL;
+ float *dists_v = use_trgt_verts ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_v") : NULL;
+ float *dists_e = use_trgt_edges ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_e") : NULL;
+ float *dists_f = use_trgt_faces ? MEM_malloc_arrayN(numIdx, sizeof(float), "dists_f") : NULL;
BLI_SPACE_TRANSFORM_SETUP(&loc2trgt, ob, obr);
get_vert2geom_distance(numIdx, v_cos, dists_v, dists_e, dists_f,
@@ -615,7 +608,7 @@ ModifierTypeInfo modifierType_WeightVGProximity = {
/* applyModifierEM */ NULL,
/* initData */ initData,
/* requiredDataMask */ requiredDataMask,
- /* freeData */ freeData,
+ /* freeData */ NULL,
/* isDisabled */ isDisabled,
/* updateDepgraph */ updateDepgraph,
/* updateDepsgraph */ updateDepsgraph,
diff --git a/source/blender/modifiers/intern/MOD_wireframe.c b/source/blender/modifiers/intern/MOD_wireframe.c
index adadd4834d4..15f8b185a3d 100644
--- a/source/blender/modifiers/intern/MOD_wireframe.c
+++ b/source/blender/modifiers/intern/MOD_wireframe.c
@@ -52,11 +52,6 @@ static void copyData(ModifierData *md, ModifierData *target)
modifier_copyData_generic(md, target);
}
-static bool isDisabled(ModifierData *UNUSED(md), int UNUSED(useRenderParams))
-{
- return false;
-}
-
static CustomDataMask requiredDataMask(Object *UNUSED(ob), ModifierData *md)
{
WireframeModifierData *wmd = (WireframeModifierData *)md;
@@ -131,7 +126,7 @@ ModifierTypeInfo modifierType_Wireframe = {
/* initData */ initData,
/* requiredDataMask */ requiredDataMask,
/* freeData */ NULL,
- /* isDisabled */ isDisabled,
+ /* isDisabled */ NULL,
/* updateDepgraph */ NULL,
/* updateDepsgraph */ NULL,
/* dependsOnTime */ NULL,
diff --git a/source/blender/nodes/CMakeLists.txt b/source/blender/nodes/CMakeLists.txt
index d20881df150..5247599bdf7 100644
--- a/source/blender/nodes/CMakeLists.txt
+++ b/source/blender/nodes/CMakeLists.txt
@@ -163,6 +163,7 @@ set(SRC
shader/nodes/node_shader_background.c
shader/nodes/node_shader_bsdf_anisotropic.c
shader/nodes/node_shader_bsdf_diffuse.c
+ shader/nodes/node_shader_bsdf_principled.c
shader/nodes/node_shader_bsdf_glass.c
shader/nodes/node_shader_bsdf_glossy.c
shader/nodes/node_shader_bsdf_toon.c
@@ -191,6 +192,9 @@ set(SRC
shader/nodes/node_shader_script.c
shader/nodes/node_shader_subsurface_scattering.c
shader/nodes/node_shader_tangent.c
+ shader/nodes/node_shader_bevel.c
+ shader/nodes/node_shader_displacement.c
+ shader/nodes/node_shader_vector_displacement.c
shader/nodes/node_shader_tex_brick.c
shader/nodes/node_shader_tex_checker.c
shader/nodes/node_shader_tex_coord.c
@@ -206,6 +210,7 @@ set(SRC
shader/nodes/node_shader_tex_wave.c
shader/nodes/node_shader_volume_scatter.c
shader/nodes/node_shader_volume_absorption.c
+ shader/nodes/node_shader_volume_principled.c
shader/nodes/node_shader_uvAlongStroke.c
shader/nodes/node_shader_uvmap.c
shader/node_shader_tree.c
@@ -288,8 +293,4 @@ if(WITH_FREESTYLE)
add_definitions(-DWITH_FREESTYLE)
endif()
-if(WITH_CYCLES AND WITH_CYCLES_DEBUG)
- add_definitions(-DWITH_CYCLES_DEBUG)
-endif()
-
blender_add_lib(bf_nodes "${SRC}" "${INC}" "${INC_SYS}")
diff --git a/source/blender/nodes/NOD_composite.h b/source/blender/nodes/NOD_composite.h
index 0215db1dd55..a5c2e604f46 100644
--- a/source/blender/nodes/NOD_composite.h
+++ b/source/blender/nodes/NOD_composite.h
@@ -139,6 +139,8 @@ void register_node_type_cmp_trackpos(void);
void register_node_type_cmp_planetrackdeform(void);
void register_node_type_cmp_cornerpin(void);
-void node_cmp_rlayers_force_hidden_passes(struct bNode *node);
+void node_cmp_rlayers_outputs(struct bNodeTree *ntree, struct bNode *node);
+void node_cmp_rlayers_register_pass(struct bNodeTree *ntree, struct bNode *node, struct Scene *scene, struct SceneRenderLayer *srl, const char *name, int type);
+const char *node_cmp_rlayers_sock_to_pass(int sock_index);
#endif
diff --git a/source/blender/nodes/NOD_shader.h b/source/blender/nodes/NOD_shader.h
index 4c0047f1d58..b00307ed7fb 100644
--- a/source/blender/nodes/NOD_shader.h
+++ b/source/blender/nodes/NOD_shader.h
@@ -78,6 +78,9 @@ void register_node_type_sh_tex_brick(void);
void register_node_type_sh_tex_pointdensity(void);
void register_node_type_sh_attribute(void);
+void register_node_type_sh_bevel(void);
+void register_node_type_sh_displacement(void);
+void register_node_type_sh_vector_displacement(void);
void register_node_type_sh_geometry(void);
void register_node_type_sh_light_path(void);
void register_node_type_sh_light_falloff(void);
@@ -106,10 +109,12 @@ void register_node_type_sh_bsdf_transparent(void);
void register_node_type_sh_bsdf_velvet(void);
void register_node_type_sh_bsdf_toon(void);
void register_node_type_sh_bsdf_anisotropic(void);
+void register_node_type_sh_bsdf_principled(void);
void register_node_type_sh_emission(void);
void register_node_type_sh_holdout(void);
void register_node_type_sh_volume_absorption(void);
void register_node_type_sh_volume_scatter(void);
+void register_node_type_sh_volume_principled(void);
void register_node_type_sh_bsdf_hair(void);
void register_node_type_sh_subsurface_scattering(void);
void register_node_type_sh_mix_shader(void);
diff --git a/source/blender/nodes/NOD_static_types.h b/source/blender/nodes/NOD_static_types.h
index a9c0df7d7e8..bc90e33ed03 100644
--- a/source/blender/nodes/NOD_static_types.h
+++ b/source/blender/nodes/NOD_static_types.h
@@ -80,6 +80,7 @@ DefNode( ShaderNode, SH_NODE_BACKGROUND, 0, "BA
DefNode( ShaderNode, SH_NODE_HOLDOUT, 0, "HOLDOUT", Holdout, "Holdout", "" )
DefNode( ShaderNode, SH_NODE_BSDF_ANISOTROPIC, def_anisotropic, "BSDF_ANISOTROPIC", BsdfAnisotropic, "Anisotropic BSDF", "" )
DefNode( ShaderNode, SH_NODE_BSDF_DIFFUSE, 0, "BSDF_DIFFUSE", BsdfDiffuse, "Diffuse BSDF", "" )
+DefNode( ShaderNode, SH_NODE_BSDF_PRINCIPLED, def_principled, "BSDF_PRINCIPLED", BsdfPrincipled, "Principled BSDF", "" )
DefNode( ShaderNode, SH_NODE_BSDF_GLOSSY, def_glossy, "BSDF_GLOSSY", BsdfGlossy, "Glossy BSDF", "" )
DefNode( ShaderNode, SH_NODE_BSDF_GLASS, def_glass, "BSDF_GLASS", BsdfGlass, "Glass BSDF", "" )
DefNode( ShaderNode, SH_NODE_BSDF_REFRACTION, def_refraction, "BSDF_REFRACTION", BsdfRefraction, "Refraction BSDF", "" )
@@ -91,6 +92,7 @@ DefNode( ShaderNode, SH_NODE_BSDF_HAIR, def_hair, "BS
DefNode( ShaderNode, SH_NODE_SUBSURFACE_SCATTERING, def_sh_subsurface, "SUBSURFACE_SCATTERING",SubsurfaceScattering,"Subsurface Scattering","")
DefNode( ShaderNode, SH_NODE_VOLUME_ABSORPTION, 0, "VOLUME_ABSORPTION", VolumeAbsorption, "Volume Absorption", "" )
DefNode( ShaderNode, SH_NODE_VOLUME_SCATTER, 0, "VOLUME_SCATTER", VolumeScatter, "Volume Scatter", "" )
+DefNode( ShaderNode, SH_NODE_VOLUME_PRINCIPLED, 0, "PRINCIPLED_VOLUME", VolumePrincipled, "Principled Volume", "" )
DefNode( ShaderNode, SH_NODE_EMISSION, 0, "EMISSION", Emission, "Emission", "" )
DefNode( ShaderNode, SH_NODE_NEW_GEOMETRY, 0, "NEW_GEOMETRY", NewGeometry, "Geometry", "" )
DefNode( ShaderNode, SH_NODE_LIGHT_PATH, 0, "LIGHT_PATH", LightPath, "Light Path", "" )
@@ -125,6 +127,9 @@ DefNode( ShaderNode, SH_NODE_UVMAP, def_sh_uvmap, "UV
DefNode( ShaderNode, SH_NODE_UVALONGSTROKE, def_sh_uvalongstroke, "UVALONGSTROKE", UVAlongStroke, "UV Along Stroke", "" )
DefNode( ShaderNode, SH_NODE_SEPXYZ, 0, "SEPXYZ", SeparateXYZ, "Separate XYZ", "" )
DefNode( ShaderNode, SH_NODE_COMBXYZ, 0, "COMBXYZ", CombineXYZ, "Combine XYZ", "" )
+DefNode( ShaderNode, SH_NODE_BEVEL, def_sh_bevel, "BEVEL", Bevel, "Bevel", "" )
+DefNode( ShaderNode, SH_NODE_DISPLACEMENT, def_sh_displacement, "DISPLACEMENT", Displacement, "Displacement", "" )
+DefNode( ShaderNode, SH_NODE_VECTOR_DISPLACEMENT,def_sh_vector_displacement,"VECTOR_DISPLACEMENT",VectorDisplacement,"Vector Displacement","" )
DefNode( CompositorNode, CMP_NODE_VIEWER, def_cmp_viewer, "VIEWER", Viewer, "Viewer", "" )
DefNode( CompositorNode, CMP_NODE_RGB, 0, "RGB", RGB, "RGB", "" )
@@ -178,7 +183,7 @@ DefNode( CompositorNode, CMP_NODE_DISPLACE, 0, "DISPL
DefNode( CompositorNode, CMP_NODE_COMBHSVA, 0, "COMBHSVA", CombHSVA, "Combine HSVA", "" )
DefNode( CompositorNode, CMP_NODE_MATH, def_math, "MATH", Math, "Math", "" )
DefNode( CompositorNode, CMP_NODE_LUMA_MATTE, def_cmp_luma_matte, "LUMA_MATTE", LumaMatte, "Luminance Key", "" )
-DefNode( CompositorNode, CMP_NODE_BRIGHTCONTRAST, 0, "BRIGHTCONTRAST", BrightContrast, "Bright/Contrast", "" )
+DefNode( CompositorNode, CMP_NODE_BRIGHTCONTRAST, def_cmp_brightcontrast, "BRIGHTCONTRAST", BrightContrast, "Bright/Contrast", "" )
DefNode( CompositorNode, CMP_NODE_GAMMA, 0, "GAMMA", Gamma, "Gamma", "" )
DefNode( CompositorNode, CMP_NODE_INVERT, def_cmp_invert, "INVERT", Invert, "Invert", "" )
DefNode( CompositorNode, CMP_NODE_NORMALIZE, 0, "NORMALIZE", Normalize, "Normalize", "" )
diff --git a/source/blender/nodes/composite/node_composite_tree.c b/source/blender/nodes/composite/node_composite_tree.c
index cb565bd5491..36778a18f77 100644
--- a/source/blender/nodes/composite/node_composite_tree.c
+++ b/source/blender/nodes/composite/node_composite_tree.c
@@ -240,8 +240,15 @@ void ntreeCompositExecTree(Scene *scene, bNodeTree *ntree, RenderData *rd, int r
/* *********************************************** */
-/* based on rules, force sockets hidden always */
-void ntreeCompositForceHidden(bNodeTree *ntree)
+/* Update the outputs of the render layer nodes.
+ * Since the outputs depend on the render engine, this part is a bit complex:
+ * - ntreeCompositUpdateRLayers is called and loops over all render layer nodes
+ * - Each render layer node calls the update function of the render engine that's used for its scene
+ * - The render engine calls RE_engine_register_pass for each pass
+ * - RE_engine_register_pass calls ntreeCompositRegisterPass,
+ * which calls node_cmp_rlayers_register_pass for every render layer node
+ */
+void ntreeCompositUpdateRLayers(bNodeTree *ntree)
{
bNode *node;
@@ -249,16 +256,20 @@ void ntreeCompositForceHidden(bNodeTree *ntree)
for (node = ntree->nodes.first; node; node = node->next) {
if (node->type == CMP_NODE_R_LAYERS)
- node_cmp_rlayers_force_hidden_passes(node);
-
- /* XXX this stuff is called all the time, don't want that.
- * Updates should only happen when actually necessary.
- */
-#if 0
- else if (node->type == CMP_NODE_IMAGE) {
- nodeUpdate(ntree, node);
- }
-#endif
+ node_cmp_rlayers_outputs(ntree, node);
+ }
+
+}
+
+void ntreeCompositRegisterPass(bNodeTree *ntree, Scene *scene, SceneRenderLayer *srl, const char *name, int type)
+{
+ bNode *node;
+
+ if (ntree == NULL) return;
+
+ for (node = ntree->nodes.first; node; node = node->next) {
+ if (node->type == CMP_NODE_R_LAYERS)
+ node_cmp_rlayers_register_pass(ntree, node, scene, srl, name, type);
}
}
diff --git a/source/blender/nodes/composite/node_composite_util.h b/source/blender/nodes/composite/node_composite_util.h
index 2dac0cc639a..22c5e6f9507 100644
--- a/source/blender/nodes/composite/node_composite_util.h
+++ b/source/blender/nodes/composite/node_composite_util.h
@@ -42,6 +42,7 @@
#include "BLT_translation.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_image.h"
#include "BKE_texture.h"
diff --git a/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c b/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
index 2ad097013ef..fde7dccb4ac 100644
--- a/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
+++ b/source/blender/nodes/composite/nodes/node_composite_bilateralblur.c
@@ -47,6 +47,7 @@ static void node_composit_init_bilateralblur(bNodeTree *UNUSED(ntree), bNode *no
{
NodeBilateralBlurData *nbbd = MEM_callocN(sizeof(NodeBilateralBlurData), "node bilateral blur data");
node->storage = nbbd;
+ nbbd->iter = 1;
nbbd->sigma_color = 0.3;
nbbd->sigma_space = 5.0;
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_brightness.c b/source/blender/nodes/composite/nodes/node_composite_brightness.c
index 62f23f417b2..26e4d3a52c9 100644
--- a/source/blender/nodes/composite/nodes/node_composite_brightness.c
+++ b/source/blender/nodes/composite/nodes/node_composite_brightness.c
@@ -46,6 +46,10 @@ static bNodeSocketTemplate cmp_node_brightcontrast_out[] = {
{ -1, 0, "" }
};
+static void node_composit_init_brightcontrast(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ node->custom1 = 1;
+}
void register_node_type_cmp_brightcontrast(void)
{
@@ -53,6 +57,7 @@ void register_node_type_cmp_brightcontrast(void)
cmp_node_type_base(&ntype, CMP_NODE_BRIGHTCONTRAST, "Bright/Contrast", NODE_CLASS_OP_COLOR, 0);
node_type_socket_templates(&ntype, cmp_node_brightcontrast_in, cmp_node_brightcontrast_out);
+ node_type_init(&ntype, node_composit_init_brightcontrast);
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_directionalblur.c b/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
index 6eb27a228ad..336eb3409ff 100644
--- a/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
+++ b/source/blender/nodes/composite/nodes/node_composite_directionalblur.c
@@ -46,6 +46,7 @@ static void node_composit_init_dblur(bNodeTree *UNUSED(ntree), bNode *node)
{
NodeDBlurData *ndbd = MEM_callocN(sizeof(NodeDBlurData), "node dblur data");
node->storage = ndbd;
+ ndbd->iter = 1;
ndbd->center_x = 0.5;
ndbd->center_y = 0.5;
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c b/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
index 952ba78aff3..124e33d186f 100644
--- a/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
+++ b/source/blender/nodes/composite/nodes/node_composite_hueSatVal.c
@@ -37,8 +37,8 @@
static bNodeSocketTemplate cmp_node_hue_sat_in[] = {
{ SOCK_RGBA, 1, N_("Image"), 1.0f, 1.0f, 1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Hue"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
- { SOCK_FLOAT, 1, N_("Saturation"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
- { SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Saturation"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Value"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Fac"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/composite/nodes/node_composite_image.c b/source/blender/nodes/composite/nodes/node_composite_image.c
index 4f02c106569..1e240c2f84b 100644
--- a/source/blender/nodes/composite/nodes/node_composite_image.c
+++ b/source/blender/nodes/composite/nodes/node_composite_image.c
@@ -32,192 +32,108 @@
#include "node_composite_util.h"
#include "BLI_utildefines.h"
+#include "BLI_linklist.h"
#include "DNA_scene_types.h"
+#include "RE_engine.h"
+
#include "BKE_context.h"
#include "BKE_global.h"
#include "BKE_main.h"
-#ifdef WITH_CYCLES_DEBUG
-# include "RE_pipeline.h"
-#endif
-
/* **************** IMAGE (and RenderResult, multilayer image) ******************** */
static bNodeSocketTemplate cmp_node_rlayers_out[] = {
- { SOCK_RGBA, 0, N_("Image"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 0, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 0, N_("Z"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_VECTOR, 0, N_("Normal"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_VECTOR, 0, N_("UV"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_VECTOR, 0, N_("Speed"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Diffuse"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Specular"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Shadow"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("AO"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Reflect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Refract"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Indirect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 0, N_("IndexOB"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 0, N_("IndexMA"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 0, N_("Mist"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Emit"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Environment"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Diffuse Direct"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Diffuse Indirect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Diffuse Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Glossy Direct"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Glossy Indirect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Glossy Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Transmission Direct"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Transmission Indirect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Transmission Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Subsurface Direct"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Subsurface Indirect"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
- { SOCK_RGBA, 0, N_("Subsurface Color"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
-#ifdef WITH_CYCLES_DEBUG
- { SOCK_RGBA, 0, N_("Debug"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
-#endif
+ { SOCK_RGBA, 0, N_("Image"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 0, N_("Alpha"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 0, N_(RE_PASSNAME_Z), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 0, N_(RE_PASSNAME_NORMAL), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 0, N_(RE_PASSNAME_UV), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_VECTOR, 0, N_(RE_PASSNAME_VECTOR), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_RGBA), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_DIFFUSE), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_SPEC), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_SHADOW), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_AO), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_REFLECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_REFRACT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_INDIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 0, N_(RE_PASSNAME_INDEXOB), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 0, N_(RE_PASSNAME_INDEXMA), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 0, N_(RE_PASSNAME_MIST), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_EMIT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_ENVIRONMENT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_DIFFUSE_DIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_DIFFUSE_INDIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_DIFFUSE_COLOR), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_GLOSSY_DIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_GLOSSY_INDIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_GLOSSY_COLOR), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_TRANSM_DIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_TRANSM_INDIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_TRANSM_COLOR), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_SUBSURFACE_DIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_SUBSURFACE_INDIRECT), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_RGBA, 0, N_(RE_PASSNAME_SUBSURFACE_COLOR), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ -1, 0, "" }
};
-static bNodeSocket *cmp_node_image_add_render_pass_output(bNodeTree *ntree, bNode *node, int pass, int rres_index)
+static void cmp_node_image_add_pass_output(bNodeTree *ntree, bNode *node,
+ const char *name, const char *passname,
+ int rres_index, int type, int is_rlayers,
+ LinkNodePair *available_sockets, int *prev_index)
{
bNodeSocket *sock;
- NodeImageLayer *sockdata;
-
- sock = node_add_socket_from_template(ntree, node, &cmp_node_rlayers_out[rres_index], SOCK_OUT);
- /* extra socket info */
- sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
- sock->storage = sockdata;
-
- sockdata->pass_flag = pass;
-
- return sock;
-}
-
-static void cmp_node_image_add_render_pass_outputs(bNodeTree *ntree, bNode *node, int passflag)
-{
- if (passflag & SCE_PASS_COMBINED) {
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_COMBINED, RRES_OUT_IMAGE);
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_COMBINED, RRES_OUT_ALPHA);
- }
-
- if (passflag & SCE_PASS_Z)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_Z, RRES_OUT_Z);
- if (passflag & SCE_PASS_NORMAL)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_NORMAL, RRES_OUT_NORMAL);
- if (passflag & SCE_PASS_VECTOR)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_VECTOR, RRES_OUT_VEC);
- if (passflag & SCE_PASS_UV)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_UV, RRES_OUT_UV);
- if (passflag & SCE_PASS_RGBA)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_RGBA, RRES_OUT_RGBA);
- if (passflag & SCE_PASS_DIFFUSE)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_DIFFUSE, RRES_OUT_DIFF);
- if (passflag & SCE_PASS_SPEC)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_SPEC, RRES_OUT_SPEC);
- if (passflag & SCE_PASS_SHADOW)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_SHADOW, RRES_OUT_SHADOW);
- if (passflag & SCE_PASS_AO)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_AO, RRES_OUT_AO);
- if (passflag & SCE_PASS_REFLECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_REFLECT, RRES_OUT_REFLECT);
- if (passflag & SCE_PASS_REFRACT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_REFRACT, RRES_OUT_REFRACT);
- if (passflag & SCE_PASS_INDIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_INDIRECT, RRES_OUT_INDIRECT);
- if (passflag & SCE_PASS_INDEXOB)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_INDEXOB, RRES_OUT_INDEXOB);
- if (passflag & SCE_PASS_INDEXMA)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_INDEXMA, RRES_OUT_INDEXMA);
- if (passflag & SCE_PASS_MIST)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_MIST, RRES_OUT_MIST);
- if (passflag & SCE_PASS_EMIT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_EMIT, RRES_OUT_EMIT);
- if (passflag & SCE_PASS_ENVIRONMENT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_ENVIRONMENT, RRES_OUT_ENV);
-
- if (passflag & SCE_PASS_DIFFUSE_DIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_DIFFUSE_DIRECT, RRES_OUT_DIFF_DIRECT);
- if (passflag & SCE_PASS_DIFFUSE_INDIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_DIFFUSE_INDIRECT, RRES_OUT_DIFF_INDIRECT);
- if (passflag & SCE_PASS_DIFFUSE_COLOR)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_DIFFUSE_COLOR, RRES_OUT_DIFF_COLOR);
-
- if (passflag & SCE_PASS_GLOSSY_DIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_GLOSSY_DIRECT, RRES_OUT_GLOSSY_DIRECT);
- if (passflag & SCE_PASS_GLOSSY_INDIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_GLOSSY_INDIRECT, RRES_OUT_GLOSSY_INDIRECT);
- if (passflag & SCE_PASS_GLOSSY_COLOR)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_GLOSSY_COLOR, RRES_OUT_GLOSSY_COLOR);
-
- if (passflag & SCE_PASS_TRANSM_DIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_TRANSM_DIRECT, RRES_OUT_TRANSM_DIRECT);
- if (passflag & SCE_PASS_TRANSM_INDIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_TRANSM_INDIRECT, RRES_OUT_TRANSM_INDIRECT);
- if (passflag & SCE_PASS_TRANSM_COLOR)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_TRANSM_COLOR, RRES_OUT_TRANSM_COLOR);
-
- if (passflag & SCE_PASS_SUBSURFACE_DIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_SUBSURFACE_DIRECT, RRES_OUT_SUBSURFACE_DIRECT);
- if (passflag & SCE_PASS_SUBSURFACE_INDIRECT)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_SUBSURFACE_INDIRECT, RRES_OUT_SUBSURFACE_INDIRECT);
- if (passflag & SCE_PASS_SUBSURFACE_COLOR)
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_SUBSURFACE_COLOR, RRES_OUT_SUBSURFACE_COLOR);
-
-#ifdef WITH_CYCLES_DEBUG
- cmp_node_image_add_render_pass_output(ntree, node, SCE_PASS_DEBUG, RRES_OUT_DEBUG);
-#endif
-}
-
-static void cmp_node_image_add_multilayer_outputs(bNodeTree *ntree, bNode *node, RenderLayer *rl)
-{
- bNodeSocket *sock;
- NodeImageLayer *sockdata;
- RenderPass *rpass;
- int index;
- int passflag = 0;
- for (rpass = rl->passes.first, index = 0; rpass; rpass = rpass->next, ++index) {
- int type;
- if (rpass->channels == 1)
- type = SOCK_FLOAT;
- else
- type = SOCK_RGBA;
-
- /* we only need one socket per type */
- if (passflag & rpass->passtype)
- continue;
-
- passflag |= rpass->passtype;
-
- sock = nodeAddStaticSocket(ntree, node, SOCK_OUT, type, PROP_NONE, rpass->internal_name, rpass->internal_name);
+ int sock_index = BLI_findstringindex(&node->outputs, name, offsetof(bNodeSocket, name));
+
+ if (sock_index < 0) {
+ /* The first 31 sockets always are the legacy hardcoded sockets.
+ * Any dynamically allocated sockets follow afterwards, and are sorted in the order in which they were stored in the RenderResult.
+ * Therefore, we remember the index of the last matched socket. New sockets are placed behind the previously traversed one, but always after the first 31. */
+ int after_index = *prev_index;
+ if (is_rlayers && after_index < 30)
+ after_index = 30;
+
+ if (rres_index >= 0) {
+ sock = node_add_socket_from_template(ntree, node, &cmp_node_rlayers_out[rres_index], SOCK_OUT);
+ }
+ else {
+ sock = nodeAddStaticSocket(ntree, node, SOCK_OUT, type, PROP_NONE, name, name);
+ }
/* extra socket info */
- sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
+ NodeImageLayer *sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
sock->storage = sockdata;
-
- sockdata->pass_index = index;
- sockdata->pass_flag = rpass->passtype;
-
- if (rpass->passtype == SCE_PASS_COMBINED) {
- sock = nodeAddStaticSocket(ntree, node, SOCK_OUT, SOCK_FLOAT, PROP_NONE, "Alpha", "Alpha");
- sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
- sock->storage = sockdata;
- sockdata->pass_index = index;
- sockdata->pass_flag = rpass->passtype;
+
+ BLI_strncpy(sockdata->pass_name, passname, sizeof(sockdata->pass_name));
+
+ sock_index = BLI_listbase_count(&node->outputs) - 1;
+ if (sock_index != after_index + 1) {
+ bNodeSocket *after_sock = BLI_findlink(&node->outputs, after_index);
+ BLI_remlink(&node->outputs, sock);
+ BLI_insertlinkafter(&node->outputs, after_sock, sock);
+ }
+ }
+ else {
+ sock = BLI_findlink(&node->outputs, sock_index);
+ NodeImageLayer *sockdata = sock->storage;
+ if (sockdata) {
+ BLI_strncpy(sockdata->pass_name, passname, sizeof(sockdata->pass_name));
}
}
+
+ BLI_linklist_append(available_sockets, sock);
+ *prev_index = sock_index;
}
-static void cmp_node_image_create_outputs(bNodeTree *ntree, bNode *node)
+static void cmp_node_image_create_outputs(bNodeTree *ntree, bNode *node, LinkNodePair *available_sockets)
{
Image *ima = (Image *)node->id;
+ ImBuf *ibuf;
+ int prev_index = -1;
if (ima) {
ImageUser *iuser = node->storage;
ImageUser load_iuser = {NULL};
- ImBuf *ibuf;
int offset = BKE_image_sequence_guess_offset(ima);
/* It is possible that image user in this node is not
@@ -238,104 +154,147 @@ static void cmp_node_image_create_outputs(bNodeTree *ntree, bNode *node)
RenderLayer *rl = BLI_findlink(&ima->rr->layers, iuser->layer);
if (rl) {
- if (ima->type != IMA_TYPE_MULTILAYER)
- cmp_node_image_add_render_pass_outputs(ntree, node, rl->passflag);
- else
- cmp_node_image_add_multilayer_outputs(ntree, node, rl);
+ RenderPass *rpass;
+ for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
+ int type;
+ if (rpass->channels == 1)
+ type = SOCK_FLOAT;
+ else
+ type = SOCK_RGBA;
+
+ cmp_node_image_add_pass_output(ntree, node, rpass->name, rpass->name, -1, type, false, available_sockets, &prev_index);
+ /* Special handling for the Combined pass to ensure compatibility. */
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED)) {
+ cmp_node_image_add_pass_output(ntree, node, "Alpha", rpass->name, -1, SOCK_FLOAT, false, available_sockets, &prev_index);
+ }
+ }
+ BKE_image_release_ibuf(ima, ibuf, NULL);
+ return;
}
- else
- cmp_node_image_add_render_pass_outputs(ntree, node, RRES_OUT_IMAGE | RRES_OUT_ALPHA);
}
- else
- cmp_node_image_add_render_pass_outputs(ntree, node, RRES_OUT_IMAGE | RRES_OUT_ALPHA | RRES_OUT_Z);
-
+ }
+
+ cmp_node_image_add_pass_output(ntree, node, "Image", RE_PASSNAME_COMBINED, -1, SOCK_RGBA, false, available_sockets, &prev_index);
+ cmp_node_image_add_pass_output(ntree, node, "Alpha", RE_PASSNAME_COMBINED, -1, SOCK_FLOAT, false, available_sockets, &prev_index);
+
+ if (ima) {
+ if (!ima->rr) {
+ cmp_node_image_add_pass_output(ntree, node, RE_PASSNAME_Z, RE_PASSNAME_Z, -1, SOCK_FLOAT, false, available_sockets, &prev_index);
+ }
BKE_image_release_ibuf(ima, ibuf, NULL);
}
- else
- cmp_node_image_add_render_pass_outputs(ntree, node, RRES_OUT_IMAGE | RRES_OUT_ALPHA);
}
-static bNodeSocket *cmp_node_image_output_find_match(bNode *UNUSED(node), bNodeSocket *newsock, ListBase *oldsocklist)
-{
- bNodeSocket *sock;
-
- for (sock = oldsocklist->first; sock; sock = sock->next)
- if (STREQ(sock->name, newsock->name))
- return sock;
- return NULL;
-}
+typedef struct RLayerUpdateData {
+ LinkNodePair *available_sockets;
+ int prev_index;
+} RLayerUpdateData;
-static bNodeSocket *cmp_node_image_output_relink(bNode *node, bNodeSocket *oldsock, int oldindex)
+void node_cmp_rlayers_register_pass(bNodeTree *ntree, bNode *node, Scene *scene, SceneRenderLayer *srl, const char *name, int type)
{
- bNodeSocket *sock;
-
- /* first try to find matching socket name */
- for (sock = node->outputs.first; sock; sock = sock->next)
- if (STREQ(sock->name, oldsock->name))
- return sock;
-
- /* no matching name, simply link to same index */
- return BLI_findlink(&node->outputs, oldindex);
+ RLayerUpdateData *data = node->storage;
+
+ if (scene == NULL || srl == NULL || data == NULL || node->id != (ID *)scene) {
+ return;
+ }
+
+ SceneRenderLayer *node_srl = BLI_findlink(&scene->r.layers, node->custom1);
+ if (node_srl != srl) {
+ return;
+ }
+
+ /* Special handling for the Combined pass to ensure compatibility. */
+ if (STREQ(name, RE_PASSNAME_COMBINED)) {
+ cmp_node_image_add_pass_output(ntree, node, "Image", name, -1, type, true, data->available_sockets, &data->prev_index);
+ cmp_node_image_add_pass_output(ntree, node, "Alpha", name, -1, SOCK_FLOAT, true, data->available_sockets, &data->prev_index);
+ }
+ else {
+ cmp_node_image_add_pass_output(ntree, node, name, name, -1, type, true, data->available_sockets, &data->prev_index);
+ }
}
-static void cmp_node_image_sync_output(bNode *UNUSED(node), bNodeSocket *UNUSED(newsock), bNodeSocket *UNUSED(oldsock))
+static void cmp_node_rlayer_create_outputs(bNodeTree *ntree, bNode *node, LinkNodePair *available_sockets)
{
- /* pass */
+ Scene *scene = (Scene *)node->id;
+
+ if (scene) {
+ RenderEngineType *engine_type = RE_engines_find(scene->r.engine);
+ if (engine_type && engine_type->update_render_passes) {
+ SceneRenderLayer *srl = BLI_findlink(&scene->r.layers, node->custom1);
+ if (srl) {
+ RLayerUpdateData *data = MEM_mallocN(sizeof(RLayerUpdateData), "render layer update data");
+ data->available_sockets = available_sockets;
+ data->prev_index = -1;
+ node->storage = data;
+
+ RenderEngine *engine = RE_engine_create(engine_type);
+ engine_type->update_render_passes(engine, scene, srl);
+ RE_engine_free(engine);
+
+ MEM_freeN(data);
+ node->storage = NULL;
+
+ return;
+ }
+ }
+ }
+
+ int prev_index = -1;
+ cmp_node_image_add_pass_output(ntree, node, "Image", RE_PASSNAME_COMBINED, RRES_OUT_IMAGE, SOCK_RGBA, true, available_sockets, &prev_index);
+ cmp_node_image_add_pass_output(ntree, node, "Alpha", RE_PASSNAME_COMBINED, RRES_OUT_ALPHA, SOCK_FLOAT, true, available_sockets, &prev_index);
}
/* XXX make this into a generic socket verification function for dynamic socket replacement (multilayer, groups, static templates) */
-static void cmp_node_image_verify_outputs(bNodeTree *ntree, bNode *node)
+static void cmp_node_image_verify_outputs(bNodeTree *ntree, bNode *node, bool rlayer)
{
- bNodeSocket *newsock, *oldsock, *oldsock_next;
- ListBase oldsocklist;
- int oldindex;
- bNodeLink *link;
-
- /* store current nodes in oldsocklist, then clear socket list */
- oldsocklist = node->outputs;
- BLI_listbase_clear(&node->outputs);
+ bNodeSocket *sock, *sock_next;
+ LinkNodePair available_sockets = {NULL, NULL};
+ int sock_index;
/* XXX make callback */
- cmp_node_image_create_outputs(ntree, node);
-
- for (newsock = node->outputs.first; newsock; newsock = newsock->next) {
- /* XXX make callback */
- oldsock = cmp_node_image_output_find_match(node, newsock, &oldsocklist);
- if (oldsock) {
- /* XXX make callback */
- cmp_node_image_sync_output(node, newsock, oldsock);
+ if (rlayer)
+ cmp_node_rlayer_create_outputs(ntree, node, &available_sockets);
+ else
+ cmp_node_image_create_outputs(ntree, node, &available_sockets);
+
+ /* Get rid of sockets whose passes are not available in the image.
+ * If sockets that are not available would be deleted, the connections to them would be lost
+ * when e.g. opening a file (since there's no render at all yet).
+ * Therefore, sockets with connected links will just be set as unavailable.
+ *
+ * Another important detail comes from compatibility with the older socket model, where there
+ * was a fixed socket per pass type that was just hidden or not. Therefore, older versions expect
+ * the first 31 passes to belong to a specific pass type.
+ * So, we keep those 31 always allocated before the others as well, even if they have no links attached. */
+ sock_index = 0;
+ for (sock = node->outputs.first; sock; sock = sock_next, sock_index++) {
+ sock_next = sock->next;
+ if (BLI_linklist_index(available_sockets.list, sock) >= 0) {
+ sock->flag &= ~(SOCK_UNAVAIL | SOCK_HIDDEN);
}
- }
-
- /* move links to new socket */
- for (oldsock = oldsocklist.first, oldindex = 0; oldsock; oldsock = oldsock->next, ++oldindex) {
- newsock = cmp_node_image_output_relink(node, oldsock, oldindex);
-
- if (newsock) {
+ else {
+ bNodeLink *link;
for (link = ntree->links.first; link; link = link->next) {
- if (link->fromsock == oldsock)
- link->fromsock = newsock;
+ if (link->fromsock == sock) break;
+ }
+ if (!link && (!rlayer || sock_index > 30)) {
+ MEM_freeN(sock->storage);
+ nodeRemoveSocket(ntree, node, sock);
+ }
+ else {
+ sock->flag |= SOCK_UNAVAIL;
}
}
}
-
- /* delete old sockets
- * XXX oldsock is not actually in the node->outputs list any more,
- * but the nodeRemoveSocket function works anyway. In future this
- * should become part of the core code, so can take care of this behavior.
- */
- for (oldsock = oldsocklist.first; oldsock; oldsock = oldsock_next) {
- oldsock_next = oldsock->next;
- MEM_freeN(oldsock->storage);
- nodeRemoveSocket(ntree, node, oldsock);
- }
+
+ BLI_linklist_free(available_sockets.list, NULL);
}
static void cmp_node_image_update(bNodeTree *ntree, bNode *node)
{
/* avoid unnecessary updates, only changes to the image/image user data are of interest */
if (node->update & NODE_UPDATE_ID)
- cmp_node_image_verify_outputs(ntree, node);
+ cmp_node_image_verify_outputs(ntree, node, false);
}
static void node_composit_init_image(bNodeTree *ntree, bNode *node)
@@ -348,7 +307,7 @@ static void node_composit_init_image(bNodeTree *ntree, bNode *node)
iuser->ok = 1;
/* setup initial outputs */
- cmp_node_image_verify_outputs(ntree, node);
+ cmp_node_image_verify_outputs(ntree, node, false);
}
static void node_composit_free_image(bNode *node)
@@ -381,6 +340,7 @@ void register_node_type_cmp_image(void)
node_type_init(&ntype, node_composit_init_image);
node_type_storage(&ntype, "ImageUser", node_composit_free_image, node_composit_copy_image);
node_type_update(&ntype, cmp_node_image_update, NULL);
+ node_type_label(&ntype, node_image_label);
nodeRegisterType(&ntype);
}
@@ -388,87 +348,44 @@ void register_node_type_cmp_image(void)
/* **************** RENDER RESULT ******************** */
-static void set_output_visible(bNode *node, int passflag, int index, int pass)
+void node_cmp_rlayers_outputs(bNodeTree *ntree, bNode *node)
{
- bNodeSocket *sock = BLI_findlink(&node->outputs, index);
- bool pass_enabled = ((passflag & pass) != 0);
-#ifdef WITH_CYCLES_DEBUG
- pass_enabled |= (pass == SCE_PASS_DEBUG);
-#endif
- /* clear the SOCK_HIDDEN flag as well, in case a socket was hidden before */
- if (pass_enabled)
- sock->flag &= ~(SOCK_HIDDEN | SOCK_UNAVAIL);
- else
- sock->flag |= SOCK_UNAVAIL;
+ cmp_node_image_verify_outputs(ntree, node, true);
}
-/* clumsy checking... should do dynamic outputs once */
-void node_cmp_rlayers_force_hidden_passes(bNode *node)
+const char *node_cmp_rlayers_sock_to_pass(int sock_index)
{
- Scene *scene = (Scene *)node->id;
- SceneRenderLayer *srl;
- int passflag;
- bNodeSocket *sock;
-
- /* must always have valid scene pointer */
- if (!scene)
- return;
-
- srl = BLI_findlink(&scene->r.layers, node->custom1);
- if (!srl)
- return;
-
- passflag = srl->passflag;
-
- for (sock = node->outputs.first; sock; sock = sock->next)
- sock->flag &= ~SOCK_UNAVAIL;
-
- set_output_visible(node, passflag, RRES_OUT_IMAGE, SCE_PASS_COMBINED);
- set_output_visible(node, passflag, RRES_OUT_ALPHA, SCE_PASS_COMBINED);
-
- set_output_visible(node, passflag, RRES_OUT_Z, SCE_PASS_Z);
- set_output_visible(node, passflag, RRES_OUT_NORMAL, SCE_PASS_NORMAL);
- set_output_visible(node, passflag, RRES_OUT_VEC, SCE_PASS_VECTOR);
- set_output_visible(node, passflag, RRES_OUT_UV, SCE_PASS_UV);
- set_output_visible(node, passflag, RRES_OUT_RGBA, SCE_PASS_RGBA);
- set_output_visible(node, passflag, RRES_OUT_DIFF, SCE_PASS_DIFFUSE);
- set_output_visible(node, passflag, RRES_OUT_SPEC, SCE_PASS_SPEC);
- set_output_visible(node, passflag, RRES_OUT_SHADOW, SCE_PASS_SHADOW);
- set_output_visible(node, passflag, RRES_OUT_AO, SCE_PASS_AO);
- set_output_visible(node, passflag, RRES_OUT_REFLECT, SCE_PASS_REFLECT);
- set_output_visible(node, passflag, RRES_OUT_REFRACT, SCE_PASS_REFRACT);
- set_output_visible(node, passflag, RRES_OUT_INDIRECT, SCE_PASS_INDIRECT);
- set_output_visible(node, passflag, RRES_OUT_INDEXOB, SCE_PASS_INDEXOB);
- set_output_visible(node, passflag, RRES_OUT_INDEXMA, SCE_PASS_INDEXMA);
- set_output_visible(node, passflag, RRES_OUT_MIST, SCE_PASS_MIST);
- set_output_visible(node, passflag, RRES_OUT_EMIT, SCE_PASS_EMIT);
- set_output_visible(node, passflag, RRES_OUT_ENV, SCE_PASS_ENVIRONMENT);
- set_output_visible(node, passflag, RRES_OUT_DIFF_DIRECT, SCE_PASS_DIFFUSE_DIRECT);
- set_output_visible(node, passflag, RRES_OUT_DIFF_INDIRECT, SCE_PASS_DIFFUSE_INDIRECT);
- set_output_visible(node, passflag, RRES_OUT_DIFF_COLOR, SCE_PASS_DIFFUSE_COLOR);
- set_output_visible(node, passflag, RRES_OUT_GLOSSY_DIRECT, SCE_PASS_GLOSSY_DIRECT);
- set_output_visible(node, passflag, RRES_OUT_GLOSSY_INDIRECT, SCE_PASS_GLOSSY_INDIRECT);
- set_output_visible(node, passflag, RRES_OUT_GLOSSY_COLOR, SCE_PASS_GLOSSY_COLOR);
- set_output_visible(node, passflag, RRES_OUT_TRANSM_DIRECT, SCE_PASS_TRANSM_DIRECT);
- set_output_visible(node, passflag, RRES_OUT_TRANSM_INDIRECT, SCE_PASS_TRANSM_INDIRECT);
- set_output_visible(node, passflag, RRES_OUT_TRANSM_COLOR, SCE_PASS_TRANSM_COLOR);
- set_output_visible(node, passflag, RRES_OUT_SUBSURFACE_DIRECT, SCE_PASS_SUBSURFACE_DIRECT);
- set_output_visible(node, passflag, RRES_OUT_SUBSURFACE_INDIRECT, SCE_PASS_SUBSURFACE_INDIRECT);
- set_output_visible(node, passflag, RRES_OUT_SUBSURFACE_COLOR, SCE_PASS_SUBSURFACE_COLOR);
-
-#ifdef WITH_CYCLES_DEBUG
- set_output_visible(node, passflag, RRES_OUT_DEBUG, SCE_PASS_DEBUG);
-#endif
+ const char *sock_to_passname[] = {
+ RE_PASSNAME_COMBINED, RE_PASSNAME_COMBINED,
+ RE_PASSNAME_Z, RE_PASSNAME_NORMAL, RE_PASSNAME_UV, RE_PASSNAME_VECTOR, RE_PASSNAME_RGBA,
+ RE_PASSNAME_DIFFUSE, RE_PASSNAME_SPEC, RE_PASSNAME_SHADOW, RE_PASSNAME_AO,
+ RE_PASSNAME_REFLECT, RE_PASSNAME_REFRACT, RE_PASSNAME_INDIRECT,
+ RE_PASSNAME_INDEXOB, RE_PASSNAME_INDEXMA, RE_PASSNAME_MIST, RE_PASSNAME_EMIT, RE_PASSNAME_ENVIRONMENT,
+ RE_PASSNAME_DIFFUSE_DIRECT, RE_PASSNAME_DIFFUSE_INDIRECT, RE_PASSNAME_DIFFUSE_COLOR,
+ RE_PASSNAME_GLOSSY_DIRECT, RE_PASSNAME_GLOSSY_INDIRECT, RE_PASSNAME_GLOSSY_COLOR,
+ RE_PASSNAME_TRANSM_DIRECT, RE_PASSNAME_TRANSM_INDIRECT, RE_PASSNAME_TRANSM_COLOR,
+ RE_PASSNAME_SUBSURFACE_DIRECT, RE_PASSNAME_SUBSURFACE_INDIRECT, RE_PASSNAME_SUBSURFACE_COLOR
+ };
+ if (sock_index > 30) {
+ return NULL;
+ }
+ return sock_to_passname[sock_index];
}
static void node_composit_init_rlayers(const bContext *C, PointerRNA *ptr)
{
Scene *scene = CTX_data_scene(C);
bNode *node = ptr->data;
-
+ int sock_index = 0;
+
node->id = &scene->id;
-
- node_cmp_rlayers_force_hidden_passes(node);
+
+ for (bNodeSocket *sock = node->outputs.first; sock; sock = sock->next, sock_index++) {
+ NodeImageLayer *sockdata = MEM_callocN(sizeof(NodeImageLayer), "node image layer");
+ sock->storage = sockdata;
+
+ BLI_strncpy(sockdata->pass_name, node_cmp_rlayers_sock_to_pass(sock_index), sizeof(sockdata->pass_name));
+ }
}
static int node_composit_poll_rlayers(bNodeType *UNUSED(ntype), bNodeTree *ntree)
@@ -489,6 +406,29 @@ static int node_composit_poll_rlayers(bNodeType *UNUSED(ntype), bNodeTree *ntree
return false;
}
+static void node_composit_free_rlayers(bNode *node)
+{
+ bNodeSocket *sock;
+
+ /* free extra socket info */
+ for (sock = node->outputs.first; sock; sock = sock->next)
+ MEM_freeN(sock->storage);
+}
+
+static void node_composit_copy_rlayers(bNodeTree *UNUSED(dest_ntree), bNode *UNUSED(dest_node), bNode *src_node)
+{
+ bNodeSocket *sock;
+
+ /* copy extra socket info */
+ for (sock = src_node->outputs.first; sock; sock = sock->next)
+ sock->new_sock->storage = MEM_dupallocN(sock->storage);
+}
+
+static void cmp_node_rlayers_update(bNodeTree *ntree, bNode *node)
+{
+ cmp_node_image_verify_outputs(ntree, node, true);
+}
+
void register_node_type_cmp_rlayers(void)
{
static bNodeType ntype;
@@ -497,6 +437,9 @@ void register_node_type_cmp_rlayers(void)
node_type_socket_templates(&ntype, NULL, cmp_node_rlayers_out);
ntype.initfunc_api = node_composit_init_rlayers;
ntype.poll = node_composit_poll_rlayers;
+ node_type_storage(&ntype, NULL, node_composit_free_rlayers, node_composit_copy_rlayers);
+ node_type_update(&ntype, cmp_node_rlayers_update, NULL);
+ node_type_init(&ntype, node_cmp_rlayers_outputs);
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/composite/nodes/node_composite_switchview.c b/source/blender/nodes/composite/nodes/node_composite_switchview.c
index d805cf4d87f..e0d9fa33f13 100644
--- a/source/blender/nodes/composite/nodes/node_composite_switchview.c
+++ b/source/blender/nodes/composite/nodes/node_composite_switchview.c
@@ -137,7 +137,6 @@ static void init_switch_view(const bContext *C, PointerRNA *ptr)
cmp_node_switch_view_sanitycheck(ntree, node);
}
-/* custom1 = mix type */
void register_node_type_cmp_switch_view(void)
{
static bNodeType ntype;
diff --git a/source/blender/nodes/composite/nodes/node_composite_valToRgb.c b/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
index 32d68550cd4..707f1d22efd 100644
--- a/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
+++ b/source/blender/nodes/composite/nodes/node_composite_valToRgb.c
@@ -46,7 +46,7 @@ static bNodeSocketTemplate cmp_node_valtorgb_out[] = {
static void node_composit_init_valtorgb(bNodeTree *UNUSED(ntree), bNode *node)
{
- node->storage = add_colorband(true);
+ node->storage = BKE_colorband_add(true);
}
void register_node_type_cmp_valtorgb(void)
diff --git a/source/blender/nodes/intern/node_exec.c b/source/blender/nodes/intern/node_exec.c
index 2347564c696..0cf131adbdc 100644
--- a/source/blender/nodes/intern/node_exec.c
+++ b/source/blender/nodes/intern/node_exec.c
@@ -78,7 +78,8 @@ void node_get_stack(bNode *node, bNodeStack *stack, bNodeStack **in, bNodeStack
static void node_init_input_index(bNodeSocket *sock, int *index)
{
- if (sock->link && sock->link->fromsock) {
+ /* Only consider existing link if from socket is valid! */
+ if (sock->link && sock->link->fromsock && sock->link->fromsock->stack_index >= 0) {
sock->stack_index = sock->link->fromsock->stack_index;
}
else {
diff --git a/source/blender/nodes/intern/node_socket.c b/source/blender/nodes/intern/node_socket.c
index 01c642b063d..342774facd0 100644
--- a/source/blender/nodes/intern/node_socket.c
+++ b/source/blender/nodes/intern/node_socket.c
@@ -112,22 +112,21 @@ static bNodeSocket *verify_socket_template(bNodeTree *ntree, bNode *node, int in
break;
}
if (sock) {
- sock->type = stemp->type;
+ if (sock->type != stemp->type) {
+ nodeModifySocketType(ntree, node, sock, stemp->type, stemp->subtype);
+ }
+
sock->limit = (stemp->limit == 0 ? 0xFFF : stemp->limit);
sock->flag |= stemp->flag;
-
- BLI_remlink(socklist, sock);
-
- return sock;
}
else {
/* no socket for this template found, make a new one */
sock = node_add_socket_from_template(ntree, node, stemp, in_out);
- /* remove the new socket from the node socket list first,
- * will be added back after verification.
- */
- BLI_remlink(socklist, sock);
}
+
+ /* remove the new socket from the node socket list first,
+ * will be added back after verification. */
+ BLI_remlink(socklist, sock);
return sock;
}
@@ -183,13 +182,14 @@ void node_verify_socket_templates(bNodeTree *ntree, bNode *node)
{
bNodeType *ntype = node->typeinfo;
/* Don't try to match socket lists when there are no templates.
- * This prevents group node sockets from being removed, without the need to explicitly
- * check the node type here.
+ * This prevents dynamically generated sockets to be removed, like for
+ * group, image or render layer nodes. We have an explicit check for the
+ * render layer node since it still has fixed sockets too.
*/
if (ntype) {
if (ntype->inputs && ntype->inputs[0].type >= 0)
verify_socket_template_list(ntree, node, SOCK_IN, &node->inputs, ntype->inputs);
- if (ntype->outputs && ntype->outputs[0].type >= 0)
+ if (ntype->outputs && ntype->outputs[0].type >= 0 && node->type != CMP_NODE_R_LAYERS)
verify_socket_template_list(ntree, node, SOCK_OUT, &node->outputs, ntype->outputs);
}
}
diff --git a/source/blender/nodes/intern/node_util.c b/source/blender/nodes/intern/node_util.c
index dd5715891d5..9f04c12fb5e 100644
--- a/source/blender/nodes/intern/node_util.c
+++ b/source/blender/nodes/intern/node_util.c
@@ -91,6 +91,12 @@ void node_blend_label(bNodeTree *UNUSED(ntree), bNode *node, char *label, int ma
BLI_strncpy(label, IFACE_(name), maxlen);
}
+void node_image_label(bNodeTree *UNUSED(ntree), bNode *node, char *label, int maxlen)
+{
+ /* if there is no loaded image, return an empty string, and let nodeLabel() fill in the proper type translation. */
+ BLI_strncpy(label, (node->id) ? node->id->name + 2 : "", maxlen);
+}
+
void node_math_label(bNodeTree *UNUSED(ntree), bNode *node, char *label, int maxlen)
{
const char *name;
@@ -118,6 +124,11 @@ void node_filter_label(bNodeTree *UNUSED(ntree), bNode *node, char *label, int m
/* test if two sockets are interchangeable */
static bool node_link_socket_match(bNodeSocket *a, bNodeSocket *b)
{
+ /* check if sockets are of the same type */
+ if (a->typeinfo != b->typeinfo) {
+ return false;
+ }
+
/* tests if alphabetic prefix matches
* this allows for imperfect matches, such as numeric suffixes,
* like Color1/Color2
diff --git a/source/blender/nodes/intern/node_util.h b/source/blender/nodes/intern/node_util.h
index 2e20a8e79d4..b4437dfcb78 100644
--- a/source/blender/nodes/intern/node_util.h
+++ b/source/blender/nodes/intern/node_util.h
@@ -72,6 +72,7 @@ extern void *node_initexec_curves(struct bNodeExecContext *context, struct bNode
/**** Labels ****/
void node_blend_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen);
+void node_image_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen);
void node_math_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen);
void node_vect_math_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen);
void node_filter_label(struct bNodeTree *ntree, struct bNode *node, char *label, int maxlen);
diff --git a/source/blender/nodes/shader/node_shader_tree.c b/source/blender/nodes/shader/node_shader_tree.c
index 40d1cfdfcb0..ce47ecd9a23 100644
--- a/source/blender/nodes/shader/node_shader_tree.c
+++ b/source/blender/nodes/shader/node_shader_tree.c
@@ -337,7 +337,9 @@ static void ntree_shader_link_builtin_group_normal(
* some internal re-linking in order to avoid cycles.
*/
bNode *group_output_node = ntreeFindType(group_ntree, NODE_GROUP_OUTPUT);
- BLI_assert(group_output_node != NULL);
+ if (group_output_node == NULL) {
+ return;
+ }
bNodeSocket *group_output_node_displacement_socket =
nodeFindSocket(group_output_node,
SOCK_IN,
@@ -447,6 +449,21 @@ static void ntree_shader_relink_displacement(bNodeTree *ntree,
* cycles in the Cycles material :)
*/
nodeRemLink(ntree, displacement_link);
+
+ /* Convert displacement vector to bump height. */
+ bNode *dot_node = nodeAddStaticNode(NULL, ntree, SH_NODE_VECT_MATH);
+ bNode *geo_node = nodeAddStaticNode(NULL, ntree, SH_NODE_NEW_GEOMETRY);
+ dot_node->custom1 = 3; /* dot product */
+
+ nodeAddLink(ntree,
+ displacement_node, displacement_socket,
+ dot_node, dot_node->inputs.first);
+ nodeAddLink(ntree,
+ geo_node, ntree_shader_node_find_output(geo_node, "Normal"),
+ dot_node, dot_node->inputs.last);
+ displacement_node = dot_node;
+ displacement_socket = ntree_shader_node_find_output(dot_node, "Value");
+
/* We can't connect displacement to normal directly, use bump node for that
* and hope that it gives good enough approximation.
*/
@@ -599,10 +616,10 @@ bool ntreeShaderExecTree(bNodeTree *ntree, ShadeInput *shi, ShadeResult *shr)
/* ensure execdata is only initialized once */
if (!exec) {
- BLI_lock_thread(LOCK_NODES);
+ BLI_thread_lock(LOCK_NODES);
if (!ntree->execdata)
ntree->execdata = ntreeShaderBeginExecTree(ntree);
- BLI_unlock_thread(LOCK_NODES);
+ BLI_thread_unlock(LOCK_NODES);
exec = ntree->execdata;
}
diff --git a/source/blender/nodes/shader/node_shader_util.c b/source/blender/nodes/shader/node_shader_util.c
index 9bd43f331fb..5bc97f13b41 100644
--- a/source/blender/nodes/shader/node_shader_util.c
+++ b/source/blender/nodes/shader/node_shader_util.c
@@ -142,28 +142,40 @@ void node_gpu_stack_from_data(struct GPUNodeStack *gs, int type, bNodeStack *ns)
{
memset(gs, 0, sizeof(*gs));
- nodestack_get_vec(gs->vec, type, ns);
- gs->link = ns->data;
-
- if (type == SOCK_FLOAT)
- gs->type = GPU_FLOAT;
- else if (type == SOCK_VECTOR)
- gs->type = GPU_VEC3;
- else if (type == SOCK_RGBA)
- gs->type = GPU_VEC4;
- else if (type == SOCK_SHADER)
- gs->type = GPU_VEC4;
- else
+ if (ns == NULL) {
+ /* node_get_stack() will generate NULL bNodeStack pointers for unknown/unsuported types of sockets... */
+ zero_v4(gs->vec);
+ gs->link = NULL;
gs->type = GPU_NONE;
+ gs->name = "";
+ gs->hasinput = false;
+ gs->hasoutput = false;
+ gs->sockettype = type;
+ }
+ else {
+ nodestack_get_vec(gs->vec, type, ns);
+ gs->link = ns->data;
- gs->name = "";
- gs->hasinput = ns->hasinput && ns->data;
- /* XXX Commented out the ns->data check here, as it seems it's not always set,
- * even though there *is* a valid connection/output... But that might need
- * further investigation.
- */
- gs->hasoutput = ns->hasoutput /*&& ns->data*/;
- gs->sockettype = ns->sockettype;
+ if (type == SOCK_FLOAT)
+ gs->type = GPU_FLOAT;
+ else if (type == SOCK_VECTOR)
+ gs->type = GPU_VEC3;
+ else if (type == SOCK_RGBA)
+ gs->type = GPU_VEC4;
+ else if (type == SOCK_SHADER)
+ gs->type = GPU_VEC4;
+ else
+ gs->type = GPU_NONE;
+
+ gs->name = "";
+ gs->hasinput = ns->hasinput && ns->data;
+ /* XXX Commented out the ns->data check here, as it seems it's not always set,
+ * even though there *is* a valid connection/output... But that might need
+ * further investigation.
+ */
+ gs->hasoutput = ns->hasoutput /*&& ns->data*/;
+ gs->sockettype = ns->sockettype;
+ }
}
void node_data_from_gpu_stack(bNodeStack *ns, GPUNodeStack *gs)
diff --git a/source/blender/nodes/shader/node_shader_util.h b/source/blender/nodes/shader/node_shader_util.h
index 4cb39e0f13b..a902ede8aa7 100644
--- a/source/blender/nodes/shader/node_shader_util.h
+++ b/source/blender/nodes/shader/node_shader_util.h
@@ -55,6 +55,7 @@
#include "BLI_threads.h"
#include "BLI_utildefines.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_global.h"
#include "BKE_image.h"
diff --git a/source/blender/nodes/shader/nodes/node_shader_bevel.c b/source/blender/nodes/shader/nodes/node_shader_bevel.c
new file mode 100644
index 00000000000..e2e4da21ef3
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_bevel.c
@@ -0,0 +1,70 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../node_shader_util.h"
+
+/* **************** OUTPUT ******************** */
+
+static bNodeSocketTemplate sh_node_bevel_in[] = {
+ { SOCK_FLOAT, 0, N_("Radius"), 0.05f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_bevel_out[] = {
+ { SOCK_VECTOR, 0, N_("Normal"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static void node_shader_init_bevel(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ node->custom1 = 4; /* samples */
+}
+
+static int gpu_shader_bevel(GPUMaterial *mat, bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
+{
+ if (!in[1].link) {
+ GPU_link(mat, "direction_transform_m4v3", GPU_builtin(GPU_VIEW_NORMAL), GPU_builtin(GPU_INVERSE_VIEW_MATRIX), &in[1].link);
+ }
+
+ return GPU_stack_link(mat, "node_bevel", in, out);
+}
+
+/* node type definition */
+void register_node_type_sh_bevel(void)
+{
+ static bNodeType ntype;
+
+ sh_node_type_base(&ntype, SH_NODE_BEVEL, "Bevel", NODE_CLASS_INPUT, 0);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_bevel_in, sh_node_bevel_out);
+ node_type_init(&ntype, node_shader_init_bevel);
+ node_type_storage(&ntype, "", NULL, NULL);
+ node_type_gpu(&ntype, gpu_shader_bevel);
+
+ nodeRegisterType(&ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
index 01ca0bd6512..6410441797a 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_anisotropic.c
@@ -31,7 +31,7 @@
static bNodeSocketTemplate sh_node_bsdf_anisotropic_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 1, N_("Roughness"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Roughness"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Anisotropy"), 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Rotation"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
index 7e1bc971c73..c13fd89d6e5 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_glossy.c
@@ -31,7 +31,7 @@
static bNodeSocketTemplate sh_node_bsdf_glossy_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
- { SOCK_FLOAT, 1, N_("Roughness"), 0.2f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Roughness"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_bsdf_principled.c b/source/blender/nodes/shader/nodes/node_shader_bsdf_principled.c
new file mode 100644
index 00000000000..e3b3f0fc9a6
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_bsdf_principled.c
@@ -0,0 +1,115 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../node_shader_util.h"
+
+/* **************** OUTPUT ******************** */
+
+static bNodeSocketTemplate sh_node_bsdf_principled_in[] = {
+ { SOCK_RGBA, 1, N_("Base Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Subsurface"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_VECTOR, 1, N_("Subsurface Radius"), 1.0f, 0.2f, 0.1f, 0.0f, 0.0f, 100.0f},
+ { SOCK_RGBA, 1, N_("Subsurface Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Metallic"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Specular"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Specular Tint"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Roughness"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Anisotropic"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Anisotropic Rotation"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Sheen"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Sheen Tint"), 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Clearcoat"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Clearcoat Roughness"), 0.03f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("IOR"), 1.45f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_FLOAT, 1, N_("Transmission"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_FLOAT, 1, N_("Transmission Roughness"),0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { SOCK_VECTOR, 1, N_("Clearcoat Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { SOCK_VECTOR, 1, N_("Tangent"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_bsdf_principled_out[] = {
+ { SOCK_SHADER, 0, N_("BSDF")},
+ { -1, 0, "" }
+};
+
+static void node_shader_init_principled(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ node->custom1 = SHD_GLOSSY_GGX;
+ node->custom2 = SHD_SUBSURFACE_BURLEY;
+}
+
+static int node_shader_gpu_bsdf_principled(GPUMaterial *mat, bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
+{
+ // normal
+ if (!in[17].link)
+ in[17].link = GPU_builtin(GPU_VIEW_NORMAL);
+ else
+ GPU_link(mat, "direction_transform_m4v3", in[17].link, GPU_builtin(GPU_VIEW_MATRIX), &in[17].link);
+
+ // clearcoat normal
+ if (!in[18].link)
+ in[18].link = GPU_builtin(GPU_VIEW_NORMAL);
+ else
+ GPU_link(mat, "direction_transform_m4v3", in[18].link, GPU_builtin(GPU_VIEW_MATRIX), &in[18].link);
+
+ return GPU_stack_link(mat, "node_bsdf_principled", in, out, GPU_builtin(GPU_VIEW_POSITION));
+}
+
+static void node_shader_update_principled(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ bNodeSocket *sock;
+ int distribution = node->custom1;
+
+ for (sock = node->inputs.first; sock; sock = sock->next) {
+ if (STREQ(sock->name, "Transmission Roughness")) {
+ if (distribution == SHD_GLOSSY_GGX)
+ sock->flag &= ~SOCK_UNAVAIL;
+ else
+ sock->flag |= SOCK_UNAVAIL;
+
+ }
+ }
+}
+
+/* node type definition */
+void register_node_type_sh_bsdf_principled(void)
+{
+ static bNodeType ntype;
+
+ sh_node_type_base(&ntype, SH_NODE_BSDF_PRINCIPLED, "Principled BSDF", NODE_CLASS_SHADER, 0);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_bsdf_principled_in, sh_node_bsdf_principled_out);
+ node_type_size_preset(&ntype, NODE_SIZE_LARGE);
+ node_type_init(&ntype, node_shader_init_principled);
+ node_type_storage(&ntype, "", NULL, NULL);
+ node_type_gpu(&ntype, node_shader_gpu_bsdf_principled);
+ node_type_update(&ntype, node_shader_update_principled, NULL);
+
+ nodeRegisterType(&ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_bump.c b/source/blender/nodes/shader/nodes/node_shader_bump.c
index b39ca5d90ee..122f02eda8a 100644
--- a/source/blender/nodes/shader/nodes/node_shader_bump.c
+++ b/source/blender/nodes/shader/nodes/node_shader_bump.c
@@ -34,7 +34,7 @@
/* **************** BUMP ******************** */
static bNodeSocketTemplate sh_node_bump_in[] = {
{ SOCK_FLOAT, 1, N_("Strength"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
- { SOCK_FLOAT, 1, N_("Distance"), 0.1f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_FLOAT, 1, N_("Distance"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
{ SOCK_FLOAT, 1, N_("Height"), 1.0f, 1.0f, 1.0f, 1.0f, -1000.0f, 1000.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
diff --git a/source/blender/nodes/shader/nodes/node_shader_displacement.c b/source/blender/nodes/shader/nodes/node_shader_displacement.c
new file mode 100644
index 00000000000..e259a9e3f6d
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_displacement.c
@@ -0,0 +1,84 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../node_shader_util.h"
+
+/* **************** OUTPUT ******************** */
+
+static bNodeSocketTemplate sh_node_displacement_in[] = {
+ { SOCK_FLOAT, 0, N_("Height"), 0.00f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_FLOAT, 0, N_("Midlevel"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_FLOAT, 0, N_("Scale"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_displacement_out[] = {
+ { SOCK_VECTOR, 0, N_("Displacement"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static void node_shader_init_displacement(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ node->custom1 = SHD_SPACE_OBJECT; /* space */
+
+ /* Set default value here for backwards compatibility. */
+ for (bNodeSocket *sock = node->inputs.first; sock; sock = sock->next) {
+ if (STREQ(sock->name, "Midlevel")) {
+ ((bNodeSocketValueFloat *)sock->default_value)->value = 0.5f;
+ }
+ }
+}
+
+static int gpu_shader_displacement(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
+{
+ if (!in[3].link) {
+ GPU_link(mat, "direction_transform_m4v3", GPU_builtin(GPU_VIEW_NORMAL), GPU_builtin(GPU_INVERSE_VIEW_MATRIX), &in[3].link);
+ }
+
+ if (node->custom1 == SHD_SPACE_OBJECT) {
+ return GPU_stack_link(mat, "node_displacement_object", in, out, GPU_builtin(GPU_OBJECT_MATRIX));
+ }
+ else {
+ return GPU_stack_link(mat, "node_displacement_world", in, out, GPU_builtin(GPU_OBJECT_MATRIX));
+ }
+}
+
+/* node type definition */
+void register_node_type_sh_displacement(void)
+{
+ static bNodeType ntype;
+
+ sh_node_type_base(&ntype, SH_NODE_DISPLACEMENT, "Displacement", NODE_CLASS_OP_VECTOR, 0);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_displacement_in, sh_node_displacement_out);
+ node_type_storage(&ntype, "", NULL, NULL);
+ node_type_init(&ntype, node_shader_init_displacement);
+ node_type_gpu(&ntype, gpu_shader_displacement);
+
+ nodeRegisterType(&ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_fresnel.c b/source/blender/nodes/shader/nodes/node_shader_fresnel.c
index d5e11795fc0..8262b70fc44 100644
--- a/source/blender/nodes/shader/nodes/node_shader_fresnel.c
+++ b/source/blender/nodes/shader/nodes/node_shader_fresnel.c
@@ -51,23 +51,33 @@ static int node_shader_gpu_fresnel(GPUMaterial *mat, bNode *UNUSED(node), bNodeE
return GPU_stack_link(mat, "node_fresnel", in, out, GPU_builtin(GPU_VIEW_POSITION));
}
-static void node_shader_exec_fresnel(void *data, int UNUSED(thread), bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), bNodeStack **in, bNodeStack **out)
+static void node_shader_exec_fresnel(void *data, int UNUSED(thread), bNode *node, bNodeExecData *UNUSED(execdata), bNodeStack **in, bNodeStack **out)
{
ShadeInput *shi = ((ShaderCallData *)data)->shi;
- float eta = max_ff(in[0]->vec[0], 0.00001);
+
+ /* Compute IOR. */
+ float eta;
+ nodestack_get_vec(&eta, SOCK_FLOAT, in[0]);
+ eta = max_ff(eta, 0.00001);
+ eta = shi->flippednor ? 1 / eta : eta;
+
+ /* Get normal from socket, but only if linked. */
+ bNodeSocket *sock_normal = node->inputs.first;
+ sock_normal = sock_normal->next;
float n[3];
- if (in[1]->hasinput) {
- copy_v3_v3(n, in[1]->vec);
+ if (sock_normal->link) {
+ nodestack_get_vec(n, SOCK_VECTOR, in[1]);
}
else {
copy_v3_v3(n, shi->vn);
}
- if(shi->use_world_space_shading)
+ if (shi->use_world_space_shading) {
mul_mat3_m4_v3((float (*)[4])RE_render_current_get_matrix(RE_VIEW_MATRIX), n);
+ }
- out[0]->vec[0] = RE_fresnel_dielectric(shi->view, n, shi->flippednor ? 1/eta : eta);
+ out[0]->vec[0] = RE_fresnel_dielectric(shi->view, n, eta);
}
/* node type definition */
diff --git a/source/blender/nodes/shader/nodes/node_shader_hair_info.c b/source/blender/nodes/shader/nodes/node_shader_hair_info.c
index 63adba750cf..6a15c59aa5b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_hair_info.c
+++ b/source/blender/nodes/shader/nodes/node_shader_hair_info.c
@@ -33,6 +33,7 @@ static bNodeSocketTemplate outputs[] = {
{ SOCK_FLOAT, 0, N_("Thickness"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
{ SOCK_VECTOR, 0, N_("Tangent Normal"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
/*{ SOCK_FLOAT, 0, N_("Fade"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},*/
+ { SOCK_FLOAT, 0, N_("Random") },
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_layer_weight.c b/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
index 90e2625b961..998e1a5687e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
+++ b/source/blender/nodes/shader/nodes/node_shader_layer_weight.c
@@ -52,24 +52,33 @@ static int node_shader_gpu_layer_weight(GPUMaterial *mat, bNode *UNUSED(node), b
return GPU_stack_link(mat, "node_layer_weight", in, out, GPU_builtin(GPU_VIEW_POSITION));
}
-static void node_shader_exec_layer_weight(void *data, int UNUSED(thread), bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), bNodeStack **in, bNodeStack **out)
+static void node_shader_exec_layer_weight(void *data, int UNUSED(thread), bNode *node, bNodeExecData *UNUSED(execdata), bNodeStack **in, bNodeStack **out)
{
ShadeInput *shi = ((ShaderCallData *)data)->shi;
- float blend = in[0]->vec[0];
+
+ /* Compute IOR. */
+ float blend;
+ nodestack_get_vec(&blend, SOCK_FLOAT, in[0]);
float eta = max_ff(1 - blend, 0.00001);
+ eta = shi->flippednor ? eta : 1 / eta;
+
+ /* Get normal from socket, but only if linked. */
+ bNodeSocket *sock_normal = node->inputs.first;
+ sock_normal = sock_normal->next;
float n[3];
- if (in[1]->hasinput) {
- copy_v3_v3(n, in[1]->vec);
+ if (sock_normal->link) {
+ nodestack_get_vec(n, SOCK_VECTOR, in[1]);
}
else {
copy_v3_v3(n, shi->vn);
}
+
if (shi->use_world_space_shading)
mul_mat3_m4_v3((float (*)[4])RE_render_current_get_matrix(RE_VIEW_MATRIX), n);
- out[0]->vec[0] = RE_fresnel_dielectric(shi->view, n, shi->flippednor ? eta : 1/eta);
+ out[0]->vec[0] = RE_fresnel_dielectric(shi->view, n, eta);
float facing = fabs(dot_v3v3(shi->view, n));
if (blend != 0.5) {
diff --git a/source/blender/nodes/shader/nodes/node_shader_normal_map.c b/source/blender/nodes/shader/nodes/node_shader_normal_map.c
index 48d1688c386..7584b5eba4d 100644
--- a/source/blender/nodes/shader/nodes/node_shader_normal_map.c
+++ b/source/blender/nodes/shader/nodes/node_shader_normal_map.c
@@ -46,8 +46,10 @@ static void node_shader_init_normal_map(bNodeTree *UNUSED(ntree), bNode *node)
node->storage = attr;
}
-static void node_shader_exec_normal_map(void *data, int UNUSED(thread), bNode *node, bNodeExecData *UNUSED(execdata), bNodeStack **in, bNodeStack **out)
- {
+static void node_shader_exec_normal_map(
+ void *data, int UNUSED(thread), bNode *node, bNodeExecData *UNUSED(execdata),
+ bNodeStack **in, bNodeStack **out)
+{
if (data) {
ShadeInput *shi = ((ShaderCallData *)data)->shi;
@@ -63,10 +65,10 @@ static void node_shader_exec_normal_map(void *data, int UNUSED(thread), bNode *n
CLAMP_MIN(strength, 0.0f);
- float *N = shi->vno;
+ float *N = shi->nmapnorm;
int uv_index = 0;
switch (nm->space) {
- case SHD_NORMAL_MAP_TANGENT:
+ case SHD_SPACE_TANGENT:
if (nm->uv_map[0]) {
/* find uv map by name */
for (int i = 0; i < shi->totuv; i++) {
@@ -94,8 +96,8 @@ static void node_shader_exec_normal_map(void *data, int UNUSED(thread), bNode *n
}
break;
- case SHD_NORMAL_MAP_OBJECT:
- case SHD_NORMAL_MAP_BLENDER_OBJECT:
+ case SHD_SPACE_OBJECT:
+ case SHD_SPACE_BLENDER_OBJECT:
if (shi->use_world_space_shading) {
mul_mat3_m4_v3((float (*)[4])RE_object_instance_get_matrix(shi->obi, RE_OBJECT_INSTANCE_MATRIX_OB), vecIn);
mul_mat3_m4_v3((float (*)[4])RE_render_current_get_matrix(RE_VIEWINV_MATRIX), N);
@@ -105,8 +107,8 @@ static void node_shader_exec_normal_map(void *data, int UNUSED(thread), bNode *n
interp_v3_v3v3(out[0]->vec, N, vecIn, strength);
break;
- case SHD_NORMAL_MAP_WORLD:
- case SHD_NORMAL_MAP_BLENDER_WORLD:
+ case SHD_SPACE_WORLD:
+ case SHD_SPACE_BLENDER_WORLD:
if (shi->use_world_space_shading)
mul_mat3_m4_v3((float (*)[4])RE_render_current_get_matrix(RE_VIEWINV_MATRIX), N);
else
@@ -148,10 +150,10 @@ static int gpu_shader_normal_map(GPUMaterial *mat, bNode *node, bNodeExecData *U
/* ******* CYCLES or BLENDER INTERNAL with world space shading flag ******* */
const char *color_to_normal_fnc_name = "color_to_normal_new_shading";
- if (nm->space == SHD_NORMAL_MAP_BLENDER_OBJECT || nm->space == SHD_NORMAL_MAP_BLENDER_WORLD || !GPU_material_use_new_shading_nodes(mat))
+ if (nm->space == SHD_SPACE_BLENDER_OBJECT || nm->space == SHD_SPACE_BLENDER_WORLD || !GPU_material_use_new_shading_nodes(mat))
color_to_normal_fnc_name = "color_to_blender_normal_new_shading";
switch (nm->space) {
- case SHD_NORMAL_MAP_TANGENT:
+ case SHD_SPACE_TANGENT:
GPU_link(mat, "color_to_normal_new_shading", realnorm, &realnorm);
GPU_link(mat, "node_normal_map", GPU_attribute(CD_TANGENT, nm->uv_map), negnorm, realnorm, &realnorm);
GPU_link(mat, "vec_math_mix", strength, realnorm, GPU_builtin(GPU_VIEW_NORMAL), &out[0].link);
@@ -159,14 +161,14 @@ static int gpu_shader_normal_map(GPUMaterial *mat, bNode *node, bNodeExecData *U
GPU_link(mat, "direction_transform_m4v3", out[0].link, GPU_builtin(GPU_INVERSE_VIEW_MATRIX), &out[0].link);
GPU_link(mat, "vect_normalize", out[0].link, &out[0].link);
return true;
- case SHD_NORMAL_MAP_OBJECT:
- case SHD_NORMAL_MAP_BLENDER_OBJECT:
+ case SHD_SPACE_OBJECT:
+ case SHD_SPACE_BLENDER_OBJECT:
GPU_link(mat, "direction_transform_m4v3", negnorm, GPU_builtin(GPU_INVERSE_VIEW_MATRIX), &negnorm);
GPU_link(mat, color_to_normal_fnc_name, realnorm, &realnorm);
GPU_link(mat, "direction_transform_m4v3", realnorm, GPU_builtin(GPU_OBJECT_MATRIX), &realnorm);
break;
- case SHD_NORMAL_MAP_WORLD:
- case SHD_NORMAL_MAP_BLENDER_WORLD:
+ case SHD_SPACE_WORLD:
+ case SHD_SPACE_BLENDER_WORLD:
GPU_link(mat, "direction_transform_m4v3", negnorm, GPU_builtin(GPU_INVERSE_VIEW_MATRIX), &negnorm);
GPU_link(mat, color_to_normal_fnc_name, realnorm, &realnorm);
break;
@@ -182,15 +184,15 @@ static int gpu_shader_normal_map(GPUMaterial *mat, bNode *node, bNodeExecData *U
GPU_link(mat, "vec_math_negate", negnorm, &negnorm);
switch (nm->space) {
- case SHD_NORMAL_MAP_TANGENT:
+ case SHD_SPACE_TANGENT:
GPU_link(mat, "node_normal_map", GPU_attribute(CD_TANGENT, nm->uv_map), negnorm, realnorm, &realnorm);
break;
- case SHD_NORMAL_MAP_OBJECT:
- case SHD_NORMAL_MAP_BLENDER_OBJECT:
+ case SHD_SPACE_OBJECT:
+ case SHD_SPACE_BLENDER_OBJECT:
GPU_link(mat, "direction_transform_m4v3", realnorm, GPU_builtin(GPU_LOC_TO_VIEW_MATRIX), &realnorm);
break;
- case SHD_NORMAL_MAP_WORLD:
- case SHD_NORMAL_MAP_BLENDER_WORLD:
+ case SHD_SPACE_WORLD:
+ case SHD_SPACE_BLENDER_WORLD:
GPU_link(mat, "direction_transform_m4v3", realnorm, GPU_builtin(GPU_VIEW_MATRIX), &realnorm);
break;
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_object_info.c b/source/blender/nodes/shader/nodes/node_shader_object_info.c
index d1905246fd4..63d3bac88a0 100644
--- a/source/blender/nodes/shader/nodes/node_shader_object_info.c
+++ b/source/blender/nodes/shader/nodes/node_shader_object_info.c
@@ -39,7 +39,16 @@ static bNodeSocketTemplate sh_node_object_info_out[] = {
static int node_shader_gpu_object_info(GPUMaterial *mat, bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
{
- return GPU_stack_link(mat, "node_object_info", in, out);
+ return GPU_stack_link(mat, "node_object_info", in, out, GPU_builtin(GPU_OBJECT_MATRIX), GPU_builtin(GPU_OBJECT_INFO));
+}
+
+static void node_shader_exec_object_info(void *data, int UNUSED(thread), bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), bNodeStack **UNUSED(in), bNodeStack **out)
+{
+ ShaderCallData *scd = (ShaderCallData *)data;
+ copy_v4_v4(out[0]->vec, RE_object_instance_get_matrix(scd->shi->obi, RE_OBJECT_INSTANCE_MATRIX_OB)[3]);
+ out[1]->vec[0] = RE_object_instance_get_object_pass_index(scd->shi->obi);
+ out[2]->vec[0] = scd->shi->mat->index;
+ out[3]->vec[0] = RE_object_instance_get_random_id(scd->shi->obi) * (1.0f / (float)0xFFFFFFFF);
}
/* node type definition */
@@ -53,6 +62,7 @@ void register_node_type_sh_object_info(void)
node_type_init(&ntype, NULL);
node_type_storage(&ntype, "", NULL, NULL);
node_type_gpu(&ntype, node_shader_gpu_object_info);
+ node_type_exec(&ntype, NULL, NULL, node_shader_exec_object_info);
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_output_material.c b/source/blender/nodes/shader/nodes/node_shader_output_material.c
index 336536b21ee..aeb8b546eed 100644
--- a/source/blender/nodes/shader/nodes/node_shader_output_material.c
+++ b/source/blender/nodes/shader/nodes/node_shader_output_material.c
@@ -32,7 +32,7 @@
static bNodeSocketTemplate sh_node_output_material_in[] = {
{ SOCK_SHADER, 1, N_("Surface")},
{ SOCK_SHADER, 1, N_("Volume")},
- { SOCK_FLOAT, 1, N_("Displacement"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { SOCK_VECTOR, 1, N_("Displacement"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/shader/nodes/node_shader_particle_info.c b/source/blender/nodes/shader/nodes/node_shader_particle_info.c
index 5f0d81e98c9..3dbe5c81c57 100644
--- a/source/blender/nodes/shader/nodes/node_shader_particle_info.c
+++ b/source/blender/nodes/shader/nodes/node_shader_particle_info.c
@@ -30,6 +30,7 @@
static bNodeSocketTemplate outputs[] = {
{ SOCK_FLOAT, 0, "Index" },
+ { SOCK_FLOAT, 0, "Random" },
{ SOCK_FLOAT, 0, "Age" },
{ SOCK_FLOAT, 0, "Lifetime" },
{ SOCK_VECTOR, 0, "Location" },
@@ -45,7 +46,7 @@ static void node_shader_exec_particle_info(void *data, int UNUSED(thread), bNode
{
ShadeInput *shi = ((ShaderCallData *)data)->shi;
- RE_instance_get_particle_info(shi->obi, out[0]->vec, out[1]->vec, out[2]->vec, out[3]->vec, out[4]->vec, out[5]->vec, out[6]->vec);
+ RE_instance_get_particle_info(shi->obi, out[0]->vec, out[1]->vec, out[2]->vec, out[3]->vec, out[4]->vec, out[5]->vec, out[6]->vec, out[7]->vec);
}
static int gpu_shader_particle_info(GPUMaterial *mat, bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
diff --git a/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c b/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c
index 7dfac32e85b..5051e37310e 100644
--- a/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c
+++ b/source/blender/nodes/shader/nodes/node_shader_subsurface_scattering.c
@@ -32,7 +32,7 @@
static bNodeSocketTemplate sh_node_subsurface_scattering_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Scale"), 1.0, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
- { SOCK_VECTOR, 1, N_("Radius"), 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f},
+ { SOCK_VECTOR, 1, N_("Radius"), 1.0f, 0.2f, 0.1f, 0.0f, 0.0f, 100.0f},
{ SOCK_FLOAT, 1, N_("Sharpness"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_FLOAT, 1, N_("Texture Blur"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
{ SOCK_VECTOR, 1, N_("Normal"), 0.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, PROP_NONE, SOCK_HIDE_VALUE},
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_brick.c b/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
index 0be47c4f751..1dfebc45d60 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_brick.c
@@ -64,7 +64,7 @@ static void node_shader_init_tex_brick(bNodeTree *UNUSED(ntree), bNode *node)
for (bNodeSocket *sock = node->inputs.first; sock; sock = sock->next) {
if (STREQ(sock->name, "Mortar Smooth")) {
- ((bNodeSocketValueFloat*)sock->default_value)->value = 0.1f;
+ ((bNodeSocketValueFloat *)sock->default_value)->value = 0.1f;
}
}
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_environment.c b/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
index 2f8f95b0675..508abbf4db1 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_environment.c
@@ -102,6 +102,7 @@ void register_node_type_sh_tex_environment(void)
node_type_init(&ntype, node_shader_init_tex_environment);
node_type_storage(&ntype, "NodeTexEnvironment", node_free_standard_storage, node_copy_standard_storage);
node_type_gpu(&ntype, node_shader_gpu_tex_environment);
+ node_type_label(&ntype, node_image_label);
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_image.c b/source/blender/nodes/shader/nodes/node_shader_tex_image.c
index 71200dfe9d3..5f5cec61513 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_image.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_image.c
@@ -126,6 +126,7 @@ void register_node_type_sh_tex_image(void)
node_type_init(&ntype, node_shader_init_tex_image);
node_type_storage(&ntype, "NodeTexImage", node_free_standard_storage, node_copy_standard_storage);
node_type_gpu(&ntype, node_shader_gpu_tex_image);
+ node_type_label(&ntype, node_image_label);
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_tex_pointdensity.c b/source/blender/nodes/shader/nodes/node_shader_tex_pointdensity.c
index 006bd0cc8bb..436eeeefb4a 100644
--- a/source/blender/nodes/shader/nodes/node_shader_tex_pointdensity.c
+++ b/source/blender/nodes/shader/nodes/node_shader_tex_pointdensity.c
@@ -27,7 +27,6 @@
#include "../node_shader_util.h"
-#include "BKE_texture.h"
#include "RE_render_ext.h"
@@ -66,7 +65,7 @@ static void node_shader_free_tex_pointdensity(bNode *node)
MEM_freeN(point_density);
}
-static void node_shader_copy_tex_pointdensity(bNodeTree * UNUSED(dest_ntree),
+static void node_shader_copy_tex_pointdensity(bNodeTree *UNUSED(dest_ntree),
bNode *dest_node,
bNode *src_node)
{
diff --git a/source/blender/nodes/shader/nodes/node_shader_valToRgb.c b/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
index 72942cce9c5..c960e006a9b 100644
--- a/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
+++ b/source/blender/nodes/shader/nodes/node_shader_valToRgb.c
@@ -53,14 +53,14 @@ static void node_shader_exec_valtorgb(void *UNUSED(data), int UNUSED(thread), bN
float fac;
nodestack_get_vec(&fac, SOCK_FLOAT, in[0]);
- do_colorband(node->storage, fac, out[0]->vec);
+ BKE_colorband_evaluate(node->storage, fac, out[0]->vec);
out[1]->vec[0] = out[0]->vec[3];
}
}
static void node_shader_init_valtorgb(bNodeTree *UNUSED(ntree), bNode *node)
{
- node->storage = add_colorband(true);
+ node->storage = BKE_colorband_add(true);
}
static int gpu_shader_valtorgb(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
@@ -68,7 +68,7 @@ static int gpu_shader_valtorgb(GPUMaterial *mat, bNode *node, bNodeExecData *UNU
float *array;
int size;
- colorband_table_RGBA(node->storage, &array, &size);
+ BKE_colorband_evaluate_table_rgba(node->storage, &array, &size);
return GPU_stack_link(mat, "valtorgb", in, out, GPU_texture(size, array));
}
diff --git a/source/blender/nodes/shader/nodes/node_shader_vectTransform.c b/source/blender/nodes/shader/nodes/node_shader_vectTransform.c
index 3c165cfcb8a..74e23aed7de 100644
--- a/source/blender/nodes/shader/nodes/node_shader_vectTransform.c
+++ b/source/blender/nodes/shader/nodes/node_shader_vectTransform.c
@@ -202,7 +202,7 @@ void register_node_type_sh_vect_transform(void)
{
static bNodeType ntype;
- sh_node_type_base(&ntype, SH_NODE_VECT_TRANSFORM, "Vector Transform", NODE_CLASS_CONVERTOR, 0);
+ sh_node_type_base(&ntype, SH_NODE_VECT_TRANSFORM, "Vector Transform", NODE_CLASS_OP_VECTOR, 0);
node_type_compatibility(&ntype, NODE_OLD_SHADING | NODE_NEW_SHADING);
node_type_init(&ntype, node_shader_init_vect_transform);
node_type_socket_templates(&ntype, sh_node_vect_transform_in, sh_node_vect_transform_out);
diff --git a/source/blender/nodes/shader/nodes/node_shader_vector_displacement.c b/source/blender/nodes/shader/nodes/node_shader_vector_displacement.c
new file mode 100644
index 00000000000..073bc3110f6
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_vector_displacement.c
@@ -0,0 +1,82 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../node_shader_util.h"
+
+/* **************** OUTPUT ******************** */
+
+static bNodeSocketTemplate sh_node_vector_displacement_in[] = {
+ { SOCK_RGBA, 0, N_("Vector"), 0.00f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f, PROP_NONE, SOCK_HIDE_VALUE},
+ { SOCK_FLOAT, 0, N_("Midlevel"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_FLOAT, 0, N_("Scale"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_vector_displacement_out[] = {
+ { SOCK_VECTOR, 0, N_("Displacement"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static void node_shader_init_vector_displacement(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ node->custom1 = SHD_SPACE_TANGENT; /* space */
+}
+
+static int gpu_shader_vector_displacement(GPUMaterial *mat, bNode *node, bNodeExecData *UNUSED(execdata), GPUNodeStack *in, GPUNodeStack *out)
+{
+ if (node->custom1 == SHD_SPACE_TANGENT) {
+ return GPU_stack_link(mat,
+ "node_vector_displacement_tangent",
+ in,
+ out,
+ GPU_attribute(CD_TANGENT, ""),
+ GPU_builtin(GPU_VIEW_NORMAL),
+ GPU_builtin(GPU_OBJECT_MATRIX),
+ GPU_builtin(GPU_VIEW_MATRIX));
+ }
+ else if (node->custom1 == SHD_SPACE_OBJECT) {
+ return GPU_stack_link(mat, "node_vector_displacement_object", in, out, GPU_builtin(GPU_OBJECT_MATRIX));
+ }
+ else {
+ return GPU_stack_link(mat, "node_vector_displacement_world", in, out);
+ }
+}
+
+/* node type definition */
+void register_node_type_sh_vector_displacement(void)
+{
+ static bNodeType ntype;
+
+ sh_node_type_base(&ntype, SH_NODE_VECTOR_DISPLACEMENT, "Vector Displacement", NODE_CLASS_OP_VECTOR, 0);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_vector_displacement_in, sh_node_vector_displacement_out);
+ node_type_storage(&ntype, "", NULL, NULL);
+ node_type_init(&ntype, node_shader_init_vector_displacement);
+ node_type_gpu(&ntype, gpu_shader_vector_displacement);
+
+ nodeRegisterType(&ntype);
+}
diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_principled.c b/source/blender/nodes/shader/nodes/node_shader_volume_principled.c
new file mode 100644
index 00000000000..e85fec1ec9d
--- /dev/null
+++ b/source/blender/nodes/shader/nodes/node_shader_volume_principled.c
@@ -0,0 +1,85 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2005 Blender Foundation.
+ * All rights reserved.
+ *
+ * The Original Code is: all of this file.
+ *
+ * Contributor(s): none yet.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+#include "../node_shader_util.h"
+
+/* **************** OUTPUT ******************** */
+
+static bNodeSocketTemplate sh_node_volume_principled_in[] = {
+ { SOCK_RGBA, 1, N_("Color"), 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 1.0f},
+ { SOCK_STRING, 1, N_("Color Attribute"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Density"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
+ { SOCK_STRING, 1, N_("Density Attribute"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Anisotropy"), 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_FACTOR},
+ { SOCK_RGBA, 1, N_("Absorption Color"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Emission Strength"), 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1000.0f},
+ { SOCK_RGBA, 1, N_("Emission Color"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Blackbody Intensity"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, PROP_FACTOR},
+ { SOCK_RGBA, 1, N_("Blackbody Tint"), 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Temperature"), 1000.0f, 0.0f, 0.0f, 0.0f, 0.0f, 6500.0f},
+ { SOCK_STRING, 1, N_("Temperature Attribute"), 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f},
+ { -1, 0, "" }
+};
+
+static bNodeSocketTemplate sh_node_volume_principled_out[] = {
+ { SOCK_SHADER, 0, N_("Volume")},
+ { -1, 0, "" }
+};
+
+static void node_shader_init_volume_principled(bNodeTree *UNUSED(ntree), bNode *node)
+{
+ for (bNodeSocket *sock = node->inputs.first; sock; sock = sock->next) {
+ if (STREQ(sock->name, "Density Attribute")) {
+ strcpy(((bNodeSocketValueString *)sock->default_value)->value, "density");
+ }
+ else if (STREQ(sock->name, "Temperature Attribute")) {
+ strcpy(((bNodeSocketValueString *)sock->default_value)->value, "temperature");
+ }
+ }
+}
+
+static int node_shader_gpu_volume_principled(GPUMaterial *UNUSED(mat), bNode *UNUSED(node), bNodeExecData *UNUSED(execdata), GPUNodeStack *UNUSED(in), GPUNodeStack *UNUSED(out))
+{
+ return false;
+}
+
+/* node type definition */
+void register_node_type_sh_volume_principled(void)
+{
+ static bNodeType ntype;
+
+ sh_node_type_base(&ntype, SH_NODE_VOLUME_PRINCIPLED, "Principled Volume", NODE_CLASS_SHADER, 0);
+ node_type_compatibility(&ntype, NODE_NEW_SHADING);
+ node_type_socket_templates(&ntype, sh_node_volume_principled_in, sh_node_volume_principled_out);
+ node_type_size_preset(&ntype, NODE_SIZE_LARGE);
+ node_type_init(&ntype, node_shader_init_volume_principled);
+ node_type_storage(&ntype, "", NULL, NULL);
+ node_type_gpu(&ntype, node_shader_gpu_volume_principled);
+
+ nodeRegisterType(&ntype);
+}
+
diff --git a/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c b/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c
index 0c5647b4ba8..ed56df257b7 100644
--- a/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c
+++ b/source/blender/nodes/shader/nodes/node_shader_volume_scatter.c
@@ -32,7 +32,7 @@
static bNodeSocketTemplate sh_node_volume_scatter_in[] = {
{ SOCK_RGBA, 1, N_("Color"), 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f},
{ SOCK_FLOAT, 1, N_("Density"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1000.0f},
- { SOCK_FLOAT, 1, N_("Anisotropy"),0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f},
+ { SOCK_FLOAT, 1, N_("Anisotropy"),0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, PROP_FACTOR},
{ -1, 0, "" }
};
diff --git a/source/blender/nodes/texture/node_texture_tree.c b/source/blender/nodes/texture/node_texture_tree.c
index 714665c303b..bc48802a7ca 100644
--- a/source/blender/nodes/texture/node_texture_tree.c
+++ b/source/blender/nodes/texture/node_texture_tree.c
@@ -345,10 +345,10 @@ int ntreeTexExecTree(
/* ensure execdata is only initialized once */
if (!exec) {
- BLI_lock_thread(LOCK_NODES);
+ BLI_thread_lock(LOCK_NODES);
if (!nodes->execdata)
ntreeTexBeginExecTree(nodes);
- BLI_unlock_thread(LOCK_NODES);
+ BLI_thread_unlock(LOCK_NODES);
exec = nodes->execdata;
}
diff --git a/source/blender/nodes/texture/node_texture_util.h b/source/blender/nodes/texture/node_texture_util.h
index 2263c271ccf..f6af5b1b6ca 100644
--- a/source/blender/nodes/texture/node_texture_util.h
+++ b/source/blender/nodes/texture/node_texture_util.h
@@ -53,6 +53,7 @@
#include "BLI_threads.h"
#include "BLI_utildefines.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_global.h"
#include "BKE_image.h"
diff --git a/source/blender/nodes/texture/nodes/node_texture_image.c b/source/blender/nodes/texture/nodes/node_texture_image.c
index 9b13589f3e1..69c8f4b7262 100644
--- a/source/blender/nodes/texture/nodes/node_texture_image.c
+++ b/source/blender/nodes/texture/nodes/node_texture_image.c
@@ -64,10 +64,10 @@ static void colorfn(float *out, TexParams *p, bNode *node, bNodeStack **UNUSED(i
if ( (!xsize) || (!ysize) ) return;
if (!ibuf->rect_float) {
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (!ibuf->rect_float)
IMB_float_from_rect(ibuf);
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
while (px < 0) px += ibuf->x;
@@ -106,6 +106,7 @@ void register_node_type_tex_image(void)
node_type_init(&ntype, init);
node_type_storage(&ntype, "ImageUser", node_free_standard_storage, node_copy_standard_storage);
node_type_exec(&ntype, NULL, NULL, exec);
-
+ node_type_label(&ntype, node_image_label);
+
nodeRegisterType(&ntype);
}
diff --git a/source/blender/nodes/texture/nodes/node_texture_valToRgb.c b/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
index a49d82d27a9..8b016c5aa50 100644
--- a/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
+++ b/source/blender/nodes/texture/nodes/node_texture_valToRgb.c
@@ -49,7 +49,7 @@ static void valtorgb_colorfn(float *out, TexParams *p, bNode *node, bNodeStack *
if (node->storage) {
float fac = tex_input_value(in[0], p, thread);
- do_colorband(node->storage, fac, out);
+ BKE_colorband_evaluate(node->storage, fac, out);
}
}
@@ -60,7 +60,7 @@ static void valtorgb_exec(void *data, int UNUSED(thread), bNode *node, bNodeExec
static void valtorgb_init(bNodeTree *UNUSED(ntree), bNode *node)
{
- node->storage = add_colorband(true);
+ node->storage = BKE_colorband_add(true);
}
void register_node_type_tex_valtorgb(void)
diff --git a/source/blender/physics/intern/BPH_mass_spring.cpp b/source/blender/physics/intern/BPH_mass_spring.cpp
index 359395b63c4..5b5639495da 100644
--- a/source/blender/physics/intern/BPH_mass_spring.cpp
+++ b/source/blender/physics/intern/BPH_mass_spring.cpp
@@ -34,7 +34,7 @@ extern "C" {
#include "DNA_cloth_types.h"
#include "DNA_scene_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_modifier_types.h"
@@ -333,19 +333,14 @@ static int UNUSED_FUNCTION(cloth_calc_helper_forces)(Object *UNUSED(ob), ClothMo
return 1;
}
-BLI_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s, float time)
+BLI_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s)
{
Cloth *cloth = clmd->clothObject;
ClothSimSettings *parms = clmd->sim_parms;
Implicit_Data *data = cloth->implicit;
- ClothVertex *verts = cloth->verts;
bool no_compress = parms->flags & CLOTH_SIMSETTINGS_FLAG_NO_SPRING_COMPRESS;
- zero_v3(s->f);
- zero_m3(s->dfdx);
- zero_m3(s->dfdv);
-
s->flags &= ~CLOTH_SPRING_FLAG_NEEDED;
// calculate force of structural + shear springs
@@ -361,31 +356,13 @@ BLI_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
if (s->type & CLOTH_SPRING_TYPE_SEWING) {
// TODO: verify, half verified (couldn't see error)
// sewing springs usually have a large distance at first so clamp the force so we don't get tunnelling through colission objects
- BPH_mass_spring_force_spring_linear(data, s->ij, s->kl, s->restlen, k, parms->Cdis, no_compress, parms->max_sewing, s->f, s->dfdx, s->dfdv);
+ BPH_mass_spring_force_spring_linear(data, s->ij, s->kl, s->restlen, k, parms->Cdis, no_compress, parms->max_sewing);
}
else {
- BPH_mass_spring_force_spring_linear(data, s->ij, s->kl, s->restlen, k, parms->Cdis, no_compress, 0.0f, s->f, s->dfdx, s->dfdv);
+ BPH_mass_spring_force_spring_linear(data, s->ij, s->kl, s->restlen, k, parms->Cdis, no_compress, 0.0f);
}
#endif
}
- else if (s->type & CLOTH_SPRING_TYPE_GOAL) {
-#ifdef CLOTH_FORCE_SPRING_GOAL
- float goal_x[3], goal_v[3];
- float k, scaling;
-
- s->flags |= CLOTH_SPRING_FLAG_NEEDED;
-
- // current_position = xold + t * (newposition - xold)
- /* divide by time_scale to prevent goal vertices' delta locations from being multiplied */
- interp_v3_v3v3(goal_x, verts[s->ij].xold, verts[s->ij].xconst, time / parms->time_scale);
- sub_v3_v3v3(goal_v, verts[s->ij].xconst, verts[s->ij].xold); // distance covered over dt==1
-
- scaling = parms->goalspring + s->stiffness * fabsf(parms->max_struct - parms->goalspring);
- k = verts[s->ij].goal * scaling / (parms->avg_spring_len + FLT_EPSILON);
-
- BPH_mass_spring_force_spring_goal(data, s->ij, goal_x, goal_v, k, parms->goalfrict * 0.01f, s->f, s->dfdx, s->dfdv);
-#endif
- }
else if (s->type & CLOTH_SPRING_TYPE_BENDING) { /* calculate force of bending springs */
#ifdef CLOTH_FORCE_SPRING_BEND
float kb, cb, scaling;
@@ -398,7 +375,7 @@ BLI_INLINE void cloth_calc_spring_force(ClothModifierData *clmd, ClothSpring *s,
// Fix for [#45084] for cloth stiffness must have cb proportional to kb
cb = kb * parms->bending_damping;
- BPH_mass_spring_force_spring_bending(data, s->ij, s->kl, s->restlen, kb, cb, s->f, s->dfdx, s->dfdv);
+ BPH_mass_spring_force_spring_bending(data, s->ij, s->kl, s->restlen, kb, cb);
#endif
}
else if (s->type & CLOTH_SPRING_TYPE_BENDING_ANG) {
@@ -474,9 +451,24 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), ListB
/* scale gravity force */
mul_v3_v3fl(gravity, clmd->scene->physics_settings.gravity, 0.001f * clmd->sim_parms->effector_weights->global_gravity);
}
+
vert = cloth->verts;
for (i = 0; i < cloth->mvert_num; i++, vert++) {
BPH_mass_spring_force_gravity(data, i, vert->mass, gravity);
+
+ /* Vertex goal springs */
+ if ((!(vert->flags & CLOTH_VERT_FLAG_PINNED)) && (vert->goal > FLT_EPSILON)) {
+ float goal_x[3], goal_v[3];
+ float k;
+
+ /* divide by time_scale to prevent goal vertices' delta locations from being multiplied */
+ interp_v3_v3v3(goal_x, vert->xold, vert->xconst, time / clmd->sim_parms->time_scale);
+ sub_v3_v3v3(goal_v, vert->xconst, vert->xold); /* distance covered over dt==1 */
+
+ k = vert->goal * clmd->sim_parms->goalspring / (clmd->sim_parms->avg_spring_len + FLT_EPSILON);
+
+ BPH_mass_spring_force_spring_goal(data, i, goal_x, goal_v, k, clmd->sim_parms->goalfrict * 0.01f);
+ }
}
#endif
@@ -544,8 +536,9 @@ static void cloth_calc_force(ClothModifierData *clmd, float UNUSED(frame), ListB
for (LinkNode *link = cloth->springs; link; link = link->next) {
ClothSpring *spring = (ClothSpring *)link->link;
// only handle active springs
- if (!(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE))
- cloth_calc_spring_force(clmd, spring, time);
+ if (!(spring->flags & CLOTH_SPRING_FLAG_DEACTIVATE)) {
+ cloth_calc_spring_force(clmd, spring);
+ }
}
}
diff --git a/source/blender/physics/intern/eigen_utils.h b/source/blender/physics/intern/eigen_utils.h
index e4a4f306aeb..8a5a9dbf5e9 100644
--- a/source/blender/physics/intern/eigen_utils.h
+++ b/source/blender/physics/intern/eigen_utils.h
@@ -32,7 +32,7 @@
* \ingroup bph
*/
-#ifdef __GNUC__
+#if defined(__GNUC__) && !defined(__clang__)
# pragma GCC diagnostic push
/* XXX suppress verbose warnings in eigen */
# pragma GCC diagnostic ignored "-Wlogical-op"
diff --git a/source/blender/physics/intern/implicit.h b/source/blender/physics/intern/implicit.h
index d1a75ca5297..2f62ab98e12 100644
--- a/source/blender/physics/intern/implicit.h
+++ b/source/blender/physics/intern/implicit.h
@@ -114,19 +114,15 @@ void BPH_mass_spring_force_edge_wind(struct Implicit_Data *data, int v1, int v2,
void BPH_mass_spring_force_vertex_wind(struct Implicit_Data *data, int v, float radius, const float (*winvec)[3]);
/* Linear spring force between two points */
bool BPH_mass_spring_force_spring_linear(struct Implicit_Data *data, int i, int j, float restlen,
- float stiffness, float damping, bool no_compress, float clamp_force,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3]);
+ float stiffness, float damping, bool no_compress, float clamp_force);
/* Bending force, forming a triangle at the base of two structural springs */
-bool BPH_mass_spring_force_spring_bending(struct Implicit_Data *data, int i, int j, float restlen,
- float kb, float cb,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3]);
+bool BPH_mass_spring_force_spring_bending(struct Implicit_Data *data, int i, int j, float restlen, float kb, float cb);
/* Angular bending force based on local target vectors */
bool BPH_mass_spring_force_spring_bending_angular(struct Implicit_Data *data, int i, int j, int k,
const float target[3], float stiffness, float damping);
/* Global goal spring */
bool BPH_mass_spring_force_spring_goal(struct Implicit_Data *data, int i, const float goal_x[3], const float goal_v[3],
- float stiffness, float damping,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3]);
+ float stiffness, float damping);
/* ======== Hair Volumetric Forces ======== */
diff --git a/source/blender/physics/intern/implicit_blender.c b/source/blender/physics/intern/implicit_blender.c
index 2ad8ee0547f..0fdc1d86d5c 100644
--- a/source/blender/physics/intern/implicit_blender.c
+++ b/source/blender/physics/intern/implicit_blender.c
@@ -37,7 +37,7 @@
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_texture_types.h"
@@ -48,7 +48,6 @@
#include "BKE_cloth.h"
#include "BKE_collision.h"
#include "BKE_effect.h"
-#include "BKE_global.h"
#include "BPH_mass_spring.h"
@@ -1579,8 +1578,7 @@ BLI_INLINE void apply_spring(Implicit_Data *data, int i, int j, const float f[3]
}
bool BPH_mass_spring_force_spring_linear(Implicit_Data *data, int i, int j, float restlen,
- float stiffness, float damping, bool no_compress, float clamp_force,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3])
+ float stiffness, float damping, bool no_compress, float clamp_force)
{
float extent[3], length, dir[3], vel[3];
@@ -1608,25 +1606,15 @@ bool BPH_mass_spring_force_spring_linear(Implicit_Data *data, int i, int j, floa
apply_spring(data, i, j, f, dfdx, dfdv);
- if (r_f) copy_v3_v3(r_f, f);
- if (r_dfdx) copy_m3_m3(r_dfdx, dfdx);
- if (r_dfdv) copy_m3_m3(r_dfdv, dfdv);
-
return true;
}
else {
- if (r_f) zero_v3(r_f);
- if (r_dfdx) zero_m3(r_dfdx);
- if (r_dfdv) zero_m3(r_dfdv);
-
return false;
}
}
/* See "Stable but Responsive Cloth" (Choi, Ko 2005) */
-bool BPH_mass_spring_force_spring_bending(Implicit_Data *data, int i, int j, float restlen,
- float kb, float cb,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3])
+bool BPH_mass_spring_force_spring_bending(Implicit_Data *data, int i, int j, float restlen, float kb, float cb)
{
float extent[3], length, dir[3], vel[3];
@@ -1646,17 +1634,9 @@ bool BPH_mass_spring_force_spring_bending(Implicit_Data *data, int i, int j, flo
apply_spring(data, i, j, f, dfdx, dfdv);
- if (r_f) copy_v3_v3(r_f, f);
- if (r_dfdx) copy_m3_m3(r_dfdx, dfdx);
- if (r_dfdv) copy_m3_m3(r_dfdv, dfdv);
-
return true;
}
else {
- if (r_f) zero_v3(r_f);
- if (r_dfdx) zero_m3(r_dfdx);
- if (r_dfdv) zero_m3(r_dfdv);
-
return false;
}
}
@@ -1945,8 +1925,7 @@ bool BPH_mass_spring_force_spring_bending_angular(Implicit_Data *data, int i, in
}
bool BPH_mass_spring_force_spring_goal(Implicit_Data *data, int i, const float goal_x[3], const float goal_v[3],
- float stiffness, float damping,
- float r_f[3], float r_dfdx[3][3], float r_dfdv[3][3])
+ float stiffness, float damping)
{
float root_goal_x[3], root_goal_v[3], extent[3], length, dir[3], vel[3];
float f[3], dfdx[3][3], dfdv[3][3];
@@ -1973,17 +1952,9 @@ bool BPH_mass_spring_force_spring_goal(Implicit_Data *data, int i, const float g
add_m3_m3m3(data->dFdX[i].m, data->dFdX[i].m, dfdx);
add_m3_m3m3(data->dFdV[i].m, data->dFdV[i].m, dfdv);
- if (r_f) copy_v3_v3(r_f, f);
- if (r_dfdx) copy_m3_m3(r_dfdx, dfdx);
- if (r_dfdv) copy_m3_m3(r_dfdv, dfdv);
-
return true;
}
else {
- if (r_f) zero_v3(r_f);
- if (r_dfdx) zero_m3(r_dfdx);
- if (r_dfdv) zero_m3(r_dfdv);
-
return false;
}
}
diff --git a/source/blender/physics/intern/implicit_eigen.cpp b/source/blender/physics/intern/implicit_eigen.cpp
index ff4c705ed61..c36fabcffb0 100644
--- a/source/blender/physics/intern/implicit_eigen.cpp
+++ b/source/blender/physics/intern/implicit_eigen.cpp
@@ -39,7 +39,7 @@
#ifdef __GNUC__
# pragma GCC diagnostic push
/* XXX suppress verbose warnings in eigen */
-# pragma GCC diagnostic ignored "-Wlogical-op"
+//# pragma GCC diagnostic ignored "-Wlogical-op"
#endif
#ifndef IMPLICIT_ENABLE_EIGEN_DEBUG
@@ -73,7 +73,7 @@
extern "C" {
#include "DNA_scene_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_texture_types.h"
diff --git a/source/blender/python/BPY_extern.h b/source/blender/python/BPY_extern.h
index 3148dab3c50..b4c36a7c516 100644
--- a/source/blender/python/BPY_extern.h
+++ b/source/blender/python/BPY_extern.h
@@ -75,7 +75,8 @@ void BPY_thread_restore(BPy_ThreadStatePtr tstate);
bool BPY_execute_filepath(struct bContext *C, const char *filepath, struct ReportList *reports);
bool BPY_execute_text(struct bContext *C, struct Text *text, struct ReportList *reports, const bool do_jump);
-bool BPY_execute_string_as_number(struct bContext *C, const char *expr, double *value, const bool verbose);
+bool BPY_execute_string_as_number(struct bContext *C, const char *expr, const bool verbose, double *r_value);
+bool BPY_execute_string_as_string(struct bContext *C, const char *expr, const bool verbose, char **r_value);
bool BPY_execute_string_ex(struct bContext *C, const char *expr, bool use_eval);
bool BPY_execute_string(struct bContext *C, const char *expr);
diff --git a/source/blender/python/BPY_extern_clog.h b/source/blender/python/BPY_extern_clog.h
new file mode 100644
index 00000000000..fbe7139ba1b
--- /dev/null
+++ b/source/blender/python/BPY_extern_clog.h
@@ -0,0 +1,35 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file BPY_extern_clog.h
+ * \ingroup python
+ *
+ * Logging defines.
+ */
+
+#ifndef __BPY_EXTERN_CLOG_H__
+#define __BPY_EXTERN_CLOG_H__
+
+
+/* bpy_interface.c */
+extern struct CLG_LogRef *BPY_LOG_RNA;
+extern struct CLG_LogRef *BPY_LOG_CONTEXT;
+
+#endif /* __BPY_EXTERN_CLOG_H__ */
diff --git a/source/blender/python/bmesh/bmesh_py_ops_call.c b/source/blender/python/bmesh/bmesh_py_ops_call.c
index 8f287918a4a..4dce0dc2a22 100644
--- a/source/blender/python/bmesh/bmesh_py_ops_call.c
+++ b/source/blender/python/bmesh/bmesh_py_ops_call.c
@@ -44,6 +44,7 @@
#include "bmesh_py_types.h"
#include "../generic/python_utildefines.h"
+#include "../generic/py_capi_utils.h"
static int bpy_bm_op_as_py_error(BMesh *bm)
{
@@ -152,11 +153,9 @@ static int bpy_slot_from_py(
switch (slot->slot_type) {
case BMO_OP_SLOT_BOOL:
{
- int param;
+ const int param = PyC_Long_AsBool(value);
- param = PyLong_AsLong(value);
-
- if (param < 0) {
+ if (param == -1) {
PyErr_Format(PyExc_TypeError,
"%.200s: keyword \"%.200s\" expected True/False or 0/1, not %.200s",
opname, slot_name, Py_TYPE(value)->tp_name);
@@ -170,23 +169,16 @@ static int bpy_slot_from_py(
}
case BMO_OP_SLOT_INT:
{
- int overflow;
- long param = PyLong_AsLongAndOverflow(value, &overflow);
- if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
- PyErr_Format(PyExc_ValueError,
- "%.200s: keyword \"%.200s\" value not in 'int' range "
- "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
- opname, slot_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- else if (param == -1 && PyErr_Occurred()) {
+ const int param = PyC_Long_AsI32(value);
+
+ if (param == -1 && PyErr_Occurred()) {
PyErr_Format(PyExc_TypeError,
"%.200s: keyword \"%.200s\" expected an int, not %.200s",
opname, slot_name, Py_TYPE(value)->tp_name);
return -1;
}
else {
- BMO_SLOT_AS_INT(slot) = (int)param;
+ BMO_SLOT_AS_INT(slot) = param;
}
break;
}
@@ -208,26 +200,19 @@ static int bpy_slot_from_py(
{
/* XXX - BMesh operator design is crappy here, operator slot should define matrix size,
* not the caller! */
- unsigned short size;
- if (!MatrixObject_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s: keyword \"%.200s\" expected a Matrix, not %.200s",
- opname, slot_name, Py_TYPE(value)->tp_name);
+ MatrixObject *pymat;
+ if (!Matrix_ParseAny(value, &pymat)) {
return -1;
}
- else if (BaseMath_ReadCallback((MatrixObject *)value) == -1) {
- return -1;
- }
- else if (((size = ((MatrixObject *)value)->num_col) != ((MatrixObject *)value)->num_row) ||
- (ELEM(size, 3, 4) == false))
- {
+ const ushort size = pymat->num_col;
+ if ((size != pymat->num_row) || (!ELEM(size, 3, 4))) {
PyErr_Format(PyExc_TypeError,
"%.200s: keyword \"%.200s\" expected a 3x3 or 4x4 matrix Matrix",
opname, slot_name);
return -1;
}
- BMO_slot_mat_set(bmop, bmop->slots_in, slot_name, ((MatrixObject *)value)->matrix, size);
+ BMO_slot_mat_set(bmop, bmop->slots_in, slot_name, pymat->matrix, size);
break;
}
case BMO_OP_SLOT_VEC:
@@ -436,7 +421,7 @@ static int bpy_slot_from_py(
return -1; /* error is set in bpy_slot_from_py_elem_check() */
}
- value_i = PyLong_AsLong(arg_value);
+ value_i = PyC_Long_AsI32(arg_value);
if (value_i == -1 && PyErr_Occurred()) {
PyErr_Format(PyExc_TypeError,
@@ -466,7 +451,7 @@ static int bpy_slot_from_py(
return -1; /* error is set in bpy_slot_from_py_elem_check() */
}
- value_i = PyLong_AsLong(arg_value);
+ value_i = PyC_Long_AsI32(arg_value);
if (value_i == -1 && PyErr_Occurred()) {
PyErr_Format(PyExc_TypeError,
@@ -581,7 +566,7 @@ static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
switch (slot->slot_subtype.map) {
case BMO_OP_SLOT_SUBTYPE_MAP_ELEM:
{
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_size(slot_hash) : 0);
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
if (slot_hash) {
GHASH_ITER (hash_iter, slot_hash) {
BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
@@ -599,7 +584,7 @@ static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
}
case BMO_OP_SLOT_SUBTYPE_MAP_FLT:
{
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_size(slot_hash) : 0);
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
if (slot_hash) {
GHASH_ITER (hash_iter, slot_hash) {
BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
@@ -617,7 +602,7 @@ static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
}
case BMO_OP_SLOT_SUBTYPE_MAP_INT:
{
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_size(slot_hash) : 0);
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
if (slot_hash) {
GHASH_ITER (hash_iter, slot_hash) {
BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
@@ -635,7 +620,7 @@ static PyObject *bpy_slot_to_py(BMesh *bm, BMOpSlot *slot)
}
case BMO_OP_SLOT_SUBTYPE_MAP_BOOL:
{
- item = _PyDict_NewPresized(slot_hash ? BLI_ghash_size(slot_hash) : 0);
+ item = _PyDict_NewPresized(slot_hash ? BLI_ghash_len(slot_hash) : 0);
if (slot_hash) {
GHASH_ITER (hash_iter, slot_hash) {
BMHeader *ele_key = BLI_ghashIterator_getKey(&hash_iter);
diff --git a/source/blender/python/bmesh/bmesh_py_types.c b/source/blender/python/bmesh/bmesh_py_types.c
index b20c03bee28..2866683b89b 100644
--- a/source/blender/python/bmesh/bmesh_py_types.c
+++ b/source/blender/python/bmesh/bmesh_py_types.c
@@ -124,25 +124,19 @@ static int bpy_bm_elem_hflag_set(BPy_BMElem *self, PyObject *value, void *flag)
BPY_BM_CHECK_INT(self);
- param = PyLong_AsLong(value);
-
- if ((unsigned int)param <= 1) {
- if (hflag == BM_ELEM_SELECT)
- BM_elem_select_set(self->bm, self->ele, param);
- else
- BM_elem_flag_set(self->ele, hflag, param);
+ if ((param = PyC_Long_AsBool(value)) == -1) {
+ return -1;
+ }
- return 0;
+ if (hflag == BM_ELEM_SELECT) {
+ BM_elem_select_set(self->bm, self->ele, param);
}
else {
- PyErr_Format(PyExc_TypeError,
- "expected True/False or 0/1, not %.200s",
- Py_TYPE(value)->tp_name);
- return -1;
+ BM_elem_flag_set(self->ele, hflag, param);
}
+ return 0;
}
-
PyDoc_STRVAR(bpy_bm_elem_index_doc,
"Index of this element.\n"
"\n"
@@ -169,21 +163,17 @@ static int bpy_bm_elem_index_set(BPy_BMElem *self, PyObject *value, void *UNUSED
BPY_BM_CHECK_INT(self);
- param = PyLong_AsLong(value);
-
- if (param == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "expected an int type");
+ if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
+ /* error is set */
return -1;
}
- else {
- BM_elem_index_set(self->ele, param); /* set_dirty! */
- /* when setting the index assume its set invalid */
- self->bm->elem_index_dirty |= self->ele->head.htype;
+ BM_elem_index_set(self->ele, param); /* set_dirty! */
- return 0;
- }
+ /* when setting the index assume its set invalid */
+ self->bm->elem_index_dirty |= self->ele->head.htype;
+
+ return 0;
}
/* type specific get/sets
@@ -506,14 +496,12 @@ static int bpy_bmface_material_index_set(BPy_BMFace *self, PyObject *value)
BPY_BM_CHECK_INT(self);
- param = PyLong_AsLong(value);
-
- if (param == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "expected an int type");
+ if (((param = PyC_Long_AsI32(value)) == -1) && PyErr_Occurred()) {
+ /* error is set */
return -1;
}
- else if ((param < 0) || (param > MAXMAT)) {
+
+ if ((param < 0) || (param > MAXMAT)) {
/* normally we clamp but in this case raise an error */
PyErr_SetString(PyExc_ValueError,
"material index outside of usable range (0 - 32766)");
@@ -916,7 +904,11 @@ static PyObject *bpy_bmesh_to_mesh(BPy_BMesh *self, PyObject *args)
/* python won't ensure matching uv/mtex */
BM_mesh_cd_validate(bm);
- BM_mesh_bm_to_me(bm, me, (&(struct BMeshToMeshParams){0}));
+ BM_mesh_bm_to_me(
+ bm, me,
+ (&(struct BMeshToMeshParams){
+ .calc_object_remap = true,
+ }));
/* we could have the user do this but if they forget blender can easy crash
* since the references arrays for the objects derived meshes are now invalid */
@@ -1049,6 +1041,13 @@ PyDoc_STRVAR(bpy_bmesh_from_mesh_doc,
" :type use_shape_key: boolean\n"
" :arg shape_key_index: The shape key index to use.\n"
" :type shape_key_index: int\n"
+"\n"
+" .. note::\n"
+"\n"
+" Multiple calls can be used to join multiple meshes.\n"
+"\n"
+" Custom-data layers are only copied from ``mesh`` on initialization.\n"
+" Further calls will copy custom-data to matching layers, layers missing on the target mesh wont be added.\n"
);
static PyObject *bpy_bmesh_from_mesh(BPy_BMesh *self, PyObject *args, PyObject *kw)
{
@@ -1113,15 +1112,16 @@ static PyObject *bpy_bmesh_select_flush(BPy_BMesh *self, PyObject *value)
BPY_BM_CHECK_OBJ(self);
- param = PyLong_AsLong(value);
- if (param != false && param != true) {
- PyErr_SetString(PyExc_TypeError,
- "expected a boolean type 0/1");
+ if ((param = PyC_Long_AsBool(value)) == -1) {
return NULL;
}
- if (param) BM_mesh_select_flush(self->bm);
- else BM_mesh_deselect_flush(self->bm);
+ if (param) {
+ BM_mesh_select_flush(self->bm);
+ }
+ else {
+ BM_mesh_deselect_flush(self->bm);
+ }
Py_RETURN_NONE;
}
@@ -1301,10 +1301,7 @@ static PyObject *bpy_bm_elem_select_set(BPy_BMElem *self, PyObject *value)
BPY_BM_CHECK_OBJ(self);
- param = PyLong_AsLong(value);
- if (param != false && param != true) {
- PyErr_SetString(PyExc_TypeError,
- "expected a boolean type 0/1");
+ if ((param = PyC_Long_AsBool(value)) == -1) {
return NULL;
}
@@ -1329,10 +1326,7 @@ static PyObject *bpy_bm_elem_hide_set(BPy_BMElem *self, PyObject *value)
BPY_BM_CHECK_OBJ(self);
- param = PyLong_AsLong(value);
- if (param != false && param != true) {
- PyErr_SetString(PyExc_TypeError,
- "expected a boolean type 0/1");
+ if ((param = PyC_Long_AsBool(value)) == -1) {
return NULL;
}
@@ -1475,7 +1469,7 @@ static PyObject *bpy_bmvert_calc_edge_angle(BPy_BMVert *self, PyObject *args)
else {
PyErr_SetString(PyExc_ValueError,
"BMVert.calc_edge_angle(): "
- "vert doesn't use 2 edges");
+ "vert must connect to exactly 2 edges");
return NULL;
}
}
@@ -3878,7 +3872,7 @@ void *BPy_BMElem_PySeq_As_Array_FAST(
BMesh *bm = (r_bm && *r_bm) ? *r_bm : NULL;
PyObject **seq_fast_items = PySequence_Fast_ITEMS(seq_fast);
const Py_ssize_t seq_len = PySequence_Fast_GET_SIZE(seq_fast);
- Py_ssize_t i;
+ Py_ssize_t i, i_last_dirty = PY_SSIZE_T_MAX;
BPy_BMElem *item;
BMElem **alloc;
@@ -3927,6 +3921,7 @@ void *BPy_BMElem_PySeq_As_Array_FAST(
if (do_unique_check) {
BM_elem_flag_enable(item->ele, BM_ELEM_INTERNAL_TAG);
+ i_last_dirty = i;
}
}
@@ -3943,6 +3938,8 @@ void *BPy_BMElem_PySeq_As_Array_FAST(
}
if (ok == false) {
+ /* Cleared above. */
+ i_last_dirty = PY_SSIZE_T_MAX;
PyErr_Format(PyExc_ValueError,
"%s: found the same %.200s used multiple times",
error_prefix, BPy_BMElem_StringFromHType(htype));
@@ -3955,6 +3952,11 @@ void *BPy_BMElem_PySeq_As_Array_FAST(
return alloc;
err_cleanup:
+ if (do_unique_check && (i_last_dirty != PY_SSIZE_T_MAX)) {
+ for (i = 0; i <= i_last_dirty; i++) {
+ BM_elem_flag_disable(alloc[i], BM_ELEM_INTERNAL_TAG);
+ }
+ }
PyMem_FREE(alloc);
return NULL;
diff --git a/source/blender/python/bmesh/bmesh_py_types_customdata.c b/source/blender/python/bmesh/bmesh_py_types_customdata.c
index 908f6b5a734..cb95ded4f0d 100644
--- a/source/blender/python/bmesh/bmesh_py_types_customdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_customdata.c
@@ -43,6 +43,7 @@
#include "../mathutils/mathutils.h"
#include "../generic/python_utildefines.h"
+#include "../generic/py_capi_utils.h"
#include "BKE_customdata.h"
@@ -1074,9 +1075,9 @@ int BPy_BMLayerItem_SetItem(BPy_BMElem *py_ele, BPy_BMLayerItem *py_layer, PyObj
}
case CD_PROP_INT:
{
- int tmp_val = PyLong_AsLong(py_value);
+ int tmp_val = PyC_Long_AsI32(py_value);
if (UNLIKELY(tmp_val == -1 && PyErr_Occurred())) {
- PyErr_Format(PyExc_TypeError, "expected an int, not a %.200s", Py_TYPE(py_value)->tp_name);
+ /* error is set */
ret = -1;
}
else {
diff --git a/source/blender/python/bmesh/bmesh_py_types_meshdata.c b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
index 92c11a03433..7984f625d96 100644
--- a/source/blender/python/bmesh/bmesh_py_types_meshdata.c
+++ b/source/blender/python/bmesh/bmesh_py_types_meshdata.c
@@ -45,6 +45,7 @@
#include "bmesh_py_types_meshdata.h"
+#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
@@ -188,7 +189,7 @@ static int bpy_bmloopuv_flag_set(BPy_BMLoopUV *self, PyObject *value, void *flag
{
const int flag = GET_INT_FROM_POINTER(flag_p);
- switch (PyLong_AsLong(value)) {
+ switch (PyC_Long_AsBool(value)) {
case true:
self->data->flag |= flag;
return 0;
@@ -196,8 +197,7 @@ static int bpy_bmloopuv_flag_set(BPy_BMLoopUV *self, PyObject *value, void *flag
self->data->flag &= ~flag;
return 0;
default:
- PyErr_SetString(PyExc_TypeError,
- "expected a boolean type 0/1");
+ /* error is set */
return -1;
}
}
@@ -297,7 +297,7 @@ static int bpy_bmvertskin_flag_set(BPy_BMVertSkin *self, PyObject *value, void *
{
const int flag = GET_INT_FROM_POINTER(flag_p);
- switch (PyLong_AsLong(value)) {
+ switch (PyC_Long_AsBool(value)) {
case true:
self->data->flag |= flag;
return 0;
@@ -305,8 +305,7 @@ static int bpy_bmvertskin_flag_set(BPy_BMVertSkin *self, PyObject *value, void *
self->data->flag &= ~flag;
return 0;
default:
- PyErr_SetString(PyExc_TypeError,
- "expected a boolean type 0/1");
+ /* error is set */
return -1;
}
}
@@ -371,12 +370,12 @@ PyObject *BPy_BMVertSkin_CreatePyObject(struct MVertSkin *mvertskin)
static void mloopcol_to_float(const MLoopCol *mloopcol, float r_col[3])
{
- rgb_uchar_to_float(r_col, (const unsigned char *)&mloopcol->r);
+ rgba_uchar_to_float(r_col, (const unsigned char *)&mloopcol->r);
}
static void mloopcol_from_float(MLoopCol *mloopcol, const float col[3])
{
- rgb_float_to_uchar((unsigned char *)&mloopcol->r, col);
+ rgba_float_to_uchar((unsigned char *)&mloopcol->r, col);
}
static unsigned char mathutils_bmloopcol_cb_index = -1;
@@ -437,8 +436,8 @@ static void bm_init_types_bmloopcol(void)
int BPy_BMLoopColor_AssignPyObject(struct MLoopCol *mloopcol, PyObject *value)
{
- float tvec[3];
- if (mathutils_array_parse(tvec, 3, 3, value, "BMLoopCol") != -1) {
+ float tvec[4];
+ if (mathutils_array_parse(tvec, 4, 4, value, "BMLoopCol") != -1) {
mloopcol_from_float(mloopcol, tvec);
return 0;
}
@@ -451,7 +450,7 @@ PyObject *BPy_BMLoopColor_CreatePyObject(struct MLoopCol *data)
{
PyObject *color_capsule;
color_capsule = PyCapsule_New(data, NULL, NULL);
- return Color_CreatePyObject_cb(color_capsule, mathutils_bmloopcol_cb_index, 0);
+ return Vector_CreatePyObject_cb(color_capsule, 4, mathutils_bmloopcol_cb_index, 0);
}
#undef MLOOPCOL_FROM_CAPSULE
diff --git a/source/blender/python/bmesh/bmesh_py_utils.c b/source/blender/python/bmesh/bmesh_py_utils.c
index 89c196dbcad..224c8295a9b 100644
--- a/source/blender/python/bmesh/bmesh_py_utils.c
+++ b/source/blender/python/bmesh/bmesh_py_utils.c
@@ -565,6 +565,10 @@ PyDoc_STRVAR(bpy_bm_utils_face_split_edgenet_doc,
" :type edgenet: :class:`bmesh.types.BMEdge`\n"
" :return: The newly created faces.\n"
" :rtype: tuple of (:class:`bmesh.types.BMFace`)\n"
+"\n"
+" .. note::\n"
+"\n"
+" Regions defined by edges need to connect to the face, otherwise they're ignored as loose edges.\n"
);
static PyObject *bpy_bm_utils_face_split_edgenet(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
@@ -646,7 +650,7 @@ static PyObject *bpy_bm_utils_face_join(PyObject *UNUSED(self), PyObject *args)
bool do_remove = true;
if (!PyArg_ParseTuple(
- args, "O|i:face_join",
+ args, "O|O&:face_join",
&py_face_array,
PyC_ParseBool, &do_remove))
{
diff --git a/source/blender/python/generic/bgl.c b/source/blender/python/generic/bgl.c
index 3ea10228ad4..072021c6ac9 100644
--- a/source/blender/python/generic/bgl.c
+++ b/source/blender/python/generic/bgl.c
@@ -472,6 +472,44 @@ int BGL_typeSize(int type)
return -1;
}
+static int gl_buffer_type_from_py_buffer(Py_buffer *pybuffer)
+{
+ char *typestr = pybuffer->format;
+ Py_ssize_t itemsize = pybuffer->itemsize;
+
+ if (ELEM(typestr[0], '<', '>', '|')) {
+ typestr += 1;
+ }
+
+ switch (typestr[0]) {
+ case 't':
+ case 'b':
+ case 'h':
+ case 'i':
+ case 'l':
+ if (itemsize == 1) return GL_BYTE;
+ if (itemsize == 2) return GL_SHORT;
+ if (itemsize == 4) return GL_INT;
+ break;
+ case 'f':
+ case 'd':
+ if (itemsize == 4) return GL_FLOAT;
+ if (itemsize == 8) return GL_DOUBLE;
+ break;
+ }
+ return -1; /* UNKNOWN */
+}
+
+static bool compare_dimensions(int ndim, int *dim1, Py_ssize_t *dim2)
+{
+ for (int i = 0; i < ndim; i++) {
+ if (dim1[i] != dim2[i]) {
+ return false;
+ }
+ }
+ return true;
+}
+
/** \} */
@@ -630,6 +668,22 @@ PyTypeObject BGL_bufferType = {
NULL /*tp_del*/
};
+
+static Buffer *BGL_MakeBuffer_FromData(PyObject *parent, int type, int ndimensions, int *dimensions, void *buf)
+{
+ Buffer *buffer = (Buffer *)PyObject_NEW(Buffer, &BGL_bufferType);
+
+ Py_XINCREF(parent);
+ buffer->parent = parent;
+ buffer->ndimensions = ndimensions;
+ buffer->dimensions = MEM_mallocN(ndimensions * sizeof(int), "Buffer dimensions");
+ memcpy(buffer->dimensions, dimensions, ndimensions * sizeof(int));
+ buffer->type = type;
+ buffer->buf.asvoid = buf;
+
+ return buffer;
+}
+
/**
* Create a buffer object
*
@@ -641,30 +695,21 @@ Buffer *BGL_MakeBuffer(int type, int ndimensions, int *dimensions, void *initbuf
{
Buffer *buffer;
void *buf = NULL;
- int i, size, length;
+ int i, size = BGL_typeSize(type);
- length = 1;
for (i = 0; i < ndimensions; i++) {
- length *= dimensions[i];
+ size *= dimensions[i];
}
- size = BGL_typeSize(type);
+ buf = MEM_mallocN(size, "Buffer buffer");
- buf = MEM_mallocN(length * size, "Buffer buffer");
-
- buffer = (Buffer *)PyObject_NEW(Buffer, &BGL_bufferType);
- buffer->parent = NULL;
- buffer->ndimensions = ndimensions;
- buffer->dimensions = MEM_mallocN(ndimensions * sizeof(int), "Buffer dimensions");
- memcpy(buffer->dimensions, dimensions, ndimensions * sizeof(int));
- buffer->type = type;
- buffer->buf.asvoid = buf;
+ buffer = BGL_MakeBuffer_FromData(NULL, type, ndimensions, dimensions, buf);
if (initbuffer) {
- memcpy(buffer->buf.asvoid, initbuffer, length * size);
+ memcpy(buffer->buf.asvoid, initbuffer, size);
}
else {
- memset(buffer->buf.asvoid, 0, length * size);
+ memset(buffer->buf.asvoid, 0, size);
}
return buffer;
}
@@ -674,7 +719,7 @@ Buffer *BGL_MakeBuffer(int type, int ndimensions, int *dimensions, void *initbuf
static PyObject *Buffer_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject *kwds)
{
PyObject *length_ob = NULL, *init = NULL;
- Buffer *buffer;
+ Buffer *buffer = NULL;
int dimensions[MAX_DIMENSIONS];
int type;
@@ -739,9 +784,32 @@ static PyObject *Buffer_new(PyTypeObject *UNUSED(type), PyObject *args, PyObject
return NULL;
}
- buffer = BGL_MakeBuffer(type, ndimensions, dimensions, NULL);
- if (init && ndimensions) {
- if (Buffer_ass_slice(buffer, 0, dimensions[0], init)) {
+ if (init && PyObject_CheckBuffer(init)) {
+ Py_buffer pybuffer;
+
+ if (PyObject_GetBuffer(init, &pybuffer, PyBUF_ND | PyBUF_FORMAT) == -1) {
+ /* PyObject_GetBuffer raise a PyExc_BufferError */
+ return NULL;
+ }
+
+ if (type != gl_buffer_type_from_py_buffer(&pybuffer)) {
+ PyErr_Format(PyExc_TypeError,
+ "`GL_TYPE` and `typestr` of object with buffer interface do not match. '%s'", pybuffer.format);
+ }
+ else if (ndimensions != pybuffer.ndim ||
+ !compare_dimensions(ndimensions, dimensions, pybuffer.shape))
+ {
+ PyErr_Format(PyExc_TypeError, "array size does not match");
+ }
+ else {
+ buffer = BGL_MakeBuffer_FromData(init, type, pybuffer.ndim, dimensions, pybuffer.buf);
+ }
+
+ PyBuffer_Release(&pybuffer);
+ }
+ else {
+ buffer = BGL_MakeBuffer(type, ndimensions, dimensions, NULL);
+ if (init && Buffer_ass_slice(buffer, 0, dimensions[0], init)) {
Py_DECREF(buffer);
return NULL;
}
@@ -774,27 +842,17 @@ static PyObject *Buffer_item(Buffer *self, int i)
}
}
else {
- Buffer *newbuf;
- int j, length, size;
+ int j, offset = i * BGL_typeSize(self->type);
- length = 1;
for (j = 1; j < self->ndimensions; j++) {
- length *= self->dimensions[j];
+ offset *= self->dimensions[j];
}
- size = BGL_typeSize(self->type);
-
- newbuf = (Buffer *)PyObject_NEW(Buffer, &BGL_bufferType);
-
- Py_INCREF(self);
- newbuf->parent = (PyObject *)self;
-
- newbuf->ndimensions = self->ndimensions - 1;
- newbuf->type = self->type;
- newbuf->buf.asvoid = self->buf.asbyte + i * length * size;
- newbuf->dimensions = MEM_mallocN(newbuf->ndimensions * sizeof(int), "Buffer dimensions");
- memcpy(newbuf->dimensions, self->dimensions + 1, newbuf->ndimensions * sizeof(int));
- return (PyObject *)newbuf;
+ return (PyObject *)BGL_MakeBuffer_FromData(
+ (PyObject *)self, self->type,
+ self->ndimensions - 1,
+ self->dimensions + 1,
+ self->buf.asbyte + offset);
}
return NULL;
diff --git a/source/blender/python/generic/bpy_internal_import.c b/source/blender/python/generic/bpy_internal_import.c
index ed2752d8372..ffac09efdde 100644
--- a/source/blender/python/generic/bpy_internal_import.c
+++ b/source/blender/python/generic/bpy_internal_import.c
@@ -248,8 +248,17 @@ PyObject *bpy_text_reimport(PyObject *module, int *found)
if ((name = PyModule_GetName(module)) == NULL)
return NULL;
- if ((filepath = (char *)PyModule_GetFilename(module)) == NULL)
- return NULL;
+ {
+ PyObject *module_file = PyModule_GetFilenameObject(module);
+ if (module_file == NULL) {
+ return NULL;
+ }
+ filepath = _PyUnicode_AsString(module_file);
+ Py_DECREF(module_file);
+ if (filepath == NULL) {
+ return NULL;
+ }
+ }
/* look up the text object */
text = BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);
@@ -276,13 +285,13 @@ static PyObject *blender_import(PyObject *UNUSED(self), PyObject *args, PyObject
int found = 0;
PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
int level = 0; /* relative imports */
-
PyObject *newmodule;
- //PyObject_Print(args, stderr, 0);
- static const char *kwlist[] = {"name", "globals", "locals", "fromlist", "level", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "s|OOOi:bpy_import_meth", (char **)kwlist,
- &name, &globals, &locals, &fromlist, &level))
+
+ static const char *_keywords[] = {"name", "globals", "locals", "fromlist", "level", NULL};
+ static _PyArg_Parser _parser = {"s|OOOi:bpy_import_meth", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &name, &globals, &locals, &fromlist, &level))
{
return NULL;
}
diff --git a/source/blender/python/generic/idprop_py_api.c b/source/blender/python/generic/idprop_py_api.c
index 2e15b7b1413..1153e0176df 100644
--- a/source/blender/python/generic/idprop_py_api.c
+++ b/source/blender/python/generic/idprop_py_api.c
@@ -43,6 +43,9 @@
#include "python_utildefines.h"
+extern bool pyrna_id_FromPyObject(PyObject *obj, ID **id);
+extern PyObject *pyrna_id_CreatePyObject(ID *id);
+extern bool pyrna_id_CheckPyObject(PyObject *obj);
/*********************** ID Property Main Wrapper Stuff ***************/
@@ -88,6 +91,11 @@ static PyObject *idprop_py_from_idp_group(ID *id, IDProperty *prop, IDProperty *
return (PyObject *)group;
}
+static PyObject *idprop_py_from_idp_id(IDProperty *prop)
+{
+ return pyrna_id_CreatePyObject(prop->data.pointer);
+}
+
static PyObject *idprop_py_from_idp_array(ID *id, IDProperty *prop)
{
BPy_IDProperty *array = PyObject_New(BPy_IDProperty, &BPy_IDArray_Type);
@@ -148,6 +156,7 @@ PyObject *BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent)
case IDP_GROUP: return idprop_py_from_idp_group(id, prop, parent);
case IDP_ARRAY: return idprop_py_from_idp_array(id, prop);
case IDP_IDPARRAY: return idprop_py_from_idp_idparray(id, prop); /* this could be better a internal type */
+ case IDP_ID: return idprop_py_from_idp_id(prop);
default: Py_RETURN_NONE;
}
}
@@ -335,19 +344,9 @@ static char idp_sequence_type(PyObject *seq_fast)
return type;
}
-/**
- * \note group can be a pointer array or a group.
- * assume we already checked key is a string.
- *
- * \return success.
- */
-bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
+static const char *idp_try_read_name(PyObject *name_obj)
{
- IDProperty *prop = NULL;
- IDPropertyTemplate val = {0};
-
- const char *name;
-
+ const char *name = NULL;
if (name_obj) {
Py_ssize_t name_size;
name = _PyUnicode_AsStringAndSize(name_obj, &name_size);
@@ -356,168 +355,307 @@ bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group,
PyErr_Format(PyExc_KeyError,
"invalid id-property key, expected a string, not a %.200s",
Py_TYPE(name_obj)->tp_name);
- return false;
+ return NULL;
}
if (name_size > MAX_IDPROP_NAME) {
PyErr_SetString(PyExc_KeyError, "the length of IDProperty names is limited to 63 characters");
- return false;
+ return NULL;
}
}
else {
name = "";
}
+ return name;
+}
- if (PyFloat_Check(ob)) {
- val.d = PyFloat_AsDouble(ob);
- prop = IDP_New(IDP_DOUBLE, &val, name);
- }
- else if (PyLong_Check(ob)) {
- val.i = _PyLong_AsInt(ob);
- if (val.i == -1 && PyErr_Occurred()) {
- return false;
- }
- prop = IDP_New(IDP_INT, &val, name);
+/* -------------------------------------------------------------------------- */
+
+/**
+ * The 'idp_from_Py*' functions expect that the input type has been checked before
+ * and return NULL if the IDProperty can't be created.
+ */
+
+static IDProperty *idp_from_PyFloat(const char *name, PyObject *ob)
+{
+ IDPropertyTemplate val = {0};
+ val.d = PyFloat_AsDouble(ob);
+ return IDP_New(IDP_DOUBLE, &val, name);
+}
+
+static IDProperty *idp_from_PyLong(const char *name, PyObject *ob)
+{
+ IDPropertyTemplate val = {0};
+ val.i = PyC_Long_AsI32(ob);
+ if (val.i == -1 && PyErr_Occurred()) {
+ return NULL;
}
- else if (PyUnicode_Check(ob)) {
+ return IDP_New(IDP_INT, &val, name);
+}
+
+static IDProperty *idp_from_PyUnicode(const char *name, PyObject *ob)
+{
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
#ifdef USE_STRING_COERCE
- Py_ssize_t value_size;
- PyObject *value_coerce = NULL;
- val.string.str = PyC_UnicodeAsByteAndSize(ob, &value_size, &value_coerce);
- val.string.len = (int)value_size + 1;
- val.string.subtype = IDP_STRING_SUB_UTF8;
- prop = IDP_New(IDP_STRING, &val, name);
- Py_XDECREF(value_coerce);
+ Py_ssize_t value_size;
+ PyObject *value_coerce = NULL;
+ val.string.str = PyC_UnicodeAsByteAndSize(ob, &value_size, &value_coerce);
+ val.string.len = (int)value_size + 1;
+ val.string.subtype = IDP_STRING_SUB_UTF8;
+ prop = IDP_New(IDP_STRING, &val, name);
+ Py_XDECREF(value_coerce);
#else
- val.str = _PyUnicode_AsString(ob);
- prop = IDP_New(IDP_STRING, val, name);
+ val.str = _PyUnicode_AsString(ob);
+ prop = IDP_New(IDP_STRING, val, name);
#endif
- }
- else if (PyBytes_Check(ob)) {
- val.string.str = PyBytes_AS_STRING(ob);
- val.string.len = PyBytes_GET_SIZE(ob);
- val.string.subtype = IDP_STRING_SUB_BYTE;
+ return prop;
+}
+
+static IDProperty *idp_from_PyBytes(const char *name, PyObject *ob)
+{
+ IDPropertyTemplate val = {0};
+ val.string.str = PyBytes_AS_STRING(ob);
+ val.string.len = PyBytes_GET_SIZE(ob);
+ val.string.subtype = IDP_STRING_SUB_BYTE;
+ return IDP_New(IDP_STRING, &val, name);
+}
- prop = IDP_New(IDP_STRING, &val, name);
- //prop = IDP_NewString(PyBytes_AS_STRING(ob), name, PyBytes_GET_SIZE(ob));
- //prop->subtype = IDP_STRING_SUB_BYTE;
+static int idp_array_type_from_format_char(char format)
+{
+ if (format == 'i') return IDP_INT;
+ if (format == 'f') return IDP_FLOAT;
+ if (format == 'd') return IDP_DOUBLE;
+ return -1;
+}
+
+static const char *idp_format_from_array_type(int type)
+{
+ if (type == IDP_INT) return "i";
+ if (type == IDP_FLOAT) return "f";
+ if (type == IDP_DOUBLE) return "d";
+ return NULL;
+}
+
+static IDProperty *idp_from_PySequence_Buffer(const char *name, Py_buffer *buffer)
+{
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
+
+ int format = idp_array_type_from_format_char(*buffer->format);
+ if (format == -1) {
+ /* should never happen as the type has been checked before */
+ return NULL;
}
- else if (PySequence_Check(ob)) {
- PyObject *ob_seq_fast;
- PyObject **ob_seq_fast_items;
- PyObject *item;
- int i;
+ else {
+ val.array.type = format;
+ val.array.len = buffer->len / buffer->itemsize;
+ }
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ memcpy(IDP_Array(prop), buffer->buf, buffer->len);
+ return prop;
+}
- if (!(ob_seq_fast = PySequence_Fast(ob, "py -> idprop"))) {
- return false;
- }
+static IDProperty *idp_from_PySequence_Fast(const char *name, PyObject *ob)
+{
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
- ob_seq_fast_items = PySequence_Fast_ITEMS(ob_seq_fast);
+ PyObject **ob_seq_fast_items;
+ PyObject *item;
+ int i;
- if ((val.array.type = idp_sequence_type(ob_seq_fast)) == (char)-1) {
- Py_DECREF(ob_seq_fast);
- PyErr_SetString(PyExc_TypeError, "only floats, ints and dicts are allowed in ID property arrays");
- return false;
- }
+ ob_seq_fast_items = PySequence_Fast_ITEMS(ob);
- /* validate sequence and derive type.
- * we assume IDP_INT unless we hit a float
- * number; then we assume it's */
+ if ((val.array.type = idp_sequence_type(ob)) == (char)-1) {
+ PyErr_SetString(PyExc_TypeError, "only floats, ints and dicts are allowed in ID property arrays");
+ return NULL;
+ }
- val.array.len = PySequence_Fast_GET_SIZE(ob_seq_fast);
+ /* validate sequence and derive type.
+ * we assume IDP_INT unless we hit a float
+ * number; then we assume it's */
- switch (val.array.type) {
- case IDP_DOUBLE:
- {
- double *prop_data;
-
- prop = IDP_New(IDP_ARRAY, &val, name);
- prop_data = IDP_Array(prop);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
- if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
- Py_DECREF(ob_seq_fast);
- return false;
- }
+ val.array.len = PySequence_Fast_GET_SIZE(ob);
+
+ switch (val.array.type) {
+ case IDP_DOUBLE:
+ {
+ double *prop_data;
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ prop_data = IDP_Array(prop);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (((prop_data[i] = PyFloat_AsDouble(item)) == -1.0) && PyErr_Occurred()) {
+ return NULL;
}
- break;
}
- case IDP_INT:
- {
- int *prop_data;
- prop = IDP_New(IDP_ARRAY, &val, name);
- prop_data = IDP_Array(prop);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
- if (((prop_data[i] = _PyLong_AsInt(item)) == -1) && PyErr_Occurred()) {
- Py_DECREF(ob_seq_fast);
- return false;
- }
+ break;
+ }
+ case IDP_INT:
+ {
+ int *prop_data;
+ prop = IDP_New(IDP_ARRAY, &val, name);
+ prop_data = IDP_Array(prop);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (((prop_data[i] = PyC_Long_AsI32(item)) == -1) && PyErr_Occurred()) {
+ return NULL;
}
- break;
}
- case IDP_IDPARRAY:
- {
- prop = IDP_NewIDPArray(name);
- for (i = 0; i < val.array.len; i++) {
- item = ob_seq_fast_items[i];
-
- if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
- Py_DECREF(ob_seq_fast);
- return false;
- }
+ break;
+ }
+ case IDP_IDPARRAY:
+ {
+ prop = IDP_NewIDPArray(name);
+ for (i = 0; i < val.array.len; i++) {
+ item = ob_seq_fast_items[i];
+ if (BPy_IDProperty_Map_ValidateAndCreate(NULL, prop, item) == false) {
+ return NULL;
}
- break;
}
- default:
- /* should never happen */
- Py_DECREF(ob_seq_fast);
- PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
- return false;
+ break;
}
+ default:
+ /* should never happen */
+ PyErr_SetString(PyExc_RuntimeError, "internal error with idp array.type");
+ return NULL;
+ }
+ return prop;
+}
- Py_DECREF(ob_seq_fast);
+
+static IDProperty *idp_from_PySequence(const char *name, PyObject *ob)
+{
+ Py_buffer buffer;
+ bool use_buffer = false;
+
+ if (PyObject_CheckBuffer(ob)) {
+ PyObject_GetBuffer(ob, &buffer, PyBUF_SIMPLE | PyBUF_FORMAT);
+ char format = *buffer.format;
+ if (ELEM(format, 'i', 'f', 'd')) {
+ use_buffer = true;
+ }
+ else {
+ PyBuffer_Release(&buffer);
+ }
}
- else if (PyMapping_Check(ob)) {
- PyObject *keys, *vals, *key, *pval;
- int i, len;
- /*yay! we get into recursive stuff now!*/
- keys = PyMapping_Keys(ob);
- vals = PyMapping_Values(ob);
-
- /* we allocate the group first; if we hit any invalid data,
- * we can delete it easily enough.*/
- prop = IDP_New(IDP_GROUP, &val, name);
- len = PyMapping_Length(ob);
- for (i = 0; i < len; i++) {
- key = PySequence_GetItem(keys, i);
- pval = PySequence_GetItem(vals, i);
- if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
- IDP_FreeProperty(prop);
- MEM_freeN(prop);
- Py_XDECREF(keys);
- Py_XDECREF(vals);
- Py_XDECREF(key);
- Py_XDECREF(pval);
- /* error is already set */
- return false;
- }
+
+ if (use_buffer) {
+ IDProperty *prop = idp_from_PySequence_Buffer(name, &buffer);
+ PyBuffer_Release(&buffer);
+ return prop;
+ }
+ else {
+ PyObject *ob_seq_fast = PySequence_Fast(ob, "py -> idprop");
+ if (ob_seq_fast != NULL) {
+ IDProperty *prop = idp_from_PySequence_Fast(name, ob_seq_fast);
+ Py_DECREF(ob_seq_fast);
+ return prop;
+ }
+ else {
+ return NULL;
+ }
+ }
+}
+
+static IDProperty *idp_from_PyMapping(const char *name, PyObject *ob)
+{
+ IDProperty *prop;
+ IDPropertyTemplate val = {0};
+
+ PyObject *keys, *vals, *key, *pval;
+ int i, len;
+ /* yay! we get into recursive stuff now! */
+ keys = PyMapping_Keys(ob);
+ vals = PyMapping_Values(ob);
+
+ /* we allocate the group first; if we hit any invalid data,
+ * we can delete it easily enough.*/
+ prop = IDP_New(IDP_GROUP, &val, name);
+ len = PyMapping_Length(ob);
+ for (i = 0; i < len; i++) {
+ key = PySequence_GetItem(keys, i);
+ pval = PySequence_GetItem(vals, i);
+ if (BPy_IDProperty_Map_ValidateAndCreate(key, prop, pval) == false) {
+ IDP_FreeProperty(prop);
+ MEM_freeN(prop);
+ Py_XDECREF(keys);
+ Py_XDECREF(vals);
Py_XDECREF(key);
Py_XDECREF(pval);
+ /* error is already set */
+ return NULL;
}
- Py_XDECREF(keys);
- Py_XDECREF(vals);
+ Py_XDECREF(key);
+ Py_XDECREF(pval);
+ }
+ Py_XDECREF(keys);
+ Py_XDECREF(vals);
+ return prop;
+}
+
+static IDProperty *idp_from_DatablockPointer(const char *name, PyObject *ob, IDPropertyTemplate *val)
+{
+ pyrna_id_FromPyObject(ob, &val->id);
+ return IDP_New(IDP_ID, val, name);
+}
+
+static IDProperty *idp_from_PyObject(PyObject *name_obj, PyObject *ob)
+{
+ IDPropertyTemplate val = {0};
+ const char *name = idp_try_read_name(name_obj);
+ if (name == NULL) {
+ return NULL;
+ }
+
+ if (PyFloat_Check(ob)) {
+ return idp_from_PyFloat(name, ob);
+ }
+ else if (PyLong_Check(ob)) {
+ return idp_from_PyLong(name, ob);
+ }
+ else if (PyUnicode_Check(ob)) {
+ return idp_from_PyUnicode(name, ob);
+ }
+ else if (PyBytes_Check(ob)) {
+ return idp_from_PyBytes(name, ob);
+ }
+ else if (PySequence_Check(ob)) {
+ return idp_from_PySequence(name, ob);
+ }
+ else if (ob == Py_None || pyrna_id_CheckPyObject(ob)) {
+ return idp_from_DatablockPointer(name, ob, &val);
+ }
+ else if (PyMapping_Check(ob)) {
+ return idp_from_PyMapping(name, ob);
}
else {
PyErr_Format(PyExc_TypeError,
"invalid id-property type %.200s not supported",
Py_TYPE(ob)->tp_name);
+ return NULL;
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+/**
+ * \note group can be a pointer array or a group.
+ * assume we already checked key is a string.
+ *
+ * \return success.
+ */
+bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *name_obj, IDProperty *group, PyObject *ob)
+{
+ IDProperty *prop = idp_from_PyObject(name_obj, ob);
+ if (prop == NULL) {
return false;
}
if (group->type == IDP_IDPARRAY) {
IDP_AppendArray(group, prop);
- // IDP_FreeProperty(item); /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
+ /* IDP_AppendArray does a shallow copy (memcpy), only free memory */
MEM_freeN(prop);
}
else {
@@ -613,6 +751,8 @@ static PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop)
return idprop_py_from_idp_float(prop);
case IDP_DOUBLE:
return idprop_py_from_idp_double(prop);
+ case IDP_ID:
+ return idprop_py_from_idp_id(prop);
case IDP_ARRAY:
{
PyObject *seq = PyList_New(prop->len);
@@ -1197,7 +1337,7 @@ static int BPy_IDArray_SetItem(BPy_IDArray *self, int index, PyObject *value)
}
case IDP_INT:
{
- const int i = _PyLong_AsInt(value);
+ const int i = PyC_Long_AsI32(value);
if (i == -1 && PyErr_Occurred()) {
return -1;
}
@@ -1371,6 +1511,44 @@ static PyMappingMethods BPy_IDArray_AsMapping = {
(objobjargproc)BPy_IDArray_ass_subscript
};
+static int itemsize_by_idarray_type(int array_type)
+{
+ if (array_type == IDP_INT) return sizeof(int);
+ if (array_type == IDP_FLOAT) return sizeof(float);
+ if (array_type == IDP_DOUBLE) return sizeof(double);
+ return -1; /* should never happen */
+}
+
+static int BPy_IDArray_getbuffer(BPy_IDArray *self, Py_buffer *view, int flags)
+{
+ IDProperty *prop = self->prop;
+ int itemsize = itemsize_by_idarray_type(prop->subtype);
+ int length = itemsize * prop->len;
+
+ if (PyBuffer_FillInfo(view, (PyObject *)self, IDP_Array(prop), length, false, flags) == -1) {
+ return -1;
+ }
+
+ view->itemsize = itemsize;
+ view->format = (char *)idp_format_from_array_type(prop->subtype);
+
+ Py_ssize_t *shape = MEM_mallocN(sizeof(Py_ssize_t), __func__);
+ shape[0] = prop->len;
+ view->shape = shape;
+
+ return 0;
+}
+
+static void BPy_IDArray_releasebuffer(BPy_IDArray *UNUSED(self), Py_buffer *view)
+{
+ MEM_freeN(view->shape);
+}
+
+static PyBufferProcs BPy_IDArray_Buffer = {
+ (getbufferproc)BPy_IDArray_getbuffer,
+ (releasebufferproc)BPy_IDArray_releasebuffer,
+};
+
PyTypeObject BPy_IDArray_Type = {
PyVarObject_HEAD_INIT(NULL, 0)
@@ -1403,7 +1581,7 @@ PyTypeObject BPy_IDArray_Type = {
NULL, /* setattrofunc tp_setattro; */
/* Functions to access object as input/output buffer */
- NULL, /* PyBufferProcs *tp_as_buffer; */
+ &BPy_IDArray_Buffer, /* PyBufferProcs *tp_as_buffer; */
/*** Flags to define presence of optional/expanded features ***/
Py_TPFLAGS_DEFAULT, /* long tp_flags; */
diff --git a/source/blender/python/generic/py_capi_utils.c b/source/blender/python/generic/py_capi_utils.c
index 7b2d58a1268..6f265b2ae87 100644
--- a/source/blender/python/generic/py_capi_utils.c
+++ b/source/blender/python/generic/py_capi_utils.c
@@ -38,6 +38,8 @@
#include "python_utildefines.h"
+#include "BLI_string.h"
+
#ifndef MATH_STANDALONE
/* only for BLI_strncpy_wchar_from_utf8, should replace with py funcs but too late in release now */
#include "BLI_string_utf8.h"
@@ -85,7 +87,7 @@ int PyC_AsArray_FAST(
/* could use is_double for 'long int' but no use now */
int *array_int = array;
for (i = 0; i < length; i++) {
- array_int[i] = PyLong_AsLong(value_fast_items[i]);
+ array_int[i] = PyC_Long_AsI32(value_fast_items[i]);
}
}
else if (type == &PyBool_Type) {
@@ -127,54 +129,61 @@ int PyC_AsArray(
return ret;
}
+/* -------------------------------------------------------------------- */
+/** \name Typed Tuple Packing
+ *
+ * \note See #PyC_Tuple_Pack_* macros that take multiple arguments.
+ *
+ * \{ */
+
/* array utility function */
-PyObject *PyC_FromArray(const void *array, int length, const PyTypeObject *type,
- const bool is_double, const char *error_prefix)
+PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len)
{
- PyObject *tuple;
- int i;
-
- tuple = PyTuple_New(length);
-
- /* for each type */
- if (type == &PyFloat_Type) {
- if (is_double) {
- const double *array_double = array;
- for (i = 0; i < length; ++i) {
- PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array_double[i]));
- }
- }
- else {
- const float *array_float = array;
- for (i = 0; i < length; ++i) {
- PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array_float[i]));
- }
- }
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
}
- else if (type == &PyLong_Type) {
- /* could use is_double for 'long int' but no use now */
- const int *array_int = array;
- for (i = 0; i < length; ++i) {
- PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array_int[i]));
- }
+ return tuple;
+}
+
+PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len)
+{
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyFloat_FromDouble(array[i]));
}
- else if (type == &PyBool_Type) {
- const int *array_bool = array;
- for (i = 0; i < length; ++i) {
- PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array_bool[i]));
- }
+ return tuple;
+}
+
+PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len)
+{
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyLong_FromLong(array[i]));
}
- else {
- Py_DECREF(tuple);
- PyErr_Format(PyExc_TypeError,
- "%s: internal error %s is invalid",
- error_prefix, type->tp_name);
- return NULL;
+ return tuple;
+}
+
+PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len)
+{
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
}
+ return tuple;
+}
+PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len)
+{
+ PyObject *tuple = PyTuple_New(len);
+ for (uint i = 0; i < len; i++) {
+ PyTuple_SET_ITEM(tuple, i, PyBool_FromLong(array[i]));
+ }
return tuple;
}
+/** \} */
+
/**
* Caller needs to ensure tuple is uninitialized.
* Handy for filling a tuple with None for eg.
@@ -203,6 +212,8 @@ void PyC_List_Fill(PyObject *list, PyObject *value)
/**
* Use with PyArg_ParseTuple's "O&" formatting.
+ *
+ * \see #PyC_Long_AsBool for a similar function to use outside of argument parsing.
*/
int PyC_ParseBool(PyObject *o, void *p)
{
@@ -225,22 +236,49 @@ int PyC_ParseBool(PyObject *o, void *p)
/* for debugging */
void PyC_ObSpit(const char *name, PyObject *var)
{
+ const char *null_str = "<null>";
fprintf(stderr, "<%s> : ", name);
if (var == NULL) {
- fprintf(stderr, "<NIL>");
+ fprintf(stderr, "%s\n", null_str);
}
else {
PyObject_Print(var, stderr, 0);
- fprintf(stderr, " ref:%d ", (int)var->ob_refcnt);
- fprintf(stderr, " ptr:%p", (void *)var);
-
- fprintf(stderr, " type:");
- if (Py_TYPE(var))
- fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
- else
- fprintf(stderr, "<NIL>");
+ const PyTypeObject *type = Py_TYPE(var);
+ fprintf(stderr,
+ " ref:%d, ptr:%p, type: %s\n",
+ (int)var->ob_refcnt, (void *)var, type ? type->tp_name : null_str);
+ }
+}
+
+/**
+ * A version of #PyC_ObSpit that writes into a string (and doesn't take a name argument).
+ * Use for logging.
+ */
+void PyC_ObSpitStr(char *result, size_t result_len, PyObject *var)
+{
+ /* No name, creator of string can manage that. */
+ const char *null_str = "<null>";
+ if (var == NULL) {
+ BLI_snprintf(result, result_len, "%s", null_str);
+ }
+ else {
+ const PyTypeObject *type = Py_TYPE(var);
+ PyObject *var_str = PyObject_Repr(var);
+ if (var_str == NULL) {
+ /* We could print error here, but this may be used for generating errors - so don't for now. */
+ PyErr_Clear();
+ }
+ BLI_snprintf(
+ result, result_len,
+ " ref=%d, ptr=%p, type=%s, value=%.200s",
+ (int)var->ob_refcnt,
+ (void *)var,
+ type ? type->tp_name : null_str,
+ var_str ? _PyUnicode_AsString(var_str) : "<error>");
+ if (var_str != NULL) {
+ Py_DECREF(var_str);
+ }
}
- fprintf(stderr, "\n");
}
void PyC_LineSpit(void)
@@ -300,7 +338,14 @@ void PyC_FileAndNum(const char **filename, int *lineno)
if (mod_name) {
PyObject *mod = PyDict_GetItem(PyImport_GetModuleDict(), mod_name);
if (mod) {
- *filename = PyModule_GetFilename(mod);
+ PyObject *mod_file = PyModule_GetFilenameObject(mod);
+ if (mod_file) {
+ *filename = _PyUnicode_AsString(mod_name);
+ Py_DECREF(mod_file);
+ }
+ else {
+ PyErr_Clear();
+ }
}
/* unlikely, fallback */
@@ -405,6 +450,25 @@ PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *for
return NULL;
}
+/**
+ * Use for Python callbacks run directly from C,
+ * when we can't use normal methods of raising exceptions.
+ */
+void PyC_Err_PrintWithFunc(PyObject *py_func)
+{
+ /* since we return to C code we can't leave the error */
+ PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
+ PyErr_Print();
+ PyErr_Clear();
+
+ /* use py style error */
+ fprintf(stderr, "File \"%s\", line %d, in %s\n",
+ _PyUnicode_AsString(f_code->co_filename),
+ f_code->co_firstlineno,
+ _PyUnicode_AsString(((PyFunctionObject *)py_func)->func_name)
+ );
+}
+
/* returns the exception string as a new PyUnicode object, depends on external traceback module */
#if 0
@@ -918,11 +982,11 @@ char *PyC_FlagSet_AsString(PyC_FlagSet *item)
return cstring;
}
-int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *value)
+int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *r_value)
{
for ( ; item->identifier; item++) {
if (STREQ(item->identifier, identifier)) {
- *value = item->value;
+ *r_value = item->value;
return 1;
}
}
@@ -930,9 +994,9 @@ int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *
return 0;
}
-int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *value, const char *error_prefix)
+int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *r_value, const char *error_prefix)
{
- if (PyC_FlagSet_ValueFromID_int(item, identifier, value) == 0) {
+ if (PyC_FlagSet_ValueFromID_int(item, identifier, r_value) == 0) {
const char *enum_str = PyC_FlagSet_AsString(item);
PyErr_Format(PyExc_ValueError,
"%s: '%.200s' not found in (%s)",
@@ -1006,7 +1070,7 @@ PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag)
*
* \note it is caller's responsibility to acquire & release GIL!
*/
-bool PyC_RunString_AsNumber(const char *expr, double *value, const char *filename)
+bool PyC_RunString_AsNumber(const char *expr, const char *filename, double *r_value)
{
PyObject *py_dict, *mod, *retval;
bool ok = true;
@@ -1058,10 +1122,10 @@ bool PyC_RunString_AsNumber(const char *expr, double *value, const char *filenam
ok = false;
}
else if (!isfinite(val)) {
- *value = 0.0;
+ *r_value = 0.0;
}
else {
- *value = val;
+ *r_value = val;
}
}
@@ -1070,4 +1134,139 @@ bool PyC_RunString_AsNumber(const char *expr, double *value, const char *filenam
return ok;
}
+bool PyC_RunString_AsString(const char *expr, const char *filename, char **r_value)
+{
+ PyObject *py_dict, *retval;
+ bool ok = true;
+ PyObject *main_mod = NULL;
+
+ PyC_MainModule_Backup(&main_mod);
+
+ py_dict = PyC_DefaultNameSpace(filename);
+
+ retval = PyRun_String(expr, Py_eval_input, py_dict, py_dict);
+
+ if (retval == NULL) {
+ ok = false;
+ }
+ else {
+ const char *val;
+ Py_ssize_t val_len;
+
+ val = _PyUnicode_AsStringAndSize(retval, &val_len);
+ if (val == NULL && PyErr_Occurred()) {
+ ok = false;
+ }
+ else {
+ char *val_alloc = MEM_mallocN(val_len + 1, __func__);
+ memcpy(val_alloc, val, val_len + 1);
+ *r_value = val_alloc;
+ }
+
+ Py_DECREF(retval);
+ }
+
+ PyC_MainModule_Restore(main_mod);
+
+ return ok;
+}
+
#endif /* #ifndef MATH_STANDALONE */
+
+/* -------------------------------------------------------------------- */
+
+/** \name Int Conversion
+ *
+ * \note Python doesn't provide overflow checks for specific bit-widths.
+ *
+ * \{ */
+
+/* Compiler optimizes out redundant checks. */
+#ifdef __GNUC__
+# pragma warning(push)
+# pragma GCC diagnostic ignored "-Wtype-limits"
+#endif
+
+/**
+ * Don't use `bool` return type, so -1 can be used as an error value.
+ */
+int PyC_Long_AsBool(PyObject *value)
+{
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY((uint)test > 1)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Python number not a bool (0/1)");
+ return -1;
+ }
+ return test;
+}
+
+int8_t PyC_Long_AsI8(PyObject *value)
+{
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY(test < INT8_MIN || test > INT8_MAX)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C int8");
+ return -1;
+ }
+ return (int8_t)test;
+}
+
+int16_t PyC_Long_AsI16(PyObject *value)
+{
+ int test = _PyLong_AsInt(value);
+ if (UNLIKELY(test < INT16_MIN || test > INT16_MAX)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C int16");
+ return -1;
+ }
+ return (int16_t)test;
+}
+
+/* Inlined in header:
+ * PyC_Long_AsI32
+ * PyC_Long_AsI64
+ */
+
+uint8_t PyC_Long_AsU8(PyObject *value)
+{
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT8_MAX)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C uint8");
+ return (uint8_t)-1;
+ }
+ return (uint8_t)test;
+}
+
+uint16_t PyC_Long_AsU16(PyObject *value)
+{
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT16_MAX)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C uint16");
+ return (uint16_t)-1;
+ }
+ return (uint16_t)test;
+}
+
+uint32_t PyC_Long_AsU32(PyObject *value)
+{
+ ulong test = PyLong_AsUnsignedLong(value);
+ if (UNLIKELY(test > UINT32_MAX)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C uint32");
+ return (uint32_t)-1;
+ }
+ return (uint32_t)test;
+}
+
+/* Inlined in header:
+ * PyC_Long_AsU64
+ */
+
+#ifdef __GNUC__
+# pragma warning(pop)
+#endif
+
+/** \} */
diff --git a/source/blender/python/generic/py_capi_utils.h b/source/blender/python/generic/py_capi_utils.h
index 04cfc8801eb..fe7a046d99c 100644
--- a/source/blender/python/generic/py_capi_utils.h
+++ b/source/blender/python/generic/py_capi_utils.h
@@ -24,11 +24,14 @@
* \ingroup pygen
*/
-
#ifndef __PY_CAPI_UTILS_H__
#define __PY_CAPI_UTILS_H__
+#include "BLI_sys_types.h"
+#include "BLI_utildefines_variadic.h"
+
void PyC_ObSpit(const char *name, PyObject *var);
+void PyC_ObSpitStr(char *result, size_t result_len, PyObject *var);
void PyC_LineSpit(void);
void PyC_StackSpit(void);
PyObject * PyC_ExceptionBuffer(void);
@@ -36,6 +39,8 @@ PyObject * PyC_ExceptionBuffer_Simple(void);
PyObject * PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...);
PyObject * PyC_FrozenSetFromStrings(const char **strings);
PyObject * PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...);
+void PyC_Err_PrintWithFunc(PyObject *py_func);
+
void PyC_FileAndNum(const char **filename, int *lineno);
void PyC_FileAndNum_Safe(const char **filename, int *lineno); /* checks python is running */
int PyC_AsArray_FAST(
@@ -44,8 +49,24 @@ int PyC_AsArray_FAST(
int PyC_AsArray(
void *array, PyObject *value, const Py_ssize_t length,
const PyTypeObject *type, const bool is_double, const char *error_prefix);
-PyObject * PyC_FromArray(const void *array, int length, const PyTypeObject *type,
- const bool is_double, const char *error_prefix);
+
+PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len);
+PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len);
+PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len);
+PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len);
+PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len);
+
+#define PyC_Tuple_Pack_F32(...) \
+ PyC_Tuple_PackArray_F32(((const float []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define PyC_Tuple_Pack_F64(...) \
+ PyC_Tuple_PackArray_F64(((const double []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define PyC_Tuple_Pack_I32(...) \
+ PyC_Tuple_PackArray_I32(((const int []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define PyC_Tuple_Pack_I32FromBool(...) \
+ PyC_Tuple_PackArray_I32FromBool(((const int []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+#define PyC_Tuple_Pack_Bool(...) \
+ PyC_Tuple_PackArray_Bool(((const bool []){__VA_ARGS__}), VA_NARGS_COUNT(__VA_ARGS__))
+
void PyC_Tuple_Fill(PyObject *tuple, PyObject *value);
void PyC_List_Fill(PyObject *list, PyObject *value);
@@ -75,13 +96,36 @@ typedef struct PyC_FlagSet {
} PyC_FlagSet;
char *PyC_FlagSet_AsString(PyC_FlagSet *item);
-int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *value);
-int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *value, const char *error_prefix);
+int PyC_FlagSet_ValueFromID_int(PyC_FlagSet *item, const char *identifier, int *r_value);
+int PyC_FlagSet_ValueFromID(PyC_FlagSet *item, const char *identifier, int *r_value, const char *error_prefix);
int PyC_FlagSet_ToBitfield(PyC_FlagSet *items, PyObject *value, int *r_value, const char *error_prefix);
PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag);
-bool PyC_RunString_AsNumber(const char *expr, double *value, const char *filename);
+bool PyC_RunString_AsNumber(const char *expr, const char *filename, double *r_value);
+bool PyC_RunString_AsString(const char *expr, const char *filename, char **r_value);
int PyC_ParseBool(PyObject *o, void *p);
+
+/* Integer parsing (with overflow checks), -1 on error. */
+int PyC_Long_AsBool(PyObject *value);
+int8_t PyC_Long_AsI8(PyObject *value);
+int16_t PyC_Long_AsI16(PyObject *value);
+#if 0 /* inline */
+int32_t PyC_Long_AsI32(PyObject *value);
+int64_t PyC_Long_AsI64(PyObject *value);
+#endif
+
+uint8_t PyC_Long_AsU8(PyObject *value);
+uint16_t PyC_Long_AsU16(PyObject *value);
+uint32_t PyC_Long_AsU32(PyObject *value);
+#if 0 /* inline */
+uint64_t PyC_Long_AsU64(PyObject *value);
+#endif
+
+/* inline so type signatures match as expected */
+Py_LOCAL_INLINE(int32_t) PyC_Long_AsI32(PyObject *value) { return (int32_t)_PyLong_AsInt(value); }
+Py_LOCAL_INLINE(int64_t) PyC_Long_AsI64(PyObject *value) { return (int64_t)PyLong_AsLongLong(value); }
+Py_LOCAL_INLINE(uint64_t) PyC_Long_AsU64(PyObject *value) { return (uint64_t)PyLong_AsUnsignedLongLong(value); }
+
#endif /* __PY_CAPI_UTILS_H__ */
diff --git a/source/blender/python/generic/python_utildefines.h b/source/blender/python/generic/python_utildefines.h
index f7d3e7a8b4a..2d2d19c05f5 100644
--- a/source/blender/python/generic/python_utildefines.h
+++ b/source/blender/python/generic/python_utildefines.h
@@ -36,16 +36,16 @@ extern "C" {
PyTupleObject *op = (PyTupleObject *)op_arg; \
PyObject **ob_items = op->ob_item; \
CHECK_TYPE_ANY(op_arg, PyObject *, PyTupleObject *); \
- BLI_assert(_VA_NARGS_COUNT(__VA_ARGS__) == PyTuple_GET_SIZE(op)); \
+ BLI_assert(VA_NARGS_COUNT(__VA_ARGS__) == PyTuple_GET_SIZE(op)); \
ARRAY_SET_ITEMS(ob_items, __VA_ARGS__); \
} (void)0
/* wrap Py_INCREF & return the result,
* use sparingly to avoid comma operator or temp var assignment */
-BLI_INLINE PyObject *Py_INCREF_RET(PyObject *op) { Py_INCREF(op); return op; }
+Py_LOCAL_INLINE(PyObject *)Py_INCREF_RET(PyObject *op) { Py_INCREF(op); return op; }
/* append & transfer ownership to the list, avoids inline Py_DECREF all over (which is quite a large macro) */
-BLI_INLINE int PyList_APPEND(PyObject *op, PyObject *v)
+Py_LOCAL_INLINE(int) PyList_APPEND(PyObject *op, PyObject *v)
{
int ret = PyList_Append(op, v);
Py_DecRef(v);
diff --git a/source/blender/python/intern/CMakeLists.txt b/source/blender/python/intern/CMakeLists.txt
index 038c1e7eb10..ae16bd4a145 100644
--- a/source/blender/python/intern/CMakeLists.txt
+++ b/source/blender/python/intern/CMakeLists.txt
@@ -23,7 +23,7 @@
#
# ***** END GPL LICENSE BLOCK *****
-set(INC
+set(INC
..
../../blenkernel
../../blenlib
@@ -35,9 +35,10 @@ set(INC
../../makesdna
../../makesrna
../../windowmanager
- ../../../../intern/cycles/blender
- ../../../../intern/opencolorio
+ ../../../../intern/clog
../../../../intern/guardedalloc
+ ../../../../intern/opencolorio
+ ../../../../intern/cycles/blender
)
set(INC_SYS
@@ -45,8 +46,6 @@ set(INC_SYS
)
set(SRC
- gpu.c
- gpu_offscreen.c
bpy.c
bpy_app.c
bpy_app_alembic.c
@@ -55,9 +54,11 @@ set(SRC
bpy_app_handlers.c
bpy_app_ocio.c
bpy_app_oiio.c
+ bpy_app_opensubdiv.c
bpy_app_openvdb.c
bpy_app_sdl.c
bpy_app_translations.c
+ bpy_capi_utils.c
bpy_driver.c
bpy_interface.c
bpy_interface_atexit.c
@@ -75,12 +76,12 @@ set(SRC
bpy_rna_driver.c
bpy_rna_id_collection.c
bpy_traceback.c
- bpy_util.c
bpy_utils_previews.c
bpy_utils_units.c
+ gpu.c
+ gpu_offscreen.c
stubs.c
- gpu.h
bpy.h
bpy_app.h
bpy_app_alembic.h
@@ -89,9 +90,11 @@ set(SRC
bpy_app_handlers.h
bpy_app_ocio.h
bpy_app_oiio.h
+ bpy_app_opensubdiv.h
bpy_app_openvdb.h
bpy_app_sdl.h
bpy_app_translations.h
+ bpy_capi_utils.h
bpy_driver.h
bpy_intern_string.h
bpy_library.h
@@ -105,10 +108,11 @@ set(SRC
bpy_rna_driver.h
bpy_rna_id_collection.h
bpy_traceback.h
- bpy_util.h
bpy_utils_previews.h
bpy_utils_units.h
+ gpu.h
../BPY_extern.h
+ ../BPY_extern_clog.h
)
# only to check if buildinfo is available
@@ -145,10 +149,6 @@ if(WITH_CODEC_FFMPEG)
add_definitions(-DWITH_FFMPEG)
endif()
-if(WITH_CODEC_QUICKTIME)
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_CODEC_SNDFILE)
add_definitions(-DWITH_SNDFILE)
endif()
@@ -242,10 +242,6 @@ if(WITH_LIBMV)
add_definitions(-DWITH_LIBMV)
endif()
-if(WITH_MOD_BOOLEAN)
- add_definitions(-DWITH_MOD_BOOLEAN)
-endif()
-
if(WITH_MOD_FLUID)
add_definitions(-DWITH_MOD_FLUID)
endif()
@@ -295,6 +291,13 @@ if(WITH_OPENIMAGEIO)
)
endif()
+if(WITH_OPENSUBDIV)
+ add_definitions(-DWITH_OPENSUBDIV)
+ list(APPEND INC
+ ../../../../intern/opensubdiv
+ )
+endif()
+
if(WITH_PLAYER)
add_definitions(-DWITH_PLAYER)
endif()
diff --git a/source/blender/python/intern/bpy.c b/source/blender/python/intern/bpy.c
index 5bbfb4912e6..7150cc65942 100644
--- a/source/blender/python/intern/bpy.c
+++ b/source/blender/python/intern/bpy.c
@@ -42,7 +42,7 @@
#include "RNA_access.h"
#include "bpy.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_rna.h"
#include "bpy_app.h"
#include "bpy_rna_id_collection.h"
@@ -118,10 +118,11 @@ static PyObject *bpy_blend_paths(PyObject *UNUSED(self), PyObject *args, PyObjec
bool absolute = false;
bool packed = false;
bool local = false;
- static const char *kwlist[] = {"absolute", "packed", "local", NULL};
- if (!PyArg_ParseTupleAndKeywords(
- args, kw, "|O&O&O&:blend_paths", (char **)kwlist,
+ static const char *_keywords[] = {"absolute", "packed", "local", NULL};
+ static _PyArg_Parser _parser = {"|O&O&O&:blend_paths", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
PyC_ParseBool, &absolute,
PyC_ParseBool, &packed,
PyC_ParseBool, &local))
@@ -147,13 +148,18 @@ static PyObject *bpy_user_resource(PyObject *UNUSED(self), PyObject *args, PyObj
const char *type;
const char *subdir = NULL;
int folder_id;
- static const char *kwlist[] = {"type", "subdir", NULL};
const char *path;
- if (!PyArg_ParseTupleAndKeywords(args, kw, "s|s:user_resource", (char **)kwlist, &type, &subdir))
+ static const char *_keywords[] = {"type", "subdir", NULL};
+ static _PyArg_Parser _parser = {"s|s:user_resource", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &type, &subdir))
+ {
return NULL;
-
+ }
+
/* stupid string compare */
if (STREQ(type, "DATAFILES")) folder_id = BLENDER_USER_DATAFILES;
else if (STREQ(type, "CONFIG")) folder_id = BLENDER_USER_CONFIG;
@@ -191,12 +197,17 @@ static PyObject *bpy_resource_path(PyObject *UNUSED(self), PyObject *args, PyObj
{
const char *type;
int major = BLENDER_VERSION / 100, minor = BLENDER_VERSION % 100;
- static const char *kwlist[] = {"type", "major", "minor", NULL};
int folder_id;
const char *path;
- if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ii:resource_path", (char **)kwlist, &type, &major, &minor))
+ static const char *_keywords[] = {"type", "major", "minor", NULL};
+ static _PyArg_Parser _parser = {"s|ii:resource_path", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &type, &major, &minor))
+ {
return NULL;
+ }
/* stupid string compare */
if (STREQ(type, "USER")) folder_id = BLENDER_RESOURCE_PATH_USER;
diff --git a/source/blender/python/intern/bpy_app.c b/source/blender/python/intern/bpy_app.c
index ed7cec2f2d5..1e2ce372727 100644
--- a/source/blender/python/intern/bpy_app.c
+++ b/source/blender/python/intern/bpy_app.c
@@ -37,6 +37,7 @@
#include "bpy_app_ffmpeg.h"
#include "bpy_app_ocio.h"
#include "bpy_app_oiio.h"
+#include "bpy_app_opensubdiv.h"
#include "bpy_app_openvdb.h"
#include "bpy_app_sdl.h"
#include "bpy_app_build_options.h"
@@ -88,6 +89,7 @@ static PyStructSequence_Field app_info_fields[] = {
{(char *)"version_cycle", (char *)"The release status of this build alpha/beta/rc/release"},
{(char *)"binary_path", (char *)"The location of blenders executable, useful for utilities that spawn new instances"},
{(char *)"background", (char *)"Boolean, True when blender is running without a user interface (started with -b)"},
+ {(char *)"factory_startup", (char *)"Boolean, True when blender is running with --factory-startup)"},
/* buildinfo */
{(char *)"build_date", (char *)"The date this blender instance was built"},
@@ -109,6 +111,7 @@ static PyStructSequence_Field app_info_fields[] = {
{(char *)"ffmpeg", (char *)"FFmpeg library information backend"},
{(char *)"ocio", (char *)"OpenColorIO library information backend"},
{(char *)"oiio", (char *)"OpenImageIO library information backend"},
+ {(char *)"opensubdiv", (char *)"OpenSubdiv library information backend"},
{(char *)"openvdb", (char *)"OpenVDB library information backend"},
{(char *)"sdl", (char *)"SDL library information backend"},
{(char *)"build_options", (char *)"A set containing most important enabled optional build features"},
@@ -117,9 +120,21 @@ static PyStructSequence_Field app_info_fields[] = {
{NULL},
};
+PyDoc_STRVAR(bpy_app_doc,
+"This module contains application values that remain unchanged during runtime.\n"
+"\n"
+"Submodules:\n"
+"\n"
+".. toctree::\n"
+" :maxdepth: 1\n"
+"\n"
+" bpy.app.handlers.rst\n"
+" bpy.app.translations.rst\n"
+);
+
static PyStructSequence_Desc app_info_desc = {
(char *)"bpy.app", /* name */
- (char *)"This module contains application values that remain unchanged during runtime.", /* doc */
+ bpy_app_doc, /* doc */
app_info_fields, /* fields */
ARRAY_SIZE(app_info_fields) - 1
};
@@ -142,8 +157,7 @@ static PyObject *make_app_info(void)
#define SetObjItem(obj) \
PyStructSequence_SET_ITEM(app_info, pos++, obj)
- SetObjItem(Py_BuildValue("(iii)",
- BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
+ SetObjItem(PyC_Tuple_Pack_I32(BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
SetObjItem(PyUnicode_FromFormat("%d.%02d (sub %d)",
BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION));
@@ -151,6 +165,7 @@ static PyObject *make_app_info(void)
SetStrItem(STRINGIFY(BLENDER_VERSION_CYCLE));
SetStrItem(BKE_appdir_program_path());
SetObjItem(PyBool_FromLong(G.background));
+ SetObjItem(PyBool_FromLong(G.factory_startup));
/* build info, use bytes since we can't assume _any_ encoding:
* see patch [#30154] for issue */
@@ -188,6 +203,7 @@ static PyObject *make_app_info(void)
SetObjItem(BPY_app_ffmpeg_struct());
SetObjItem(BPY_app_ocio_struct());
SetObjItem(BPY_app_oiio_struct());
+ SetObjItem(BPY_app_opensubdiv_struct());
SetObjItem(BPY_app_openvdb_struct());
SetObjItem(BPY_app_sdl_struct());
SetObjItem(BPY_app_build_options_struct());
@@ -275,7 +291,7 @@ static PyObject *bpy_app_debug_value_get(PyObject *UNUSED(self), void *UNUSED(cl
static int bpy_app_debug_value_set(PyObject *UNUSED(self), PyObject *value, void *UNUSED(closure))
{
- int param = PyLong_AsLong(value);
+ int param = PyC_Long_AsI32(value);
if (param == -1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "bpy.app.debug_value can only be set to a whole number");
@@ -341,6 +357,11 @@ static PyGetSetDef bpy_app_getsets[] = {
{(char *)"debug_handlers", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_HANDLERS},
{(char *)"debug_wm", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_WM},
{(char *)"debug_depsgraph", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH},
+ {(char *)"debug_depsgraph_build", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_BUILD},
+ {(char *)"debug_depsgraph_eval", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_EVAL},
+ {(char *)"debug_depsgraph_tag", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_TAG},
+ {(char *)"debug_depsgraph_time", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_TIME},
+ {(char *)"debug_depsgraph_pretty", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_DEPSGRAPH_PRETTY},
{(char *)"debug_simdata", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_SIMDATA},
{(char *)"debug_gpumem", bpy_app_debug_get, bpy_app_debug_set, (char *)bpy_app_debug_doc, (void *)G_DEBUG_GPU_MEM},
diff --git a/source/blender/python/intern/bpy_app_alembic.c b/source/blender/python/intern/bpy_app_alembic.c
index 90e6a02b418..2a1a031a629 100644
--- a/source/blender/python/intern/bpy_app_alembic.c
+++ b/source/blender/python/intern/bpy_app_alembic.c
@@ -34,6 +34,8 @@
#include "bpy_app_alembic.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_ALEMBIC
# include "ABC_alembic.h"
#endif
@@ -79,11 +81,11 @@ static PyObject *make_alembic_info(void)
const int patch = curversion - ((curversion / 100 ) * 100);
SetObjItem(PyBool_FromLong(1));
- SetObjItem(Py_BuildValue("(iii)", major, minor, patch));
+ SetObjItem(PyC_Tuple_Pack_I32(major, minor, patch));
SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d", major, minor, patch));
#else
SetObjItem(PyBool_FromLong(0));
- SetObjItem(Py_BuildValue("(iii)", 0, 0, 0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
SetStrItem("Unknown");
#endif
diff --git a/source/blender/python/intern/bpy_app_build_options.c b/source/blender/python/intern/bpy_app_build_options.c
index a6b98567a9a..d5c325e4317 100644
--- a/source/blender/python/intern/bpy_app_build_options.c
+++ b/source/blender/python/intern/bpy_app_build_options.c
@@ -37,7 +37,6 @@ static PyStructSequence_Field app_builtopts_info_fields[] = {
{(char *)"bullet", NULL},
{(char *)"codec_avi", NULL},
{(char *)"codec_ffmpeg", NULL},
- {(char *)"codec_quicktime", NULL},
{(char *)"codec_sndfile", NULL},
{(char *)"compositor", NULL},
{(char *)"cycles", NULL},
@@ -59,7 +58,6 @@ static PyStructSequence_Field app_builtopts_info_fields[] = {
{(char *)"sdl_dynload", NULL},
{(char *)"jack", NULL},
{(char *)"libmv", NULL},
- {(char *)"mod_boolean", NULL},
{(char *)"mod_fluid", NULL},
{(char *)"mod_oceansim", NULL},
{(char *)"mod_remesh", NULL},
@@ -112,12 +110,6 @@ static PyObject *make_builtopts_info(void)
SetObjIncref(Py_False);
#endif
-#ifdef WITH_QUICKTIME
- SetObjIncref(Py_True);
-#else
- SetObjIncref(Py_False);
-#endif
-
#ifdef WITH_SNDFILE
SetObjIncref(Py_True);
#else
@@ -244,12 +236,6 @@ static PyObject *make_builtopts_info(void)
SetObjIncref(Py_False);
#endif
-#ifdef WITH_MOD_BOOLEAN
- SetObjIncref(Py_True);
-#else
- SetObjIncref(Py_False);
-#endif
-
#ifdef WITH_MOD_FLUID
SetObjIncref(Py_True);
#else
diff --git a/source/blender/python/intern/bpy_app_ffmpeg.c b/source/blender/python/intern/bpy_app_ffmpeg.c
index fd516e4547f..9f8355db72b 100644
--- a/source/blender/python/intern/bpy_app_ffmpeg.c
+++ b/source/blender/python/intern/bpy_app_ffmpeg.c
@@ -29,6 +29,8 @@
#include "bpy_app_ffmpeg.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_FFMPEG
#include <libavcodec/avcodec.h>
#include <libavdevice/avdevice.h>
@@ -91,8 +93,7 @@ static PyObject *make_ffmpeg_info(void)
#ifdef WITH_FFMPEG
# define FFMPEG_LIB_VERSION(lib) { \
curversion = lib ## _version(); \
- SetObjItem(Py_BuildValue("(iii)", \
- curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
+ SetObjItem(PyC_Tuple_Pack_I32(curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d", \
curversion >> 16, (curversion >> 8) % 256, curversion % 256)); \
} (void)0
diff --git a/source/blender/python/intern/bpy_app_handlers.c b/source/blender/python/intern/bpy_app_handlers.c
index 1cc2d6f1307..90aa22de5bf 100644
--- a/source/blender/python/intern/bpy_app_handlers.c
+++ b/source/blender/python/intern/bpy_app_handlers.c
@@ -59,8 +59,12 @@ static PyStructSequence_Field app_cb_info_fields[] = {
{(char *)"load_post", (char *)"on loading a new blend file (after)"},
{(char *)"save_pre", (char *)"on saving a blend file (before)"},
{(char *)"save_post", (char *)"on saving a blend file (after)"},
- {(char *)"scene_update_pre", (char *)"on updating the scenes data (before)"},
- {(char *)"scene_update_post", (char *)"on updating the scenes data (after)"},
+ {(char *)"scene_update_pre", (char *)"on every scene data update. Does not imply that anything changed in the "
+ "scene, just that the dependency graph is about to be reevaluated, and the "
+ "scene is about to be updated by Blender's animation system."},
+ {(char *)"scene_update_post", (char *)"on every scene data update. Does not imply that anything changed in the "
+ "scene, just that the dependency graph was reevaluated, and the scene was "
+ "possibly updated by Blender's animation system."},
{(char *)"game_pre", (char *)"on starting the game engine"},
{(char *)"game_post", (char *)"on ending the game engine"},
{(char *)"version_update", (char *)"on ending the versioning code"},
@@ -126,7 +130,7 @@ static PyObject *bpy_app_handlers_persistent_new(PyTypeObject *UNUSED(type), PyO
/* dummy type because decorators can't be PyCFunctions */
static PyTypeObject BPyPersistent_Type = {
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
PyVarObject_HEAD_INIT(NULL, 0)
#else
PyVarObject_HEAD_INIT(&PyType_Type, 0)
@@ -206,7 +210,7 @@ PyObject *BPY_app_handlers_struct(void)
{
PyObject *ret;
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
BPyPersistent_Type.ob_base.ob_base.ob_type = &PyType_Type;
#endif
diff --git a/source/blender/python/intern/bpy_app_ocio.c b/source/blender/python/intern/bpy_app_ocio.c
index 02e4044219a..9997e6b87f1 100644
--- a/source/blender/python/intern/bpy_app_ocio.c
+++ b/source/blender/python/intern/bpy_app_ocio.c
@@ -29,6 +29,8 @@
#include "bpy_app_ocio.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_OCIO
# include "ocio_capi.h"
#endif
@@ -74,13 +76,12 @@ static PyObject *make_ocio_info(void)
#ifdef WITH_OCIO
curversion = OCIO_getVersionHex();
SetObjItem(PyBool_FromLong(1));
- SetObjItem(Py_BuildValue("(iii)",
- curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
#else
SetObjItem(PyBool_FromLong(0));
- SetObjItem(Py_BuildValue("(iii)", 0, 0, 0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
SetStrItem("Unknown");
#endif
diff --git a/source/blender/python/intern/bpy_app_oiio.c b/source/blender/python/intern/bpy_app_oiio.c
index 60daf3ddd8b..e14b48ff7cf 100644
--- a/source/blender/python/intern/bpy_app_oiio.c
+++ b/source/blender/python/intern/bpy_app_oiio.c
@@ -29,6 +29,8 @@
#include "bpy_app_oiio.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_OPENIMAGEIO
# include "openimageio_api.h"
#endif
@@ -74,13 +76,12 @@ static PyObject *make_oiio_info(void)
#ifdef WITH_OPENIMAGEIO
curversion = OIIO_getVersionHex();
SetObjItem(PyBool_FromLong(1));
- SetObjItem(Py_BuildValue("(iii)",
- curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
curversion / 10000, (curversion / 100) % 100, curversion % 100));
#else
SetObjItem(PyBool_FromLong(0));
- SetObjItem(Py_BuildValue("(iii)", 0, 0, 0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
SetStrItem("Unknown");
#endif
diff --git a/source/blender/python/intern/bpy_app_opensubdiv.c b/source/blender/python/intern/bpy_app_opensubdiv.c
new file mode 100644
index 00000000000..096374794c9
--- /dev/null
+++ b/source/blender/python/intern/bpy_app_opensubdiv.c
@@ -0,0 +1,110 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Sergey Sharybin
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/python/intern/bpy_app_opensubdiv.c
+ * \ingroup pythonintern
+ */
+
+#include <Python.h>
+#include "BLI_utildefines.h"
+
+#include "bpy_app_opensubdiv.h"
+
+#include "../generic/py_capi_utils.h"
+
+#ifdef WITH_OPENSUBDIV
+# include "opensubdiv_capi.h"
+#endif
+
+static PyTypeObject BlenderAppOpenSubdivType;
+
+static PyStructSequence_Field app_opensubdiv_info_fields[] = {
+ {(char *)"supported", (char *)("Boolean, True when Blender is built with OpenSubdiv support")},
+ {(char *)("version"), (char *)("The OpenSubdiv version as a tuple of 3 numbers")},
+ {(char *)("version_string"), (char *)("The OpenSubdiv version formatted as a string")},
+ {NULL}
+};
+
+static PyStructSequence_Desc app_opensubdiv_info_desc = {
+ (char *)"bpy.app.opensubdiv", /* name */
+ (char *)"This module contains information about OpenSubdiv blender is linked against", /* doc */
+ app_opensubdiv_info_fields, /* fields */
+ ARRAY_SIZE(app_opensubdiv_info_fields) - 1
+};
+
+static PyObject *make_opensubdiv_info(void)
+{
+ PyObject *opensubdiv_info;
+ int pos = 0;
+
+ opensubdiv_info = PyStructSequence_New(&BlenderAppOpenSubdivType);
+ if (opensubdiv_info == NULL) {
+ return NULL;
+ }
+
+#ifndef WITH_OPENSUBDIV
+#define SetStrItem(str) \
+ PyStructSequence_SET_ITEM(opensubdiv_info, pos++, PyUnicode_FromString(str))
+#endif
+
+#define SetObjItem(obj) \
+ PyStructSequence_SET_ITEM(opensubdiv_info, pos++, obj)
+
+#ifdef WITH_OPENSUBDIV
+ int curversion = openSubdiv_getVersionHex();
+ SetObjItem(PyBool_FromLong(1));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion / 10000, (curversion / 100) % 100, curversion % 100));
+ SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
+ curversion / 10000, (curversion / 100) % 100, curversion % 100));
+#else
+ SetObjItem(PyBool_FromLong(0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
+ SetStrItem("Unknown");
+#endif
+
+ if (PyErr_Occurred()) {
+ Py_CLEAR(opensubdiv_info);
+ return NULL;
+ }
+
+#undef SetStrItem
+#undef SetObjItem
+
+ return opensubdiv_info;
+}
+
+PyObject *BPY_app_opensubdiv_struct(void)
+{
+ PyObject *ret;
+
+ PyStructSequence_InitType(&BlenderAppOpenSubdivType, &app_opensubdiv_info_desc);
+
+ ret = make_opensubdiv_info();
+
+ /* prevent user from creating new instances */
+ BlenderAppOpenSubdivType.tp_init = NULL;
+ BlenderAppOpenSubdivType.tp_new = NULL;
+ /* without this we can't do set(sys.modules) [#29635] */
+ BlenderAppOpenSubdivType.tp_hash = (hashfunc)_Py_HashPointer;
+
+ return ret;
+}
diff --git a/source/blender/python/intern/bpy_app_opensubdiv.h b/source/blender/python/intern/bpy_app_opensubdiv.h
new file mode 100644
index 00000000000..b1da218b168
--- /dev/null
+++ b/source/blender/python/intern/bpy_app_opensubdiv.h
@@ -0,0 +1,32 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * Contributor(s): Sergey Sharybin
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/python/intern/bpy_app_opensubdiv.h
+ * \ingroup pythonintern
+ */
+
+#ifndef __BPY_APP_OPENSUBDIV_H__
+#define __BPY_APP_OPENSUBDIV_H__
+
+PyObject *BPY_app_opensubdiv_struct(void);
+
+#endif /* __BPY_APP_OPENSUBDIV_H__ */
diff --git a/source/blender/python/intern/bpy_app_openvdb.c b/source/blender/python/intern/bpy_app_openvdb.c
index 8a24aaf0555..0b385206d7b 100644
--- a/source/blender/python/intern/bpy_app_openvdb.c
+++ b/source/blender/python/intern/bpy_app_openvdb.c
@@ -34,6 +34,8 @@
#include "bpy_app_openvdb.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_OPENVDB
# include "openvdb_capi.h"
#endif
@@ -79,13 +81,12 @@ static PyObject *make_openvdb_info(void)
#ifdef WITH_OPENVDB
curversion = OpenVDB_getVersionHex();
SetObjItem(PyBool_FromLong(1));
- SetObjItem(Py_BuildValue("(iii)",
- curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
+ SetObjItem(PyC_Tuple_Pack_I32(curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
SetObjItem(PyUnicode_FromFormat("%2d, %2d, %2d",
curversion >> 24, (curversion >> 16) % 256, (curversion >> 8) % 256));
#else
SetObjItem(PyBool_FromLong(0));
- SetObjItem(Py_BuildValue("(iii)", 0, 0, 0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
SetStrItem("Unknown");
#endif
diff --git a/source/blender/python/intern/bpy_app_sdl.c b/source/blender/python/intern/bpy_app_sdl.c
index 2f4d8e6c325..816ad2833cc 100644
--- a/source/blender/python/intern/bpy_app_sdl.c
+++ b/source/blender/python/intern/bpy_app_sdl.c
@@ -29,6 +29,8 @@
#include "bpy_app_sdl.h"
+#include "../generic/py_capi_utils.h"
+
#ifdef WITH_SDL
/* SDL force defines __SSE__ and __SSE2__ flags, which generates warnings
* because we pass those defines via command line as well. For until there's
@@ -56,7 +58,7 @@ static PyStructSequence_Field app_sdl_info_fields[] = {
{(char *)"available", (char *)("Boolean, True when SDL is available. This is False when "
"either *supported* is False, or *dynload* is True and "
"Blender cannot find the correct library.")},
- {NULL}
+ {NULL}
};
static PyStructSequence_Desc app_sdl_info_desc = {
@@ -103,7 +105,7 @@ static PyObject *make_sdl_info(void)
# endif
# endif
- SetObjItem(Py_BuildValue("(iii)", version.major, version.minor, version.patch));
+ SetObjItem(PyC_Tuple_Pack_I32(version.major, version.minor, version.patch));
if (sdl_available) {
SetObjItem(PyUnicode_FromFormat("%d.%d.%d", version.major, version.minor, version.patch));
}
@@ -114,7 +116,7 @@ static PyObject *make_sdl_info(void)
#else // WITH_SDL=OFF
SetObjItem(PyBool_FromLong(0));
- SetObjItem(Py_BuildValue("(iii)", 0, 0, 0));
+ SetObjItem(PyC_Tuple_Pack_I32(0, 0, 0));
SetStrItem("Unknown");
SetObjItem(PyBool_FromLong(0));
#endif
diff --git a/source/blender/python/intern/bpy_util.c b/source/blender/python/intern/bpy_capi_utils.c
index 2b8ad6ccb90..7232e4ea821 100644
--- a/source/blender/python/intern/bpy_util.c
+++ b/source/blender/python/intern/bpy_capi_utils.c
@@ -20,11 +20,11 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/python/intern/bpy_util.c
+/** \file blender/python/intern/bpy_capi_utils.c
* \ingroup pythonintern
*
- * This file contains blender/python utility functions for the api's internal
- * use (unrelated to 'bpy.utils')
+ * This file contains Blender/Python utility functions to help implementing API's.
+ * This is not related to a particular module.
*/
#include <Python.h>
@@ -32,7 +32,7 @@
#include "BLI_utildefines.h"
#include "BLI_dynstr.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "MEM_guardedalloc.h"
@@ -47,10 +47,10 @@ static bContext *__py_context = NULL;
bContext *BPy_GetContext(void) { return __py_context; }
void BPy_SetContext(bContext *C) { __py_context = C; }
-char *BPy_enum_as_string(EnumPropertyItem *item)
+char *BPy_enum_as_string(const EnumPropertyItem *item)
{
DynStr *dynstr = BLI_dynstr_new();
- EnumPropertyItem *e;
+ const EnumPropertyItem *e;
char *cstring;
for (e = item; item->identifier; item++) {
diff --git a/source/blender/python/intern/bpy_util.h b/source/blender/python/intern/bpy_capi_utils.h
index 63cb7920bd1..abb37d6e30c 100644
--- a/source/blender/python/intern/bpy_util.h
+++ b/source/blender/python/intern/bpy_capi_utils.h
@@ -20,21 +20,21 @@
* ***** END GPL LICENSE BLOCK *****
*/
-/** \file blender/python/intern/bpy_util.h
+/** \file blender/python/intern/bpy_capi_utils.h
* \ingroup pythonintern
*/
-#ifndef __BPY_UTIL_H__
-#define __BPY_UTIL_H__
+#ifndef __BPY_CAPI_UTILS_H__
+#define __BPY_CAPI_UTILS_H__
-#if PY_VERSION_HEX < 0x03050000
-# error "Python 3.5 or greater is required, you'll need to update your python."
+#if PY_VERSION_HEX < 0x03060000
+# error "Python 3.6 or greater is required, you'll need to update your python."
#endif
struct EnumPropertyItem;
struct ReportList;
-char *BPy_enum_as_string(struct EnumPropertyItem *item);
+char *BPy_enum_as_string(const struct EnumPropertyItem *item);
#define BLANK_PYTHON_TYPE {PyVarObject_HEAD_INIT(NULL, 0) NULL}
@@ -50,4 +50,4 @@ void BPy_SetContext(struct bContext *C);
extern void bpy_context_set(struct bContext *C, PyGILState_STATE *gilstate);
extern void bpy_context_clear(struct bContext *C, PyGILState_STATE *gilstate);
-#endif /* __BPY_UTIL_H__ */
+#endif /* __BPY_CAPI_UTILS_H__ */
diff --git a/source/blender/python/intern/bpy_interface.c b/source/blender/python/intern/bpy_interface.c
index 311f621e13b..99f87c61c5a 100644
--- a/source/blender/python/intern/bpy_interface.c
+++ b/source/blender/python/intern/bpy_interface.c
@@ -33,6 +33,8 @@
#include "MEM_guardedalloc.h"
+#include "CLG_log.h"
+
#include "BLI_utildefines.h"
#include "BLI_path_util.h"
#include "BLI_fileops.h"
@@ -47,7 +49,7 @@
#include "gpu.h"
#include "bpy_rna.h"
#include "bpy_path.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_traceback.h"
#include "bpy_intern_string.h"
@@ -75,6 +77,9 @@
#include "../bmesh/bmesh_py_api.h"
#include "../mathutils/mathutils.h"
+/* Logging types to use anywhere in the Python modules. */
+CLG_LOGREF_DECLARE_GLOBAL(BPY_LOG_CONTEXT, "bpy.context");
+CLG_LOGREF_DECLARE_GLOBAL(BPY_LOG_RNA, "bpy.rna");
/* for internal use, when starting and ending python scripts */
@@ -480,11 +485,20 @@ static bool python_script_exec(
* object, but as written in the Python/C API Ref Manual, chapter 2,
* 'FILE structs for different C libraries can be different and
* incompatible'.
- * So now we load the script file data to a buffer */
+ * So now we load the script file data to a buffer.
+ *
+ * Note on use of 'globals()', it's important not copy the dictionary because
+ * tools may inspect 'sys.modules["__main__"]' for variables defined in the code
+ * where using a copy of 'globals()' causes code execution
+ * to leave the main namespace untouched. see: T51444
+ *
+ * This leaves us with the problem of variables being included,
+ * currently this is worked around using 'dict.__del__' it's ugly but works.
+ */
{
const char *pystring =
- "ns = globals().copy()\n"
- "with open(__file__, 'rb') as f: exec(compile(f.read(), __file__, 'exec'), ns)";
+ "with open(__file__, 'rb') as f:"
+ "exec(compile(f.read(), __file__, 'exec'), globals().__delitem__('f') or globals())";
fclose(fp);
@@ -572,21 +586,58 @@ void BPY_DECREF_RNA_INVALIDATE(void *pyob_ptr)
/**
* \return success
*/
-bool BPY_execute_string_as_number(bContext *C, const char *expr, double *value, const bool verbose)
+bool BPY_execute_string_as_number(bContext *C, const char *expr, const bool verbose, double *r_value)
+{
+ PyGILState_STATE gilstate;
+ bool ok = true;
+
+ if (!r_value || !expr) {
+ return -1;
+ }
+
+ if (expr[0] == '\0') {
+ *r_value = 0.0;
+ return ok;
+ }
+
+ bpy_context_set(C, &gilstate);
+
+ ok = PyC_RunString_AsNumber(expr, "<blender button>", r_value);
+
+ if (ok == false) {
+ if (verbose) {
+ BPy_errors_to_report_ex(CTX_wm_reports(C), false, false);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
+
+ bpy_context_clear(C, &gilstate);
+
+ return ok;
+}
+
+/**
+ * \return success
+ */
+bool BPY_execute_string_as_string(bContext *C, const char *expr, const bool verbose, char **r_value)
{
PyGILState_STATE gilstate;
bool ok = true;
- if (!value || !expr) return -1;
+ if (!r_value || !expr) {
+ return -1;
+ }
if (expr[0] == '\0') {
- *value = 0.0;
+ *r_value = NULL;
return ok;
}
bpy_context_set(C, &gilstate);
- ok = PyC_RunString_AsNumber(expr, value, "<blender button>");
+ ok = PyC_RunString_AsString(expr, "<blender button>", r_value);
if (ok == false) {
if (verbose) {
@@ -602,6 +653,7 @@ bool BPY_execute_string_as_number(bContext *C, const char *expr, double *value,
return ok;
}
+
bool BPY_execute_string_ex(bContext *C, const char *expr, bool use_eval)
{
PyGILState_STATE gilstate;
@@ -753,8 +805,9 @@ int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *
CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
}
else {
- printf("PyContext: '%s' list item not a valid type in sequece type '%s'\n",
- member, Py_TYPE(item)->tp_name);
+ CLOG_INFO(BPY_LOG_CONTEXT, 1,
+ "'%s' list item not a valid type in sequence type '%s'",
+ member, Py_TYPE(item)->tp_name);
}
}
@@ -766,16 +819,14 @@ int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *
if (done == false) {
if (item) {
- printf("PyContext '%s' not a valid type\n", member);
+ CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not a valid type", member);
}
else {
- printf("PyContext '%s' not found\n", member);
+ CLOG_INFO(BPY_LOG_CONTEXT, 1, "'%s' not found\n", member);
}
}
else {
- if (G.debug & G_DEBUG_PYTHON) {
- printf("PyContext '%s' found\n", member);
- }
+ CLOG_INFO(BPY_LOG_CONTEXT, 2, "'%s' found", member);
}
if (use_gil)
@@ -822,6 +873,7 @@ static void bpy_module_delay_init(PyObject *bpy_proxy)
BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
BLI_path_cwd(filename_abs, sizeof(filename_abs));
+ Py_DECREF(filename_obj);
argv[0] = filename_abs;
argv[1] = NULL;
diff --git a/source/blender/python/intern/bpy_interface_atexit.c b/source/blender/python/intern/bpy_interface_atexit.c
index 5c4f6ba327c..3608a26d113 100644
--- a/source/blender/python/intern/bpy_interface_atexit.c
+++ b/source/blender/python/intern/bpy_interface_atexit.c
@@ -33,7 +33,7 @@
#include "BLI_utildefines.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy.h" /* own include */
#include "WM_api.h"
diff --git a/source/blender/python/intern/bpy_library_load.c b/source/blender/python/intern/bpy_library_load.c
index 15f3c665fcf..20226ffe6a3 100644
--- a/source/blender/python/intern/bpy_library_load.c
+++ b/source/blender/python/intern/bpy_library_load.c
@@ -48,7 +48,7 @@
#include "DNA_space_types.h" /* FILE_LINK, FILE_RELPATH */
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_library.h"
#include "../generic/py_capi_utils.h"
@@ -73,7 +73,7 @@ typedef struct {
} BPy_Library;
static PyObject *bpy_lib_load(PyObject *self, PyObject *args, PyObject *kwds);
-static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *args);
+static PyObject *bpy_lib_enter(BPy_Library *self);
static PyObject *bpy_lib_exit(BPy_Library *self, PyObject *args);
static PyObject *bpy_lib_dir(BPy_Library *self);
@@ -183,17 +183,17 @@ PyDoc_STRVAR(bpy_lib_load_doc,
" :arg relative: When True the path is stored relative to the open blend file.\n"
" :type relative: bool\n"
);
-static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
+static PyObject *bpy_lib_load(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"filepath", "link", "relative", NULL};
Main *bmain = CTX_data_main(BPy_GetContext());
BPy_Library *ret;
const char *filename = NULL;
bool is_rel = false, is_link = false;
- if (!PyArg_ParseTupleAndKeywords(
- args, kwds,
- "s|O&O&:load", (char **)kwlist,
+ static const char *_keywords[] = {"filepath", "link", "relative", NULL};
+ static _PyArg_Parser _parser = {"s|O&O&:load", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
&filename,
PyC_ParseBool, &is_link,
PyC_ParseBool, &is_rel))
@@ -237,7 +237,7 @@ static PyObject *_bpy_names(BPy_Library *self, int blocktype)
return list;
}
-static PyObject *bpy_lib_enter(BPy_Library *self, PyObject *UNUSED(args))
+static PyObject *bpy_lib_enter(BPy_Library *self)
{
PyObject *ret;
BPy_Library *self_from;
diff --git a/source/blender/python/intern/bpy_library_write.c b/source/blender/python/intern/bpy_library_write.c
index bf91253141a..9ca6092eab3 100644
--- a/source/blender/python/intern/bpy_library_write.c
+++ b/source/blender/python/intern/bpy_library_write.c
@@ -43,7 +43,7 @@
#include "RNA_types.h"
#include "bpy_rna.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_library.h"
#include "../generic/py_capi_utils.h"
@@ -69,24 +69,23 @@ PyDoc_STRVAR(bpy_lib_write_doc,
" :arg compress: When True, write a compressed blend file.\n"
" :type compress: bool\n"
);
-static PyObject *bpy_lib_write(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
+static PyObject *bpy_lib_write(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {
- "filepath", "datablocks",
- /* optional */
- "relative_remap", "fake_user", "compress",
- NULL,
- };
-
/* args */
const char *filepath;
char filepath_abs[FILE_MAX];
PyObject *datablocks = NULL;
bool use_relative_remap = false, use_fake_user = false, use_compress = false;
- if (!PyArg_ParseTupleAndKeywords(
- args, kwds,
- "sO!|$O&O&O&:write", (char **)kwlist,
+ static const char *_keywords[] = {
+ "filepath", "datablocks",
+ /* optional */
+ "relative_remap", "fake_user", "compress",
+ NULL,
+ };
+ static _PyArg_Parser _parser = {"sO!|$O&O&O&:write", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
&filepath,
&PySet_Type, &datablocks,
PyC_ParseBool, &use_relative_remap,
diff --git a/source/blender/python/intern/bpy_operator.c b/source/blender/python/intern/bpy_operator.c
index bd3e5736c6c..0cadbc30a9f 100644
--- a/source/blender/python/intern/bpy_operator.c
+++ b/source/blender/python/intern/bpy_operator.c
@@ -43,7 +43,7 @@
#include "bpy_operator.h"
#include "bpy_operator_wrap.h"
#include "bpy_rna.h" /* for setting arg props only - pyrna_py_to_prop() */
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "../generic/bpy_internal_import.h"
#include "../generic/py_capi_utils.h"
#include "../generic/python_utildefines.h"
@@ -384,7 +384,7 @@ static PyObject *pyop_dir(PyObject *UNUSED(self))
int i;
WM_operatortype_iter(&iter);
- list = PyList_New(BLI_ghash_size(iter.gh));
+ list = PyList_New(BLI_ghash_len(iter.gh));
for (i = 0; !BLI_ghashIterator_done(&iter); BLI_ghashIterator_step(&iter), i++) {
wmOperatorType *ot = BLI_ghashIterator_getValue(&iter);
@@ -450,7 +450,7 @@ static PyObject *pyop_getinstance(PyObject *UNUSED(self), PyObject *value)
op = PyMem_MALLOC(sizeof(wmOperator));
memset(op, 0, sizeof(wmOperator));
#endif
- BLI_strncpy(op->idname, op->idname, sizeof(op->idname)); /* in case its needed */
+ BLI_strncpy(op->idname, ot->idname, sizeof(op->idname)); /* in case its needed */
op->type = ot;
RNA_pointer_create(NULL, &RNA_Operator, op, &ptr);
diff --git a/source/blender/python/intern/bpy_operator_wrap.c b/source/blender/python/intern/bpy_operator_wrap.c
index 11e27ca3e3c..9d57adca946 100644
--- a/source/blender/python/intern/bpy_operator_wrap.c
+++ b/source/blender/python/intern/bpy_operator_wrap.c
@@ -48,10 +48,12 @@ static void operator_properties_init(wmOperatorType *ot)
PyTypeObject *py_class = ot->ext.data;
RNA_struct_blender_type_set(ot->ext.srna, ot);
- /* only call this so pyrna_deferred_register_class gives a useful error
- * WM_operatortype_append_ptr will call RNA_def_struct_identifier
- * later */
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ /* Only call this so pyrna_deferred_register_class gives a useful error
+ * WM_operatortype_append_ptr will call RNA_def_struct_identifier later.
+ *
+ * Note the 'no_struct_map' function is used since the actual struct name is already used by the operator.
+ */
+ RNA_def_struct_identifier_no_struct_map(ot->srna, ot->idname);
if (pyrna_deferred_register_class(ot->srna, py_class) != 0) {
PyErr_Print(); /* failed to register operator props */
@@ -118,7 +120,7 @@ static void operator_properties_init(wmOperatorType *ot)
}
-void operator_wrapper(wmOperatorType *ot, void *userdata)
+void BPY_RNA_operator_wrapper(wmOperatorType *ot, void *userdata)
{
/* take care not to overwrite anything set in
* WM_operatortype_append_ptr before opfunc() is called */
@@ -134,7 +136,7 @@ void operator_wrapper(wmOperatorType *ot, void *userdata)
operator_properties_init(ot);
}
-void macro_wrapper(wmOperatorType *ot, void *userdata)
+void BPY_RNA_operator_macro_wrapper(wmOperatorType *ot, void *userdata)
{
wmOperatorType *data = (wmOperatorType *)userdata;
diff --git a/source/blender/python/intern/bpy_operator_wrap.h b/source/blender/python/intern/bpy_operator_wrap.h
index 05a566a1485..0828c58e2bd 100644
--- a/source/blender/python/intern/bpy_operator_wrap.h
+++ b/source/blender/python/intern/bpy_operator_wrap.h
@@ -33,7 +33,7 @@ struct wmOperatorType;
PyObject *PYOP_wrap_macro_define(PyObject *self, PyObject *args);
/* exposed to rna/wm api */
-void operator_wrapper(struct wmOperatorType *ot, void *userdata);
-void macro_wrapper(struct wmOperatorType *ot, void *userdata);
+void BPY_RNA_operator_wrapper(struct wmOperatorType *ot, void *userdata);
+void BPY_RNA_operator_macro_wrapper(struct wmOperatorType *ot, void *userdata);
#endif
diff --git a/source/blender/python/intern/bpy_props.c b/source/blender/python/intern/bpy_props.c
index e61018865ab..d3eddff4b9a 100644
--- a/source/blender/python/intern/bpy_props.c
+++ b/source/blender/python/intern/bpy_props.c
@@ -37,7 +37,7 @@
#include "bpy_props.h"
#include "bpy_rna.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "BKE_idprop.h"
@@ -50,15 +50,17 @@
#include "../generic/py_capi_utils.h"
/* initial definition of callback slots we'll probably have more than 1 */
-#define BPY_DATA_CB_SLOT_SIZE 3
-
-#define BPY_DATA_CB_SLOT_UPDATE 0
-#define BPY_DATA_CB_SLOT_GET 1
-#define BPY_DATA_CB_SLOT_SET 2
+enum {
+ BPY_DATA_CB_SLOT_UPDATE = 0,
+ BPY_DATA_CB_SLOT_GET = 1,
+ BPY_DATA_CB_SLOT_SET = 2,
+ BPY_DATA_CB_SLOT_POLL = 3,
+ BPY_DATA_CB_SLOT_SIZE = 4,
+};
extern BPy_StructRNA *bpy_context_module;
-static EnumPropertyItem property_flag_items[] = {
+static const EnumPropertyItem property_flag_items[] = {
{PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
{PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
{PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
@@ -72,7 +74,7 @@ static EnumPropertyItem property_flag_items[] = {
"'TEXTEDIT_UPDATE'].\n" \
" :type options: set\n" \
-static EnumPropertyItem property_flag_enum_items[] = {
+static const EnumPropertyItem property_flag_enum_items[] = {
{PROP_HIDDEN, "HIDDEN", 0, "Hidden", ""},
{PROP_SKIP_SAVE, "SKIP_SAVE", 0, "Skip Save", ""},
{PROP_ANIMATABLE, "ANIMATABLE", 0, "Animatable", ""},
@@ -88,7 +90,7 @@ static EnumPropertyItem property_flag_enum_items[] = {
/* XXX Keep in sync with rna_rna.c's rna_enum_property_subtype_items ???
* Currently it is not...
*/
-static EnumPropertyItem property_subtype_string_items[] = {
+static const EnumPropertyItem property_subtype_string_items[] = {
{PROP_FILEPATH, "FILE_PATH", 0, "File Path", ""},
{PROP_DIRPATH, "DIR_PATH", 0, "Directory Path", ""},
{PROP_FILENAME, "FILE_NAME", 0, "Filename", ""},
@@ -102,7 +104,7 @@ static EnumPropertyItem property_subtype_string_items[] = {
" :arg subtype: Enumerator in ['FILE_PATH', 'DIR_PATH', 'FILE_NAME', 'BYTE_STRING', 'PASSWORD', 'NONE'].\n" \
" :type subtype: string\n" \
-static EnumPropertyItem property_subtype_number_items[] = {
+static const EnumPropertyItem property_subtype_number_items[] = {
{PROP_PIXEL, "PIXEL", 0, "Pixel", ""},
{PROP_UNSIGNED, "UNSIGNED", 0, "Unsigned", ""},
{PROP_PERCENTAGE, "PERCENTAGE", 0, "Percentage", ""},
@@ -118,7 +120,7 @@ static EnumPropertyItem property_subtype_number_items[] = {
" :arg subtype: Enumerator in ['PIXEL', 'UNSIGNED', 'PERCENTAGE', 'FACTOR', 'ANGLE', 'TIME', 'DISTANCE', 'NONE'].\n" \
" :type subtype: string\n" \
-static EnumPropertyItem property_subtype_array_items[] = {
+static const EnumPropertyItem property_subtype_array_items[] = {
{PROP_COLOR, "COLOR", 0, "Color", ""},
{PROP_TRANSLATION, "TRANSLATION", 0, "Translation", ""},
{PROP_DIRECTION, "DIRECTION", 0, "Direction", ""},
@@ -178,22 +180,6 @@ static PyObject *pyrna_struct_as_instance(PointerRNA *ptr)
return self;
}
-/* could be moved into bpy_utils */
-static void printf_func_error(PyObject *py_func)
-{
- /* since we return to C code we can't leave the error */
- PyCodeObject *f_code = (PyCodeObject *)PyFunction_GET_CODE(py_func);
- PyErr_Print();
- PyErr_Clear();
-
- /* use py style error */
- fprintf(stderr, "File \"%s\", line %d, in %s\n",
- _PyUnicode_AsString(f_code->co_filename),
- f_code->co_firstlineno,
- _PyUnicode_AsString(((PyFunctionObject *)py_func)->func_name)
- );
-}
-
static void bpy_prop_assign_flag(PropertyRNA *prop, const int flag)
{
const int flag_mask = ((PROP_ANIMATABLE) & ~flag);
@@ -230,7 +216,7 @@ static PyObject *bpy_prop_deferred_return(PyObject *func, PyObject *kw)
static void bpy_prop_update_cb(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop)
{
PyGILState_STATE gilstate;
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -259,12 +245,12 @@ static void bpy_prop_update_cb(struct bContext *C, struct PointerRNA *ptr, struc
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -279,7 +265,7 @@ static void bpy_prop_update_cb(struct bContext *C, struct PointerRNA *ptr, struc
static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -311,14 +297,14 @@ static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = false;
}
else {
- value = PyLong_AsLong(ret);
+ value = PyC_Long_AsI32(ret);
if (value == -1 && PyErr_Occurred()) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = false;
}
@@ -337,7 +323,7 @@ static int bpy_prop_boolean_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -370,12 +356,12 @@ static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -389,9 +375,54 @@ static void bpy_prop_boolean_set_cb(struct PointerRNA *ptr, struct PropertyRNA *
}
}
+static int bpy_prop_poll_cb(struct PointerRNA *self, PointerRNA candidate, struct PropertyRNA *prop)
+{
+ PyObject *py_self;
+ PyObject *py_candidate;
+ PyObject *py_func;
+ PyObject **py_data = RNA_property_py_data_get(prop);
+ PyObject *args;
+ PyObject *ret;
+ bool result;
+ const int is_write_ok = pyrna_write_check();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
+
+ BLI_assert(self != NULL);
+
+ py_self = pyrna_struct_as_instance(self);
+ py_candidate = pyrna_struct_as_instance(&candidate);
+ py_func = py_data[BPY_DATA_CB_SLOT_POLL];
+
+ if (!is_write_ok)
+ pyrna_write_set(true);
+
+ args = PyTuple_New(2);
+ PyTuple_SET_ITEM(args, 0, py_self);
+ PyTuple_SET_ITEM(args, 1, py_candidate);
+
+ ret = PyObject_CallObject(py_func, args);
+
+ Py_DECREF(args);
+
+ if (ret == NULL) {
+ PyC_Err_PrintWithFunc(py_func);
+ result = false;
+ }
+ else {
+ result = PyObject_IsTrue(ret);
+ Py_DECREF(ret);
+ }
+
+ PyGILState_Release(gilstate);
+ if (!is_write_ok)
+ pyrna_write_set(false);
+
+ return result;
+}
+
static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -423,14 +454,14 @@ static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct Propert
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = false;
}
else {
if (PyC_AsArray(values, ret, len, &PyBool_Type, false, "BoolVectorProperty get") == -1) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = false;
@@ -452,7 +483,7 @@ static void bpy_prop_boolean_array_get_cb(struct PointerRNA *ptr, struct Propert
static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -480,24 +511,20 @@ static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct Propert
self = pyrna_struct_as_instance(ptr);
PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_FromArray(values, len, &PyBool_Type, false, "BoolVectorProperty set");
- if (!py_values) {
- printf_func_error(py_func);
- }
- else
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_I32FromBool(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
ret = PyObject_CallObject(py_func, args);
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -513,7 +540,7 @@ static void bpy_prop_boolean_array_set_cb(struct PointerRNA *ptr, struct Propert
static int bpy_prop_int_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -545,14 +572,14 @@ static int bpy_prop_int_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = 0.0f;
}
else {
- value = PyLong_AsLong(ret);
+ value = PyC_Long_AsI32(ret);
if (value == -1 && PyErr_Occurred()) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = 0;
}
@@ -571,7 +598,7 @@ static int bpy_prop_int_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
static void bpy_prop_int_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -604,12 +631,12 @@ static void bpy_prop_int_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -625,7 +652,7 @@ static void bpy_prop_int_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop
static void bpy_prop_int_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -657,14 +684,14 @@ static void bpy_prop_int_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = 0;
}
else {
if (PyC_AsArray(values, ret, len, &PyLong_Type, false, "IntVectorProperty get") == -1) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = 0;
@@ -686,7 +713,7 @@ static void bpy_prop_int_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA
static void bpy_prop_int_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const int *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -714,24 +741,20 @@ static void bpy_prop_int_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA
self = pyrna_struct_as_instance(ptr);
PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_FromArray(values, len, &PyLong_Type, false, "IntVectorProperty set");
- if (!py_values) {
- printf_func_error(py_func);
- }
- else
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_I32(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
ret = PyObject_CallObject(py_func, args);
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -747,7 +770,7 @@ static void bpy_prop_int_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA
static float bpy_prop_float_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -779,14 +802,14 @@ static float bpy_prop_float_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = 0.0f;
}
else {
value = PyFloat_AsDouble(ret);
if (value == -1.0f && PyErr_Occurred()) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = 0.0f;
}
@@ -805,7 +828,7 @@ static float bpy_prop_float_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
static void bpy_prop_float_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, float value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -838,12 +861,12 @@ static void bpy_prop_float_set_cb(struct PointerRNA *ptr, struct PropertyRNA *pr
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -859,7 +882,7 @@ static void bpy_prop_float_set_cb(struct PointerRNA *ptr, struct PropertyRNA *pr
static void bpy_prop_float_array_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, float *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -891,14 +914,14 @@ static void bpy_prop_float_array_get_cb(struct PointerRNA *ptr, struct PropertyR
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = 0.0f;
}
else {
if (PyC_AsArray(values, ret, len, &PyFloat_Type, false, "FloatVectorProperty get") == -1) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
for (i = 0; i < len; ++i)
values[i] = 0.0f;
@@ -920,7 +943,7 @@ static void bpy_prop_float_array_get_cb(struct PointerRNA *ptr, struct PropertyR
static void bpy_prop_float_array_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const float *values)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -948,24 +971,20 @@ static void bpy_prop_float_array_set_cb(struct PointerRNA *ptr, struct PropertyR
self = pyrna_struct_as_instance(ptr);
PyTuple_SET_ITEM(args, 0, self);
- py_values = PyC_FromArray(values, len, &PyFloat_Type, false, "FloatVectorProperty set");
- if (!py_values) {
- printf_func_error(py_func);
- }
- else
- PyTuple_SET_ITEM(args, 1, py_values);
+ py_values = PyC_Tuple_PackArray_F32(values, len);
+ PyTuple_SET_ITEM(args, 1, py_values);
ret = PyObject_CallObject(py_func, args);
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -981,7 +1000,7 @@ static void bpy_prop_float_array_set_cb(struct PointerRNA *ptr, struct PropertyR
static void bpy_prop_string_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, char *value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -1012,14 +1031,14 @@ static void bpy_prop_string_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value[0] = '\0';
}
else if (!PyUnicode_Check(ret)) {
PyErr_Format(PyExc_TypeError,
"return value must be a string, not %.200s",
Py_TYPE(ret)->tp_name);
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value[0] = '\0';
Py_DECREF(ret);
}
@@ -1040,7 +1059,7 @@ static void bpy_prop_string_get_cb(struct PointerRNA *ptr, struct PropertyRNA *p
static int bpy_prop_string_length_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -1072,14 +1091,14 @@ static int bpy_prop_string_length_cb(struct PointerRNA *ptr, struct PropertyRNA
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
length = 0;
}
else if (!PyUnicode_Check(ret)) {
PyErr_Format(PyExc_TypeError,
"return value must be a string, not %.200s",
Py_TYPE(ret)->tp_name);
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
length = 0;
Py_DECREF(ret);
}
@@ -1102,7 +1121,7 @@ static int bpy_prop_string_length_cb(struct PointerRNA *ptr, struct PropertyRNA
static void bpy_prop_string_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, const char *value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -1132,7 +1151,7 @@ static void bpy_prop_string_set_cb(struct PointerRNA *ptr, struct PropertyRNA *p
py_value = PyUnicode_FromString(value);
if (!py_value) {
PyErr_SetString(PyExc_ValueError, "the return value must be a string");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else
PyTuple_SET_ITEM(args, 1, py_value);
@@ -1142,12 +1161,12 @@ static void bpy_prop_string_set_cb(struct PointerRNA *ptr, struct PropertyRNA *p
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -1163,7 +1182,7 @@ static void bpy_prop_string_set_cb(struct PointerRNA *ptr, struct PropertyRNA *p
static int bpy_prop_enum_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -1195,14 +1214,14 @@ static int bpy_prop_enum_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = RNA_property_enum_get_default(ptr, prop);
}
else {
- value = PyLong_AsLong(ret);
+ value = PyC_Long_AsI32(ret);
if (value == -1 && PyErr_Occurred()) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
value = RNA_property_enum_get_default(ptr, prop);
}
@@ -1221,7 +1240,7 @@ static int bpy_prop_enum_get_cb(struct PointerRNA *ptr, struct PropertyRNA *prop
static void bpy_prop_enum_set_cb(struct PointerRNA *ptr, struct PropertyRNA *prop, int value)
{
- PyObject **py_data = (PyObject **)RNA_property_py_data_get(prop);
+ PyObject **py_data = RNA_property_py_data_get(prop);
PyObject *py_func;
PyObject *args;
PyObject *self;
@@ -1254,12 +1273,12 @@ static void bpy_prop_enum_set_cb(struct PointerRNA *ptr, struct PropertyRNA *pro
Py_DECREF(args);
if (ret == NULL) {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
else {
if (ret != Py_None) {
PyErr_SetString(PyExc_ValueError, "the return value must be None");
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
}
Py_DECREF(ret);
@@ -1300,7 +1319,7 @@ static size_t strswapbufcpy(char *buf, const char **orig)
static int icon_id_from_name(const char *name)
{
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int id;
if (name[0]) {
@@ -1314,7 +1333,7 @@ static int icon_id_from_name(const char *name)
return 0;
}
-static EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const bool is_enum_flag)
+static const EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, int *defvalue, const bool is_enum_flag)
{
EnumPropertyItem *items;
PyObject *item;
@@ -1470,7 +1489,7 @@ static EnumPropertyItem *enum_items_from_py(PyObject *seq_fast, PyObject *def, i
return items;
}
-static EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
+static const EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C, PointerRNA *ptr, PropertyRNA *prop, bool *r_free)
{
PyGILState_STATE gilstate;
@@ -1479,7 +1498,7 @@ static EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C, PointerRNA *
PyObject *args;
PyObject *items; /* returned from the function call */
- EnumPropertyItem *eitems = NULL;
+ const EnumPropertyItem *eitems = NULL;
int err = 0;
if (C) {
@@ -1537,7 +1556,7 @@ static EnumPropertyItem *bpy_prop_enum_itemf_cb(struct bContext *C, PointerRNA *
*r_free = true;
}
else {
- printf_func_error(py_func);
+ PyC_Err_PrintWithFunc(py_func);
eitems = DummyRNA_NULL_items;
}
@@ -1598,6 +1617,16 @@ static void bpy_prop_callback_assign_update(struct PropertyRNA *prop, PyObject *
}
}
+static void bpy_prop_callback_assign_pointer(struct PropertyRNA *prop, PyObject *poll_cb)
+{
+ if (poll_cb && poll_cb != Py_None) {
+ PyObject **py_data = bpy_prop_py_data_get(prop);
+
+ RNA_def_property_poll_runtime(prop, (void *) bpy_prop_poll_cb);
+ py_data[BPY_DATA_CB_SLOT_POLL] = poll_cb;
+ }
+}
+
static void bpy_prop_callback_assign_boolean(struct PropertyRNA *prop, PyObject *get_cb, PyObject *set_cb)
{
BooleanPropertyGetFunc rna_get_cb = NULL;
@@ -1829,7 +1858,22 @@ static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop, PyObject *ge
#_func"(options={ ...}):"))) \
{ \
return NULL; \
- } (void)0
+ } \
+ { \
+ const EnumPropertyItem *tag_defines = RNA_struct_property_tag_defines(srna); \
+ if (py_tags && !tag_defines) { \
+ PyErr_Format(PyExc_TypeError, \
+ #_func"(): property-tags not available for '%s'", \
+ RNA_struct_identifier(srna)); \
+ return NULL; \
+ } \
+ if (UNLIKELY(py_tags && pyrna_set_to_enum_bitfield( \
+ tag_defines, py_tags, \
+ &prop_tags, #_func"(tags={ ...}):"))) \
+ { \
+ return NULL; \
+ } \
+ }(void)0
#define BPY_PROPDEF_SUBTYPE_CHECK(_func, _property_flag_items, _subtype) \
BPY_PROPDEF_CHECK(_func, _property_flag_items); \
@@ -1893,6 +1937,11 @@ static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop, PyObject *ge
" *Warning* there are no safety checks to avoid infinite recursion.\n" \
" :type update: function\n" \
+#define BPY_PROPDEF_POLL_DOC \
+" :arg poll: function to be called to determine whether an item is valid for this property.\n" \
+" The function must take 2 values (self, object) and return Bool.\n" \
+" :type poll: function\n" \
+
#define BPY_PROPDEF_GET_DOC \
" :arg get: Function to be called when this value is 'read',\n" \
" This function must take 1 value (self) and return the value of the property.\n" \
@@ -1904,9 +1953,13 @@ static void bpy_prop_callback_assign_enum(struct PropertyRNA *prop, PyObject *ge
" :type set: function\n" \
#define BPY_PROPDEF_TYPE_DOC \
-" :arg type: A subclass of :class:`bpy.types.PropertyGroup`.\n" \
+" :arg type: A subclass of :class:`bpy.types.PropertyGroup` or :class:`bpy.types.ID`.\n" \
" :type type: class\n" \
+#define BPY_PROPDEF_TAGS_DOC \
+" :arg tags: Enumerator of tags that are defined by parent class.\n" \
+" :type tags: set\n" \
+
#if 0
static int bpy_struct_id_used(StructRNA *srna, char *identifier)
{
@@ -1925,6 +1978,7 @@ PyDoc_STRVAR(BPy_BoolProperty_doc,
"description=\"\", "
"default=False, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"update=None, "
"get=None, "
@@ -1935,6 +1989,7 @@ PyDoc_STRVAR(BPy_BoolProperty_doc,
BPY_PROPDEF_NAME_DOC
BPY_PROPDEF_DESC_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_NUMBER_DOC
BPY_PROPDEF_UPDATE_DOC
BPY_PROPDEF_GET_DOC
@@ -1947,26 +2002,32 @@ static PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
BPY_PROPDEF_HEAD(BoolProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "options", "subtype", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
bool def = false;
PropertyRNA *prop;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssO&O!sOOO:BoolProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, PyC_ParseBool, &def,
- &PySet_Type, &pyopts, &pysubtype,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "options", "tags", "subtype",
+ "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssO&O!O!sOOO:BoolProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, PyC_ParseBool, &def,
+ &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -1987,6 +2048,9 @@ static PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
RNA_def_property_boolean_default(prop, def);
RNA_def_property_ui_text(prop, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2003,6 +2067,7 @@ PyDoc_STRVAR(BPy_BoolVectorProperty_doc,
"description=\"\", "
"default=(False, False, False), "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"size=3, "
"update=None, "
@@ -2016,6 +2081,7 @@ BPY_PROPDEF_DESC_DOC
" :arg default: sequence of booleans the length of *size*.\n"
" :type default: sequence\n"
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_ARRAY_DOC
BPY_PROPDEF_VECSIZE_DOC
BPY_PROPDEF_UPDATE_DOC
@@ -2029,8 +2095,6 @@ static PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject
BPY_PROPDEF_HEAD(BoolVectorProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "options", "subtype", "size", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
int def[PYRNA_STACK_ARRAY] = {0};
@@ -2039,18 +2103,27 @@ static PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject
PyObject *pydef = NULL;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssOO!siOOO:BoolVectorProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &pydef,
- &PySet_Type, &pyopts, &pysubtype, &size,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "options", "tags", "subtype", "size",
+ "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOO!O!siOOO:BoolVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &pydef,
+ &PySet_Type, &pyopts, &PySet_Type, &py_tags,
+ &pysubtype, &size,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2083,6 +2156,9 @@ static PyObject *BPy_BoolVectorProperty(PyObject *self, PyObject *args, PyObject
if (pydef) RNA_def_property_boolean_array_default(prop, def);
RNA_def_property_ui_text(prop, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2102,6 +2178,7 @@ PyDoc_STRVAR(BPy_IntProperty_doc,
"soft_min=-2**31, soft_max=2**31-1, "
"step=1, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"update=None, "
"get=None, "
@@ -2121,6 +2198,7 @@ BPY_PROPDEF_NUM_SOFTMIN_DOC
" :type soft_max: int\n"
BPY_PROPDEF_INT_STEP_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_NUMBER_DOC
BPY_PROPDEF_UPDATE_DOC
BPY_PROPDEF_GET_DOC
@@ -2133,28 +2211,34 @@ static PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
BPY_PROPDEF_HEAD(IntProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "options", "subtype", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1, def = 0;
PropertyRNA *prop;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssiiiiiiO!sOOO:IntProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &def,
- &min, &max, &soft_min, &soft_max,
- &step, &PySet_Type, &pyopts, &pysubtype,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "min", "max", "soft_min", "soft_max",
+ "step", "options", "tags", "subtype",
+ "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssiiiiiiO!O!sOOO:IntProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &def,
+ &min, &max, &soft_min, &soft_max,
+ &step, &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2177,6 +2261,9 @@ static PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
RNA_def_property_range(prop, min, max);
RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2195,6 +2282,7 @@ PyDoc_STRVAR(BPy_IntVectorProperty_doc,
"soft_max=2**31-1, "
"step=1, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"size=3, "
"update=None, "
@@ -2217,6 +2305,7 @@ BPY_PROPDEF_NUM_SOFTMAX_DOC
" :type soft_max: int\n"
BPY_PROPDEF_INT_STEP_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_ARRAY_DOC
BPY_PROPDEF_VECSIZE_DOC
BPY_PROPDEF_UPDATE_DOC
@@ -2230,9 +2319,6 @@ static PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject
BPY_PROPDEF_HEAD(IntVectorProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "options", "subtype", "size", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
int min = INT_MIN, max = INT_MAX, soft_min = INT_MIN, soft_max = INT_MAX, step = 1;
@@ -2242,20 +2328,29 @@ static PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject
PyObject *pydef = NULL;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssOiiiiiO!siOOO:IntVectorProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &pydef,
- &min, &max, &soft_min, &soft_max,
- &step, &PySet_Type, &pyopts,
- &pysubtype, &size,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "min", "max", "soft_min", "soft_max",
+ "step", "options", "tags", "subtype", "size",
+ "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOiiiiiO!O!siOOO:IntVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &pydef,
+ &min, &max, &soft_min, &soft_max,
+ &step, &PySet_Type, &pyopts, &PySet_Type, &py_tags,
+ &pysubtype, &size,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2289,6 +2384,9 @@ static PyObject *BPy_IntVectorProperty(PyObject *self, PyObject *args, PyObject
RNA_def_property_ui_text(prop, name ? name : id, description);
RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, 3);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2309,6 +2407,7 @@ PyDoc_STRVAR(BPy_FloatProperty_doc,
"step=3, "
"precision=2, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"unit='NONE', "
"update=None, "
@@ -2330,6 +2429,7 @@ BPY_PROPDEF_NUM_SOFTMAX_DOC
BPY_PROPDEF_FLOAT_STEP_DOC
BPY_PROPDEF_FLOAT_PREC_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_NUMBER_DOC
BPY_PROPDEF_UNIT_DOC
BPY_PROPDEF_UPDATE_DOC
@@ -2343,10 +2443,6 @@ static PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
BPY_PROPDEF_HEAD(FloatProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "precision", "options", "subtype",
- "unit", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3, def = 0.0f;
@@ -2354,6 +2450,7 @@ static PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
PropertyRNA *prop;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
const char *pyunit = NULL;
@@ -2361,15 +2458,23 @@ static PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssffffffiO!ssOOO:FloatProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &def,
- &min, &max, &soft_min, &soft_max,
- &step, &precision, &PySet_Type,
- &pyopts, &pysubtype, &pyunit,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "min", "max", "soft_min", "soft_max",
+ "step", "precision", "options", "tags", "subtype",
+ "unit", "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssffffffiO!O!ssOOO:FloatProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &def,
+ &min, &max, &soft_min, &soft_max,
+ &step, &precision, &PySet_Type,
+ &pyopts, &PySet_Type, &py_tags, &pysubtype, &pyunit,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2397,6 +2502,9 @@ static PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
RNA_def_property_ui_text(prop, name ? name : id, description);
RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2416,6 +2524,7 @@ PyDoc_STRVAR(BPy_FloatVectorProperty_doc,
"step=3, "
"precision=2, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"unit='NONE', "
"size=3, "
@@ -2438,6 +2547,7 @@ BPY_PROPDEF_NUM_SOFTMIN_DOC
BPY_PROPDEF_NUM_SOFTMAX_DOC
" :type soft_max: float\n"
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_FLOAT_STEP_DOC
BPY_PROPDEF_FLOAT_PREC_DOC
BPY_PROPDEF_SUBTYPE_ARRAY_DOC
@@ -2454,10 +2564,6 @@ static PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObjec
BPY_PROPDEF_HEAD(FloatVectorProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "min", "max", "soft_min", "soft_max",
- "step", "precision", "options", "subtype",
- "unit", "size", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
float min = -FLT_MAX, max = FLT_MAX, soft_min = -FLT_MAX, soft_max = FLT_MAX, step = 3;
@@ -2467,6 +2573,7 @@ static PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObjec
PyObject *pydef = NULL;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
const char *pyunit = NULL;
@@ -2474,15 +2581,23 @@ static PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObjec
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|ssOfffffiO!ssiOOO:FloatVectorProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &pydef,
- &min, &max, &soft_min, &soft_max,
- &step, &precision, &PySet_Type,
- &pyopts, &pysubtype, &pyunit, &size,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "min", "max", "soft_min", "soft_max",
+ "step", "precision", "options", "tags", "subtype",
+ "unit", "size", "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|ssOfffffiO!O!ssiOOO:FloatVectorProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &pydef,
+ &min, &max, &soft_min, &soft_max,
+ &step, &precision, &PySet_Type,
+ &pyopts, &PySet_Type, &py_tags, &pysubtype, &pyunit, &size,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2521,6 +2636,9 @@ static PyObject *BPy_FloatVectorProperty(PyObject *self, PyObject *args, PyObjec
RNA_def_property_ui_text(prop, name ? name : id, description);
RNA_def_property_ui_range(prop, MAX2(soft_min, min), MIN2(soft_max, max), step, precision);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2537,6 +2655,7 @@ PyDoc_STRVAR(BPy_StringProperty_doc,
"default=\"\", "
"maxlen=0, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"subtype='NONE', "
"update=None, "
"get=None, "
@@ -2551,6 +2670,7 @@ BPY_PROPDEF_DESC_DOC
" :arg maxlen: maximum length of the string.\n"
" :type maxlen: int\n"
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_SUBTYPE_STRING_DOC
BPY_PROPDEF_UPDATE_DOC
BPY_PROPDEF_GET_DOC
@@ -2563,26 +2683,32 @@ static PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw
BPY_PROPDEF_HEAD(StringProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "name", "description", "default",
- "maxlen", "options", "subtype", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "", *def = "";
int id_len;
int maxlen = 0;
PropertyRNA *prop;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
const char *pysubtype = NULL;
int subtype = PROP_NONE;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#|sssiO!sOOO:StringProperty",
- (char **)kwlist, &id, &id_len,
- &name, &description, &def,
- &maxlen, &PySet_Type, &pyopts, &pysubtype,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "name", "description", "default",
+ "maxlen", "options", "tags", "subtype",
+ "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#|sssiO!O!sOOO:StringProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &name, &description, &def,
+ &maxlen, &PySet_Type, &pyopts, &PySet_Type, &py_tags, &pysubtype,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2604,6 +2730,9 @@ static PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw
if (def && def[0]) RNA_def_property_string_default(prop, def);
RNA_def_property_ui_text(prop, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2620,6 +2749,7 @@ PyDoc_STRVAR(BPy_EnumProperty_doc,
"description=\"\", "
"default=None, "
"options={'ANIMATABLE'}, "
+ "tags={}, "
"update=None, "
"get=None, "
"set=None)\n"
@@ -2637,7 +2767,8 @@ PyDoc_STRVAR(BPy_EnumProperty_doc,
" :icon: An icon string identifier or integer icon value\n"
" (e.g. returned by :class:`bpy.types.UILayout.icon`)\n"
" :number: Unique value used as the identifier for this item (stored in file data).\n"
-" Use when the identifier may need to change.\n"
+" Use when the identifier may need to change. If the *ENUM_FLAG* option is used,\n"
+" the values are bitmasks and should be powers of two.\n"
"\n"
" When an item only contains 4 items they define ``(identifier, name, description, number)``.\n"
"\n"
@@ -2660,6 +2791,7 @@ BPY_PROPDEF_DESC_DOC
" (i.e. if a callback function is given as *items* parameter).\n"
" :type default: string or set\n"
BPY_PROPDEF_OPTIONS_ENUM_DOC
+BPY_PROPDEF_TAGS_DOC
BPY_PROPDEF_UPDATE_DOC
BPY_PROPDEF_GET_DOC
BPY_PROPDEF_SET_DOC
@@ -2671,28 +2803,33 @@ static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
BPY_PROPDEF_HEAD(EnumProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "items", "name", "description", "default",
- "options", "update", "get", "set", NULL};
const char *id = NULL, *name = NULL, *description = "";
PyObject *def = NULL;
int id_len;
int defvalue = 0;
PyObject *items, *items_fast;
- EnumPropertyItem *eitems;
+ const EnumPropertyItem *eitems;
PropertyRNA *prop;
PyObject *pyopts = NULL;
int opts = 0;
+ int prop_tags = 0;
bool is_itemf = false;
PyObject *update_cb = NULL;
PyObject *get_cb = NULL;
PyObject *set_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#O|ssOO!OOO:EnumProperty",
- (char **)kwlist, &id, &id_len,
- &items, &name, &description,
- &def, &PySet_Type, &pyopts,
- &update_cb, &get_cb, &set_cb))
+ PyObject *py_tags = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "items", "name", "description", "default",
+ "options", "tags", "update", "get", "set", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssOO!O!OOO:EnumProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &items, &name, &description,
+ &def, &PySet_Type, &pyopts, &PySet_Type, &py_tags,
+ &update_cb, &get_cb, &set_cb))
{
return NULL;
}
@@ -2754,6 +2891,9 @@ static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
if (opts & PROP_ENUM_FLAG) prop = RNA_def_enum_flag(srna, id, eitems, defvalue, name ? name : id, description);
else prop = RNA_def_enum(srna, id, eitems, defvalue, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
@@ -2766,13 +2906,13 @@ static PyObject *BPy_EnumProperty(PyObject *self, PyObject *args, PyObject *kw)
* otherwise if this is a generator it may free the strings before we copy them */
Py_DECREF(items_fast);
- MEM_freeN(eitems);
+ MEM_freeN((void *)eitems);
}
}
Py_RETURN_NONE;
}
-static StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix)
+StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix)
{
StructRNA *srna;
@@ -2782,25 +2922,18 @@ static StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix
PyObject *msg = PyC_ExceptionBuffer();
const char *msg_char = _PyUnicode_AsString(msg);
PyErr_Format(PyExc_TypeError,
- "%.200s expected an RNA type derived from PropertyGroup, failed with: %s",
+ "%.200s expected an RNA type, failed with: %s",
error_prefix, msg_char);
Py_DECREF(msg);
}
else {
PyErr_Format(PyExc_TypeError,
- "%.200s expected an RNA type derived from PropertyGroup, failed with type '%s'",
+ "%.200s expected an RNA type, failed with type '%s'",
error_prefix, Py_TYPE(value)->tp_name);
}
return NULL;
}
- if (!RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s expected an RNA type derived from PropertyGroup",
- error_prefix);
- return NULL;
- }
-
return srna;
}
@@ -2809,6 +2942,8 @@ PyDoc_STRVAR(BPy_PointerProperty_doc,
"name=\"\", "
"description=\"\", "
"options={'ANIMATABLE'}, "
+ "tags={}, "
+ "poll=None, "
"update=None)\n"
"\n"
" Returns a new pointer property definition.\n"
@@ -2817,50 +2952,75 @@ BPY_PROPDEF_TYPE_DOC
BPY_PROPDEF_NAME_DOC
BPY_PROPDEF_DESC_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
+BPY_PROPDEF_POLL_DOC
BPY_PROPDEF_UPDATE_DOC
);
-static PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
+PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw)
{
StructRNA *srna;
BPY_PROPDEF_HEAD(PointerProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "type", "name", "description", "options", "update", NULL};
const char *id = NULL, *name = NULL, *description = "";
int id_len;
PropertyRNA *prop;
StructRNA *ptype;
PyObject *type = Py_None;
PyObject *pyopts = NULL;
+ PyObject *py_tags = NULL;
int opts = 0;
- PyObject *update_cb = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#O|ssO!O:PointerProperty",
- (char **)kwlist, &id, &id_len,
- &type, &name, &description,
- &PySet_Type, &pyopts,
- &update_cb))
+ int prop_tags = 0;
+ PyObject *update_cb = NULL, *poll_cb = NULL;
+
+ static const char *_keywords[] = {
+ "attr", "type", "name", "description", "options",
+ "tags", "poll", "update", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssO!O!OO:PointerProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &type, &name, &description,
+ &PySet_Type, &pyopts, &PySet_Type, &py_tags,
+ &poll_cb, &update_cb))
{
return NULL;
}
BPY_PROPDEF_CHECK(PointerProperty, property_flag_items);
- ptype = pointer_type_from_py(type, "PointerProperty(...):");
+ ptype = pointer_type_from_py(type, "PointerProperty(...)");
if (!ptype)
return NULL;
-
+ if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup) && !RNA_struct_is_ID(ptype)) {
+ PyErr_Format(PyExc_TypeError,
+ "PointerProperty(...) expected an RNA type derived from %.200s or %.200s",
+ RNA_struct_ui_name(&RNA_ID), RNA_struct_ui_name(&RNA_PropertyGroup));
+ return NULL;
+ }
if (bpy_prop_callback_check(update_cb, "update", 2) == -1) {
return NULL;
}
-
+ if (bpy_prop_callback_check(poll_cb, "poll", 2) == -1) {
+ return NULL;
+ }
prop = RNA_def_pointer_runtime(srna, id, ptype, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
+
+ if (RNA_struct_idprops_contains_datablock(ptype)) {
+ if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
+ RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
+ }
+ }
bpy_prop_callback_assign_update(prop, update_cb);
+ bpy_prop_callback_assign_pointer(prop, poll_cb);
RNA_def_property_duplicate_pointers(srna, prop);
}
Py_RETURN_NONE;
@@ -2870,7 +3030,8 @@ PyDoc_STRVAR(BPy_CollectionProperty_doc,
".. function:: CollectionProperty(type=None, "
"name=\"\", "
"description=\"\", "
- "options={'ANIMATABLE'})\n"
+ "options={'ANIMATABLE'}, "
+ "tags={})\n"
"\n"
" Returns a new collection property definition.\n"
"\n"
@@ -2878,28 +3039,35 @@ BPY_PROPDEF_TYPE_DOC
BPY_PROPDEF_NAME_DOC
BPY_PROPDEF_DESC_DOC
BPY_PROPDEF_OPTIONS_DOC
+BPY_PROPDEF_TAGS_DOC
);
-static PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
+PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw)
{
StructRNA *srna;
BPY_PROPDEF_HEAD(CollectionProperty);
if (srna) {
- static const char *kwlist[] = {"attr", "type", "name", "description", "options", NULL};
- const char *id = NULL, *name = NULL, *description = "";
int id_len;
+ const char *id = NULL, *name = NULL, *description = "";
PropertyRNA *prop;
StructRNA *ptype;
PyObject *type = Py_None;
PyObject *pyopts = NULL;
+ PyObject *py_tags = NULL;
int opts = 0;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s#O|ssO!:CollectionProperty",
- (char **)kwlist, &id, &id_len,
- &type, &name, &description,
- &PySet_Type, &pyopts))
+ int prop_tags = 0;
+
+ static const char *_keywords[] = {
+ "attr", "type", "name", "description",
+ "options", "tags", NULL,
+ };
+ static _PyArg_Parser _parser = {"s#O|ssO!O!:CollectionProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id, &id_len,
+ &type, &name, &description,
+ &PySet_Type, &pyopts, &PySet_Type, &py_tags))
{
return NULL;
}
@@ -2910,17 +3078,33 @@ static PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject
if (!ptype)
return NULL;
+ if (!RNA_struct_is_a(ptype, &RNA_PropertyGroup)) {
+ PyErr_Format(PyExc_TypeError,
+ "CollectionProperty(...) expected an RNA type derived from %.200s",
+ RNA_struct_ui_name(&RNA_ID), RNA_struct_ui_name(&RNA_PropertyGroup));
+ return NULL;
+ }
+
prop = RNA_def_collection_runtime(srna, id, ptype, name ? name : id, description);
+ if (py_tags) {
+ RNA_def_property_tags(prop, prop_tags);
+ }
if (pyopts) {
bpy_prop_assign_flag(prop, opts);
}
+
+ if (RNA_struct_idprops_contains_datablock(ptype)) {
+ if (RNA_struct_is_a(srna, &RNA_PropertyGroup)) {
+ RNA_def_struct_flag(srna, STRUCT_CONTAINS_DATABLOCK_IDPROPERTIES);
+ }
+ }
RNA_def_property_duplicate_pointers(srna, prop);
}
Py_RETURN_NONE;
}
PyDoc_STRVAR(BPy_RemoveProperty_doc,
-".. function:: RemoveProperty(cls, attr="")\n"
+".. function:: RemoveProperty(cls, attr)\n"
"\n"
" Removes a dynamically defined property.\n"
"\n"
@@ -2958,13 +3142,15 @@ static PyObject *BPy_RemoveProperty(PyObject *self, PyObject *args, PyObject *kw
return NULL;
}
else {
- static const char *kwlist[] = {"attr", NULL};
-
const char *id = NULL;
- if (!PyArg_ParseTupleAndKeywords(args, kw,
- "s:RemoveProperty",
- (char **)kwlist, &id))
+ static const char *_keywords[] = {
+ "attr", NULL,
+ };
+ static _PyArg_Parser _parser = {"s:RemoveProperty", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &id))
{
return NULL;
}
diff --git a/source/blender/python/intern/bpy_props.h b/source/blender/python/intern/bpy_props.h
index c9934ca0cf3..614c1b4b708 100644
--- a/source/blender/python/intern/bpy_props.h
+++ b/source/blender/python/intern/bpy_props.h
@@ -30,6 +30,10 @@
PyObject *BPY_rna_props(void);
+PyObject *BPy_PointerProperty(PyObject *self, PyObject *args, PyObject *kw);
+PyObject *BPy_CollectionProperty(PyObject *self, PyObject *args, PyObject *kw);
+StructRNA *pointer_type_from_py(PyObject *value, const char *error_prefix);
+
#define PYRNA_STACK_ARRAY 32
#endif
diff --git a/source/blender/python/intern/bpy_rna.c b/source/blender/python/intern/bpy_rna.c
index 2fd46ab94f0..baaae066b4b 100644
--- a/source/blender/python/intern/bpy_rna.c
+++ b/source/blender/python/intern/bpy_rna.c
@@ -45,11 +45,12 @@
#include "BLI_utildefines.h"
#include "BPY_extern.h"
+#include "BPY_extern_clog.h"
#include "bpy_rna.h"
#include "bpy_rna_anim.h"
#include "bpy_props.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_rna_callback.h"
#include "bpy_intern_string.h"
@@ -61,6 +62,8 @@
#include "RNA_define.h" /* RNA_def_property_free_identifier */
#include "RNA_access.h"
+#include "CLG_log.h"
+
#include "MEM_guardedalloc.h"
#include "BKE_main.h"
@@ -70,6 +73,8 @@
#include "BKE_report.h"
#include "BKE_idprop.h"
+/* only for types */
+#include "BKE_node.h"
#include "../generic/idprop_py_api.h" /* for IDprop lookups */
#include "../generic/py_capi_utils.h"
@@ -221,7 +226,7 @@ static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakre
GHash *weakinfo_hash = PyCapsule_GetPointer(weakinfo_capsule, NULL);
- if (BLI_ghash_size(weakinfo_hash) > 1) {
+ if (BLI_ghash_len(weakinfo_hash) > 1) {
BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
}
else { /* get the last id and free it */
@@ -241,7 +246,7 @@ static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
#ifdef DEBUG_RNA_WEAKREF
- fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
+ fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_len(weakinfo_hash));
#endif
while (!BLI_ghashIterator_done(&weakinfo_hash_iter)) {
@@ -264,7 +269,7 @@ static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
BLI_ghash_free(weakinfo_hash, NULL, NULL);
- if (BLI_ghash_size(id_weakref_pool) == 0) {
+ if (BLI_ghash_len(id_weakref_pool) == 0) {
BLI_ghash_free(id_weakref_pool, NULL, NULL);
id_weakref_pool = NULL;
#ifdef DEBUG_RNA_WEAKREF
@@ -756,7 +761,7 @@ thick_wrap_slice:
/* same as RNA_enum_value_from_id but raises an exception */
int pyrna_enum_value_from_id(
- EnumPropertyItem *item, const char *identifier, int *r_value,
+ const EnumPropertyItem *item, const char *identifier, int *r_value,
const char *error_prefix)
{
if (RNA_enum_value_from_id(item, identifier, r_value) == 0) {
@@ -806,7 +811,7 @@ static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
@@ -836,7 +841,7 @@ static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
@@ -1165,7 +1170,7 @@ static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
{
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
const char *result;
bool free = false;
@@ -1177,8 +1182,9 @@ static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
result = "";
}
- if (free)
- MEM_freeN(item);
+ if (free) {
+ MEM_freeN((void *)item);
+ }
return result;
}
@@ -1219,7 +1225,7 @@ static int pyrna_string_to_enum(
* needed when we want to use the full range of a signed short/char.
*/
BLI_bitmap *pyrna_set_to_enum_bitmap(
- EnumPropertyItem *items, PyObject *value,
+ const EnumPropertyItem *items, PyObject *value,
int type_size, bool type_convert_sign,
int bitmap_size,
const char *error_prefix)
@@ -1275,7 +1281,7 @@ error:
/* 'value' _must_ be a set type, error check before calling */
int pyrna_set_to_enum_bitfield(
- EnumPropertyItem *items, PyObject *value, int *r_value,
+ const EnumPropertyItem *items, PyObject *value, int *r_value,
const char *error_prefix)
{
/* set of enum items, concatenate all values with OR */
@@ -1313,7 +1319,7 @@ static int pyrna_prop_to_enum_bitfield(
PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value,
const char *error_prefix)
{
- EnumPropertyItem *item;
+ const EnumPropertyItem *item;
int ret;
bool free = false;
@@ -1344,13 +1350,14 @@ static int pyrna_prop_to_enum_bitfield(
}
}
- if (free)
- MEM_freeN(item);
+ if (free) {
+ MEM_freeN((void *)item);
+ }
return ret;
}
-PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
+PyObject *pyrna_enum_bitfield_to_py(const EnumPropertyItem *items, int value)
{
PyObject *ret = PySet_New(NULL);
const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
@@ -1394,8 +1401,8 @@ static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
ret = PyUnicode_FromString(identifier);
}
else {
- EnumPropertyItem *enum_item;
- bool free = false;
+ const EnumPropertyItem *enum_item;
+ bool free;
/* don't throw error here, can't trust blender 100% to give the
* right values, python code should not generate error for that */
@@ -1404,6 +1411,9 @@ static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
ret = PyUnicode_FromString(enum_item->identifier);
}
else {
+ if (free) {
+ MEM_freeN((void *)enum_item);
+ }
RNA_property_enum_items(NULL, ptr, prop, &enum_item, NULL, &free);
/* Do not print warning in case of DummyRNA_NULL_items, this one will never match any value... */
@@ -1411,10 +1421,11 @@ static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
/* prefer not fail silently in case of api errors, maybe disable it later */
- printf("RNA Warning: Current value \"%d\" "
- "matches no enum in '%s', '%s', '%s'\n",
- val, RNA_struct_identifier(ptr->type),
- ptr_name, RNA_property_identifier(prop));
+ CLOG_WARN(BPY_LOG_RNA,
+ "current value '%d' "
+ "matches no enum in '%s', '%s', '%s'",
+ val, RNA_struct_identifier(ptr->type),
+ ptr_name, RNA_property_identifier(prop));
#if 0 /* gives python decoding errors while generating docs :( */
char error_str[256];
@@ -1434,8 +1445,9 @@ static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
ret = PyUnicode_FromString("");
}
- if (free)
- MEM_freeN(enum_item);
+ if (free) {
+ MEM_freeN((void *)enum_item);
+ }
#if 0
PyErr_Format(PyExc_AttributeError,
"RNA Error: Current value \"%d\" matches no enum", val);
@@ -1640,7 +1652,7 @@ static int pyrna_py_to_prop(
param = PyObject_IsTrue(value);
}
else {
- param = PyLong_AsLong(value);
+ param = PyC_Long_AsI32(value);
if (UNLIKELY(param & ~1)) { /* only accept 0/1 */
param = -1; /* error out below */
@@ -1743,10 +1755,8 @@ static int pyrna_py_to_prop(
return -1;
}
else {
- /* same as unicode */
- /* XXX, this is suspect but needed for function calls, need to see if theres a better way */
if (data) *((char **)data) = (char *)param;
- else RNA_property_string_set(ptr, prop, param);
+ else RNA_property_string_set_bytes(ptr, prop, param, PyBytes_Size(value));
}
}
else {
@@ -1934,16 +1944,10 @@ static int pyrna_py_to_prop(
}
else {
/* data == NULL, assign to RNA */
- if (value == Py_None) {
- PointerRNA valueptr = {{NULL}};
- RNA_property_pointer_set(ptr, prop, valueptr);
- }
- else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
- RNA_property_pointer_set(ptr, prop, param->ptr);
- }
- else {
+ if (value == Py_None || RNA_struct_is_a(param->ptr.type, ptr_type))
+ RNA_property_pointer_set(ptr, prop, value == Py_None ? PointerRNA_NULL : param->ptr);
+ else
raise_error = true;
- }
}
if (raise_error) {
@@ -2082,10 +2086,10 @@ static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, P
switch (RNA_property_type(prop)) {
case PROP_BOOLEAN:
{
- int param = PyLong_AsLong(value);
+ int param = PyC_Long_AsBool(value);
- if (param < 0 || param > 1) {
- PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
+ if (param == -1) {
+ /* error is set */
ret = -1;
}
else {
@@ -2095,7 +2099,7 @@ static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, P
}
case PROP_INT:
{
- int param = PyLong_AsLong(value);
+ int param = PyC_Long_AsI32(value);
if (param == -1 && PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError, "expected an int type");
ret = -1;
@@ -2715,7 +2719,7 @@ static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
- return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
+ return pyrna_prop_array_subscript_int(self, i);
}
else if (PySlice_Check(key)) {
Py_ssize_t step = 1;
@@ -3277,6 +3281,20 @@ static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObje
return -1;
}
+ if (value && BPy_StructRNA_Check(value)) {
+ BPy_StructRNA *val = (BPy_StructRNA *)value;
+ if (val && self->ptr.type && val->ptr.type) {
+ if (!RNA_struct_idprops_datablock_allowed(self->ptr.type) &&
+ RNA_struct_idprops_contains_datablock(val->ptr.type))
+ {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "bpy_struct[key] = val: datablock id properties not supported for this type");
+ return -1;
+ }
+ }
+ }
+
return BPy_Wrap_SetMapItem(group, key, value);
}
@@ -3696,6 +3714,110 @@ static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
return pyrna_struct_CreatePyObject(&r_ptr);
}
+/**
+ * \note Return value is borrowed, caller must incref.
+ */
+static PyObject *pyrna_struct_bl_rna_find_subclass_recursive(PyObject *cls, const char *id)
+{
+ PyObject *ret_test = NULL;
+ PyObject *subclasses = ((PyTypeObject *)cls)->tp_subclasses;
+ if (subclasses) {
+ /* Unfortunately we can't use the dict key because Python class names
+ * don't match the bl_idname used internally. */
+ BLI_assert(PyDict_CheckExact(subclasses));
+ PyObject *key = NULL;
+ Py_ssize_t pos = 0;
+ PyObject *value = NULL;
+ while (PyDict_Next(subclasses, &pos, &key, &value)) {
+ BLI_assert(PyWeakref_CheckRef(value));
+ PyObject *subcls = PyWeakref_GET_OBJECT(value);
+ if (subcls != Py_None) {
+ BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(
+ ((PyTypeObject *)subcls)->tp_dict, bpy_intern_str_bl_rna);
+ if (py_srna) {
+ StructRNA *srna = py_srna->ptr.data;
+ if (STREQ(id, RNA_struct_identifier(srna))) {
+ ret_test = subcls;
+ break;
+ }
+ }
+ ret_test = pyrna_struct_bl_rna_find_subclass_recursive(subcls, id);
+ if (ret_test) {
+ break;
+ }
+ }
+ }
+ }
+ return ret_test;
+}
+
+PyDoc_STRVAR(pyrna_struct_bl_rna_get_subclass_py_doc,
+".. classmethod:: bl_rna_get_subclass_py(id, default=None)\n"
+"\n"
+" :arg id: The RNA type identifier.\n"
+" :type id: string\n"
+" :return: The class or default when not found.\n"
+" :rtype: type\n"
+);
+static PyObject *pyrna_struct_bl_rna_get_subclass_py(PyObject *cls, PyObject *args)
+{
+ char *id;
+ PyObject *ret_default = Py_None;
+
+ if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass_py", &id, &ret_default)) {
+ return NULL;
+ }
+ PyObject *ret = pyrna_struct_bl_rna_find_subclass_recursive(cls, id);
+ if (ret == NULL) {
+ ret = ret_default;
+ }
+ return Py_INCREF_RET(ret);
+}
+
+PyDoc_STRVAR(pyrna_struct_bl_rna_get_subclass_doc,
+".. classmethod:: bl_rna_get_subclass(id, default=None)\n"
+"\n"
+" :arg id: The RNA type identifier.\n"
+" :type id: string\n"
+" :return: The RNA type or default when not found.\n"
+" :rtype: :class:`bpy.types.Struct` subclass\n"
+);
+static PyObject *pyrna_struct_bl_rna_get_subclass(PyObject *cls, PyObject *args)
+{
+ char *id;
+ PyObject *ret_default = Py_None;
+
+ if (!PyArg_ParseTuple(args, "s|O:bl_rna_get_subclass", &id, &ret_default)) {
+ return NULL;
+ }
+
+
+ const BPy_StructRNA *py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)cls)->tp_dict, bpy_intern_str_bl_rna);
+ if (py_srna == NULL) {
+ PyErr_SetString(PyExc_ValueError, "Not a registered class");
+ return NULL;
+
+ }
+ const StructRNA *srna_base = py_srna->ptr.data;
+
+ PointerRNA ptr;
+ if (srna_base == &RNA_Node) {
+ bNodeType *nt = nodeTypeFind(id);
+ if (nt) {
+ RNA_pointer_create(NULL, &RNA_Struct, nt->ext.srna, &ptr);
+ return pyrna_struct_CreatePyObject(&ptr);
+ }
+ }
+ else {
+ /* TODO, panels, menus etc. */
+ PyErr_Format(PyExc_ValueError, "Class type \"%.200s\" not supported",
+ RNA_struct_identifier(srna_base));
+ return NULL;
+ }
+
+ return Py_INCREF_RET(ret_default);
+}
+
static void pyrna_dir_members_py__add_keys(PyObject *list, PyObject *dict)
{
PyObject *list_tmp;
@@ -4994,6 +5116,8 @@ static struct PyMethodDef pyrna_struct_methods[] = {
{"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_VARARGS, pyrna_struct_path_resolve_doc},
{"path_from_id", (PyCFunction)pyrna_struct_path_from_id, METH_VARARGS, pyrna_struct_path_from_id_doc},
{"type_recast", (PyCFunction)pyrna_struct_type_recast, METH_NOARGS, pyrna_struct_type_recast_doc},
+ {"bl_rna_get_subclass_py", (PyCFunction) pyrna_struct_bl_rna_get_subclass_py, METH_VARARGS | METH_CLASS, pyrna_struct_bl_rna_get_subclass_py_doc},
+ {"bl_rna_get_subclass", (PyCFunction) pyrna_struct_bl_rna_get_subclass, METH_VARARGS | METH_CLASS, pyrna_struct_bl_rna_get_subclass_doc},
{"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
/* experimental */
@@ -5160,7 +5284,7 @@ static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *dat
ret = Matrix_CreatePyObject(data, 3, 3, NULL);
break;
}
- /* fall-through */
+ ATTR_FALLTHROUGH;
#endif
default:
ret = PyTuple_New(len);
@@ -5684,7 +5808,7 @@ PyTypeObject pyrna_struct_meta_idprop_Type = {
NULL, /* struct PyMethodDef *tp_methods; */
NULL, /* struct PyMemberDef *tp_members; */
NULL, /* struct PyGetSetDef *tp_getset; */
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
NULL, /* defer assignment */
#else
&PyType_Type, /* struct _typeobject *tp_base; */
@@ -6259,7 +6383,7 @@ static PyTypeObject pyrna_prop_collection_iter_Type = {
NULL, /* reprfunc tp_str; */
/* will only use these if this is a subtype of a py class */
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
NULL, /* defer assignment */
#else
PyObject_GenericGetAttr, /* getattrofunc tp_getattro; */
@@ -6292,7 +6416,7 @@ static PyTypeObject pyrna_prop_collection_iter_Type = {
#endif
/*** Added in release 2.2 ***/
/* Iterators */
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
NULL, /* defer assignment */
#else
PyObject_SelfIter, /* getiterfunc tp_iter; */
@@ -6476,7 +6600,7 @@ static PyObject *pyrna_srna_ExternalType(StructRNA *srna)
if (bpy_types == NULL) {
PyErr_Print();
PyErr_Clear();
- fprintf(stderr, "%s: failed to find 'bpy_types' module\n", __func__);
+ CLOG_ERROR(BPY_LOG_RNA, "failed to find 'bpy_types' module");
return NULL;
}
bpy_types_dict = PyModule_GetDict(bpy_types); /* borrow */
@@ -6494,20 +6618,22 @@ static PyObject *pyrna_srna_ExternalType(StructRNA *srna)
PyObject *tp_slots = PyDict_GetItem(((PyTypeObject *)newclass)->tp_dict, bpy_intern_str___slots__);
if (tp_slots == NULL) {
- fprintf(stderr, "%s: expected class '%s' to have __slots__ defined\n\nSee bpy_types.py\n", __func__, idname);
+ CLOG_ERROR(BPY_LOG_RNA, "expected class '%s' to have __slots__ defined, see bpy_types.py", idname);
newclass = NULL;
}
else if (PyTuple_GET_SIZE(tp_bases)) {
PyObject *base = PyTuple_GET_ITEM(tp_bases, 0);
if (base_compare != base) {
- fprintf(stderr, "%s: incorrect subclassing of SRNA '%s'\nSee bpy_types.py\n", __func__, idname);
- PyC_ObSpit("Expected! ", base_compare);
+ char pyob_info[256];
+ PyC_ObSpitStr(pyob_info, sizeof(pyob_info), base_compare);
+ CLOG_ERROR(BPY_LOG_RNA,
+ "incorrect subclassing of SRNA '%s', expected '%s', see bpy_types.py",
+ idname, pyob_info);
newclass = NULL;
}
else {
- if (G.debug & G_DEBUG_PYTHON)
- fprintf(stderr, "SRNA Subclassed: '%s'\n", idname);
+ CLOG_INFO(BPY_LOG_RNA, 2, "SRNA sub-classed: '%s'", idname);
}
}
}
@@ -6605,7 +6731,7 @@ static PyObject *pyrna_srna_Subtype(StructRNA *srna)
}
else {
/* this should not happen */
- printf("%s: error registering '%s'\n", __func__, idname);
+ CLOG_ERROR(BPY_LOG_RNA, "failed to register '%s'", idname);
PyErr_Print();
PyErr_Clear();
}
@@ -6640,7 +6766,30 @@ PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr)
if (ptr->data == NULL && ptr->type == NULL) { /* Operator RNA has NULL data */
Py_RETURN_NONE;
}
- else {
+
+ /* New in 2.8x, since not many types support instancing
+ * we may want to use a flag to avoid looping over all classes. - campbell */
+ void **instance = ptr->data ? RNA_struct_instance(ptr) : NULL;
+ if (instance && *instance) {
+ pyrna = *instance;
+
+ /* Refine may have changed types after the first instance was created. */
+ if (ptr->type == pyrna->ptr.type) {
+ Py_INCREF(pyrna);
+ return (PyObject *)pyrna;
+ }
+ else {
+ /* Existing users will need to use 'type_recast' method. */
+ Py_DECREF(pyrna);
+ *instance = NULL;
+ /* Continue as if no instance was made */
+#if 0 /* no need to assign, will be written to next... */
+ pyrna = NULL;
+#endif
+ }
+ }
+
+ {
PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
if (tp) {
@@ -6648,7 +6797,7 @@ PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr)
Py_DECREF(tp); /* srna owns, cant hold a ref */
}
else {
- fprintf(stderr, "%s: could not make type\n", __func__);
+ CLOG_WARN(BPY_LOG_RNA, "could not make type '%s'", RNA_struct_identifier(ptr->type));
pyrna = (BPy_StructRNA *) PyObject_GC_New(BPy_StructRNA, &pyrna_struct_Type);
#ifdef USE_WEAKREFS
pyrna->in_weakreflist = NULL;
@@ -6661,6 +6810,12 @@ PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr)
return NULL;
}
+ /* Blender's instance owns a reference (to avoid Python freeing it). */
+ if (instance) {
+ *instance = pyrna;
+ Py_INCREF(pyrna);
+ }
+
pyrna->ptr = *ptr;
#ifdef PYRNA_FREE_SUPPORT
pyrna->freeptr = false;
@@ -6745,7 +6900,7 @@ PyObject *pyrna_id_CreatePyObject(ID *id)
bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
{
- if (BPy_StructRNA_Check(obj) && (RNA_struct_is_ID(((BPy_StructRNA *)obj)->ptr.type))) {
+ if (pyrna_id_CheckPyObject(obj)) {
*id = ((BPy_StructRNA *)obj)->ptr.id.data;
return true;
}
@@ -6755,6 +6910,11 @@ bool pyrna_id_FromPyObject(PyObject *obj, ID **id)
}
}
+bool pyrna_id_CheckPyObject(PyObject *obj)
+{
+ return BPy_StructRNA_Check(obj) && (RNA_struct_is_ID(((BPy_StructRNA *) obj)->ptr.type));
+}
+
void BPY_rna_init(void)
{
#ifdef USE_MATHUTILS /* register mathutils callbacks, ok to run more than once. */
@@ -6763,7 +6923,7 @@ void BPY_rna_init(void)
#endif
/* for some reason MSVC complains of these */
-#if defined(_MSC_VER) || defined(FREE_WINDOWS)
+#if defined(_MSC_VER)
pyrna_struct_meta_idprop_Type.tp_base = &PyType_Type;
pyrna_prop_collection_iter_Type.tp_iter = PyObject_SelfIter;
@@ -6911,15 +7071,7 @@ static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
{
StructRNA *srna = itemptr.data;
- StructRNA *srna_base = RNA_struct_base(itemptr.data);
- /* skip own operators, these double up [#29666] */
- if (srna_base == &RNA_Operator) {
- /* do nothing */
- }
- else {
- /* add to python list */
- PyList_APPEND(ret, PyUnicode_FromString(RNA_struct_identifier(srna)));
- }
+ PyList_APPEND(ret, PyUnicode_FromString(RNA_struct_identifier(srna)));
}
RNA_PROP_END;
@@ -7089,6 +7241,21 @@ static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item
args_fake = PyTuple_New(1);
PyTuple_SET_ITEM(args_fake, 0, py_srna_cobject);
+ PyObject *type = PyDict_GetItemString(py_kw, "type");
+ StructRNA *type_srna = srna_from_self(type, "");
+ if (type_srna) {
+ if (!RNA_struct_idprops_datablock_allowed(srna) &&
+ (*(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) == BPy_PointerProperty ||
+ *(PyCFunctionWithKeywords)PyCFunction_GET_FUNCTION(py_func) == BPy_CollectionProperty) &&
+ RNA_struct_idprops_contains_datablock(type_srna))
+ {
+ PyErr_Format(PyExc_ValueError,
+ "bpy_struct \"%.200s\" doesn't support datablock properties \n",
+ RNA_struct_identifier(srna));
+ return -1;
+ }
+ }
+
py_ret = PyObject_Call(py_func, args_fake, py_kw);
if (py_ret) {
@@ -7237,15 +7404,12 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
{
const ListBase *lb;
Link *link;
- FunctionRNA *func;
- PropertyRNA *prop;
const char *class_type = RNA_struct_identifier(srna);
StructRNA *srna_base = RNA_struct_base(srna);
PyObject *py_class = (PyObject *)py_data;
PyObject *base_class = RNA_struct_py_type_get(srna);
PyObject *item;
- int i, flag, arg_count, func_arg_count, func_arg_min_count = 0;
- bool is_staticmethod;
+ int i, arg_count, func_arg_count, func_arg_min_count = 0;
const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; /* __name__ */
if (srna_base) {
@@ -7266,9 +7430,12 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
lb = RNA_struct_type_functions(srna);
i = 0;
for (link = lb->first; link; link = link->next) {
- func = (FunctionRNA *)link;
- flag = RNA_function_flag(func);
- is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
+ FunctionRNA *func = (FunctionRNA *)link;
+ const int flag = RNA_function_flag(func);
+ /* TODO(campbell): this is used for classmethod's too,
+ * even though class methods should have 'FUNC_USE_SELF_TYPE' set, see Operator.poll for eg.
+ * Keep this as-is since its working but we should be using 'FUNC_USE_SELF_TYPE' for many functions. */
+ const bool is_staticmethod = (flag & FUNC_NO_SELF) && !(flag & FUNC_USE_SELF_TYPE);
if (!(flag & FUNC_REGISTER))
continue;
@@ -7294,7 +7461,8 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
if (is_staticmethod) {
if (PyMethod_Check(item) == 0) {
PyErr_Format(PyExc_TypeError,
- "expected %.200s, %.200s class \"%.200s\" attribute to be a method, not a %.200s",
+ "expected %.200s, %.200s class \"%.200s\" "
+ "attribute to be a static/class method, not a %.200s",
class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
return -1;
}
@@ -7303,7 +7471,8 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
else {
if (PyFunction_Check(item) == 0) {
PyErr_Format(PyExc_TypeError,
- "expected %.200s, %.200s class \"%.200s\" attribute to be a function, not a %.200s",
+ "expected %.200s, %.200s class \"%.200s\" "
+ "attribute to be a function, not a %.200s",
class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
return -1;
}
@@ -7315,7 +7484,7 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
/* note, the number of args we check for and the number of args we give to
- * @staticmethods are different (quirk of python),
+ * '@staticmethods' are different (quirk of python),
* this is why rna_function_arg_count() doesn't return the value -1*/
if (is_staticmethod) {
func_arg_count++;
@@ -7346,8 +7515,8 @@ static int bpy_class_validate_recursive(PointerRNA *dummyptr, StructRNA *srna, v
lb = RNA_struct_type_properties(srna);
for (link = lb->first; link; link = link->next) {
const char *identifier;
- prop = (PropertyRNA *)link;
- flag = RNA_property_flag(prop);
+ PropertyRNA *prop = (PropertyRNA *)link;
+ const int flag = RNA_property_flag(prop);
if (!(flag & PROP_REGISTER))
continue;
@@ -7411,7 +7580,6 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
PyObject *args;
PyObject *ret = NULL, *py_srna = NULL, *py_class_instance = NULL, *parmitem;
PyTypeObject *py_class;
- void **py_class_instance_store = NULL;
PropertyRNA *parm;
ParameterIterator iter;
PointerRNA funcptr;
@@ -7426,7 +7594,7 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
PyGILState_STATE gilstate;
#ifdef USE_PEDANTIC_WRITE
- const bool is_operator = RNA_struct_is_a(ptr->type, &RNA_Operator);
+ const bool is_readonly_init = !RNA_struct_is_a(ptr->type, &RNA_Operator);
// const char *func_id = RNA_function_identifier(func); /* UNUSED */
/* testing, for correctness, not operator and not draw function */
const bool is_readonly = !(RNA_function_flag(func) & FUNC_ALLOW_WRITE);
@@ -7435,8 +7603,7 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
py_class = RNA_struct_py_type_get(ptr->type);
/* rare case. can happen when registering subclasses */
if (py_class == NULL) {
- fprintf(stderr, "%s: unable to get python class for rna struct '%.200s'\n",
- __func__, RNA_struct_identifier(ptr->type));
+ CLOG_WARN(BPY_LOG_RNA, "unable to get Python class for rna struct '%.200s'", RNA_struct_identifier(ptr->type));
return -1;
}
@@ -7461,10 +7628,6 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
py_class_instance = *instance;
Py_INCREF(py_class_instance);
}
- else {
- /* store the instance here once its created */
- py_class_instance_store = instance;
- }
}
}
/* end exception */
@@ -7491,7 +7654,7 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
if (py_class->tp_init) {
#ifdef USE_PEDANTIC_WRITE
const int prev_write = rna_disallow_writes;
- rna_disallow_writes = is_operator ? false : true; /* only operators can write on __init__ */
+ rna_disallow_writes = is_readonly_init ? false : true; /* only operators can write on __init__ */
#endif
/* true in most cases even when the class its self doesn't define an __init__ function. */
@@ -7535,10 +7698,6 @@ static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, Param
if (py_class_instance == NULL) {
err = -1; /* so the error is not overridden below */
}
- else if (py_class_instance_store) {
- *py_class_instance_store = py_class_instance;
- Py_INCREF(py_class_instance);
- }
}
}
diff --git a/source/blender/python/intern/bpy_rna.h b/source/blender/python/intern/bpy_rna.h
index e38d4f095d6..f666294666e 100644
--- a/source/blender/python/intern/bpy_rna.h
+++ b/source/blender/python/intern/bpy_rna.h
@@ -179,20 +179,24 @@ PyObject *pyrna_prop_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop);
/* extern'd by other modules which don't deal closely with RNA */
PyObject *pyrna_id_CreatePyObject(struct ID *id);
bool pyrna_id_FromPyObject(PyObject *obj, struct ID **id);
+bool pyrna_id_CheckPyObject(PyObject *obj);
/* operators also need this to set args */
int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const bool all_args, const char *error_prefix);
PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop);
unsigned int *pyrna_set_to_enum_bitmap(
- struct EnumPropertyItem *items, PyObject *value,
+ const struct EnumPropertyItem *items, PyObject *value,
int type_size, bool type_convert_sign,
int bitmap_size,
const char *error_prefix);
-PyObject *pyrna_enum_bitfield_to_py(struct EnumPropertyItem *items, int value);
-int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix);
+PyObject *pyrna_enum_bitfield_to_py(
+ const struct EnumPropertyItem *items, int value);
+int pyrna_set_to_enum_bitfield(
+ const struct EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix);
-int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix);
+int pyrna_enum_value_from_id(
+ const EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix);
int pyrna_deferred_register_class(struct StructRNA *srna, PyTypeObject *py_class);
diff --git a/source/blender/python/intern/bpy_rna_anim.c b/source/blender/python/intern/bpy_rna_anim.c
index 8a0130babd5..9f9bb46c8bb 100644
--- a/source/blender/python/intern/bpy_rna_anim.c
+++ b/source/blender/python/intern/bpy_rna_anim.c
@@ -53,7 +53,7 @@
#include "WM_types.h"
#include "bpy_rna.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_rna_anim.h"
#include "../generic/python_utildefines.h"
diff --git a/source/blender/python/intern/bpy_rna_array.c b/source/blender/python/intern/bpy_rna_array.c
index 38931cd85de..ed9d1e9c0e5 100644
--- a/source/blender/python/intern/bpy_rna_array.c
+++ b/source/blender/python/intern/bpy_rna_array.c
@@ -28,16 +28,23 @@
#include <Python.h>
+#include "CLG_log.h"
+
+#include "BLI_utildefines.h"
+
#include "RNA_types.h"
#include "bpy_rna.h"
#include "BKE_global.h"
-#include "MEM_guardedalloc.h"
-#include "BLI_utildefines.h"
+#include "MEM_guardedalloc.h"
#include "RNA_access.h"
+#include "BPY_extern_clog.h"
+
+#include "../generic/py_capi_utils.h"
+
#define USE_MATHUTILS
#ifdef USE_MATHUTILS
@@ -550,7 +557,7 @@ static void py_to_float(const struct ItemConvertArgData *arg, PyObject *py, char
static void py_to_int(const struct ItemConvertArgData *arg, PyObject *py, char *data)
{
const int *range = arg->int_data.range;
- int value = (int)PyLong_AsLong(py);
+ int value = PyC_Long_AsI32(py);
CLAMP(value, range[0], range[1]);
*(int *)data = value;
}
@@ -782,8 +789,7 @@ PyObject *pyrna_py_from_array_index(BPy_PropertyArrayRNA *self, PointerRNA *ptr,
len = RNA_property_multi_array_length(ptr, prop, arraydim);
if (index >= len || index < 0) {
/* this shouldn't happen because higher level funcs must check for invalid index */
- if (G.debug & G_DEBUG_PYTHON)
- printf("%s: invalid index %d for array with length=%d\n", __func__, index, len);
+ CLOG_WARN(BPY_LOG_RNA, "invalid index %d for array with length=%d", index, len);
PyErr_SetString(PyExc_IndexError, "out of range");
return NULL;
diff --git a/source/blender/python/intern/bpy_rna_callback.c b/source/blender/python/intern/bpy_rna_callback.c
index df1c4155a6d..01a25137a98 100644
--- a/source/blender/python/intern/bpy_rna_callback.c
+++ b/source/blender/python/intern/bpy_rna_callback.c
@@ -36,7 +36,7 @@
#include "bpy_rna.h"
#include "bpy_rna_callback.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "DNA_space_types.h"
#include "DNA_screen_types.h"
@@ -53,7 +53,7 @@
#define RNA_CAPSULE_ID "RNA_HANDLE"
#define RNA_CAPSULE_ID_INVALID "RNA_HANDLE_REMOVED"
-static EnumPropertyItem region_draw_mode_items[] = {
+static const EnumPropertyItem region_draw_mode_items[] = {
{REGION_DRAW_POST_PIXEL, "POST_PIXEL", 0, "Post Pixel", ""},
{REGION_DRAW_POST_VIEW, "POST_VIEW", 0, "Post View", ""},
{REGION_DRAW_PRE_VIEW, "PRE_VIEW", 0, "Pre View", ""},
@@ -189,7 +189,7 @@ PyObject *pyrna_callback_classmethod_add(PyObject *UNUSED(self), PyObject *args)
StructRNA *srna;
if (PyTuple_GET_SIZE(args) < 2) {
- PyErr_SetString(PyExc_ValueError, "handler_add(handle): expected at least 2 args");
+ PyErr_SetString(PyExc_ValueError, "handler_add(handler): expected at least 2 args");
return NULL;
}
@@ -252,7 +252,7 @@ PyObject *pyrna_callback_classmethod_remove(PyObject *UNUSED(self), PyObject *ar
int cb_regiontype;
if (PyTuple_GET_SIZE(args) < 2) {
- PyErr_SetString(PyExc_ValueError, "callback_remove(handle): expected at least 2 args");
+ PyErr_SetString(PyExc_ValueError, "callback_remove(handler): expected at least 2 args");
return NULL;
}
@@ -263,7 +263,7 @@ PyObject *pyrna_callback_classmethod_remove(PyObject *UNUSED(self), PyObject *ar
py_handle = PyTuple_GET_ITEM(args, 1);
handle = PyCapsule_GetPointer(py_handle, RNA_CAPSULE_ID);
if (handle == NULL) {
- PyErr_SetString(PyExc_ValueError, "callback_remove(handle): NULL handle given, invalid or already removed");
+ PyErr_SetString(PyExc_ValueError, "callback_remove(handler): NULL handler given, invalid or already removed");
return NULL;
}
diff --git a/source/blender/python/intern/bpy_rna_driver.c b/source/blender/python/intern/bpy_rna_driver.c
index b4c0de51c04..1135ba121e3 100644
--- a/source/blender/python/intern/bpy_rna_driver.c
+++ b/source/blender/python/intern/bpy_rna_driver.c
@@ -63,7 +63,15 @@ PyObject *pyrna_driver_get_variable_value(
}
else {
/* object & property */
- driver_arg = pyrna_prop_to_py(&ptr, prop);
+ PropertyType type = RNA_property_type(prop);
+ if (type == PROP_ENUM) {
+ /* Note that enum's are converted to strings by default,
+ * we want to avoid that, see: T52213 */
+ driver_arg = PyLong_FromLong(RNA_property_enum_get(&ptr, prop));
+ }
+ else {
+ driver_arg = pyrna_prop_to_py(&ptr, prop);
+ }
}
}
else {
diff --git a/source/blender/python/intern/bpy_rna_id_collection.c b/source/blender/python/intern/bpy_rna_id_collection.c
index 72705ffb3fb..ee40d30d73b 100644
--- a/source/blender/python/intern/bpy_rna_id_collection.c
+++ b/source/blender/python/intern/bpy_rna_id_collection.c
@@ -44,7 +44,7 @@
#include "DNA_object_types.h"
#include "DNA_key_types.h"
-#include "bpy_util.h"
+#include "bpy_capi_utils.h"
#include "bpy_rna_id_collection.h"
#include "../generic/py_capi_utils.h"
@@ -163,7 +163,6 @@ static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject *
Main *bmain = G.main; /* XXX Ugly, but should work! */
#endif
- static const char *kwlist[] = {"subset", "key_types", "value_types", NULL};
PyObject *subset = NULL;
PyObject *key_types = NULL;
@@ -173,9 +172,10 @@ static PyObject *bpy_user_map(PyObject *UNUSED(self), PyObject *args, PyObject *
PyObject *ret = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(
- args, kwds, "|O$O!O!:user_map", (char **)kwlist,
+ static const char *_keywords[] = {"subset", "key_types", "value_types", NULL};
+ static _PyArg_Parser _parser = {"|O$O!O!:user_map", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kwds, &_parser,
&subset,
&PySet_Type, &key_types,
&PySet_Type, &val_types))
diff --git a/source/blender/python/intern/bpy_utils_units.c b/source/blender/python/intern/bpy_utils_units.c
index 974d7c5549c..0ef689d1a5a 100644
--- a/source/blender/python/intern/bpy_utils_units.c
+++ b/source/blender/python/intern/bpy_utils_units.c
@@ -174,8 +174,6 @@ PyDoc_STRVAR(bpyunits_to_value_doc,
);
static PyObject *bpyunits_to_value(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"unit_system", "unit_category", "str_input", "str_ref_unit", NULL};
-
char *usys_str = NULL, *ucat_str = NULL, *inpt = NULL, *uref = NULL;
const float scale = 1.0f;
@@ -185,8 +183,13 @@ static PyObject *bpyunits_to_value(PyObject *UNUSED(self), PyObject *args, PyObj
int usys, ucat;
PyObject *ret;
- if (!PyArg_ParseTupleAndKeywords(args, kw, "sss#|z:bpy.utils.units.to_value", (char **)kwlist,
- &usys_str, &ucat_str, &inpt, &str_len, &uref))
+ static const char *_keywords[] = {
+ "unit_system", "unit_category", "str_input", "str_ref_unit", NULL,
+ };
+ static _PyArg_Parser _parser = {"sss#|z:to_value", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &usys_str, &ucat_str, &inpt, &str_len, &uref))
{
return NULL;
}
@@ -201,7 +204,7 @@ static PyObject *bpyunits_to_value(PyObject *UNUSED(self), PyObject *args, PyObj
bUnit_ReplaceString(str, (int)str_len, uref, scale, usys, ucat);
- if (!PyC_RunString_AsNumber(str, &result, "<bpy_units_api>")) {
+ if (!PyC_RunString_AsNumber(str, "<bpy_units_api>", &result)) {
if (PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
@@ -244,9 +247,6 @@ PyDoc_STRVAR(bpyunits_to_string_doc,
);
static PyObject *bpyunits_to_string(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
- static const char *kwlist[] = {"unit_system", "unit_category", "value",
- "precision", "split_unit", "compatible_unit", NULL};
-
char *usys_str = NULL, *ucat_str = NULL;
double value = 0.0;
int precision = 3;
@@ -254,9 +254,13 @@ static PyObject *bpyunits_to_string(PyObject *UNUSED(self), PyObject *args, PyOb
int usys, ucat;
- if (!PyArg_ParseTupleAndKeywords(
- args, kw,
- "ssd|iO&O&:bpy.utils.units.to_string", (char **)kwlist,
+ static const char *_keywords[] = {
+ "unit_system", "unit_category", "value",
+ "precision", "split_unit", "compatible_unit", NULL,
+ };
+ static _PyArg_Parser _parser = {"ssd|iO&O&:to_string", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
&usys_str, &ucat_str, &value, &precision,
PyC_ParseBool, &split_unit,
PyC_ParseBool, &compatible_unit))
diff --git a/source/blender/python/intern/gpu.c b/source/blender/python/intern/gpu.c
index 48230a723d2..60ce00c583e 100644
--- a/source/blender/python/intern/gpu.c
+++ b/source/blender/python/intern/gpu.c
@@ -207,7 +207,7 @@ PyDoc_STRVAR(GPU_export_shader_doc,
" :return: Dictionary defining the shader, uniforms and attributes.\n"
" :rtype: Dict"
);
-static PyObject *GPU_export_shader(PyObject *UNUSED(self), PyObject *args, PyObject *kwds)
+static PyObject *GPU_export_shader(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
{
PyObject *pyscene;
PyObject *pymat;
@@ -224,11 +224,14 @@ static PyObject *GPU_export_shader(PyObject *UNUSED(self), PyObject *args, PyObj
GPUInputUniform *uniform;
GPUInputAttribute *attribute;
- static const char *kwlist[] = {"scene", "material", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:export_shader", (char **)(kwlist), &pyscene, &pymat))
+ static const char *_keywords[] = {"scene", "material", NULL};
+ static _PyArg_Parser _parser = {"OO:export_shader", _keywords, 0};
+ if (!_PyArg_ParseTupleAndKeywordsFast(
+ args, kw, &_parser,
+ &pyscene, &pymat))
+ {
return NULL;
-
+ }
scene = (Scene *)PyC_RNA_AsPointer(pyscene, "Scene");
if (scene == NULL) {
return NULL;
diff --git a/source/blender/python/intern/gpu_offscreen.c b/source/blender/python/intern/gpu_offscreen.c
index c4863b2a92f..3c340d14e3f 100644
--- a/source/blender/python/intern/gpu_offscreen.c
+++ b/source/blender/python/intern/gpu_offscreen.c
@@ -144,36 +144,6 @@ static PyObject *pygpu_offscreen_unbind(BPy_GPUOffScreen *self, PyObject *args,
Py_RETURN_NONE;
}
-/**
- * Use with PyArg_ParseTuple's "O&" formatting.
- */
-static int pygpu_offscreen_check_matrix(PyObject *o, void *p)
-{
- MatrixObject **pymat_p = p;
- MatrixObject *pymat = (MatrixObject *)o;
-
- if (!MatrixObject_Check(pymat)) {
- PyErr_Format(PyExc_TypeError,
- "expected a mathutils.Matrix, not a %.200s",
- Py_TYPE(o)->tp_name);
- return 0;
- }
-
- if (BaseMath_ReadCallback(pymat) == -1) {
- return 0;
- }
-
- if ((pymat->num_col != 4) ||
- (pymat->num_row != 4))
- {
- PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
- return 0;
- }
-
- *pymat_p = pymat;
- return 1;
-}
-
PyDoc_STRVAR(pygpu_offscreen_draw_view3d_doc,
"draw_view3d(scene, view3d, region, modelview_matrix, projection_matrix)\n"
"\n"
@@ -202,15 +172,15 @@ static PyObject *pygpu_offscreen_draw_view3d(BPy_GPUOffScreen *self, PyObject *a
ARegion *ar;
GPUFX *fx;
GPUFXSettings fx_settings;
- void *rv3d_mats;
+ struct RV3DMatrixStore *rv3d_mats;
BPY_GPU_OFFSCREEN_CHECK_OBJ(self);
if (!PyArg_ParseTupleAndKeywords(
args, kwds, "OOOO&O&:draw_view3d", (char **)(kwlist),
&py_scene, &py_view3d, &py_region,
- pygpu_offscreen_check_matrix, &py_mat_projection,
- pygpu_offscreen_check_matrix, &py_mat_modelview) ||
+ Matrix_Parse4x4, &py_mat_projection,
+ Matrix_Parse4x4, &py_mat_modelview) ||
(!(scene = PyC_RNA_AsPointer(py_scene, "Scene")) ||
!(v3d = PyC_RNA_AsPointer(py_view3d, "SpaceView3D")) ||
!(ar = PyC_RNA_AsPointer(py_region, "Region"))))
diff --git a/source/blender/python/mathutils/mathutils.c b/source/blender/python/mathutils/mathutils.c
index 5c505247a97..96ae0a9e50f 100644
--- a/source/blender/python/mathutils/mathutils.c
+++ b/source/blender/python/mathutils/mathutils.c
@@ -1,4 +1,4 @@
-/*
+/*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -38,18 +38,31 @@
#endif
PyDoc_STRVAR(M_Mathutils_doc,
-"This module provides access to the math classes:\n"
+"This module provides access to math operations.\n"
+"\n"
+".. note::\n"
+"\n"
+" Classes, methods and attributes that accept vectors also accept other numeric sequences,\n"
+" such as tuples, lists."
+"\n\n"
+"Submodules:\n"
+"\n"
+".. toctree::\n"
+" :maxdepth: 1\n"
+"\n"
+" mathutils.geometry.rst\n"
+" mathutils.bvhtree.rst\n"
+" mathutils.kdtree.rst\n"
+" mathutils.interpolate.rst\n"
+" mathutils.noise.rst\n"
+"\n"
+"The :mod:`mathutils` module provides the following classes:\n"
"\n"
"- :class:`Color`,\n"
"- :class:`Euler`,\n"
"- :class:`Matrix`,\n"
"- :class:`Quaternion`,\n"
"- :class:`Vector`,\n"
-"\n"
-".. note::\n"
-"\n"
-" Classes, methods and attributes that accept vectors also accept other numeric sequences,\n"
-" such as tuples, lists."
);
static int mathutils_array_parse_fast(float *array,
int size,
@@ -219,7 +232,7 @@ int mathutils_array_parse_alloc(float **array, int array_min, PyObject *value, c
error_prefix, size, array_min);
return -1;
}
-
+
*array = PyMem_Malloc(size * sizeof(float));
memcpy(*array, ((BaseMathObject *)value)->data, size * sizeof(float));
return size;
@@ -422,7 +435,7 @@ static Mathutils_Callback *mathutils_callbacks[MATHUTILS_TOT_CB] = {NULL};
unsigned char Mathutils_RegisterCallback(Mathutils_Callback *cb)
{
unsigned char i;
-
+
/* find the first free slot */
for (i = 0; mathutils_callbacks[i]; i++) {
if (mathutils_callbacks[i] == cb) /* already registered? */
@@ -541,8 +554,8 @@ char BaseMathObject_freeze_doc[] =
;
PyObject *BaseMathObject_freeze(BaseMathObject *self)
{
- if (self->flag & BASE_MATH_FLAG_IS_WRAP) {
- PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped data");
+ if ((self->flag & BASE_MATH_FLAG_IS_WRAP) || (self->cb_user != NULL)) {
+ PyErr_SetString(PyExc_TypeError, "Cannot freeze wrapped/owned data");
return NULL;
}
@@ -625,14 +638,14 @@ PyMODINIT_FUNC PyInit_mathutils(void)
return NULL;
mod = PyModule_Create(&M_Mathutils_module_def);
-
+
/* each type has its own new() function */
PyModule_AddObject(mod, vector_Type.tp_name, (PyObject *)&vector_Type);
PyModule_AddObject(mod, matrix_Type.tp_name, (PyObject *)&matrix_Type);
PyModule_AddObject(mod, euler_Type.tp_name, (PyObject *)&euler_Type);
PyModule_AddObject(mod, quaternion_Type.tp_name, (PyObject *)&quaternion_Type);
PyModule_AddObject(mod, color_Type.tp_name, (PyObject *)&color_Type);
-
+
/* submodule */
PyModule_AddObject(mod, "geometry", (submodule = PyInit_mathutils_geometry()));
/* XXX, python doesnt do imports with this usefully yet
diff --git a/source/blender/python/mathutils/mathutils.h b/source/blender/python/mathutils/mathutils.h
index 6ac75565c66..ec927a9e316 100644
--- a/source/blender/python/mathutils/mathutils.h
+++ b/source/blender/python/mathutils/mathutils.h
@@ -41,9 +41,18 @@ extern char BaseMathObject_owner_doc[];
(struct_name *)((base_type ? (base_type)->tp_alloc(base_type, 0) : _PyObject_GC_New(&(root_type))));
-/* BaseMathObject.flag */
+/** BaseMathObject.flag */
enum {
+ /**
+ * Do not own the memory used in this vector,
+ * \note This is error prone if the memory may be freed while this vector is in use.
+ * Prefer using callbacks where possible, see: #Mathutils_RegisterCallback
+ */
BASE_MATH_FLAG_IS_WRAP = (1 << 0),
+ /**
+ * Prevent changes to the vector so it can be used as a set or dictionary key for example.
+ * (typical use cases for tuple).
+ */
BASE_MATH_FLAG_IS_FROZEN = (1 << 1),
};
#define BASE_MATH_FLAG_DEFAULT 0
@@ -69,6 +78,10 @@ typedef struct {
#include "mathutils_Euler.h"
#include "mathutils_Color.h"
+/* avoid checking all types */
+#define BaseMathObject_CheckExact(v) \
+ (Py_TYPE(v)->tp_dealloc == (destructor)BaseMathObject_dealloc)
+
PyObject *BaseMathObject_owner_get(BaseMathObject *self, void *);
PyObject *BaseMathObject_is_wrapped_get(BaseMathObject *self, void *);
PyObject *BaseMathObject_is_frozen_get(BaseMathObject *self, void *);
diff --git a/source/blender/python/mathutils/mathutils_Color.c b/source/blender/python/mathutils/mathutils_Color.c
index add8c2451ff..9997cd9c1f5 100644
--- a/source/blender/python/mathutils/mathutils_Color.c
+++ b/source/blender/python/mathutils/mathutils_Color.c
@@ -173,7 +173,7 @@ static PyObject *Color_richcmpr(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
diff --git a/source/blender/python/mathutils/mathutils_Color.h b/source/blender/python/mathutils/mathutils_Color.h
index 1290f73da62..e1a392de3da 100644
--- a/source/blender/python/mathutils/mathutils_Color.h
+++ b/source/blender/python/mathutils/mathutils_Color.h
@@ -30,7 +30,8 @@
#define __MATHUTILS_COLOR_H__
extern PyTypeObject color_Type;
-#define ColorObject_Check(_v) PyObject_TypeCheck((_v), &color_Type)
+#define ColorObject_Check(v) PyObject_TypeCheck((v), &color_Type)
+#define ColorObject_CheckExact(v) (Py_TYPE(v) == &color_Type)
typedef struct {
BASE_MATH_MEMBERS(col);
diff --git a/source/blender/python/mathutils/mathutils_Euler.c b/source/blender/python/mathutils/mathutils_Euler.c
index 54adc826af7..026384743bd 100644
--- a/source/blender/python/mathutils/mathutils_Euler.c
+++ b/source/blender/python/mathutils/mathutils_Euler.c
@@ -65,7 +65,7 @@ static PyObject *Euler_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
case 2:
if ((order = euler_order_from_string(order_str, "mathutils.Euler()")) == -1)
return NULL;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case 1:
if (mathutils_array_parse(eul, EULER_SIZE, EULER_SIZE, seq, "mathutils.Euler()") == -1)
return NULL;
@@ -370,7 +370,7 @@ static PyObject *Euler_richcmpr(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
@@ -689,6 +689,8 @@ PyDoc_STRVAR(euler_doc,
"\n"
" This object gives access to Eulers in Blender.\n"
"\n"
+" .. seealso:: `Euler angles <https://en.wikipedia.org/wiki/Euler_angles>`__ on Wikipedia.\n"
+"\n"
" :param angles: Three angles, in radians.\n"
" :type angles: 3d vector\n"
" :param order: Optional order of the angles, a permutation of ``XYZ``.\n"
diff --git a/source/blender/python/mathutils/mathutils_Euler.h b/source/blender/python/mathutils/mathutils_Euler.h
index 744f39faed1..4f5ba76b8df 100644
--- a/source/blender/python/mathutils/mathutils_Euler.h
+++ b/source/blender/python/mathutils/mathutils_Euler.h
@@ -29,7 +29,8 @@
*/
extern PyTypeObject euler_Type;
-#define EulerObject_Check(_v) PyObject_TypeCheck((_v), &euler_Type)
+#define EulerObject_Check(v) PyObject_TypeCheck((v), &euler_Type)
+#define EulerObject_CheckExact(v) (Py_TYPE(v) == &euler_Type)
typedef struct {
BASE_MATH_MEMBERS(eul);
diff --git a/source/blender/python/mathutils/mathutils_Matrix.c b/source/blender/python/mathutils/mathutils_Matrix.c
index 4e980e4c0e6..cc6a5367895 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.c
+++ b/source/blender/python/mathutils/mathutils_Matrix.c
@@ -1301,7 +1301,7 @@ PyDoc_STRVAR(Matrix_to_scale_doc,
" :return: Return the scale of a matrix.\n"
" :rtype: :class:`Vector`\n"
"\n"
-" .. note:: This method does not return negative a scale on any axis because it is not possible to obtain this data from the matrix alone.\n"
+" .. note:: This method does not return a negative scale on any axis because it is not possible to obtain this data from the matrix alone.\n"
);
static PyObject *Matrix_to_scale(MatrixObject *self)
{
@@ -1390,11 +1390,11 @@ PyDoc_STRVAR(Matrix_invert_doc,
"\n"
" Set the matrix to its inverse.\n"
"\n"
-" :arg fallback: Set the matrix to this value when the inverse can't be calculated\n"
+" :arg fallback: Set the matrix to this value when the inverse cannot be calculated\n"
" (instead of raising a :exc:`ValueError` exception).\n"
" :type fallback: :class:`Matrix`\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Inverse_matrix>\n"
+" .. seealso:: `Inverse matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on Wikipedia.\n"
);
static PyObject *Matrix_invert(MatrixObject *self, PyObject *args)
{
@@ -1505,7 +1505,7 @@ PyDoc_STRVAR(Matrix_invert_safe_doc,
" If degenerated (e.g. zero scale on an axis), add some epsilon to its diagonal, to get an invertible one.\n"
" If tweaked matrix is still degenerated, set to the identity matrix instead.\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Inverse_matrix>\n"
+" .. seealso:: `Inverse Matrix <https://en.wikipedia.org/wiki/Inverse_matrix>` on Wikipedia.\n"
);
static PyObject *Matrix_invert_safe(MatrixObject *self)
{
@@ -1554,9 +1554,9 @@ PyDoc_STRVAR(Matrix_adjugate_doc,
"\n"
" Set the matrix to its adjugate.\n"
"\n"
-" .. note:: When the matrix cant be adjugated a :exc:`ValueError` exception is raised.\n"
+" .. note:: When the matrix cannot be adjugated a :exc:`ValueError` exception is raised.\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Adjugate_matrix>\n"
+" .. seealso:: `Adjugate matrix <https://en.wikipedia.org/wiki/Adjugate_matrix>` on Wikipedia.\n"
);
static PyObject *Matrix_adjugate(MatrixObject *self)
{
@@ -1641,9 +1641,9 @@ static PyObject *Matrix_rotate(MatrixObject *self, PyObject *value)
PyDoc_STRVAR(Matrix_decompose_doc,
".. method:: decompose()\n"
"\n"
-" Return the location, rotation and scale components of this matrix.\n"
+" Return the translation, rotation, and scale components of this matrix.\n"
"\n"
-" :return: loc, rot, scale triple.\n"
+" :return: tuple of translation, rotation, and scale\n"
" :rtype: (:class:`Vector`, :class:`Quaternion`, :class:`Vector`)"
);
static PyObject *Matrix_decompose(MatrixObject *self)
@@ -1680,7 +1680,8 @@ static PyObject *Matrix_decompose(MatrixObject *self)
PyDoc_STRVAR(Matrix_lerp_doc,
".. function:: lerp(other, factor)\n"
"\n"
-" Returns the interpolation of two matrices.\n"
+" Returns the interpolation of two matrices. Uses polar decomposition, see"
+" \"Matrix Animation and Polar Decomposition\", Shoemake and Duff, 1992.\n"
"\n"
" :arg other: value to interpolate with.\n"
" :type other: :class:`Matrix`\n"
@@ -1709,10 +1710,18 @@ static PyObject *Matrix_lerp(MatrixObject *self, PyObject *args)
/* TODO, different sized matrix */
if (self->num_col == 4 && self->num_row == 4) {
+#ifdef MATH_STANDALONE
blend_m4_m4m4((float (*)[4])mat, (float (*)[4])self->matrix, (float (*)[4])mat2->matrix, fac);
+#else
+ interp_m4_m4m4((float (*)[4])mat, (float (*)[4])self->matrix, (float (*)[4])mat2->matrix, fac);
+#endif
}
else if (self->num_col == 3 && self->num_row == 3) {
+#ifdef MATH_STANDALONE
blend_m3_m3m3((float (*)[3])mat, (float (*)[3])self->matrix, (float (*)[3])mat2->matrix, fac);
+#else
+ interp_m3_m3m3((float (*)[3])mat, (float (*)[3])self->matrix, (float (*)[3])mat2->matrix, fac);
+#endif
}
else {
PyErr_SetString(PyExc_ValueError,
@@ -1733,7 +1742,7 @@ PyDoc_STRVAR(Matrix_determinant_doc,
" :return: Return the determinant of a matrix.\n"
" :rtype: float\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Determinant>\n"
+" .. seealso:: `Determinant <https://en.wikipedia.org/wiki/Determinant>` on Wikipedia.\n"
);
static PyObject *Matrix_determinant(MatrixObject *self)
{
@@ -1755,7 +1764,7 @@ PyDoc_STRVAR(Matrix_transpose_doc,
"\n"
" Set the matrix to its transpose.\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Transpose>\n"
+" .. seealso:: `Transpose <https://en.wikipedia.org/wiki/Transpose>` on Wikipedia.\n"
);
static PyObject *Matrix_transpose(MatrixObject *self)
{
@@ -1887,10 +1896,10 @@ PyDoc_STRVAR(Matrix_identity_doc,
"\n"
" Set the matrix to the identity matrix.\n"
"\n"
-" .. note:: An object with zero location and rotation, a scale of one,\n"
+" .. note:: An object with a location and rotation of zero, and a scale of one\n"
" will have an identity matrix.\n"
"\n"
-" .. seealso:: <https://en.wikipedia.org/wiki/Identity_matrix>\n"
+" .. seealso:: `Identity matrix <https://en.wikipedia.org/wiki/Identity_matrix>` on Wikipedia.\n"
);
static PyObject *Matrix_identity(MatrixObject *self)
{
@@ -2034,7 +2043,7 @@ static PyObject *Matrix_richcmpr(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
@@ -2914,6 +2923,73 @@ PyObject *Matrix_CreatePyObject_cb(PyObject *cb_user,
return (PyObject *) self;
}
+/**
+ * Use with PyArg_ParseTuple's "O&" formatting.
+ */
+static bool Matrix_ParseCheck(MatrixObject *pymat)
+{
+ if (!MatrixObject_Check(pymat)) {
+ PyErr_Format(PyExc_TypeError,
+ "expected a mathutils.Matrix, not a %.200s",
+ Py_TYPE(pymat)->tp_name);
+ return 0;
+ }
+ /* sets error */
+ if (BaseMath_ReadCallback(pymat) == -1) {
+ return 0;
+ }
+ return 1;
+}
+
+int Matrix_ParseAny(PyObject *o, void *p)
+{
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
+
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ *pymat_p = pymat;
+ return 1;
+}
+
+int Matrix_Parse3x3(PyObject *o, void *p)
+{
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
+
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ if ((pymat->num_col != 3) ||
+ (pymat->num_row != 3))
+ {
+ PyErr_SetString(PyExc_ValueError, "matrix must be 3x3");
+ return 0;
+ }
+
+ *pymat_p = pymat;
+ return 1;
+}
+
+int Matrix_Parse4x4(PyObject *o, void *p)
+{
+ MatrixObject **pymat_p = p;
+ MatrixObject *pymat = (MatrixObject *)o;
+
+ if (!Matrix_ParseCheck(pymat)) {
+ return 0;
+ }
+ if ((pymat->num_col != 4) ||
+ (pymat->num_row != 4))
+ {
+ PyErr_SetString(PyExc_ValueError, "matrix must be 4x4");
+ return 0;
+ }
+
+ *pymat_p = pymat;
+ return 1;
+}
/* ----------------------------------------------------------------------------
* special type for alternate access */
diff --git a/source/blender/python/mathutils/mathutils_Matrix.h b/source/blender/python/mathutils/mathutils_Matrix.h
index 542a0e349c7..d2fbe6a04d5 100644
--- a/source/blender/python/mathutils/mathutils_Matrix.h
+++ b/source/blender/python/mathutils/mathutils_Matrix.h
@@ -30,7 +30,10 @@
extern PyTypeObject matrix_Type;
extern PyTypeObject matrix_access_Type;
-#define MatrixObject_Check(_v) PyObject_TypeCheck((_v), &matrix_Type)
+
+#define MatrixObject_Check(v) PyObject_TypeCheck((v), &matrix_Type)
+#define MatrixObject_CheckExact(v) (Py_TYPE(v) == &matrix_Type)
+
#define MATRIX_MAX_DIM 4
/* matrix[row][col] == MATRIX_ITEM_INDEX(matrix, row, col) */
@@ -77,6 +80,11 @@ PyObject *Matrix_CreatePyObject_cb(
unsigned char cb_type, unsigned char cb_subtype
) ATTR_WARN_UNUSED_RESULT;
+/* PyArg_ParseTuple's "O&" formatting helpers. */
+int Matrix_ParseAny(PyObject *o, void *p);
+int Matrix_Parse3x3(PyObject *o, void *p);
+int Matrix_Parse4x4(PyObject *o, void *p);
+
extern unsigned char mathutils_matrix_row_cb_index; /* default */
extern unsigned char mathutils_matrix_col_cb_index;
extern unsigned char mathutils_matrix_translation_cb_index;
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.c b/source/blender/python/mathutils/mathutils_Quaternion.c
index 71b3cf8ddac..d283c717a46 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.c
+++ b/source/blender/python/mathutils/mathutils_Quaternion.c
@@ -552,7 +552,7 @@ static PyObject *Quaternion_richcmpr(PyObject *a, PyObject *b, int op)
switch (op) {
case Py_NE:
ok = !ok;
- /* fall-through */
+ ATTR_FALLTHROUGH;
case Py_EQ:
res = ok ? Py_False : Py_True;
break;
diff --git a/source/blender/python/mathutils/mathutils_Quaternion.h b/source/blender/python/mathutils/mathutils_Quaternion.h
index 66ee3362906..46f305b0f0e 100644
--- a/source/blender/python/mathutils/mathutils_Quaternion.h
+++ b/source/blender/python/mathutils/mathutils_Quaternion.h
@@ -28,7 +28,9 @@
*/
extern PyTypeObject quaternion_Type;
-#define QuaternionObject_Check(_v) PyObject_TypeCheck((_v), &quaternion_Type)
+
+#define QuaternionObject_Check(v) PyObject_TypeCheck((v), &quaternion_Type)
+#define QuaternionObject_CheckExact(v) (Py_TYPE(v) == &quaternion_Type)
typedef struct {
BASE_MATH_MEMBERS(quat);
diff --git a/source/blender/python/mathutils/mathutils_Vector.c b/source/blender/python/mathutils/mathutils_Vector.c
index afc8a30a6b5..65450505e08 100644
--- a/source/blender/python/mathutils/mathutils_Vector.c
+++ b/source/blender/python/mathutils/mathutils_Vector.c
@@ -32,10 +32,17 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
+#include "../generic/py_capi_utils.h"
+
#ifndef MATH_STANDALONE
# include "BLI_dynstr.h"
#endif
+/**
+ * Higher dimensions are supported, for many common operations
+ * (dealing with vector/matrix multiply or handling as 3D locations)
+ * stack memory is used with a fixed size - defined here.
+ */
#define MAX_DIMENSIONS 4
/* Swizzle axes get packed into a single value that is used as a closure. Each
@@ -50,7 +57,8 @@ static PyObject *Vector_deepcopy(VectorObject *self, PyObject *args);
static PyObject *Vector_to_tuple_ext(VectorObject *self, int ndigits);
static int row_vector_multiplication(float rvec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat);
-/* Supports 2D, 3D, and 4D vector objects both int and float values
+/**
+ * Supports 2D, 3D, and 4D vector objects both int and float values
* accepted. Mixed float and int values accepted. Ints are parsed to float
*/
static PyObject *Vector_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -403,7 +411,7 @@ static PyObject *Vector_resize(VectorObject *self, PyObject *value)
return NULL;
}
- if ((size = PyLong_AsLong(value)) == -1) {
+ if ((size = PyC_Long_AsI32(value)) == -1) {
PyErr_SetString(PyExc_TypeError,
"Vector.resize(size): "
"expected size argument to be an integer");
@@ -836,9 +844,11 @@ static PyObject *Vector_orthogonal(VectorObject *self)
}
-/*
- * Vector.reflect(mirror): return a reflected vector on the mirror normal
- * vec - ((2 * DotVecs(vec, mirror)) * mirror)
+/**
+ * Vector.reflect(mirror): return a reflected vector on the mirror normal.
+ * <pre>
+ * vec - ((2 * dot(vec, mirror)) * mirror)
+ * </pre>
*/
PyDoc_STRVAR(Vector_reflect_doc,
".. method:: reflect(mirror)\n"
@@ -1644,13 +1654,16 @@ static PyObject *Vector_isub(PyObject *v1, PyObject *v2)
* multiplication */
-/* COLUMN VECTOR Multiplication (Matrix X Vector)
+/**
+ * column vector multiplication (Matrix * Vector)
+ * <pre>
* [1][4][7] [a]
* [2][5][8] * [b]
* [3][6][9] [c]
+ * </pre>
*
- * note: vector/matrix multiplication IS NOT COMMUTATIVE!!!!
- * note: assume read callbacks have been done first.
+ * \note Vector/Matrix multiplication is not commutative.
+ * \note Assume read callbacks have been done first.
*/
int column_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat)
{
@@ -2199,9 +2212,67 @@ static PyObject *Vector_length_squared_get(VectorObject *self, void *UNUSED(clos
return PyFloat_FromDouble(dot_vn_vn(self->vec, self->vec, self->size));
}
-/* Get a new Vector according to the provided swizzle. This function has little
- * error checking, as we are in control of the inputs: the closure is set by us
- * in Vector_createSwizzleGetSeter. */
+
+/**
+ * Python script used to make swizzle array:
+ *
+ * \code{.py}
+ * SWIZZLE_BITS_PER_AXIS = 3
+ * SWIZZLE_VALID_AXIS = 0x4
+ *
+ * axis_dict = {}
+ * axis_pos = {'x': 0, 'y': 1, 'z': 2, 'w': 3}
+ * axises = 'xyzw'
+ * while len(axises) >= 2:
+ * for axis_0 in axises:
+ * axis_0_pos = axis_pos[axis_0]
+ * for axis_1 in axises:
+ * axis_1_pos = axis_pos[axis_1]
+ * axis_dict[axis_0 + axis_1] = (
+ * '((%s | SWIZZLE_VALID_AXIS) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS))' %
+ * (axis_0_pos, axis_1_pos))
+ * if len(axises) > 2:
+ * for axis_2 in axises:
+ * axis_2_pos = axis_pos[axis_2]
+ * axis_dict[axis_0 + axis_1 + axis_2] = (
+ * '((%s | SWIZZLE_VALID_AXIS) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))' %
+ * (axis_0_pos, axis_1_pos, axis_2_pos))
+ * if len(axises) > 3:
+ * for axis_3 in axises:
+ * axis_3_pos = axis_pos[axis_3]
+ * axis_dict[axis_0 + axis_1 + axis_2 + axis_3] = (
+ * '((%s | SWIZZLE_VALID_AXIS) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)) | '
+ * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3))) ' %
+ * (axis_0_pos, axis_1_pos, axis_2_pos, axis_3_pos))
+ *
+ * axises = axises[:-1]
+ *
+ *
+ * items = list(axis_dict.items())
+ * items.sort(key=lambda a: a[0].replace('x', '0').replace('y', '1').replace('z', '2').replace('w', '3'))
+ *
+ * unique = set()
+ * for key, val in items:
+ * num = eval(val)
+ * set_str = 'Vector_swizzle_set' if (len(set(key)) == len(key)) else 'NULL'
+ * key_args = ', '.join(["'%s'" % c for c in key.upper()])
+ * print('\t{(char *)"%s", %s(getter)Vector_swizzle_get, (setter)%s, NULL, SWIZZLE%d(%s)},' %
+ * (key, (' ' * (4 - len(key))), set_str, len(key), key_args))
+ * unique.add(num)
+ *
+ * if len(unique) != len(items):
+ * print("ERROR, duplicate values found")
+ * \endcode
+ */
+
+/**
+ * Get a new Vector according to the provided swizzle bits.
+ */
static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
{
size_t axis_to;
@@ -2232,7 +2303,8 @@ static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
return Vector_CreatePyObject(vec, axis_to, Py_TYPE(self));
}
-/* Set the items of this vector using a swizzle.
+/**
+ * Set the items of this vector using a swizzle.
* - If value is a vector or list this operates like an array copy, except that
* the destination is effectively re-ordered as defined by the swizzle. At
* most min(len(source), len(dest)) values will be copied.
@@ -2240,8 +2312,8 @@ static PyObject *Vector_swizzle_get(VectorObject *self, void *closure)
* - If an axis appears more than once in the swizzle, the final occurrence is
* the one that determines its value.
*
- * Returns 0 on success and -1 on failure. On failure, the vector will be
- * unchanged. */
+ * \return 0 on success and -1 on failure. On failure, the vector will be unchanged.
+ */
static int Vector_swizzle_set(VectorObject *self, PyObject *value, void *closure)
{
size_t size_from;
@@ -2324,19 +2396,14 @@ static int Vector_swizzle_set(VectorObject *self, PyObject *value, void *closure
return 0;
}
-/* XYZW -> 0123 */
-#define AXIS_FROM_CHAR(a) (((a) != 'W') ? ((a) - 'X') : 3)
-
-#define _VA_SWIZZLE_1(a) ( \
- ((AXIS_FROM_CHAR(a) | SWIZZLE_VALID_AXIS)))
-#define _VA_SWIZZLE_2(a, b) (_VA_SWIZZLE_1(a) | \
- ((AXIS_FROM_CHAR(b) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS)))
-#define _VA_SWIZZLE_3(a, b, c) (_VA_SWIZZLE_2(a, b) | \
- ((AXIS_FROM_CHAR(c) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))
-#define _VA_SWIZZLE_4(a, b, c, d) (_VA_SWIZZLE_3(a, b, c) | \
- ((AXIS_FROM_CHAR(d) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3)))
+#define _SWIZZLE1(a) ((a) | SWIZZLE_VALID_AXIS)
+#define _SWIZZLE2(a, b) (_SWIZZLE1(a) | (((b) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS)))
+#define _SWIZZLE3(a, b, c) (_SWIZZLE2(a, b) | (((c) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))
+#define _SWIZZLE4(a, b, c, d) (_SWIZZLE3(a, b, c) | (((d) | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3)))
-#define SWIZZLE(...) SET_INT_IN_POINTER(VA_NARGS_CALL_OVERLOAD(_VA_SWIZZLE_, __VA_ARGS__))
+#define SWIZZLE2(a, b) SET_INT_IN_POINTER(_SWIZZLE2(a, b))
+#define SWIZZLE3(a, b, c) SET_INT_IN_POINTER(_SWIZZLE3(a, b, c))
+#define SWIZZLE4(a, b, c, d) SET_INT_IN_POINTER(_SWIZZLE4(a, b, c, d))
/*****************************************************************************/
/* Python attributes get/set structure: */
@@ -2353,416 +2420,366 @@ static PyGetSetDef Vector_getseters[] = {
{(char *)"is_frozen", (getter)BaseMathObject_is_frozen_get, (setter)NULL, BaseMathObject_is_frozen_doc, NULL},
{(char *)"owner", (getter)BaseMathObject_owner_get, (setter)NULL, BaseMathObject_owner_doc, NULL},
- /* autogenerated swizzle attrs, see python script below */
- {(char *)"xx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X')},
- {(char *)"xxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'X')},
- {(char *)"xxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'X', 'X')},
- {(char *)"xxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'X', 'Y')},
- {(char *)"xxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'X', 'Z')},
- {(char *)"xxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'X', 'W')},
- {(char *)"xxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Y')},
- {(char *)"xxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Y', 'X')},
- {(char *)"xxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Y', 'Y')},
- {(char *)"xxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Y', 'Z')},
- {(char *)"xxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Y', 'W')},
- {(char *)"xxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Z')},
- {(char *)"xxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Z', 'X')},
- {(char *)"xxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Z', 'Y')},
- {(char *)"xxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Z', 'Z')},
- {(char *)"xxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'Z', 'W')},
- {(char *)"xxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'W')},
- {(char *)"xxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'W', 'X')},
- {(char *)"xxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'W', 'Y')},
- {(char *)"xxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'W', 'Z')},
- {(char *)"xxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'X', 'W', 'W')},
- {(char *)"xy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Y')},
- {(char *)"xyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'X')},
- {(char *)"xyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'X', 'X')},
- {(char *)"xyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'X', 'Y')},
- {(char *)"xyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'X', 'Z')},
- {(char *)"xyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'X', 'W')},
- {(char *)"xyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Y')},
- {(char *)"xyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Y', 'X')},
- {(char *)"xyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Y', 'Y')},
- {(char *)"xyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Y', 'Z')},
- {(char *)"xyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Y', 'W')},
- {(char *)"xyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Y', 'Z')},
- {(char *)"xyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Z', 'X')},
- {(char *)"xyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Z', 'Y')},
- {(char *)"xyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'Z', 'Z')},
- {(char *)"xyzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Y', 'Z', 'W')},
- {(char *)"xyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Y', 'W')},
- {(char *)"xywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'W', 'X')},
- {(char *)"xywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'W', 'Y')},
- {(char *)"xywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Y', 'W', 'Z')},
- {(char *)"xyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Y', 'W', 'W')},
- {(char *)"xz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Z')},
- {(char *)"xzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'X')},
- {(char *)"xzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'X', 'X')},
- {(char *)"xzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'X', 'Y')},
- {(char *)"xzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'X', 'Z')},
- {(char *)"xzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'X', 'W')},
- {(char *)"xzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Z', 'Y')},
- {(char *)"xzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Y', 'X')},
- {(char *)"xzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Y', 'Y')},
- {(char *)"xzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Y', 'Z')},
- {(char *)"xzyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Z', 'Y', 'W')},
- {(char *)"xzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Z')},
- {(char *)"xzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Z', 'X')},
- {(char *)"xzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Z', 'Y')},
- {(char *)"xzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Z', 'Z')},
- {(char *)"xzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'Z', 'W')},
- {(char *)"xzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Z', 'W')},
- {(char *)"xzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'W', 'X')},
- {(char *)"xzwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'Z', 'W', 'Y')},
- {(char *)"xzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'W', 'Z')},
- {(char *)"xzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'Z', 'W', 'W')},
- {(char *)"xw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'W')},
- {(char *)"xwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'X')},
- {(char *)"xwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'X', 'X')},
- {(char *)"xwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'X', 'Y')},
- {(char *)"xwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'X', 'Z')},
- {(char *)"xwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'X', 'W')},
- {(char *)"xwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'W', 'Y')},
- {(char *)"xwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Y', 'X')},
- {(char *)"xwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Y', 'Y')},
- {(char *)"xwyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'W', 'Y', 'Z')},
- {(char *)"xwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Y', 'W')},
- {(char *)"xwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'W', 'Z')},
- {(char *)"xwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Z', 'X')},
- {(char *)"xwzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('X', 'W', 'Z', 'Y')},
- {(char *)"xwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Z', 'Z')},
- {(char *)"xwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'Z', 'W')},
- {(char *)"xww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'W')},
- {(char *)"xwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'W', 'X')},
- {(char *)"xwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'W', 'Y')},
- {(char *)"xwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'W', 'Z')},
- {(char *)"xwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('X', 'W', 'W', 'W')},
- {(char *)"yx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'X')},
- {(char *)"yxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'X')},
- {(char *)"yxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'X', 'X')},
- {(char *)"yxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'X', 'Y')},
- {(char *)"yxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'X', 'Z')},
- {(char *)"yxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'X', 'W')},
- {(char *)"yxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Y')},
- {(char *)"yxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Y', 'X')},
- {(char *)"yxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Y', 'Y')},
- {(char *)"yxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Y', 'Z')},
- {(char *)"yxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Y', 'W')},
- {(char *)"yxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'X', 'Z')},
- {(char *)"yxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Z', 'X')},
- {(char *)"yxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Z', 'Y')},
- {(char *)"yxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'Z', 'Z')},
- {(char *)"yxzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'X', 'Z', 'W')},
- {(char *)"yxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'X', 'W')},
- {(char *)"yxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'W', 'X')},
- {(char *)"yxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'W', 'Y')},
- {(char *)"yxwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'X', 'W', 'Z')},
- {(char *)"yxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'X', 'W', 'W')},
- {(char *)"yy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y')},
- {(char *)"yyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'X')},
- {(char *)"yyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'X', 'X')},
- {(char *)"yyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'X', 'Y')},
- {(char *)"yyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'X', 'Z')},
- {(char *)"yyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'X', 'W')},
- {(char *)"yyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Y')},
- {(char *)"yyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Y', 'X')},
- {(char *)"yyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Y', 'Y')},
- {(char *)"yyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Y', 'Z')},
- {(char *)"yyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Y', 'W')},
- {(char *)"yyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Z')},
- {(char *)"yyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Z', 'X')},
- {(char *)"yyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Z', 'Y')},
- {(char *)"yyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Z', 'Z')},
- {(char *)"yyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'Z', 'W')},
- {(char *)"yyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'W')},
- {(char *)"yywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'W', 'X')},
- {(char *)"yywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'W', 'Y')},
- {(char *)"yywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'W', 'Z')},
- {(char *)"yyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Y', 'W', 'W')},
- {(char *)"yz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'Z')},
- {(char *)"yzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'Z', 'X')},
- {(char *)"yzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'X', 'X')},
- {(char *)"yzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'X', 'Y')},
- {(char *)"yzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'X', 'Z')},
- {(char *)"yzxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'Z', 'X', 'W')},
- {(char *)"yzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Y')},
- {(char *)"yzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Y', 'X')},
- {(char *)"yzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Y', 'Y')},
- {(char *)"yzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Y', 'Z')},
- {(char *)"yzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Y', 'W')},
- {(char *)"yzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Z')},
- {(char *)"yzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Z', 'X')},
- {(char *)"yzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Z', 'Y')},
- {(char *)"yzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Z', 'Z')},
- {(char *)"yzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'Z', 'W')},
- {(char *)"yzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'Z', 'W')},
- {(char *)"yzwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'Z', 'W', 'X')},
- {(char *)"yzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'W', 'Y')},
- {(char *)"yzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'W', 'Z')},
- {(char *)"yzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'Z', 'W', 'W')},
- {(char *)"yw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'W')},
- {(char *)"ywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'W', 'X')},
- {(char *)"ywxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'X', 'X')},
- {(char *)"ywxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'X', 'Y')},
- {(char *)"ywxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'W', 'X', 'Z')},
- {(char *)"ywxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'X', 'W')},
- {(char *)"ywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Y')},
- {(char *)"ywyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Y', 'X')},
- {(char *)"ywyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Y', 'Y')},
- {(char *)"ywyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Y', 'Z')},
- {(char *)"ywyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Y', 'W')},
- {(char *)"ywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'W', 'Z')},
- {(char *)"ywzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Y', 'W', 'Z', 'X')},
- {(char *)"ywzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Z', 'Y')},
- {(char *)"ywzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Z', 'Z')},
- {(char *)"ywzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'Z', 'W')},
- {(char *)"yww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'W')},
- {(char *)"ywwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'W', 'X')},
- {(char *)"ywwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'W', 'Y')},
- {(char *)"ywwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'W', 'Z')},
- {(char *)"ywww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Y', 'W', 'W', 'W')},
- {(char *)"zx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'X')},
- {(char *)"zxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'X')},
- {(char *)"zxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'X', 'X')},
- {(char *)"zxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'X', 'Y')},
- {(char *)"zxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'X', 'Z')},
- {(char *)"zxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'X', 'W')},
- {(char *)"zxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'X', 'Y')},
- {(char *)"zxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Y', 'X')},
- {(char *)"zxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Y', 'Y')},
- {(char *)"zxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Y', 'Z')},
- {(char *)"zxyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'X', 'Y', 'W')},
- {(char *)"zxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Z')},
- {(char *)"zxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Z', 'X')},
- {(char *)"zxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Z', 'Y')},
- {(char *)"zxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Z', 'Z')},
- {(char *)"zxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'Z', 'W')},
- {(char *)"zxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'X', 'W')},
- {(char *)"zxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'W', 'X')},
- {(char *)"zxwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'X', 'W', 'Y')},
- {(char *)"zxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'W', 'Z')},
- {(char *)"zxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'X', 'W', 'W')},
- {(char *)"zy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'Y')},
- {(char *)"zyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'Y', 'X')},
- {(char *)"zyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'X', 'X')},
- {(char *)"zyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'X', 'Y')},
- {(char *)"zyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'X', 'Z')},
- {(char *)"zyxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'Y', 'X', 'W')},
- {(char *)"zyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Y')},
- {(char *)"zyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Y', 'X')},
- {(char *)"zyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Y', 'Y')},
- {(char *)"zyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Y', 'Z')},
- {(char *)"zyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Y', 'W')},
- {(char *)"zyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Z')},
- {(char *)"zyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Z', 'X')},
- {(char *)"zyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Z', 'Y')},
- {(char *)"zyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Z', 'Z')},
- {(char *)"zyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'Z', 'W')},
- {(char *)"zyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'Y', 'W')},
- {(char *)"zywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'Y', 'W', 'X')},
- {(char *)"zywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'W', 'Y')},
- {(char *)"zywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'W', 'Z')},
- {(char *)"zyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Y', 'W', 'W')},
- {(char *)"zz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z')},
- {(char *)"zzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'X')},
- {(char *)"zzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'X', 'X')},
- {(char *)"zzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'X', 'Y')},
- {(char *)"zzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'X', 'Z')},
- {(char *)"zzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'X', 'W')},
- {(char *)"zzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Y')},
- {(char *)"zzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Y', 'X')},
- {(char *)"zzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Y', 'Y')},
- {(char *)"zzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Y', 'Z')},
- {(char *)"zzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Y', 'W')},
- {(char *)"zzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Z')},
- {(char *)"zzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Z', 'X')},
- {(char *)"zzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Z', 'Y')},
- {(char *)"zzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Z', 'Z')},
- {(char *)"zzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'Z', 'W')},
- {(char *)"zzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'W')},
- {(char *)"zzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'W', 'X')},
- {(char *)"zzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'W', 'Y')},
- {(char *)"zzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'W', 'Z')},
- {(char *)"zzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'Z', 'W', 'W')},
- {(char *)"zw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'W')},
- {(char *)"zwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'W', 'X')},
- {(char *)"zwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'X', 'X')},
- {(char *)"zwxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'W', 'X', 'Y')},
- {(char *)"zwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'X', 'Z')},
- {(char *)"zwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'X', 'W')},
- {(char *)"zwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'W', 'Y')},
- {(char *)"zwyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('Z', 'W', 'Y', 'X')},
- {(char *)"zwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Y', 'Y')},
- {(char *)"zwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Y', 'Z')},
- {(char *)"zwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Y', 'W')},
- {(char *)"zwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Z')},
- {(char *)"zwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Z', 'X')},
- {(char *)"zwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Z', 'Y')},
- {(char *)"zwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Z', 'Z')},
- {(char *)"zwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'Z', 'W')},
- {(char *)"zww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'W')},
- {(char *)"zwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'W', 'X')},
- {(char *)"zwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'W', 'Y')},
- {(char *)"zwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'W', 'Z')},
- {(char *)"zwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('Z', 'W', 'W', 'W')},
- {(char *)"wx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'X')},
- {(char *)"wxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'X')},
- {(char *)"wxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'X', 'X')},
- {(char *)"wxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'X', 'Y')},
- {(char *)"wxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'X', 'Z')},
- {(char *)"wxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'X', 'W')},
- {(char *)"wxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'X', 'Y')},
- {(char *)"wxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Y', 'X')},
- {(char *)"wxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Y', 'Y')},
- {(char *)"wxyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'X', 'Y', 'Z')},
- {(char *)"wxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Y', 'W')},
- {(char *)"wxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'X', 'Z')},
- {(char *)"wxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Z', 'X')},
- {(char *)"wxzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'X', 'Z', 'Y')},
- {(char *)"wxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Z', 'Z')},
- {(char *)"wxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'Z', 'W')},
- {(char *)"wxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'W')},
- {(char *)"wxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'W', 'X')},
- {(char *)"wxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'W', 'Y')},
- {(char *)"wxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'W', 'Z')},
- {(char *)"wxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'X', 'W', 'W')},
- {(char *)"wy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Y')},
- {(char *)"wyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Y', 'X')},
- {(char *)"wyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'X', 'X')},
- {(char *)"wyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'X', 'Y')},
- {(char *)"wyxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Y', 'X', 'Z')},
- {(char *)"wyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'X', 'W')},
- {(char *)"wyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Y')},
- {(char *)"wyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Y', 'X')},
- {(char *)"wyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Y', 'Y')},
- {(char *)"wyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Y', 'Z')},
- {(char *)"wyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Y', 'W')},
- {(char *)"wyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Y', 'Z')},
- {(char *)"wyzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Y', 'Z', 'X')},
- {(char *)"wyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Z', 'Y')},
- {(char *)"wyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Z', 'Z')},
- {(char *)"wyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'Z', 'W')},
- {(char *)"wyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'W')},
- {(char *)"wywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'W', 'X')},
- {(char *)"wywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'W', 'Y')},
- {(char *)"wywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'W', 'Z')},
- {(char *)"wyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Y', 'W', 'W')},
- {(char *)"wz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Z')},
- {(char *)"wzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Z', 'X')},
- {(char *)"wzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'X', 'X')},
- {(char *)"wzxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Z', 'X', 'Y')},
- {(char *)"wzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'X', 'Z')},
- {(char *)"wzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'X', 'W')},
- {(char *)"wzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Z', 'Y')},
- {(char *)"wzyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE('W', 'Z', 'Y', 'X')},
- {(char *)"wzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Y', 'Y')},
- {(char *)"wzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Y', 'Z')},
- {(char *)"wzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Y', 'W')},
- {(char *)"wzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Z')},
- {(char *)"wzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Z', 'X')},
- {(char *)"wzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Z', 'Y')},
- {(char *)"wzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Z', 'Z')},
- {(char *)"wzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'Z', 'W')},
- {(char *)"wzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'W')},
- {(char *)"wzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'W', 'X')},
- {(char *)"wzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'W', 'Y')},
- {(char *)"wzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'W', 'Z')},
- {(char *)"wzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'Z', 'W', 'W')},
- {(char *)"ww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W')},
- {(char *)"wwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'X')},
- {(char *)"wwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'X', 'X')},
- {(char *)"wwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'X', 'Y')},
- {(char *)"wwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'X', 'Z')},
- {(char *)"wwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'X', 'W')},
- {(char *)"wwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Y')},
- {(char *)"wwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Y', 'X')},
- {(char *)"wwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Y', 'Y')},
- {(char *)"wwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Y', 'Z')},
- {(char *)"wwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Y', 'W')},
- {(char *)"wwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Z')},
- {(char *)"wwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Z', 'X')},
- {(char *)"wwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Z', 'Y')},
- {(char *)"wwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Z', 'Z')},
- {(char *)"wwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'Z', 'W')},
- {(char *)"www", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'W')},
- {(char *)"wwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'W', 'X')},
- {(char *)"wwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'W', 'Y')},
- {(char *)"wwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'W', 'Z')},
- {(char *)"wwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE('W', 'W', 'W', 'W')},
+ /* autogenerated swizzle attrs, see Python script above */
+ {(char *)"xx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(0, 0)},
+ {(char *)"xxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 0)},
+ {(char *)"xxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 0)},
+ {(char *)"xxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 1)},
+ {(char *)"xxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 2)},
+ {(char *)"xxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 0, 3)},
+ {(char *)"xxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 1)},
+ {(char *)"xxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 0)},
+ {(char *)"xxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 1)},
+ {(char *)"xxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 2)},
+ {(char *)"xxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 1, 3)},
+ {(char *)"xxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 2)},
+ {(char *)"xxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 0)},
+ {(char *)"xxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 1)},
+ {(char *)"xxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 2)},
+ {(char *)"xxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 2, 3)},
+ {(char *)"xxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 0, 3)},
+ {(char *)"xxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 0)},
+ {(char *)"xxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 1)},
+ {(char *)"xxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 2)},
+ {(char *)"xxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 0, 3, 3)},
+ {(char *)"xy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 1)},
+ {(char *)"xyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 0)},
+ {(char *)"xyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 0)},
+ {(char *)"xyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 1)},
+ {(char *)"xyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 2)},
+ {(char *)"xyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 0, 3)},
+ {(char *)"xyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 1, 1)},
+ {(char *)"xyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 0)},
+ {(char *)"xyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 1)},
+ {(char *)"xyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 2)},
+ {(char *)"xyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 1, 3)},
+ {(char *)"xyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 2)},
+ {(char *)"xyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 0)},
+ {(char *)"xyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 1)},
+ {(char *)"xyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 2, 2)},
+ {(char *)"xyzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 2, 3)},
+ {(char *)"xyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 1, 3)},
+ {(char *)"xywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 0)},
+ {(char *)"xywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 1)},
+ {(char *)"xywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 1, 3, 2)},
+ {(char *)"xyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 1, 3, 3)},
+ {(char *)"xz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 2)},
+ {(char *)"xzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 0)},
+ {(char *)"xzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 0)},
+ {(char *)"xzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 1)},
+ {(char *)"xzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 2)},
+ {(char *)"xzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 0, 3)},
+ {(char *)"xzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 1)},
+ {(char *)"xzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 0)},
+ {(char *)"xzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 1)},
+ {(char *)"xzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 1, 2)},
+ {(char *)"xzyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 1, 3)},
+ {(char *)"xzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 2, 2)},
+ {(char *)"xzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 0)},
+ {(char *)"xzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 1)},
+ {(char *)"xzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 2)},
+ {(char *)"xzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 2, 3)},
+ {(char *)"xzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 2, 3)},
+ {(char *)"xzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 0)},
+ {(char *)"xzwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 2, 3, 1)},
+ {(char *)"xzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 2)},
+ {(char *)"xzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 2, 3, 3)},
+ {(char *)"xw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(0, 3)},
+ {(char *)"xwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 0)},
+ {(char *)"xwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 0)},
+ {(char *)"xwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 1)},
+ {(char *)"xwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 2)},
+ {(char *)"xwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 0, 3)},
+ {(char *)"xwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 1)},
+ {(char *)"xwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 0)},
+ {(char *)"xwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 1)},
+ {(char *)"xwyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 1, 2)},
+ {(char *)"xwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 1, 3)},
+ {(char *)"xwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(0, 3, 2)},
+ {(char *)"xwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 0)},
+ {(char *)"xwzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(0, 3, 2, 1)},
+ {(char *)"xwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 2)},
+ {(char *)"xwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 2, 3)},
+ {(char *)"xww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(0, 3, 3)},
+ {(char *)"xwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 0)},
+ {(char *)"xwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 1)},
+ {(char *)"xwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 2)},
+ {(char *)"xwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(0, 3, 3, 3)},
+ {(char *)"yx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 0)},
+ {(char *)"yxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 0)},
+ {(char *)"yxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 0)},
+ {(char *)"yxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 1)},
+ {(char *)"yxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 2)},
+ {(char *)"yxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 0, 3)},
+ {(char *)"yxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 0, 1)},
+ {(char *)"yxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 0)},
+ {(char *)"yxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 1)},
+ {(char *)"yxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 2)},
+ {(char *)"yxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 1, 3)},
+ {(char *)"yxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 2)},
+ {(char *)"yxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 0)},
+ {(char *)"yxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 1)},
+ {(char *)"yxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 2, 2)},
+ {(char *)"yxzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 2, 3)},
+ {(char *)"yxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 0, 3)},
+ {(char *)"yxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 0)},
+ {(char *)"yxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 1)},
+ {(char *)"yxwz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 0, 3, 2)},
+ {(char *)"yxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 0, 3, 3)},
+ {(char *)"yy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(1, 1)},
+ {(char *)"yyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 0)},
+ {(char *)"yyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 0)},
+ {(char *)"yyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 1)},
+ {(char *)"yyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 2)},
+ {(char *)"yyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 0, 3)},
+ {(char *)"yyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 1)},
+ {(char *)"yyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 0)},
+ {(char *)"yyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 1)},
+ {(char *)"yyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 2)},
+ {(char *)"yyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 1, 3)},
+ {(char *)"yyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 2)},
+ {(char *)"yyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 0)},
+ {(char *)"yyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 1)},
+ {(char *)"yyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 2)},
+ {(char *)"yyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 2, 3)},
+ {(char *)"yyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 1, 3)},
+ {(char *)"yywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 0)},
+ {(char *)"yywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 1)},
+ {(char *)"yywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 2)},
+ {(char *)"yyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 1, 3, 3)},
+ {(char *)"yz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 2)},
+ {(char *)"yzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 0)},
+ {(char *)"yzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 0)},
+ {(char *)"yzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 1)},
+ {(char *)"yzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 0, 2)},
+ {(char *)"yzxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 0, 3)},
+ {(char *)"yzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 1)},
+ {(char *)"yzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 0)},
+ {(char *)"yzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 1)},
+ {(char *)"yzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 2)},
+ {(char *)"yzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 1, 3)},
+ {(char *)"yzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 2, 2)},
+ {(char *)"yzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 0)},
+ {(char *)"yzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 1)},
+ {(char *)"yzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 2)},
+ {(char *)"yzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 2, 3)},
+ {(char *)"yzw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 2, 3)},
+ {(char *)"yzwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 2, 3, 0)},
+ {(char *)"yzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 1)},
+ {(char *)"yzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 2)},
+ {(char *)"yzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 2, 3, 3)},
+ {(char *)"yw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(1, 3)},
+ {(char *)"ywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 0)},
+ {(char *)"ywxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 0)},
+ {(char *)"ywxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 1)},
+ {(char *)"ywxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 0, 2)},
+ {(char *)"ywxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 0, 3)},
+ {(char *)"ywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 1)},
+ {(char *)"ywyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 0)},
+ {(char *)"ywyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 1)},
+ {(char *)"ywyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 2)},
+ {(char *)"ywyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 1, 3)},
+ {(char *)"ywz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(1, 3, 2)},
+ {(char *)"ywzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(1, 3, 2, 0)},
+ {(char *)"ywzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 1)},
+ {(char *)"ywzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 2)},
+ {(char *)"ywzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 2, 3)},
+ {(char *)"yww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(1, 3, 3)},
+ {(char *)"ywwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 0)},
+ {(char *)"ywwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 1)},
+ {(char *)"ywwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 2)},
+ {(char *)"ywww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(1, 3, 3, 3)},
+ {(char *)"zx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 0)},
+ {(char *)"zxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 0)},
+ {(char *)"zxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 0)},
+ {(char *)"zxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 1)},
+ {(char *)"zxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 2)},
+ {(char *)"zxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 0, 3)},
+ {(char *)"zxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 1)},
+ {(char *)"zxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 0)},
+ {(char *)"zxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 1)},
+ {(char *)"zxyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 1, 2)},
+ {(char *)"zxyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 1, 3)},
+ {(char *)"zxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 0, 2)},
+ {(char *)"zxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 0)},
+ {(char *)"zxzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 1)},
+ {(char *)"zxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 2)},
+ {(char *)"zxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 2, 3)},
+ {(char *)"zxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 0, 3)},
+ {(char *)"zxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 0)},
+ {(char *)"zxwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 0, 3, 1)},
+ {(char *)"zxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 2)},
+ {(char *)"zxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 0, 3, 3)},
+ {(char *)"zy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 1)},
+ {(char *)"zyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 0)},
+ {(char *)"zyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 0)},
+ {(char *)"zyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 1)},
+ {(char *)"zyxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 0, 2)},
+ {(char *)"zyxw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 0, 3)},
+ {(char *)"zyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 1)},
+ {(char *)"zyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 0)},
+ {(char *)"zyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 1)},
+ {(char *)"zyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 2)},
+ {(char *)"zyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 1, 3)},
+ {(char *)"zyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 1, 2)},
+ {(char *)"zyzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 0)},
+ {(char *)"zyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 1)},
+ {(char *)"zyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 2)},
+ {(char *)"zyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 2, 3)},
+ {(char *)"zyw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 1, 3)},
+ {(char *)"zywx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 1, 3, 0)},
+ {(char *)"zywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 1)},
+ {(char *)"zywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 2)},
+ {(char *)"zyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 1, 3, 3)},
+ {(char *)"zz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(2, 2)},
+ {(char *)"zzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 0)},
+ {(char *)"zzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 0)},
+ {(char *)"zzxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 1)},
+ {(char *)"zzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 2)},
+ {(char *)"zzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 0, 3)},
+ {(char *)"zzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 1)},
+ {(char *)"zzyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 0)},
+ {(char *)"zzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 1)},
+ {(char *)"zzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 2)},
+ {(char *)"zzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 1, 3)},
+ {(char *)"zzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 2)},
+ {(char *)"zzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 0)},
+ {(char *)"zzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 1)},
+ {(char *)"zzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 2)},
+ {(char *)"zzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 2, 3)},
+ {(char *)"zzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 2, 3)},
+ {(char *)"zzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 0)},
+ {(char *)"zzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 1)},
+ {(char *)"zzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 2)},
+ {(char *)"zzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 2, 3, 3)},
+ {(char *)"zw", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(2, 3)},
+ {(char *)"zwx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 0)},
+ {(char *)"zwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 0)},
+ {(char *)"zwxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 0, 1)},
+ {(char *)"zwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 2)},
+ {(char *)"zwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 0, 3)},
+ {(char *)"zwy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(2, 3, 1)},
+ {(char *)"zwyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(2, 3, 1, 0)},
+ {(char *)"zwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 1)},
+ {(char *)"zwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 2)},
+ {(char *)"zwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 1, 3)},
+ {(char *)"zwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 2)},
+ {(char *)"zwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 0)},
+ {(char *)"zwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 1)},
+ {(char *)"zwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 2)},
+ {(char *)"zwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 2, 3)},
+ {(char *)"zww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(2, 3, 3)},
+ {(char *)"zwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 0)},
+ {(char *)"zwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 1)},
+ {(char *)"zwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 2)},
+ {(char *)"zwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(2, 3, 3, 3)},
+ {(char *)"wx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 0)},
+ {(char *)"wxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 0)},
+ {(char *)"wxxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 0)},
+ {(char *)"wxxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 1)},
+ {(char *)"wxxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 2)},
+ {(char *)"wxxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 0, 3)},
+ {(char *)"wxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 1)},
+ {(char *)"wxyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 0)},
+ {(char *)"wxyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 1)},
+ {(char *)"wxyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 1, 2)},
+ {(char *)"wxyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 1, 3)},
+ {(char *)"wxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 0, 2)},
+ {(char *)"wxzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 0)},
+ {(char *)"wxzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 0, 2, 1)},
+ {(char *)"wxzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 2)},
+ {(char *)"wxzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 2, 3)},
+ {(char *)"wxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 0, 3)},
+ {(char *)"wxwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 0)},
+ {(char *)"wxwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 1)},
+ {(char *)"wxwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 2)},
+ {(char *)"wxww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 0, 3, 3)},
+ {(char *)"wy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 1)},
+ {(char *)"wyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 0)},
+ {(char *)"wyxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 0)},
+ {(char *)"wyxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 1)},
+ {(char *)"wyxz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 0, 2)},
+ {(char *)"wyxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 0, 3)},
+ {(char *)"wyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 1)},
+ {(char *)"wyyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 0)},
+ {(char *)"wyyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 1)},
+ {(char *)"wyyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 2)},
+ {(char *)"wyyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 1, 3)},
+ {(char *)"wyz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 1, 2)},
+ {(char *)"wyzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 1, 2, 0)},
+ {(char *)"wyzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 1)},
+ {(char *)"wyzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 2)},
+ {(char *)"wyzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 2, 3)},
+ {(char *)"wyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 1, 3)},
+ {(char *)"wywx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 0)},
+ {(char *)"wywy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 1)},
+ {(char *)"wywz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 2)},
+ {(char *)"wyww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 1, 3, 3)},
+ {(char *)"wz", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE2(3, 2)},
+ {(char *)"wzx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 0)},
+ {(char *)"wzxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 0)},
+ {(char *)"wzxy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 0, 1)},
+ {(char *)"wzxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 2)},
+ {(char *)"wzxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 0, 3)},
+ {(char *)"wzy", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE3(3, 2, 1)},
+ {(char *)"wzyx", (getter)Vector_swizzle_get, (setter)Vector_swizzle_set, NULL, SWIZZLE4(3, 2, 1, 0)},
+ {(char *)"wzyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 1)},
+ {(char *)"wzyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 2)},
+ {(char *)"wzyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 1, 3)},
+ {(char *)"wzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 2)},
+ {(char *)"wzzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 0)},
+ {(char *)"wzzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 1)},
+ {(char *)"wzzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 2)},
+ {(char *)"wzzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 2, 3)},
+ {(char *)"wzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 2, 3)},
+ {(char *)"wzwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 0)},
+ {(char *)"wzwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 1)},
+ {(char *)"wzwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 2)},
+ {(char *)"wzww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 2, 3, 3)},
+ {(char *)"ww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE2(3, 3)},
+ {(char *)"wwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 0)},
+ {(char *)"wwxx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 0)},
+ {(char *)"wwxy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 1)},
+ {(char *)"wwxz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 2)},
+ {(char *)"wwxw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 0, 3)},
+ {(char *)"wwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 1)},
+ {(char *)"wwyx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 0)},
+ {(char *)"wwyy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 1)},
+ {(char *)"wwyz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 2)},
+ {(char *)"wwyw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 1, 3)},
+ {(char *)"wwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 2)},
+ {(char *)"wwzx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 0)},
+ {(char *)"wwzy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 1)},
+ {(char *)"wwzz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 2)},
+ {(char *)"wwzw", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 2, 3)},
+ {(char *)"www", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE3(3, 3, 3)},
+ {(char *)"wwwx", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 0)},
+ {(char *)"wwwy", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 1)},
+ {(char *)"wwwz", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 2)},
+ {(char *)"wwww", (getter)Vector_swizzle_get, (setter)NULL, NULL, SWIZZLE4(3, 3, 3, 3)},
#undef AXIS_FROM_CHAR
-#undef SWIZZLE
-#undef _VA_SWIZZLE_1
-#undef _VA_SWIZZLE_2
-#undef _VA_SWIZZLE_3
-#undef _VA_SWIZZLE_4
+#undef SWIZZLE1
+#undef SWIZZLE2
+#undef SWIZZLE3
+#undef SWIZZLE4
+#undef _SWIZZLE1
+#undef _SWIZZLE2
+#undef _SWIZZLE3
+#undef _SWIZZLE4
{NULL, NULL, NULL, NULL, NULL} /* Sentinel */
};
/**
- * Python script used to make swizzle array:
- *
- * \code{.py}
- * SWIZZLE_BITS_PER_AXIS = 3
- * SWIZZLE_VALID_AXIS = 0x4
- *
- * axis_dict = {}
- * axis_pos = {'x': 0, 'y': 1, 'z': 2, 'w': 3}
- * axises = 'xyzw'
- * while len(axises) >= 2:
- * for axis_0 in axises:
- * axis_0_pos = axis_pos[axis_0]
- * for axis_1 in axises:
- * axis_1_pos = axis_pos[axis_1]
- * axis_dict[axis_0 + axis_1] = (
- * '((%s | SWIZZLE_VALID_AXIS) | '
- * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS))' %
- * (axis_0_pos, axis_1_pos))
- * if len(axises) > 2:
- * for axis_2 in axises:
- * axis_2_pos = axis_pos[axis_2]
- * axis_dict[axis_0 + axis_1 + axis_2] = (
- * '((%s | SWIZZLE_VALID_AXIS) | '
- * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
- * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)))' %
- * (axis_0_pos, axis_1_pos, axis_2_pos))
- * if len(axises) > 3:
- * for axis_3 in axises:
- * axis_3_pos = axis_pos[axis_3]
- * axis_dict[axis_0 + axis_1 + axis_2 + axis_3] = (
- * '((%s | SWIZZLE_VALID_AXIS) | '
- * '((%s | SWIZZLE_VALID_AXIS) << SWIZZLE_BITS_PER_AXIS) | '
- * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 2)) | '
- * '((%s | SWIZZLE_VALID_AXIS) << (SWIZZLE_BITS_PER_AXIS * 3))) ' %
- * (axis_0_pos, axis_1_pos, axis_2_pos, axis_3_pos))
- *
- * axises = axises[:-1]
- *
- *
- * items = list(axis_dict.items())
- * items.sort(key=lambda a: a[0].replace('x', '0').replace('y', '1').replace('z', '2').replace('w', '3'))
- *
- * unique = set()
- * for key, val in items:
- * num = eval(val)
- * set_str = 'Vector_swizzle_set' if (len(set(key)) == len(key)) else 'NULL'
- * key_args = ', '.join(["'%s'" % c for c in key.upper()])
- * print('\t{(char *)"%s", %s(getter)Vector_swizzle_get, (setter)%s, NULL, SWIZZLE(%s)},' %
- * (key, (' ' * (4 - len(key))), set_str, key_args))
- * unique.add(num)
- *
- * if len(unique) != len(items):
- * print("ERROR, duplicate values found")
- * \endcode
- */
-
-/* ROW VECTOR Multiplication - Vector X Matrix
+ * Row vector multiplication - (Vector * Matrix)
+ * <pre>
* [x][y][z] * [1][4][7]
* [2][5][8]
* [3][6][9]
- * vector/matrix multiplication IS NOT COMMUTATIVE!!!! */
+ * </pre>
+ * \note vector/matrix multiplication is not commutative.
+ */
static int row_vector_multiplication(float r_vec[MAX_DIMENSIONS], VectorObject *vec, MatrixObject *mat)
{
float vec_cpy[MAX_DIMENSIONS];
@@ -2863,10 +2880,11 @@ static struct PyMethodDef Vector_methods[] = {
};
-/* Note
- * Py_TPFLAGS_CHECKTYPES allows us to avoid casting all types to Vector when coercing
- * but this means for eg that
- * (vec * mat) and (mat * vec) both get sent to Vector_mul and it needs to sort out the order
+/**
+ * Note:
+ * #Py_TPFLAGS_CHECKTYPES allows us to avoid casting all types to Vector when coercing
+ * but this means for eg that (vec * mat) and (mat * vec)
+ * both get sent to Vector_mul and it needs to sort out the order
*/
PyDoc_STRVAR(vector_doc,
@@ -3010,6 +3028,11 @@ PyObject *Vector_CreatePyObject(
return (PyObject *)self;
}
+/**
+ * Create a vector that wraps existing memory.
+ *
+ * \param vec: Use this vector in-place.
+ */
PyObject *Vector_CreatePyObject_wrap(
float *vec, const int size,
PyTypeObject *base_type)
@@ -3036,6 +3059,10 @@ PyObject *Vector_CreatePyObject_wrap(
return (PyObject *) self;
}
+/**
+ * Create a vector where the value is defined by registered callbacks,
+ * see: #Mathutils_RegisterCallback
+ */
PyObject *Vector_CreatePyObject_cb(
PyObject *cb_user, int size,
unsigned char cb_type, unsigned char cb_subtype)
@@ -3052,6 +3079,9 @@ PyObject *Vector_CreatePyObject_cb(
return (PyObject *)self;
}
+/**
+ * \param vec: Initialized vector value to use in-place, allocated with: PyMem_Malloc
+ */
PyObject *Vector_CreatePyObject_alloc(
float *vec, const int size,
PyTypeObject *base_type)
diff --git a/source/blender/python/mathutils/mathutils_Vector.h b/source/blender/python/mathutils/mathutils_Vector.h
index 74ca3336f4b..9ebf9457f2b 100644
--- a/source/blender/python/mathutils/mathutils_Vector.h
+++ b/source/blender/python/mathutils/mathutils_Vector.h
@@ -29,7 +29,9 @@
#define __MATHUTILS_VECTOR_H__
extern PyTypeObject vector_Type;
-#define VectorObject_Check(_v) PyObject_TypeCheck((_v), &vector_Type)
+
+#define VectorObject_Check(v) PyObject_TypeCheck((v), &vector_Type)
+#define VectorObject_CheckExact(v) (Py_TYPE(v) == &vector_Type)
typedef struct {
BASE_MATH_MEMBERS(vec);
diff --git a/source/blender/python/mathutils/mathutils_bvhtree.c b/source/blender/python/mathutils/mathutils_bvhtree.c
index 1eb8644a9a6..c044cc54965 100644
--- a/source/blender/python/mathutils/mathutils_bvhtree.c
+++ b/source/blender/python/mathutils/mathutils_bvhtree.c
@@ -33,7 +33,7 @@
#include "BLI_utildefines.h"
#include "BLI_kdopbvh.h"
-#include "BLI_polyfill2d.h"
+#include "BLI_polyfill_2d.h"
#include "BLI_math.h"
#include "BLI_ghash.h"
#include "BLI_memarena.h"
@@ -391,7 +391,7 @@ static PyObject *py_bvhtree_ray_cast(PyBVHTree *self, PyObject *args)
PyDoc_STRVAR(py_bvhtree_find_nearest_doc,
".. method:: find_nearest(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
"\n"
-" Find the nearest element to a point.\n"
+" Find the nearest element (typically face index) to a point.\n"
"\n"
" :arg co: Find nearest element to this point.\n"
" :type co: :class:`Vector`\n"
@@ -476,7 +476,7 @@ static void py_bvhtree_nearest_point_range_cb(void *userdata, int index, const f
PyDoc_STRVAR(py_bvhtree_find_nearest_range_doc,
".. method:: find_nearest_range(origin, distance=" PYBVH_MAX_DIST_STR ")\n"
"\n"
-" Find the nearest elements to a point in the distance range.\n"
+" Find the nearest elements (typically face index) to a point in the distance range.\n"
"\n"
" :arg co: Find nearest elements to this point.\n"
" :type co: :class:`Vector`\n"
@@ -761,7 +761,7 @@ static PyObject *C_BVHTree_FromPolygons(PyObject *UNUSED(cls), PyObject *args, P
py_tricoords_fast_items = PySequence_Fast_ITEMS(py_tricoords_fast);
for (j = 0; j < 3; j++) {
- tri[j] = (unsigned int)_PyLong_AsInt(py_tricoords_fast_items[j]);
+ tri[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
if (UNLIKELY(tri[j] >= (unsigned int)coords_len)) {
PyErr_Format(PyExc_ValueError,
"%s: index %d must be less than %d",
@@ -812,7 +812,7 @@ static PyObject *C_BVHTree_FromPolygons(PyObject *UNUSED(cls), PyObject *args, P
p_plink_prev = &plink->next;
for (j = 0; j < py_tricoords_len; j++) {
- plink->poly[j] = (unsigned int)_PyLong_AsInt(py_tricoords_fast_items[j]);
+ plink->poly[j] = PyC_Long_AsU32(py_tricoords_fast_items[j]);
if (UNLIKELY(plink->poly[j] >= (unsigned int)coords_len)) {
PyErr_Format(PyExc_ValueError,
"%s: index %d must be less than %d",
@@ -872,7 +872,7 @@ static PyObject *C_BVHTree_FromPolygons(PyObject *UNUSED(cls), PyObject *args, P
mul_v2_m3v3(proj_coords[j], axis_mat, coords[plink->poly[j]]);
}
- BLI_polyfill_calc_arena((const float (*)[2])proj_coords, plink->len, 1, tris_offset, pf_arena);
+ BLI_polyfill_calc_arena(proj_coords, plink->len, 1, tris_offset, pf_arena);
j = plink->len - 2;
while (j--) {
@@ -1156,7 +1156,6 @@ static PyObject *C_BVHTree_FromObject(PyObject *UNUSED(cls), PyObject *args, PyO
/* Get data for tessellation */
{
- DM_ensure_looptri(dm);
lt = dm->getLoopTriArray(dm);
tris_len = (unsigned int)dm->getNumLoopTri(dm);
diff --git a/source/blender/python/mathutils/mathutils_bvhtree.h b/source/blender/python/mathutils/mathutils_bvhtree.h
index 634556d68f7..445a393b93e 100644
--- a/source/blender/python/mathutils/mathutils_bvhtree.h
+++ b/source/blender/python/mathutils/mathutils_bvhtree.h
@@ -30,7 +30,7 @@ PyMODINIT_FUNC PyInit_mathutils_bvhtree(void);
extern PyTypeObject PyBVHTree_Type;
-#define PyBVHTree_Check(_v) PyObject_TypeCheck((_v), &PyBVHTree_Type)
+#define PyBVHTree_Check(v) PyObject_TypeCheck((v), &PyBVHTree_Type)
#define PyBVHTree_CheckExact(v) (Py_TYPE(v) == &PyBVHTree_Type)
#endif /* __MATHUTILS_BVHTREE_H__ */
diff --git a/source/blender/python/mathutils/mathutils_geometry.c b/source/blender/python/mathutils/mathutils_geometry.c
index 868e4b38408..d935949fd8c 100644
--- a/source/blender/python/mathutils/mathutils_geometry.c
+++ b/source/blender/python/mathutils/mathutils_geometry.c
@@ -34,8 +34,8 @@
#ifndef MATH_STANDALONE /* define when building outside blender */
# include "MEM_guardedalloc.h"
# include "BLI_blenlib.h"
-# include "BLI_boxpack2d.h"
-# include "BLI_convexhull2d.h"
+# include "BLI_boxpack_2d.h"
+# include "BLI_convexhull_2d.h"
# include "BKE_displist.h"
# include "BKE_curve.h"
#endif
@@ -742,7 +742,7 @@ static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObjec
float lambda;
PyObject *ret;
int size = 2;
-
+
if (!PyArg_ParseTuple(
args, "OOO:intersect_point_line",
&py_pt, &py_line_a, &py_line_b))
@@ -760,7 +760,7 @@ static PyObject *M_Geometry_intersect_point_line(PyObject *UNUSED(self), PyObjec
/* do the calculation */
lambda = closest_to_line_v3(pt_out, pt, line_a, line_b);
-
+
ret = PyTuple_New(2);
PyTuple_SET_ITEMS(ret,
Vector_CreatePyObject(pt_out, size, NULL),
@@ -882,7 +882,7 @@ static PyObject *M_Geometry_intersect_point_quad_2d(PyObject *UNUSED(self), PyOb
PyObject *py_pt, *py_quad[4];
float pt[2], quad[4][2];
int i;
-
+
if (!PyArg_ParseTuple(
args, "OOOOO:intersect_point_quad_2d",
&py_pt, UNPACK4_EX(&, py_quad, )))
@@ -954,12 +954,12 @@ PyDoc_STRVAR(M_Geometry_barycentric_transform_doc,
" :type tri_a2: :class:`mathutils.Vector`\n"
" :arg tri_a3: source triangle vertex.\n"
" :type tri_a3: :class:`mathutils.Vector`\n"
-" :arg tri_a1: target triangle vertex.\n"
-" :type tri_a1: :class:`mathutils.Vector`\n"
-" :arg tri_a2: target triangle vertex.\n"
-" :type tri_a2: :class:`mathutils.Vector`\n"
-" :arg tri_a3: target triangle vertex.\n"
-" :type tri_a3: :class:`mathutils.Vector`\n"
+" :arg tri_b1: target triangle vertex.\n"
+" :type tri_b1: :class:`mathutils.Vector`\n"
+" :arg tri_b2: target triangle vertex.\n"
+" :type tri_b2: :class:`mathutils.Vector`\n"
+" :arg tri_b3: target triangle vertex.\n"
+" :type tri_b3: :class:`mathutils.Vector`\n"
" :return: The transformed point\n"
" :rtype: :class:`mathutils.Vector`'s\n"
);
@@ -1279,7 +1279,7 @@ static PyObject *M_Geometry_tessellate_polygon(PyObject *UNUSED(self), PyObject
index = 0;
dl_face = dl->index;
while (index < dl->parts) {
- PyList_SET_ITEM(tri_list, index, Py_BuildValue("iii", dl_face[0], dl_face[1], dl_face[2]));
+ PyList_SET_ITEM(tri_list, index, PyC_Tuple_Pack_I32(dl_face[0], dl_face[1], dl_face[2]));
dl_face += 3;
index++;
}
@@ -1430,7 +1430,7 @@ static PyObject *M_Geometry_box_fit_2d(PyObject *UNUSED(self), PyObject *pointli
if (len) {
/* Non Python function */
- angle = BLI_convexhull_aabb_fit_points_2d((const float (*)[2])points, len);
+ angle = BLI_convexhull_aabb_fit_points_2d(points, len);
PyMem_Free(points);
}
@@ -1468,7 +1468,7 @@ static PyObject *M_Geometry_convex_hull_2d(PyObject *UNUSED(self), PyObject *poi
index_map = MEM_mallocN(sizeof(*index_map) * len * 2, __func__);
/* Non Python function */
- len_ret = BLI_convexhull_2d((const float (*)[2])points, len, index_map);
+ len_ret = BLI_convexhull_2d(points, len, index_map);
ret = PyList_New(len_ret);
for (i = 0; i < len_ret; i++) {
diff --git a/source/blender/quicktime/apple/qtkit_export.m b/source/blender/quicktime/apple/qtkit_export.m
deleted file mode 100644
index 1ac3c58f888..00000000000
--- a/source/blender/quicktime/apple/qtkit_export.m
+++ /dev/null
@@ -1,884 +0,0 @@
-/*
- * Code to create QuickTime Movies with Blender
- *
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- *
- * The Original Code is written by Rob Haarsma (phase)
- *
- * Contributor(s): Stefan Gartner (sgefant)
- * Damien Plisson 11/2009
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-#ifdef WITH_QUICKTIME
-#if defined(_WIN32) || defined(__APPLE__)
-
-#include <stdio.h>
-#include <string.h>
-
-#include "DNA_scene_types.h"
-#include "DNA_userdef_types.h"
-
-#ifdef WITH_AUDASPACE
-# include AUD_DEVICE_H
-#endif
-
-#include "BLI_utildefines.h"
-#include "BKE_global.h"
-#include "BKE_main.h"
-#include "BKE_scene.h"
-#include "BKE_report.h"
-
-#include "BLI_blenlib.h"
-
-#include "BLI_sys_types.h"
-
-#include "IMB_imbuf.h"
-#include "IMB_imbuf_types.h"
-
-#include "MEM_guardedalloc.h"
-
-#ifdef __APPLE__
-/* evil */
-#ifndef __AIFF__
-#define __AIFF__
-#endif
-#import <Cocoa/Cocoa.h>
-#import <QTKit/QTKit.h>
-#include <AudioToolbox/AudioToolbox.h>
-
-#include "quicktime_import.h"
-#include "quicktime_export.h"
-
-#endif /* __APPLE__ */
-
-typedef struct QuicktimeExport {
- QTMovie *movie;
-
- NSString *filename;
-
- QTTime frameDuration;
- NSDictionary *frameAttributes;
-
- NSString *videoTempFileName;
- /* Audio section */
- AUD_Device *audioInputDevice;
- AudioFileID audioFile;
- NSString *audioFileName;
- AudioConverterRef audioConverter;
- AudioBufferList audioBufferList;
- AudioStreamBasicDescription audioInputFormat, audioOutputFormat;
- AudioStreamPacketDescription *audioOutputPktDesc;
- SInt64 audioFilePos;
- char *audioInputBuffer;
- char *audioOutputBuffer;
- UInt32 audioCodecMaxOutputPacketSize;
- UInt64 audioTotalExportedFrames, audioTotalSavedFrames;
- UInt64 audioLastFrame;
- SInt64 audioOutputPktPos;
-
-} QuicktimeExport;
-
-#define AUDIOOUTPUTBUFFERSIZE 65536
-
-#pragma mark rna helper functions
-
-/* Video codec */
-static QuicktimeCodecTypeDesc qtVideoCodecList[] = {
- {kRawCodecType, 1, "Uncompressed"},
- {k422YpCbCr8CodecType, 2, "Uncompressed 8-bit 4:2:2"},
- {k422YpCbCr10CodecType, 3, "Uncompressed 10-bit 4:2:2"},
- {kComponentVideoCodecType, 4, "Component Video"},
- {kPixletCodecType, 5, "Pixlet"},
- {kPNGCodecType, 6, "PNG"},
- {kJPEGCodecType, 7, "JPEG"},
- {kMotionJPEGACodecType, 8, "M-JPEG A"},
- {kMotionJPEGBCodecType, 9, "M-JPEG B"},
- {kDVCPALCodecType, 10, "DV PAL"},
- {kDVCNTSCCodecType, 11, "DV/DVCPRO NTSC"},
- {kDVCPROHD720pCodecType, 12, "DVCPRO HD 720p"},
- {kDVCPROHD1080i50CodecType, 13, "DVCPRO HD 1080i50"},
- {kDVCPROHD1080i60CodecType, 14, "DVCPRO HD 1080i60"},
- {kMPEG4VisualCodecType, 15, "MPEG4"},
- {kH263CodecType, 16, "H.263"},
- {kH264CodecType, 17, "H.264"},
- {kAnimationCodecType, 18, "Animation"},
- {0,0,NULL}};
-
-static int qtVideoCodecCount = 18;
-
-int quicktime_get_num_videocodecs()
-{
- return qtVideoCodecCount;
-}
-
-QuicktimeCodecTypeDesc* quicktime_get_videocodecType_desc(int indexValue)
-{
- if ((indexValue>=0) && (indexValue < qtVideoCodecCount))
- return &qtVideoCodecList[indexValue];
- else
- return NULL;
-}
-
-int quicktime_rnatmpvalue_from_videocodectype(int codecType)
-{
- int i;
- for (i = 0; i < qtVideoCodecCount; i++) {
- if (qtVideoCodecList[i].codecType == codecType)
- return qtVideoCodecList[i].rnatmpvalue;
- }
-
- return 0;
-}
-
-int quicktime_videocodecType_from_rnatmpvalue(int rnatmpvalue)
-{
- int i;
- for (i = 0; i < qtVideoCodecCount; i++) {
- if (qtVideoCodecList[i].rnatmpvalue == rnatmpvalue)
- return qtVideoCodecList[i].codecType;
- }
-
- return 0;
-}
-
-/* Audio codec */
-static QuicktimeCodecTypeDesc qtAudioCodecList[] = {
- {0, 0, "No audio"},
- {kAudioFormatLinearPCM, 1, "LPCM"},
- {kAudioFormatAppleLossless, 2, "Apple Lossless"},
- {kAudioFormatMPEG4AAC, 3, "AAC"},
- {0,0,NULL}};
-
-static int qtAudioCodecCount = 4;
-
-int quicktime_get_num_audiocodecs()
-{
- return qtAudioCodecCount;
-}
-
-QuicktimeCodecTypeDesc* quicktime_get_audiocodecType_desc(int indexValue)
-{
- if ((indexValue>=0) && (indexValue < qtAudioCodecCount))
- return &qtAudioCodecList[indexValue];
- else
- return NULL;
-}
-
-int quicktime_rnatmpvalue_from_audiocodectype(int codecType)
-{
- int i;
- for (i = 0; i < qtAudioCodecCount; i++) {
- if (qtAudioCodecList[i].codecType == codecType)
- return qtAudioCodecList[i].rnatmpvalue;
- }
-
- return 0;
-}
-
-int quicktime_audiocodecType_from_rnatmpvalue(int rnatmpvalue)
-{
- int i;
- for (i = 0; i < qtAudioCodecCount; i++) {
- if (qtAudioCodecList[i].rnatmpvalue == rnatmpvalue)
- return qtAudioCodecList[i].codecType;
- }
-
- return 0;
-}
-
-
-static NSString *stringWithCodecType(int codecType)
-{
- char str[5];
-
- *((int *)str) = EndianU32_NtoB(codecType);
- str[4] = 0;
-
- return [NSString stringWithCString:str encoding:NSASCIIStringEncoding];
-}
-
-void makeqtstring(RenderData *rd, char *string, bool preview)
-{
- int sfra, efra;
-
- char txt[64];
-
- if (preview) {
- sfra = rd->psfra;
- efra = rd->pefra;
- }
- else {
- sfra = rd->sfra;
- efra = rd->efra;
- }
-
- strcpy(string, rd->pic);
- BLI_path_abs(string, G.main->name);
-
- BLI_make_existing_file(string);
-
- if (BLI_strcasecmp(string + strlen(string) - 4, ".mov")) {
- sprintf(txt, "%04d-%04d.mov", (rd->sfra) , (rd->efra) );
- strcat(string, txt);
- }
-}
-
-void filepath_qt(char *string, RenderData *rd, bool preview, const char *suffix)
-{
- int sfra, efra;
-
- if (string == NULL) return;
-
- if (preview) {
- sfra = rd->psfra;
- efra = rd->pefra;
- }
- else {
- sfra = rd->sfra;
- efra = rd->efra;
- }
-
- strcpy(string, rd->pic);
- BLI_path_abs(string, G.main->name);
-
- BLI_make_existing_file(string);
-
- if (rd->scemode & R_EXTENSION) {
- if (!BLI_testextensie(string, ".mov")) {
- BLI_path_frame_range(string, sfra, efra, 4);
- strcat(string, ".mov");
- }
- }
- else {
- if (BLI_path_frame_check_chars(string)) {
- BLI_path_frame_range(string, sfra, efra, 4);
- }
- }
-
- BLI_path_suffix(string, FILE_MAX, suffix, "");
-}
-
-void *context_create_qt(void)
-{
- QuicktimeExport *qtexport = MEM_callocN(sizeof(QuicktimeExport), "QuicktimeExport");
- return qtexport;
-}
-
-void context_free_qt(void *context_v)
-{
- QuicktimeExport *qtexport = context_v;
- if (qtexport) {
- MEM_freeN(qtexport);
- }
-}
-
-#pragma mark audio export functions
-
-static OSStatus write_cookie(AudioConverterRef converter, AudioFileID outfile)
-{
- // grab the cookie from the converter and write it to the file
- UInt32 cookieSize = 0;
- OSStatus err = AudioConverterGetPropertyInfo(converter, kAudioConverterCompressionMagicCookie, &cookieSize, NULL);
- // if there is an error here, then the format doesn't have a cookie, so on we go
- if (!err && cookieSize) {
- char* cookie = malloc(cookieSize);
-
- err = AudioConverterGetProperty(converter, kAudioConverterCompressionMagicCookie, &cookieSize, cookie);
-
- if (!err)
- err = AudioFileSetProperty (outfile, kAudioFilePropertyMagicCookieData, cookieSize, cookie);
- // even though some formats have cookies, some files don't take them
-
- free(cookie);
- }
- return err;
-}
-
-/* AudioConverter input stream callback */
-static OSStatus AudioConverterInputCallback(AudioConverterRef inAudioConverter,
- UInt32* ioNumberDataPackets,
- AudioBufferList* ioData,
- AudioStreamPacketDescription** outDataPacketDescription,
- void* inUserData)
-{
- QuicktimeExport *qtexport = inUserData;
- if (qtexport->audioTotalExportedFrames >= qtexport->audioLastFrame) { /* EOF */
- *ioNumberDataPackets = 0;
- return noErr;
- }
-
- if (qtexport->audioInputFormat.mBytesPerPacket * *ioNumberDataPackets > AUDIOOUTPUTBUFFERSIZE)
- *ioNumberDataPackets = AUDIOOUTPUTBUFFERSIZE / qtexport->audioInputFormat.mBytesPerPacket;
-
- if ((qtexport->audioTotalExportedFrames + *ioNumberDataPackets) > qtexport->audioLastFrame)
- *ioNumberDataPackets = (qtexport->audioLastFrame - qtexport->audioTotalExportedFrames) / qtexport->audioInputFormat.mFramesPerPacket;
-
- qtexport->audioTotalExportedFrames += *ioNumberDataPackets;
-
- AUD_Device_read(qtexport->audioInputDevice, (UInt8 *)qtexport->audioInputBuffer,
- qtexport->audioInputFormat.mFramesPerPacket * *ioNumberDataPackets);
-
- ioData->mBuffers[0].mDataByteSize = qtexport->audioInputFormat.mBytesPerPacket * *ioNumberDataPackets;
- ioData->mBuffers[0].mData = qtexport->audioInputBuffer;
- ioData->mBuffers[0].mNumberChannels = qtexport->audioInputFormat.mChannelsPerFrame;
-
- return noErr;
-}
-
-
-#pragma mark export functions
-
-int start_qt(
- void *context_v, struct Scene *scene, struct RenderData *rd, int UNUSED(rectx), int UNUSED(recty),
- ReportList *reports, bool preview, const char *UNUSED(suffix))
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSError *error;
- char name[1024];
- int success = 1;
- OSStatus err = noErr;
- int sfra, efra;
- QuicktimeExport *qtexport = context_v;
-
- if (preview) {
- sfra = rd->psfra;
- efra = rd->pefra;
- }
- else {
- sfra = rd->sfra;
- efra = rd->efra;
- }
-
- [QTMovie enterQTKitOnThread];
-
- /* Check first if the QuickTime 7.2.1 initToWritableFile: method is available */
- if ([[[[QTMovie alloc] init] autorelease] respondsToSelector:@selector(initToWritableFile:error:)] != YES) {
- BKE_report(reports, RPT_ERROR, "\nUnable to create quicktime movie, need Quicktime rev 7.2.1 or later");
- success = 0;
- }
- else {
- makeqtstring(rd, name, preview);
- qtexport->filename = [[NSString alloc] initWithUTF8String:name];
- qtexport->movie = nil;
- qtexport->audioFile = NULL;
-
- if (rd->qtcodecsettings.audiocodecType) {
- // generate a name for our video & audio files
- /* Init audio file */
- CFURLRef outputFileURL;
- char extension[32];
- AudioFileTypeID audioFileType;
-
- switch (rd->qtcodecsettings.audiocodecType) {
- case kAudioFormatLinearPCM:
- audioFileType = kAudioFileWAVEType;
- strcpy(extension,".wav");
- break;
- case kAudioFormatMPEG4AAC:
- case kAudioFormatAppleLossless:
- audioFileType = kAudioFileM4AType;
- strcpy(extension, ".m4a");
- break;
- default:
- audioFileType = kAudioFileAIFFType;
- strcpy(extension,".aiff");
- break;
- }
-
- tmpnam(name);
- strcat(name, extension);
- outputFileURL = CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault,(UInt8 *)name, strlen(name), false);
-
- if (outputFileURL) {
-
- qtexport->audioFileName = [[NSString alloc] initWithCString:name
- encoding:[NSString defaultCStringEncoding]];
-
- qtexport->audioInputFormat.mSampleRate = U.audiorate;
- qtexport->audioInputFormat.mFormatID = kAudioFormatLinearPCM;
- qtexport->audioInputFormat.mChannelsPerFrame = U.audiochannels;
- switch (U.audioformat) {
- case AUD_FORMAT_U8:
- qtexport->audioInputFormat.mBitsPerChannel = 8;
- qtexport->audioInputFormat.mFormatFlags = 0;
- break;
- case AUD_FORMAT_S24:
- qtexport->audioInputFormat.mBitsPerChannel = 24;
- qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- case AUD_FORMAT_S32:
- qtexport->audioInputFormat.mBitsPerChannel = 32;
- qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- case AUD_FORMAT_FLOAT32:
- qtexport->audioInputFormat.mBitsPerChannel = 32;
- qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
- break;
- case AUD_FORMAT_FLOAT64:
- qtexport->audioInputFormat.mBitsPerChannel = 64;
- qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
- break;
- case AUD_FORMAT_S16:
- default:
- qtexport->audioInputFormat.mBitsPerChannel = 16;
- qtexport->audioInputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- }
- qtexport->audioInputFormat.mBytesPerFrame = qtexport->audioInputFormat.mChannelsPerFrame * qtexport->audioInputFormat.mBitsPerChannel / 8;
- qtexport->audioInputFormat.mFramesPerPacket = 1; /*If not ==1, then need to check input callback for "rounding" issues"*/
- qtexport->audioInputFormat.mBytesPerPacket = qtexport->audioInputFormat.mBytesPerFrame;
- qtexport->audioInputFormat.mFormatFlags |= kLinearPCMFormatFlagIsPacked;
-
-
- /*Output format*/
- qtexport->audioOutputFormat.mFormatID = rd->qtcodecsettings.audiocodecType;
- //TODO: set audio channels
- qtexport->audioOutputFormat.mChannelsPerFrame = 2;
- qtexport->audioOutputFormat.mSampleRate = rd->qtcodecsettings.audioSampleRate;
-
- /* Default value for compressed formats, overridden after if not the case */
- qtexport->audioOutputFormat.mFramesPerPacket = 0;
- qtexport->audioOutputFormat.mBytesPerFrame = 0;
- qtexport->audioOutputFormat.mBytesPerPacket = 0;
- qtexport->audioOutputFormat.mBitsPerChannel = 0;
-
- switch (rd->qtcodecsettings.audiocodecType) {
- case kAudioFormatMPEG4AAC:
- qtexport->audioOutputFormat.mFormatFlags = kMPEG4Object_AAC_Main;
- /* AAC codec does not handle sample rates above 48kHz, force this limit instead of getting an error afterwards */
- if (qtexport->audioOutputFormat.mSampleRate > 48000) qtexport->audioOutputFormat.mSampleRate = 48000;
- break;
- case kAudioFormatAppleLossless:
- switch (U.audioformat) {
- case AUD_FORMAT_S16:
- qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_16BitSourceData;
- break;
- case AUD_FORMAT_S24:
- qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData;
- break;
- case AUD_FORMAT_S32:
- qtexport->audioOutputFormat.mFormatFlags = kAppleLosslessFormatFlag_32BitSourceData;
- break;
- case AUD_FORMAT_U8:
- case AUD_FORMAT_FLOAT32:
- case AUD_FORMAT_FLOAT64:
- default:
- break;
- }
- break;
- case kAudioFormatLinearPCM:
- default:
- switch (rd->qtcodecsettings.audioBitDepth) {
- case AUD_FORMAT_U8:
- qtexport->audioOutputFormat.mBitsPerChannel = 8;
- qtexport->audioOutputFormat.mFormatFlags = 0;
- break;
- case AUD_FORMAT_S24:
- qtexport->audioOutputFormat.mBitsPerChannel = 24;
- qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- case AUD_FORMAT_S32:
- qtexport->audioOutputFormat.mBitsPerChannel = 32;
- qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- case AUD_FORMAT_FLOAT32:
- qtexport->audioOutputFormat.mBitsPerChannel = 32;
- qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
- break;
- case AUD_FORMAT_FLOAT64:
- qtexport->audioOutputFormat.mBitsPerChannel = 64;
- qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsFloat;
- break;
- case AUD_FORMAT_S16:
- default:
- qtexport->audioOutputFormat.mBitsPerChannel = 16;
- qtexport->audioOutputFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
- break;
- }
- qtexport->audioOutputFormat.mFormatFlags |= kLinearPCMFormatFlagIsPacked;
- qtexport->audioOutputFormat.mBytesPerPacket = qtexport->audioOutputFormat.mChannelsPerFrame * (qtexport->audioOutputFormat.mBitsPerChannel / 8);
- qtexport->audioOutputFormat.mFramesPerPacket = 1;
- qtexport->audioOutputFormat.mBytesPerFrame = qtexport->audioOutputFormat.mBytesPerPacket;
- break;
- }
-
- err = AudioFileCreateWithURL(outputFileURL, audioFileType, &qtexport->audioOutputFormat, kAudioFileFlags_EraseFile, &qtexport->audioFile);
- CFRelease(outputFileURL);
-
- if (err)
- BKE_report(reports, RPT_ERROR, "\nQuicktime: unable to create temporary audio file. Format error ?");
- else {
- err = AudioConverterNew(&qtexport->audioInputFormat, &qtexport->audioOutputFormat, &qtexport->audioConverter);
- if (err) {
- BKE_report(reports, RPT_ERROR, "\nQuicktime: unable to initialize audio codec converter. Format error ?");
- AudioFileClose(qtexport->audioFile);
- qtexport->audioFile = NULL;
- [qtexport->audioFileName release];
- qtexport->audioFileName = nil;
- }
- else {
- UInt32 prop,propSize;
- /* Set up codec properties */
- if (rd->qtcodecsettings.audiocodecType == kAudioFormatMPEG4AAC) { /* Lossy compressed format */
- prop = rd->qtcodecsettings.audioBitRate;
- AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterEncodeBitRate,
- sizeof(prop), &prop);
-
- if (rd->qtcodecsettings.audioCodecFlags & QTAUDIO_FLAG_CODEC_ISCBR)
- prop = kAudioCodecBitRateControlMode_Constant;
- else
- prop = kAudioCodecBitRateControlMode_LongTermAverage;
- AudioConverterSetProperty(qtexport->audioConverter, kAudioCodecPropertyBitRateControlMode,
- sizeof(prop), &prop);
- }
- /* Conversion quality : if performance impact then offer degraded option */
- if ((rd->qtcodecsettings.audioCodecFlags & QTAUDIO_FLAG_RESAMPLE_NOHQ) == 0) {
- prop = kAudioConverterSampleRateConverterComplexity_Mastering;
- AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterSampleRateConverterComplexity,
- sizeof(prop), &prop);
-
- prop = kAudioConverterQuality_Max;
- AudioConverterSetProperty(qtexport->audioConverter, kAudioConverterSampleRateConverterQuality,
- sizeof(prop), &prop);
- }
-
- write_cookie(qtexport->audioConverter, qtexport->audioFile);
-
- /* Allocate output buffer */
- if (qtexport->audioOutputFormat.mBytesPerPacket ==0) /* VBR */
- AudioConverterGetProperty(qtexport->audioConverter, kAudioConverterPropertyMaximumOutputPacketSize,
- &propSize, &qtexport->audioCodecMaxOutputPacketSize);
- else
- qtexport->audioCodecMaxOutputPacketSize = qtexport->audioOutputFormat.mBytesPerPacket;
-
- qtexport->audioInputBuffer = MEM_mallocN(AUDIOOUTPUTBUFFERSIZE, "qt_audio_inputPacket");
- qtexport->audioOutputBuffer = MEM_mallocN(AUDIOOUTPUTBUFFERSIZE, "qt_audio_outputPacket");
- qtexport->audioOutputPktDesc = MEM_mallocN(sizeof(AudioStreamPacketDescription) * AUDIOOUTPUTBUFFERSIZE / qtexport->audioCodecMaxOutputPacketSize,
- "qt_audio_pktdesc");
- }
- }
- }
-
- if (err == noErr) {
- qtexport->videoTempFileName = [[NSString alloc] initWithCString:tmpnam(nil)
- encoding:[NSString defaultCStringEncoding]];
- if (qtexport->videoTempFileName) {
- qtexport->movie = [[QTMovie alloc] initToWritableFile:qtexport->videoTempFileName error:&error];
- }
-
- }
- }
- else
- qtexport->movie = [[QTMovie alloc] initToWritableFile:qtexport->filename error:&error];
-
- if (qtexport->movie == nil) {
- BKE_report(reports, RPT_ERROR, "Unable to create quicktime movie.");
- success = 0;
- if (qtexport->filename) [qtexport->filename release];
- qtexport->filename = nil;
- if (qtexport->audioFileName) [qtexport->audioFileName release];
- qtexport->audioFileName = nil;
- if (qtexport->videoTempFileName) [qtexport->videoTempFileName release];
- qtexport->videoTempFileName = nil;
- [QTMovie exitQTKitOnThread];
- }
- else {
- [qtexport->movie retain];
- [qtexport->movie setAttribute:[NSNumber numberWithBool:YES] forKey:QTMovieEditableAttribute];
- [qtexport->movie setAttribute:@"Made with Blender" forKey:QTMovieCopyrightAttribute];
-
- qtexport->frameDuration = QTMakeTime(rd->frs_sec_base * 1000, rd->frs_sec * 1000);
-
- /* specifying the codec attributes : try to retrieve them from render data first*/
- if (rd->qtcodecsettings.codecType) {
- qtexport->frameAttributes = [
- NSDictionary dictionaryWithObjectsAndKeys:
- stringWithCodecType(rd->qtcodecsettings.codecType),
- QTAddImageCodecType,
- [NSNumber numberWithLong:((rd->qtcodecsettings.codecSpatialQuality)*codecLosslessQuality)/100],
- QTAddImageCodecQuality,
- nil];
- }
- else {
- qtexport->frameAttributes = [
- NSDictionary dictionaryWithObjectsAndKeys:@"jpeg",
- QTAddImageCodecType,
- [NSNumber numberWithLong:codecHighQuality],
- QTAddImageCodecQuality,
- nil];
- }
- [qtexport->frameAttributes retain];
-
- if (qtexport->audioFile) {
- /* Init audio input stream */
- AUD_DeviceSpecs specs;
-
- specs.channels = U.audiochannels;
- specs.format = U.audioformat;
- specs.rate = U.audiorate;
- qtexport->audioInputDevice = AUD_openReadDevice(specs);
- AUD_playDevice(qtexport->audioInputDevice, scene->sound_scene, sfra * rd->frs_sec_base / rd->frs_sec);
-
- qtexport->audioOutputPktPos = 0;
- qtexport->audioTotalExportedFrames = 0;
- qtexport->audioTotalSavedFrames = 0;
-
- qtexport->audioLastFrame = (efra - sfra) * qtexport->audioInputFormat.mSampleRate * rd->frs_sec_base / rd->frs_sec;
- }
- }
- }
-
- [pool drain];
-
- return success;
-}
-
-int append_qt(
- void *context_v, struct RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty,
- const char *UNUSED(suffix), ReportList *reports)
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- NSBitmapImageRep *blBitmapFormatImage;
- NSImage *frameImage;
- OSStatus err = noErr;
- unsigned char *from_Ptr,*to_Ptr;
- int y,from_i,to_i;
- QuicktimeExport *qtexport = context_v;
-
- /* Create bitmap image rep in blender format (32bit RGBA) */
- blBitmapFormatImage = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
- pixelsWide:rectx
- pixelsHigh:recty
- bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
- colorSpaceName:NSCalibratedRGBColorSpace
- bitmapFormat:NSAlphaNonpremultipliedBitmapFormat
- bytesPerRow:rectx*4
- bitsPerPixel:32];
- if (!blBitmapFormatImage) {
- [pool drain];
- return 0;
- }
-
- from_Ptr = (unsigned char *)pixels;
- to_Ptr = (unsigned char *)[blBitmapFormatImage bitmapData];
- for (y = 0; y < recty; y++) {
- to_i = (recty-y-1)*rectx;
- from_i = y*rectx;
- memcpy(to_Ptr+4*to_i, from_Ptr+4*from_i, 4*rectx);
- }
-
- frameImage = [[NSImage alloc] initWithSize:NSMakeSize(rectx, recty)];
- [frameImage addRepresentation:blBitmapFormatImage];
-
- /* Add the image to the movie clip */
- [qtexport->movie addImage:frameImage
- forDuration:qtexport->frameDuration
- withAttributes:qtexport->frameAttributes];
-
- [blBitmapFormatImage release];
- [frameImage release];
-
-
- if (qtexport->audioFile) {
- UInt32 audioPacketsConverted;
-
- // Upper limit on total exported audio frames for this particular video frame
- const UInt64 exportedAudioFrameLimit = (frame - start_frame) * qtexport->audioInputFormat.mSampleRate * rd->frs_sec_base / rd->frs_sec;
-
- /* Append audio */
- while (qtexport->audioTotalExportedFrames < exportedAudioFrameLimit) {
-
- qtexport->audioBufferList.mNumberBuffers = 1;
- qtexport->audioBufferList.mBuffers[0].mNumberChannels = qtexport->audioOutputFormat.mChannelsPerFrame;
- qtexport->audioBufferList.mBuffers[0].mDataByteSize = AUDIOOUTPUTBUFFERSIZE;
- qtexport->audioBufferList.mBuffers[0].mData = qtexport->audioOutputBuffer;
-
- // Convert one audio packet at a time so that enclosing while loop can
- // keep audio processing in sync with video frames.
- // Previously, this was set to (AUDIOOUTPUTBUFFERSIZE / qtexport->audioCodecMaxOutputPacketSize),
- // however this may cause AudioConverterFillComplexBuffer to convert audio spanning multiple
- // video frames, which breaks animation of audio parameters such as volume for fade-in/out.
- audioPacketsConverted = 1;
-
- err = AudioConverterFillComplexBuffer(qtexport->audioConverter, AudioConverterInputCallback,
- qtexport, &audioPacketsConverted, &qtexport->audioBufferList, qtexport->audioOutputPktDesc);
- if (audioPacketsConverted) {
- AudioFileWritePackets(qtexport->audioFile, false, qtexport->audioBufferList.mBuffers[0].mDataByteSize,
- qtexport->audioOutputPktDesc, qtexport->audioOutputPktPos, &audioPacketsConverted, qtexport->audioOutputBuffer);
- qtexport->audioOutputPktPos += audioPacketsConverted;
-
- if (qtexport->audioOutputFormat.mFramesPerPacket) {
- // this is the common case: format has constant frames per packet
- qtexport->audioTotalSavedFrames += (audioPacketsConverted * qtexport->audioOutputFormat.mFramesPerPacket);
- }
- else {
- unsigned int i;
- // if there are variable frames per packet, then we have to do this for each packeet
- for (i = 0; i < audioPacketsConverted; ++i)
- qtexport->audioTotalSavedFrames += qtexport->audioOutputPktDesc[i].mVariableFramesInPacket;
- }
-
-
- }
- else {
- //Error getting audio packets
- BKE_reportf(reports, RPT_ERROR, "Unable to get further audio packets from frame %i, error = 0x%x",(int)qtexport->audioTotalExportedFrames,err);
- break;
- }
-
- }
- }
- [pool drain];
-
- return 1;
-}
-
-
-void end_qt(void *context_v)
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- QuicktimeExport *qtexport = context_v;
-
- if (qtexport->movie) {
-
- if (qtexport->audioFile)
- {
- NSDictionary *dict = nil;
- QTMovie *audioTmpMovie = nil;
- NSError *error;
- NSFileManager *fileManager;
-
- /* Mux video and audio then save file */
-
- /* Write last frames for VBR files */
- if (qtexport->audioOutputFormat.mBitsPerChannel == 0) {
- OSStatus err = noErr;
- AudioConverterPrimeInfo primeInfo;
- UInt32 primeSize = sizeof(primeInfo);
-
- err = AudioConverterGetProperty(qtexport->audioConverter, kAudioConverterPrimeInfo, &primeSize, &primeInfo);
- if (err == noErr) {
- // there's priming to write out to the file
- AudioFilePacketTableInfo pti;
- pti.mPrimingFrames = primeInfo.leadingFrames;
- pti.mRemainderFrames = primeInfo.trailingFrames;
- pti.mNumberValidFrames = qtexport->audioTotalSavedFrames - pti.mPrimingFrames - pti.mRemainderFrames;
- AudioFileSetProperty(qtexport->audioFile, kAudioFilePropertyPacketTableInfo, sizeof(pti), &pti);
- }
-
- }
-
- write_cookie(qtexport->audioConverter, qtexport->audioFile);
- AudioConverterDispose(qtexport->audioConverter);
- AudioFileClose(qtexport->audioFile);
- AUD_Device_free(qtexport->audioInputDevice);
- qtexport->audioFile = NULL;
- qtexport->audioInputDevice = NULL;
- MEM_freeN(qtexport->audioInputBuffer);
- MEM_freeN(qtexport->audioOutputBuffer);
- MEM_freeN(qtexport->audioOutputPktDesc);
-
- /* Reopen audio file and merge it */
- audioTmpMovie = [QTMovie movieWithFile:qtexport->audioFileName error:&error];
- if (audioTmpMovie) {
- NSArray *audioTracks = [audioTmpMovie tracksOfMediaType:QTMediaTypeSound];
- QTTrack *audioTrack = nil;
- if ( [audioTracks count] > 0 ) {
- audioTrack = [audioTracks objectAtIndex:0];
- }
-
- if (audioTrack) {
- QTTimeRange totalRange;
- totalRange.time = QTZeroTime;
- totalRange.duration = [[audioTmpMovie attributeForKey:QTMovieDurationAttribute] QTTimeValue];
-
- [qtexport->movie insertSegmentOfTrack:audioTrack timeRange:totalRange atTime:QTZeroTime];
- }
- }
-
- /* Save file */
- dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES]
- forKey:QTMovieFlatten];
-
- if (dict) {
- [qtexport->movie writeToFile:qtexport->filename withAttributes:dict];
- }
-
- /* Delete temp files */
- fileManager = [[NSFileManager alloc] init];
- [fileManager removeItemAtPath:qtexport->audioFileName error:&error];
- [fileManager removeItemAtPath:qtexport->videoTempFileName error:&error];
- [fileManager release];
- }
- else {
- /* Flush update of the movie file */
- [qtexport->movie updateMovieFile];
-
- [qtexport->movie invalidate];
- }
-
- /* Clean up movie structure */
- if (qtexport->filename) [qtexport->filename release];
- qtexport->filename = nil;
- if (qtexport->audioFileName) [qtexport->audioFileName release];
- qtexport->audioFileName = nil;
- if (qtexport->videoTempFileName) [qtexport->videoTempFileName release];
- qtexport->videoTempFileName = nil;
- [qtexport->frameAttributes release];
- [qtexport->movie release];
- }
-
- [QTMovie exitQTKitOnThread];
- [pool drain];
-}
-
-
-void free_qtcomponentdata(void)
-{
-}
-
-void quicktime_verify_image_type(RenderData *rd, ImageFormatData *imf)
-{
- if (imf->imtype == R_IMF_IMTYPE_QUICKTIME) {
- if ((rd->qtcodecsettings.codecType <= 0) ||
- (rd->qtcodecsettings.codecSpatialQuality < 0) ||
- (rd->qtcodecsettings.codecSpatialQuality > 100))
- {
- rd->qtcodecsettings.codecType = kJPEGCodecType;
- rd->qtcodecsettings.codecSpatialQuality = (codecHighQuality * 100) / codecLosslessQuality;
- }
- if ((rd->qtcodecsettings.audioSampleRate < 21000) ||
- (rd->qtcodecsettings.audioSampleRate > 193000))
- {
- rd->qtcodecsettings.audioSampleRate = 48000;
- }
-
- if (rd->qtcodecsettings.audioBitDepth == 0) {
- rd->qtcodecsettings.audioBitDepth = AUD_FORMAT_S16;
- }
-
- if (rd->qtcodecsettings.audioBitRate == 0) {
- rd->qtcodecsettings.audioBitRate = 256000;
- }
- }
-}
-
-#endif /* _WIN32 || __APPLE__ */
-#endif /* WITH_QUICKTIME */
-
diff --git a/source/blender/quicktime/apple/qtkit_import.m b/source/blender/quicktime/apple/qtkit_import.m
deleted file mode 100644
index ba7ee0a8936..00000000000
--- a/source/blender/quicktime/apple/qtkit_import.m
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * Code to use Quicktime to load images/movies as texture.
- *
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- *
- * The Original Code is written by Rob Haarsma (phase)
- *
- * Contributor(s): Stefan Gartner (sgefant)
- * Damien Plisson 11/2009
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-#ifdef WITH_QUICKTIME
-
-#include "MEM_guardedalloc.h"
-
-#include "IMB_anim.h"
-#include "BLI_sys_types.h"
-#include "BLI_utildefines.h"
-#include "BKE_global.h"
-
-#include "BLI_dynstr.h"
-#include "BLI_path_util.h"
-
-#import <Cocoa/Cocoa.h>
-#import <QTKit/QTKit.h>
-
-#include "quicktime_import.h"
-#include "quicktime_export.h"
-
-// quicktime structure definition
-// this structure is part of the anim struct
-
-typedef struct _QuicktimeMovie {
- QTMovie *movie;
- QTMedia *media;
-
- long durationTime;
- long durationScale;
- long framecount;
-
-
- ImBuf *ibuf;
-
- long previousPosition;
-
-} QuicktimeMovie;
-
-
-#define QTIME_DEBUG 0
-
-
-void quicktime_init(void)
-{
- G.have_quicktime = true;
-}
-
-void quicktime_exit(void)
-{
- if (G.have_quicktime) {
- free_qtcomponentdata();
- }
-}
-
-
-int anim_is_quicktime(const char *name)
-{
- NSAutoreleasePool *pool;
-
- // don't let quicktime movie import handle these
-
- if (BLI_testextensie_n(
- name,
- ".swf",
- ".txt",
- ".mpg",
- ".vob", /* disabled, vob is essential .mpg, don't handle */
- ".avi", /* wouldn't be appropriate ;) */
- ".mov", /* disabled, suboptimal decoding speed */
- ".mp4", /* disabled, suboptimal decoding speed */
- ".m4v", /* disabled, suboptimal decoding speed */
- ".tga",
- ".png",
- ".bmp",
- ".jpg",
- ".tif",
- ".exr",
- ".wav",
- ".zip",
- ".mp3",
- NULL))
- {
- return 0;
- }
-
- if (QTIME_DEBUG) printf("qt: checking as movie: %s\n", name);
-
- pool = [[NSAutoreleasePool alloc] init];
-
- if ([QTMovie canInitWithFile:[NSString stringWithCString:name
- encoding:[NSString defaultCStringEncoding]]])
- {
- [pool drain];
- return true;
- }
- else
- {
- [pool drain];
- return false;
- }
-}
-
-
-void free_anim_quicktime(struct anim *anim)
-{
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
- if (anim == NULL) return;
- if (anim->qtime == NULL) return;
-
- if (anim->qtime->ibuf)
- IMB_freeImBuf(anim->qtime->ibuf);
-
- [anim->qtime->media release];
- [anim->qtime->movie release];
-
- [QTMovie exitQTKitOnThread];
-
- if (anim->qtime) MEM_freeN (anim->qtime);
-
- anim->qtime = NULL;
-
- anim->duration = 0;
-
- [pool drain];
-}
-
-static ImBuf *nsImageToiBuf(NSImage *sourceImage, int width, int height)
-{
- ImBuf *ibuf = NULL;
- uchar *rasterRGB = NULL;
- uchar *rasterRGBA = NULL;
- uchar *toIBuf = NULL;
- int x, y, to_i, from_i;
- NSSize bitmapSize;
- NSBitmapImageRep *blBitmapFormatImageRGB,*blBitmapFormatImageRGBA, *bitmapImage = nil;
- NSEnumerator *enumerator;
- NSImageRep *representation;
-
- ibuf = IMB_allocImBuf(width, height, 32, IB_rect);
- if (!ibuf) {
- if (QTIME_DEBUG) {
- printf("quicktime_import: could not allocate memory for the image.\n");
- }
- return NULL;
- }
-
- /*Get the bitmap of the image*/
- enumerator = [[sourceImage representations] objectEnumerator];
- while ((representation = [enumerator nextObject])) {
- if ([representation isKindOfClass:[NSBitmapImageRep class]]) {
- bitmapImage = (NSBitmapImageRep *)representation;
- break;
- }
- }
- if (bitmapImage == nil) return NULL;
-
- if (([bitmapImage bitsPerPixel] == 32) && (([bitmapImage bitmapFormat] & 0x5) == 0)
- && ![bitmapImage isPlanar]) {
- /* Try a fast copy if the image is a meshed RGBA 32bit bitmap*/
- toIBuf = (uchar *)ibuf->rect;
- rasterRGB = (uchar *)[bitmapImage bitmapData];
- for (y = 0; y < height; y++) {
- to_i = (height-y-1)*width;
- from_i = y*width;
- memcpy(toIBuf+4*to_i, rasterRGB+4*from_i, 4*width);
- }
- }
- else {
-
- bitmapSize.width = width;
- bitmapSize.height = height;
-
- /* Tell cocoa image resolution is same as current system one */
- [bitmapImage setSize:bitmapSize];
-
- /* Convert the image in a RGBA 32bit format */
- /* As Core Graphics does not support contextes with non premutliplied alpha,
- * we need to get alpha key values in a separate batch */
-
- /* First get RGB values w/o Alpha to avoid pre-multiplication, 32bit but last byte is unused */
- blBitmapFormatImageRGB = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
- pixelsWide:width
- pixelsHigh:height
- bitsPerSample:8 samplesPerPixel:3 hasAlpha:NO isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bitmapFormat:0
- bytesPerRow:4*width
- bitsPerPixel:32/*RGB format padded to 32bits*/];
-
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:blBitmapFormatImageRGB]];
- [bitmapImage draw];
- [NSGraphicsContext restoreGraphicsState];
-
- rasterRGB = (uchar *)[blBitmapFormatImageRGB bitmapData];
- if (rasterRGB == NULL) {
- [blBitmapFormatImageRGB release];
- return NULL;
- }
-
- /* Then get Alpha values by getting the RGBA image (that is premultiplied btw) */
- blBitmapFormatImageRGBA = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:NULL
- pixelsWide:width
- pixelsHigh:height
- bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO
- colorSpaceName:NSDeviceRGBColorSpace
- bitmapFormat:0
- bytesPerRow:4*width
- bitsPerPixel:32/* RGBA */];
-
- [NSGraphicsContext saveGraphicsState];
- [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:blBitmapFormatImageRGBA]];
- [bitmapImage draw];
- [NSGraphicsContext restoreGraphicsState];
-
- rasterRGBA = (uchar *)[blBitmapFormatImageRGBA bitmapData];
- if (rasterRGBA == NULL) {
- [blBitmapFormatImageRGB release];
- [blBitmapFormatImageRGBA release];
- return NULL;
- }
-
- /*Copy the image to ibuf, flipping it vertically*/
- toIBuf = (uchar *)ibuf->rect;
- for (y = 0; y < height; y++) {
- for (x = 0; x < width; x++) {
- to_i = (height-y-1)*width + x;
- from_i = y*width + x;
-
- toIBuf[4*to_i] = rasterRGB[4*from_i]; /* R */
- toIBuf[4*to_i+1] = rasterRGB[4*from_i+1]; /* G */
- toIBuf[4*to_i+2] = rasterRGB[4*from_i+2]; /* B */
- toIBuf[4*to_i+3] = rasterRGBA[4*from_i+3]; /* A */
- }
- }
-
- [blBitmapFormatImageRGB release];
- [blBitmapFormatImageRGBA release];
- }
-
- return ibuf;
-}
-
-ImBuf *qtime_fetchibuf (struct anim *anim, int position)
-{
- NSImage *frameImage;
- QTTime time;
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- ImBuf *ibuf;
-
- if (anim == NULL) {
- return (NULL);
- }
-
- if (position == anim->qtime->previousPosition+1) { //Optimize sequential read
- [anim->qtime->movie stepForward];
- frameImage = [anim->qtime->movie currentFrameImage];
- anim->qtime->previousPosition++;
- }
- else {
- time.timeScale = anim->qtime->durationScale;
- time.timeValue = (anim->qtime->durationTime * position) / anim->qtime->framecount;
-
- [anim->qtime->movie setCurrentTime:time];
- frameImage = [anim->qtime->movie currentFrameImage];
-
- anim->qtime->previousPosition = position;
- }
-
- if (frameImage == nil) {
- if (QTIME_DEBUG) printf ("Error reading frame from Quicktime");
- [pool drain];
- return NULL;
- }
-
- ibuf = nsImageToiBuf(frameImage,anim->x, anim->y);
- [pool drain];
-
- return ibuf;
-}
-
-
-int startquicktime(struct anim *anim)
-{
- NSAutoreleasePool *pool;
- NSArray* videoTracks;
- NSSize frameSize;
- QTTime qtTimeDuration;
- NSDictionary *attributes;
-
- anim->qtime = MEM_callocN(sizeof(QuicktimeMovie),"animqt");
-
- if (anim->qtime == NULL) {
- if (QTIME_DEBUG) printf("Can't alloc qtime: %s\n", anim->name);
- return -1;
- }
-
- pool = [[NSAutoreleasePool alloc] init];
-
- [QTMovie enterQTKitOnThread];
-
- attributes = [NSDictionary dictionaryWithObjectsAndKeys:
- [NSString stringWithCString:anim->name
- encoding:[NSString defaultCStringEncoding]], QTMovieFileNameAttribute,
- [NSNumber numberWithBool:NO], QTMovieEditableAttribute,
- nil];
-
- anim->qtime->movie = [QTMovie movieWithAttributes:attributes error:NULL];
-
- if (!anim->qtime->movie) {
- if (QTIME_DEBUG) printf("qt: bad movie %s\n", anim->name);
- MEM_freeN(anim->qtime);
- if (QTIME_DEBUG) printf("qt: can't load %s\n", anim->name);
- [QTMovie exitQTKitOnThread];
- [pool drain];
- return -1;
- }
- [anim->qtime->movie retain];
-
- // sets Media and Track!
-
- videoTracks = [anim->qtime->movie tracksOfMediaType:QTMediaTypeVideo];
-
- if ([videoTracks count] == 0) {
- if (QTIME_DEBUG) printf("qt: no video tracks for movie %s\n", anim->name);
- [anim->qtime->movie release];
- MEM_freeN(anim->qtime);
- if (QTIME_DEBUG) printf("qt: can't load %s\n", anim->name);
- [QTMovie exitQTKitOnThread];
- [pool drain];
- return -1;
- }
-
- anim->qtime->media = [[videoTracks objectAtIndex:0] media];
- [anim->qtime->media retain];
-
-
- frameSize = [[anim->qtime->movie attributeForKey:QTMovieNaturalSizeAttribute] sizeValue];
- anim->x = frameSize.width;
- anim->y = frameSize.height;
-
- if (anim->x == 0 && anim->y == 0) {
- if (QTIME_DEBUG) printf("qt: error, no dimensions\n");
- free_anim_quicktime(anim);
- [pool drain];
- return -1;
- }
-
- anim->qtime->ibuf = IMB_allocImBuf(anim->x, anim->y, 32, IB_rect);
-
- qtTimeDuration = [[anim->qtime->media attributeForKey:QTMediaDurationAttribute] QTTimeValue];
- anim->qtime->durationTime = qtTimeDuration.timeValue;
- anim->qtime->durationScale = qtTimeDuration.timeScale;
-
- anim->qtime->framecount = [[anim->qtime->media attributeForKey:QTMediaSampleCountAttribute] longValue];
- anim->qtime->previousPosition = -2; //Force seeking for first read
-
- //fill blender's anim struct
-
- anim->duration = anim->qtime->framecount;
- anim->params = 0;
-
- anim->interlacing = 0;
- anim->orientation = 0;
- anim->framesize = anim->x * anim->y * 4;
-
- anim->curposition = 0;
-
- [pool drain];
-
- return 0;
-}
-
-#endif /* WITH_QUICKTIME */
-
diff --git a/source/blender/quicktime/quicktime_export.h b/source/blender/quicktime/quicktime_export.h
deleted file mode 100644
index aaa3f5c9070..00000000000
--- a/source/blender/quicktime/quicktime_export.h
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 *****
- */
-
-/** \file blender/quicktime/quicktime_export.h
- * \ingroup quicktime
- */
-
-
-#ifndef __QUICKTIME_EXPORT_H__
-#define __QUICKTIME_EXPORT_H__
-
-#if defined (_WIN32) || (__APPLE__)
-
-#define __AIFF__
-
-
-#define QTAUDIO_FLAG_RESAMPLE_NOHQ 1
-#define QTAUDIO_FLAG_CODEC_ISCBR 2
-
-
-/*Codec list*/
-typedef struct QuicktimeCodecTypeDesc {
- int codecType;
- int rnatmpvalue;
- const char *codecName;
-} QuicktimeCodecTypeDesc;
-
-// quicktime movie output functions
-struct ImageFormatData;
-struct RenderData;
-struct ReportList;
-struct Scene;
-
-int start_qt(void *context_v, struct Scene *scene, struct RenderData *rd, int rectx, int recty, struct ReportList *reports, bool preview, const char *suffix); //for movie handle (BKE writeavi.c now)
-int append_qt(void *context_v, struct RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, const char *suffix, struct ReportList *reports);
-void end_qt(void *context_v);
-void filepath_qt(char *string, struct RenderData *rd, bool preview, const char *suffix);
-void *context_create_qt(void);
-void context_free_qt(void *context_v);
-
-/*RNA helper functions */
-void quicktime_verify_image_type(struct RenderData *rd, struct ImageFormatData *imf); //used by RNA for defaults values init, if needed
-/*Video codec type*/
-int quicktime_get_num_videocodecs(void);
-QuicktimeCodecTypeDesc *quicktime_get_videocodecType_desc(int indexValue);
-int quicktime_rnatmpvalue_from_videocodectype(int codecType);
-int quicktime_videocodecType_from_rnatmpvalue(int rnatmpvalue);
-
-/*Audio codec type*/
-int quicktime_get_num_audiocodecs(void);
-QuicktimeCodecTypeDesc *quicktime_get_audiocodecType_desc(int indexValue);
-int quicktime_rnatmpvalue_from_audiocodectype(int codecType);
-int quicktime_audiocodecType_from_rnatmpvalue(int rnatmpvalue);
-
-void free_qtcomponentdata(void);
-void makeqtstring(struct RenderData *rd, char *string, bool preview); //for playanim.c
-
-
-#ifdef __APPLE__
-//Include the quicktime codec types constants that are missing in QTKitDefines.h
-enum {
- kRawCodecType = 'raw ',
- kCinepakCodecType = 'cvid',
- kGraphicsCodecType = 'smc ',
- kAnimationCodecType = 'rle ',
- kVideoCodecType = 'rpza',
- kComponentVideoCodecType = 'yuv2',
- kJPEGCodecType = 'jpeg',
- kMotionJPEGACodecType = 'mjpa',
- kMotionJPEGBCodecType = 'mjpb',
- kSGICodecType = '.SGI',
- kPlanarRGBCodecType = '8BPS',
- kMacPaintCodecType = 'PNTG',
- kGIFCodecType = 'gif ',
- kPhotoCDCodecType = 'kpcd',
- kQuickDrawGXCodecType = 'qdgx',
- kAVRJPEGCodecType = 'avr ',
- kOpenDMLJPEGCodecType = 'dmb1',
- kBMPCodecType = 'WRLE',
- kWindowsRawCodecType = 'WRAW',
- kVectorCodecType = 'path',
- kQuickDrawCodecType = 'qdrw',
- kWaterRippleCodecType = 'ripl',
- kFireCodecType = 'fire',
- kCloudCodecType = 'clou',
- kH261CodecType = 'h261',
- kH263CodecType = 'h263',
- kDVCNTSCCodecType = 'dvc ', /* DV - NTSC and DVCPRO NTSC (available in QuickTime 6.0 or later)*/
- /* NOTE: kDVCProNTSCCodecType is deprecated. */
- /* Use kDVCNTSCCodecType instead -- as far as the codecs are concerned, */
- /* the two data formats are identical.*/
- kDVCPALCodecType = 'dvcp',
- kDVCProPALCodecType = 'dvpp', /* available in QuickTime 6.0 or later*/
- kDVCPro50NTSCCodecType = 'dv5n',
- kDVCPro50PALCodecType = 'dv5p',
- kDVCPro100NTSCCodecType = 'dv1n',
- kDVCPro100PALCodecType = 'dv1p',
- kDVCPROHD720pCodecType = 'dvhp',
- kDVCPROHD1080i60CodecType = 'dvh6',
- kDVCPROHD1080i50CodecType = 'dvh5',
- kBaseCodecType = 'base',
- kFLCCodecType = 'flic',
- kTargaCodecType = 'tga ',
- kPNGCodecType = 'png ',
- kTIFFCodecType = 'tiff', /* NOTE: despite what might seem obvious from the two constants*/
- /* below and their names, they really are correct. 'yuvu' really */
- /* does mean signed, and 'yuvs' really does mean unsigned. Really. */
- kComponentVideoSigned = 'yuvu',
- kComponentVideoUnsigned = 'yuvs',
- kCMYKCodecType = 'cmyk',
- kMicrosoftVideo1CodecType = 'msvc',
- kSorensonCodecType = 'SVQ1',
- kSorenson3CodecType = 'SVQ3', /* available in QuickTime 5 and later*/
- kIndeo4CodecType = 'IV41',
- kMPEG4VisualCodecType = 'mp4v',
- k64ARGBCodecType = 'b64a',
- k48RGBCodecType = 'b48r',
- k32AlphaGrayCodecType = 'b32a',
- k16GrayCodecType = 'b16g',
- kMpegYUV420CodecType = 'myuv',
- kYUV420CodecType = 'y420',
- kSorensonYUV9CodecType = 'syv9',
- k422YpCbCr8CodecType = '2vuy', /* Component Y'CbCr 8-bit 4:2:2 */
- k444YpCbCr8CodecType = 'v308', /* Component Y'CbCr 8-bit 4:4:4 */
- k4444YpCbCrA8CodecType = 'v408', /* Component Y'CbCrA 8-bit 4:4:4:4 */
- k422YpCbCr16CodecType = 'v216', /* Component Y'CbCr 10,12,14,16-bit 4:2:2*/
- k422YpCbCr10CodecType = 'v210', /* Component Y'CbCr 10-bit 4:2:2 */
- k444YpCbCr10CodecType = 'v410', /* Component Y'CbCr 10-bit 4:4:4 */
- k4444YpCbCrA8RCodecType = 'r408', /* Component Y'CbCrA 8-bit 4:4:4:4, rendering format. full range alpha, zero biased yuv*/
- kJPEG2000CodecType = 'mjp2',
- kPixletCodecType = 'pxlt',
- kH264CodecType = 'avc1'
-};
-#endif
-
-#endif /* (_WIN32) || (__APPLE__) */
-
-#endif /* __QUICKTIME_IMP_H__ */
diff --git a/source/blender/quicktime/quicktime_import.h b/source/blender/quicktime/quicktime_import.h
deleted file mode 100644
index 3c6b2028031..00000000000
--- a/source/blender/quicktime/quicktime_import.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Quicktime_import.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- *
- * The Original Code is Copyright (C) 2002-2003 by TNCCI Inc.
- * All rights reserved.
- *
- * The Original Code is: all of this file.
- *
- * Contributor(s): none yet.
- *
- * ***** END GPL LICENSE BLOCK *****
- */
-
-/** \file blender/quicktime/quicktime_import.h
- * \ingroup quicktime
- */
-
-
-
-#ifndef __QUICKTIME_IMPORT_H__
-#define __QUICKTIME_IMPORT_H__
-
-#define __AIFF__
-
-#include "../imbuf/IMB_imbuf.h"
-#include "../imbuf/IMB_imbuf_types.h"
-
-#ifdef _WIN32
-# ifndef __FIXMATH__
-# include <FixMath.h>
-# endif /* __FIXMATH__ */
-#endif /* _WIN32 _ */
-
-/* init/exit */
-
-void quicktime_init(void);
-void quicktime_exit(void);
-
-/* quicktime movie import functions */
-
-int anim_is_quicktime(const char *name);
-int startquicktime(struct anim *anim);
-void free_anim_quicktime(struct anim *anim);
-ImBuf *qtime_fetchibuf(struct anim *anim, int position);
-
-#endif /* __QUICKTIME_IMPORT_H__ */
diff --git a/source/blender/render/CMakeLists.txt b/source/blender/render/CMakeLists.txt
index 9e40ab02ee4..27ec6bf8ba6 100644
--- a/source/blender/render/CMakeLists.txt
+++ b/source/blender/render/CMakeLists.txt
@@ -34,7 +34,9 @@ set(INC
../depsgraph
../makesdna
../makesrna
+ ../nodes
../physics
+ ../../../intern/atomic
../../../intern/guardedalloc
../../../intern/mikktspace
../../../intern/smoke/extern
@@ -146,16 +148,6 @@ if(WITH_FREESTYLE)
add_definitions(-DWITH_FREESTYLE)
endif()
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../quicktime
- )
- list(APPEND INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_GAMEENGINE)
add_definitions(-DWITH_GAMEENGINE)
endif()
@@ -164,10 +156,6 @@ if(WITH_INTERNATIONAL)
add_definitions(-DWITH_INTERNATIONAL)
endif()
-if(WITH_CYCLES AND WITH_CYCLES_DEBUG)
- add_definitions(-DWITH_CYCLES_DEBUG)
-endif()
-
if(APPLE)
# SSE math is enabled by default on x86_64
if(CMAKE_OSX_ARCHITECTURES MATCHES "i386")
diff --git a/source/blender/render/extern/include/RE_bake.h b/source/blender/render/extern/include/RE_bake.h
index a04d1d6632c..090e0e6c28d 100644
--- a/source/blender/render/extern/include/RE_bake.h
+++ b/source/blender/render/extern/include/RE_bake.h
@@ -72,13 +72,13 @@ bool RE_bake_has_engine(struct Render *re);
bool RE_bake_engine(
struct Render *re, struct Object *object, const int object_id, const BakePixel pixel_array[],
- const size_t num_pixels, const int depth, const ScenePassType pass_type, const int pass_filter, float result[]);
+ const size_t num_pixels, const int depth, const eScenePassType pass_type, const int pass_filter, float result[]);
/* bake.c */
-int RE_pass_depth(const ScenePassType pass_type);
+int RE_pass_depth(const eScenePassType pass_type);
bool RE_bake_internal(
struct Render *re, struct Object *object, const BakePixel pixel_array[],
- const size_t num_pixels, const int depth, const ScenePassType pass_type, float result[]);
+ const size_t num_pixels, const int depth, const eScenePassType pass_type, float result[]);
bool RE_bake_pixels_populate_from_objects(
struct Mesh *me_low, BakePixel pixel_array_from[], BakePixel pixel_array_to[],
@@ -95,13 +95,13 @@ void RE_bake_margin(struct ImBuf *ibuf, char *mask, const int margin);
void RE_bake_normal_world_to_object(
const BakePixel pixel_array[], const size_t num_pixels, const int depth, float result[],
- struct Object *ob, const BakeNormalSwizzle normal_swizzle[3]);
+ struct Object *ob, const eBakeNormalSwizzle normal_swizzle[3]);
void RE_bake_normal_world_to_tangent(
const BakePixel pixel_array[], const size_t num_pixels, const int depth, float result[],
- struct Mesh *me, const BakeNormalSwizzle normal_swizzle[3], float mat[4][4]);
+ struct Mesh *me, const eBakeNormalSwizzle normal_swizzle[3], float mat[4][4]);
void RE_bake_normal_world_to_world(
const BakePixel pixel_array[], const size_t num_pixels, const int depth, float result[],
- const BakeNormalSwizzle normal_swizzle[3]);
+ const eBakeNormalSwizzle normal_swizzle[3]);
void RE_bake_ibuf_clear(struct Image *image, const bool is_tangent);
diff --git a/source/blender/render/extern/include/RE_engine.h b/source/blender/render/extern/include/RE_engine.h
index f83a210275f..321eda0175f 100644
--- a/source/blender/render/extern/include/RE_engine.h
+++ b/source/blender/render/extern/include/RE_engine.h
@@ -96,6 +96,7 @@ typedef struct RenderEngineType {
void (*view_draw)(struct RenderEngine *engine, const struct bContext *context);
void (*update_script_node)(struct RenderEngine *engine, struct bNodeTree *ntree, struct bNode *node);
+ void (*update_render_passes)(struct RenderEngine *engine, struct Scene *scene, struct SceneRenderLayer *srl);
/* RNA integration */
ExtensionRNA ext;
@@ -139,7 +140,9 @@ void RE_result_load_from_file(struct RenderResult *result, struct ReportList *re
struct RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w, int h, const char *layername, const char *viewname);
void RE_engine_update_result(RenderEngine *engine, struct RenderResult *result);
-void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int cancel, int merge_results);
+void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, const char *chan_id, const char *layername);
+void RE_engine_end_result(RenderEngine *engine, struct RenderResult *result, int cancel, int highlight, int merge_results);
+struct RenderResult *RE_engine_get_result(struct RenderEngine *engine);
const char *RE_engine_active_view_get(RenderEngine *engine);
void RE_engine_active_view_set(RenderEngine *engine, const char *viewname);
@@ -160,6 +163,9 @@ bool RE_engine_is_external(struct Render *re);
void RE_engine_frame_set(struct RenderEngine *engine, int frame, float subframe);
+void RE_engine_register_pass(struct RenderEngine *engine, struct Scene *scene, struct SceneRenderLayer *srl,
+ const char *name, int channels, const char *chanid, int type);
+
/* Engine Types */
void RE_engines_init(void);
diff --git a/source/blender/render/extern/include/RE_pipeline.h b/source/blender/render/extern/include/RE_pipeline.h
index f535aa5aa71..8065de831ba 100644
--- a/source/blender/render/extern/include/RE_pipeline.h
+++ b/source/blender/render/extern/include/RE_pipeline.h
@@ -83,25 +83,19 @@ typedef struct RenderView {
typedef struct RenderPass {
struct RenderPass *next, *prev;
- int passtype, channels;
+ int channels;
char name[64]; /* amount defined in openexr_multi.h */
char chan_id[8]; /* amount defined in openexr_multi.h */
float *rect;
int rectx, recty;
- char internal_name[64]; /* EXR_PASS_MAXNAME */
+ char fullname[64]; /* EXR_PASS_MAXNAME */
char view[64]; /* EXR_VIEW_MAXNAME */
int view_id; /* quick lookup */
- int debug_type;
+ int pad;
} RenderPass;
-enum {
- RENDER_PASS_DEBUG_BVH_TRAVERSED_NODES = 0,
- RENDER_PASS_DEBUG_BVH_TRAVERSED_INSTANCES = 1,
- RENDER_PASS_DEBUG_RAY_BOUNCES = 2,
- RENDER_PASS_DEBUG_BVH_INTERSECTIONS = 3,
-};
/* a renderlayer is a full image, but with all passes and samples */
/* size of the rects is defined in RenderResult */
@@ -200,6 +194,10 @@ typedef struct RenderStats {
struct Render *RE_NewRender(const char *name);
struct Render *RE_GetRender(const char *name);
+struct Scene;
+struct Render *RE_NewSceneRender(const struct Scene *scene);
+struct Render *RE_GetSceneRender(const struct Scene *scene);
+
/* assign default dummy callbacks */
void RE_InitRenderCB(struct Render *re);
@@ -236,7 +234,9 @@ void RE_render_result_rect_from_ibuf(
struct ImBuf *ibuf, const int view_id);
struct RenderLayer *RE_GetRenderLayer(struct RenderResult *rr, const char *name);
-float *RE_RenderLayerGetPass(volatile struct RenderLayer *rl, int passtype, const char *viewname);
+float *RE_RenderLayerGetPass(volatile struct RenderLayer *rl, const char *name, const char *viewname);
+
+bool RE_HasSingleLayer(struct Render *re);
/* add passes for grease pencil */
struct RenderPass *RE_create_gp_pass(struct RenderResult *rr, const char *layername, const char *viewname);
@@ -312,7 +312,7 @@ void RE_PreviewRender(struct Render *re, struct Main *bmain, struct Scene *scene
bool RE_ReadRenderResult(struct Scene *scene, struct Scene *scenode);
bool RE_WriteRenderResult(
struct ReportList *reports, RenderResult *rr, const char *filename,
- struct ImageFormatData *imf, const bool multiview, const char *view);
+ struct ImageFormatData *imf, const char *view, int layer);
struct RenderResult *RE_MultilayerConvert(
void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty);
@@ -336,15 +336,13 @@ void RE_current_scene_update_cb(struct Render *re, void *handle, void (*f)(void
/* should move to kernel once... still unsure on how/where */
float RE_filter_value(int type, float x);
-/* vector blur zbuffer method */
-void RE_zbuf_accumulate_vecblur(
- struct NodeBlurData *nbd, int xsize, int ysize, float *newrect,
- const float *imgrect, float *vecbufrect, const float *zbufrect);
int RE_seq_render_active(struct Scene *scene, struct RenderData *rd);
bool RE_layers_have_name(struct RenderResult *result);
+bool RE_passes_have_name(struct RenderLayer *rl);
+struct RenderPass *RE_pass_find_by_name(volatile struct RenderLayer *rl, const char *name, const char *viewname);
struct RenderPass *RE_pass_find_by_type(volatile struct RenderLayer *rl, int passtype, const char *viewname);
/* shaded view or baking options */
@@ -381,26 +379,19 @@ bool RE_allow_render_generic_object(struct Object *ob);
/* RE_updateRenderInstances flag */
enum {
RE_OBJECT_INSTANCES_UPDATE_VIEW = (1 << 0),
- RE_OBJECT_INSTANCES_UPDATE_OBMAT = (1 << 1),
+ RE_OBJECT_INSTANCES_UPDATE_OBMAT = (1 << 1)
};
void RE_updateRenderInstances(Render *re, int flag);
/******* defined in render_result.c *********/
-bool RE_HasFakeLayer(RenderResult *res);
+bool RE_HasCombinedLayer(RenderResult *res);
+bool RE_HasFloatPixels(RenderResult *res);
bool RE_RenderResult_is_stereo(RenderResult *res);
struct RenderView *RE_RenderViewGetById(struct RenderResult *res, const int view_id);
struct RenderView *RE_RenderViewGetByName(struct RenderResult *res, const char *viewname);
RenderResult *RE_DuplicateRenderResult(RenderResult *rr);
-/******* Debug pass helper functions *********/
-
-#ifdef WITH_CYCLES_DEBUG
-int RE_debug_pass_num_channels_get(int pass_type);
-const char *RE_debug_pass_name_get(int pass_type);
-int RE_debug_pass_type_get(struct Render *re);
-#endif
-
#endif /* __RE_PIPELINE_H__ */
diff --git a/source/blender/render/extern/include/RE_render_ext.h b/source/blender/render/extern/include/RE_render_ext.h
index 2b5d0ca4e14..971be381f97 100644
--- a/source/blender/render/extern/include/RE_render_ext.h
+++ b/source/blender/render/extern/include/RE_render_ext.h
@@ -45,7 +45,7 @@ struct Scene;
/* render_texture.c */
/* used by particle.c, effect.c, editmesh_modes.c and brush.c, returns 1 if rgb, 0 otherwise */
int externtex(
- struct MTex *mtex, const float vec[3], float *tin, float *tr, float *tg, float *tb, float *ta,
+ const struct MTex *mtex, const float vec[3], float *tin, float *tr, float *tg, float *tb, float *ta,
const int thread, struct ImagePool *pool, const bool skip_load_image, const bool texnode_preview);
void texture_rgb_blend(float in[3], const float tex[3], const float out[3], float fact, float facg, int blendtype);
float texture_value_blend(float tex, float out, float fact, float facg, int blendtype);
@@ -62,9 +62,6 @@ void RE_sample_material_color(
/* imagetexture.c */
void ibuf_sample(struct ImBuf *ibuf, float fx, float fy, float dx, float dy, float result[4]);
-/* zbuf.c */
-void antialias_tagbuf(int xsize, int ysize, char *rectmove);
-
/* pointdensity.c */
struct PointDensity;
@@ -89,4 +86,3 @@ void RE_point_density_sample(
void RE_point_density_free(struct PointDensity *pd);
#endif /* __RE_RENDER_EXT_H__ */
-
diff --git a/source/blender/render/extern/include/RE_shader_ext.h b/source/blender/render/extern/include/RE_shader_ext.h
index ae389fdfd2e..e1cb922f6a5 100644
--- a/source/blender/render/extern/include/RE_shader_ext.h
+++ b/source/blender/render/extern/include/RE_shader_ext.h
@@ -178,6 +178,7 @@ typedef struct ShadeInput {
unsigned int lay;
int layflag, passflag, combinedflag;
+ short object_pass_index;
struct Group *light_override;
struct Material *mat_override;
@@ -216,7 +217,7 @@ int multitex_nodes(struct Tex *tex, float texvec[3], float dxt[3], float dyt[3],
const short thread, short which_output, struct ShadeInput *shi, struct MTex *mtex,
struct ImagePool *pool);
float RE_lamp_get_data(struct ShadeInput *shi, struct Object *lamp_obj, float col[4], float lv[3], float *dist, float shadow[4]);
-void RE_instance_get_particle_info(struct ObjectInstanceRen *obi, float *index, float *age, float *lifetime, float co[3], float *size, float vel[3], float angvel[3]);
+void RE_instance_get_particle_info(struct ObjectInstanceRen *obi, float *index, float *random, float *age, float *lifetime, float co[3], float *size, float vel[3], float angvel[3]);
float RE_fresnel_dielectric(float incoming[3], float normal[3], float eta);
@@ -241,6 +242,9 @@ enum {
const float (*RE_object_instance_get_matrix(struct ObjectInstanceRen *obi, int matrix_id))[4];
+float RE_object_instance_get_object_pass_index(struct ObjectInstanceRen *obi);
+float RE_object_instance_get_random_id(struct ObjectInstanceRen *obi);
+
enum {
RE_VIEW_MATRIX,
RE_VIEWINV_MATRIX,
diff --git a/source/blender/render/intern/include/render_result.h b/source/blender/render/intern/include/render_result.h
index 0c4f4e20325..8d293c938c7 100644
--- a/source/blender/render/intern/include/render_result.h
+++ b/source/blender/render/intern/include/render_result.h
@@ -67,6 +67,11 @@ void render_result_views_new(struct RenderResult *rr, struct RenderData *rd);
void render_result_merge(struct RenderResult *rr, struct RenderResult *rrpart);
+/* Add Passes */
+
+void render_result_clone_passes(struct Render *re, struct RenderResult *rr, const char *viewname);
+void render_result_add_pass(struct RenderResult *rr, const char *name, int channels, const char *chan_id, const char *layername, const char *viewname);
+
/* Free */
void render_result_free(struct RenderResult *rr);
@@ -84,7 +89,7 @@ void render_result_exr_file_begin(struct Render *re);
void render_result_exr_file_end(struct Render *re);
/* render pass wrapper for gpencil */
-struct RenderPass *gp_add_pass(struct RenderResult *rr, struct RenderLayer *rl, int channels, int passtype, const char *viewname);
+struct RenderPass *gp_add_pass(struct RenderResult *rr, struct RenderLayer *rl, int channels, const char *name, const char *viewname);
void render_result_exr_file_merge(struct RenderResult *rr, struct RenderResult *rrpart, const char *viewname);
@@ -110,6 +115,7 @@ void render_result_rect_get_pixels(struct RenderResult *rr,
void render_result_views_shallowcopy(struct RenderResult *dst, struct RenderResult *src);
void render_result_views_shallowdelete(struct RenderResult *rr);
+bool render_result_has_views(struct RenderResult *rr);
#endif /* __RENDER_RESULT_H__ */
diff --git a/source/blender/render/intern/include/render_types.h b/source/blender/render/intern/include/render_types.h
index b3a5ccdae17..45206f21ae4 100644
--- a/source/blender/render/intern/include/render_types.h
+++ b/source/blender/render/intern/include/render_types.h
@@ -118,7 +118,8 @@ typedef struct RenderPart {
enum {
PART_STATUS_NONE = 0,
PART_STATUS_IN_PROGRESS = 1,
- PART_STATUS_READY = 2
+ PART_STATUS_RENDERED = 2,
+ PART_STATUS_MERGED = 3
};
/* controls state of render, everything that's read-only during render stage */
@@ -335,7 +336,7 @@ typedef struct ObjectRen {
char (*mcol)[MAX_CUSTOMDATA_LAYER_NAME];
int actmtface, actmcol, bakemtface;
- char tangent_mask; /* which tangent layer should be calculated */
+ short tangent_mask; /* which tangent layer should be calculated */
float obmat[4][4]; /* only used in convertblender.c, for instancing */
@@ -382,6 +383,8 @@ typedef struct ObjectInstanceRen {
float part_co[3];
float part_vel[3];
float part_avel[3];
+
+ unsigned int random_id;
} ObjectInstanceRen;
/* ------------------------------------------------------------------------- */
diff --git a/source/blender/render/intern/include/rendercore.h b/source/blender/render/intern/include/rendercore.h
index 7254fd25ee6..f4c4a50ac27 100644
--- a/source/blender/render/intern/include/rendercore.h
+++ b/source/blender/render/intern/include/rendercore.h
@@ -34,6 +34,12 @@
#include "render_types.h"
+#include "RE_engine.h"
+
+#include "DNA_node_types.h"
+
+#include "NOD_composite.h"
+
struct ShadeInput;
struct ShadeResult;
struct World;
@@ -77,6 +83,8 @@ void zbufshade_sss_tile(struct RenderPart *pa);
int get_sample_layers(struct RenderPart *pa, struct RenderLayer *rl, struct RenderLayer **rlpp);
+void render_internal_update_passes(struct RenderEngine *engine, struct Scene *scene, struct SceneRenderLayer *srl);
+
/* -------- ray.c ------- */
diff --git a/source/blender/render/intern/include/shading.h b/source/blender/render/intern/include/shading.h
index 13f16ce0bd7..3ef6e9d7476 100644
--- a/source/blender/render/intern/include/shading.h
+++ b/source/blender/render/intern/include/shading.h
@@ -57,7 +57,7 @@ typedef struct ShadeSample {
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_set_triangle(struct ShadeInput *shi, int obi, int facenr, int normal_flip);
void shade_input_copy_triangle(struct ShadeInput *shi, struct ShadeInput *from);
void shade_input_calc_viewco(struct ShadeInput *shi, float x, float y, float z, float view[3], float dxyview[2], float co[3], float dxco[3], float dyco[3]);
void shade_input_set_viewco(struct ShadeInput *shi, float x, float y, float sx, float sy, float z);
diff --git a/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp b/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
index 81e41a20f2e..103fa3e6034 100644
--- a/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
+++ b/source/blender/render/intern/raytrace/rayobject_rtbuild.cpp
@@ -59,6 +59,7 @@ static void rtbuild_init(RTBuilder *b)
b->primitives.begin = NULL;
b->primitives.end = NULL;
b->primitives.maxsize = 0;
+ b->depth = 0;
for (int i = 0; i < RTBUILD_MAX_CHILDS; i++)
b->child_offset[i] = 0;
@@ -178,6 +179,8 @@ RTBuilder *rtbuild_get_child(RTBuilder *b, int child, RTBuilder *tmp)
{
rtbuild_init(tmp);
+ tmp->depth = b->depth + 1;
+
for (int i = 0; i < 3; i++)
if (b->sorted_begin[i]) {
tmp->sorted_begin[i] = b->sorted_begin[i] + b->child_offset[child];
@@ -336,6 +339,15 @@ int rtbuild_heuristic_object_split(RTBuilder *b, int nchilds)
int baxis = -1, boffset = 0;
if (size > nchilds) {
+ if (b->depth > RTBUILD_MAX_SAH_DEPTH) {
+ // for degenerate cases we avoid running out of stack space
+ // by simply splitting the children in the middle
+ b->child_offset[0] = 0;
+ b->child_offset[1] = (size+1)/2;
+ b->child_offset[2] = size;
+ return 2;
+ }
+
float bcost = FLT_MAX;
baxis = -1;
boffset = size / 2;
diff --git a/source/blender/render/intern/raytrace/rayobject_rtbuild.h b/source/blender/render/intern/raytrace/rayobject_rtbuild.h
index 9e296da144b..061d76e3a3e 100644
--- a/source/blender/render/intern/raytrace/rayobject_rtbuild.h
+++ b/source/blender/render/intern/raytrace/rayobject_rtbuild.h
@@ -42,14 +42,15 @@ extern "C" {
/*
* Ray Tree Builder
* this structs helps building any type of tree
- * it contains several methods to organiza/split nodes
+ * it contains several methods to organize/split nodes
* allowing to create a given tree on the fly.
*
* Idea is that other trees BVH, BIH can use this code to
* generate with simple calls, and then convert to the theirs
* specific structure on the fly.
*/
-#define RTBUILD_MAX_CHILDS 32
+#define RTBUILD_MAX_CHILDS 32
+#define RTBUILD_MAX_SAH_DEPTH 256
typedef struct RTBuilder {
@@ -79,6 +80,8 @@ typedef struct RTBuilder {
float bb[6];
+ /* current depth */
+ int depth;
} RTBuilder;
/* used during creation */
diff --git a/source/blender/render/intern/source/bake.c b/source/blender/render/intern/source/bake.c
index 31e461b4536..b5a37d1d42b 100644
--- a/source/blender/render/intern/source/bake.c
+++ b/source/blender/render/intern/source/bake.c
@@ -609,7 +609,7 @@ static int get_next_bake_face(BakeShade *bs)
return 0;
}
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
for (; obi; obi = obi->next, v = 0) {
obr = obi->obr;
@@ -724,13 +724,13 @@ static int get_next_bake_face(BakeShade *bs)
bs->vlr = vlr;
bs->vdone++; /* only for error message if nothing was rendered */
v++;
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return 1;
}
}
}
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
return 0;
}
@@ -845,7 +845,7 @@ static void shade_tface(BakeShade *bs)
if (bs->use_mask || bs->use_displacement_buffer) {
BakeImBufuserData *userdata = bs->ibuf->userdata;
if (userdata == NULL) {
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
userdata = bs->ibuf->userdata;
if (userdata == NULL) /* since the thread was locked, its possible another thread alloced the value */
userdata = MEM_callocN(sizeof(BakeImBufuserData), "BakeImBufuserData");
@@ -864,7 +864,7 @@ static void shade_tface(BakeShade *bs)
bs->ibuf->userdata = userdata;
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
}
bs->rect_mask = userdata->mask_buffer;
@@ -1040,7 +1040,7 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_up
BKE_main_id_tag_listbase(&G.main->mesh, LIB_TAG_DOIT, false);
}
- BLI_init_threads(&threads, do_bake_thread, re->r.threads);
+ BLI_threadpool_init(&threads, do_bake_thread, re->r.threads);
handles = MEM_callocN(sizeof(BakeShade) * re->r.threads, "BakeShade");
@@ -1077,7 +1077,7 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_up
handles[a].displacement_min = FLT_MAX;
handles[a].displacement_max = -FLT_MAX;
- BLI_insert_thread(&threads, &handles[a]);
+ BLI_threadpool_insert(&threads, &handles[a]);
}
/* wait for everything to be done */
@@ -1151,7 +1151,7 @@ int RE_bake_shade_all_selected(Render *re, int type, Object *actob, short *do_up
MEM_freeN(handles);
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
if (vdone == 0) {
result = BAKE_RESULT_NO_OBJECTS;
diff --git a/source/blender/render/intern/source/bake_api.c b/source/blender/render/intern/source/bake_api.c
index 73424a4e846..505af3c2fa8 100644
--- a/source/blender/render/intern/source/bake_api.c
+++ b/source/blender/render/intern/source/bake_api.c
@@ -684,6 +684,10 @@ void RE_bake_pixels_populate(
int mat_nr = mp->mat_nr;
int image_id = bake_images->lookup[mat_nr];
+ if (image_id < 0) {
+ continue;
+ }
+
bd.bk_image = &bake_images->data[image_id];
bd.primitive_id = ++p_id;
@@ -730,7 +734,7 @@ static void normal_uncompress(float out[3], const float in[3])
out[i] = 2.0f * in[i] - 1.0f;
}
-static void normal_compress(float out[3], const float in[3], const BakeNormalSwizzle normal_swizzle[3])
+static void normal_compress(float out[3], const float in[3], const eBakeNormalSwizzle normal_swizzle[3])
{
const int swizzle_index[6] = {
0, /* R_BAKE_POSX */
@@ -773,7 +777,7 @@ static void normal_compress(float out[3], const float in[3], const BakeNormalSwi
*/
void RE_bake_normal_world_to_tangent(
const BakePixel pixel_array[], const size_t num_pixels, const int depth,
- float result[], Mesh *me, const BakeNormalSwizzle normal_swizzle[3],
+ float result[], Mesh *me, const eBakeNormalSwizzle normal_swizzle[3],
float mat[4][4])
{
size_t i;
@@ -884,7 +888,7 @@ void RE_bake_normal_world_to_tangent(
void RE_bake_normal_world_to_object(
const BakePixel pixel_array[], const size_t num_pixels, const int depth,
- float result[], struct Object *ob, const BakeNormalSwizzle normal_swizzle[3])
+ float result[], struct Object *ob, const eBakeNormalSwizzle normal_swizzle[3])
{
size_t i;
float iobmat[4][4];
@@ -912,7 +916,7 @@ void RE_bake_normal_world_to_object(
void RE_bake_normal_world_to_world(
const BakePixel pixel_array[], const size_t num_pixels, const int depth,
- float result[], const BakeNormalSwizzle normal_swizzle[3])
+ float result[], const eBakeNormalSwizzle normal_swizzle[3])
{
size_t i;
@@ -971,7 +975,7 @@ static bool bake_uv(const BakePixel pixel_array[], const size_t num_pixels, cons
bool RE_bake_internal(
Render *UNUSED(re), Object *UNUSED(object), const BakePixel pixel_array[],
- const size_t num_pixels, const int depth, const ScenePassType pass_type, float result[])
+ const size_t num_pixels, const int depth, const eScenePassType pass_type, float result[])
{
switch (pass_type) {
case SCE_PASS_UV:
@@ -984,7 +988,7 @@ bool RE_bake_internal(
return false;
}
-int RE_pass_depth(const ScenePassType pass_type)
+int RE_pass_depth(const eScenePassType pass_type)
{
/* IMB_buffer_byte_from_float assumes 4 channels
* making it work for now - XXX */
diff --git a/source/blender/render/intern/source/convertblender.c b/source/blender/render/intern/source/convertblender.c
index 263ea3d4ef2..52cd5c3449e 100644
--- a/source/blender/render/intern/source/convertblender.c
+++ b/source/blender/render/intern/source/convertblender.c
@@ -56,7 +56,7 @@
#include "DNA_modifier_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
-#include "DNA_object_fluidsim.h"
+#include "DNA_object_fluidsim_types.h"
#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_texture_types.h"
@@ -271,7 +271,7 @@ static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr, int do_tangent)
}
else return;
- tangent_from_uv(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
+ tangent_from_uv_v3(uv1, uv2, uv3, v1->co, v2->co, v3->co, vlr->n, tang);
if (do_tangent) {
tav= RE_vertren_get_tangent(obr, v1, 1);
@@ -283,7 +283,7 @@ static void calc_tangent_vector(ObjectRen *obr, VlakRen *vlr, int do_tangent)
}
if (v4) {
- tangent_from_uv(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
+ tangent_from_uv_v3(uv1, uv3, uv4, v1->co, v3->co, v4->co, vlr->n, tang);
if (do_tangent) {
tav= RE_vertren_get_tangent(obr, v1, 1);
@@ -398,7 +398,7 @@ static void calc_vertexnormals(Render *UNUSED(re), ObjectRen *obr, bool do_verte
float *n4= (vlr->v4)? vlr->v4->n: NULL;
const float *c4= (vlr->v4)? vlr->v4->co: NULL;
- accumulate_vertex_normals(vlr->v1->n, vlr->v2->n, vlr->v3->n, n4,
+ accumulate_vertex_normals_v3(vlr->v1->n, vlr->v2->n, vlr->v3->n, n4,
vlr->n, vlr->v1->co, vlr->v2->co, vlr->v3->co, c4);
}
if (do_tangent) {
@@ -3439,10 +3439,9 @@ static void init_render_mesh(Render *re, ObjectRen *obr, int timeoffset)
if (need_nmap_tangent_concrete || need_tangent) {
int uv_start = CustomData_get_layer_index(&dm->faceData, CD_MTFACE);
int uv_index = CustomData_get_named_layer_index(&dm->faceData, CD_MTFACE, layer->name);
- BLI_assert(uv_start >= 0 && uv_index >= 0);
- if ((uv_start < 0 || uv_index < 0))
- continue;
- int n = uv_index - uv_start;
+
+ /* if there are no UVs, orco tangents are in first slot */
+ int n = (uv_start >= 0 && uv_index >= 0) ? uv_index - uv_start : 0;
const float *tangent = (const float *) layer->data;
float *ftang = RE_vlakren_get_nmap_tangent(obr, vlr, n, true);
@@ -3795,12 +3794,13 @@ static GroupObject *add_render_lamp(Render *re, Object *ob)
copy_v3_v3(vec, ob->obmat[2]);
normalize_v3(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);
+ 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;
@@ -4658,14 +4658,22 @@ static void add_render_object(Render *re, Object *ob, Object *par, DupliObject *
index= (dob)? dob->persistent_id[0]: 0;
+ /* It seems that we may generate psys->renderdata recursively in some nasty intricated cases of
+ * several levels of bupliobject (see T51524).
+ * For now, basic rule is, do not restore psys if it was already in 'render state'.
+ * Another, more robust solution could be to add some reference counting to that renderdata... */
+ bool psys_has_renderdata = false;
+
/* the emitter has to be processed first (render levels of modifiers) */
/* so here we only check if the emitter should be rendered */
if (ob->particlesystem.first) {
show_emitter= 0;
for (psys=ob->particlesystem.first; psys; psys=psys->next) {
show_emitter += psys->part->draw & PART_DRAW_EMITTER;
- if (!(re->r.scemode & R_VIEWPORT_PREVIEW))
+ if (!(re->r.scemode & R_VIEWPORT_PREVIEW)) {
+ psys_has_renderdata |= (psys->renderdata != NULL);
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 */
@@ -4712,8 +4720,9 @@ static void add_render_object(Render *re, Object *ob, Object *par, DupliObject *
if (dob)
psys->flag |= PSYS_USE_IMAT;
init_render_object_data(re, obr, timeoffset);
- if (!(re->r.scemode & R_VIEWPORT_PREVIEW))
+ if (!(re->r.scemode & R_VIEWPORT_PREVIEW) && !psys_has_renderdata) {
psys_render_restore(ob, psys);
+ }
psys->flag &= ~PSYS_USE_IMAT;
/* only add instance for objects that have not been used for dupli */
diff --git a/source/blender/render/intern/source/envmap.c b/source/blender/render/intern/source/envmap.c
index d97e18d6511..40b249192f9 100644
--- a/source/blender/render/intern/source/envmap.c
+++ b/source/blender/render/intern/source/envmap.c
@@ -61,6 +61,7 @@
#include "renderpipeline.h"
#include "texture.h"
#include "zbuf.h"
+#include "render_result.h"
/* ------------------------------------------------------------------------- */
@@ -69,7 +70,7 @@ static void envmap_split_ima(EnvMap *env, ImBuf *ibuf)
int dx, part;
/* after lock we test cube[1], if set the other thread has done it fine */
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (env->cube[1] == NULL) {
BKE_texture_envmap_free_data(env);
@@ -117,7 +118,7 @@ static void envmap_split_ima(EnvMap *env, ImBuf *ibuf)
}
}
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
/* ------------------------------------------------------------------------- */
@@ -142,8 +143,8 @@ static Render *envmap_render_copy(Render *re, EnvMap *env)
/* set up renderdata */
render_copy_renderdata(&envre->r, &re->r);
envre->r.mode &= ~(R_BORDER | R_PANORAMA | R_ORTHO | R_MBLUR);
- BLI_listbase_clear(&envre->r.layers);
- BLI_listbase_clear(&envre->r.views);
+ BLI_freelistN(&envre->r.layers);
+ BLI_freelistN(&envre->r.views);
envre->r.filtertype = 0;
envre->r.tilex = envre->r.xsch / 2;
envre->r.tiley = envre->r.ysch / 2;
@@ -493,13 +494,20 @@ static void render_envmap(Render *re, EnvMap *env)
env_rotate_scene(envre, tmat, 0);
if (re->test_break(re->tbh) == 0) {
- RenderLayer *rl = envre->result->layers.first;
int y;
float *alpha;
float *rect;
+ if (envre->result->do_exr_tile) {
+ BLI_rw_mutex_lock(&envre->resultmutex, THREAD_LOCK_WRITE);
+ render_result_exr_file_end(envre);
+ BLI_rw_mutex_unlock(&envre->resultmutex);
+ }
+
+ RenderLayer *rl = envre->result->layers.first;
+
/* envmap is rendered independently of multiview */
- rect = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, "");
+ rect = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, "");
ibuf = IMB_allocImBuf(envre->rectx, envre->recty, 24, IB_rect | IB_rectfloat);
memcpy(ibuf->rect_float, rect, ibuf->channels * ibuf->x * ibuf->y * sizeof(float));
diff --git a/source/blender/render/intern/source/external_engine.c b/source/blender/render/intern/source/external_engine.c
index fd9d95c63b6..fdf914102b0 100644
--- a/source/blender/render/intern/source/external_engine.c
+++ b/source/blender/render/intern/source/external_engine.c
@@ -1,11 +1,10 @@
/*
-
* ***** 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
@@ -62,13 +61,14 @@
#include "renderpipeline.h"
#include "render_types.h"
#include "render_result.h"
+#include "rendercore.h"
/* Render Engine Types */
static RenderEngineType internal_render_type = {
NULL, NULL,
"BLENDER_RENDER", N_("Blender Render"), RE_INTERNAL,
- NULL, NULL, NULL, NULL, NULL, NULL,
+ NULL, NULL, NULL, NULL, NULL, NULL, render_internal_update_passes,
{NULL, NULL, NULL}
};
@@ -77,7 +77,7 @@ static RenderEngineType internal_render_type = {
static RenderEngineType internal_game_type = {
NULL, NULL,
"BLENDER_GAME", N_("Blender Game"), RE_INTERNAL | RE_GAME,
- NULL, NULL, NULL, NULL, NULL, NULL,
+ NULL, NULL, NULL, NULL, NULL, NULL, NULL,
{NULL, NULL, NULL}
};
@@ -143,7 +143,7 @@ RenderEngine *RE_engine_create_ex(RenderEngineType *type, bool use_for_viewport)
if (use_for_viewport) {
engine->flag |= RE_ENGINE_USED_FOR_VIEWPORT;
- BLI_begin_threaded_malloc();
+ BLI_threaded_malloc_begin();
}
return engine;
@@ -158,7 +158,7 @@ void RE_engine_free(RenderEngine *engine)
#endif
if (engine->flag & RE_ENGINE_USED_FOR_VIEWPORT) {
- BLI_end_threaded_malloc();
+ BLI_threaded_malloc_end();
}
MEM_freeN(engine);
@@ -212,6 +212,8 @@ RenderResult *RE_engine_begin_result(RenderEngine *engine, int x, int y, int w,
/* can be NULL if we CLAMP the width or height to 0 */
if (result) {
+ render_result_clone_passes(re, result, viewname);
+
RenderPart *pa;
/* Copy EXR tile settings, so pipeline knows whether this is a result
@@ -245,7 +247,18 @@ void RE_engine_update_result(RenderEngine *engine, RenderResult *result)
}
}
-void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel, int merge_results)
+void RE_engine_add_pass(RenderEngine *engine, const char *name, int channels, const char *chan_id, const char *layername)
+{
+ Render *re = engine->re;
+
+ if (!re || !re->result) {
+ return;
+ }
+
+ render_result_add_pass(re->result, name, channels, chan_id, layername, NULL);
+}
+
+void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel, int highlight, int merge_results)
{
Render *re = engine->re;
@@ -254,12 +267,12 @@ void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel
}
/* merge. on break, don't merge in result for preview renders, looks nicer */
- if (!cancel) {
+ if (!highlight) {
/* for exr tile render, detect tiles that are done */
RenderPart *pa = get_part_from_result(re, result);
if (pa) {
- pa->status = PART_STATUS_READY;
+ pa->status = (!cancel && merge_results)? PART_STATUS_MERGED: PART_STATUS_RENDERED;
}
else if (re->result->do_exr_tile) {
/* if written result does not match any tile and we are using save
@@ -270,7 +283,7 @@ void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel
if (!cancel || merge_results) {
if (re->result->do_exr_tile) {
- if (!cancel) {
+ if (!cancel && merge_results) {
render_result_exr_file_merge(re->result, result, re->viewname);
}
}
@@ -289,6 +302,11 @@ void RE_engine_end_result(RenderEngine *engine, RenderResult *result, int cancel
render_result_free(result);
}
+RenderResult *RE_engine_get_result(RenderEngine *engine)
+{
+ return engine->re->result;
+}
+
/* Cancel */
int RE_engine_test_break(RenderEngine *engine)
@@ -489,7 +507,7 @@ bool RE_bake_engine(
Render *re, Object *object,
const int object_id, const BakePixel pixel_array[],
const size_t num_pixels, const int depth,
- const ScenePassType pass_type, const int pass_filter,
+ const eScenePassType pass_type, const int pass_filter,
float result[])
{
RenderEngineType *type = RE_engines_find(re->r.engine);
@@ -760,3 +778,22 @@ int RE_engine_render(Render *re, int do_all)
return 1;
}
+void RE_engine_register_pass(struct RenderEngine *engine, struct Scene *scene, struct SceneRenderLayer *srl,
+ const char *name, int UNUSED(channels), const char *UNUSED(chanid), int type)
+{
+ /* The channel information is currently not used, but is part of the API in case it's needed in the future. */
+
+ if (!(scene && srl && engine)) {
+ return;
+ }
+
+ /* Register the pass in all scenes that have a render layer node for this layer.
+ * Since multiple scenes can be used in the compositor, the code must loop over all scenes
+ * and check whether their nodetree has a node that needs to be updated. */
+ Scene *sce;
+ for (sce = G.main->scene.first; sce; sce = sce->id.next) {
+ if (sce->nodetree) {
+ ntreeCompositRegisterPass(sce->nodetree, scene, srl, name, type);
+ }
+ }
+}
diff --git a/source/blender/render/intern/source/imagetexture.c b/source/blender/render/intern/source/imagetexture.c
index 04010522c12..6e5d10fcc84 100644
--- a/source/blender/render/intern/source/imagetexture.c
+++ b/source/blender/render/intern/source/imagetexture.c
@@ -890,18 +890,18 @@ static void image_mipmap_test(Tex *tex, ImBuf *ibuf)
if ((ibuf->flags & IB_fields) == 0) {
if (ibuf->mipmap[0] && (ibuf->userflags & IB_MIPMAP_INVALID)) {
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (ibuf->userflags & IB_MIPMAP_INVALID) {
IMB_remakemipmap(ibuf, tex->imaflag & TEX_GAUSS_MIP);
ibuf->userflags &= ~IB_MIPMAP_INVALID;
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
if (ibuf->mipmap[0] == NULL) {
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (ibuf->mipmap[0] == NULL)
IMB_makemipmap(ibuf, tex->imaflag & TEX_GAUSS_MIP);
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
/* if no mipmap could be made, fall back on non-mipmap render */
if (ibuf->mipmap[0] == NULL) {
@@ -1172,7 +1172,7 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
a = max_ff(a, 1.0f);
b = max_ff(b, 1.0f);
fProbes = 2.f*(a / b) - 1.f;
- AFD.iProbes = iroundf(fProbes);
+ AFD.iProbes = round_fl_to_int(fProbes);
AFD.iProbes = MIN2(AFD.iProbes, tex->afmax);
if (AFD.iProbes < fProbes)
b = 2.f*a / (float)(AFD.iProbes + 1);
@@ -1277,7 +1277,7 @@ static int imagewraposa_aniso(Tex *tex, Image *ima, ImBuf *ibuf, const float tex
b = max_ff(b, 1.0f);
fProbes = 2.f*(a / b) - 1.f;
/* no limit to number of Probes here */
- AFD.iProbes = iroundf(fProbes);
+ AFD.iProbes = round_fl_to_int(fProbes);
if (AFD.iProbes < fProbes) b = 2.f*a / (float)(AFD.iProbes + 1);
AFD.majrad = a/ff;
AFD.minrad = b/ff;
diff --git a/source/blender/render/intern/source/initrender.c b/source/blender/render/intern/source/initrender.c
index 970a3937657..ce3331e9a92 100644
--- a/source/blender/render/intern/source/initrender.c
+++ b/source/blender/render/intern/source/initrender.c
@@ -38,7 +38,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_utildefines.h"
#include "DNA_camera_types.h"
@@ -48,10 +48,6 @@
#include "BKE_camera.h"
-#ifdef WITH_QUICKTIME
-#include "quicktime_export.h"
-#endif
-
/* this module */
#include "renderpipeline.h"
#include "render_types.h"
diff --git a/source/blender/render/intern/source/multires_bake.c b/source/blender/render/intern/source/multires_bake.c
index fba5836ac32..9e0685d55f1 100644
--- a/source/blender/render/intern/source/multires_bake.c
+++ b/source/blender/render/intern/source/multires_bake.c
@@ -466,7 +466,7 @@ static void do_multires_bake(MultiresBakeRender *bkr, Image *ima, bool require_t
bake_data = initBakeData(bkr, ima);
if (tot_thread > 1)
- BLI_init_threads(&threads, do_multires_bake_thread, tot_thread);
+ BLI_threadpool_init(&threads, do_multires_bake_thread, tot_thread);
handles = MEM_callocN(tot_thread * sizeof(MultiresBakeThread), "do_multires_bake handles");
@@ -509,12 +509,12 @@ static void do_multires_bake(MultiresBakeRender *bkr, Image *ima, bool require_t
init_bake_rast(&handle->bake_rast, ibuf, &handle->data, flush_pixel, bkr->do_update);
if (tot_thread > 1)
- BLI_insert_thread(&threads, handle);
+ BLI_threadpool_insert(&threads, handle);
}
/* run threads */
if (tot_thread > 1)
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
else
do_multires_bake_thread(&handles[0]);
diff --git a/source/blender/render/intern/source/occlusion.c b/source/blender/render/intern/source/occlusion.c
index cd93898d846..42200a8278c 100644
--- a/source/blender/render/intern/source/occlusion.c
+++ b/source/blender/render/intern/source/occlusion.c
@@ -553,7 +553,7 @@ static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, i
occ_build_8_split(tree, begin, end, offset, count);
if (depth == 1 && tree->dothreadedbuild)
- BLI_init_threads(&threads, exec_occ_build, tree->totbuildthread);
+ BLI_threadpool_init(&threads, exec_occ_build, tree->totbuildthread);
for (b = 0; b < TOTCHILD; b++) {
if (count[b] == 0) {
@@ -566,7 +566,7 @@ static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, i
}
else {
if (tree->dothreadedbuild)
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
child = BLI_memarena_alloc(tree->arena, sizeof(OccNode));
node->child[b].node = child;
@@ -576,7 +576,7 @@ static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, i
tree->maxdepth = depth + 1;
if (tree->dothreadedbuild)
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
if (depth == 1 && tree->dothreadedbuild) {
othreads[totthread].tree = tree;
@@ -584,7 +584,7 @@ static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, i
othreads[totthread].begin = offset[b];
othreads[totthread].end = offset[b] + count[b];
othreads[totthread].depth = depth + 1;
- BLI_insert_thread(&threads, &othreads[totthread]);
+ BLI_threadpool_insert(&threads, &othreads[totthread]);
totthread++;
}
else
@@ -593,7 +593,7 @@ static void occ_build_recursive(OcclusionTree *tree, OccNode *node, int begin, i
}
if (depth == 1 && tree->dothreadedbuild)
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
}
/* combine area, position and sh */
@@ -1313,12 +1313,12 @@ void make_occ_tree(Render *re)
exec_strandsurface_sample(&othreads[0]);
}
else {
- BLI_init_threads(&threads, exec_strandsurface_sample, totthread);
+ BLI_threadpool_init(&threads, exec_strandsurface_sample, totthread);
for (a = 0; a < totthread; a++)
- BLI_insert_thread(&threads, &othreads[a]);
+ BLI_threadpool_insert(&threads, &othreads[a]);
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
}
for (a = 0; a < mesh->totface; a++) {
diff --git a/source/blender/render/intern/source/pipeline.c b/source/blender/render/intern/source/pipeline.c
index 52eca5f7005..67c87d5d9b8 100644
--- a/source/blender/render/intern/source/pipeline.c
+++ b/source/blender/render/intern/source/pipeline.c
@@ -37,9 +37,11 @@
#include <errno.h>
#include "DNA_anim_types.h"
+#include "DNA_group_types.h"
#include "DNA_image_types.h"
#include "DNA_node_types.h"
#include "DNA_object_types.h"
+#include "DNA_particle_types.h"
#include "DNA_scene_types.h"
#include "DNA_sequence_types.h"
#include "DNA_userdef_types.h"
@@ -82,6 +84,7 @@
#include "IMB_colormanagement.h"
#include "IMB_imbuf.h"
#include "IMB_imbuf_types.h"
+#include "IMB_metadata.h"
#include "RE_engine.h"
#include "RE_pipeline.h"
@@ -239,9 +242,9 @@ void RE_FreeRenderResult(RenderResult *res)
render_result_free(res);
}
-float *RE_RenderLayerGetPass(volatile RenderLayer *rl, int passtype, const char *viewname)
+float *RE_RenderLayerGetPass(volatile RenderLayer *rl, const char *name, const char *viewname)
{
- RenderPass *rpass = RE_pass_find_by_type(rl, passtype, viewname);
+ RenderPass *rpass = RE_pass_find_by_name(rl, name, viewname);
return rpass ? rpass->rect : NULL;
}
@@ -255,6 +258,11 @@ RenderLayer *RE_GetRenderLayer(RenderResult *rr, const char *name)
}
}
+bool RE_HasSingleLayer(Render *re)
+{
+ return (re->r.scemode & R_SINGLE_LAYER);
+}
+
RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, bool predivide, int rectx, int recty)
{
return render_result_new_from_exr(exrhandle, colorspace, predivide, rectx, recty);
@@ -262,12 +270,19 @@ RenderResult *RE_MultilayerConvert(void *exrhandle, const char *colorspace, bool
RenderLayer *render_get_active_layer(Render *re, RenderResult *rr)
{
- RenderLayer *rl = BLI_findlink(&rr->layers, re->r.actlay);
-
- if (rl)
- return rl;
- else
- return rr->layers.first;
+ SceneRenderLayer *srl = BLI_findlink(&re->r.layers, re->r.actlay);
+
+ if (srl) {
+ RenderLayer *rl = BLI_findstring(&rr->layers,
+ srl->name,
+ offsetof(RenderLayer, name));
+
+ if (rl) {
+ return rl;
+ }
+ }
+
+ return rr->layers.first;
}
static int render_scene_needs_vector(Render *re)
@@ -307,7 +322,6 @@ Render *RE_GetRender(const char *name)
return re;
}
-
/* if you want to know exactly what has been done */
RenderResult *RE_AcquireResultRead(Render *re)
{
@@ -375,6 +389,7 @@ void RE_AcquireResultImageViews(Render *re, RenderResult *rr)
render_result_views_shallowcopy(rr, re->result);
rv = rr->views.first;
+ rr->have_combined = (rv->rectf != NULL);
/* active layer */
rl = render_get_active_layer(re, re->result);
@@ -382,18 +397,17 @@ void RE_AcquireResultImageViews(Render *re, RenderResult *rr)
if (rl) {
if (rv->rectf == NULL) {
for (rview = (RenderView *)rr->views.first; rview; rview = rview->next) {
- rview->rectf = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, rview->name);
+ rview->rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, rview->name);
}
}
if (rv->rectz == NULL) {
for (rview = (RenderView *)rr->views.first; rview; rview = rview->next) {
- rview->rectz = RE_RenderLayerGetPass(rl, SCE_PASS_Z, rview->name);
+ rview->rectz = RE_RenderLayerGetPass(rl, RE_PASSNAME_Z, rview->name);
}
}
}
- rr->have_combined = (rv->rectf != NULL);
rr->layers = re->result->layers;
rr->xof = re->disprect.xmin;
rr->yof = re->disprect.ymin;
@@ -432,6 +446,7 @@ void RE_AcquireResultImage(Render *re, RenderResult *rr, const int view_id)
/* actview view */
rv = RE_RenderViewGetById(re->result, view_id);
+ rr->have_combined = (rv->rectf != NULL);
rr->rectf = rv->rectf;
rr->rectz = rv->rectz;
@@ -442,13 +457,12 @@ void RE_AcquireResultImage(Render *re, RenderResult *rr, const int view_id)
if (rl) {
if (rv->rectf == NULL)
- rr->rectf = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, rv->name);
+ rr->rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, rv->name);
if (rv->rectz == NULL)
- rr->rectz = RE_RenderLayerGetPass(rl, SCE_PASS_Z, rv->name);
+ rr->rectz = RE_RenderLayerGetPass(rl, RE_PASSNAME_Z, rv->name);
}
- rr->have_combined = (rv->rectf != NULL);
rr->layers = re->result->layers;
rr->views = re->result->views;
@@ -514,6 +528,36 @@ Render *RE_NewRender(const char *name)
return re;
}
+/* MAX_ID_NAME + sizeof(Library->name) + space + null-terminator. */
+#define MAX_SCENE_RENDER_NAME (MAX_ID_NAME + 1024 + 2)
+
+static void scene_render_name_get(const Scene *scene,
+ const size_t max_size,
+ char *render_name)
+{
+ if (ID_IS_LINKED(scene)) {
+ BLI_snprintf(render_name, max_size, "%s %s",
+ scene->id.lib->id.name, scene->id.name);
+ }
+ else {
+ BLI_snprintf(render_name, max_size, "%s", scene->id.name);
+ }
+}
+
+Render *RE_GetSceneRender(const Scene *scene)
+{
+ char render_name[MAX_SCENE_RENDER_NAME];
+ scene_render_name_get(scene, sizeof(render_name), render_name);
+ return RE_GetRender(render_name);
+}
+
+Render *RE_NewSceneRender(const Scene *scene)
+{
+ char render_name[MAX_SCENE_RENDER_NAME];
+ scene_render_name_get(scene, sizeof(render_name), render_name);
+ return RE_NewRender(render_name);
+}
+
/* called for new renders and when finishing rendering so
* we always have valid callbacks on a render */
void RE_InitRenderCB(Render *re)
@@ -723,6 +767,8 @@ void RE_InitState(Render *re, Render *source, RenderData *rd,
re->r.size = source->r.size;
}
+ re_init_resolution(re, source, winx, winy, disprect);
+
/* disable border if it's a full render anyway */
if (re->r.border.xmin == 0.0f && re->r.border.xmax == 1.0f &&
re->r.border.ymin == 0.0f && re->r.border.ymax == 1.0f)
@@ -730,8 +776,6 @@ void RE_InitState(Render *re, Render *source, RenderData *rd,
re->r.mode &= ~R_BORDER;
}
- re_init_resolution(re, source, winx, winy, disprect);
-
if (re->rectx < 1 || re->recty < 1 || (BKE_imtype_is_movie(rd->im_format.imtype) &&
(re->rectx < 16 || re->recty < 16) ))
{
@@ -808,7 +852,7 @@ void RE_InitState(Render *re, Render *source, RenderData *rd,
re->result = MEM_callocN(sizeof(RenderResult), "new render result");
re->result->rectx = re->rectx;
re->result->recty = re->recty;
- render_result_view_new(re->result, "new temporary view");
+ render_result_view_new(re->result, "");
}
if (re->r.scemode & R_VIEWPORT_PREVIEW)
@@ -842,7 +886,7 @@ static void render_result_rescale(Render *re)
if (src_rectf == NULL) {
RenderLayer *rl = render_get_active_layer(re, re->result);
if (rl != NULL) {
- src_rectf = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, NULL);
+ src_rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, NULL);
}
}
@@ -861,7 +905,7 @@ static void render_result_rescale(Render *re)
RenderLayer *rl;
rl = render_get_active_layer(re, re->result);
if (rl != NULL) {
- dst_rectf = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, NULL);
+ dst_rectf = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, NULL);
}
}
@@ -1104,7 +1148,7 @@ static void *do_part_thread(void *pa_v)
BLI_rw_mutex_unlock(&R.resultmutex);
}
- pa->status = PART_STATUS_READY;
+ pa->status = PART_STATUS_MERGED;
return NULL;
}
@@ -1210,7 +1254,7 @@ static int sort_and_queue_parts(Render *re, int minx, ThreadQueue *workqueue)
/* find center of rendered parts, image center counts for 1 too */
for (pa = re->parts.first; pa; pa = pa->next) {
- if (pa->status == PART_STATUS_READY) {
+ if (pa->status >= PART_STATUS_RENDERED) {
centx += BLI_rcti_cent_x(&pa->disprect);
centy += BLI_rcti_cent_y(&pa->disprect);
tot++;
@@ -1376,7 +1420,7 @@ static void threaded_tile_processor(Render *re)
BLI_thread_queue_nowait(workqueue);
/* start all threads */
- BLI_init_threads(&threads, do_render_thread, re->r.threads);
+ BLI_threadpool_init(&threads, do_render_thread, re->r.threads);
for (a = 0; a < re->r.threads; a++) {
thread[a].workqueue = workqueue;
@@ -1392,7 +1436,7 @@ static void threaded_tile_processor(Render *re)
thread[a].duh = NULL;
}
- BLI_insert_thread(&threads, &thread[a]);
+ BLI_threadpool_insert(&threads, &thread[a]);
}
/* wait for results to come back */
@@ -1436,7 +1480,7 @@ static void threaded_tile_processor(Render *re)
}
}
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
if ((g_break=re->test_break(re->tbh)))
break;
@@ -1655,7 +1699,7 @@ static void merge_renderresult_blur(RenderResult *rr, RenderResult *brr, float b
/* passes are allocated in sync */
rpass1 = rl1->passes.first;
for (rpass = rl->passes.first; rpass && rpass1; rpass = rpass->next, rpass1 = rpass1->next) {
- if ((rpass->passtype & SCE_PASS_COMBINED) && key_alpha)
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED) && key_alpha)
addblur_rect_key(rr, rpass->rect, rpass1->rect, blurfac);
else
addblur_rect(rr, rpass->rect, rpass1->rect, blurfac, rpass->channels);
@@ -1855,6 +1899,8 @@ static void render_result_uncrop(Render *re)
rres = render_result_new(re, &re->disprect, 0, RR_USE_MEM, RR_ALL_LAYERS, RR_ALL_VIEWS);
+ render_result_clone_passes(re, rres, NULL);
+
render_result_merge(rres, re->result);
render_result_free(re->result);
re->result = rres;
@@ -1911,7 +1957,7 @@ 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);
+ Render *resc = RE_NewSceneRender(sce);
int winx = re->winx, winy = re->winy;
sce->r.cfra = cfra;
@@ -2057,6 +2103,28 @@ static void tag_dependend_objects_for_render(Scene *scene, int renderlay)
DAG_id_tag_update(&smd->target->id, OB_RECALC_DATA);
}
}
+ else if (md->type == eModifierType_ParticleSystem) {
+ ParticleSystemModifierData *psmd = (ParticleSystemModifierData *)md;
+ ParticleSystem *psys = psmd->psys;
+ ParticleSettings *part = psys->part;
+ switch (part->ren_as) {
+ case PART_DRAW_OB:
+ if (part->dup_ob != NULL) {
+ DAG_id_tag_update(&part->dup_ob->id, OB_RECALC_DATA);
+ }
+ break;
+ case PART_DRAW_GR:
+ if (part->dup_group != NULL) {
+ for (GroupObject *go = part->dup_group->gobject.first;
+ go != NULL;
+ go = go->next)
+ {
+ DAG_id_tag_update(&go->ob->id, OB_RECALC_DATA);
+ }
+ }
+ break;
+ }
+ }
}
}
}
@@ -2346,7 +2414,7 @@ static void do_merge_fullsample(Render *re, bNodeTree *ntree)
tag_scenes_for_render(re);
for (sce = re->main->scene.first; sce; sce = sce->id.next) {
if (sce->id.tag & LIB_TAG_DOIT) {
- re1 = RE_GetRender(sce->id.name);
+ re1 = RE_GetSceneRender(sce);
if (re1 && (re1->r.scemode & R_FULL_SAMPLE)) {
if (sample) {
@@ -3276,19 +3344,19 @@ void RE_RenderFreestyleExternal(Render *re)
bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scene, const bool stamp, char *name)
{
- bool is_mono;
bool ok = true;
RenderData *rd = &scene->r;
if (!rr)
return false;
- is_mono = BLI_listbase_count_ex(&rr->views, 2) < 2;
+ bool is_mono = BLI_listbase_count_at_most(&rr->views, 2) < 2;
+ bool is_exr_rr = ELEM(rd->im_format.imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) &&
+ RE_HasFloatPixels(rr);
- if (ELEM(rd->im_format.imtype, R_IMF_IMTYPE_OPENEXR, R_IMF_IMTYPE_MULTILAYER) &&
- rd->im_format.views_format == R_IMF_VIEWS_MULTIVIEW)
+ if (rd->im_format.views_format == R_IMF_VIEWS_MULTIVIEW && is_exr_rr)
{
- ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, true, NULL);
+ ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, NULL, -1);
render_print_save_message(reports, name, ok, errno);
}
@@ -3306,33 +3374,34 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen
BKE_scene_multiview_view_filepath_get(&scene->r, filepath, rv->name, name);
}
- if (rd->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
- ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, false, rv->name);
+ if (is_exr_rr) {
+ ok = RE_WriteRenderResult(reports, rr, name, &rd->im_format, rv->name, -1);
render_print_save_message(reports, name, ok, errno);
- }
- else {
- ImBuf *ibuf = render_result_rect_to_ibuf(rr, rd, view_id);
-
- IMB_colormanagement_imbuf_for_write(ibuf, true, false, &scene->view_settings,
- &scene->display_settings, &rd->im_format);
-
- ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf, name, &rd->im_format, stamp);
/* optional preview images for exr */
- if (ok && rd->im_format.imtype == R_IMF_IMTYPE_OPENEXR && (rd->im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
+ if (ok && (rd->im_format.flag & R_IMF_FLAG_PREVIEW_JPG)) {
ImageFormatData imf = rd->im_format;
imf.imtype = R_IMF_IMTYPE_JPEG90;
if (BLI_testextensie(name, ".exr"))
name[strlen(name) - 4] = 0;
BKE_image_path_ensure_ext_from_imformat(name, &imf);
- ibuf->planes = 24;
- IMB_colormanagement_imbuf_for_write(ibuf, true, false, &scene->view_settings,
- &scene->display_settings, &imf);
+ ImBuf *ibuf = render_result_rect_to_ibuf(rr, rd, view_id);
+ ibuf->planes = 24;
ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf, name, &imf, stamp);
+
+ IMB_freeImBuf(ibuf);
}
+ }
+ else {
+ ImBuf *ibuf = render_result_rect_to_ibuf(rr, rd, view_id);
+
+ IMB_colormanagement_imbuf_for_write(ibuf, true, false, &scene->view_settings,
+ &scene->display_settings, &rd->im_format);
+
+ ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf, name, &rd->im_format, stamp);
/* imbuf knows which rects are not part of ibuf */
IMB_freeImBuf(ibuf);
@@ -3343,7 +3412,7 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen
BLI_assert(scene->r.im_format.views_format == R_IMF_VIEWS_STEREO_3D);
if (rd->im_format.imtype == R_IMF_IMTYPE_MULTILAYER) {
- printf("Stereo 3D not support for MultiLayer image: %s\n", name);
+ printf("Stereo 3D not supported for MultiLayer image: %s\n", name);
}
else {
ImBuf *ibuf_arr[3] = {NULL};
@@ -3363,7 +3432,7 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen
ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf_arr[2], name, &rd->im_format, stamp);
/* optional preview images for exr */
- if (ok && rd->im_format.imtype == R_IMF_IMTYPE_OPENEXR &&
+ if (ok && is_exr_rr &&
(rd->im_format.flag & R_IMF_FLAG_PREVIEW_JPG))
{
ImageFormatData imf = rd->im_format;
@@ -3375,9 +3444,6 @@ bool RE_WriteRenderViewsImage(ReportList *reports, RenderResult *rr, Scene *scen
BKE_image_path_ensure_ext_from_imformat(name, &imf);
ibuf_arr[2]->planes = 24;
- IMB_colormanagement_imbuf_for_write(ibuf_arr[2], true, false, &scene->view_settings,
- &scene->display_settings, &imf);
-
ok = render_imbuf_write_stamp_test(reports, scene, rr, ibuf_arr[2], name, &rd->im_format, stamp);
}
@@ -3401,7 +3467,7 @@ bool RE_WriteRenderViewsMovie(
if (!rr)
return false;
- is_mono = BLI_listbase_count_ex(&rr->views, 2) < 2;
+ is_mono = BLI_listbase_count_at_most(&rr->views, 2) < 2;
if (is_mono || (scene->r.im_format.views_format == R_IMF_VIEWS_INDIVIDUAL)) {
int view_id;
@@ -3856,9 +3922,9 @@ bool RE_ReadRenderResult(Scene *scene, Scene *scenode)
scene = scenode;
/* get render: it can be called from UI with draw callbacks */
- re = RE_GetRender(scene->id.name);
+ re = RE_GetSceneRender(scene);
if (re == NULL)
- re = RE_NewRender(scene->id.name);
+ re = RE_NewSceneRender(scene);
RE_InitState(re, NULL, &scene->r, NULL, winx, winy, &disprect);
re->scene = scene;
re->scene_color_manage = BKE_scene_check_color_management_enabled(scene);
@@ -3887,7 +3953,7 @@ void RE_layer_load_from_file(RenderLayer *layer, ReportList *reports, const char
/* multiview: since the API takes no 'view', we use the first combined pass found */
for (rpass = layer->passes.first; rpass; rpass = rpass->next)
- if (rpass->passtype == SCE_PASS_COMBINED)
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED))
break;
if (rpass == NULL)
@@ -3999,10 +4065,10 @@ bool RE_WriteEnvmapResult(struct ReportList *reports, Scene *scene, EnvMap *env,
}
}
-/* used in the interface to decide whether to show layers */
+/* Used in the interface to decide whether to show layers or passes. */
bool RE_layers_have_name(struct RenderResult *rr)
{
- switch (BLI_listbase_count_ex(&rr->layers, 2)) {
+ switch (BLI_listbase_count_at_most(&rr->layers, 2)) {
case 0:
return false;
case 1:
@@ -4013,13 +4079,23 @@ bool RE_layers_have_name(struct RenderResult *rr)
return false;
}
-RenderPass *RE_pass_find_by_type(volatile RenderLayer *rl, int passtype, const char *viewname)
+bool RE_passes_have_name(struct RenderLayer *rl)
+{
+ for (RenderPass *rp = rl->passes.first; rp; rp = rp->next) {
+ if (!STREQ(rp->name, "Combined")) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+RenderPass *RE_pass_find_by_name(volatile RenderLayer *rl, const char *name, const char *viewname)
{
RenderPass *rp = NULL;
for (rp = rl->passes.last; rp; rp = rp->prev) {
- if (rp->passtype == passtype) {
-
+ if (STREQ(rp->name, name)) {
if (viewname == NULL || viewname[0] == '\0')
break;
else if (STREQ(rp->view, viewname))
@@ -4029,6 +4105,50 @@ RenderPass *RE_pass_find_by_type(volatile RenderLayer *rl, int passtype, const c
return rp;
}
+/* Only provided for API compatibility, don't use this in new code! */
+RenderPass *RE_pass_find_by_type(volatile RenderLayer *rl, int passtype, const char *viewname)
+{
+#define CHECK_PASS(NAME) \
+ if (passtype == SCE_PASS_ ## NAME) \
+ return RE_pass_find_by_name(rl, RE_PASSNAME_ ## NAME, viewname);
+
+ CHECK_PASS(COMBINED);
+ CHECK_PASS(Z);
+ CHECK_PASS(VECTOR);
+ CHECK_PASS(NORMAL);
+ CHECK_PASS(UV);
+ CHECK_PASS(RGBA);
+ CHECK_PASS(EMIT);
+ CHECK_PASS(DIFFUSE);
+ CHECK_PASS(SPEC);
+ CHECK_PASS(SHADOW);
+ CHECK_PASS(AO);
+ CHECK_PASS(ENVIRONMENT);
+ CHECK_PASS(INDIRECT);
+ CHECK_PASS(REFLECT);
+ CHECK_PASS(REFRACT);
+ CHECK_PASS(INDEXOB);
+ CHECK_PASS(INDEXMA);
+ CHECK_PASS(MIST);
+ CHECK_PASS(RAYHITS);
+ CHECK_PASS(DIFFUSE_DIRECT);
+ CHECK_PASS(DIFFUSE_INDIRECT);
+ CHECK_PASS(DIFFUSE_COLOR);
+ CHECK_PASS(GLOSSY_DIRECT);
+ CHECK_PASS(GLOSSY_INDIRECT);
+ CHECK_PASS(GLOSSY_COLOR);
+ CHECK_PASS(TRANSM_DIRECT);
+ CHECK_PASS(TRANSM_INDIRECT);
+ CHECK_PASS(TRANSM_COLOR);
+ CHECK_PASS(SUBSURFACE_DIRECT);
+ CHECK_PASS(SUBSURFACE_INDIRECT);
+ CHECK_PASS(SUBSURFACE_COLOR);
+
+#undef CHECK_PASS
+
+ return NULL;
+}
+
/* create a renderlayer and renderpass for grease pencil layer */
RenderPass *RE_create_gp_pass(RenderResult *rr, const char *layername, const char *viewname)
{
@@ -4046,7 +4166,7 @@ RenderPass *RE_create_gp_pass(RenderResult *rr, const char *layername, const cha
}
/* clear previous pass if exist or the new image will be over previous one*/
- RenderPass *rp = RE_pass_find_by_type(rl, SCE_PASS_COMBINED, viewname);
+ RenderPass *rp = RE_pass_find_by_name(rl, RE_PASSNAME_COMBINED, viewname);
if (rp) {
if (rp->rect) {
MEM_freeN(rp->rect);
@@ -4054,5 +4174,5 @@ RenderPass *RE_create_gp_pass(RenderResult *rr, const char *layername, const cha
BLI_freelinkN(&rl->passes, rp);
}
/* create a totally new pass */
- return gp_add_pass(rr, rl, 4, SCE_PASS_COMBINED, viewname);
+ return gp_add_pass(rr, rl, 4, RE_PASSNAME_COMBINED, viewname);
}
diff --git a/source/blender/render/intern/source/pixelshading.c b/source/blender/render/intern/source/pixelshading.c
index 97d6b060e0a..ddbdb35bf51 100644
--- a/source/blender/render/intern/source/pixelshading.c
+++ b/source/blender/render/intern/source/pixelshading.c
@@ -576,7 +576,7 @@ void shadeSunView(float col_r[3], const float view[3])
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);
+ lar->sunsky->sky_colorspace);
ramp_blend(lar->sunsky->skyblendtype, col_r, lar->sunsky->skyblendfac, sun_collector);
}
diff --git a/source/blender/render/intern/source/pointdensity.c b/source/blender/render/intern/source/pointdensity.c
index a03ea9cb896..b75d996ff27 100644
--- a/source/blender/render/intern/source/pointdensity.c
+++ b/source/blender/render/intern/source/pointdensity.c
@@ -48,6 +48,7 @@
#include "DNA_particle_types.h"
#include "DNA_texture_types.h"
+#include "BKE_colorband.h"
#include "BKE_deform.h"
#include "BKE_DerivedMesh.h"
#include "BKE_lattice.h"
@@ -55,7 +56,6 @@
#include "BKE_object.h"
#include "BKE_particle.h"
#include "BKE_scene.h"
-#include "BKE_texture.h"
#include "BKE_colortools.h"
#include "render_types.h"
@@ -781,7 +781,7 @@ static int pointdensity_color(PointDensity *pd, TexResult *texres, float age, co
switch (pd->color_source) {
case TEX_PD_COLOR_PARTAGE:
if (pd->coba) {
- if (do_colorband(pd->coba, age, rgba)) {
+ if (BKE_colorband_evaluate(pd->coba, age, rgba)) {
texres->talpha = true;
copy_v3_v3(&texres->tr, rgba);
texres->tin *= rgba[3];
@@ -794,7 +794,7 @@ static int pointdensity_color(PointDensity *pd, TexResult *texres, float age, co
float speed = len_v3(vec) * pd->speed_scale;
if (pd->coba) {
- if (do_colorband(pd->coba, speed, rgba)) {
+ if (BKE_colorband_evaluate(pd->coba, speed, rgba)) {
texres->talpha = true;
copy_v3_v3(&texres->tr, rgba);
texres->tin *= rgba[3];
@@ -826,7 +826,7 @@ static int pointdensity_color(PointDensity *pd, TexResult *texres, float age, co
break;
case TEX_PD_COLOR_VERTWEIGHT:
texres->talpha = true;
- if (pd->coba && do_colorband(pd->coba, col[0], rgba)) {
+ if (pd->coba && BKE_colorband_evaluate(pd->coba, col[0], rgba)) {
copy_v3_v3(&texres->tr, rgba);
texres->tin *= rgba[3];
}
@@ -983,11 +983,12 @@ void RE_point_density_minmax(
}
else {
float radius[3] = {pd->radius, pd->radius, pd->radius};
- float *loc, *size;
+ BoundBox *bb = BKE_object_boundbox_get(object);
- if (BKE_object_obdata_texspace_get(pd->object, NULL, &loc, &size, NULL)) {
- sub_v3_v3v3(r_min, loc, size);
- add_v3_v3v3(r_max, loc, size);
+ if (bb != NULL) {
+ BLI_assert((bb->flag & BOUNDBOX_DIRTY) == 0);
+ copy_v3_v3(r_min, bb->vec[0]);
+ copy_v3_v3(r_max, bb->vec[6]);
/* Adjust texture space to include density points on the boundaries. */
sub_v3_v3(r_min, radius);
add_v3_v3(r_max, radius);
@@ -1006,7 +1007,10 @@ typedef struct SampleCallbackData {
float *values;
} SampleCallbackData;
-static void point_density_sample_func(void *data_v, const int iter)
+static void point_density_sample_func(
+ void *__restrict data_v,
+ const int iter,
+ const ParallelRangeTLS *__restrict UNUSED(tls))
{
SampleCallbackData *data = (SampleCallbackData *)data_v;
@@ -1079,11 +1083,14 @@ void RE_point_density_sample(
data.min = min;
data.dim = dim;
data.values = values;
+ ParallelRangeSettings settings;
+ BLI_parallel_range_settings_defaults(&settings);
+ settings.use_threading = (resolution > 32);
BLI_task_parallel_range(0,
resolution,
&data,
point_density_sample_func,
- resolution > 32);
+ &settings);
free_pointdensity(pd);
}
diff --git a/source/blender/render/intern/source/render_result.c b/source/blender/render/intern/source/render_result.c
index f276c01e86a..25377fb4f7e 100644
--- a/source/blender/render/intern/source/render_result.c
+++ b/source/blender/render/intern/source/render_result.c
@@ -36,7 +36,6 @@
#include "MEM_guardedalloc.h"
-#include "BKE_appdir.h"
#include "BLI_utildefines.h"
#include "BLI_listbase.h"
#include "BLI_hash_md5.h"
@@ -45,6 +44,7 @@
#include "BLI_string.h"
#include "BLI_threads.h"
+#include "BKE_appdir.h"
#include "BKE_image.h"
#include "BKE_global.h"
#include "BKE_main.h"
@@ -80,6 +80,8 @@ static void render_result_views_free(RenderResult *res)
MEM_freeN(rv);
}
+
+ res->have_combined = false;
}
void render_result_free(RenderResult *res)
@@ -116,8 +118,8 @@ void render_result_free(RenderResult *res)
MEM_freeN(res->text);
if (res->error)
MEM_freeN(res->error);
- if (res->stamp_data)
- MEM_freeN(res->stamp_data);
+
+ BKE_stamp_data_free(res->stamp_data);
MEM_freeN(res);
}
@@ -173,363 +175,72 @@ void render_result_views_shallowdelete(RenderResult *rr)
}
}
-static const char *name_from_passtype(int passtype, int channel)
-{
- if (passtype == SCE_PASS_COMBINED) {
- if (channel == -1) return "Combined";
- if (channel == 0) return "Combined.R";
- if (channel == 1) return "Combined.G";
- if (channel == 2) return "Combined.B";
- return "Combined.A";
- }
- if (passtype == SCE_PASS_Z) {
- if (channel == -1) return "Depth";
- return "Depth.Z";
- }
- if (passtype == SCE_PASS_VECTOR) {
- if (channel == -1) return "Vector";
- if (channel == 0) return "Vector.X";
- if (channel == 1) return "Vector.Y";
- if (channel == 2) return "Vector.Z";
- return "Vector.W";
- }
- if (passtype == SCE_PASS_NORMAL) {
- if (channel == -1) return "Normal";
- if (channel == 0) return "Normal.X";
- if (channel == 1) return "Normal.Y";
- return "Normal.Z";
- }
- if (passtype == SCE_PASS_UV) {
- if (channel == -1) return "UV";
- if (channel == 0) return "UV.U";
- if (channel == 1) return "UV.V";
- return "UV.A";
- }
- if (passtype == SCE_PASS_RGBA) {
- if (channel == -1) return "Color";
- if (channel == 0) return "Color.R";
- if (channel == 1) return "Color.G";
- if (channel == 2) return "Color.B";
- return "Color.A";
- }
- if (passtype == SCE_PASS_EMIT) {
- if (channel == -1) return "Emit";
- if (channel == 0) return "Emit.R";
- if (channel == 1) return "Emit.G";
- return "Emit.B";
- }
- if (passtype == SCE_PASS_DIFFUSE) {
- if (channel == -1) return "Diffuse";
- if (channel == 0) return "Diffuse.R";
- if (channel == 1) return "Diffuse.G";
- return "Diffuse.B";
- }
- if (passtype == SCE_PASS_SPEC) {
- if (channel == -1) return "Spec";
- if (channel == 0) return "Spec.R";
- if (channel == 1) return "Spec.G";
- return "Spec.B";
- }
- if (passtype == SCE_PASS_SHADOW) {
- if (channel == -1) return "Shadow";
- if (channel == 0) return "Shadow.R";
- if (channel == 1) return "Shadow.G";
- return "Shadow.B";
- }
- if (passtype == SCE_PASS_AO) {
- if (channel == -1) return "AO";
- if (channel == 0) return "AO.R";
- if (channel == 1) return "AO.G";
- return "AO.B";
- }
- if (passtype == SCE_PASS_ENVIRONMENT) {
- if (channel == -1) return "Env";
- if (channel == 0) return "Env.R";
- if (channel == 1) return "Env.G";
- return "Env.B";
- }
- if (passtype == SCE_PASS_INDIRECT) {
- if (channel == -1) return "Indirect";
- if (channel == 0) return "Indirect.R";
- if (channel == 1) return "Indirect.G";
- return "Indirect.B";
- }
- if (passtype == SCE_PASS_REFLECT) {
- if (channel == -1) return "Reflect";
- if (channel == 0) return "Reflect.R";
- if (channel == 1) return "Reflect.G";
- return "Reflect.B";
- }
- if (passtype == SCE_PASS_REFRACT) {
- if (channel == -1) return "Refract";
- if (channel == 0) return "Refract.R";
- if (channel == 1) return "Refract.G";
- return "Refract.B";
- }
- if (passtype == SCE_PASS_INDEXOB) {
- if (channel == -1) return "IndexOB";
- return "IndexOB.X";
- }
- if (passtype == SCE_PASS_INDEXMA) {
- if (channel == -1) return "IndexMA";
- return "IndexMA.X";
- }
- if (passtype == SCE_PASS_MIST) {
- if (channel == -1) return "Mist";
- return "Mist.Z";
- }
- if (passtype == SCE_PASS_RAYHITS) {
- if (channel == -1) return "Rayhits";
- if (channel == 0) return "Rayhits.R";
- if (channel == 1) return "Rayhits.G";
- return "Rayhits.B";
- }
- if (passtype == SCE_PASS_DIFFUSE_DIRECT) {
- if (channel == -1) return "DiffDir";
- if (channel == 0) return "DiffDir.R";
- if (channel == 1) return "DiffDir.G";
- return "DiffDir.B";
- }
- if (passtype == SCE_PASS_DIFFUSE_INDIRECT) {
- if (channel == -1) return "DiffInd";
- if (channel == 0) return "DiffInd.R";
- if (channel == 1) return "DiffInd.G";
- return "DiffInd.B";
- }
- if (passtype == SCE_PASS_DIFFUSE_COLOR) {
- if (channel == -1) return "DiffCol";
- if (channel == 0) return "DiffCol.R";
- if (channel == 1) return "DiffCol.G";
- return "DiffCol.B";
- }
- if (passtype == SCE_PASS_GLOSSY_DIRECT) {
- if (channel == -1) return "GlossDir";
- if (channel == 0) return "GlossDir.R";
- if (channel == 1) return "GlossDir.G";
- return "GlossDir.B";
- }
- if (passtype == SCE_PASS_GLOSSY_INDIRECT) {
- if (channel == -1) return "GlossInd";
- if (channel == 0) return "GlossInd.R";
- if (channel == 1) return "GlossInd.G";
- return "GlossInd.B";
- }
- if (passtype == SCE_PASS_GLOSSY_COLOR) {
- if (channel == -1) return "GlossCol";
- if (channel == 0) return "GlossCol.R";
- if (channel == 1) return "GlossCol.G";
- return "GlossCol.B";
- }
- if (passtype == SCE_PASS_TRANSM_DIRECT) {
- if (channel == -1) return "TransDir";
- if (channel == 0) return "TransDir.R";
- if (channel == 1) return "TransDir.G";
- return "TransDir.B";
- }
- if (passtype == SCE_PASS_TRANSM_INDIRECT) {
- if (channel == -1) return "TransInd";
- if (channel == 0) return "TransInd.R";
- if (channel == 1) return "TransInd.G";
- return "TransInd.B";
- }
- if (passtype == SCE_PASS_TRANSM_COLOR) {
- if (channel == -1) return "TransCol";
- if (channel == 0) return "TransCol.R";
- if (channel == 1) return "TransCol.G";
- return "TransCol.B";
- }
- if (passtype == SCE_PASS_SUBSURFACE_DIRECT) {
- if (channel == -1) return "SubsurfaceDir";
- if (channel == 0) return "SubsurfaceDir.R";
- if (channel == 1) return "SubsurfaceDir.G";
- return "SubsurfaceDir.B";
- }
- if (passtype == SCE_PASS_SUBSURFACE_INDIRECT) {
- if (channel == -1) return "SubsurfaceInd";
- if (channel == 0) return "SubsurfaceInd.R";
- if (channel == 1) return "SubsurfaceInd.G";
- return "SubsurfaceInd.B";
- }
- if (passtype == SCE_PASS_SUBSURFACE_COLOR) {
- if (channel == -1) return "SubsurfaceCol";
- if (channel == 0) return "SubsurfaceCol.R";
- if (channel == 1) return "SubsurfaceCol.G";
- return "SubsurfaceCol.B";
- }
- return "Unknown";
-}
-static int passtype_from_name(const char *str, int passflag)
+static char* set_pass_name(char *outname, const char *name, int channel, const char *chan_id)
{
- /* We do not really support several pass of the same types, so in case we are opening an EXR file with several pass
- * names detected as same pass type, only return that pass type the first time, and return 'uknown' for the others.
- * See T48466. */
-#define RETURN_PASS(_passtype) return (passflag & (_passtype)) ? 0 : (_passtype)
-
- if (STRPREFIX(str, "Combined"))
- RETURN_PASS(SCE_PASS_COMBINED);
-
- if (STRPREFIX(str, "Depth"))
- RETURN_PASS(SCE_PASS_Z);
-
- if (STRPREFIX(str, "Vector"))
- RETURN_PASS(SCE_PASS_VECTOR);
-
- if (STRPREFIX(str, "Normal"))
- RETURN_PASS(SCE_PASS_NORMAL);
-
- if (STRPREFIX(str, "UV"))
- RETURN_PASS(SCE_PASS_UV);
-
- if (STRPREFIX(str, "Color"))
- RETURN_PASS(SCE_PASS_RGBA);
-
- if (STRPREFIX(str, "Emit"))
- RETURN_PASS(SCE_PASS_EMIT);
-
- if (STRPREFIX(str, "Diffuse"))
- RETURN_PASS(SCE_PASS_DIFFUSE);
-
- if (STRPREFIX(str, "Spec"))
- RETURN_PASS(SCE_PASS_SPEC);
-
- if (STRPREFIX(str, "Shadow"))
- RETURN_PASS(SCE_PASS_SHADOW);
-
- if (STRPREFIX(str, "AO"))
- RETURN_PASS(SCE_PASS_AO);
-
- if (STRPREFIX(str, "Env"))
- RETURN_PASS(SCE_PASS_ENVIRONMENT);
-
- if (STRPREFIX(str, "Indirect"))
- RETURN_PASS(SCE_PASS_INDIRECT);
-
- if (STRPREFIX(str, "Reflect"))
- RETURN_PASS(SCE_PASS_REFLECT);
-
- if (STRPREFIX(str, "Refract"))
- RETURN_PASS(SCE_PASS_REFRACT);
-
- if (STRPREFIX(str, "IndexOB"))
- RETURN_PASS(SCE_PASS_INDEXOB);
-
- if (STRPREFIX(str, "IndexMA"))
- RETURN_PASS(SCE_PASS_INDEXMA);
-
- if (STRPREFIX(str, "Mist"))
- RETURN_PASS(SCE_PASS_MIST);
-
- if (STRPREFIX(str, "RayHits"))
- RETURN_PASS(SCE_PASS_RAYHITS);
-
- if (STRPREFIX(str, "DiffDir"))
- RETURN_PASS(SCE_PASS_DIFFUSE_DIRECT);
-
- if (STRPREFIX(str, "DiffInd"))
- RETURN_PASS(SCE_PASS_DIFFUSE_INDIRECT);
-
- if (STRPREFIX(str, "DiffCol"))
- RETURN_PASS(SCE_PASS_DIFFUSE_COLOR);
-
- if (STRPREFIX(str, "GlossDir"))
- RETURN_PASS(SCE_PASS_GLOSSY_DIRECT);
-
- if (STRPREFIX(str, "GlossInd"))
- RETURN_PASS(SCE_PASS_GLOSSY_INDIRECT);
-
- if (STRPREFIX(str, "GlossCol"))
- RETURN_PASS(SCE_PASS_GLOSSY_COLOR);
-
- if (STRPREFIX(str, "TransDir"))
- RETURN_PASS(SCE_PASS_TRANSM_DIRECT);
-
- if (STRPREFIX(str, "TransInd"))
- RETURN_PASS(SCE_PASS_TRANSM_INDIRECT);
-
- if (STRPREFIX(str, "TransCol"))
- RETURN_PASS(SCE_PASS_TRANSM_COLOR);
-
- if (STRPREFIX(str, "SubsurfaceDir"))
- RETURN_PASS(SCE_PASS_SUBSURFACE_DIRECT);
-
- if (STRPREFIX(str, "SubsurfaceInd"))
- RETURN_PASS(SCE_PASS_SUBSURFACE_INDIRECT);
-
- if (STRPREFIX(str, "SubsurfaceCol"))
- RETURN_PASS(SCE_PASS_SUBSURFACE_COLOR);
-
- return 0;
-
-#undef RETURN_PASS
+ BLI_strncpy(outname, name, EXR_PASS_MAXNAME);
+ if (channel >= 0) {
+ char token[3] = {'.', chan_id[channel], '\0'};
+ strncat(outname, token, EXR_PASS_MAXNAME);
+ }
+ return outname;
}
-
-static void set_pass_name(char *passname, int passtype, int channel, const char *view)
+static void set_pass_full_name(char *fullname, const char *name, int channel, const char *view, const char *chan_id)
{
- const char delims[] = {'.', '\0'};
- const char *sep;
- const char *token;
- size_t len;
-
- const char *passtype_name = name_from_passtype(passtype, channel);
-
- if (view == NULL || view[0] == '\0') {
- BLI_strncpy(passname, passtype_name, EXR_PASS_MAXNAME);
- return;
- }
-
- len = BLI_str_rpartition(passtype_name, delims, &sep, &token);
-
- if (sep) {
- BLI_snprintf(passname, EXR_PASS_MAXNAME, "%.*s.%s.%s", (int)len, passtype_name, view, token);
+ BLI_strncpy(fullname, name, EXR_PASS_MAXNAME);
+ if (view && view[0]) {
+ strncat(fullname, ".", EXR_PASS_MAXNAME);
+ strncat(fullname, view, EXR_PASS_MAXNAME);
}
- else {
- BLI_snprintf(passname, EXR_PASS_MAXNAME, "%s.%s", passtype_name, view);
+ if (channel >= 0) {
+ char token[3] = {'.', chan_id[channel], '\0'};
+ strncat(fullname, token, EXR_PASS_MAXNAME);
}
}
/********************************** New **************************************/
-static RenderPass *render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype, const char *viewname)
+static RenderPass *render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int channels, const char *name, const char *viewname, const char *chan_id)
{
const int view_id = BLI_findstringindex(&rr->views, viewname, offsetof(RenderView, name));
- const char *typestr = name_from_passtype(passtype, -1);
- RenderPass *rpass = MEM_callocN(sizeof(RenderPass), typestr);
+ RenderPass *rpass = MEM_callocN(sizeof(RenderPass), name);
size_t rectsize = ((size_t)rr->rectx) * rr->recty * channels;
- rpass->passtype = passtype;
rpass->channels = channels;
rpass->rectx = rl->rectx;
rpass->recty = rl->recty;
rpass->view_id = view_id;
- set_pass_name(rpass->name, rpass->passtype, -1, viewname);
- BLI_strncpy(rpass->internal_name, typestr, sizeof(rpass->internal_name));
+ BLI_strncpy(rpass->name, name, sizeof(rpass->name));
+ BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
BLI_strncpy(rpass->view, viewname, sizeof(rpass->view));
+ set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
if (rl->exrhandle) {
int a;
- for (a = 0; a < channels; a++)
- IMB_exr_add_channel(rl->exrhandle, rl->name, name_from_passtype(passtype, a), viewname, 0, 0, NULL, false);
+ for (a = 0; a < channels; a++) {
+ char passname[EXR_PASS_MAXNAME];
+ IMB_exr_add_channel(rl->exrhandle, rl->name, set_pass_name(passname, rpass->name, a, rpass->chan_id), viewname, 0, 0, NULL, false);
+ }
}
else {
float *rect;
int x;
- rpass->rect = MEM_mapallocN(sizeof(float) * rectsize, typestr);
+ rpass->rect = MEM_mapallocN(sizeof(float) * rectsize, name);
if (rpass->rect == NULL) {
MEM_freeN(rpass);
return NULL;
}
- if (passtype == SCE_PASS_VECTOR) {
+ if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
/* initialize to max speed */
rect = rpass->rect;
for (x = rectsize - 1; x >= 0; x--)
rect[x] = PASS_VECTOR_MAX;
}
- else if (passtype == SCE_PASS_Z) {
+ else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
rect = rpass->rect;
for (x = rectsize - 1; x >= 0; x--)
rect[x] = 10e10;
@@ -541,58 +252,10 @@ static RenderPass *render_layer_add_pass(RenderResult *rr, RenderLayer *rl, int
return rpass;
}
/* wrapper called from render_opengl */
-RenderPass *gp_add_pass(RenderResult *rr, RenderLayer *rl, int channels, int passtype, const char *viewname)
-{
- return render_layer_add_pass(rr, rl, channels, passtype, viewname);
-}
-
-#ifdef WITH_CYCLES_DEBUG
-const char *RE_debug_pass_name_get(int debug_type)
-{
- switch (debug_type) {
- case RENDER_PASS_DEBUG_BVH_TRAVERSED_NODES:
- return "BVH Traversed Nodes";
- case RENDER_PASS_DEBUG_BVH_TRAVERSED_INSTANCES:
- return "BVH Traversed Instances";
- case RENDER_PASS_DEBUG_BVH_INTERSECTIONS:
- return "BVH Primitive Intersections";
- case RENDER_PASS_DEBUG_RAY_BOUNCES:
- return "Ray Bounces";
- }
- return "Unknown";
-}
-
-int RE_debug_pass_num_channels_get(int UNUSED(debug_type))
-{
- /* Only single case currently, might be handy for further debug passes. */
- return 1;
-}
-
-static RenderPass *render_layer_add_debug_pass(RenderResult *rr,
- RenderLayer *rl,
- int pass_type,
- int debug_type,
- const char *view)
-{
- const char *name = RE_debug_pass_name_get(debug_type);
- int channels = RE_debug_pass_num_channels_get(debug_type);
- RenderPass *rpass = render_layer_add_pass(rr, rl, channels, pass_type, view);
- if (rpass == NULL) {
- return NULL;
- }
- rpass->debug_type = debug_type;
- BLI_strncpy(rpass->name,
- name,
- sizeof(rpass->name));
- BLI_strncpy(rpass->internal_name, rpass->name, sizeof(rpass->internal_name));
- return rpass;
-}
-
-int RE_debug_pass_type_get(Render *re)
+RenderPass *gp_add_pass(RenderResult *rr, RenderLayer *rl, int channels, const char *name, const char *viewname)
{
- return re->r.debug_pass_type;
+ return render_layer_add_pass(rr, rl, channels, name, viewname, "RGBA");
}
-#endif
/* called by main render as well for parts */
/* will read info from Render *re to define layers */
@@ -683,89 +346,77 @@ RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuf
if (rr->do_exr_tile)
IMB_exr_add_view(rl->exrhandle, view);
-#define RENDER_LAYER_ADD_PASS_SAFE(rr, rl, channels, passtype, viewname) \
+#define RENDER_LAYER_ADD_PASS_SAFE(rr, rl, channels, name, viewname, chan_id) \
do { \
- if (render_layer_add_pass(rr, rl, channels, passtype, viewname) == NULL) { \
+ if (render_layer_add_pass(rr, rl, channels, name, viewname, chan_id) == NULL) { \
render_result_free(rr); \
return NULL; \
} \
} while (false)
/* a renderlayer should always have a Combined pass*/
- render_layer_add_pass(rr, rl, 4, SCE_PASS_COMBINED, view);
+ render_layer_add_pass(rr, rl, 4, "Combined", view, "RGBA");
if (srl->passflag & SCE_PASS_Z)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, SCE_PASS_Z, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_Z, view, "Z");
if (srl->passflag & SCE_PASS_VECTOR)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, SCE_PASS_VECTOR, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_VECTOR, view, "XYZW");
if (srl->passflag & SCE_PASS_NORMAL)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_NORMAL, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_NORMAL, view, "XYZ");
if (srl->passflag & SCE_PASS_UV)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_UV, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_UV, view, "UVA");
if (srl->passflag & SCE_PASS_RGBA)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, SCE_PASS_RGBA, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_RGBA, view, "RGBA");
if (srl->passflag & SCE_PASS_EMIT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_EMIT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_EMIT, view, "RGB");
if (srl->passflag & SCE_PASS_DIFFUSE)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_DIFFUSE, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE, view, "RGB");
if (srl->passflag & SCE_PASS_SPEC)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_SPEC, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SPEC, view, "RGB");
if (srl->passflag & SCE_PASS_AO)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_AO, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_AO, view, "RGB");
if (srl->passflag & SCE_PASS_ENVIRONMENT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_ENVIRONMENT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_ENVIRONMENT, view, "RGB");
if (srl->passflag & SCE_PASS_INDIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_INDIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_INDIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_SHADOW)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_SHADOW, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SHADOW, view, "RGB");
if (srl->passflag & SCE_PASS_REFLECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_REFLECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_REFLECT, view, "RGB");
if (srl->passflag & SCE_PASS_REFRACT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_REFRACT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_REFRACT, view, "RGB");
if (srl->passflag & SCE_PASS_INDEXOB)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, SCE_PASS_INDEXOB, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXOB, view, "X");
if (srl->passflag & SCE_PASS_INDEXMA)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, SCE_PASS_INDEXMA, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_INDEXMA, view, "X");
if (srl->passflag & SCE_PASS_MIST)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, SCE_PASS_MIST, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 1, RE_PASSNAME_MIST, view, "Z");
if (rl->passflag & SCE_PASS_RAYHITS)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, SCE_PASS_RAYHITS, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 4, RE_PASSNAME_RAYHITS, view, "RGB");
if (srl->passflag & SCE_PASS_DIFFUSE_DIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_DIFFUSE_DIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_DIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_DIFFUSE_INDIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_DIFFUSE_INDIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_INDIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_DIFFUSE_COLOR)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_DIFFUSE_COLOR, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_DIFFUSE_COLOR, view, "RGB");
if (srl->passflag & SCE_PASS_GLOSSY_DIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_GLOSSY_DIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_DIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_GLOSSY_INDIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_GLOSSY_INDIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_INDIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_GLOSSY_COLOR)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_GLOSSY_COLOR, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_GLOSSY_COLOR, view, "RGB");
if (srl->passflag & SCE_PASS_TRANSM_DIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_TRANSM_DIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_DIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_TRANSM_INDIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_TRANSM_INDIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_INDIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_TRANSM_COLOR)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_TRANSM_COLOR, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_TRANSM_COLOR, view, "RGB");
if (srl->passflag & SCE_PASS_SUBSURFACE_DIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_SUBSURFACE_DIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_DIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_SUBSURFACE_INDIRECT)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_SUBSURFACE_INDIRECT, view);
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_INDIRECT, view, "RGB");
if (srl->passflag & SCE_PASS_SUBSURFACE_COLOR)
- RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, SCE_PASS_SUBSURFACE_COLOR, view);
-
-#ifdef WITH_CYCLES_DEBUG
- if (BKE_scene_use_new_shading_nodes(re->scene)) {
- if (render_layer_add_debug_pass(rr, rl, SCE_PASS_DEBUG,
- re->r.debug_pass_type, view) == NULL)
- {
- render_result_free(rr);
- return NULL;
- }
- }
-#endif
-
+ RENDER_LAYER_ADD_PASS_SAFE(rr, rl, 3, RE_PASSNAME_SUBSURFACE_COLOR, view, "RGB");
#undef RENDER_LAYER_ADD_PASS_SAFE
}
}
@@ -794,7 +445,7 @@ RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuf
IMB_exr_add_view(rl->exrhandle, view);
/* a renderlayer should always have a Combined pass */
- render_layer_add_pass(rr, rl, 4, SCE_PASS_COMBINED, view);
+ render_layer_add_pass(rr, rl, 4, RE_PASSNAME_COMBINED, view, "RGBA");
}
/* note, this has to be in sync with scene.c */
@@ -813,6 +464,60 @@ RenderResult *render_result_new(Render *re, rcti *partrct, int crop, int savebuf
return rr;
}
+void render_result_clone_passes(Render *re, RenderResult *rr, const char *viewname)
+{
+ RenderLayer *rl;
+ RenderPass *main_rp;
+
+ for (rl = rr->layers.first; rl; rl = rl->next) {
+ RenderLayer *main_rl = BLI_findstring(&re->result->layers, rl->name, offsetof(RenderLayer, name));
+ if (!main_rl) {
+ continue;
+ }
+
+ for (main_rp = main_rl->passes.first; main_rp; main_rp = main_rp->next) {
+ if (viewname && viewname[0] && !STREQ(main_rp->view, viewname)) {
+ continue;
+ }
+
+ /* Compare fullname to make sure that the view also is equal. */
+ RenderPass *rp = BLI_findstring(&rl->passes, main_rp->fullname, offsetof(RenderPass, fullname));
+ if (!rp) {
+ render_layer_add_pass(rr, rl, main_rp->channels, main_rp->name, main_rp->view, main_rp->chan_id);
+ }
+ }
+ }
+}
+
+void render_result_add_pass(RenderResult *rr, const char *name, int channels, const char *chan_id, const char *layername, const char *viewname)
+{
+ RenderLayer *rl;
+ RenderPass *rp;
+ RenderView *rv;
+
+ for (rl = rr->layers.first; rl; rl = rl->next) {
+ if (layername && layername[0] && !STREQ(rl->name, layername)) {
+ continue;
+ }
+
+ for (rv = rr->views.first; rv; rv = rv->next) {
+ const char *view = rv->name;
+
+ if (viewname && viewname[0] && !STREQ(view, viewname)) continue;
+
+ /* Ensure that the pass doesn't exist yet. */
+ for (rp = rl->passes.first; rp; rp = rp->next) {
+ if (!STREQ(rp->name, name)) continue;
+ if (!STREQ(rp->view, view)) continue;
+ }
+
+ if (!rp) {
+ render_layer_add_pass(rr, rl, channels, name, view, chan_id);
+ }
+ }
+ }
+}
+
/* allocate osa new results for samples */
RenderResult *render_result_new_full_sample(Render *re, ListBase *lb, rcti *partrct, int crop, int savebuffers, const char *viewname)
{
@@ -830,6 +535,50 @@ RenderResult *render_result_new_full_sample(Render *re, ListBase *lb, rcti *part
return lb->first;
}
+static int passtype_from_name(const char *name)
+{
+ const char delim[] = {'.', '\0'};
+ const char *sep, *suf;
+ int len = BLI_str_partition(name, delim, &sep, &suf);
+
+#define CHECK_PASS(NAME) if (STREQLEN(name, RE_PASSNAME_ ## NAME, len)) return SCE_PASS_ ## NAME
+
+ CHECK_PASS(COMBINED);
+ CHECK_PASS(Z);
+ CHECK_PASS(VECTOR);
+ CHECK_PASS(NORMAL);
+ CHECK_PASS(UV);
+ CHECK_PASS(RGBA);
+ CHECK_PASS(EMIT);
+ CHECK_PASS(DIFFUSE);
+ CHECK_PASS(SPEC);
+ CHECK_PASS(SHADOW);
+ CHECK_PASS(AO);
+ CHECK_PASS(ENVIRONMENT);
+ CHECK_PASS(INDIRECT);
+ CHECK_PASS(REFLECT);
+ CHECK_PASS(REFRACT);
+ CHECK_PASS(INDEXOB);
+ CHECK_PASS(INDEXMA);
+ CHECK_PASS(MIST);
+ CHECK_PASS(RAYHITS);
+ CHECK_PASS(DIFFUSE_DIRECT);
+ CHECK_PASS(DIFFUSE_INDIRECT);
+ CHECK_PASS(DIFFUSE_COLOR);
+ CHECK_PASS(GLOSSY_DIRECT);
+ CHECK_PASS(GLOSSY_INDIRECT);
+ CHECK_PASS(GLOSSY_COLOR);
+ CHECK_PASS(TRANSM_DIRECT);
+ CHECK_PASS(TRANSM_INDIRECT);
+ CHECK_PASS(TRANSM_COLOR);
+ CHECK_PASS(SUBSURFACE_DIRECT);
+ CHECK_PASS(SUBSURFACE_INDIRECT);
+ CHECK_PASS(SUBSURFACE_COLOR);
+
+#undef CHECK_PASS
+ return 0;
+}
+
/* callbacks for render_result_new_from_exr */
static void *ml_addlayer_cb(void *base, const char *str)
{
@@ -838,41 +587,35 @@ static void *ml_addlayer_cb(void *base, const char *str)
rl = MEM_callocN(sizeof(RenderLayer), "new render layer");
BLI_addtail(&rr->layers, rl);
-
+
BLI_strncpy(rl->name, str, EXR_LAY_MAXNAME);
return rl;
}
-static void ml_addpass_cb(void *base, void *lay, const char *str, float *rect, int totchan, const char *chan_id, const char *view)
+static void ml_addpass_cb(void *base, void *lay, const char *name, float *rect, int totchan, const char *chan_id, const char *view)
{
RenderResult *rr = base;
RenderLayer *rl = lay;
RenderPass *rpass = MEM_callocN(sizeof(RenderPass), "loaded pass");
- int a;
-
+
BLI_addtail(&rl->passes, rpass);
rpass->channels = totchan;
- rpass->passtype = passtype_from_name(str, rl->passflag);
- if (rpass->passtype == 0)
- printf("unknown pass %s\n", str);
- rl->passflag |= rpass->passtype;
-
+ rl->passflag |= passtype_from_name(name);
+
/* channel id chars */
- for (a = 0; a < totchan; a++)
- rpass->chan_id[a] = chan_id[a];
+ BLI_strncpy(rpass->chan_id, chan_id, sizeof(rpass->chan_id));
rpass->rect = rect;
+ BLI_strncpy(rpass->name, name, EXR_PASS_MAXNAME);
+ BLI_strncpy(rpass->view, view, sizeof(rpass->view));
+ set_pass_full_name(rpass->fullname, name, -1, view, rpass->chan_id);
+
if (view[0] != '\0') {
- BLI_snprintf(rpass->name, sizeof(rpass->name), "%s.%s", str, view);
rpass->view_id = BLI_findstringindex(&rr->views, view, offsetof(RenderView, name));
}
else {
- BLI_strncpy(rpass->name, str, sizeof(rpass->name));
rpass->view_id = 0;
}
-
- BLI_strncpy(rpass->view, view, sizeof(rpass->view));
- BLI_strncpy(rpass->internal_name, str, sizeof(rpass->internal_name));
}
static void *ml_addview_cb(void *base, const char *str)
@@ -912,12 +655,30 @@ static int order_render_passes(const void *a, const void *b)
// 1 if a is after b
RenderPass *rpa = (RenderPass *) a;
RenderPass *rpb = (RenderPass *) b;
+ unsigned int passtype_a = passtype_from_name(rpa->name);
+ unsigned int passtype_b = passtype_from_name(rpb->name);
- if (rpa->passtype > rpb->passtype)
+ /* Render passes with default type always go first. */
+ if (passtype_b && !passtype_a)
return 1;
- else if (rpa->passtype < rpb->passtype)
+ if (passtype_a && !passtype_b)
return 0;
+ if (passtype_a && passtype_b) {
+ if (passtype_a > passtype_b)
+ return 1;
+ else if (passtype_a < passtype_b)
+ return 0;
+ }
+ else {
+ int cmp = strncmp(rpa->name, rpb->name, EXR_PASS_MAXNAME);
+ if (cmp > 0)
+ return 1;
+ if (cmp < 0)
+ return 0;
+ }
+
+
/* they have the same type */
/* left first */
if (STREQ(rpa->view, STEREO_LEFT_NAME))
@@ -992,11 +753,17 @@ void render_result_views_new(RenderResult *rr, RenderData *rd)
}
/* we always need at least one view */
- if (BLI_listbase_count_ex(&rr->views, 1) == 0) {
+ if (BLI_listbase_count_at_most(&rr->views, 1) == 0) {
render_result_view_new(rr, "");
}
}
+bool render_result_has_views(RenderResult *rr)
+{
+ RenderView *rv = rr->views.first;
+ return (rv && (rv->next || rv->name[0]));
+}
+
/*********************************** Merge ***********************************/
static void do_merge_tile(RenderResult *rr, RenderResult *rrpart, float *target, float *tile, int pixsize)
@@ -1049,7 +816,7 @@ void render_result_merge(RenderResult *rr, RenderResult *rrpart)
rpass = rpass->next)
{
/* renderresult have all passes, renderpart only the active view's passes */
- if (strcmp(rpassp->name, rpass->name) != 0)
+ if (strcmp(rpassp->fullname, rpass->fullname) != 0)
continue;
do_merge_tile(rr, rrpart, rpass->rect, rpassp->rect, rpass->channels);
@@ -1061,119 +828,134 @@ void render_result_merge(RenderResult *rr, RenderResult *rrpart)
}
}
-/* for passes read from files, these have names stored */
-static char *make_pass_name(RenderPass *rpass, int chan)
+/* Called from the UI and render pipeline, to save multilayer and multiview
+ * images, optionally isolating a specific, view, layer or RGBA/Z pass. */
+bool RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *filename, ImageFormatData *imf, const char *view, int layer)
{
- static char name[EXR_PASS_MAXNAME];
- int len;
-
- BLI_strncpy(name, rpass->name, EXR_PASS_MAXNAME);
- len = strlen(name);
- name[len] = '.';
- name[len + 1] = rpass->chan_id[chan];
- name[len + 2] = 0;
-
- return name;
-}
-
-/* called from within UI and render pipeline, saves both rendered result as a file-read result
- * if multiview is true saves all views in a multiview exr
- * else if view is not NULL saves single view
- * else saves stereo3d
- */
-bool RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *filename, ImageFormatData *imf, const bool multiview, const char *view)
-{
- RenderLayer *rl;
- RenderPass *rpass;
- RenderView *rview;
void *exrhandle = IMB_exr_get_handle();
- bool success;
- int a, nr;
- const char *chan_view = NULL;
- int compress = (imf ? imf->exr_codec : 0);
- size_t width, height;
-
- const bool is_mono = view && !multiview;
- const bool use_half_float = (imf != NULL) ? (imf->depth == R_IMF_CHAN_DEPTH_16) : false;
-
- width = rr->rectx;
- height = rr->recty;
+ const bool half_float = (imf && imf->depth == R_IMF_CHAN_DEPTH_16);
+ const bool multi_layer = !(imf && imf->imtype == R_IMF_IMTYPE_OPENEXR);
+ const bool write_z = !multi_layer && (imf && (imf->flag & R_IMF_FLAG_ZBUF));
- if (imf && imf->imtype == R_IMF_IMTYPE_OPENEXR && multiview) {
- /* single layer OpenEXR */
- const char *RGBAZ[] = {"R", "G", "B", "A", "Z"};
- for (nr = 0, rview = rr->views.first; rview; rview = rview->next, nr++) {
- IMB_exr_add_view(exrhandle, rview->name);
+ /* Write first layer if not multilayer and no layer was specified. */
+ if (!multi_layer && layer == -1) {
+ layer = 0;
+ }
- if (rview->rectf) {
- for (a = 0; a < 4; a++) {
- IMB_exr_add_channel(exrhandle, "", RGBAZ[a],
- rview->name, 4, 4 * width, rview->rectf + a,
- use_half_float);
- }
- if (rview->rectz) {
- /* Z pass is always stored as float. */
- IMB_exr_add_channel(exrhandle, "", RGBAZ[4],
- rview->name, 1, width, rview->rectz,
- false);
- }
+ /* First add views since IMB_exr_add_channel checks number of views. */
+ if (render_result_has_views(rr)) {
+ for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
+ if (!view || STREQ(view, rview->name)) {
+ IMB_exr_add_view(exrhandle, rview->name);
}
}
}
- else {
- for (nr = 0, rview = rr->views.first; rview; rview = rview->next, nr++) {
- if (is_mono) {
- if (!STREQ(view, rview->name)) {
+
+ /* Compositing result. */
+ if (rr->have_combined) {
+ for (RenderView *rview = rr->views.first; rview; rview = rview->next) {
+ if (!rview->rectf) {
+ continue;
+ }
+
+ const char *viewname = rview->name;
+ if (view) {
+ if (!STREQ(view, viewname)) {
continue;
}
- chan_view = "";
+ else {
+ viewname = "";
+ }
}
- else {
- /* if rendered only one view, we treat as a a non-view render */
- chan_view = rview->name;
+
+ /* Skip compositing if only a single other layer is requested. */
+ if (!multi_layer && layer != 0) {
+ continue;
}
- IMB_exr_add_view(exrhandle, rview->name);
+ for (int a = 0; a < 4; a++) {
+ char passname[EXR_PASS_MAXNAME];
+ char layname[EXR_PASS_MAXNAME];
+ const char *chan_id = "RGBA";
- if (rview->rectf) {
- for (a = 0; a < 4; a++) {
- IMB_exr_add_channel(exrhandle, "Composite", name_from_passtype(SCE_PASS_COMBINED, a),
- chan_view, 4, 4 * width, rview->rectf + a,
- use_half_float);
+ if (multi_layer) {
+ set_pass_name(passname, "Combined", a, chan_id);
+ BLI_strncpy(layname, "Composite", sizeof(layname));
+ }
+ else {
+ passname[0] = chan_id[a];
+ passname[1] = '\0';
+ layname[0] = '\0';
}
+
+ IMB_exr_add_channel(exrhandle, layname, passname, viewname,
+ 4, 4 * rr->rectx, rview->rectf + a, half_float);
+ }
+
+ if (write_z && rview->rectz) {
+ const char *layname = (multi_layer)? "Composite": "";
+ IMB_exr_add_channel(exrhandle, layname, "Z", viewname,
+ 1, rr->rectx, rview->rectz, false);
}
}
+ }
- /* add layers/passes and assign channels */
- for (rl = rr->layers.first; rl; rl = rl->next) {
+ /* Other render layers. */
+ int nr = (rr->have_combined)? 1: 0;
+ for (RenderLayer *rl = rr->layers.first; rl; rl = rl->next, nr++) {
+ /* Skip other render layers if requested. */
+ if (!multi_layer && nr != layer) {
+ continue;
+ }
- /* passes are allocated in sync */
- for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
- const int xstride = rpass->channels;
-
- if (is_mono) {
- if (!STREQ(view, rpass->view)) {
- continue;
- }
- chan_view = "";
+ for (RenderPass *rp = rl->passes.first; rp; rp = rp->next) {
+ /* Skip non-RGBA and Z passes if not using multi layer. */
+ if (!multi_layer && !(STREQ(rp->name, RE_PASSNAME_COMBINED) ||
+ STREQ(rp->name, "") ||
+ (STREQ(rp->name, RE_PASSNAME_Z) && write_z))) {
+ continue;
+ }
+
+ /* Skip pass if it does not match the requested view(s). */
+ const char *viewname = rp->view;
+ if (view) {
+ if (!STREQ(view, viewname)) {
+ continue;
}
else {
- /* if rendered only one view, we treat as a a non-view render */
- chan_view = (nr > 1 ? rpass->view :"");
+ viewname = "";
}
+ }
- for (a = 0; a < xstride; a++) {
- if (rpass->passtype) {
- IMB_exr_add_channel(exrhandle, rl->name, name_from_passtype(rpass->passtype, a), chan_view,
- xstride, xstride * width, rpass->rect + a,
- rpass->passtype == SCE_PASS_Z ? false : use_half_float);
- }
- else {
- IMB_exr_add_channel(exrhandle, rl->name, make_pass_name(rpass, a), chan_view,
- xstride, xstride * width, rpass->rect + a,
- use_half_float);
- }
+ /* We only store RGBA passes as half float, for
+ * others precision loss can be problematic. */
+ bool pass_half_float = half_float &&
+ (STREQ(rp->chan_id, "RGB") ||
+ STREQ(rp->chan_id, "RGBA") ||
+ STREQ(rp->chan_id, "R") ||
+ STREQ(rp->chan_id, "G") ||
+ STREQ(rp->chan_id, "B") ||
+ STREQ(rp->chan_id, "A"));
+
+
+ for (int a = 0; a < rp->channels; a++) {
+ /* Save Combined as RGBA if single layer save. */
+ char passname[EXR_PASS_MAXNAME];
+ char layname[EXR_PASS_MAXNAME];
+
+ if (multi_layer) {
+ set_pass_name(passname, rp->name, a, rp->chan_id);
+ BLI_strncpy(layname, rl->name, sizeof(layname));
+ }
+ else {
+ passname[0] = rp->chan_id[a];
+ passname[1] = '\0';
+ layname[0] = '\0';
}
+
+ IMB_exr_add_channel(exrhandle, layname, passname, viewname,
+ rp->channels, rp->channels * rr->rectx, rp->rect + a,
+ pass_half_float);
}
}
}
@@ -1182,14 +964,14 @@ bool RE_WriteRenderResult(ReportList *reports, RenderResult *rr, const char *fil
BLI_make_existing_file(filename);
- if (IMB_exr_begin_write(exrhandle, filename, width, height, compress, rr->stamp_data)) {
+ int compress = (imf ? imf->exr_codec : 0);
+ bool success = IMB_exr_begin_write(exrhandle, filename, rr->rectx, rr->recty, compress, rr->stamp_data);
+ if (success) {
IMB_exr_write_channels(exrhandle);
- success = true;
}
else {
/* TODO, get the error from openexr's exception */
BKE_reportf(reports, RPT_ERROR, "Error writing render result, %s (see console)", strerror(errno));
- success = false;
}
IMB_exr_close(exrhandle);
@@ -1259,7 +1041,7 @@ static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart, cons
RenderPass *rpassp;
int offs, partx, party;
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
for (rlp = rrpart->layers.first; rlp; rlp = rlp->next) {
rl = RE_GetRenderLayer(rr, rlp->name);
@@ -1281,12 +1063,12 @@ static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart, cons
for (rpassp = rlp->passes.first; rpassp; rpassp = rpassp->next) {
const int xstride = rpassp->channels;
int a;
- char passname[EXR_PASS_MAXNAME];
+ char fullname[EXR_PASS_MAXNAME];
for (a = 0; a < xstride; a++) {
- set_pass_name(passname, rpassp->passtype, a, rpassp->view);
+ set_pass_full_name(fullname, rpassp->name, a, viewname, rpassp->chan_id);
- IMB_exr_set_channel(rl->exrhandle, rlp->name, passname,
+ IMB_exr_set_channel(rl->exrhandle, rlp->name, fullname,
xstride, xstride * rrpart->rectx, rpassp->rect + a + xstride * offs);
}
}
@@ -1305,10 +1087,10 @@ static void save_render_result_tile(RenderResult *rr, RenderResult *rrpart, cons
continue;
}
- IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, viewname);
+ IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, viewname, false);
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
void render_result_save_empty_result_tiles(Render *re)
@@ -1319,13 +1101,11 @@ void render_result_save_empty_result_tiles(Render *re)
for (rr = re->result; rr; rr = rr->next) {
for (rl = rr->layers.first; rl; rl = rl->next) {
- IMB_exr_clear_channels(rl->exrhandle);
-
for (pa = re->parts.first; pa; pa = pa->next) {
- if (pa->status != PART_STATUS_READY) {
+ if (pa->status != PART_STATUS_MERGED) {
int party = pa->disprect.ymin - re->disprect.ymin + pa->crop;
int partx = pa->disprect.xmin - re->disprect.xmin + pa->crop;
- IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, re->viewname);
+ IMB_exrtile_write_channels(rl->exrhandle, partx, party, 0, re->viewname, true);
}
}
}
@@ -1449,15 +1229,15 @@ int render_result_exr_file_read_path(RenderResult *rr, RenderLayer *rl_single, c
for (rpass = rl->passes.first; rpass; rpass = rpass->next) {
const int xstride = rpass->channels;
int a;
- char passname[EXR_PASS_MAXNAME];
+ char fullname[EXR_PASS_MAXNAME];
for (a = 0; a < xstride; a++) {
- set_pass_name(passname, rpass->passtype, a, rpass->view);
- IMB_exr_set_channel(exrhandle, rl->name, passname,
+ set_pass_full_name(fullname, rpass->name, a, rpass->view, rpass->chan_id);
+ IMB_exr_set_channel(exrhandle, rl->name, fullname,
xstride, xstride * rectx, rpass->rect + a);
}
- set_pass_name(rpass->name, rpass->passtype, -1, rpass->view);
+ set_pass_full_name(rpass->fullname, rpass->name, -1, rpass->view, rpass->chan_id);
}
}
@@ -1504,7 +1284,7 @@ void render_result_exr_file_cache_write(Render *re)
render_result_exr_file_cache_path(re->scene, root, str);
printf("Caching exr file, %dx%d, %s\n", rr->rectx, rr->recty, str);
- RE_WriteRenderResult(NULL, rr, str, NULL, true, NULL);
+ RE_WriteRenderResult(NULL, rr, str, NULL, NULL, -1);
}
/* For cache, makes exact copy of render result */
@@ -1578,6 +1358,8 @@ void RE_render_result_rect_from_ibuf(RenderResult *rr, RenderData *UNUSED(rd), I
RenderView *rv = RE_RenderViewGetById(rr, view_id);
if (ibuf->rect_float) {
+ rr->have_combined = true;
+
if (!rv->rectf)
rv->rectf = MEM_mallocN(4 * sizeof(float) * rr->rectx * rr->recty, "render_seq rectf");
@@ -1588,6 +1370,8 @@ void RE_render_result_rect_from_ibuf(RenderResult *rr, RenderData *UNUSED(rd), I
MEM_SAFE_FREE(rv->rect32);
}
else if (ibuf->rect) {
+ rr->have_combined = true;
+
if (!rv->rect32)
rv->rect32 = MEM_mallocN(sizeof(int) * rr->rectx * rr->recty, "render_seq rect");
@@ -1629,7 +1413,7 @@ void render_result_rect_get_pixels(RenderResult *rr, unsigned int *rect, int rec
/*************************** multiview functions *****************************/
-bool RE_HasFakeLayer(RenderResult *res)
+bool RE_HasCombinedLayer(RenderResult *res)
{
RenderView *rv;
@@ -1643,6 +1427,19 @@ bool RE_HasFakeLayer(RenderResult *res)
return (rv->rect32 || rv->rectf);
}
+bool RE_HasFloatPixels(RenderResult *res)
+{
+ RenderView *rview;
+
+ for (rview = res->views.first; rview; rview = rview->next) {
+ if (rview->rect32 && !rview->rectf) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
bool RE_RenderResult_is_stereo(RenderResult *res)
{
if (! BLI_findstring(&res->views, STEREO_LEFT_NAME, offsetof(RenderView, name)))
@@ -1709,9 +1506,6 @@ static RenderView *duplicate_render_view(RenderView *rview)
if (new_rview->rectf != NULL) {
new_rview->rectf = MEM_dupallocN(new_rview->rectf);
}
- if (new_rview->rectf != NULL) {
- new_rview->rectf = MEM_dupallocN(new_rview->rectf);
- }
if (new_rview->rectz != NULL) {
new_rview->rectz = MEM_dupallocN(new_rview->rectz);
}
diff --git a/source/blender/render/intern/source/render_texture.c b/source/blender/render/intern/source/render_texture.c
index b4a14f5337d..e66dd86a75a 100644
--- a/source/blender/render/intern/source/render_texture.c
+++ b/source/blender/render/intern/source/render_texture.c
@@ -54,6 +54,7 @@
#include "BKE_node.h"
#include "BKE_animsys.h"
+#include "BKE_colorband.h"
#include "BKE_DerivedMesh.h"
#include "BKE_global.h"
#include "BKE_main.h"
@@ -161,15 +162,15 @@ static void tex_normal_derivate(Tex *tex, TexResult *texres)
{
if (tex->flag & TEX_COLORBAND) {
float col[4];
- if (do_colorband(tex->coba, texres->tin, col)) {
+ if (BKE_colorband_evaluate(tex->coba, texres->tin, col)) {
float fac0, fac1, fac2, fac3;
fac0= (col[0]+col[1]+col[2]);
- do_colorband(tex->coba, texres->nor[0], col);
+ BKE_colorband_evaluate(tex->coba, texres->nor[0], col);
fac1= (col[0]+col[1]+col[2]);
- do_colorband(tex->coba, texres->nor[1], col);
+ BKE_colorband_evaluate(tex->coba, texres->nor[1], col);
fac2= (col[0]+col[1]+col[2]);
- do_colorband(tex->coba, texres->nor[2], col);
+ BKE_colorband_evaluate(tex->coba, texres->nor[2], col);
fac3= (col[0]+col[1]+col[2]);
texres->nor[0]= (fac0 - fac1) / 3.0f;
@@ -781,7 +782,8 @@ static int cubemap_glob(const float n[3], float x, float y, float z, float *adr1
/* ------------------------------------------------------------------------- */
/* mtex argument only for projection switches */
-static int cubemap(MTex *mtex, VlakRen *vlr, const float n[3], float x, float y, float z, float *adr1, float *adr2)
+static int cubemap(
+ const MTex *mtex, VlakRen *vlr, const float n[3], float x, float y, float z, float *adr1, float *adr2)
{
int proj[4]={0, ME_PROJXY, ME_PROJXZ, ME_PROJYZ}, ret= 0;
@@ -873,7 +875,8 @@ static int cubemap_ob(Object *ob, const float n[3], float x, float y, float z, f
/* ------------------------------------------------------------------------- */
-static void do_2d_mapping(MTex *mtex, float texvec[3], VlakRen *vlr, const float n[3], float dxt[3], float dyt[3])
+static void do_2d_mapping(
+ const MTex *mtex, float texvec[3], VlakRen *vlr, const float n[3], float dxt[3], float dyt[3])
{
Tex *tex;
Object *ob= NULL;
@@ -1112,14 +1115,15 @@ static int multitex(Tex *tex,
const short which_output,
struct ImagePool *pool,
const bool skip_load_image,
- const bool texnode_preview)
+ const bool texnode_preview,
+ const bool use_nodes)
{
float tmpvec[3];
int retval = 0; /* return value, int:0, col:1, nor:2, everything:3 */
texres->talpha = false; /* is set when image texture returns alpha (considered premul) */
- if (tex->use_nodes && tex->nodetree) {
+ if (use_nodes && tex->use_nodes && tex->nodetree) {
retval = ntreeTexExecTree(tex->nodetree, texres, texvec, dxt, dyt, osatex, thread,
tex, which_output, R.r.cfra, texnode_preview, NULL, NULL);
}
@@ -1215,7 +1219,7 @@ static int multitex(Tex *tex,
if (tex->flag & TEX_COLORBAND) {
float col[4];
- if (do_colorband(tex->coba, texres->tin, col)) {
+ if (BKE_colorband_evaluate(tex->coba, texres->tin, col)) {
texres->talpha = true;
texres->tr= col[0];
texres->tg= col[1];
@@ -1239,7 +1243,8 @@ static int multitex_nodes_intern(Tex *tex,
ImagePool *pool,
const bool scene_color_manage,
const bool skip_load_image,
- const bool texnode_preview)
+ const bool texnode_preview,
+ const bool use_nodes)
{
if (tex==NULL) {
memset(texres, 0, sizeof(TexResult));
@@ -1264,7 +1269,8 @@ static int multitex_nodes_intern(Tex *tex,
which_output,
pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ use_nodes);
if (mtex->mapto & (MAP_COL+MAP_COLSPEC+MAP_COLMIR)) {
ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
@@ -1311,7 +1317,8 @@ static int multitex_nodes_intern(Tex *tex,
which_output,
pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ use_nodes);
{
ImBuf *ibuf = BKE_image_pool_acquire_ibuf(tex->ima, &tex->iuser, pool);
@@ -1341,7 +1348,8 @@ static int multitex_nodes_intern(Tex *tex,
which_output,
pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ use_nodes);
}
}
@@ -1354,7 +1362,8 @@ int multitex_nodes(Tex *tex, float texvec[3], float dxt[3], float dyt[3], int os
return multitex_nodes_intern(tex, texvec, dxt, dyt, osatex, texres,
thread, which_output, shi, mtex, pool, R.scene_color_manage,
(R.r.scemode & R_NO_IMAGE_LOAD) != 0,
- (R.r.scemode & R_TEXNODE_PREVIEW) != 0);
+ (R.r.scemode & R_TEXNODE_PREVIEW) != 0,
+ true);
}
/* this is called for surface shading */
@@ -1378,7 +1387,8 @@ static int multitex_mtex(ShadeInput *shi, MTex *mtex, float texvec[3], float dxt
mtex->which_output,
pool,
skip_load_image,
- (R.r.scemode & R_TEXNODE_PREVIEW) != 0);
+ (R.r.scemode & R_TEXNODE_PREVIEW) != 0,
+ true);
}
}
@@ -1408,7 +1418,8 @@ int multitex_ext(Tex *tex,
pool,
scene_color_manage,
skip_load_image,
- false);
+ false,
+ true);
}
/* extern-tex doesn't support nodes (ntreeBeginExec() can't be called when rendering is going on)\
@@ -1417,13 +1428,19 @@ int multitex_ext(Tex *tex,
*/
int multitex_ext_safe(Tex *tex, float texvec[3], TexResult *texres, struct ImagePool *pool, bool scene_color_manage, const bool skip_load_image)
{
- int use_nodes= tex->use_nodes, retval;
-
- tex->use_nodes = false;
- retval= multitex_nodes_intern(tex, texvec, NULL, NULL, 0, texres, 0, 0, NULL, NULL, pool, scene_color_manage, skip_load_image, false);
- tex->use_nodes= use_nodes;
-
- return retval;
+ return multitex_nodes_intern(tex,
+ texvec,
+ NULL, NULL,
+ 0,
+ texres,
+ 0,
+ 0,
+ NULL, NULL,
+ pool,
+ scene_color_manage,
+ skip_load_image,
+ false,
+ false);
}
@@ -1481,6 +1498,7 @@ void texture_rgb_blend(float in[3], const float tex[3], const float out[3], floa
case MTEX_SUB:
fact= -fact;
+ ATTR_FALLTHROUGH;
case MTEX_ADD:
fact*= facg;
in[0]= (fact*tex[0] + out[0]);
@@ -1595,6 +1613,7 @@ float texture_value_blend(float tex, float out, float fact, float facg, int blen
case MTEX_SUB:
fact= -fact;
+ ATTR_FALLTHROUGH;
case MTEX_ADD:
in= fact*tex + out;
break;
@@ -2873,7 +2892,8 @@ void do_volume_tex(ShadeInput *shi, const float *xyz, int mapto_flag, float col_
mtex->which_output,
re->pool,
skip_load_image,
- texnode_preview); /* NULL = dxt/dyt, 0 = shi->osatex - not supported */
+ texnode_preview,
+ true); /* NULL = dxt/dyt, 0 = shi->osatex - not supported */
/* texture output */
@@ -3051,7 +3071,8 @@ void do_halo_tex(HaloRen *har, float xn, float yn, float col_r[4])
mtex->which_output,
har->pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ true);
/* texture output */
if (rgb && (mtex->texflag & MTEX_RGBTOINT)) {
@@ -3274,7 +3295,8 @@ void do_sky_tex(
mtex->which_output,
R.pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ true);
/* texture output */
if (rgb && (mtex->texflag & MTEX_RGBTOINT)) {
@@ -3500,7 +3522,8 @@ void do_lamp_tex(LampRen *la, const float lavec[3], ShadeInput *shi, float col_r
mtex->which_output,
R.pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ true);
/* texture output */
if (rgb && (mtex->texflag & MTEX_RGBTOINT)) {
@@ -3574,7 +3597,7 @@ void do_lamp_tex(LampRen *la, const float lavec[3], ShadeInput *shi, float col_r
/* ------------------------------------------------------------------------- */
-int externtex(MTex *mtex,
+int externtex(const MTex *mtex,
const float vec[3],
float *tin, float *tr, float *tg, float *tb, float *ta,
const int thread,
@@ -3614,7 +3637,8 @@ int externtex(MTex *mtex,
mtex->which_output,
pool,
skip_load_image,
- texnode_preview);
+ texnode_preview,
+ true);
if (rgb) {
texr.tin = IMB_colormanagement_get_luminance(&texr.tr);
@@ -3651,7 +3675,7 @@ void render_realtime_texture(ShadeInput *shi, Image *ima)
if (R.r.scemode & R_NO_TEX) return;
if (firsttime) {
- BLI_lock_thread(LOCK_IMAGE);
+ BLI_thread_lock(LOCK_IMAGE);
if (firsttime) {
const int num_threads = BLI_system_thread_count();
for (a = 0; a < num_threads; a++) {
@@ -3662,7 +3686,7 @@ void render_realtime_texture(ShadeInput *shi, Image *ima)
firsttime= 0;
}
- BLI_unlock_thread(LOCK_IMAGE);
+ BLI_thread_unlock(LOCK_IMAGE);
}
tex= &imatex[shi->thread];
@@ -3730,7 +3754,7 @@ Material *RE_sample_material_init(Material *orig_mat, Scene *scene)
if (!orig_mat) return NULL;
/* copy material */
- mat = localize_material(orig_mat);
+ mat = BKE_material_localize(orig_mat);
/* update material anims */
BKE_animsys_evaluate_animdata(scene, &mat->id, mat->adt, BKE_scene_frame_get(scene), ADT_RECALC_ANIM);
diff --git a/source/blender/render/intern/source/rendercore.c b/source/blender/render/intern/source/rendercore.c
index 910ea16607e..77f399d08d1 100644
--- a/source/blender/render/intern/source/rendercore.c
+++ b/source/blender/render/intern/source/rendercore.c
@@ -180,11 +180,12 @@ static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, in
flarec= 0;
if (fullsample) {
- for (sample=0; sample<totsample; sample++)
+ for (sample=0; sample<totsample; sample++) {
if (ps->mask & (1 << sample)) {
- float *pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float *pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
addalphaAddfacFloat(pass + od*4, col, har->add);
}
+ }
}
else {
fac= ((float)amountm)/(float)R.osa;
@@ -215,11 +216,12 @@ static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, in
}
if (fullsample) {
- for (sample=0; sample<totsample; sample++)
+ for (sample=0; sample<totsample; sample++) {
if (!(mask & (1 << sample))) {
- float *pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float *pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
addalphaAddfacFloat(pass + od*4, col, har->add);
}
+ }
}
else {
col[0]= accol[0];
@@ -228,7 +230,7 @@ static void halo_pixelstruct(HaloRen *har, RenderLayer **rlpp, int totsample, in
col[3]= accol[3];
for (sample=0; sample<totsample; sample++) {
- float *pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float *pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
addalphaAddfacFloat(pass + od*4, col, har->add);
}
}
@@ -312,7 +314,7 @@ static void halo_tile(RenderPart *pa, RenderLayer *rl)
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++) {
- float * rect= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float * rect= RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
addalphaAddfacFloat(rect + od*4, col, har->add);
}
}
@@ -367,7 +369,7 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
if (fullsample) {
for (sample=0; sample<totsample; sample++) {
if (ps->mask & (1 << sample)) {
- pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
pass += od * 4;
pass[0]+= col[0];
pass[1]+= col[1];
@@ -379,7 +381,7 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
}
else {
fac= ((float)count)/(float)R.osa;
- pass = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ pass = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
pass += od * 4;
pass[0]+= fac*col[0];
pass[1]+= fac*col[1];
@@ -401,7 +403,7 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
for (sample=0; sample<totsample; sample++) {
if (!(mask & (1 << sample))) {
- pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
pass += od * 4;
pass[0]+= col[0];
pass[1]+= col[1];
@@ -413,7 +415,7 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
}
else {
fac= ((float)R.osa-totsamp)/(float)R.osa;
- pass = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ pass = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
pass += od * 4;
pass[0]+= fac*col[0];
pass[1]+= fac*col[1];
@@ -433,7 +435,7 @@ static void lamphalo_tile(RenderPart *pa, RenderLayer *rl)
renderspothalo(&shi, col, 1.0f);
for (sample=0; sample<totsample; sample++) {
- pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
pass += od * 4;
pass[0]+= col[0];
pass[1]+= col[1];
@@ -462,101 +464,96 @@ static void add_filt_passes(RenderLayer *rl, int curmask, int rectx, int offset,
float *fp, *col= NULL;
int pixsize= 3;
- switch (rpass->passtype) {
- case SCE_PASS_COMBINED:
- add_filt_fmask(curmask, shr->combined, rpass->rect + 4*offset, rectx);
- break;
- case SCE_PASS_Z:
- fp= rpass->rect + offset;
- *fp= shr->z;
- break;
- case SCE_PASS_RGBA:
- col= shr->col;
- pixsize= 4;
- break;
- case SCE_PASS_EMIT:
- col= shr->emit;
- break;
- case SCE_PASS_DIFFUSE:
- col= shr->diff;
- break;
- case SCE_PASS_SPEC:
- col= shr->spec;
- break;
- case SCE_PASS_SHADOW:
- col= shr->shad;
- break;
- case SCE_PASS_AO:
- col= shr->ao;
- break;
- case SCE_PASS_ENVIRONMENT:
- col= shr->env;
- break;
- case SCE_PASS_INDIRECT:
- col= shr->indirect;
- break;
- case SCE_PASS_REFLECT:
- col= shr->refl;
- break;
- case SCE_PASS_REFRACT:
- col= shr->refr;
- break;
- case SCE_PASS_NORMAL:
- col= shr->nor;
- break;
- case SCE_PASS_UV:
- /* box filter only, gauss will screwup UV too much */
- if (shi->totuv) {
- float mult= (float)count_mask(curmask)/(float)R.osa;
- fp= rpass->rect + 3*offset;
- fp[0]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[0]);
- fp[1]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[1]);
- fp[2]+= mult;
- }
- break;
- case SCE_PASS_INDEXOB:
- /* no filter */
- if (shi->vlr) {
- fp= rpass->rect + offset;
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED)) {
+ add_filt_fmask(curmask, shr->combined, rpass->rect + 4*offset, rectx);
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
+ fp = rpass->rect + offset;
+ *fp = shr->z;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_RGBA)) {
+ col = shr->col;
+ pixsize = 4;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_EMIT)) {
+ col = shr->emit;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_DIFFUSE)) {
+ col = shr->diff;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SPEC)) {
+ col = shr->spec;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SHADOW)) {
+ col = shr->shad;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_AO)) {
+ col = shr->ao;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_ENVIRONMENT)) {
+ col = shr->env;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDIRECT)) {
+ col = shr->indirect;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFLECT)) {
+ col = shr->refl;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFRACT)) {
+ col = shr->refr;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_NORMAL)) {
+ col = shr->nor;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_UV)) {
+ /* box filter only, gauss will screwup UV too much */
+ if (shi->totuv) {
+ float mult = (float)count_mask(curmask)/(float)R.osa;
+ fp = rpass->rect + 3*offset;
+ fp[0]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[0]);
+ fp[1]+= mult*(0.5f + 0.5f*shi->uv[shi->actuv].uv[1]);
+ fp[2]+= mult;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDEXOB)) {
+ /* no filter */
+ if (shi->vlr) {
+ fp = rpass->rect + offset;
+ if (*fp==0.0f)
+ *fp = (float)shi->obr->ob->index;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDEXMA)) {
+ /* no filter */
+ if (shi->vlr) {
+ fp = rpass->rect + offset;
if (*fp==0.0f)
- *fp= (float)shi->obr->ob->index;
- }
- break;
- case SCE_PASS_INDEXMA:
- /* no filter */
- if (shi->vlr) {
- fp= rpass->rect + offset;
- if (*fp==0.0f)
- *fp= (float)shi->mat->index;
- }
- break;
- case SCE_PASS_MIST:
- /* */
- col= &shr->mist;
- pixsize= 1;
- break;
-
- case SCE_PASS_VECTOR:
- {
- /* add minimum speed in pixel, no filter */
- fp= rpass->rect + 4*offset;
- if ( (ABS(shr->winspeed[0]) + ABS(shr->winspeed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
- fp[0]= shr->winspeed[0];
- fp[1]= shr->winspeed[1];
- }
- if ( (ABS(shr->winspeed[2]) + ABS(shr->winspeed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
- fp[2]= shr->winspeed[2];
- fp[3]= shr->winspeed[3];
- }
-
- break;
+ *fp = (float)shi->mat->index;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_MIST)) {
+ /* */
+ col = &shr->mist;
+ pixsize = 1;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
+ /* add minimum speed in pixel, no filter */
+ fp = rpass->rect + 4*offset;
+ if ( (ABS(shr->winspeed[0]) + ABS(shr->winspeed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
+ fp[0] = shr->winspeed[0];
+ fp[1] = shr->winspeed[1];
+ }
+ if ( (ABS(shr->winspeed[2]) + ABS(shr->winspeed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
+ fp[2] = shr->winspeed[2];
+ fp[3] = shr->winspeed[3];
}
- case SCE_PASS_RAYHITS:
- /* */
- col= shr->rayhits;
- pixsize= 4;
- break;
}
+ else if (STREQ(rpass->name, RE_PASSNAME_RAYHITS)) {
+ /* */
+ col = shr->rayhits;
+ pixsize= 4;
+ }
+
if (col) {
fp= rpass->rect + pixsize*offset;
add_filt_fmask_pixsize(curmask, col, fp, rectx, pixsize);
@@ -574,86 +571,85 @@ static void add_passes(RenderLayer *rl, int offset, ShadeInput *shi, ShadeResult
float *col= NULL, uvcol[3];
int a, pixsize= 3;
- switch (rpass->passtype) {
- case SCE_PASS_COMBINED:
- /* copy combined to use for preview */
- copy_v4_v4(rpass->rect + 4*offset, shr->combined);
- break;
- case SCE_PASS_Z:
- fp= rpass->rect + offset;
- *fp= shr->z;
- break;
- case SCE_PASS_RGBA:
- col= shr->col;
- pixsize= 4;
- break;
- case SCE_PASS_EMIT:
- col= shr->emit;
- break;
- case SCE_PASS_DIFFUSE:
- col= shr->diff;
- break;
- case SCE_PASS_SPEC:
- col= shr->spec;
- break;
- case SCE_PASS_SHADOW:
- col= shr->shad;
- break;
- case SCE_PASS_AO:
- col= shr->ao;
- break;
- case SCE_PASS_ENVIRONMENT:
- col= shr->env;
- break;
- case SCE_PASS_INDIRECT:
- col= shr->indirect;
- break;
- case SCE_PASS_REFLECT:
- col= shr->refl;
- break;
- case SCE_PASS_REFRACT:
- col= shr->refr;
- break;
- case SCE_PASS_NORMAL:
- col= shr->nor;
- break;
- case SCE_PASS_UV:
- if (shi->totuv) {
- uvcol[0]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[0];
- uvcol[1]= 0.5f + 0.5f*shi->uv[shi->actuv].uv[1];
- uvcol[2]= 1.0f;
- col= uvcol;
- }
- break;
- case SCE_PASS_VECTOR:
- col= shr->winspeed;
- pixsize= 4;
- break;
- case SCE_PASS_INDEXOB:
- if (shi->vlr) {
- fp= rpass->rect + offset;
- *fp= (float)shi->obr->ob->index;
- }
- break;
- case SCE_PASS_INDEXMA:
- if (shi->vlr) {
- fp= rpass->rect + offset;
- *fp= (float)shi->mat->index;
- }
- break;
- case SCE_PASS_MIST:
- fp= rpass->rect + offset;
- *fp= shr->mist;
- break;
- case SCE_PASS_RAYHITS:
- col= shr->rayhits;
- pixsize= 4;
- break;
+ if (STREQ(rpass->name, RE_PASSNAME_COMBINED)) {
+ /* copy combined to use for preview */
+ copy_v4_v4(rpass->rect + 4*offset, shr->combined);
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
+ fp = rpass->rect + offset;
+ *fp = shr->z;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_RGBA)) {
+ col = shr->col;
+ pixsize = 4;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_EMIT)) {
+ col = shr->emit;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_DIFFUSE)) {
+ col = shr->diff;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SPEC)) {
+ col = shr->spec;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SHADOW)) {
+ col = shr->shad;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_AO)) {
+ col = shr->ao;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_ENVIRONMENT)) {
+ col = shr->env;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDIRECT)) {
+ col = shr->indirect;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFLECT)) {
+ col = shr->refl;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFRACT)) {
+ col = shr->refr;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_NORMAL)) {
+ col = shr->nor;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_UV)) {
+ if (shi->totuv) {
+ uvcol[0] = 0.5f + 0.5f*shi->uv[shi->actuv].uv[0];
+ uvcol[1] = 0.5f + 0.5f*shi->uv[shi->actuv].uv[1];
+ uvcol[2] = 1.0f;
+ col = uvcol;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
+ col = shr->winspeed;
+ pixsize = 4;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDEXOB)) {
+ if (shi->vlr) {
+ fp = rpass->rect + offset;
+ *fp = (float)shi->obr->ob->index;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDEXMA)) {
+ if (shi->vlr) {
+ fp = rpass->rect + offset;
+ *fp = (float)shi->mat->index;
+ }
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_MIST)) {
+ fp = rpass->rect + offset;
+ *fp = shr->mist;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_RAYHITS)) {
+ col = shr->rayhits;
+ pixsize = 4;
}
+
if (col) {
- fp= rpass->rect + pixsize*offset;
+ fp = rpass->rect + pixsize*offset;
for (a=0; a<pixsize; a++)
- fp[a]= col[a];
+ fp[a] = col[a];
}
}
}
@@ -696,7 +692,7 @@ static void sky_tile(RenderPart *pa, RenderLayer *rl)
bool done = false;
for (sample= 0; sample<totsample; sample++) {
- float *pass = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float *pass = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
pass += od;
if (pass[3]<1.0f) {
@@ -737,7 +733,7 @@ static void atm_tile(RenderPart *pa, RenderLayer *rl)
/* 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)
+ if (STREQ(zpass->name, RE_PASSNAME_Z))
break;
if (zpass==NULL) return;
@@ -758,8 +754,8 @@ static void atm_tile(RenderPart *pa, RenderLayer *rl)
int sample;
for (sample=0; sample<totsample; sample++) {
- const float *zrect = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_Z, R.viewname) + od;
- float *rgbrect = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname) + 4*od;
+ const float *zrect = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_Z, R.viewname) + od;
+ float *rgbrect = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname) + 4*od;
float rgb[3] = {0};
bool done = false;
@@ -994,7 +990,7 @@ static void clamp_alpha_rgb_range(RenderPart *pa, RenderLayer *rl)
return;
for (sample= 0; sample<totsample; sample++) {
- float *rectf = RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_COMBINED, R.viewname);
+ float *rectf = RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_COMBINED, R.viewname);
for (y= pa->rectx*pa->recty; y>0; y--, rectf+=4) {
rectf[0] = MAX2(rectf[0], 0.0f);
@@ -1076,7 +1072,7 @@ static void reset_sky_speed(RenderPart *pa, RenderLayer *rl)
totsample= get_sample_layers(pa, rl, rlpp);
for (sample= 0; sample<totsample; sample++) {
- fp= RE_RenderLayerGetPass(rlpp[sample], SCE_PASS_VECTOR, R.viewname);
+ fp= RE_RenderLayerGetPass(rlpp[sample], RE_PASSNAME_VECTOR, R.viewname);
if (fp==NULL) break;
for (a= 4*pa->rectx*pa->recty - 1; a>=0; a--)
@@ -1187,7 +1183,7 @@ void zbufshadeDA_tile(RenderPart *pa)
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) {
- float *rect = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ float *rect = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
if ((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
@@ -1339,7 +1335,7 @@ 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) {
- float *rect= RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ float *rect= RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
if ((rl->layflag & SCE_LAY_ZMASK) && (rl->layflag & SCE_LAY_NEG_ZMASK))
pa->rectmask= MEM_mallocN(sizeof(int)*pa->rectx*pa->recty, "rectmask");
@@ -1676,7 +1672,7 @@ void zbufshade_sss_tile(RenderPart *pa)
return;
}
- fcol= RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ fcol= RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
co= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSCo");
color= MEM_mallocN(sizeof(float)*3*handle.totps, "SSSColor");
@@ -1969,7 +1965,7 @@ void add_halo_flare(Render *re)
if ((rl->layflag & SCE_LAY_HALO) == 0)
continue;
- rect = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, re->viewname);
+ rect = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, re->viewname);
if (rect==NULL)
continue;
@@ -1998,3 +1994,37 @@ void add_halo_flare(Render *re)
}
}
+void render_internal_update_passes(RenderEngine *engine, Scene *scene, SceneRenderLayer *srl)
+{
+ int type;
+
+ RE_engine_register_pass(engine, scene, srl, RE_PASSNAME_COMBINED, 4, "RGBA", SOCK_RGBA);
+
+#define CHECK_PASS(name, channels, chanid) \
+ if (srl->passflag & (SCE_PASS_ ## name)) { \
+ if (channels == 4) type = SOCK_RGBA; \
+ else if (channels == 3) type = SOCK_VECTOR; \
+ else type = SOCK_FLOAT; \
+ RE_engine_register_pass(engine, scene, srl, RE_PASSNAME_ ## name, channels, chanid, type); \
+ }
+
+ CHECK_PASS(Z, 1, "Z");
+ CHECK_PASS(VECTOR, 4, "XYZW");
+ CHECK_PASS(NORMAL, 3, "XYZ");
+ CHECK_PASS(UV, 3, "UVA");
+ CHECK_PASS(RGBA, 4, "RGBA");
+ CHECK_PASS(EMIT, 3, "RGB");
+ CHECK_PASS(DIFFUSE, 3, "RGB");
+ CHECK_PASS(SPEC, 3, "RGB");
+ CHECK_PASS(AO, 3, "RGB");
+ CHECK_PASS(ENVIRONMENT, 3, "RGB");
+ CHECK_PASS(INDIRECT, 3, "RGB");
+ CHECK_PASS(SHADOW, 3, "RGB");
+ CHECK_PASS(REFLECT, 3, "RGB");
+ CHECK_PASS(REFRACT, 3, "RGB");
+ CHECK_PASS(INDEXOB, 1, "X");
+ CHECK_PASS(INDEXMA, 1, "X");
+ CHECK_PASS(MIST, 1, "Z");
+
+#undef CHECK_PASS
+}
diff --git a/source/blender/render/intern/source/renderdatabase.c b/source/blender/render/intern/source/renderdatabase.c
index 76e6ca8d467..2fbfcc64c8f 100644
--- a/source/blender/render/intern/source/renderdatabase.c
+++ b/source/blender/render/intern/source/renderdatabase.c
@@ -66,6 +66,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
+#include "BLI_hash.h"
#include "DNA_material_types.h"
#include "DNA_meshdata_types.h"
@@ -1458,6 +1459,14 @@ ObjectInstanceRen *RE_addRenderInstance(
}
}
+ /* Fill object info */
+ if (dob) {
+ obi->random_id = dob->random_id;
+ }
+ else {
+ obi->random_id = BLI_hash_int_2d(BLI_hash_string(obi->ob->id.name + 2), 0);
+ }
+
RE_updateRenderInstance(re, obi, RE_OBJECT_INSTANCES_UPDATE_OBMAT | RE_OBJECT_INSTANCES_UPDATE_VIEW);
if (mat) {
@@ -1473,9 +1482,10 @@ ObjectInstanceRen *RE_addRenderInstance(
return obi;
}
-void RE_instance_get_particle_info(struct ObjectInstanceRen *obi, float *index, float *age, float *lifetime, float co[3], float *size, float vel[3], float angvel[3])
+void RE_instance_get_particle_info(struct ObjectInstanceRen *obi, float *index, float *random, float *age, float *lifetime, float co[3], float *size, float vel[3], float angvel[3])
{
*index = obi->part_index;
+ *random = BLI_hash_int_01(obi->part_index);
*age = obi->part_age;
*lifetime = obi->part_lifetime;
copy_v3_v3(co, obi->part_co);
diff --git a/source/blender/render/intern/source/shadbuf.c b/source/blender/render/intern/source/shadbuf.c
index 6dd7e2c152d..fb441662829 100644
--- a/source/blender/render/intern/source/shadbuf.c
+++ b/source/blender/render/intern/source/shadbuf.c
@@ -40,7 +40,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_memarena.h"
#include "BLI_rand.h"
#include "BLI_utildefines.h"
@@ -787,10 +787,10 @@ void makeshadowbuf(Render *re, LampRen *lar)
shb->totbuf= lar->buffers;
/* jitter, weights - not threadsafe! */
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
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);
+ BLI_thread_unlock(LOCK_CUSTOM1);
if (shb->totbuf==4) jitbuf= give_jitter_tab(2);
else if (shb->totbuf==9) jitbuf= give_jitter_tab(3);
@@ -814,21 +814,21 @@ static void *do_shadow_thread(void *re_v)
LampRen *lar;
do {
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
for (lar=re->lampren.first; lar; lar=lar->next) {
if (lar->shb && !lar->thread_assigned) {
lar->thread_assigned= 1;
break;
}
}
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
/* if type is irregular, this only sets the perspective matrix and autoclips */
if (lar) {
makeshadowbuf(re, lar);
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
lar->thread_ready= 1;
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
}
} while (lar && !re->test_break(re->tbh));
@@ -878,10 +878,10 @@ void threaded_makeshadowbufs(Render *re)
lar->thread_ready= 0;
}
- BLI_init_threads(&threads, do_shadow_thread, totthread);
+ BLI_threadpool_init(&threads, do_shadow_thread, totthread);
for (a=0; a<totthread; a++)
- BLI_insert_thread(&threads, re);
+ BLI_threadpool_insert(&threads, re);
/* keep rendering as long as there are shadow buffers not ready */
do {
@@ -890,14 +890,14 @@ void threaded_makeshadowbufs(Render *re)
PIL_sleep_ms(50);
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
for (lar=re->lampren.first; lar; lar= lar->next)
if (lar->shb && !lar->thread_ready)
break;
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
} while (lar);
- BLI_end_threads(&threads);
+ BLI_threadpool_end(&threads);
/* unset threadsafety */
re->test_break= test_break;
diff --git a/source/blender/render/intern/source/shadeinput.c b/source/blender/render/intern/source/shadeinput.c
index 20602314526..b4ff5f52fcf 100644
--- a/source/blender/render/intern/source/shadeinput.c
+++ b/source/blender/render/intern/source/shadeinput.c
@@ -292,12 +292,8 @@ void shade_input_set_triangle_i(ShadeInput *shi, ObjectInstanceRen *obi, VlakRen
}
}
-/* note, facenr declared volatile due to over-eager -O2 optimization's
- * on cygwin (particularly -frerun-cse-after-loop)
- */
-
/* copy data from face to ShadeInput, scanline case */
-void shade_input_set_triangle(ShadeInput *shi, volatile int obi, volatile int facenr, int UNUSED(normal_flip))
+void shade_input_set_triangle(ShadeInput *shi, int obi, int facenr, int UNUSED(normal_flip))
{
if (facenr > 0) {
shi->obi = &R.objectinstance[obi];
diff --git a/source/blender/render/intern/source/shadeoutput.c b/source/blender/render/intern/source/shadeoutput.c
index c4de95e863e..83827067775 100644
--- a/source/blender/render/intern/source/shadeoutput.c
+++ b/source/blender/render/intern/source/shadeoutput.c
@@ -27,7 +27,6 @@
* \ingroup render
*/
-
#include <stdio.h>
#include <float.h>
#include <math.h>
@@ -36,10 +35,9 @@
#include "BLI_math.h"
#include "BLI_utildefines.h"
+#include "BKE_colorband.h"
#include "BKE_colortools.h"
#include "BKE_material.h"
-#include "BKE_texture.h"
-
#include "DNA_group_types.h"
#include "DNA_lamp_types.h"
@@ -951,7 +949,7 @@ static void ramp_diffuse_result(float *diff, ShadeInput *shi)
if (ma->ramp_col) {
if (ma->rampin_col==MA_RAMP_IN_RESULT) {
float fac = IMB_colormanagement_get_luminance(diff);
- do_colorband(ma->ramp_col, fac, col);
+ BKE_colorband_evaluate(ma->ramp_col, fac, col);
/* blending method */
fac= col[3]*ma->rampfac_col;
@@ -981,21 +979,21 @@ static void add_to_diffuse(float diff[3], const ShadeInput *shi, const float is,
/* input */
switch (ma->rampin_col) {
- case MA_RAMP_IN_ENERGY:
- fac = IMB_colormanagement_get_luminance(rgb);
- break;
- case MA_RAMP_IN_SHADER:
- fac = is;
- break;
- case MA_RAMP_IN_NOR:
- fac = dot_v3v3(shi->view, shi->vn);
- break;
- default:
- fac = 0.0f;
- break;
+ case MA_RAMP_IN_ENERGY:
+ fac = IMB_colormanagement_get_luminance(rgb);
+ break;
+ case MA_RAMP_IN_SHADER:
+ fac = is;
+ break;
+ case MA_RAMP_IN_NOR:
+ fac = dot_v3v3(shi->view, shi->vn);
+ break;
+ default:
+ fac = 0.0f;
+ break;
}
- do_colorband(ma->ramp_col, fac, col);
+ BKE_colorband_evaluate(ma->ramp_col, fac, col);
/* blending method */
fac = col[3] * ma->rampfac_col;
@@ -1024,7 +1022,7 @@ static void ramp_spec_result(float spec_col[3], ShadeInput *shi)
float col[4];
float fac = IMB_colormanagement_get_luminance(spec_col);
- do_colorband(ma->ramp_spec, fac, col);
+ BKE_colorband_evaluate(ma->ramp_spec, fac, col);
/* blending method */
fac= col[3]*ma->rampfac_spec;
@@ -1064,7 +1062,7 @@ static void do_specular_ramp(ShadeInput *shi, float is, float t, float spec[3])
break;
}
- do_colorband(ma->ramp_spec, fac, col);
+ BKE_colorband_evaluate(ma->ramp_spec, fac, col);
/* blending method */
fac= col[3]*ma->rampfac_spec;
@@ -2141,9 +2139,19 @@ const float (*RE_object_instance_get_matrix(struct ObjectInstanceRen *obi, int m
return NULL;
}
+float RE_object_instance_get_object_pass_index(struct ObjectInstanceRen *obi)
+{
+ return obi->ob->index;
+}
+
+float RE_object_instance_get_random_id(struct ObjectInstanceRen *obi)
+{
+ return obi->random_id;
+}
+
const float (*RE_render_current_get_matrix(int matrix_id))[4]
{
- switch(matrix_id) {
+ switch (matrix_id) {
case RE_VIEW_MATRIX:
return (const float(*)[4])R.viewmat;
case RE_VIEWINV_MATRIX:
@@ -2171,4 +2179,4 @@ float RE_fresnel_dielectric(float incoming[3], float normal[3], float eta)
}
return result;
-} \ No newline at end of file
+}
diff --git a/source/blender/render/intern/source/sss.c b/source/blender/render/intern/source/sss.c
index 26ca3ad50e0..c29da9b17c6 100644
--- a/source/blender/render/intern/source/sss.c
+++ b/source/blender/render/intern/source/sss.c
@@ -973,9 +973,9 @@ void sss_add_points(Render *re, float (*co)[3], float (*color)[3], float *area,
p->area= area;
p->totpoint= totpoint;
- BLI_lock_thread(LOCK_CUSTOM1);
+ BLI_thread_lock(LOCK_CUSTOM1);
BLI_addtail(re->sss_points, p);
- BLI_unlock_thread(LOCK_CUSTOM1);
+ BLI_thread_unlock(LOCK_CUSTOM1);
}
}
diff --git a/source/blender/render/intern/source/sunsky.c b/source/blender/render/intern/source/sunsky.c
index d4e53eb7305..f0cf29e98ca 100644
--- a/source/blender/render/intern/source/sunsky.c
+++ b/source/blender/render/intern/source/sunsky.c
@@ -398,7 +398,7 @@ void InitAtmosphere(struct SunSky *sunSky, float sun_intens, float mief, float r
vLambda2[0] = fLambda2[0];
vLambda2[1] = fLambda2[1];
vLambda2[2] = fLambda2[2];
-
+
vLambda4[0] = fLambda4[0];
vLambda4[1] = fLambda4[1];
vLambda4[2] = fLambda4[2];
diff --git a/source/blender/render/intern/source/volume_precache.c b/source/blender/render/intern/source/volume_precache.c
index 5377d0eba00..752a9df0b79 100644
--- a/source/blender/render/intern/source/volume_precache.c
+++ b/source/blender/render/intern/source/volume_precache.c
@@ -60,6 +60,8 @@
#include "volumetric.h"
#include "volume_precache.h"
+#include "atomic_ops.h"
+
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
/* defined in pipeline.c, is hardcopy of active dynamic allocated Render */
@@ -509,7 +511,8 @@ static void *vol_precache_part_test(void *data)
*/
typedef struct VolPrecacheState {
double lasttime;
- int totparts;
+ unsigned int doneparts;
+ unsigned int totparts;
} VolPrecacheState;
static void vol_precache_part(TaskPool * __restrict pool, void *taskdata, int UNUSED(threadid))
@@ -574,13 +577,15 @@ static void vol_precache_part(TaskPool * __restrict pool, void *taskdata, int UN
}
}
+ unsigned int doneparts = atomic_add_and_fetch_u(&state->doneparts, 1);
+
time = PIL_check_seconds_timer();
if (time - state->lasttime > 1.0) {
ThreadMutex *mutex = BLI_task_pool_user_mutex(pool);
if (BLI_mutex_trylock(mutex)) {
char str[64];
- float ratio = (float)BLI_task_pool_tasks_done(pool)/(float)state->totparts;
+ float ratio = (float)doneparts/(float)state->totparts;
BLI_snprintf(str, sizeof(str), IFACE_("Precaching volume: %d%%"), (int)(100.0f * ratio));
re->i.infostr = str;
re->stats_draw(re->sdh, &re->i);
@@ -631,6 +636,7 @@ static void precache_launch_parts(Render *re, RayObject *tree, ShadeInput *shi,
/* setup task scheduler */
memset(&state, 0, sizeof(state));
+ state.doneparts = 0;
state.totparts = parts[0]*parts[1]*parts[2];
state.lasttime = PIL_check_seconds_timer();
diff --git a/source/blender/render/intern/source/volumetric.c b/source/blender/render/intern/source/volumetric.c
index 610e86caa13..7fe52328781 100644
--- a/source/blender/render/intern/source/volumetric.c
+++ b/source/blender/render/intern/source/volumetric.c
@@ -275,10 +275,12 @@ static float metadensity(Object *ob, const float co[3])
break;
case MB_CUBE:
tp[2] = (tp[2] > ml->expz) ? (tp[2] - ml->expz) : ((tp[2] < -ml->expz) ? (tp[2] + ml->expz) : 0.f);
- /* no break, xy as plane */
+ /* no break, xy as plane */
+ ATTR_FALLTHROUGH;
case MB_PLANE:
tp[1] = (tp[1] > ml->expy) ? (tp[1] - ml->expy) : ((tp[1] < -ml->expy) ? (tp[1] + ml->expy) : 0.f);
- /* no break, x as tube */
+ /* no break, x as tube */
+ ATTR_FALLTHROUGH;
case MB_TUBE:
tp[0] = (tp[0] > ml->expx) ? (tp[0] - ml->expx) : ((tp[0] < -ml->expx) ? (tp[0] + ml->expx) : 0.f);
}
diff --git a/source/blender/render/intern/source/voxeldata.c b/source/blender/render/intern/source/voxeldata.c
index 1022aeeec66..c45bde300e7 100644
--- a/source/blender/render/intern/source/voxeldata.c
+++ b/source/blender/render/intern/source/voxeldata.c
@@ -61,7 +61,7 @@
#include "BPH_mass_spring.h"
#include "DNA_texture_types.h"
-#include "DNA_object_force.h"
+#include "DNA_object_force_types.h"
#include "DNA_object_types.h"
#include "DNA_particle_types.h"
#include "DNA_modifier_types.h"
diff --git a/source/blender/render/intern/source/zbuf.c b/source/blender/render/intern/source/zbuf.c
index 9f777631e52..aa073ad9a83 100644
--- a/source/blender/render/intern/source/zbuf.c
+++ b/source/blender/render/intern/source/zbuf.c
@@ -42,7 +42,7 @@
#include "BLI_math.h"
#include "BLI_blenlib.h"
-#include "BLI_jitter.h"
+#include "BLI_jitter_2d.h"
#include "BLI_threads.h"
#include "BLI_utildefines.h"
@@ -393,7 +393,7 @@ static void zbuffillAc4(ZSpan *zspan, int obi, int zvlnr,
zverg-= zspan->polygon_offset;
while (x>=0) {
- intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+ intzverg = round_db_to_int_clamp(zverg);
if ( intzverg < *rz) {
if (!zspan->rectmask || intzverg > *rm) {
@@ -1137,7 +1137,7 @@ static void zbuffillGLinv4(ZSpan *zspan, int obi, int zvlnr,
x= sn2-sn1;
while (x>=0) {
- intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+ intzverg = round_db_to_int_clamp(zverg);
if ( intzverg > *rz || *rz==0x7FFFFFFF) { /* UNIQUE LINE: see comment above */
if (!zspan->rectmask || intzverg > *rm) {
@@ -1260,7 +1260,7 @@ static void zbuffillGL4(ZSpan *zspan, int obi, int zvlnr,
x= sn2-sn1;
while (x>=0) {
- intzverg= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+ intzverg = round_db_to_int_clamp(zverg);
if (intzverg < *rz) { /* ONLY UNIQUE LINE: see comment above */
if (!zspan->rectmask || intzverg > *rm) {
@@ -1383,7 +1383,7 @@ static void zbuffillGL_onlyZ(ZSpan *zspan, int UNUSED(obi), int UNUSED(zvlnr),
x= sn2-sn1;
while (x>=0) {
- int zvergi= (int)CLAMPIS(zverg, INT_MIN, INT_MAX);
+ int zvergi = round_db_to_int_clamp(zverg);
/* option: maintain two depth values, closest and 2nd closest */
if (zvergi < *rz) {
@@ -1564,20 +1564,13 @@ void zspan_scanconvert(ZSpan *zspan, void *handle, float *v1, float *v2, float *
vy0= ((double)my2)*vyd + (double)xx1;
/* correct span */
- sn1= (my0 + my2)/2;
- if (zspan->span1[sn1] < zspan->span2[sn1]) {
- span1= zspan->span1+my2;
- span2= zspan->span2+my2;
- }
- else {
- span1= zspan->span2+my2;
- span2= zspan->span1+my2;
- }
+ span1= zspan->span1+my2;
+ span2= zspan->span2+my2;
for (i = 0, y = my2; y >= my0; i++, y--, span1--, span2--) {
- sn1= floor(*span1);
- sn2= floor(*span2);
+ sn1= floor(min_ff(*span1, *span2));
+ sn2= floor(max_ff(*span1, *span2));
sn1++;
if (sn2>=rectx) sn2= rectx-1;
@@ -1601,7 +1594,6 @@ void zspan_scanconvert(ZSpan *zspan, void *handle, float *v1, float *v2, float *
* Note: uses globals.
* \param v1 start coordinate s
* \param v2 target coordinate t
- * \param b1
* \param b2
* \param b3
* \param a index for coordinate (x, y, or z)
@@ -2650,559 +2642,6 @@ void zbuffer_sss(RenderPart *pa, unsigned int lay, void *handle, void (*func)(vo
zbuf_free_span(&zspan);
}
-/* ******************** VECBLUR ACCUM BUF ************************* */
-
-typedef struct DrawBufPixel {
- const float *colpoin;
- float alpha;
-} DrawBufPixel;
-
-
-static void zbuf_fill_in_rgba(ZSpan *zspan, DrawBufPixel *col, float *v1, float *v2, float *v3, float *v4)
-{
- DrawBufPixel *rectpofs, *rp;
- double zxd, zyd, zy0, zverg;
- float x0, y0, z0;
- float x1, y1, z1, x2, y2, z2, xx1;
- const float *span1, *span2;
- float *rectzofs, *rz;
- int x, y;
- int sn1, sn2, rectx, my0, my2;
-
- /* init */
- zbuf_init_span(zspan);
-
- /* set spans */
- zbuf_add_to_span(zspan, v1, v2);
- zbuf_add_to_span(zspan, v2, v3);
- zbuf_add_to_span(zspan, v3, v4);
- zbuf_add_to_span(zspan, v4, v1);
-
- /* clipped */
- if (zspan->minp2==NULL || zspan->maxp2==NULL) return;
-
- my0 = max_ii(zspan->miny1, zspan->miny2);
- my2 = min_ii(zspan->maxy1, zspan->maxy2);
-
- // printf("my %d %d\n", my0, my2);
- if (my2<my0) return;
-
- /* ZBUF DX DY, in floats still */
- x1= v1[0]- v2[0];
- x2= v2[0]- v3[0];
- y1= v1[1]- v2[1];
- y2= v2[1]- v3[1];
- z1= v1[2]- v2[2];
- z2= v2[2]- v3[2];
- x0= y1*z2-z1*y2;
- y0= z1*x2-x1*z2;
- z0= x1*y2-y1*x2;
-
- if (z0==0.0f) return;
-
- xx1= (x0*v1[0] + y0*v1[1])/z0 + v1[2];
-
- zxd= -(double)x0/(double)z0;
- zyd= -(double)y0/(double)z0;
- zy0= ((double)my2)*zyd + (double)xx1;
-
- /* start-offset in rect */
- rectx= zspan->rectx;
- rectzofs= (float *)(zspan->rectz + rectx*my2);
- rectpofs= ((DrawBufPixel *)zspan->rectp) + rectx*my2;
-
- /* correct span */
- sn1= (my0 + my2)/2;
- if (zspan->span1[sn1] < zspan->span2[sn1]) {
- span1= zspan->span1+my2;
- span2= zspan->span2+my2;
- }
- else {
- span1= zspan->span2+my2;
- span2= zspan->span1+my2;
- }
-
- for (y=my2; y>=my0; y--, span1--, span2--) {
-
- sn1= floor(*span1);
- sn2= floor(*span2);
- sn1++;
-
- if (sn2>=rectx) sn2= rectx-1;
- if (sn1<0) sn1= 0;
-
- if (sn2>=sn1) {
- zverg= (double)sn1*zxd + zy0;
- rz= rectzofs+sn1;
- rp= rectpofs+sn1;
- x= sn2-sn1;
-
- while (x>=0) {
- if (zverg < (double)*rz) {
- *rz= zverg;
- *rp= *col;
- }
- zverg+= zxd;
- rz++;
- rp++;
- x--;
- }
- }
-
- zy0-=zyd;
- rectzofs-= rectx;
- rectpofs-= rectx;
- }
-}
-
-/* char value==255 is filled in, rest should be zero */
-/* returns alpha values, but sets alpha to 1 for zero alpha pixels that have an alpha value as neighbor */
-void antialias_tagbuf(int xsize, int ysize, char *rectmove)
-{
- char *row1, *row2, *row3;
- char prev, next;
- int a, x, y, step;
-
- /* 1: tag pixels to be candidate for AA */
- for (y=2; y<ysize; y++) {
- /* setup rows */
- row1= rectmove + (y-2)*xsize;
- row2= row1 + xsize;
- row3= row2 + xsize;
- for (x=2; x<xsize; x++, row1++, row2++, row3++) {
- if (row2[1]) {
- if (row2[0]==0 || row2[2]==0 || row1[1]==0 || row3[1]==0)
- row2[1]= 128;
- }
- }
- }
-
- /* 2: evaluate horizontal scanlines and calculate alphas */
- row1= rectmove;
- for (y=0; y<ysize; y++) {
- row1++;
- for (x=1; x<xsize; x++, row1++) {
- if (row1[0]==128 && row1[1]==128) {
- /* find previous color and next color and amount of steps to blend */
- prev= row1[-1];
- step= 1;
- while (x+step<xsize && row1[step]==128)
- step++;
-
- if (x+step!=xsize) {
- /* now we can blend values */
- next= row1[step];
-
- /* note, prev value can be next value, but we do this loop to clear 128 then */
- for (a=0; a<step; a++) {
- int fac, mfac;
-
- fac= ((a+1)<<8)/(step+1);
- mfac= 255-fac;
-
- row1[a]= (prev*mfac + next*fac)>>8;
- }
- }
- }
- }
- }
-
- /* 3: evaluate vertical scanlines and calculate alphas */
- /* use for reading a copy of the original tagged buffer */
- for (x=0; x<xsize; x++) {
- row1= rectmove + x+xsize;
-
- for (y=1; y<ysize; y++, row1+=xsize) {
- if (row1[0]==128 && row1[xsize]==128) {
- /* find previous color and next color and amount of steps to blend */
- prev= row1[-xsize];
- step= 1;
- while (y+step<ysize && row1[step*xsize]==128)
- step++;
-
- if (y+step!=ysize) {
- /* now we can blend values */
- next= row1[step*xsize];
- /* note, prev value can be next value, but we do this loop to clear 128 then */
- for (a=0; a<step; a++) {
- int fac, mfac;
-
- fac= ((a+1)<<8)/(step+1);
- mfac= 255-fac;
-
- row1[a*xsize]= (prev*mfac + next*fac)>>8;
- }
- }
- }
- }
- }
-
- /* last: pixels with 0 we fill in zbuffer, with 1 we skip for mask */
- for (y=2; y<ysize; y++) {
- /* setup rows */
- row1= rectmove + (y-2)*xsize;
- row2= row1 + xsize;
- row3= row2 + xsize;
- for (x=2; x<xsize; x++, row1++, row2++, row3++) {
- if (row2[1]==0) {
- if (row2[0]>1 || row2[2]>1 || row1[1]>1 || row3[1]>1)
- row2[1]= 1;
- }
- }
- }
-}
-
-/* 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 - 0.5*p1 - 0.5*p3 */
- p2[0]= -0.5f*p1[0] - 0.5f*p3[0];
- p2[1]= -0.5f*p1[1] - 0.5f*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,
- const float *imgrect, float *vecbufrect, const float *zbufrect)
-{
- ZSpan zspan;
- DrawBufPixel *rectdraw, *dr;
- static float jit[256][2];
- float v1[3], v2[3], v3[3], v4[3], fx, fy;
- const float *dimg, *dz, *ro;
- float *rectvz, *dvz, *dvec1, *dvec2, *dz1, *dz2, *rectz;
- float *minvecbufrect= NULL, *rectweight, *rw, *rectmax, *rm;
- float maxspeedsq= (float)nbd->maxspeed*nbd->maxspeed;
- int y, x, step, maxspeed=nbd->maxspeed, samples= nbd->samples;
- int tsktsk= 0;
- static int firsttime= 1;
- char *rectmove, *dm;
-
- zbuf_alloc_span(&zspan, xsize, ysize, 1.0f);
- zspan.zmulx= ((float)xsize)/2.0f;
- zspan.zmuly= ((float)ysize)/2.0f;
- zspan.zofsx= 0.0f;
- zspan.zofsy= 0.0f;
-
- /* the buffers */
- rectz= MEM_mapallocN(sizeof(float)*xsize*ysize, "zbuf accum");
- zspan.rectz= (int *)rectz;
-
- 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;
- for (x= 4*xsize*ysize; x>0; x--, dvec1++) {
- if (dvec1[0]==PASS_VECTOR_MAX) {
- dvec1[0]= 0.0f;
- tsktsk= 1;
- }
- }
- if (tsktsk) printf("Found uninitialized speed in vector buffer... fixed.\n");
-
- /* min speed? then copy speedbuffer to recalculate speed vectors */
- if (nbd->minspeed) {
- float minspeed= (float)nbd->minspeed;
- float minspeedsq= minspeed*minspeed;
-
- minvecbufrect= MEM_mapallocN(4*sizeof(float)*xsize*ysize, "minspeed buf");
-
- dvec1= vecbufrect;
- dvec2= minvecbufrect;
- for (x= 2*xsize*ysize; x>0; x--, dvec1+=2, dvec2+=2) {
- if (dvec1[0]==0.0f && dvec1[1]==0.0f) {
- dvec2[0]= dvec1[0];
- dvec2[1]= dvec1[1];
- }
- else {
- float speedsq= dvec1[0]*dvec1[0] + dvec1[1]*dvec1[1];
- if (speedsq <= minspeedsq) {
- dvec2[0]= 0.0f;
- dvec2[1]= 0.0f;
- }
- else {
- speedsq = 1.0f - minspeed / sqrtf(speedsq);
- dvec2[0]= speedsq*dvec1[0];
- dvec2[1]= speedsq*dvec1[1];
- }
- }
- }
- SWAP(float *, minvecbufrect, vecbufrect);
- }
-
- /* make vertex buffer with averaged speed and zvalues */
- rectvz= MEM_mapallocN(4*sizeof(float)*(xsize+1)*(ysize+1), "vertices");
- dvz= rectvz;
- for (y=0; y<=ysize; y++) {
-
- if (y==0)
- dvec1= vecbufrect + 4*y*xsize;
- else
- dvec1= vecbufrect + 4*(y-1)*xsize;
-
- if (y==ysize)
- dvec2= vecbufrect + 4*(y-1)*xsize;
- else
- dvec2= vecbufrect + 4*y*xsize;
-
- for (x=0; x<=xsize; x++) {
-
- /* two vectors, so a step loop */
- for (step=0; step<2; step++, dvec1+=2, dvec2+=2, dvz+=2) {
- /* average on minimal speed */
- int div= 0;
-
- if (x!=0) {
- if (dvec1[-4]!=0.0f || dvec1[-3]!=0.0f) {
- dvz[0]= dvec1[-4];
- dvz[1]= dvec1[-3];
- div++;
- }
- if (dvec2[-4]!=0.0f || dvec2[-3]!=0.0f) {
- if (div==0) {
- dvz[0]= dvec2[-4];
- dvz[1]= dvec2[-3];
- div++;
- }
- else if ( (ABS(dvec2[-4]) + ABS(dvec2[-3]))< (ABS(dvz[0]) + ABS(dvz[1])) ) {
- dvz[0]= dvec2[-4];
- dvz[1]= dvec2[-3];
- }
- }
- }
-
- if (x!=xsize) {
- if (dvec1[0]!=0.0f || dvec1[1]!=0.0f) {
- if (div==0) {
- dvz[0]= dvec1[0];
- dvz[1]= dvec1[1];
- div++;
- }
- else if ( (ABS(dvec1[0]) + ABS(dvec1[1]))< (ABS(dvz[0]) + ABS(dvz[1])) ) {
- dvz[0]= dvec1[0];
- dvz[1]= dvec1[1];
- }
- }
- if (dvec2[0]!=0.0f || dvec2[1]!=0.0f) {
- if (div==0) {
- dvz[0]= dvec2[0];
- dvz[1]= dvec2[1];
- }
- else if ( (ABS(dvec2[0]) + ABS(dvec2[1]))< (ABS(dvz[0]) + ABS(dvz[1])) ) {
- dvz[0]= dvec2[0];
- dvz[1]= dvec2[1];
- }
- }
- }
- if (maxspeed) {
- float speedsq= dvz[0]*dvz[0] + dvz[1]*dvz[1];
- if (speedsq > maxspeedsq) {
- speedsq = (float)maxspeed / sqrtf(speedsq);
- dvz[0]*= speedsq;
- dvz[1]*= speedsq;
- }
- }
- }
- }
- }
-
- /* set border speeds to keep border speeds on border */
- dz1= rectvz;
- 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+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;
- dz2[2]= 0.0f;
- }
-
- /* tag moving pixels, only these faces we draw */
- 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))
- *dm= 255;
- }
-
- antialias_tagbuf(xsize, ysize, rectmove);
-
- /* has to become static, the init-jit calls a random-seed, screwing up texture noise node */
- if (firsttime) {
- firsttime= 0;
- BLI_jitter_init(jit, 256);
- }
-
- memset(newrect, 0, sizeof(float)*xsize*ysize*4);
-
- /* accumulate */
- samples/= 2;
- for (step= 1; step<=samples; step++) {
- float speedfac= 0.5f*nbd->fac*(float)step/(float)(samples+1);
- 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)
- for (x= xsize*ysize-1; x>=0; x--) rectz[x]= 10e16;
- else
- for (x= xsize*ysize-1; x>=0; x--) {
- if (rectmove[x]==0)
- rectz[x]= zbufrect[x];
- else
- rectz[x]= 10e16;
- }
-
- /* clear drawing buffer */
- for (x= xsize*ysize-1; x>=0; x--) rectdraw[x].colpoin= NULL;
-
- dimg= imgrect;
- dm= rectmove;
- dz= zbufrect;
- dz1= rectvz;
- dz2= rectvz + 4*(xsize + 1);
-
- if (side) {
- if (nbd->curved==0) {
- dz1+= 2;
- dz2+= 2;
- }
- speedfac= -speedfac;
- }
-
- 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 */
- 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+=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 */
- 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;
-
- 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);
-}
-
/* ******************** ABUF ************************* */
/**
@@ -3494,7 +2933,7 @@ static void add_transp_speed(RenderLayer *rl, int offset, float speed[4], float
RenderPass *rpass;
for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if (rpass->passtype==SCE_PASS_VECTOR) {
+ if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
float *fp= rpass->rect + 4*offset;
if (speed==NULL) {
@@ -3528,7 +2967,7 @@ static void add_transp_obindex(RenderLayer *rl, int offset, Object *ob)
RenderPass *rpass;
for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if (rpass->passtype == SCE_PASS_INDEXOB) {
+ if (STREQ(rpass->name, RE_PASSNAME_INDEXOB)) {
float *fp= rpass->rect + offset;
*fp= (float)ob->index;
break;
@@ -3541,7 +2980,7 @@ static void add_transp_material_index(RenderLayer *rl, int offset, Material *mat
RenderPass *rpass;
for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
- if (rpass->passtype == SCE_PASS_INDEXMA) {
+ if (STREQ(rpass->name, RE_PASSNAME_INDEXMA)) {
float *fp= rpass->rect + offset;
*fp= (float)mat->index;
break;
@@ -3558,78 +2997,74 @@ static void merge_transp_passes(RenderLayer *rl, ShadeResult *shr)
int delta= sizeof(ShadeResult)/4;
for (rpass= rl->passes.first; rpass; rpass= rpass->next) {
- float *col= NULL;
- int pixsize= 3;
+ float *col = NULL;
+ int pixsize = 3;
- switch (rpass->passtype) {
- case SCE_PASS_RGBA:
- col= shr->col;
- pixsize= 4;
- break;
- case SCE_PASS_EMIT:
- col= shr->emit;
- break;
- case SCE_PASS_DIFFUSE:
- col= shr->diff;
- break;
- case SCE_PASS_SPEC:
- col= shr->spec;
- break;
- case SCE_PASS_SHADOW:
- col= shr->shad;
- break;
- case SCE_PASS_AO:
- col= shr->ao;
- break;
- case SCE_PASS_ENVIRONMENT:
- col= shr->env;
- break;
- case SCE_PASS_INDIRECT:
- col= shr->indirect;
- break;
- case SCE_PASS_REFLECT:
- col= shr->refl;
- break;
- case SCE_PASS_REFRACT:
- col= shr->refr;
- break;
- 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:
+ if (STREQ(rpass->name, RE_PASSNAME_RGBA)) {
+ col = shr->col;
+ pixsize = 4;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_EMIT)) {
+ col = shr->emit;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_DIFFUSE)) {
+ col = shr->diff;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SPEC)) {
+ col = shr->spec;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SHADOW)) {
+ col = shr->shad;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_AO)) {
+ col = shr->ao;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_ENVIRONMENT)) {
+ col = shr->env;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDIRECT)) {
+ col = shr->indirect;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFLECT)) {
+ col = shr->refl;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFRACT)) {
+ col = shr->refr;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_NORMAL)) {
+ col = shr->nor;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_MIST)) {
+ col = &shr->mist;
+ pixsize = 1;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_Z)) {
+ col = &shr->z;
+ pixsize = 1;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_VECTOR)) {
+ ShadeResult *shr_t = shr+1;
+ float *fp = shr->winspeed; /* was initialized */
+ int samp;
+
+ /* add minimum speed in pixel */
+ for (samp = 1; samp<R.osa; samp++, shr_t++) {
- {
- ShadeResult *shr_t= shr+1;
- float *fp= shr->winspeed; /* was initialized */
- int samp;
+ if (shr_t->combined[3] > 0.0f) {
+ const float *speed = shr_t->winspeed;
- /* add minimum speed in pixel */
- for (samp= 1; samp<R.osa; samp++, shr_t++) {
-
- if (shr_t->combined[3] > 0.0f) {
- const float *speed= shr_t->winspeed;
-
- if ( (ABS(speed[0]) + ABS(speed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
- fp[0]= speed[0];
- fp[1]= speed[1];
- }
- if ( (ABS(speed[2]) + ABS(speed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
- fp[2]= speed[2];
- fp[3]= speed[3];
- }
- }
+ if ( (ABS(speed[0]) + ABS(speed[1]))< (ABS(fp[0]) + ABS(fp[1])) ) {
+ fp[0] = speed[0];
+ fp[1] = speed[1];
+ }
+ if ( (ABS(speed[2]) + ABS(speed[3]))< (ABS(fp[2]) + ABS(fp[3])) ) {
+ fp[2] = speed[2];
+ fp[3] = speed[3];
}
}
- break;
+ }
}
+
if (col) {
const float *fp= col+delta;
int samp;
@@ -3661,53 +3096,51 @@ static void add_transp_passes(RenderLayer *rl, int offset, ShadeResult *shr, flo
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);
- break;
- case SCE_PASS_EMIT:
- col= shr->emit;
- break;
- case SCE_PASS_DIFFUSE:
- col= shr->diff;
- break;
- case SCE_PASS_SPEC:
- col= shr->spec;
- break;
- case SCE_PASS_SHADOW:
- col= shr->shad;
- break;
- case SCE_PASS_AO:
- col= shr->ao;
- break;
- case SCE_PASS_ENVIRONMENT:
- col= shr->env;
- break;
- case SCE_PASS_INDIRECT:
- col= shr->indirect;
- break;
- case SCE_PASS_REFLECT:
- col= shr->refl;
- break;
- case SCE_PASS_REFRACT:
- col= shr->refr;
- break;
- case SCE_PASS_NORMAL:
- col= shr->nor;
- break;
- case SCE_PASS_MIST:
- col= &shr->mist;
- pixsize= 1;
- break;
+ if (STREQ(rpass->name, RE_PASSNAME_Z)) {
+ fp = rpass->rect + offset;
+ if (shr->z < *fp)
+ *fp = shr->z;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_RGBA)) {
+ fp = rpass->rect + 4*offset;
+ addAlphaOverFloat(fp, shr->col);
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_EMIT)) {
+ col = shr->emit;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_DIFFUSE)) {
+ col = shr->diff;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SPEC)) {
+ col = shr->spec;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_SHADOW)) {
+ col = shr->shad;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_AO)) {
+ col = shr->ao;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_ENVIRONMENT)) {
+ col = shr->env;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_INDIRECT)) {
+ col = shr->indirect;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFLECT)) {
+ col = shr->refl;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_REFRACT)) {
+ col = shr->refr;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_NORMAL)) {
+ col = shr->nor;
+ }
+ else if (STREQ(rpass->name, RE_PASSNAME_MIST)) {
+ col = &shr->mist;
+ pixsize = 1;
}
- if (col) {
+ if (col) {
fp= rpass->rect + pixsize*offset;
fp[0]= col[0] + (1.0f-alpha)*fp[0];
if (pixsize==3) {
@@ -3964,7 +3397,7 @@ static void reset_sky_speedvectors(RenderPart *pa, RenderLayer *rl, float *rectf
float *fp, *col;
int a;
- fp = RE_RenderLayerGetPass(rl, SCE_PASS_VECTOR, R.viewname);
+ fp = RE_RenderLayerGetPass(rl, RE_PASSNAME_VECTOR, R.viewname);
if (fp==NULL) return;
col= rectf+3;
@@ -4058,7 +3491,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
/* zero alpha pixels get speed vector max again */
if (addpassflag & SCE_PASS_VECTOR)
if (rl->layflag & SCE_LAY_SOLID) {
- float *rect = RE_RenderLayerGetPass(rl, SCE_PASS_COMBINED, R.viewname);
+ float *rect = RE_RenderLayerGetPass(rl, RE_PASSNAME_COMBINED, R.viewname);
reset_sky_speedvectors(pa, rl, rl->acolrect ? rl->acolrect : rect); /* if acolrect is set we use it */
}
/* filtered render, for now we assume only 1 filter size */
@@ -4246,7 +3679,7 @@ unsigned short *zbuffer_transp_shade(RenderPart *pa, RenderLayer *rl, float *pas
if (alpha != 0.0f) {
RenderLayer *rl_other = ssamp.rlpp[a];
- float *rect = RE_RenderLayerGetPass(rl_other , SCE_PASS_COMBINED, R.viewname);
+ float *rect = RE_RenderLayerGetPass(rl_other , RE_PASSNAME_COMBINED, R.viewname);
addAlphaOverFloat(rect + 4 * od, samp_shr[a].combined);
add_transp_passes(rl_other , od, &samp_shr[a], alpha);
diff --git a/source/blender/windowmanager/CMakeLists.txt b/source/blender/windowmanager/CMakeLists.txt
index b6245a8c0d1..50f99251489 100644
--- a/source/blender/windowmanager/CMakeLists.txt
+++ b/source/blender/windowmanager/CMakeLists.txt
@@ -39,6 +39,7 @@ set(INC
../nodes
../render/extern/include
../../gameengine/BlenderRoutines
+ ../../../intern/clog
../../../intern/ghost
../../../intern/guardedalloc
../../../intern/glew-mx
@@ -60,12 +61,14 @@ set(SRC
intern/wm_files.c
intern/wm_files_link.c
intern/wm_gesture.c
+ intern/wm_gesture_ops.c
intern/wm_init_exit.c
intern/wm_jobs.c
intern/wm_keymap.c
intern/wm_operator_props.c
intern/wm_operators.c
intern/wm_subwindow.c
+ intern/wm_tooltip.c
intern/wm_window.c
intern/wm_stereo.c
@@ -100,16 +103,6 @@ if(WITH_OPENCOLLADA)
add_definitions(-DWITH_COLLADA)
endif()
-if(WITH_CODEC_QUICKTIME)
- list(APPEND INC
- ../quicktime
- )
- list(APPEND INC_SYS
- ${QUICKTIME_INCLUDE_DIRS}
- )
- add_definitions(-DWITH_QUICKTIME)
-endif()
-
if(WITH_CODEC_FFMPEG)
list(APPEND INC_SYS
${FFMPEG_INCLUDE_DIRS}
@@ -128,10 +121,6 @@ if(WITH_PYTHON)
../python
)
add_definitions(-DWITH_PYTHON)
-
- if(WITH_PYTHON_SECURITY)
- add_definitions(-DWITH_PYTHON_SECURITY)
- endif()
endif()
if(WITH_GAMEENGINE)
diff --git a/source/blender/windowmanager/WM_api.h b/source/blender/windowmanager/WM_api.h
index 0f66ca98fbe..662272f3446 100644
--- a/source/blender/windowmanager/WM_api.h
+++ b/source/blender/windowmanager/WM_api.h
@@ -102,7 +102,8 @@ enum {
};
struct wmWindow *WM_window_open(struct bContext *C, const struct rcti *rect);
-struct wmWindow *WM_window_open_temp(struct bContext *C, const struct rcti *rect_init, int type);
+struct wmWindow *WM_window_open_temp(struct bContext *C, int x, int y, int sizex, int sizey, int type);
+void WM_window_set_dpi(wmWindow *win);
/* returns true if draw method is triple buffer */
bool WM_is_draw_triple(struct wmWindow *win);
@@ -115,7 +116,7 @@ void WM_file_autoexec_init(const char *filepath);
bool WM_file_read(struct bContext *C, const char *filepath, struct ReportList *reports);
void WM_autosave_init(struct wmWindowManager *wm);
void WM_recover_last_session(struct bContext *C, struct ReportList *reports);
-void WM_file_tag_modified(const struct bContext *C);
+void WM_file_tag_modified(void);
void WM_lib_reload(struct Library *lib, struct bContext *C, struct ReportList *reports);
@@ -185,9 +186,9 @@ enum {
struct wmEventHandler *WM_event_add_dropbox_handler(ListBase *handlers, ListBase *dropboxes);
/* mouse */
-void WM_event_add_mousemove(struct bContext *C);
-bool WM_modal_tweak_exit(const struct wmEvent *event, int tweak_event);
-bool WM_event_is_absolute(const struct wmEvent *event);
+void WM_event_add_mousemove(const struct bContext *C);
+bool WM_event_is_modal_tweak_exit(const struct wmEvent *event, int tweak_event);
+bool WM_event_is_last_mousemove(const struct wmEvent *event);
#ifdef WITH_INPUT_NDOF
/* 3D mouse */
@@ -204,11 +205,11 @@ void WM_report_banner_show(void);
void WM_report(ReportType type, const char *message);
void WM_reportf(ReportType type, const char *format, ...) ATTR_PRINTF_FORMAT(2, 3);
-void wm_event_add_ex(
+struct wmEvent *wm_event_add_ex(
struct wmWindow *win, const struct wmEvent *event_to_add,
const struct wmEvent *event_to_add_after)
ATTR_NONNULL(1, 2);
-void wm_event_add(
+struct wmEvent *wm_event_add(
struct wmWindow *win, const struct wmEvent *event_to_add)
ATTR_NONNULL(1, 2);
@@ -228,6 +229,7 @@ void WM_operator_view3d_unit_defaults(struct bContext *C, struct wmOperator *op
int WM_operator_smooth_viewtx_get(const struct wmOperator *op);
int WM_menu_invoke_ex(struct bContext *C, struct wmOperator *op, int opcontext);
int WM_menu_invoke (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
+void WM_menu_name_call(struct bContext *C, const char *menu_name, short context);
int WM_enum_search_invoke(struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
/* invoke callback, confirm menu + exec */
int WM_operator_confirm (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
@@ -252,6 +254,7 @@ int WM_operator_confirm_message(struct bContext *C, struct wmOperator *o
/* operator api */
void WM_operator_free (struct wmOperator *op);
+void WM_operator_free_all_after(wmWindowManager *wm, struct wmOperator *op);
void WM_operator_type_set(struct wmOperator *op, struct wmOperatorType *ot);
void WM_operator_stack_clear(struct wmWindowManager *wm);
void WM_operator_handlers_clear(wmWindowManager *wm, struct wmOperatorType *ot);
@@ -276,6 +279,7 @@ int WM_operator_call (struct bContext *C, struct wmOperator *op);
int WM_operator_call_notest(struct bContext *C, struct wmOperator *op);
int WM_operator_repeat (struct bContext *C, struct wmOperator *op);
bool WM_operator_repeat_check(const struct bContext *C, struct wmOperator *op);
+bool WM_operator_is_repeat(const struct bContext *C, const struct wmOperator *op);
int WM_operator_name_call_ptr(struct bContext *C, struct wmOperatorType *ot, short context, struct PointerRNA *properties);
int WM_operator_name_call(struct bContext *C, const char *opstring, short context, struct PointerRNA *properties);
int WM_operator_call_py(struct bContext *C, struct wmOperatorType *ot, short context, struct PointerRNA *properties, struct ReportList *reports, const bool is_undo);
@@ -305,9 +309,18 @@ void WM_operator_properties_filesel(
void WM_operator_properties_border(struct wmOperatorType *ot);
void WM_operator_properties_border_to_rcti(struct wmOperator *op, struct rcti *rect);
void WM_operator_properties_border_to_rctf(struct wmOperator *op, rctf *rect);
-void WM_operator_properties_gesture_border(struct wmOperatorType *ot, bool extend);
-void WM_operator_properties_mouse_select(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_border_ex(struct wmOperatorType *ot, bool deselect, bool extend);
+void WM_operator_properties_gesture_border(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_border_select(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_border_zoom(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_lasso_ex(struct wmOperatorType *ot, bool deselect, bool extend);
+void WM_operator_properties_gesture_lasso(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_lasso_select(struct wmOperatorType *ot);
void WM_operator_properties_gesture_straightline(struct wmOperatorType *ot, int cursor);
+void WM_operator_properties_gesture_circle_ex(struct wmOperatorType *ot, bool deselect);
+void WM_operator_properties_gesture_circle(struct wmOperatorType *ot);
+void WM_operator_properties_gesture_circle_select(struct wmOperatorType *ot);
+void WM_operator_properties_mouse_select(struct wmOperatorType *ot);
void WM_operator_properties_select_all(struct wmOperatorType *ot);
void WM_operator_properties_select_action(struct wmOperatorType *ot, int default_action);
void WM_operator_properties_select_action_simple(struct wmOperatorType *ot, int default_action);
@@ -351,6 +364,7 @@ bool WM_operator_pystring_abbreviate(char *str, int str_len_max);
char *WM_prop_pystring_assign(struct bContext *C, struct PointerRNA *ptr, struct PropertyRNA *prop, int index);
void WM_operator_bl_idname(char *to, const char *from);
void WM_operator_py_idname(char *to, const char *from);
+bool WM_operator_py_idname_ok_or_report(struct ReportList *reports, const char *classname, const char *idname);
/* *************** uilist types ******************** */
void WM_uilisttype_init(void);
@@ -365,11 +379,12 @@ struct MenuType *WM_menutype_find(const char *idname, bool quiet);
bool WM_menutype_add(struct MenuType *mt);
void WM_menutype_freelink(struct MenuType *mt);
void WM_menutype_free(void);
+bool WM_menutype_poll(struct bContext *C, struct MenuType *mt);
- /* default operator callbacks for border/circle/lasso */
-int WM_border_select_invoke (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
-int WM_border_select_modal (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
-void WM_border_select_cancel(struct bContext *C, struct wmOperator *op);
+/* wm_gesture_ops.c */
+int WM_gesture_border_invoke (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
+int WM_gesture_border_modal (struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
+void WM_gesture_border_cancel(struct bContext *C, struct wmOperator *op);
int WM_gesture_circle_invoke(struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
int WM_gesture_circle_modal(struct bContext *C, struct wmOperator *op, const struct wmEvent *event);
void WM_gesture_circle_cancel(struct bContext *C, struct wmOperator *op);
@@ -493,6 +508,11 @@ void WM_progress_set(struct wmWindow *win, float progress);
void WM_progress_clear(struct wmWindow *win);
/* Draw (for screenshot) */
+void *WM_draw_cb_activate(
+ struct wmWindow *win,
+ void(*draw)(const struct wmWindow *, void *),
+ void *customdata);
+void WM_draw_cb_exit(struct wmWindow *win, void *handle);
void WM_redraw_windows(struct bContext *C);
void WM_main_playanim(int argc, const char **argv);
@@ -518,6 +538,17 @@ bool WM_event_is_tablet(const struct wmEvent *event);
bool WM_event_is_ime_switch(const struct wmEvent *event);
#endif
+/* wm_tooltip.c */
+typedef struct ARegion *(*wmTooltipInitFn)(struct bContext *, struct ARegion *, bool *);
+
+void WM_tooltip_timer_init(
+ struct bContext *C, struct wmWindow *win, struct ARegion *ar,
+ wmTooltipInitFn init);
+void WM_tooltip_timer_clear(struct bContext *C, struct wmWindow *win);
+void WM_tooltip_clear(struct bContext *C, struct wmWindow *win);
+void WM_tooltip_init(struct bContext *C, struct wmWindow *win);
+void WM_tooltip_refresh(struct bContext *C, struct wmWindow *win);
+
#ifdef __cplusplus
}
#endif
diff --git a/source/blender/windowmanager/WM_keymap.h b/source/blender/windowmanager/WM_keymap.h
index a6413369a8f..b4d4d55479d 100644
--- a/source/blender/windowmanager/WM_keymap.h
+++ b/source/blender/windowmanager/WM_keymap.h
@@ -68,7 +68,7 @@ wmKeyMapItem *WM_keymap_add_menu_pie(struct wmKeyMap *keymap, const char *idname
int val, int modifier, int keymodifier);
bool WM_keymap_remove_item(struct wmKeyMap *keymap, struct wmKeyMapItem *kmi);
-int WM_keymap_item_to_string(wmKeyMapItem *kmi, const bool compact, const int len, char *r_str);
+int WM_keymap_item_to_string(wmKeyMapItem *kmi, const bool compact, char *result, const int result_len);
wmKeyMap *WM_keymap_list_find(ListBase *lb, const char *idname, int spaceid, int regionid);
wmKeyMap *WM_keymap_find(struct wmKeyConfig *keyconf, const char *idname, int spaceid, int regionid);
@@ -76,21 +76,24 @@ wmKeyMap *WM_keymap_find_all(const struct bContext *C, const char *idname, int s
wmKeyMap *WM_keymap_active(struct wmWindowManager *wm, struct wmKeyMap *keymap);
wmKeyMap *WM_keymap_guess_opname(const struct bContext *C, const char *opname);
bool WM_keymap_remove(struct wmKeyConfig *keyconfig, struct wmKeyMap *keymap);
-
+bool WM_keymap_poll(struct bContext *C, struct wmKeyMap *keymap);
+
wmKeyMapItem *WM_keymap_item_find_id(struct wmKeyMap *keymap, int id);
int WM_keymap_item_compare(struct wmKeyMapItem *k1, struct wmKeyMapItem *k2);
/* Modal Keymap */
int WM_modalkeymap_items_to_string(
- struct wmKeyMap *km, const int propvalue, const bool compact, const int len, char *r_str);
+ struct wmKeyMap *km, const int propvalue, const bool compact,
+ char *result, const int result_len);
int WM_modalkeymap_operator_items_to_string(
- struct wmOperatorType *ot, const int propvalue, const bool compact, const int len, char *r_str);
+ struct wmOperatorType *ot, const int propvalue, const bool compact,
+ char *result, const int result_len);
char *WM_modalkeymap_operator_items_to_string_buf(
struct wmOperatorType *ot, const int propvalue, const bool compact,
- const int max_len, int *r_available_len, char **r_str);
+ const int max_len, int *r_available_len, char **r_result);
-wmKeyMap *WM_modalkeymap_add(struct wmKeyConfig *keyconf, const char *idname, struct EnumPropertyItem *items);
+wmKeyMap *WM_modalkeymap_add(struct wmKeyConfig *keyconf, const char *idname, const struct EnumPropertyItem *items);
wmKeyMap *WM_modalkeymap_get(struct wmKeyConfig *keyconf, const char *idname);
wmKeyMapItem *WM_modalkeymap_add_item(struct wmKeyMap *km, int type, int val, int modifier, int keymodifier, int value);
wmKeyMapItem *WM_modalkeymap_add_item_str(struct wmKeyMap *km, int type, int val, int modifier, int keymodifier, const char *value);
@@ -109,14 +112,16 @@ int WM_keymap_map_type_get(struct wmKeyMapItem *kmi);
const char *WM_key_event_string(const short type, const bool compact);
int WM_keymap_item_raw_to_string(
const short shift, const short ctrl, const short alt, const short oskey, const short keymodifier,
- const short val, const short type, const bool compact, const int len, char *r_str);
+ const short val, const short type, const bool compact,
+ char *result, const int result_len);
wmKeyMapItem *WM_key_event_operator(
const struct bContext *C, const char *opname, int opcontext,
struct IDProperty *properties, const bool is_hotkey,
struct wmKeyMap **r_keymap);
-char *WM_key_event_operator_string(
+char *WM_key_event_operator_string(
const struct bContext *C, const char *opname, int opcontext,
- struct IDProperty *properties, const bool is_strict, int len, char *r_str);
+ struct IDProperty *properties, const bool is_strict,
+ char *result, const int result_len);
const char *WM_bool_as_string(bool test);
diff --git a/source/blender/windowmanager/WM_types.h b/source/blender/windowmanager/WM_types.h
index cd46e24264d..8c94c2ff043 100644
--- a/source/blender/windowmanager/WM_types.h
+++ b/source/blender/windowmanager/WM_types.h
@@ -409,11 +409,17 @@ typedef struct wmNotifier {
typedef struct wmGesture {
struct wmGesture *next, *prev;
int event_type; /* event->type */
- int mode; /* for modal callback */
int type; /* gesture type define */
int swinid; /* initial subwindow id where it started */
int points; /* optional, amount of points stored */
- int size; /* optional, maximum amount of points stored */
+ int points_alloc; /* optional, maximum amount of points stored */
+ int modal_state;
+
+ /* For modal operators which may be running idle, waiting for an event to activate the gesture.
+ * Typically this is set when the user is click-dragging the gesture (border and circle select for eg). */
+ uint is_active : 1;
+ /* Use for gestures that support both immediate or delayed activation. */
+ uint wait_for_input : 1;
void *customdata;
/* customdata for border is a recti */
@@ -423,6 +429,7 @@ typedef struct wmGesture {
/* free pointer to use for operator allocs (if set, its freed on exit)*/
void *userdata;
+ bool userdata_free;
} wmGesture;
/* ************** wmEvent ************************ */
@@ -454,8 +461,9 @@ typedef struct wmEvent {
short keymodifier; /* rawkey modifier */
/* set in case a KM_PRESS went by unhandled */
- short check_click;
-
+ char check_click;
+ char is_motion_absolute;
+
/* keymap item, set by handler (weak?) */
const char *keymap_idname;
@@ -500,6 +508,10 @@ typedef struct wmNDOFMotionData {
} wmNDOFMotionData;
#endif /* WITH_INPUT_NDOF */
+typedef enum { /* Timer flags */
+ WM_TIMER_NO_FREE_CUSTOM_DATA = 1 << 0, /* Do not attempt to free customdata pointer even if non-NULL. */
+} wmTimerFlags;
+
typedef struct wmTimer {
struct wmTimer *next, *prev;
@@ -507,6 +519,7 @@ typedef struct wmTimer {
double timestep; /* set by timer user */
int event_type; /* set by timer user, goes to event system */
+ wmTimerFlags flags; /* Various flags controlling timer options, see below. */
void *customdata; /* set by timer user, to allow custom values */
double duration; /* total running time in seconds */
@@ -515,7 +528,7 @@ typedef struct wmTimer {
double ltime; /* internal, last time timer was activated */
double ntime; /* internal, next time we want to activate the timer */
double stime; /* internal, when the timer started */
- int sleep; /* internal, put timers to sleep when needed */
+ bool sleep; /* internal, put timers to sleep when needed */
} wmTimer;
typedef struct wmOperatorType {
@@ -542,7 +555,15 @@ typedef struct wmOperatorType {
* canceled due to some external reason, cancel is called
* - see defines below for return values */
int (*invoke)(struct bContext *, struct wmOperator *, const struct wmEvent *) ATTR_WARN_UNUSED_RESULT;
+
+ /* Called when a modal operator is canceled (not used often).
+ * Internal cleanup can be done here if needed. */
void (*cancel)(struct bContext *, struct wmOperator *);
+
+ /* Modal is used for operators which continuously run, eg:
+ * fly mode, knife tool, circle select are all examples of modal operators.
+ * Modal operators can handle events which would normally access other operators,
+ * they keep running until they don't return `OPERATOR_RUNNING_MODAL`. */
int (*modal)(struct bContext *, struct wmOperator *, const struct wmEvent *) ATTR_WARN_UNUSED_RESULT;
/* verify if the operator can be executed in the current context, note
@@ -674,6 +695,23 @@ typedef struct wmDropBox {
} wmDropBox;
+/**
+ * Struct to store tool-tip timer and possible creation if the time is reached.
+ * Allows UI code to call #WM_tooltip_timer_init without each user having to handle the timer.
+ */
+typedef struct wmTooltipState {
+ /** Create tooltip on this event. */
+ struct wmTimer *timer;
+ /** The region the tooltip is created in. */
+ struct ARegion *region_from;
+ /** The tooltip region. */
+ struct ARegion *region;
+ /** Create the tooltip region (assign to 'region'). */
+ struct ARegion *(*init)(struct bContext *, struct ARegion *, bool *r_exit_on_event);
+ /** Exit on any event, not needed for buttons since their highlight state is used. */
+ bool exit_on_event;
+} wmTooltipState;
+
/* *************** migrated stuff, clean later? ************** */
typedef struct RecentFile {
@@ -681,6 +719,14 @@ typedef struct RecentFile {
char *filepath;
} RecentFile;
+/* Logging */
+struct CLG_LogRef;
+/* wm_init_exit.c */
+extern struct CLG_LogRef *WM_LOG_OPERATORS;
+extern struct CLG_LogRef *WM_LOG_HANDLERS;
+extern struct CLG_LogRef *WM_LOG_EVENTS;
+extern struct CLG_LogRef *WM_LOG_KEYMAPS;
+
#ifdef __cplusplus
}
diff --git a/source/blender/windowmanager/intern/wm.c b/source/blender/windowmanager/intern/wm.c
index b76a1f1d422..8be7555b34a 100644
--- a/source/blender/windowmanager/intern/wm.c
+++ b/source/blender/windowmanager/intern/wm.c
@@ -61,6 +61,7 @@
#include "wm.h"
#include "ED_screen.h"
+#include "BKE_undo_system.h"
#ifdef WITH_PYTHON
#include "BPY_extern.h"
@@ -107,6 +108,17 @@ void WM_operator_free(wmOperator *op)
MEM_freeN(op);
}
+void WM_operator_free_all_after(wmWindowManager *wm, struct wmOperator *op)
+{
+ op = op->next;
+ while (op != NULL) {
+ wmOperator *op_next = op->next;
+ BLI_remlink(&wm->operators, op);
+ WM_operator_free(op);
+ op = op_next;
+ }
+}
+
/**
* Use with extreme care!,
* properties, customdata etc - must be compatible.
@@ -149,18 +161,23 @@ static void wm_reports_free(wmWindowManager *wm)
void wm_operator_register(bContext *C, wmOperator *op)
{
wmWindowManager *wm = CTX_wm_manager(C);
- int tot;
+ int tot = 0;
BLI_addtail(&wm->operators, op);
- tot = BLI_listbase_count(&wm->operators);
-
- while (tot > MAX_OP_REGISTERED) {
- wmOperator *opt = wm->operators.first;
- BLI_remlink(&wm->operators, opt);
- WM_operator_free(opt);
- tot--;
+
+ /* only count registered operators */
+ while (op) {
+ wmOperator *op_prev = op->prev;
+ if (op->type->flag & OPTYPE_REGISTER) {
+ tot += 1;
+ }
+ if (tot > MAX_OP_REGISTERED) {
+ BLI_remlink(&wm->operators, op);
+ WM_operator_free(op);
+ }
+ op = op_prev;
}
-
+
/* so the console is redrawn */
WM_event_add_notifier(C, NC_SPACE | ND_SPACE_INFO_REPORT, NULL);
WM_event_add_notifier(C, NC_WM | ND_HISTORY, NULL);
@@ -321,6 +338,14 @@ void WM_menutype_free(void)
menutypes_hash = NULL;
}
+bool WM_menutype_poll(bContext *C, MenuType *mt)
+{
+ if (mt->poll != NULL) {
+ return mt->poll(C, mt);
+ }
+ return true;
+}
+
/* ****************************************** */
void WM_keymap_init(bContext *C)
@@ -414,7 +439,7 @@ void wm_clear_default_size(bContext *C)
/* on startup, it adds all data, for matching */
void wm_add_default(bContext *C)
{
- wmWindowManager *wm = BKE_libblock_alloc(CTX_data_main(C), ID_WM, "WinMan");
+ wmWindowManager *wm = BKE_libblock_alloc(CTX_data_main(C), ID_WM, "WinMan", 0);
wmWindow *win;
bScreen *screen = CTX_wm_screen(C); /* XXX from file read hrmf */
@@ -461,25 +486,33 @@ void wm_close_and_free(bContext *C, wmWindowManager *wm)
WM_drag_free_list(&wm->drags);
wm_reports_free(wm);
-
+
+ if (wm->undo_stack) {
+ BKE_undosys_stack_destroy(wm->undo_stack);
+ wm->undo_stack = NULL;
+ }
+
if (C && CTX_wm_manager(C) == wm) CTX_wm_manager_set(C, NULL);
}
void wm_close_and_free_all(bContext *C, ListBase *wmlist)
{
- Main *bmain = CTX_data_main(C);
wmWindowManager *wm;
-
+
while ((wm = wmlist->first)) {
wm_close_and_free(C, wm);
BLI_remlink(wmlist, wm);
- BKE_libblock_free_data(bmain, &wm->id);
+ BKE_libblock_free_data(&wm->id, true);
MEM_freeN(wm);
}
}
void WM_main(bContext *C)
{
+ /* Single refresh before handling events.
+ * This ensures we don't run operators before the depsgraph has been evaluated. */
+ wm_event_do_refresh_wm_and_depsgraph(C);
+
while (1) {
/* get events from ghost, handle window events, add to window queues */
diff --git a/source/blender/windowmanager/intern/wm_cursors.c b/source/blender/windowmanager/intern/wm_cursors.c
index d4c3928bd6c..ad5e83ceda7 100644
--- a/source/blender/windowmanager/intern/wm_cursors.c
+++ b/source/blender/windowmanager/intern/wm_cursors.c
@@ -213,13 +213,10 @@ void WM_cursor_grab_enable(wmWindow *win, bool wrap, bool hide, int bounds[4])
}
if ((G.debug & G_DEBUG) == 0) {
if (win->ghostwin) {
- const GHOST_TabletData *tabletdata = GHOST_GetTabletData(win->ghostwin);
-
/* Note: There is no tabletdata on Windows if no tablet device is connected. */
- if (!tabletdata)
- GHOST_SetCursorGrab(win->ghostwin, mode, bounds, NULL);
- else if (tabletdata->Active == GHOST_kTabletModeNone)
+ if (win->eventstate->is_motion_absolute == false) {
GHOST_SetCursorGrab(win->ghostwin, mode, bounds, NULL);
+ }
win->grabcursor = mode;
}
diff --git a/source/blender/windowmanager/intern/wm_dragdrop.c b/source/blender/windowmanager/intern/wm_dragdrop.c
index 3a53906a8e8..dd01efdb4c4 100644
--- a/source/blender/windowmanager/intern/wm_dragdrop.c
+++ b/source/blender/windowmanager/intern/wm_dragdrop.c
@@ -185,7 +185,7 @@ void WM_drag_free_list(struct ListBase *lb)
}
}
-static const char *dropbox_active(bContext *C, ListBase *handlers, wmDrag *drag, wmEvent *event)
+static const char *dropbox_active(bContext *C, ListBase *handlers, wmDrag *drag, const wmEvent *event)
{
wmEventHandler *handler = handlers->first;
for (; handler; handler = handler->next) {
@@ -203,7 +203,7 @@ static const char *dropbox_active(bContext *C, ListBase *handlers, wmDrag *drag,
}
/* return active operator name when mouse is in box */
-static const char *wm_dropbox_active(bContext *C, wmDrag *drag, wmEvent *event)
+static const char *wm_dropbox_active(bContext *C, wmDrag *drag, const wmEvent *event)
{
wmWindow *win = CTX_wm_window(C);
ScrArea *sa = CTX_wm_area(C);
@@ -223,7 +223,7 @@ static const char *wm_dropbox_active(bContext *C, wmDrag *drag, wmEvent *event)
}
-static void wm_drop_operator_options(bContext *C, wmDrag *drag, wmEvent *event)
+static void wm_drop_operator_options(bContext *C, wmDrag *drag, const wmEvent *event)
{
wmWindow *win = CTX_wm_window(C);
const int winsize_x = WM_window_pixels_x(win);
@@ -253,7 +253,7 @@ static void wm_drop_operator_options(bContext *C, wmDrag *drag, wmEvent *event)
}
/* called in inner handler loop, region context */
-void wm_drags_check_ops(bContext *C, wmEvent *event)
+void wm_drags_check_ops(bContext *C, const wmEvent *event)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmDrag *drag;
diff --git a/source/blender/windowmanager/intern/wm_draw.c b/source/blender/windowmanager/intern/wm_draw.c
index 77ffa46b990..e1f21699057 100644
--- a/source/blender/windowmanager/intern/wm_draw.c
+++ b/source/blender/windowmanager/intern/wm_draw.c
@@ -128,10 +128,10 @@ static bool wm_area_test_invalid_backbuf(ScrArea *sa)
if (sa->spacetype == SPACE_VIEW3D)
return (((View3D *)sa->spacedata.first)->flag & V3D_INVALID_BACKBUF) != 0;
else
- return 1;
+ return true;
}
-static void wm_region_test_render_do_draw(bScreen *screen, ScrArea *sa, ARegion *ar)
+static void wm_region_test_render_do_draw(const bScreen *screen, ScrArea *sa, ARegion *ar)
{
/* tag region for redraw from render engine preview running inside of it */
if (sa->spacetype == SPACE_VIEW3D) {
@@ -157,6 +157,46 @@ static void wm_region_test_render_do_draw(bScreen *screen, ScrArea *sa, ARegion
/********************** draw all **************************/
/* - reference method, draw all each time */
+typedef struct WindowDrawCB {
+ struct WindowDrawCB *next, *prev;
+
+ void(*draw)(const struct wmWindow *, void *);
+ void *customdata;
+
+} WindowDrawCB;
+
+void *WM_draw_cb_activate(
+ wmWindow *win,
+ void(*draw)(const struct wmWindow *, void *),
+ void *customdata)
+{
+ WindowDrawCB *wdc = MEM_callocN(sizeof(*wdc), "WindowDrawCB");
+
+ BLI_addtail(&win->drawcalls, wdc);
+ wdc->draw = draw;
+ wdc->customdata = customdata;
+
+ return wdc;
+}
+
+void WM_draw_cb_exit(wmWindow *win, void *handle)
+{
+ for (WindowDrawCB *wdc = win->drawcalls.first; wdc; wdc = wdc->next) {
+ if (wdc == (WindowDrawCB *)handle) {
+ BLI_remlink(&win->drawcalls, wdc);
+ MEM_freeN(wdc);
+ return;
+ }
+ }
+}
+
+static void wm_draw_callbacks(wmWindow *win)
+{
+ for (WindowDrawCB *wdc = win->drawcalls.first; wdc; wdc = wdc->next) {
+ wdc->draw(win, wdc->customdata);
+ }
+}
+
static void wm_method_draw_full(bContext *C, wmWindow *win)
{
bScreen *screen = win->screen;
@@ -181,8 +221,9 @@ static void wm_method_draw_full(bContext *C, wmWindow *win)
CTX_wm_area_set(C, NULL);
}
- ED_screen_draw(win);
- win->screen->do_draw = false;
+ ED_screen_draw_edges(win);
+ screen->do_draw = false;
+ wm_draw_callbacks(win);
/* draw overlapping regions */
for (ar = screen->regionbase.first; ar; ar = ar->next) {
@@ -318,17 +359,19 @@ static void wm_method_draw_overlap_all(bContext *C, wmWindow *win, int exchange)
/* after area regions so we can do area 'overlay' drawing */
if (screen->do_draw) {
- ED_screen_draw(win);
- win->screen->do_draw = false;
+ ED_screen_draw_edges(win);
+ screen->do_draw = false;
+ wm_draw_callbacks(win);
if (exchange)
screen->swap = WIN_FRONT_OK;
}
else if (exchange) {
if (screen->swap == WIN_FRONT_OK) {
- ED_screen_draw(win);
- win->screen->do_draw = false;
+ ED_screen_draw_edges(win);
+ screen->do_draw = false;
screen->swap = WIN_BOTH_OK;
+ wm_draw_callbacks(win);
}
else if (screen->swap == WIN_BACK_OK)
screen->swap = WIN_FRONT_OK;
@@ -514,7 +557,6 @@ static void wm_draw_region_blend(wmWindow *win, ARegion *ar, wmDrawTriple *tripl
static void wm_method_draw_triple(bContext *C, wmWindow *win)
{
wmWindowManager *wm = CTX_wm_manager(C);
- wmDrawTriple *triple;
wmDrawData *dd, *dd_next, *drawdata = win->drawdata.first;
bScreen *screen = win->screen;
ScrArea *sa;
@@ -554,7 +596,7 @@ static void wm_method_draw_triple(bContext *C, wmWindow *win)
MEM_freeN(dd);
}
- triple = drawdata->triple;
+ wmDrawTriple *triple = drawdata->triple;
/* draw marked area regions */
for (sa = screen->areabase.first; sa; sa = sa->next) {
@@ -562,7 +604,6 @@ static void wm_method_draw_triple(bContext *C, wmWindow *win)
for (ar = sa->regionbase.first; ar; ar = ar->next) {
if (ar->swinid && ar->do_draw) {
-
if (ar->overlap == false) {
CTX_wm_region_set(C, ar);
ED_region_do_draw(C, ar);
@@ -622,8 +663,9 @@ static void wm_method_draw_triple(bContext *C, wmWindow *win)
}
/* after area regions so we can do area 'overlay' drawing */
- ED_screen_draw(win);
+ ED_screen_draw_edges(win);
win->screen->do_draw = false;
+ wm_draw_callbacks(win);
/* draw floating regions (menus) */
for (ar = screen->regionbase.first; ar; ar = ar->next) {
@@ -645,7 +687,7 @@ static void wm_method_draw_triple(bContext *C, wmWindow *win)
}
}
-static void wm_method_draw_triple_multiview(bContext *C, wmWindow *win, StereoViews sview)
+static void wm_method_draw_triple_multiview(bContext *C, wmWindow *win, eStereoViews sview)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmDrawData *drawdata;
@@ -792,9 +834,10 @@ static void wm_method_draw_triple_multiview(bContext *C, wmWindow *win, StereoVi
}
/* after area regions so we can do area 'overlay' drawing */
- ED_screen_draw(win);
+ ED_screen_draw_edges(win);
if (sview == STEREO_RIGHT_ID)
win->screen->do_draw = false;
+ wm_draw_callbacks(win);
/* draw floating regions (menus) */
for (ar = screen->regionbase.first; ar; ar = ar->next) {
@@ -826,11 +869,12 @@ static void wm_method_draw_triple_multiview(bContext *C, wmWindow *win, StereoVi
/* quick test to prevent changing window drawable */
static bool wm_draw_update_test_window(wmWindow *win)
{
+ const bScreen *screen = win->screen;
ScrArea *sa;
ARegion *ar;
bool do_draw = false;
- for (ar = win->screen->regionbase.first; ar; ar = ar->next) {
+ for (ar = screen->regionbase.first; ar; ar = ar->next) {
if (ar->do_draw_overlay) {
wm_tag_redraw_overlay(win, ar);
ar->do_draw_overlay = false;
@@ -839,9 +883,9 @@ static bool wm_draw_update_test_window(wmWindow *win)
do_draw = true;
}
- for (sa = win->screen->areabase.first; sa; sa = sa->next) {
+ for (sa = screen->areabase.first; sa; sa = sa->next) {
for (ar = sa->regionbase.first; ar; ar = ar->next) {
- wm_region_test_render_do_draw(win->screen, sa, ar);
+ wm_region_test_render_do_draw(screen, sa, ar);
if (ar->swinid && ar->do_draw)
do_draw = true;
@@ -849,43 +893,31 @@ static bool wm_draw_update_test_window(wmWindow *win)
}
if (do_draw)
- return 1;
+ return true;
- if (win->screen->do_refresh)
- return 1;
- if (win->screen->do_draw)
- return 1;
- if (win->screen->do_draw_gesture)
- return 1;
- if (win->screen->do_draw_paintcursor)
- return 1;
- if (win->screen->do_draw_drag)
- return 1;
+ if (screen->do_refresh)
+ return true;
+ if (screen->do_draw)
+ return true;
+ if (screen->do_draw_gesture)
+ return true;
+ if (screen->do_draw_paintcursor)
+ return true;
+ if (screen->do_draw_drag)
+ return true;
- return 0;
+ return false;
}
static int wm_automatic_draw_method(wmWindow *win)
{
- /* Ideally all cards would work well with triple buffer, since if it works
- * well gives the least redraws and is considerably faster at partial redraw
- * for sculpting or drawing overlapping menus. For typically lower end cards
- * copy to texture is slow though and so we use overlap instead there. */
-
+ /* We assume all supported GPUs now support triple buffer well. */
if (win->drawmethod == USER_DRAW_AUTOMATIC) {
- /* Windows software driver darkens color on each redraw */
- if (GPU_type_matches(GPU_DEVICE_SOFTWARE, GPU_OS_WIN, GPU_DRIVER_SOFTWARE))
- return USER_DRAW_OVERLAP_FLIP;
- else if (GPU_type_matches(GPU_DEVICE_SOFTWARE, GPU_OS_UNIX, GPU_DRIVER_SOFTWARE))
- return USER_DRAW_OVERLAP;
- /* drawing lower color depth again degrades colors each time */
- else if (GPU_color_depth() < 24)
- return USER_DRAW_OVERLAP;
- else
- return USER_DRAW_TRIPLE;
+ return USER_DRAW_TRIPLE;
}
- else
+ else {
return win->drawmethod;
+ }
}
bool WM_is_draw_triple(wmWindow *win)
@@ -916,7 +948,6 @@ void wm_draw_update(bContext *C)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmWindow *win;
- int drawmethod;
#ifdef WITH_OPENSUBDIV
BKE_subsurf_free_unused_buffers();
@@ -926,15 +957,14 @@ void wm_draw_update(bContext *C)
for (win = wm->windows.first; win; win = win->next) {
#ifdef WIN32
- if (GPU_type_matches(GPU_DEVICE_INTEL, GPU_OS_ANY, GPU_DRIVER_ANY)) {
- GHOST_TWindowState state = GHOST_GetWindowState(win->ghostwin);
-
- if (state == GHOST_kWindowStateMinimized) {
- /* do not update minimized windows, it gives issues on intel drivers (see [#33223])
- * anyway, it seems logical to skip update for invisible windows
- */
- continue;
- }
+ GHOST_TWindowState state = GHOST_GetWindowState(win->ghostwin);
+
+ if (state == GHOST_kWindowStateMinimized) {
+ /* do not update minimized windows, gives issues on Intel (see T33223)
+ * and AMD (see T50856). it seems logical to skip update for invisible
+ * window anyway.
+ */
+ continue;
}
#endif
if (win->drawmethod != U.wmdrawmethod) {
@@ -943,16 +973,18 @@ void wm_draw_update(bContext *C)
}
if (wm_draw_update_test_window(win)) {
+ bScreen *screen = win->screen;
+
CTX_wm_window_set(C, win);
/* sets context window+screen */
wm_window_make_drawable(wm, win);
/* notifiers for screen redraw */
- if (win->screen->do_refresh)
+ if (screen->do_refresh)
ED_screen_refresh(wm, win);
- drawmethod = wm_automatic_draw_method(win);
+ int drawmethod = wm_automatic_draw_method(win);
if (win->drawfail)
wm_method_draw_overlap_all(C, win, 0);
@@ -973,9 +1005,9 @@ void wm_draw_update(bContext *C)
}
}
- win->screen->do_draw_gesture = false;
- win->screen->do_draw_paintcursor = false;
- win->screen->do_draw_drag = false;
+ screen->do_draw_gesture = false;
+ screen->do_draw_paintcursor = false;
+ screen->do_draw_drag = false;
wm_window_swap_buffers(win);
diff --git a/source/blender/windowmanager/intern/wm_event_system.c b/source/blender/windowmanager/intern/wm_event_system.c
index 9571dfd75d6..bc4dc5217cb 100644
--- a/source/blender/windowmanager/intern/wm_event_system.c
+++ b/source/blender/windowmanager/intern/wm_event_system.c
@@ -43,6 +43,8 @@
#include "MEM_guardedalloc.h"
+#include "CLG_log.h"
+
#include "GHOST_C-api.h"
#include "BLI_blenlib.h"
@@ -65,6 +67,7 @@
#include "ED_screen.h"
#include "ED_view3d.h"
#include "ED_util.h"
+#include "ED_undo.h"
#include "RNA_access.h"
@@ -83,6 +86,9 @@
#include "RNA_enum_types.h"
+/* Motion in pixels allowed before we don't consider single/double click. */
+#define WM_EVENT_CLICK_WIGGLE_ROOM 2
+
static void wm_notifier_clear(wmNotifier *note);
static void update_tablet_data(wmWindow *win, wmEvent *event);
@@ -91,7 +97,7 @@ static int wm_operator_call_internal(bContext *C, wmOperatorType *ot, PointerRNA
/* ************ event management ************** */
-void wm_event_add_ex(wmWindow *win, const wmEvent *event_to_add, const wmEvent *event_to_add_after)
+wmEvent *wm_event_add_ex(wmWindow *win, const wmEvent *event_to_add, const wmEvent *event_to_add_after)
{
wmEvent *event = MEM_mallocN(sizeof(wmEvent), "wmEvent");
@@ -99,6 +105,13 @@ void wm_event_add_ex(wmWindow *win, const wmEvent *event_to_add, const wmEvent *
update_tablet_data(win, event);
+ if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
+ /* We could have a preference to support relative tablet motion (we can't detect that). */
+ event->is_motion_absolute = (
+ (event->tablet_data != NULL) &&
+ (event->tablet_data->Active != GHOST_kTabletModeNone));
+ }
+
if (event_to_add_after == NULL) {
BLI_addtail(&win->queue, event);
}
@@ -106,11 +119,12 @@ void wm_event_add_ex(wmWindow *win, const wmEvent *event_to_add, const wmEvent *
/* note, strictly speaking this breaks const-correctness, however we're only changing 'next' member */
BLI_insertlinkafter(&win->queue, (void *)event_to_add_after, event);
}
+ return event;
}
-void wm_event_add(wmWindow *win, const wmEvent *event_to_add)
+wmEvent *wm_event_add(wmWindow *win, const wmEvent *event_to_add)
{
- wm_event_add_ex(win, event_to_add, NULL);
+ return wm_event_add_ex(win, event_to_add, NULL);
}
void wm_event_free(wmEvent *event)
@@ -263,13 +277,56 @@ static void wm_notifier_clear(wmNotifier *note)
memset(((char *)note) + sizeof(Link), 0, sizeof(*note) - sizeof(Link));
}
+/**
+ * Was part of #wm_event_do_notifiers, split out so it can be called once before entering the #WM_main loop.
+ * This ensures operators don't run before the UI and depsgraph are initialized.
+ */
+void wm_event_do_refresh_wm_and_depsgraph(bContext *C)
+{
+ wmWindowManager *wm = CTX_wm_manager(C);
+ uint64_t win_combine_v3d_datamask = 0;
+
+ /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
+ for (wmWindow *win = wm->windows.first; win; win = win->next) {
+ win_combine_v3d_datamask |= ED_view3d_screen_datamask(win->screen);
+ }
+
+ /* cached: editor refresh callbacks now, they get context */
+ for (wmWindow *win = wm->windows.first; win; win = win->next) {
+ ScrArea *sa;
+
+ CTX_wm_window_set(C, win);
+ for (sa = win->screen->areabase.first; sa; sa = sa->next) {
+ if (sa->do_refresh) {
+ CTX_wm_area_set(C, sa);
+ ED_area_do_refresh(C, sa);
+ }
+ }
+
+ /* XXX make lock in future, or separated derivedmesh users in scene */
+ if (G.is_rendering == false) {
+ /* depsgraph & animation: update tagged datablocks */
+ Main *bmain = CTX_data_main(C);
+
+ /* copied to set's in scene_update_tagged_recursive() */
+ win->screen->scene->customdata_mask = win_combine_v3d_datamask;
+
+ /* XXX, hack so operators can enforce datamasks [#26482], gl render */
+ win->screen->scene->customdata_mask |= win->screen->scene->customdata_mask_modal;
+
+ BKE_scene_update_tagged(bmain->eval_ctx, bmain, win->screen->scene);
+ }
+ }
+
+ CTX_wm_window_set(C, NULL);
+}
+
/* called in mainloop */
void wm_event_do_notifiers(bContext *C)
{
wmWindowManager *wm = CTX_wm_manager(C);
wmNotifier *note, *next;
wmWindow *win;
- uint64_t win_combine_v3d_datamask = 0;
if (wm == NULL)
return;
@@ -299,13 +356,11 @@ void wm_event_do_notifiers(bContext *C)
ED_screen_set(C, note->reference); // XXX hrms, think this over!
- if (G.debug & G_DEBUG_EVENTS)
- printf("%s: screen set %p\n", __func__, note->reference);
+ CLOG_INFO(WM_LOG_EVENTS, 1, "screen set %p", note->reference);
}
else if (note->data == ND_SCREENDELETE) {
ED_screen_delete(C, note->reference); // XXX hrms, think this over!
- if (G.debug & G_DEBUG_EVENTS)
- printf("%s: screen delete %p\n", __func__, note->reference);
+ CLOG_INFO(WM_LOG_EVENTS, 1, "screen delete %p", note->reference);
}
}
}
@@ -373,39 +428,7 @@ void wm_event_do_notifiers(bContext *C)
MEM_freeN(note);
}
- /* combine datamasks so 1 win doesn't disable UV's in another [#26448] */
- for (win = wm->windows.first; win; win = win->next) {
- win_combine_v3d_datamask |= ED_view3d_screen_datamask(win->screen);
- }
-
- /* cached: editor refresh callbacks now, they get context */
- for (win = wm->windows.first; win; win = win->next) {
- ScrArea *sa;
-
- CTX_wm_window_set(C, win);
- for (sa = win->screen->areabase.first; sa; sa = sa->next) {
- if (sa->do_refresh) {
- CTX_wm_area_set(C, sa);
- ED_area_do_refresh(C, sa);
- }
- }
-
- /* XXX make lock in future, or separated derivedmesh users in scene */
- if (G.is_rendering == false) {
- /* depsgraph & animation: update tagged datablocks */
- Main *bmain = CTX_data_main(C);
-
- /* copied to set's in scene_update_tagged_recursive() */
- win->screen->scene->customdata_mask = win_combine_v3d_datamask;
-
- /* XXX, hack so operators can enforce datamasks [#26482], gl render */
- win->screen->scene->customdata_mask |= win->screen->scene->customdata_mask_modal;
-
- BKE_scene_update_tagged(bmain->eval_ctx, bmain, win->screen->scene);
- }
- }
-
- CTX_wm_window_set(C, NULL);
+ wm_event_do_refresh_wm_and_depsgraph(C);
}
static int wm_event_always_pass(const wmEvent *event)
@@ -523,14 +546,6 @@ int WM_operator_poll_context(bContext *C, wmOperatorType *ot, short context)
return wm_operator_call_internal(C, ot, NULL, NULL, context, true);
}
-static void wm_operator_print(bContext *C, wmOperator *op)
-{
- /* context is needed for enum function */
- char *buf = WM_operator_pystring(C, op, false, true);
- puts(buf);
- MEM_freeN(buf);
-}
-
/**
* Sets the active region for this space from the context.
*
@@ -610,9 +625,14 @@ void WM_report_banner_show(void)
wm_reports->reporttimer->customdata = rti;
}
-bool WM_event_is_absolute(const wmEvent *event)
+bool WM_event_is_last_mousemove(const wmEvent *event)
{
- return (event->tablet_data != NULL);
+ while ((event = event->next)) {
+ if (ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
+ return false;
+ }
+ }
+ return true;
}
#ifdef WITH_INPUT_NDOF
@@ -684,12 +704,9 @@ static void wm_operator_reports(bContext *C, wmOperator *op, int retval, bool ca
CTX_wm_region_set(C, ar_prev);
}
}
-
+
if (retval & OPERATOR_FINISHED) {
- if (G.debug & G_DEBUG_WM) {
- /* todo - this print may double up, might want to check more flags then the FINISHED */
- wm_operator_print(C, op);
- }
+ CLOG_STR_INFO_N(WM_LOG_OPERATORS, 1, WM_operator_pystring(C, op, false, true));
if (caller_owns_reports == false) {
BKE_reports_print(op->reports, RPT_DEBUG); /* print out reports to console. */
@@ -715,15 +732,21 @@ static void wm_operator_reports(bContext *C, wmOperator *op, int retval, bool ca
*/
static bool wm_operator_register_check(wmWindowManager *wm, wmOperatorType *ot)
{
- return wm && (wm->op_undo_depth == 0) && (ot->flag & OPTYPE_REGISTER);
+ /* Check undo flag here since undo operators are also added to the list,
+ * to support checking if the same operator is run twice. */
+ return wm && (wm->op_undo_depth == 0) && (ot->flag & (OPTYPE_REGISTER | OPTYPE_UNDO));
}
-static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat)
+static void wm_operator_finished(bContext *C, wmOperator *op, const bool repeat, const bool store)
{
wmWindowManager *wm = CTX_wm_manager(C);
op->customdata = NULL;
+ if (store) {
+ WM_operator_last_properties_store(op);
+ }
+
/* we don't want to do undo pushes for operators that are being
* called from operators that already do an undo push. usually
* this will happen for python operators that call C operators */
@@ -769,14 +792,22 @@ static int wm_operator_exec(bContext *C, wmOperator *op, const bool repeat, cons
return retval;
if (op->type->exec) {
- if (op->type->flag & OPTYPE_UNDO)
+ if (op->type->flag & OPTYPE_UNDO) {
wm->op_undo_depth++;
+ }
+ if (repeat) {
+ op->flag |= OP_IS_REPEAT;
+ }
retval = op->type->exec(C, op);
OPERATOR_RETVAL_CHECK(retval);
+ if (repeat) {
+ op->flag &= ~OP_IS_REPEAT;
+ }
- if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
+ if (op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm) {
wm->op_undo_depth--;
+ }
}
/* XXX Disabled the repeat check to address part 2 of #31840.
@@ -786,12 +817,7 @@ static int wm_operator_exec(bContext *C, wmOperator *op, const bool repeat, cons
wm_operator_reports(C, op, retval, false);
if (retval & OPERATOR_FINISHED) {
- if (store) {
- if (wm->op_undo_depth == 0) { /* not called by py script */
- WM_operator_last_properties_store(op);
- }
- }
- wm_operator_finished(C, op, repeat);
+ wm_operator_finished(C, op, repeat, store && wm->op_undo_depth == 0);
}
else if (repeat == 0) {
/* warning: modal from exec is bad practice, but avoid crashing. */
@@ -878,6 +904,20 @@ bool WM_operator_repeat_check(const bContext *UNUSED(C), wmOperator *op)
return false;
}
+bool WM_operator_is_repeat(const bContext *C, const wmOperator *op)
+{
+ /* may be in the operators list or not */
+ wmOperator *op_prev;
+ if (op->prev == NULL && op->next == NULL) {
+ wmWindowManager *wm = CTX_wm_manager(C);
+ op_prev = wm->operators.last;
+ }
+ else {
+ op_prev = op->prev;
+ }
+ return (op_prev && (op->type == op_prev->type));
+}
+
static wmOperator *wm_operator_create(wmWindowManager *wm, wmOperatorType *ot,
PointerRNA *properties, ReportList *reports)
{
@@ -991,9 +1031,7 @@ bool WM_operator_last_properties_init(wmOperator *op)
IDProperty *replaceprops = IDP_New(IDP_GROUP, &val, "wmOperatorProperties");
PropertyRNA *iterprop;
- if (G.debug & G_DEBUG_WM) {
- printf("%s: loading previous properties for '%s'\n", __func__, op->type->idname);
- }
+ CLOG_INFO(WM_LOG_OPERATORS, 1, "loading previous properties for '%s'", op->type->idname);
iterprop = RNA_struct_iterator_property(op->type->srna);
@@ -1038,9 +1076,7 @@ bool WM_operator_last_properties_store(wmOperator *op)
}
if (op->properties) {
- if (G.debug & G_DEBUG_WM) {
- printf("%s: storing properties for '%s'\n", __func__, op->type->idname);
- }
+ CLOG_INFO(WM_LOG_OPERATORS, 1, "storing properties for '%s'", op->type->idname);
op->type->last_properties = IDP_CopyProperty(op->properties);
return true;
}
@@ -1089,6 +1125,9 @@ void WM_operator_last_properties_alloc(struct wmOperator *op, const char *idname
}
}
+/**
+ * Also used for exec when 'event' is NULL.
+ */
static int wm_operator_invoke(
bContext *C, wmOperatorType *ot, wmEvent *event,
PointerRNA *properties, ReportList *reports, const bool poll_only)
@@ -1104,18 +1143,21 @@ static int wm_operator_invoke(
wmOperator *op = wm_operator_create(wm, ot, properties, reports); /* if reports == NULL, they'll be initialized */
const bool is_nested_call = (wm->op_undo_depth != 0);
- op->flag |= OP_IS_INVOKE;
+ if (event != NULL) {
+ op->flag |= OP_IS_INVOKE;
+ }
/* initialize setting from previous run */
if (!is_nested_call) { /* not called by py script */
WM_operator_last_properties_init(op);
}
- if ((G.debug & G_DEBUG_HANDLERS) && ((event == NULL) || (event->type != MOUSEMOVE))) {
- printf("%s: handle evt %d win %d op %s\n",
- __func__, event ? event->type : 0, CTX_wm_screen(C)->subwinactive, ot->idname);
+ if ((event == NULL) || (event->type != MOUSEMOVE)) {
+ CLOG_INFO(WM_LOG_HANDLERS, 2,
+ "handle evt %d win %d op %s",
+ event ? event->type : 0, CTX_wm_screen(C)->subwinactive, ot->idname);
}
-
+
if (op->type->invoke && event) {
wm_region_mouse_co(C, event);
@@ -1140,9 +1182,9 @@ static int wm_operator_invoke(
}
else {
/* debug, important to leave a while, should never happen */
- printf("%s: invalid operator call '%s'\n", __func__, ot->idname);
+ CLOG_ERROR(WM_LOG_OPERATORS, "invalid operator call '%s'", op->idname);
}
-
+
/* Note, if the report is given as an argument then assume the caller will deal with displaying them
* currently python only uses this */
if (!(retval & OPERATOR_HANDLED) && (retval & (OPERATOR_FINISHED | OPERATOR_CANCELLED))) {
@@ -1154,10 +1196,8 @@ static int wm_operator_invoke(
/* do nothing, wm_operator_exec() has been called somewhere */
}
else if (retval & OPERATOR_FINISHED) {
- if (!is_nested_call) { /* not called by py script */
- WM_operator_last_properties_store(op);
- }
- wm_operator_finished(C, op, 0);
+ const bool store = !is_nested_call;
+ wm_operator_finished(C, op, false, store);
}
else if (retval & OPERATOR_RUNNING_MODAL) {
/* take ownership of reports (in case python provided own) */
@@ -1252,6 +1292,8 @@ static int wm_operator_call_internal(
switch (context) {
case WM_OP_INVOKE_DEFAULT:
case WM_OP_INVOKE_REGION_WIN:
+ case WM_OP_INVOKE_REGION_PREVIEW:
+ case WM_OP_INVOKE_REGION_CHANNELS:
case WM_OP_INVOKE_AREA:
case WM_OP_INVOKE_SCREEN:
/* window is needed for invoke, cancel operator */
@@ -1378,6 +1420,19 @@ int WM_operator_name_call(bContext *C, const char *opstring, short context, Poin
}
/**
+ * Call an existent menu. The menu can be created in C or Python.
+ */
+void WM_menu_name_call(bContext *C, const char *menu_name, short context)
+{
+ wmOperatorType *ot = WM_operatortype_find("WM_OT_call_menu", false);
+ PointerRNA ptr;
+ WM_operator_properties_create_ptr(&ptr, ot);
+ RNA_string_set(&ptr, "name", menu_name);
+ WM_operator_name_call_ptr(C, ot, context, &ptr);
+ WM_operator_properties_free(&ptr);
+}
+
+/**
* Similar to #WM_operator_name_call called with #WM_OP_EXEC_DEFAULT context.
*
* - #wmOperatorType is used instead of operator name since python already has the operator type.
@@ -1404,8 +1459,10 @@ int WM_operator_call_py(
if (is_undo && op->type->flag & OPTYPE_UNDO && CTX_wm_manager(C) == wm)
wm->op_undo_depth--;
}
- else
- printf("error \"%s\" operator has no exec function, python cannot call it\n", op->type->name);
+ else {
+ CLOG_WARN(WM_LOG_OPERATORS, "\"%s\" operator has no exec function, Python cannot call it", op->type->name);
+ }
+
#endif
/* not especially nice using undo depth here, its used so py never
@@ -1449,8 +1506,9 @@ static void wm_handler_op_context(bContext *C, wmEventHandler *handler, const wm
if (sa == NULL) {
/* when changing screen layouts with running modal handlers (like render display), this
* is not an error to print */
- if (handler->op == NULL)
- printf("internal error: handler (%s) has invalid area\n", handler->op->type->idname);
+ if (handler->op == NULL) {
+ CLOG_ERROR(WM_LOG_HANDLERS, "internal error: handler (%s) has invalid area", handler->op->type->idname);
+ }
}
else {
ARegion *ar;
@@ -1733,7 +1791,7 @@ static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHand
/* important to run 'wm_operator_finished' before NULLing the context members */
if (retval & OPERATOR_FINISHED) {
- wm_operator_finished(C, op, 0);
+ wm_operator_finished(C, op, false, true);
handler->op = NULL;
}
else if (retval & (OPERATOR_CANCELLED | OPERATOR_FINISHED)) {
@@ -1763,10 +1821,9 @@ static int wm_handler_operator_call(bContext *C, ListBase *handlers, wmEventHand
//retval &= ~OPERATOR_PASS_THROUGH;
}
}
-
}
else {
- printf("%s: error '%s' missing modal\n", __func__, op->idname);
+ CLOG_ERROR(WM_LOG_HANDLERS, "missing modal '%s'", op->idname);
}
}
else {
@@ -2042,7 +2099,7 @@ static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers
PRINT("%s: checking '%s' ...", __func__, keymap->idname);
- if (!keymap->poll || keymap->poll(C)) {
+ if (WM_keymap_poll(C, keymap)) {
PRINT("pass\n");
@@ -2057,19 +2114,15 @@ static int wm_handlers_do_intern(bContext *C, wmEvent *event, ListBase *handlers
action |= wm_handler_operator_call(C, handlers, handler, event, kmi->ptr);
if (action & WM_HANDLER_BREAK) {
/* not always_pass here, it denotes removed handler */
-
- if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
- printf("%s: handled! '%s'\n", __func__, kmi->idname);
-
+ CLOG_INFO(WM_LOG_HANDLERS, 2, "handled! '%s'", kmi->idname);
break;
}
else {
if (action & WM_HANDLER_HANDLED) {
- if (G.debug & (G_DEBUG_EVENTS | G_DEBUG_HANDLERS))
- printf("%s: handled - and pass on! '%s'\n", __func__, kmi->idname);
+ CLOG_INFO(WM_LOG_HANDLERS, 2, "handled - and pass on! '%s'", kmi->idname);
}
else {
- PRINT("%s: un-handled '%s'\n", __func__, kmi->idname);
+ CLOG_INFO(WM_LOG_HANDLERS, 2, "un-handled '%s'", kmi->idname);
}
}
}
@@ -2190,15 +2243,20 @@ static int wm_handlers_do(bContext *C, wmEvent *event, ListBase *handlers)
(win->eventstate->prevval == KM_PRESS) &&
(win->eventstate->check_click == true))
{
- event->val = KM_CLICK;
-
- if (G.debug & (G_DEBUG_HANDLERS)) {
- printf("%s: handling CLICK\n", __func__);
- }
+ if ((abs(event->x - win->eventstate->prevclickx)) <= WM_EVENT_CLICK_WIGGLE_ROOM &&
+ (abs(event->y - win->eventstate->prevclicky)) <= WM_EVENT_CLICK_WIGGLE_ROOM)
+ {
+ event->val = KM_CLICK;
- action |= wm_handlers_do_intern(C, event, handlers);
+ CLOG_INFO(WM_LOG_HANDLERS, 1, "handling CLICK");
+
+ action |= wm_handlers_do_intern(C, event, handlers);
- event->val = KM_RELEASE;
+ event->val = KM_RELEASE;
+ }
+ else {
+ win->eventstate->check_click = 0;
+ }
}
else if (event->val == KM_DBL_CLICK) {
event->val = KM_PRESS;
@@ -2412,13 +2470,14 @@ void wm_event_do_handlers(bContext *C)
if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
printf("\n%s: Handling event\n", __func__);
+
WM_event_print(event);
}
/* take care of pie event filter */
if (wm_event_pie_filter(win, event)) {
- if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS) && !ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
- printf("\n%s: event filtered due to pie button pressed\n", __func__);
+ if (!ELEM(event->type, MOUSEMOVE, INBETWEEN_MOUSEMOVE)) {
+ CLOG_INFO(WM_LOG_HANDLERS, 1, "event filtered due to pie button pressed");
}
BLI_remlink(&win->queue, event);
wm_event_free(event);
@@ -2427,6 +2486,13 @@ void wm_event_do_handlers(bContext *C)
CTX_wm_window_set(C, win);
+ /* Clear tool-tip on mouse move. */
+ if (win->screen->tool_tip && win->screen->tool_tip->exit_on_event) {
+ if (ISMOUSE(event->type)) {
+ WM_tooltip_clear(C, win);
+ }
+ }
+
/* we let modal handlers get active area/region, also wm_paintcursor_test needs it */
CTX_wm_area_set(C, area_event_inside(C, &event->x));
CTX_wm_region_set(C, region_event_inside(C, &event->x));
@@ -2443,7 +2509,17 @@ void wm_event_do_handlers(bContext *C)
/* fileread case */
if (CTX_wm_window(C) == NULL)
return;
-
+
+ /* check for a tooltip */
+ {
+ bScreen *screen = CTX_wm_window(C)->screen;
+ if (screen->tool_tip && screen->tool_tip->timer) {
+ if ((event->type == TIMER) && (event->customdata == screen->tool_tip->timer)) {
+ WM_tooltip_init(C, win);
+ }
+ }
+ }
+
/* check dragging, creates new event or frees, adds draw tag */
wm_event_drag_test(wm, win, event);
@@ -2685,7 +2761,7 @@ wmEventHandler *WM_event_add_keymap_handler(ListBase *handlers, wmKeyMap *keymap
wmEventHandler *handler;
if (!keymap) {
- printf("%s: called with NULL keymap\n", __func__);
+ CLOG_WARN(WM_LOG_HANDLERS, "called with NULL keymap");
return NULL;
}
@@ -2853,7 +2929,7 @@ static void WM_event_remove_handler(ListBase *handlers, wmEventHandler *handler)
}
#endif
-void WM_event_add_mousemove(bContext *C)
+void WM_event_add_mousemove(const bContext *C)
{
wmWindow *window = CTX_wm_window(C);
@@ -2862,7 +2938,7 @@ void WM_event_add_mousemove(bContext *C)
/* for modal callbacks, check configuration for how to interpret exit with tweaks */
-bool WM_modal_tweak_exit(const wmEvent *event, int tweak_event)
+bool WM_event_is_modal_tweak_exit(const wmEvent *event, int tweak_event)
{
/* if the release-confirm userpref setting is enabled,
* tweak events can be canceled when mouse is released
@@ -3147,8 +3223,9 @@ static bool wm_event_is_double_click(wmEvent *event, const wmEvent *event_state)
(event_state->prevval == KM_RELEASE) &&
(event->val == KM_PRESS))
{
- if ((ISMOUSE(event->type) == false) || ((ABS(event->x - event_state->prevclickx)) <= 2 &&
- (ABS(event->y - event_state->prevclicky)) <= 2))
+ if ((ISMOUSE(event->type) == false) ||
+ ((abs(event->x - event_state->prevclickx)) <= WM_EVENT_CLICK_WIGGLE_ROOM &&
+ (abs(event->y - event_state->prevclicky)) <= WM_EVENT_CLICK_WIGGLE_ROOM))
{
if ((PIL_check_seconds_timer() - event_state->prevclicktime) * 1000 < U.dbl_click_time) {
return true;
@@ -3159,7 +3236,7 @@ static bool wm_event_is_double_click(wmEvent *event, const wmEvent *event_state)
return false;
}
-static void wm_event_add_mousemove(wmWindow *win, const wmEvent *event)
+static wmEvent *wm_event_add_mousemove(wmWindow *win, const wmEvent *event)
{
wmEvent *event_last = win->queue.last;
@@ -3169,16 +3246,13 @@ static void wm_event_add_mousemove(wmWindow *win, const wmEvent *event)
if (event_last && event_last->type == MOUSEMOVE)
event_last->type = INBETWEEN_MOUSEMOVE;
- wm_event_add(win, event);
-
- {
- wmEvent *event_new = win->queue.last;
- if (event_last == NULL) {
- event_last = win->eventstate;
- }
-
- copy_v2_v2_int(&event_new->prevx, &event_last->x);
+ wmEvent *event_new = wm_event_add(win, event);
+ if (event_last == NULL) {
+ event_last = win->eventstate;
}
+
+ copy_v2_v2_int(&event_new->prevx, &event_last->x);
+ return event_new;
}
/* windows store own event queues, no bContext here */
@@ -3205,9 +3279,14 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
GHOST_TEventCursorData *cd = customdata;
copy_v2_v2_int(&event.x, &cd->x);
+ wm_stereo3d_mouse_offset_apply(win, &event.x);
+
event.type = MOUSEMOVE;
- wm_event_add_mousemove(win, &event);
- copy_v2_v2_int(&evt->x, &event.x);
+ {
+ wmEvent *event_new = wm_event_add_mousemove(win, &event);
+ copy_v2_v2_int(&evt->x, &event_new->x);
+ evt->is_motion_absolute = event_new->is_motion_absolute;
+ }
/* also add to other window if event is there, this makes overdraws disappear nicely */
/* it remaps mousecoord to other window in event */
@@ -3219,8 +3298,11 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
copy_v2_v2_int(&oevent.x, &event.x);
oevent.type = MOUSEMOVE;
- wm_event_add_mousemove(owin, &oevent);
- copy_v2_v2_int(&oevt->x, &oevent.x);
+ {
+ wmEvent *event_new = wm_event_add_mousemove(owin, &oevent);
+ copy_v2_v2_int(&oevt->x, &event_new->x);
+ oevt->is_motion_absolute = event_new->is_motion_absolute;
+ }
}
break;
@@ -3300,8 +3382,7 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
/* double click test */
if (wm_event_is_double_click(&event, evt)) {
- if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS))
- printf("%s Send double click\n", __func__);
+ CLOG_INFO(WM_LOG_HANDLERS, 1, "Send double click");
event.val = KM_DBL_CLICK;
}
if (event.val == KM_PRESS) {
@@ -3355,7 +3436,7 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
/* ghost should do this already for key up */
if (event.utf8_buf[0]) {
- printf("%s: ghost on your platform is misbehaving, utf8 events on key up!\n", __func__);
+ CLOG_ERROR(WM_LOG_EVENTS, "ghost on your platform is misbehaving, utf8 events on key up!");
}
event.utf8_buf[0] = '\0';
}
@@ -3368,8 +3449,9 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
if (event.utf8_buf[0]) {
if (BLI_str_utf8_size(event.utf8_buf) == -1) {
- printf("%s: ghost detected an invalid unicode character '%d'!\n",
- __func__, (int)(unsigned char)event.utf8_buf[0]);
+ CLOG_ERROR(WM_LOG_EVENTS,
+ "ghost detected an invalid unicode character '%d'",
+ (int)(unsigned char)event.utf8_buf[0]);
event.utf8_buf[0] = '\0';
}
}
@@ -3418,8 +3500,7 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
/* double click test */
/* if previous event was same type, and previous was release, and now it presses... */
if (wm_event_is_double_click(&event, evt)) {
- if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS))
- printf("%s Send double click\n", __func__);
+ CLOG_INFO(WM_LOG_HANDLERS, 1, "Send double click");
evt->val = event.val = KM_DBL_CLICK;
}
@@ -3489,9 +3570,7 @@ void wm_event_add_ghostevent(wmWindowManager *wm, wmWindow *win, int type, int U
attach_ndof_data(&event, customdata);
wm_event_add(win, &event);
- if (G.debug & (G_DEBUG_HANDLERS | G_DEBUG_EVENTS))
- printf("%s sending NDOF_MOTION, prev = %d %d\n", __func__, event.x, event.y);
-
+ CLOG_INFO(WM_LOG_HANDLERS, 1, "sending NDOF_MOTION, prev = %d %d", event.x, event.y);
break;
}
diff --git a/source/blender/windowmanager/intern/wm_files.c b/source/blender/windowmanager/intern/wm_files.c
index 05d63869074..da5ebd7abcd 100644
--- a/source/blender/windowmanager/intern/wm_files.c
+++ b/source/blender/windowmanager/intern/wm_files.c
@@ -62,6 +62,8 @@
#include "BLT_translation.h"
+#include "BLF_api.h"
+
#include "DNA_mesh_types.h" /* only for USE_BMESH_SAVE_AS_COMPAT */
#include "DNA_object_types.h"
#include "DNA_space_types.h"
@@ -71,7 +73,6 @@
#include "DNA_windowmanager_types.h"
#include "BKE_appdir.h"
-#include "BKE_utildefines.h"
#include "BKE_autoexec.h"
#include "BKE_blender.h"
#include "BKE_blendfile.h"
@@ -86,9 +87,11 @@
#include "BKE_sound.h"
#include "BKE_scene.h"
#include "BKE_screen.h"
+#include "BKE_undo_system.h"
#include "BLO_readfile.h"
#include "BLO_writefile.h"
+#include "BLO_undofile.h" /* to save from an undo memfile */
#include "RNA_access.h"
#include "RNA_define.h"
@@ -102,6 +105,7 @@
#include "ED_screen.h"
#include "ED_view3d.h"
#include "ED_util.h"
+#include "ED_undo.h"
#include "GHOST_C-api.h"
#include "GHOST_Path-api.h"
@@ -316,10 +320,8 @@ static void wm_window_match_do(bContext *C, ListBase *oldwmlist)
}
/* in case UserDef was read, we re-initialize all, and do versioning */
-static void wm_init_userdef(bContext *C, const bool from_memory)
+static void wm_init_userdef(Main *bmain, const bool read_userdef_from_memory)
{
- Main *bmain = CTX_data_main(C);
-
/* versioning is here */
UI_init_userdef();
@@ -327,23 +329,23 @@ static void wm_init_userdef(bContext *C, const bool from_memory)
BKE_sound_init(bmain);
/* needed so loading a file from the command line respects user-pref [#26156] */
- BKE_BIT_TEST_SET(G.fileflags, U.flag & USER_FILENOUI, G_FILE_NO_UI);
+ SET_FLAG_FROM_TEST(G.fileflags, U.flag & USER_FILENOUI, G_FILE_NO_UI);
/* set the python auto-execute setting from user prefs */
/* enabled by default, unless explicitly enabled in the command line which overrides */
if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
- BKE_BIT_TEST_SET(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
+ SET_FLAG_FROM_TEST(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
}
/* avoid re-saving for every small change to our prefs, allow overrides */
- if (from_memory) {
+ if (read_userdef_from_memory) {
BLO_update_defaults_userpref_blend();
}
/* update tempdir from user preferences */
BKE_tempdir_init(U.tempdir);
- BKE_blender_userdef_refresh();
+ BLF_antialias_set((U.text_render & USER_TEXT_DISABLE_AA) == 0);
}
@@ -451,7 +453,7 @@ void wm_file_read_report(bContext *C)
* Logic shared between #WM_file_read & #wm_homefile_read,
* updates to make after reading a file.
*/
-static void wm_file_read_post(bContext *C, bool is_startup_file)
+static void wm_file_read_post(bContext *C, const bool is_startup_file, const bool use_userdef)
{
bool addons_loaded = false;
wmWindowManager *wm = CTX_wm_manager(C);
@@ -470,9 +472,14 @@ static void wm_file_read_post(bContext *C, bool is_startup_file)
if (is_startup_file) {
/* possible python hasn't been initialized */
if (CTX_py_init_get(C)) {
- /* sync addons, these may have changed from the defaults */
- BPY_execute_string(C, "__import__('addon_utils').reset_all()");
-
+ if (use_userdef) {
+ /* Only run when we have a template path found. */
+ if (BKE_appdir_app_template_any()) {
+ BPY_execute_string(C, "__import__('bl_app_template_utils').reset()");
+ }
+ /* sync addons, these may have changed from the defaults */
+ BPY_execute_string(C, "__import__('addon_utils').reset_all()");
+ }
BPY_python_reset(C);
addons_loaded = true;
}
@@ -482,6 +489,8 @@ static void wm_file_read_post(bContext *C, bool is_startup_file)
BPY_python_reset(C);
addons_loaded = true;
}
+#else
+ UNUSED_VARS(use_userdef);
#endif /* WITH_PYTHON */
WM_operatortype_last_properties_clear_all();
@@ -516,9 +525,13 @@ static void wm_file_read_post(bContext *C, bool is_startup_file)
}
if (!G.background) {
-// undo_editmode_clear();
- BKE_undo_reset();
- BKE_undo_write(C, "original"); /* save current state */
+ if (wm->undo_stack == NULL) {
+ wm->undo_stack = BKE_undosys_stack_create();
+ }
+ else {
+ BKE_undosys_stack_clear(wm->undo_stack);
+ }
+ BKE_undosys_stack_init_from_main(wm->undo_stack, CTX_data_main(C));
}
}
@@ -554,7 +567,7 @@ bool WM_file_read(bContext *C, const char *filepath, ReportList *reports)
/* confusing this global... */
G.relbase_valid = 1;
- retval = BKE_blendfile_read(C, filepath, reports);
+ retval = BKE_blendfile_read(C, filepath, reports, 0);
/* when loading startup.blend's, we can be left with a blank path */
if (G.main->name[0]) {
G.save_over = 1;
@@ -577,7 +590,7 @@ bool WM_file_read(bContext *C, const char *filepath, ReportList *reports)
if (retval == BKE_BLENDFILE_READ_OK_USERPREFS) {
/* in case a userdef is read from regular .blend */
- wm_init_userdef(C, false);
+ wm_init_userdef(G.main, false);
}
if (retval != BKE_BLENDFILE_READ_FAIL) {
@@ -586,14 +599,10 @@ bool WM_file_read(bContext *C, const char *filepath, ReportList *reports)
}
}
- wm_file_read_post(C, false);
+ wm_file_read_post(C, false, false);
success = true;
}
-#if 0
- else if (retval == BKE_READ_EXOTIC_OK_OTHER)
- BKE_undo_write(C, "Import file");
-#endif
else if (retval == BKE_READ_EXOTIC_FAIL_OPEN) {
BKE_reportf(reports, RPT_ERROR, "Cannot read file '%s': %s", filepath,
errno ? strerror(errno) : TIP_("unable to open the file"));
@@ -629,35 +638,50 @@ bool WM_file_read(bContext *C, const char *filepath, ReportList *reports)
/**
- * called on startup, (context entirely filled with NULLs)
- * or called for 'New File'
- * both startup.blend and userpref.blend are checked
- * the optional parameter custom_file points to an alternative startup page
- * custom_file can be NULL
+ * Called on startup, (context entirely filled with NULLs)
+ * or called for 'New File' both startup.blend and userpref.blend are checked.
+ *
+ * \param use_factory_settings: Ignore on-disk startup file, use bundled ``datatoc_startup_blend`` instead.
+ * Used for "Restore Factory Settings".
+ * \param use_userdef: Load factory settings as well as startup file.
+ * Disabled for "File New" we don't want to reload preferences.
+ * \param filepath_startup_override: Optional path pointing to an alternative blend file (may be NULL).
+ * \param app_template_override: Template to use instead of the template defined in user-preferences.
+ * When not-null, this is written into the user preferences.
*/
-int wm_homefile_read(bContext *C, ReportList *reports, bool from_memory, const char *custom_file)
+int wm_homefile_read(
+ bContext *C, ReportList *reports,
+ bool use_factory_settings, bool use_empty_data, bool use_userdef,
+ const char *filepath_startup_override, const char *app_template_override)
{
ListBase wmbase;
- char startstr[FILE_MAX];
- char prefstr[FILE_MAX];
- int success = 0;
+ bool success = false;
+
+ char filepath_startup[FILE_MAX];
+ char filepath_userdef[FILE_MAX];
+
+ /* When 'app_template' is set: '{BLENDER_USER_CONFIG}/{app_template}' */
+ char app_template_system[FILE_MAX];
+ /* When 'app_template' is set: '{BLENDER_SYSTEM_SCRIPTS}/startup/bl_app_templates_system/{app_template}' */
+ char app_template_config[FILE_MAX];
/* Indicates whether user preferences were really load from memory.
*
- * This is used for versioning code, and for this we can not rely on from_memory
+ * This is used for versioning code, and for this we can not rely on use_factory_settings
* passed via argument. This is because there might be configuration folder
* exists but it might not have userpref.blend and in this case we fallback to
* reading home file from memory.
*
* And in this case versioning code is to be run.
*/
- bool read_userdef_from_memory = true;
+ bool read_userdef_from_memory = false;
+ eBLOReadSkip skip_flags = use_userdef ? 0 : BLO_READ_SKIP_USERDEF;
/* options exclude eachother */
- BLI_assert((from_memory && custom_file) == 0);
+ BLI_assert((use_factory_settings && filepath_startup_override) == 0);
if ((G.f & G_SCRIPT_OVERRIDE_PREF) == 0) {
- BKE_BIT_TEST_SET(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
+ SET_FLAG_FROM_TEST(G.f, (U.flag & USER_SCRIPT_AUTOEXEC_DISABLE) == 0, G_SCRIPT_AUTOEXEC);
}
BLI_callback_exec(CTX_data_main(C), NULL, BLI_CB_EVT_LOAD_PRE);
@@ -665,77 +689,166 @@ int wm_homefile_read(bContext *C, ReportList *reports, bool from_memory, const c
UI_view2d_zoom_cache_reset();
G.relbase_valid = 0;
- if (!from_memory) {
- const char * const cfgdir = BKE_appdir_folder_id(BLENDER_USER_CONFIG, NULL);
- if (custom_file) {
- BLI_strncpy(startstr, custom_file, FILE_MAX);
- if (cfgdir) {
- BLI_make_file_string(G.main->name, prefstr, cfgdir, BLENDER_USERPREF_FILE);
+ /* put aside screens to match with persistent windows later */
+ wm_window_match_init(C, &wmbase);
+
+ filepath_startup[0] = '\0';
+ filepath_userdef[0] = '\0';
+ app_template_system[0] = '\0';
+ app_template_config[0] = '\0';
+
+ const char * const cfgdir = BKE_appdir_folder_id(BLENDER_USER_CONFIG, NULL);
+ if (!use_factory_settings) {
+ if (cfgdir) {
+ BLI_path_join(filepath_startup, sizeof(filepath_startup), cfgdir, BLENDER_STARTUP_FILE, NULL);
+ if (use_userdef) {
+ BLI_path_join(filepath_userdef, sizeof(filepath_startup), cfgdir, BLENDER_USERPREF_FILE, NULL);
}
- else {
- prefstr[0] = '\0';
+ }
+ else {
+ use_factory_settings = true;
+ }
+
+ if (filepath_startup_override) {
+ BLI_strncpy(filepath_startup, filepath_startup_override, FILE_MAX);
+ }
+ }
+
+ /* load preferences before startup.blend */
+ if (use_userdef) {
+ if (!use_factory_settings && BLI_exists(filepath_userdef)) {
+ UserDef *userdef = BKE_blendfile_userdef_read(filepath_userdef, NULL);
+ if (userdef != NULL) {
+ BKE_blender_userdef_data_set_and_free(userdef);
+ userdef = NULL;
+
+ skip_flags |= BLO_READ_SKIP_USERDEF;
+ printf("Read prefs: %s\n", filepath_userdef);
}
}
- else if (cfgdir) {
- BLI_make_file_string(G.main->name, startstr, cfgdir, BLENDER_STARTUP_FILE);
- BLI_make_file_string(G.main->name, prefstr, cfgdir, BLENDER_USERPREF_FILE);
+ }
+
+ const char *app_template = NULL;
+
+ if (filepath_startup_override != NULL) {
+ /* pass */
+ }
+ else if (app_template_override) {
+ /* This may be clearing the current template by setting to an empty string. */
+ app_template = app_template_override;
+ }
+ else if (!use_factory_settings && U.app_template[0]) {
+ app_template = U.app_template;
+ }
+
+ if ((app_template != NULL) && (app_template[0] != '\0')) {
+ BKE_appdir_app_template_id_search(app_template, app_template_system, sizeof(app_template_system));
+
+ /* Insert template name into startup file. */
+
+ /* note that the path is being set even when 'use_factory_settings == true'
+ * this is done so we can load a templates factory-settings */
+ if (!use_factory_settings) {
+ BLI_path_join(app_template_config, sizeof(app_template_config), cfgdir, app_template, NULL);
+ BLI_path_join(filepath_startup, sizeof(filepath_startup), app_template_config, BLENDER_STARTUP_FILE, NULL);
+ if (BLI_access(filepath_startup, R_OK) != 0) {
+ filepath_startup[0] = '\0';
+ }
}
else {
- startstr[0] = '\0';
- prefstr[0] = '\0';
- from_memory = 1;
+ filepath_startup[0] = '\0';
+ }
+
+ if (filepath_startup[0] == '\0') {
+ BLI_path_join(filepath_startup, sizeof(filepath_startup), app_template_system, BLENDER_STARTUP_FILE, NULL);
}
}
-
- /* put aside screens to match with persistent windows later */
- wm_window_match_init(C, &wmbase);
-
- if (!from_memory) {
- if (BLI_access(startstr, R_OK) == 0) {
- success = (BKE_blendfile_read(C, startstr, NULL) != BKE_BLENDFILE_READ_FAIL);
+
+ if (!use_factory_settings || (filepath_startup[0] != '\0')) {
+ if (BLI_access(filepath_startup, R_OK) == 0) {
+ success = (BKE_blendfile_read(C, filepath_startup, NULL, skip_flags) != BKE_BLENDFILE_READ_FAIL);
}
if (BLI_listbase_is_empty(&U.themes)) {
if (G.debug & G_DEBUG)
- printf("\nNote: No (valid) '%s' found, fall back to built-in default.\n\n", startstr);
- success = 0;
+ printf("\nNote: No (valid) '%s' found, fall back to built-in default.\n\n", filepath_startup);
+ success = false;
}
}
- if (success == 0 && custom_file && reports) {
- BKE_reportf(reports, RPT_ERROR, "Could not read '%s'", custom_file);
- /*We can not return from here because wm is already reset*/
+ if (success == false && filepath_startup_override && reports) {
+ /* We can not return from here because wm is already reset */
+ BKE_reportf(reports, RPT_ERROR, "Could not read '%s'", filepath_startup_override);
}
- if (success == 0) {
- success = BKE_blendfile_read_from_memory(C, datatoc_startup_blend, datatoc_startup_blend_size, NULL, true);
+ if (success == false) {
+ success = BKE_blendfile_read_from_memory(
+ C, datatoc_startup_blend, datatoc_startup_blend_size,
+ NULL, skip_flags, true);
+ if (success) {
+ if (use_userdef) {
+ if ((skip_flags & BLO_READ_SKIP_USERDEF) == 0) {
+ read_userdef_from_memory = true;
+ }
+ }
+ }
if (BLI_listbase_is_empty(&wmbase)) {
wm_clear_default_size(C);
}
- BKE_tempdir_init(U.tempdir);
+ }
-#ifdef WITH_PYTHON_SECURITY
- /* use alternative setting for security nuts
- * otherwise we'd need to patch the binary blob - startup.blend.c */
- U.flag |= USER_SCRIPT_AUTOEXEC_DISABLE;
-#endif
+ if (use_empty_data) {
+ BKE_blendfile_read_make_empty(C);
}
-
- /* check new prefs only after startup.blend was finished */
- if (!from_memory && BLI_exists(prefstr)) {
- int done = BKE_blendfile_read_userdef(prefstr, NULL);
- if (done != BKE_BLENDFILE_READ_FAIL) {
- read_userdef_from_memory = false;
- printf("Read new prefs: %s\n", prefstr);
+
+ /* Load template preferences,
+ * unlike regular preferences we only use some of the settings,
+ * see: BKE_blender_userdef_set_app_template */
+ if (app_template_system[0] != '\0') {
+ char temp_path[FILE_MAX];
+ temp_path[0] = '\0';
+ if (!use_factory_settings) {
+ BLI_path_join(temp_path, sizeof(temp_path), app_template_config, BLENDER_USERPREF_FILE, NULL);
+ if (BLI_access(temp_path, R_OK) != 0) {
+ temp_path[0] = '\0';
+ }
+ }
+
+ if (temp_path[0] == '\0') {
+ BLI_path_join(temp_path, sizeof(temp_path), app_template_system, BLENDER_USERPREF_FILE, NULL);
+ }
+
+ if (use_userdef) {
+ UserDef *userdef_template = NULL;
+ /* just avoids missing file warning */
+ if (BLI_exists(temp_path)) {
+ userdef_template = BKE_blendfile_userdef_read(temp_path, NULL);
+ }
+ if (userdef_template == NULL) {
+ /* we need to have preferences load to overwrite preferences from previous template */
+ userdef_template = BKE_blendfile_userdef_read_from_memory(
+ datatoc_startup_blend, datatoc_startup_blend_size, NULL);
+ read_userdef_from_memory = true;
+ }
+ if (userdef_template) {
+ BKE_blender_userdef_app_template_data_set_and_free(userdef_template);
+ userdef_template = NULL;
+ }
}
}
-
+
+ if (app_template_override) {
+ BLI_strncpy(U.app_template, app_template_override, sizeof(U.app_template));
+ }
+
/* prevent buggy files that had G_FILE_RELATIVE_REMAP written out by mistake. Screws up autosaves otherwise
* can remove this eventually, only in a 2.53 and older, now its not written */
G.fileflags &= ~G_FILE_RELATIVE_REMAP;
- /* check userdef before open window, keymaps etc */
- wm_init_userdef(C, read_userdef_from_memory);
+ if (use_userdef) {
+ /* check userdef before open window, keymaps etc */
+ wm_init_userdef(CTX_data_main(C), read_userdef_from_memory);
+ }
/* match the read WM with current WM */
wm_window_match_do(C, &wmbase);
@@ -743,14 +856,19 @@ int wm_homefile_read(bContext *C, ReportList *reports, bool from_memory, const c
G.main->name[0] = '\0';
- /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
- if (!G.background) GPU_default_lights();
-
- /* XXX */
- G.save_over = 0; // start with save preference untitled.blend
- G.fileflags &= ~G_FILE_AUTOPLAY; /* disable autoplay in startup.blend... */
+ if (use_userdef) {
+ /* When loading factory settings, the reset solid OpenGL lights need to be applied. */
+ if (!G.background) {
+ GPU_default_lights();
+ }
+ }
+
+ /* start with save preference untitled.blend */
+ G.save_over = 0;
+ /* disable auto-play in startup.blend... */
+ G.fileflags &= ~G_FILE_AUTOPLAY;
- wm_file_read_post(C, true);
+ wm_file_read_post(C, true, use_userdef);
return true;
}
@@ -918,14 +1036,14 @@ static ImBuf *blend_file_thumb(Scene *scene, bScreen *screen, BlendThumbnail **t
ibuf = ED_view3d_draw_offscreen_imbuf_simple(
scene, scene->camera,
BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
- IB_rect, OB_SOLID, false, false, false, R_ALPHAPREMUL, 0, false, NULL,
+ IB_rect, V3D_OFSDRAW_NONE, OB_SOLID, R_ALPHAPREMUL, 0, NULL,
NULL, NULL, err_out);
}
else {
ibuf = ED_view3d_draw_offscreen_imbuf(
scene, v3d, ar,
BLEN_THUMB_SIZE * 2, BLEN_THUMB_SIZE * 2,
- IB_rect, false, R_ALPHAPREMUL, 0, false, NULL,
+ IB_rect, V3D_OFSDRAW_NONE, R_ALPHAPREMUL, 0, NULL,
NULL, NULL, err_out);
}
@@ -998,7 +1116,7 @@ static int wm_file_write(bContext *C, const char *filepath, int fileflags, Repor
BKE_reportf(reports, RPT_ERROR, "Cannot save blend file, path '%s' is not writable", filepath);
return ret;
}
-
+
/* note: used to replace the file extension (to ensure '.blend'),
* no need to now because the operator ensures,
* its handy for scripts to save to a predefined name without blender editing it */
@@ -1054,8 +1172,8 @@ static int wm_file_write(bContext *C, const char *filepath, int fileflags, Repor
G.save_over = 1; /* disable untitled.blend convention */
}
- BKE_BIT_TEST_SET(G.fileflags, fileflags & G_FILE_COMPRESS, G_FILE_COMPRESS);
- BKE_BIT_TEST_SET(G.fileflags, fileflags & G_FILE_AUTOPLAY, G_FILE_AUTOPLAY);
+ SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_COMPRESS, G_FILE_COMPRESS);
+ SET_FLAG_FROM_TEST(G.fileflags, fileflags & G_FILE_AUTOPLAY, G_FILE_AUTOPLAY);
/* prevent background mode scripts from clobbering history */
if (do_history) {
@@ -1156,7 +1274,10 @@ void wm_autosave_timer(const bContext *C, wmWindowManager *wm, wmTimer *UNUSED(w
if (U.uiflag & USER_GLOBALUNDO) {
/* fast save of last undobuffer, now with UI */
- BKE_undo_save_file(filepath);
+ struct MemFile *memfile = ED_undosys_stack_memfile_get_active(wm->undo_stack);
+ if (memfile) {
+ BLO_memfile_write_file(memfile, filepath);
+ }
}
else {
/* save as regular blend file */
@@ -1240,13 +1361,13 @@ void wm_open_init_use_scripts(wmOperator *op, bool use_prefs)
/** \} */
-void WM_file_tag_modified(const bContext *C)
+void WM_file_tag_modified(void)
{
- wmWindowManager *wm = CTX_wm_manager(C);
+ wmWindowManager *wm = G.main->wm.first;
if (wm->file_saved) {
wm->file_saved = 0;
/* notifier that data changed, for save-over warning or header */
- WM_event_add_notifier(C, NC_WM | ND_DATACHANGED, NULL);
+ WM_main_add_notifier(NC_WM | ND_DATACHANGED, NULL);
}
}
@@ -1264,6 +1385,13 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op)
char filepath[FILE_MAX];
int fileflags;
+ const char *app_template = U.app_template[0] ? U.app_template : NULL;
+ const char * const cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, app_template);
+ if (cfgdir == NULL) {
+ BKE_report(op->reports, RPT_ERROR, "Unable to create user config path");
+ return OPERATOR_CANCELLED;
+ }
+
BLI_callback_exec(G.main, NULL, BLI_CB_EVT_SAVE_PRE);
/* check current window and close it if temp */
@@ -1273,7 +1401,8 @@ static int wm_homefile_write_exec(bContext *C, wmOperator *op)
/* update keymaps in user preferences */
WM_keyconfig_update(wm);
- BLI_make_file_string("/", filepath, BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL), BLENDER_STARTUP_FILE);
+ BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_STARTUP_FILE, NULL);
+
printf("trying to save homefile at %s ", filepath);
ED_editors_flush_edits(C, false);
@@ -1351,21 +1480,56 @@ static int wm_userpref_write_exec(bContext *C, wmOperator *op)
{
wmWindowManager *wm = CTX_wm_manager(C);
char filepath[FILE_MAX];
+ const char *cfgdir;
+ bool ok = true;
/* update keymaps in user preferences */
WM_keyconfig_update(wm);
- BLI_make_file_string("/", filepath, BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL), BLENDER_USERPREF_FILE);
- printf("trying to save userpref at %s ", filepath);
+ if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, NULL))) {
+ bool ok_write;
+ BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
+ printf("trying to save userpref at %s ", filepath);
- if (BKE_blendfile_write_userdef(filepath, op->reports) == 0) {
- printf("fail\n");
- return OPERATOR_CANCELLED;
+ if (U.app_template[0]) {
+ ok_write = BKE_blendfile_userdef_write_app_template(filepath, op->reports);
+ }
+ else {
+ ok_write = BKE_blendfile_userdef_write(filepath, op->reports);
+ }
+
+ if (ok_write) {
+ printf("ok\n");
+ }
+ else {
+ printf("fail\n");
+ ok = false;
+ }
+ }
+ else {
+ BKE_report(op->reports, RPT_ERROR, "Unable to create userpref path");
}
- printf("ok\n");
+ if (U.app_template[0]) {
+ if ((cfgdir = BKE_appdir_folder_id_create(BLENDER_USER_CONFIG, U.app_template))) {
+ /* Also save app-template prefs */
+ BLI_path_join(filepath, sizeof(filepath), cfgdir, BLENDER_USERPREF_FILE, NULL);
+ printf("trying to save app-template userpref at %s ", filepath);
+ if (BKE_blendfile_userdef_write(filepath, op->reports) != 0) {
+ printf("ok\n");
+ }
+ else {
+ printf("fail\n");
+ ok = false;
+ }
+ }
+ else {
+ BKE_report(op->reports, RPT_ERROR, "Unable to create app-template userpref path");
+ ok = false;
+ }
+ }
- return OPERATOR_FINISHED;
+ return ok ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
}
void WM_OT_save_userpref(wmOperatorType *ot)
@@ -1400,17 +1564,18 @@ void WM_OT_read_history(wmOperatorType *ot)
static int wm_homefile_read_exec(bContext *C, wmOperator *op)
{
- const bool from_memory = (STREQ(op->type->idname, "WM_OT_read_factory_settings"));
+ const bool use_factory_settings = (STREQ(op->type->idname, "WM_OT_read_factory_settings"));
+ bool use_userdef = false;
char filepath_buf[FILE_MAX];
const char *filepath = NULL;
- if (!from_memory) {
+ if (!use_factory_settings) {
PropertyRNA *prop = RNA_struct_find_property(op->ptr, "filepath");
/* This can be used when loading of a start-up file should only change
* the scene content but keep the blender UI as it is. */
wm_open_init_load_ui(op, true);
- BKE_BIT_TEST_SET(G.fileflags, !RNA_boolean_get(op->ptr, "load_ui"), G_FILE_NO_UI);
+ SET_FLAG_FROM_TEST(G.fileflags, !RNA_boolean_get(op->ptr, "load_ui"), G_FILE_NO_UI);
if (RNA_property_is_set(op->ptr, prop)) {
RNA_property_string_get(op->ptr, prop, filepath_buf);
@@ -1424,9 +1589,36 @@ static int wm_homefile_read_exec(bContext *C, wmOperator *op)
else {
/* always load UI for factory settings (prefs will re-init) */
G.fileflags &= ~G_FILE_NO_UI;
+ /* Always load preferences with factory settings. */
+ use_userdef = true;
+ }
+
+ char app_template_buf[sizeof(U.app_template)];
+ const char *app_template;
+ PropertyRNA *prop_app_template = RNA_struct_find_property(op->ptr, "app_template");
+ const bool use_splash = !use_factory_settings && RNA_boolean_get(op->ptr, "use_splash");
+ const bool use_empty_data = RNA_boolean_get(op->ptr, "use_empty");
+
+ if (prop_app_template && RNA_property_is_set(op->ptr, prop_app_template)) {
+ RNA_property_string_get(op->ptr, prop_app_template, app_template_buf);
+ app_template = app_template_buf;
+
+ /* Always load preferences when switching templates. */
+ use_userdef = true;
+ }
+ else {
+ app_template = NULL;
}
- return wm_homefile_read(C, op->reports, from_memory, filepath) ? OPERATOR_FINISHED : OPERATOR_CANCELLED;
+ if (wm_homefile_read(C, op->reports, use_factory_settings, use_empty_data, use_userdef, filepath, app_template)) {
+ if (use_splash) {
+ WM_init_splash(C);
+ }
+ return OPERATOR_FINISHED;
+ }
+ else {
+ return OPERATOR_CANCELLED;
+ }
}
void WM_OT_read_homefile(wmOperatorType *ot)
@@ -1449,17 +1641,36 @@ void WM_OT_read_homefile(wmOperatorType *ot)
"Load user interface setup from the .blend file");
RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+ prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
+ /* So the splash can be kept open after loading a file (for templates). */
+ prop = RNA_def_boolean(ot->srna, "use_splash", false, "Splash", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
+ prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
/* omit poll to run in background mode */
}
void WM_OT_read_factory_settings(wmOperatorType *ot)
{
+ PropertyRNA *prop;
+
ot->name = "Load Factory Settings";
ot->idname = "WM_OT_read_factory_settings";
ot->description = "Load default file and user preferences";
ot->invoke = WM_operator_confirm;
ot->exec = wm_homefile_read_exec;
+
+ prop = RNA_def_string(ot->srna, "app_template", "Template", sizeof(U.app_template), "", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
+ prop = RNA_def_boolean(ot->srna, "use_empty", false, "Empty", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
/* omit poll to run in background mode */
}
@@ -1847,20 +2058,24 @@ static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
fileflags = G.fileflags & ~G_FILE_USERPREFS;
/* set compression flag */
- BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "compress"),
- G_FILE_COMPRESS);
- BKE_BIT_TEST_SET(fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
- G_FILE_RELATIVE_REMAP);
- BKE_BIT_TEST_SET(fileflags,
- (RNA_struct_property_is_set(op->ptr, "copy") &&
- RNA_boolean_get(op->ptr, "copy")),
- G_FILE_SAVE_COPY);
+ SET_FLAG_FROM_TEST(
+ fileflags, RNA_boolean_get(op->ptr, "compress"),
+ G_FILE_COMPRESS);
+ SET_FLAG_FROM_TEST(
+ fileflags, RNA_boolean_get(op->ptr, "relative_remap"),
+ G_FILE_RELATIVE_REMAP);
+ SET_FLAG_FROM_TEST(
+ fileflags,
+ (RNA_struct_property_is_set(op->ptr, "copy") &&
+ RNA_boolean_get(op->ptr, "copy")),
+ G_FILE_SAVE_COPY);
#ifdef USE_BMESH_SAVE_AS_COMPAT
- BKE_BIT_TEST_SET(fileflags,
- (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
- RNA_boolean_get(op->ptr, "use_mesh_compat")),
- G_FILE_MESH_COMPAT);
+ SET_FLAG_FROM_TEST(
+ fileflags,
+ (RNA_struct_find_property(op->ptr, "use_mesh_compat") &&
+ RNA_boolean_get(op->ptr, "use_mesh_compat")),
+ G_FILE_MESH_COMPAT);
#else
# error "don't remove by accident"
#endif
@@ -1870,6 +2085,10 @@ static int wm_save_as_mainfile_exec(bContext *C, wmOperator *op)
WM_event_add_notifier(C, NC_WM | ND_FILESAVE, NULL);
+ if (RNA_boolean_get(op->ptr, "exit")) {
+ wm_exit_schedule_delayed(C);
+ }
+
return OPERATOR_FINISHED;
}
@@ -1941,11 +2160,13 @@ static int wm_save_mainfile_invoke(bContext *C, wmOperator *op, const wmEvent *U
char path[FILE_MAX];
RNA_string_get(op->ptr, "filepath", path);
- if (BLI_exists(path)) {
+ if (RNA_boolean_get(op->ptr, "check_existing") && BLI_exists(path)) {
ret = WM_operator_confirm_message_ex(C, op, IFACE_("Save Over?"), ICON_QUESTION, path);
}
else {
ret = wm_save_as_mainfile_exec(C, op);
+ /* Without this there is no feedback the file was saved. */
+ BKE_reportf(op->reports, RPT_INFO, "Saved \"%s\"", BLI_path_basename(path));
}
}
else {
@@ -1967,12 +2188,16 @@ void WM_OT_save_mainfile(wmOperatorType *ot)
ot->check = blend_save_check;
/* omit window poll so this can work in background mode */
+ PropertyRNA *prop;
WM_operator_properties_filesel(
ot, FILE_TYPE_FOLDER | FILE_TYPE_BLENDER, FILE_BLENDER, FILE_SAVE,
WM_FILESEL_FILEPATH, FILE_DEFAULTDISPLAY, FILE_SORT_ALPHA);
RNA_def_boolean(ot->srna, "compress", false, "Compress", "Write compressed .blend file");
RNA_def_boolean(ot->srna, "relative_remap", false, "Remap Relative",
"Remap relative paths when saving in a different directory");
+
+ prop = RNA_def_boolean(ot->srna, "exit", false, "Exit", "Exit Blender after saving");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
}
/** \} */
diff --git a/source/blender/windowmanager/intern/wm_files_link.c b/source/blender/windowmanager/intern/wm_files_link.c
index 3b733f9558c..fb611290aa5 100644
--- a/source/blender/windowmanager/intern/wm_files_link.c
+++ b/source/blender/windowmanager/intern/wm_files_link.c
@@ -157,7 +157,7 @@ typedef struct WMLinkAppendData {
LinkNodePair items;
int num_libraries;
int num_items;
- short flag;
+ int flag; /* Combines eFileSel_Params_Flag from DNA_space_types.h and BLO_LibLinkFlags from BLO_readfile.h */
/* Internal 'private' data */
MemArena *memarena;
@@ -211,9 +211,7 @@ static WMLinkAppendDataItem *wm_link_append_data_item_add(
return item;
}
-static void wm_link_do(
- WMLinkAppendData *lapp_data, ReportList *reports, Main *bmain, Scene *scene, View3D *v3d,
- const bool use_placeholders, const bool force_indirect)
+static void wm_link_do(WMLinkAppendData *lapp_data, ReportList *reports, Main *bmain, Scene *scene, View3D *v3d)
{
Main *mainl;
BlendHandle *bh;
@@ -260,8 +258,7 @@ static void wm_link_do(
continue;
}
- new_id = BLO_library_link_named_part_ex(
- mainl, &bh, item->idcode, item->name, flag, scene, v3d, use_placeholders, force_indirect);
+ new_id = BLO_library_link_named_part_ex(mainl, &bh, item->idcode, item->name, flag, scene, v3d);
if (new_id) {
/* If the link is successful, clear item's libs 'todo' flags.
@@ -282,10 +279,9 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
Scene *scene = CTX_data_scene(C);
PropertyRNA *prop;
WMLinkAppendData *lapp_data;
- char path[FILE_MAX_LIBEXTRA], root[FILE_MAXDIR], libname[FILE_MAX], relname[FILE_MAX];
+ char path[FILE_MAX_LIBEXTRA], root[FILE_MAXDIR], libname[FILE_MAX_LIBEXTRA], relname[FILE_MAX];
char *group, *name;
int totfiles = 0;
- short flag;
RNA_string_get(op->ptr, "filename", relname);
RNA_string_get(op->ptr, "directory", root);
@@ -322,7 +318,7 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
return OPERATOR_CANCELLED;
}
- flag = wm_link_append_flag(op);
+ short flag = wm_link_append_flag(op);
/* sanity checks for flag */
if (scene && scene->id.lib) {
@@ -332,6 +328,8 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
scene = NULL;
}
+ /* We need to add nothing from BLO_LibLinkFlags to flag here. */
+
/* from here down, no error returns */
if (scene && RNA_boolean_get(op->ptr, "autoselect")) {
@@ -402,10 +400,16 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
BLI_BITMAP_ENABLE(item->libraries, 0);
}
+ if (lapp_data->num_items == 0) {
+ /* Early out in case there is nothing to link. */
+ wm_link_append_data_free(lapp_data);
+ return OPERATOR_CANCELLED;
+ }
+
/* XXX We'd need re-entrant locking on Main for this to work... */
/* BKE_main_lock(bmain); */
- wm_link_do(lapp_data, op->reports, bmain, scene, CTX_wm_view3d(C), false, false);
+ wm_link_do(lapp_data, op->reports, bmain, scene, CTX_wm_view3d(C));
/* BKE_main_unlock(bmain); */
@@ -446,7 +450,9 @@ static int wm_link_append_exec(bContext *C, wmOperator *op)
BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, false);
/* recreate dependency graph to include new objects */
- DAG_scene_relations_rebuild(bmain, scene);
+ if (scene) {
+ DAG_scene_relations_rebuild(bmain, scene);
+ }
/* free gpu materials, some materials depend on existing objects, such as lamps so freeing correctly refreshes */
GPU_materials_free();
@@ -589,10 +595,15 @@ static void lib_relocate_do(
}
}
+ if (lapp_data->num_items == 0) {
+ /* Early out in case there is nothing to do. */
+ return;
+ }
+
BKE_main_id_tag_all(bmain, LIB_TAG_PRE_EXISTING, true);
/* We do not want any instanciation here! */
- wm_link_do(lapp_data, reports, bmain, NULL, NULL, do_reload, do_reload);
+ wm_link_do(lapp_data, reports, bmain, NULL, NULL);
BKE_main_lock(bmain);
@@ -608,7 +619,8 @@ static void lib_relocate_do(
}
/* Note that in reload case, we also want to replace indirect usages. */
- const short remap_flags = ID_REMAP_SKIP_NEVER_NULL_USAGE | (do_reload ? 0 : ID_REMAP_SKIP_INDIRECT_USAGE);
+ const short remap_flags = ID_REMAP_SKIP_NEVER_NULL_USAGE | ID_REMAP_NO_INDIRECT_PROXY_DATA_USAGE |
+ (do_reload ? 0 : ID_REMAP_SKIP_INDIRECT_USAGE);
for (item_idx = 0, itemlink = lapp_data->items.list; itemlink; item_idx++, itemlink = itemlink->next) {
WMLinkAppendDataItem *item = itemlink->link;
ID *old_id = item->customdata;
@@ -755,7 +767,7 @@ void WM_lib_reload(Library *lib, bContext *C, ReportList *reports)
return;
}
- WMLinkAppendData *lapp_data = wm_link_append_data_new(0);
+ WMLinkAppendData *lapp_data = wm_link_append_data_new(BLO_LIBLINK_USE_PLACEHOLDERS | BLO_LIBLINK_FORCE_INDIRECT);
wm_link_append_data_library_add(lapp_data, lib->filepath);
@@ -866,6 +878,10 @@ static int wm_lib_relocate_exec_do(bContext *C, wmOperator *op, bool do_reload)
}
}
+ if (do_reload) {
+ lapp_data->flag |= BLO_LIBLINK_USE_PLACEHOLDERS | BLO_LIBLINK_FORCE_INDIRECT;
+ }
+
lib_relocate_do(bmain, scene, lib, lapp_data, op->reports, do_reload);
wm_link_append_data_free(lapp_data);
diff --git a/source/blender/windowmanager/intern/wm_gesture.c b/source/blender/windowmanager/intern/wm_gesture.c
index 46203333eb5..1a4381a1275 100644
--- a/source/blender/windowmanager/intern/wm_gesture.c
+++ b/source/blender/windowmanager/intern/wm_gesture.c
@@ -41,7 +41,7 @@
#include "BLI_blenlib.h"
#include "BLI_math.h"
#include "BLI_utildefines.h"
-#include "BLI_lasso.h"
+#include "BLI_lasso_2d.h"
#include "BKE_context.h"
@@ -71,6 +71,8 @@ wmGesture *WM_gesture_new(bContext *C, const wmEvent *event, int type)
gesture->type = type;
gesture->event_type = event->type;
gesture->swinid = ar->swinid; /* means only in area-region context! */
+ gesture->userdata_free = true; /* Free if userdata is set. */
+ gesture->modal_state = GESTURE_MODAL_NOP;
wm_subwindow_origin_get(window, gesture->swinid, &sx, &sy);
@@ -83,11 +85,7 @@ wmGesture *WM_gesture_new(bContext *C, const wmEvent *event, int type)
rect->xmin = event->x - sx;
rect->ymin = event->y - sy;
if (type == WM_GESTURE_CIRCLE) {
-#ifdef GESTURE_MEMORY
- rect->xmax = circle_select_size;
-#else
- rect->xmax = 25; // XXX temp
-#endif
+ /* caller is responsible for initializing 'xmax' to radius. */
}
else {
rect->xmax = event->x - sx;
@@ -96,11 +94,11 @@ wmGesture *WM_gesture_new(bContext *C, const wmEvent *event, int type)
}
else if (ELEM(type, WM_GESTURE_LINES, WM_GESTURE_LASSO)) {
short *lasso;
- gesture->customdata = lasso = MEM_callocN(2 * sizeof(short) * WM_LASSO_MIN_POINTS, "lasso points");
+ gesture->points_alloc = 1024;
+ gesture->customdata = lasso = MEM_mallocN(sizeof(short[2]) * gesture->points_alloc, "lasso points");
lasso[0] = event->x - sx;
lasso[1] = event->y - sy;
gesture->points = 1;
- gesture->size = WM_LASSO_MIN_POINTS;
}
return gesture;
@@ -114,7 +112,7 @@ void WM_gesture_end(bContext *C, wmGesture *gesture)
win->tweak = NULL;
BLI_remlink(&win->gesture, gesture);
MEM_freeN(gesture->customdata);
- if (gesture->userdata) {
+ if (gesture->userdata && gesture->userdata_free) {
MEM_freeN(gesture->userdata);
}
MEM_freeN(gesture);
@@ -137,7 +135,7 @@ int wm_gesture_evaluate(wmGesture *gesture)
int dx = BLI_rcti_size_x(rect);
int dy = BLI_rcti_size_y(rect);
if (abs(dx) + abs(dy) > U.tweak_threshold) {
- int theta = iroundf(4.0f * atan2f((float)dy, (float)dx) / (float)M_PI);
+ int theta = round_fl_to_int(4.0f * atan2f((float)dy, (float)dx) / (float)M_PI);
int val = EVT_GESTURE_W;
if (theta == 0) val = EVT_GESTURE_E;
@@ -376,10 +374,12 @@ void wm_gesture_draw(wmWindow *win)
else if (gt->type == WM_GESTURE_CIRCLE)
wm_gesture_draw_circle(gt);
else if (gt->type == WM_GESTURE_CROSS_RECT) {
- if (gt->mode == 1)
+ if (gt->is_active) {
wm_gesture_draw_rect(gt);
- else
+ }
+ else {
wm_gesture_draw_cross(win, gt);
+ }
}
else if (gt->type == WM_GESTURE_LINES)
wm_gesture_draw_lasso(win, gt, false);
diff --git a/source/blender/windowmanager/intern/wm_gesture_ops.c b/source/blender/windowmanager/intern/wm_gesture_ops.c
new file mode 100644
index 00000000000..a554727cacd
--- /dev/null
+++ b/source/blender/windowmanager/intern/wm_gesture_ops.c
@@ -0,0 +1,883 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * The Original Code is Copyright (C) 2007 Blender Foundation.
+ * All rights reserved.
+ *
+ * Contributor(s): Blender Foundation
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/windowmanager/intern/wm_gesture_ops.c
+ * \ingroup wm
+ *
+ * Default operator callbacks for use with gestures (border/circle/lasso/straightline).
+ * Operators themselves are defined elsewhere.
+ *
+ * - Keymaps are in ``wm_operators.c``.
+ * - Property definitions are in ``wm_operator_props.c``.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "DNA_windowmanager_types.h"
+
+#include "BLI_math.h"
+
+#include "BKE_context.h"
+
+#include "WM_types.h"
+#include "WM_api.h"
+
+#include "wm.h"
+#include "wm_event_types.h"
+#include "wm_event_system.h"
+#include "wm_subwindow.h"
+
+#include "ED_screen.h"
+
+#include "RNA_access.h"
+#include "RNA_define.h"
+
+/* -------------------------------------------------------------------- */
+/** \name Internal Gesture Utilities
+ *
+ * Border gesture has two types:
+ * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
+ * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
+ *
+ * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type).
+ *
+ * \{ */
+
+static void gesture_modal_end(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+
+ WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
+ op->customdata = NULL;
+
+ ED_area_tag_redraw(CTX_wm_area(C));
+
+ if (RNA_struct_find_property(op->ptr, "cursor")) {
+ WM_cursor_modal_restore(CTX_wm_window(C));
+ }
+}
+
+static void gesture_modal_state_to_operator(wmOperator *op, int modal_state)
+{
+ PropertyRNA *prop;
+
+ switch (modal_state) {
+ case GESTURE_MODAL_SELECT:
+ case GESTURE_MODAL_DESELECT:
+ if ((prop = RNA_struct_find_property(op->ptr, "deselect"))) {
+ RNA_property_boolean_set(op->ptr, prop, (modal_state == GESTURE_MODAL_DESELECT));
+ }
+ break;
+ case GESTURE_MODAL_IN:
+ case GESTURE_MODAL_OUT:
+ if ((prop = RNA_struct_find_property(op->ptr, "zoom_out"))) {
+ RNA_property_boolean_set(op->ptr, prop, (modal_state == GESTURE_MODAL_OUT));
+ }
+ break;
+ }
+}
+
+static int gesture_modal_state_from_operator(wmOperator *op)
+{
+ PropertyRNA *prop;
+
+ if ((prop = RNA_struct_find_property(op->ptr, "deselect"))) {
+ if (RNA_property_is_set(op->ptr, prop)) {
+ return RNA_property_boolean_get(op->ptr, prop) ? GESTURE_MODAL_DESELECT : GESTURE_MODAL_SELECT;
+ }
+ }
+ if ((prop = RNA_struct_find_property(op->ptr, "zoom_out"))) {
+ if (RNA_property_is_set(op->ptr, prop)) {
+ return RNA_property_boolean_get(op->ptr, prop) ? GESTURE_MODAL_OUT : GESTURE_MODAL_IN;
+ }
+ }
+ return GESTURE_MODAL_NOP;
+}
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Border Gesture
+ *
+ * Border gesture has two types:
+ * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
+ * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
+ *
+ * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type).
+ *
+ * \{ */
+
+static bool gesture_border_apply_rect(wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+
+ if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
+ return 0;
+
+
+ /* operator arguments and storage. */
+ RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
+ RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
+ RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
+ RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
+
+ return 1;
+}
+
+static bool gesture_border_apply(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+
+ int retval;
+
+ if (!gesture_border_apply_rect(op)) {
+ return 0;
+ }
+
+ gesture_modal_state_to_operator(op, gesture->modal_state);
+
+ retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+
+ return 1;
+}
+
+int WM_gesture_border_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ int modal_state = gesture_modal_state_from_operator(op);
+
+ if (ISTWEAK(event->type) || (modal_state != GESTURE_MODAL_NOP)) {
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
+ }
+ else {
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
+ }
+
+ /* Starting with the mode starts immediately, like having 'wait_for_input' disabled (some tools use this). */
+ if (modal_state == GESTURE_MODAL_NOP) {
+ wmGesture *gesture = op->customdata;
+ gesture->wait_for_input = true;
+ }
+ else {
+ wmGesture *gesture = op->customdata;
+ gesture->modal_state = modal_state;
+ }
+
+ /* add modal handler */
+ WM_event_add_modal_handler(C, op);
+
+ wm_gesture_tag_redraw(C);
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+int WM_gesture_border_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+ int sx, sy;
+
+ if (event->type == MOUSEMOVE) {
+ wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
+
+ if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->is_active == false) {
+ rect->xmin = rect->xmax = event->x - sx;
+ rect->ymin = rect->ymax = event->y - sy;
+ }
+ else {
+ rect->xmax = event->x - sx;
+ rect->ymax = event->y - sy;
+ }
+ gesture_border_apply_rect(op);
+
+ wm_gesture_tag_redraw(C);
+ }
+ else if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case GESTURE_MODAL_BEGIN:
+ if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->is_active == false) {
+ gesture->is_active = true;
+ wm_gesture_tag_redraw(C);
+ }
+ break;
+ case GESTURE_MODAL_SELECT:
+ case GESTURE_MODAL_DESELECT:
+ case GESTURE_MODAL_IN:
+ case GESTURE_MODAL_OUT:
+ if (gesture->wait_for_input) {
+ gesture->modal_state = event->val;
+ }
+ if (gesture_border_apply(C, op)) {
+ gesture_modal_end(C, op);
+ return OPERATOR_FINISHED;
+ }
+ gesture_modal_end(C, op);
+ return OPERATOR_CANCELLED;
+
+ case GESTURE_MODAL_CANCEL:
+ gesture_modal_end(C, op);
+ return OPERATOR_CANCELLED;
+ }
+
+ }
+#ifdef WITH_INPUT_NDOF
+ else if (event->type == NDOF_MOTION) {
+ return OPERATOR_PASS_THROUGH;
+ }
+#endif
+
+#if 0
+ /* Allow view navigation??? */
+ else {
+ return OPERATOR_PASS_THROUGH;
+ }
+#endif
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+void WM_gesture_border_cancel(bContext *C, wmOperator *op)
+{
+ gesture_modal_end(C, op);
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Circle Gesture
+ *
+ * Currently only used for selection or modal paint stuff,
+ * calls ``exec`` while hold mouse, exits on release (with no difference between cancel and confirm).
+ *
+ * \{ */
+
+static void gesture_circle_apply(bContext *C, wmOperator *op);
+
+int WM_gesture_circle_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ int modal_state = gesture_modal_state_from_operator(op);
+
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+
+ /* Default or previously stored value. */
+ rect->xmax = RNA_int_get(op->ptr, "radius");
+
+ /* Starting with the mode starts immediately, like having 'wait_for_input' disabled (some tools use this). */
+ if (modal_state == GESTURE_MODAL_NOP) {
+ gesture->wait_for_input = true;
+ }
+ else {
+ gesture->is_active = true;
+ gesture->modal_state = modal_state;
+ gesture_circle_apply(C, op);
+ }
+
+ /* add modal handler */
+ WM_event_add_modal_handler(C, op);
+
+ wm_gesture_tag_redraw(C);
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+static void gesture_circle_apply(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+
+ if (gesture->modal_state == GESTURE_MODAL_NOP) {
+ return;
+ }
+
+ /* operator arguments and storage. */
+ RNA_int_set(op->ptr, "x", rect->xmin);
+ RNA_int_set(op->ptr, "y", rect->ymin);
+ RNA_int_set(op->ptr, "radius", rect->xmax);
+
+ gesture_modal_state_to_operator(op, gesture->modal_state);
+
+ if (op->type->exec) {
+ int retval;
+ retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
+}
+
+int WM_gesture_circle_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+ int sx, sy;
+
+ if (event->type == MOUSEMOVE) {
+ wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
+
+ rect->xmin = event->x - sx;
+ rect->ymin = event->y - sy;
+
+ wm_gesture_tag_redraw(C);
+
+ if (gesture->is_active) {
+ gesture_circle_apply(C, op);
+ }
+ }
+ else if (event->type == EVT_MODAL_MAP) {
+ bool is_circle_size = false;
+ bool is_finished = false;
+ float fac;
+
+ switch (event->val) {
+ case GESTURE_MODAL_CIRCLE_SIZE:
+ fac = 0.3f * (event->y - event->prevy);
+ if (fac > 0)
+ rect->xmax += ceil(fac);
+ else
+ rect->xmax += floor(fac);
+ if (rect->xmax < 1) rect->xmax = 1;
+ is_circle_size = true;
+ break;
+ case GESTURE_MODAL_CIRCLE_ADD:
+ rect->xmax += 2 + rect->xmax / 10;
+ is_circle_size = true;
+ break;
+ case GESTURE_MODAL_CIRCLE_SUB:
+ rect->xmax -= 2 + rect->xmax / 10;
+ if (rect->xmax < 1) rect->xmax = 1;
+ is_circle_size = true;
+ break;
+ case GESTURE_MODAL_SELECT:
+ case GESTURE_MODAL_DESELECT:
+ case GESTURE_MODAL_NOP:
+ {
+ if (gesture->wait_for_input) {
+ gesture->modal_state = event->val;
+ }
+ if (event->val == GESTURE_MODAL_NOP) {
+ /* Single action, click-drag & release to exit. */
+ if (gesture->wait_for_input == false) {
+ is_finished = true;
+ }
+ }
+ else {
+ /* apply first click */
+ gesture_circle_apply(C, op);
+ gesture->is_active = true;
+ wm_gesture_tag_redraw(C);
+ }
+ break;
+ }
+ case GESTURE_MODAL_CANCEL:
+ case GESTURE_MODAL_CONFIRM:
+ is_finished = true;
+ }
+
+ if (is_finished) {
+ gesture_modal_end(C, op);
+ return OPERATOR_FINISHED; /* use finish or we don't get an undo */
+ }
+
+ if (is_circle_size) {
+ wm_gesture_tag_redraw(C);
+
+ /* So next use remembers last seen size, even if we didn't apply it. */
+ RNA_int_set(op->ptr, "radius", rect->xmax);
+ }
+ }
+#ifdef WITH_INPUT_NDOF
+ else if (event->type == NDOF_MOTION) {
+ return OPERATOR_PASS_THROUGH;
+ }
+#endif
+
+#if 0
+ /* Allow view navigation??? */
+ /* note, this gives issues:
+ * 1) other modal ops run on top (border select),
+ * 2) middlemouse is used now 3) tablet/trackpad? */
+ else {
+ return OPERATOR_PASS_THROUGH;
+ }
+#endif
+
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+void WM_gesture_circle_cancel(bContext *C, wmOperator *op)
+{
+ gesture_modal_end(C, op);
+}
+
+#if 0
+/* template to copy from */
+void WM_OT_circle_gesture(wmOperatorType *ot)
+{
+ ot->name = "Circle Gesture";
+ ot->idname = "WM_OT_circle_gesture";
+ ot->description = "Enter rotate mode with a circular gesture";
+
+ ot->invoke = WM_gesture_circle_invoke;
+ ot->modal = WM_gesture_circle_modal;
+ ot->poll = WM_operator_winactive;
+
+ /* properties */
+ WM_operator_properties_gesture_circle(ot);
+
+}
+#endif
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Tweak Gesture
+ * \{ */
+
+static void gesture_tweak_modal(bContext *C, const wmEvent *event)
+{
+ wmWindow *window = CTX_wm_window(C);
+ wmGesture *gesture = window->tweak;
+ rcti *rect = gesture->customdata;
+ int sx, sy, val;
+
+ switch (event->type) {
+ case MOUSEMOVE:
+ case INBETWEEN_MOUSEMOVE:
+
+ wm_subwindow_origin_get(window, gesture->swinid, &sx, &sy);
+
+ rect->xmax = event->x - sx;
+ rect->ymax = event->y - sy;
+
+ if ((val = wm_gesture_evaluate(gesture))) {
+ wmEvent tevent;
+
+ wm_event_init_from_window(window, &tevent);
+ /* We want to get coord from start of drag, not from point where it becomes a tweak event, see T40549 */
+ tevent.x = rect->xmin + sx;
+ tevent.y = rect->ymin + sy;
+ if (gesture->event_type == LEFTMOUSE)
+ tevent.type = EVT_TWEAK_L;
+ else if (gesture->event_type == RIGHTMOUSE)
+ tevent.type = EVT_TWEAK_R;
+ else
+ tevent.type = EVT_TWEAK_M;
+ tevent.val = val;
+ /* mouse coords! */
+
+ /* important we add immediately after this event, so future mouse releases
+ * (which may be in the queue already), are handled in order, see T44740 */
+ wm_event_add_ex(window, &tevent, event);
+
+ WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
+ }
+
+ break;
+
+ case LEFTMOUSE:
+ case RIGHTMOUSE:
+ case MIDDLEMOUSE:
+ if (gesture->event_type == event->type) {
+ WM_gesture_end(C, gesture);
+
+ /* when tweak fails we should give the other keymap entries a chance */
+
+ /* XXX, assigning to readonly, BAD JUJU! */
+ ((wmEvent *)event)->val = KM_RELEASE;
+ }
+ break;
+ default:
+ if (!ISTIMER(event->type) && event->type != EVENT_NONE) {
+ WM_gesture_end(C, gesture);
+ }
+ break;
+ }
+}
+
+/* standard tweak, called after window handlers passed on event */
+void wm_tweakevent_test(bContext *C, const wmEvent *event, int action)
+{
+ wmWindow *win = CTX_wm_window(C);
+
+ if (win->tweak == NULL) {
+ if (CTX_wm_region(C)) {
+ if (event->val == KM_PRESS) {
+ if (ELEM(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE)) {
+ win->tweak = WM_gesture_new(C, event, WM_GESTURE_TWEAK);
+ }
+ }
+ }
+ }
+ else {
+ /* no tweaks if event was handled */
+ if ((action & WM_HANDLER_BREAK)) {
+ WM_gesture_end(C, win->tweak);
+ }
+ else
+ gesture_tweak_modal(C, event);
+ }
+}
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Lasso Gesture
+ * \{ */
+
+int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ PropertyRNA *prop;
+
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_LASSO);
+
+ /* add modal handler */
+ WM_event_add_modal_handler(C, op);
+
+ wm_gesture_tag_redraw(C);
+
+ if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
+ WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+int WM_gesture_lines_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ PropertyRNA *prop;
+
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_LINES);
+
+ /* add modal handler */
+ WM_event_add_modal_handler(C, op);
+
+ wm_gesture_tag_redraw(C);
+
+ if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
+ WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+
+static void gesture_lasso_apply(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+ PointerRNA itemptr;
+ float loc[2];
+ int i;
+ const short *lasso = gesture->customdata;
+
+ /* operator storage as path. */
+
+ RNA_collection_clear(op->ptr, "path");
+ for (i = 0; i < gesture->points; i++, lasso += 2) {
+ loc[0] = lasso[0];
+ loc[1] = lasso[1];
+ RNA_collection_add(op->ptr, "path", &itemptr);
+ RNA_float_set_array(&itemptr, "loc", loc);
+ }
+
+ gesture_modal_end(C, op);
+
+ if (op->type->exec) {
+ int retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
+}
+
+int WM_gesture_lasso_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ wmGesture *gesture = op->customdata;
+ int sx, sy;
+
+ switch (event->type) {
+ case MOUSEMOVE:
+ case INBETWEEN_MOUSEMOVE:
+
+ wm_gesture_tag_redraw(C);
+
+ wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
+
+ if (gesture->points == gesture->points_alloc) {
+ gesture->points_alloc *= 2;
+ gesture->customdata = MEM_reallocN(gesture->customdata, sizeof(short[2]) * gesture->points_alloc);
+ }
+
+ {
+ int x, y;
+ short *lasso = gesture->customdata;
+
+ lasso += (2 * gesture->points - 2);
+ x = (event->x - sx - lasso[0]);
+ y = (event->y - sy - lasso[1]);
+
+ /* make a simple distance check to get a smoother lasso
+ * add only when at least 2 pixels between this and previous location */
+ if ((x * x + y * y) > 4) {
+ lasso += 2;
+ lasso[0] = event->x - sx;
+ lasso[1] = event->y - sy;
+ gesture->points++;
+ }
+ }
+ break;
+
+ case LEFTMOUSE:
+ case MIDDLEMOUSE:
+ case RIGHTMOUSE:
+ if (event->val == KM_RELEASE) { /* key release */
+ gesture_lasso_apply(C, op);
+ return OPERATOR_FINISHED;
+ }
+ break;
+ case ESCKEY:
+ gesture_modal_end(C, op);
+ return OPERATOR_CANCELLED;
+ }
+ return OPERATOR_RUNNING_MODAL;
+}
+
+int WM_gesture_lines_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ return WM_gesture_lasso_modal(C, op, event);
+}
+
+void WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
+{
+ gesture_modal_end(C, op);
+}
+
+void WM_gesture_lines_cancel(bContext *C, wmOperator *op)
+{
+ gesture_modal_end(C, op);
+}
+
+/**
+ * helper function, we may want to add options for conversion to view space
+ *
+ * caller must free.
+ */
+const int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
+{
+ PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
+ int (*mcords)[2] = NULL;
+ BLI_assert(prop != NULL);
+
+ if (prop) {
+ const int len = RNA_property_collection_length(op->ptr, prop);
+
+ if (len) {
+ int i = 0;
+ mcords = MEM_mallocN(sizeof(int) * 2 * len, __func__);
+
+ RNA_PROP_BEGIN (op->ptr, itemptr, prop)
+ {
+ float loc[2];
+
+ RNA_float_get_array(&itemptr, "loc", loc);
+ mcords[i][0] = (int)loc[0];
+ mcords[i][1] = (int)loc[1];
+ i++;
+ }
+ RNA_PROP_END;
+ }
+ *mcords_tot = len;
+ }
+ else {
+ *mcords_tot = 0;
+ }
+
+ /* cast for 'const' */
+ return (const int (*)[2])mcords;
+}
+
+#if 0
+/* template to copy from */
+
+static int gesture_lasso_exec(bContext *C, wmOperator *op)
+{
+ RNA_BEGIN (op->ptr, itemptr, "path")
+ {
+ float loc[2];
+
+ RNA_float_get_array(&itemptr, "loc", loc);
+ printf("Location: %f %f\n", loc[0], loc[1]);
+ }
+ RNA_END;
+
+ return OPERATOR_FINISHED;
+}
+
+void WM_OT_lasso_gesture(wmOperatorType *ot)
+{
+ PropertyRNA *prop;
+
+ ot->name = "Lasso Gesture";
+ ot->idname = "WM_OT_lasso_gesture";
+ ot->description = "Select objects within the lasso as you move the pointer";
+
+ ot->invoke = WM_gesture_lasso_invoke;
+ ot->modal = WM_gesture_lasso_modal;
+ ot->exec = gesture_lasso_exec;
+
+ ot->poll = WM_operator_winactive;
+
+ prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
+ RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
+}
+#endif
+
+
+/** \} */
+
+
+/* -------------------------------------------------------------------- */
+/** \name Straight Line Gesture
+ * \{ */
+
+static bool gesture_straightline_apply(bContext *C, wmOperator *op)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+
+ if (rect->xmin == rect->xmax && rect->ymin == rect->ymax)
+ return 0;
+
+ /* operator arguments and storage. */
+ RNA_int_set(op->ptr, "xstart", rect->xmin);
+ RNA_int_set(op->ptr, "ystart", rect->ymin);
+ RNA_int_set(op->ptr, "xend", rect->xmax);
+ RNA_int_set(op->ptr, "yend", rect->ymax);
+
+ if (op->type->exec) {
+ int retval = op->type->exec(C, op);
+ OPERATOR_RETVAL_CHECK(retval);
+ }
+
+ return 1;
+}
+
+int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ PropertyRNA *prop;
+
+ op->customdata = WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
+
+ if (ISTWEAK(event->type)) {
+ wmGesture *gesture = op->customdata;
+ gesture->is_active = true;
+ }
+
+ /* add modal handler */
+ WM_event_add_modal_handler(C, op);
+
+ wm_gesture_tag_redraw(C);
+
+ if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
+ WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+int WM_gesture_straightline_modal(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ wmGesture *gesture = op->customdata;
+ rcti *rect = gesture->customdata;
+ int sx, sy;
+
+ if (event->type == MOUSEMOVE) {
+ wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
+
+ if (gesture->is_active == false) {
+ rect->xmin = rect->xmax = event->x - sx;
+ rect->ymin = rect->ymax = event->y - sy;
+ }
+ else {
+ rect->xmax = event->x - sx;
+ rect->ymax = event->y - sy;
+ gesture_straightline_apply(C, op);
+ }
+
+ wm_gesture_tag_redraw(C);
+ }
+ else if (event->type == EVT_MODAL_MAP) {
+ switch (event->val) {
+ case GESTURE_MODAL_BEGIN:
+ if (gesture->is_active == false) {
+ gesture->is_active = true;
+ wm_gesture_tag_redraw(C);
+ }
+ break;
+ case GESTURE_MODAL_SELECT:
+ if (gesture_straightline_apply(C, op)) {
+ gesture_modal_end(C, op);
+ return OPERATOR_FINISHED;
+ }
+ gesture_modal_end(C, op);
+ return OPERATOR_CANCELLED;
+
+ case GESTURE_MODAL_CANCEL:
+ gesture_modal_end(C, op);
+ return OPERATOR_CANCELLED;
+ }
+ }
+
+ return OPERATOR_RUNNING_MODAL;
+}
+
+void WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
+{
+ gesture_modal_end(C, op);
+}
+
+#if 0
+/* template to copy from */
+void WM_OT_straightline_gesture(wmOperatorType *ot)
+{
+ PropertyRNA *prop;
+
+ ot->name = "Straight Line Gesture";
+ ot->idname = "WM_OT_straightline_gesture";
+ ot->description = "Draw a straight line as you move the pointer";
+
+ ot->invoke = WM_gesture_straightline_invoke;
+ ot->modal = WM_gesture_straightline_modal;
+ ot->exec = gesture_straightline_exec;
+
+ ot->poll = WM_operator_winactive;
+
+ WM_operator_properties_gesture_straightline(ot, 0);
+}
+#endif
+
+/** \} */
diff --git a/source/blender/windowmanager/intern/wm_init_exit.c b/source/blender/windowmanager/intern/wm_init_exit.c
index c11c398c616..52682523212 100644
--- a/source/blender/windowmanager/intern/wm_init_exit.c
+++ b/source/blender/windowmanager/intern/wm_init_exit.c
@@ -40,6 +40,8 @@
#include "MEM_guardedalloc.h"
+#include "CLG_log.h"
+
#include "DNA_genfile.h"
#include "DNA_scene_types.h"
#include "DNA_userdef_types.h"
@@ -53,6 +55,7 @@
#include "BLI_utildefines.h"
#include "BLO_writefile.h"
+#include "BLO_undofile.h"
#include "BKE_blender.h"
#include "BKE_blender_undo.h"
@@ -110,6 +113,7 @@
#include "ED_space_api.h"
#include "ED_screen.h"
#include "ED_util.h"
+#include "ED_undo.h"
#include "UI_interface.h"
#include "BLF_api.h"
@@ -127,6 +131,11 @@
# include "BKE_subsurf.h"
#endif
+CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_OPERATORS, "wm.operator");
+CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_HANDLERS, "wm.handler");
+CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_EVENTS, "wm.event");
+CLG_LOGREF_DECLARE_GLOBAL(WM_LOG_KEYMAPS, "wm.keymap");
+
static void wm_init_reports(bContext *C)
{
ReportList *reports = CTX_wm_reports(C);
@@ -142,11 +151,6 @@ static void wm_free_reports(bContext *C)
BKE_reports_clear(reports);
}
-static void wm_undo_kill_callback(bContext *C)
-{
- WM_jobs_kill_all_except(CTX_wm_manager(C), CTX_wm_screen(C));
-}
-
bool wm_start_with_console = false; /* used in creator.c */
/* only called once, for startup */
@@ -165,7 +169,7 @@ void WM_init(bContext *C, int argc, const char **argv)
WM_menutype_init();
WM_uilisttype_init();
- BKE_undo_callback_wm_kill_jobs_set(wm_undo_kill_callback);
+ ED_undosys_type_init();
BKE_library_callback_free_window_manager_set(wm_close_and_free); /* library.c */
BKE_library_callback_free_notifier_reference_set(WM_main_remove_notifier_reference); /* library.c */
@@ -181,18 +185,15 @@ void WM_init(bContext *C, int argc, const char **argv)
ED_file_init(); /* for fsmenu */
ED_node_init_butfuncs();
- BLF_init(11, U.dpi); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
+ BLF_init(); /* Please update source/gamengine/GamePlayer/GPG_ghost.cpp if you change this */
BLT_lang_init();
- /* Enforce loading the UI for the initial homefile */
- G.fileflags &= ~G_FILE_NO_UI;
-
/* reports cant be initialized before the wm,
* but keep before file reading, since that may report errors */
wm_init_reports(C);
/* get the default database, plus a wm */
- wm_homefile_read(C, NULL, G.factory_startup, NULL);
+ wm_homefile_read(C, NULL, G.factory_startup, false, true, NULL, NULL);
BLT_lang_set(NULL);
@@ -437,6 +438,29 @@ static void wait_for_console_key(void)
}
#endif
+static int wm_exit_handler(bContext *C, const wmEvent *event, void *userdata)
+{
+ WM_exit(C);
+
+ UNUSED_VARS(event, userdata);
+ return WM_UI_HANDLER_BREAK;
+}
+
+/**
+ * Cause a delayed WM_exit() call to avoid leaking memory when trying to exit from within operators.
+ */
+void wm_exit_schedule_delayed(const bContext *C)
+{
+ /* What we do here is a little bit hacky, but quite simple and doesn't require bigger
+ * changes: Add a handler wrapping WM_exit() to cause a delayed call of it. */
+
+ wmWindow *win = CTX_wm_window(C);
+
+ /* Use modal UI handler for now. Could add separate WM handlers or so, but probably not worth it. */
+ WM_event_add_ui_handler(C, &win->modalhandlers, wm_exit_handler, NULL, NULL, 0);
+ WM_event_add_mousemove(C); /* ensure handler actually gets called */
+}
+
/**
* \note doesn't run exit() call #WM_exit() for that.
*/
@@ -444,8 +468,6 @@ void WM_exit_ext(bContext *C, const bool do_python)
{
wmWindowManager *wm = C ? CTX_wm_manager(C) : NULL;
- BKE_sound_exit();
-
/* first wrap up running stuff, we assume only the active WM is running */
/* modal handlers are on window level freed, others too? */
/* note; same code copied in wm_files.c */
@@ -453,7 +475,8 @@ void WM_exit_ext(bContext *C, const bool do_python)
wmWindow *win;
if (!G.background) {
- if ((U.uiflag2 & USER_KEEP_SESSION) || BKE_undo_is_valid(NULL)) {
+ struct MemFile *undo_memfile = wm->undo_stack ? ED_undosys_stack_memfile_get_active(wm->undo_stack) : NULL;
+ if ((U.uiflag2 & USER_KEEP_SESSION) || (undo_memfile != NULL)) {
/* save the undo state as quit.blend */
char filename[FILE_MAX];
bool has_edited;
@@ -464,7 +487,7 @@ void WM_exit_ext(bContext *C, const bool do_python)
has_edited = ED_editors_flush_edits(C, false);
if ((has_edited && BLO_write_file(CTX_data_main(C), filename, fileflags, NULL, NULL)) ||
- BKE_undo_save_file(filename))
+ (undo_memfile && BLO_memfile_write_file(undo_memfile, filename)))
{
printf("Saved session recovery to '%s'\n", filename);
}
@@ -487,11 +510,13 @@ void WM_exit_ext(bContext *C, const bool do_python)
wm_dropbox_free();
WM_menutype_free();
WM_uilisttype_free();
-
+
/* all non-screen and non-space stuff editors did, like editmode */
if (C)
ED_editors_exit(C);
+ ED_undosys_type_free();
+
// XXX
// BIF_GlobalReebFree();
// BIF_freeRetarget();
@@ -569,12 +594,10 @@ void WM_exit_ext(bContext *C, const bool do_python)
GPU_exit();
}
- BKE_undo_reset();
-
ED_file_exit(); /* for fsmenu */
UI_exit();
- BKE_blender_userdef_free();
+ BKE_blender_userdef_data_free(&U, false);
RNA_exit(); /* should be after BPY_python_end so struct python slots are cleared */
@@ -591,6 +614,12 @@ void WM_exit_ext(bContext *C, const bool do_python)
BLI_threadapi_exit();
+ /* No need to call this early, rather do it late so that other pieces of Blender using sound may exit cleanly,
+ * see also T50676. */
+ BKE_sound_exit();
+
+ CLG_exit();
+
BKE_blender_atexit();
if (MEM_get_memory_blocks_in_use() != 0) {
@@ -605,6 +634,10 @@ void WM_exit_ext(bContext *C, const bool do_python)
BKE_tempdir_session_purge();
}
+/**
+ * \brief Main exit function to close Blender ordinarily.
+ * \note Use #wm_exit_schedule_delayed() to close Blender from an operator. Might leak memory otherwise.
+ */
void WM_exit(bContext *C)
{
WM_exit_ext(C, 1);
diff --git a/source/blender/windowmanager/intern/wm_jobs.c b/source/blender/windowmanager/intern/wm_jobs.c
index 5580d3217a5..f9fe787ed2d 100644
--- a/source/blender/windowmanager/intern/wm_jobs.c
+++ b/source/blender/windowmanager/intern/wm_jobs.c
@@ -379,7 +379,7 @@ static void wm_jobs_test_suspend_stop(wmWindowManager *wm, wmJob *test)
}
}
- /* possible suspend ourselfs, waiting for other jobs, or de-suspend */
+ /* Possible suspend ourselves, waiting for other jobs, or de-suspend. */
test->suspended = suspend;
// if (suspend) printf("job suspended: %s\n", test->name);
}
@@ -418,8 +418,8 @@ void WM_jobs_start(wmWindowManager *wm, wmJob *wm_job)
// printf("job started: %s\n", wm_job->name);
- BLI_init_threads(&wm_job->threads, do_job_thread, 1);
- BLI_insert_thread(&wm_job->threads, wm_job);
+ BLI_threadpool_init(&wm_job->threads, do_job_thread, 1);
+ BLI_threadpool_insert(&wm_job->threads, wm_job);
}
/* restarted job has timer already */
@@ -450,7 +450,7 @@ static void wm_jobs_kill_job(wmWindowManager *wm, wmJob *wm_job)
wm_job->stop = true;
WM_job_main_thread_lock_release(wm_job);
- BLI_end_threads(&wm_job->threads);
+ BLI_threadpool_end(&wm_job->threads);
WM_job_main_thread_lock_acquire(wm_job);
if (wm_job->endjob)
@@ -601,7 +601,7 @@ void wm_jobs_timer(const bContext *C, wmWindowManager *wm, wmTimer *wt)
wm_job->running = false;
WM_job_main_thread_lock_release(wm_job);
- BLI_end_threads(&wm_job->threads);
+ BLI_threadpool_end(&wm_job->threads);
WM_job_main_thread_lock_acquire(wm_job);
if (wm_job->endnote)
diff --git a/source/blender/windowmanager/intern/wm_keymap.c b/source/blender/windowmanager/intern/wm_keymap.c
index e201fa433d4..bcfc97a1e23 100644
--- a/source/blender/windowmanager/intern/wm_keymap.c
+++ b/source/blender/windowmanager/intern/wm_keymap.c
@@ -1,4 +1,5 @@
/*
+ *
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
@@ -39,6 +40,7 @@
#include "DNA_windowmanager_types.h"
#include "MEM_guardedalloc.h"
+#include "CLG_log.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
@@ -121,6 +123,13 @@ static void wm_keymap_item_properties_update_ot(wmKeyMapItem *kmi)
if (ot->srna != kmi->ptr->type) {
/* matches wm_keymap_item_properties_set but doesnt alloc new ptr */
WM_operator_properties_create_ptr(kmi->ptr, ot);
+ /* 'kmi->ptr->data' NULL'd above, keep using existing properties.
+ * Note: the operators property types may have changed,
+ * we will need a more comprehensive sanitize function to support this properly.
+ */
+ if (kmi->properties) {
+ kmi->ptr->data = kmi->properties;
+ }
WM_operator_properties_sanitize(kmi->ptr, 1);
}
}
@@ -391,6 +400,15 @@ bool WM_keymap_remove(wmKeyConfig *keyconf, wmKeyMap *keymap)
}
}
+
+bool WM_keymap_poll(bContext *C, wmKeyMap *keymap)
+{
+ if (keymap->poll != NULL) {
+ return keymap->poll(C);
+ }
+ return true;
+}
+
static void keymap_event_set(wmKeyMapItem *kmi, short type, short val, int modifier, short keymodifier)
{
kmi->type = type;
@@ -778,7 +796,7 @@ wmKeyMap *WM_keymap_find_all(const bContext *C, const char *idname, int spaceid,
/* modal maps get linked to a running operator, and filter the keys before sending to modal() callback */
-wmKeyMap *WM_modalkeymap_add(wmKeyConfig *keyconf, const char *idname, EnumPropertyItem *items)
+wmKeyMap *WM_modalkeymap_add(wmKeyConfig *keyconf, const char *idname, const EnumPropertyItem *items)
{
wmKeyMap *km = WM_keymap_find(keyconf, idname, 0, 0);
km->flag |= KEYMAP_MODAL;
@@ -870,11 +888,13 @@ wmKeyMapItem *WM_modalkeymap_find_propvalue(wmKeyMap *km, const int propvalue)
void WM_modalkeymap_assign(wmKeyMap *km, const char *opname)
{
wmOperatorType *ot = WM_operatortype_find(opname, 0);
-
- if (ot)
+
+ if (ot) {
ot->modalkeymap = km;
- else
- printf("error: modalkeymap_assign, unknown operator %s\n", opname);
+ }
+ else {
+ CLOG_ERROR(WM_LOG_KEYMAPS, "unknown operator '%s'", opname);
+ }
}
static void wm_user_modal_keymap_set_items(wmWindowManager *wm, wmKeyMap *km)
@@ -912,7 +932,7 @@ static void wm_user_modal_keymap_set_items(wmWindowManager *wm, wmKeyMap *km)
const char *WM_key_event_string(const short type, const bool compact)
{
- EnumPropertyItem *it;
+ const EnumPropertyItem *it;
const int i = RNA_enum_from_value(rna_enum_event_type_items, (int)type);
if (i == -1) {
@@ -933,7 +953,7 @@ const char *WM_key_event_string(const short type, const bool compact)
int WM_keymap_item_raw_to_string(
const short shift, const short ctrl, const short alt, const short oskey,
const short keymodifier, const short val, const short type, const bool compact,
- const int len, char *r_str)
+ char *result, const int result_len)
{
#define ADD_SEP if (p != buf) *p++ = ' '; (void)0
@@ -993,20 +1013,23 @@ int WM_keymap_item_raw_to_string(
BLI_assert(p - buf < sizeof(buf));
/* We need utf8 here, otherwise we may 'cut' some unicode chars like arrows... */
- return BLI_strncpy_utf8_rlen(r_str, buf, len);
+ return BLI_strncpy_utf8_rlen(result, buf, result_len);
#undef ADD_SEP
}
-int WM_keymap_item_to_string(wmKeyMapItem *kmi, const bool compact, const int len, char *r_str)
+int WM_keymap_item_to_string(
+ wmKeyMapItem *kmi, const bool compact,
+ char *result, const int result_len)
{
return WM_keymap_item_raw_to_string(
- kmi->shift, kmi->ctrl, kmi->alt, kmi->oskey, kmi->keymodifier, kmi->val, kmi->type,
- compact, len, r_str);
+ kmi->shift, kmi->ctrl, kmi->alt, kmi->oskey, kmi->keymodifier, kmi->val, kmi->type,
+ compact, result, result_len);
}
int WM_modalkeymap_items_to_string(
- wmKeyMap *km, const int propvalue, const bool compact, const int len, char *r_str)
+ wmKeyMap *km, const int propvalue, const bool compact,
+ char *result, const int result_len)
{
int totlen = 0;
bool add_sep = false;
@@ -1016,17 +1039,17 @@ int WM_modalkeymap_items_to_string(
/* Find all shortcuts related to that propvalue! */
for (kmi = WM_modalkeymap_find_propvalue(km, propvalue);
- kmi && totlen < (len - 2);
+ kmi && totlen < (result_len - 2);
kmi = wm_modalkeymap_find_propvalue_iter(km, kmi, propvalue))
{
if (add_sep) {
- r_str[totlen++] = '/';
- r_str[totlen] = '\0';
+ result[totlen++] = '/';
+ result[totlen] = '\0';
}
else {
add_sep = true;
}
- totlen += WM_keymap_item_to_string(kmi, compact, len - totlen, &r_str[totlen]);
+ totlen += WM_keymap_item_to_string(kmi, compact, &result[totlen], result_len - totlen);
}
}
@@ -1034,25 +1057,26 @@ int WM_modalkeymap_items_to_string(
}
int WM_modalkeymap_operator_items_to_string(
- wmOperatorType *ot, const int propvalue, const bool compact, const int len, char *r_str)
+ wmOperatorType *ot, const int propvalue, const bool compact,
+ char *result, const int result_len)
{
- return WM_modalkeymap_items_to_string(ot->modalkeymap, propvalue, compact, len, r_str);
+ return WM_modalkeymap_items_to_string(ot->modalkeymap, propvalue, compact, result, result_len);
}
char *WM_modalkeymap_operator_items_to_string_buf(
wmOperatorType *ot, const int propvalue, const bool compact,
- const int max_len, int *r_available_len, char **r_str)
+ const int max_len, int *r_available_len, char **r_result)
{
- char *ret = *r_str;
+ char *ret = *r_result;
if (*r_available_len > 1) {
int used_len = WM_modalkeymap_operator_items_to_string(
- ot, propvalue, compact, min_ii(*r_available_len, max_len), ret) + 1;
+ ot, propvalue, compact, ret, min_ii(*r_available_len, max_len)) + 1;
*r_available_len -= used_len;
- *r_str += used_len;
+ *r_result += used_len;
if (*r_available_len == 0) {
- (*r_str)--; /* So that *str keeps pointing on a valid char, we'll stay on it anyway. */
+ (*r_result)--; /* So that *result keeps pointing on a valid char, we'll stay on it anyway. */
}
}
else {
@@ -1076,7 +1100,7 @@ static wmKeyMapItem *wm_keymap_item_find_handlers(
for (handler = handlers->first; handler; handler = handler->next) {
keymap = WM_keymap_active(wm, handler->keymap);
- if (keymap && (!keymap->poll || keymap->poll((bContext *)C))) {
+ if (keymap && WM_keymap_poll((bContext *)C, keymap)) {
for (kmi = keymap->items.first; kmi; kmi = kmi->next) {
/* skip disabled keymap items [T38447] */
if (kmi->flag & KMI_INACTIVE)
@@ -1119,7 +1143,7 @@ static wmKeyMapItem *wm_keymap_item_find_handlers(
if (IDP_EqualsProperties_ex(properties, properties_default, is_strict)) {
char kmi_str[128];
- WM_keymap_item_to_string(kmi, false, sizeof(kmi_str), kmi_str);
+ WM_keymap_item_to_string(kmi, false, kmi_str, sizeof(kmi_str));
/* Note gievn properties could come from other things than menu entry... */
printf("%s: Some set values in menu entry match default op values, "
"this might not be desired!\n", opname);
@@ -1269,7 +1293,7 @@ static wmKeyMapItem *wm_keymap_item_find(
kmi = wm_keymap_item_find_props(C, opname, opcontext, properties_default, is_strict, is_hotkey, &km);
if (kmi) {
char kmi_str[128];
- WM_keymap_item_to_string(kmi, false, sizeof(kmi_str), kmi_str);
+ WM_keymap_item_to_string(kmi, false, kmi_str, sizeof(kmi_str));
printf("%s: Some set values in keymap entry match default op values, "
"this might not be desired!\n", opname);
printf("\tkm: '%s', kmi: '%s'\n", km->idname, kmi_str);
@@ -1295,13 +1319,14 @@ static wmKeyMapItem *wm_keymap_item_find(
char *WM_key_event_operator_string(
const bContext *C, const char *opname, int opcontext,
- IDProperty *properties, const bool is_strict, int len, char *r_str)
+ IDProperty *properties, const bool is_strict,
+ char *result, const int result_len)
{
wmKeyMapItem *kmi = wm_keymap_item_find(C, opname, opcontext, properties, false, is_strict, NULL);
-
+
if (kmi) {
- WM_keymap_item_to_string(kmi, false, len, r_str);
- return r_str;
+ WM_keymap_item_to_string(kmi, false, result, result_len);
+ return result;
}
return NULL;
@@ -1707,7 +1732,7 @@ wmKeyMap *WM_keymap_guess_opname(const bContext *C, const char *opname)
km = WM_keymap_find_all(C, "Mesh", 0, 0);
/* some mesh operators are active in object mode too, like add-prim */
- if (km && km->poll && km->poll((bContext *)C) == 0) {
+ if (km && !WM_keymap_poll((bContext *)C, km)) {
km = WM_keymap_find_all(C, "Object Mode", 0, 0);
}
}
@@ -1717,7 +1742,7 @@ wmKeyMap *WM_keymap_guess_opname(const bContext *C, const char *opname)
km = WM_keymap_find_all(C, "Curve", 0, 0);
/* some curve operators are active in object mode too, like add-prim */
- if (km && km->poll && km->poll((bContext *)C) == 0) {
+ if (km && !WM_keymap_poll((bContext *)C, km)) {
km = WM_keymap_find_all(C, "Object Mode", 0, 0);
}
}
@@ -1745,7 +1770,7 @@ wmKeyMap *WM_keymap_guess_opname(const bContext *C, const char *opname)
km = WM_keymap_find_all(C, "Metaball", 0, 0);
/* some mball operators are active in object mode too, like add-prim */
- if (km && km->poll && km->poll((bContext *)C) == 0) {
+ if (km && !WM_keymap_poll((bContext *)C, km)) {
km = WM_keymap_find_all(C, "Object Mode", 0, 0);
}
}
@@ -1797,7 +1822,7 @@ wmKeyMap *WM_keymap_guess_opname(const bContext *C, const char *opname)
* Mesh keymap is probably not ideal, but best place I could find to put those. */
if (sl->spacetype == SPACE_VIEW3D) {
km = WM_keymap_find_all(C, "Mesh", 0, 0);
- if (km && km->poll && !km->poll((bContext *)C)) {
+ if (km && !WM_keymap_poll((bContext *)C, km)) {
km = NULL;
}
}
diff --git a/source/blender/windowmanager/intern/wm_operator_props.c b/source/blender/windowmanager/intern/wm_operator_props.c
index 18836f34c99..72e4ff1d83a 100644
--- a/source/blender/windowmanager/intern/wm_operator_props.c
+++ b/source/blender/windowmanager/intern/wm_operator_props.c
@@ -49,7 +49,7 @@ void WM_operator_properties_filesel(
{
PropertyRNA *prop;
- static EnumPropertyItem file_display_items[] = {
+ static const EnumPropertyItem file_display_items[] = {
{FILE_DEFAULTDISPLAY, "DEFAULT", 0, "Default", "Automatically determine display type for files"},
{FILE_SHORTDISPLAY, "LIST_SHORT", ICON_SHORTDISPLAY, "Short List", "Display files as short list"},
{FILE_LONGDISPLAY, "LIST_LONG", ICON_LONGDISPLAY, "Long List", "Display files as a detailed list"},
@@ -135,7 +135,7 @@ static void wm_operator_properties_select_action_ex(wmOperatorType *ot, int defa
void WM_operator_properties_select_action(wmOperatorType *ot, int default_action)
{
- static EnumPropertyItem select_actions[] = {
+ static const EnumPropertyItem select_actions[] = {
{SEL_TOGGLE, "TOGGLE", 0, "Toggle", "Toggle selection for all elements"},
{SEL_SELECT, "SELECT", 0, "Select", "Select all elements"},
{SEL_DESELECT, "DESELECT", 0, "Deselect", "Deselect all elements"},
@@ -151,7 +151,7 @@ void WM_operator_properties_select_action(wmOperatorType *ot, int default_action
*/
void WM_operator_properties_select_action_simple(wmOperatorType *ot, int default_action)
{
- static EnumPropertyItem select_actions[] = {
+ static const EnumPropertyItem select_actions[] = {
{SEL_SELECT, "SELECT", 0, "Select", "Select all elements"},
{SEL_DESELECT, "DESELECT", 0, "Deselect", "Deselect all elements"},
{0, NULL, 0, NULL, NULL}
@@ -224,30 +224,69 @@ void WM_operator_properties_border_to_rctf(struct wmOperator *op, rctf *rect)
BLI_rctf_rcti_copy(rect, &rect_i);
}
-void WM_operator_properties_gesture_border(wmOperatorType *ot, bool extend)
+/**
+ * Use with #WM_gesture_border_invoke
+ */
+void WM_operator_properties_gesture_border_ex(wmOperatorType *ot, bool deselect, bool extend)
{
- RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX);
-
WM_operator_properties_border(ot);
+ if (deselect) {
+ RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Deselect rather than select items");
+ }
if (extend) {
RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend selection instead of deselecting everything first");
}
}
-void WM_operator_properties_mouse_select(wmOperatorType *ot)
+void WM_operator_properties_gesture_border_select(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_border_ex(ot, true, true);
+}
+void WM_operator_properties_gesture_border(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_border_ex(ot, false, false);
+}
+
+void WM_operator_properties_gesture_border_zoom(wmOperatorType *ot)
{
+ WM_operator_properties_border(ot);
+
PropertyRNA *prop;
+ prop = RNA_def_boolean(ot->srna, "zoom_out", false, "Zoom Out", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+}
- prop = RNA_def_boolean(ot->srna, "extend", false, "Extend",
- "Extend selection instead of deselecting everything first");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- prop = RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Remove from selection");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- prop = RNA_def_boolean(ot->srna, "toggle", false, "Toggle Selection", "Toggle the selection");
- RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+/**
+ * Use with #WM_gesture_lasso_invoke
+ */
+void WM_operator_properties_gesture_lasso_ex(wmOperatorType *ot, bool deselect, bool extend)
+{
+ PropertyRNA *prop;
+ prop = RNA_def_collection_runtime(ot->srna, "path", &RNA_OperatorMousePath, "Path", "");
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+
+ if (deselect) {
+ RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Deselect rather than select items");
+ }
+ if (extend) {
+ RNA_def_boolean(ot->srna, "extend", true, "Extend", "Extend selection instead of deselecting everything first");
+ }
}
+void WM_operator_properties_gesture_lasso(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_lasso_ex(ot, false, false);
+}
+
+void WM_operator_properties_gesture_lasso_select(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_lasso_ex(ot, true, true);
+}
+
+/**
+ * Use with #WM_gesture_straightline_invoke
+ */
void WM_operator_properties_gesture_straightline(wmOperatorType *ot, int cursor)
{
PropertyRNA *prop;
@@ -269,6 +308,48 @@ void WM_operator_properties_gesture_straightline(wmOperatorType *ot, int cursor)
}
/**
+ * Use with #WM_gesture_circle_invoke
+ */
+void WM_operator_properties_gesture_circle_ex(wmOperatorType *ot, bool deselect)
+{
+ PropertyRNA *prop;
+ const int radius_default = 25;
+
+ prop = RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX);
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+ prop = RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX);
+ RNA_def_property_flag(prop, PROP_HIDDEN | PROP_SKIP_SAVE);
+ RNA_def_int(ot->srna, "radius", radius_default, 1, INT_MAX, "Radius", "", 1, INT_MAX);
+
+ if (deselect) {
+ RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Deselect rather than select items");
+ }
+}
+
+void WM_operator_properties_gesture_circle(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_circle_ex(ot, false);
+}
+
+void WM_operator_properties_gesture_circle_select(wmOperatorType *ot)
+{
+ WM_operator_properties_gesture_circle_ex(ot, true);
+}
+
+void WM_operator_properties_mouse_select(wmOperatorType *ot)
+{
+ PropertyRNA *prop;
+
+ prop = RNA_def_boolean(ot->srna, "extend", false, "Extend",
+ "Extend selection instead of deselecting everything first");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ prop = RNA_def_boolean(ot->srna, "deselect", false, "Deselect", "Remove from selection");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ prop = RNA_def_boolean(ot->srna, "toggle", false, "Toggle Selection", "Toggle the selection");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+}
+
+/**
* \param nth_can_disable: Enable if we want to be able to select no interval at all.
*/
void WM_operator_properties_checker_interval(wmOperatorType *ot, bool nth_can_disable)
diff --git a/source/blender/windowmanager/intern/wm_operators.c b/source/blender/windowmanager/intern/wm_operators.c
index cef5e7e4a8e..f46358f83cf 100644
--- a/source/blender/windowmanager/intern/wm_operators.c
+++ b/source/blender/windowmanager/intern/wm_operators.c
@@ -46,6 +46,8 @@
#include "MEM_guardedalloc.h"
+#include "CLG_log.h"
+
#include "DNA_ID.h"
#include "DNA_object_types.h"
#include "DNA_screen_types.h"
@@ -58,7 +60,7 @@
#include "PIL_time.h"
#include "BLI_blenlib.h"
-#include "BLI_dial.h"
+#include "BLI_dial_2d.h"
#include "BLI_dynstr.h" /*for WM_operator_pystring */
#include "BLI_math.h"
#include "BLI_utildefines.h"
@@ -94,7 +96,7 @@
#include "ED_numinput.h"
#include "ED_screen.h"
-#include "ED_util.h"
+#include "ED_undo.h"
#include "ED_view3d.h"
#include "GPU_basic_shader.h"
@@ -115,7 +117,6 @@
#include "wm_event_system.h"
#include "wm_event_types.h"
#include "wm_files.h"
-#include "wm_subwindow.h"
#include "wm_window.h"
static GHash *global_ops_hash = NULL;
@@ -140,12 +141,12 @@ wmOperatorType *WM_operatortype_find(const char *idname, bool quiet)
}
if (!quiet) {
- printf("search for unknown operator '%s', '%s'\n", idname_bl, idname);
+ CLOG_INFO(WM_LOG_OPERATORS, 0, "search for unknown operator '%s', '%s'\n", idname_bl, idname);
}
}
else {
if (!quiet) {
- printf("search for empty operator\n");
+ CLOG_INFO(WM_LOG_OPERATORS, 0, "search for empty operator");
}
}
@@ -171,13 +172,12 @@ void WM_operatortype_append(void (*opfunc)(wmOperatorType *))
opfunc(ot);
if (ot->name == NULL) {
- fprintf(stderr, "ERROR: Operator %s has no name property!\n", ot->idname);
- ot->name = N_("Dummy Name");
+ CLOG_ERROR(WM_LOG_OPERATORS, "Operator '%s' has no name property", ot->idname);
}
/* XXX All ops should have a description but for now allow them not to. */
RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP);
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
}
@@ -193,7 +193,7 @@ void WM_operatortype_append_ptr(void (*opfunc)(wmOperatorType *, void *), void *
ot->translation_context = BLT_I18NCONTEXT_OPERATOR_DEFAULT;
opfunc(ot, userdata);
RNA_def_struct_ui_text(ot->srna, ot->name, ot->description ? ot->description : UNDOCUMENTED_OPERATOR_TIP);
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
}
@@ -256,7 +256,7 @@ static int wm_macro_exec(bContext *C, wmOperator *op)
}
}
else {
- printf("%s: '%s' cant exec macro\n", __func__, opm->type->idname);
+ CLOG_WARN(WM_LOG_OPERATORS, "'%s' cant exec macro", opm->type->idname);
}
}
@@ -301,8 +301,9 @@ static int wm_macro_modal(bContext *C, wmOperator *op, const wmEvent *event)
wmOperator *opm = op->opm;
int retval = OPERATOR_FINISHED;
- if (opm == NULL)
- printf("%s: macro error, calling NULL modal()\n", __func__);
+ if (opm == NULL) {
+ CLOG_ERROR(WM_LOG_OPERATORS, "macro error, calling NULL modal()");
+ }
else {
retval = opm->type->modal(C, opm, event);
OPERATOR_RETVAL_CHECK(retval);
@@ -376,7 +377,7 @@ wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *nam
const char *i18n_context;
if (WM_operatortype_find(idname, true)) {
- printf("%s: macro error: operator %s exists\n", __func__, idname);
+ CLOG_ERROR(WM_LOG_OPERATORS, "operator %s exists, cannot create macro", idname);
return NULL;
}
@@ -398,7 +399,7 @@ wmOperatorType *WM_operatortype_append_macro(const char *idname, const char *nam
ot->description = UNDOCUMENTED_OPERATOR_TIP;
RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
/* Use i18n context from ext.srna if possible (py operators). */
i18n_context = ot->ext.srna ? RNA_struct_translation_context(ot->ext.srna) : BLT_I18NCONTEXT_OPERATOR_DEFAULT;
RNA_def_struct_translation_context(ot->srna, i18n_context);
@@ -432,7 +433,7 @@ void WM_operatortype_append_macro_ptr(void (*opfunc)(wmOperatorType *, void *),
opfunc(ot, userdata);
RNA_def_struct_ui_text(ot->srna, ot->name, ot->description);
- RNA_def_struct_identifier(ot->srna, ot->idname);
+ RNA_def_struct_identifier(&BLENDER_RNA, ot->srna, ot->idname);
BLI_ghash_insert(global_ops_hash, (void *)ot->idname, ot);
}
@@ -573,6 +574,46 @@ void WM_operator_bl_idname(char *to, const char *from)
}
/**
+ * Sanity check to ensure #WM_operator_bl_idname won't fail.
+ * \returns true when there are no problems with \a idname, otherwise report an error.
+ */
+bool WM_operator_py_idname_ok_or_report(ReportList *reports, const char *classname, const char *idname)
+{
+ const char *ch = idname;
+ int dot = 0;
+ int i;
+ for (i = 0; *ch; i++, ch++) {
+ if ((*ch >= 'a' && *ch <= 'z') || (*ch >= '0' && *ch <= '9') || *ch == '_') {
+ /* pass */
+ }
+ else if (*ch == '.') {
+ dot++;
+ }
+ else {
+ BKE_reportf(reports, RPT_ERROR,
+ "Registering operator class: '%s', invalid bl_idname '%s', at position %d",
+ classname, idname, i);
+ return false;
+ }
+ }
+
+ if (i > (MAX_NAME - 3)) {
+ BKE_reportf(reports, RPT_ERROR, "Registering operator class: '%s', invalid bl_idname '%s', "
+ "is too long, maximum length is %d", classname, idname,
+ MAX_NAME - 3);
+ return false;
+ }
+
+ if (dot != 1) {
+ BKE_reportf(reports, RPT_ERROR,
+ "Registering operator class: '%s', invalid bl_idname '%s', must contain 1 '.' character",
+ classname, idname);
+ return false;
+ }
+ return true;
+}
+
+/**
* Print a string representation of the operator, with the args that it runs so python can run it again.
*
* When calling from an existing wmOperator, better to use simple version:
@@ -806,9 +847,19 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert
} \
} (void)0
+#define CTX_TEST_SPACE_TYPE(space_data_type, member_full, dataptr_cmp) \
+ { \
+ const char *ctx_member_full = member_full; \
+ if (space_data->spacetype == space_data_type && ptr->data == dataptr_cmp) { \
+ member_id = ctx_member_full; \
+ break; \
+ } \
+ } (void)0
+
switch (GS(((ID *)ptr->id.data)->name)) {
case ID_SCE:
{
+ CTX_TEST_PTR_DATA_TYPE(C, "active_gpencil_brush", RNA_GPencilBrush, ptr, CTX_data_active_gpencil_brush(C));
CTX_TEST_PTR_ID(C, "scene", ptr->id.data);
break;
}
@@ -843,12 +894,22 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert
{
CTX_TEST_PTR_ID(C, "screen", ptr->id.data);
- CTX_TEST_PTR_DATA_TYPE(C, "space_data", RNA_Space, ptr, CTX_wm_space_data(C));
+ SpaceLink *space_data = CTX_wm_space_data(C);
+
+ CTX_TEST_PTR_DATA_TYPE(C, "space_data", RNA_Space, ptr, space_data);
CTX_TEST_PTR_DATA_TYPE(C, "area", RNA_Area, ptr, CTX_wm_area(C));
CTX_TEST_PTR_DATA_TYPE(C, "region", RNA_Region, ptr, CTX_wm_region(C));
+ CTX_TEST_SPACE_TYPE(SPACE_IMAGE, "space_data.uv_editor", space_data);
+ CTX_TEST_SPACE_TYPE(SPACE_VIEW3D, "space_data.fx_settings", &(CTX_wm_view3d(C)->fx_settings));
+ CTX_TEST_SPACE_TYPE(SPACE_NLA, "space_data.dopesheet", CTX_wm_space_nla(C)->ads);
+ CTX_TEST_SPACE_TYPE(SPACE_IPO, "space_data.dopesheet", CTX_wm_space_graph(C)->ads);
+ CTX_TEST_SPACE_TYPE(SPACE_ACTION, "space_data.dopesheet", &(CTX_wm_space_action(C)->ads));
+ CTX_TEST_SPACE_TYPE(SPACE_FILE, "space_data.params", CTX_wm_space_file(C)->params);
break;
}
+ default:
+ break;
}
if (member_id) {
@@ -860,6 +921,7 @@ static char *wm_prop_pystring_from_context(bContext *C, PointerRNA *ptr, Propert
}
#undef CTX_TEST_PTR_ID
#undef CTX_TEST_PTR_ID_CAST
+#undef CTX_TEST_SPACE_TYPE
}
return ret;
@@ -900,7 +962,7 @@ void WM_operator_properties_create_ptr(PointerRNA *ptr, wmOperatorType *ot)
void WM_operator_properties_create(PointerRNA *ptr, const char *opstring)
{
- wmOperatorType *ot = WM_operatortype_find(opstring, 0);
+ wmOperatorType *ot = WM_operatortype_find(opstring, false);
if (ot)
WM_operator_properties_create_ptr(ptr, ot);
@@ -1075,11 +1137,14 @@ int WM_menu_invoke_ex(bContext *C, wmOperator *op, int opcontext)
uiLayout *layout;
if (prop == NULL) {
- printf("%s: %s has no enum property set\n", __func__, op->type->idname);
+ CLOG_ERROR(WM_LOG_OPERATORS,
+ "'%s' has no enum property set",
+ op->type->idname);
}
else if (RNA_property_type(prop) != PROP_ENUM) {
- printf("%s: %s \"%s\" is not an enum property\n",
- __func__, op->type->idname, RNA_property_identifier(prop));
+ CLOG_ERROR(WM_LOG_OPERATORS,
+ "'%s', '%s' is not an enum property",
+ op->type->idname, RNA_property_identifier(prop));
}
else if (RNA_property_is_set(op->ptr, prop)) {
const int retval = op->type->exec(C, op);
@@ -1118,6 +1183,7 @@ static uiBlock *wm_enum_search_menu(bContext *C, ARegion *ar, void *arg_op)
block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
UI_block_flag_enable(block, UI_BLOCK_LOOP | UI_BLOCK_MOVEMOUSE_QUIT | UI_BLOCK_SEARCH_MENU);
+ search[0] = '\0';
#if 0 /* ok, this isn't so easy... */
uiDefBut(block, UI_BTYPE_LABEL, 0, RNA_struct_ui_name(op->type->srna), 10, 10, UI_searchbox_size_x(), UI_UNIT_Y, NULL, 0.0, 0.0, 0, 0, "");
#endif
@@ -1162,7 +1228,7 @@ int WM_operator_confirm_message_ex(bContext *C, wmOperator *op,
pup = UI_popup_menu_begin(C, title, icon);
layout = UI_popup_menu_layout(pup);
- uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0);
+ uiItemFullO_ptr(layout, op->type, message, ICON_NONE, properties, WM_OP_EXEC_REGION_WIN, 0, NULL);
UI_popup_menu_end(C, pup);
return OPERATOR_INTERFACE;
@@ -1345,13 +1411,13 @@ static uiBlock *wm_block_create_redo(bContext *C, ARegion *ar, void *arg_op)
if (op->type->flag & OPTYPE_MACRO) {
for (op = op->macro.first; op; op = op->next) {
- uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
+ uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
if (op->next)
uiItemS(layout);
}
}
else {
- uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
+ uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
}
UI_block_bounds_set_popup(block, 4, 0, 0);
@@ -1372,7 +1438,7 @@ static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
wmOpPopUp *data = arg1;
uiBlock *block = arg2;
- /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be cancelled
+ /* Explicitly set UI_RETURN_OK flag, otherwise the menu might be canceled
* in case WM_operator_call_ex exits/reloads the current file (T49199). */
UI_popup_menu_retval_set(block, UI_RETURN_OK, true);
@@ -1402,20 +1468,6 @@ static void dialog_exec_cb(bContext *C, void *arg1, void *arg2)
}
}
-static void popup_check_cb(bContext *C, void *op_ptr, void *UNUSED(arg))
-{
- wmOperator *op = op_ptr;
- if (op->type->check) {
- if (op->type->check(C, op)) {
- /* check for popup and re-layout buttons */
- ARegion *ar_menu = CTX_wm_menu(C);
- if (ar_menu) {
- ED_region_tag_refresh_ui(ar_menu);
- }
- }
- }
-}
-
/* Dialogs are popups that require user verification (click OK) before exec */
static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
{
@@ -1434,9 +1486,7 @@ static uiBlock *wm_block_dialog_create(bContext *C, ARegion *ar, void *userData)
layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
- UI_block_func_set(block, popup_check_cb, op, NULL);
-
- uiLayoutOperatorButs(C, layout, op, NULL, 'H', UI_LAYOUT_OP_SHOW_TITLE);
+ uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'H', UI_TEMPLATE_OP_PROPS_SHOW_TITLE);
/* clear so the OK button is left alone */
UI_block_func_set(block, NULL, NULL, NULL);
@@ -1474,10 +1524,8 @@ static uiBlock *wm_operator_ui_create(bContext *C, ARegion *ar, void *userData)
layout = UI_block_layout(block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 0, 0, data->width, data->height, 0, style);
- UI_block_func_set(block, popup_check_cb, op, NULL);
-
/* since ui is defined the auto-layout args are not used */
- uiLayoutOperatorButs(C, layout, op, NULL, 'V', 0);
+ uiTemplateOperatorPropertyButs(C, layout, op, NULL, 'V', 0);
UI_block_func_set(block, NULL, NULL, NULL);
@@ -1522,7 +1570,7 @@ int WM_operator_ui_popup(bContext *C, wmOperator *op, int width, int height)
data->width = width;
data->height = height;
data->free_op = true; /* if this runs and gets registered we may want not to free it */
- UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data);
+ UI_popup_block_ex(C, wm_operator_ui_create, NULL, wm_operator_ui_popup_cancel, data, op);
return OPERATOR_RUNNING_MODAL;
}
@@ -1552,7 +1600,7 @@ static int wm_operator_props_popup_ex(bContext *C, wmOperator *op,
if (!do_redo || !(U.uiflag & USER_GLOBALUNDO))
return WM_operator_props_dialog_popup(C, op, 15 * UI_UNIT_X, UI_UNIT_Y);
- UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op);
+ UI_popup_block_ex(C, wm_block_create_redo, NULL, wm_block_redo_cancel_cb, op, op);
if (do_call)
wm_block_redo_cb(C, op, 0);
@@ -1594,7 +1642,7 @@ int WM_operator_props_dialog_popup(bContext *C, wmOperator *op, int width, int h
data->free_op = true; /* if this runs and gets registered we may want not to free it */
/* op is not executed until popup OK but is clicked */
- UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data);
+ UI_popup_block_ex(C, wm_block_dialog_create, wm_operator_ui_popup_ok, wm_operator_ui_popup_cancel, data, op);
return OPERATOR_RUNNING_MODAL;
}
@@ -1761,6 +1809,37 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
ibuf = IMB_ibImageFromMemory((unsigned char *)datatoc_splash_png,
datatoc_splash_png_size, IB_rect, NULL, "<splash screen>");
}
+
+ /* overwrite splash with template image */
+ if (U.app_template[0] != '\0') {
+ ImBuf *ibuf_template = NULL;
+ char splash_filepath[FILE_MAX];
+ char template_directory[FILE_MAX];
+
+ if (BKE_appdir_app_template_id_search(
+ U.app_template,
+ template_directory, sizeof(template_directory)))
+ {
+ BLI_join_dirfile(
+ splash_filepath, sizeof(splash_filepath), template_directory,
+ (U.pixelsize == 2) ? "splash_2x.png" : "splash.png");
+ ibuf_template = IMB_loadiffname(splash_filepath, IB_rect, NULL);
+ if (ibuf_template) {
+ const int x_expect = ibuf->x;
+ const int y_expect = 230 * (int)U.pixelsize;
+ /* don't cover the header text */
+ if (ibuf_template->x == x_expect && ibuf_template->y == y_expect) {
+ memcpy(ibuf->rect, ibuf_template->rect, ibuf_template->x * ibuf_template->y * sizeof(char[4]));
+ }
+ else {
+ CLOG_ERROR(WM_LOG_OPERATORS,
+ "Splash expected %dx%d found %dx%d, ignoring: %s\n",
+ x_expect, y_expect, ibuf_template->x, ibuf_template->y, splash_filepath);
+ }
+ IMB_freeImBuf(ibuf_template);
+ }
+ }
+ }
#endif
block = UI_block_begin(C, ar, "_popup", UI_EMBOSS);
@@ -1786,13 +1865,13 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
if (version_suffix != NULL && version_suffix[0]) {
/* placed after the version number in the image,
* placing y is tricky to match baseline */
- int x = 260 - (2 * UI_DPI_WINDOW_FAC);
- int y = 242 + (4 * UI_DPI_WINDOW_FAC);
- int w = 240;
+ int x = 260 * U.pixelsize - (2 * UI_DPI_FAC);
+ int y = 242 * U.pixelsize + (4 * UI_DPI_FAC);
+ int w = 240 * U.pixelsize;
/* hack to have text draw 'text_sel' */
UI_block_emboss_set(block, UI_EMBOSS_NONE);
- but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x * U.pixelsize, y * U.pixelsize, w * U.pixelsize, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
+ but = uiDefBut(block, UI_BTYPE_LABEL, 0, version_suffix, x, y, w, UI_UNIT_Y, NULL, 0, 0, 0, 0, NULL);
/* XXX, set internal flag - UI_SELECT */
UI_but_flag_enable(but, 1);
UI_block_emboss_set(block, UI_EMBOSS);
@@ -1819,10 +1898,7 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
UI_block_emboss_set(block, UI_EMBOSS);
/* show the splash menu (containing interaction presets), using python */
if (mt) {
- Menu menu = {NULL};
- menu.layout = layout;
- menu.type = mt;
- mt->draw(C, &menu);
+ UI_menutype_draw(C, mt, layout);
// wmWindowManager *wm = CTX_wm_manager(C);
// uiItemM(layout, C, "USERPREF_MT_keyconfigs", U.keyconfigstr, ICON_NONE);
@@ -1849,13 +1925,11 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
"https://docs.blender.org/manual/en/dev/");
uiItemStringO(col, IFACE_("Blender Website"), ICON_URL, "WM_OT_url_open", "url", "http://www.blender.org");
if (STREQ(STRINGIFY(BLENDER_VERSION_CYCLE), "release")) {
- BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d"
- STRINGIFY(BLENDER_VERSION_CHAR) "_release",
+ BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/%d.%d"STRINGIFY(BLENDER_VERSION_CHAR),
BLENDER_VERSION / 100, BLENDER_VERSION % 100);
}
else {
- BLI_snprintf(url, sizeof(url), "http://www.blender.org/documentation/blender_python_api_%d_%d_%d",
- BLENDER_VERSION / 100, BLENDER_VERSION % 100, BLENDER_SUBVERSION);
+ BLI_snprintf(url, sizeof(url), "https://docs.blender.org/api/master");
}
uiItemStringO(col, IFACE_("Python API Reference"), ICON_URL, "WM_OT_url_open", "url", url);
uiItemL(col, "", ICON_NONE);
@@ -1881,10 +1955,7 @@ static uiBlock *wm_block_create_splash(bContext *C, ARegion *ar, void *UNUSED(ar
mt = WM_menutype_find("USERPREF_MT_splash_footer", false);
if (mt) {
- Menu menu = {NULL};
- menu.layout = uiLayoutColumn(layout, false);
- menu.type = mt;
- mt->draw(C, &menu);
+ UI_menutype_draw(C, mt, uiLayoutColumn(layout, false));
}
UI_block_bounds_set_centered(block, 0);
@@ -2095,22 +2166,29 @@ static void WM_OT_window_fullscreen_toggle(wmOperatorType *ot)
ot->poll = WM_operator_winactive;
}
-static int wm_exit_blender_exec(bContext *C, wmOperator *op)
+static int wm_exit_blender_exec(bContext *C, wmOperator *UNUSED(op))
{
- WM_operator_free(op);
-
- WM_exit(C);
-
+ wm_quit_with_optional_confirmation_prompt(C, CTX_wm_window(C));
return OPERATOR_FINISHED;
}
+static int wm_exit_blender_invoke(bContext *C, wmOperator *op, const wmEvent *event)
+{
+ if (U.uiflag & USER_QUIT_PROMPT) {
+ return wm_exit_blender_exec(C, op);
+ }
+ else {
+ return WM_operator_confirm(C, op, event);
+ }
+}
+
static void WM_OT_quit_blender(wmOperatorType *ot)
{
ot->name = "Quit Blender";
ot->idname = "WM_OT_quit_blender";
ot->description = "Quit Blender";
- ot->invoke = WM_operator_confirm;
+ ot->invoke = wm_exit_blender_invoke;
ot->exec = wm_exit_blender_exec;
}
@@ -2171,705 +2249,6 @@ void WM_paint_cursor_end(wmWindowManager *wm, void *handle)
}
}
-/* ************ window gesture operator-callback definitions ************** */
-/*
- * These are default callbacks for use in operators requiring gesture input
- */
-
-/* **************** Border gesture *************** */
-
-/**
- * Border gesture has two types:
- * -# #WM_GESTURE_CROSS_RECT: starts a cross, on mouse click it changes to border.
- * -# #WM_GESTURE_RECT: starts immediate as a border, on mouse click or release it ends.
- *
- * It stores 4 values (xmin, xmax, ymin, ymax) and event it ended with (event_type)
- */
-
-static int border_apply_rect(wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
-
- if (rect->xmin == rect->xmax || rect->ymin == rect->ymax)
- return 0;
-
-
- /* operator arguments and storage. */
- RNA_int_set(op->ptr, "xmin", min_ii(rect->xmin, rect->xmax));
- RNA_int_set(op->ptr, "ymin", min_ii(rect->ymin, rect->ymax));
- RNA_int_set(op->ptr, "xmax", max_ii(rect->xmin, rect->xmax));
- RNA_int_set(op->ptr, "ymax", max_ii(rect->ymin, rect->ymax));
-
- return 1;
-}
-
-static int border_apply(bContext *C, wmOperator *op, int gesture_mode)
-{
- PropertyRNA *prop;
-
- int retval;
-
- if (!border_apply_rect(op))
- return 0;
-
- /* XXX weak; border should be configured for this without reading event types */
- if ((prop = RNA_struct_find_property(op->ptr, "gesture_mode"))) {
- RNA_property_int_set(op->ptr, prop, gesture_mode);
- }
-
- retval = op->type->exec(C, op);
- OPERATOR_RETVAL_CHECK(retval);
-
- return 1;
-}
-
-static void wm_gesture_end(bContext *C, wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
-
- WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
- op->customdata = NULL;
-
- ED_area_tag_redraw(CTX_wm_area(C));
-
- if (RNA_struct_find_property(op->ptr, "cursor")) {
- WM_cursor_modal_restore(CTX_wm_window(C));
- }
-}
-
-int WM_border_select_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- if (ISTWEAK(event->type))
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_RECT);
- else
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_CROSS_RECT);
-
- /* add modal handler */
- WM_event_add_modal_handler(C, op);
-
- wm_gesture_tag_redraw(C);
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-int WM_border_select_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
- int sx, sy;
-
- if (event->type == MOUSEMOVE) {
- wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
-
- if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
- rect->xmin = rect->xmax = event->x - sx;
- rect->ymin = rect->ymax = event->y - sy;
- }
- else {
- rect->xmax = event->x - sx;
- rect->ymax = event->y - sy;
- }
- border_apply_rect(op);
-
- wm_gesture_tag_redraw(C);
- }
- else if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case GESTURE_MODAL_BEGIN:
- if (gesture->type == WM_GESTURE_CROSS_RECT && gesture->mode == 0) {
- gesture->mode = 1;
- wm_gesture_tag_redraw(C);
- }
- break;
- case GESTURE_MODAL_SELECT:
- case GESTURE_MODAL_DESELECT:
- case GESTURE_MODAL_IN:
- case GESTURE_MODAL_OUT:
- if (border_apply(C, op, event->val)) {
- wm_gesture_end(C, op);
- return OPERATOR_FINISHED;
- }
- wm_gesture_end(C, op);
- return OPERATOR_CANCELLED;
-
- case GESTURE_MODAL_CANCEL:
- wm_gesture_end(C, op);
- return OPERATOR_CANCELLED;
- }
-
- }
-#ifdef WITH_INPUT_NDOF
- else if (event->type == NDOF_MOTION) {
- return OPERATOR_PASS_THROUGH;
- }
-#endif
-// /* Allow view navigation??? */
-// else {
-// return OPERATOR_PASS_THROUGH;
-// }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-void WM_border_select_cancel(bContext *C, wmOperator *op)
-{
- wm_gesture_end(C, op);
-}
-
-/* **************** circle gesture *************** */
-/* works now only for selection or modal paint stuff, calls exec while hold mouse, exit on release */
-
-#ifdef GESTURE_MEMORY
-int circle_select_size = 25; /* XXX - need some operator memory thing! */
-#endif
-
-int WM_gesture_circle_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_CIRCLE);
-
- /* add modal handler */
- WM_event_add_modal_handler(C, op);
-
- wm_gesture_tag_redraw(C);
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-static void gesture_circle_apply(bContext *C, wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
-
- if (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_NOP)
- return;
-
- /* operator arguments and storage. */
- RNA_int_set(op->ptr, "x", rect->xmin);
- RNA_int_set(op->ptr, "y", rect->ymin);
- RNA_int_set(op->ptr, "radius", rect->xmax);
-
- if (op->type->exec) {
- int retval;
- retval = op->type->exec(C, op);
- OPERATOR_RETVAL_CHECK(retval);
- }
-#ifdef GESTURE_MEMORY
- circle_select_size = rect->xmax;
-#endif
-}
-
-int WM_gesture_circle_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
- int sx, sy;
-
- if (event->type == MOUSEMOVE) {
- wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
-
- rect->xmin = event->x - sx;
- rect->ymin = event->y - sy;
-
- wm_gesture_tag_redraw(C);
-
- if (gesture->mode)
- gesture_circle_apply(C, op);
- }
- else if (event->type == EVT_MODAL_MAP) {
- float fac;
-
- switch (event->val) {
- case GESTURE_MODAL_CIRCLE_SIZE:
- fac = 0.3f * (event->y - event->prevy);
- if (fac > 0)
- rect->xmax += ceil(fac);
- else
- rect->xmax += floor(fac);
- if (rect->xmax < 1) rect->xmax = 1;
- wm_gesture_tag_redraw(C);
- break;
- case GESTURE_MODAL_CIRCLE_ADD:
- rect->xmax += 2 + rect->xmax / 10;
- wm_gesture_tag_redraw(C);
- break;
- case GESTURE_MODAL_CIRCLE_SUB:
- rect->xmax -= 2 + rect->xmax / 10;
- if (rect->xmax < 1) rect->xmax = 1;
- wm_gesture_tag_redraw(C);
- break;
- case GESTURE_MODAL_SELECT:
- case GESTURE_MODAL_DESELECT:
- case GESTURE_MODAL_NOP:
- if (RNA_struct_find_property(op->ptr, "gesture_mode"))
- RNA_int_set(op->ptr, "gesture_mode", event->val);
-
- if (event->val != GESTURE_MODAL_NOP) {
- /* apply first click */
- gesture_circle_apply(C, op);
- gesture->mode = 1;
- wm_gesture_tag_redraw(C);
- }
- break;
-
- case GESTURE_MODAL_CANCEL:
- case GESTURE_MODAL_CONFIRM:
- wm_gesture_end(C, op);
- return OPERATOR_FINISHED; /* use finish or we don't get an undo */
- }
- }
-#ifdef WITH_INPUT_NDOF
- else if (event->type == NDOF_MOTION) {
- return OPERATOR_PASS_THROUGH;
- }
-#endif
- /* Allow view navigation??? */
- /* note, this gives issues: 1) other modal ops run on top (border select), 2) middlemouse is used now 3) tablet/trackpad? */
-// else {
-// return OPERATOR_PASS_THROUGH;
-// }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-void WM_gesture_circle_cancel(bContext *C, wmOperator *op)
-{
- wm_gesture_end(C, op);
-}
-
-#if 0
-/* template to copy from */
-void WM_OT_circle_gesture(wmOperatorType *ot)
-{
- ot->name = "Circle Gesture";
- ot->idname = "WM_OT_circle_gesture";
- ot->description = "Enter rotate mode with a circular gesture";
-
- ot->invoke = WM_gesture_circle_invoke;
- ot->modal = WM_gesture_circle_modal;
-
- ot->poll = WM_operator_winactive;
-
- RNA_def_property(ot->srna, "x", PROP_INT, PROP_NONE);
- RNA_def_property(ot->srna, "y", PROP_INT, PROP_NONE);
- RNA_def_property(ot->srna, "radius", PROP_INT, PROP_NONE);
-
-}
-#endif
-
-/* **************** Tweak gesture *************** */
-
-static void tweak_gesture_modal(bContext *C, const wmEvent *event)
-{
- wmWindow *window = CTX_wm_window(C);
- wmGesture *gesture = window->tweak;
- rcti *rect = gesture->customdata;
- int sx, sy, val;
-
- switch (event->type) {
- case MOUSEMOVE:
- case INBETWEEN_MOUSEMOVE:
-
- wm_subwindow_origin_get(window, gesture->swinid, &sx, &sy);
-
- rect->xmax = event->x - sx;
- rect->ymax = event->y - sy;
-
- if ((val = wm_gesture_evaluate(gesture))) {
- wmEvent tevent;
-
- wm_event_init_from_window(window, &tevent);
- /* We want to get coord from start of drag, not from point where it becomes a tweak event, see T40549 */
- tevent.x = rect->xmin + sx;
- tevent.y = rect->ymin + sy;
- if (gesture->event_type == LEFTMOUSE)
- tevent.type = EVT_TWEAK_L;
- else if (gesture->event_type == RIGHTMOUSE)
- tevent.type = EVT_TWEAK_R;
- else
- tevent.type = EVT_TWEAK_M;
- tevent.val = val;
- /* mouse coords! */
-
- /* important we add immediately after this event, so future mouse releases
- * (which may be in the queue already), are handled in order, see T44740 */
- wm_event_add_ex(window, &tevent, event);
-
- WM_gesture_end(C, gesture); /* frees gesture itself, and unregisters from window */
- }
-
- break;
-
- case LEFTMOUSE:
- case RIGHTMOUSE:
- case MIDDLEMOUSE:
- if (gesture->event_type == event->type) {
- WM_gesture_end(C, gesture);
-
- /* when tweak fails we should give the other keymap entries a chance */
-
- /* XXX, assigning to readonly, BAD JUJU! */
- ((wmEvent *)event)->val = KM_RELEASE;
- }
- break;
- default:
- if (!ISTIMER(event->type) && event->type != EVENT_NONE) {
- WM_gesture_end(C, gesture);
- }
- break;
- }
-}
-
-/* standard tweak, called after window handlers passed on event */
-void wm_tweakevent_test(bContext *C, wmEvent *event, int action)
-{
- wmWindow *win = CTX_wm_window(C);
-
- if (win->tweak == NULL) {
- if (CTX_wm_region(C)) {
- if (event->val == KM_PRESS) {
- if (ELEM(event->type, LEFTMOUSE, MIDDLEMOUSE, RIGHTMOUSE)) {
- win->tweak = WM_gesture_new(C, event, WM_GESTURE_TWEAK);
- }
- }
- }
- }
- else {
- /* no tweaks if event was handled */
- if ((action & WM_HANDLER_BREAK)) {
- WM_gesture_end(C, win->tweak);
- }
- else
- tweak_gesture_modal(C, event);
- }
-}
-
-/* *********************** lasso gesture ****************** */
-
-int WM_gesture_lasso_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- PropertyRNA *prop;
-
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_LASSO);
-
- /* add modal handler */
- WM_event_add_modal_handler(C, op);
-
- wm_gesture_tag_redraw(C);
-
- if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
- WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-int WM_gesture_lines_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- PropertyRNA *prop;
-
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_LINES);
-
- /* add modal handler */
- WM_event_add_modal_handler(C, op);
-
- wm_gesture_tag_redraw(C);
-
- if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
- WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-
-static void gesture_lasso_apply(bContext *C, wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
- PointerRNA itemptr;
- float loc[2];
- int i;
- const short *lasso = gesture->customdata;
-
- /* operator storage as path. */
-
- RNA_collection_clear(op->ptr, "path");
- for (i = 0; i < gesture->points; i++, lasso += 2) {
- loc[0] = lasso[0];
- loc[1] = lasso[1];
- RNA_collection_add(op->ptr, "path", &itemptr);
- RNA_float_set_array(&itemptr, "loc", loc);
- }
-
- wm_gesture_end(C, op);
-
- if (op->type->exec) {
- int retval = op->type->exec(C, op);
- OPERATOR_RETVAL_CHECK(retval);
- }
-}
-
-int WM_gesture_lasso_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- wmGesture *gesture = op->customdata;
- int sx, sy;
-
- switch (event->type) {
- case MOUSEMOVE:
- case INBETWEEN_MOUSEMOVE:
-
- wm_gesture_tag_redraw(C);
-
- wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
-
- if (gesture->points == gesture->size) {
- short *old_lasso = gesture->customdata;
- gesture->customdata = MEM_callocN(2 * sizeof(short) * (gesture->size + WM_LASSO_MIN_POINTS), "lasso points");
- memcpy(gesture->customdata, old_lasso, 2 * sizeof(short) * gesture->size);
- gesture->size = gesture->size + WM_LASSO_MIN_POINTS;
- MEM_freeN(old_lasso);
- // printf("realloc\n");
- }
-
- {
- int x, y;
- short *lasso = gesture->customdata;
-
- lasso += (2 * gesture->points - 2);
- x = (event->x - sx - lasso[0]);
- y = (event->y - sy - lasso[1]);
-
- /* make a simple distance check to get a smoother lasso
- * add only when at least 2 pixels between this and previous location */
- if ((x * x + y * y) > 4) {
- lasso += 2;
- lasso[0] = event->x - sx;
- lasso[1] = event->y - sy;
- gesture->points++;
- }
- }
- break;
-
- case LEFTMOUSE:
- case MIDDLEMOUSE:
- case RIGHTMOUSE:
- if (event->val == KM_RELEASE) { /* key release */
- gesture_lasso_apply(C, op);
- return OPERATOR_FINISHED;
- }
- break;
- case ESCKEY:
- wm_gesture_end(C, op);
- return OPERATOR_CANCELLED;
- }
- return OPERATOR_RUNNING_MODAL;
-}
-
-int WM_gesture_lines_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- return WM_gesture_lasso_modal(C, op, event);
-}
-
-void WM_gesture_lasso_cancel(bContext *C, wmOperator *op)
-{
- wm_gesture_end(C, op);
-}
-
-void WM_gesture_lines_cancel(bContext *C, wmOperator *op)
-{
- wm_gesture_end(C, op);
-}
-
-/**
- * helper function, we may want to add options for conversion to view space
- *
- * caller must free.
- */
-const int (*WM_gesture_lasso_path_to_array(bContext *UNUSED(C), wmOperator *op, int *mcords_tot))[2]
-{
- PropertyRNA *prop = RNA_struct_find_property(op->ptr, "path");
- int (*mcords)[2] = NULL;
- BLI_assert(prop != NULL);
-
- if (prop) {
- const int len = RNA_property_collection_length(op->ptr, prop);
-
- if (len) {
- int i = 0;
- mcords = MEM_mallocN(sizeof(int) * 2 * len, __func__);
-
- RNA_PROP_BEGIN (op->ptr, itemptr, prop)
- {
- float loc[2];
-
- RNA_float_get_array(&itemptr, "loc", loc);
- mcords[i][0] = (int)loc[0];
- mcords[i][1] = (int)loc[1];
- i++;
- }
- RNA_PROP_END;
- }
- *mcords_tot = len;
- }
- else {
- *mcords_tot = 0;
- }
-
- /* cast for 'const' */
- return (const int (*)[2])mcords;
-}
-
-#if 0
-/* template to copy from */
-
-static int gesture_lasso_exec(bContext *C, wmOperator *op)
-{
- RNA_BEGIN (op->ptr, itemptr, "path")
- {
- float loc[2];
-
- RNA_float_get_array(&itemptr, "loc", loc);
- printf("Location: %f %f\n", loc[0], loc[1]);
- }
- RNA_END;
-
- return OPERATOR_FINISHED;
-}
-
-void WM_OT_lasso_gesture(wmOperatorType *ot)
-{
- PropertyRNA *prop;
-
- ot->name = "Lasso Gesture";
- ot->idname = "WM_OT_lasso_gesture";
- ot->description = "Select objects within the lasso as you move the pointer";
-
- ot->invoke = WM_gesture_lasso_invoke;
- ot->modal = WM_gesture_lasso_modal;
- ot->exec = gesture_lasso_exec;
-
- ot->poll = WM_operator_winactive;
-
- prop = RNA_def_property(ot->srna, "path", PROP_COLLECTION, PROP_NONE);
- RNA_def_property_struct_runtime(prop, &RNA_OperatorMousePath);
-}
-#endif
-
-/* *********************** straight line gesture ****************** */
-
-static int straightline_apply(bContext *C, wmOperator *op)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
-
- if (rect->xmin == rect->xmax && rect->ymin == rect->ymax)
- return 0;
-
- /* operator arguments and storage. */
- RNA_int_set(op->ptr, "xstart", rect->xmin);
- RNA_int_set(op->ptr, "ystart", rect->ymin);
- RNA_int_set(op->ptr, "xend", rect->xmax);
- RNA_int_set(op->ptr, "yend", rect->ymax);
-
- if (op->type->exec) {
- int retval = op->type->exec(C, op);
- OPERATOR_RETVAL_CHECK(retval);
- }
-
- return 1;
-}
-
-
-int WM_gesture_straightline_invoke(bContext *C, wmOperator *op, const wmEvent *event)
-{
- PropertyRNA *prop;
-
- op->customdata = WM_gesture_new(C, event, WM_GESTURE_STRAIGHTLINE);
-
- /* add modal handler */
- WM_event_add_modal_handler(C, op);
-
- wm_gesture_tag_redraw(C);
-
- if ((prop = RNA_struct_find_property(op->ptr, "cursor"))) {
- WM_cursor_modal_set(CTX_wm_window(C), RNA_property_int_get(op->ptr, prop));
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-int WM_gesture_straightline_modal(bContext *C, wmOperator *op, const wmEvent *event)
-{
- wmGesture *gesture = op->customdata;
- rcti *rect = gesture->customdata;
- int sx, sy;
-
- if (event->type == MOUSEMOVE) {
- wm_subwindow_origin_get(CTX_wm_window(C), gesture->swinid, &sx, &sy);
-
- if (gesture->mode == 0) {
- rect->xmin = rect->xmax = event->x - sx;
- rect->ymin = rect->ymax = event->y - sy;
- }
- else {
- rect->xmax = event->x - sx;
- rect->ymax = event->y - sy;
- straightline_apply(C, op);
- }
-
- wm_gesture_tag_redraw(C);
- }
- else if (event->type == EVT_MODAL_MAP) {
- switch (event->val) {
- case GESTURE_MODAL_BEGIN:
- if (gesture->mode == 0) {
- gesture->mode = 1;
- wm_gesture_tag_redraw(C);
- }
- break;
- case GESTURE_MODAL_SELECT:
- if (straightline_apply(C, op)) {
- wm_gesture_end(C, op);
- return OPERATOR_FINISHED;
- }
- wm_gesture_end(C, op);
- return OPERATOR_CANCELLED;
-
- case GESTURE_MODAL_CANCEL:
- wm_gesture_end(C, op);
- return OPERATOR_CANCELLED;
- }
-
- }
-
- return OPERATOR_RUNNING_MODAL;
-}
-
-void WM_gesture_straightline_cancel(bContext *C, wmOperator *op)
-{
- wm_gesture_end(C, op);
-}
-
-#if 0
-/* template to copy from */
-void WM_OT_straightline_gesture(wmOperatorType *ot)
-{
- PropertyRNA *prop;
-
- ot->name = "Straight Line Gesture";
- ot->idname = "WM_OT_straightline_gesture";
- ot->description = "Draw a straight line as you move the pointer";
-
- ot->invoke = WM_gesture_straightline_invoke;
- ot->modal = WM_gesture_straightline_modal;
- ot->exec = gesture_straightline_exec;
-
- ot->poll = WM_operator_winactive;
-
- WM_operator_properties_gesture_straightline(ot, 0);
-}
-#endif
-
/* *********************** radial control ****************** */
#define WM_RADIAL_CONTROL_DISPLAY_SIZE (200 * UI_DPI_FAC)
@@ -3661,26 +3040,38 @@ static void WM_OT_radial_control(wmOperatorType *ot)
ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO | OPTYPE_BLOCKING;
/* all paths relative to the context */
- RNA_def_string(ot->srna, "data_path_primary", NULL, 0, "Primary Data Path", "Primary path of property to be set by the radial control");
+ PropertyRNA *prop;
+ prop = RNA_def_string(ot->srna, "data_path_primary", NULL, 0, "Primary Data Path", "Primary path of property to be set by the radial control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "data_path_secondary", NULL, 0, "Secondary Data Path", "Secondary path of property to be set by the radial control");
+ prop = RNA_def_string(ot->srna, "data_path_secondary", NULL, 0, "Secondary Data Path", "Secondary path of property to be set by the radial control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "use_secondary", NULL, 0, "Use Secondary", "Path of property to select between the primary and secondary data paths");
+ prop = RNA_def_string(ot->srna, "use_secondary", NULL, 0, "Use Secondary", "Path of property to select between the primary and secondary data paths");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "rotation_path", NULL, 0, "Rotation Path", "Path of property used to rotate the texture display");
+ prop = RNA_def_string(ot->srna, "rotation_path", NULL, 0, "Rotation Path", "Path of property used to rotate the texture display");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "color_path", NULL, 0, "Color Path", "Path of property used to set the color of the control");
+ prop = RNA_def_string(ot->srna, "color_path", NULL, 0, "Color Path", "Path of property used to set the color of the control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "fill_color_path", NULL, 0, "Fill Color Path", "Path of property used to set the fill color of the control");
+ prop = RNA_def_string(ot->srna, "fill_color_path", NULL, 0, "Fill Color Path", "Path of property used to set the fill color of the control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "fill_color_override_path", NULL, 0, "Fill Color Override Path", "");
- RNA_def_string(ot->srna, "fill_color_override_test_path", NULL, 0, "Fill Color Override Test", "");
+ prop = RNA_def_string(ot->srna, "fill_color_override_path", NULL, 0, "Fill Color Override Path", "");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
+ prop = RNA_def_string(ot->srna, "fill_color_override_test_path", NULL, 0, "Fill Color Override Test", "");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "zoom_path", NULL, 0, "Zoom Path", "Path of property used to set the zoom level for the control");
+ prop = RNA_def_string(ot->srna, "zoom_path", NULL, 0, "Zoom Path", "Path of property used to set the zoom level for the control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_string(ot->srna, "image_id", NULL, 0, "Image ID", "Path of ID that is used to generate an image for the control");
+ prop = RNA_def_string(ot->srna, "image_id", NULL, 0, "Image ID", "Path of ID that is used to generate an image for the control");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
- RNA_def_boolean(ot->srna, "secondary_tex", false, "Secondary Texture", "Tweak brush secondary/mask texture");
+ prop = RNA_def_boolean(ot->srna, "secondary_tex", false, "Secondary Texture", "Tweak brush secondary/mask texture");
+ RNA_def_property_flag(prop, PROP_SKIP_SAVE);
}
/* ************************** timer for testing ***************** */
@@ -3710,7 +3101,7 @@ enum {
eRTUndo = 6,
};
-static EnumPropertyItem redraw_timer_type_items[] = {
+static const EnumPropertyItem redraw_timer_type_items[] = {
{eRTDrawRegion, "DRAW", 0, "Draw Region", "Draw Region"},
{eRTDrawRegionSwap, "DRAW_SWAP", 0, "Draw Region + Swap", "Draw Region and Swap"},
{eRTDrawWindow, "DRAW_WIN", 0, "Draw Window", "Draw Window"},
@@ -3904,7 +3295,7 @@ static void previews_id_ensure(bContext *C, Scene *scene, ID *id)
/* Only preview non-library datablocks, lib ones do not pertain to this .blend file!
* Same goes for ID with no user. */
- if (!ID_IS_LINKED_DATABLOCK(id) && (id->us != 0)) {
+ if (!ID_IS_LINKED(id) && (id->us != 0)) {
UI_id_icon_render(C, scene, id, false, false);
UI_id_icon_render(C, scene, id, true, false);
}
@@ -3978,7 +3369,7 @@ static void WM_OT_previews_ensure(wmOperatorType *ot)
/* *************************** Datablocks previews clear ************* */
/* Only types supporting previews currently. */
-static EnumPropertyItem preview_id_type_items[] = {
+static const EnumPropertyItem preview_id_type_items[] = {
{FILTER_ID_SCE, "SCENE", 0, "Scenes", ""},
{FILTER_ID_GR, "GROUP", 0, "Groups", ""},
{FILTER_ID_OB, "OBJECT", 0, "Objects", ""},
@@ -4179,7 +3570,7 @@ void wm_operatortype_init(void)
/* circleselect-like modal operators */
static void gesture_circle_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{GESTURE_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{GESTURE_MODAL_CONFIRM, "CONFIRM", 0, "Confirm", ""},
{GESTURE_MODAL_CIRCLE_ADD, "ADD", 0, "Add", ""},
@@ -4210,14 +3601,15 @@ static void gesture_circle_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, 0, 0, GESTURE_MODAL_SELECT);
+ /* Note: use 'KM_ANY' for release, so the circle exits on any mouse release,
+ * this is needed when circle select is activated as a tool. */
+
/* left mouse shift for deselect too */
WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, KM_SHIFT, 0, GESTURE_MODAL_DESELECT);
- WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_SHIFT, 0, GESTURE_MODAL_NOP);
+ WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, GESTURE_MODAL_NOP);
WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_PRESS, 0, 0, GESTURE_MODAL_DESELECT); // default 2.4x
- WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, 0, 0, GESTURE_MODAL_NOP); // default 2.4x
-
- WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, 0, 0, GESTURE_MODAL_NOP);
+ WM_modalkeymap_add_item(keymap, MIDDLEMOUSE, KM_RELEASE, KM_ANY, 0, GESTURE_MODAL_NOP); // default 2.4x
WM_modalkeymap_add_item(keymap, WHEELUPMOUSE, KM_PRESS, 0, 0, GESTURE_MODAL_CIRCLE_SUB);
WM_modalkeymap_add_item(keymap, PADMINUS, KM_PRESS, 0, 0, GESTURE_MODAL_CIRCLE_SUB);
@@ -4240,7 +3632,7 @@ static void gesture_circle_modal_keymap(wmKeyConfig *keyconf)
/* straight line modal operators */
static void gesture_straightline_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{GESTURE_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{GESTURE_MODAL_SELECT, "SELECT", 0, "Select", ""},
{GESTURE_MODAL_BEGIN, "BEGIN", 0, "Begin", ""},
@@ -4259,7 +3651,7 @@ static void gesture_straightline_modal_keymap(wmKeyConfig *keyconf)
WM_modalkeymap_add_item(keymap, RIGHTMOUSE, KM_ANY, KM_ANY, 0, GESTURE_MODAL_CANCEL);
WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_PRESS, 0, 0, GESTURE_MODAL_BEGIN);
- WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, 0, 0, GESTURE_MODAL_SELECT);
+ WM_modalkeymap_add_item(keymap, LEFTMOUSE, KM_RELEASE, KM_ANY, 0, GESTURE_MODAL_SELECT);
/* assign map to operators */
WM_modalkeymap_assign(keymap, "IMAGE_OT_sample_line");
@@ -4271,7 +3663,7 @@ static void gesture_straightline_modal_keymap(wmKeyConfig *keyconf)
/* borderselect-like modal operators */
static void gesture_border_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{GESTURE_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{GESTURE_MODAL_SELECT, "SELECT", 0, "Select", ""},
{GESTURE_MODAL_DESELECT, "DESELECT", 0, "DeSelect", ""},
@@ -4337,7 +3729,7 @@ static void gesture_border_modal_keymap(wmKeyConfig *keyconf)
/* zoom to border modal operators */
static void gesture_zoom_border_modal_keymap(wmKeyConfig *keyconf)
{
- static EnumPropertyItem modal_items[] = {
+ static const EnumPropertyItem modal_items[] = {
{GESTURE_MODAL_CANCEL, "CANCEL", 0, "Cancel", ""},
{GESTURE_MODAL_IN, "IN", 0, "In", ""},
{GESTURE_MODAL_OUT, "OUT", 0, "Out", ""},
@@ -4485,15 +3877,31 @@ void wm_window_keymap(wmKeyConfig *keyconf)
gesture_straightline_modal_keymap(keyconf);
}
+/**
+ * Filter functions that can be used with rna_id_itemf() below.
+ * Should return false if 'id' should be excluded.
+ */
+static bool rna_id_enum_filter_single(ID *id, void *user_data)
+{
+ return (id != user_data);
+}
+
/* Generic itemf's for operators that take library args */
-static EnumPropertyItem *rna_id_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(ptr), bool *r_free, ID *id, bool local)
+static const EnumPropertyItem *rna_id_itemf(
+ bContext *UNUSED(C), PointerRNA *UNUSED(ptr),
+ bool *r_free, ID *id, bool local,
+ bool (*filter_ids)(ID *id, void *user_data), void *user_data)
{
EnumPropertyItem item_tmp = {0}, *item = NULL;
int totitem = 0;
int i = 0;
for (; id; id = id->next) {
- if (local == false || !ID_IS_LINKED_DATABLOCK(id)) {
+ if ((filter_ids != NULL) && filter_ids(user_data, id) == false) {
+ i++;
+ continue;
+ }
+ if (local == false || !ID_IS_LINKED(id)) {
item_tmp.identifier = item_tmp.name = id->name + 2;
item_tmp.value = i++;
RNA_enum_item_add(&item, &totitem, &item_tmp);
@@ -4507,58 +3915,64 @@ static EnumPropertyItem *rna_id_itemf(bContext *UNUSED(C), PointerRNA *UNUSED(pt
}
/* can add more as needed */
-EnumPropertyItem *RNA_action_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_action_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->action.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->action.first : NULL, false, NULL, NULL);
}
#if 0 /* UNUSED */
-EnumPropertyItem *RNA_action_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_action_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->action.first : NULL, true);
}
#endif
-EnumPropertyItem *RNA_group_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_group_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->group.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->group.first : NULL, false, NULL, NULL);
}
-EnumPropertyItem *RNA_group_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_group_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->group.first : NULL, true);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->group.first : NULL, true, NULL, NULL);
}
-EnumPropertyItem *RNA_image_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_image_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->image.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->image.first : NULL, false, NULL, NULL);
}
-EnumPropertyItem *RNA_image_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_image_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->image.first : NULL, true);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->image.first : NULL, true, NULL, NULL);
}
-EnumPropertyItem *RNA_scene_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_scene_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->scene.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->scene.first : NULL, false, NULL, NULL);
}
-EnumPropertyItem *RNA_scene_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_scene_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->scene.first : NULL, true);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->scene.first : NULL, true, NULL, NULL);
}
-
-EnumPropertyItem *RNA_movieclip_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_scene_without_active_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+{
+ Scene *scene_active = C ? CTX_data_scene(C) : NULL;
+ return rna_id_itemf(
+ C, ptr, r_free, C ? (ID *)CTX_data_main(C)->scene.first : NULL, true,
+ rna_id_enum_filter_single, scene_active);
+}
+const EnumPropertyItem *RNA_movieclip_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->movieclip.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->movieclip.first : NULL, false, NULL, NULL);
}
-EnumPropertyItem *RNA_movieclip_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_movieclip_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->movieclip.first : NULL, true);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->movieclip.first : NULL, true, NULL, NULL);
}
-EnumPropertyItem *RNA_mask_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_mask_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->mask.first : NULL, false);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->mask.first : NULL, false, NULL, NULL);
}
-EnumPropertyItem *RNA_mask_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
+const EnumPropertyItem *RNA_mask_local_itemf(bContext *C, PointerRNA *ptr, PropertyRNA *UNUSED(prop), bool *r_free)
{
- return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->mask.first : NULL, true);
+ return rna_id_itemf(C, ptr, r_free, C ? (ID *)CTX_data_main(C)->mask.first : NULL, true, NULL, NULL);
}
diff --git a/source/blender/windowmanager/intern/wm_playanim.c b/source/blender/windowmanager/intern/wm_playanim.c
index 6bf7bcc2934..77378cf8e0c 100644
--- a/source/blender/windowmanager/intern/wm_playanim.c
+++ b/source/blender/windowmanager/intern/wm_playanim.c
@@ -1256,7 +1256,7 @@ static char *wm_main_playanim_intern(int argc, const char **argv)
//GHOST_ActivateWindowDrawingContext(g_WS.ghost_window);
/* initialize the font */
- BLF_init(11, 72);
+ BLF_init();
ps.fontid = BLF_load_mem("monospace", (unsigned char *)datatoc_bmonofont_ttf, datatoc_bmonofont_ttf_size);
BLF_size(ps.fontid, 11, 72);
@@ -1428,8 +1428,7 @@ static char *wm_main_playanim_intern(int argc, const char **argv)
ps.next_frame = ps.direction;
-
- while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, 0)) || ps.wait2) {
+ while ((hasevent = GHOST_ProcessEvents(g_WS.ghost_system, ps.wait2))) {
if (hasevent) {
GHOST_DispatchEvents(g_WS.ghost_system);
}
diff --git a/source/blender/windowmanager/intern/wm_stereo.c b/source/blender/windowmanager/intern/wm_stereo.c
index 46cee907991..55fe2ec846c 100644
--- a/source/blender/windowmanager/intern/wm_stereo.c
+++ b/source/blender/windowmanager/intern/wm_stereo.c
@@ -345,6 +345,32 @@ bool WM_stereo3d_enabled(wmWindow *win, bool skip_stereo3d_check)
return true;
}
+/**
+ * If needed, this adjusts \a r_mouse_xy so that drawn cursor and handled mouse position are matching visually.
+ */
+void wm_stereo3d_mouse_offset_apply(wmWindow *win, int *r_mouse_xy)
+{
+ if (!WM_stereo3d_enabled(win, false))
+ return;
+
+ if (win->stereo3d_format->display_mode == S3D_DISPLAY_SIDEBYSIDE) {
+ const int half_x = win->sizex / 2;
+ /* right half of the screen */
+ if (r_mouse_xy[0] > half_x) {
+ r_mouse_xy[0] -= half_x;
+ }
+ r_mouse_xy[0] *= 2;
+ }
+ else if (win->stereo3d_format->display_mode == S3D_DISPLAY_TOPBOTTOM) {
+ const int half_y = win->sizey / 2;
+ /* upper half of the screen */
+ if (r_mouse_xy[1] > half_y) {
+ r_mouse_xy[1] -= half_y;
+ }
+ r_mouse_xy[1] *= 2;
+ }
+}
+
/************************** Stereo 3D operator **********************************/
typedef struct Stereo3dData {
Stereo3dFormat stereo3d_format;
diff --git a/source/blender/windowmanager/intern/wm_tooltip.c b/source/blender/windowmanager/intern/wm_tooltip.c
new file mode 100644
index 00000000000..86ca95ef377
--- /dev/null
+++ b/source/blender/windowmanager/intern/wm_tooltip.c
@@ -0,0 +1,106 @@
+/*
+ * ***** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ *
+ * ***** END GPL LICENSE BLOCK *****
+ */
+
+/** \file blender/windowmanager/intern/wm_tooltip.c
+ * \ingroup wm
+ *
+ * Manages a per-window tool-tip.
+ */
+
+#include "MEM_guardedalloc.h"
+
+#include "BLI_utildefines.h"
+
+#include "BKE_context.h"
+
+#include "ED_screen.h"
+
+#include "UI_interface.h"
+
+#include "WM_api.h"
+#include "WM_types.h"
+
+void WM_tooltip_timer_init(
+ bContext *C, wmWindow *win, ARegion *ar,
+ wmTooltipInitFn init)
+{
+ bScreen *screen = win->screen;
+ wmWindowManager *wm = CTX_wm_manager(C);
+ if (screen->tool_tip == NULL) {
+ screen->tool_tip = MEM_callocN(sizeof(*screen->tool_tip), __func__);
+ }
+ screen->tool_tip->region_from = ar;
+ screen->tool_tip->timer = WM_event_add_timer(wm, win, TIMER, UI_TOOLTIP_DELAY);
+ screen->tool_tip->init = init;
+}
+
+void WM_tooltip_timer_clear(bContext *C, wmWindow *win)
+{
+ wmWindowManager *wm = CTX_wm_manager(C);
+ bScreen *screen = win->screen;
+ if (screen->tool_tip != NULL) {
+ if (screen->tool_tip->timer != NULL) {
+ WM_event_remove_timer(wm, win, screen->tool_tip->timer);
+ screen->tool_tip->timer = NULL;
+ }
+ }
+}
+
+void WM_tooltip_clear(bContext *C, wmWindow *win)
+{
+ WM_tooltip_timer_clear(C, win);
+ bScreen *screen = win->screen;
+ if (screen->tool_tip != NULL) {
+ if (screen->tool_tip->region) {
+ UI_tooltip_free(C, screen, screen->tool_tip->region);
+ screen->tool_tip->region = NULL;
+ }
+ MEM_freeN(screen->tool_tip);
+ screen->tool_tip = NULL;
+ }
+}
+
+void WM_tooltip_init(bContext *C, wmWindow *win)
+{
+ WM_tooltip_timer_clear(C, win);
+ bScreen *screen = win->screen;
+ if (screen->tool_tip->region) {
+ UI_tooltip_free(C, screen, screen->tool_tip->region);
+ screen->tool_tip->region = NULL;
+ }
+ screen->tool_tip->region = screen->tool_tip->init(
+ C, screen->tool_tip->region_from, &screen->tool_tip->exit_on_event);
+ if (screen->tool_tip->region == NULL) {
+ WM_tooltip_clear(C, win);
+ }
+}
+
+void WM_tooltip_refresh(bContext *C, wmWindow *win)
+{
+ WM_tooltip_timer_clear(C, win);
+ bScreen *screen = win->screen;
+ if (screen->tool_tip != NULL) {
+ if (screen->tool_tip->region) {
+ UI_tooltip_free(C, screen, screen->tool_tip->region);
+ screen->tool_tip->region = NULL;
+ }
+ WM_tooltip_init(C, win);
+ }
+}
diff --git a/source/blender/windowmanager/intern/wm_window.c b/source/blender/windowmanager/intern/wm_window.c
index 2d43c47679d..06bd60e8692 100644
--- a/source/blender/windowmanager/intern/wm_window.c
+++ b/source/blender/windowmanager/intern/wm_window.c
@@ -70,6 +70,7 @@
#include "ED_fileselect.h"
#include "UI_interface.h"
+#include "UI_resources.h"
#include "PIL_time.h"
@@ -77,6 +78,7 @@
#include "GPU_extensions.h"
#include "GPU_init_exit.h"
#include "GPU_glew.h"
+#include "BLF_api.h"
/* for assert */
#ifndef NDEBUG
@@ -294,11 +296,158 @@ wmWindow *wm_window_copy_test(bContext *C, wmWindow *win_src)
}
}
+
+/* -------------------------------------------------------------------- */
+/** \name Quit Confirmation Dialog
+ * \{ */
+
+/** Cancel quitting and close the dialog */
+static void wm_block_confirm_quit_cancel(bContext *C, void *arg_block, void *UNUSED(arg))
+{
+ wmWindow *win = CTX_wm_window(C);
+ UI_popup_block_close(C, win, arg_block);
+}
+
+/** Discard the file changes and quit */
+static void wm_block_confirm_quit_discard(bContext *C, void *arg_block, void *UNUSED(arg))
+{
+ wmWindow *win = CTX_wm_window(C);
+ UI_popup_block_close(C, win, arg_block);
+ WM_exit(C);
+}
+
+/* Save changes and quit */
+static void wm_block_confirm_quit_save(bContext *C, void *arg_block, void *UNUSED(arg))
+{
+ PointerRNA props_ptr;
+ wmWindow *win = CTX_wm_window(C);
+
+ UI_popup_block_close(C, win, arg_block);
+
+ wmOperatorType *ot = WM_operatortype_find("WM_OT_save_mainfile", false);
+
+ WM_operator_properties_create_ptr(&props_ptr, ot);
+ RNA_boolean_set(&props_ptr, "exit", true);
+ /* No need for second confirmation popup. */
+ RNA_boolean_set(&props_ptr, "check_existing", false);
+ WM_operator_name_call_ptr(C, ot, WM_OP_INVOKE_DEFAULT, &props_ptr);
+ WM_operator_properties_free(&props_ptr);
+}
+
+
+/* Build the confirm dialog UI */
+static uiBlock *block_create_confirm_quit(struct bContext *C, struct ARegion *ar, void *UNUSED(arg1))
+{
+
+ uiStyle *style = UI_style_get();
+ uiBlock *block = UI_block_begin(C, ar, "confirm_quit_popup", UI_EMBOSS);
+
+ UI_block_flag_enable(block, UI_BLOCK_KEEP_OPEN | UI_BLOCK_LOOP | UI_BLOCK_NO_WIN_CLIP | UI_BLOCK_NUMSELECT);
+ UI_block_emboss_set(block, UI_EMBOSS);
+
+ uiLayout *layout = UI_block_layout(
+ block, UI_LAYOUT_VERTICAL, UI_LAYOUT_PANEL, 10, 2, U.widget_unit * 24, U.widget_unit * 6, 0, style);
+
+ /* Text and some vertical space */
+ {
+ char *message;
+ if (G.main->name[0] == '\0') {
+ message = BLI_strdup(IFACE_("This file has not been saved yet. Save before closing?"));
+ }
+ else {
+ const char *basename = BLI_path_basename(G.main->name);
+ message = BLI_sprintfN(IFACE_("Save changes to \"%s\" before closing?"), basename);
+ }
+ uiItemL(layout, message, ICON_ERROR);
+ MEM_freeN(message);
+ }
+
+ uiItemS(layout);
+ uiItemS(layout);
+
+
+ /* Buttons */
+ uiBut *but;
+
+ uiLayout *split = uiLayoutSplit(layout, 0.0f, true);
+
+ uiLayout *col = uiLayoutColumn(split, false);
+
+ but = uiDefIconTextBut(
+ block, UI_BTYPE_BUT, 0, ICON_SCREEN_BACK, IFACE_("Cancel"), 0, 0, 0, UI_UNIT_Y,
+ NULL, 0, 0, 0, 0, TIP_("Do not quit"));
+ UI_but_func_set(but, wm_block_confirm_quit_cancel, block, NULL);
+
+ /* empty space between buttons */
+ col = uiLayoutColumn(split, false);
+ uiItemS(col);
+
+ col = uiLayoutColumn(split, 1);
+ but = uiDefIconTextBut(
+ block, UI_BTYPE_BUT, 0, ICON_CANCEL, IFACE_("Discard Changes"), 0, 0, 50, UI_UNIT_Y,
+ NULL, 0, 0, 0, 0, TIP_("Discard changes and quit"));
+ UI_but_func_set(but, wm_block_confirm_quit_discard, block, NULL);
+
+ col = uiLayoutColumn(split, 1);
+ but = uiDefIconTextBut(
+ block, UI_BTYPE_BUT, 0, ICON_FILE_TICK, IFACE_("Save & Quit"), 0, 0, 50, UI_UNIT_Y,
+ NULL, 0, 0, 0, 0, TIP_("Save and quit"));
+ UI_but_func_set(but, wm_block_confirm_quit_save, block, NULL);
+
+ UI_block_bounds_set_centered(block, 10);
+
+ return block;
+}
+
+
+/**
+ * Call the confirm dialog on quitting. It's displayed in the context window so
+ * caller should set it as desired.
+ */
+static void wm_confirm_quit(bContext *C)
+{
+ wmWindow *win = CTX_wm_window(C);
+
+ if (GHOST_SupportsNativeDialogs() == 0) {
+ UI_popup_block_invoke(C, block_create_confirm_quit, NULL);
+ }
+ else if (GHOST_confirmQuit(win->ghostwin)) {
+ wm_exit_schedule_delayed(C);
+ }
+}
+
+/**
+ * Call the quit confirmation prompt or exit directly if needed. The use can
+ * still cancel via the confirmation popup. Also, this may not quit Blender
+ * immediately, but rather schedule the closing.
+ *
+ * \param win The window to show the confirmation popup/window in.
+ */
+void wm_quit_with_optional_confirmation_prompt(bContext *C, wmWindow *win)
+{
+ wmWindowManager *wm = CTX_wm_manager(C);
+ wmWindow *win_ctx = CTX_wm_window(C);
+
+ /* The popup will be displayed in the context window which may not be set
+ * here (this function gets called outside of normal event handling loop). */
+ CTX_wm_window_set(C, win);
+
+ if ((U.uiflag & USER_QUIT_PROMPT) && !wm->file_saved && !G.background) {
+ wm_confirm_quit(C);
+ }
+ else {
+ wm_exit_schedule_delayed(C);
+ }
+
+ CTX_wm_window_set(C, win_ctx);
+}
+
+/** \} */
+
/* this is event from ghost, or exit-blender op */
void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
{
wmWindow *tmpwin;
- bool do_exit = false;
/* first check if we have to quit (there are non-temp remaining windows) */
for (tmpwin = wm->windows.first; tmpwin; tmpwin = tmpwin->next) {
@@ -308,21 +457,11 @@ void wm_window_close(bContext *C, wmWindowManager *wm, wmWindow *win)
break;
}
- if (tmpwin == NULL)
- do_exit = 1;
-
- if ((U.uiflag & USER_QUIT_PROMPT) && !wm->file_saved) {
- if (do_exit) {
- if (!GHOST_confirmQuit(win->ghostwin))
- return;
- }
- }
-
- /* let WM_exit do all freeing, for correct quit.blend save */
- if (do_exit) {
- WM_exit(C);
+ if (tmpwin == NULL) {
+ wm_quit_with_optional_confirmation_prompt(C, win);
}
else {
+ /* We're just closing a window */
bScreen *screen = win->screen;
BLI_remlink(&wm->windows, win);
@@ -374,14 +513,49 @@ void wm_window_title(wmWindowManager *wm, wmWindow *win)
}
}
-static float wm_window_get_virtual_pixelsize(void)
+void WM_window_set_dpi(wmWindow *win)
{
- return ((U.virtual_pixel == VIRTUAL_PIXEL_NATIVE) ? 1.0f : 2.0f);
-}
+ float auto_dpi = GHOST_GetDPIHint(win->ghostwin);
-float wm_window_pixelsize(wmWindow *win)
-{
- return (GHOST_GetNativePixelSize(win->ghostwin) * wm_window_get_virtual_pixelsize());
+ /* Clamp auto DPI to 96, since our font/interface drawing does not work well
+ * with lower sizes. The main case we are interested in supporting is higher
+ * DPI. If a smaller UI is desired it is still possible to adjust UI scale. */
+ auto_dpi = max_ff(auto_dpi, 96.0f);
+
+ /* Lazily init UI scale size, preserving backwards compatibility by
+ * computing UI scale from ratio of previous DPI and auto DPI */
+ if (U.ui_scale == 0) {
+ int virtual_pixel = (U.virtual_pixel == VIRTUAL_PIXEL_NATIVE) ? 1 : 2;
+
+ if (U.dpi == 0) {
+ U.ui_scale = virtual_pixel;
+ }
+ else {
+ U.ui_scale = (virtual_pixel * U.dpi * 96.0f) / (auto_dpi * 72.0f);
+ }
+
+ CLAMP(U.ui_scale, 0.25f, 4.0f);
+ }
+
+ /* Blender's UI drawing assumes DPI 72 as a good default following macOS
+ * while Windows and Linux use DPI 96. GHOST assumes a default 96 so we
+ * remap the DPI to Blender's convention. */
+ auto_dpi *= GHOST_GetNativePixelSize(win->ghostwin);
+ int dpi = auto_dpi * U.ui_scale * (72.0 / 96.0f);
+
+ /* Automatically set larger pixel size for high DPI. */
+ int pixelsize = max_ii(1, (int)(dpi / 64));
+ /* User adjustment for pixel size. */
+ pixelsize = max_ii(1, pixelsize + U.ui_line_width);
+
+ /* Set user preferences globals for drawing, and for forward compatibility. */
+ U.pixelsize = pixelsize;
+ U.dpi = dpi / pixelsize;
+ U.virtual_pixel = (pixelsize == 1) ? VIRTUAL_PIXEL_NATIVE : VIRTUAL_PIXEL_DOUBLE;
+ U.widget_unit = (U.pixelsize * U.dpi * 20 + 36) / 72;
+
+ /* update font drawing */
+ BLF_default_dpi(U.pixelsize * U.dpi);
}
/* belongs to below */
@@ -412,12 +586,7 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wm
ghostwin = GHOST_CreateWindow(g_system, title,
win->posx, posy, win->sizex, win->sizey,
-#ifdef __APPLE__
- /* we agreed to not set any fullscreen or iconized state on startup */
- GHOST_kWindowStateNormal,
-#else
(GHOST_TWindowState)win->windowstate,
-#endif
GHOST_kDrawingContextTypeOpenGL,
glSettings);
@@ -441,8 +610,12 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wm
/* store actual window size in blender window */
bounds = GHOST_GetClientBounds(win->ghostwin);
- win->sizex = GHOST_GetWidthRectangle(bounds);
- win->sizey = GHOST_GetHeightRectangle(bounds);
+
+ /* win32: gives undefined window size when minimized */
+ if (GHOST_GetWindowState(win->ghostwin) != GHOST_kWindowStateMinimized) {
+ win->sizex = GHOST_GetWidthRectangle(bounds);
+ win->sizey = GHOST_GetHeightRectangle(bounds);
+ }
GHOST_DisposeRectangle(bounds);
#ifndef __APPLE__
@@ -456,10 +629,8 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wm
glClear(GL_COLOR_BUFFER_BIT);
}
- /* displays with larger native pixels, like Macbook. Used to scale dpi with */
/* needed here, because it's used before it reads userdef */
- U.pixelsize = wm_window_pixelsize(win);
- BKE_blender_userdef_refresh();
+ WM_window_set_dpi(win);
wm_window_swap_buffers(win);
@@ -472,7 +643,7 @@ static void wm_window_ghostwindow_add(wmWindowManager *wm, const char *title, wm
}
/**
- * Initialize #wmWindows without ghostwin, open these and clear.
+ * Initialize #wmWindow without ghostwin, open these and clear.
*
* window size is read from window, if 0 it uses prefsize
* called in #WM_check, also inits stuff after file read.
@@ -618,15 +789,27 @@ wmWindow *WM_window_open(bContext *C, const rcti *rect)
* \param type: WM_WINDOW_RENDER, WM_WINDOW_USERPREFS...
* \return the window or NULL.
*/
-wmWindow *WM_window_open_temp(bContext *C, const rcti *rect_init, int type)
+wmWindow *WM_window_open_temp(bContext *C, int x, int y, int sizex, int sizey, int type)
{
wmWindow *win_prev = CTX_wm_window(C);
wmWindow *win;
ScrArea *sa;
Scene *scene = CTX_data_scene(C);
const char *title;
- rcti rect = *rect_init;
- const short px_virtual = (short)wm_window_get_virtual_pixelsize();
+
+ /* convert to native OS window coordinates */
+ const float native_pixel_size = GHOST_GetNativePixelSize(win_prev->ghostwin);
+ x /= native_pixel_size;
+ y /= native_pixel_size;
+ sizex /= native_pixel_size;
+ sizey /= native_pixel_size;
+
+ /* calculate postition */
+ rcti rect;
+ rect.xmin = x + win_prev->posx - sizex / 2;
+ rect.ymin = y + win_prev->posy - sizey / 2;
+ rect.xmax = rect.xmin + sizex;
+ rect.ymax = rect.ymin + sizey;
/* changes rect to fit within desktop */
wm_window_check_position(&rect);
@@ -644,9 +827,8 @@ wmWindow *WM_window_open_temp(bContext *C, const rcti *rect_init, int type)
win->posy = rect.ymin;
}
- /* multiply with virtual pixelsize, ghost handles native one (e.g. for retina) */
- win->sizex = BLI_rcti_size_x(&rect) * px_virtual;
- win->sizey = BLI_rcti_size_y(&rect) * px_virtual;
+ win->sizex = BLI_rcti_size_x(&rect);
+ win->sizey = BLI_rcti_size_y(&rect);
if (win->ghostwin) {
wm_window_set_size(win, win->sizex, win->sizey);
@@ -835,8 +1017,7 @@ void wm_window_make_drawable(wmWindowManager *wm, wmWindow *win)
GHOST_ActivateWindowDrawingContext(win->ghostwin);
/* this can change per window */
- U.pixelsize = wm_window_pixelsize(win);
- BKE_blender_userdef_refresh();
+ WM_window_set_dpi(win);
}
}
@@ -1035,6 +1216,8 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr
if (type == GHOST_kEventWindowSize) {
WM_jobs_stop(wm, win->screen, NULL);
}
+
+ WM_window_set_dpi(win);
/* win32: gives undefined window size when minimized */
if (state != GHOST_kWindowStateMinimized) {
@@ -1118,7 +1301,18 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr
}
break;
}
-
+
+ case GHOST_kEventWindowDPIHintChanged:
+ {
+ WM_window_set_dpi(win);
+ /* font's are stored at each DPI level, without this we can easy load 100's of fonts */
+ BLF_cache_clear();
+
+ WM_main_add_notifier(NC_WINDOW, NULL); /* full redraw */
+ WM_main_add_notifier(NC_SCREEN | NA_EDITED, NULL); /* refresh region sizes */
+ break;
+ }
+
case GHOST_kEventOpenMainFile:
{
PointerRNA props_ptr;
@@ -1199,11 +1393,9 @@ static int ghost_event_proc(GHOST_EventHandle evt, GHOST_TUserDataPtr C_void_ptr
{
// only update if the actual pixel size changes
float prev_pixelsize = U.pixelsize;
- U.pixelsize = wm_window_pixelsize(win);
+ WM_window_set_dpi(win);
if (U.pixelsize != prev_pixelsize) {
- BKE_blender_userdef_refresh();
-
// close all popups since they are positioned with the pixel
// size baked in and it's difficult to correct them
wmWindow *oldWindow = CTX_wm_window(C);
@@ -1407,6 +1599,7 @@ wmTimer *WM_event_add_timer_notifier(wmWindowManager *wm, wmWindow *win, unsigne
wt->timestep = timestep;
wt->win = win;
wt->customdata = SET_UINT_IN_POINTER(type);
+ wt->flags |= WM_TIMER_NO_FREE_CUSTOM_DATA;
BLI_addtail(&wm->timers, wt);
@@ -1428,8 +1621,9 @@ void WM_event_remove_timer(wmWindowManager *wm, wmWindow *UNUSED(win), wmTimer *
wm->reports.reporttimer = NULL;
BLI_remlink(&wm->timers, wt);
- if (wt->customdata)
+ if (wt->customdata != NULL && (wt->flags & WM_TIMER_NO_FREE_CUSTOM_DATA) == 0) {
MEM_freeN(wt->customdata);
+ }
MEM_freeN(wt);
/* there might be events in queue with this timer as customdata */
diff --git a/source/blender/windowmanager/wm.h b/source/blender/windowmanager/wm.h
index 2f06ddab1e8..5ced36a104f 100644
--- a/source/blender/windowmanager/wm.h
+++ b/source/blender/windowmanager/wm.h
@@ -43,6 +43,9 @@ typedef struct wmPaintCursor {
void (*draw)(bContext *C, int, int, void *customdata);
} wmPaintCursor;
+
+void wm_exit_schedule_delayed(const bContext *C);
+
extern void wm_close_and_free(bContext *C, wmWindowManager *);
extern void wm_close_and_free_all(bContext *C, ListBase *);
@@ -57,14 +60,14 @@ void wm_operatortype_free(void);
void wm_operatortype_init(void);
void wm_window_keymap(wmKeyConfig *keyconf);
-void wm_tweakevent_test(bContext *C, wmEvent *event, int action);
-
/* wm_gesture.c */
-#define WM_LASSO_MIN_POINTS 1024
void wm_gesture_draw(struct wmWindow *win);
int wm_gesture_evaluate(wmGesture *gesture);
void wm_gesture_tag_redraw(bContext *C);
+/* wm_gesture_ops.c */
+void wm_tweakevent_test(bContext *C, const wmEvent *event, int action);
+
/* wm_jobs.c */
void wm_jobs_timer(const bContext *C, wmWindowManager *wm, wmTimer *wt);
void wm_jobs_timer_ended(wmWindowManager *wm, wmTimer *wt);
@@ -78,6 +81,7 @@ void wm_autosave_location(char *filepath);
/* wm_stereo.c */
void wm_method_draw_stereo3d(const bContext *C, wmWindow *win);
+void wm_stereo3d_mouse_offset_apply(wmWindow *win, int *r_mouse_xy);
int wm_stereo3d_set_exec(bContext *C, wmOperator *op);
int wm_stereo3d_set_invoke(bContext *C, wmOperator *op, const wmEvent *event);
void wm_stereo3d_set_draw(bContext *C, wmOperator *op);
@@ -88,12 +92,4 @@ void wm_stereo3d_set_cancel(bContext *C, wmOperator *op);
void wm_open_init_load_ui(wmOperator *op, bool use_prefs);
void wm_open_init_use_scripts(wmOperator *op, bool use_prefs);
-/* hack to store circle select size - campbell, must replace with nice operator memory */
-#define GESTURE_MEMORY
-
-#ifdef GESTURE_MEMORY
-extern int circle_select_size;
-#endif
-
#endif /* __WM_H__ */
-
diff --git a/source/blender/windowmanager/wm_event_system.h b/source/blender/windowmanager/wm_event_system.h
index efc01b1f8a8..9977e73f2fd 100644
--- a/source/blender/windowmanager/wm_event_system.h
+++ b/source/blender/windowmanager/wm_event_system.h
@@ -71,7 +71,7 @@ typedef struct wmEventHandler {
} wmEventHandler;
-/* custom types for handlers, for signalling, freeing */
+/* custom types for handlers, for signaling, freeing */
enum {
WM_HANDLER_DEFAULT,
WM_HANDLER_FILESELECT
@@ -87,14 +87,14 @@ void wm_event_do_handlers (bContext *C);
void wm_event_add_ghostevent (wmWindowManager *wm, wmWindow *win, int type, int time, void *customdata);
-void wm_event_do_notifiers (bContext *C);
+void wm_event_do_refresh_wm_and_depsgraph(bContext *C);
+void wm_event_do_notifiers(bContext *C);
/* wm_keymap.c */
/* wm_dropbox.c */
void wm_dropbox_free(void);
-void wm_drags_check_ops(bContext *C, wmEvent *event);
+void wm_drags_check_ops(bContext *C, const wmEvent *event);
void wm_drags_draw(bContext *C, wmWindow *win, rcti *rect);
#endif /* __WM_EVENT_SYSTEM_H__ */
-
diff --git a/source/blender/windowmanager/wm_event_types.h b/source/blender/windowmanager/wm_event_types.h
index 3085f138846..090c8c90280 100644
--- a/source/blender/windowmanager/wm_event_types.h
+++ b/source/blender/windowmanager/wm_event_types.h
@@ -431,6 +431,7 @@ enum {
GESTURE_MODAL_CANCEL = 1,
GESTURE_MODAL_CONFIRM = 2,
+ /* Uses 'deselect' operator property. */
GESTURE_MODAL_SELECT = 3,
GESTURE_MODAL_DESELECT = 4,
@@ -441,6 +442,7 @@ enum {
GESTURE_MODAL_BEGIN = 8, /* border select/straight line, activate, use release to detect which button */
+ /* Uses 'zoom_out' operator property. */
GESTURE_MODAL_IN = 9,
GESTURE_MODAL_OUT = 10,
diff --git a/source/blender/windowmanager/wm_files.h b/source/blender/windowmanager/wm_files.h
index 396907a3f6d..b102b6c7cc7 100644
--- a/source/blender/windowmanager/wm_files.h
+++ b/source/blender/windowmanager/wm_files.h
@@ -35,7 +35,10 @@ struct wmOperatorType;
/* wm_files.c */
void wm_history_file_read(void);
-int wm_homefile_read(struct bContext *C, struct ReportList *reports, bool from_memory, const char *filepath);
+int wm_homefile_read(
+ struct bContext *C, struct ReportList *reports,
+ bool use_factory_settings, bool use_empty_data, bool use_userdef,
+ const char *filepath_startup_override, const char *app_template_override);
void wm_file_read_report(bContext *C);
void WM_OT_save_homefile(struct wmOperatorType *ot);
diff --git a/source/blender/windowmanager/wm_window.h b/source/blender/windowmanager/wm_window.h
index c106f9d7851..5209af87960 100644
--- a/source/blender/windowmanager/wm_window.h
+++ b/source/blender/windowmanager/wm_window.h
@@ -63,8 +63,6 @@ void wm_window_swap_buffers (wmWindow *win);
void wm_window_set_swap_interval(wmWindow *win, int interval);
bool wm_window_get_swap_interval(wmWindow *win, int *intervalOut);
-float wm_window_pixelsize(wmWindow *win);
-
void wm_get_cursor_position (wmWindow *win, int *x, int *y);
void wm_cursor_position_from_ghost (wmWindow *win, int *x, int *y);
void wm_cursor_position_to_ghost (wmWindow *win, int *x, int *y);
@@ -80,6 +78,7 @@ void wm_window_IME_end (wmWindow *win);
int wm_window_close_exec(bContext *C, struct wmOperator *op);
int wm_window_duplicate_exec(bContext *C, struct wmOperator *op);
int wm_window_fullscreen_toggle_exec(bContext *C, struct wmOperator *op);
+void wm_quit_with_optional_confirmation_prompt(bContext *C, wmWindow *win) ATTR_NONNULL();
/* Initial (unmaximized) size to start with for
* systems that can't find it for themselves (X11).